1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
3 #![feature(crate_visibility_modifier)]
4 #![feature(label_break_value)]
6 #![feature(rustc_diagnostic_macros)]
8 #![recursion_limit="256"]
10 #![deny(rust_2018_idioms)]
12 pub use rustc::hir::def::{Namespace, PerNS};
14 use GenericParameters::*;
17 use rustc::hir::map::{Definitions, DefCollector};
18 use rustc::hir::{self, PrimTy, Bool, Char, Float, Int, Uint, Str};
19 use rustc::middle::cstore::CrateStore;
20 use rustc::session::Session;
22 use rustc::hir::def::*;
23 use rustc::hir::def::Namespace::*;
24 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
25 use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
26 use rustc::ty::{self, DefIdTree};
27 use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap};
28 use rustc::{bug, span_bug};
30 use rustc_metadata::creader::CrateLoader;
31 use rustc_metadata::cstore::CStore;
33 use syntax::source_map::SourceMap;
34 use syntax::ext::hygiene::{Mark, Transparency, SyntaxContext};
35 use syntax::ast::{self, Name, NodeId, Ident, FloatTy, IntTy, UintTy};
36 use syntax::ext::base::SyntaxExtension;
37 use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
38 use syntax::ext::base::MacroKind;
39 use syntax::symbol::{Symbol, keywords};
40 use syntax::util::lev_distance::find_best_match_for_name;
42 use syntax::visit::{self, FnKind, Visitor};
44 use syntax::ast::{CRATE_NODE_ID, Arm, IsAsync, BindingMode, Block, Crate, Expr, ExprKind};
45 use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParamKind, Generics};
46 use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind};
47 use syntax::ast::{Label, Local, Mutability, Pat, PatKind, Path};
48 use syntax::ast::{QSelf, TraitItemKind, TraitRef, Ty, TyKind};
50 use syntax::{span_err, struct_span_err, unwrap_or, walk_list};
52 use syntax_pos::{BytePos, Span, DUMMY_SP, MultiSpan};
53 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
57 use std::cell::{Cell, RefCell};
58 use std::{cmp, fmt, iter, mem, ptr};
59 use std::collections::BTreeSet;
60 use std::mem::replace;
61 use rustc_data_structures::ptr_key::PtrKey;
62 use rustc_data_structures::sync::Lrc;
64 use resolve_imports::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver};
65 use macros::{InvocationData, LegacyBinding, ParentScope};
67 // N.B., this module needs to be declared first so diagnostics are
68 // registered before they are used.
73 mod build_reduced_graph;
76 fn is_known_tool(name: Name) -> bool {
77 ["clippy", "rustfmt"].contains(&&*name.as_str())
87 AbsolutePath(Namespace),
92 /// A free importable items suggested in case of resolution failure.
93 struct ImportSuggestion {
98 /// A field or associated item from self type suggested in case of resolution failure.
99 enum AssocSuggestion {
106 struct BindingError {
108 origin: BTreeSet<Span>,
109 target: BTreeSet<Span>,
112 struct TypoSuggestion {
115 /// The kind of the binding ("crate", "module", etc.)
118 /// An appropriate article to refer to the binding ("a", "an", etc.)
119 article: &'static str,
122 impl PartialOrd for BindingError {
123 fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> {
124 Some(self.cmp(other))
128 impl PartialEq for BindingError {
129 fn eq(&self, other: &BindingError) -> bool {
130 self.name == other.name
134 impl Ord for BindingError {
135 fn cmp(&self, other: &BindingError) -> cmp::Ordering {
136 self.name.cmp(&other.name)
140 /// A span, message, replacement text, and applicability.
141 type Suggestion = (Span, String, String, Applicability);
143 enum ResolutionError<'a> {
144 /// Error E0401: can't use type or const parameters from outer function.
145 GenericParamsFromOuterFunction(Def),
146 /// Error E0403: the name is already used for a type or const parameter in this generic
148 NameAlreadyUsedInParameterList(Name, &'a Span),
149 /// Error E0407: method is not a member of trait.
150 MethodNotMemberOfTrait(Name, &'a str),
151 /// Error E0437: type is not a member of trait.
152 TypeNotMemberOfTrait(Name, &'a str),
153 /// Error E0438: const is not a member of trait.
154 ConstNotMemberOfTrait(Name, &'a str),
155 /// Error E0408: variable `{}` is not bound in all patterns.
156 VariableNotBoundInPattern(&'a BindingError),
157 /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
158 VariableBoundWithDifferentMode(Name, Span),
159 /// Error E0415: identifier is bound more than once in this parameter list.
160 IdentifierBoundMoreThanOnceInParameterList(&'a str),
161 /// Error E0416: identifier is bound more than once in the same pattern.
162 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
163 /// Error E0426: use of undeclared label.
164 UndeclaredLabel(&'a str, Option<Name>),
165 /// Error E0429: `self` imports are only allowed within a `{ }` list.
166 SelfImportsOnlyAllowedWithin,
167 /// Error E0430: `self` import can only appear once in the list.
168 SelfImportCanOnlyAppearOnceInTheList,
169 /// Error E0431: `self` import can only appear in an import list with a non-empty prefix.
170 SelfImportOnlyInImportListWithNonEmptyPrefix,
171 /// Error E0433: failed to resolve.
172 FailedToResolve { label: String, suggestion: Option<Suggestion> },
173 /// Error E0434: can't capture dynamic environment in a fn item.
174 CannotCaptureDynamicEnvironmentInFnItem,
175 /// Error E0435: attempt to use a non-constant value in a constant.
176 AttemptToUseNonConstantValueInConstant,
177 /// Error E0530: `X` bindings cannot shadow `Y`s.
178 BindingShadowsSomethingUnacceptable(&'a str, Name, &'a NameBinding<'a>),
179 /// Error E0128: type parameters with a default cannot use forward-declared identifiers.
180 ForwardDeclaredTyParam, // FIXME(const_generics:defaults)
183 /// Combines an error with provided span and emits it.
185 /// This takes the error provided, combines it with the span and any additional spans inside the
186 /// error and emits it.
187 fn resolve_error<'sess, 'a>(resolver: &'sess Resolver<'_>,
189 resolution_error: ResolutionError<'a>) {
190 resolve_struct_error(resolver, span, resolution_error).emit();
193 fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver<'_>,
195 resolution_error: ResolutionError<'a>)
196 -> DiagnosticBuilder<'sess> {
197 match resolution_error {
198 ResolutionError::GenericParamsFromOuterFunction(outer_def) => {
199 let mut err = struct_span_err!(resolver.session,
202 "can't use generic parameters from outer function",
204 err.span_label(span, format!("use of generic parameter from outer function"));
206 let cm = resolver.session.source_map();
208 Def::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
209 if let Some(impl_span) = maybe_impl_defid.and_then(|def_id| {
210 resolver.definitions.opt_span(def_id)
213 reduce_impl_span_to_impl_keyword(cm, impl_span),
214 "`Self` type implicitly declared here, by this `impl`",
217 match (maybe_trait_defid, maybe_impl_defid) {
219 err.span_label(span, "can't use `Self` here");
222 err.span_label(span, "use a type here instead");
224 (None, None) => bug!("`impl` without trait nor type?"),
228 Def::TyParam(def_id) => {
229 if let Some(span) = resolver.definitions.opt_span(def_id) {
230 err.span_label(span, "type variable from outer function");
233 Def::ConstParam(def_id) => {
234 if let Some(span) = resolver.definitions.opt_span(def_id) {
235 err.span_label(span, "const variable from outer function");
239 bug!("GenericParamsFromOuterFunction should only be used with Def::SelfTy, \
244 // Try to retrieve the span of the function signature and generate a new message with
245 // a local type or const parameter.
246 let sugg_msg = &format!("try using a local generic parameter instead");
247 if let Some((sugg_span, new_snippet)) = cm.generate_local_type_param_snippet(span) {
248 // Suggest the modification to the user
253 Applicability::MachineApplicable,
255 } else if let Some(sp) = cm.generate_fn_name_span(span) {
257 format!("try adding a local generic parameter in this method instead"));
259 err.help(&format!("try using a local generic parameter instead"));
264 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
265 let mut err = struct_span_err!(resolver.session,
268 "the name `{}` is already used for a generic \
269 parameter in this list of generic parameters",
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 {
362 "a label with a similar name exists in this scope",
363 lev_candidate.to_string(),
364 Applicability::MaybeIncorrect,
367 err.span_label(span, format!("undeclared label `{}`", name));
371 ResolutionError::SelfImportsOnlyAllowedWithin => {
372 struct_span_err!(resolver.session,
376 "`self` imports are only allowed within a { } list")
378 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
379 let mut err = struct_span_err!(resolver.session, span, E0430,
380 "`self` import can only appear once in an import list");
381 err.span_label(span, "can only appear once in an import list");
384 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
385 let mut err = struct_span_err!(resolver.session, span, E0431,
386 "`self` import can only appear in an import list with \
387 a non-empty prefix");
388 err.span_label(span, "can only appear in an import list with a non-empty prefix");
391 ResolutionError::FailedToResolve { label, suggestion } => {
392 let mut err = struct_span_err!(resolver.session, span, E0433,
393 "failed to resolve: {}", &label);
394 err.span_label(span, label);
396 if let Some((span, msg, suggestion, applicability)) = suggestion {
397 err.span_suggestion(span, &msg, suggestion, applicability);
402 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
403 let mut err = struct_span_err!(resolver.session,
407 "can't capture dynamic environment in a fn item");
408 err.help("use the `|| { ... }` closure form instead");
411 ResolutionError::AttemptToUseNonConstantValueInConstant => {
412 let mut err = struct_span_err!(resolver.session, span, E0435,
413 "attempt to use a non-constant value in a constant");
414 err.span_label(span, "non-constant value");
417 ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
418 let shadows_what = binding.descr();
419 let mut err = struct_span_err!(resolver.session, span, E0530, "{}s cannot shadow {}s",
420 what_binding, shadows_what);
421 err.span_label(span, format!("cannot be named the same as {} {}",
422 binding.article(), shadows_what));
423 let participle = if binding.is_import() { "imported" } else { "defined" };
424 let msg = format!("the {} `{}` is {} here", shadows_what, name, participle);
425 err.span_label(binding.span, msg);
428 ResolutionError::ForwardDeclaredTyParam => {
429 let mut err = struct_span_err!(resolver.session, span, E0128,
430 "type parameters with a default cannot use \
431 forward declared identifiers");
433 span, "defaulted type parameters cannot be forward declared".to_string());
439 /// Adjust the impl span so that just the `impl` keyword is taken by removing
440 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
441 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
443 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
444 /// parser. If you need to use this function or something similar, please consider updating the
445 /// `source_map` functions and this function to something more robust.
446 fn reduce_impl_span_to_impl_keyword(cm: &SourceMap, impl_span: Span) -> Span {
447 let impl_span = cm.span_until_char(impl_span, '<');
448 let impl_span = cm.span_until_whitespace(impl_span);
452 #[derive(Copy, Clone, Debug)]
455 binding_mode: BindingMode,
458 /// Map from the name in a pattern to its binding mode.
459 type BindingMap = FxHashMap<Ident, BindingInfo>;
461 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
472 fn descr(self) -> &'static str {
474 PatternSource::Match => "match binding",
475 PatternSource::IfLet => "if let binding",
476 PatternSource::WhileLet => "while let binding",
477 PatternSource::Let => "let binding",
478 PatternSource::For => "for binding",
479 PatternSource::FnParam => "function parameter",
484 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
485 enum AliasPossibility {
490 #[derive(Copy, Clone, Debug)]
491 enum PathSource<'a> {
492 // Type paths `Path`.
494 // Trait paths in bounds or impls.
495 Trait(AliasPossibility),
496 // Expression paths `path`, with optional parent context.
497 Expr(Option<&'a Expr>),
498 // Paths in path patterns `Path`.
500 // Paths in struct expressions and patterns `Path { .. }`.
502 // Paths in tuple struct patterns `Path(..)`.
504 // `m::A::B` in `<T as m::A>::B::C`.
505 TraitItem(Namespace),
506 // Path in `pub(path)`
510 impl<'a> PathSource<'a> {
511 fn namespace(self) -> Namespace {
513 PathSource::Type | PathSource::Trait(_) | PathSource::Struct |
514 PathSource::Visibility => TypeNS,
515 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
516 PathSource::TraitItem(ns) => ns,
520 fn global_by_default(self) -> bool {
522 PathSource::Visibility => true,
523 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
524 PathSource::Struct | PathSource::TupleStruct |
525 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
529 fn defer_to_typeck(self) -> bool {
531 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
532 PathSource::Struct | PathSource::TupleStruct => true,
533 PathSource::Trait(_) | PathSource::TraitItem(..) |
534 PathSource::Visibility => false,
538 fn descr_expected(self) -> &'static str {
540 PathSource::Type => "type",
541 PathSource::Trait(_) => "trait",
542 PathSource::Pat => "unit struct/variant or constant",
543 PathSource::Struct => "struct, variant or union type",
544 PathSource::TupleStruct => "tuple struct/variant",
545 PathSource::Visibility => "module",
546 PathSource::TraitItem(ns) => match ns {
547 TypeNS => "associated type",
548 ValueNS => "method or associated constant",
549 MacroNS => bug!("associated macro"),
551 PathSource::Expr(parent) => match parent.map(|p| &p.node) {
552 // "function" here means "anything callable" rather than `Def::Fn`,
553 // this is not precise but usually more helpful than just "value".
554 Some(&ExprKind::Call(..)) => "function",
560 fn is_expected(self, def: Def) -> bool {
562 PathSource::Type => match def {
563 Def::Struct(..) | Def::Union(..) | Def::Enum(..) |
564 Def::Trait(..) | Def::TraitAlias(..) | Def::TyAlias(..) |
565 Def::AssociatedTy(..) | Def::PrimTy(..) | Def::TyParam(..) |
566 Def::SelfTy(..) | Def::Existential(..) | Def::ForeignTy(..) => true,
569 PathSource::Trait(AliasPossibility::No) => match def {
570 Def::Trait(..) => true,
573 PathSource::Trait(AliasPossibility::Maybe) => match def {
574 Def::Trait(..) => true,
575 Def::TraitAlias(..) => true,
578 PathSource::Expr(..) => match def {
579 Def::Ctor(_, _, CtorKind::Const) | Def::Ctor(_, _, CtorKind::Fn) |
580 Def::Const(..) | Def::Static(..) | Def::Local(..) | Def::Upvar(..) |
581 Def::Fn(..) | Def::Method(..) | Def::AssociatedConst(..) |
582 Def::SelfCtor(..) | Def::ConstParam(..) => true,
585 PathSource::Pat => match def {
586 Def::Ctor(_, _, CtorKind::Const) |
587 Def::Const(..) | Def::AssociatedConst(..) |
588 Def::SelfCtor(..) => true,
591 PathSource::TupleStruct => match def {
592 Def::Ctor(_, _, CtorKind::Fn) | Def::SelfCtor(..) => true,
595 PathSource::Struct => match def {
596 Def::Struct(..) | Def::Union(..) | Def::Variant(..) |
597 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => true,
600 PathSource::TraitItem(ns) => match def {
601 Def::AssociatedConst(..) | Def::Method(..) if ns == ValueNS => true,
602 Def::AssociatedTy(..) if ns == TypeNS => true,
605 PathSource::Visibility => match def {
606 Def::Mod(..) => true,
612 fn error_code(self, has_unexpected_resolution: bool) -> &'static str {
613 __diagnostic_used!(E0404);
614 __diagnostic_used!(E0405);
615 __diagnostic_used!(E0412);
616 __diagnostic_used!(E0422);
617 __diagnostic_used!(E0423);
618 __diagnostic_used!(E0425);
619 __diagnostic_used!(E0531);
620 __diagnostic_used!(E0532);
621 __diagnostic_used!(E0573);
622 __diagnostic_used!(E0574);
623 __diagnostic_used!(E0575);
624 __diagnostic_used!(E0576);
625 __diagnostic_used!(E0577);
626 __diagnostic_used!(E0578);
627 match (self, has_unexpected_resolution) {
628 (PathSource::Trait(_), true) => "E0404",
629 (PathSource::Trait(_), false) => "E0405",
630 (PathSource::Type, true) => "E0573",
631 (PathSource::Type, false) => "E0412",
632 (PathSource::Struct, true) => "E0574",
633 (PathSource::Struct, false) => "E0422",
634 (PathSource::Expr(..), true) => "E0423",
635 (PathSource::Expr(..), false) => "E0425",
636 (PathSource::Pat, true) | (PathSource::TupleStruct, true) => "E0532",
637 (PathSource::Pat, false) | (PathSource::TupleStruct, false) => "E0531",
638 (PathSource::TraitItem(..), true) => "E0575",
639 (PathSource::TraitItem(..), false) => "E0576",
640 (PathSource::Visibility, true) => "E0577",
641 (PathSource::Visibility, false) => "E0578",
646 // A minimal representation of a path segment. We use this in resolve because
647 // we synthesize 'path segments' which don't have the rest of an AST or HIR
649 #[derive(Clone, Copy, Debug)]
656 fn from_path(path: &Path) -> Vec<Segment> {
657 path.segments.iter().map(|s| s.into()).collect()
660 fn from_ident(ident: Ident) -> Segment {
667 fn names_to_string(segments: &[Segment]) -> String {
668 names_to_string(&segments.iter()
669 .map(|seg| seg.ident)
670 .collect::<Vec<_>>())
674 impl<'a> From<&'a ast::PathSegment> for Segment {
675 fn from(seg: &'a ast::PathSegment) -> Segment {
683 struct UsePlacementFinder {
684 target_module: NodeId,
689 impl UsePlacementFinder {
690 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, bool) {
691 let mut finder = UsePlacementFinder {
696 visit::walk_crate(&mut finder, krate);
697 (finder.span, finder.found_use)
701 impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
704 module: &'tcx ast::Mod,
706 _: &[ast::Attribute],
709 if self.span.is_some() {
712 if node_id != self.target_module {
713 visit::walk_mod(self, module);
716 // find a use statement
717 for item in &module.items {
719 ItemKind::Use(..) => {
720 // don't suggest placing a use before the prelude
721 // import or other generated ones
722 if item.span.ctxt().outer().expn_info().is_none() {
723 self.span = Some(item.span.shrink_to_lo());
724 self.found_use = true;
728 // don't place use before extern crate
729 ItemKind::ExternCrate(_) => {}
730 // but place them before the first other item
731 _ => if self.span.map_or(true, |span| item.span < span ) {
732 if item.span.ctxt().outer().expn_info().is_none() {
733 // don't insert between attributes and an item
734 if item.attrs.is_empty() {
735 self.span = Some(item.span.shrink_to_lo());
737 // find the first attribute on the item
738 for attr in &item.attrs {
739 if self.span.map_or(true, |span| attr.span < span) {
740 self.span = Some(attr.span.shrink_to_lo());
751 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
752 impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> {
753 fn visit_item(&mut self, item: &'tcx Item) {
754 self.resolve_item(item);
756 fn visit_arm(&mut self, arm: &'tcx Arm) {
757 self.resolve_arm(arm);
759 fn visit_block(&mut self, block: &'tcx Block) {
760 self.resolve_block(block);
762 fn visit_anon_const(&mut self, constant: &'tcx ast::AnonConst) {
763 debug!("visit_anon_const {:?}", constant);
764 self.with_constant_rib(|this| {
765 visit::walk_anon_const(this, constant);
768 fn visit_expr(&mut self, expr: &'tcx Expr) {
769 self.resolve_expr(expr, None);
771 fn visit_local(&mut self, local: &'tcx Local) {
772 self.resolve_local(local);
774 fn visit_ty(&mut self, ty: &'tcx Ty) {
776 TyKind::Path(ref qself, ref path) => {
777 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
779 TyKind::ImplicitSelf => {
780 let self_ty = keywords::SelfUpper.ident();
781 let def = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
782 .map_or(Def::Err, |d| d.def());
783 self.record_def(ty.id, PathResolution::new(def));
787 visit::walk_ty(self, ty);
789 fn visit_poly_trait_ref(&mut self,
790 tref: &'tcx ast::PolyTraitRef,
791 m: &'tcx ast::TraitBoundModifier) {
792 self.smart_resolve_path(tref.trait_ref.ref_id, None,
793 &tref.trait_ref.path, PathSource::Trait(AliasPossibility::Maybe));
794 visit::walk_poly_trait_ref(self, tref, m);
796 fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
797 let generic_params = match foreign_item.node {
798 ForeignItemKind::Fn(_, ref generics) => {
799 HasGenericParams(generics, ItemRibKind)
801 ForeignItemKind::Static(..) => NoGenericParams,
802 ForeignItemKind::Ty => NoGenericParams,
803 ForeignItemKind::Macro(..) => NoGenericParams,
805 self.with_generic_param_rib(generic_params, |this| {
806 visit::walk_foreign_item(this, foreign_item);
809 fn visit_fn(&mut self,
810 function_kind: FnKind<'tcx>,
811 declaration: &'tcx FnDecl,
815 debug!("(resolving function) entering function");
816 let (rib_kind, asyncness) = match function_kind {
817 FnKind::ItemFn(_, ref header, ..) =>
818 (FnItemRibKind, header.asyncness.node),
819 FnKind::Method(_, ref sig, _, _) =>
820 (TraitOrImplItemRibKind, sig.header.asyncness.node),
821 FnKind::Closure(_) =>
822 // Async closures aren't resolved through `visit_fn`-- they're
823 // processed separately
824 (ClosureRibKind(node_id), IsAsync::NotAsync),
827 // Create a value rib for the function.
828 self.ribs[ValueNS].push(Rib::new(rib_kind));
830 // Create a label rib for the function.
831 self.label_ribs.push(Rib::new(rib_kind));
833 // Add each argument to the rib.
834 let mut bindings_list = FxHashMap::default();
835 for argument in &declaration.inputs {
836 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
838 self.visit_ty(&argument.ty);
840 debug!("(resolving function) recorded argument");
842 visit::walk_fn_ret_ty(self, &declaration.output);
844 // Resolve the function body, potentially inside the body of an async closure
845 if let IsAsync::Async { closure_id, .. } = asyncness {
846 let rib_kind = ClosureRibKind(closure_id);
847 self.ribs[ValueNS].push(Rib::new(rib_kind));
848 self.label_ribs.push(Rib::new(rib_kind));
851 match function_kind {
852 FnKind::ItemFn(.., body) |
853 FnKind::Method(.., body) => {
854 self.visit_block(body);
856 FnKind::Closure(body) => {
857 self.visit_expr(body);
861 // Leave the body of the async closure
862 if asyncness.is_async() {
863 self.label_ribs.pop();
864 self.ribs[ValueNS].pop();
867 debug!("(resolving function) leaving function");
869 self.label_ribs.pop();
870 self.ribs[ValueNS].pop();
873 fn visit_generics(&mut self, generics: &'tcx Generics) {
874 // For type parameter defaults, we have to ban access
875 // to following type parameters, as the InternalSubsts can only
876 // provide previous type parameters as they're built. We
877 // put all the parameters on the ban list and then remove
878 // them one by one as they are processed and become available.
879 let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
880 let mut found_default = false;
881 default_ban_rib.bindings.extend(generics.params.iter()
882 .filter_map(|param| match param.kind {
883 GenericParamKind::Const { .. } |
884 GenericParamKind::Lifetime { .. } => None,
885 GenericParamKind::Type { ref default, .. } => {
886 found_default |= default.is_some();
888 Some((Ident::with_empty_ctxt(param.ident.name), Def::Err))
895 for param in &generics.params {
897 GenericParamKind::Lifetime { .. } => self.visit_generic_param(param),
898 GenericParamKind::Type { ref default, .. } => {
899 for bound in ¶m.bounds {
900 self.visit_param_bound(bound);
903 if let Some(ref ty) = default {
904 self.ribs[TypeNS].push(default_ban_rib);
906 default_ban_rib = self.ribs[TypeNS].pop().unwrap();
909 // Allow all following defaults to refer to this type parameter.
910 default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(param.ident.name));
912 GenericParamKind::Const { ref ty } => {
913 for bound in ¶m.bounds {
914 self.visit_param_bound(bound);
921 for p in &generics.where_clause.predicates {
922 self.visit_where_predicate(p);
927 #[derive(Copy, Clone)]
928 enum GenericParameters<'a, 'b> {
930 HasGenericParams(// Type parameters.
933 // The kind of the rib used for type parameters.
937 /// The rib kind controls the translation of local
938 /// definitions (`Def::Local`) to upvars (`Def::Upvar`).
939 #[derive(Copy, Clone, Debug)]
941 /// No translation needs to be applied.
944 /// We passed through a closure scope at the given `NodeId`.
945 /// Translate upvars as appropriate.
946 ClosureRibKind(NodeId /* func id */),
948 /// We passed through an impl or trait and are now in one of its
949 /// methods or associated types. Allow references to ty params that impl or trait
950 /// binds. Disallow any other upvars (including other ty params that are
952 TraitOrImplItemRibKind,
954 /// We passed through a function definition. Disallow upvars.
955 /// Permit only those const parameters that are specified in the function's generics.
958 /// We passed through an item scope. Disallow upvars.
961 /// We're in a constant item. Can't refer to dynamic stuff.
964 /// We passed through a module.
965 ModuleRibKind(Module<'a>),
967 /// We passed through a `macro_rules!` statement
968 MacroDefinition(DefId),
970 /// All bindings in this rib are type parameters that can't be used
971 /// from the default of a type parameter because they're not declared
972 /// before said type parameter. Also see the `visit_generics` override.
973 ForwardTyParamBanRibKind,
976 /// A single local scope.
978 /// A rib represents a scope names can live in. Note that these appear in many places, not just
979 /// around braces. At any place where the list of accessible names (of the given namespace)
980 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
981 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
984 /// Different [rib kinds](enum.RibKind) are transparent for different names.
986 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
987 /// resolving, the name is looked up from inside out.
990 bindings: FxHashMap<Ident, Def>,
995 fn new(kind: RibKind<'a>) -> Rib<'a> {
997 bindings: Default::default(),
1003 /// An intermediate resolution result.
1005 /// This refers to the thing referred by a name. The difference between `Def` and `Item` is that
1006 /// items are visible in their whole block, while defs only from the place they are defined
1008 enum LexicalScopeBinding<'a> {
1009 Item(&'a NameBinding<'a>),
1013 impl<'a> LexicalScopeBinding<'a> {
1014 fn item(self) -> Option<&'a NameBinding<'a>> {
1016 LexicalScopeBinding::Item(binding) => Some(binding),
1021 fn def(self) -> Def {
1023 LexicalScopeBinding::Item(binding) => binding.def(),
1024 LexicalScopeBinding::Def(def) => def,
1029 #[derive(Copy, Clone, Debug)]
1030 enum ModuleOrUniformRoot<'a> {
1034 /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
1035 CrateRootAndExternPrelude,
1037 /// Virtual module that denotes resolution in extern prelude.
1038 /// Used for paths starting with `::` on 2018 edition.
1041 /// Virtual module that denotes resolution in current scope.
1042 /// Used only for resolving single-segment imports. The reason it exists is that import paths
1043 /// are always split into two parts, the first of which should be some kind of module.
1047 impl ModuleOrUniformRoot<'_> {
1048 fn same_def(lhs: Self, rhs: Self) -> bool {
1050 (ModuleOrUniformRoot::Module(lhs),
1051 ModuleOrUniformRoot::Module(rhs)) => lhs.def() == rhs.def(),
1052 (ModuleOrUniformRoot::CrateRootAndExternPrelude,
1053 ModuleOrUniformRoot::CrateRootAndExternPrelude) |
1054 (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude) |
1055 (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true,
1061 #[derive(Clone, Debug)]
1062 enum PathResult<'a> {
1063 Module(ModuleOrUniformRoot<'a>),
1064 NonModule(PathResolution),
1069 suggestion: Option<Suggestion>,
1070 is_error_from_last_segment: bool,
1075 /// An anonymous module; e.g., just a block.
1079 /// fn f() {} // (1)
1080 /// { // This is an anonymous module
1081 /// f(); // This resolves to (2) as we are inside the block.
1082 /// fn f() {} // (2)
1084 /// f(); // Resolves to (1)
1088 /// Any module with a name.
1092 /// * A normal module ‒ either `mod from_file;` or `mod from_block { }`.
1093 /// * A trait or an enum (it implicitly contains associated types, methods and variant
1098 /// One node in the tree of modules.
1099 pub struct ModuleData<'a> {
1100 parent: Option<Module<'a>>,
1103 // The def id of the closest normal module (`mod`) ancestor (including this module).
1104 normal_ancestor_id: DefId,
1106 resolutions: RefCell<FxHashMap<(Ident, Namespace), &'a RefCell<NameResolution<'a>>>>,
1107 single_segment_macro_resolutions: RefCell<Vec<(Ident, MacroKind, ParentScope<'a>,
1108 Option<&'a NameBinding<'a>>)>>,
1109 multi_segment_macro_resolutions: RefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>,
1111 builtin_attrs: RefCell<Vec<(Ident, ParentScope<'a>)>>,
1113 // Macro invocations that can expand into items in this module.
1114 unresolved_invocations: RefCell<FxHashSet<Mark>>,
1116 no_implicit_prelude: bool,
1118 glob_importers: RefCell<Vec<&'a ImportDirective<'a>>>,
1119 globs: RefCell<Vec<&'a ImportDirective<'a>>>,
1121 // Used to memoize the traits in this module for faster searches through all traits in scope.
1122 traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
1124 // Whether this module is populated. If not populated, any attempt to
1125 // access the children must be preceded with a
1126 // `populate_module_if_necessary` call.
1127 populated: Cell<bool>,
1129 /// Span of the module itself. Used for error reporting.
1135 type Module<'a> = &'a ModuleData<'a>;
1137 impl<'a> ModuleData<'a> {
1138 fn new(parent: Option<Module<'a>>,
1140 normal_ancestor_id: DefId,
1142 span: Span) -> Self {
1147 resolutions: Default::default(),
1148 single_segment_macro_resolutions: RefCell::new(Vec::new()),
1149 multi_segment_macro_resolutions: RefCell::new(Vec::new()),
1150 builtin_attrs: RefCell::new(Vec::new()),
1151 unresolved_invocations: Default::default(),
1152 no_implicit_prelude: false,
1153 glob_importers: RefCell::new(Vec::new()),
1154 globs: RefCell::new(Vec::new()),
1155 traits: RefCell::new(None),
1156 populated: Cell::new(normal_ancestor_id.is_local()),
1162 fn for_each_child<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1163 for (&(ident, ns), name_resolution) in self.resolutions.borrow().iter() {
1164 name_resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1168 fn for_each_child_stable<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1169 let resolutions = self.resolutions.borrow();
1170 let mut resolutions = resolutions.iter().collect::<Vec<_>>();
1171 resolutions.sort_by_cached_key(|&(&(ident, ns), _)| (ident.as_str(), ns));
1172 for &(&(ident, ns), &resolution) in resolutions.iter() {
1173 resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1177 fn def(&self) -> Option<Def> {
1179 ModuleKind::Def(def, _) => Some(def),
1184 fn def_id(&self) -> Option<DefId> {
1185 self.def().as_ref().map(Def::def_id)
1188 // `self` resolves to the first module ancestor that `is_normal`.
1189 fn is_normal(&self) -> bool {
1191 ModuleKind::Def(Def::Mod(_), _) => true,
1196 fn is_trait(&self) -> bool {
1198 ModuleKind::Def(Def::Trait(_), _) => true,
1203 fn nearest_item_scope(&'a self) -> Module<'a> {
1204 if self.is_trait() { self.parent.unwrap() } else { self }
1207 fn is_ancestor_of(&self, mut other: &Self) -> bool {
1208 while !ptr::eq(self, other) {
1209 if let Some(parent) = other.parent {
1219 impl<'a> fmt::Debug for ModuleData<'a> {
1220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1221 write!(f, "{:?}", self.def())
1225 /// Records a possibly-private value, type, or module definition.
1226 #[derive(Clone, Debug)]
1227 pub struct NameBinding<'a> {
1228 kind: NameBindingKind<'a>,
1229 ambiguity: Option<(&'a NameBinding<'a>, AmbiguityKind)>,
1232 vis: ty::Visibility,
1235 pub trait ToNameBinding<'a> {
1236 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
1239 impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
1240 fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
1245 #[derive(Clone, Debug)]
1246 enum NameBindingKind<'a> {
1247 Def(Def, /* is_macro_export */ bool),
1250 binding: &'a NameBinding<'a>,
1251 directive: &'a ImportDirective<'a>,
1256 impl<'a> NameBindingKind<'a> {
1257 /// Is this a name binding of a import?
1258 fn is_import(&self) -> bool {
1260 NameBindingKind::Import { .. } => true,
1266 struct PrivacyError<'a>(Span, Ident, &'a NameBinding<'a>);
1268 struct UseError<'a> {
1269 err: DiagnosticBuilder<'a>,
1270 /// Attach `use` statements for these candidates.
1271 candidates: Vec<ImportSuggestion>,
1272 /// The `NodeId` of the module to place the use-statements in.
1274 /// Whether the diagnostic should state that it's "better".
1278 #[derive(Clone, Copy, PartialEq, Debug)]
1279 enum AmbiguityKind {
1283 LegacyHelperVsPrelude,
1288 MoreExpandedVsOuter,
1291 impl AmbiguityKind {
1292 fn descr(self) -> &'static str {
1294 AmbiguityKind::Import =>
1295 "name vs any other name during import resolution",
1296 AmbiguityKind::BuiltinAttr =>
1297 "built-in attribute vs any other name",
1298 AmbiguityKind::DeriveHelper =>
1299 "derive helper attribute vs any other name",
1300 AmbiguityKind::LegacyHelperVsPrelude =>
1301 "legacy plugin helper attribute vs name from prelude",
1302 AmbiguityKind::LegacyVsModern =>
1303 "`macro_rules` vs non-`macro_rules` from other module",
1304 AmbiguityKind::GlobVsOuter =>
1305 "glob import vs any other name from outer scope during import/macro resolution",
1306 AmbiguityKind::GlobVsGlob =>
1307 "glob import vs glob import in the same module",
1308 AmbiguityKind::GlobVsExpanded =>
1309 "glob import vs macro-expanded name in the same \
1310 module during import/macro resolution",
1311 AmbiguityKind::MoreExpandedVsOuter =>
1312 "macro-expanded name vs less macro-expanded name \
1313 from outer scope during import/macro resolution",
1318 /// Miscellaneous bits of metadata for better ambiguity error reporting.
1319 #[derive(Clone, Copy, PartialEq)]
1320 enum AmbiguityErrorMisc {
1327 struct AmbiguityError<'a> {
1328 kind: AmbiguityKind,
1330 b1: &'a NameBinding<'a>,
1331 b2: &'a NameBinding<'a>,
1332 misc1: AmbiguityErrorMisc,
1333 misc2: AmbiguityErrorMisc,
1336 impl<'a> NameBinding<'a> {
1337 fn module(&self) -> Option<Module<'a>> {
1339 NameBindingKind::Module(module) => Some(module),
1340 NameBindingKind::Import { binding, .. } => binding.module(),
1345 fn def(&self) -> Def {
1347 NameBindingKind::Def(def, _) => def,
1348 NameBindingKind::Module(module) => module.def().unwrap(),
1349 NameBindingKind::Import { binding, .. } => binding.def(),
1353 fn is_ambiguity(&self) -> bool {
1354 self.ambiguity.is_some() || match self.kind {
1355 NameBindingKind::Import { binding, .. } => binding.is_ambiguity(),
1360 // We sometimes need to treat variants as `pub` for backwards compatibility.
1361 fn pseudo_vis(&self) -> ty::Visibility {
1362 if self.is_variant() && self.def().def_id().is_local() {
1363 ty::Visibility::Public
1369 fn is_variant(&self) -> bool {
1371 NameBindingKind::Def(Def::Variant(..), _) |
1372 NameBindingKind::Def(Def::Ctor(_, CtorOf::Variant, ..), _) => true,
1377 fn is_extern_crate(&self) -> bool {
1379 NameBindingKind::Import {
1380 directive: &ImportDirective {
1381 subclass: ImportDirectiveSubclass::ExternCrate { .. }, ..
1384 NameBindingKind::Module(
1385 &ModuleData { kind: ModuleKind::Def(Def::Mod(def_id), _), .. }
1386 ) => def_id.index == CRATE_DEF_INDEX,
1391 fn is_import(&self) -> bool {
1393 NameBindingKind::Import { .. } => true,
1398 fn is_glob_import(&self) -> bool {
1400 NameBindingKind::Import { directive, .. } => directive.is_glob(),
1405 fn is_importable(&self) -> bool {
1407 Def::AssociatedConst(..) | Def::Method(..) | Def::AssociatedTy(..) => false,
1412 fn is_macro_def(&self) -> bool {
1414 NameBindingKind::Def(Def::Macro(..), _) => true,
1419 fn macro_kind(&self) -> Option<MacroKind> {
1421 Def::Macro(_, kind) => Some(kind),
1422 Def::NonMacroAttr(..) => Some(MacroKind::Attr),
1427 fn descr(&self) -> &'static str {
1428 if self.is_extern_crate() { "extern crate" } else { self.def().kind_name() }
1431 fn article(&self) -> &'static str {
1432 if self.is_extern_crate() { "an" } else { self.def().article() }
1435 // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
1436 // at some expansion round `max(invoc, binding)` when they both emerged from macros.
1437 // Then this function returns `true` if `self` may emerge from a macro *after* that
1438 // in some later round and screw up our previously found resolution.
1439 // See more detailed explanation in
1440 // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
1441 fn may_appear_after(&self, invoc_parent_expansion: Mark, binding: &NameBinding<'_>) -> bool {
1442 // self > max(invoc, binding) => !(self <= invoc || self <= binding)
1443 // Expansions are partially ordered, so "may appear after" is an inversion of
1444 // "certainly appears before or simultaneously" and includes unordered cases.
1445 let self_parent_expansion = self.expansion;
1446 let other_parent_expansion = binding.expansion;
1447 let certainly_before_other_or_simultaneously =
1448 other_parent_expansion.is_descendant_of(self_parent_expansion);
1449 let certainly_before_invoc_or_simultaneously =
1450 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1451 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1455 /// Interns the names of the primitive types.
1457 /// All other types are defined somewhere and possibly imported, but the primitive ones need
1458 /// special handling, since they have no place of origin.
1460 struct PrimitiveTypeTable {
1461 primitive_types: FxHashMap<Name, PrimTy>,
1464 impl PrimitiveTypeTable {
1465 fn new() -> PrimitiveTypeTable {
1466 let mut table = PrimitiveTypeTable::default();
1468 table.intern("bool", Bool);
1469 table.intern("char", Char);
1470 table.intern("f32", Float(FloatTy::F32));
1471 table.intern("f64", Float(FloatTy::F64));
1472 table.intern("isize", Int(IntTy::Isize));
1473 table.intern("i8", Int(IntTy::I8));
1474 table.intern("i16", Int(IntTy::I16));
1475 table.intern("i32", Int(IntTy::I32));
1476 table.intern("i64", Int(IntTy::I64));
1477 table.intern("i128", Int(IntTy::I128));
1478 table.intern("str", Str);
1479 table.intern("usize", Uint(UintTy::Usize));
1480 table.intern("u8", Uint(UintTy::U8));
1481 table.intern("u16", Uint(UintTy::U16));
1482 table.intern("u32", Uint(UintTy::U32));
1483 table.intern("u64", Uint(UintTy::U64));
1484 table.intern("u128", Uint(UintTy::U128));
1488 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1489 self.primitive_types.insert(Symbol::intern(string), primitive_type);
1493 #[derive(Debug, Default, Clone)]
1494 pub struct ExternPreludeEntry<'a> {
1495 extern_crate_item: Option<&'a NameBinding<'a>>,
1496 pub introduced_by_item: bool,
1499 /// The main resolver class.
1501 /// This is the visitor that walks the whole crate.
1502 pub struct Resolver<'a> {
1503 session: &'a Session,
1506 pub definitions: Definitions,
1508 graph_root: Module<'a>,
1510 prelude: Option<Module<'a>>,
1511 pub extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
1513 /// N.B., this is used only for better diagnostics, not name resolution itself.
1514 has_self: FxHashSet<DefId>,
1516 /// Names of fields of an item `DefId` accessible with dot syntax.
1517 /// Used for hints during error reporting.
1518 field_names: FxHashMap<DefId, Vec<Name>>,
1520 /// All imports known to succeed or fail.
1521 determined_imports: Vec<&'a ImportDirective<'a>>,
1523 /// All non-determined imports.
1524 indeterminate_imports: Vec<&'a ImportDirective<'a>>,
1526 /// The module that represents the current item scope.
1527 current_module: Module<'a>,
1529 /// The current set of local scopes for types and values.
1530 /// FIXME #4948: Reuse ribs to avoid allocation.
1531 ribs: PerNS<Vec<Rib<'a>>>,
1533 /// The current set of local scopes, for labels.
1534 label_ribs: Vec<Rib<'a>>,
1536 /// The trait that the current context can refer to.
1537 current_trait_ref: Option<(Module<'a>, TraitRef)>,
1539 /// The current self type if inside an impl (used for better errors).
1540 current_self_type: Option<Ty>,
1542 /// The current self item if inside an ADT (used for better errors).
1543 current_self_item: Option<NodeId>,
1545 /// FIXME: Refactor things so that these fields are passed through arguments and not resolver.
1546 /// We are resolving a last import segment during import validation.
1547 last_import_segment: bool,
1548 /// This binding should be ignored during in-module resolution, so that we don't get
1549 /// "self-confirming" import resolutions during import validation.
1550 blacklisted_binding: Option<&'a NameBinding<'a>>,
1552 /// The idents for the primitive types.
1553 primitive_type_table: PrimitiveTypeTable,
1556 import_map: ImportMap,
1557 pub freevars: FreevarMap,
1558 freevars_seen: NodeMap<NodeMap<usize>>,
1559 pub export_map: ExportMap,
1560 pub trait_map: TraitMap,
1562 /// A map from nodes to anonymous modules.
1563 /// Anonymous modules are pseudo-modules that are implicitly created around items
1564 /// contained within blocks.
1566 /// For example, if we have this:
1574 /// There will be an anonymous module created around `g` with the ID of the
1575 /// entry block for `f`.
1576 block_map: NodeMap<Module<'a>>,
1577 module_map: FxHashMap<DefId, Module<'a>>,
1578 extern_module_map: FxHashMap<(DefId, bool /* MacrosOnly? */), Module<'a>>,
1579 binding_parent_modules: FxHashMap<PtrKey<'a, NameBinding<'a>>, Module<'a>>,
1581 /// Maps glob imports to the names of items actually imported.
1582 pub glob_map: GlobMap,
1584 used_imports: FxHashSet<(NodeId, Namespace)>,
1585 pub maybe_unused_trait_imports: NodeSet,
1586 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
1588 /// A list of labels as of yet unused. Labels will be removed from this map when
1589 /// they are used (in a `break` or `continue` statement)
1590 pub unused_labels: FxHashMap<NodeId, Span>,
1592 /// Privacy errors are delayed until the end in order to deduplicate them.
1593 privacy_errors: Vec<PrivacyError<'a>>,
1594 /// Ambiguity errors are delayed for deduplication.
1595 ambiguity_errors: Vec<AmbiguityError<'a>>,
1596 /// `use` injections are delayed for better placement and deduplication.
1597 use_injections: Vec<UseError<'a>>,
1598 /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
1599 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
1601 arenas: &'a ResolverArenas<'a>,
1602 dummy_binding: &'a NameBinding<'a>,
1604 crate_loader: &'a mut CrateLoader<'a>,
1605 macro_names: FxHashSet<Ident>,
1606 builtin_macros: FxHashMap<Name, &'a NameBinding<'a>>,
1607 macro_use_prelude: FxHashMap<Name, &'a NameBinding<'a>>,
1608 pub all_macros: FxHashMap<Name, Def>,
1609 macro_map: FxHashMap<DefId, Lrc<SyntaxExtension>>,
1610 macro_defs: FxHashMap<Mark, DefId>,
1611 local_macro_def_scopes: FxHashMap<NodeId, Module<'a>>,
1613 /// List of crate local macros that we need to warn about as being unused.
1614 /// Right now this only includes macro_rules! macros, and macros 2.0.
1615 unused_macros: FxHashSet<DefId>,
1617 /// Maps the `Mark` of an expansion to its containing module or block.
1618 invocations: FxHashMap<Mark, &'a InvocationData<'a>>,
1620 /// Avoid duplicated errors for "name already defined".
1621 name_already_seen: FxHashMap<Name, Span>,
1623 potentially_unused_imports: Vec<&'a ImportDirective<'a>>,
1625 /// Table for mapping struct IDs into struct constructor IDs,
1626 /// it's not used during normal resolution, only for better error reporting.
1627 struct_constructors: DefIdMap<(Def, ty::Visibility)>,
1629 /// Only used for better errors on `fn(): fn()`.
1630 current_type_ascription: Vec<Span>,
1632 injected_crate: Option<Module<'a>>,
1635 /// Nothing really interesting here; it just provides memory for the rest of the crate.
1637 pub struct ResolverArenas<'a> {
1638 modules: arena::TypedArena<ModuleData<'a>>,
1639 local_modules: RefCell<Vec<Module<'a>>>,
1640 name_bindings: arena::TypedArena<NameBinding<'a>>,
1641 import_directives: arena::TypedArena<ImportDirective<'a>>,
1642 name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1643 invocation_data: arena::TypedArena<InvocationData<'a>>,
1644 legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
1647 impl<'a> ResolverArenas<'a> {
1648 fn alloc_module(&'a self, module: ModuleData<'a>) -> Module<'a> {
1649 let module = self.modules.alloc(module);
1650 if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) {
1651 self.local_modules.borrow_mut().push(module);
1655 fn local_modules(&'a self) -> std::cell::Ref<'a, Vec<Module<'a>>> {
1656 self.local_modules.borrow()
1658 fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1659 self.name_bindings.alloc(name_binding)
1661 fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
1662 -> &'a ImportDirective<'_> {
1663 self.import_directives.alloc(import_directive)
1665 fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1666 self.name_resolutions.alloc(Default::default())
1668 fn alloc_invocation_data(&'a self, expansion_data: InvocationData<'a>)
1669 -> &'a InvocationData<'a> {
1670 self.invocation_data.alloc(expansion_data)
1672 fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
1673 self.legacy_bindings.alloc(binding)
1677 impl<'a, 'b: 'a> ty::DefIdTree for &'a Resolver<'b> {
1678 fn parent(self, id: DefId) -> Option<DefId> {
1680 LOCAL_CRATE => self.definitions.def_key(id.index).parent,
1681 _ => self.cstore.def_key(id).parent,
1682 }.map(|index| DefId { index, ..id })
1686 /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that
1687 /// the resolver is no longer needed as all the relevant information is inline.
1688 impl<'a> hir::lowering::Resolver for Resolver<'a> {
1689 fn resolve_hir_path(
1694 self.resolve_hir_path_cb(path, is_value,
1695 |resolver, span, error| resolve_error(resolver, span, error))
1698 fn resolve_str_path(
1701 crate_root: Option<&str>,
1702 components: &[&str],
1705 let root = if crate_root.is_some() {
1710 let segments = iter::once(root.ident())
1712 crate_root.into_iter()
1713 .chain(components.iter().cloned())
1714 .map(Ident::from_str)
1715 ).map(|i| self.new_ast_path_segment(i)).collect::<Vec<_>>();
1718 let path = ast::Path {
1723 self.resolve_hir_path(&path, is_value)
1726 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution> {
1727 self.def_map.get(&id).cloned()
1730 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>> {
1731 self.import_map.get(&id).cloned().unwrap_or_default()
1734 fn definitions(&mut self) -> &mut Definitions {
1735 &mut self.definitions
1739 impl<'a> Resolver<'a> {
1740 /// Rustdoc uses this to resolve things in a recoverable way. `ResolutionError<'a>`
1741 /// isn't something that can be returned because it can't be made to live that long,
1742 /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1743 /// just that an error occurred.
1744 pub fn resolve_str_path_error(&mut self, span: Span, path_str: &str, is_value: bool)
1745 -> Result<hir::Path, ()> {
1746 let mut errored = false;
1748 let path = if path_str.starts_with("::") {
1751 segments: iter::once(keywords::PathRoot.ident())
1753 path_str.split("::").skip(1).map(Ident::from_str)
1755 .map(|i| self.new_ast_path_segment(i))
1763 .map(Ident::from_str)
1764 .map(|i| self.new_ast_path_segment(i))
1768 let path = self.resolve_hir_path_cb(&path, is_value, |_, _, _| errored = true);
1769 if errored || path.def == Def::Err {
1776 /// Like `resolve_hir_path`, but takes a callback in case there was an error.
1777 fn resolve_hir_path_cb<F>(
1783 where F: for<'c, 'b> FnOnce(&'c mut Resolver<'_>, Span, ResolutionError<'b>)
1785 let namespace = if is_value { ValueNS } else { TypeNS };
1786 let span = path.span;
1787 let segments = &path.segments;
1788 let path = Segment::from_path(&path);
1789 // FIXME(Manishearth): intra-doc links won't get warned of epoch changes.
1790 let def = match self.resolve_path_without_parent_scope(&path, Some(namespace), true,
1791 span, CrateLint::No) {
1792 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1793 module.def().unwrap(),
1794 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 =>
1795 path_res.base_def(),
1796 PathResult::NonModule(..) => {
1797 error_callback(self, span, ResolutionError::FailedToResolve {
1798 label: String::from("type-relative paths are not supported in this context"),
1803 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
1804 PathResult::Failed { span, label, suggestion, .. } => {
1805 error_callback(self, span, ResolutionError::FailedToResolve {
1813 let segments: Vec<_> = segments.iter().map(|seg| {
1814 let mut hir_seg = hir::PathSegment::from_ident(seg.ident);
1815 hir_seg.def = Some(self.def_map.get(&seg.id).map_or(Def::Err, |p| p.base_def()));
1821 segments: segments.into(),
1825 fn new_ast_path_segment(&self, ident: Ident) -> ast::PathSegment {
1826 let mut seg = ast::PathSegment::from_ident(ident);
1827 seg.id = self.session.next_node_id();
1832 impl<'a> Resolver<'a> {
1833 pub fn new(session: &'a Session,
1837 crate_loader: &'a mut CrateLoader<'a>,
1838 arenas: &'a ResolverArenas<'a>)
1840 let root_def_id = DefId::local(CRATE_DEF_INDEX);
1841 let root_module_kind = ModuleKind::Def(Def::Mod(root_def_id), keywords::Invalid.name());
1842 let graph_root = arenas.alloc_module(ModuleData {
1843 no_implicit_prelude: attr::contains_name(&krate.attrs, "no_implicit_prelude"),
1844 ..ModuleData::new(None, root_module_kind, root_def_id, Mark::root(), krate.span)
1846 let mut module_map = FxHashMap::default();
1847 module_map.insert(DefId::local(CRATE_DEF_INDEX), graph_root);
1849 let mut definitions = Definitions::new();
1850 DefCollector::new(&mut definitions, Mark::root())
1851 .collect_root(crate_name, session.local_crate_disambiguator());
1853 let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'_>> =
1854 session.opts.externs.iter().map(|kv| (Ident::from_str(kv.0), Default::default()))
1857 if !attr::contains_name(&krate.attrs, "no_core") {
1858 extern_prelude.insert(Ident::from_str("core"), Default::default());
1859 if !attr::contains_name(&krate.attrs, "no_std") {
1860 extern_prelude.insert(Ident::from_str("std"), Default::default());
1861 if session.rust_2018() {
1862 extern_prelude.insert(Ident::from_str("meta"), Default::default());
1867 let mut invocations = FxHashMap::default();
1868 invocations.insert(Mark::root(),
1869 arenas.alloc_invocation_data(InvocationData::root(graph_root)));
1871 let mut macro_defs = FxHashMap::default();
1872 macro_defs.insert(Mark::root(), root_def_id);
1881 // The outermost module has def ID 0; this is not reflected in the
1887 has_self: FxHashSet::default(),
1888 field_names: FxHashMap::default(),
1890 determined_imports: Vec::new(),
1891 indeterminate_imports: Vec::new(),
1893 current_module: graph_root,
1895 value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1896 type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1897 macro_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1899 label_ribs: Vec::new(),
1901 current_trait_ref: None,
1902 current_self_type: None,
1903 current_self_item: None,
1904 last_import_segment: false,
1905 blacklisted_binding: None,
1907 primitive_type_table: PrimitiveTypeTable::new(),
1909 def_map: Default::default(),
1910 import_map: Default::default(),
1911 freevars: Default::default(),
1912 freevars_seen: Default::default(),
1913 export_map: FxHashMap::default(),
1914 trait_map: Default::default(),
1916 block_map: Default::default(),
1917 extern_module_map: FxHashMap::default(),
1918 binding_parent_modules: FxHashMap::default(),
1920 glob_map: Default::default(),
1922 used_imports: FxHashSet::default(),
1923 maybe_unused_trait_imports: Default::default(),
1924 maybe_unused_extern_crates: Vec::new(),
1926 unused_labels: FxHashMap::default(),
1928 privacy_errors: Vec::new(),
1929 ambiguity_errors: Vec::new(),
1930 use_injections: Vec::new(),
1931 macro_expanded_macro_export_errors: BTreeSet::new(),
1934 dummy_binding: arenas.alloc_name_binding(NameBinding {
1935 kind: NameBindingKind::Def(Def::Err, false),
1937 expansion: Mark::root(),
1939 vis: ty::Visibility::Public,
1943 macro_names: FxHashSet::default(),
1944 builtin_macros: FxHashMap::default(),
1945 macro_use_prelude: FxHashMap::default(),
1946 all_macros: FxHashMap::default(),
1947 macro_map: FxHashMap::default(),
1950 local_macro_def_scopes: FxHashMap::default(),
1951 name_already_seen: FxHashMap::default(),
1952 potentially_unused_imports: Vec::new(),
1953 struct_constructors: Default::default(),
1954 unused_macros: FxHashSet::default(),
1955 current_type_ascription: Vec::new(),
1956 injected_crate: None,
1960 pub fn arenas() -> ResolverArenas<'a> {
1964 /// Runs the function on each namespace.
1965 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1971 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1973 match self.macro_defs.get(&ctxt.outer()) {
1974 Some(&def_id) => return def_id,
1975 None => ctxt.remove_mark(),
1980 /// Entry point to crate resolution.
1981 pub fn resolve_crate(&mut self, krate: &Crate) {
1982 ImportResolver { resolver: self }.finalize_imports();
1983 self.current_module = self.graph_root;
1984 self.finalize_current_module_macro_resolutions();
1986 visit::walk_crate(self, krate);
1988 check_unused::check_crate(self, krate);
1989 self.report_errors(krate);
1990 self.crate_loader.postprocess(krate);
1997 normal_ancestor_id: DefId,
2001 let module = ModuleData::new(Some(parent), kind, normal_ancestor_id, expansion, span);
2002 self.arenas.alloc_module(module)
2005 fn record_use(&mut self, ident: Ident, ns: Namespace,
2006 used_binding: &'a NameBinding<'a>, is_lexical_scope: bool) {
2007 if let Some((b2, kind)) = used_binding.ambiguity {
2008 self.ambiguity_errors.push(AmbiguityError {
2009 kind, ident, b1: used_binding, b2,
2010 misc1: AmbiguityErrorMisc::None,
2011 misc2: AmbiguityErrorMisc::None,
2014 if let NameBindingKind::Import { directive, binding, ref used } = used_binding.kind {
2015 // Avoid marking `extern crate` items that refer to a name from extern prelude,
2016 // but not introduce it, as used if they are accessed from lexical scope.
2017 if is_lexical_scope {
2018 if let Some(entry) = self.extern_prelude.get(&ident.modern()) {
2019 if let Some(crate_item) = entry.extern_crate_item {
2020 if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
2027 directive.used.set(true);
2028 self.used_imports.insert((directive.id, ns));
2029 self.add_to_glob_map(&directive, ident);
2030 self.record_use(ident, ns, binding, false);
2035 fn add_to_glob_map(&mut self, directive: &ImportDirective<'_>, ident: Ident) {
2036 if directive.is_glob() {
2037 self.glob_map.entry(directive.id).or_default().insert(ident.name);
2041 /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
2042 /// More specifically, we proceed up the hierarchy of scopes and return the binding for
2043 /// `ident` in the first scope that defines it (or None if no scopes define it).
2045 /// A block's items are above its local variables in the scope hierarchy, regardless of where
2046 /// the items are defined in the block. For example,
2049 /// g(); // Since there are no local variables in scope yet, this resolves to the item.
2052 /// g(); // This resolves to the local variable `g` since it shadows the item.
2056 /// Invariant: This must only be called during main resolution, not during
2057 /// import resolution.
2058 fn resolve_ident_in_lexical_scope(&mut self,
2061 record_used_id: Option<NodeId>,
2063 -> Option<LexicalScopeBinding<'a>> {
2064 assert!(ns == TypeNS || ns == ValueNS);
2065 if ident.name == keywords::Invalid.name() {
2066 return Some(LexicalScopeBinding::Def(Def::Err));
2068 ident.span = if ident.name == keywords::SelfUpper.name() {
2069 // FIXME(jseyfried) improve `Self` hygiene
2070 ident.span.with_ctxt(SyntaxContext::empty())
2071 } else if ns == TypeNS {
2074 ident.span.modern_and_legacy()
2077 // Walk backwards up the ribs in scope.
2078 let record_used = record_used_id.is_some();
2079 let mut module = self.graph_root;
2080 for i in (0 .. self.ribs[ns].len()).rev() {
2081 debug!("walk rib\n{:?}", self.ribs[ns][i].bindings);
2082 if let Some(def) = self.ribs[ns][i].bindings.get(&ident).cloned() {
2083 // The ident resolves to a type parameter or local variable.
2084 return Some(LexicalScopeBinding::Def(
2085 self.adjust_local_def(ns, i, def, record_used, path_span)
2089 module = match self.ribs[ns][i].kind {
2090 ModuleRibKind(module) => module,
2091 MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => {
2092 // If an invocation of this macro created `ident`, give up on `ident`
2093 // and switch to `ident`'s source from the macro definition.
2094 ident.span.remove_mark();
2100 let item = self.resolve_ident_in_module_unadjusted(
2101 ModuleOrUniformRoot::Module(module),
2107 if let Ok(binding) = item {
2108 // The ident resolves to an item.
2109 return Some(LexicalScopeBinding::Item(binding));
2113 ModuleKind::Block(..) => {}, // We can see through blocks
2118 ident.span = ident.span.modern();
2119 let mut poisoned = None;
2121 let opt_module = if let Some(node_id) = record_used_id {
2122 self.hygienic_lexical_parent_with_compatibility_fallback(module, &mut ident.span,
2123 node_id, &mut poisoned)
2125 self.hygienic_lexical_parent(module, &mut ident.span)
2127 module = unwrap_or!(opt_module, break);
2128 let orig_current_module = self.current_module;
2129 self.current_module = module; // Lexical resolutions can never be a privacy error.
2130 let result = self.resolve_ident_in_module_unadjusted(
2131 ModuleOrUniformRoot::Module(module),
2137 self.current_module = orig_current_module;
2141 if let Some(node_id) = poisoned {
2142 self.session.buffer_lint_with_diagnostic(
2143 lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
2144 node_id, ident.span,
2145 &format!("cannot find {} `{}` in this scope", ns.descr(), ident),
2146 lint::builtin::BuiltinLintDiagnostics::
2147 ProcMacroDeriveResolutionFallback(ident.span),
2150 return Some(LexicalScopeBinding::Item(binding))
2152 Err(Determined) => continue,
2153 Err(Undetermined) =>
2154 span_bug!(ident.span, "undetermined resolution during main resolution pass"),
2158 if !module.no_implicit_prelude {
2160 if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
2161 return Some(LexicalScopeBinding::Item(binding));
2164 if ns == TypeNS && is_known_tool(ident.name) {
2165 let binding = (Def::ToolMod, ty::Visibility::Public,
2166 DUMMY_SP, Mark::root()).to_name_binding(self.arenas);
2167 return Some(LexicalScopeBinding::Item(binding));
2169 if let Some(prelude) = self.prelude {
2170 if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
2171 ModuleOrUniformRoot::Module(prelude),
2177 return Some(LexicalScopeBinding::Item(binding));
2185 fn hygienic_lexical_parent(&mut self, module: Module<'a>, span: &mut Span)
2186 -> Option<Module<'a>> {
2187 if !module.expansion.is_descendant_of(span.ctxt().outer()) {
2188 return Some(self.macro_def_scope(span.remove_mark()));
2191 if let ModuleKind::Block(..) = module.kind {
2192 return Some(module.parent.unwrap());
2198 fn hygienic_lexical_parent_with_compatibility_fallback(&mut self, module: Module<'a>,
2199 span: &mut Span, node_id: NodeId,
2200 poisoned: &mut Option<NodeId>)
2201 -> Option<Module<'a>> {
2202 if let module @ Some(..) = self.hygienic_lexical_parent(module, span) {
2206 // We need to support the next case under a deprecation warning
2209 // ---- begin: this comes from a proc macro derive
2210 // mod implementation_details {
2211 // // Note that `MyStruct` is not in scope here.
2212 // impl SomeTrait for MyStruct { ... }
2216 // So we have to fall back to the module's parent during lexical resolution in this case.
2217 if let Some(parent) = module.parent {
2218 // Inner module is inside the macro, parent module is outside of the macro.
2219 if module.expansion != parent.expansion &&
2220 module.expansion.is_descendant_of(parent.expansion) {
2221 // The macro is a proc macro derive
2222 if module.expansion.looks_like_proc_macro_derive() {
2223 if parent.expansion.is_descendant_of(span.ctxt().outer()) {
2224 *poisoned = Some(node_id);
2225 return module.parent;
2234 fn resolve_ident_in_module(
2236 module: ModuleOrUniformRoot<'a>,
2239 parent_scope: Option<&ParentScope<'a>>,
2242 ) -> Result<&'a NameBinding<'a>, Determinacy> {
2243 self.resolve_ident_in_module_ext(
2244 module, ident, ns, parent_scope, record_used, path_span
2245 ).map_err(|(determinacy, _)| determinacy)
2248 fn resolve_ident_in_module_ext(
2250 module: ModuleOrUniformRoot<'a>,
2253 parent_scope: Option<&ParentScope<'a>>,
2256 ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
2257 let orig_current_module = self.current_module;
2259 ModuleOrUniformRoot::Module(module) => {
2260 ident.span = ident.span.modern();
2261 if let Some(def) = ident.span.adjust(module.expansion) {
2262 self.current_module = self.macro_def_scope(def);
2265 ModuleOrUniformRoot::ExternPrelude => {
2266 ident.span = ident.span.modern();
2267 ident.span.adjust(Mark::root());
2269 ModuleOrUniformRoot::CrateRootAndExternPrelude |
2270 ModuleOrUniformRoot::CurrentScope => {
2274 let result = self.resolve_ident_in_module_unadjusted_ext(
2275 module, ident, ns, parent_scope, false, record_used, path_span,
2277 self.current_module = orig_current_module;
2281 fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> {
2282 let mut ctxt = ident.span.ctxt();
2283 let mark = if ident.name == keywords::DollarCrate.name() {
2284 // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
2285 // we don't want to pretend that the `macro_rules!` definition is in the `macro`
2286 // as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks.
2287 // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
2288 // definitions actually produced by `macro` and `macro` definitions produced by
2289 // `macro_rules!`, but at least such configurations are not stable yet.
2290 ctxt = ctxt.modern_and_legacy();
2291 let mut iter = ctxt.marks().into_iter().rev().peekable();
2292 let mut result = None;
2293 // Find the last modern mark from the end if it exists.
2294 while let Some(&(mark, transparency)) = iter.peek() {
2295 if transparency == Transparency::Opaque {
2296 result = Some(mark);
2302 // Then find the last legacy mark from the end if it exists.
2303 for (mark, transparency) in iter {
2304 if transparency == Transparency::SemiTransparent {
2305 result = Some(mark);
2312 ctxt = ctxt.modern();
2313 ctxt.adjust(Mark::root())
2315 let module = match mark {
2316 Some(def) => self.macro_def_scope(def),
2317 None => return self.graph_root,
2319 self.get_module(DefId { index: CRATE_DEF_INDEX, ..module.normal_ancestor_id })
2322 fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
2323 let mut module = self.get_module(module.normal_ancestor_id);
2324 while module.span.ctxt().modern() != *ctxt {
2325 let parent = module.parent.unwrap_or_else(|| self.macro_def_scope(ctxt.remove_mark()));
2326 module = self.get_module(parent.normal_ancestor_id);
2333 // We maintain a list of value ribs and type ribs.
2335 // Simultaneously, we keep track of the current position in the module
2336 // graph in the `current_module` pointer. When we go to resolve a name in
2337 // the value or type namespaces, we first look through all the ribs and
2338 // then query the module graph. When we resolve a name in the module
2339 // namespace, we can skip all the ribs (since nested modules are not
2340 // allowed within blocks in Rust) and jump straight to the current module
2343 // Named implementations are handled separately. When we find a method
2344 // call, we consult the module node to find all of the implementations in
2345 // scope. This information is lazily cached in the module node. We then
2346 // generate a fake "implementation scope" containing all the
2347 // implementations thus found, for compatibility with old resolve pass.
2349 pub fn with_scope<F, T>(&mut self, id: NodeId, f: F) -> T
2350 where F: FnOnce(&mut Resolver<'_>) -> T
2352 let id = self.definitions.local_def_id(id);
2353 let module = self.module_map.get(&id).cloned(); // clones a reference
2354 if let Some(module) = module {
2355 // Move down in the graph.
2356 let orig_module = replace(&mut self.current_module, module);
2357 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
2358 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
2360 self.finalize_current_module_macro_resolutions();
2363 self.current_module = orig_module;
2364 self.ribs[ValueNS].pop();
2365 self.ribs[TypeNS].pop();
2372 /// Searches the current set of local scopes for labels. Returns the first non-`None` label that
2373 /// is returned by the given predicate function
2375 /// Stops after meeting a closure.
2376 fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
2377 where P: Fn(&Rib<'_>, Ident) -> Option<R>
2379 for rib in self.label_ribs.iter().rev() {
2382 // If an invocation of this macro created `ident`, give up on `ident`
2383 // and switch to `ident`'s source from the macro definition.
2384 MacroDefinition(def) => {
2385 if def == self.macro_def(ident.span.ctxt()) {
2386 ident.span.remove_mark();
2390 // Do not resolve labels across function boundary
2394 let r = pred(rib, ident);
2402 fn resolve_adt(&mut self, item: &Item, generics: &Generics) {
2403 debug!("resolve_adt");
2404 self.with_current_self_item(item, |this| {
2405 this.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2406 let item_def_id = this.definitions.local_def_id(item.id);
2407 this.with_self_rib(Def::SelfTy(None, Some(item_def_id)), |this| {
2408 visit::walk_item(this, item);
2414 fn future_proof_import(&mut self, use_tree: &ast::UseTree) {
2415 let segments = &use_tree.prefix.segments;
2416 if !segments.is_empty() {
2417 let ident = segments[0].ident;
2418 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
2422 let nss = match use_tree.kind {
2423 ast::UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
2426 let report_error = |this: &Self, ns| {
2427 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2428 this.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
2432 match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
2433 Some(LexicalScopeBinding::Def(..)) => {
2434 report_error(self, ns);
2436 Some(LexicalScopeBinding::Item(binding)) => {
2437 let orig_blacklisted_binding =
2438 mem::replace(&mut self.blacklisted_binding, Some(binding));
2439 if let Some(LexicalScopeBinding::Def(..)) =
2440 self.resolve_ident_in_lexical_scope(ident, ns, None,
2441 use_tree.prefix.span) {
2442 report_error(self, ns);
2444 self.blacklisted_binding = orig_blacklisted_binding;
2449 } else if let ast::UseTreeKind::Nested(use_trees) = &use_tree.kind {
2450 for (use_tree, _) in use_trees {
2451 self.future_proof_import(use_tree);
2456 fn resolve_item(&mut self, item: &Item) {
2457 let name = item.ident.name;
2458 debug!("(resolving item) resolving {} ({:?})", name, item.node);
2461 ItemKind::Ty(_, ref generics) |
2462 ItemKind::Fn(_, _, ref generics, _) |
2463 ItemKind::Existential(_, ref generics) => {
2464 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind),
2465 |this| visit::walk_item(this, item));
2468 ItemKind::Enum(_, ref generics) |
2469 ItemKind::Struct(_, ref generics) |
2470 ItemKind::Union(_, ref generics) => {
2471 self.resolve_adt(item, generics);
2474 ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
2475 self.resolve_implementation(generics,
2481 ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
2482 // Create a new rib for the trait-wide type parameters.
2483 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2484 let local_def_id = this.definitions.local_def_id(item.id);
2485 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
2486 this.visit_generics(generics);
2487 walk_list!(this, visit_param_bound, bounds);
2489 for trait_item in trait_items {
2490 let generic_params = HasGenericParams(&trait_item.generics,
2491 TraitOrImplItemRibKind);
2492 this.with_generic_param_rib(generic_params, |this| {
2493 match trait_item.node {
2494 TraitItemKind::Const(ref ty, ref default) => {
2497 // Only impose the restrictions of
2498 // ConstRibKind for an actual constant
2499 // expression in a provided default.
2500 if let Some(ref expr) = *default{
2501 this.with_constant_rib(|this| {
2502 this.visit_expr(expr);
2506 TraitItemKind::Method(_, _) => {
2507 visit::walk_trait_item(this, trait_item)
2509 TraitItemKind::Type(..) => {
2510 visit::walk_trait_item(this, trait_item)
2512 TraitItemKind::Macro(_) => {
2513 panic!("unexpanded macro in resolve!")
2522 ItemKind::TraitAlias(ref generics, ref bounds) => {
2523 // Create a new rib for the trait-wide type parameters.
2524 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2525 let local_def_id = this.definitions.local_def_id(item.id);
2526 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
2527 this.visit_generics(generics);
2528 walk_list!(this, visit_param_bound, bounds);
2533 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
2534 self.with_scope(item.id, |this| {
2535 visit::walk_item(this, item);
2539 ItemKind::Static(ref ty, _, ref expr) |
2540 ItemKind::Const(ref ty, ref expr) => {
2541 debug!("resolve_item ItemKind::Const");
2542 self.with_item_rib(|this| {
2544 this.with_constant_rib(|this| {
2545 this.visit_expr(expr);
2550 ItemKind::Use(ref use_tree) => {
2551 self.future_proof_import(use_tree);
2554 ItemKind::ExternCrate(..) |
2555 ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
2556 // do nothing, these are just around to be encoded
2559 ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
2563 fn with_generic_param_rib<'b, F>(&'b mut self, generic_params: GenericParameters<'a, 'b>, f: F)
2564 where F: FnOnce(&mut Resolver<'_>)
2566 debug!("with_generic_param_rib");
2567 match generic_params {
2568 HasGenericParams(generics, rib_kind) => {
2569 let mut function_type_rib = Rib::new(rib_kind);
2570 let mut function_value_rib = Rib::new(rib_kind);
2571 let mut seen_bindings = FxHashMap::default();
2572 for param in &generics.params {
2574 GenericParamKind::Lifetime { .. } => {}
2575 GenericParamKind::Type { .. } => {
2576 let ident = param.ident.modern();
2577 debug!("with_generic_param_rib: {}", param.id);
2579 if seen_bindings.contains_key(&ident) {
2580 let span = seen_bindings.get(&ident).unwrap();
2581 let err = ResolutionError::NameAlreadyUsedInParameterList(
2585 resolve_error(self, param.ident.span, err);
2587 seen_bindings.entry(ident).or_insert(param.ident.span);
2589 // Plain insert (no renaming).
2590 let def = Def::TyParam(self.definitions.local_def_id(param.id));
2591 function_type_rib.bindings.insert(ident, def);
2592 self.record_def(param.id, PathResolution::new(def));
2594 GenericParamKind::Const { .. } => {
2595 let ident = param.ident.modern();
2596 debug!("with_generic_param_rib: {}", param.id);
2598 if seen_bindings.contains_key(&ident) {
2599 let span = seen_bindings.get(&ident).unwrap();
2600 let err = ResolutionError::NameAlreadyUsedInParameterList(
2604 resolve_error(self, param.ident.span, err);
2606 seen_bindings.entry(ident).or_insert(param.ident.span);
2608 let def = Def::ConstParam(self.definitions.local_def_id(param.id));
2609 function_value_rib.bindings.insert(ident, def);
2610 self.record_def(param.id, PathResolution::new(def));
2614 self.ribs[ValueNS].push(function_value_rib);
2615 self.ribs[TypeNS].push(function_type_rib);
2618 NoGenericParams => {
2625 if let HasGenericParams(..) = generic_params {
2626 self.ribs[TypeNS].pop();
2627 self.ribs[ValueNS].pop();
2631 fn with_label_rib<F>(&mut self, f: F)
2632 where F: FnOnce(&mut Resolver<'_>)
2634 self.label_ribs.push(Rib::new(NormalRibKind));
2636 self.label_ribs.pop();
2639 fn with_item_rib<F>(&mut self, f: F)
2640 where F: FnOnce(&mut Resolver<'_>)
2642 self.ribs[ValueNS].push(Rib::new(ItemRibKind));
2643 self.ribs[TypeNS].push(Rib::new(ItemRibKind));
2645 self.ribs[TypeNS].pop();
2646 self.ribs[ValueNS].pop();
2649 fn with_constant_rib<F>(&mut self, f: F)
2650 where F: FnOnce(&mut Resolver<'_>)
2652 debug!("with_constant_rib");
2653 self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
2654 self.label_ribs.push(Rib::new(ConstantItemRibKind));
2656 self.label_ribs.pop();
2657 self.ribs[ValueNS].pop();
2660 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2661 where F: FnOnce(&mut Resolver<'_>) -> T
2663 // Handle nested impls (inside fn bodies)
2664 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2665 let result = f(self);
2666 self.current_self_type = previous_value;
2670 fn with_current_self_item<T, F>(&mut self, self_item: &Item, f: F) -> T
2671 where F: FnOnce(&mut Resolver<'_>) -> T
2673 let previous_value = replace(&mut self.current_self_item, Some(self_item.id));
2674 let result = f(self);
2675 self.current_self_item = previous_value;
2679 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
2680 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2681 where F: FnOnce(&mut Resolver<'_>, Option<DefId>) -> T
2683 let mut new_val = None;
2684 let mut new_id = None;
2685 if let Some(trait_ref) = opt_trait_ref {
2686 let path: Vec<_> = Segment::from_path(&trait_ref.path);
2687 let def = self.smart_resolve_path_fragment(
2691 trait_ref.path.span,
2692 PathSource::Trait(AliasPossibility::No),
2693 CrateLint::SimplePath(trait_ref.ref_id),
2695 if def != Def::Err {
2696 new_id = Some(def.def_id());
2697 let span = trait_ref.path.span;
2698 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2699 self.resolve_path_without_parent_scope(
2704 CrateLint::SimplePath(trait_ref.ref_id),
2707 new_val = Some((module, trait_ref.clone()));
2711 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2712 let result = f(self, new_id);
2713 self.current_trait_ref = original_trait_ref;
2717 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2718 where F: FnOnce(&mut Resolver<'_>)
2720 let mut self_type_rib = Rib::new(NormalRibKind);
2722 // Plain insert (no renaming, since types are not currently hygienic)
2723 self_type_rib.bindings.insert(keywords::SelfUpper.ident(), self_def);
2724 self.ribs[TypeNS].push(self_type_rib);
2726 self.ribs[TypeNS].pop();
2729 fn with_self_struct_ctor_rib<F>(&mut self, impl_id: DefId, f: F)
2730 where F: FnOnce(&mut Resolver<'_>)
2732 let self_def = Def::SelfCtor(impl_id);
2733 let mut self_type_rib = Rib::new(NormalRibKind);
2734 self_type_rib.bindings.insert(keywords::SelfUpper.ident(), self_def);
2735 self.ribs[ValueNS].push(self_type_rib);
2737 self.ribs[ValueNS].pop();
2740 fn resolve_implementation(&mut self,
2741 generics: &Generics,
2742 opt_trait_reference: &Option<TraitRef>,
2745 impl_items: &[ImplItem]) {
2746 debug!("resolve_implementation");
2747 // If applicable, create a rib for the type parameters.
2748 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2749 // Dummy self type for better errors if `Self` is used in the trait path.
2750 this.with_self_rib(Def::SelfTy(None, None), |this| {
2751 // Resolve the trait reference, if necessary.
2752 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2753 let item_def_id = this.definitions.local_def_id(item_id);
2754 this.with_self_rib(Def::SelfTy(trait_id, Some(item_def_id)), |this| {
2755 if let Some(trait_ref) = opt_trait_reference.as_ref() {
2756 // Resolve type arguments in the trait path.
2757 visit::walk_trait_ref(this, trait_ref);
2759 // Resolve the self type.
2760 this.visit_ty(self_type);
2761 // Resolve the generic parameters.
2762 this.visit_generics(generics);
2763 // Resolve the items within the impl.
2764 this.with_current_self_type(self_type, |this| {
2765 this.with_self_struct_ctor_rib(item_def_id, |this| {
2766 debug!("resolve_implementation with_self_struct_ctor_rib");
2767 for impl_item in impl_items {
2768 this.resolve_visibility(&impl_item.vis);
2770 // We also need a new scope for the impl item type parameters.
2771 let generic_params = HasGenericParams(&impl_item.generics,
2772 TraitOrImplItemRibKind);
2773 this.with_generic_param_rib(generic_params, |this| {
2774 use self::ResolutionError::*;
2775 match impl_item.node {
2776 ImplItemKind::Const(..) => {
2778 "resolve_implementation ImplItemKind::Const",
2780 // If this is a trait impl, ensure the const
2782 this.check_trait_item(
2786 |n, s| ConstNotMemberOfTrait(n, s),
2789 this.with_constant_rib(|this| {
2790 visit::walk_impl_item(this, impl_item)
2793 ImplItemKind::Method(..) => {
2794 // If this is a trait impl, ensure the method
2796 this.check_trait_item(impl_item.ident,
2799 |n, s| MethodNotMemberOfTrait(n, s));
2801 visit::walk_impl_item(this, impl_item);
2803 ImplItemKind::Type(ref ty) => {
2804 // If this is a trait impl, ensure the type
2806 this.check_trait_item(impl_item.ident,
2809 |n, s| TypeNotMemberOfTrait(n, s));
2813 ImplItemKind::Existential(ref bounds) => {
2814 // If this is a trait impl, ensure the type
2816 this.check_trait_item(impl_item.ident,
2819 |n, s| TypeNotMemberOfTrait(n, s));
2821 for bound in bounds {
2822 this.visit_param_bound(bound);
2825 ImplItemKind::Macro(_) =>
2826 panic!("unexpanded macro in resolve!"),
2838 fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
2839 where F: FnOnce(Name, &str) -> ResolutionError<'_>
2841 // If there is a TraitRef in scope for an impl, then the method must be in the
2843 if let Some((module, _)) = self.current_trait_ref {
2844 if self.resolve_ident_in_module(
2845 ModuleOrUniformRoot::Module(module),
2852 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2853 resolve_error(self, span, err(ident.name, &path_names_to_string(path)));
2858 fn resolve_local(&mut self, local: &Local) {
2859 // Resolve the type.
2860 walk_list!(self, visit_ty, &local.ty);
2862 // Resolve the initializer.
2863 walk_list!(self, visit_expr, &local.init);
2865 // Resolve the pattern.
2866 self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap::default());
2869 // build a map from pattern identifiers to binding-info's.
2870 // this is done hygienically. This could arise for a macro
2871 // that expands into an or-pattern where one 'x' was from the
2872 // user and one 'x' came from the macro.
2873 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2874 let mut binding_map = FxHashMap::default();
2876 pat.walk(&mut |pat| {
2877 if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
2878 if sub_pat.is_some() || match self.def_map.get(&pat.id).map(|res| res.base_def()) {
2879 Some(Def::Local(..)) => true,
2882 let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
2883 binding_map.insert(ident, binding_info);
2892 // check that all of the arms in an or-pattern have exactly the
2893 // same set of bindings, with the same binding modes for each.
2894 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) {
2895 if pats.is_empty() {
2899 let mut missing_vars = FxHashMap::default();
2900 let mut inconsistent_vars = FxHashMap::default();
2901 for (i, p) in pats.iter().enumerate() {
2902 let map_i = self.binding_mode_map(&p);
2904 for (j, q) in pats.iter().enumerate() {
2909 let map_j = self.binding_mode_map(&q);
2910 for (&key, &binding_i) in &map_i {
2911 if map_j.is_empty() { // Account for missing bindings when
2912 let binding_error = missing_vars // map_j has none.
2914 .or_insert(BindingError {
2916 origin: BTreeSet::new(),
2917 target: BTreeSet::new(),
2919 binding_error.origin.insert(binding_i.span);
2920 binding_error.target.insert(q.span);
2922 for (&key_j, &binding_j) in &map_j {
2923 match map_i.get(&key_j) {
2924 None => { // missing binding
2925 let binding_error = missing_vars
2927 .or_insert(BindingError {
2929 origin: BTreeSet::new(),
2930 target: BTreeSet::new(),
2932 binding_error.origin.insert(binding_j.span);
2933 binding_error.target.insert(p.span);
2935 Some(binding_i) => { // check consistent binding
2936 if binding_i.binding_mode != binding_j.binding_mode {
2939 .or_insert((binding_j.span, binding_i.span));
2947 let mut missing_vars = missing_vars.iter().collect::<Vec<_>>();
2948 missing_vars.sort();
2949 for (_, v) in missing_vars {
2951 *v.origin.iter().next().unwrap(),
2952 ResolutionError::VariableNotBoundInPattern(v));
2954 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
2955 inconsistent_vars.sort();
2956 for (name, v) in inconsistent_vars {
2957 resolve_error(self, v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
2961 fn resolve_arm(&mut self, arm: &Arm) {
2962 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2964 let mut bindings_list = FxHashMap::default();
2965 for pattern in &arm.pats {
2966 self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list);
2969 // This has to happen *after* we determine which pat_idents are variants.
2970 self.check_consistent_bindings(&arm.pats);
2972 if let Some(ast::Guard::If(ref expr)) = arm.guard {
2973 self.visit_expr(expr)
2975 self.visit_expr(&arm.body);
2977 self.ribs[ValueNS].pop();
2980 fn resolve_block(&mut self, block: &Block) {
2981 debug!("(resolving block) entering block");
2982 // Move down in the graph, if there's an anonymous module rooted here.
2983 let orig_module = self.current_module;
2984 let anonymous_module = self.block_map.get(&block.id).cloned(); // clones a reference
2986 let mut num_macro_definition_ribs = 0;
2987 if let Some(anonymous_module) = anonymous_module {
2988 debug!("(resolving block) found anonymous module, moving down");
2989 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2990 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2991 self.current_module = anonymous_module;
2992 self.finalize_current_module_macro_resolutions();
2994 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2997 // Descend into the block.
2998 for stmt in &block.stmts {
2999 if let ast::StmtKind::Item(ref item) = stmt.node {
3000 if let ast::ItemKind::MacroDef(..) = item.node {
3001 num_macro_definition_ribs += 1;
3002 let def = self.definitions.local_def_id(item.id);
3003 self.ribs[ValueNS].push(Rib::new(MacroDefinition(def)));
3004 self.label_ribs.push(Rib::new(MacroDefinition(def)));
3008 self.visit_stmt(stmt);
3012 self.current_module = orig_module;
3013 for _ in 0 .. num_macro_definition_ribs {
3014 self.ribs[ValueNS].pop();
3015 self.label_ribs.pop();
3017 self.ribs[ValueNS].pop();
3018 if anonymous_module.is_some() {
3019 self.ribs[TypeNS].pop();
3021 debug!("(resolving block) leaving block");
3024 fn fresh_binding(&mut self,
3027 outer_pat_id: NodeId,
3028 pat_src: PatternSource,
3029 bindings: &mut FxHashMap<Ident, NodeId>)
3031 // Add the binding to the local ribs, if it
3032 // doesn't already exist in the bindings map. (We
3033 // must not add it if it's in the bindings map
3034 // because that breaks the assumptions later
3035 // passes make about or-patterns.)
3036 let ident = ident.modern_and_legacy();
3037 let mut def = Def::Local(pat_id);
3038 match bindings.get(&ident).cloned() {
3039 Some(id) if id == outer_pat_id => {
3040 // `Variant(a, a)`, error
3044 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
3048 Some(..) if pat_src == PatternSource::FnParam => {
3049 // `fn f(a: u8, a: u8)`, error
3053 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
3057 Some(..) if pat_src == PatternSource::Match ||
3058 pat_src == PatternSource::IfLet ||
3059 pat_src == PatternSource::WhileLet => {
3060 // `Variant1(a) | Variant2(a)`, ok
3061 // Reuse definition from the first `a`.
3062 def = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident];
3065 span_bug!(ident.span, "two bindings with the same name from \
3066 unexpected pattern source {:?}", pat_src);
3069 // A completely fresh binding, add to the lists if it's valid.
3070 if ident.name != keywords::Invalid.name() {
3071 bindings.insert(ident, outer_pat_id);
3072 self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident, def);
3077 PathResolution::new(def)
3080 fn resolve_pattern(&mut self,
3082 pat_src: PatternSource,
3083 // Maps idents to the node ID for the
3084 // outermost pattern that binds them.
3085 bindings: &mut FxHashMap<Ident, NodeId>) {
3086 // Visit all direct subpatterns of this pattern.
3087 let outer_pat_id = pat.id;
3088 pat.walk(&mut |pat| {
3089 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.node);
3091 PatKind::Ident(bmode, ident, ref opt_pat) => {
3092 // First try to resolve the identifier as some existing
3093 // entity, then fall back to a fresh binding.
3094 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS,
3096 .and_then(LexicalScopeBinding::item);
3097 let resolution = binding.map(NameBinding::def).and_then(|def| {
3098 let is_syntactic_ambiguity = opt_pat.is_none() &&
3099 bmode == BindingMode::ByValue(Mutability::Immutable);
3101 Def::Ctor(_, _, CtorKind::Const) |
3102 Def::Const(..) if is_syntactic_ambiguity => {
3103 // Disambiguate in favor of a unit struct/variant
3104 // or constant pattern.
3105 self.record_use(ident, ValueNS, binding.unwrap(), false);
3106 Some(PathResolution::new(def))
3108 Def::Ctor(..) | Def::Const(..) | Def::Static(..) => {
3109 // This is unambiguously a fresh binding, either syntactically
3110 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
3111 // to something unusable as a pattern (e.g., constructor function),
3112 // but we still conservatively report an error, see
3113 // issues/33118#issuecomment-233962221 for one reason why.
3117 ResolutionError::BindingShadowsSomethingUnacceptable(
3118 pat_src.descr(), ident.name, binding.unwrap())
3122 Def::Fn(..) | Def::Err => {
3123 // These entities are explicitly allowed
3124 // to be shadowed by fresh bindings.
3128 span_bug!(ident.span, "unexpected definition for an \
3129 identifier in pattern: {:?}", def);
3132 }).unwrap_or_else(|| {
3133 self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
3136 self.record_def(pat.id, resolution);
3139 PatKind::TupleStruct(ref path, ..) => {
3140 self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
3143 PatKind::Path(ref qself, ref path) => {
3144 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
3147 PatKind::Struct(ref path, ..) => {
3148 self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
3156 visit::walk_pat(self, pat);
3159 // High-level and context dependent path resolution routine.
3160 // Resolves the path and records the resolution into definition map.
3161 // If resolution fails tries several techniques to find likely
3162 // resolution candidates, suggest imports or other help, and report
3163 // errors in user friendly way.
3164 fn smart_resolve_path(&mut self,
3166 qself: Option<&QSelf>,
3168 source: PathSource<'_>)
3170 self.smart_resolve_path_with_crate_lint(id, qself, path, source, CrateLint::SimplePath(id))
3173 /// A variant of `smart_resolve_path` where you also specify extra
3174 /// information about where the path came from; this extra info is
3175 /// sometimes needed for the lint that recommends rewriting
3176 /// absolute paths to `crate`, so that it knows how to frame the
3177 /// suggestion. If you are just resolving a path like `foo::bar`
3178 /// that appears in an arbitrary location, then you just want
3179 /// `CrateLint::SimplePath`, which is what `smart_resolve_path`
3180 /// already provides.
3181 fn smart_resolve_path_with_crate_lint(
3184 qself: Option<&QSelf>,
3186 source: PathSource<'_>,
3187 crate_lint: CrateLint
3188 ) -> PathResolution {
3189 self.smart_resolve_path_fragment(
3192 &Segment::from_path(path),
3199 fn smart_resolve_path_fragment(&mut self,
3201 qself: Option<&QSelf>,
3204 source: PathSource<'_>,
3205 crate_lint: CrateLint)
3207 let ns = source.namespace();
3208 let is_expected = &|def| source.is_expected(def);
3210 let report_errors = |this: &mut Self, def: Option<Def>| {
3211 let (err, candidates) = this.smart_resolve_report_errors(path, span, source, def);
3212 let def_id = this.current_module.normal_ancestor_id;
3213 let node_id = this.definitions.as_local_node_id(def_id).unwrap();
3214 let better = def.is_some();
3215 this.use_injections.push(UseError { err, candidates, node_id, better });
3216 err_path_resolution()
3219 let resolution = match self.resolve_qpath_anywhere(
3225 source.defer_to_typeck(),
3226 source.global_by_default(),
3229 Some(resolution) if resolution.unresolved_segments() == 0 => {
3230 if is_expected(resolution.base_def()) || resolution.base_def() == Def::Err {
3233 // Add a temporary hack to smooth the transition to new struct ctor
3234 // visibility rules. See #38932 for more details.
3236 if let Def::Struct(def_id) = resolution.base_def() {
3237 if let Some((ctor_def, ctor_vis))
3238 = self.struct_constructors.get(&def_id).cloned() {
3239 if is_expected(ctor_def) && self.is_accessible(ctor_vis) {
3240 let lint = lint::builtin::LEGACY_CONSTRUCTOR_VISIBILITY;
3241 self.session.buffer_lint(lint, id, span,
3242 "private struct constructors are not usable through \
3243 re-exports in outer modules",
3245 res = Some(PathResolution::new(ctor_def));
3250 res.unwrap_or_else(|| report_errors(self, Some(resolution.base_def())))
3253 Some(resolution) if source.defer_to_typeck() => {
3254 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
3255 // or `<T>::A::B`. If `B` should be resolved in value namespace then
3256 // it needs to be added to the trait map.
3258 let item_name = path.last().unwrap().ident;
3259 let traits = self.get_traits_containing_item(item_name, ns);
3260 self.trait_map.insert(id, traits);
3264 _ => report_errors(self, None)
3267 if let PathSource::TraitItem(..) = source {} else {
3268 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
3269 self.record_def(id, resolution);
3274 /// Only used in a specific case of type ascription suggestions
3276 fn get_colon_suggestion_span(&self, start: Span) -> Span {
3277 let cm = self.session.source_map();
3278 start.to(cm.next_point(start))
3281 fn type_ascription_suggestion(
3283 err: &mut DiagnosticBuilder<'_>,
3286 debug!("type_ascription_suggetion {:?}", base_span);
3287 let cm = self.session.source_map();
3288 let base_snippet = cm.span_to_snippet(base_span);
3289 debug!("self.current_type_ascription {:?}", self.current_type_ascription);
3290 if let Some(sp) = self.current_type_ascription.last() {
3293 // Try to find the `:`; bail on first non-':' / non-whitespace.
3294 sp = cm.next_point(sp);
3295 if let Ok(snippet) = cm.span_to_snippet(sp.to(cm.next_point(sp))) {
3296 let line_sp = cm.lookup_char_pos(sp.hi()).line;
3297 let line_base_sp = cm.lookup_char_pos(base_span.lo()).line;
3299 let mut show_label = true;
3300 if line_sp != line_base_sp {
3301 err.span_suggestion_short(
3303 "did you mean to use `;` here instead?",
3305 Applicability::MaybeIncorrect,
3308 let colon_sp = self.get_colon_suggestion_span(sp);
3309 let after_colon_sp = self.get_colon_suggestion_span(
3310 colon_sp.shrink_to_hi(),
3312 if !cm.span_to_snippet(after_colon_sp).map(|s| s == " ")
3315 err.span_suggestion(
3317 "maybe you meant to write a path separator here",
3319 Applicability::MaybeIncorrect,
3323 if let Ok(base_snippet) = base_snippet {
3324 let mut sp = after_colon_sp;
3326 // Try to find an assignment
3327 sp = cm.next_point(sp);
3328 let snippet = cm.span_to_snippet(sp.to(cm.next_point(sp)));
3330 Ok(ref x) if x.as_str() == "=" => {
3331 err.span_suggestion(
3333 "maybe you meant to write an assignment here",
3334 format!("let {}", base_snippet),
3335 Applicability::MaybeIncorrect,
3340 Ok(ref x) if x.as_str() == "\n" => break,
3348 err.span_label(base_span,
3349 "expecting a type here because of type ascription");
3352 } else if !snippet.trim().is_empty() {
3353 debug!("tried to find type ascription `:` token, couldn't find it");
3363 fn self_type_is_available(&mut self, span: Span) -> bool {
3364 let binding = self.resolve_ident_in_lexical_scope(keywords::SelfUpper.ident(),
3365 TypeNS, None, span);
3366 if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
3369 fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
3370 let ident = Ident::new(keywords::SelfLower.name(), self_span);
3371 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
3372 if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
3375 // Resolve in alternative namespaces if resolution in the primary namespace fails.
3376 fn resolve_qpath_anywhere(&mut self,
3378 qself: Option<&QSelf>,
3380 primary_ns: Namespace,
3382 defer_to_typeck: bool,
3383 global_by_default: bool,
3384 crate_lint: CrateLint)
3385 -> Option<PathResolution> {
3386 let mut fin_res = None;
3387 // FIXME: can't resolve paths in macro namespace yet, macros are
3388 // processed by the little special hack below.
3389 for (i, ns) in [primary_ns, TypeNS, ValueNS, /*MacroNS*/].iter().cloned().enumerate() {
3390 if i == 0 || ns != primary_ns {
3391 match self.resolve_qpath(id, qself, path, ns, span, global_by_default, crate_lint) {
3392 // If defer_to_typeck, then resolution > no resolution,
3393 // otherwise full resolution > partial resolution > no resolution.
3394 Some(res) if res.unresolved_segments() == 0 || defer_to_typeck =>
3396 res => if fin_res.is_none() { fin_res = res },
3400 if primary_ns != MacroNS &&
3401 (self.macro_names.contains(&path[0].ident.modern()) ||
3402 self.builtin_macros.get(&path[0].ident.name).cloned()
3403 .and_then(NameBinding::macro_kind) == Some(MacroKind::Bang) ||
3404 self.macro_use_prelude.get(&path[0].ident.name).cloned()
3405 .and_then(NameBinding::macro_kind) == Some(MacroKind::Bang)) {
3406 // Return some dummy definition, it's enough for error reporting.
3408 PathResolution::new(Def::Macro(DefId::local(CRATE_DEF_INDEX), MacroKind::Bang))
3414 /// Handles paths that may refer to associated items.
3415 fn resolve_qpath(&mut self,
3417 qself: Option<&QSelf>,
3421 global_by_default: bool,
3422 crate_lint: CrateLint)
3423 -> Option<PathResolution> {
3425 "resolve_qpath(id={:?}, qself={:?}, path={:?}, \
3426 ns={:?}, span={:?}, global_by_default={:?})",
3435 if let Some(qself) = qself {
3436 if qself.position == 0 {
3437 // This is a case like `<T>::B`, where there is no
3438 // trait to resolve. In that case, we leave the `B`
3439 // segment to be resolved by type-check.
3440 return Some(PathResolution::with_unresolved_segments(
3441 Def::Mod(DefId::local(CRATE_DEF_INDEX)), path.len()
3445 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
3447 // Currently, `path` names the full item (`A::B::C`, in
3448 // our example). so we extract the prefix of that that is
3449 // the trait (the slice upto and including
3450 // `qself.position`). And then we recursively resolve that,
3451 // but with `qself` set to `None`.
3453 // However, setting `qself` to none (but not changing the
3454 // span) loses the information about where this path
3455 // *actually* appears, so for the purposes of the crate
3456 // lint we pass along information that this is the trait
3457 // name from a fully qualified path, and this also
3458 // contains the full span (the `CrateLint::QPathTrait`).
3459 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
3460 let res = self.smart_resolve_path_fragment(
3463 &path[..=qself.position],
3465 PathSource::TraitItem(ns),
3466 CrateLint::QPathTrait {
3468 qpath_span: qself.path_span,
3472 // The remaining segments (the `C` in our example) will
3473 // have to be resolved by type-check, since that requires doing
3474 // trait resolution.
3475 return Some(PathResolution::with_unresolved_segments(
3476 res.base_def(), res.unresolved_segments() + path.len() - qself.position - 1
3480 let result = match self.resolve_path_without_parent_scope(
3487 PathResult::NonModule(path_res) => path_res,
3488 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
3489 PathResolution::new(module.def().unwrap())
3491 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
3492 // don't report an error right away, but try to fallback to a primitive type.
3493 // So, we are still able to successfully resolve something like
3495 // use std::u8; // bring module u8 in scope
3496 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
3497 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
3498 // // not to non-existent std::u8::max_value
3501 // Such behavior is required for backward compatibility.
3502 // The same fallback is used when `a` resolves to nothing.
3503 PathResult::Module(ModuleOrUniformRoot::Module(_)) |
3504 PathResult::Failed { .. }
3505 if (ns == TypeNS || path.len() > 1) &&
3506 self.primitive_type_table.primitive_types
3507 .contains_key(&path[0].ident.name) => {
3508 let prim = self.primitive_type_table.primitive_types[&path[0].ident.name];
3509 PathResolution::with_unresolved_segments(Def::PrimTy(prim), path.len() - 1)
3511 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3512 PathResolution::new(module.def().unwrap()),
3513 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
3514 resolve_error(self, span, ResolutionError::FailedToResolve { label, suggestion });
3515 err_path_resolution()
3517 PathResult::Module(..) | PathResult::Failed { .. } => return None,
3518 PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
3521 if path.len() > 1 && !global_by_default && result.base_def() != Def::Err &&
3522 path[0].ident.name != keywords::PathRoot.name() &&
3523 path[0].ident.name != keywords::DollarCrate.name() {
3524 let unqualified_result = {
3525 match self.resolve_path_without_parent_scope(
3526 &[*path.last().unwrap()],
3532 PathResult::NonModule(path_res) => path_res.base_def(),
3533 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3534 module.def().unwrap(),
3535 _ => return Some(result),
3538 if result.base_def() == unqualified_result {
3539 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
3540 self.session.buffer_lint(lint, id, span, "unnecessary qualification")
3547 fn resolve_path_without_parent_scope(
3550 opt_ns: Option<Namespace>, // `None` indicates a module path in import
3553 crate_lint: CrateLint,
3554 ) -> PathResult<'a> {
3555 // Macro and import paths must have full parent scope available during resolution,
3556 // other paths will do okay with parent module alone.
3557 assert!(opt_ns != None && opt_ns != Some(MacroNS));
3558 let parent_scope = ParentScope { module: self.current_module, ..self.dummy_parent_scope() };
3559 self.resolve_path(path, opt_ns, &parent_scope, record_used, path_span, crate_lint)
3565 opt_ns: Option<Namespace>, // `None` indicates a module path in import
3566 parent_scope: &ParentScope<'a>,
3569 crate_lint: CrateLint,
3570 ) -> PathResult<'a> {
3571 let mut module = None;
3572 let mut allow_super = true;
3573 let mut second_binding = None;
3574 self.current_module = parent_scope.module;
3577 "resolve_path(path={:?}, opt_ns={:?}, record_used={:?}, \
3578 path_span={:?}, crate_lint={:?})",
3586 for (i, &Segment { ident, id }) in path.iter().enumerate() {
3587 debug!("resolve_path ident {} {:?} {:?}", i, ident, id);
3588 let record_segment_def = |this: &mut Self, def| {
3590 if let Some(id) = id {
3591 if !this.def_map.contains_key(&id) {
3592 assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id");
3593 this.record_def(id, PathResolution::new(def));
3599 let is_last = i == path.len() - 1;
3600 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
3601 let name = ident.name;
3603 allow_super &= ns == TypeNS &&
3604 (name == keywords::SelfLower.name() ||
3605 name == keywords::Super.name());
3608 if allow_super && name == keywords::Super.name() {
3609 let mut ctxt = ident.span.ctxt().modern();
3610 let self_module = match i {
3611 0 => Some(self.resolve_self(&mut ctxt, self.current_module)),
3613 Some(ModuleOrUniformRoot::Module(module)) => Some(module),
3617 if let Some(self_module) = self_module {
3618 if let Some(parent) = self_module.parent {
3619 module = Some(ModuleOrUniformRoot::Module(
3620 self.resolve_self(&mut ctxt, parent)));
3624 let msg = "there are too many initial `super`s.".to_string();
3625 return PathResult::Failed {
3629 is_error_from_last_segment: false,
3633 if name == keywords::SelfLower.name() {
3634 let mut ctxt = ident.span.ctxt().modern();
3635 module = Some(ModuleOrUniformRoot::Module(
3636 self.resolve_self(&mut ctxt, self.current_module)));
3639 if name == keywords::PathRoot.name() && ident.span.rust_2018() {
3640 module = Some(ModuleOrUniformRoot::ExternPrelude);
3643 if name == keywords::PathRoot.name() &&
3644 ident.span.rust_2015() && self.session.rust_2018() {
3645 // `::a::b` from 2015 macro on 2018 global edition
3646 module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude);
3649 if name == keywords::PathRoot.name() ||
3650 name == keywords::Crate.name() ||
3651 name == keywords::DollarCrate.name() {
3652 // `::a::b`, `crate::a::b` or `$crate::a::b`
3653 module = Some(ModuleOrUniformRoot::Module(
3654 self.resolve_crate_root(ident)));
3660 // Report special messages for path segment keywords in wrong positions.
3661 if ident.is_path_segment_keyword() && i != 0 {
3662 let name_str = if name == keywords::PathRoot.name() {
3663 "crate root".to_string()
3665 format!("`{}`", name)
3667 let label = if i == 1 && path[0].ident.name == keywords::PathRoot.name() {
3668 format!("global paths cannot start with {}", name_str)
3670 format!("{} in paths can only be used in start position", name_str)
3672 return PathResult::Failed {
3676 is_error_from_last_segment: false,
3680 let binding = if let Some(module) = module {
3681 self.resolve_ident_in_module(module, ident, ns, None, record_used, path_span)
3682 } else if opt_ns.is_none() || opt_ns == Some(MacroNS) {
3683 assert!(ns == TypeNS);
3684 let scopes = if opt_ns.is_none() { ScopeSet::Import(ns) } else { ScopeSet::Module };
3685 self.early_resolve_ident_in_lexical_scope(ident, scopes, parent_scope, record_used,
3686 record_used, path_span)
3688 let record_used_id =
3689 if record_used { crate_lint.node_id().or(Some(CRATE_NODE_ID)) } else { None };
3690 match self.resolve_ident_in_lexical_scope(ident, ns, record_used_id, path_span) {
3691 // we found a locally-imported or available item/module
3692 Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
3693 // we found a local variable or type param
3694 Some(LexicalScopeBinding::Def(def))
3695 if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => {
3696 record_segment_def(self, def);
3697 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3701 _ => Err(Determinacy::determined(record_used)),
3708 second_binding = Some(binding);
3710 let def = binding.def();
3711 let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(def);
3712 if let Some(next_module) = binding.module() {
3713 module = Some(ModuleOrUniformRoot::Module(next_module));
3714 record_segment_def(self, def);
3715 } else if def == Def::ToolMod && i + 1 != path.len() {
3716 if binding.is_import() {
3717 self.session.struct_span_err(
3718 ident.span, "cannot use a tool module through an import"
3720 binding.span, "the tool module imported here"
3723 let def = Def::NonMacroAttr(NonMacroAttrKind::Tool);
3724 return PathResult::NonModule(PathResolution::new(def));
3725 } else if def == Def::Err {
3726 return PathResult::NonModule(err_path_resolution());
3727 } else if opt_ns.is_some() && (is_last || maybe_assoc) {
3728 self.lint_if_path_starts_with_module(
3734 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3735 def, path.len() - i - 1
3738 return PathResult::Failed {
3740 label: format!("not a module `{}`", ident),
3742 is_error_from_last_segment: is_last,
3746 Err(Undetermined) => return PathResult::Indeterminate,
3747 Err(Determined) => {
3748 if let Some(ModuleOrUniformRoot::Module(module)) = module {
3749 if opt_ns.is_some() && !module.is_normal() {
3750 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3751 module.def().unwrap(), path.len() - i
3755 let module_def = match module {
3756 Some(ModuleOrUniformRoot::Module(module)) => module.def(),
3759 let (label, suggestion) = if module_def == self.graph_root.def() {
3760 let is_mod = |def| match def { Def::Mod(..) => true, _ => false };
3761 let mut candidates =
3762 self.lookup_import_candidates(ident, TypeNS, is_mod);
3763 candidates.sort_by_cached_key(|c| {
3764 (c.path.segments.len(), c.path.to_string())
3766 if let Some(candidate) = candidates.get(0) {
3768 String::from("unresolved import"),
3771 String::from("a similar path exists"),
3772 candidate.path.to_string(),
3773 Applicability::MaybeIncorrect,
3776 } else if !ident.is_reserved() {
3777 (format!("maybe a missing `extern crate {};`?", ident), None)
3779 // the parser will already have complained about the keyword being used
3780 return PathResult::NonModule(err_path_resolution());
3783 (format!("use of undeclared type or module `{}`", ident), None)
3785 (format!("could not find `{}` in `{}`", ident, path[i - 1].ident), None)
3787 return PathResult::Failed {
3791 is_error_from_last_segment: is_last,
3797 self.lint_if_path_starts_with_module(crate_lint, path, path_span, second_binding);
3799 PathResult::Module(match module {
3800 Some(module) => module,
3801 None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
3802 _ => span_bug!(path_span, "resolve_path: non-empty path `{:?}` has no module", path),
3806 fn lint_if_path_starts_with_module(
3808 crate_lint: CrateLint,
3811 second_binding: Option<&NameBinding<'_>>,
3813 let (diag_id, diag_span) = match crate_lint {
3814 CrateLint::No => return,
3815 CrateLint::SimplePath(id) => (id, path_span),
3816 CrateLint::UsePath { root_id, root_span } => (root_id, root_span),
3817 CrateLint::QPathTrait { qpath_id, qpath_span } => (qpath_id, qpath_span),
3820 let first_name = match path.get(0) {
3821 // In the 2018 edition this lint is a hard error, so nothing to do
3822 Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name,
3826 // We're only interested in `use` paths which should start with
3827 // `{{root}}` currently.
3828 if first_name != keywords::PathRoot.name() {
3833 // If this import looks like `crate::...` it's already good
3834 Some(Segment { ident, .. }) if ident.name == keywords::Crate.name() => return,
3835 // Otherwise go below to see if it's an extern crate
3837 // If the path has length one (and it's `PathRoot` most likely)
3838 // then we don't know whether we're gonna be importing a crate or an
3839 // item in our crate. Defer this lint to elsewhere
3843 // If the first element of our path was actually resolved to an
3844 // `ExternCrate` (also used for `crate::...`) then no need to issue a
3845 // warning, this looks all good!
3846 if let Some(binding) = second_binding {
3847 if let NameBindingKind::Import { directive: d, .. } = binding.kind {
3848 // Careful: we still want to rewrite paths from
3849 // renamed extern crates.
3850 if let ImportDirectiveSubclass::ExternCrate { source: None, .. } = d.subclass {
3856 let diag = lint::builtin::BuiltinLintDiagnostics
3857 ::AbsPathWithModule(diag_span);
3858 self.session.buffer_lint_with_diagnostic(
3859 lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
3861 "absolute paths must start with `self`, `super`, \
3862 `crate`, or an external crate name in the 2018 edition",
3866 // Resolve a local definition, potentially adjusting for closures.
3867 fn adjust_local_def(&mut self,
3872 span: Span) -> Def {
3873 debug!("adjust_local_def");
3874 let ribs = &self.ribs[ns][rib_index + 1..];
3876 // An invalid forward use of a type parameter from a previous default.
3877 if let ForwardTyParamBanRibKind = self.ribs[ns][rib_index].kind {
3879 resolve_error(self, span, ResolutionError::ForwardDeclaredTyParam);
3881 assert_eq!(def, Def::Err);
3887 span_bug!(span, "unexpected {:?} in bindings", def)
3889 Def::Local(node_id) => {
3890 use ResolutionError::*;
3891 let mut res_err = None;
3895 NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) |
3896 ForwardTyParamBanRibKind => {
3897 // Nothing to do. Continue.
3899 ClosureRibKind(function_id) => {
3902 let seen = self.freevars_seen
3905 if let Some(&index) = seen.get(&node_id) {
3906 def = Def::Upvar(node_id, index, function_id);
3909 let vec = self.freevars
3912 let depth = vec.len();
3913 def = Def::Upvar(node_id, depth, function_id);
3920 seen.insert(node_id, depth);
3923 ItemRibKind | FnItemRibKind | TraitOrImplItemRibKind => {
3924 // This was an attempt to access an upvar inside a
3925 // named function item. This is not allowed, so we
3928 // We don't immediately trigger a resolve error, because
3929 // we want certain other resolution errors (namely those
3930 // emitted for `ConstantItemRibKind` below) to take
3932 res_err = Some(CannotCaptureDynamicEnvironmentInFnItem);
3935 ConstantItemRibKind => {
3936 // Still doesn't deal with upvars
3938 resolve_error(self, span, AttemptToUseNonConstantValueInConstant);
3944 if let Some(res_err) = res_err {
3945 resolve_error(self, span, res_err);
3949 Def::TyParam(..) | Def::SelfTy(..) => {
3952 NormalRibKind | TraitOrImplItemRibKind | ClosureRibKind(..) |
3953 ModuleRibKind(..) | MacroDefinition(..) | ForwardTyParamBanRibKind |
3954 ConstantItemRibKind => {
3955 // Nothing to do. Continue.
3957 ItemRibKind | FnItemRibKind => {
3958 // This was an attempt to use a type parameter outside its scope.
3963 ResolutionError::GenericParamsFromOuterFunction(def),
3971 Def::ConstParam(..) => {
3972 let mut ribs = ribs.iter().peekable();
3973 if let Some(Rib { kind: FnItemRibKind, .. }) = ribs.peek() {
3974 // When declaring const parameters inside function signatures, the first rib
3975 // is always a `FnItemRibKind`. In this case, we can skip it, to avoid it
3976 // (spuriously) conflicting with the const param.
3980 if let ItemRibKind | FnItemRibKind = rib.kind {
3981 // This was an attempt to use a const parameter outside its scope.
3986 ResolutionError::GenericParamsFromOuterFunction(def),
3998 fn lookup_assoc_candidate<FilterFn>(&mut self,
4001 filter_fn: FilterFn)
4002 -> Option<AssocSuggestion>
4003 where FilterFn: Fn(Def) -> bool
4005 fn extract_node_id(t: &Ty) -> Option<NodeId> {
4007 TyKind::Path(None, _) => Some(t.id),
4008 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
4009 // This doesn't handle the remaining `Ty` variants as they are not
4010 // that commonly the self_type, it might be interesting to provide
4011 // support for those in future.
4016 // Fields are generally expected in the same contexts as locals.
4017 if filter_fn(Def::Local(ast::DUMMY_NODE_ID)) {
4018 if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
4019 // Look for a field with the same name in the current self_type.
4020 if let Some(resolution) = self.def_map.get(&node_id) {
4021 match resolution.base_def() {
4022 Def::Struct(did) | Def::Union(did)
4023 if resolution.unresolved_segments() == 0 => {
4024 if let Some(field_names) = self.field_names.get(&did) {
4025 if field_names.iter().any(|&field_name| ident.name == field_name) {
4026 return Some(AssocSuggestion::Field);
4036 // Look for associated items in the current trait.
4037 if let Some((module, _)) = self.current_trait_ref {
4038 if let Ok(binding) = self.resolve_ident_in_module(
4039 ModuleOrUniformRoot::Module(module),
4046 let def = binding.def();
4048 return Some(if self.has_self.contains(&def.def_id()) {
4049 AssocSuggestion::MethodWithSelf
4051 AssocSuggestion::AssocItem
4060 fn lookup_typo_candidate<FilterFn>(
4064 filter_fn: FilterFn,
4066 ) -> Option<TypoSuggestion>
4068 FilterFn: Fn(Def) -> bool,
4070 let add_module_candidates = |module: Module<'_>, names: &mut Vec<TypoSuggestion>| {
4071 for (&(ident, _), resolution) in module.resolutions.borrow().iter() {
4072 if let Some(binding) = resolution.borrow().binding {
4073 if filter_fn(binding.def()) {
4074 names.push(TypoSuggestion {
4075 candidate: ident.name,
4076 article: binding.def().article(),
4077 kind: binding.def().kind_name(),
4084 let mut names = Vec::new();
4085 if path.len() == 1 {
4086 // Search in lexical scope.
4087 // Walk backwards up the ribs in scope and collect candidates.
4088 for rib in self.ribs[ns].iter().rev() {
4089 // Locals and type parameters
4090 for (ident, def) in &rib.bindings {
4091 if filter_fn(*def) {
4092 names.push(TypoSuggestion {
4093 candidate: ident.name,
4094 article: def.article(),
4095 kind: def.kind_name(),
4100 if let ModuleRibKind(module) = rib.kind {
4101 // Items from this module
4102 add_module_candidates(module, &mut names);
4104 if let ModuleKind::Block(..) = module.kind {
4105 // We can see through blocks
4107 // Items from the prelude
4108 if !module.no_implicit_prelude {
4109 names.extend(self.extern_prelude.clone().iter().flat_map(|(ident, _)| {
4111 .maybe_process_path_extern(ident.name, ident.span)
4112 .and_then(|crate_id| {
4113 let crate_mod = Def::Mod(DefId {
4115 index: CRATE_DEF_INDEX,
4118 if filter_fn(crate_mod) {
4119 Some(TypoSuggestion {
4120 candidate: ident.name,
4130 if let Some(prelude) = self.prelude {
4131 add_module_candidates(prelude, &mut names);
4138 // Add primitive types to the mix
4139 if filter_fn(Def::PrimTy(Bool)) {
4141 self.primitive_type_table.primitive_types.iter().map(|(name, _)| {
4145 kind: "primitive type",
4151 // Search in module.
4152 let mod_path = &path[..path.len() - 1];
4153 if let PathResult::Module(module) = self.resolve_path_without_parent_scope(
4154 mod_path, Some(TypeNS), false, span, CrateLint::No
4156 if let ModuleOrUniformRoot::Module(module) = module {
4157 add_module_candidates(module, &mut names);
4162 let name = path[path.len() - 1].ident.name;
4163 // Make sure error reporting is deterministic.
4164 names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
4166 match find_best_match_for_name(
4167 names.iter().map(|suggestion| &suggestion.candidate),
4171 Some(found) if found != name => names
4173 .find(|suggestion| suggestion.candidate == found),
4178 fn with_resolved_label<F>(&mut self, label: Option<Label>, id: NodeId, f: F)
4179 where F: FnOnce(&mut Resolver<'_>)
4181 if let Some(label) = label {
4182 self.unused_labels.insert(id, label.ident.span);
4183 let def = Def::Label(id);
4184 self.with_label_rib(|this| {
4185 let ident = label.ident.modern_and_legacy();
4186 this.label_ribs.last_mut().unwrap().bindings.insert(ident, def);
4194 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
4195 self.with_resolved_label(label, id, |this| this.visit_block(block));
4198 fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
4199 // First, record candidate traits for this expression if it could
4200 // result in the invocation of a method call.
4202 self.record_candidate_traits_for_expr_if_necessary(expr);
4204 // Next, resolve the node.
4206 ExprKind::Path(ref qself, ref path) => {
4207 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
4208 visit::walk_expr(self, expr);
4211 ExprKind::Struct(ref path, ..) => {
4212 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
4213 visit::walk_expr(self, expr);
4216 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4217 let def = self.search_label(label.ident, |rib, ident| {
4218 rib.bindings.get(&ident.modern_and_legacy()).cloned()
4222 // Search again for close matches...
4223 // Picks the first label that is "close enough", which is not necessarily
4224 // the closest match
4225 let close_match = self.search_label(label.ident, |rib, ident| {
4226 let names = rib.bindings.iter().filter_map(|(id, _)| {
4227 if id.span.ctxt() == label.ident.span.ctxt() {
4233 find_best_match_for_name(names, &*ident.as_str(), None)
4235 self.record_def(expr.id, err_path_resolution());
4238 ResolutionError::UndeclaredLabel(&label.ident.as_str(),
4241 Some(Def::Label(id)) => {
4242 // Since this def is a label, it is never read.
4243 self.record_def(expr.id, PathResolution::new(Def::Label(id)));
4244 self.unused_labels.remove(&id);
4247 span_bug!(expr.span, "label wasn't mapped to a label def!");
4251 // visit `break` argument if any
4252 visit::walk_expr(self, expr);
4255 ExprKind::IfLet(ref pats, ref subexpression, ref if_block, ref optional_else) => {
4256 self.visit_expr(subexpression);
4258 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
4259 let mut bindings_list = FxHashMap::default();
4261 self.resolve_pattern(pat, PatternSource::IfLet, &mut bindings_list);
4263 // This has to happen *after* we determine which pat_idents are variants
4264 self.check_consistent_bindings(pats);
4265 self.visit_block(if_block);
4266 self.ribs[ValueNS].pop();
4268 optional_else.as_ref().map(|expr| self.visit_expr(expr));
4271 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
4273 ExprKind::While(ref subexpression, ref block, label) => {
4274 self.with_resolved_label(label, expr.id, |this| {
4275 this.visit_expr(subexpression);
4276 this.visit_block(block);
4280 ExprKind::WhileLet(ref pats, ref subexpression, ref block, label) => {
4281 self.with_resolved_label(label, expr.id, |this| {
4282 this.visit_expr(subexpression);
4283 this.ribs[ValueNS].push(Rib::new(NormalRibKind));
4284 let mut bindings_list = FxHashMap::default();
4286 this.resolve_pattern(pat, PatternSource::WhileLet, &mut bindings_list);
4288 // This has to happen *after* we determine which pat_idents are variants.
4289 this.check_consistent_bindings(pats);
4290 this.visit_block(block);
4291 this.ribs[ValueNS].pop();
4295 ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
4296 self.visit_expr(subexpression);
4297 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
4298 self.resolve_pattern(pattern, PatternSource::For, &mut FxHashMap::default());
4300 self.resolve_labeled_block(label, expr.id, block);
4302 self.ribs[ValueNS].pop();
4305 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4307 // Equivalent to `visit::walk_expr` + passing some context to children.
4308 ExprKind::Field(ref subexpression, _) => {
4309 self.resolve_expr(subexpression, Some(expr));
4311 ExprKind::MethodCall(ref segment, ref arguments) => {
4312 let mut arguments = arguments.iter();
4313 self.resolve_expr(arguments.next().unwrap(), Some(expr));
4314 for argument in arguments {
4315 self.resolve_expr(argument, None);
4317 self.visit_path_segment(expr.span, segment);
4320 ExprKind::Call(ref callee, ref arguments) => {
4321 self.resolve_expr(callee, Some(expr));
4322 for argument in arguments {
4323 self.resolve_expr(argument, None);
4326 ExprKind::Type(ref type_expr, _) => {
4327 self.current_type_ascription.push(type_expr.span);
4328 visit::walk_expr(self, expr);
4329 self.current_type_ascription.pop();
4331 // Resolve the body of async exprs inside the async closure to which they desugar
4332 ExprKind::Async(_, async_closure_id, ref block) => {
4333 let rib_kind = ClosureRibKind(async_closure_id);
4334 self.ribs[ValueNS].push(Rib::new(rib_kind));
4335 self.label_ribs.push(Rib::new(rib_kind));
4336 self.visit_block(&block);
4337 self.label_ribs.pop();
4338 self.ribs[ValueNS].pop();
4340 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
4341 // resolve the arguments within the proper scopes so that usages of them inside the
4342 // closure are detected as upvars rather than normal closure arg usages.
4344 _, IsAsync::Async { closure_id: inner_closure_id, .. }, _,
4345 ref fn_decl, ref body, _span,
4347 let rib_kind = ClosureRibKind(expr.id);
4348 self.ribs[ValueNS].push(Rib::new(rib_kind));
4349 self.label_ribs.push(Rib::new(rib_kind));
4350 // Resolve arguments:
4351 let mut bindings_list = FxHashMap::default();
4352 for argument in &fn_decl.inputs {
4353 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
4354 self.visit_ty(&argument.ty);
4356 // No need to resolve return type-- the outer closure return type is
4357 // FunctionRetTy::Default
4359 // Now resolve the inner closure
4361 let rib_kind = ClosureRibKind(inner_closure_id);
4362 self.ribs[ValueNS].push(Rib::new(rib_kind));
4363 self.label_ribs.push(Rib::new(rib_kind));
4364 // No need to resolve arguments: the inner closure has none.
4365 // Resolve the return type:
4366 visit::walk_fn_ret_ty(self, &fn_decl.output);
4368 self.visit_expr(body);
4369 self.label_ribs.pop();
4370 self.ribs[ValueNS].pop();
4372 self.label_ribs.pop();
4373 self.ribs[ValueNS].pop();
4376 visit::walk_expr(self, expr);
4381 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4383 ExprKind::Field(_, ident) => {
4384 // FIXME(#6890): Even though you can't treat a method like a
4385 // field, we need to add any trait methods we find that match
4386 // the field name so that we can do some nice error reporting
4387 // later on in typeck.
4388 let traits = self.get_traits_containing_item(ident, ValueNS);
4389 self.trait_map.insert(expr.id, traits);
4391 ExprKind::MethodCall(ref segment, ..) => {
4392 debug!("(recording candidate traits for expr) recording traits for {}",
4394 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
4395 self.trait_map.insert(expr.id, traits);
4403 fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
4404 -> Vec<TraitCandidate> {
4405 debug!("(getting traits containing item) looking for '{}'", ident.name);
4407 let mut found_traits = Vec::new();
4408 // Look for the current trait.
4409 if let Some((module, _)) = self.current_trait_ref {
4410 if self.resolve_ident_in_module(
4411 ModuleOrUniformRoot::Module(module),
4418 let def_id = module.def_id().unwrap();
4419 found_traits.push(TraitCandidate { def_id: def_id, import_id: None });
4423 ident.span = ident.span.modern();
4424 let mut search_module = self.current_module;
4426 self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
4427 search_module = unwrap_or!(
4428 self.hygienic_lexical_parent(search_module, &mut ident.span), break
4432 if let Some(prelude) = self.prelude {
4433 if !search_module.no_implicit_prelude {
4434 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
4441 fn get_traits_in_module_containing_item(&mut self,
4445 found_traits: &mut Vec<TraitCandidate>) {
4446 assert!(ns == TypeNS || ns == ValueNS);
4447 let mut traits = module.traits.borrow_mut();
4448 if traits.is_none() {
4449 let mut collected_traits = Vec::new();
4450 module.for_each_child(|name, ns, binding| {
4451 if ns != TypeNS { return }
4452 match binding.def() {
4454 Def::TraitAlias(_) => collected_traits.push((name, binding)),
4458 *traits = Some(collected_traits.into_boxed_slice());
4461 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
4462 // Traits have pseudo-modules that can be used to search for the given ident.
4463 if let Some(module) = binding.module() {
4464 let mut ident = ident;
4465 if ident.span.glob_adjust(
4467 binding.span.ctxt().modern(),
4471 if self.resolve_ident_in_module_unadjusted(
4472 ModuleOrUniformRoot::Module(module),
4478 let import_id = match binding.kind {
4479 NameBindingKind::Import { directive, .. } => {
4480 self.maybe_unused_trait_imports.insert(directive.id);
4481 self.add_to_glob_map(&directive, trait_name);
4486 let trait_def_id = module.def_id().unwrap();
4487 found_traits.push(TraitCandidate { def_id: trait_def_id, import_id });
4489 } else if let Def::TraitAlias(_) = binding.def() {
4490 // For now, just treat all trait aliases as possible candidates, since we don't
4491 // know if the ident is somewhere in the transitive bounds.
4493 let import_id = match binding.kind {
4494 NameBindingKind::Import { directive, .. } => {
4495 self.maybe_unused_trait_imports.insert(directive.id);
4496 self.add_to_glob_map(&directive, trait_name);
4501 let trait_def_id = binding.def().def_id();
4502 found_traits.push(TraitCandidate { def_id: trait_def_id, import_id });
4504 bug!("candidate is not trait or trait alias?")
4509 fn lookup_import_candidates_from_module<FilterFn>(&mut self,
4510 lookup_ident: Ident,
4511 namespace: Namespace,
4512 start_module: &'a ModuleData<'a>,
4514 filter_fn: FilterFn)
4515 -> Vec<ImportSuggestion>
4516 where FilterFn: Fn(Def) -> bool
4518 let mut candidates = Vec::new();
4519 let mut seen_modules = FxHashSet::default();
4520 let not_local_module = crate_name != keywords::Crate.ident();
4521 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), not_local_module)];
4523 while let Some((in_module,
4525 in_module_is_extern)) = worklist.pop() {
4526 self.populate_module_if_necessary(in_module);
4528 // We have to visit module children in deterministic order to avoid
4529 // instabilities in reported imports (#43552).
4530 in_module.for_each_child_stable(|ident, ns, name_binding| {
4531 // avoid imports entirely
4532 if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
4533 // avoid non-importable candidates as well
4534 if !name_binding.is_importable() { return; }
4536 // collect results based on the filter function
4537 if ident.name == lookup_ident.name && ns == namespace {
4538 let def = name_binding.def();
4541 let mut segms = path_segments.clone();
4542 if lookup_ident.span.rust_2018() {
4543 // crate-local absolute paths start with `crate::` in edition 2018
4544 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
4546 0, ast::PathSegment::from_ident(crate_name)
4550 segms.push(ast::PathSegment::from_ident(ident));
4552 span: name_binding.span,
4555 // the entity is accessible in the following cases:
4556 // 1. if it's defined in the same crate, it's always
4557 // accessible (since private entities can be made public)
4558 // 2. if it's defined in another crate, it's accessible
4559 // only if both the module is public and the entity is
4560 // declared as public (due to pruning, we don't explore
4561 // outside crate private modules => no need to check this)
4562 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
4563 let did = match def {
4564 Def::Ctor(did, ..) => self.parent(did),
4565 _ => def.opt_def_id(),
4567 candidates.push(ImportSuggestion { did, path });
4572 // collect submodules to explore
4573 if let Some(module) = name_binding.module() {
4575 let mut path_segments = path_segments.clone();
4576 path_segments.push(ast::PathSegment::from_ident(ident));
4578 let is_extern_crate_that_also_appears_in_prelude =
4579 name_binding.is_extern_crate() &&
4580 lookup_ident.span.rust_2018();
4582 let is_visible_to_user =
4583 !in_module_is_extern || name_binding.vis == ty::Visibility::Public;
4585 if !is_extern_crate_that_also_appears_in_prelude && is_visible_to_user {
4586 // add the module to the lookup
4587 let is_extern = in_module_is_extern || name_binding.is_extern_crate();
4588 if seen_modules.insert(module.def_id().unwrap()) {
4589 worklist.push((module, path_segments, is_extern));
4599 /// When name resolution fails, this method can be used to look up candidate
4600 /// entities with the expected name. It allows filtering them using the
4601 /// supplied predicate (which should be used to only accept the types of
4602 /// definitions expected, e.g., traits). The lookup spans across all crates.
4604 /// N.B., the method does not look into imports, but this is not a problem,
4605 /// since we report the definitions (thus, the de-aliased imports).
4606 fn lookup_import_candidates<FilterFn>(&mut self,
4607 lookup_ident: Ident,
4608 namespace: Namespace,
4609 filter_fn: FilterFn)
4610 -> Vec<ImportSuggestion>
4611 where FilterFn: Fn(Def) -> bool
4613 let mut suggestions = self.lookup_import_candidates_from_module(
4614 lookup_ident, namespace, self.graph_root, keywords::Crate.ident(), &filter_fn);
4616 if lookup_ident.span.rust_2018() {
4617 let extern_prelude_names = self.extern_prelude.clone();
4618 for (ident, _) in extern_prelude_names.into_iter() {
4619 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name,
4621 let crate_root = self.get_module(DefId {
4623 index: CRATE_DEF_INDEX,
4625 self.populate_module_if_necessary(&crate_root);
4627 suggestions.extend(self.lookup_import_candidates_from_module(
4628 lookup_ident, namespace, crate_root, ident, &filter_fn));
4636 fn find_module(&mut self,
4638 -> Option<(Module<'a>, ImportSuggestion)>
4640 let mut result = None;
4641 let mut seen_modules = FxHashSet::default();
4642 let mut worklist = vec![(self.graph_root, Vec::new())];
4644 while let Some((in_module, path_segments)) = worklist.pop() {
4645 // abort if the module is already found
4646 if result.is_some() { break; }
4648 self.populate_module_if_necessary(in_module);
4650 in_module.for_each_child_stable(|ident, _, name_binding| {
4651 // abort if the module is already found or if name_binding is private external
4652 if result.is_some() || !name_binding.vis.is_visible_locally() {
4655 if let Some(module) = name_binding.module() {
4657 let mut path_segments = path_segments.clone();
4658 path_segments.push(ast::PathSegment::from_ident(ident));
4659 if module.def() == Some(module_def) {
4661 span: name_binding.span,
4662 segments: path_segments,
4664 let did = module.def().and_then(|def| def.opt_def_id());
4665 result = Some((module, ImportSuggestion { did, path }));
4667 // add the module to the lookup
4668 if seen_modules.insert(module.def_id().unwrap()) {
4669 worklist.push((module, path_segments));
4679 fn collect_enum_variants(&mut self, enum_def: Def) -> Option<Vec<Path>> {
4680 if let Def::Enum(..) = enum_def {} else {
4681 panic!("Non-enum def passed to collect_enum_variants: {:?}", enum_def)
4684 self.find_module(enum_def).map(|(enum_module, enum_import_suggestion)| {
4685 self.populate_module_if_necessary(enum_module);
4687 let mut variants = Vec::new();
4688 enum_module.for_each_child_stable(|ident, _, name_binding| {
4689 if let Def::Variant(..) = name_binding.def() {
4690 let mut segms = enum_import_suggestion.path.segments.clone();
4691 segms.push(ast::PathSegment::from_ident(ident));
4692 variants.push(Path {
4693 span: name_binding.span,
4702 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
4703 debug!("(recording def) recording {:?} for {}", resolution, node_id);
4704 if let Some(prev_res) = self.def_map.insert(node_id, resolution) {
4705 panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
4709 fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
4711 ast::VisibilityKind::Public => ty::Visibility::Public,
4712 ast::VisibilityKind::Crate(..) => {
4713 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
4715 ast::VisibilityKind::Inherited => {
4716 ty::Visibility::Restricted(self.current_module.normal_ancestor_id)
4718 ast::VisibilityKind::Restricted { ref path, id, .. } => {
4719 // For visibilities we are not ready to provide correct implementation of "uniform
4720 // paths" right now, so on 2018 edition we only allow module-relative paths for now.
4721 // On 2015 edition visibilities are resolved as crate-relative by default,
4722 // so we are prepending a root segment if necessary.
4723 let ident = path.segments.get(0).expect("empty path in visibility").ident;
4724 let crate_root = if ident.is_path_segment_keyword() {
4726 } else if ident.span.rust_2018() {
4727 let msg = "relative paths are not supported in visibilities on 2018 edition";
4728 self.session.struct_span_err(ident.span, msg)
4732 format!("crate::{}", path),
4733 Applicability::MaybeIncorrect,
4736 return ty::Visibility::Public;
4738 let ctxt = ident.span.ctxt();
4739 Some(Segment::from_ident(Ident::new(
4740 keywords::PathRoot.name(), path.span.shrink_to_lo().with_ctxt(ctxt)
4744 let segments = crate_root.into_iter()
4745 .chain(path.segments.iter().map(|seg| seg.into())).collect::<Vec<_>>();
4746 let def = self.smart_resolve_path_fragment(
4751 PathSource::Visibility,
4752 CrateLint::SimplePath(id),
4754 if def == Def::Err {
4755 ty::Visibility::Public
4757 let vis = ty::Visibility::Restricted(def.def_id());
4758 if self.is_accessible(vis) {
4761 self.session.span_err(path.span, "visibilities can only be restricted \
4762 to ancestor modules");
4763 ty::Visibility::Public
4770 fn is_accessible(&self, vis: ty::Visibility) -> bool {
4771 vis.is_accessible_from(self.current_module.normal_ancestor_id, self)
4774 fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
4775 vis.is_accessible_from(module.normal_ancestor_id, self)
4778 fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) {
4779 if let Some(old_module) = self.binding_parent_modules.insert(PtrKey(binding), module) {
4780 if !ptr::eq(module, old_module) {
4781 span_bug!(binding.span, "parent module is reset for binding");
4786 fn disambiguate_legacy_vs_modern(
4788 legacy: &'a NameBinding<'a>,
4789 modern: &'a NameBinding<'a>,
4791 // Some non-controversial subset of ambiguities "modern macro name" vs "macro_rules"
4792 // is disambiguated to mitigate regressions from macro modularization.
4793 // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
4794 match (self.binding_parent_modules.get(&PtrKey(legacy)),
4795 self.binding_parent_modules.get(&PtrKey(modern))) {
4796 (Some(legacy), Some(modern)) =>
4797 legacy.normal_ancestor_id == modern.normal_ancestor_id &&
4798 modern.is_ancestor_of(legacy),
4803 fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
4804 if b.span.is_dummy() {
4805 let add_built_in = match b.def() {
4806 // These already contain the "built-in" prefix or look bad with it.
4807 Def::NonMacroAttr(..) | Def::PrimTy(..) | Def::ToolMod => false,
4810 let (built_in, from) = if from_prelude {
4811 ("", " from prelude")
4812 } else if b.is_extern_crate() && !b.is_import() &&
4813 self.session.opts.externs.get(&ident.as_str()).is_some() {
4814 ("", " passed with `--extern`")
4815 } else if add_built_in {
4821 let article = if built_in.is_empty() { b.article() } else { "a" };
4822 format!("{a}{built_in} {thing}{from}",
4823 a = article, thing = b.descr(), built_in = built_in, from = from)
4825 let introduced = if b.is_import() { "imported" } else { "defined" };
4826 format!("the {thing} {introduced} here",
4827 thing = b.descr(), introduced = introduced)
4831 fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
4832 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
4833 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
4834 // We have to print the span-less alternative first, otherwise formatting looks bad.
4835 (b2, b1, misc2, misc1, true)
4837 (b1, b2, misc1, misc2, false)
4840 let mut err = struct_span_err!(self.session, ident.span, E0659,
4841 "`{ident}` is ambiguous ({why})",
4842 ident = ident, why = kind.descr());
4843 err.span_label(ident.span, "ambiguous name");
4845 let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
4846 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
4847 let note_msg = format!("`{ident}` could{also} refer to {what}",
4848 ident = ident, also = also, what = what);
4850 let mut help_msgs = Vec::new();
4851 if b.is_glob_import() && (kind == AmbiguityKind::GlobVsGlob ||
4852 kind == AmbiguityKind::GlobVsExpanded ||
4853 kind == AmbiguityKind::GlobVsOuter &&
4854 swapped != also.is_empty()) {
4855 help_msgs.push(format!("consider adding an explicit import of \
4856 `{ident}` to disambiguate", ident = ident))
4858 if b.is_extern_crate() && ident.span.rust_2018() {
4859 help_msgs.push(format!(
4860 "use `::{ident}` to refer to this {thing} unambiguously",
4861 ident = ident, thing = b.descr(),
4864 if misc == AmbiguityErrorMisc::SuggestCrate {
4865 help_msgs.push(format!(
4866 "use `crate::{ident}` to refer to this {thing} unambiguously",
4867 ident = ident, thing = b.descr(),
4869 } else if misc == AmbiguityErrorMisc::SuggestSelf {
4870 help_msgs.push(format!(
4871 "use `self::{ident}` to refer to this {thing} unambiguously",
4872 ident = ident, thing = b.descr(),
4876 err.span_note(b.span, ¬e_msg);
4877 for (i, help_msg) in help_msgs.iter().enumerate() {
4878 let or = if i == 0 { "" } else { "or " };
4879 err.help(&format!("{}{}", or, help_msg));
4883 could_refer_to(b1, misc1, "");
4884 could_refer_to(b2, misc2, " also");
4888 fn report_errors(&mut self, krate: &Crate) {
4889 self.report_with_use_injections(krate);
4891 for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
4892 let msg = "macro-expanded `macro_export` macros from the current crate \
4893 cannot be referred to by absolute paths";
4894 self.session.buffer_lint_with_diagnostic(
4895 lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
4896 CRATE_NODE_ID, span_use, msg,
4897 lint::builtin::BuiltinLintDiagnostics::
4898 MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
4902 for ambiguity_error in &self.ambiguity_errors {
4903 self.report_ambiguity_error(ambiguity_error);
4906 let mut reported_spans = FxHashSet::default();
4907 for &PrivacyError(dedup_span, ident, binding) in &self.privacy_errors {
4908 if reported_spans.insert(dedup_span) {
4909 span_err!(self.session, ident.span, E0603, "{} `{}` is private",
4910 binding.descr(), ident.name);
4915 fn report_with_use_injections(&mut self, krate: &Crate) {
4916 for UseError { mut err, candidates, node_id, better } in self.use_injections.drain(..) {
4917 let (span, found_use) = UsePlacementFinder::check(krate, node_id);
4918 if !candidates.is_empty() {
4919 show_candidates(&mut err, span, &candidates, better, found_use);
4925 fn report_conflict<'b>(&mut self,
4929 new_binding: &NameBinding<'b>,
4930 old_binding: &NameBinding<'b>) {
4931 // Error on the second of two conflicting names
4932 if old_binding.span.lo() > new_binding.span.lo() {
4933 return self.report_conflict(parent, ident, ns, old_binding, new_binding);
4936 let container = match parent.kind {
4937 ModuleKind::Def(Def::Mod(_), _) => "module",
4938 ModuleKind::Def(Def::Trait(_), _) => "trait",
4939 ModuleKind::Block(..) => "block",
4943 let old_noun = match old_binding.is_import() {
4945 false => "definition",
4948 let new_participle = match new_binding.is_import() {
4953 let (name, span) = (ident.name, self.session.source_map().def_span(new_binding.span));
4955 if let Some(s) = self.name_already_seen.get(&name) {
4961 let old_kind = match (ns, old_binding.module()) {
4962 (ValueNS, _) => "value",
4963 (MacroNS, _) => "macro",
4964 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
4965 (TypeNS, Some(module)) if module.is_normal() => "module",
4966 (TypeNS, Some(module)) if module.is_trait() => "trait",
4967 (TypeNS, _) => "type",
4970 let msg = format!("the name `{}` is defined multiple times", name);
4972 let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
4973 (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
4974 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
4975 true => struct_span_err!(self.session, span, E0254, "{}", msg),
4976 false => struct_span_err!(self.session, span, E0260, "{}", msg),
4978 _ => match (old_binding.is_import(), new_binding.is_import()) {
4979 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
4980 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
4981 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
4985 err.note(&format!("`{}` must be defined only once in the {} namespace of this {}",
4990 err.span_label(span, format!("`{}` re{} here", name, new_participle));
4992 self.session.source_map().def_span(old_binding.span),
4993 format!("previous {} of the {} `{}` here", old_noun, old_kind, name),
4996 // See https://github.com/rust-lang/rust/issues/32354
4997 use NameBindingKind::Import;
4998 let directive = match (&new_binding.kind, &old_binding.kind) {
4999 // If there are two imports where one or both have attributes then prefer removing the
5000 // import without attributes.
5001 (Import { directive: new, .. }, Import { directive: old, .. }) if {
5002 !new_binding.span.is_dummy() && !old_binding.span.is_dummy() &&
5003 (new.has_attributes || old.has_attributes)
5005 if old.has_attributes {
5006 Some((new, new_binding.span, true))
5008 Some((old, old_binding.span, true))
5011 // Otherwise prioritize the new binding.
5012 (Import { directive, .. }, other) if !new_binding.span.is_dummy() =>
5013 Some((directive, new_binding.span, other.is_import())),
5014 (other, Import { directive, .. }) if !old_binding.span.is_dummy() =>
5015 Some((directive, old_binding.span, other.is_import())),
5019 // Check if the target of the use for both bindings is the same.
5020 let duplicate = new_binding.def().opt_def_id() == old_binding.def().opt_def_id();
5021 let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
5022 let from_item = self.extern_prelude.get(&ident)
5023 .map(|entry| entry.introduced_by_item)
5025 // Only suggest removing an import if both bindings are to the same def, if both spans
5026 // aren't dummy spans. Further, if both bindings are imports, then the ident must have
5027 // been introduced by a item.
5028 let should_remove_import = duplicate && !has_dummy_span &&
5029 ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
5032 Some((directive, span, true)) if should_remove_import && directive.is_nested() =>
5033 self.add_suggestion_for_duplicate_nested_use(&mut err, directive, span),
5034 Some((directive, _, true)) if should_remove_import && !directive.is_glob() => {
5035 // Simple case - remove the entire import. Due to the above match arm, this can
5036 // only be a single use so just remove it entirely.
5037 err.tool_only_span_suggestion(
5038 directive.use_span_with_attributes,
5039 "remove unnecessary import",
5041 Applicability::MaybeIncorrect,
5044 Some((directive, span, _)) =>
5045 self.add_suggestion_for_rename_of_use(&mut err, name, directive, span),
5050 self.name_already_seen.insert(name, span);
5053 /// This function adds a suggestion to change the binding name of a new import that conflicts
5054 /// with an existing import.
5056 /// ```ignore (diagnostic)
5057 /// help: you can use `as` to change the binding name of the import
5059 /// LL | use foo::bar as other_bar;
5060 /// | ^^^^^^^^^^^^^^^^^^^^^
5062 fn add_suggestion_for_rename_of_use(
5064 err: &mut DiagnosticBuilder<'_>,
5066 directive: &ImportDirective<'_>,
5069 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
5070 format!("Other{}", name)
5072 format!("other_{}", name)
5075 let mut suggestion = None;
5076 match directive.subclass {
5077 ImportDirectiveSubclass::SingleImport { type_ns_only: true, .. } =>
5078 suggestion = Some(format!("self as {}", suggested_name)),
5079 ImportDirectiveSubclass::SingleImport { source, .. } => {
5080 if let Some(pos) = source.span.hi().0.checked_sub(binding_span.lo().0)
5081 .map(|pos| pos as usize) {
5082 if let Ok(snippet) = self.session.source_map()
5083 .span_to_snippet(binding_span) {
5084 if pos <= snippet.len() {
5085 suggestion = Some(format!(
5089 if snippet.ends_with(";") { ";" } else { "" }
5095 ImportDirectiveSubclass::ExternCrate { source, target, .. } =>
5096 suggestion = Some(format!(
5097 "extern crate {} as {};",
5098 source.unwrap_or(target.name),
5101 _ => unreachable!(),
5104 let rename_msg = "you can use `as` to change the binding name of the import";
5105 if let Some(suggestion) = suggestion {
5106 err.span_suggestion(
5110 Applicability::MaybeIncorrect,
5113 err.span_label(binding_span, rename_msg);
5117 /// This function adds a suggestion to remove a unnecessary binding from an import that is
5118 /// nested. In the following example, this function will be invoked to remove the `a` binding
5119 /// in the second use statement:
5121 /// ```ignore (diagnostic)
5122 /// use issue_52891::a;
5123 /// use issue_52891::{d, a, e};
5126 /// The following suggestion will be added:
5128 /// ```ignore (diagnostic)
5129 /// use issue_52891::{d, a, e};
5130 /// ^-- help: remove unnecessary import
5133 /// If the nested use contains only one import then the suggestion will remove the entire
5136 /// It is expected that the directive provided is a nested import - this isn't checked by the
5137 /// function. If this invariant is not upheld, this function's behaviour will be unexpected
5138 /// as characters expected by span manipulations won't be present.
5139 fn add_suggestion_for_duplicate_nested_use(
5141 err: &mut DiagnosticBuilder<'_>,
5142 directive: &ImportDirective<'_>,
5145 assert!(directive.is_nested());
5146 let message = "remove unnecessary import";
5147 let source_map = self.session.source_map();
5149 // Two examples will be used to illustrate the span manipulations we're doing:
5151 // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is
5152 // `a` and `directive.use_span` is `issue_52891::{d, a, e};`.
5153 // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is
5154 // `a` and `directive.use_span` is `issue_52891::{d, e, a};`.
5156 // Find the span of everything after the binding.
5157 // ie. `a, e};` or `a};`
5158 let binding_until_end = binding_span.with_hi(directive.use_span.hi());
5160 // Find everything after the binding but not including the binding.
5161 // ie. `, e};` or `};`
5162 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
5164 // Keep characters in the span until we encounter something that isn't a comma or
5168 // Also note whether a closing brace character was encountered. If there
5169 // was, then later go backwards to remove any trailing commas that are left.
5170 let mut found_closing_brace = false;
5171 let after_binding_until_next_binding = source_map.span_take_while(
5172 after_binding_until_end,
5174 if ch == '}' { found_closing_brace = true; }
5175 ch == ' ' || ch == ','
5179 // Combine the two spans.
5180 // ie. `a, ` or `a`.
5182 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
5183 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
5185 // If there was a closing brace then identify the span to remove any trailing commas from
5186 // previous imports.
5187 if found_closing_brace {
5188 if let Ok(prev_source) = source_map.span_to_prev_source(span) {
5189 // `prev_source` will contain all of the source that came before the span.
5190 // Then split based on a command and take the first (ie. closest to our span)
5191 // snippet. In the example, this is a space.
5192 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
5193 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
5194 if prev_comma.len() > 1 && prev_starting_brace.len() > 1 {
5195 let prev_comma = prev_comma.first().unwrap();
5196 let prev_starting_brace = prev_starting_brace.first().unwrap();
5198 // If the amount of source code before the comma is greater than
5199 // the amount of source code before the starting brace then we've only
5200 // got one item in the nested item (eg. `issue_52891::{self}`).
5201 if prev_comma.len() > prev_starting_brace.len() {
5202 // So just remove the entire line...
5203 err.span_suggestion(
5204 directive.use_span_with_attributes,
5207 Applicability::MaybeIncorrect,
5212 let span = span.with_lo(BytePos(
5213 // Take away the number of bytes for the characters we've found and an
5214 // extra for the comma.
5215 span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1
5217 err.tool_only_span_suggestion(
5218 span, message, String::new(), Applicability::MaybeIncorrect,
5225 err.span_suggestion(span, message, String::new(), Applicability::MachineApplicable);
5228 fn extern_prelude_get(&mut self, ident: Ident, speculative: bool)
5229 -> Option<&'a NameBinding<'a>> {
5230 if ident.is_path_segment_keyword() {
5231 // Make sure `self`, `super` etc produce an error when passed to here.
5234 self.extern_prelude.get(&ident.modern()).cloned().and_then(|entry| {
5235 if let Some(binding) = entry.extern_crate_item {
5236 if !speculative && entry.introduced_by_item {
5237 self.record_use(ident, TypeNS, binding, false);
5241 let crate_id = if !speculative {
5242 self.crate_loader.process_path_extern(ident.name, ident.span)
5243 } else if let Some(crate_id) =
5244 self.crate_loader.maybe_process_path_extern(ident.name, ident.span) {
5249 let crate_root = self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
5250 self.populate_module_if_necessary(&crate_root);
5251 Some((crate_root, ty::Visibility::Public, DUMMY_SP, Mark::root())
5252 .to_name_binding(self.arenas))
5258 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
5259 namespace == TypeNS && path.len() == 1 && path[0].ident.name == keywords::SelfUpper.name()
5262 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
5263 namespace == ValueNS && path.len() == 1 && path[0].ident.name == keywords::SelfLower.name()
5266 fn names_to_string(idents: &[Ident]) -> String {
5267 let mut result = String::new();
5268 for (i, ident) in idents.iter()
5269 .filter(|ident| ident.name != keywords::PathRoot.name())
5272 result.push_str("::");
5274 result.push_str(&ident.as_str());
5279 fn path_names_to_string(path: &Path) -> String {
5280 names_to_string(&path.segments.iter()
5281 .map(|seg| seg.ident)
5282 .collect::<Vec<_>>())
5285 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
5286 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
5287 let variant_path = &suggestion.path;
5288 let variant_path_string = path_names_to_string(variant_path);
5290 let path_len = suggestion.path.segments.len();
5291 let enum_path = ast::Path {
5292 span: suggestion.path.span,
5293 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
5295 let enum_path_string = path_names_to_string(&enum_path);
5297 (variant_path_string, enum_path_string)
5300 /// When an entity with a given name is not available in scope, we search for
5301 /// entities with that name in all crates. This method allows outputting the
5302 /// results of this search in a programmer-friendly way
5303 fn show_candidates(err: &mut DiagnosticBuilder<'_>,
5304 // This is `None` if all placement locations are inside expansions
5306 candidates: &[ImportSuggestion],
5310 // we want consistent results across executions, but candidates are produced
5311 // by iterating through a hash map, so make sure they are ordered:
5312 let mut path_strings: Vec<_> =
5313 candidates.into_iter().map(|c| path_names_to_string(&c.path)).collect();
5314 path_strings.sort();
5316 let better = if better { "better " } else { "" };
5317 let msg_diff = match path_strings.len() {
5318 1 => " is found in another module, you can import it",
5319 _ => "s are found in other modules, you can import them",
5321 let msg = format!("possible {}candidate{} into scope", better, msg_diff);
5323 if let Some(span) = span {
5324 for candidate in &mut path_strings {
5325 // produce an additional newline to separate the new use statement
5326 // from the directly following item.
5327 let additional_newline = if found_use {
5332 *candidate = format!("use {};\n{}", candidate, additional_newline);
5335 err.span_suggestions(
5338 path_strings.into_iter(),
5339 Applicability::Unspecified,
5344 for candidate in path_strings {
5346 msg.push_str(&candidate);
5351 /// A somewhat inefficient routine to obtain the name of a module.
5352 fn module_to_string(module: Module<'_>) -> Option<String> {
5353 let mut names = Vec::new();
5355 fn collect_mod(names: &mut Vec<Ident>, module: Module<'_>) {
5356 if let ModuleKind::Def(_, name) = module.kind {
5357 if let Some(parent) = module.parent {
5358 names.push(Ident::with_empty_ctxt(name));
5359 collect_mod(names, parent);
5362 // danger, shouldn't be ident?
5363 names.push(Ident::from_str("<opaque>"));
5364 collect_mod(names, module.parent.unwrap());
5367 collect_mod(&mut names, module);
5369 if names.is_empty() {
5372 Some(names_to_string(&names.into_iter()
5374 .collect::<Vec<_>>()))
5377 fn err_path_resolution() -> PathResolution {
5378 PathResolution::new(Def::Err)
5381 #[derive(Copy, Clone, Debug)]
5383 /// Do not issue the lint.
5386 /// This lint applies to some arbitrary path; e.g., `impl ::foo::Bar`.
5387 /// In this case, we can take the span of that path.
5390 /// This lint comes from a `use` statement. In this case, what we
5391 /// care about really is the *root* `use` statement; e.g., if we
5392 /// have nested things like `use a::{b, c}`, we care about the
5394 UsePath { root_id: NodeId, root_span: Span },
5396 /// This is the "trait item" from a fully qualified path. For example,
5397 /// we might be resolving `X::Y::Z` from a path like `<T as X::Y>::Z`.
5398 /// The `path_span` is the span of the to the trait itself (`X::Y`).
5399 QPathTrait { qpath_id: NodeId, qpath_span: Span },
5403 fn node_id(&self) -> Option<NodeId> {
5405 CrateLint::No => None,
5406 CrateLint::SimplePath(id) |
5407 CrateLint::UsePath { root_id: id, .. } |
5408 CrateLint::QPathTrait { qpath_id: id, .. } => Some(id),
5413 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }