1 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
2 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
3 html_root_url = "https://doc.rust-lang.org/nightly/")]
5 #![feature(crate_visibility_modifier)]
6 #![feature(label_break_value)]
8 #![feature(rustc_diagnostic_macros)]
9 #![feature(slice_sort_by_cached_key)]
11 #![recursion_limit="256"]
14 extern crate bitflags;
19 extern crate syntax_pos;
20 extern crate rustc_errors as errors;
24 extern crate rustc_data_structures;
25 extern crate rustc_metadata;
27 pub use rustc::hir::def::{Namespace, PerNS};
29 use self::TypeParameters::*;
32 use rustc::hir::map::{Definitions, DefCollector};
33 use rustc::hir::{self, PrimTy, Bool, Char, Float, Int, Uint, Str};
34 use rustc::middle::cstore::CrateStore;
35 use rustc::session::Session;
37 use rustc::hir::def::*;
38 use rustc::hir::def::Namespace::*;
39 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
40 use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
41 use rustc::session::config::nightly_options;
43 use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap};
45 use rustc_metadata::creader::CrateLoader;
46 use rustc_metadata::cstore::CStore;
48 use syntax::source_map::SourceMap;
49 use syntax::ext::hygiene::{Mark, Transparency, SyntaxContext};
50 use syntax::ast::{self, Name, NodeId, Ident, FloatTy, IntTy, UintTy};
51 use syntax::ext::base::SyntaxExtension;
52 use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
53 use syntax::ext::base::MacroKind;
54 use syntax::symbol::{Symbol, keywords};
55 use syntax::util::lev_distance::find_best_match_for_name;
57 use syntax::visit::{self, FnKind, Visitor};
59 use syntax::ast::{CRATE_NODE_ID, Arm, IsAsync, BindingMode, Block, Crate, Expr, ExprKind};
60 use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParamKind, Generics};
61 use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind};
62 use syntax::ast::{Label, Local, Mutability, Pat, PatKind, Path};
63 use syntax::ast::{QSelf, TraitItemKind, TraitRef, Ty, TyKind};
66 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
67 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
69 use std::cell::{Cell, RefCell};
70 use std::{cmp, fmt, iter, ptr};
71 use std::collections::BTreeSet;
72 use std::mem::replace;
73 use rustc_data_structures::ptr_key::PtrKey;
74 use rustc_data_structures::sync::Lrc;
76 use resolve_imports::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver};
77 use macros::{InvocationData, LegacyBinding, ParentScope};
79 // N.B., this module needs to be declared first so diagnostics are
80 // registered before they are used.
85 mod build_reduced_graph;
88 fn is_known_tool(name: Name) -> bool {
89 ["clippy", "rustfmt"].contains(&&*name.as_str())
99 AbsolutePath(Namespace),
104 /// A free importable items suggested in case of resolution failure.
105 struct ImportSuggestion {
109 /// A field or associated item from self type suggested in case of resolution failure.
110 enum AssocSuggestion {
117 struct BindingError {
119 origin: BTreeSet<Span>,
120 target: BTreeSet<Span>,
123 impl PartialOrd for BindingError {
124 fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> {
125 Some(self.cmp(other))
129 impl PartialEq for BindingError {
130 fn eq(&self, other: &BindingError) -> bool {
131 self.name == other.name
135 impl Ord for BindingError {
136 fn cmp(&self, other: &BindingError) -> cmp::Ordering {
137 self.name.cmp(&other.name)
141 enum ResolutionError<'a> {
142 /// error E0401: can't use type parameters from outer function
143 TypeParametersFromOuterFunction(Def),
144 /// error E0403: the name is already used for a type parameter in this type parameter list
145 NameAlreadyUsedInTypeParameterList(Name, &'a Span),
146 /// error E0407: method is not a member of trait
147 MethodNotMemberOfTrait(Name, &'a str),
148 /// error E0437: type is not a member of trait
149 TypeNotMemberOfTrait(Name, &'a str),
150 /// error E0438: const is not a member of trait
151 ConstNotMemberOfTrait(Name, &'a str),
152 /// error E0408: variable `{}` is not bound in all patterns
153 VariableNotBoundInPattern(&'a BindingError),
154 /// error E0409: variable `{}` is bound in inconsistent ways within the same match arm
155 VariableBoundWithDifferentMode(Name, Span),
156 /// error E0415: identifier is bound more than once in this parameter list
157 IdentifierBoundMoreThanOnceInParameterList(&'a str),
158 /// error E0416: identifier is bound more than once in the same pattern
159 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
160 /// error E0426: use of undeclared label
161 UndeclaredLabel(&'a str, Option<Name>),
162 /// error E0429: `self` imports are only allowed within a { } list
163 SelfImportsOnlyAllowedWithin,
164 /// error E0430: `self` import can only appear once in the list
165 SelfImportCanOnlyAppearOnceInTheList,
166 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
167 SelfImportOnlyInImportListWithNonEmptyPrefix,
168 /// error E0433: failed to resolve
169 FailedToResolve(&'a str),
170 /// error E0434: can't capture dynamic environment in a fn item
171 CannotCaptureDynamicEnvironmentInFnItem,
172 /// error E0435: attempt to use a non-constant value in a constant
173 AttemptToUseNonConstantValueInConstant,
174 /// error E0530: X bindings cannot shadow Ys
175 BindingShadowsSomethingUnacceptable(&'a str, Name, &'a NameBinding<'a>),
176 /// error E0128: type parameters with a default cannot use forward declared identifiers
177 ForwardDeclaredTyParam,
180 /// Combines an error with provided span and emits it
182 /// This takes the error provided, combines it with the span and any additional spans inside the
183 /// error and emits it.
184 fn resolve_error<'sess, 'a>(resolver: &'sess Resolver,
186 resolution_error: ResolutionError<'a>) {
187 resolve_struct_error(resolver, span, resolution_error).emit();
190 fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
192 resolution_error: ResolutionError<'a>)
193 -> DiagnosticBuilder<'sess> {
194 match resolution_error {
195 ResolutionError::TypeParametersFromOuterFunction(outer_def) => {
196 let mut err = struct_span_err!(resolver.session,
199 "can't use type parameters from outer function");
200 err.span_label(span, "use of type variable from outer function");
202 let cm = resolver.session.source_map();
204 Def::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
205 if let Some(impl_span) = maybe_impl_defid.and_then(|def_id| {
206 resolver.definitions.opt_span(def_id)
209 reduce_impl_span_to_impl_keyword(cm, impl_span),
210 "`Self` type implicitly declared here, by this `impl`",
213 match (maybe_trait_defid, maybe_impl_defid) {
215 err.span_label(span, "can't use `Self` here");
218 err.span_label(span, "use a type here instead");
220 (None, None) => bug!("`impl` without trait nor type?"),
224 Def::TyParam(typaram_defid) => {
225 if let Some(typaram_span) = resolver.definitions.opt_span(typaram_defid) {
226 err.span_label(typaram_span, "type variable from outer function");
230 bug!("TypeParametersFromOuterFunction should only be used with Def::SelfTy or \
235 // Try to retrieve the span of the function signature and generate a new message with
236 // a local type parameter
237 let sugg_msg = "try using a local type parameter instead";
238 if let Some((sugg_span, new_snippet)) = cm.generate_local_type_param_snippet(span) {
239 // Suggest the modification to the user
240 err.span_suggestion_with_applicability(
244 Applicability::MachineApplicable,
246 } else if let Some(sp) = cm.generate_fn_name_span(span) {
247 err.span_label(sp, "try adding a local type parameter in this method instead");
249 err.help("try using a local type parameter instead");
254 ResolutionError::NameAlreadyUsedInTypeParameterList(name, first_use_span) => {
255 let mut err = struct_span_err!(resolver.session,
258 "the name `{}` is already used for a type parameter \
259 in this type parameter list",
261 err.span_label(span, "already used");
262 err.span_label(first_use_span.clone(), format!("first use of `{}`", name));
265 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
266 let mut err = struct_span_err!(resolver.session,
269 "method `{}` is not a member of trait `{}`",
272 err.span_label(span, format!("not a member of trait `{}`", trait_));
275 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
276 let mut err = struct_span_err!(resolver.session,
279 "type `{}` is not a member of trait `{}`",
282 err.span_label(span, format!("not a member of trait `{}`", trait_));
285 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
286 let mut err = struct_span_err!(resolver.session,
289 "const `{}` is not a member of trait `{}`",
292 err.span_label(span, format!("not a member of trait `{}`", trait_));
295 ResolutionError::VariableNotBoundInPattern(binding_error) => {
296 let target_sp = binding_error.target.iter().cloned().collect::<Vec<_>>();
297 let msp = MultiSpan::from_spans(target_sp.clone());
298 let msg = format!("variable `{}` is not bound in all patterns", binding_error.name);
299 let mut err = resolver.session.struct_span_err_with_code(
302 DiagnosticId::Error("E0408".into()),
304 for sp in target_sp {
305 err.span_label(sp, format!("pattern doesn't bind `{}`", binding_error.name));
307 let origin_sp = binding_error.origin.iter().cloned();
308 for sp in origin_sp {
309 err.span_label(sp, "variable not in all patterns");
313 ResolutionError::VariableBoundWithDifferentMode(variable_name,
314 first_binding_span) => {
315 let mut err = struct_span_err!(resolver.session,
318 "variable `{}` is bound in inconsistent \
319 ways within the same match arm",
321 err.span_label(span, "bound in different ways");
322 err.span_label(first_binding_span, "first binding");
325 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
326 let mut err = struct_span_err!(resolver.session,
329 "identifier `{}` is bound more than once in this parameter list",
331 err.span_label(span, "used as parameter more than once");
334 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
335 let mut err = struct_span_err!(resolver.session,
338 "identifier `{}` is bound more than once in the same pattern",
340 err.span_label(span, "used in a pattern more than once");
343 ResolutionError::UndeclaredLabel(name, lev_candidate) => {
344 let mut err = struct_span_err!(resolver.session,
347 "use of undeclared label `{}`",
349 if let Some(lev_candidate) = lev_candidate {
350 err.span_label(span, format!("did you mean `{}`?", lev_candidate));
352 err.span_label(span, format!("undeclared label `{}`", name));
356 ResolutionError::SelfImportsOnlyAllowedWithin => {
357 struct_span_err!(resolver.session,
361 "`self` imports are only allowed within a { } list")
363 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
364 let mut err = struct_span_err!(resolver.session, span, E0430,
365 "`self` import can only appear once in an import list");
366 err.span_label(span, "can only appear once in an import list");
369 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
370 let mut err = struct_span_err!(resolver.session, span, E0431,
371 "`self` import can only appear in an import list with \
372 a non-empty prefix");
373 err.span_label(span, "can only appear in an import list with a non-empty prefix");
376 ResolutionError::FailedToResolve(msg) => {
377 let mut err = struct_span_err!(resolver.session, span, E0433,
378 "failed to resolve: {}", msg);
379 err.span_label(span, msg);
382 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
383 let mut err = struct_span_err!(resolver.session,
387 "can't capture dynamic environment in a fn item");
388 err.help("use the `|| { ... }` closure form instead");
391 ResolutionError::AttemptToUseNonConstantValueInConstant => {
392 let mut err = struct_span_err!(resolver.session, span, E0435,
393 "attempt to use a non-constant value in a constant");
394 err.span_label(span, "non-constant value");
397 ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
398 let shadows_what = binding.descr();
399 let mut err = struct_span_err!(resolver.session, span, E0530, "{}s cannot shadow {}s",
400 what_binding, shadows_what);
401 err.span_label(span, format!("cannot be named the same as {} {}",
402 binding.article(), shadows_what));
403 let participle = if binding.is_import() { "imported" } else { "defined" };
404 let msg = format!("the {} `{}` is {} here", shadows_what, name, participle);
405 err.span_label(binding.span, msg);
408 ResolutionError::ForwardDeclaredTyParam => {
409 let mut err = struct_span_err!(resolver.session, span, E0128,
410 "type parameters with a default cannot use \
411 forward declared identifiers");
413 span, "defaulted type parameters cannot be forward declared".to_string());
419 /// Adjust the impl span so that just the `impl` keyword is taken by removing
420 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
421 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`)
423 /// Attention: The method used is very fragile since it essentially duplicates the work of the
424 /// parser. If you need to use this function or something similar, please consider updating the
425 /// source_map functions and this function to something more robust.
426 fn reduce_impl_span_to_impl_keyword(cm: &SourceMap, impl_span: Span) -> Span {
427 let impl_span = cm.span_until_char(impl_span, '<');
428 let impl_span = cm.span_until_whitespace(impl_span);
432 #[derive(Copy, Clone, Debug)]
435 binding_mode: BindingMode,
438 /// Map from the name in a pattern to its binding mode.
439 type BindingMap = FxHashMap<Ident, BindingInfo>;
441 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
452 fn descr(self) -> &'static str {
454 PatternSource::Match => "match binding",
455 PatternSource::IfLet => "if let binding",
456 PatternSource::WhileLet => "while let binding",
457 PatternSource::Let => "let binding",
458 PatternSource::For => "for binding",
459 PatternSource::FnParam => "function parameter",
464 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
465 enum AliasPossibility {
470 #[derive(Copy, Clone, Debug)]
471 enum PathSource<'a> {
472 // Type paths `Path`.
474 // Trait paths in bounds or impls.
475 Trait(AliasPossibility),
476 // Expression paths `path`, with optional parent context.
477 Expr(Option<&'a Expr>),
478 // Paths in path patterns `Path`.
480 // Paths in struct expressions and patterns `Path { .. }`.
482 // Paths in tuple struct patterns `Path(..)`.
484 // `m::A::B` in `<T as m::A>::B::C`.
485 TraitItem(Namespace),
486 // Path in `pub(path)`
490 impl<'a> PathSource<'a> {
491 fn namespace(self) -> Namespace {
493 PathSource::Type | PathSource::Trait(_) | PathSource::Struct |
494 PathSource::Visibility => TypeNS,
495 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
496 PathSource::TraitItem(ns) => ns,
500 fn global_by_default(self) -> bool {
502 PathSource::Visibility => true,
503 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
504 PathSource::Struct | PathSource::TupleStruct |
505 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
509 fn defer_to_typeck(self) -> bool {
511 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
512 PathSource::Struct | PathSource::TupleStruct => true,
513 PathSource::Trait(_) | PathSource::TraitItem(..) |
514 PathSource::Visibility => false,
518 fn descr_expected(self) -> &'static str {
520 PathSource::Type => "type",
521 PathSource::Trait(_) => "trait",
522 PathSource::Pat => "unit struct/variant or constant",
523 PathSource::Struct => "struct, variant or union type",
524 PathSource::TupleStruct => "tuple struct/variant",
525 PathSource::Visibility => "module",
526 PathSource::TraitItem(ns) => match ns {
527 TypeNS => "associated type",
528 ValueNS => "method or associated constant",
529 MacroNS => bug!("associated macro"),
531 PathSource::Expr(parent) => match parent.map(|p| &p.node) {
532 // "function" here means "anything callable" rather than `Def::Fn`,
533 // this is not precise but usually more helpful than just "value".
534 Some(&ExprKind::Call(..)) => "function",
540 fn is_expected(self, def: Def) -> bool {
542 PathSource::Type => match def {
543 Def::Struct(..) | Def::Union(..) | Def::Enum(..) |
544 Def::Trait(..) | Def::TraitAlias(..) | Def::TyAlias(..) |
545 Def::AssociatedTy(..) | Def::PrimTy(..) | Def::TyParam(..) |
546 Def::SelfTy(..) | Def::Existential(..) |
547 Def::ForeignTy(..) => true,
550 PathSource::Trait(AliasPossibility::No) => match def {
551 Def::Trait(..) => true,
554 PathSource::Trait(AliasPossibility::Maybe) => match def {
555 Def::Trait(..) => true,
556 Def::TraitAlias(..) => true,
559 PathSource::Expr(..) => match def {
560 Def::StructCtor(_, CtorKind::Const) | Def::StructCtor(_, CtorKind::Fn) |
561 Def::VariantCtor(_, CtorKind::Const) | Def::VariantCtor(_, CtorKind::Fn) |
562 Def::Const(..) | Def::Static(..) | Def::Local(..) | Def::Upvar(..) |
563 Def::Fn(..) | Def::Method(..) | Def::AssociatedConst(..) |
564 Def::SelfCtor(..) => true,
567 PathSource::Pat => match def {
568 Def::StructCtor(_, CtorKind::Const) |
569 Def::VariantCtor(_, CtorKind::Const) |
570 Def::Const(..) | Def::AssociatedConst(..) |
571 Def::SelfCtor(..) => true,
574 PathSource::TupleStruct => match def {
575 Def::StructCtor(_, CtorKind::Fn) |
576 Def::VariantCtor(_, CtorKind::Fn) |
577 Def::SelfCtor(..) => true,
580 PathSource::Struct => match def {
581 Def::Struct(..) | Def::Union(..) | Def::Variant(..) |
582 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => true,
585 PathSource::TraitItem(ns) => match def {
586 Def::AssociatedConst(..) | Def::Method(..) if ns == ValueNS => true,
587 Def::AssociatedTy(..) if ns == TypeNS => true,
590 PathSource::Visibility => match def {
591 Def::Mod(..) => true,
597 fn error_code(self, has_unexpected_resolution: bool) -> &'static str {
598 __diagnostic_used!(E0404);
599 __diagnostic_used!(E0405);
600 __diagnostic_used!(E0412);
601 __diagnostic_used!(E0422);
602 __diagnostic_used!(E0423);
603 __diagnostic_used!(E0425);
604 __diagnostic_used!(E0531);
605 __diagnostic_used!(E0532);
606 __diagnostic_used!(E0573);
607 __diagnostic_used!(E0574);
608 __diagnostic_used!(E0575);
609 __diagnostic_used!(E0576);
610 __diagnostic_used!(E0577);
611 __diagnostic_used!(E0578);
612 match (self, has_unexpected_resolution) {
613 (PathSource::Trait(_), true) => "E0404",
614 (PathSource::Trait(_), false) => "E0405",
615 (PathSource::Type, true) => "E0573",
616 (PathSource::Type, false) => "E0412",
617 (PathSource::Struct, true) => "E0574",
618 (PathSource::Struct, false) => "E0422",
619 (PathSource::Expr(..), true) => "E0423",
620 (PathSource::Expr(..), false) => "E0425",
621 (PathSource::Pat, true) | (PathSource::TupleStruct, true) => "E0532",
622 (PathSource::Pat, false) | (PathSource::TupleStruct, false) => "E0531",
623 (PathSource::TraitItem(..), true) => "E0575",
624 (PathSource::TraitItem(..), false) => "E0576",
625 (PathSource::Visibility, true) => "E0577",
626 (PathSource::Visibility, false) => "E0578",
631 // A minimal representation of a path segment. We use this in resolve because
632 // we synthesize 'path segments' which don't have the rest of an AST or HIR
634 #[derive(Clone, Copy, Debug)]
641 fn from_path(path: &Path) -> Vec<Segment> {
642 path.segments.iter().map(|s| s.into()).collect()
645 fn from_ident(ident: Ident) -> Segment {
652 fn names_to_string(segments: &[Segment]) -> String {
653 names_to_string(&segments.iter()
654 .map(|seg| seg.ident)
655 .collect::<Vec<_>>())
659 impl<'a> From<&'a ast::PathSegment> for Segment {
660 fn from(seg: &'a ast::PathSegment) -> Segment {
668 struct UsePlacementFinder {
669 target_module: NodeId,
674 impl UsePlacementFinder {
675 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, bool) {
676 let mut finder = UsePlacementFinder {
681 visit::walk_crate(&mut finder, krate);
682 (finder.span, finder.found_use)
686 impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
689 module: &'tcx ast::Mod,
691 _: &[ast::Attribute],
694 if self.span.is_some() {
697 if node_id != self.target_module {
698 visit::walk_mod(self, module);
701 // find a use statement
702 for item in &module.items {
704 ItemKind::Use(..) => {
705 // don't suggest placing a use before the prelude
706 // import or other generated ones
707 if item.span.ctxt().outer().expn_info().is_none() {
708 self.span = Some(item.span.shrink_to_lo());
709 self.found_use = true;
713 // don't place use before extern crate
714 ItemKind::ExternCrate(_) => {}
715 // but place them before the first other item
716 _ => if self.span.map_or(true, |span| item.span < span ) {
717 if item.span.ctxt().outer().expn_info().is_none() {
718 // don't insert between attributes and an item
719 if item.attrs.is_empty() {
720 self.span = Some(item.span.shrink_to_lo());
722 // find the first attribute on the item
723 for attr in &item.attrs {
724 if self.span.map_or(true, |span| attr.span < span) {
725 self.span = Some(attr.span.shrink_to_lo());
736 /// This thing walks the whole crate in DFS manner, visiting each item, resolving names as it goes.
737 impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> {
738 fn visit_item(&mut self, item: &'tcx Item) {
739 self.resolve_item(item);
741 fn visit_arm(&mut self, arm: &'tcx Arm) {
742 self.resolve_arm(arm);
744 fn visit_block(&mut self, block: &'tcx Block) {
745 self.resolve_block(block);
747 fn visit_anon_const(&mut self, constant: &'tcx ast::AnonConst) {
748 self.with_constant_rib(|this| {
749 visit::walk_anon_const(this, constant);
752 fn visit_expr(&mut self, expr: &'tcx Expr) {
753 self.resolve_expr(expr, None);
755 fn visit_local(&mut self, local: &'tcx Local) {
756 self.resolve_local(local);
758 fn visit_ty(&mut self, ty: &'tcx Ty) {
760 TyKind::Path(ref qself, ref path) => {
761 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
763 TyKind::ImplicitSelf => {
764 let self_ty = keywords::SelfUpper.ident();
765 let def = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
766 .map_or(Def::Err, |d| d.def());
767 self.record_def(ty.id, PathResolution::new(def));
771 visit::walk_ty(self, ty);
773 fn visit_poly_trait_ref(&mut self,
774 tref: &'tcx ast::PolyTraitRef,
775 m: &'tcx ast::TraitBoundModifier) {
776 self.smart_resolve_path(tref.trait_ref.ref_id, None,
777 &tref.trait_ref.path, PathSource::Trait(AliasPossibility::Maybe));
778 visit::walk_poly_trait_ref(self, tref, m);
780 fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
781 let type_parameters = match foreign_item.node {
782 ForeignItemKind::Fn(_, ref generics) => {
783 HasTypeParameters(generics, ItemRibKind)
785 ForeignItemKind::Static(..) => NoTypeParameters,
786 ForeignItemKind::Ty => NoTypeParameters,
787 ForeignItemKind::Macro(..) => NoTypeParameters,
789 self.with_type_parameter_rib(type_parameters, |this| {
790 visit::walk_foreign_item(this, foreign_item);
793 fn visit_fn(&mut self,
794 function_kind: FnKind<'tcx>,
795 declaration: &'tcx FnDecl,
799 let (rib_kind, asyncness) = match function_kind {
800 FnKind::ItemFn(_, ref header, ..) =>
801 (ItemRibKind, header.asyncness),
802 FnKind::Method(_, ref sig, _, _) =>
803 (TraitOrImplItemRibKind, sig.header.asyncness),
804 FnKind::Closure(_) =>
805 // Async closures aren't resolved through `visit_fn`-- they're
806 // processed separately
807 (ClosureRibKind(node_id), IsAsync::NotAsync),
810 // Create a value rib for the function.
811 self.ribs[ValueNS].push(Rib::new(rib_kind));
813 // Create a label rib for the function.
814 self.label_ribs.push(Rib::new(rib_kind));
816 // Add each argument to the rib.
817 let mut bindings_list = FxHashMap::default();
818 for argument in &declaration.inputs {
819 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
821 self.visit_ty(&argument.ty);
823 debug!("(resolving function) recorded argument");
825 visit::walk_fn_ret_ty(self, &declaration.output);
827 // Resolve the function body, potentially inside the body of an async closure
828 if let IsAsync::Async { closure_id, .. } = asyncness {
829 let rib_kind = ClosureRibKind(closure_id);
830 self.ribs[ValueNS].push(Rib::new(rib_kind));
831 self.label_ribs.push(Rib::new(rib_kind));
834 match function_kind {
835 FnKind::ItemFn(.., body) |
836 FnKind::Method(.., body) => {
837 self.visit_block(body);
839 FnKind::Closure(body) => {
840 self.visit_expr(body);
844 // Leave the body of the async closure
845 if asyncness.is_async() {
846 self.label_ribs.pop();
847 self.ribs[ValueNS].pop();
850 debug!("(resolving function) leaving function");
852 self.label_ribs.pop();
853 self.ribs[ValueNS].pop();
855 fn visit_generics(&mut self, generics: &'tcx Generics) {
856 // For type parameter defaults, we have to ban access
857 // to following type parameters, as the Substs can only
858 // provide previous type parameters as they're built. We
859 // put all the parameters on the ban list and then remove
860 // them one by one as they are processed and become available.
861 let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
862 let mut found_default = false;
863 default_ban_rib.bindings.extend(generics.params.iter()
864 .filter_map(|param| match param.kind {
865 GenericParamKind::Lifetime { .. } => None,
866 GenericParamKind::Type { ref default, .. } => {
867 found_default |= default.is_some();
869 Some((Ident::with_empty_ctxt(param.ident.name), Def::Err))
876 for param in &generics.params {
878 GenericParamKind::Lifetime { .. } => self.visit_generic_param(param),
879 GenericParamKind::Type { ref default, .. } => {
880 for bound in ¶m.bounds {
881 self.visit_param_bound(bound);
884 if let Some(ref ty) = default {
885 self.ribs[TypeNS].push(default_ban_rib);
887 default_ban_rib = self.ribs[TypeNS].pop().unwrap();
890 // Allow all following defaults to refer to this type parameter.
891 default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(param.ident.name));
895 for p in &generics.where_clause.predicates {
896 self.visit_where_predicate(p);
901 #[derive(Copy, Clone)]
902 enum TypeParameters<'a, 'b> {
904 HasTypeParameters(// Type parameters.
907 // The kind of the rib used for type parameters.
911 /// The rib kind controls the translation of local
912 /// definitions (`Def::Local`) to upvars (`Def::Upvar`).
913 #[derive(Copy, Clone, Debug)]
915 /// No translation needs to be applied.
918 /// We passed through a closure scope at the given node ID.
919 /// Translate upvars as appropriate.
920 ClosureRibKind(NodeId /* func id */),
922 /// We passed through an impl or trait and are now in one of its
923 /// methods or associated types. Allow references to ty params that impl or trait
924 /// binds. Disallow any other upvars (including other ty params that are
926 TraitOrImplItemRibKind,
928 /// We passed through an item scope. Disallow upvars.
931 /// We're in a constant item. Can't refer to dynamic stuff.
934 /// We passed through a module.
935 ModuleRibKind(Module<'a>),
937 /// We passed through a `macro_rules!` statement
938 MacroDefinition(DefId),
940 /// All bindings in this rib are type parameters that can't be used
941 /// from the default of a type parameter because they're not declared
942 /// before said type parameter. Also see the `visit_generics` override.
943 ForwardTyParamBanRibKind,
948 /// A rib represents a scope names can live in. Note that these appear in many places, not just
949 /// around braces. At any place where the list of accessible names (of the given namespace)
950 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
951 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
954 /// Different [rib kinds](enum.RibKind) are transparent for different names.
956 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
957 /// resolving, the name is looked up from inside out.
960 bindings: FxHashMap<Ident, Def>,
965 fn new(kind: RibKind<'a>) -> Rib<'a> {
967 bindings: Default::default(),
973 /// An intermediate resolution result.
975 /// This refers to the thing referred by a name. The difference between `Def` and `Item` is that
976 /// items are visible in their whole block, while defs only from the place they are defined
978 enum LexicalScopeBinding<'a> {
979 Item(&'a NameBinding<'a>),
983 impl<'a> LexicalScopeBinding<'a> {
984 fn item(self) -> Option<&'a NameBinding<'a>> {
986 LexicalScopeBinding::Item(binding) => Some(binding),
991 fn def(self) -> Def {
993 LexicalScopeBinding::Item(binding) => binding.def(),
994 LexicalScopeBinding::Def(def) => def,
999 #[derive(Copy, Clone, Debug)]
1000 enum ModuleOrUniformRoot<'a> {
1004 /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
1005 CrateRootAndExternPrelude,
1007 /// Virtual module that denotes resolution in extern prelude.
1008 /// Used for paths starting with `::` on 2018 edition or `extern::`.
1011 /// Virtual module that denotes resolution in current scope.
1012 /// Used only for resolving single-segment imports. The reason it exists is that import paths
1013 /// are always split into two parts, the first of which should be some kind of module.
1017 impl<'a> PartialEq for ModuleOrUniformRoot<'a> {
1018 fn eq(&self, other: &Self) -> bool {
1019 match (*self, *other) {
1020 (ModuleOrUniformRoot::Module(lhs),
1021 ModuleOrUniformRoot::Module(rhs)) => ptr::eq(lhs, rhs),
1022 (ModuleOrUniformRoot::CrateRootAndExternPrelude,
1023 ModuleOrUniformRoot::CrateRootAndExternPrelude) |
1024 (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude) |
1025 (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true,
1031 #[derive(Clone, Debug)]
1032 enum PathResult<'a> {
1033 Module(ModuleOrUniformRoot<'a>),
1034 NonModule(PathResolution),
1036 Failed(Span, String, bool /* is the error from the last segment? */),
1040 /// An anonymous module, eg. just a block.
1044 /// fn f() {} // (1)
1045 /// { // This is an anonymous module
1046 /// f(); // This resolves to (2) as we are inside the block.
1047 /// fn f() {} // (2)
1049 /// f(); // Resolves to (1)
1053 /// Any module with a name.
1057 /// * A normal module ‒ either `mod from_file;` or `mod from_block { }`.
1058 /// * A trait or an enum (it implicitly contains associated types, methods and variant
1063 /// One node in the tree of modules.
1064 pub struct ModuleData<'a> {
1065 parent: Option<Module<'a>>,
1068 // The def id of the closest normal module (`mod`) ancestor (including this module).
1069 normal_ancestor_id: DefId,
1071 resolutions: RefCell<FxHashMap<(Ident, Namespace), &'a RefCell<NameResolution<'a>>>>,
1072 single_segment_macro_resolutions: RefCell<Vec<(Ident, MacroKind, ParentScope<'a>,
1073 Option<&'a NameBinding<'a>>)>>,
1074 multi_segment_macro_resolutions: RefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>,
1076 builtin_attrs: RefCell<Vec<(Ident, ParentScope<'a>)>>,
1078 // Macro invocations that can expand into items in this module.
1079 unresolved_invocations: RefCell<FxHashSet<Mark>>,
1081 no_implicit_prelude: bool,
1083 glob_importers: RefCell<Vec<&'a ImportDirective<'a>>>,
1084 globs: RefCell<Vec<&'a ImportDirective<'a>>>,
1086 // Used to memoize the traits in this module for faster searches through all traits in scope.
1087 traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
1089 // Whether this module is populated. If not populated, any attempt to
1090 // access the children must be preceded with a
1091 // `populate_module_if_necessary` call.
1092 populated: Cell<bool>,
1094 /// Span of the module itself. Used for error reporting.
1100 type Module<'a> = &'a ModuleData<'a>;
1102 impl<'a> ModuleData<'a> {
1103 fn new(parent: Option<Module<'a>>,
1105 normal_ancestor_id: DefId,
1107 span: Span) -> Self {
1112 resolutions: Default::default(),
1113 single_segment_macro_resolutions: RefCell::new(Vec::new()),
1114 multi_segment_macro_resolutions: RefCell::new(Vec::new()),
1115 builtin_attrs: RefCell::new(Vec::new()),
1116 unresolved_invocations: Default::default(),
1117 no_implicit_prelude: false,
1118 glob_importers: RefCell::new(Vec::new()),
1119 globs: RefCell::new(Vec::new()),
1120 traits: RefCell::new(None),
1121 populated: Cell::new(normal_ancestor_id.is_local()),
1127 fn for_each_child<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1128 for (&(ident, ns), name_resolution) in self.resolutions.borrow().iter() {
1129 name_resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1133 fn for_each_child_stable<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1134 let resolutions = self.resolutions.borrow();
1135 let mut resolutions = resolutions.iter().collect::<Vec<_>>();
1136 resolutions.sort_by_cached_key(|&(&(ident, ns), _)| (ident.as_str(), ns));
1137 for &(&(ident, ns), &resolution) in resolutions.iter() {
1138 resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1142 fn def(&self) -> Option<Def> {
1144 ModuleKind::Def(def, _) => Some(def),
1149 fn def_id(&self) -> Option<DefId> {
1150 self.def().as_ref().map(Def::def_id)
1153 // `self` resolves to the first module ancestor that `is_normal`.
1154 fn is_normal(&self) -> bool {
1156 ModuleKind::Def(Def::Mod(_), _) => true,
1161 fn is_trait(&self) -> bool {
1163 ModuleKind::Def(Def::Trait(_), _) => true,
1168 fn nearest_item_scope(&'a self) -> Module<'a> {
1169 if self.is_trait() { self.parent.unwrap() } else { self }
1172 fn is_ancestor_of(&self, mut other: &Self) -> bool {
1173 while !ptr::eq(self, other) {
1174 if let Some(parent) = other.parent {
1184 impl<'a> fmt::Debug for ModuleData<'a> {
1185 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1186 write!(f, "{:?}", self.def())
1190 /// Records a possibly-private value, type, or module definition.
1191 #[derive(Clone, Debug)]
1192 pub struct NameBinding<'a> {
1193 kind: NameBindingKind<'a>,
1196 vis: ty::Visibility,
1199 pub trait ToNameBinding<'a> {
1200 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
1203 impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
1204 fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
1209 #[derive(Clone, Debug)]
1210 enum NameBindingKind<'a> {
1211 Def(Def, /* is_macro_export */ bool),
1214 binding: &'a NameBinding<'a>,
1215 directive: &'a ImportDirective<'a>,
1219 kind: AmbiguityKind,
1220 b1: &'a NameBinding<'a>,
1221 b2: &'a NameBinding<'a>,
1225 struct PrivacyError<'a>(Span, Ident, &'a NameBinding<'a>);
1227 struct UseError<'a> {
1228 err: DiagnosticBuilder<'a>,
1229 /// Attach `use` statements for these candidates
1230 candidates: Vec<ImportSuggestion>,
1231 /// The node id of the module to place the use statements in
1233 /// Whether the diagnostic should state that it's "better"
1237 #[derive(Clone, Copy, PartialEq, Debug)]
1238 enum AmbiguityKind {
1243 LegacyHelperVsPrelude,
1248 MoreExpandedVsOuter,
1251 impl AmbiguityKind {
1252 fn descr(self) -> &'static str {
1254 AmbiguityKind::Import =>
1255 "name vs any other name during import resolution",
1256 AmbiguityKind::AbsolutePath =>
1257 "name in the crate root vs extern crate during absolute path resolution",
1258 AmbiguityKind::BuiltinAttr =>
1259 "built-in attribute vs any other name",
1260 AmbiguityKind::DeriveHelper =>
1261 "derive helper attribute vs any other name",
1262 AmbiguityKind::LegacyHelperVsPrelude =>
1263 "legacy plugin helper attribute vs name from prelude",
1264 AmbiguityKind::LegacyVsModern =>
1265 "`macro_rules` vs non-`macro_rules` from other module",
1266 AmbiguityKind::GlobVsOuter =>
1267 "glob import vs any other name from outer scope during import/macro resolution",
1268 AmbiguityKind::GlobVsGlob =>
1269 "glob import vs glob import in the same module",
1270 AmbiguityKind::GlobVsExpanded =>
1271 "glob import vs macro-expanded name in the same \
1272 module during import/macro resolution",
1273 AmbiguityKind::MoreExpandedVsOuter =>
1274 "macro-expanded name vs less macro-expanded name \
1275 from outer scope during import/macro resolution",
1280 /// Miscellaneous bits of metadata for better ambiguity error reporting.
1281 #[derive(Clone, Copy, PartialEq)]
1282 enum AmbiguityErrorMisc {
1289 struct AmbiguityError<'a> {
1290 kind: AmbiguityKind,
1292 b1: &'a NameBinding<'a>,
1293 b2: &'a NameBinding<'a>,
1294 misc1: AmbiguityErrorMisc,
1295 misc2: AmbiguityErrorMisc,
1298 impl<'a> NameBinding<'a> {
1299 fn module(&self) -> Option<Module<'a>> {
1301 NameBindingKind::Module(module) => Some(module),
1302 NameBindingKind::Import { binding, .. } => binding.module(),
1307 fn def(&self) -> Def {
1309 NameBindingKind::Def(def, _) => def,
1310 NameBindingKind::Module(module) => module.def().unwrap(),
1311 NameBindingKind::Import { binding, .. } => binding.def(),
1312 NameBindingKind::Ambiguity { .. } => Def::Err,
1316 fn def_ignoring_ambiguity(&self) -> Def {
1318 NameBindingKind::Import { binding, .. } => binding.def_ignoring_ambiguity(),
1319 NameBindingKind::Ambiguity { b1, .. } => b1.def_ignoring_ambiguity(),
1324 // We sometimes need to treat variants as `pub` for backwards compatibility
1325 fn pseudo_vis(&self) -> ty::Visibility {
1326 if self.is_variant() && self.def().def_id().is_local() {
1327 ty::Visibility::Public
1333 fn is_variant(&self) -> bool {
1335 NameBindingKind::Def(Def::Variant(..), _) |
1336 NameBindingKind::Def(Def::VariantCtor(..), _) => true,
1341 fn is_extern_crate(&self) -> bool {
1343 NameBindingKind::Import {
1344 directive: &ImportDirective {
1345 subclass: ImportDirectiveSubclass::ExternCrate { .. }, ..
1348 NameBindingKind::Module(
1349 &ModuleData { kind: ModuleKind::Def(Def::Mod(def_id), _), .. }
1350 ) => def_id.index == CRATE_DEF_INDEX,
1355 fn is_import(&self) -> bool {
1357 NameBindingKind::Import { .. } => true,
1362 fn is_glob_import(&self) -> bool {
1364 NameBindingKind::Import { directive, .. } => directive.is_glob(),
1365 NameBindingKind::Ambiguity { b1, .. } => b1.is_glob_import(),
1370 fn is_importable(&self) -> bool {
1372 Def::AssociatedConst(..) | Def::Method(..) | Def::AssociatedTy(..) => false,
1377 fn is_macro_def(&self) -> bool {
1379 NameBindingKind::Def(Def::Macro(..), _) => true,
1384 fn macro_kind(&self) -> Option<MacroKind> {
1385 match self.def_ignoring_ambiguity() {
1386 Def::Macro(_, kind) => Some(kind),
1387 Def::NonMacroAttr(..) => Some(MacroKind::Attr),
1392 fn descr(&self) -> &'static str {
1393 if self.is_extern_crate() { "extern crate" } else { self.def().kind_name() }
1396 fn article(&self) -> &'static str {
1397 if self.is_extern_crate() { "an" } else { self.def().article() }
1400 // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
1401 // at some expansion round `max(invoc, binding)` when they both emerged from macros.
1402 // Then this function returns `true` if `self` may emerge from a macro *after* that
1403 // in some later round and screw up our previously found resolution.
1404 // See more detailed explanation in
1405 // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
1406 fn may_appear_after(&self, invoc_parent_expansion: Mark, binding: &NameBinding) -> bool {
1407 // self > max(invoc, binding) => !(self <= invoc || self <= binding)
1408 // Expansions are partially ordered, so "may appear after" is an inversion of
1409 // "certainly appears before or simultaneously" and includes unordered cases.
1410 let self_parent_expansion = self.expansion;
1411 let other_parent_expansion = binding.expansion;
1412 let certainly_before_other_or_simultaneously =
1413 other_parent_expansion.is_descendant_of(self_parent_expansion);
1414 let certainly_before_invoc_or_simultaneously =
1415 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1416 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1420 /// Interns the names of the primitive types.
1422 /// All other types are defined somewhere and possibly imported, but the primitive ones need
1423 /// special handling, since they have no place of origin.
1425 struct PrimitiveTypeTable {
1426 primitive_types: FxHashMap<Name, PrimTy>,
1429 impl PrimitiveTypeTable {
1430 fn new() -> PrimitiveTypeTable {
1431 let mut table = PrimitiveTypeTable::default();
1433 table.intern("bool", Bool);
1434 table.intern("char", Char);
1435 table.intern("f32", Float(FloatTy::F32));
1436 table.intern("f64", Float(FloatTy::F64));
1437 table.intern("isize", Int(IntTy::Isize));
1438 table.intern("i8", Int(IntTy::I8));
1439 table.intern("i16", Int(IntTy::I16));
1440 table.intern("i32", Int(IntTy::I32));
1441 table.intern("i64", Int(IntTy::I64));
1442 table.intern("i128", Int(IntTy::I128));
1443 table.intern("str", Str);
1444 table.intern("usize", Uint(UintTy::Usize));
1445 table.intern("u8", Uint(UintTy::U8));
1446 table.intern("u16", Uint(UintTy::U16));
1447 table.intern("u32", Uint(UintTy::U32));
1448 table.intern("u64", Uint(UintTy::U64));
1449 table.intern("u128", Uint(UintTy::U128));
1453 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1454 self.primitive_types.insert(Symbol::intern(string), primitive_type);
1458 #[derive(Default, Clone)]
1459 pub struct ExternPreludeEntry<'a> {
1460 extern_crate_item: Option<&'a NameBinding<'a>>,
1461 pub introduced_by_item: bool,
1464 /// The main resolver class.
1466 /// This is the visitor that walks the whole crate.
1467 pub struct Resolver<'a> {
1468 session: &'a Session,
1471 pub definitions: Definitions,
1473 graph_root: Module<'a>,
1475 prelude: Option<Module<'a>>,
1476 pub extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
1478 /// n.b. This is used only for better diagnostics, not name resolution itself.
1479 has_self: FxHashSet<DefId>,
1481 /// Names of fields of an item `DefId` accessible with dot syntax.
1482 /// Used for hints during error reporting.
1483 field_names: FxHashMap<DefId, Vec<Name>>,
1485 /// All imports known to succeed or fail.
1486 determined_imports: Vec<&'a ImportDirective<'a>>,
1488 /// All non-determined imports.
1489 indeterminate_imports: Vec<&'a ImportDirective<'a>>,
1491 /// The module that represents the current item scope.
1492 current_module: Module<'a>,
1494 /// The current set of local scopes for types and values.
1495 /// FIXME #4948: Reuse ribs to avoid allocation.
1496 ribs: PerNS<Vec<Rib<'a>>>,
1498 /// The current set of local scopes, for labels.
1499 label_ribs: Vec<Rib<'a>>,
1501 /// The trait that the current context can refer to.
1502 current_trait_ref: Option<(Module<'a>, TraitRef)>,
1504 /// The current self type if inside an impl (used for better errors).
1505 current_self_type: Option<Ty>,
1507 /// The current self item if inside an ADT (used for better errors).
1508 current_self_item: Option<NodeId>,
1510 /// FIXME: Refactor things so that these fields are passed through arguments and not resolver.
1511 /// We are resolving a last import segment during import validation.
1512 last_import_segment: bool,
1513 /// This binding should be ignored during in-module resolution, so that we don't get
1514 /// "self-confirming" import resolutions during import validation.
1515 blacklisted_binding: Option<&'a NameBinding<'a>>,
1517 /// The idents for the primitive types.
1518 primitive_type_table: PrimitiveTypeTable,
1521 import_map: ImportMap,
1522 pub freevars: FreevarMap,
1523 freevars_seen: NodeMap<NodeMap<usize>>,
1524 pub export_map: ExportMap,
1525 pub trait_map: TraitMap,
1527 /// A map from nodes to anonymous modules.
1528 /// Anonymous modules are pseudo-modules that are implicitly created around items
1529 /// contained within blocks.
1531 /// For example, if we have this:
1539 /// There will be an anonymous module created around `g` with the ID of the
1540 /// entry block for `f`.
1541 block_map: NodeMap<Module<'a>>,
1542 module_map: FxHashMap<DefId, Module<'a>>,
1543 extern_module_map: FxHashMap<(DefId, bool /* MacrosOnly? */), Module<'a>>,
1544 binding_parent_modules: FxHashMap<PtrKey<'a, NameBinding<'a>>, Module<'a>>,
1546 pub make_glob_map: bool,
1547 /// Maps imports to the names of items actually imported (this actually maps
1548 /// all imports, but only glob imports are actually interesting).
1549 pub glob_map: GlobMap,
1551 used_imports: FxHashSet<(NodeId, Namespace)>,
1552 pub maybe_unused_trait_imports: NodeSet,
1553 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
1555 /// A list of labels as of yet unused. Labels will be removed from this map when
1556 /// they are used (in a `break` or `continue` statement)
1557 pub unused_labels: FxHashMap<NodeId, Span>,
1559 /// privacy errors are delayed until the end in order to deduplicate them
1560 privacy_errors: Vec<PrivacyError<'a>>,
1561 /// ambiguity errors are delayed for deduplication
1562 ambiguity_errors: Vec<AmbiguityError<'a>>,
1563 /// `use` injections are delayed for better placement and deduplication
1564 use_injections: Vec<UseError<'a>>,
1565 /// crate-local macro expanded `macro_export` referred to by a module-relative path
1566 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
1568 arenas: &'a ResolverArenas<'a>,
1569 dummy_binding: &'a NameBinding<'a>,
1571 crate_loader: &'a mut CrateLoader<'a>,
1572 macro_names: FxHashSet<Ident>,
1573 builtin_macros: FxHashMap<Name, &'a NameBinding<'a>>,
1574 macro_use_prelude: FxHashMap<Name, &'a NameBinding<'a>>,
1575 pub all_macros: FxHashMap<Name, Def>,
1576 macro_map: FxHashMap<DefId, Lrc<SyntaxExtension>>,
1577 macro_defs: FxHashMap<Mark, DefId>,
1578 local_macro_def_scopes: FxHashMap<NodeId, Module<'a>>,
1579 pub found_unresolved_macro: bool,
1581 /// List of crate local macros that we need to warn about as being unused.
1582 /// Right now this only includes macro_rules! macros, and macros 2.0.
1583 unused_macros: FxHashSet<DefId>,
1585 /// Maps the `Mark` of an expansion to its containing module or block.
1586 invocations: FxHashMap<Mark, &'a InvocationData<'a>>,
1588 /// Avoid duplicated errors for "name already defined".
1589 name_already_seen: FxHashMap<Name, Span>,
1591 potentially_unused_imports: Vec<&'a ImportDirective<'a>>,
1593 /// This table maps struct IDs into struct constructor IDs,
1594 /// it's not used during normal resolution, only for better error reporting.
1595 struct_constructors: DefIdMap<(Def, ty::Visibility)>,
1597 /// Only used for better errors on `fn(): fn()`
1598 current_type_ascription: Vec<Span>,
1600 injected_crate: Option<Module<'a>>,
1603 /// Nothing really interesting here, it just provides memory for the rest of the crate.
1605 pub struct ResolverArenas<'a> {
1606 modules: arena::TypedArena<ModuleData<'a>>,
1607 local_modules: RefCell<Vec<Module<'a>>>,
1608 name_bindings: arena::TypedArena<NameBinding<'a>>,
1609 import_directives: arena::TypedArena<ImportDirective<'a>>,
1610 name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1611 invocation_data: arena::TypedArena<InvocationData<'a>>,
1612 legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
1615 impl<'a> ResolverArenas<'a> {
1616 fn alloc_module(&'a self, module: ModuleData<'a>) -> Module<'a> {
1617 let module = self.modules.alloc(module);
1618 if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) {
1619 self.local_modules.borrow_mut().push(module);
1623 fn local_modules(&'a self) -> ::std::cell::Ref<'a, Vec<Module<'a>>> {
1624 self.local_modules.borrow()
1626 fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1627 self.name_bindings.alloc(name_binding)
1629 fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
1630 -> &'a ImportDirective {
1631 self.import_directives.alloc(import_directive)
1633 fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1634 self.name_resolutions.alloc(Default::default())
1636 fn alloc_invocation_data(&'a self, expansion_data: InvocationData<'a>)
1637 -> &'a InvocationData<'a> {
1638 self.invocation_data.alloc(expansion_data)
1640 fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
1641 self.legacy_bindings.alloc(binding)
1645 impl<'a, 'b: 'a> ty::DefIdTree for &'a Resolver<'b> {
1646 fn parent(self, id: DefId) -> Option<DefId> {
1648 LOCAL_CRATE => self.definitions.def_key(id.index).parent,
1649 _ => self.cstore.def_key(id).parent,
1650 }.map(|index| DefId { index, ..id })
1654 /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that
1655 /// the resolver is no longer needed as all the relevant information is inline.
1656 impl<'a> hir::lowering::Resolver for Resolver<'a> {
1657 fn resolve_hir_path(
1662 self.resolve_hir_path_cb(path, is_value,
1663 |resolver, span, error| resolve_error(resolver, span, error))
1666 fn resolve_str_path(
1669 crate_root: Option<&str>,
1670 components: &[&str],
1673 let segments = iter::once(keywords::PathRoot.ident())
1675 crate_root.into_iter()
1676 .chain(components.iter().cloned())
1677 .map(Ident::from_str)
1678 ).map(|i| self.new_ast_path_segment(i)).collect::<Vec<_>>();
1681 let path = ast::Path {
1686 self.resolve_hir_path(&path, is_value)
1689 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution> {
1690 self.def_map.get(&id).cloned()
1693 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>> {
1694 self.import_map.get(&id).cloned().unwrap_or_default()
1697 fn definitions(&mut self) -> &mut Definitions {
1698 &mut self.definitions
1702 impl<'a> Resolver<'a> {
1703 /// Rustdoc uses this to resolve things in a recoverable way. ResolutionError<'a>
1704 /// isn't something that can be returned because it can't be made to live that long,
1705 /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1706 /// just that an error occurred.
1707 pub fn resolve_str_path_error(&mut self, span: Span, path_str: &str, is_value: bool)
1708 -> Result<hir::Path, ()> {
1710 let mut errored = false;
1712 let path = if path_str.starts_with("::") {
1715 segments: iter::once(keywords::PathRoot.ident())
1717 path_str.split("::").skip(1).map(Ident::from_str)
1719 .map(|i| self.new_ast_path_segment(i))
1727 .map(Ident::from_str)
1728 .map(|i| self.new_ast_path_segment(i))
1732 let path = self.resolve_hir_path_cb(&path, is_value, |_, _, _| errored = true);
1733 if errored || path.def == Def::Err {
1740 /// resolve_hir_path, but takes a callback in case there was an error
1741 fn resolve_hir_path_cb<F>(
1747 where F: for<'c, 'b> FnOnce(&'c mut Resolver, Span, ResolutionError<'b>)
1749 let namespace = if is_value { ValueNS } else { TypeNS };
1750 let span = path.span;
1751 let segments = &path.segments;
1752 let path = Segment::from_path(&path);
1753 // FIXME (Manishearth): Intra doc links won't get warned of epoch changes
1754 let def = match self.resolve_path_without_parent_scope(&path, Some(namespace), true,
1755 span, CrateLint::No) {
1756 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1757 module.def().unwrap(),
1758 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 =>
1759 path_res.base_def(),
1760 PathResult::NonModule(..) => {
1761 let msg = "type-relative paths are not supported in this context";
1762 error_callback(self, span, ResolutionError::FailedToResolve(msg));
1765 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
1766 PathResult::Failed(span, msg, _) => {
1767 error_callback(self, span, ResolutionError::FailedToResolve(&msg));
1772 let segments: Vec<_> = segments.iter().map(|seg| {
1773 let mut hir_seg = hir::PathSegment::from_ident(seg.ident);
1774 hir_seg.def = Some(self.def_map.get(&seg.id).map_or(Def::Err, |p| p.base_def()));
1780 segments: segments.into(),
1784 fn new_ast_path_segment(&self, ident: Ident) -> ast::PathSegment {
1785 let mut seg = ast::PathSegment::from_ident(ident);
1786 seg.id = self.session.next_node_id();
1791 impl<'a> Resolver<'a> {
1792 pub fn new(session: &'a Session,
1796 make_glob_map: MakeGlobMap,
1797 crate_loader: &'a mut CrateLoader<'a>,
1798 arenas: &'a ResolverArenas<'a>)
1800 let root_def_id = DefId::local(CRATE_DEF_INDEX);
1801 let root_module_kind = ModuleKind::Def(Def::Mod(root_def_id), keywords::Invalid.name());
1802 let graph_root = arenas.alloc_module(ModuleData {
1803 no_implicit_prelude: attr::contains_name(&krate.attrs, "no_implicit_prelude"),
1804 ..ModuleData::new(None, root_module_kind, root_def_id, Mark::root(), krate.span)
1806 let mut module_map = FxHashMap::default();
1807 module_map.insert(DefId::local(CRATE_DEF_INDEX), graph_root);
1809 let mut definitions = Definitions::new();
1810 DefCollector::new(&mut definitions, Mark::root())
1811 .collect_root(crate_name, session.local_crate_disambiguator());
1813 let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry> =
1814 session.opts.externs.iter().map(|kv| (Ident::from_str(kv.0), Default::default()))
1817 if !attr::contains_name(&krate.attrs, "no_core") {
1818 extern_prelude.insert(Ident::from_str("core"), Default::default());
1819 if !attr::contains_name(&krate.attrs, "no_std") {
1820 extern_prelude.insert(Ident::from_str("std"), Default::default());
1821 if session.rust_2018() {
1822 extern_prelude.insert(Ident::from_str("meta"), Default::default());
1827 let mut invocations = FxHashMap::default();
1828 invocations.insert(Mark::root(),
1829 arenas.alloc_invocation_data(InvocationData::root(graph_root)));
1831 let mut macro_defs = FxHashMap::default();
1832 macro_defs.insert(Mark::root(), root_def_id);
1841 // The outermost module has def ID 0; this is not reflected in the
1847 has_self: FxHashSet::default(),
1848 field_names: FxHashMap::default(),
1850 determined_imports: Vec::new(),
1851 indeterminate_imports: Vec::new(),
1853 current_module: graph_root,
1855 value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1856 type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1857 macro_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1859 label_ribs: Vec::new(),
1861 current_trait_ref: None,
1862 current_self_type: None,
1863 current_self_item: None,
1864 last_import_segment: false,
1865 blacklisted_binding: None,
1867 primitive_type_table: PrimitiveTypeTable::new(),
1869 def_map: Default::default(),
1870 import_map: Default::default(),
1871 freevars: Default::default(),
1872 freevars_seen: Default::default(),
1873 export_map: FxHashMap::default(),
1874 trait_map: Default::default(),
1876 block_map: Default::default(),
1877 extern_module_map: FxHashMap::default(),
1878 binding_parent_modules: FxHashMap::default(),
1880 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1881 glob_map: Default::default(),
1883 used_imports: FxHashSet::default(),
1884 maybe_unused_trait_imports: Default::default(),
1885 maybe_unused_extern_crates: Vec::new(),
1887 unused_labels: FxHashMap::default(),
1889 privacy_errors: Vec::new(),
1890 ambiguity_errors: Vec::new(),
1891 use_injections: Vec::new(),
1892 macro_expanded_macro_export_errors: BTreeSet::new(),
1895 dummy_binding: arenas.alloc_name_binding(NameBinding {
1896 kind: NameBindingKind::Def(Def::Err, false),
1897 expansion: Mark::root(),
1899 vis: ty::Visibility::Public,
1903 macro_names: FxHashSet::default(),
1904 builtin_macros: FxHashMap::default(),
1905 macro_use_prelude: FxHashMap::default(),
1906 all_macros: FxHashMap::default(),
1907 macro_map: FxHashMap::default(),
1910 local_macro_def_scopes: FxHashMap::default(),
1911 name_already_seen: FxHashMap::default(),
1912 potentially_unused_imports: Vec::new(),
1913 struct_constructors: Default::default(),
1914 found_unresolved_macro: false,
1915 unused_macros: FxHashSet::default(),
1916 current_type_ascription: Vec::new(),
1917 injected_crate: None,
1921 pub fn arenas() -> ResolverArenas<'a> {
1925 /// Runs the function on each namespace.
1926 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1932 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1934 match self.macro_defs.get(&ctxt.outer()) {
1935 Some(&def_id) => return def_id,
1936 None => ctxt.remove_mark(),
1941 /// Entry point to crate resolution.
1942 pub fn resolve_crate(&mut self, krate: &Crate) {
1943 ImportResolver { resolver: self }.finalize_imports();
1944 self.current_module = self.graph_root;
1945 self.finalize_current_module_macro_resolutions();
1947 visit::walk_crate(self, krate);
1949 check_unused::check_crate(self, krate);
1950 self.report_errors(krate);
1951 self.crate_loader.postprocess(krate);
1958 normal_ancestor_id: DefId,
1962 let module = ModuleData::new(Some(parent), kind, normal_ancestor_id, expansion, span);
1963 self.arenas.alloc_module(module)
1966 fn record_use(&mut self, ident: Ident, ns: Namespace,
1967 used_binding: &'a NameBinding<'a>, is_lexical_scope: bool) {
1968 match used_binding.kind {
1969 NameBindingKind::Import { directive, binding, ref used } if !used.get() => {
1970 // Avoid marking `extern crate` items that refer to a name from extern prelude,
1971 // but not introduce it, as used if they are accessed from lexical scope.
1972 if is_lexical_scope {
1973 if let Some(entry) = self.extern_prelude.get(&ident.modern()) {
1974 if let Some(crate_item) = entry.extern_crate_item {
1975 if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
1982 directive.used.set(true);
1983 self.used_imports.insert((directive.id, ns));
1984 self.add_to_glob_map(directive.id, ident);
1985 self.record_use(ident, ns, binding, false);
1987 NameBindingKind::Ambiguity { kind, b1, b2 } => {
1988 self.ambiguity_errors.push(AmbiguityError {
1989 kind, ident, b1, b2,
1990 misc1: AmbiguityErrorMisc::None,
1991 misc2: AmbiguityErrorMisc::None,
1998 fn add_to_glob_map(&mut self, id: NodeId, ident: Ident) {
1999 if self.make_glob_map {
2000 self.glob_map.entry(id).or_default().insert(ident.name);
2004 /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
2005 /// More specifically, we proceed up the hierarchy of scopes and return the binding for
2006 /// `ident` in the first scope that defines it (or None if no scopes define it).
2008 /// A block's items are above its local variables in the scope hierarchy, regardless of where
2009 /// the items are defined in the block. For example,
2012 /// g(); // Since there are no local variables in scope yet, this resolves to the item.
2015 /// g(); // This resolves to the local variable `g` since it shadows the item.
2019 /// Invariant: This must only be called during main resolution, not during
2020 /// import resolution.
2021 fn resolve_ident_in_lexical_scope(&mut self,
2024 record_used_id: Option<NodeId>,
2026 -> Option<LexicalScopeBinding<'a>> {
2027 let record_used = record_used_id.is_some();
2028 assert!(ns == TypeNS || ns == ValueNS);
2030 ident.span = if ident.name == keywords::SelfUpper.name() {
2031 // FIXME(jseyfried) improve `Self` hygiene
2032 ident.span.with_ctxt(SyntaxContext::empty())
2037 ident = ident.modern_and_legacy();
2040 // Walk backwards up the ribs in scope.
2041 let mut module = self.graph_root;
2042 for i in (0 .. self.ribs[ns].len()).rev() {
2043 if let Some(def) = self.ribs[ns][i].bindings.get(&ident).cloned() {
2044 // The ident resolves to a type parameter or local variable.
2045 return Some(LexicalScopeBinding::Def(
2046 self.adjust_local_def(ns, i, def, record_used, path_span)
2050 module = match self.ribs[ns][i].kind {
2051 ModuleRibKind(module) => module,
2052 MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => {
2053 // If an invocation of this macro created `ident`, give up on `ident`
2054 // and switch to `ident`'s source from the macro definition.
2055 ident.span.remove_mark();
2061 let item = self.resolve_ident_in_module_unadjusted(
2062 ModuleOrUniformRoot::Module(module),
2068 if let Ok(binding) = item {
2069 // The ident resolves to an item.
2070 return Some(LexicalScopeBinding::Item(binding));
2074 ModuleKind::Block(..) => {}, // We can see through blocks
2079 ident.span = ident.span.modern();
2080 let mut poisoned = None;
2082 let opt_module = if let Some(node_id) = record_used_id {
2083 self.hygienic_lexical_parent_with_compatibility_fallback(module, &mut ident.span,
2084 node_id, &mut poisoned)
2086 self.hygienic_lexical_parent(module, &mut ident.span)
2088 module = unwrap_or!(opt_module, break);
2089 let orig_current_module = self.current_module;
2090 self.current_module = module; // Lexical resolutions can never be a privacy error.
2091 let result = self.resolve_ident_in_module_unadjusted(
2092 ModuleOrUniformRoot::Module(module),
2098 self.current_module = orig_current_module;
2102 if let Some(node_id) = poisoned {
2103 self.session.buffer_lint_with_diagnostic(
2104 lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
2105 node_id, ident.span,
2106 &format!("cannot find {} `{}` in this scope", ns.descr(), ident),
2107 lint::builtin::BuiltinLintDiagnostics::
2108 ProcMacroDeriveResolutionFallback(ident.span),
2111 return Some(LexicalScopeBinding::Item(binding))
2113 Err(Determined) => continue,
2114 Err(Undetermined) =>
2115 span_bug!(ident.span, "undetermined resolution during main resolution pass"),
2119 if !module.no_implicit_prelude {
2121 if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
2122 return Some(LexicalScopeBinding::Item(binding));
2125 if ns == TypeNS && is_known_tool(ident.name) {
2126 let binding = (Def::ToolMod, ty::Visibility::Public,
2127 DUMMY_SP, Mark::root()).to_name_binding(self.arenas);
2128 return Some(LexicalScopeBinding::Item(binding));
2130 if let Some(prelude) = self.prelude {
2131 if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
2132 ModuleOrUniformRoot::Module(prelude),
2138 return Some(LexicalScopeBinding::Item(binding));
2146 fn hygienic_lexical_parent(&mut self, module: Module<'a>, span: &mut Span)
2147 -> Option<Module<'a>> {
2148 if !module.expansion.is_descendant_of(span.ctxt().outer()) {
2149 return Some(self.macro_def_scope(span.remove_mark()));
2152 if let ModuleKind::Block(..) = module.kind {
2153 return Some(module.parent.unwrap());
2159 fn hygienic_lexical_parent_with_compatibility_fallback(&mut self, module: Module<'a>,
2160 span: &mut Span, node_id: NodeId,
2161 poisoned: &mut Option<NodeId>)
2162 -> Option<Module<'a>> {
2163 if let module @ Some(..) = self.hygienic_lexical_parent(module, span) {
2167 // We need to support the next case under a deprecation warning
2170 // ---- begin: this comes from a proc macro derive
2171 // mod implementation_details {
2172 // // Note that `MyStruct` is not in scope here.
2173 // impl SomeTrait for MyStruct { ... }
2177 // So we have to fall back to the module's parent during lexical resolution in this case.
2178 if let Some(parent) = module.parent {
2179 // Inner module is inside the macro, parent module is outside of the macro.
2180 if module.expansion != parent.expansion &&
2181 module.expansion.is_descendant_of(parent.expansion) {
2182 // The macro is a proc macro derive
2183 if module.expansion.looks_like_proc_macro_derive() {
2184 if parent.expansion.is_descendant_of(span.ctxt().outer()) {
2185 *poisoned = Some(node_id);
2186 return module.parent;
2195 fn resolve_ident_in_module(
2197 module: ModuleOrUniformRoot<'a>,
2200 parent_scope: Option<&ParentScope<'a>>,
2203 ) -> Result<&'a NameBinding<'a>, Determinacy> {
2204 self.resolve_ident_in_module_ext(
2205 module, ident, ns, parent_scope, record_used, path_span
2206 ).map_err(|(determinacy, _)| determinacy)
2209 fn resolve_ident_in_module_ext(
2211 module: ModuleOrUniformRoot<'a>,
2214 parent_scope: Option<&ParentScope<'a>>,
2217 ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
2218 let orig_current_module = self.current_module;
2220 ModuleOrUniformRoot::Module(module) => {
2221 ident.span = ident.span.modern();
2222 if let Some(def) = ident.span.adjust(module.expansion) {
2223 self.current_module = self.macro_def_scope(def);
2226 ModuleOrUniformRoot::ExternPrelude => {
2227 ident.span = ident.span.modern();
2228 ident.span.adjust(Mark::root());
2230 ModuleOrUniformRoot::CrateRootAndExternPrelude |
2231 ModuleOrUniformRoot::CurrentScope => {
2235 let result = self.resolve_ident_in_module_unadjusted_ext(
2236 module, ident, ns, parent_scope, false, record_used, path_span,
2238 self.current_module = orig_current_module;
2242 fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> {
2243 let mut ctxt = ident.span.ctxt();
2244 let mark = if ident.name == keywords::DollarCrate.name() {
2245 // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
2246 // we don't want to pretend that the `macro_rules!` definition is in the `macro`
2247 // as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks.
2248 // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
2249 // definitions actually produced by `macro` and `macro` definitions produced by
2250 // `macro_rules!`, but at least such configurations are not stable yet.
2251 ctxt = ctxt.modern_and_legacy();
2252 let mut iter = ctxt.marks().into_iter().rev().peekable();
2253 let mut result = None;
2254 // Find the last modern mark from the end if it exists.
2255 while let Some(&(mark, transparency)) = iter.peek() {
2256 if transparency == Transparency::Opaque {
2257 result = Some(mark);
2263 // Then find the last legacy mark from the end if it exists.
2264 for (mark, transparency) in iter {
2265 if transparency == Transparency::SemiTransparent {
2266 result = Some(mark);
2273 ctxt = ctxt.modern();
2274 ctxt.adjust(Mark::root())
2276 let module = match mark {
2277 Some(def) => self.macro_def_scope(def),
2278 None => return self.graph_root,
2280 self.get_module(DefId { index: CRATE_DEF_INDEX, ..module.normal_ancestor_id })
2283 fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
2284 let mut module = self.get_module(module.normal_ancestor_id);
2285 while module.span.ctxt().modern() != *ctxt {
2286 let parent = module.parent.unwrap_or_else(|| self.macro_def_scope(ctxt.remove_mark()));
2287 module = self.get_module(parent.normal_ancestor_id);
2294 // We maintain a list of value ribs and type ribs.
2296 // Simultaneously, we keep track of the current position in the module
2297 // graph in the `current_module` pointer. When we go to resolve a name in
2298 // the value or type namespaces, we first look through all the ribs and
2299 // then query the module graph. When we resolve a name in the module
2300 // namespace, we can skip all the ribs (since nested modules are not
2301 // allowed within blocks in Rust) and jump straight to the current module
2304 // Named implementations are handled separately. When we find a method
2305 // call, we consult the module node to find all of the implementations in
2306 // scope. This information is lazily cached in the module node. We then
2307 // generate a fake "implementation scope" containing all the
2308 // implementations thus found, for compatibility with old resolve pass.
2310 pub fn with_scope<F, T>(&mut self, id: NodeId, f: F) -> T
2311 where F: FnOnce(&mut Resolver) -> T
2313 let id = self.definitions.local_def_id(id);
2314 let module = self.module_map.get(&id).cloned(); // clones a reference
2315 if let Some(module) = module {
2316 // Move down in the graph.
2317 let orig_module = replace(&mut self.current_module, module);
2318 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
2319 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
2321 self.finalize_current_module_macro_resolutions();
2324 self.current_module = orig_module;
2325 self.ribs[ValueNS].pop();
2326 self.ribs[TypeNS].pop();
2333 /// Searches the current set of local scopes for labels. Returns the first non-None label that
2334 /// is returned by the given predicate function
2336 /// Stops after meeting a closure.
2337 fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
2338 where P: Fn(&Rib, Ident) -> Option<R>
2340 for rib in self.label_ribs.iter().rev() {
2343 // If an invocation of this macro created `ident`, give up on `ident`
2344 // and switch to `ident`'s source from the macro definition.
2345 MacroDefinition(def) => {
2346 if def == self.macro_def(ident.span.ctxt()) {
2347 ident.span.remove_mark();
2351 // Do not resolve labels across function boundary
2355 let r = pred(rib, ident);
2363 fn resolve_adt(&mut self, item: &Item, generics: &Generics) {
2364 self.with_current_self_item(item, |this| {
2365 this.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2366 let item_def_id = this.definitions.local_def_id(item.id);
2367 this.with_self_rib(Def::SelfTy(None, Some(item_def_id)), |this| {
2368 visit::walk_item(this, item);
2374 fn future_proof_import(&mut self, use_tree: &ast::UseTree) {
2375 let segments = &use_tree.prefix.segments;
2376 if !segments.is_empty() {
2377 let ident = segments[0].ident;
2378 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
2382 let nss = match use_tree.kind {
2383 ast::UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
2387 if let Some(LexicalScopeBinding::Def(..)) =
2388 self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
2389 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2390 self.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
2393 } else if let ast::UseTreeKind::Nested(use_trees) = &use_tree.kind {
2394 for (use_tree, _) in use_trees {
2395 self.future_proof_import(use_tree);
2400 fn resolve_item(&mut self, item: &Item) {
2401 let name = item.ident.name;
2402 debug!("(resolving item) resolving {}", name);
2405 ItemKind::Ty(_, ref generics) |
2406 ItemKind::Fn(_, _, ref generics, _) |
2407 ItemKind::Existential(_, ref generics) => {
2408 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind),
2409 |this| visit::walk_item(this, item));
2412 ItemKind::Enum(_, ref generics) |
2413 ItemKind::Struct(_, ref generics) |
2414 ItemKind::Union(_, ref generics) => {
2415 self.resolve_adt(item, generics);
2418 ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
2419 self.resolve_implementation(generics,
2425 ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
2426 // Create a new rib for the trait-wide type parameters.
2427 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2428 let local_def_id = this.definitions.local_def_id(item.id);
2429 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
2430 this.visit_generics(generics);
2431 walk_list!(this, visit_param_bound, bounds);
2433 for trait_item in trait_items {
2434 let type_parameters = HasTypeParameters(&trait_item.generics,
2435 TraitOrImplItemRibKind);
2436 this.with_type_parameter_rib(type_parameters, |this| {
2437 match trait_item.node {
2438 TraitItemKind::Const(ref ty, ref default) => {
2441 // Only impose the restrictions of
2442 // ConstRibKind for an actual constant
2443 // expression in a provided default.
2444 if let Some(ref expr) = *default{
2445 this.with_constant_rib(|this| {
2446 this.visit_expr(expr);
2450 TraitItemKind::Method(_, _) => {
2451 visit::walk_trait_item(this, trait_item)
2453 TraitItemKind::Type(..) => {
2454 visit::walk_trait_item(this, trait_item)
2456 TraitItemKind::Macro(_) => {
2457 panic!("unexpanded macro in resolve!")
2466 ItemKind::TraitAlias(ref generics, ref bounds) => {
2467 // Create a new rib for the trait-wide type parameters.
2468 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2469 let local_def_id = this.definitions.local_def_id(item.id);
2470 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
2471 this.visit_generics(generics);
2472 walk_list!(this, visit_param_bound, bounds);
2477 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
2478 self.with_scope(item.id, |this| {
2479 visit::walk_item(this, item);
2483 ItemKind::Static(ref ty, _, ref expr) |
2484 ItemKind::Const(ref ty, ref expr) => {
2485 self.with_item_rib(|this| {
2487 this.with_constant_rib(|this| {
2488 this.visit_expr(expr);
2493 ItemKind::Use(ref use_tree) => {
2494 self.future_proof_import(use_tree);
2497 ItemKind::ExternCrate(..) |
2498 ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
2499 // do nothing, these are just around to be encoded
2502 ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
2506 fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
2507 where F: FnOnce(&mut Resolver)
2509 match type_parameters {
2510 HasTypeParameters(generics, rib_kind) => {
2511 let mut function_type_rib = Rib::new(rib_kind);
2512 let mut seen_bindings = FxHashMap::default();
2513 for param in &generics.params {
2515 GenericParamKind::Lifetime { .. } => {}
2516 GenericParamKind::Type { .. } => {
2517 let ident = param.ident.modern();
2518 debug!("with_type_parameter_rib: {}", param.id);
2520 if seen_bindings.contains_key(&ident) {
2521 let span = seen_bindings.get(&ident).unwrap();
2522 let err = ResolutionError::NameAlreadyUsedInTypeParameterList(
2526 resolve_error(self, param.ident.span, err);
2528 seen_bindings.entry(ident).or_insert(param.ident.span);
2530 // Plain insert (no renaming).
2531 let def = Def::TyParam(self.definitions.local_def_id(param.id));
2532 function_type_rib.bindings.insert(ident, def);
2533 self.record_def(param.id, PathResolution::new(def));
2537 self.ribs[TypeNS].push(function_type_rib);
2540 NoTypeParameters => {
2547 if let HasTypeParameters(..) = type_parameters {
2548 self.ribs[TypeNS].pop();
2552 fn with_label_rib<F>(&mut self, f: F)
2553 where F: FnOnce(&mut Resolver)
2555 self.label_ribs.push(Rib::new(NormalRibKind));
2557 self.label_ribs.pop();
2560 fn with_item_rib<F>(&mut self, f: F)
2561 where F: FnOnce(&mut Resolver)
2563 self.ribs[ValueNS].push(Rib::new(ItemRibKind));
2564 self.ribs[TypeNS].push(Rib::new(ItemRibKind));
2566 self.ribs[TypeNS].pop();
2567 self.ribs[ValueNS].pop();
2570 fn with_constant_rib<F>(&mut self, f: F)
2571 where F: FnOnce(&mut Resolver)
2573 self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
2574 self.label_ribs.push(Rib::new(ConstantItemRibKind));
2576 self.label_ribs.pop();
2577 self.ribs[ValueNS].pop();
2580 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2581 where F: FnOnce(&mut Resolver) -> T
2583 // Handle nested impls (inside fn bodies)
2584 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2585 let result = f(self);
2586 self.current_self_type = previous_value;
2590 fn with_current_self_item<T, F>(&mut self, self_item: &Item, f: F) -> T
2591 where F: FnOnce(&mut Resolver) -> T
2593 let previous_value = replace(&mut self.current_self_item, Some(self_item.id));
2594 let result = f(self);
2595 self.current_self_item = previous_value;
2599 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`)
2600 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2601 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2603 let mut new_val = None;
2604 let mut new_id = None;
2605 if let Some(trait_ref) = opt_trait_ref {
2606 let path: Vec<_> = Segment::from_path(&trait_ref.path);
2607 let def = self.smart_resolve_path_fragment(
2611 trait_ref.path.span,
2612 PathSource::Trait(AliasPossibility::No),
2613 CrateLint::SimplePath(trait_ref.ref_id),
2615 if def != Def::Err {
2616 new_id = Some(def.def_id());
2617 let span = trait_ref.path.span;
2618 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2619 self.resolve_path_without_parent_scope(
2624 CrateLint::SimplePath(trait_ref.ref_id),
2627 new_val = Some((module, trait_ref.clone()));
2631 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2632 let result = f(self, new_id);
2633 self.current_trait_ref = original_trait_ref;
2637 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2638 where F: FnOnce(&mut Resolver)
2640 let mut self_type_rib = Rib::new(NormalRibKind);
2642 // plain insert (no renaming, types are not currently hygienic....)
2643 self_type_rib.bindings.insert(keywords::SelfUpper.ident(), self_def);
2644 self.ribs[TypeNS].push(self_type_rib);
2646 self.ribs[TypeNS].pop();
2649 fn with_self_struct_ctor_rib<F>(&mut self, impl_id: DefId, f: F)
2650 where F: FnOnce(&mut Resolver)
2652 let self_def = Def::SelfCtor(impl_id);
2653 let mut self_type_rib = Rib::new(NormalRibKind);
2654 self_type_rib.bindings.insert(keywords::SelfUpper.ident(), self_def);
2655 self.ribs[ValueNS].push(self_type_rib);
2657 self.ribs[ValueNS].pop();
2660 fn resolve_implementation(&mut self,
2661 generics: &Generics,
2662 opt_trait_reference: &Option<TraitRef>,
2665 impl_items: &[ImplItem]) {
2666 // If applicable, create a rib for the type parameters.
2667 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2668 // Dummy self type for better errors if `Self` is used in the trait path.
2669 this.with_self_rib(Def::SelfTy(None, None), |this| {
2670 // Resolve the trait reference, if necessary.
2671 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2672 let item_def_id = this.definitions.local_def_id(item_id);
2673 this.with_self_rib(Def::SelfTy(trait_id, Some(item_def_id)), |this| {
2674 if let Some(trait_ref) = opt_trait_reference.as_ref() {
2675 // Resolve type arguments in the trait path.
2676 visit::walk_trait_ref(this, trait_ref);
2678 // Resolve the self type.
2679 this.visit_ty(self_type);
2680 // Resolve the type parameters.
2681 this.visit_generics(generics);
2682 // Resolve the items within the impl.
2683 this.with_current_self_type(self_type, |this| {
2684 this.with_self_struct_ctor_rib(item_def_id, |this| {
2685 for impl_item in impl_items {
2686 this.resolve_visibility(&impl_item.vis);
2688 // We also need a new scope for the impl item type parameters.
2689 let type_parameters = HasTypeParameters(&impl_item.generics,
2690 TraitOrImplItemRibKind);
2691 this.with_type_parameter_rib(type_parameters, |this| {
2692 use self::ResolutionError::*;
2693 match impl_item.node {
2694 ImplItemKind::Const(..) => {
2695 // If this is a trait impl, ensure the const
2697 this.check_trait_item(impl_item.ident,
2700 |n, s| ConstNotMemberOfTrait(n, s));
2701 this.with_constant_rib(|this|
2702 visit::walk_impl_item(this, impl_item)
2705 ImplItemKind::Method(..) => {
2706 // If this is a trait impl, ensure the method
2708 this.check_trait_item(impl_item.ident,
2711 |n, s| MethodNotMemberOfTrait(n, s));
2713 visit::walk_impl_item(this, impl_item);
2715 ImplItemKind::Type(ref ty) => {
2716 // If this is a trait impl, ensure the type
2718 this.check_trait_item(impl_item.ident,
2721 |n, s| TypeNotMemberOfTrait(n, s));
2725 ImplItemKind::Existential(ref bounds) => {
2726 // If this is a trait impl, ensure the type
2728 this.check_trait_item(impl_item.ident,
2731 |n, s| TypeNotMemberOfTrait(n, s));
2733 for bound in bounds {
2734 this.visit_param_bound(bound);
2737 ImplItemKind::Macro(_) =>
2738 panic!("unexpanded macro in resolve!"),
2750 fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
2751 where F: FnOnce(Name, &str) -> ResolutionError
2753 // If there is a TraitRef in scope for an impl, then the method must be in the
2755 if let Some((module, _)) = self.current_trait_ref {
2756 if self.resolve_ident_in_module(
2757 ModuleOrUniformRoot::Module(module),
2764 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2765 resolve_error(self, span, err(ident.name, &path_names_to_string(path)));
2770 fn resolve_local(&mut self, local: &Local) {
2771 // Resolve the type.
2772 walk_list!(self, visit_ty, &local.ty);
2774 // Resolve the initializer.
2775 walk_list!(self, visit_expr, &local.init);
2777 // Resolve the pattern.
2778 self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap::default());
2781 // build a map from pattern identifiers to binding-info's.
2782 // this is done hygienically. This could arise for a macro
2783 // that expands into an or-pattern where one 'x' was from the
2784 // user and one 'x' came from the macro.
2785 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2786 let mut binding_map = FxHashMap::default();
2788 pat.walk(&mut |pat| {
2789 if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
2790 if sub_pat.is_some() || match self.def_map.get(&pat.id).map(|res| res.base_def()) {
2791 Some(Def::Local(..)) => true,
2794 let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
2795 binding_map.insert(ident, binding_info);
2804 // check that all of the arms in an or-pattern have exactly the
2805 // same set of bindings, with the same binding modes for each.
2806 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) {
2807 if pats.is_empty() {
2811 let mut missing_vars = FxHashMap::default();
2812 let mut inconsistent_vars = FxHashMap::default();
2813 for (i, p) in pats.iter().enumerate() {
2814 let map_i = self.binding_mode_map(&p);
2816 for (j, q) in pats.iter().enumerate() {
2821 let map_j = self.binding_mode_map(&q);
2822 for (&key, &binding_i) in &map_i {
2823 if map_j.is_empty() { // Account for missing bindings when
2824 let binding_error = missing_vars // map_j has none.
2826 .or_insert(BindingError {
2828 origin: BTreeSet::new(),
2829 target: BTreeSet::new(),
2831 binding_error.origin.insert(binding_i.span);
2832 binding_error.target.insert(q.span);
2834 for (&key_j, &binding_j) in &map_j {
2835 match map_i.get(&key_j) {
2836 None => { // missing binding
2837 let binding_error = missing_vars
2839 .or_insert(BindingError {
2841 origin: BTreeSet::new(),
2842 target: BTreeSet::new(),
2844 binding_error.origin.insert(binding_j.span);
2845 binding_error.target.insert(p.span);
2847 Some(binding_i) => { // check consistent binding
2848 if binding_i.binding_mode != binding_j.binding_mode {
2851 .or_insert((binding_j.span, binding_i.span));
2859 let mut missing_vars = missing_vars.iter().collect::<Vec<_>>();
2860 missing_vars.sort();
2861 for (_, v) in missing_vars {
2863 *v.origin.iter().next().unwrap(),
2864 ResolutionError::VariableNotBoundInPattern(v));
2866 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
2867 inconsistent_vars.sort();
2868 for (name, v) in inconsistent_vars {
2869 resolve_error(self, v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
2873 fn resolve_arm(&mut self, arm: &Arm) {
2874 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2876 let mut bindings_list = FxHashMap::default();
2877 for pattern in &arm.pats {
2878 self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list);
2881 // This has to happen *after* we determine which pat_idents are variants.
2882 self.check_consistent_bindings(&arm.pats);
2884 if let Some(ast::Guard::If(ref expr)) = arm.guard {
2885 self.visit_expr(expr)
2887 self.visit_expr(&arm.body);
2889 self.ribs[ValueNS].pop();
2892 fn resolve_block(&mut self, block: &Block) {
2893 debug!("(resolving block) entering block");
2894 // Move down in the graph, if there's an anonymous module rooted here.
2895 let orig_module = self.current_module;
2896 let anonymous_module = self.block_map.get(&block.id).cloned(); // clones a reference
2898 let mut num_macro_definition_ribs = 0;
2899 if let Some(anonymous_module) = anonymous_module {
2900 debug!("(resolving block) found anonymous module, moving down");
2901 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2902 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2903 self.current_module = anonymous_module;
2904 self.finalize_current_module_macro_resolutions();
2906 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2909 // Descend into the block.
2910 for stmt in &block.stmts {
2911 if let ast::StmtKind::Item(ref item) = stmt.node {
2912 if let ast::ItemKind::MacroDef(..) = item.node {
2913 num_macro_definition_ribs += 1;
2914 let def = self.definitions.local_def_id(item.id);
2915 self.ribs[ValueNS].push(Rib::new(MacroDefinition(def)));
2916 self.label_ribs.push(Rib::new(MacroDefinition(def)));
2920 self.visit_stmt(stmt);
2924 self.current_module = orig_module;
2925 for _ in 0 .. num_macro_definition_ribs {
2926 self.ribs[ValueNS].pop();
2927 self.label_ribs.pop();
2929 self.ribs[ValueNS].pop();
2930 if anonymous_module.is_some() {
2931 self.ribs[TypeNS].pop();
2933 debug!("(resolving block) leaving block");
2936 fn fresh_binding(&mut self,
2939 outer_pat_id: NodeId,
2940 pat_src: PatternSource,
2941 bindings: &mut FxHashMap<Ident, NodeId>)
2943 // Add the binding to the local ribs, if it
2944 // doesn't already exist in the bindings map. (We
2945 // must not add it if it's in the bindings map
2946 // because that breaks the assumptions later
2947 // passes make about or-patterns.)
2948 let ident = ident.modern_and_legacy();
2949 let mut def = Def::Local(pat_id);
2950 match bindings.get(&ident).cloned() {
2951 Some(id) if id == outer_pat_id => {
2952 // `Variant(a, a)`, error
2956 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2960 Some(..) if pat_src == PatternSource::FnParam => {
2961 // `fn f(a: u8, a: u8)`, error
2965 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2969 Some(..) if pat_src == PatternSource::Match ||
2970 pat_src == PatternSource::IfLet ||
2971 pat_src == PatternSource::WhileLet => {
2972 // `Variant1(a) | Variant2(a)`, ok
2973 // Reuse definition from the first `a`.
2974 def = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident];
2977 span_bug!(ident.span, "two bindings with the same name from \
2978 unexpected pattern source {:?}", pat_src);
2981 // A completely fresh binding, add to the lists if it's valid.
2982 if ident.name != keywords::Invalid.name() {
2983 bindings.insert(ident, outer_pat_id);
2984 self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident, def);
2989 PathResolution::new(def)
2992 fn resolve_pattern(&mut self,
2994 pat_src: PatternSource,
2995 // Maps idents to the node ID for the
2996 // outermost pattern that binds them.
2997 bindings: &mut FxHashMap<Ident, NodeId>) {
2998 // Visit all direct subpatterns of this pattern.
2999 let outer_pat_id = pat.id;
3000 pat.walk(&mut |pat| {
3001 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.node);
3003 PatKind::Ident(bmode, ident, ref opt_pat) => {
3004 // First try to resolve the identifier as some existing
3005 // entity, then fall back to a fresh binding.
3006 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS,
3008 .and_then(LexicalScopeBinding::item);
3009 let resolution = binding.map(NameBinding::def).and_then(|def| {
3010 let is_syntactic_ambiguity = opt_pat.is_none() &&
3011 bmode == BindingMode::ByValue(Mutability::Immutable);
3013 Def::StructCtor(_, CtorKind::Const) |
3014 Def::VariantCtor(_, CtorKind::Const) |
3015 Def::Const(..) if is_syntactic_ambiguity => {
3016 // Disambiguate in favor of a unit struct/variant
3017 // or constant pattern.
3018 self.record_use(ident, ValueNS, binding.unwrap(), false);
3019 Some(PathResolution::new(def))
3021 Def::StructCtor(..) | Def::VariantCtor(..) |
3022 Def::Const(..) | Def::Static(..) => {
3023 // This is unambiguously a fresh binding, either syntactically
3024 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
3025 // to something unusable as a pattern (e.g., constructor function),
3026 // but we still conservatively report an error, see
3027 // issues/33118#issuecomment-233962221 for one reason why.
3031 ResolutionError::BindingShadowsSomethingUnacceptable(
3032 pat_src.descr(), ident.name, binding.unwrap())
3036 Def::Fn(..) | Def::Err => {
3037 // These entities are explicitly allowed
3038 // to be shadowed by fresh bindings.
3042 span_bug!(ident.span, "unexpected definition for an \
3043 identifier in pattern: {:?}", def);
3046 }).unwrap_or_else(|| {
3047 self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
3050 self.record_def(pat.id, resolution);
3053 PatKind::TupleStruct(ref path, ..) => {
3054 self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
3057 PatKind::Path(ref qself, ref path) => {
3058 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
3061 PatKind::Struct(ref path, ..) => {
3062 self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
3070 visit::walk_pat(self, pat);
3073 // High-level and context dependent path resolution routine.
3074 // Resolves the path and records the resolution into definition map.
3075 // If resolution fails tries several techniques to find likely
3076 // resolution candidates, suggest imports or other help, and report
3077 // errors in user friendly way.
3078 fn smart_resolve_path(&mut self,
3080 qself: Option<&QSelf>,
3084 self.smart_resolve_path_with_crate_lint(id, qself, path, source, CrateLint::SimplePath(id))
3087 /// A variant of `smart_resolve_path` where you also specify extra
3088 /// information about where the path came from; this extra info is
3089 /// sometimes needed for the lint that recommends rewriting
3090 /// absolute paths to `crate`, so that it knows how to frame the
3091 /// suggestion. If you are just resolving a path like `foo::bar`
3092 /// that appears...somewhere, though, then you just want
3093 /// `CrateLint::SimplePath`, which is what `smart_resolve_path`
3094 /// already provides.
3095 fn smart_resolve_path_with_crate_lint(
3098 qself: Option<&QSelf>,
3101 crate_lint: CrateLint
3102 ) -> PathResolution {
3103 self.smart_resolve_path_fragment(
3106 &Segment::from_path(path),
3113 fn smart_resolve_path_fragment(&mut self,
3115 qself: Option<&QSelf>,
3119 crate_lint: CrateLint)
3121 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
3122 let ns = source.namespace();
3123 let is_expected = &|def| source.is_expected(def);
3124 let is_enum_variant = &|def| if let Def::Variant(..) = def { true } else { false };
3126 // Base error is amended with one short label and possibly some longer helps/notes.
3127 let report_errors = |this: &mut Self, def: Option<Def>| {
3128 // Make the base error.
3129 let expected = source.descr_expected();
3130 let path_str = Segment::names_to_string(path);
3131 let item_str = path.last().unwrap().ident;
3132 let code = source.error_code(def.is_some());
3133 let (base_msg, fallback_label, base_span) = if let Some(def) = def {
3134 (format!("expected {}, found {} `{}`", expected, def.kind_name(), path_str),
3135 format!("not a {}", expected),
3138 let item_span = path.last().unwrap().ident.span;
3139 let (mod_prefix, mod_str) = if path.len() == 1 {
3140 (String::new(), "this scope".to_string())
3141 } else if path.len() == 2 && path[0].ident.name == keywords::PathRoot.name() {
3142 (String::new(), "the crate root".to_string())
3144 let mod_path = &path[..path.len() - 1];
3145 let mod_prefix = match this.resolve_path_without_parent_scope(
3146 mod_path, Some(TypeNS), false, span, CrateLint::No
3148 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3151 }.map_or(String::new(), |def| format!("{} ", def.kind_name()));
3152 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
3154 (format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
3155 format!("not found in {}", mod_str),
3159 let code = DiagnosticId::Error(code.into());
3160 let mut err = this.session.struct_span_err_with_code(base_span, &base_msg, code);
3162 // Emit help message for fake-self from other languages like `this`(javascript)
3163 if ["this", "my"].contains(&&*item_str.as_str())
3164 && this.self_value_is_available(path[0].ident.span, span) {
3165 err.span_suggestion_with_applicability(
3169 Applicability::MaybeIncorrect,
3173 // Emit special messages for unresolved `Self` and `self`.
3174 if is_self_type(path, ns) {
3175 __diagnostic_used!(E0411);
3176 err.code(DiagnosticId::Error("E0411".into()));
3177 err.span_label(span, format!("`Self` is only available in impls, traits, \
3178 and type definitions"));
3179 return (err, Vec::new());
3181 if is_self_value(path, ns) {
3182 debug!("smart_resolve_path_fragment E0424 source:{:?}", source);
3184 __diagnostic_used!(E0424);
3185 err.code(DiagnosticId::Error("E0424".into()));
3186 err.span_label(span, match source {
3187 PathSource::Pat => {
3188 format!("`self` value is a keyword \
3189 and may not be bound to \
3190 variables or shadowed")
3193 format!("`self` value is a keyword \
3194 only available in methods \
3195 with `self` parameter")
3198 return (err, Vec::new());
3201 // Try to lookup the name in more relaxed fashion for better error reporting.
3202 let ident = path.last().unwrap().ident;
3203 let candidates = this.lookup_import_candidates(ident, ns, is_expected);
3204 if candidates.is_empty() && is_expected(Def::Enum(DefId::local(CRATE_DEF_INDEX))) {
3205 let enum_candidates =
3206 this.lookup_import_candidates(ident, ns, is_enum_variant);
3207 let mut enum_candidates = enum_candidates.iter()
3209 import_candidate_to_enum_paths(&suggestion)
3210 }).collect::<Vec<_>>();
3211 enum_candidates.sort();
3213 if !enum_candidates.is_empty() {
3214 // contextualize for E0412 "cannot find type", but don't belabor the point
3215 // (that it's a variant) for E0573 "expected type, found variant"
3216 let preamble = if def.is_none() {
3217 let others = match enum_candidates.len() {
3219 2 => " and 1 other".to_owned(),
3220 n => format!(" and {} others", n)
3222 format!("there is an enum variant `{}`{}; ",
3223 enum_candidates[0].0, others)
3227 let msg = format!("{}try using the variant's enum", preamble);
3229 err.span_suggestions_with_applicability(
3232 enum_candidates.into_iter()
3233 .map(|(_variant_path, enum_ty_path)| enum_ty_path)
3234 // variants reëxported in prelude doesn't mean `prelude::v1` is the
3235 // type name! FIXME: is there a more principled way to do this that
3236 // would work for other reëxports?
3237 .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
3238 // also say `Option` rather than `std::prelude::v1::Option`
3239 .map(|enum_ty_path| {
3240 // FIXME #56861: DRYer prelude filtering
3241 enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
3243 Applicability::MachineApplicable,
3247 if path.len() == 1 && this.self_type_is_available(span) {
3248 if let Some(candidate) = this.lookup_assoc_candidate(ident, ns, is_expected) {
3249 let self_is_available = this.self_value_is_available(path[0].ident.span, span);
3251 AssocSuggestion::Field => {
3252 err.span_suggestion_with_applicability(
3255 format!("self.{}", path_str),
3256 Applicability::MachineApplicable,
3258 if !self_is_available {
3259 err.span_label(span, format!("`self` value is a keyword \
3261 methods with `self` parameter"));
3264 AssocSuggestion::MethodWithSelf if self_is_available => {
3265 err.span_suggestion_with_applicability(
3268 format!("self.{}", path_str),
3269 Applicability::MachineApplicable,
3272 AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
3273 err.span_suggestion_with_applicability(
3276 format!("Self::{}", path_str),
3277 Applicability::MachineApplicable,
3281 return (err, candidates);
3285 let mut levenshtein_worked = false;
3287 // Try Levenshtein algorithm.
3288 if let Some(candidate) = this.lookup_typo_candidate(path, ns, is_expected, span) {
3289 err.span_label(ident_span, format!("did you mean `{}`?", candidate));
3290 levenshtein_worked = true;
3293 // Try context dependent help if relaxed lookup didn't work.
3294 if let Some(def) = def {
3295 match (def, source) {
3296 (Def::Macro(..), _) => {
3297 err.span_label(span, format!("did you mean `{}!(...)`?", path_str));
3298 return (err, candidates);
3300 (Def::TyAlias(..), PathSource::Trait(_)) => {
3301 err.span_label(span, "type aliases cannot be used as traits");
3302 if nightly_options::is_nightly_build() {
3303 err.note("did you mean to use a trait alias?");
3305 return (err, candidates);
3307 (Def::Mod(..), PathSource::Expr(Some(parent))) => match parent.node {
3308 ExprKind::Field(_, ident) => {
3309 err.span_label(parent.span, format!("did you mean `{}::{}`?",
3311 return (err, candidates);
3313 ExprKind::MethodCall(ref segment, ..) => {
3314 err.span_label(parent.span, format!("did you mean `{}::{}(...)`?",
3315 path_str, segment.ident));
3316 return (err, candidates);
3320 (Def::Enum(..), PathSource::TupleStruct)
3321 | (Def::Enum(..), PathSource::Expr(..)) => {
3322 if let Some(variants) = this.collect_enum_variants(def) {
3323 err.note(&format!("did you mean to use one \
3324 of the following variants?\n{}",
3326 .map(|suggestion| path_names_to_string(suggestion))
3327 .map(|suggestion| format!("- `{}`", suggestion))
3328 .collect::<Vec<_>>()
3332 err.note("did you mean to use one of the enum's variants?");
3334 return (err, candidates);
3336 (Def::Struct(def_id), _) if ns == ValueNS => {
3337 if let Some((ctor_def, ctor_vis))
3338 = this.struct_constructors.get(&def_id).cloned() {
3339 let accessible_ctor = this.is_accessible(ctor_vis);
3340 if is_expected(ctor_def) && !accessible_ctor {
3341 err.span_label(span, format!("constructor is not visible \
3342 here due to private fields"));
3345 // HACK(estebank): find a better way to figure out that this was a
3346 // parser issue where a struct literal is being used on an expression
3347 // where a brace being opened means a block is being started. Look
3348 // ahead for the next text to see if `span` is followed by a `{`.
3349 let sm = this.session.source_map();
3352 sp = sm.next_point(sp);
3353 match sm.span_to_snippet(sp) {
3354 Ok(ref snippet) => {
3355 if snippet.chars().any(|c| { !c.is_whitespace() }) {
3362 let followed_by_brace = match sm.span_to_snippet(sp) {
3363 Ok(ref snippet) if snippet == "{" => true,
3367 PathSource::Expr(Some(parent)) => {
3369 ExprKind::MethodCall(ref path_assignment, _) => {
3370 err.span_suggestion_with_applicability(
3371 sm.start_point(parent.span)
3372 .to(path_assignment.ident.span),
3373 "use `::` to access an associated function",
3376 path_assignment.ident),
3377 Applicability::MaybeIncorrect
3379 return (err, candidates);
3384 format!("did you mean `{} {{ /* fields */ }}`?",
3387 return (err, candidates);
3391 PathSource::Expr(None) if followed_by_brace == true => {
3394 format!("did you mean `({} {{ /* fields */ }})`?",
3397 return (err, candidates);
3402 format!("did you mean `{} {{ /* fields */ }}`?",
3405 return (err, candidates);
3409 return (err, candidates);
3411 (Def::Union(..), _) |
3412 (Def::Variant(..), _) |
3413 (Def::VariantCtor(_, CtorKind::Fictive), _) if ns == ValueNS => {
3414 err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?",
3416 return (err, candidates);
3418 (Def::SelfTy(..), _) if ns == ValueNS => {
3419 err.span_label(span, fallback_label);
3420 err.note("can't use `Self` as a constructor, you must use the \
3421 implemented struct");
3422 return (err, candidates);
3424 (Def::TyAlias(_), _) | (Def::AssociatedTy(..), _) if ns == ValueNS => {
3425 err.note("can't use a type alias as a constructor");
3426 return (err, candidates);
3433 if !levenshtein_worked {
3434 err.span_label(base_span, fallback_label);
3435 this.type_ascription_suggestion(&mut err, base_span);
3439 let report_errors = |this: &mut Self, def: Option<Def>| {
3440 let (err, candidates) = report_errors(this, def);
3441 let def_id = this.current_module.normal_ancestor_id;
3442 let node_id = this.definitions.as_local_node_id(def_id).unwrap();
3443 let better = def.is_some();
3444 this.use_injections.push(UseError { err, candidates, node_id, better });
3445 err_path_resolution()
3448 let resolution = match self.resolve_qpath_anywhere(
3454 source.defer_to_typeck(),
3455 source.global_by_default(),
3458 Some(resolution) if resolution.unresolved_segments() == 0 => {
3459 if is_expected(resolution.base_def()) || resolution.base_def() == Def::Err {
3462 // Add a temporary hack to smooth the transition to new struct ctor
3463 // visibility rules. See #38932 for more details.
3465 if let Def::Struct(def_id) = resolution.base_def() {
3466 if let Some((ctor_def, ctor_vis))
3467 = self.struct_constructors.get(&def_id).cloned() {
3468 if is_expected(ctor_def) && self.is_accessible(ctor_vis) {
3469 let lint = lint::builtin::LEGACY_CONSTRUCTOR_VISIBILITY;
3470 self.session.buffer_lint(lint, id, span,
3471 "private struct constructors are not usable through \
3472 re-exports in outer modules",
3474 res = Some(PathResolution::new(ctor_def));
3479 res.unwrap_or_else(|| report_errors(self, Some(resolution.base_def())))
3482 Some(resolution) if source.defer_to_typeck() => {
3483 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
3484 // or `<T>::A::B`. If `B` should be resolved in value namespace then
3485 // it needs to be added to the trait map.
3487 let item_name = path.last().unwrap().ident;
3488 let traits = self.get_traits_containing_item(item_name, ns);
3489 self.trait_map.insert(id, traits);
3493 _ => report_errors(self, None)
3496 if let PathSource::TraitItem(..) = source {} else {
3497 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
3498 self.record_def(id, resolution);
3503 fn type_ascription_suggestion(&self,
3504 err: &mut DiagnosticBuilder,
3506 debug!("type_ascription_suggetion {:?}", base_span);
3507 let cm = self.session.source_map();
3508 debug!("self.current_type_ascription {:?}", self.current_type_ascription);
3509 if let Some(sp) = self.current_type_ascription.last() {
3511 loop { // try to find the `:`, bail on first non-':'/non-whitespace
3512 sp = cm.next_point(sp);
3513 if let Ok(snippet) = cm.span_to_snippet(sp.to(cm.next_point(sp))) {
3514 debug!("snippet {:?}", snippet);
3515 let line_sp = cm.lookup_char_pos(sp.hi()).line;
3516 let line_base_sp = cm.lookup_char_pos(base_span.lo()).line;
3517 debug!("{:?} {:?}", line_sp, line_base_sp);
3519 err.span_label(base_span,
3520 "expecting a type here because of type ascription");
3521 if line_sp != line_base_sp {
3522 err.span_suggestion_short_with_applicability(
3524 "did you mean to use `;` here instead?",
3526 Applicability::MaybeIncorrect,
3530 } else if !snippet.trim().is_empty() {
3531 debug!("tried to find type ascription `:` token, couldn't find it");
3541 fn self_type_is_available(&mut self, span: Span) -> bool {
3542 let binding = self.resolve_ident_in_lexical_scope(keywords::SelfUpper.ident(),
3543 TypeNS, None, span);
3544 if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
3547 fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
3548 let ident = Ident::new(keywords::SelfLower.name(), self_span);
3549 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
3550 if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
3553 // Resolve in alternative namespaces if resolution in the primary namespace fails.
3554 fn resolve_qpath_anywhere(&mut self,
3556 qself: Option<&QSelf>,
3558 primary_ns: Namespace,
3560 defer_to_typeck: bool,
3561 global_by_default: bool,
3562 crate_lint: CrateLint)
3563 -> Option<PathResolution> {
3564 let mut fin_res = None;
3565 // FIXME: can't resolve paths in macro namespace yet, macros are
3566 // processed by the little special hack below.
3567 for (i, ns) in [primary_ns, TypeNS, ValueNS, /*MacroNS*/].iter().cloned().enumerate() {
3568 if i == 0 || ns != primary_ns {
3569 match self.resolve_qpath(id, qself, path, ns, span, global_by_default, crate_lint) {
3570 // If defer_to_typeck, then resolution > no resolution,
3571 // otherwise full resolution > partial resolution > no resolution.
3572 Some(res) if res.unresolved_segments() == 0 || defer_to_typeck =>
3574 res => if fin_res.is_none() { fin_res = res },
3578 if primary_ns != MacroNS &&
3579 (self.macro_names.contains(&path[0].ident.modern()) ||
3580 self.builtin_macros.get(&path[0].ident.name).cloned()
3581 .and_then(NameBinding::macro_kind) == Some(MacroKind::Bang) ||
3582 self.macro_use_prelude.get(&path[0].ident.name).cloned()
3583 .and_then(NameBinding::macro_kind) == Some(MacroKind::Bang)) {
3584 // Return some dummy definition, it's enough for error reporting.
3586 PathResolution::new(Def::Macro(DefId::local(CRATE_DEF_INDEX), MacroKind::Bang))
3592 /// Handles paths that may refer to associated items.
3593 fn resolve_qpath(&mut self,
3595 qself: Option<&QSelf>,
3599 global_by_default: bool,
3600 crate_lint: CrateLint)
3601 -> Option<PathResolution> {
3603 "resolve_qpath(id={:?}, qself={:?}, path={:?}, \
3604 ns={:?}, span={:?}, global_by_default={:?})",
3613 if let Some(qself) = qself {
3614 if qself.position == 0 {
3615 // This is a case like `<T>::B`, where there is no
3616 // trait to resolve. In that case, we leave the `B`
3617 // segment to be resolved by type-check.
3618 return Some(PathResolution::with_unresolved_segments(
3619 Def::Mod(DefId::local(CRATE_DEF_INDEX)), path.len()
3623 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
3625 // Currently, `path` names the full item (`A::B::C`, in
3626 // our example). so we extract the prefix of that that is
3627 // the trait (the slice upto and including
3628 // `qself.position`). And then we recursively resolve that,
3629 // but with `qself` set to `None`.
3631 // However, setting `qself` to none (but not changing the
3632 // span) loses the information about where this path
3633 // *actually* appears, so for the purposes of the crate
3634 // lint we pass along information that this is the trait
3635 // name from a fully qualified path, and this also
3636 // contains the full span (the `CrateLint::QPathTrait`).
3637 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
3638 let res = self.smart_resolve_path_fragment(
3641 &path[..=qself.position],
3643 PathSource::TraitItem(ns),
3644 CrateLint::QPathTrait {
3646 qpath_span: qself.path_span,
3650 // The remaining segments (the `C` in our example) will
3651 // have to be resolved by type-check, since that requires doing
3652 // trait resolution.
3653 return Some(PathResolution::with_unresolved_segments(
3654 res.base_def(), res.unresolved_segments() + path.len() - qself.position - 1
3658 let result = match self.resolve_path_without_parent_scope(
3665 PathResult::NonModule(path_res) => path_res,
3666 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
3667 PathResolution::new(module.def().unwrap())
3669 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
3670 // don't report an error right away, but try to fallback to a primitive type.
3671 // So, we are still able to successfully resolve something like
3673 // use std::u8; // bring module u8 in scope
3674 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
3675 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
3676 // // not to non-existent std::u8::max_value
3679 // Such behavior is required for backward compatibility.
3680 // The same fallback is used when `a` resolves to nothing.
3681 PathResult::Module(ModuleOrUniformRoot::Module(_)) |
3682 PathResult::Failed(..)
3683 if (ns == TypeNS || path.len() > 1) &&
3684 self.primitive_type_table.primitive_types
3685 .contains_key(&path[0].ident.name) => {
3686 let prim = self.primitive_type_table.primitive_types[&path[0].ident.name];
3687 PathResolution::with_unresolved_segments(Def::PrimTy(prim), path.len() - 1)
3689 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3690 PathResolution::new(module.def().unwrap()),
3691 PathResult::Failed(span, msg, false) => {
3692 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
3693 err_path_resolution()
3695 PathResult::Module(..) | PathResult::Failed(..) => return None,
3696 PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
3699 if path.len() > 1 && !global_by_default && result.base_def() != Def::Err &&
3700 path[0].ident.name != keywords::PathRoot.name() &&
3701 path[0].ident.name != keywords::DollarCrate.name() {
3702 let unqualified_result = {
3703 match self.resolve_path_without_parent_scope(
3704 &[*path.last().unwrap()],
3710 PathResult::NonModule(path_res) => path_res.base_def(),
3711 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3712 module.def().unwrap(),
3713 _ => return Some(result),
3716 if result.base_def() == unqualified_result {
3717 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
3718 self.session.buffer_lint(lint, id, span, "unnecessary qualification")
3725 fn resolve_path_without_parent_scope(
3728 opt_ns: Option<Namespace>, // `None` indicates a module path in import
3731 crate_lint: CrateLint,
3732 ) -> PathResult<'a> {
3733 // Macro and import paths must have full parent scope available during resolution,
3734 // other paths will do okay with parent module alone.
3735 assert!(opt_ns != None && opt_ns != Some(MacroNS));
3736 let parent_scope = ParentScope { module: self.current_module, ..self.dummy_parent_scope() };
3737 self.resolve_path(path, opt_ns, &parent_scope, record_used, path_span, crate_lint)
3743 opt_ns: Option<Namespace>, // `None` indicates a module path in import
3744 parent_scope: &ParentScope<'a>,
3747 crate_lint: CrateLint,
3748 ) -> PathResult<'a> {
3749 let mut module = None;
3750 let mut allow_super = true;
3751 let mut second_binding = None;
3752 self.current_module = parent_scope.module;
3755 "resolve_path(path={:?}, opt_ns={:?}, record_used={:?}, \
3756 path_span={:?}, crate_lint={:?})",
3764 for (i, &Segment { ident, id }) in path.iter().enumerate() {
3765 debug!("resolve_path ident {} {:?} {:?}", i, ident, id);
3766 let record_segment_def = |this: &mut Self, def| {
3768 if let Some(id) = id {
3769 if !this.def_map.contains_key(&id) {
3770 assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id");
3771 this.record_def(id, PathResolution::new(def));
3777 let is_last = i == path.len() - 1;
3778 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
3779 let name = ident.name;
3781 allow_super &= ns == TypeNS &&
3782 (name == keywords::SelfLower.name() ||
3783 name == keywords::Super.name());
3786 if allow_super && name == keywords::Super.name() {
3787 let mut ctxt = ident.span.ctxt().modern();
3788 let self_module = match i {
3789 0 => Some(self.resolve_self(&mut ctxt, self.current_module)),
3791 Some(ModuleOrUniformRoot::Module(module)) => Some(module),
3795 if let Some(self_module) = self_module {
3796 if let Some(parent) = self_module.parent {
3797 module = Some(ModuleOrUniformRoot::Module(
3798 self.resolve_self(&mut ctxt, parent)));
3802 let msg = "there are too many initial `super`s.".to_string();
3803 return PathResult::Failed(ident.span, msg, false);
3806 if name == keywords::SelfLower.name() {
3807 let mut ctxt = ident.span.ctxt().modern();
3808 module = Some(ModuleOrUniformRoot::Module(
3809 self.resolve_self(&mut ctxt, self.current_module)));
3812 if name == keywords::Extern.name() ||
3813 name == keywords::PathRoot.name() && ident.span.rust_2018() {
3814 module = Some(ModuleOrUniformRoot::ExternPrelude);
3817 if name == keywords::PathRoot.name() &&
3818 ident.span.rust_2015() && self.session.rust_2018() {
3819 // `::a::b` from 2015 macro on 2018 global edition
3820 module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude);
3823 if name == keywords::PathRoot.name() ||
3824 name == keywords::Crate.name() ||
3825 name == keywords::DollarCrate.name() {
3826 // `::a::b`, `crate::a::b` or `$crate::a::b`
3827 module = Some(ModuleOrUniformRoot::Module(
3828 self.resolve_crate_root(ident)));
3834 // Report special messages for path segment keywords in wrong positions.
3835 if ident.is_path_segment_keyword() && i != 0 {
3836 let name_str = if name == keywords::PathRoot.name() {
3837 "crate root".to_string()
3839 format!("`{}`", name)
3841 let msg = if i == 1 && path[0].ident.name == keywords::PathRoot.name() {
3842 format!("global paths cannot start with {}", name_str)
3844 format!("{} in paths can only be used in start position", name_str)
3846 return PathResult::Failed(ident.span, msg, false);
3849 let binding = if let Some(module) = module {
3850 self.resolve_ident_in_module(module, ident, ns, None, record_used, path_span)
3851 } else if opt_ns.is_none() || opt_ns == Some(MacroNS) {
3852 assert!(ns == TypeNS);
3853 let scopes = if opt_ns.is_none() { ScopeSet::Import(ns) } else { ScopeSet::Module };
3854 self.early_resolve_ident_in_lexical_scope(ident, scopes, parent_scope, record_used,
3855 record_used, path_span)
3857 let record_used_id =
3858 if record_used { crate_lint.node_id().or(Some(CRATE_NODE_ID)) } else { None };
3859 match self.resolve_ident_in_lexical_scope(ident, ns, record_used_id, path_span) {
3860 // we found a locally-imported or available item/module
3861 Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
3862 // we found a local variable or type param
3863 Some(LexicalScopeBinding::Def(def))
3864 if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => {
3865 record_segment_def(self, def);
3866 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3870 _ => Err(Determinacy::determined(record_used)),
3877 second_binding = Some(binding);
3879 let def = binding.def();
3880 let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(def);
3881 if let Some(next_module) = binding.module() {
3882 module = Some(ModuleOrUniformRoot::Module(next_module));
3883 record_segment_def(self, def);
3884 } else if def == Def::ToolMod && i + 1 != path.len() {
3885 let def = Def::NonMacroAttr(NonMacroAttrKind::Tool);
3886 return PathResult::NonModule(PathResolution::new(def));
3887 } else if def == Def::Err {
3888 return PathResult::NonModule(err_path_resolution());
3889 } else if opt_ns.is_some() && (is_last || maybe_assoc) {
3890 self.lint_if_path_starts_with_module(
3896 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3897 def, path.len() - i - 1
3900 return PathResult::Failed(ident.span,
3901 format!("not a module `{}`", ident),
3905 Err(Undetermined) => return PathResult::Indeterminate,
3906 Err(Determined) => {
3907 if let Some(ModuleOrUniformRoot::Module(module)) = module {
3908 if opt_ns.is_some() && !module.is_normal() {
3909 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3910 module.def().unwrap(), path.len() - i
3914 let module_def = match module {
3915 Some(ModuleOrUniformRoot::Module(module)) => module.def(),
3918 let msg = if module_def == self.graph_root.def() {
3919 let is_mod = |def| match def { Def::Mod(..) => true, _ => false };
3920 let mut candidates =
3921 self.lookup_import_candidates(ident, TypeNS, is_mod);
3922 candidates.sort_by_cached_key(|c| {
3923 (c.path.segments.len(), c.path.to_string())
3925 if let Some(candidate) = candidates.get(0) {
3926 format!("did you mean `{}`?", candidate.path)
3928 format!("maybe a missing `extern crate {};`?", ident)
3931 format!("use of undeclared type or module `{}`", ident)
3933 format!("could not find `{}` in `{}`", ident, path[i - 1].ident)
3935 return PathResult::Failed(ident.span, msg, is_last);
3940 self.lint_if_path_starts_with_module(crate_lint, path, path_span, second_binding);
3942 PathResult::Module(match module {
3943 Some(module) => module,
3944 None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
3945 _ => span_bug!(path_span, "resolve_path: non-empty path `{:?}` has no module", path),
3949 fn lint_if_path_starts_with_module(
3951 crate_lint: CrateLint,
3954 second_binding: Option<&NameBinding>,
3956 let (diag_id, diag_span) = match crate_lint {
3957 CrateLint::No => return,
3958 CrateLint::SimplePath(id) => (id, path_span),
3959 CrateLint::UsePath { root_id, root_span } => (root_id, root_span),
3960 CrateLint::QPathTrait { qpath_id, qpath_span } => (qpath_id, qpath_span),
3963 let first_name = match path.get(0) {
3964 // In the 2018 edition this lint is a hard error, so nothing to do
3965 Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name,
3969 // We're only interested in `use` paths which should start with
3970 // `{{root}}` or `extern` currently.
3971 if first_name != keywords::Extern.name() && first_name != keywords::PathRoot.name() {
3976 // If this import looks like `crate::...` it's already good
3977 Some(Segment { ident, .. }) if ident.name == keywords::Crate.name() => return,
3978 // Otherwise go below to see if it's an extern crate
3980 // If the path has length one (and it's `PathRoot` most likely)
3981 // then we don't know whether we're gonna be importing a crate or an
3982 // item in our crate. Defer this lint to elsewhere
3986 // If the first element of our path was actually resolved to an
3987 // `ExternCrate` (also used for `crate::...`) then no need to issue a
3988 // warning, this looks all good!
3989 if let Some(binding) = second_binding {
3990 if let NameBindingKind::Import { directive: d, .. } = binding.kind {
3991 // Careful: we still want to rewrite paths from
3992 // renamed extern crates.
3993 if let ImportDirectiveSubclass::ExternCrate { source: None, .. } = d.subclass {
3999 let diag = lint::builtin::BuiltinLintDiagnostics
4000 ::AbsPathWithModule(diag_span);
4001 self.session.buffer_lint_with_diagnostic(
4002 lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
4004 "absolute paths must start with `self`, `super`, \
4005 `crate`, or an external crate name in the 2018 edition",
4009 // Resolve a local definition, potentially adjusting for closures.
4010 fn adjust_local_def(&mut self,
4015 span: Span) -> Def {
4016 let ribs = &self.ribs[ns][rib_index + 1..];
4018 // An invalid forward use of a type parameter from a previous default.
4019 if let ForwardTyParamBanRibKind = self.ribs[ns][rib_index].kind {
4021 resolve_error(self, span, ResolutionError::ForwardDeclaredTyParam);
4023 assert_eq!(def, Def::Err);
4029 span_bug!(span, "unexpected {:?} in bindings", def)
4031 Def::Local(node_id) => {
4034 NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) |
4035 ForwardTyParamBanRibKind => {
4036 // Nothing to do. Continue.
4038 ClosureRibKind(function_id) => {
4041 let seen = self.freevars_seen
4044 if let Some(&index) = seen.get(&node_id) {
4045 def = Def::Upvar(node_id, index, function_id);
4048 let vec = self.freevars
4051 let depth = vec.len();
4052 def = Def::Upvar(node_id, depth, function_id);
4059 seen.insert(node_id, depth);
4062 ItemRibKind | TraitOrImplItemRibKind => {
4063 // This was an attempt to access an upvar inside a
4064 // named function item. This is not allowed, so we
4067 resolve_error(self, span,
4068 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
4072 ConstantItemRibKind => {
4073 // Still doesn't deal with upvars
4075 resolve_error(self, span,
4076 ResolutionError::AttemptToUseNonConstantValueInConstant);
4083 Def::TyParam(..) | Def::SelfTy(..) => {
4086 NormalRibKind | TraitOrImplItemRibKind | ClosureRibKind(..) |
4087 ModuleRibKind(..) | MacroDefinition(..) | ForwardTyParamBanRibKind |
4088 ConstantItemRibKind => {
4089 // Nothing to do. Continue.
4092 // This was an attempt to use a type parameter outside
4095 resolve_error(self, span,
4096 ResolutionError::TypeParametersFromOuterFunction(def));
4108 fn lookup_assoc_candidate<FilterFn>(&mut self,
4111 filter_fn: FilterFn)
4112 -> Option<AssocSuggestion>
4113 where FilterFn: Fn(Def) -> bool
4115 fn extract_node_id(t: &Ty) -> Option<NodeId> {
4117 TyKind::Path(None, _) => Some(t.id),
4118 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
4119 // This doesn't handle the remaining `Ty` variants as they are not
4120 // that commonly the self_type, it might be interesting to provide
4121 // support for those in future.
4126 // Fields are generally expected in the same contexts as locals.
4127 if filter_fn(Def::Local(ast::DUMMY_NODE_ID)) {
4128 if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
4129 // Look for a field with the same name in the current self_type.
4130 if let Some(resolution) = self.def_map.get(&node_id) {
4131 match resolution.base_def() {
4132 Def::Struct(did) | Def::Union(did)
4133 if resolution.unresolved_segments() == 0 => {
4134 if let Some(field_names) = self.field_names.get(&did) {
4135 if field_names.iter().any(|&field_name| ident.name == field_name) {
4136 return Some(AssocSuggestion::Field);
4146 // Look for associated items in the current trait.
4147 if let Some((module, _)) = self.current_trait_ref {
4148 if let Ok(binding) = self.resolve_ident_in_module(
4149 ModuleOrUniformRoot::Module(module),
4156 let def = binding.def();
4158 return Some(if self.has_self.contains(&def.def_id()) {
4159 AssocSuggestion::MethodWithSelf
4161 AssocSuggestion::AssocItem
4170 fn lookup_typo_candidate<FilterFn>(&mut self,
4173 filter_fn: FilterFn,
4176 where FilterFn: Fn(Def) -> bool
4178 let add_module_candidates = |module: Module, names: &mut Vec<Name>| {
4179 for (&(ident, _), resolution) in module.resolutions.borrow().iter() {
4180 if let Some(binding) = resolution.borrow().binding {
4181 if filter_fn(binding.def()) {
4182 names.push(ident.name);
4188 let mut names = Vec::new();
4189 if path.len() == 1 {
4190 // Search in lexical scope.
4191 // Walk backwards up the ribs in scope and collect candidates.
4192 for rib in self.ribs[ns].iter().rev() {
4193 // Locals and type parameters
4194 for (ident, def) in &rib.bindings {
4195 if filter_fn(*def) {
4196 names.push(ident.name);
4200 if let ModuleRibKind(module) = rib.kind {
4201 // Items from this module
4202 add_module_candidates(module, &mut names);
4204 if let ModuleKind::Block(..) = module.kind {
4205 // We can see through blocks
4207 // Items from the prelude
4208 if !module.no_implicit_prelude {
4209 names.extend(self.extern_prelude.iter().map(|(ident, _)| ident.name));
4210 if let Some(prelude) = self.prelude {
4211 add_module_candidates(prelude, &mut names);
4218 // Add primitive types to the mix
4219 if filter_fn(Def::PrimTy(Bool)) {
4221 self.primitive_type_table.primitive_types.iter().map(|(name, _)| name)
4225 // Search in module.
4226 let mod_path = &path[..path.len() - 1];
4227 if let PathResult::Module(module) = self.resolve_path_without_parent_scope(
4228 mod_path, Some(TypeNS), false, span, CrateLint::No
4230 if let ModuleOrUniformRoot::Module(module) = module {
4231 add_module_candidates(module, &mut names);
4236 let name = path[path.len() - 1].ident.name;
4237 // Make sure error reporting is deterministic.
4238 names.sort_by_cached_key(|name| name.as_str());
4239 match find_best_match_for_name(names.iter(), &name.as_str(), None) {
4240 Some(found) if found != name => Some(found),
4245 fn with_resolved_label<F>(&mut self, label: Option<Label>, id: NodeId, f: F)
4246 where F: FnOnce(&mut Resolver)
4248 if let Some(label) = label {
4249 self.unused_labels.insert(id, label.ident.span);
4250 let def = Def::Label(id);
4251 self.with_label_rib(|this| {
4252 let ident = label.ident.modern_and_legacy();
4253 this.label_ribs.last_mut().unwrap().bindings.insert(ident, def);
4261 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
4262 self.with_resolved_label(label, id, |this| this.visit_block(block));
4265 fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
4266 // First, record candidate traits for this expression if it could
4267 // result in the invocation of a method call.
4269 self.record_candidate_traits_for_expr_if_necessary(expr);
4271 // Next, resolve the node.
4273 ExprKind::Path(ref qself, ref path) => {
4274 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
4275 visit::walk_expr(self, expr);
4278 ExprKind::Struct(ref path, ..) => {
4279 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
4280 visit::walk_expr(self, expr);
4283 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4284 let def = self.search_label(label.ident, |rib, ident| {
4285 rib.bindings.get(&ident.modern_and_legacy()).cloned()
4289 // Search again for close matches...
4290 // Picks the first label that is "close enough", which is not necessarily
4291 // the closest match
4292 let close_match = self.search_label(label.ident, |rib, ident| {
4293 let names = rib.bindings.iter().map(|(id, _)| &id.name);
4294 find_best_match_for_name(names, &*ident.as_str(), None)
4296 self.record_def(expr.id, err_path_resolution());
4299 ResolutionError::UndeclaredLabel(&label.ident.as_str(),
4302 Some(Def::Label(id)) => {
4303 // Since this def is a label, it is never read.
4304 self.record_def(expr.id, PathResolution::new(Def::Label(id)));
4305 self.unused_labels.remove(&id);
4308 span_bug!(expr.span, "label wasn't mapped to a label def!");
4312 // visit `break` argument if any
4313 visit::walk_expr(self, expr);
4316 ExprKind::IfLet(ref pats, ref subexpression, ref if_block, ref optional_else) => {
4317 self.visit_expr(subexpression);
4319 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
4320 let mut bindings_list = FxHashMap::default();
4322 self.resolve_pattern(pat, PatternSource::IfLet, &mut bindings_list);
4324 // This has to happen *after* we determine which pat_idents are variants
4325 self.check_consistent_bindings(pats);
4326 self.visit_block(if_block);
4327 self.ribs[ValueNS].pop();
4329 optional_else.as_ref().map(|expr| self.visit_expr(expr));
4332 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
4334 ExprKind::While(ref subexpression, ref block, label) => {
4335 self.with_resolved_label(label, expr.id, |this| {
4336 this.visit_expr(subexpression);
4337 this.visit_block(block);
4341 ExprKind::WhileLet(ref pats, ref subexpression, ref block, label) => {
4342 self.with_resolved_label(label, expr.id, |this| {
4343 this.visit_expr(subexpression);
4344 this.ribs[ValueNS].push(Rib::new(NormalRibKind));
4345 let mut bindings_list = FxHashMap::default();
4347 this.resolve_pattern(pat, PatternSource::WhileLet, &mut bindings_list);
4349 // This has to happen *after* we determine which pat_idents are variants.
4350 this.check_consistent_bindings(pats);
4351 this.visit_block(block);
4352 this.ribs[ValueNS].pop();
4356 ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
4357 self.visit_expr(subexpression);
4358 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
4359 self.resolve_pattern(pattern, PatternSource::For, &mut FxHashMap::default());
4361 self.resolve_labeled_block(label, expr.id, block);
4363 self.ribs[ValueNS].pop();
4366 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4368 // Equivalent to `visit::walk_expr` + passing some context to children.
4369 ExprKind::Field(ref subexpression, _) => {
4370 self.resolve_expr(subexpression, Some(expr));
4372 ExprKind::MethodCall(ref segment, ref arguments) => {
4373 let mut arguments = arguments.iter();
4374 self.resolve_expr(arguments.next().unwrap(), Some(expr));
4375 for argument in arguments {
4376 self.resolve_expr(argument, None);
4378 self.visit_path_segment(expr.span, segment);
4381 ExprKind::Call(ref callee, ref arguments) => {
4382 self.resolve_expr(callee, Some(expr));
4383 for argument in arguments {
4384 self.resolve_expr(argument, None);
4387 ExprKind::Type(ref type_expr, _) => {
4388 self.current_type_ascription.push(type_expr.span);
4389 visit::walk_expr(self, expr);
4390 self.current_type_ascription.pop();
4392 // Resolve the body of async exprs inside the async closure to which they desugar
4393 ExprKind::Async(_, async_closure_id, ref block) => {
4394 let rib_kind = ClosureRibKind(async_closure_id);
4395 self.ribs[ValueNS].push(Rib::new(rib_kind));
4396 self.label_ribs.push(Rib::new(rib_kind));
4397 self.visit_block(&block);
4398 self.label_ribs.pop();
4399 self.ribs[ValueNS].pop();
4401 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
4402 // resolve the arguments within the proper scopes so that usages of them inside the
4403 // closure are detected as upvars rather than normal closure arg usages.
4405 _, IsAsync::Async { closure_id: inner_closure_id, .. }, _,
4406 ref fn_decl, ref body, _span,
4408 let rib_kind = ClosureRibKind(expr.id);
4409 self.ribs[ValueNS].push(Rib::new(rib_kind));
4410 self.label_ribs.push(Rib::new(rib_kind));
4411 // Resolve arguments:
4412 let mut bindings_list = FxHashMap::default();
4413 for argument in &fn_decl.inputs {
4414 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
4415 self.visit_ty(&argument.ty);
4417 // No need to resolve return type-- the outer closure return type is
4418 // FunctionRetTy::Default
4420 // Now resolve the inner closure
4422 let rib_kind = ClosureRibKind(inner_closure_id);
4423 self.ribs[ValueNS].push(Rib::new(rib_kind));
4424 self.label_ribs.push(Rib::new(rib_kind));
4425 // No need to resolve arguments: the inner closure has none.
4426 // Resolve the return type:
4427 visit::walk_fn_ret_ty(self, &fn_decl.output);
4429 self.visit_expr(body);
4430 self.label_ribs.pop();
4431 self.ribs[ValueNS].pop();
4433 self.label_ribs.pop();
4434 self.ribs[ValueNS].pop();
4437 visit::walk_expr(self, expr);
4442 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4444 ExprKind::Field(_, ident) => {
4445 // FIXME(#6890): Even though you can't treat a method like a
4446 // field, we need to add any trait methods we find that match
4447 // the field name so that we can do some nice error reporting
4448 // later on in typeck.
4449 let traits = self.get_traits_containing_item(ident, ValueNS);
4450 self.trait_map.insert(expr.id, traits);
4452 ExprKind::MethodCall(ref segment, ..) => {
4453 debug!("(recording candidate traits for expr) recording traits for {}",
4455 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
4456 self.trait_map.insert(expr.id, traits);
4464 fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
4465 -> Vec<TraitCandidate> {
4466 debug!("(getting traits containing item) looking for '{}'", ident.name);
4468 let mut found_traits = Vec::new();
4469 // Look for the current trait.
4470 if let Some((module, _)) = self.current_trait_ref {
4471 if self.resolve_ident_in_module(
4472 ModuleOrUniformRoot::Module(module),
4479 let def_id = module.def_id().unwrap();
4480 found_traits.push(TraitCandidate { def_id: def_id, import_id: None });
4484 ident.span = ident.span.modern();
4485 let mut search_module = self.current_module;
4487 self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
4488 search_module = unwrap_or!(
4489 self.hygienic_lexical_parent(search_module, &mut ident.span), break
4493 if let Some(prelude) = self.prelude {
4494 if !search_module.no_implicit_prelude {
4495 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
4502 fn get_traits_in_module_containing_item(&mut self,
4506 found_traits: &mut Vec<TraitCandidate>) {
4507 assert!(ns == TypeNS || ns == ValueNS);
4508 let mut traits = module.traits.borrow_mut();
4509 if traits.is_none() {
4510 let mut collected_traits = Vec::new();
4511 module.for_each_child(|name, ns, binding| {
4512 if ns != TypeNS { return }
4513 if let Def::Trait(_) = binding.def() {
4514 collected_traits.push((name, binding));
4517 *traits = Some(collected_traits.into_boxed_slice());
4520 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
4521 let module = binding.module().unwrap();
4522 let mut ident = ident;
4523 if ident.span.glob_adjust(module.expansion, binding.span.ctxt().modern()).is_none() {
4526 if self.resolve_ident_in_module_unadjusted(
4527 ModuleOrUniformRoot::Module(module),
4533 let import_id = match binding.kind {
4534 NameBindingKind::Import { directive, .. } => {
4535 self.maybe_unused_trait_imports.insert(directive.id);
4536 self.add_to_glob_map(directive.id, trait_name);
4541 let trait_def_id = module.def_id().unwrap();
4542 found_traits.push(TraitCandidate { def_id: trait_def_id, import_id: import_id });
4547 fn lookup_import_candidates_from_module<FilterFn>(&mut self,
4548 lookup_ident: Ident,
4549 namespace: Namespace,
4550 start_module: &'a ModuleData<'a>,
4552 filter_fn: FilterFn)
4553 -> Vec<ImportSuggestion>
4554 where FilterFn: Fn(Def) -> bool
4556 let mut candidates = Vec::new();
4557 let mut seen_modules = FxHashSet::default();
4558 let not_local_module = crate_name != keywords::Crate.ident();
4559 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), not_local_module)];
4561 while let Some((in_module,
4563 in_module_is_extern)) = worklist.pop() {
4564 self.populate_module_if_necessary(in_module);
4566 // We have to visit module children in deterministic order to avoid
4567 // instabilities in reported imports (#43552).
4568 in_module.for_each_child_stable(|ident, ns, name_binding| {
4569 // avoid imports entirely
4570 if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
4571 // avoid non-importable candidates as well
4572 if !name_binding.is_importable() { return; }
4574 // collect results based on the filter function
4575 if ident.name == lookup_ident.name && ns == namespace {
4576 if filter_fn(name_binding.def()) {
4578 let mut segms = path_segments.clone();
4579 if lookup_ident.span.rust_2018() {
4580 // crate-local absolute paths start with `crate::` in edition 2018
4581 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
4583 0, ast::PathSegment::from_ident(crate_name)
4587 segms.push(ast::PathSegment::from_ident(ident));
4589 span: name_binding.span,
4592 // the entity is accessible in the following cases:
4593 // 1. if it's defined in the same crate, it's always
4594 // accessible (since private entities can be made public)
4595 // 2. if it's defined in another crate, it's accessible
4596 // only if both the module is public and the entity is
4597 // declared as public (due to pruning, we don't explore
4598 // outside crate private modules => no need to check this)
4599 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
4600 candidates.push(ImportSuggestion { path });
4605 // collect submodules to explore
4606 if let Some(module) = name_binding.module() {
4608 let mut path_segments = path_segments.clone();
4609 path_segments.push(ast::PathSegment::from_ident(ident));
4611 let is_extern_crate_that_also_appears_in_prelude =
4612 name_binding.is_extern_crate() &&
4613 lookup_ident.span.rust_2018();
4615 let is_visible_to_user =
4616 !in_module_is_extern || name_binding.vis == ty::Visibility::Public;
4618 if !is_extern_crate_that_also_appears_in_prelude && is_visible_to_user {
4619 // add the module to the lookup
4620 let is_extern = in_module_is_extern || name_binding.is_extern_crate();
4621 if seen_modules.insert(module.def_id().unwrap()) {
4622 worklist.push((module, path_segments, is_extern));
4632 /// When name resolution fails, this method can be used to look up candidate
4633 /// entities with the expected name. It allows filtering them using the
4634 /// supplied predicate (which should be used to only accept the types of
4635 /// definitions expected e.g., traits). The lookup spans across all crates.
4637 /// NOTE: The method does not look into imports, but this is not a problem,
4638 /// since we report the definitions (thus, the de-aliased imports).
4639 fn lookup_import_candidates<FilterFn>(&mut self,
4640 lookup_ident: Ident,
4641 namespace: Namespace,
4642 filter_fn: FilterFn)
4643 -> Vec<ImportSuggestion>
4644 where FilterFn: Fn(Def) -> bool
4646 let mut suggestions = self.lookup_import_candidates_from_module(
4647 lookup_ident, namespace, self.graph_root, keywords::Crate.ident(), &filter_fn);
4649 if lookup_ident.span.rust_2018() {
4650 let extern_prelude_names = self.extern_prelude.clone();
4651 for (ident, _) in extern_prelude_names.into_iter() {
4652 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name,
4654 let crate_root = self.get_module(DefId {
4656 index: CRATE_DEF_INDEX,
4658 self.populate_module_if_necessary(&crate_root);
4660 suggestions.extend(self.lookup_import_candidates_from_module(
4661 lookup_ident, namespace, crate_root, ident, &filter_fn));
4669 fn find_module(&mut self,
4671 -> Option<(Module<'a>, ImportSuggestion)>
4673 let mut result = None;
4674 let mut seen_modules = FxHashSet::default();
4675 let mut worklist = vec![(self.graph_root, Vec::new())];
4677 while let Some((in_module, path_segments)) = worklist.pop() {
4678 // abort if the module is already found
4679 if result.is_some() { break; }
4681 self.populate_module_if_necessary(in_module);
4683 in_module.for_each_child_stable(|ident, _, name_binding| {
4684 // abort if the module is already found or if name_binding is private external
4685 if result.is_some() || !name_binding.vis.is_visible_locally() {
4688 if let Some(module) = name_binding.module() {
4690 let mut path_segments = path_segments.clone();
4691 path_segments.push(ast::PathSegment::from_ident(ident));
4692 if module.def() == Some(module_def) {
4694 span: name_binding.span,
4695 segments: path_segments,
4697 result = Some((module, ImportSuggestion { path }));
4699 // add the module to the lookup
4700 if seen_modules.insert(module.def_id().unwrap()) {
4701 worklist.push((module, path_segments));
4711 fn collect_enum_variants(&mut self, enum_def: Def) -> Option<Vec<Path>> {
4712 if let Def::Enum(..) = enum_def {} else {
4713 panic!("Non-enum def passed to collect_enum_variants: {:?}", enum_def)
4716 self.find_module(enum_def).map(|(enum_module, enum_import_suggestion)| {
4717 self.populate_module_if_necessary(enum_module);
4719 let mut variants = Vec::new();
4720 enum_module.for_each_child_stable(|ident, _, name_binding| {
4721 if let Def::Variant(..) = name_binding.def() {
4722 let mut segms = enum_import_suggestion.path.segments.clone();
4723 segms.push(ast::PathSegment::from_ident(ident));
4724 variants.push(Path {
4725 span: name_binding.span,
4734 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
4735 debug!("(recording def) recording {:?} for {}", resolution, node_id);
4736 if let Some(prev_res) = self.def_map.insert(node_id, resolution) {
4737 panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
4741 fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
4743 ast::VisibilityKind::Public => ty::Visibility::Public,
4744 ast::VisibilityKind::Crate(..) => {
4745 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
4747 ast::VisibilityKind::Inherited => {
4748 ty::Visibility::Restricted(self.current_module.normal_ancestor_id)
4750 ast::VisibilityKind::Restricted { ref path, id, .. } => {
4751 // For visibilities we are not ready to provide correct implementation of "uniform
4752 // paths" right now, so on 2018 edition we only allow module-relative paths for now.
4753 // On 2015 edition visibilities are resolved as crate-relative by default,
4754 // so we are prepending a root segment if necessary.
4755 let ident = path.segments.get(0).expect("empty path in visibility").ident;
4756 let crate_root = if ident.is_path_segment_keyword() {
4758 } else if ident.span.rust_2018() {
4759 let msg = "relative paths are not supported in visibilities on 2018 edition";
4760 self.session.struct_span_err(ident.span, msg)
4761 .span_suggestion(path.span, "try", format!("crate::{}", path))
4763 return ty::Visibility::Public;
4765 let ctxt = ident.span.ctxt();
4766 Some(Segment::from_ident(Ident::new(
4767 keywords::PathRoot.name(), path.span.shrink_to_lo().with_ctxt(ctxt)
4771 let segments = crate_root.into_iter()
4772 .chain(path.segments.iter().map(|seg| seg.into())).collect::<Vec<_>>();
4773 let def = self.smart_resolve_path_fragment(
4778 PathSource::Visibility,
4779 CrateLint::SimplePath(id),
4781 if def == Def::Err {
4782 ty::Visibility::Public
4784 let vis = ty::Visibility::Restricted(def.def_id());
4785 if self.is_accessible(vis) {
4788 self.session.span_err(path.span, "visibilities can only be restricted \
4789 to ancestor modules");
4790 ty::Visibility::Public
4797 fn is_accessible(&self, vis: ty::Visibility) -> bool {
4798 vis.is_accessible_from(self.current_module.normal_ancestor_id, self)
4801 fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
4802 vis.is_accessible_from(module.normal_ancestor_id, self)
4805 fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) {
4806 if let Some(old_module) = self.binding_parent_modules.insert(PtrKey(binding), module) {
4807 if !ptr::eq(module, old_module) {
4808 span_bug!(binding.span, "parent module is reset for binding");
4813 fn disambiguate_legacy_vs_modern(
4815 legacy: &'a NameBinding<'a>,
4816 modern: &'a NameBinding<'a>,
4818 // Some non-controversial subset of ambiguities "modern macro name" vs "macro_rules"
4819 // is disambiguated to mitigate regressions from macro modularization.
4820 // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
4821 match (self.binding_parent_modules.get(&PtrKey(legacy)),
4822 self.binding_parent_modules.get(&PtrKey(modern))) {
4823 (Some(legacy), Some(modern)) =>
4824 legacy.normal_ancestor_id == modern.normal_ancestor_id &&
4825 modern.is_ancestor_of(legacy),
4830 fn binding_description(&self, b: &NameBinding, ident: Ident, from_prelude: bool) -> String {
4831 if b.span.is_dummy() {
4832 let add_built_in = match b.def() {
4833 // These already contain the "built-in" prefix or look bad with it.
4834 Def::NonMacroAttr(..) | Def::PrimTy(..) | Def::ToolMod => false,
4837 let (built_in, from) = if from_prelude {
4838 ("", " from prelude")
4839 } else if b.is_extern_crate() && !b.is_import() &&
4840 self.session.opts.externs.get(&ident.as_str()).is_some() {
4841 ("", " passed with `--extern`")
4842 } else if add_built_in {
4848 let article = if built_in.is_empty() { b.article() } else { "a" };
4849 format!("{a}{built_in} {thing}{from}",
4850 a = article, thing = b.descr(), built_in = built_in, from = from)
4852 let introduced = if b.is_import() { "imported" } else { "defined" };
4853 format!("the {thing} {introduced} here",
4854 thing = b.descr(), introduced = introduced)
4858 fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError) {
4859 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
4860 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
4861 // We have to print the span-less alternative first, otherwise formatting looks bad.
4862 (b2, b1, misc2, misc1, true)
4864 (b1, b2, misc1, misc2, false)
4867 let mut err = struct_span_err!(self.session, ident.span, E0659,
4868 "`{ident}` is ambiguous ({why})",
4869 ident = ident, why = kind.descr());
4870 err.span_label(ident.span, "ambiguous name");
4872 let mut could_refer_to = |b: &NameBinding, misc: AmbiguityErrorMisc, also: &str| {
4873 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
4874 let note_msg = format!("`{ident}` could{also} refer to {what}",
4875 ident = ident, also = also, what = what);
4877 let mut help_msgs = Vec::new();
4878 if b.is_glob_import() && (kind == AmbiguityKind::GlobVsGlob ||
4879 kind == AmbiguityKind::GlobVsExpanded ||
4880 kind == AmbiguityKind::GlobVsOuter &&
4881 swapped != also.is_empty()) {
4882 help_msgs.push(format!("consider adding an explicit import of \
4883 `{ident}` to disambiguate", ident = ident))
4885 if b.is_extern_crate() && ident.span.rust_2018() {
4886 help_msgs.push(format!(
4887 "use `::{ident}` to refer to this {thing} unambiguously",
4888 ident = ident, thing = b.descr(),
4891 if misc == AmbiguityErrorMisc::SuggestCrate {
4892 help_msgs.push(format!(
4893 "use `crate::{ident}` to refer to this {thing} unambiguously",
4894 ident = ident, thing = b.descr(),
4896 } else if misc == AmbiguityErrorMisc::SuggestSelf {
4897 help_msgs.push(format!(
4898 "use `self::{ident}` to refer to this {thing} unambiguously",
4899 ident = ident, thing = b.descr(),
4903 if b.span.is_dummy() {
4904 err.note(¬e_msg);
4906 err.span_note(b.span, ¬e_msg);
4908 for (i, help_msg) in help_msgs.iter().enumerate() {
4909 let or = if i == 0 { "" } else { "or " };
4910 err.help(&format!("{}{}", or, help_msg));
4914 could_refer_to(b1, misc1, "");
4915 could_refer_to(b2, misc2, " also");
4919 fn report_errors(&mut self, krate: &Crate) {
4920 self.report_with_use_injections(krate);
4922 for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
4923 let msg = "macro-expanded `macro_export` macros from the current crate \
4924 cannot be referred to by absolute paths";
4925 self.session.buffer_lint_with_diagnostic(
4926 lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
4927 CRATE_NODE_ID, span_use, msg,
4928 lint::builtin::BuiltinLintDiagnostics::
4929 MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
4933 for ambiguity_error in &self.ambiguity_errors {
4934 self.report_ambiguity_error(ambiguity_error);
4937 let mut reported_spans = FxHashSet::default();
4938 for &PrivacyError(dedup_span, ident, binding) in &self.privacy_errors {
4939 if reported_spans.insert(dedup_span) {
4940 span_err!(self.session, ident.span, E0603, "{} `{}` is private",
4941 binding.descr(), ident.name);
4946 fn report_with_use_injections(&mut self, krate: &Crate) {
4947 for UseError { mut err, candidates, node_id, better } in self.use_injections.drain(..) {
4948 let (span, found_use) = UsePlacementFinder::check(krate, node_id);
4949 if !candidates.is_empty() {
4950 show_candidates(&mut err, span, &candidates, better, found_use);
4956 fn report_conflict<'b>(&mut self,
4960 new_binding: &NameBinding<'b>,
4961 old_binding: &NameBinding<'b>) {
4962 // Error on the second of two conflicting names
4963 if old_binding.span.lo() > new_binding.span.lo() {
4964 return self.report_conflict(parent, ident, ns, old_binding, new_binding);
4967 let container = match parent.kind {
4968 ModuleKind::Def(Def::Mod(_), _) => "module",
4969 ModuleKind::Def(Def::Trait(_), _) => "trait",
4970 ModuleKind::Block(..) => "block",
4974 let old_noun = match old_binding.is_import() {
4976 false => "definition",
4979 let new_participle = match new_binding.is_import() {
4984 let (name, span) = (ident.name, self.session.source_map().def_span(new_binding.span));
4986 if let Some(s) = self.name_already_seen.get(&name) {
4992 let old_kind = match (ns, old_binding.module()) {
4993 (ValueNS, _) => "value",
4994 (MacroNS, _) => "macro",
4995 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
4996 (TypeNS, Some(module)) if module.is_normal() => "module",
4997 (TypeNS, Some(module)) if module.is_trait() => "trait",
4998 (TypeNS, _) => "type",
5001 let msg = format!("the name `{}` is defined multiple times", name);
5003 let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
5004 (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
5005 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
5006 true => struct_span_err!(self.session, span, E0254, "{}", msg),
5007 false => struct_span_err!(self.session, span, E0260, "{}", msg),
5009 _ => match (old_binding.is_import(), new_binding.is_import()) {
5010 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
5011 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
5012 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
5016 err.note(&format!("`{}` must be defined only once in the {} namespace of this {}",
5021 err.span_label(span, format!("`{}` re{} here", name, new_participle));
5022 if !old_binding.span.is_dummy() {
5023 err.span_label(self.session.source_map().def_span(old_binding.span),
5024 format!("previous {} of the {} `{}` here", old_noun, old_kind, name));
5027 // See https://github.com/rust-lang/rust/issues/32354
5028 if old_binding.is_import() || new_binding.is_import() {
5029 let binding = if new_binding.is_import() && !new_binding.span.is_dummy() {
5035 let cm = self.session.source_map();
5036 let rename_msg = "you can use `as` to change the binding name of the import";
5040 NameBindingKind::Import { directive, ..},
5043 cm.span_to_snippet(binding.span),
5044 binding.kind.clone(),
5045 binding.span.is_dummy(),
5047 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
5048 format!("Other{}", name)
5050 format!("other_{}", name)
5053 err.span_suggestion_with_applicability(
5056 match directive.subclass {
5057 ImportDirectiveSubclass::SingleImport { type_ns_only: true, .. } =>
5058 format!("self as {}", suggested_name),
5059 ImportDirectiveSubclass::SingleImport { source, .. } =>
5062 &snippet[..((source.span.hi().0 - binding.span.lo().0) as usize)],
5064 if snippet.ends_with(";") {
5070 ImportDirectiveSubclass::ExternCrate { source, target, .. } =>
5072 "extern crate {} as {};",
5073 source.unwrap_or(target.name),
5076 _ => unreachable!(),
5078 Applicability::MaybeIncorrect,
5081 err.span_label(binding.span, rename_msg);
5086 self.name_already_seen.insert(name, span);
5089 fn extern_prelude_get(&mut self, ident: Ident, speculative: bool)
5090 -> Option<&'a NameBinding<'a>> {
5091 if ident.is_path_segment_keyword() {
5092 // Make sure `self`, `super` etc produce an error when passed to here.
5095 self.extern_prelude.get(&ident.modern()).cloned().and_then(|entry| {
5096 if let Some(binding) = entry.extern_crate_item {
5099 let crate_id = if !speculative {
5100 self.crate_loader.process_path_extern(ident.name, ident.span)
5101 } else if let Some(crate_id) =
5102 self.crate_loader.maybe_process_path_extern(ident.name, ident.span) {
5107 let crate_root = self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
5108 self.populate_module_if_necessary(&crate_root);
5109 Some((crate_root, ty::Visibility::Public, DUMMY_SP, Mark::root())
5110 .to_name_binding(self.arenas))
5116 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
5117 namespace == TypeNS && path.len() == 1 && path[0].ident.name == keywords::SelfUpper.name()
5120 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
5121 namespace == ValueNS && path.len() == 1 && path[0].ident.name == keywords::SelfLower.name()
5124 fn names_to_string(idents: &[Ident]) -> String {
5125 let mut result = String::new();
5126 for (i, ident) in idents.iter()
5127 .filter(|ident| ident.name != keywords::PathRoot.name())
5130 result.push_str("::");
5132 result.push_str(&ident.as_str());
5137 fn path_names_to_string(path: &Path) -> String {
5138 names_to_string(&path.segments.iter()
5139 .map(|seg| seg.ident)
5140 .collect::<Vec<_>>())
5143 /// Get the stringified path for an enum from an `ImportSuggestion` for an enum variant.
5144 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
5145 let variant_path = &suggestion.path;
5146 let variant_path_string = path_names_to_string(variant_path);
5148 let path_len = suggestion.path.segments.len();
5149 let enum_path = ast::Path {
5150 span: suggestion.path.span,
5151 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
5153 let enum_path_string = path_names_to_string(&enum_path);
5155 (variant_path_string, enum_path_string)
5159 /// When an entity with a given name is not available in scope, we search for
5160 /// entities with that name in all crates. This method allows outputting the
5161 /// results of this search in a programmer-friendly way
5162 fn show_candidates(err: &mut DiagnosticBuilder,
5163 // This is `None` if all placement locations are inside expansions
5165 candidates: &[ImportSuggestion],
5169 // we want consistent results across executions, but candidates are produced
5170 // by iterating through a hash map, so make sure they are ordered:
5171 let mut path_strings: Vec<_> =
5172 candidates.into_iter().map(|c| path_names_to_string(&c.path)).collect();
5173 path_strings.sort();
5175 let better = if better { "better " } else { "" };
5176 let msg_diff = match path_strings.len() {
5177 1 => " is found in another module, you can import it",
5178 _ => "s are found in other modules, you can import them",
5180 let msg = format!("possible {}candidate{} into scope", better, msg_diff);
5182 if let Some(span) = span {
5183 for candidate in &mut path_strings {
5184 // produce an additional newline to separate the new use statement
5185 // from the directly following item.
5186 let additional_newline = if found_use {
5191 *candidate = format!("use {};\n{}", candidate, additional_newline);
5194 err.span_suggestions_with_applicability(
5197 path_strings.into_iter(),
5198 Applicability::Unspecified,
5203 for candidate in path_strings {
5205 msg.push_str(&candidate);
5210 /// A somewhat inefficient routine to obtain the name of a module.
5211 fn module_to_string(module: Module) -> Option<String> {
5212 let mut names = Vec::new();
5214 fn collect_mod(names: &mut Vec<Ident>, module: Module) {
5215 if let ModuleKind::Def(_, name) = module.kind {
5216 if let Some(parent) = module.parent {
5217 names.push(Ident::with_empty_ctxt(name));
5218 collect_mod(names, parent);
5221 // danger, shouldn't be ident?
5222 names.push(Ident::from_str("<opaque>"));
5223 collect_mod(names, module.parent.unwrap());
5226 collect_mod(&mut names, module);
5228 if names.is_empty() {
5231 Some(names_to_string(&names.into_iter()
5233 .collect::<Vec<_>>()))
5236 fn err_path_resolution() -> PathResolution {
5237 PathResolution::new(Def::Err)
5240 #[derive(PartialEq,Copy, Clone)]
5241 pub enum MakeGlobMap {
5246 #[derive(Copy, Clone, Debug)]
5248 /// Do not issue the lint
5251 /// This lint applies to some random path like `impl ::foo::Bar`
5252 /// or whatever. In this case, we can take the span of that path.
5255 /// This lint comes from a `use` statement. In this case, what we
5256 /// care about really is the *root* `use` statement; e.g., if we
5257 /// have nested things like `use a::{b, c}`, we care about the
5259 UsePath { root_id: NodeId, root_span: Span },
5261 /// This is the "trait item" from a fully qualified path. For example,
5262 /// we might be resolving `X::Y::Z` from a path like `<T as X::Y>::Z`.
5263 /// The `path_span` is the span of the to the trait itself (`X::Y`).
5264 QPathTrait { qpath_id: NodeId, qpath_span: Span },
5268 fn node_id(&self) -> Option<NodeId> {
5270 CrateLint::No => None,
5271 CrateLint::SimplePath(id) |
5272 CrateLint::UsePath { root_id: id, .. } |
5273 CrateLint::QPathTrait { qpath_id: id, .. } => Some(id),
5278 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }