1 // ignore-tidy-filelength
3 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
5 #![feature(crate_visibility_modifier)]
6 #![feature(label_break_value)]
9 #![feature(rustc_diagnostic_macros)]
11 #![recursion_limit="256"]
13 #![deny(rust_2018_idioms)]
14 #![deny(unused_lifetimes)]
16 pub use rustc::hir::def::{Namespace, PerNS};
19 use GenericParameters::*;
21 use smallvec::smallvec;
23 use rustc::hir::map::Definitions;
24 use rustc::hir::{self, PrimTy, Bool, Char, Float, Int, Uint, Str};
25 use rustc::middle::cstore::CrateStore;
26 use rustc::session::Session;
28 use rustc::hir::def::{
29 self, DefKind, PartialRes, CtorKind, CtorOf, NonMacroAttrKind, ExportMap
31 use rustc::hir::def::Namespace::*;
32 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
33 use rustc::hir::{TraitCandidate, TraitMap, GlobMap};
35 use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap};
36 use rustc::{bug, span_bug};
38 use rustc_metadata::creader::CrateLoader;
39 use rustc_metadata::cstore::CStore;
41 use syntax::source_map::SourceMap;
42 use syntax::ext::hygiene::{ExpnId, Transparency, SyntaxContext};
43 use syntax::ast::{self, Name, NodeId, Ident, FloatTy, IntTy, UintTy};
44 use syntax::ext::base::SyntaxExtension;
45 use syntax::ext::base::MacroKind;
46 use syntax::symbol::{Symbol, kw, sym};
47 use syntax::util::lev_distance::find_best_match_for_name;
49 use syntax::visit::{self, FnKind, Visitor};
51 use syntax::ast::{CRATE_NODE_ID, Arm, IsAsync, BindingMode, Block, Crate, Expr, ExprKind};
52 use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParamKind, Generics};
53 use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind};
54 use syntax::ast::{Label, Local, Mutability, Pat, PatKind, Path};
55 use syntax::ast::{QSelf, TraitItem, TraitItemKind, TraitRef, Ty, TyKind};
57 use syntax::{span_err, struct_span_err, unwrap_or, walk_list};
59 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
60 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
64 use std::cell::{Cell, RefCell};
65 use std::{cmp, fmt, iter, mem, ptr};
66 use std::collections::BTreeSet;
67 use std::mem::replace;
68 use rustc_data_structures::ptr_key::PtrKey;
69 use rustc_data_structures::sync::Lrc;
70 use smallvec::SmallVec;
72 use diagnostics::{Suggestion, ImportSuggestion};
73 use diagnostics::{find_span_of_binding_until_next_binding, extend_span_to_previous_binding};
74 use resolve_imports::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver};
75 use macros::{InvocationData, LegacyBinding, LegacyScope};
77 type Res = def::Res<NodeId>;
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 const KNOWN_TOOLS: &[Name] = &[sym::clippy, sym::rustfmt];
95 #[derive(Copy, Clone, PartialEq, Debug)]
96 pub enum Determinacy {
102 fn determined(determined: bool) -> Determinacy {
103 if determined { Determinacy::Determined } else { Determinacy::Undetermined }
107 /// A specific scope in which a name can be looked up.
108 /// This enum is currently used only for early resolution (imports and macros),
109 /// but not for late resolution yet.
110 #[derive(Clone, Copy)]
113 MacroRules(LegacyScope<'a>),
125 /// Names from different contexts may want to visit different subsets of all specific scopes
126 /// with different restrictions when looking up the resolution.
127 /// This enum is currently used only for early resolution (imports and macros),
128 /// but not for late resolution yet.
131 AbsolutePath(Namespace),
136 /// Everything you need to know about a name's location to resolve it.
137 /// Serves as a starting point for the scope visitor.
138 /// This struct is currently used only for early resolution (imports and macros),
139 /// but not for late resolution yet.
140 #[derive(Clone, Debug)]
141 pub struct ParentScope<'a> {
144 legacy: LegacyScope<'a>,
145 derives: Vec<ast::Path>,
149 struct BindingError {
151 origin: BTreeSet<Span>,
152 target: BTreeSet<Span>,
155 impl PartialOrd for BindingError {
156 fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> {
157 Some(self.cmp(other))
161 impl PartialEq for BindingError {
162 fn eq(&self, other: &BindingError) -> bool {
163 self.name == other.name
167 impl Ord for BindingError {
168 fn cmp(&self, other: &BindingError) -> cmp::Ordering {
169 self.name.cmp(&other.name)
173 enum ResolutionError<'a> {
174 /// Error E0401: can't use type or const parameters from outer function.
175 GenericParamsFromOuterFunction(Res),
176 /// Error E0403: the name is already used for a type or const parameter in this generic
178 NameAlreadyUsedInParameterList(Name, &'a Span),
179 /// Error E0407: method is not a member of trait.
180 MethodNotMemberOfTrait(Name, &'a str),
181 /// Error E0437: type is not a member of trait.
182 TypeNotMemberOfTrait(Name, &'a str),
183 /// Error E0438: const is not a member of trait.
184 ConstNotMemberOfTrait(Name, &'a str),
185 /// Error E0408: variable `{}` is not bound in all patterns.
186 VariableNotBoundInPattern(&'a BindingError),
187 /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
188 VariableBoundWithDifferentMode(Name, Span),
189 /// Error E0415: identifier is bound more than once in this parameter list.
190 IdentifierBoundMoreThanOnceInParameterList(&'a str),
191 /// Error E0416: identifier is bound more than once in the same pattern.
192 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
193 /// Error E0426: use of undeclared label.
194 UndeclaredLabel(&'a str, Option<Name>),
195 /// Error E0429: `self` imports are only allowed within a `{ }` list.
196 SelfImportsOnlyAllowedWithin,
197 /// Error E0430: `self` import can only appear once in the list.
198 SelfImportCanOnlyAppearOnceInTheList,
199 /// Error E0431: `self` import can only appear in an import list with a non-empty prefix.
200 SelfImportOnlyInImportListWithNonEmptyPrefix,
201 /// Error E0433: failed to resolve.
202 FailedToResolve { label: String, suggestion: Option<Suggestion> },
203 /// Error E0434: can't capture dynamic environment in a fn item.
204 CannotCaptureDynamicEnvironmentInFnItem,
205 /// Error E0435: attempt to use a non-constant value in a constant.
206 AttemptToUseNonConstantValueInConstant,
207 /// Error E0530: `X` bindings cannot shadow `Y`s.
208 BindingShadowsSomethingUnacceptable(&'a str, Name, &'a NameBinding<'a>),
209 /// Error E0128: type parameters with a default cannot use forward-declared identifiers.
210 ForwardDeclaredTyParam, // FIXME(const_generics:defaults)
211 /// Error E0671: const parameter cannot depend on type parameter.
212 ConstParamDependentOnTypeParam,
215 /// Combines an error with provided span and emits it.
217 /// This takes the error provided, combines it with the span and any additional spans inside the
218 /// error and emits it.
219 fn resolve_error(resolver: &Resolver<'_>,
221 resolution_error: ResolutionError<'_>) {
222 resolve_struct_error(resolver, span, resolution_error).emit();
225 fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver<'_>,
227 resolution_error: ResolutionError<'a>)
228 -> DiagnosticBuilder<'sess> {
229 match resolution_error {
230 ResolutionError::GenericParamsFromOuterFunction(outer_res) => {
231 let mut err = struct_span_err!(resolver.session,
234 "can't use generic parameters from outer function",
236 err.span_label(span, format!("use of generic parameter from outer function"));
238 let cm = resolver.session.source_map();
240 Res::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
241 if let Some(impl_span) = maybe_impl_defid.and_then(|def_id| {
242 resolver.definitions.opt_span(def_id)
245 reduce_impl_span_to_impl_keyword(cm, impl_span),
246 "`Self` type implicitly declared here, by this `impl`",
249 match (maybe_trait_defid, maybe_impl_defid) {
251 err.span_label(span, "can't use `Self` here");
254 err.span_label(span, "use a type here instead");
256 (None, None) => bug!("`impl` without trait nor type?"),
260 Res::Def(DefKind::TyParam, def_id) => {
261 if let Some(span) = resolver.definitions.opt_span(def_id) {
262 err.span_label(span, "type parameter from outer function");
265 Res::Def(DefKind::ConstParam, def_id) => {
266 if let Some(span) = resolver.definitions.opt_span(def_id) {
267 err.span_label(span, "const parameter from outer function");
271 bug!("GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
276 // Try to retrieve the span of the function signature and generate a new message with
277 // a local type or const parameter.
278 let sugg_msg = &format!("try using a local generic parameter instead");
279 if let Some((sugg_span, new_snippet)) = cm.generate_local_type_param_snippet(span) {
280 // Suggest the modification to the user
285 Applicability::MachineApplicable,
287 } else if let Some(sp) = cm.generate_fn_name_span(span) {
289 format!("try adding a local generic parameter in this method instead"));
291 err.help(&format!("try using a local generic parameter instead"));
296 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
297 let mut err = struct_span_err!(resolver.session,
300 "the name `{}` is already used for a generic \
301 parameter in this list of generic parameters",
303 err.span_label(span, "already used");
304 err.span_label(first_use_span.clone(), format!("first use of `{}`", name));
307 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
308 let mut err = struct_span_err!(resolver.session,
311 "method `{}` is not a member of trait `{}`",
314 err.span_label(span, format!("not a member of trait `{}`", trait_));
317 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
318 let mut err = struct_span_err!(resolver.session,
321 "type `{}` is not a member of trait `{}`",
324 err.span_label(span, format!("not a member of trait `{}`", trait_));
327 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
328 let mut err = struct_span_err!(resolver.session,
331 "const `{}` is not a member of trait `{}`",
334 err.span_label(span, format!("not a member of trait `{}`", trait_));
337 ResolutionError::VariableNotBoundInPattern(binding_error) => {
338 let target_sp = binding_error.target.iter().cloned().collect::<Vec<_>>();
339 let msp = MultiSpan::from_spans(target_sp.clone());
340 let msg = format!("variable `{}` is not bound in all patterns", binding_error.name);
341 let mut err = resolver.session.struct_span_err_with_code(
344 DiagnosticId::Error("E0408".into()),
346 for sp in target_sp {
347 err.span_label(sp, format!("pattern doesn't bind `{}`", binding_error.name));
349 let origin_sp = binding_error.origin.iter().cloned();
350 for sp in origin_sp {
351 err.span_label(sp, "variable not in all patterns");
355 ResolutionError::VariableBoundWithDifferentMode(variable_name,
356 first_binding_span) => {
357 let mut err = struct_span_err!(resolver.session,
360 "variable `{}` is bound in inconsistent \
361 ways within the same match arm",
363 err.span_label(span, "bound in different ways");
364 err.span_label(first_binding_span, "first binding");
367 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
368 let mut err = struct_span_err!(resolver.session,
371 "identifier `{}` is bound more than once in this parameter list",
373 err.span_label(span, "used as parameter more than once");
376 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
377 let mut err = struct_span_err!(resolver.session,
380 "identifier `{}` is bound more than once in the same pattern",
382 err.span_label(span, "used in a pattern more than once");
385 ResolutionError::UndeclaredLabel(name, lev_candidate) => {
386 let mut err = struct_span_err!(resolver.session,
389 "use of undeclared label `{}`",
391 if let Some(lev_candidate) = lev_candidate {
394 "a label with a similar name exists in this scope",
395 lev_candidate.to_string(),
396 Applicability::MaybeIncorrect,
399 err.span_label(span, format!("undeclared label `{}`", name));
403 ResolutionError::SelfImportsOnlyAllowedWithin => {
404 struct_span_err!(resolver.session,
408 "`self` imports are only allowed within a { } list")
410 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
411 let mut err = struct_span_err!(resolver.session, span, E0430,
412 "`self` import can only appear once in an import list");
413 err.span_label(span, "can only appear once in an import list");
416 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
417 let mut err = struct_span_err!(resolver.session, span, E0431,
418 "`self` import can only appear in an import list with \
419 a non-empty prefix");
420 err.span_label(span, "can only appear in an import list with a non-empty prefix");
423 ResolutionError::FailedToResolve { label, suggestion } => {
424 let mut err = struct_span_err!(resolver.session, span, E0433,
425 "failed to resolve: {}", &label);
426 err.span_label(span, label);
428 if let Some((suggestions, msg, applicability)) = suggestion {
429 err.multipart_suggestion(&msg, suggestions, applicability);
434 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
435 let mut err = struct_span_err!(resolver.session,
439 "can't capture dynamic environment in a fn item");
440 err.help("use the `|| { ... }` closure form instead");
443 ResolutionError::AttemptToUseNonConstantValueInConstant => {
444 let mut err = struct_span_err!(resolver.session, span, E0435,
445 "attempt to use a non-constant value in a constant");
446 err.span_label(span, "non-constant value");
449 ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
450 let shadows_what = binding.descr();
451 let mut err = struct_span_err!(resolver.session, span, E0530, "{}s cannot shadow {}s",
452 what_binding, shadows_what);
453 err.span_label(span, format!("cannot be named the same as {} {}",
454 binding.article(), shadows_what));
455 let participle = if binding.is_import() { "imported" } else { "defined" };
456 let msg = format!("the {} `{}` is {} here", shadows_what, name, participle);
457 err.span_label(binding.span, msg);
460 ResolutionError::ForwardDeclaredTyParam => {
461 let mut err = struct_span_err!(resolver.session, span, E0128,
462 "type parameters with a default cannot use \
463 forward declared identifiers");
465 span, "defaulted type parameters cannot be forward declared".to_string());
468 ResolutionError::ConstParamDependentOnTypeParam => {
469 let mut err = struct_span_err!(
473 "const parameters cannot depend on type parameters"
475 err.span_label(span, format!("const parameter depends on type parameter"));
481 /// Adjust the impl span so that just the `impl` keyword is taken by removing
482 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
483 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
485 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
486 /// parser. If you need to use this function or something similar, please consider updating the
487 /// `source_map` functions and this function to something more robust.
488 fn reduce_impl_span_to_impl_keyword(cm: &SourceMap, impl_span: Span) -> Span {
489 let impl_span = cm.span_until_char(impl_span, '<');
490 let impl_span = cm.span_until_whitespace(impl_span);
494 #[derive(Copy, Clone, Debug)]
497 binding_mode: BindingMode,
500 /// Map from the name in a pattern to its binding mode.
501 type BindingMap = FxHashMap<Ident, BindingInfo>;
503 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
512 fn descr(self) -> &'static str {
514 PatternSource::Match => "match binding",
515 PatternSource::Let => "let binding",
516 PatternSource::For => "for binding",
517 PatternSource::FnParam => "function parameter",
522 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
523 enum AliasPossibility {
528 #[derive(Copy, Clone, Debug)]
529 enum PathSource<'a> {
530 // Type paths `Path`.
532 // Trait paths in bounds or impls.
533 Trait(AliasPossibility),
534 // Expression paths `path`, with optional parent context.
535 Expr(Option<&'a Expr>),
536 // Paths in path patterns `Path`.
538 // Paths in struct expressions and patterns `Path { .. }`.
540 // Paths in tuple struct patterns `Path(..)`.
542 // `m::A::B` in `<T as m::A>::B::C`.
543 TraitItem(Namespace),
544 // Path in `pub(path)`
548 impl<'a> PathSource<'a> {
549 fn namespace(self) -> Namespace {
551 PathSource::Type | PathSource::Trait(_) | PathSource::Struct |
552 PathSource::Visibility => TypeNS,
553 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
554 PathSource::TraitItem(ns) => ns,
558 fn global_by_default(self) -> bool {
560 PathSource::Visibility => true,
561 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
562 PathSource::Struct | PathSource::TupleStruct |
563 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
567 fn defer_to_typeck(self) -> bool {
569 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
570 PathSource::Struct | PathSource::TupleStruct => true,
571 PathSource::Trait(_) | PathSource::TraitItem(..) |
572 PathSource::Visibility => false,
576 fn descr_expected(self) -> &'static str {
578 PathSource::Type => "type",
579 PathSource::Trait(_) => "trait",
580 PathSource::Pat => "unit struct/variant or constant",
581 PathSource::Struct => "struct, variant or union type",
582 PathSource::TupleStruct => "tuple struct/variant",
583 PathSource::Visibility => "module",
584 PathSource::TraitItem(ns) => match ns {
585 TypeNS => "associated type",
586 ValueNS => "method or associated constant",
587 MacroNS => bug!("associated macro"),
589 PathSource::Expr(parent) => match parent.map(|p| &p.node) {
590 // "function" here means "anything callable" rather than `DefKind::Fn`,
591 // this is not precise but usually more helpful than just "value".
592 Some(&ExprKind::Call(..)) => "function",
598 fn is_expected(self, res: Res) -> bool {
600 PathSource::Type => match res {
601 Res::Def(DefKind::Struct, _)
602 | Res::Def(DefKind::Union, _)
603 | Res::Def(DefKind::Enum, _)
604 | Res::Def(DefKind::Trait, _)
605 | Res::Def(DefKind::TraitAlias, _)
606 | Res::Def(DefKind::TyAlias, _)
607 | Res::Def(DefKind::AssocTy, _)
609 | Res::Def(DefKind::TyParam, _)
611 | Res::Def(DefKind::Existential, _)
612 | Res::Def(DefKind::ForeignTy, _) => true,
615 PathSource::Trait(AliasPossibility::No) => match res {
616 Res::Def(DefKind::Trait, _) => true,
619 PathSource::Trait(AliasPossibility::Maybe) => match res {
620 Res::Def(DefKind::Trait, _) => true,
621 Res::Def(DefKind::TraitAlias, _) => true,
624 PathSource::Expr(..) => match res {
625 Res::Def(DefKind::Ctor(_, CtorKind::Const), _)
626 | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
627 | Res::Def(DefKind::Const, _)
628 | Res::Def(DefKind::Static, _)
630 | Res::Def(DefKind::Fn, _)
631 | Res::Def(DefKind::Method, _)
632 | Res::Def(DefKind::AssocConst, _)
634 | Res::Def(DefKind::ConstParam, _) => true,
637 PathSource::Pat => match res {
638 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) |
639 Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) |
640 Res::SelfCtor(..) => true,
643 PathSource::TupleStruct => match res {
644 Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..) => true,
647 PathSource::Struct => match res {
648 Res::Def(DefKind::Struct, _)
649 | Res::Def(DefKind::Union, _)
650 | Res::Def(DefKind::Variant, _)
651 | Res::Def(DefKind::TyAlias, _)
652 | Res::Def(DefKind::AssocTy, _)
653 | Res::SelfTy(..) => true,
656 PathSource::TraitItem(ns) => match res {
657 Res::Def(DefKind::AssocConst, _)
658 | Res::Def(DefKind::Method, _) if ns == ValueNS => true,
659 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
662 PathSource::Visibility => match res {
663 Res::Def(DefKind::Mod, _) => true,
669 fn error_code(self, has_unexpected_resolution: bool) -> &'static str {
670 __diagnostic_used!(E0404);
671 __diagnostic_used!(E0405);
672 __diagnostic_used!(E0412);
673 __diagnostic_used!(E0422);
674 __diagnostic_used!(E0423);
675 __diagnostic_used!(E0425);
676 __diagnostic_used!(E0531);
677 __diagnostic_used!(E0532);
678 __diagnostic_used!(E0573);
679 __diagnostic_used!(E0574);
680 __diagnostic_used!(E0575);
681 __diagnostic_used!(E0576);
682 __diagnostic_used!(E0577);
683 __diagnostic_used!(E0578);
684 match (self, has_unexpected_resolution) {
685 (PathSource::Trait(_), true) => "E0404",
686 (PathSource::Trait(_), false) => "E0405",
687 (PathSource::Type, true) => "E0573",
688 (PathSource::Type, false) => "E0412",
689 (PathSource::Struct, true) => "E0574",
690 (PathSource::Struct, false) => "E0422",
691 (PathSource::Expr(..), true) => "E0423",
692 (PathSource::Expr(..), false) => "E0425",
693 (PathSource::Pat, true) | (PathSource::TupleStruct, true) => "E0532",
694 (PathSource::Pat, false) | (PathSource::TupleStruct, false) => "E0531",
695 (PathSource::TraitItem(..), true) => "E0575",
696 (PathSource::TraitItem(..), false) => "E0576",
697 (PathSource::Visibility, true) => "E0577",
698 (PathSource::Visibility, false) => "E0578",
703 // A minimal representation of a path segment. We use this in resolve because
704 // we synthesize 'path segments' which don't have the rest of an AST or HIR
706 #[derive(Clone, Copy, Debug)]
713 fn from_path(path: &Path) -> Vec<Segment> {
714 path.segments.iter().map(|s| s.into()).collect()
717 fn from_ident(ident: Ident) -> Segment {
724 fn names_to_string(segments: &[Segment]) -> String {
725 names_to_string(&segments.iter()
726 .map(|seg| seg.ident)
727 .collect::<Vec<_>>())
731 impl<'a> From<&'a ast::PathSegment> for Segment {
732 fn from(seg: &'a ast::PathSegment) -> Segment {
740 struct UsePlacementFinder {
741 target_module: NodeId,
746 impl UsePlacementFinder {
747 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, bool) {
748 let mut finder = UsePlacementFinder {
753 visit::walk_crate(&mut finder, krate);
754 (finder.span, finder.found_use)
758 impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
761 module: &'tcx ast::Mod,
763 _: &[ast::Attribute],
766 if self.span.is_some() {
769 if node_id != self.target_module {
770 visit::walk_mod(self, module);
773 // find a use statement
774 for item in &module.items {
776 ItemKind::Use(..) => {
777 // don't suggest placing a use before the prelude
778 // import or other generated ones
779 if item.span.ctxt().outer_expn_info().is_none() {
780 self.span = Some(item.span.shrink_to_lo());
781 self.found_use = true;
785 // don't place use before extern crate
786 ItemKind::ExternCrate(_) => {}
787 // but place them before the first other item
788 _ => if self.span.map_or(true, |span| item.span < span ) {
789 if item.span.ctxt().outer_expn_info().is_none() {
790 // don't insert between attributes and an item
791 if item.attrs.is_empty() {
792 self.span = Some(item.span.shrink_to_lo());
794 // find the first attribute on the item
795 for attr in &item.attrs {
796 if self.span.map_or(true, |span| attr.span < span) {
797 self.span = Some(attr.span.shrink_to_lo());
808 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
809 impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> {
810 fn visit_item(&mut self, item: &'tcx Item) {
811 self.resolve_item(item);
813 fn visit_arm(&mut self, arm: &'tcx Arm) {
814 self.resolve_arm(arm);
816 fn visit_block(&mut self, block: &'tcx Block) {
817 self.resolve_block(block);
819 fn visit_anon_const(&mut self, constant: &'tcx ast::AnonConst) {
820 debug!("visit_anon_const {:?}", constant);
821 self.with_constant_rib(|this| {
822 visit::walk_anon_const(this, constant);
825 fn visit_expr(&mut self, expr: &'tcx Expr) {
826 self.resolve_expr(expr, None);
828 fn visit_local(&mut self, local: &'tcx Local) {
829 self.resolve_local(local);
831 fn visit_ty(&mut self, ty: &'tcx Ty) {
833 TyKind::Path(ref qself, ref path) => {
834 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
836 TyKind::ImplicitSelf => {
837 let self_ty = Ident::with_empty_ctxt(kw::SelfUpper);
838 let res = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
839 .map_or(Res::Err, |d| d.res());
840 self.record_partial_res(ty.id, PartialRes::new(res));
844 visit::walk_ty(self, ty);
846 fn visit_poly_trait_ref(&mut self,
847 tref: &'tcx ast::PolyTraitRef,
848 m: &'tcx ast::TraitBoundModifier) {
849 self.smart_resolve_path(tref.trait_ref.ref_id, None,
850 &tref.trait_ref.path, PathSource::Trait(AliasPossibility::Maybe));
851 visit::walk_poly_trait_ref(self, tref, m);
853 fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
854 let generic_params = match foreign_item.node {
855 ForeignItemKind::Fn(_, ref generics) => {
856 HasGenericParams(generics, ItemRibKind)
858 ForeignItemKind::Static(..) => NoGenericParams,
859 ForeignItemKind::Ty => NoGenericParams,
860 ForeignItemKind::Macro(..) => NoGenericParams,
862 self.with_generic_param_rib(generic_params, |this| {
863 visit::walk_foreign_item(this, foreign_item);
866 fn visit_fn(&mut self,
867 function_kind: FnKind<'tcx>,
868 declaration: &'tcx FnDecl,
872 debug!("(resolving function) entering function");
873 let rib_kind = match function_kind {
874 FnKind::ItemFn(..) => FnItemRibKind,
875 FnKind::Method(..) => AssocItemRibKind,
876 FnKind::Closure(_) => NormalRibKind,
879 // Create a value rib for the function.
880 self.ribs[ValueNS].push(Rib::new(rib_kind));
882 // Create a label rib for the function.
883 self.label_ribs.push(Rib::new(rib_kind));
885 // Add each argument to the rib.
886 let mut bindings_list = FxHashMap::default();
887 for argument in &declaration.inputs {
888 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
890 self.visit_ty(&argument.ty);
892 debug!("(resolving function) recorded argument");
894 visit::walk_fn_ret_ty(self, &declaration.output);
896 // Resolve the function body, potentially inside the body of an async closure
897 match function_kind {
898 FnKind::ItemFn(.., body) |
899 FnKind::Method(.., body) => {
900 self.visit_block(body);
902 FnKind::Closure(body) => {
903 self.visit_expr(body);
907 debug!("(resolving function) leaving function");
909 self.label_ribs.pop();
910 self.ribs[ValueNS].pop();
913 fn visit_generics(&mut self, generics: &'tcx Generics) {
914 // For type parameter defaults, we have to ban access
915 // to following type parameters, as the InternalSubsts can only
916 // provide previous type parameters as they're built. We
917 // put all the parameters on the ban list and then remove
918 // them one by one as they are processed and become available.
919 let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
920 let mut found_default = false;
921 default_ban_rib.bindings.extend(generics.params.iter()
922 .filter_map(|param| match param.kind {
923 GenericParamKind::Const { .. } |
924 GenericParamKind::Lifetime { .. } => None,
925 GenericParamKind::Type { ref default, .. } => {
926 found_default |= default.is_some();
928 Some((Ident::with_empty_ctxt(param.ident.name), Res::Err))
935 // We also ban access to type parameters for use as the types of const parameters.
936 let mut const_ty_param_ban_rib = Rib::new(TyParamAsConstParamTy);
937 const_ty_param_ban_rib.bindings.extend(generics.params.iter()
939 if let GenericParamKind::Type { .. } = param.kind {
945 .map(|param| (Ident::with_empty_ctxt(param.ident.name), Res::Err)));
947 for param in &generics.params {
949 GenericParamKind::Lifetime { .. } => self.visit_generic_param(param),
950 GenericParamKind::Type { ref default, .. } => {
951 for bound in ¶m.bounds {
952 self.visit_param_bound(bound);
955 if let Some(ref ty) = default {
956 self.ribs[TypeNS].push(default_ban_rib);
958 default_ban_rib = self.ribs[TypeNS].pop().unwrap();
961 // Allow all following defaults to refer to this type parameter.
962 default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(param.ident.name));
964 GenericParamKind::Const { ref ty } => {
965 self.ribs[TypeNS].push(const_ty_param_ban_rib);
967 for bound in ¶m.bounds {
968 self.visit_param_bound(bound);
973 const_ty_param_ban_rib = self.ribs[TypeNS].pop().unwrap();
977 for p in &generics.where_clause.predicates {
978 self.visit_where_predicate(p);
983 #[derive(Copy, Clone)]
984 enum GenericParameters<'a, 'b> {
986 HasGenericParams(// Type parameters.
989 // The kind of the rib used for type parameters.
993 /// The rib kind restricts certain accesses,
994 /// e.g. to a `Res::Local` of an outer item.
995 #[derive(Copy, Clone, Debug)]
997 /// No restriction needs to be applied.
1000 /// We passed through an impl or trait and are now in one of its
1001 /// methods or associated types. Allow references to ty params that impl or trait
1002 /// binds. Disallow any other upvars (including other ty params that are
1006 /// We passed through a function definition. Disallow upvars.
1007 /// Permit only those const parameters that are specified in the function's generics.
1010 /// We passed through an item scope. Disallow upvars.
1013 /// We're in a constant item. Can't refer to dynamic stuff.
1014 ConstantItemRibKind,
1016 /// We passed through a module.
1017 ModuleRibKind(Module<'a>),
1019 /// We passed through a `macro_rules!` statement
1020 MacroDefinition(DefId),
1022 /// All bindings in this rib are type parameters that can't be used
1023 /// from the default of a type parameter because they're not declared
1024 /// before said type parameter. Also see the `visit_generics` override.
1025 ForwardTyParamBanRibKind,
1027 /// We forbid the use of type parameters as the types of const parameters.
1028 TyParamAsConstParamTy,
1031 /// A single local scope.
1033 /// A rib represents a scope names can live in. Note that these appear in many places, not just
1034 /// around braces. At any place where the list of accessible names (of the given namespace)
1035 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
1036 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
1039 /// Different [rib kinds](enum.RibKind) are transparent for different names.
1041 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
1042 /// resolving, the name is looked up from inside out.
1044 struct Rib<'a, R = Res> {
1045 bindings: FxHashMap<Ident, R>,
1049 impl<'a, R> Rib<'a, R> {
1050 fn new(kind: RibKind<'a>) -> Rib<'a, R> {
1052 bindings: Default::default(),
1058 /// An intermediate resolution result.
1060 /// This refers to the thing referred by a name. The difference between `Res` and `Item` is that
1061 /// items are visible in their whole block, while `Res`es only from the place they are defined
1064 enum LexicalScopeBinding<'a> {
1065 Item(&'a NameBinding<'a>),
1069 impl<'a> LexicalScopeBinding<'a> {
1070 fn item(self) -> Option<&'a NameBinding<'a>> {
1072 LexicalScopeBinding::Item(binding) => Some(binding),
1077 fn res(self) -> Res {
1079 LexicalScopeBinding::Item(binding) => binding.res(),
1080 LexicalScopeBinding::Res(res) => res,
1085 #[derive(Copy, Clone, Debug)]
1086 enum ModuleOrUniformRoot<'a> {
1090 /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
1091 CrateRootAndExternPrelude,
1093 /// Virtual module that denotes resolution in extern prelude.
1094 /// Used for paths starting with `::` on 2018 edition.
1097 /// Virtual module that denotes resolution in current scope.
1098 /// Used only for resolving single-segment imports. The reason it exists is that import paths
1099 /// are always split into two parts, the first of which should be some kind of module.
1103 impl ModuleOrUniformRoot<'_> {
1104 fn same_def(lhs: Self, rhs: Self) -> bool {
1106 (ModuleOrUniformRoot::Module(lhs),
1107 ModuleOrUniformRoot::Module(rhs)) => lhs.def_id() == rhs.def_id(),
1108 (ModuleOrUniformRoot::CrateRootAndExternPrelude,
1109 ModuleOrUniformRoot::CrateRootAndExternPrelude) |
1110 (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude) |
1111 (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true,
1117 #[derive(Clone, Debug)]
1118 enum PathResult<'a> {
1119 Module(ModuleOrUniformRoot<'a>),
1120 NonModule(PartialRes),
1125 suggestion: Option<Suggestion>,
1126 is_error_from_last_segment: bool,
1131 /// An anonymous module; e.g., just a block.
1135 /// fn f() {} // (1)
1136 /// { // This is an anonymous module
1137 /// f(); // This resolves to (2) as we are inside the block.
1138 /// fn f() {} // (2)
1140 /// f(); // Resolves to (1)
1144 /// Any module with a name.
1148 /// * A normal module ‒ either `mod from_file;` or `mod from_block { }`.
1149 /// * A trait or an enum (it implicitly contains associated types, methods and variant
1151 Def(DefKind, DefId, Name),
1155 /// Get name of the module.
1156 pub fn name(&self) -> Option<Name> {
1158 ModuleKind::Block(..) => None,
1159 ModuleKind::Def(.., name) => Some(*name),
1164 /// One node in the tree of modules.
1165 pub struct ModuleData<'a> {
1166 parent: Option<Module<'a>>,
1169 // The def id of the closest normal module (`mod`) ancestor (including this module).
1170 normal_ancestor_id: DefId,
1172 resolutions: RefCell<FxHashMap<(Ident, Namespace), &'a RefCell<NameResolution<'a>>>>,
1173 single_segment_macro_resolutions: RefCell<Vec<(Ident, MacroKind, ParentScope<'a>,
1174 Option<&'a NameBinding<'a>>)>>,
1175 multi_segment_macro_resolutions: RefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>,
1177 builtin_attrs: RefCell<Vec<(Ident, ParentScope<'a>)>>,
1179 // Macro invocations that can expand into items in this module.
1180 unresolved_invocations: RefCell<FxHashSet<ExpnId>>,
1182 no_implicit_prelude: bool,
1184 glob_importers: RefCell<Vec<&'a ImportDirective<'a>>>,
1185 globs: RefCell<Vec<&'a ImportDirective<'a>>>,
1187 // Used to memoize the traits in this module for faster searches through all traits in scope.
1188 traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
1190 // Whether this module is populated. If not populated, any attempt to
1191 // access the children must be preceded with a
1192 // `populate_module_if_necessary` call.
1193 populated: Cell<bool>,
1195 /// Span of the module itself. Used for error reporting.
1201 type Module<'a> = &'a ModuleData<'a>;
1203 impl<'a> ModuleData<'a> {
1204 fn new(parent: Option<Module<'a>>,
1206 normal_ancestor_id: DefId,
1208 span: Span) -> Self {
1213 resolutions: Default::default(),
1214 single_segment_macro_resolutions: RefCell::new(Vec::new()),
1215 multi_segment_macro_resolutions: RefCell::new(Vec::new()),
1216 builtin_attrs: RefCell::new(Vec::new()),
1217 unresolved_invocations: Default::default(),
1218 no_implicit_prelude: false,
1219 glob_importers: RefCell::new(Vec::new()),
1220 globs: RefCell::new(Vec::new()),
1221 traits: RefCell::new(None),
1222 populated: Cell::new(normal_ancestor_id.is_local()),
1228 fn for_each_child<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1229 for (&(ident, ns), name_resolution) in self.resolutions.borrow().iter() {
1230 name_resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1234 fn for_each_child_stable<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1235 let resolutions = self.resolutions.borrow();
1236 let mut resolutions = resolutions.iter().collect::<Vec<_>>();
1237 resolutions.sort_by_cached_key(|&(&(ident, ns), _)| (ident.as_str(), ns));
1238 for &(&(ident, ns), &resolution) in resolutions.iter() {
1239 resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1243 fn res(&self) -> Option<Res> {
1245 ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
1250 fn def_kind(&self) -> Option<DefKind> {
1252 ModuleKind::Def(kind, ..) => Some(kind),
1257 fn def_id(&self) -> Option<DefId> {
1259 ModuleKind::Def(_, def_id, _) => Some(def_id),
1264 // `self` resolves to the first module ancestor that `is_normal`.
1265 fn is_normal(&self) -> bool {
1267 ModuleKind::Def(DefKind::Mod, _, _) => true,
1272 fn is_trait(&self) -> bool {
1274 ModuleKind::Def(DefKind::Trait, _, _) => true,
1279 fn nearest_item_scope(&'a self) -> Module<'a> {
1280 if self.is_trait() { self.parent.unwrap() } else { self }
1283 fn is_ancestor_of(&self, mut other: &Self) -> bool {
1284 while !ptr::eq(self, other) {
1285 if let Some(parent) = other.parent {
1295 impl<'a> fmt::Debug for ModuleData<'a> {
1296 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1297 write!(f, "{:?}", self.res())
1301 /// Records a possibly-private value, type, or module definition.
1302 #[derive(Clone, Debug)]
1303 pub struct NameBinding<'a> {
1304 kind: NameBindingKind<'a>,
1305 ambiguity: Option<(&'a NameBinding<'a>, AmbiguityKind)>,
1308 vis: ty::Visibility,
1311 pub trait ToNameBinding<'a> {
1312 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
1315 impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
1316 fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
1321 #[derive(Clone, Debug)]
1322 enum NameBindingKind<'a> {
1323 Res(Res, /* is_macro_export */ bool),
1326 binding: &'a NameBinding<'a>,
1327 directive: &'a ImportDirective<'a>,
1332 impl<'a> NameBindingKind<'a> {
1333 /// Is this a name binding of a import?
1334 fn is_import(&self) -> bool {
1336 NameBindingKind::Import { .. } => true,
1342 struct PrivacyError<'a>(Span, Ident, &'a NameBinding<'a>);
1344 struct UseError<'a> {
1345 err: DiagnosticBuilder<'a>,
1346 /// Attach `use` statements for these candidates.
1347 candidates: Vec<ImportSuggestion>,
1348 /// The `NodeId` of the module to place the use-statements in.
1350 /// Whether the diagnostic should state that it's "better".
1354 #[derive(Clone, Copy, PartialEq, Debug)]
1355 enum AmbiguityKind {
1359 LegacyHelperVsPrelude,
1364 MoreExpandedVsOuter,
1367 impl AmbiguityKind {
1368 fn descr(self) -> &'static str {
1370 AmbiguityKind::Import =>
1371 "name vs any other name during import resolution",
1372 AmbiguityKind::BuiltinAttr =>
1373 "built-in attribute vs any other name",
1374 AmbiguityKind::DeriveHelper =>
1375 "derive helper attribute vs any other name",
1376 AmbiguityKind::LegacyHelperVsPrelude =>
1377 "legacy plugin helper attribute vs name from prelude",
1378 AmbiguityKind::LegacyVsModern =>
1379 "`macro_rules` vs non-`macro_rules` from other module",
1380 AmbiguityKind::GlobVsOuter =>
1381 "glob import vs any other name from outer scope during import/macro resolution",
1382 AmbiguityKind::GlobVsGlob =>
1383 "glob import vs glob import in the same module",
1384 AmbiguityKind::GlobVsExpanded =>
1385 "glob import vs macro-expanded name in the same \
1386 module during import/macro resolution",
1387 AmbiguityKind::MoreExpandedVsOuter =>
1388 "macro-expanded name vs less macro-expanded name \
1389 from outer scope during import/macro resolution",
1394 /// Miscellaneous bits of metadata for better ambiguity error reporting.
1395 #[derive(Clone, Copy, PartialEq)]
1396 enum AmbiguityErrorMisc {
1403 struct AmbiguityError<'a> {
1404 kind: AmbiguityKind,
1406 b1: &'a NameBinding<'a>,
1407 b2: &'a NameBinding<'a>,
1408 misc1: AmbiguityErrorMisc,
1409 misc2: AmbiguityErrorMisc,
1412 impl<'a> NameBinding<'a> {
1413 fn module(&self) -> Option<Module<'a>> {
1415 NameBindingKind::Module(module) => Some(module),
1416 NameBindingKind::Import { binding, .. } => binding.module(),
1421 fn res(&self) -> Res {
1423 NameBindingKind::Res(res, _) => res,
1424 NameBindingKind::Module(module) => module.res().unwrap(),
1425 NameBindingKind::Import { binding, .. } => binding.res(),
1429 fn is_ambiguity(&self) -> bool {
1430 self.ambiguity.is_some() || match self.kind {
1431 NameBindingKind::Import { binding, .. } => binding.is_ambiguity(),
1436 // We sometimes need to treat variants as `pub` for backwards compatibility.
1437 fn pseudo_vis(&self) -> ty::Visibility {
1438 if self.is_variant() && self.res().def_id().is_local() {
1439 ty::Visibility::Public
1445 fn is_variant(&self) -> bool {
1447 NameBindingKind::Res(Res::Def(DefKind::Variant, _), _) |
1448 NameBindingKind::Res(Res::Def(DefKind::Ctor(CtorOf::Variant, ..), _), _) => true,
1453 fn is_extern_crate(&self) -> bool {
1455 NameBindingKind::Import {
1456 directive: &ImportDirective {
1457 subclass: ImportDirectiveSubclass::ExternCrate { .. }, ..
1460 NameBindingKind::Module(
1461 &ModuleData { kind: ModuleKind::Def(DefKind::Mod, def_id, _), .. }
1462 ) => def_id.index == CRATE_DEF_INDEX,
1467 fn is_import(&self) -> bool {
1469 NameBindingKind::Import { .. } => true,
1474 fn is_glob_import(&self) -> bool {
1476 NameBindingKind::Import { directive, .. } => directive.is_glob(),
1481 fn is_importable(&self) -> bool {
1483 Res::Def(DefKind::AssocConst, _)
1484 | Res::Def(DefKind::Method, _)
1485 | Res::Def(DefKind::AssocTy, _) => false,
1490 fn is_macro_def(&self) -> bool {
1492 NameBindingKind::Res(Res::Def(DefKind::Macro(..), _), _) => true,
1497 fn macro_kind(&self) -> Option<MacroKind> {
1498 self.res().macro_kind()
1501 fn descr(&self) -> &'static str {
1502 if self.is_extern_crate() { "extern crate" } else { self.res().descr() }
1505 fn article(&self) -> &'static str {
1506 if self.is_extern_crate() { "an" } else { self.res().article() }
1509 // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
1510 // at some expansion round `max(invoc, binding)` when they both emerged from macros.
1511 // Then this function returns `true` if `self` may emerge from a macro *after* that
1512 // in some later round and screw up our previously found resolution.
1513 // See more detailed explanation in
1514 // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
1515 fn may_appear_after(&self, invoc_parent_expansion: ExpnId, binding: &NameBinding<'_>) -> bool {
1516 // self > max(invoc, binding) => !(self <= invoc || self <= binding)
1517 // Expansions are partially ordered, so "may appear after" is an inversion of
1518 // "certainly appears before or simultaneously" and includes unordered cases.
1519 let self_parent_expansion = self.expansion;
1520 let other_parent_expansion = binding.expansion;
1521 let certainly_before_other_or_simultaneously =
1522 other_parent_expansion.is_descendant_of(self_parent_expansion);
1523 let certainly_before_invoc_or_simultaneously =
1524 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1525 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1529 /// Interns the names of the primitive types.
1531 /// All other types are defined somewhere and possibly imported, but the primitive ones need
1532 /// special handling, since they have no place of origin.
1533 struct PrimitiveTypeTable {
1534 primitive_types: FxHashMap<Name, PrimTy>,
1537 impl PrimitiveTypeTable {
1538 fn new() -> PrimitiveTypeTable {
1539 let mut table = FxHashMap::default();
1541 table.insert(sym::bool, Bool);
1542 table.insert(sym::char, Char);
1543 table.insert(sym::f32, Float(FloatTy::F32));
1544 table.insert(sym::f64, Float(FloatTy::F64));
1545 table.insert(sym::isize, Int(IntTy::Isize));
1546 table.insert(sym::i8, Int(IntTy::I8));
1547 table.insert(sym::i16, Int(IntTy::I16));
1548 table.insert(sym::i32, Int(IntTy::I32));
1549 table.insert(sym::i64, Int(IntTy::I64));
1550 table.insert(sym::i128, Int(IntTy::I128));
1551 table.insert(sym::str, Str);
1552 table.insert(sym::usize, Uint(UintTy::Usize));
1553 table.insert(sym::u8, Uint(UintTy::U8));
1554 table.insert(sym::u16, Uint(UintTy::U16));
1555 table.insert(sym::u32, Uint(UintTy::U32));
1556 table.insert(sym::u64, Uint(UintTy::U64));
1557 table.insert(sym::u128, Uint(UintTy::U128));
1558 Self { primitive_types: table }
1562 #[derive(Debug, Default, Clone)]
1563 pub struct ExternPreludeEntry<'a> {
1564 extern_crate_item: Option<&'a NameBinding<'a>>,
1565 pub introduced_by_item: bool,
1568 /// The main resolver class.
1570 /// This is the visitor that walks the whole crate.
1571 pub struct Resolver<'a> {
1572 session: &'a Session,
1575 pub definitions: Definitions,
1577 graph_root: Module<'a>,
1579 prelude: Option<Module<'a>>,
1580 pub extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
1582 /// N.B., this is used only for better diagnostics, not name resolution itself.
1583 has_self: FxHashSet<DefId>,
1585 /// Names of fields of an item `DefId` accessible with dot syntax.
1586 /// Used for hints during error reporting.
1587 field_names: FxHashMap<DefId, Vec<Name>>,
1589 /// All imports known to succeed or fail.
1590 determined_imports: Vec<&'a ImportDirective<'a>>,
1592 /// All non-determined imports.
1593 indeterminate_imports: Vec<&'a ImportDirective<'a>>,
1595 /// The module that represents the current item scope.
1596 current_module: Module<'a>,
1598 /// The current set of local scopes for types and values.
1599 /// FIXME #4948: Reuse ribs to avoid allocation.
1600 ribs: PerNS<Vec<Rib<'a>>>,
1602 /// The current set of local scopes, for labels.
1603 label_ribs: Vec<Rib<'a, NodeId>>,
1605 /// The trait that the current context can refer to.
1606 current_trait_ref: Option<(Module<'a>, TraitRef)>,
1608 /// The current trait's associated types' ident, used for diagnostic suggestions.
1609 current_trait_assoc_types: Vec<Ident>,
1611 /// The current self type if inside an impl (used for better errors).
1612 current_self_type: Option<Ty>,
1614 /// The current self item if inside an ADT (used for better errors).
1615 current_self_item: Option<NodeId>,
1617 /// FIXME: Refactor things so that these fields are passed through arguments and not resolver.
1618 /// We are resolving a last import segment during import validation.
1619 last_import_segment: bool,
1620 /// This binding should be ignored during in-module resolution, so that we don't get
1621 /// "self-confirming" import resolutions during import validation.
1622 blacklisted_binding: Option<&'a NameBinding<'a>>,
1624 /// The idents for the primitive types.
1625 primitive_type_table: PrimitiveTypeTable,
1627 /// Resolutions for nodes that have a single resolution.
1628 partial_res_map: NodeMap<PartialRes>,
1629 /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
1630 import_res_map: NodeMap<PerNS<Option<Res>>>,
1631 /// Resolutions for labels (node IDs of their corresponding blocks or loops).
1632 label_res_map: NodeMap<NodeId>,
1634 pub export_map: ExportMap<NodeId>,
1635 pub trait_map: TraitMap,
1637 /// A map from nodes to anonymous modules.
1638 /// Anonymous modules are pseudo-modules that are implicitly created around items
1639 /// contained within blocks.
1641 /// For example, if we have this:
1649 /// There will be an anonymous module created around `g` with the ID of the
1650 /// entry block for `f`.
1651 block_map: NodeMap<Module<'a>>,
1652 module_map: FxHashMap<DefId, Module<'a>>,
1653 extern_module_map: FxHashMap<(DefId, bool /* MacrosOnly? */), Module<'a>>,
1654 binding_parent_modules: FxHashMap<PtrKey<'a, NameBinding<'a>>, Module<'a>>,
1656 /// Maps glob imports to the names of items actually imported.
1657 pub glob_map: GlobMap,
1659 used_imports: FxHashSet<(NodeId, Namespace)>,
1660 pub maybe_unused_trait_imports: NodeSet,
1661 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
1663 /// A list of labels as of yet unused. Labels will be removed from this map when
1664 /// they are used (in a `break` or `continue` statement)
1665 pub unused_labels: FxHashMap<NodeId, Span>,
1667 /// Privacy errors are delayed until the end in order to deduplicate them.
1668 privacy_errors: Vec<PrivacyError<'a>>,
1669 /// Ambiguity errors are delayed for deduplication.
1670 ambiguity_errors: Vec<AmbiguityError<'a>>,
1671 /// `use` injections are delayed for better placement and deduplication.
1672 use_injections: Vec<UseError<'a>>,
1673 /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
1674 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
1676 arenas: &'a ResolverArenas<'a>,
1677 dummy_binding: &'a NameBinding<'a>,
1679 crate_loader: &'a mut CrateLoader<'a>,
1680 macro_names: FxHashSet<Ident>,
1681 builtin_macros: FxHashMap<Name, SyntaxExtension>,
1682 macro_use_prelude: FxHashMap<Name, &'a NameBinding<'a>>,
1683 pub all_macros: FxHashMap<Name, Res>,
1684 macro_map: FxHashMap<DefId, Lrc<SyntaxExtension>>,
1685 dummy_ext_bang: Lrc<SyntaxExtension>,
1686 dummy_ext_derive: Lrc<SyntaxExtension>,
1687 non_macro_attrs: [Lrc<SyntaxExtension>; 2],
1688 macro_defs: FxHashMap<ExpnId, DefId>,
1689 local_macro_def_scopes: FxHashMap<NodeId, Module<'a>>,
1690 unused_macros: NodeMap<Span>,
1691 proc_macro_stubs: NodeSet,
1693 /// Maps the `ExpnId` of an expansion to its containing module or block.
1694 invocations: FxHashMap<ExpnId, &'a InvocationData<'a>>,
1696 /// Avoid duplicated errors for "name already defined".
1697 name_already_seen: FxHashMap<Name, Span>,
1699 potentially_unused_imports: Vec<&'a ImportDirective<'a>>,
1701 /// Table for mapping struct IDs into struct constructor IDs,
1702 /// it's not used during normal resolution, only for better error reporting.
1703 struct_constructors: DefIdMap<(Res, ty::Visibility)>,
1705 /// Only used for better errors on `fn(): fn()`.
1706 current_type_ascription: Vec<Span>,
1708 injected_crate: Option<Module<'a>>,
1710 /// Features enabled for this crate.
1711 active_features: FxHashSet<Symbol>,
1714 /// Nothing really interesting here; it just provides memory for the rest of the crate.
1716 pub struct ResolverArenas<'a> {
1717 modules: arena::TypedArena<ModuleData<'a>>,
1718 local_modules: RefCell<Vec<Module<'a>>>,
1719 name_bindings: arena::TypedArena<NameBinding<'a>>,
1720 import_directives: arena::TypedArena<ImportDirective<'a>>,
1721 name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1722 invocation_data: arena::TypedArena<InvocationData<'a>>,
1723 legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
1726 impl<'a> ResolverArenas<'a> {
1727 fn alloc_module(&'a self, module: ModuleData<'a>) -> Module<'a> {
1728 let module = self.modules.alloc(module);
1729 if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) {
1730 self.local_modules.borrow_mut().push(module);
1734 fn local_modules(&'a self) -> std::cell::Ref<'a, Vec<Module<'a>>> {
1735 self.local_modules.borrow()
1737 fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1738 self.name_bindings.alloc(name_binding)
1740 fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
1741 -> &'a ImportDirective<'_> {
1742 self.import_directives.alloc(import_directive)
1744 fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1745 self.name_resolutions.alloc(Default::default())
1747 fn alloc_invocation_data(&'a self, expansion_data: InvocationData<'a>)
1748 -> &'a InvocationData<'a> {
1749 self.invocation_data.alloc(expansion_data)
1751 fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
1752 self.legacy_bindings.alloc(binding)
1756 impl<'a, 'b> ty::DefIdTree for &'a Resolver<'b> {
1757 fn parent(self, id: DefId) -> Option<DefId> {
1759 LOCAL_CRATE => self.definitions.def_key(id.index).parent,
1760 _ => self.cstore.def_key(id).parent,
1761 }.map(|index| DefId { index, ..id })
1765 /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that
1766 /// the resolver is no longer needed as all the relevant information is inline.
1767 impl<'a> hir::lowering::Resolver for Resolver<'a> {
1768 fn resolve_ast_path(
1773 self.resolve_ast_path_cb(path, is_value,
1774 |resolver, span, error| resolve_error(resolver, span, error))
1777 fn resolve_str_path(
1780 crate_root: Option<Symbol>,
1781 components: &[Symbol],
1783 ) -> (ast::Path, Res) {
1784 let root = if crate_root.is_some() {
1789 let segments = iter::once(Ident::with_empty_ctxt(root))
1791 crate_root.into_iter()
1792 .chain(components.iter().cloned())
1793 .map(Ident::with_empty_ctxt)
1794 ).map(|i| self.new_ast_path_segment(i)).collect::<Vec<_>>();
1796 let path = ast::Path {
1801 let res = self.resolve_ast_path(&path, is_value);
1805 fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes> {
1806 self.partial_res_map.get(&id).cloned()
1809 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res>> {
1810 self.import_res_map.get(&id).cloned().unwrap_or_default()
1813 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId> {
1814 self.label_res_map.get(&id).cloned()
1817 fn definitions(&mut self) -> &mut Definitions {
1818 &mut self.definitions
1822 impl<'a> Resolver<'a> {
1823 /// Rustdoc uses this to resolve things in a recoverable way. `ResolutionError<'a>`
1824 /// isn't something that can be returned because it can't be made to live that long,
1825 /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1826 /// just that an error occurred.
1827 pub fn resolve_str_path_error(&mut self, span: Span, path_str: &str, is_value: bool)
1828 -> Result<(ast::Path, Res), ()> {
1829 let mut errored = false;
1831 let path = if path_str.starts_with("::") {
1834 segments: iter::once(Ident::with_empty_ctxt(kw::PathRoot))
1836 path_str.split("::").skip(1).map(Ident::from_str)
1838 .map(|i| self.new_ast_path_segment(i))
1846 .map(Ident::from_str)
1847 .map(|i| self.new_ast_path_segment(i))
1851 let res = self.resolve_ast_path_cb(&path, is_value, |_, _, _| errored = true);
1852 if errored || res == def::Res::Err {
1859 /// Like `resolve_ast_path`, but takes a callback in case there was an error.
1860 // FIXME(eddyb) use `Result` or something instead of callbacks.
1861 fn resolve_ast_path_cb<F>(
1867 where F: for<'c, 'b> FnOnce(&'c mut Resolver<'_>, Span, ResolutionError<'b>)
1869 let namespace = if is_value { ValueNS } else { TypeNS };
1870 let span = path.span;
1871 let path = Segment::from_path(&path);
1872 // FIXME(Manishearth): intra-doc links won't get warned of epoch changes.
1873 match self.resolve_path_without_parent_scope(&path, Some(namespace), true,
1874 span, CrateLint::No) {
1875 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1876 module.res().unwrap(),
1877 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 =>
1878 path_res.base_res(),
1879 PathResult::NonModule(..) => {
1880 error_callback(self, span, ResolutionError::FailedToResolve {
1881 label: String::from("type-relative paths are not supported in this context"),
1886 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
1887 PathResult::Failed { span, label, suggestion, .. } => {
1888 error_callback(self, span, ResolutionError::FailedToResolve {
1897 fn new_ast_path_segment(&self, ident: Ident) -> ast::PathSegment {
1898 let mut seg = ast::PathSegment::from_ident(ident);
1899 seg.id = self.session.next_node_id();
1904 impl<'a> Resolver<'a> {
1905 pub fn new(session: &'a Session,
1909 crate_loader: &'a mut CrateLoader<'a>,
1910 arenas: &'a ResolverArenas<'a>)
1912 let root_def_id = DefId::local(CRATE_DEF_INDEX);
1913 let root_module_kind = ModuleKind::Def(
1918 let graph_root = arenas.alloc_module(ModuleData {
1919 no_implicit_prelude: attr::contains_name(&krate.attrs, sym::no_implicit_prelude),
1920 ..ModuleData::new(None, root_module_kind, root_def_id, ExpnId::root(), krate.span)
1922 let mut module_map = FxHashMap::default();
1923 module_map.insert(DefId::local(CRATE_DEF_INDEX), graph_root);
1925 let mut definitions = Definitions::default();
1926 definitions.create_root_def(crate_name, session.local_crate_disambiguator());
1928 let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'_>> =
1929 session.opts.externs.iter().map(|kv| (Ident::from_str(kv.0), Default::default()))
1932 if !attr::contains_name(&krate.attrs, sym::no_core) {
1933 extern_prelude.insert(Ident::with_empty_ctxt(sym::core), Default::default());
1934 if !attr::contains_name(&krate.attrs, sym::no_std) {
1935 extern_prelude.insert(Ident::with_empty_ctxt(sym::std), Default::default());
1936 if session.rust_2018() {
1937 extern_prelude.insert(Ident::with_empty_ctxt(sym::meta), Default::default());
1942 let mut invocations = FxHashMap::default();
1943 invocations.insert(ExpnId::root(),
1944 arenas.alloc_invocation_data(InvocationData::root(graph_root)));
1946 let mut macro_defs = FxHashMap::default();
1947 macro_defs.insert(ExpnId::root(), root_def_id);
1949 let features = session.features_untracked();
1950 let non_macro_attr =
1951 |mark_used| Lrc::new(SyntaxExtension::non_macro_attr(mark_used, session.edition()));
1960 // The outermost module has def ID 0; this is not reflected in the
1966 has_self: FxHashSet::default(),
1967 field_names: FxHashMap::default(),
1969 determined_imports: Vec::new(),
1970 indeterminate_imports: Vec::new(),
1972 current_module: graph_root,
1974 value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1975 type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1976 macro_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1978 label_ribs: Vec::new(),
1980 current_trait_ref: None,
1981 current_trait_assoc_types: Vec::new(),
1982 current_self_type: None,
1983 current_self_item: None,
1984 last_import_segment: false,
1985 blacklisted_binding: None,
1987 primitive_type_table: PrimitiveTypeTable::new(),
1989 partial_res_map: Default::default(),
1990 import_res_map: Default::default(),
1991 label_res_map: Default::default(),
1992 export_map: FxHashMap::default(),
1993 trait_map: Default::default(),
1995 block_map: Default::default(),
1996 extern_module_map: FxHashMap::default(),
1997 binding_parent_modules: FxHashMap::default(),
1999 glob_map: Default::default(),
2001 used_imports: FxHashSet::default(),
2002 maybe_unused_trait_imports: Default::default(),
2003 maybe_unused_extern_crates: Vec::new(),
2005 unused_labels: FxHashMap::default(),
2007 privacy_errors: Vec::new(),
2008 ambiguity_errors: Vec::new(),
2009 use_injections: Vec::new(),
2010 macro_expanded_macro_export_errors: BTreeSet::new(),
2013 dummy_binding: arenas.alloc_name_binding(NameBinding {
2014 kind: NameBindingKind::Res(Res::Err, false),
2016 expansion: ExpnId::root(),
2018 vis: ty::Visibility::Public,
2022 macro_names: FxHashSet::default(),
2023 builtin_macros: Default::default(),
2024 macro_use_prelude: FxHashMap::default(),
2025 all_macros: FxHashMap::default(),
2026 macro_map: FxHashMap::default(),
2027 dummy_ext_bang: Lrc::new(SyntaxExtension::dummy_bang(session.edition())),
2028 dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(session.edition())),
2029 non_macro_attrs: [non_macro_attr(false), non_macro_attr(true)],
2032 local_macro_def_scopes: FxHashMap::default(),
2033 name_already_seen: FxHashMap::default(),
2034 potentially_unused_imports: Vec::new(),
2035 struct_constructors: Default::default(),
2036 unused_macros: Default::default(),
2037 proc_macro_stubs: Default::default(),
2038 current_type_ascription: Vec::new(),
2039 injected_crate: None,
2041 features.declared_lib_features.iter().map(|(feat, ..)| *feat)
2042 .chain(features.declared_lang_features.iter().map(|(feat, ..)| *feat))
2047 pub fn arenas() -> ResolverArenas<'a> {
2051 fn non_macro_attr(&self, mark_used: bool) -> Lrc<SyntaxExtension> {
2052 self.non_macro_attrs[mark_used as usize].clone()
2055 fn dummy_ext(&self, macro_kind: MacroKind) -> Lrc<SyntaxExtension> {
2057 MacroKind::Bang => self.dummy_ext_bang.clone(),
2058 MacroKind::Derive => self.dummy_ext_derive.clone(),
2059 MacroKind::Attr => self.non_macro_attr(true),
2063 /// Runs the function on each namespace.
2064 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
2070 fn is_builtin_macro(&mut self, def_id: Option<DefId>) -> bool {
2071 def_id.and_then(|def_id| self.get_macro_by_def_id(def_id))
2072 .map_or(false, |ext| ext.is_builtin)
2075 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
2077 match self.macro_defs.get(&ctxt.outer_expn()) {
2078 Some(&def_id) => return def_id,
2079 None => ctxt.remove_mark(),
2084 /// Entry point to crate resolution.
2085 pub fn resolve_crate(&mut self, krate: &Crate) {
2086 ImportResolver { resolver: self }.finalize_imports();
2087 self.current_module = self.graph_root;
2088 self.finalize_current_module_macro_resolutions();
2090 visit::walk_crate(self, krate);
2092 check_unused::check_crate(self, krate);
2093 self.report_errors(krate);
2094 self.crate_loader.postprocess(krate);
2101 normal_ancestor_id: DefId,
2105 let module = ModuleData::new(Some(parent), kind, normal_ancestor_id, expn_id, span);
2106 self.arenas.alloc_module(module)
2109 fn record_use(&mut self, ident: Ident, ns: Namespace,
2110 used_binding: &'a NameBinding<'a>, is_lexical_scope: bool) {
2111 if let Some((b2, kind)) = used_binding.ambiguity {
2112 self.ambiguity_errors.push(AmbiguityError {
2113 kind, ident, b1: used_binding, b2,
2114 misc1: AmbiguityErrorMisc::None,
2115 misc2: AmbiguityErrorMisc::None,
2118 if let NameBindingKind::Import { directive, binding, ref used } = used_binding.kind {
2119 // Avoid marking `extern crate` items that refer to a name from extern prelude,
2120 // but not introduce it, as used if they are accessed from lexical scope.
2121 if is_lexical_scope {
2122 if let Some(entry) = self.extern_prelude.get(&ident.modern()) {
2123 if let Some(crate_item) = entry.extern_crate_item {
2124 if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
2131 directive.used.set(true);
2132 self.used_imports.insert((directive.id, ns));
2133 self.add_to_glob_map(&directive, ident);
2134 self.record_use(ident, ns, binding, false);
2139 fn add_to_glob_map(&mut self, directive: &ImportDirective<'_>, ident: Ident) {
2140 if directive.is_glob() {
2141 self.glob_map.entry(directive.id).or_default().insert(ident.name);
2145 /// A generic scope visitor.
2146 /// Visits scopes in order to resolve some identifier in them or perform other actions.
2147 /// If the callback returns `Some` result, we stop visiting scopes and return it.
2150 scope_set: ScopeSet,
2151 parent_scope: &ParentScope<'a>,
2153 mut visitor: impl FnMut(&mut Self, Scope<'a>, /*use_prelude*/ bool, Ident) -> Option<T>,
2155 // General principles:
2156 // 1. Not controlled (user-defined) names should have higher priority than controlled names
2157 // built into the language or standard library. This way we can add new names into the
2158 // language or standard library without breaking user code.
2159 // 2. "Closed set" below means new names cannot appear after the current resolution attempt.
2160 // Places to search (in order of decreasing priority):
2162 // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
2163 // (open set, not controlled).
2164 // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
2165 // (open, not controlled).
2166 // 3. Extern prelude (open, the open part is from macro expansions, not controlled).
2167 // 4. Tool modules (closed, controlled right now, but not in the future).
2168 // 5. Standard library prelude (de-facto closed, controlled).
2169 // 6. Language prelude (closed, controlled).
2171 // 1. FIXME: Ribs (local variables), there's no necessary infrastructure yet
2172 // (open set, not controlled).
2173 // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
2174 // (open, not controlled).
2175 // 3. Standard library prelude (de-facto closed, controlled).
2177 // 1-3. Derive helpers (open, not controlled). All ambiguities with other names
2178 // are currently reported as errors. They should be higher in priority than preludes
2179 // and probably even names in modules according to the "general principles" above. They
2180 // also should be subject to restricted shadowing because are effectively produced by
2181 // derives (you need to resolve the derive first to add helpers into scope), but they
2182 // should be available before the derive is expanded for compatibility.
2183 // It's mess in general, so we are being conservative for now.
2184 // 1-3. `macro_rules` (open, not controlled), loop through legacy scopes. Have higher
2185 // priority than prelude macros, but create ambiguities with macros in modules.
2186 // 1-3. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
2187 // (open, not controlled). Have higher priority than prelude macros, but create
2188 // ambiguities with `macro_rules`.
2189 // 4. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
2190 // 4a. User-defined prelude from macro-use
2191 // (open, the open part is from macro expansions, not controlled).
2192 // 4b. "Standard library prelude" part implemented through `macro-use` (closed, controlled).
2193 // 4c. Standard library prelude (de-facto closed, controlled).
2194 // 6. Language prelude: builtin attributes (closed, controlled).
2195 // 4-6. Legacy plugin helpers (open, not controlled). Similar to derive helpers,
2196 // but introduced by legacy plugins using `register_attribute`. Priority is somewhere
2197 // in prelude, not sure where exactly (creates ambiguities with any other prelude names).
2199 let rust_2015 = ident.span.rust_2015();
2200 let (ns, is_absolute_path) = match scope_set {
2201 ScopeSet::Import(ns) => (ns, false),
2202 ScopeSet::AbsolutePath(ns) => (ns, true),
2203 ScopeSet::Macro(_) => (MacroNS, false),
2204 ScopeSet::Module => (TypeNS, false),
2206 let mut scope = match ns {
2207 _ if is_absolute_path => Scope::CrateRoot,
2208 TypeNS | ValueNS => Scope::Module(parent_scope.module),
2209 MacroNS => Scope::DeriveHelpers,
2211 let mut ident = ident.modern();
2212 let mut use_prelude = !parent_scope.module.no_implicit_prelude;
2215 let visit = match scope {
2216 Scope::DeriveHelpers => true,
2217 Scope::MacroRules(..) => true,
2218 Scope::CrateRoot => true,
2219 Scope::Module(..) => true,
2220 Scope::MacroUsePrelude => use_prelude || rust_2015,
2221 Scope::BuiltinAttrs => true,
2222 Scope::LegacyPluginHelpers => use_prelude || rust_2015,
2223 Scope::ExternPrelude => use_prelude || is_absolute_path,
2224 Scope::ToolPrelude => use_prelude,
2225 Scope::StdLibPrelude => use_prelude || ns == MacroNS,
2226 Scope::BuiltinTypes => true,
2230 if let break_result @ Some(..) = visitor(self, scope, use_prelude, ident) {
2231 return break_result;
2235 scope = match scope {
2236 Scope::DeriveHelpers =>
2237 Scope::MacroRules(parent_scope.legacy),
2238 Scope::MacroRules(legacy_scope) => match legacy_scope {
2239 LegacyScope::Binding(binding) => Scope::MacroRules(
2240 binding.parent_legacy_scope
2242 LegacyScope::Invocation(invoc) => Scope::MacroRules(
2243 invoc.output_legacy_scope.get().unwrap_or(invoc.parent_legacy_scope)
2245 LegacyScope::Empty => Scope::Module(parent_scope.module),
2247 Scope::CrateRoot => match ns {
2249 ident.span.adjust(ExpnId::root());
2250 Scope::ExternPrelude
2252 ValueNS | MacroNS => break,
2254 Scope::Module(module) => {
2255 use_prelude = !module.no_implicit_prelude;
2256 match self.hygienic_lexical_parent(module, &mut ident.span) {
2257 Some(parent_module) => Scope::Module(parent_module),
2259 ident.span.adjust(ExpnId::root());
2261 TypeNS => Scope::ExternPrelude,
2262 ValueNS => Scope::StdLibPrelude,
2263 MacroNS => Scope::MacroUsePrelude,
2268 Scope::MacroUsePrelude => Scope::StdLibPrelude,
2269 Scope::BuiltinAttrs => Scope::LegacyPluginHelpers,
2270 Scope::LegacyPluginHelpers => break, // nowhere else to search
2271 Scope::ExternPrelude if is_absolute_path => break,
2272 Scope::ExternPrelude => Scope::ToolPrelude,
2273 Scope::ToolPrelude => Scope::StdLibPrelude,
2274 Scope::StdLibPrelude => match ns {
2275 TypeNS => Scope::BuiltinTypes,
2276 ValueNS => break, // nowhere else to search
2277 MacroNS => Scope::BuiltinAttrs,
2279 Scope::BuiltinTypes => break, // nowhere else to search
2286 /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
2287 /// More specifically, we proceed up the hierarchy of scopes and return the binding for
2288 /// `ident` in the first scope that defines it (or None if no scopes define it).
2290 /// A block's items are above its local variables in the scope hierarchy, regardless of where
2291 /// the items are defined in the block. For example,
2294 /// g(); // Since there are no local variables in scope yet, this resolves to the item.
2297 /// g(); // This resolves to the local variable `g` since it shadows the item.
2301 /// Invariant: This must only be called during main resolution, not during
2302 /// import resolution.
2303 fn resolve_ident_in_lexical_scope(&mut self,
2306 record_used_id: Option<NodeId>,
2308 -> Option<LexicalScopeBinding<'a>> {
2309 assert!(ns == TypeNS || ns == ValueNS);
2310 if ident.name == kw::Invalid {
2311 return Some(LexicalScopeBinding::Res(Res::Err));
2313 ident.span = if ident.name == kw::SelfUpper {
2314 // FIXME(jseyfried) improve `Self` hygiene
2315 ident.span.with_ctxt(SyntaxContext::empty())
2316 } else if ns == TypeNS {
2319 ident.span.modern_and_legacy()
2322 // Walk backwards up the ribs in scope.
2323 let record_used = record_used_id.is_some();
2324 let mut module = self.graph_root;
2325 for i in (0 .. self.ribs[ns].len()).rev() {
2326 debug!("walk rib\n{:?}", self.ribs[ns][i].bindings);
2327 if let Some(res) = self.ribs[ns][i].bindings.get(&ident).cloned() {
2328 // The ident resolves to a type parameter or local variable.
2329 return Some(LexicalScopeBinding::Res(
2330 self.validate_res_from_ribs(ns, i, res, record_used, path_span),
2334 module = match self.ribs[ns][i].kind {
2335 ModuleRibKind(module) => module,
2336 MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => {
2337 // If an invocation of this macro created `ident`, give up on `ident`
2338 // and switch to `ident`'s source from the macro definition.
2339 ident.span.remove_mark();
2345 let item = self.resolve_ident_in_module_unadjusted(
2346 ModuleOrUniformRoot::Module(module),
2352 if let Ok(binding) = item {
2353 // The ident resolves to an item.
2354 return Some(LexicalScopeBinding::Item(binding));
2358 ModuleKind::Block(..) => {}, // We can see through blocks
2363 ident.span = ident.span.modern();
2364 let mut poisoned = None;
2366 let opt_module = if let Some(node_id) = record_used_id {
2367 self.hygienic_lexical_parent_with_compatibility_fallback(module, &mut ident.span,
2368 node_id, &mut poisoned)
2370 self.hygienic_lexical_parent(module, &mut ident.span)
2372 module = unwrap_or!(opt_module, break);
2373 let orig_current_module = self.current_module;
2374 self.current_module = module; // Lexical resolutions can never be a privacy error.
2375 let result = self.resolve_ident_in_module_unadjusted(
2376 ModuleOrUniformRoot::Module(module),
2382 self.current_module = orig_current_module;
2386 if let Some(node_id) = poisoned {
2387 self.session.buffer_lint_with_diagnostic(
2388 lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
2389 node_id, ident.span,
2390 &format!("cannot find {} `{}` in this scope", ns.descr(), ident),
2391 lint::builtin::BuiltinLintDiagnostics::
2392 ProcMacroDeriveResolutionFallback(ident.span),
2395 return Some(LexicalScopeBinding::Item(binding))
2397 Err(Determined) => continue,
2398 Err(Undetermined) =>
2399 span_bug!(ident.span, "undetermined resolution during main resolution pass"),
2403 if !module.no_implicit_prelude {
2404 ident.span.adjust(ExpnId::root());
2406 if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
2407 return Some(LexicalScopeBinding::Item(binding));
2410 if ns == TypeNS && KNOWN_TOOLS.contains(&ident.name) {
2411 let binding = (Res::ToolMod, ty::Visibility::Public,
2412 DUMMY_SP, ExpnId::root()).to_name_binding(self.arenas);
2413 return Some(LexicalScopeBinding::Item(binding));
2415 if let Some(prelude) = self.prelude {
2416 if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
2417 ModuleOrUniformRoot::Module(prelude),
2423 return Some(LexicalScopeBinding::Item(binding));
2431 fn hygienic_lexical_parent(&mut self, module: Module<'a>, span: &mut Span)
2432 -> Option<Module<'a>> {
2433 if !module.expansion.outer_expn_is_descendant_of(span.ctxt()) {
2434 return Some(self.macro_def_scope(span.remove_mark()));
2437 if let ModuleKind::Block(..) = module.kind {
2438 return Some(module.parent.unwrap());
2444 fn hygienic_lexical_parent_with_compatibility_fallback(&mut self, module: Module<'a>,
2445 span: &mut Span, node_id: NodeId,
2446 poisoned: &mut Option<NodeId>)
2447 -> Option<Module<'a>> {
2448 if let module @ Some(..) = self.hygienic_lexical_parent(module, span) {
2452 // We need to support the next case under a deprecation warning
2455 // ---- begin: this comes from a proc macro derive
2456 // mod implementation_details {
2457 // // Note that `MyStruct` is not in scope here.
2458 // impl SomeTrait for MyStruct { ... }
2462 // So we have to fall back to the module's parent during lexical resolution in this case.
2463 if let Some(parent) = module.parent {
2464 // Inner module is inside the macro, parent module is outside of the macro.
2465 if module.expansion != parent.expansion &&
2466 module.expansion.is_descendant_of(parent.expansion) {
2467 // The macro is a proc macro derive
2468 if module.expansion.looks_like_proc_macro_derive() {
2469 if parent.expansion.outer_expn_is_descendant_of(span.ctxt()) {
2470 *poisoned = Some(node_id);
2471 return module.parent;
2480 fn resolve_ident_in_module(
2482 module: ModuleOrUniformRoot<'a>,
2485 parent_scope: Option<&ParentScope<'a>>,
2488 ) -> Result<&'a NameBinding<'a>, Determinacy> {
2489 self.resolve_ident_in_module_ext(
2490 module, ident, ns, parent_scope, record_used, path_span
2491 ).map_err(|(determinacy, _)| determinacy)
2494 fn resolve_ident_in_module_ext(
2496 module: ModuleOrUniformRoot<'a>,
2499 parent_scope: Option<&ParentScope<'a>>,
2502 ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
2503 let orig_current_module = self.current_module;
2505 ModuleOrUniformRoot::Module(module) => {
2506 if let Some(def) = ident.span.modernize_and_adjust(module.expansion) {
2507 self.current_module = self.macro_def_scope(def);
2510 ModuleOrUniformRoot::ExternPrelude => {
2511 ident.span.modernize_and_adjust(ExpnId::root());
2513 ModuleOrUniformRoot::CrateRootAndExternPrelude |
2514 ModuleOrUniformRoot::CurrentScope => {
2518 let result = self.resolve_ident_in_module_unadjusted_ext(
2519 module, ident, ns, parent_scope, false, record_used, path_span,
2521 self.current_module = orig_current_module;
2525 fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> {
2526 let mut ctxt = ident.span.ctxt();
2527 let mark = if ident.name == kw::DollarCrate {
2528 // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
2529 // we don't want to pretend that the `macro_rules!` definition is in the `macro`
2530 // as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks.
2531 // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
2532 // definitions actually produced by `macro` and `macro` definitions produced by
2533 // `macro_rules!`, but at least such configurations are not stable yet.
2534 ctxt = ctxt.modern_and_legacy();
2535 let mut iter = ctxt.marks().into_iter().rev().peekable();
2536 let mut result = None;
2537 // Find the last modern mark from the end if it exists.
2538 while let Some(&(mark, transparency)) = iter.peek() {
2539 if transparency == Transparency::Opaque {
2540 result = Some(mark);
2546 // Then find the last legacy mark from the end if it exists.
2547 for (mark, transparency) in iter {
2548 if transparency == Transparency::SemiTransparent {
2549 result = Some(mark);
2556 ctxt = ctxt.modern();
2557 ctxt.adjust(ExpnId::root())
2559 let module = match mark {
2560 Some(def) => self.macro_def_scope(def),
2561 None => return self.graph_root,
2563 self.get_module(DefId { index: CRATE_DEF_INDEX, ..module.normal_ancestor_id })
2566 fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
2567 let mut module = self.get_module(module.normal_ancestor_id);
2568 while module.span.ctxt().modern() != *ctxt {
2569 let parent = module.parent.unwrap_or_else(|| self.macro_def_scope(ctxt.remove_mark()));
2570 module = self.get_module(parent.normal_ancestor_id);
2577 // We maintain a list of value ribs and type ribs.
2579 // Simultaneously, we keep track of the current position in the module
2580 // graph in the `current_module` pointer. When we go to resolve a name in
2581 // the value or type namespaces, we first look through all the ribs and
2582 // then query the module graph. When we resolve a name in the module
2583 // namespace, we can skip all the ribs (since nested modules are not
2584 // allowed within blocks in Rust) and jump straight to the current module
2587 // Named implementations are handled separately. When we find a method
2588 // call, we consult the module node to find all of the implementations in
2589 // scope. This information is lazily cached in the module node. We then
2590 // generate a fake "implementation scope" containing all the
2591 // implementations thus found, for compatibility with old resolve pass.
2593 pub fn with_scope<F, T>(&mut self, id: NodeId, f: F) -> T
2594 where F: FnOnce(&mut Resolver<'_>) -> T
2596 let id = self.definitions.local_def_id(id);
2597 let module = self.module_map.get(&id).cloned(); // clones a reference
2598 if let Some(module) = module {
2599 // Move down in the graph.
2600 let orig_module = replace(&mut self.current_module, module);
2601 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
2602 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
2604 self.finalize_current_module_macro_resolutions();
2607 self.current_module = orig_module;
2608 self.ribs[ValueNS].pop();
2609 self.ribs[TypeNS].pop();
2616 /// Searches the current set of local scopes for labels. Returns the first non-`None` label that
2617 /// is returned by the given predicate function
2619 /// Stops after meeting a closure.
2620 fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
2621 where P: Fn(&Rib<'_, NodeId>, Ident) -> Option<R>
2623 for rib in self.label_ribs.iter().rev() {
2626 // If an invocation of this macro created `ident`, give up on `ident`
2627 // and switch to `ident`'s source from the macro definition.
2628 MacroDefinition(def) => {
2629 if def == self.macro_def(ident.span.ctxt()) {
2630 ident.span.remove_mark();
2634 // Do not resolve labels across function boundary
2638 let r = pred(rib, ident);
2646 fn resolve_adt(&mut self, item: &Item, generics: &Generics) {
2647 debug!("resolve_adt");
2648 self.with_current_self_item(item, |this| {
2649 this.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2650 let item_def_id = this.definitions.local_def_id(item.id);
2651 this.with_self_rib(Res::SelfTy(None, Some(item_def_id)), |this| {
2652 visit::walk_item(this, item);
2658 fn future_proof_import(&mut self, use_tree: &ast::UseTree) {
2659 let segments = &use_tree.prefix.segments;
2660 if !segments.is_empty() {
2661 let ident = segments[0].ident;
2662 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
2666 let nss = match use_tree.kind {
2667 ast::UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
2670 let report_error = |this: &Self, ns| {
2671 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2672 this.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
2676 match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
2677 Some(LexicalScopeBinding::Res(..)) => {
2678 report_error(self, ns);
2680 Some(LexicalScopeBinding::Item(binding)) => {
2681 let orig_blacklisted_binding =
2682 mem::replace(&mut self.blacklisted_binding, Some(binding));
2683 if let Some(LexicalScopeBinding::Res(..)) =
2684 self.resolve_ident_in_lexical_scope(ident, ns, None,
2685 use_tree.prefix.span) {
2686 report_error(self, ns);
2688 self.blacklisted_binding = orig_blacklisted_binding;
2693 } else if let ast::UseTreeKind::Nested(use_trees) = &use_tree.kind {
2694 for (use_tree, _) in use_trees {
2695 self.future_proof_import(use_tree);
2700 fn resolve_item(&mut self, item: &Item) {
2701 let name = item.ident.name;
2702 debug!("(resolving item) resolving {} ({:?})", name, item.node);
2705 ItemKind::Ty(_, ref generics) |
2706 ItemKind::Existential(_, ref generics) |
2707 ItemKind::Fn(_, _, ref generics, _) => {
2708 self.with_generic_param_rib(
2709 HasGenericParams(generics, ItemRibKind),
2710 |this| visit::walk_item(this, item)
2714 ItemKind::Enum(_, ref generics) |
2715 ItemKind::Struct(_, ref generics) |
2716 ItemKind::Union(_, ref generics) => {
2717 self.resolve_adt(item, generics);
2720 ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
2721 self.resolve_implementation(generics,
2727 ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
2728 // Create a new rib for the trait-wide type parameters.
2729 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2730 let local_def_id = this.definitions.local_def_id(item.id);
2731 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
2732 this.visit_generics(generics);
2733 walk_list!(this, visit_param_bound, bounds);
2735 for trait_item in trait_items {
2736 this.with_trait_items(trait_items, |this| {
2737 let generic_params = HasGenericParams(
2738 &trait_item.generics,
2741 this.with_generic_param_rib(generic_params, |this| {
2742 match trait_item.node {
2743 TraitItemKind::Const(ref ty, ref default) => {
2746 // Only impose the restrictions of
2747 // ConstRibKind for an actual constant
2748 // expression in a provided default.
2749 if let Some(ref expr) = *default{
2750 this.with_constant_rib(|this| {
2751 this.visit_expr(expr);
2755 TraitItemKind::Method(_, _) => {
2756 visit::walk_trait_item(this, trait_item)
2758 TraitItemKind::Type(..) => {
2759 visit::walk_trait_item(this, trait_item)
2761 TraitItemKind::Macro(_) => {
2762 panic!("unexpanded macro in resolve!")
2772 ItemKind::TraitAlias(ref generics, ref bounds) => {
2773 // Create a new rib for the trait-wide type parameters.
2774 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2775 let local_def_id = this.definitions.local_def_id(item.id);
2776 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
2777 this.visit_generics(generics);
2778 walk_list!(this, visit_param_bound, bounds);
2783 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
2784 self.with_scope(item.id, |this| {
2785 visit::walk_item(this, item);
2789 ItemKind::Static(ref ty, _, ref expr) |
2790 ItemKind::Const(ref ty, ref expr) => {
2791 debug!("resolve_item ItemKind::Const");
2792 self.with_item_rib(|this| {
2794 this.with_constant_rib(|this| {
2795 this.visit_expr(expr);
2800 ItemKind::Use(ref use_tree) => {
2801 self.future_proof_import(use_tree);
2804 ItemKind::ExternCrate(..) |
2805 ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
2806 // do nothing, these are just around to be encoded
2809 ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
2813 fn with_generic_param_rib<'b, F>(&'b mut self, generic_params: GenericParameters<'a, 'b>, f: F)
2814 where F: FnOnce(&mut Resolver<'_>)
2816 debug!("with_generic_param_rib");
2817 match generic_params {
2818 HasGenericParams(generics, rib_kind) => {
2819 let mut function_type_rib = Rib::new(rib_kind);
2820 let mut function_value_rib = Rib::new(rib_kind);
2821 let mut seen_bindings = FxHashMap::default();
2822 for param in &generics.params {
2824 GenericParamKind::Lifetime { .. } => {}
2825 GenericParamKind::Type { .. } => {
2826 let ident = param.ident.modern();
2827 debug!("with_generic_param_rib: {}", param.id);
2829 if seen_bindings.contains_key(&ident) {
2830 let span = seen_bindings.get(&ident).unwrap();
2831 let err = ResolutionError::NameAlreadyUsedInParameterList(
2835 resolve_error(self, param.ident.span, err);
2837 seen_bindings.entry(ident).or_insert(param.ident.span);
2839 // Plain insert (no renaming).
2842 self.definitions.local_def_id(param.id),
2844 function_type_rib.bindings.insert(ident, res);
2845 self.record_partial_res(param.id, PartialRes::new(res));
2847 GenericParamKind::Const { .. } => {
2848 let ident = param.ident.modern();
2849 debug!("with_generic_param_rib: {}", param.id);
2851 if seen_bindings.contains_key(&ident) {
2852 let span = seen_bindings.get(&ident).unwrap();
2853 let err = ResolutionError::NameAlreadyUsedInParameterList(
2857 resolve_error(self, param.ident.span, err);
2859 seen_bindings.entry(ident).or_insert(param.ident.span);
2862 DefKind::ConstParam,
2863 self.definitions.local_def_id(param.id),
2865 function_value_rib.bindings.insert(ident, res);
2866 self.record_partial_res(param.id, PartialRes::new(res));
2870 self.ribs[ValueNS].push(function_value_rib);
2871 self.ribs[TypeNS].push(function_type_rib);
2874 NoGenericParams => {
2881 if let HasGenericParams(..) = generic_params {
2882 self.ribs[TypeNS].pop();
2883 self.ribs[ValueNS].pop();
2887 fn with_label_rib<F>(&mut self, f: F)
2888 where F: FnOnce(&mut Resolver<'_>)
2890 self.label_ribs.push(Rib::new(NormalRibKind));
2892 self.label_ribs.pop();
2895 fn with_item_rib<F>(&mut self, f: F)
2896 where F: FnOnce(&mut Resolver<'_>)
2898 self.ribs[ValueNS].push(Rib::new(ItemRibKind));
2899 self.ribs[TypeNS].push(Rib::new(ItemRibKind));
2901 self.ribs[TypeNS].pop();
2902 self.ribs[ValueNS].pop();
2905 fn with_constant_rib<F>(&mut self, f: F)
2906 where F: FnOnce(&mut Resolver<'_>)
2908 debug!("with_constant_rib");
2909 self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
2910 self.label_ribs.push(Rib::new(ConstantItemRibKind));
2912 self.label_ribs.pop();
2913 self.ribs[ValueNS].pop();
2916 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2917 where F: FnOnce(&mut Resolver<'_>) -> T
2919 // Handle nested impls (inside fn bodies)
2920 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2921 let result = f(self);
2922 self.current_self_type = previous_value;
2926 fn with_current_self_item<T, F>(&mut self, self_item: &Item, f: F) -> T
2927 where F: FnOnce(&mut Resolver<'_>) -> T
2929 let previous_value = replace(&mut self.current_self_item, Some(self_item.id));
2930 let result = f(self);
2931 self.current_self_item = previous_value;
2935 /// When evaluating a `trait` use its associated types' idents for suggestionsa in E0412.
2936 fn with_trait_items<T, F>(&mut self, trait_items: &Vec<TraitItem>, f: F) -> T
2937 where F: FnOnce(&mut Resolver<'_>) -> T
2939 let trait_assoc_types = replace(
2940 &mut self.current_trait_assoc_types,
2941 trait_items.iter().filter_map(|item| match &item.node {
2942 TraitItemKind::Type(bounds, _) if bounds.len() == 0 => Some(item.ident),
2946 let result = f(self);
2947 self.current_trait_assoc_types = trait_assoc_types;
2951 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
2952 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2953 where F: FnOnce(&mut Resolver<'_>, Option<DefId>) -> T
2955 let mut new_val = None;
2956 let mut new_id = None;
2957 if let Some(trait_ref) = opt_trait_ref {
2958 let path: Vec<_> = Segment::from_path(&trait_ref.path);
2959 let res = self.smart_resolve_path_fragment(
2963 trait_ref.path.span,
2964 PathSource::Trait(AliasPossibility::No),
2965 CrateLint::SimplePath(trait_ref.ref_id),
2967 if res != Res::Err {
2968 new_id = Some(res.def_id());
2969 let span = trait_ref.path.span;
2970 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2971 self.resolve_path_without_parent_scope(
2976 CrateLint::SimplePath(trait_ref.ref_id),
2979 new_val = Some((module, trait_ref.clone()));
2983 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2984 let result = f(self, new_id);
2985 self.current_trait_ref = original_trait_ref;
2989 fn with_self_rib<F>(&mut self, self_res: Res, f: F)
2990 where F: FnOnce(&mut Resolver<'_>)
2992 let mut self_type_rib = Rib::new(NormalRibKind);
2994 // Plain insert (no renaming, since types are not currently hygienic)
2995 self_type_rib.bindings.insert(Ident::with_empty_ctxt(kw::SelfUpper), self_res);
2996 self.ribs[TypeNS].push(self_type_rib);
2998 self.ribs[TypeNS].pop();
3001 fn with_self_struct_ctor_rib<F>(&mut self, impl_id: DefId, f: F)
3002 where F: FnOnce(&mut Resolver<'_>)
3004 let self_res = Res::SelfCtor(impl_id);
3005 let mut self_type_rib = Rib::new(NormalRibKind);
3006 self_type_rib.bindings.insert(Ident::with_empty_ctxt(kw::SelfUpper), self_res);
3007 self.ribs[ValueNS].push(self_type_rib);
3009 self.ribs[ValueNS].pop();
3012 fn resolve_implementation(&mut self,
3013 generics: &Generics,
3014 opt_trait_reference: &Option<TraitRef>,
3017 impl_items: &[ImplItem]) {
3018 debug!("resolve_implementation");
3019 // If applicable, create a rib for the type parameters.
3020 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
3021 // Dummy self type for better errors if `Self` is used in the trait path.
3022 this.with_self_rib(Res::SelfTy(None, None), |this| {
3023 // Resolve the trait reference, if necessary.
3024 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
3025 let item_def_id = this.definitions.local_def_id(item_id);
3026 this.with_self_rib(Res::SelfTy(trait_id, Some(item_def_id)), |this| {
3027 if let Some(trait_ref) = opt_trait_reference.as_ref() {
3028 // Resolve type arguments in the trait path.
3029 visit::walk_trait_ref(this, trait_ref);
3031 // Resolve the self type.
3032 this.visit_ty(self_type);
3033 // Resolve the generic parameters.
3034 this.visit_generics(generics);
3035 // Resolve the items within the impl.
3036 this.with_current_self_type(self_type, |this| {
3037 this.with_self_struct_ctor_rib(item_def_id, |this| {
3038 debug!("resolve_implementation with_self_struct_ctor_rib");
3039 for impl_item in impl_items {
3040 this.resolve_visibility(&impl_item.vis);
3042 // We also need a new scope for the impl item type parameters.
3043 let generic_params = HasGenericParams(&impl_item.generics,
3045 this.with_generic_param_rib(generic_params, |this| {
3046 use self::ResolutionError::*;
3047 match impl_item.node {
3048 ImplItemKind::Const(..) => {
3050 "resolve_implementation ImplItemKind::Const",
3052 // If this is a trait impl, ensure the const
3054 this.check_trait_item(
3058 |n, s| ConstNotMemberOfTrait(n, s),
3061 this.with_constant_rib(|this| {
3062 visit::walk_impl_item(this, impl_item)
3065 ImplItemKind::Method(..) => {
3066 // If this is a trait impl, ensure the method
3068 this.check_trait_item(impl_item.ident,
3071 |n, s| MethodNotMemberOfTrait(n, s));
3073 visit::walk_impl_item(this, impl_item);
3075 ImplItemKind::Type(ref ty) => {
3076 // If this is a trait impl, ensure the type
3078 this.check_trait_item(impl_item.ident,
3081 |n, s| TypeNotMemberOfTrait(n, s));
3085 ImplItemKind::Existential(ref bounds) => {
3086 // If this is a trait impl, ensure the type
3088 this.check_trait_item(impl_item.ident,
3091 |n, s| TypeNotMemberOfTrait(n, s));
3093 for bound in bounds {
3094 this.visit_param_bound(bound);
3097 ImplItemKind::Macro(_) =>
3098 panic!("unexpanded macro in resolve!"),
3110 fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
3111 where F: FnOnce(Name, &str) -> ResolutionError<'_>
3113 // If there is a TraitRef in scope for an impl, then the method must be in the
3115 if let Some((module, _)) = self.current_trait_ref {
3116 if self.resolve_ident_in_module(
3117 ModuleOrUniformRoot::Module(module),
3124 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3125 resolve_error(self, span, err(ident.name, &path_names_to_string(path)));
3130 fn resolve_local(&mut self, local: &Local) {
3131 // Resolve the type.
3132 walk_list!(self, visit_ty, &local.ty);
3134 // Resolve the initializer.
3135 walk_list!(self, visit_expr, &local.init);
3137 // Resolve the pattern.
3138 self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap::default());
3141 // build a map from pattern identifiers to binding-info's.
3142 // this is done hygienically. This could arise for a macro
3143 // that expands into an or-pattern where one 'x' was from the
3144 // user and one 'x' came from the macro.
3145 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
3146 let mut binding_map = FxHashMap::default();
3148 pat.walk(&mut |pat| {
3149 if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
3150 if sub_pat.is_some() || match self.partial_res_map.get(&pat.id)
3151 .map(|res| res.base_res()) {
3152 Some(Res::Local(..)) => true,
3155 let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
3156 binding_map.insert(ident, binding_info);
3165 // Checks that all of the arms in an or-pattern have exactly the
3166 // same set of bindings, with the same binding modes for each.
3167 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) {
3168 if pats.is_empty() {
3172 let mut missing_vars = FxHashMap::default();
3173 let mut inconsistent_vars = FxHashMap::default();
3174 for (i, p) in pats.iter().enumerate() {
3175 let map_i = self.binding_mode_map(&p);
3177 for (j, q) in pats.iter().enumerate() {
3182 let map_j = self.binding_mode_map(&q);
3183 for (&key, &binding_i) in &map_i {
3184 if map_j.is_empty() { // Account for missing bindings when
3185 let binding_error = missing_vars // `map_j` has none.
3187 .or_insert(BindingError {
3189 origin: BTreeSet::new(),
3190 target: BTreeSet::new(),
3192 binding_error.origin.insert(binding_i.span);
3193 binding_error.target.insert(q.span);
3195 for (&key_j, &binding_j) in &map_j {
3196 match map_i.get(&key_j) {
3197 None => { // missing binding
3198 let binding_error = missing_vars
3200 .or_insert(BindingError {
3202 origin: BTreeSet::new(),
3203 target: BTreeSet::new(),
3205 binding_error.origin.insert(binding_j.span);
3206 binding_error.target.insert(p.span);
3208 Some(binding_i) => { // check consistent binding
3209 if binding_i.binding_mode != binding_j.binding_mode {
3212 .or_insert((binding_j.span, binding_i.span));
3220 let mut missing_vars = missing_vars.iter().collect::<Vec<_>>();
3221 missing_vars.sort();
3222 for (_, v) in missing_vars {
3224 *v.origin.iter().next().unwrap(),
3225 ResolutionError::VariableNotBoundInPattern(v));
3227 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
3228 inconsistent_vars.sort();
3229 for (name, v) in inconsistent_vars {
3230 resolve_error(self, v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
3234 fn resolve_arm(&mut self, arm: &Arm) {
3235 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3237 self.resolve_pats(&arm.pats, PatternSource::Match);
3239 if let Some(ref expr) = arm.guard {
3240 self.visit_expr(expr)
3242 self.visit_expr(&arm.body);
3244 self.ribs[ValueNS].pop();
3247 /// Arising from `source`, resolve a sequence of patterns (top level or-patterns).
3248 fn resolve_pats(&mut self, pats: &[P<Pat>], source: PatternSource) {
3249 let mut bindings_list = FxHashMap::default();
3251 self.resolve_pattern(pat, source, &mut bindings_list);
3253 // This has to happen *after* we determine which pat_idents are variants
3254 self.check_consistent_bindings(pats);
3257 fn resolve_block(&mut self, block: &Block) {
3258 debug!("(resolving block) entering block");
3259 // Move down in the graph, if there's an anonymous module rooted here.
3260 let orig_module = self.current_module;
3261 let anonymous_module = self.block_map.get(&block.id).cloned(); // clones a reference
3263 let mut num_macro_definition_ribs = 0;
3264 if let Some(anonymous_module) = anonymous_module {
3265 debug!("(resolving block) found anonymous module, moving down");
3266 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
3267 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
3268 self.current_module = anonymous_module;
3269 self.finalize_current_module_macro_resolutions();
3271 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3274 // Descend into the block.
3275 for stmt in &block.stmts {
3276 if let ast::StmtKind::Item(ref item) = stmt.node {
3277 if let ast::ItemKind::MacroDef(..) = item.node {
3278 num_macro_definition_ribs += 1;
3279 let res = self.definitions.local_def_id(item.id);
3280 self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
3281 self.label_ribs.push(Rib::new(MacroDefinition(res)));
3285 self.visit_stmt(stmt);
3289 self.current_module = orig_module;
3290 for _ in 0 .. num_macro_definition_ribs {
3291 self.ribs[ValueNS].pop();
3292 self.label_ribs.pop();
3294 self.ribs[ValueNS].pop();
3295 if anonymous_module.is_some() {
3296 self.ribs[TypeNS].pop();
3298 debug!("(resolving block) leaving block");
3301 fn fresh_binding(&mut self,
3304 outer_pat_id: NodeId,
3305 pat_src: PatternSource,
3306 bindings: &mut FxHashMap<Ident, NodeId>)
3308 // Add the binding to the local ribs, if it
3309 // doesn't already exist in the bindings map. (We
3310 // must not add it if it's in the bindings map
3311 // because that breaks the assumptions later
3312 // passes make about or-patterns.)
3313 let ident = ident.modern_and_legacy();
3314 let mut res = Res::Local(pat_id);
3315 match bindings.get(&ident).cloned() {
3316 Some(id) if id == outer_pat_id => {
3317 // `Variant(a, a)`, error
3321 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
3325 Some(..) if pat_src == PatternSource::FnParam => {
3326 // `fn f(a: u8, a: u8)`, error
3330 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
3334 Some(..) if pat_src == PatternSource::Match ||
3335 pat_src == PatternSource::Let => {
3336 // `Variant1(a) | Variant2(a)`, ok
3337 // Reuse definition from the first `a`.
3338 res = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident];
3341 span_bug!(ident.span, "two bindings with the same name from \
3342 unexpected pattern source {:?}", pat_src);
3345 // A completely fresh binding, add to the lists if it's valid.
3346 if ident.name != kw::Invalid {
3347 bindings.insert(ident, outer_pat_id);
3348 self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident, res);
3356 fn resolve_pattern(&mut self,
3358 pat_src: PatternSource,
3359 // Maps idents to the node ID for the
3360 // outermost pattern that binds them.
3361 bindings: &mut FxHashMap<Ident, NodeId>) {
3362 // Visit all direct subpatterns of this pattern.
3363 let outer_pat_id = pat.id;
3364 pat.walk(&mut |pat| {
3365 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.node);
3367 PatKind::Ident(bmode, ident, ref opt_pat) => {
3368 // First try to resolve the identifier as some existing
3369 // entity, then fall back to a fresh binding.
3370 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS,
3372 .and_then(LexicalScopeBinding::item);
3373 let res = binding.map(NameBinding::res).and_then(|res| {
3374 let is_syntactic_ambiguity = opt_pat.is_none() &&
3375 bmode == BindingMode::ByValue(Mutability::Immutable);
3377 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) |
3378 Res::Def(DefKind::Const, _) if is_syntactic_ambiguity => {
3379 // Disambiguate in favor of a unit struct/variant
3380 // or constant pattern.
3381 self.record_use(ident, ValueNS, binding.unwrap(), false);
3384 Res::Def(DefKind::Ctor(..), _)
3385 | Res::Def(DefKind::Const, _)
3386 | Res::Def(DefKind::Static, _) => {
3387 // This is unambiguously a fresh binding, either syntactically
3388 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
3389 // to something unusable as a pattern (e.g., constructor function),
3390 // but we still conservatively report an error, see
3391 // issues/33118#issuecomment-233962221 for one reason why.
3395 ResolutionError::BindingShadowsSomethingUnacceptable(
3396 pat_src.descr(), ident.name, binding.unwrap())
3400 Res::Def(DefKind::Fn, _) | Res::Err => {
3401 // These entities are explicitly allowed
3402 // to be shadowed by fresh bindings.
3406 span_bug!(ident.span, "unexpected resolution for an \
3407 identifier in pattern: {:?}", res);
3410 }).unwrap_or_else(|| {
3411 self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
3414 self.record_partial_res(pat.id, PartialRes::new(res));
3417 PatKind::TupleStruct(ref path, ..) => {
3418 self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
3421 PatKind::Path(ref qself, ref path) => {
3422 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
3425 PatKind::Struct(ref path, ..) => {
3426 self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
3434 visit::walk_pat(self, pat);
3437 // High-level and context dependent path resolution routine.
3438 // Resolves the path and records the resolution into definition map.
3439 // If resolution fails tries several techniques to find likely
3440 // resolution candidates, suggest imports or other help, and report
3441 // errors in user friendly way.
3442 fn smart_resolve_path(&mut self,
3444 qself: Option<&QSelf>,
3446 source: PathSource<'_>) {
3447 self.smart_resolve_path_fragment(
3450 &Segment::from_path(path),
3453 CrateLint::SimplePath(id),
3457 fn smart_resolve_path_fragment(&mut self,
3459 qself: Option<&QSelf>,
3462 source: PathSource<'_>,
3463 crate_lint: CrateLint)
3465 let ns = source.namespace();
3466 let is_expected = &|res| source.is_expected(res);
3468 let report_errors = |this: &mut Self, res: Option<Res>| {
3469 let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res);
3470 let def_id = this.current_module.normal_ancestor_id;
3471 let node_id = this.definitions.as_local_node_id(def_id).unwrap();
3472 let better = res.is_some();
3473 this.use_injections.push(UseError { err, candidates, node_id, better });
3474 PartialRes::new(Res::Err)
3477 let partial_res = match self.resolve_qpath_anywhere(
3483 source.defer_to_typeck(),
3484 source.global_by_default(),
3487 Some(partial_res) if partial_res.unresolved_segments() == 0 => {
3488 if is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err {
3491 // Add a temporary hack to smooth the transition to new struct ctor
3492 // visibility rules. See #38932 for more details.
3494 if let Res::Def(DefKind::Struct, def_id) = partial_res.base_res() {
3495 if let Some((ctor_res, ctor_vis))
3496 = self.struct_constructors.get(&def_id).cloned() {
3497 if is_expected(ctor_res) && self.is_accessible(ctor_vis) {
3498 let lint = lint::builtin::LEGACY_CONSTRUCTOR_VISIBILITY;
3499 self.session.buffer_lint(lint, id, span,
3500 "private struct constructors are not usable through \
3501 re-exports in outer modules",
3503 res = Some(PartialRes::new(ctor_res));
3508 res.unwrap_or_else(|| report_errors(self, Some(partial_res.base_res())))
3511 Some(partial_res) if source.defer_to_typeck() => {
3512 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
3513 // or `<T>::A::B`. If `B` should be resolved in value namespace then
3514 // it needs to be added to the trait map.
3516 let item_name = path.last().unwrap().ident;
3517 let traits = self.get_traits_containing_item(item_name, ns);
3518 self.trait_map.insert(id, traits);
3521 let mut std_path = vec![Segment::from_ident(Ident::with_empty_ctxt(sym::std))];
3522 std_path.extend(path);
3523 if self.primitive_type_table.primitive_types.contains_key(&path[0].ident.name) {
3524 let cl = CrateLint::No;
3526 if let PathResult::Module(_) | PathResult::NonModule(_) =
3527 self.resolve_path_without_parent_scope(&std_path, ns, false, span, cl)
3529 // check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
3530 let item_span = path.iter().last().map(|segment| segment.ident.span)
3532 debug!("accessed item from `std` submodule as a bare type {:?}", std_path);
3533 let mut hm = self.session.confused_type_with_std_module.borrow_mut();
3534 hm.insert(item_span, span);
3535 // In some places (E0223) we only have access to the full path
3536 hm.insert(span, span);
3541 _ => report_errors(self, None)
3544 if let PathSource::TraitItem(..) = source {} else {
3545 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
3546 self.record_partial_res(id, partial_res);
3551 /// Only used in a specific case of type ascription suggestions
3553 fn get_colon_suggestion_span(&self, start: Span) -> Span {
3554 let cm = self.session.source_map();
3555 start.to(cm.next_point(start))
3558 fn type_ascription_suggestion(
3560 err: &mut DiagnosticBuilder<'_>,
3563 debug!("type_ascription_suggetion {:?}", base_span);
3564 let cm = self.session.source_map();
3565 let base_snippet = cm.span_to_snippet(base_span);
3566 debug!("self.current_type_ascription {:?}", self.current_type_ascription);
3567 if let Some(sp) = self.current_type_ascription.last() {
3570 // Try to find the `:`; bail on first non-':' / non-whitespace.
3571 sp = cm.next_point(sp);
3572 if let Ok(snippet) = cm.span_to_snippet(sp.to(cm.next_point(sp))) {
3573 let line_sp = cm.lookup_char_pos(sp.hi()).line;
3574 let line_base_sp = cm.lookup_char_pos(base_span.lo()).line;
3576 let mut show_label = true;
3577 if line_sp != line_base_sp {
3578 err.span_suggestion_short(
3580 "did you mean to use `;` here instead?",
3582 Applicability::MaybeIncorrect,
3585 let colon_sp = self.get_colon_suggestion_span(sp);
3586 let after_colon_sp = self.get_colon_suggestion_span(
3587 colon_sp.shrink_to_hi(),
3589 if !cm.span_to_snippet(after_colon_sp).map(|s| s == " ")
3592 err.span_suggestion(
3594 "maybe you meant to write a path separator here",
3596 Applicability::MaybeIncorrect,
3600 if let Ok(base_snippet) = base_snippet {
3601 let mut sp = after_colon_sp;
3603 // Try to find an assignment
3604 sp = cm.next_point(sp);
3605 let snippet = cm.span_to_snippet(sp.to(cm.next_point(sp)));
3607 Ok(ref x) if x.as_str() == "=" => {
3608 err.span_suggestion(
3610 "maybe you meant to write an assignment here",
3611 format!("let {}", base_snippet),
3612 Applicability::MaybeIncorrect,
3617 Ok(ref x) if x.as_str() == "\n" => break,
3625 err.span_label(base_span,
3626 "expecting a type here because of type ascription");
3629 } else if !snippet.trim().is_empty() {
3630 debug!("tried to find type ascription `:` token, couldn't find it");
3640 fn self_type_is_available(&mut self, span: Span) -> bool {
3641 let binding = self.resolve_ident_in_lexical_scope(
3642 Ident::with_empty_ctxt(kw::SelfUpper),
3647 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
3650 fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
3651 let ident = Ident::new(kw::SelfLower, self_span);
3652 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
3653 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
3656 // Resolve in alternative namespaces if resolution in the primary namespace fails.
3657 fn resolve_qpath_anywhere(
3660 qself: Option<&QSelf>,
3662 primary_ns: Namespace,
3664 defer_to_typeck: bool,
3665 global_by_default: bool,
3666 crate_lint: CrateLint,
3667 ) -> Option<PartialRes> {
3668 let mut fin_res = None;
3669 for (i, ns) in [primary_ns, TypeNS, ValueNS].iter().cloned().enumerate() {
3670 if i == 0 || ns != primary_ns {
3671 match self.resolve_qpath(id, qself, path, ns, span, global_by_default, crate_lint) {
3672 // If defer_to_typeck, then resolution > no resolution,
3673 // otherwise full resolution > partial resolution > no resolution.
3674 Some(partial_res) if partial_res.unresolved_segments() == 0 ||
3676 return Some(partial_res),
3677 partial_res => if fin_res.is_none() { fin_res = partial_res },
3683 assert!(primary_ns != MacroNS);
3684 if qself.is_none() {
3685 let path_seg = |seg: &Segment| ast::PathSegment::from_ident(seg.ident);
3686 let path = Path { segments: path.iter().map(path_seg).collect(), span };
3688 ParentScope { module: self.current_module, ..self.dummy_parent_scope() };
3689 if let Ok((_, res)) =
3690 self.resolve_macro_path(&path, None, &parent_scope, false, false) {
3691 return Some(PartialRes::new(res));
3698 /// Handles paths that may refer to associated items.
3702 qself: Option<&QSelf>,
3706 global_by_default: bool,
3707 crate_lint: CrateLint,
3708 ) -> Option<PartialRes> {
3710 "resolve_qpath(id={:?}, qself={:?}, path={:?}, \
3711 ns={:?}, span={:?}, global_by_default={:?})",
3720 if let Some(qself) = qself {
3721 if qself.position == 0 {
3722 // This is a case like `<T>::B`, where there is no
3723 // trait to resolve. In that case, we leave the `B`
3724 // segment to be resolved by type-check.
3725 return Some(PartialRes::with_unresolved_segments(
3726 Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)), path.len()
3730 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
3732 // Currently, `path` names the full item (`A::B::C`, in
3733 // our example). so we extract the prefix of that that is
3734 // the trait (the slice upto and including
3735 // `qself.position`). And then we recursively resolve that,
3736 // but with `qself` set to `None`.
3738 // However, setting `qself` to none (but not changing the
3739 // span) loses the information about where this path
3740 // *actually* appears, so for the purposes of the crate
3741 // lint we pass along information that this is the trait
3742 // name from a fully qualified path, and this also
3743 // contains the full span (the `CrateLint::QPathTrait`).
3744 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
3745 let partial_res = self.smart_resolve_path_fragment(
3748 &path[..=qself.position],
3750 PathSource::TraitItem(ns),
3751 CrateLint::QPathTrait {
3753 qpath_span: qself.path_span,
3757 // The remaining segments (the `C` in our example) will
3758 // have to be resolved by type-check, since that requires doing
3759 // trait resolution.
3760 return Some(PartialRes::with_unresolved_segments(
3761 partial_res.base_res(),
3762 partial_res.unresolved_segments() + path.len() - qself.position - 1,
3766 let result = match self.resolve_path_without_parent_scope(
3773 PathResult::NonModule(path_res) => path_res,
3774 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
3775 PartialRes::new(module.res().unwrap())
3777 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
3778 // don't report an error right away, but try to fallback to a primitive type.
3779 // So, we are still able to successfully resolve something like
3781 // use std::u8; // bring module u8 in scope
3782 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
3783 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
3784 // // not to non-existent std::u8::max_value
3787 // Such behavior is required for backward compatibility.
3788 // The same fallback is used when `a` resolves to nothing.
3789 PathResult::Module(ModuleOrUniformRoot::Module(_)) |
3790 PathResult::Failed { .. }
3791 if (ns == TypeNS || path.len() > 1) &&
3792 self.primitive_type_table.primitive_types
3793 .contains_key(&path[0].ident.name) => {
3794 let prim = self.primitive_type_table.primitive_types[&path[0].ident.name];
3795 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
3797 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3798 PartialRes::new(module.res().unwrap()),
3799 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
3800 resolve_error(self, span, ResolutionError::FailedToResolve { label, suggestion });
3801 PartialRes::new(Res::Err)
3803 PathResult::Module(..) | PathResult::Failed { .. } => return None,
3804 PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
3807 if path.len() > 1 && !global_by_default && result.base_res() != Res::Err &&
3808 path[0].ident.name != kw::PathRoot &&
3809 path[0].ident.name != kw::DollarCrate {
3810 let unqualified_result = {
3811 match self.resolve_path_without_parent_scope(
3812 &[*path.last().unwrap()],
3818 PathResult::NonModule(path_res) => path_res.base_res(),
3819 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3820 module.res().unwrap(),
3821 _ => return Some(result),
3824 if result.base_res() == unqualified_result {
3825 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
3826 self.session.buffer_lint(lint, id, span, "unnecessary qualification")
3833 fn resolve_path_without_parent_scope(
3836 opt_ns: Option<Namespace>, // `None` indicates a module path in import
3839 crate_lint: CrateLint,
3840 ) -> PathResult<'a> {
3841 // Macro and import paths must have full parent scope available during resolution,
3842 // other paths will do okay with parent module alone.
3843 assert!(opt_ns != None && opt_ns != Some(MacroNS));
3844 let parent_scope = ParentScope { module: self.current_module, ..self.dummy_parent_scope() };
3845 self.resolve_path(path, opt_ns, &parent_scope, record_used, path_span, crate_lint)
3851 opt_ns: Option<Namespace>, // `None` indicates a module path in import
3852 parent_scope: &ParentScope<'a>,
3855 crate_lint: CrateLint,
3856 ) -> PathResult<'a> {
3857 let mut module = None;
3858 let mut allow_super = true;
3859 let mut second_binding = None;
3860 self.current_module = parent_scope.module;
3863 "resolve_path(path={:?}, opt_ns={:?}, record_used={:?}, \
3864 path_span={:?}, crate_lint={:?})",
3872 for (i, &Segment { ident, id }) in path.iter().enumerate() {
3873 debug!("resolve_path ident {} {:?} {:?}", i, ident, id);
3874 let record_segment_res = |this: &mut Self, res| {
3876 if let Some(id) = id {
3877 if !this.partial_res_map.contains_key(&id) {
3878 assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id");
3879 this.record_partial_res(id, PartialRes::new(res));
3885 let is_last = i == path.len() - 1;
3886 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
3887 let name = ident.name;
3889 allow_super &= ns == TypeNS &&
3890 (name == kw::SelfLower ||
3894 if allow_super && name == kw::Super {
3895 let mut ctxt = ident.span.ctxt().modern();
3896 let self_module = match i {
3897 0 => Some(self.resolve_self(&mut ctxt, self.current_module)),
3899 Some(ModuleOrUniformRoot::Module(module)) => Some(module),
3903 if let Some(self_module) = self_module {
3904 if let Some(parent) = self_module.parent {
3905 module = Some(ModuleOrUniformRoot::Module(
3906 self.resolve_self(&mut ctxt, parent)));
3910 let msg = "there are too many initial `super`s.".to_string();
3911 return PathResult::Failed {
3915 is_error_from_last_segment: false,
3919 if name == kw::SelfLower {
3920 let mut ctxt = ident.span.ctxt().modern();
3921 module = Some(ModuleOrUniformRoot::Module(
3922 self.resolve_self(&mut ctxt, self.current_module)));
3925 if name == kw::PathRoot && ident.span.rust_2018() {
3926 module = Some(ModuleOrUniformRoot::ExternPrelude);
3929 if name == kw::PathRoot &&
3930 ident.span.rust_2015() && self.session.rust_2018() {
3931 // `::a::b` from 2015 macro on 2018 global edition
3932 module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude);
3935 if name == kw::PathRoot ||
3936 name == kw::Crate ||
3937 name == kw::DollarCrate {
3938 // `::a::b`, `crate::a::b` or `$crate::a::b`
3939 module = Some(ModuleOrUniformRoot::Module(
3940 self.resolve_crate_root(ident)));
3946 // Report special messages for path segment keywords in wrong positions.
3947 if ident.is_path_segment_keyword() && i != 0 {
3948 let name_str = if name == kw::PathRoot {
3949 "crate root".to_string()
3951 format!("`{}`", name)
3953 let label = if i == 1 && path[0].ident.name == kw::PathRoot {
3954 format!("global paths cannot start with {}", name_str)
3956 format!("{} in paths can only be used in start position", name_str)
3958 return PathResult::Failed {
3962 is_error_from_last_segment: false,
3966 let binding = if let Some(module) = module {
3967 self.resolve_ident_in_module(module, ident, ns, None, record_used, path_span)
3968 } else if opt_ns.is_none() || opt_ns == Some(MacroNS) {
3969 assert!(ns == TypeNS);
3970 let scopes = if opt_ns.is_none() { ScopeSet::Import(ns) } else { ScopeSet::Module };
3971 self.early_resolve_ident_in_lexical_scope(ident, scopes, parent_scope, record_used,
3972 record_used, path_span)
3974 let record_used_id =
3975 if record_used { crate_lint.node_id().or(Some(CRATE_NODE_ID)) } else { None };
3976 match self.resolve_ident_in_lexical_scope(ident, ns, record_used_id, path_span) {
3977 // we found a locally-imported or available item/module
3978 Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
3979 // we found a local variable or type param
3980 Some(LexicalScopeBinding::Res(res))
3981 if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => {
3982 record_segment_res(self, res);
3983 return PathResult::NonModule(PartialRes::with_unresolved_segments(
3987 _ => Err(Determinacy::determined(record_used)),
3994 second_binding = Some(binding);
3996 let res = binding.res();
3997 let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res);
3998 if let Some(next_module) = binding.module() {
3999 module = Some(ModuleOrUniformRoot::Module(next_module));
4000 record_segment_res(self, res);
4001 } else if res == Res::ToolMod && i + 1 != path.len() {
4002 if binding.is_import() {
4003 self.session.struct_span_err(
4004 ident.span, "cannot use a tool module through an import"
4006 binding.span, "the tool module imported here"
4009 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
4010 return PathResult::NonModule(PartialRes::new(res));
4011 } else if res == Res::Err {
4012 return PathResult::NonModule(PartialRes::new(Res::Err));
4013 } else if opt_ns.is_some() && (is_last || maybe_assoc) {
4014 self.lint_if_path_starts_with_module(
4020 return PathResult::NonModule(PartialRes::with_unresolved_segments(
4021 res, path.len() - i - 1
4024 let label = format!(
4025 "`{}` is {} {}, not a module",
4031 return PathResult::Failed {
4035 is_error_from_last_segment: is_last,
4039 Err(Undetermined) => return PathResult::Indeterminate,
4040 Err(Determined) => {
4041 if let Some(ModuleOrUniformRoot::Module(module)) = module {
4042 if opt_ns.is_some() && !module.is_normal() {
4043 return PathResult::NonModule(PartialRes::with_unresolved_segments(
4044 module.res().unwrap(), path.len() - i
4048 let module_res = match module {
4049 Some(ModuleOrUniformRoot::Module(module)) => module.res(),
4052 let (label, suggestion) = if module_res == self.graph_root.res() {
4053 let is_mod = |res| {
4054 match res { Res::Def(DefKind::Mod, _) => true, _ => false }
4056 let mut candidates =
4057 self.lookup_import_candidates(ident, TypeNS, is_mod);
4058 candidates.sort_by_cached_key(|c| {
4059 (c.path.segments.len(), c.path.to_string())
4061 if let Some(candidate) = candidates.get(0) {
4063 String::from("unresolved import"),
4065 vec![(ident.span, candidate.path.to_string())],
4066 String::from("a similar path exists"),
4067 Applicability::MaybeIncorrect,
4070 } else if !ident.is_reserved() {
4071 (format!("maybe a missing `extern crate {};`?", ident), None)
4073 // the parser will already have complained about the keyword being used
4074 return PathResult::NonModule(PartialRes::new(Res::Err));
4077 (format!("use of undeclared type or module `{}`", ident), None)
4079 (format!("could not find `{}` in `{}`", ident, path[i - 1].ident), None)
4081 return PathResult::Failed {
4085 is_error_from_last_segment: is_last,
4091 self.lint_if_path_starts_with_module(crate_lint, path, path_span, second_binding);
4093 PathResult::Module(match module {
4094 Some(module) => module,
4095 None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
4096 _ => span_bug!(path_span, "resolve_path: non-empty path `{:?}` has no module", path),
4100 fn lint_if_path_starts_with_module(
4102 crate_lint: CrateLint,
4105 second_binding: Option<&NameBinding<'_>>,
4107 let (diag_id, diag_span) = match crate_lint {
4108 CrateLint::No => return,
4109 CrateLint::SimplePath(id) => (id, path_span),
4110 CrateLint::UsePath { root_id, root_span } => (root_id, root_span),
4111 CrateLint::QPathTrait { qpath_id, qpath_span } => (qpath_id, qpath_span),
4114 let first_name = match path.get(0) {
4115 // In the 2018 edition this lint is a hard error, so nothing to do
4116 Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name,
4120 // We're only interested in `use` paths which should start with
4121 // `{{root}}` currently.
4122 if first_name != kw::PathRoot {
4127 // If this import looks like `crate::...` it's already good
4128 Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
4129 // Otherwise go below to see if it's an extern crate
4131 // If the path has length one (and it's `PathRoot` most likely)
4132 // then we don't know whether we're gonna be importing a crate or an
4133 // item in our crate. Defer this lint to elsewhere
4137 // If the first element of our path was actually resolved to an
4138 // `ExternCrate` (also used for `crate::...`) then no need to issue a
4139 // warning, this looks all good!
4140 if let Some(binding) = second_binding {
4141 if let NameBindingKind::Import { directive: d, .. } = binding.kind {
4142 // Careful: we still want to rewrite paths from
4143 // renamed extern crates.
4144 if let ImportDirectiveSubclass::ExternCrate { source: None, .. } = d.subclass {
4150 let diag = lint::builtin::BuiltinLintDiagnostics
4151 ::AbsPathWithModule(diag_span);
4152 self.session.buffer_lint_with_diagnostic(
4153 lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
4155 "absolute paths must start with `self`, `super`, \
4156 `crate`, or an external crate name in the 2018 edition",
4160 // Validate a local resolution (from ribs).
4161 fn validate_res_from_ribs(
4169 debug!("validate_res_from_ribs({:?})", res);
4170 let ribs = &self.ribs[ns][rib_index + 1..];
4172 // An invalid forward use of a type parameter from a previous default.
4173 if let ForwardTyParamBanRibKind = self.ribs[ns][rib_index].kind {
4175 resolve_error(self, span, ResolutionError::ForwardDeclaredTyParam);
4177 assert_eq!(res, Res::Err);
4181 // An invalid use of a type parameter as the type of a const parameter.
4182 if let TyParamAsConstParamTy = self.ribs[ns][rib_index].kind {
4184 resolve_error(self, span, ResolutionError::ConstParamDependentOnTypeParam);
4186 assert_eq!(res, Res::Err);
4192 use ResolutionError::*;
4193 let mut res_err = None;
4197 NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) |
4198 ForwardTyParamBanRibKind | TyParamAsConstParamTy => {
4199 // Nothing to do. Continue.
4201 ItemRibKind | FnItemRibKind | AssocItemRibKind => {
4202 // This was an attempt to access an upvar inside a
4203 // named function item. This is not allowed, so we
4206 // We don't immediately trigger a resolve error, because
4207 // we want certain other resolution errors (namely those
4208 // emitted for `ConstantItemRibKind` below) to take
4210 res_err = Some(CannotCaptureDynamicEnvironmentInFnItem);
4213 ConstantItemRibKind => {
4214 // Still doesn't deal with upvars
4216 resolve_error(self, span, AttemptToUseNonConstantValueInConstant);
4222 if let Some(res_err) = res_err {
4223 resolve_error(self, span, res_err);
4227 Res::Def(DefKind::TyParam, _) | Res::SelfTy(..) => {
4230 NormalRibKind | AssocItemRibKind |
4231 ModuleRibKind(..) | MacroDefinition(..) | ForwardTyParamBanRibKind |
4232 ConstantItemRibKind | TyParamAsConstParamTy => {
4233 // Nothing to do. Continue.
4235 ItemRibKind | FnItemRibKind => {
4236 // This was an attempt to use a type parameter outside its scope.
4241 ResolutionError::GenericParamsFromOuterFunction(res),
4249 Res::Def(DefKind::ConstParam, _) => {
4250 let mut ribs = ribs.iter().peekable();
4251 if let Some(Rib { kind: FnItemRibKind, .. }) = ribs.peek() {
4252 // When declaring const parameters inside function signatures, the first rib
4253 // is always a `FnItemRibKind`. In this case, we can skip it, to avoid it
4254 // (spuriously) conflicting with the const param.
4258 if let ItemRibKind | FnItemRibKind = rib.kind {
4259 // This was an attempt to use a const parameter outside its scope.
4264 ResolutionError::GenericParamsFromOuterFunction(res),
4276 fn with_resolved_label<F>(&mut self, label: Option<Label>, id: NodeId, f: F)
4277 where F: FnOnce(&mut Resolver<'_>)
4279 if let Some(label) = label {
4280 self.unused_labels.insert(id, label.ident.span);
4281 self.with_label_rib(|this| {
4282 let ident = label.ident.modern_and_legacy();
4283 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
4291 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
4292 self.with_resolved_label(label, id, |this| this.visit_block(block));
4295 fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
4296 // First, record candidate traits for this expression if it could
4297 // result in the invocation of a method call.
4299 self.record_candidate_traits_for_expr_if_necessary(expr);
4301 // Next, resolve the node.
4303 ExprKind::Path(ref qself, ref path) => {
4304 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
4305 visit::walk_expr(self, expr);
4308 ExprKind::Struct(ref path, ..) => {
4309 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
4310 visit::walk_expr(self, expr);
4313 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4314 let node_id = self.search_label(label.ident, |rib, ident| {
4315 rib.bindings.get(&ident.modern_and_legacy()).cloned()
4319 // Search again for close matches...
4320 // Picks the first label that is "close enough", which is not necessarily
4321 // the closest match
4322 let close_match = self.search_label(label.ident, |rib, ident| {
4323 let names = rib.bindings.iter().filter_map(|(id, _)| {
4324 if id.span.ctxt() == label.ident.span.ctxt() {
4330 find_best_match_for_name(names, &*ident.as_str(), None)
4332 self.record_partial_res(expr.id, PartialRes::new(Res::Err));
4335 ResolutionError::UndeclaredLabel(&label.ident.as_str(),
4339 // Since this res is a label, it is never read.
4340 self.label_res_map.insert(expr.id, node_id);
4341 self.unused_labels.remove(&node_id);
4345 // visit `break` argument if any
4346 visit::walk_expr(self, expr);
4349 ExprKind::Let(ref pats, ref scrutinee) => {
4350 self.visit_expr(scrutinee);
4351 self.resolve_pats(pats, PatternSource::Let);
4354 ExprKind::If(ref cond, ref then, ref opt_else) => {
4355 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
4356 self.visit_expr(cond);
4357 self.visit_block(then);
4358 self.ribs[ValueNS].pop();
4360 opt_else.as_ref().map(|expr| self.visit_expr(expr));
4363 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
4365 ExprKind::While(ref subexpression, ref block, label) => {
4366 self.with_resolved_label(label, expr.id, |this| {
4367 this.ribs[ValueNS].push(Rib::new(NormalRibKind));
4368 this.visit_expr(subexpression);
4369 this.visit_block(block);
4370 this.ribs[ValueNS].pop();
4374 ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
4375 self.visit_expr(subexpression);
4376 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
4377 self.resolve_pattern(pattern, PatternSource::For, &mut FxHashMap::default());
4379 self.resolve_labeled_block(label, expr.id, block);
4381 self.ribs[ValueNS].pop();
4384 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4386 // Equivalent to `visit::walk_expr` + passing some context to children.
4387 ExprKind::Field(ref subexpression, _) => {
4388 self.resolve_expr(subexpression, Some(expr));
4390 ExprKind::MethodCall(ref segment, ref arguments) => {
4391 let mut arguments = arguments.iter();
4392 self.resolve_expr(arguments.next().unwrap(), Some(expr));
4393 for argument in arguments {
4394 self.resolve_expr(argument, None);
4396 self.visit_path_segment(expr.span, segment);
4399 ExprKind::Call(ref callee, ref arguments) => {
4400 self.resolve_expr(callee, Some(expr));
4401 for argument in arguments {
4402 self.resolve_expr(argument, None);
4405 ExprKind::Type(ref type_expr, _) => {
4406 self.current_type_ascription.push(type_expr.span);
4407 visit::walk_expr(self, expr);
4408 self.current_type_ascription.pop();
4410 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
4411 // resolve the arguments within the proper scopes so that usages of them inside the
4412 // closure are detected as upvars rather than normal closure arg usages.
4414 _, IsAsync::Async { .. }, _,
4415 ref fn_decl, ref body, _span,
4417 let rib_kind = NormalRibKind;
4418 self.ribs[ValueNS].push(Rib::new(rib_kind));
4419 // Resolve arguments:
4420 let mut bindings_list = FxHashMap::default();
4421 for argument in &fn_decl.inputs {
4422 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
4423 self.visit_ty(&argument.ty);
4425 // No need to resolve return type-- the outer closure return type is
4426 // FunctionRetTy::Default
4428 // Now resolve the inner closure
4430 // No need to resolve arguments: the inner closure has none.
4431 // Resolve the return type:
4432 visit::walk_fn_ret_ty(self, &fn_decl.output);
4434 self.visit_expr(body);
4436 self.ribs[ValueNS].pop();
4439 visit::walk_expr(self, expr);
4444 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4446 ExprKind::Field(_, ident) => {
4447 // FIXME(#6890): Even though you can't treat a method like a
4448 // field, we need to add any trait methods we find that match
4449 // the field name so that we can do some nice error reporting
4450 // later on in typeck.
4451 let traits = self.get_traits_containing_item(ident, ValueNS);
4452 self.trait_map.insert(expr.id, traits);
4454 ExprKind::MethodCall(ref segment, ..) => {
4455 debug!("(recording candidate traits for expr) recording traits for {}",
4457 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
4458 self.trait_map.insert(expr.id, traits);
4466 fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
4467 -> Vec<TraitCandidate> {
4468 debug!("(getting traits containing item) looking for '{}'", ident.name);
4470 let mut found_traits = Vec::new();
4471 // Look for the current trait.
4472 if let Some((module, _)) = self.current_trait_ref {
4473 if self.resolve_ident_in_module(
4474 ModuleOrUniformRoot::Module(module),
4481 let def_id = module.def_id().unwrap();
4482 found_traits.push(TraitCandidate { def_id: def_id, import_ids: smallvec![] });
4486 ident.span = ident.span.modern();
4487 let mut search_module = self.current_module;
4489 self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
4490 search_module = unwrap_or!(
4491 self.hygienic_lexical_parent(search_module, &mut ident.span), break
4495 if let Some(prelude) = self.prelude {
4496 if !search_module.no_implicit_prelude {
4497 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
4504 fn get_traits_in_module_containing_item(&mut self,
4508 found_traits: &mut Vec<TraitCandidate>) {
4509 assert!(ns == TypeNS || ns == ValueNS);
4510 let mut traits = module.traits.borrow_mut();
4511 if traits.is_none() {
4512 let mut collected_traits = Vec::new();
4513 module.for_each_child(|name, ns, binding| {
4514 if ns != TypeNS { return }
4515 match binding.res() {
4516 Res::Def(DefKind::Trait, _) |
4517 Res::Def(DefKind::TraitAlias, _) => collected_traits.push((name, binding)),
4521 *traits = Some(collected_traits.into_boxed_slice());
4524 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
4525 // Traits have pseudo-modules that can be used to search for the given ident.
4526 if let Some(module) = binding.module() {
4527 let mut ident = ident;
4528 if ident.span.glob_adjust(
4534 if self.resolve_ident_in_module_unadjusted(
4535 ModuleOrUniformRoot::Module(module),
4541 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
4542 let trait_def_id = module.def_id().unwrap();
4543 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
4545 } else if let Res::Def(DefKind::TraitAlias, _) = binding.res() {
4546 // For now, just treat all trait aliases as possible candidates, since we don't
4547 // know if the ident is somewhere in the transitive bounds.
4548 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
4549 let trait_def_id = binding.res().def_id();
4550 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
4552 bug!("candidate is not trait or trait alias?")
4557 fn find_transitive_imports(&mut self, mut kind: &NameBindingKind<'_>,
4558 trait_name: Ident) -> SmallVec<[NodeId; 1]> {
4559 let mut import_ids = smallvec![];
4560 while let NameBindingKind::Import { directive, binding, .. } = kind {
4561 self.maybe_unused_trait_imports.insert(directive.id);
4562 self.add_to_glob_map(&directive, trait_name);
4563 import_ids.push(directive.id);
4564 kind = &binding.kind;
4569 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
4570 debug!("(recording res) recording {:?} for {}", resolution, node_id);
4571 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
4572 panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
4576 fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
4578 ast::VisibilityKind::Public => ty::Visibility::Public,
4579 ast::VisibilityKind::Crate(..) => {
4580 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
4582 ast::VisibilityKind::Inherited => {
4583 ty::Visibility::Restricted(self.current_module.normal_ancestor_id)
4585 ast::VisibilityKind::Restricted { ref path, id, .. } => {
4586 // For visibilities we are not ready to provide correct implementation of "uniform
4587 // paths" right now, so on 2018 edition we only allow module-relative paths for now.
4588 // On 2015 edition visibilities are resolved as crate-relative by default,
4589 // so we are prepending a root segment if necessary.
4590 let ident = path.segments.get(0).expect("empty path in visibility").ident;
4591 let crate_root = if ident.is_path_segment_keyword() {
4593 } else if ident.span.rust_2018() {
4594 let msg = "relative paths are not supported in visibilities on 2018 edition";
4595 self.session.struct_span_err(ident.span, msg)
4599 format!("crate::{}", path),
4600 Applicability::MaybeIncorrect,
4603 return ty::Visibility::Public;
4605 let ctxt = ident.span.ctxt();
4606 Some(Segment::from_ident(Ident::new(
4607 kw::PathRoot, path.span.shrink_to_lo().with_ctxt(ctxt)
4611 let segments = crate_root.into_iter()
4612 .chain(path.segments.iter().map(|seg| seg.into())).collect::<Vec<_>>();
4613 let res = self.smart_resolve_path_fragment(
4618 PathSource::Visibility,
4619 CrateLint::SimplePath(id),
4621 if res == Res::Err {
4622 ty::Visibility::Public
4624 let vis = ty::Visibility::Restricted(res.def_id());
4625 if self.is_accessible(vis) {
4628 self.session.span_err(path.span, "visibilities can only be restricted \
4629 to ancestor modules");
4630 ty::Visibility::Public
4637 fn is_accessible(&self, vis: ty::Visibility) -> bool {
4638 vis.is_accessible_from(self.current_module.normal_ancestor_id, self)
4641 fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
4642 vis.is_accessible_from(module.normal_ancestor_id, self)
4645 fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) {
4646 if let Some(old_module) = self.binding_parent_modules.insert(PtrKey(binding), module) {
4647 if !ptr::eq(module, old_module) {
4648 span_bug!(binding.span, "parent module is reset for binding");
4653 fn disambiguate_legacy_vs_modern(
4655 legacy: &'a NameBinding<'a>,
4656 modern: &'a NameBinding<'a>,
4658 // Some non-controversial subset of ambiguities "modern macro name" vs "macro_rules"
4659 // is disambiguated to mitigate regressions from macro modularization.
4660 // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
4661 match (self.binding_parent_modules.get(&PtrKey(legacy)),
4662 self.binding_parent_modules.get(&PtrKey(modern))) {
4663 (Some(legacy), Some(modern)) =>
4664 legacy.normal_ancestor_id == modern.normal_ancestor_id &&
4665 modern.is_ancestor_of(legacy),
4670 fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
4671 if b.span.is_dummy() {
4672 let add_built_in = match b.res() {
4673 // These already contain the "built-in" prefix or look bad with it.
4674 Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod => false,
4677 let (built_in, from) = if from_prelude {
4678 ("", " from prelude")
4679 } else if b.is_extern_crate() && !b.is_import() &&
4680 self.session.opts.externs.get(&ident.as_str()).is_some() {
4681 ("", " passed with `--extern`")
4682 } else if add_built_in {
4688 let article = if built_in.is_empty() { b.article() } else { "a" };
4689 format!("{a}{built_in} {thing}{from}",
4690 a = article, thing = b.descr(), built_in = built_in, from = from)
4692 let introduced = if b.is_import() { "imported" } else { "defined" };
4693 format!("the {thing} {introduced} here",
4694 thing = b.descr(), introduced = introduced)
4698 fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
4699 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
4700 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
4701 // We have to print the span-less alternative first, otherwise formatting looks bad.
4702 (b2, b1, misc2, misc1, true)
4704 (b1, b2, misc1, misc2, false)
4707 let mut err = struct_span_err!(self.session, ident.span, E0659,
4708 "`{ident}` is ambiguous ({why})",
4709 ident = ident, why = kind.descr());
4710 err.span_label(ident.span, "ambiguous name");
4712 let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
4713 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
4714 let note_msg = format!("`{ident}` could{also} refer to {what}",
4715 ident = ident, also = also, what = what);
4717 let mut help_msgs = Vec::new();
4718 if b.is_glob_import() && (kind == AmbiguityKind::GlobVsGlob ||
4719 kind == AmbiguityKind::GlobVsExpanded ||
4720 kind == AmbiguityKind::GlobVsOuter &&
4721 swapped != also.is_empty()) {
4722 help_msgs.push(format!("consider adding an explicit import of \
4723 `{ident}` to disambiguate", ident = ident))
4725 if b.is_extern_crate() && ident.span.rust_2018() {
4726 help_msgs.push(format!(
4727 "use `::{ident}` to refer to this {thing} unambiguously",
4728 ident = ident, thing = b.descr(),
4731 if misc == AmbiguityErrorMisc::SuggestCrate {
4732 help_msgs.push(format!(
4733 "use `crate::{ident}` to refer to this {thing} unambiguously",
4734 ident = ident, thing = b.descr(),
4736 } else if misc == AmbiguityErrorMisc::SuggestSelf {
4737 help_msgs.push(format!(
4738 "use `self::{ident}` to refer to this {thing} unambiguously",
4739 ident = ident, thing = b.descr(),
4743 err.span_note(b.span, ¬e_msg);
4744 for (i, help_msg) in help_msgs.iter().enumerate() {
4745 let or = if i == 0 { "" } else { "or " };
4746 err.help(&format!("{}{}", or, help_msg));
4750 could_refer_to(b1, misc1, "");
4751 could_refer_to(b2, misc2, " also");
4755 fn report_errors(&mut self, krate: &Crate) {
4756 self.report_with_use_injections(krate);
4758 for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
4759 let msg = "macro-expanded `macro_export` macros from the current crate \
4760 cannot be referred to by absolute paths";
4761 self.session.buffer_lint_with_diagnostic(
4762 lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
4763 CRATE_NODE_ID, span_use, msg,
4764 lint::builtin::BuiltinLintDiagnostics::
4765 MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
4769 for ambiguity_error in &self.ambiguity_errors {
4770 self.report_ambiguity_error(ambiguity_error);
4773 let mut reported_spans = FxHashSet::default();
4774 for &PrivacyError(dedup_span, ident, binding) in &self.privacy_errors {
4775 if reported_spans.insert(dedup_span) {
4776 span_err!(self.session, ident.span, E0603, "{} `{}` is private",
4777 binding.descr(), ident.name);
4782 fn report_with_use_injections(&mut self, krate: &Crate) {
4783 for UseError { mut err, candidates, node_id, better } in self.use_injections.drain(..) {
4784 let (span, found_use) = UsePlacementFinder::check(krate, node_id);
4785 if !candidates.is_empty() {
4786 diagnostics::show_candidates(&mut err, span, &candidates, better, found_use);
4792 fn report_conflict<'b>(&mut self,
4796 new_binding: &NameBinding<'b>,
4797 old_binding: &NameBinding<'b>) {
4798 // Error on the second of two conflicting names
4799 if old_binding.span.lo() > new_binding.span.lo() {
4800 return self.report_conflict(parent, ident, ns, old_binding, new_binding);
4803 let container = match parent.kind {
4804 ModuleKind::Def(DefKind::Mod, _, _) => "module",
4805 ModuleKind::Def(DefKind::Trait, _, _) => "trait",
4806 ModuleKind::Block(..) => "block",
4810 let old_noun = match old_binding.is_import() {
4812 false => "definition",
4815 let new_participle = match new_binding.is_import() {
4820 let (name, span) = (ident.name, self.session.source_map().def_span(new_binding.span));
4822 if let Some(s) = self.name_already_seen.get(&name) {
4828 let old_kind = match (ns, old_binding.module()) {
4829 (ValueNS, _) => "value",
4830 (MacroNS, _) => "macro",
4831 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
4832 (TypeNS, Some(module)) if module.is_normal() => "module",
4833 (TypeNS, Some(module)) if module.is_trait() => "trait",
4834 (TypeNS, _) => "type",
4837 let msg = format!("the name `{}` is defined multiple times", name);
4839 let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
4840 (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
4841 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
4842 true => struct_span_err!(self.session, span, E0254, "{}", msg),
4843 false => struct_span_err!(self.session, span, E0260, "{}", msg),
4845 _ => match (old_binding.is_import(), new_binding.is_import()) {
4846 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
4847 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
4848 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
4852 err.note(&format!("`{}` must be defined only once in the {} namespace of this {}",
4857 err.span_label(span, format!("`{}` re{} here", name, new_participle));
4859 self.session.source_map().def_span(old_binding.span),
4860 format!("previous {} of the {} `{}` here", old_noun, old_kind, name),
4863 // See https://github.com/rust-lang/rust/issues/32354
4864 use NameBindingKind::Import;
4865 let directive = match (&new_binding.kind, &old_binding.kind) {
4866 // If there are two imports where one or both have attributes then prefer removing the
4867 // import without attributes.
4868 (Import { directive: new, .. }, Import { directive: old, .. }) if {
4869 !new_binding.span.is_dummy() && !old_binding.span.is_dummy() &&
4870 (new.has_attributes || old.has_attributes)
4872 if old.has_attributes {
4873 Some((new, new_binding.span, true))
4875 Some((old, old_binding.span, true))
4878 // Otherwise prioritize the new binding.
4879 (Import { directive, .. }, other) if !new_binding.span.is_dummy() =>
4880 Some((directive, new_binding.span, other.is_import())),
4881 (other, Import { directive, .. }) if !old_binding.span.is_dummy() =>
4882 Some((directive, old_binding.span, other.is_import())),
4886 // Check if the target of the use for both bindings is the same.
4887 let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
4888 let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
4889 let from_item = self.extern_prelude.get(&ident)
4890 .map(|entry| entry.introduced_by_item)
4892 // Only suggest removing an import if both bindings are to the same def, if both spans
4893 // aren't dummy spans. Further, if both bindings are imports, then the ident must have
4894 // been introduced by a item.
4895 let should_remove_import = duplicate && !has_dummy_span &&
4896 ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
4899 Some((directive, span, true)) if should_remove_import && directive.is_nested() =>
4900 self.add_suggestion_for_duplicate_nested_use(&mut err, directive, span),
4901 Some((directive, _, true)) if should_remove_import && !directive.is_glob() => {
4902 // Simple case - remove the entire import. Due to the above match arm, this can
4903 // only be a single use so just remove it entirely.
4904 err.tool_only_span_suggestion(
4905 directive.use_span_with_attributes,
4906 "remove unnecessary import",
4908 Applicability::MaybeIncorrect,
4911 Some((directive, span, _)) =>
4912 self.add_suggestion_for_rename_of_use(&mut err, name, directive, span),
4917 self.name_already_seen.insert(name, span);
4920 /// This function adds a suggestion to change the binding name of a new import that conflicts
4921 /// with an existing import.
4923 /// ```ignore (diagnostic)
4924 /// help: you can use `as` to change the binding name of the import
4926 /// LL | use foo::bar as other_bar;
4927 /// | ^^^^^^^^^^^^^^^^^^^^^
4929 fn add_suggestion_for_rename_of_use(
4931 err: &mut DiagnosticBuilder<'_>,
4933 directive: &ImportDirective<'_>,
4936 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
4937 format!("Other{}", name)
4939 format!("other_{}", name)
4942 let mut suggestion = None;
4943 match directive.subclass {
4944 ImportDirectiveSubclass::SingleImport { type_ns_only: true, .. } =>
4945 suggestion = Some(format!("self as {}", suggested_name)),
4946 ImportDirectiveSubclass::SingleImport { source, .. } => {
4947 if let Some(pos) = source.span.hi().0.checked_sub(binding_span.lo().0)
4948 .map(|pos| pos as usize) {
4949 if let Ok(snippet) = self.session.source_map()
4950 .span_to_snippet(binding_span) {
4951 if pos <= snippet.len() {
4952 suggestion = Some(format!(
4956 if snippet.ends_with(";") { ";" } else { "" }
4962 ImportDirectiveSubclass::ExternCrate { source, target, .. } =>
4963 suggestion = Some(format!(
4964 "extern crate {} as {};",
4965 source.unwrap_or(target.name),
4968 _ => unreachable!(),
4971 let rename_msg = "you can use `as` to change the binding name of the import";
4972 if let Some(suggestion) = suggestion {
4973 err.span_suggestion(
4977 Applicability::MaybeIncorrect,
4980 err.span_label(binding_span, rename_msg);
4984 /// This function adds a suggestion to remove a unnecessary binding from an import that is
4985 /// nested. In the following example, this function will be invoked to remove the `a` binding
4986 /// in the second use statement:
4988 /// ```ignore (diagnostic)
4989 /// use issue_52891::a;
4990 /// use issue_52891::{d, a, e};
4993 /// The following suggestion will be added:
4995 /// ```ignore (diagnostic)
4996 /// use issue_52891::{d, a, e};
4997 /// ^-- help: remove unnecessary import
5000 /// If the nested use contains only one import then the suggestion will remove the entire
5003 /// It is expected that the directive provided is a nested import - this isn't checked by the
5004 /// function. If this invariant is not upheld, this function's behaviour will be unexpected
5005 /// as characters expected by span manipulations won't be present.
5006 fn add_suggestion_for_duplicate_nested_use(
5008 err: &mut DiagnosticBuilder<'_>,
5009 directive: &ImportDirective<'_>,
5012 assert!(directive.is_nested());
5013 let message = "remove unnecessary import";
5015 // Two examples will be used to illustrate the span manipulations we're doing:
5017 // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is
5018 // `a` and `directive.use_span` is `issue_52891::{d, a, e};`.
5019 // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is
5020 // `a` and `directive.use_span` is `issue_52891::{d, e, a};`.
5022 let (found_closing_brace, span) = find_span_of_binding_until_next_binding(
5023 self.session, binding_span, directive.use_span,
5026 // If there was a closing brace then identify the span to remove any trailing commas from
5027 // previous imports.
5028 if found_closing_brace {
5029 if let Some(span) = extend_span_to_previous_binding(self.session, span) {
5030 err.tool_only_span_suggestion(span, message, String::new(),
5031 Applicability::MaybeIncorrect);
5033 // Remove the entire line if we cannot extend the span back, this indicates a
5034 // `issue_52891::{self}` case.
5035 err.span_suggestion(directive.use_span_with_attributes, message, String::new(),
5036 Applicability::MaybeIncorrect);
5042 err.span_suggestion(span, message, String::new(), Applicability::MachineApplicable);
5045 fn extern_prelude_get(&mut self, ident: Ident, speculative: bool)
5046 -> Option<&'a NameBinding<'a>> {
5047 if ident.is_path_segment_keyword() {
5048 // Make sure `self`, `super` etc produce an error when passed to here.
5051 self.extern_prelude.get(&ident.modern()).cloned().and_then(|entry| {
5052 if let Some(binding) = entry.extern_crate_item {
5053 if !speculative && entry.introduced_by_item {
5054 self.record_use(ident, TypeNS, binding, false);
5058 let crate_id = if !speculative {
5059 self.crate_loader.process_path_extern(ident.name, ident.span)
5060 } else if let Some(crate_id) =
5061 self.crate_loader.maybe_process_path_extern(ident.name, ident.span) {
5066 let crate_root = self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
5067 self.populate_module_if_necessary(&crate_root);
5068 Some((crate_root, ty::Visibility::Public, DUMMY_SP, ExpnId::root())
5069 .to_name_binding(self.arenas))
5075 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
5076 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
5079 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
5080 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
5083 fn names_to_string(idents: &[Ident]) -> String {
5084 let mut result = String::new();
5085 for (i, ident) in idents.iter()
5086 .filter(|ident| ident.name != kw::PathRoot)
5089 result.push_str("::");
5091 result.push_str(&ident.as_str());
5096 fn path_names_to_string(path: &Path) -> String {
5097 names_to_string(&path.segments.iter()
5098 .map(|seg| seg.ident)
5099 .collect::<Vec<_>>())
5102 /// A somewhat inefficient routine to obtain the name of a module.
5103 fn module_to_string(module: Module<'_>) -> Option<String> {
5104 let mut names = Vec::new();
5106 fn collect_mod(names: &mut Vec<Ident>, module: Module<'_>) {
5107 if let ModuleKind::Def(.., name) = module.kind {
5108 if let Some(parent) = module.parent {
5109 names.push(Ident::with_empty_ctxt(name));
5110 collect_mod(names, parent);
5113 // danger, shouldn't be ident?
5114 names.push(Ident::from_str("<opaque>"));
5115 collect_mod(names, module.parent.unwrap());
5118 collect_mod(&mut names, module);
5120 if names.is_empty() {
5123 Some(names_to_string(&names.into_iter()
5125 .collect::<Vec<_>>()))
5128 #[derive(Copy, Clone, Debug)]
5130 /// Do not issue the lint.
5133 /// This lint applies to some arbitrary path; e.g., `impl ::foo::Bar`.
5134 /// In this case, we can take the span of that path.
5137 /// This lint comes from a `use` statement. In this case, what we
5138 /// care about really is the *root* `use` statement; e.g., if we
5139 /// have nested things like `use a::{b, c}`, we care about the
5141 UsePath { root_id: NodeId, root_span: Span },
5143 /// This is the "trait item" from a fully qualified path. For example,
5144 /// we might be resolving `X::Y::Z` from a path like `<T as X::Y>::Z`.
5145 /// The `path_span` is the span of the to the trait itself (`X::Y`).
5146 QPathTrait { qpath_id: NodeId, qpath_span: Span },
5150 fn node_id(&self) -> Option<NodeId> {
5152 CrateLint::No => None,
5153 CrateLint::SimplePath(id) |
5154 CrateLint::UsePath { root_id: id, .. } |
5155 CrateLint::QPathTrait { qpath_id: id, .. } => Some(id),
5160 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }