]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/lib.rs
Auto merge of #68037 - msizanoen1:riscv-ci, r=alexcrichton
[rust.git] / src / librustc_resolve / lib.rs
1 //! This crate is responsible for the part of name resolution that doesn't require type checker.
2 //!
3 //! Module structure of the crate is built here.
4 //! Paths in macros, imports, expressions, types, patterns are resolved here.
5 //! Label and lifetime names are resolved here as well.
6 //!
7 //! Type-relative name resolution (methods, fields, associated items) happens in `librustc_typeck`.
8
9 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
10 #![feature(bool_to_option)]
11 #![feature(crate_visibility_modifier)]
12 #![feature(label_break_value)]
13 #![feature(nll)]
14 #![recursion_limit = "256"]
15
16 pub use rustc_hir::def::{Namespace, PerNS};
17
18 use Determinacy::*;
19
20 use rustc::hir::exports::ExportMap;
21 use rustc::hir::map::{DefKey, Definitions};
22 use rustc::lint;
23 use rustc::middle::cstore::{CrateStore, MetadataLoaderDyn};
24 use rustc::span_bug;
25 use rustc::ty::query::Providers;
26 use rustc::ty::{self, DefIdTree, ResolverOutputs};
27 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
28 use rustc_data_structures::ptr_key::PtrKey;
29 use rustc_data_structures::sync::Lrc;
30 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
31 use rustc_expand::base::SyntaxExtension;
32 use rustc_hir::def::Namespace::*;
33 use rustc_hir::def::{self, CtorOf, DefKind, NonMacroAttrKind, PartialRes};
34 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, CRATE_DEF_INDEX, LOCAL_CRATE};
35 use rustc_hir::PrimTy::{self, Bool, Char, Float, Int, Str, Uint};
36 use rustc_hir::{GlobMap, TraitMap};
37 use rustc_metadata::creader::{CStore, CrateLoader};
38 use rustc_session::lint::{BuiltinLintDiagnostics, LintBuffer};
39 use rustc_session::node_id::{NodeMap, NodeSet};
40 use rustc_session::Session;
41 use rustc_span::hygiene::{ExpnId, ExpnKind, MacroKind, SyntaxContext, Transparency};
42 use rustc_span::source_map::Spanned;
43 use rustc_span::symbol::{kw, sym};
44 use rustc_span::{Span, DUMMY_SP};
45 use syntax::ast::{self, FloatTy, Ident, IntTy, Name, NodeId, UintTy};
46 use syntax::ast::{Crate, CRATE_NODE_ID};
47 use syntax::ast::{ItemKind, Path};
48 use syntax::attr;
49 use syntax::print::pprust;
50 use syntax::unwrap_or;
51 use syntax::visit::{self, Visitor};
52
53 use log::debug;
54 use std::cell::{Cell, RefCell};
55 use std::collections::BTreeSet;
56 use std::{cmp, fmt, iter, ptr};
57
58 use diagnostics::{extend_span_to_previous_binding, find_span_of_binding_until_next_binding};
59 use diagnostics::{ImportSuggestion, Suggestion};
60 use imports::{ImportDirective, ImportDirectiveSubclass, ImportResolver, NameResolution};
61 use late::{HasGenericParams, PathSource, Rib, RibKind::*};
62 use macros::{LegacyBinding, LegacyScope};
63
64 use rustc_error_codes::*;
65
66 type Res = def::Res<NodeId>;
67
68 mod build_reduced_graph;
69 mod check_unused;
70 mod def_collector;
71 mod diagnostics;
72 mod imports;
73 mod late;
74 mod lifetimes;
75 mod macros;
76
77 enum Weak {
78     Yes,
79     No,
80 }
81
82 #[derive(Copy, Clone, PartialEq, Debug)]
83 pub enum Determinacy {
84     Determined,
85     Undetermined,
86 }
87
88 impl Determinacy {
89     fn determined(determined: bool) -> Determinacy {
90         if determined { Determinacy::Determined } else { Determinacy::Undetermined }
91     }
92 }
93
94 /// A specific scope in which a name can be looked up.
95 /// This enum is currently used only for early resolution (imports and macros),
96 /// but not for late resolution yet.
97 #[derive(Clone, Copy)]
98 enum Scope<'a> {
99     DeriveHelpers(ExpnId),
100     DeriveHelpersCompat,
101     MacroRules(LegacyScope<'a>),
102     CrateRoot,
103     Module(Module<'a>),
104     RegisteredAttrs,
105     MacroUsePrelude,
106     BuiltinAttrs,
107     ExternPrelude,
108     ToolPrelude,
109     StdLibPrelude,
110     BuiltinTypes,
111 }
112
113 /// Names from different contexts may want to visit different subsets of all specific scopes
114 /// with different restrictions when looking up the resolution.
115 /// This enum is currently used only for early resolution (imports and macros),
116 /// but not for late resolution yet.
117 enum ScopeSet {
118     /// All scopes with the given namespace.
119     All(Namespace, /*is_import*/ bool),
120     /// Crate root, then extern prelude (used for mixed 2015-2018 mode in macros).
121     AbsolutePath(Namespace),
122     /// All scopes with macro namespace and the given macro kind restriction.
123     Macro(MacroKind),
124 }
125
126 /// Everything you need to know about a name's location to resolve it.
127 /// Serves as a starting point for the scope visitor.
128 /// This struct is currently used only for early resolution (imports and macros),
129 /// but not for late resolution yet.
130 #[derive(Clone, Copy, Debug)]
131 pub struct ParentScope<'a> {
132     module: Module<'a>,
133     expansion: ExpnId,
134     legacy: LegacyScope<'a>,
135     derives: &'a [ast::Path],
136 }
137
138 impl<'a> ParentScope<'a> {
139     /// Creates a parent scope with the passed argument used as the module scope component,
140     /// and other scope components set to default empty values.
141     pub fn module(module: Module<'a>) -> ParentScope<'a> {
142         ParentScope { module, expansion: ExpnId::root(), legacy: LegacyScope::Empty, derives: &[] }
143     }
144 }
145
146 #[derive(Eq)]
147 struct BindingError {
148     name: Name,
149     origin: BTreeSet<Span>,
150     target: BTreeSet<Span>,
151     could_be_path: bool,
152 }
153
154 impl PartialOrd for BindingError {
155     fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> {
156         Some(self.cmp(other))
157     }
158 }
159
160 impl PartialEq for BindingError {
161     fn eq(&self, other: &BindingError) -> bool {
162         self.name == other.name
163     }
164 }
165
166 impl Ord for BindingError {
167     fn cmp(&self, other: &BindingError) -> cmp::Ordering {
168         self.name.cmp(&other.name)
169     }
170 }
171
172 enum ResolutionError<'a> {
173     /// Error E0401: can't use type or const parameters from outer function.
174     GenericParamsFromOuterFunction(Res, HasGenericParams),
175     /// Error E0403: the name is already used for a type or const parameter in this generic
176     /// parameter list.
177     NameAlreadyUsedInParameterList(Name, Span),
178     /// Error E0407: method is not a member of trait.
179     MethodNotMemberOfTrait(Name, &'a str),
180     /// Error E0437: type is not a member of trait.
181     TypeNotMemberOfTrait(Name, &'a str),
182     /// Error E0438: const is not a member of trait.
183     ConstNotMemberOfTrait(Name, &'a str),
184     /// Error E0408: variable `{}` is not bound in all patterns.
185     VariableNotBoundInPattern(&'a BindingError),
186     /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
187     VariableBoundWithDifferentMode(Name, Span),
188     /// Error E0415: identifier is bound more than once in this parameter list.
189     IdentifierBoundMoreThanOnceInParameterList(&'a str),
190     /// Error E0416: identifier is bound more than once in the same pattern.
191     IdentifierBoundMoreThanOnceInSamePattern(&'a str),
192     /// Error E0426: use of undeclared label.
193     UndeclaredLabel(&'a str, Option<Name>),
194     /// Error E0429: `self` imports are only allowed within a `{ }` list.
195     SelfImportsOnlyAllowedWithin,
196     /// Error E0430: `self` import can only appear once in the list.
197     SelfImportCanOnlyAppearOnceInTheList,
198     /// Error E0431: `self` import can only appear in an import list with a non-empty prefix.
199     SelfImportOnlyInImportListWithNonEmptyPrefix,
200     /// Error E0433: failed to resolve.
201     FailedToResolve { label: String, suggestion: Option<Suggestion> },
202     /// Error E0434: can't capture dynamic environment in a fn item.
203     CannotCaptureDynamicEnvironmentInFnItem,
204     /// Error E0435: attempt to use a non-constant value in a constant.
205     AttemptToUseNonConstantValueInConstant,
206     /// Error E0530: `X` bindings cannot shadow `Y`s.
207     BindingShadowsSomethingUnacceptable(&'a str, Name, &'a NameBinding<'a>),
208     /// Error E0128: type parameters with a default cannot use forward-declared identifiers.
209     ForwardDeclaredTyParam, // FIXME(const_generics:defaults)
210     /// Error E0735: type parameters with a default cannot use `Self`
211     SelfInTyParamDefault,
212 }
213
214 enum VisResolutionError<'a> {
215     Relative2018(Span, &'a ast::Path),
216     AncestorOnly(Span),
217     FailedToResolve(Span, String, Option<Suggestion>),
218     ExpectedFound(Span, String, Res),
219     Indeterminate(Span),
220     ModuleOnly(Span),
221 }
222
223 // A minimal representation of a path segment. We use this in resolve because
224 // we synthesize 'path segments' which don't have the rest of an AST or HIR
225 // `PathSegment`.
226 #[derive(Clone, Copy, Debug)]
227 pub struct Segment {
228     ident: Ident,
229     id: Option<NodeId>,
230 }
231
232 impl Segment {
233     fn from_path(path: &Path) -> Vec<Segment> {
234         path.segments.iter().map(|s| s.into()).collect()
235     }
236
237     fn from_ident(ident: Ident) -> Segment {
238         Segment { ident, id: None }
239     }
240
241     fn names_to_string(segments: &[Segment]) -> String {
242         names_to_string(&segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>())
243     }
244 }
245
246 impl<'a> From<&'a ast::PathSegment> for Segment {
247     fn from(seg: &'a ast::PathSegment) -> Segment {
248         Segment { ident: seg.ident, id: Some(seg.id) }
249     }
250 }
251
252 struct UsePlacementFinder {
253     target_module: NodeId,
254     span: Option<Span>,
255     found_use: bool,
256 }
257
258 impl UsePlacementFinder {
259     fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, bool) {
260         let mut finder = UsePlacementFinder { target_module, span: None, found_use: false };
261         visit::walk_crate(&mut finder, krate);
262         (finder.span, finder.found_use)
263     }
264 }
265
266 impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
267     fn visit_mod(
268         &mut self,
269         module: &'tcx ast::Mod,
270         _: Span,
271         _: &[ast::Attribute],
272         node_id: NodeId,
273     ) {
274         if self.span.is_some() {
275             return;
276         }
277         if node_id != self.target_module {
278             visit::walk_mod(self, module);
279             return;
280         }
281         // find a use statement
282         for item in &module.items {
283             match item.kind {
284                 ItemKind::Use(..) => {
285                     // don't suggest placing a use before the prelude
286                     // import or other generated ones
287                     if !item.span.from_expansion() {
288                         self.span = Some(item.span.shrink_to_lo());
289                         self.found_use = true;
290                         return;
291                     }
292                 }
293                 // don't place use before extern crate
294                 ItemKind::ExternCrate(_) => {}
295                 // but place them before the first other item
296                 _ => {
297                     if self.span.map_or(true, |span| item.span < span) {
298                         if !item.span.from_expansion() {
299                             // don't insert between attributes and an item
300                             if item.attrs.is_empty() {
301                                 self.span = Some(item.span.shrink_to_lo());
302                             } else {
303                                 // find the first attribute on the item
304                                 for attr in &item.attrs {
305                                     if self.span.map_or(true, |span| attr.span < span) {
306                                         self.span = Some(attr.span.shrink_to_lo());
307                                     }
308                                 }
309                             }
310                         }
311                     }
312                 }
313             }
314         }
315     }
316 }
317
318 /// An intermediate resolution result.
319 ///
320 /// This refers to the thing referred by a name. The difference between `Res` and `Item` is that
321 /// items are visible in their whole block, while `Res`es only from the place they are defined
322 /// forward.
323 #[derive(Debug)]
324 enum LexicalScopeBinding<'a> {
325     Item(&'a NameBinding<'a>),
326     Res(Res),
327 }
328
329 impl<'a> LexicalScopeBinding<'a> {
330     fn item(self) -> Option<&'a NameBinding<'a>> {
331         match self {
332             LexicalScopeBinding::Item(binding) => Some(binding),
333             _ => None,
334         }
335     }
336
337     fn res(self) -> Res {
338         match self {
339             LexicalScopeBinding::Item(binding) => binding.res(),
340             LexicalScopeBinding::Res(res) => res,
341         }
342     }
343 }
344
345 #[derive(Copy, Clone, Debug)]
346 enum ModuleOrUniformRoot<'a> {
347     /// Regular module.
348     Module(Module<'a>),
349
350     /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
351     CrateRootAndExternPrelude,
352
353     /// Virtual module that denotes resolution in extern prelude.
354     /// Used for paths starting with `::` on 2018 edition.
355     ExternPrelude,
356
357     /// Virtual module that denotes resolution in current scope.
358     /// Used only for resolving single-segment imports. The reason it exists is that import paths
359     /// are always split into two parts, the first of which should be some kind of module.
360     CurrentScope,
361 }
362
363 impl ModuleOrUniformRoot<'_> {
364     fn same_def(lhs: Self, rhs: Self) -> bool {
365         match (lhs, rhs) {
366             (ModuleOrUniformRoot::Module(lhs), ModuleOrUniformRoot::Module(rhs)) => {
367                 lhs.def_id() == rhs.def_id()
368             }
369             (
370                 ModuleOrUniformRoot::CrateRootAndExternPrelude,
371                 ModuleOrUniformRoot::CrateRootAndExternPrelude,
372             )
373             | (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude)
374             | (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true,
375             _ => false,
376         }
377     }
378 }
379
380 #[derive(Clone, Debug)]
381 enum PathResult<'a> {
382     Module(ModuleOrUniformRoot<'a>),
383     NonModule(PartialRes),
384     Indeterminate,
385     Failed {
386         span: Span,
387         label: String,
388         suggestion: Option<Suggestion>,
389         is_error_from_last_segment: bool,
390     },
391 }
392
393 enum ModuleKind {
394     /// An anonymous module; e.g., just a block.
395     ///
396     /// ```
397     /// fn main() {
398     ///     fn f() {} // (1)
399     ///     { // This is an anonymous module
400     ///         f(); // This resolves to (2) as we are inside the block.
401     ///         fn f() {} // (2)
402     ///     }
403     ///     f(); // Resolves to (1)
404     /// }
405     /// ```
406     Block(NodeId),
407     /// Any module with a name.
408     ///
409     /// This could be:
410     ///
411     /// * A normal module â€’ either `mod from_file;` or `mod from_block { }`.
412     /// * A trait or an enum (it implicitly contains associated types, methods and variant
413     ///   constructors).
414     Def(DefKind, DefId, Name),
415 }
416
417 impl ModuleKind {
418     /// Get name of the module.
419     pub fn name(&self) -> Option<Name> {
420         match self {
421             ModuleKind::Block(..) => None,
422             ModuleKind::Def(.., name) => Some(*name),
423         }
424     }
425 }
426
427 /// A key that identifies a binding in a given `Module`.
428 ///
429 /// Multiple bindings in the same module can have the same key (in a valid
430 /// program) if all but one of them come from glob imports.
431 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
432 struct BindingKey {
433     /// The identifier for the binding, aways the `modern` version of the
434     /// identifier.
435     ident: Ident,
436     ns: Namespace,
437     /// 0 if ident is not `_`, otherwise a value that's unique to the specific
438     /// `_` in the expanded AST that introduced this binding.
439     disambiguator: u32,
440 }
441
442 type Resolutions<'a> = RefCell<FxIndexMap<BindingKey, &'a RefCell<NameResolution<'a>>>>;
443
444 /// One node in the tree of modules.
445 pub struct ModuleData<'a> {
446     parent: Option<Module<'a>>,
447     kind: ModuleKind,
448
449     // The def id of the closest normal module (`mod`) ancestor (including this module).
450     normal_ancestor_id: DefId,
451
452     // Mapping between names and their (possibly in-progress) resolutions in this module.
453     // Resolutions in modules from other crates are not populated until accessed.
454     lazy_resolutions: Resolutions<'a>,
455     // True if this is a module from other crate that needs to be populated on access.
456     populate_on_access: Cell<bool>,
457
458     // Macro invocations that can expand into items in this module.
459     unexpanded_invocations: RefCell<FxHashSet<ExpnId>>,
460
461     no_implicit_prelude: bool,
462
463     glob_importers: RefCell<Vec<&'a ImportDirective<'a>>>,
464     globs: RefCell<Vec<&'a ImportDirective<'a>>>,
465
466     // Used to memoize the traits in this module for faster searches through all traits in scope.
467     traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
468
469     /// Span of the module itself. Used for error reporting.
470     span: Span,
471
472     expansion: ExpnId,
473 }
474
475 type Module<'a> = &'a ModuleData<'a>;
476
477 impl<'a> ModuleData<'a> {
478     fn new(
479         parent: Option<Module<'a>>,
480         kind: ModuleKind,
481         normal_ancestor_id: DefId,
482         expansion: ExpnId,
483         span: Span,
484     ) -> Self {
485         ModuleData {
486             parent,
487             kind,
488             normal_ancestor_id,
489             lazy_resolutions: Default::default(),
490             populate_on_access: Cell::new(!normal_ancestor_id.is_local()),
491             unexpanded_invocations: Default::default(),
492             no_implicit_prelude: false,
493             glob_importers: RefCell::new(Vec::new()),
494             globs: RefCell::new(Vec::new()),
495             traits: RefCell::new(None),
496             span,
497             expansion,
498         }
499     }
500
501     fn for_each_child<R, F>(&'a self, resolver: &mut R, mut f: F)
502     where
503         R: AsMut<Resolver<'a>>,
504         F: FnMut(&mut R, Ident, Namespace, &'a NameBinding<'a>),
505     {
506         for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
507             name_resolution.borrow().binding.map(|binding| f(resolver, key.ident, key.ns, binding));
508         }
509     }
510
511     fn res(&self) -> Option<Res> {
512         match self.kind {
513             ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
514             _ => None,
515         }
516     }
517
518     fn def_id(&self) -> Option<DefId> {
519         match self.kind {
520             ModuleKind::Def(_, def_id, _) => Some(def_id),
521             _ => None,
522         }
523     }
524
525     // `self` resolves to the first module ancestor that `is_normal`.
526     fn is_normal(&self) -> bool {
527         match self.kind {
528             ModuleKind::Def(DefKind::Mod, _, _) => true,
529             _ => false,
530         }
531     }
532
533     fn is_trait(&self) -> bool {
534         match self.kind {
535             ModuleKind::Def(DefKind::Trait, _, _) => true,
536             _ => false,
537         }
538     }
539
540     fn nearest_item_scope(&'a self) -> Module<'a> {
541         match self.kind {
542             ModuleKind::Def(DefKind::Enum, ..) | ModuleKind::Def(DefKind::Trait, ..) => {
543                 self.parent.expect("enum or trait module without a parent")
544             }
545             _ => self,
546         }
547     }
548
549     fn is_ancestor_of(&self, mut other: &Self) -> bool {
550         while !ptr::eq(self, other) {
551             if let Some(parent) = other.parent {
552                 other = parent;
553             } else {
554                 return false;
555             }
556         }
557         true
558     }
559 }
560
561 impl<'a> fmt::Debug for ModuleData<'a> {
562     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
563         write!(f, "{:?}", self.res())
564     }
565 }
566
567 /// Records a possibly-private value, type, or module definition.
568 #[derive(Clone, Debug)]
569 pub struct NameBinding<'a> {
570     kind: NameBindingKind<'a>,
571     ambiguity: Option<(&'a NameBinding<'a>, AmbiguityKind)>,
572     expansion: ExpnId,
573     span: Span,
574     vis: ty::Visibility,
575 }
576
577 pub trait ToNameBinding<'a> {
578     fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
579 }
580
581 impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
582     fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
583         self
584     }
585 }
586
587 #[derive(Clone, Debug)]
588 enum NameBindingKind<'a> {
589     Res(Res, /* is_macro_export */ bool),
590     Module(Module<'a>),
591     Import { binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>, used: Cell<bool> },
592 }
593
594 impl<'a> NameBindingKind<'a> {
595     /// Is this a name binding of a import?
596     fn is_import(&self) -> bool {
597         match *self {
598             NameBindingKind::Import { .. } => true,
599             _ => false,
600         }
601     }
602 }
603
604 struct PrivacyError<'a> {
605     ident: Ident,
606     binding: &'a NameBinding<'a>,
607     dedup_span: Span,
608 }
609
610 struct UseError<'a> {
611     err: DiagnosticBuilder<'a>,
612     /// Attach `use` statements for these candidates.
613     candidates: Vec<ImportSuggestion>,
614     /// The `NodeId` of the module to place the use-statements in.
615     node_id: NodeId,
616     /// Whether the diagnostic should state that it's "better".
617     better: bool,
618 }
619
620 #[derive(Clone, Copy, PartialEq, Debug)]
621 enum AmbiguityKind {
622     Import,
623     BuiltinAttr,
624     DeriveHelper,
625     LegacyVsModern,
626     GlobVsOuter,
627     GlobVsGlob,
628     GlobVsExpanded,
629     MoreExpandedVsOuter,
630 }
631
632 impl AmbiguityKind {
633     fn descr(self) -> &'static str {
634         match self {
635             AmbiguityKind::Import => "name vs any other name during import resolution",
636             AmbiguityKind::BuiltinAttr => "built-in attribute vs any other name",
637             AmbiguityKind::DeriveHelper => "derive helper attribute vs any other name",
638             AmbiguityKind::LegacyVsModern => "`macro_rules` vs non-`macro_rules` from other module",
639             AmbiguityKind::GlobVsOuter => {
640                 "glob import vs any other name from outer scope during import/macro resolution"
641             }
642             AmbiguityKind::GlobVsGlob => "glob import vs glob import in the same module",
643             AmbiguityKind::GlobVsExpanded => {
644                 "glob import vs macro-expanded name in the same \
645                  module during import/macro resolution"
646             }
647             AmbiguityKind::MoreExpandedVsOuter => {
648                 "macro-expanded name vs less macro-expanded name \
649                  from outer scope during import/macro resolution"
650             }
651         }
652     }
653 }
654
655 /// Miscellaneous bits of metadata for better ambiguity error reporting.
656 #[derive(Clone, Copy, PartialEq)]
657 enum AmbiguityErrorMisc {
658     SuggestCrate,
659     SuggestSelf,
660     FromPrelude,
661     None,
662 }
663
664 struct AmbiguityError<'a> {
665     kind: AmbiguityKind,
666     ident: Ident,
667     b1: &'a NameBinding<'a>,
668     b2: &'a NameBinding<'a>,
669     misc1: AmbiguityErrorMisc,
670     misc2: AmbiguityErrorMisc,
671 }
672
673 impl<'a> NameBinding<'a> {
674     fn module(&self) -> Option<Module<'a>> {
675         match self.kind {
676             NameBindingKind::Module(module) => Some(module),
677             NameBindingKind::Import { binding, .. } => binding.module(),
678             _ => None,
679         }
680     }
681
682     fn res(&self) -> Res {
683         match self.kind {
684             NameBindingKind::Res(res, _) => res,
685             NameBindingKind::Module(module) => module.res().unwrap(),
686             NameBindingKind::Import { binding, .. } => binding.res(),
687         }
688     }
689
690     fn is_ambiguity(&self) -> bool {
691         self.ambiguity.is_some()
692             || match self.kind {
693                 NameBindingKind::Import { binding, .. } => binding.is_ambiguity(),
694                 _ => false,
695             }
696     }
697
698     // We sometimes need to treat variants as `pub` for backwards compatibility.
699     fn pseudo_vis(&self) -> ty::Visibility {
700         if self.is_variant() && self.res().def_id().is_local() {
701             ty::Visibility::Public
702         } else {
703             self.vis
704         }
705     }
706
707     fn is_variant(&self) -> bool {
708         match self.kind {
709             NameBindingKind::Res(Res::Def(DefKind::Variant, _), _)
710             | NameBindingKind::Res(Res::Def(DefKind::Ctor(CtorOf::Variant, ..), _), _) => true,
711             _ => false,
712         }
713     }
714
715     fn is_extern_crate(&self) -> bool {
716         match self.kind {
717             NameBindingKind::Import {
718                 directive:
719                     &ImportDirective { subclass: ImportDirectiveSubclass::ExternCrate { .. }, .. },
720                 ..
721             } => true,
722             NameBindingKind::Module(&ModuleData {
723                 kind: ModuleKind::Def(DefKind::Mod, def_id, _),
724                 ..
725             }) => def_id.index == CRATE_DEF_INDEX,
726             _ => false,
727         }
728     }
729
730     fn is_import(&self) -> bool {
731         match self.kind {
732             NameBindingKind::Import { .. } => true,
733             _ => false,
734         }
735     }
736
737     fn is_glob_import(&self) -> bool {
738         match self.kind {
739             NameBindingKind::Import { directive, .. } => directive.is_glob(),
740             _ => false,
741         }
742     }
743
744     fn is_importable(&self) -> bool {
745         match self.res() {
746             Res::Def(DefKind::AssocConst, _)
747             | Res::Def(DefKind::Method, _)
748             | Res::Def(DefKind::AssocTy, _) => false,
749             _ => true,
750         }
751     }
752
753     fn is_macro_def(&self) -> bool {
754         match self.kind {
755             NameBindingKind::Res(Res::Def(DefKind::Macro(..), _), _) => true,
756             _ => false,
757         }
758     }
759
760     fn macro_kind(&self) -> Option<MacroKind> {
761         self.res().macro_kind()
762     }
763
764     // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
765     // at some expansion round `max(invoc, binding)` when they both emerged from macros.
766     // Then this function returns `true` if `self` may emerge from a macro *after* that
767     // in some later round and screw up our previously found resolution.
768     // See more detailed explanation in
769     // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
770     fn may_appear_after(&self, invoc_parent_expansion: ExpnId, binding: &NameBinding<'_>) -> bool {
771         // self > max(invoc, binding) => !(self <= invoc || self <= binding)
772         // Expansions are partially ordered, so "may appear after" is an inversion of
773         // "certainly appears before or simultaneously" and includes unordered cases.
774         let self_parent_expansion = self.expansion;
775         let other_parent_expansion = binding.expansion;
776         let certainly_before_other_or_simultaneously =
777             other_parent_expansion.is_descendant_of(self_parent_expansion);
778         let certainly_before_invoc_or_simultaneously =
779             invoc_parent_expansion.is_descendant_of(self_parent_expansion);
780         !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
781     }
782 }
783
784 /// Interns the names of the primitive types.
785 ///
786 /// All other types are defined somewhere and possibly imported, but the primitive ones need
787 /// special handling, since they have no place of origin.
788 struct PrimitiveTypeTable {
789     primitive_types: FxHashMap<Name, PrimTy>,
790 }
791
792 impl PrimitiveTypeTable {
793     fn new() -> PrimitiveTypeTable {
794         let mut table = FxHashMap::default();
795
796         table.insert(sym::bool, Bool);
797         table.insert(sym::char, Char);
798         table.insert(sym::f32, Float(FloatTy::F32));
799         table.insert(sym::f64, Float(FloatTy::F64));
800         table.insert(sym::isize, Int(IntTy::Isize));
801         table.insert(sym::i8, Int(IntTy::I8));
802         table.insert(sym::i16, Int(IntTy::I16));
803         table.insert(sym::i32, Int(IntTy::I32));
804         table.insert(sym::i64, Int(IntTy::I64));
805         table.insert(sym::i128, Int(IntTy::I128));
806         table.insert(sym::str, Str);
807         table.insert(sym::usize, Uint(UintTy::Usize));
808         table.insert(sym::u8, Uint(UintTy::U8));
809         table.insert(sym::u16, Uint(UintTy::U16));
810         table.insert(sym::u32, Uint(UintTy::U32));
811         table.insert(sym::u64, Uint(UintTy::U64));
812         table.insert(sym::u128, Uint(UintTy::U128));
813         Self { primitive_types: table }
814     }
815 }
816
817 #[derive(Debug, Default, Clone)]
818 pub struct ExternPreludeEntry<'a> {
819     extern_crate_item: Option<&'a NameBinding<'a>>,
820     pub introduced_by_item: bool,
821 }
822
823 /// The main resolver class.
824 ///
825 /// This is the visitor that walks the whole crate.
826 pub struct Resolver<'a> {
827     session: &'a Session,
828
829     definitions: Definitions,
830
831     graph_root: Module<'a>,
832
833     prelude: Option<Module<'a>>,
834     extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
835
836     /// N.B., this is used only for better diagnostics, not name resolution itself.
837     has_self: FxHashSet<DefId>,
838
839     /// Names of fields of an item `DefId` accessible with dot syntax.
840     /// Used for hints during error reporting.
841     field_names: FxHashMap<DefId, Vec<Spanned<Name>>>,
842
843     /// All imports known to succeed or fail.
844     determined_imports: Vec<&'a ImportDirective<'a>>,
845
846     /// All non-determined imports.
847     indeterminate_imports: Vec<&'a ImportDirective<'a>>,
848
849     /// FIXME: Refactor things so that these fields are passed through arguments and not resolver.
850     /// We are resolving a last import segment during import validation.
851     last_import_segment: bool,
852     /// This binding should be ignored during in-module resolution, so that we don't get
853     /// "self-confirming" import resolutions during import validation.
854     blacklisted_binding: Option<&'a NameBinding<'a>>,
855
856     /// The idents for the primitive types.
857     primitive_type_table: PrimitiveTypeTable,
858
859     /// Resolutions for nodes that have a single resolution.
860     partial_res_map: NodeMap<PartialRes>,
861     /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
862     import_res_map: NodeMap<PerNS<Option<Res>>>,
863     /// Resolutions for labels (node IDs of their corresponding blocks or loops).
864     label_res_map: NodeMap<NodeId>,
865
866     /// `CrateNum` resolutions of `extern crate` items.
867     extern_crate_map: NodeMap<CrateNum>,
868     export_map: ExportMap<NodeId>,
869     trait_map: TraitMap,
870
871     /// A map from nodes to anonymous modules.
872     /// Anonymous modules are pseudo-modules that are implicitly created around items
873     /// contained within blocks.
874     ///
875     /// For example, if we have this:
876     ///
877     ///  fn f() {
878     ///      fn g() {
879     ///          ...
880     ///      }
881     ///  }
882     ///
883     /// There will be an anonymous module created around `g` with the ID of the
884     /// entry block for `f`.
885     block_map: NodeMap<Module<'a>>,
886     /// A fake module that contains no definition and no prelude. Used so that
887     /// some AST passes can generate identifiers that only resolve to local or
888     /// language items.
889     empty_module: Module<'a>,
890     module_map: FxHashMap<DefId, Module<'a>>,
891     extern_module_map: FxHashMap<DefId, Module<'a>>,
892     binding_parent_modules: FxHashMap<PtrKey<'a, NameBinding<'a>>, Module<'a>>,
893     underscore_disambiguator: u32,
894
895     /// Maps glob imports to the names of items actually imported.
896     glob_map: GlobMap,
897
898     used_imports: FxHashSet<(NodeId, Namespace)>,
899     maybe_unused_trait_imports: NodeSet,
900     maybe_unused_extern_crates: Vec<(NodeId, Span)>,
901
902     /// Privacy errors are delayed until the end in order to deduplicate them.
903     privacy_errors: Vec<PrivacyError<'a>>,
904     /// Ambiguity errors are delayed for deduplication.
905     ambiguity_errors: Vec<AmbiguityError<'a>>,
906     /// `use` injections are delayed for better placement and deduplication.
907     use_injections: Vec<UseError<'a>>,
908     /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
909     macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
910
911     arenas: &'a ResolverArenas<'a>,
912     dummy_binding: &'a NameBinding<'a>,
913
914     crate_loader: CrateLoader<'a>,
915     macro_names: FxHashSet<Ident>,
916     builtin_macros: FxHashMap<Name, SyntaxExtension>,
917     registered_attrs: FxHashSet<Ident>,
918     registered_tools: FxHashSet<Ident>,
919     macro_use_prelude: FxHashMap<Name, &'a NameBinding<'a>>,
920     all_macros: FxHashMap<Name, Res>,
921     macro_map: FxHashMap<DefId, Lrc<SyntaxExtension>>,
922     dummy_ext_bang: Lrc<SyntaxExtension>,
923     dummy_ext_derive: Lrc<SyntaxExtension>,
924     non_macro_attrs: [Lrc<SyntaxExtension>; 2],
925     macro_defs: FxHashMap<ExpnId, DefId>,
926     local_macro_def_scopes: FxHashMap<NodeId, Module<'a>>,
927     ast_transform_scopes: FxHashMap<ExpnId, Module<'a>>,
928     unused_macros: NodeMap<Span>,
929     proc_macro_stubs: NodeSet,
930     /// Traces collected during macro resolution and validated when it's complete.
931     single_segment_macro_resolutions:
932         Vec<(Ident, MacroKind, ParentScope<'a>, Option<&'a NameBinding<'a>>)>,
933     multi_segment_macro_resolutions:
934         Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>, Option<Res>)>,
935     builtin_attrs: Vec<(Ident, ParentScope<'a>)>,
936     /// `derive(Copy)` marks items they are applied to so they are treated specially later.
937     /// Derive macros cannot modify the item themselves and have to store the markers in the global
938     /// context, so they attach the markers to derive container IDs using this resolver table.
939     containers_deriving_copy: FxHashSet<ExpnId>,
940     /// Parent scopes in which the macros were invoked.
941     /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere.
942     invocation_parent_scopes: FxHashMap<ExpnId, ParentScope<'a>>,
943     /// Legacy scopes *produced* by expanding the macro invocations,
944     /// include all the `macro_rules` items and other invocations generated by them.
945     output_legacy_scopes: FxHashMap<ExpnId, LegacyScope<'a>>,
946     /// Helper attributes that are in scope for the given expansion.
947     helper_attrs: FxHashMap<ExpnId, Vec<Ident>>,
948
949     /// Avoid duplicated errors for "name already defined".
950     name_already_seen: FxHashMap<Name, Span>,
951
952     potentially_unused_imports: Vec<&'a ImportDirective<'a>>,
953
954     /// Table for mapping struct IDs into struct constructor IDs,
955     /// it's not used during normal resolution, only for better error reporting.
956     struct_constructors: DefIdMap<(Res, ty::Visibility)>,
957
958     /// Features enabled for this crate.
959     active_features: FxHashSet<Name>,
960
961     /// Stores enum visibilities to properly build a reduced graph
962     /// when visiting the correspondent variants.
963     variant_vis: DefIdMap<ty::Visibility>,
964
965     lint_buffer: LintBuffer,
966
967     next_node_id: NodeId,
968 }
969
970 /// Nothing really interesting here; it just provides memory for the rest of the crate.
971 #[derive(Default)]
972 pub struct ResolverArenas<'a> {
973     modules: arena::TypedArena<ModuleData<'a>>,
974     local_modules: RefCell<Vec<Module<'a>>>,
975     name_bindings: arena::TypedArena<NameBinding<'a>>,
976     import_directives: arena::TypedArena<ImportDirective<'a>>,
977     name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
978     legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
979     ast_paths: arena::TypedArena<ast::Path>,
980 }
981
982 impl<'a> ResolverArenas<'a> {
983     fn alloc_module(&'a self, module: ModuleData<'a>) -> Module<'a> {
984         let module = self.modules.alloc(module);
985         if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) {
986             self.local_modules.borrow_mut().push(module);
987         }
988         module
989     }
990     fn local_modules(&'a self) -> std::cell::Ref<'a, Vec<Module<'a>>> {
991         self.local_modules.borrow()
992     }
993     fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
994         self.name_bindings.alloc(name_binding)
995     }
996     fn alloc_import_directive(
997         &'a self,
998         import_directive: ImportDirective<'a>,
999     ) -> &'a ImportDirective<'_> {
1000         self.import_directives.alloc(import_directive)
1001     }
1002     fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1003         self.name_resolutions.alloc(Default::default())
1004     }
1005     fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
1006         self.legacy_bindings.alloc(binding)
1007     }
1008     fn alloc_ast_paths(&'a self, paths: &[ast::Path]) -> &'a [ast::Path] {
1009         self.ast_paths.alloc_from_iter(paths.iter().cloned())
1010     }
1011 }
1012
1013 impl<'a> AsMut<Resolver<'a>> for Resolver<'a> {
1014     fn as_mut(&mut self) -> &mut Resolver<'a> {
1015         self
1016     }
1017 }
1018
1019 impl<'a, 'b> DefIdTree for &'a Resolver<'b> {
1020     fn parent(self, id: DefId) -> Option<DefId> {
1021         match id.krate {
1022             LOCAL_CRATE => self.definitions.def_key(id.index).parent,
1023             _ => self.cstore().def_key(id).parent,
1024         }
1025         .map(|index| DefId { index, ..id })
1026     }
1027 }
1028
1029 /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that
1030 /// the resolver is no longer needed as all the relevant information is inline.
1031 impl rustc_ast_lowering::Resolver for Resolver<'_> {
1032     fn def_key(&mut self, id: DefId) -> DefKey {
1033         if id.is_local() { self.definitions().def_key(id.index) } else { self.cstore().def_key(id) }
1034     }
1035
1036     fn item_generics_num_lifetimes(&self, def_id: DefId, sess: &Session) -> usize {
1037         self.cstore().item_generics_num_lifetimes(def_id, sess)
1038     }
1039
1040     fn resolve_str_path(
1041         &mut self,
1042         span: Span,
1043         crate_root: Option<Name>,
1044         components: &[Name],
1045         ns: Namespace,
1046     ) -> (ast::Path, Res) {
1047         let root = if crate_root.is_some() { kw::PathRoot } else { kw::Crate };
1048         let segments = iter::once(Ident::with_dummy_span(root))
1049             .chain(
1050                 crate_root
1051                     .into_iter()
1052                     .chain(components.iter().cloned())
1053                     .map(Ident::with_dummy_span),
1054             )
1055             .map(|i| self.new_ast_path_segment(i))
1056             .collect::<Vec<_>>();
1057
1058         let path = ast::Path { span, segments };
1059
1060         let parent_scope = &ParentScope::module(self.graph_root);
1061         let res = match self.resolve_ast_path(&path, ns, parent_scope) {
1062             Ok(res) => res,
1063             Err((span, error)) => {
1064                 self.report_error(span, error);
1065                 Res::Err
1066             }
1067         };
1068         (path, res)
1069     }
1070
1071     fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes> {
1072         self.partial_res_map.get(&id).cloned()
1073     }
1074
1075     fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res>> {
1076         self.import_res_map.get(&id).cloned().unwrap_or_default()
1077     }
1078
1079     fn get_label_res(&mut self, id: NodeId) -> Option<NodeId> {
1080         self.label_res_map.get(&id).cloned()
1081     }
1082
1083     fn definitions(&mut self) -> &mut Definitions {
1084         &mut self.definitions
1085     }
1086
1087     fn lint_buffer(&mut self) -> &mut LintBuffer {
1088         &mut self.lint_buffer
1089     }
1090
1091     fn next_node_id(&mut self) -> NodeId {
1092         self.next_node_id()
1093     }
1094 }
1095
1096 impl<'a> Resolver<'a> {
1097     pub fn new(
1098         session: &'a Session,
1099         krate: &Crate,
1100         crate_name: &str,
1101         metadata_loader: &'a MetadataLoaderDyn,
1102         arenas: &'a ResolverArenas<'a>,
1103     ) -> Resolver<'a> {
1104         let root_def_id = DefId::local(CRATE_DEF_INDEX);
1105         let root_module_kind = ModuleKind::Def(DefKind::Mod, root_def_id, kw::Invalid);
1106         let graph_root = arenas.alloc_module(ModuleData {
1107             no_implicit_prelude: attr::contains_name(&krate.attrs, sym::no_implicit_prelude),
1108             ..ModuleData::new(None, root_module_kind, root_def_id, ExpnId::root(), krate.span)
1109         });
1110         let empty_module_kind = ModuleKind::Def(DefKind::Mod, root_def_id, kw::Invalid);
1111         let empty_module = arenas.alloc_module(ModuleData {
1112             no_implicit_prelude: true,
1113             ..ModuleData::new(
1114                 Some(graph_root),
1115                 empty_module_kind,
1116                 root_def_id,
1117                 ExpnId::root(),
1118                 DUMMY_SP,
1119             )
1120         });
1121         let mut module_map = FxHashMap::default();
1122         module_map.insert(DefId::local(CRATE_DEF_INDEX), graph_root);
1123
1124         let mut definitions = Definitions::default();
1125         definitions.create_root_def(crate_name, session.local_crate_disambiguator());
1126
1127         let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'_>> = session
1128             .opts
1129             .externs
1130             .iter()
1131             .filter(|(_, entry)| entry.add_prelude)
1132             .map(|(name, _)| (Ident::from_str(name), Default::default()))
1133             .collect();
1134
1135         if !attr::contains_name(&krate.attrs, sym::no_core) {
1136             extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default());
1137             if !attr::contains_name(&krate.attrs, sym::no_std) {
1138                 extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default());
1139                 if session.rust_2018() {
1140                     extern_prelude.insert(Ident::with_dummy_span(sym::meta), Default::default());
1141                 }
1142             }
1143         }
1144
1145         let (registered_attrs, registered_tools) =
1146             macros::registered_attrs_and_tools(session, &krate.attrs);
1147
1148         let mut invocation_parent_scopes = FxHashMap::default();
1149         invocation_parent_scopes.insert(ExpnId::root(), ParentScope::module(graph_root));
1150
1151         let mut macro_defs = FxHashMap::default();
1152         macro_defs.insert(ExpnId::root(), root_def_id);
1153
1154         let features = session.features_untracked();
1155         let non_macro_attr =
1156             |mark_used| Lrc::new(SyntaxExtension::non_macro_attr(mark_used, session.edition()));
1157
1158         Resolver {
1159             session,
1160
1161             definitions,
1162
1163             // The outermost module has def ID 0; this is not reflected in the
1164             // AST.
1165             graph_root,
1166             prelude: None,
1167             extern_prelude,
1168
1169             has_self: FxHashSet::default(),
1170             field_names: FxHashMap::default(),
1171
1172             determined_imports: Vec::new(),
1173             indeterminate_imports: Vec::new(),
1174
1175             last_import_segment: false,
1176             blacklisted_binding: None,
1177
1178             primitive_type_table: PrimitiveTypeTable::new(),
1179
1180             partial_res_map: Default::default(),
1181             import_res_map: Default::default(),
1182             label_res_map: Default::default(),
1183             extern_crate_map: Default::default(),
1184             export_map: FxHashMap::default(),
1185             trait_map: Default::default(),
1186             underscore_disambiguator: 0,
1187             empty_module,
1188             module_map,
1189             block_map: Default::default(),
1190             extern_module_map: FxHashMap::default(),
1191             binding_parent_modules: FxHashMap::default(),
1192             ast_transform_scopes: FxHashMap::default(),
1193
1194             glob_map: Default::default(),
1195
1196             used_imports: FxHashSet::default(),
1197             maybe_unused_trait_imports: Default::default(),
1198             maybe_unused_extern_crates: Vec::new(),
1199
1200             privacy_errors: Vec::new(),
1201             ambiguity_errors: Vec::new(),
1202             use_injections: Vec::new(),
1203             macro_expanded_macro_export_errors: BTreeSet::new(),
1204
1205             arenas,
1206             dummy_binding: arenas.alloc_name_binding(NameBinding {
1207                 kind: NameBindingKind::Res(Res::Err, false),
1208                 ambiguity: None,
1209                 expansion: ExpnId::root(),
1210                 span: DUMMY_SP,
1211                 vis: ty::Visibility::Public,
1212             }),
1213
1214             crate_loader: CrateLoader::new(session, metadata_loader, crate_name),
1215             macro_names: FxHashSet::default(),
1216             builtin_macros: Default::default(),
1217             registered_attrs,
1218             registered_tools,
1219             macro_use_prelude: FxHashMap::default(),
1220             all_macros: FxHashMap::default(),
1221             macro_map: FxHashMap::default(),
1222             dummy_ext_bang: Lrc::new(SyntaxExtension::dummy_bang(session.edition())),
1223             dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(session.edition())),
1224             non_macro_attrs: [non_macro_attr(false), non_macro_attr(true)],
1225             invocation_parent_scopes,
1226             output_legacy_scopes: Default::default(),
1227             helper_attrs: Default::default(),
1228             macro_defs,
1229             local_macro_def_scopes: FxHashMap::default(),
1230             name_already_seen: FxHashMap::default(),
1231             potentially_unused_imports: Vec::new(),
1232             struct_constructors: Default::default(),
1233             unused_macros: Default::default(),
1234             proc_macro_stubs: Default::default(),
1235             single_segment_macro_resolutions: Default::default(),
1236             multi_segment_macro_resolutions: Default::default(),
1237             builtin_attrs: Default::default(),
1238             containers_deriving_copy: Default::default(),
1239             active_features: features
1240                 .declared_lib_features
1241                 .iter()
1242                 .map(|(feat, ..)| *feat)
1243                 .chain(features.declared_lang_features.iter().map(|(feat, ..)| *feat))
1244                 .collect(),
1245             variant_vis: Default::default(),
1246             lint_buffer: LintBuffer::default(),
1247             next_node_id: NodeId::from_u32(1),
1248         }
1249     }
1250
1251     pub fn next_node_id(&mut self) -> NodeId {
1252         let next = self
1253             .next_node_id
1254             .as_usize()
1255             .checked_add(1)
1256             .expect("input too large; ran out of NodeIds");
1257         self.next_node_id = ast::NodeId::from_usize(next);
1258         self.next_node_id
1259     }
1260
1261     pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1262         &mut self.lint_buffer
1263     }
1264
1265     pub fn arenas() -> ResolverArenas<'a> {
1266         Default::default()
1267     }
1268
1269     pub fn into_outputs(self) -> ResolverOutputs {
1270         ResolverOutputs {
1271             definitions: self.definitions,
1272             cstore: Box::new(self.crate_loader.into_cstore()),
1273             extern_crate_map: self.extern_crate_map,
1274             export_map: self.export_map,
1275             trait_map: self.trait_map,
1276             glob_map: self.glob_map,
1277             maybe_unused_trait_imports: self.maybe_unused_trait_imports,
1278             maybe_unused_extern_crates: self.maybe_unused_extern_crates,
1279             extern_prelude: self
1280                 .extern_prelude
1281                 .iter()
1282                 .map(|(ident, entry)| (ident.name, entry.introduced_by_item))
1283                 .collect(),
1284         }
1285     }
1286
1287     pub fn clone_outputs(&self) -> ResolverOutputs {
1288         ResolverOutputs {
1289             definitions: self.definitions.clone(),
1290             cstore: Box::new(self.cstore().clone()),
1291             extern_crate_map: self.extern_crate_map.clone(),
1292             export_map: self.export_map.clone(),
1293             trait_map: self.trait_map.clone(),
1294             glob_map: self.glob_map.clone(),
1295             maybe_unused_trait_imports: self.maybe_unused_trait_imports.clone(),
1296             maybe_unused_extern_crates: self.maybe_unused_extern_crates.clone(),
1297             extern_prelude: self
1298                 .extern_prelude
1299                 .iter()
1300                 .map(|(ident, entry)| (ident.name, entry.introduced_by_item))
1301                 .collect(),
1302         }
1303     }
1304
1305     pub fn cstore(&self) -> &CStore {
1306         self.crate_loader.cstore()
1307     }
1308
1309     fn non_macro_attr(&self, mark_used: bool) -> Lrc<SyntaxExtension> {
1310         self.non_macro_attrs[mark_used as usize].clone()
1311     }
1312
1313     fn dummy_ext(&self, macro_kind: MacroKind) -> Lrc<SyntaxExtension> {
1314         match macro_kind {
1315             MacroKind::Bang => self.dummy_ext_bang.clone(),
1316             MacroKind::Derive => self.dummy_ext_derive.clone(),
1317             MacroKind::Attr => self.non_macro_attr(true),
1318         }
1319     }
1320
1321     /// Runs the function on each namespace.
1322     fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1323         f(self, TypeNS);
1324         f(self, ValueNS);
1325         f(self, MacroNS);
1326     }
1327
1328     fn is_builtin_macro(&mut self, res: Res) -> bool {
1329         self.get_macro(res).map_or(false, |ext| ext.is_builtin)
1330     }
1331
1332     fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1333         loop {
1334             match self.macro_defs.get(&ctxt.outer_expn()) {
1335                 Some(&def_id) => return def_id,
1336                 None => ctxt.remove_mark(),
1337             };
1338         }
1339     }
1340
1341     /// Entry point to crate resolution.
1342     pub fn resolve_crate(&mut self, krate: &Crate) {
1343         let _prof_timer = self.session.prof.generic_activity("resolve_crate");
1344
1345         ImportResolver { r: self }.finalize_imports();
1346         self.finalize_macro_resolutions();
1347
1348         self.late_resolve_crate(krate);
1349
1350         self.check_unused(krate);
1351         self.report_errors(krate);
1352         self.crate_loader.postprocess(krate);
1353     }
1354
1355     fn new_module(
1356         &self,
1357         parent: Module<'a>,
1358         kind: ModuleKind,
1359         normal_ancestor_id: DefId,
1360         expn_id: ExpnId,
1361         span: Span,
1362     ) -> Module<'a> {
1363         let module = ModuleData::new(Some(parent), kind, normal_ancestor_id, expn_id, span);
1364         self.arenas.alloc_module(module)
1365     }
1366
1367     fn new_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey {
1368         let ident = ident.modern();
1369         let disambiguator = if ident.name == kw::Underscore {
1370             self.underscore_disambiguator += 1;
1371             self.underscore_disambiguator
1372         } else {
1373             0
1374         };
1375         BindingKey { ident, ns, disambiguator }
1376     }
1377
1378     fn resolutions(&mut self, module: Module<'a>) -> &'a Resolutions<'a> {
1379         if module.populate_on_access.get() {
1380             module.populate_on_access.set(false);
1381             self.build_reduced_graph_external(module);
1382         }
1383         &module.lazy_resolutions
1384     }
1385
1386     fn resolution(
1387         &mut self,
1388         module: Module<'a>,
1389         key: BindingKey,
1390     ) -> &'a RefCell<NameResolution<'a>> {
1391         *self
1392             .resolutions(module)
1393             .borrow_mut()
1394             .entry(key)
1395             .or_insert_with(|| self.arenas.alloc_name_resolution())
1396     }
1397
1398     fn record_use(
1399         &mut self,
1400         ident: Ident,
1401         ns: Namespace,
1402         used_binding: &'a NameBinding<'a>,
1403         is_lexical_scope: bool,
1404     ) {
1405         if let Some((b2, kind)) = used_binding.ambiguity {
1406             self.ambiguity_errors.push(AmbiguityError {
1407                 kind,
1408                 ident,
1409                 b1: used_binding,
1410                 b2,
1411                 misc1: AmbiguityErrorMisc::None,
1412                 misc2: AmbiguityErrorMisc::None,
1413             });
1414         }
1415         if let NameBindingKind::Import { directive, binding, ref used } = used_binding.kind {
1416             // Avoid marking `extern crate` items that refer to a name from extern prelude,
1417             // but not introduce it, as used if they are accessed from lexical scope.
1418             if is_lexical_scope {
1419                 if let Some(entry) = self.extern_prelude.get(&ident.modern()) {
1420                     if let Some(crate_item) = entry.extern_crate_item {
1421                         if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
1422                             return;
1423                         }
1424                     }
1425                 }
1426             }
1427             used.set(true);
1428             directive.used.set(true);
1429             self.used_imports.insert((directive.id, ns));
1430             self.add_to_glob_map(&directive, ident);
1431             self.record_use(ident, ns, binding, false);
1432         }
1433     }
1434
1435     #[inline]
1436     fn add_to_glob_map(&mut self, directive: &ImportDirective<'_>, ident: Ident) {
1437         if directive.is_glob() {
1438             self.glob_map.entry(directive.id).or_default().insert(ident.name);
1439         }
1440     }
1441
1442     /// A generic scope visitor.
1443     /// Visits scopes in order to resolve some identifier in them or perform other actions.
1444     /// If the callback returns `Some` result, we stop visiting scopes and return it.
1445     fn visit_scopes<T>(
1446         &mut self,
1447         scope_set: ScopeSet,
1448         parent_scope: &ParentScope<'a>,
1449         ident: Ident,
1450         mut visitor: impl FnMut(&mut Self, Scope<'a>, /*use_prelude*/ bool, Ident) -> Option<T>,
1451     ) -> Option<T> {
1452         // General principles:
1453         // 1. Not controlled (user-defined) names should have higher priority than controlled names
1454         //    built into the language or standard library. This way we can add new names into the
1455         //    language or standard library without breaking user code.
1456         // 2. "Closed set" below means new names cannot appear after the current resolution attempt.
1457         // Places to search (in order of decreasing priority):
1458         // (Type NS)
1459         // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
1460         //    (open set, not controlled).
1461         // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
1462         //    (open, not controlled).
1463         // 3. Extern prelude (open, the open part is from macro expansions, not controlled).
1464         // 4. Tool modules (closed, controlled right now, but not in the future).
1465         // 5. Standard library prelude (de-facto closed, controlled).
1466         // 6. Language prelude (closed, controlled).
1467         // (Value NS)
1468         // 1. FIXME: Ribs (local variables), there's no necessary infrastructure yet
1469         //    (open set, not controlled).
1470         // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
1471         //    (open, not controlled).
1472         // 3. Standard library prelude (de-facto closed, controlled).
1473         // (Macro NS)
1474         // 1-3. Derive helpers (open, not controlled). All ambiguities with other names
1475         //    are currently reported as errors. They should be higher in priority than preludes
1476         //    and probably even names in modules according to the "general principles" above. They
1477         //    also should be subject to restricted shadowing because are effectively produced by
1478         //    derives (you need to resolve the derive first to add helpers into scope), but they
1479         //    should be available before the derive is expanded for compatibility.
1480         //    It's mess in general, so we are being conservative for now.
1481         // 1-3. `macro_rules` (open, not controlled), loop through legacy scopes. Have higher
1482         //    priority than prelude macros, but create ambiguities with macros in modules.
1483         // 1-3. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
1484         //    (open, not controlled). Have higher priority than prelude macros, but create
1485         //    ambiguities with `macro_rules`.
1486         // 4. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
1487         // 4a. User-defined prelude from macro-use
1488         //    (open, the open part is from macro expansions, not controlled).
1489         // 4b. "Standard library prelude" part implemented through `macro-use` (closed, controlled).
1490         // 4c. Standard library prelude (de-facto closed, controlled).
1491         // 6. Language prelude: builtin attributes (closed, controlled).
1492
1493         let rust_2015 = ident.span.rust_2015();
1494         let (ns, macro_kind, is_absolute_path) = match scope_set {
1495             ScopeSet::All(ns, _) => (ns, None, false),
1496             ScopeSet::AbsolutePath(ns) => (ns, None, true),
1497             ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false),
1498         };
1499         // Jump out of trait or enum modules, they do not act as scopes.
1500         let module = parent_scope.module.nearest_item_scope();
1501         let mut scope = match ns {
1502             _ if is_absolute_path => Scope::CrateRoot,
1503             TypeNS | ValueNS => Scope::Module(module),
1504             MacroNS => Scope::DeriveHelpers(parent_scope.expansion),
1505         };
1506         let mut ident = ident.modern();
1507         let mut use_prelude = !module.no_implicit_prelude;
1508
1509         loop {
1510             let visit = match scope {
1511                 // Derive helpers are not in scope when resolving derives in the same container.
1512                 Scope::DeriveHelpers(expn_id) => {
1513                     !(expn_id == parent_scope.expansion && macro_kind == Some(MacroKind::Derive))
1514                 }
1515                 Scope::DeriveHelpersCompat => true,
1516                 Scope::MacroRules(..) => true,
1517                 Scope::CrateRoot => true,
1518                 Scope::Module(..) => true,
1519                 Scope::RegisteredAttrs => use_prelude,
1520                 Scope::MacroUsePrelude => use_prelude || rust_2015,
1521                 Scope::BuiltinAttrs => true,
1522                 Scope::ExternPrelude => use_prelude || is_absolute_path,
1523                 Scope::ToolPrelude => use_prelude,
1524                 Scope::StdLibPrelude => use_prelude || ns == MacroNS,
1525                 Scope::BuiltinTypes => true,
1526             };
1527
1528             if visit {
1529                 if let break_result @ Some(..) = visitor(self, scope, use_prelude, ident) {
1530                     return break_result;
1531                 }
1532             }
1533
1534             scope = match scope {
1535                 Scope::DeriveHelpers(expn_id) if expn_id != ExpnId::root() => {
1536                     // Derive helpers are not visible to code generated by bang or derive macros.
1537                     let expn_data = expn_id.expn_data();
1538                     match expn_data.kind {
1539                         ExpnKind::Root
1540                         | ExpnKind::Macro(MacroKind::Bang, _)
1541                         | ExpnKind::Macro(MacroKind::Derive, _) => Scope::DeriveHelpersCompat,
1542                         _ => Scope::DeriveHelpers(expn_data.parent),
1543                     }
1544                 }
1545                 Scope::DeriveHelpers(..) => Scope::DeriveHelpersCompat,
1546                 Scope::DeriveHelpersCompat => Scope::MacroRules(parent_scope.legacy),
1547                 Scope::MacroRules(legacy_scope) => match legacy_scope {
1548                     LegacyScope::Binding(binding) => Scope::MacroRules(binding.parent_legacy_scope),
1549                     LegacyScope::Invocation(invoc_id) => Scope::MacroRules(
1550                         self.output_legacy_scopes
1551                             .get(&invoc_id)
1552                             .cloned()
1553                             .unwrap_or(self.invocation_parent_scopes[&invoc_id].legacy),
1554                     ),
1555                     LegacyScope::Empty => Scope::Module(module),
1556                 },
1557                 Scope::CrateRoot => match ns {
1558                     TypeNS => {
1559                         ident.span.adjust(ExpnId::root());
1560                         Scope::ExternPrelude
1561                     }
1562                     ValueNS | MacroNS => break,
1563                 },
1564                 Scope::Module(module) => {
1565                     use_prelude = !module.no_implicit_prelude;
1566                     match self.hygienic_lexical_parent(module, &mut ident.span) {
1567                         Some(parent_module) => Scope::Module(parent_module),
1568                         None => {
1569                             ident.span.adjust(ExpnId::root());
1570                             match ns {
1571                                 TypeNS => Scope::ExternPrelude,
1572                                 ValueNS => Scope::StdLibPrelude,
1573                                 MacroNS => Scope::RegisteredAttrs,
1574                             }
1575                         }
1576                     }
1577                 }
1578                 Scope::RegisteredAttrs => Scope::MacroUsePrelude,
1579                 Scope::MacroUsePrelude => Scope::StdLibPrelude,
1580                 Scope::BuiltinAttrs => break, // nowhere else to search
1581                 Scope::ExternPrelude if is_absolute_path => break,
1582                 Scope::ExternPrelude => Scope::ToolPrelude,
1583                 Scope::ToolPrelude => Scope::StdLibPrelude,
1584                 Scope::StdLibPrelude => match ns {
1585                     TypeNS => Scope::BuiltinTypes,
1586                     ValueNS => break, // nowhere else to search
1587                     MacroNS => Scope::BuiltinAttrs,
1588                 },
1589                 Scope::BuiltinTypes => break, // nowhere else to search
1590             };
1591         }
1592
1593         None
1594     }
1595
1596     /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
1597     /// More specifically, we proceed up the hierarchy of scopes and return the binding for
1598     /// `ident` in the first scope that defines it (or None if no scopes define it).
1599     ///
1600     /// A block's items are above its local variables in the scope hierarchy, regardless of where
1601     /// the items are defined in the block. For example,
1602     /// ```rust
1603     /// fn f() {
1604     ///    g(); // Since there are no local variables in scope yet, this resolves to the item.
1605     ///    let g = || {};
1606     ///    fn g() {}
1607     ///    g(); // This resolves to the local variable `g` since it shadows the item.
1608     /// }
1609     /// ```
1610     ///
1611     /// Invariant: This must only be called during main resolution, not during
1612     /// import resolution.
1613     fn resolve_ident_in_lexical_scope(
1614         &mut self,
1615         mut ident: Ident,
1616         ns: Namespace,
1617         parent_scope: &ParentScope<'a>,
1618         record_used_id: Option<NodeId>,
1619         path_span: Span,
1620         ribs: &[Rib<'a>],
1621     ) -> Option<LexicalScopeBinding<'a>> {
1622         assert!(ns == TypeNS || ns == ValueNS);
1623         if ident.name == kw::Invalid {
1624             return Some(LexicalScopeBinding::Res(Res::Err));
1625         }
1626         let (general_span, modern_span) = if ident.name == kw::SelfUpper {
1627             // FIXME(jseyfried) improve `Self` hygiene
1628             let empty_span = ident.span.with_ctxt(SyntaxContext::root());
1629             (empty_span, empty_span)
1630         } else if ns == TypeNS {
1631             let modern_span = ident.span.modern();
1632             (modern_span, modern_span)
1633         } else {
1634             (ident.span.modern_and_legacy(), ident.span.modern())
1635         };
1636         ident.span = general_span;
1637         let modern_ident = Ident { span: modern_span, ..ident };
1638
1639         // Walk backwards up the ribs in scope.
1640         let record_used = record_used_id.is_some();
1641         let mut module = self.graph_root;
1642         for i in (0..ribs.len()).rev() {
1643             debug!("walk rib\n{:?}", ribs[i].bindings);
1644             // Use the rib kind to determine whether we are resolving parameters
1645             // (modern hygiene) or local variables (legacy hygiene).
1646             let rib_ident = if ribs[i].kind.contains_params() { modern_ident } else { ident };
1647             if let Some(res) = ribs[i].bindings.get(&rib_ident).cloned() {
1648                 // The ident resolves to a type parameter or local variable.
1649                 return Some(LexicalScopeBinding::Res(self.validate_res_from_ribs(
1650                     i,
1651                     rib_ident,
1652                     res,
1653                     record_used,
1654                     path_span,
1655                     ribs,
1656                 )));
1657             }
1658
1659             module = match ribs[i].kind {
1660                 ModuleRibKind(module) => module,
1661                 MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => {
1662                     // If an invocation of this macro created `ident`, give up on `ident`
1663                     // and switch to `ident`'s source from the macro definition.
1664                     ident.span.remove_mark();
1665                     continue;
1666                 }
1667                 _ => continue,
1668             };
1669
1670             let item = self.resolve_ident_in_module_unadjusted(
1671                 ModuleOrUniformRoot::Module(module),
1672                 ident,
1673                 ns,
1674                 parent_scope,
1675                 record_used,
1676                 path_span,
1677             );
1678             if let Ok(binding) = item {
1679                 // The ident resolves to an item.
1680                 return Some(LexicalScopeBinding::Item(binding));
1681             }
1682
1683             match module.kind {
1684                 ModuleKind::Block(..) => {} // We can see through blocks
1685                 _ => break,
1686             }
1687         }
1688
1689         ident = modern_ident;
1690         let mut poisoned = None;
1691         loop {
1692             let opt_module = if let Some(node_id) = record_used_id {
1693                 self.hygienic_lexical_parent_with_compatibility_fallback(
1694                     module,
1695                     &mut ident.span,
1696                     node_id,
1697                     &mut poisoned,
1698                 )
1699             } else {
1700                 self.hygienic_lexical_parent(module, &mut ident.span)
1701             };
1702             module = unwrap_or!(opt_module, break);
1703             let adjusted_parent_scope = &ParentScope { module, ..*parent_scope };
1704             let result = self.resolve_ident_in_module_unadjusted(
1705                 ModuleOrUniformRoot::Module(module),
1706                 ident,
1707                 ns,
1708                 adjusted_parent_scope,
1709                 record_used,
1710                 path_span,
1711             );
1712
1713             match result {
1714                 Ok(binding) => {
1715                     if let Some(node_id) = poisoned {
1716                         self.lint_buffer.buffer_lint_with_diagnostic(
1717                             lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
1718                             node_id,
1719                             ident.span,
1720                             &format!("cannot find {} `{}` in this scope", ns.descr(), ident),
1721                             BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(ident.span),
1722                         );
1723                     }
1724                     return Some(LexicalScopeBinding::Item(binding));
1725                 }
1726                 Err(Determined) => continue,
1727                 Err(Undetermined) => {
1728                     span_bug!(ident.span, "undetermined resolution during main resolution pass")
1729                 }
1730             }
1731         }
1732
1733         if !module.no_implicit_prelude {
1734             ident.span.adjust(ExpnId::root());
1735             if ns == TypeNS {
1736                 if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
1737                     return Some(LexicalScopeBinding::Item(binding));
1738                 }
1739                 if let Some(ident) = self.registered_tools.get(&ident) {
1740                     let binding =
1741                         (Res::ToolMod, ty::Visibility::Public, ident.span, ExpnId::root())
1742                             .to_name_binding(self.arenas);
1743                     return Some(LexicalScopeBinding::Item(binding));
1744                 }
1745             }
1746             if let Some(prelude) = self.prelude {
1747                 if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
1748                     ModuleOrUniformRoot::Module(prelude),
1749                     ident,
1750                     ns,
1751                     parent_scope,
1752                     false,
1753                     path_span,
1754                 ) {
1755                     return Some(LexicalScopeBinding::Item(binding));
1756                 }
1757             }
1758         }
1759
1760         if ns == TypeNS {
1761             if let Some(prim_ty) = self.primitive_type_table.primitive_types.get(&ident.name) {
1762                 let binding =
1763                     (Res::PrimTy(*prim_ty), ty::Visibility::Public, DUMMY_SP, ExpnId::root())
1764                         .to_name_binding(self.arenas);
1765                 return Some(LexicalScopeBinding::Item(binding));
1766             }
1767         }
1768
1769         None
1770     }
1771
1772     fn hygienic_lexical_parent(
1773         &mut self,
1774         module: Module<'a>,
1775         span: &mut Span,
1776     ) -> Option<Module<'a>> {
1777         if !module.expansion.outer_expn_is_descendant_of(span.ctxt()) {
1778             return Some(self.macro_def_scope(span.remove_mark()));
1779         }
1780
1781         if let ModuleKind::Block(..) = module.kind {
1782             return Some(module.parent.unwrap().nearest_item_scope());
1783         }
1784
1785         None
1786     }
1787
1788     fn hygienic_lexical_parent_with_compatibility_fallback(
1789         &mut self,
1790         module: Module<'a>,
1791         span: &mut Span,
1792         node_id: NodeId,
1793         poisoned: &mut Option<NodeId>,
1794     ) -> Option<Module<'a>> {
1795         if let module @ Some(..) = self.hygienic_lexical_parent(module, span) {
1796             return module;
1797         }
1798
1799         // We need to support the next case under a deprecation warning
1800         // ```
1801         // struct MyStruct;
1802         // ---- begin: this comes from a proc macro derive
1803         // mod implementation_details {
1804         //     // Note that `MyStruct` is not in scope here.
1805         //     impl SomeTrait for MyStruct { ... }
1806         // }
1807         // ---- end
1808         // ```
1809         // So we have to fall back to the module's parent during lexical resolution in this case.
1810         if let Some(parent) = module.parent {
1811             // Inner module is inside the macro, parent module is outside of the macro.
1812             if module.expansion != parent.expansion
1813                 && module.expansion.is_descendant_of(parent.expansion)
1814             {
1815                 // The macro is a proc macro derive
1816                 if let Some(&def_id) = self.macro_defs.get(&module.expansion) {
1817                     if let Some(ext) = self.get_macro_by_def_id(def_id) {
1818                         if !ext.is_builtin && ext.macro_kind() == MacroKind::Derive {
1819                             if parent.expansion.outer_expn_is_descendant_of(span.ctxt()) {
1820                                 *poisoned = Some(node_id);
1821                                 return module.parent;
1822                             }
1823                         }
1824                     }
1825                 }
1826             }
1827         }
1828
1829         None
1830     }
1831
1832     fn resolve_ident_in_module(
1833         &mut self,
1834         module: ModuleOrUniformRoot<'a>,
1835         ident: Ident,
1836         ns: Namespace,
1837         parent_scope: &ParentScope<'a>,
1838         record_used: bool,
1839         path_span: Span,
1840     ) -> Result<&'a NameBinding<'a>, Determinacy> {
1841         self.resolve_ident_in_module_ext(module, ident, ns, parent_scope, record_used, path_span)
1842             .map_err(|(determinacy, _)| determinacy)
1843     }
1844
1845     fn resolve_ident_in_module_ext(
1846         &mut self,
1847         module: ModuleOrUniformRoot<'a>,
1848         mut ident: Ident,
1849         ns: Namespace,
1850         parent_scope: &ParentScope<'a>,
1851         record_used: bool,
1852         path_span: Span,
1853     ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
1854         let tmp_parent_scope;
1855         let mut adjusted_parent_scope = parent_scope;
1856         match module {
1857             ModuleOrUniformRoot::Module(m) => {
1858                 if let Some(def) = ident.span.modernize_and_adjust(m.expansion) {
1859                     tmp_parent_scope =
1860                         ParentScope { module: self.macro_def_scope(def), ..*parent_scope };
1861                     adjusted_parent_scope = &tmp_parent_scope;
1862                 }
1863             }
1864             ModuleOrUniformRoot::ExternPrelude => {
1865                 ident.span.modernize_and_adjust(ExpnId::root());
1866             }
1867             ModuleOrUniformRoot::CrateRootAndExternPrelude | ModuleOrUniformRoot::CurrentScope => {
1868                 // No adjustments
1869             }
1870         }
1871         let result = self.resolve_ident_in_module_unadjusted_ext(
1872             module,
1873             ident,
1874             ns,
1875             adjusted_parent_scope,
1876             false,
1877             record_used,
1878             path_span,
1879         );
1880         result
1881     }
1882
1883     fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> {
1884         let mut ctxt = ident.span.ctxt();
1885         let mark = if ident.name == kw::DollarCrate {
1886             // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
1887             // we don't want to pretend that the `macro_rules!` definition is in the `macro`
1888             // as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks.
1889             // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
1890             // definitions actually produced by `macro` and `macro` definitions produced by
1891             // `macro_rules!`, but at least such configurations are not stable yet.
1892             ctxt = ctxt.modern_and_legacy();
1893             let mut iter = ctxt.marks().into_iter().rev().peekable();
1894             let mut result = None;
1895             // Find the last modern mark from the end if it exists.
1896             while let Some(&(mark, transparency)) = iter.peek() {
1897                 if transparency == Transparency::Opaque {
1898                     result = Some(mark);
1899                     iter.next();
1900                 } else {
1901                     break;
1902                 }
1903             }
1904             // Then find the last legacy mark from the end if it exists.
1905             for (mark, transparency) in iter {
1906                 if transparency == Transparency::SemiTransparent {
1907                     result = Some(mark);
1908                 } else {
1909                     break;
1910                 }
1911             }
1912             result
1913         } else {
1914             ctxt = ctxt.modern();
1915             ctxt.adjust(ExpnId::root())
1916         };
1917         let module = match mark {
1918             Some(def) => self.macro_def_scope(def),
1919             None => return self.graph_root,
1920         };
1921         self.get_module(DefId { index: CRATE_DEF_INDEX, ..module.normal_ancestor_id })
1922     }
1923
1924     fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
1925         let mut module = self.get_module(module.normal_ancestor_id);
1926         while module.span.ctxt().modern() != *ctxt {
1927             let parent = module.parent.unwrap_or_else(|| self.macro_def_scope(ctxt.remove_mark()));
1928             module = self.get_module(parent.normal_ancestor_id);
1929         }
1930         module
1931     }
1932
1933     fn resolve_path(
1934         &mut self,
1935         path: &[Segment],
1936         opt_ns: Option<Namespace>, // `None` indicates a module path in import
1937         parent_scope: &ParentScope<'a>,
1938         record_used: bool,
1939         path_span: Span,
1940         crate_lint: CrateLint,
1941     ) -> PathResult<'a> {
1942         self.resolve_path_with_ribs(
1943             path,
1944             opt_ns,
1945             parent_scope,
1946             record_used,
1947             path_span,
1948             crate_lint,
1949             None,
1950         )
1951     }
1952
1953     fn resolve_path_with_ribs(
1954         &mut self,
1955         path: &[Segment],
1956         opt_ns: Option<Namespace>, // `None` indicates a module path in import
1957         parent_scope: &ParentScope<'a>,
1958         record_used: bool,
1959         path_span: Span,
1960         crate_lint: CrateLint,
1961         ribs: Option<&PerNS<Vec<Rib<'a>>>>,
1962     ) -> PathResult<'a> {
1963         let mut module = None;
1964         let mut allow_super = true;
1965         let mut second_binding = None;
1966
1967         debug!(
1968             "resolve_path(path={:?}, opt_ns={:?}, record_used={:?}, \
1969              path_span={:?}, crate_lint={:?})",
1970             path, opt_ns, record_used, path_span, crate_lint,
1971         );
1972
1973         for (i, &Segment { ident, id }) in path.iter().enumerate() {
1974             debug!("resolve_path ident {} {:?} {:?}", i, ident, id);
1975             let record_segment_res = |this: &mut Self, res| {
1976                 if record_used {
1977                     if let Some(id) = id {
1978                         if !this.partial_res_map.contains_key(&id) {
1979                             assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id");
1980                             this.record_partial_res(id, PartialRes::new(res));
1981                         }
1982                     }
1983                 }
1984             };
1985
1986             let is_last = i == path.len() - 1;
1987             let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1988             let name = ident.name;
1989
1990             allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super);
1991
1992             if ns == TypeNS {
1993                 if allow_super && name == kw::Super {
1994                     let mut ctxt = ident.span.ctxt().modern();
1995                     let self_module = match i {
1996                         0 => Some(self.resolve_self(&mut ctxt, parent_scope.module)),
1997                         _ => match module {
1998                             Some(ModuleOrUniformRoot::Module(module)) => Some(module),
1999                             _ => None,
2000                         },
2001                     };
2002                     if let Some(self_module) = self_module {
2003                         if let Some(parent) = self_module.parent {
2004                             module = Some(ModuleOrUniformRoot::Module(
2005                                 self.resolve_self(&mut ctxt, parent),
2006                             ));
2007                             continue;
2008                         }
2009                     }
2010                     let msg = "there are too many leading `super` keywords".to_string();
2011                     return PathResult::Failed {
2012                         span: ident.span,
2013                         label: msg,
2014                         suggestion: None,
2015                         is_error_from_last_segment: false,
2016                     };
2017                 }
2018                 if i == 0 {
2019                     if name == kw::SelfLower {
2020                         let mut ctxt = ident.span.ctxt().modern();
2021                         module = Some(ModuleOrUniformRoot::Module(
2022                             self.resolve_self(&mut ctxt, parent_scope.module),
2023                         ));
2024                         continue;
2025                     }
2026                     if name == kw::PathRoot && ident.span.rust_2018() {
2027                         module = Some(ModuleOrUniformRoot::ExternPrelude);
2028                         continue;
2029                     }
2030                     if name == kw::PathRoot && ident.span.rust_2015() && self.session.rust_2018() {
2031                         // `::a::b` from 2015 macro on 2018 global edition
2032                         module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude);
2033                         continue;
2034                     }
2035                     if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate {
2036                         // `::a::b`, `crate::a::b` or `$crate::a::b`
2037                         module = Some(ModuleOrUniformRoot::Module(self.resolve_crate_root(ident)));
2038                         continue;
2039                     }
2040                 }
2041             }
2042
2043             // Report special messages for path segment keywords in wrong positions.
2044             if ident.is_path_segment_keyword() && i != 0 {
2045                 let name_str = if name == kw::PathRoot {
2046                     "crate root".to_string()
2047                 } else {
2048                     format!("`{}`", name)
2049                 };
2050                 let label = if i == 1 && path[0].ident.name == kw::PathRoot {
2051                     format!("global paths cannot start with {}", name_str)
2052                 } else {
2053                     format!("{} in paths can only be used in start position", name_str)
2054                 };
2055                 return PathResult::Failed {
2056                     span: ident.span,
2057                     label,
2058                     suggestion: None,
2059                     is_error_from_last_segment: false,
2060                 };
2061             }
2062
2063             let binding = if let Some(module) = module {
2064                 self.resolve_ident_in_module(
2065                     module,
2066                     ident,
2067                     ns,
2068                     parent_scope,
2069                     record_used,
2070                     path_span,
2071                 )
2072             } else if ribs.is_none() || opt_ns.is_none() || opt_ns == Some(MacroNS) {
2073                 let scopes = ScopeSet::All(ns, opt_ns.is_none());
2074                 self.early_resolve_ident_in_lexical_scope(
2075                     ident,
2076                     scopes,
2077                     parent_scope,
2078                     record_used,
2079                     record_used,
2080                     path_span,
2081                 )
2082             } else {
2083                 let record_used_id =
2084                     if record_used { crate_lint.node_id().or(Some(CRATE_NODE_ID)) } else { None };
2085                 match self.resolve_ident_in_lexical_scope(
2086                     ident,
2087                     ns,
2088                     parent_scope,
2089                     record_used_id,
2090                     path_span,
2091                     &ribs.unwrap()[ns],
2092                 ) {
2093                     // we found a locally-imported or available item/module
2094                     Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
2095                     // we found a local variable or type param
2096                     Some(LexicalScopeBinding::Res(res))
2097                         if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) =>
2098                     {
2099                         record_segment_res(self, res);
2100                         return PathResult::NonModule(PartialRes::with_unresolved_segments(
2101                             res,
2102                             path.len() - 1,
2103                         ));
2104                     }
2105                     _ => Err(Determinacy::determined(record_used)),
2106                 }
2107             };
2108
2109             match binding {
2110                 Ok(binding) => {
2111                     if i == 1 {
2112                         second_binding = Some(binding);
2113                     }
2114                     let res = binding.res();
2115                     let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res);
2116                     if let Some(next_module) = binding.module() {
2117                         module = Some(ModuleOrUniformRoot::Module(next_module));
2118                         record_segment_res(self, res);
2119                     } else if res == Res::ToolMod && i + 1 != path.len() {
2120                         if binding.is_import() {
2121                             self.session
2122                                 .struct_span_err(
2123                                     ident.span,
2124                                     "cannot use a tool module through an import",
2125                                 )
2126                                 .span_note(binding.span, "the tool module imported here")
2127                                 .emit();
2128                         }
2129                         let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
2130                         return PathResult::NonModule(PartialRes::new(res));
2131                     } else if res == Res::Err {
2132                         return PathResult::NonModule(PartialRes::new(Res::Err));
2133                     } else if opt_ns.is_some() && (is_last || maybe_assoc) {
2134                         self.lint_if_path_starts_with_module(
2135                             crate_lint,
2136                             path,
2137                             path_span,
2138                             second_binding,
2139                         );
2140                         return PathResult::NonModule(PartialRes::with_unresolved_segments(
2141                             res,
2142                             path.len() - i - 1,
2143                         ));
2144                     } else {
2145                         let label = format!(
2146                             "`{}` is {} {}, not a module",
2147                             ident,
2148                             res.article(),
2149                             res.descr(),
2150                         );
2151
2152                         return PathResult::Failed {
2153                             span: ident.span,
2154                             label,
2155                             suggestion: None,
2156                             is_error_from_last_segment: is_last,
2157                         };
2158                     }
2159                 }
2160                 Err(Undetermined) => return PathResult::Indeterminate,
2161                 Err(Determined) => {
2162                     if let Some(ModuleOrUniformRoot::Module(module)) = module {
2163                         if opt_ns.is_some() && !module.is_normal() {
2164                             return PathResult::NonModule(PartialRes::with_unresolved_segments(
2165                                 module.res().unwrap(),
2166                                 path.len() - i,
2167                             ));
2168                         }
2169                     }
2170                     let module_res = match module {
2171                         Some(ModuleOrUniformRoot::Module(module)) => module.res(),
2172                         _ => None,
2173                     };
2174                     let (label, suggestion) = if module_res == self.graph_root.res() {
2175                         let is_mod = |res| match res {
2176                             Res::Def(DefKind::Mod, _) => true,
2177                             _ => false,
2178                         };
2179                         let mut candidates = self.lookup_import_candidates(ident, TypeNS, is_mod);
2180                         candidates.sort_by_cached_key(|c| {
2181                             (c.path.segments.len(), pprust::path_to_string(&c.path))
2182                         });
2183                         if let Some(candidate) = candidates.get(0) {
2184                             (
2185                                 String::from("unresolved import"),
2186                                 Some((
2187                                     vec![(ident.span, pprust::path_to_string(&candidate.path))],
2188                                     String::from("a similar path exists"),
2189                                     Applicability::MaybeIncorrect,
2190                                 )),
2191                             )
2192                         } else if !ident.is_reserved() {
2193                             (format!("maybe a missing crate `{}`?", ident), None)
2194                         } else {
2195                             // the parser will already have complained about the keyword being used
2196                             return PathResult::NonModule(PartialRes::new(Res::Err));
2197                         }
2198                     } else if i == 0 {
2199                         (format!("use of undeclared type or module `{}`", ident), None)
2200                     } else {
2201                         (format!("could not find `{}` in `{}`", ident, path[i - 1].ident), None)
2202                     };
2203                     return PathResult::Failed {
2204                         span: ident.span,
2205                         label,
2206                         suggestion,
2207                         is_error_from_last_segment: is_last,
2208                     };
2209                 }
2210             }
2211         }
2212
2213         self.lint_if_path_starts_with_module(crate_lint, path, path_span, second_binding);
2214
2215         PathResult::Module(match module {
2216             Some(module) => module,
2217             None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
2218             _ => span_bug!(path_span, "resolve_path: non-empty path `{:?}` has no module", path),
2219         })
2220     }
2221
2222     fn lint_if_path_starts_with_module(
2223         &mut self,
2224         crate_lint: CrateLint,
2225         path: &[Segment],
2226         path_span: Span,
2227         second_binding: Option<&NameBinding<'_>>,
2228     ) {
2229         let (diag_id, diag_span) = match crate_lint {
2230             CrateLint::No => return,
2231             CrateLint::SimplePath(id) => (id, path_span),
2232             CrateLint::UsePath { root_id, root_span } => (root_id, root_span),
2233             CrateLint::QPathTrait { qpath_id, qpath_span } => (qpath_id, qpath_span),
2234         };
2235
2236         let first_name = match path.get(0) {
2237             // In the 2018 edition this lint is a hard error, so nothing to do
2238             Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name,
2239             _ => return,
2240         };
2241
2242         // We're only interested in `use` paths which should start with
2243         // `{{root}}` currently.
2244         if first_name != kw::PathRoot {
2245             return;
2246         }
2247
2248         match path.get(1) {
2249             // If this import looks like `crate::...` it's already good
2250             Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
2251             // Otherwise go below to see if it's an extern crate
2252             Some(_) => {}
2253             // If the path has length one (and it's `PathRoot` most likely)
2254             // then we don't know whether we're gonna be importing a crate or an
2255             // item in our crate. Defer this lint to elsewhere
2256             None => return,
2257         }
2258
2259         // If the first element of our path was actually resolved to an
2260         // `ExternCrate` (also used for `crate::...`) then no need to issue a
2261         // warning, this looks all good!
2262         if let Some(binding) = second_binding {
2263             if let NameBindingKind::Import { directive: d, .. } = binding.kind {
2264                 // Careful: we still want to rewrite paths from
2265                 // renamed extern crates.
2266                 if let ImportDirectiveSubclass::ExternCrate { source: None, .. } = d.subclass {
2267                     return;
2268                 }
2269             }
2270         }
2271
2272         let diag = BuiltinLintDiagnostics::AbsPathWithModule(diag_span);
2273         self.lint_buffer.buffer_lint_with_diagnostic(
2274             lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
2275             diag_id,
2276             diag_span,
2277             "absolute paths must start with `self`, `super`, \
2278              `crate`, or an external crate name in the 2018 edition",
2279             diag,
2280         );
2281     }
2282
2283     // Validate a local resolution (from ribs).
2284     fn validate_res_from_ribs(
2285         &mut self,
2286         rib_index: usize,
2287         rib_ident: Ident,
2288         res: Res,
2289         record_used: bool,
2290         span: Span,
2291         all_ribs: &[Rib<'a>],
2292     ) -> Res {
2293         debug!("validate_res_from_ribs({:?})", res);
2294         let ribs = &all_ribs[rib_index + 1..];
2295
2296         // An invalid forward use of a type parameter from a previous default.
2297         if let ForwardTyParamBanRibKind = all_ribs[rib_index].kind {
2298             if record_used {
2299                 let res_error = if rib_ident.name == kw::SelfUpper {
2300                     ResolutionError::SelfInTyParamDefault
2301                 } else {
2302                     ResolutionError::ForwardDeclaredTyParam
2303                 };
2304                 self.report_error(span, res_error);
2305             }
2306             assert_eq!(res, Res::Err);
2307             return Res::Err;
2308         }
2309
2310         match res {
2311             Res::Local(_) => {
2312                 use ResolutionError::*;
2313                 let mut res_err = None;
2314
2315                 for rib in ribs {
2316                     match rib.kind {
2317                         NormalRibKind
2318                         | ModuleRibKind(..)
2319                         | MacroDefinition(..)
2320                         | ForwardTyParamBanRibKind => {
2321                             // Nothing to do. Continue.
2322                         }
2323                         ItemRibKind(_) | FnItemRibKind | AssocItemRibKind => {
2324                             // This was an attempt to access an upvar inside a
2325                             // named function item. This is not allowed, so we
2326                             // report an error.
2327                             if record_used {
2328                                 // We don't immediately trigger a resolve error, because
2329                                 // we want certain other resolution errors (namely those
2330                                 // emitted for `ConstantItemRibKind` below) to take
2331                                 // precedence.
2332                                 res_err = Some(CannotCaptureDynamicEnvironmentInFnItem);
2333                             }
2334                         }
2335                         ConstantItemRibKind => {
2336                             // Still doesn't deal with upvars
2337                             if record_used {
2338                                 self.report_error(span, AttemptToUseNonConstantValueInConstant);
2339                             }
2340                             return Res::Err;
2341                         }
2342                     }
2343                 }
2344                 if let Some(res_err) = res_err {
2345                     self.report_error(span, res_err);
2346                     return Res::Err;
2347                 }
2348             }
2349             Res::Def(DefKind::TyParam, _) | Res::SelfTy(..) => {
2350                 for rib in ribs {
2351                     let has_generic_params = match rib.kind {
2352                         NormalRibKind
2353                         | AssocItemRibKind
2354                         | ModuleRibKind(..)
2355                         | MacroDefinition(..)
2356                         | ForwardTyParamBanRibKind
2357                         | ConstantItemRibKind => {
2358                             // Nothing to do. Continue.
2359                             continue;
2360                         }
2361                         // This was an attempt to use a type parameter outside its scope.
2362                         ItemRibKind(has_generic_params) => has_generic_params,
2363                         FnItemRibKind => HasGenericParams::Yes,
2364                     };
2365
2366                     if record_used {
2367                         self.report_error(
2368                             span,
2369                             ResolutionError::GenericParamsFromOuterFunction(
2370                                 res,
2371                                 has_generic_params,
2372                             ),
2373                         );
2374                     }
2375                     return Res::Err;
2376                 }
2377             }
2378             Res::Def(DefKind::ConstParam, _) => {
2379                 let mut ribs = ribs.iter().peekable();
2380                 if let Some(Rib { kind: FnItemRibKind, .. }) = ribs.peek() {
2381                     // When declaring const parameters inside function signatures, the first rib
2382                     // is always a `FnItemRibKind`. In this case, we can skip it, to avoid it
2383                     // (spuriously) conflicting with the const param.
2384                     ribs.next();
2385                 }
2386                 for rib in ribs {
2387                     let has_generic_params = match rib.kind {
2388                         ItemRibKind(has_generic_params) => has_generic_params,
2389                         FnItemRibKind => HasGenericParams::Yes,
2390                         _ => continue,
2391                     };
2392
2393                     // This was an attempt to use a const parameter outside its scope.
2394                     if record_used {
2395                         self.report_error(
2396                             span,
2397                             ResolutionError::GenericParamsFromOuterFunction(
2398                                 res,
2399                                 has_generic_params,
2400                             ),
2401                         );
2402                     }
2403                     return Res::Err;
2404                 }
2405             }
2406             _ => {}
2407         }
2408         res
2409     }
2410
2411     fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2412         debug!("(recording res) recording {:?} for {}", resolution, node_id);
2413         if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2414             panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
2415         }
2416     }
2417
2418     fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
2419         vis.is_accessible_from(module.normal_ancestor_id, self)
2420     }
2421
2422     fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) {
2423         if let Some(old_module) = self.binding_parent_modules.insert(PtrKey(binding), module) {
2424             if !ptr::eq(module, old_module) {
2425                 span_bug!(binding.span, "parent module is reset for binding");
2426             }
2427         }
2428     }
2429
2430     fn disambiguate_legacy_vs_modern(
2431         &self,
2432         legacy: &'a NameBinding<'a>,
2433         modern: &'a NameBinding<'a>,
2434     ) -> bool {
2435         // Some non-controversial subset of ambiguities "modern macro name" vs "macro_rules"
2436         // is disambiguated to mitigate regressions from macro modularization.
2437         // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
2438         match (
2439             self.binding_parent_modules.get(&PtrKey(legacy)),
2440             self.binding_parent_modules.get(&PtrKey(modern)),
2441         ) {
2442             (Some(legacy), Some(modern)) => {
2443                 legacy.normal_ancestor_id == modern.normal_ancestor_id
2444                     && modern.is_ancestor_of(legacy)
2445             }
2446             _ => false,
2447         }
2448     }
2449
2450     fn report_errors(&mut self, krate: &Crate) {
2451         self.report_with_use_injections(krate);
2452
2453         for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
2454             let msg = "macro-expanded `macro_export` macros from the current crate \
2455                        cannot be referred to by absolute paths";
2456             self.lint_buffer.buffer_lint_with_diagnostic(
2457                 lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
2458                 CRATE_NODE_ID,
2459                 span_use,
2460                 msg,
2461                 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
2462             );
2463         }
2464
2465         for ambiguity_error in &self.ambiguity_errors {
2466             self.report_ambiguity_error(ambiguity_error);
2467         }
2468
2469         let mut reported_spans = FxHashSet::default();
2470         for error in &self.privacy_errors {
2471             if reported_spans.insert(error.dedup_span) {
2472                 self.report_privacy_error(error);
2473             }
2474         }
2475     }
2476
2477     fn report_with_use_injections(&mut self, krate: &Crate) {
2478         for UseError { mut err, candidates, node_id, better } in self.use_injections.drain(..) {
2479             let (span, found_use) = UsePlacementFinder::check(krate, node_id);
2480             if !candidates.is_empty() {
2481                 diagnostics::show_candidates(&mut err, span, &candidates, better, found_use);
2482             }
2483             err.emit();
2484         }
2485     }
2486
2487     fn report_conflict<'b>(
2488         &mut self,
2489         parent: Module<'_>,
2490         ident: Ident,
2491         ns: Namespace,
2492         new_binding: &NameBinding<'b>,
2493         old_binding: &NameBinding<'b>,
2494     ) {
2495         // Error on the second of two conflicting names
2496         if old_binding.span.lo() > new_binding.span.lo() {
2497             return self.report_conflict(parent, ident, ns, old_binding, new_binding);
2498         }
2499
2500         let container = match parent.kind {
2501             ModuleKind::Def(DefKind::Mod, _, _) => "module",
2502             ModuleKind::Def(DefKind::Trait, _, _) => "trait",
2503             ModuleKind::Block(..) => "block",
2504             _ => "enum",
2505         };
2506
2507         let old_noun = match old_binding.is_import() {
2508             true => "import",
2509             false => "definition",
2510         };
2511
2512         let new_participle = match new_binding.is_import() {
2513             true => "imported",
2514             false => "defined",
2515         };
2516
2517         let (name, span) = (ident.name, self.session.source_map().def_span(new_binding.span));
2518
2519         if let Some(s) = self.name_already_seen.get(&name) {
2520             if s == &span {
2521                 return;
2522             }
2523         }
2524
2525         let old_kind = match (ns, old_binding.module()) {
2526             (ValueNS, _) => "value",
2527             (MacroNS, _) => "macro",
2528             (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
2529             (TypeNS, Some(module)) if module.is_normal() => "module",
2530             (TypeNS, Some(module)) if module.is_trait() => "trait",
2531             (TypeNS, _) => "type",
2532         };
2533
2534         let msg = format!("the name `{}` is defined multiple times", name);
2535
2536         let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
2537             (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
2538             (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
2539                 true => struct_span_err!(self.session, span, E0254, "{}", msg),
2540                 false => struct_span_err!(self.session, span, E0260, "{}", msg),
2541             },
2542             _ => match (old_binding.is_import(), new_binding.is_import()) {
2543                 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
2544                 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
2545                 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
2546             },
2547         };
2548
2549         err.note(&format!(
2550             "`{}` must be defined only once in the {} namespace of this {}",
2551             name,
2552             ns.descr(),
2553             container
2554         ));
2555
2556         err.span_label(span, format!("`{}` re{} here", name, new_participle));
2557         err.span_label(
2558             self.session.source_map().def_span(old_binding.span),
2559             format!("previous {} of the {} `{}` here", old_noun, old_kind, name),
2560         );
2561
2562         // See https://github.com/rust-lang/rust/issues/32354
2563         use NameBindingKind::Import;
2564         let directive = match (&new_binding.kind, &old_binding.kind) {
2565             // If there are two imports where one or both have attributes then prefer removing the
2566             // import without attributes.
2567             (Import { directive: new, .. }, Import { directive: old, .. })
2568                 if {
2569                     !new_binding.span.is_dummy()
2570                         && !old_binding.span.is_dummy()
2571                         && (new.has_attributes || old.has_attributes)
2572                 } =>
2573             {
2574                 if old.has_attributes {
2575                     Some((new, new_binding.span, true))
2576                 } else {
2577                     Some((old, old_binding.span, true))
2578                 }
2579             }
2580             // Otherwise prioritize the new binding.
2581             (Import { directive, .. }, other) if !new_binding.span.is_dummy() => {
2582                 Some((directive, new_binding.span, other.is_import()))
2583             }
2584             (other, Import { directive, .. }) if !old_binding.span.is_dummy() => {
2585                 Some((directive, old_binding.span, other.is_import()))
2586             }
2587             _ => None,
2588         };
2589
2590         // Check if the target of the use for both bindings is the same.
2591         let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
2592         let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
2593         let from_item =
2594             self.extern_prelude.get(&ident).map(|entry| entry.introduced_by_item).unwrap_or(true);
2595         // Only suggest removing an import if both bindings are to the same def, if both spans
2596         // aren't dummy spans. Further, if both bindings are imports, then the ident must have
2597         // been introduced by a item.
2598         let should_remove_import = duplicate
2599             && !has_dummy_span
2600             && ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
2601
2602         match directive {
2603             Some((directive, span, true)) if should_remove_import && directive.is_nested() => {
2604                 self.add_suggestion_for_duplicate_nested_use(&mut err, directive, span)
2605             }
2606             Some((directive, _, true)) if should_remove_import && !directive.is_glob() => {
2607                 // Simple case - remove the entire import. Due to the above match arm, this can
2608                 // only be a single use so just remove it entirely.
2609                 err.tool_only_span_suggestion(
2610                     directive.use_span_with_attributes,
2611                     "remove unnecessary import",
2612                     String::new(),
2613                     Applicability::MaybeIncorrect,
2614                 );
2615             }
2616             Some((directive, span, _)) => {
2617                 self.add_suggestion_for_rename_of_use(&mut err, name, directive, span)
2618             }
2619             _ => {}
2620         }
2621
2622         err.emit();
2623         self.name_already_seen.insert(name, span);
2624     }
2625
2626     /// This function adds a suggestion to change the binding name of a new import that conflicts
2627     /// with an existing import.
2628     ///
2629     /// ```ignore (diagnostic)
2630     /// help: you can use `as` to change the binding name of the import
2631     ///    |
2632     /// LL | use foo::bar as other_bar;
2633     ///    |     ^^^^^^^^^^^^^^^^^^^^^
2634     /// ```
2635     fn add_suggestion_for_rename_of_use(
2636         &self,
2637         err: &mut DiagnosticBuilder<'_>,
2638         name: Name,
2639         directive: &ImportDirective<'_>,
2640         binding_span: Span,
2641     ) {
2642         let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
2643             format!("Other{}", name)
2644         } else {
2645             format!("other_{}", name)
2646         };
2647
2648         let mut suggestion = None;
2649         match directive.subclass {
2650             ImportDirectiveSubclass::SingleImport { type_ns_only: true, .. } => {
2651                 suggestion = Some(format!("self as {}", suggested_name))
2652             }
2653             ImportDirectiveSubclass::SingleImport { source, .. } => {
2654                 if let Some(pos) =
2655                     source.span.hi().0.checked_sub(binding_span.lo().0).map(|pos| pos as usize)
2656                 {
2657                     if let Ok(snippet) = self.session.source_map().span_to_snippet(binding_span) {
2658                         if pos <= snippet.len() {
2659                             suggestion = Some(format!(
2660                                 "{} as {}{}",
2661                                 &snippet[..pos],
2662                                 suggested_name,
2663                                 if snippet.ends_with(";") { ";" } else { "" }
2664                             ))
2665                         }
2666                     }
2667                 }
2668             }
2669             ImportDirectiveSubclass::ExternCrate { source, target, .. } => {
2670                 suggestion = Some(format!(
2671                     "extern crate {} as {};",
2672                     source.unwrap_or(target.name),
2673                     suggested_name,
2674                 ))
2675             }
2676             _ => unreachable!(),
2677         }
2678
2679         let rename_msg = "you can use `as` to change the binding name of the import";
2680         if let Some(suggestion) = suggestion {
2681             err.span_suggestion(
2682                 binding_span,
2683                 rename_msg,
2684                 suggestion,
2685                 Applicability::MaybeIncorrect,
2686             );
2687         } else {
2688             err.span_label(binding_span, rename_msg);
2689         }
2690     }
2691
2692     /// This function adds a suggestion to remove a unnecessary binding from an import that is
2693     /// nested. In the following example, this function will be invoked to remove the `a` binding
2694     /// in the second use statement:
2695     ///
2696     /// ```ignore (diagnostic)
2697     /// use issue_52891::a;
2698     /// use issue_52891::{d, a, e};
2699     /// ```
2700     ///
2701     /// The following suggestion will be added:
2702     ///
2703     /// ```ignore (diagnostic)
2704     /// use issue_52891::{d, a, e};
2705     ///                      ^-- help: remove unnecessary import
2706     /// ```
2707     ///
2708     /// If the nested use contains only one import then the suggestion will remove the entire
2709     /// line.
2710     ///
2711     /// It is expected that the directive provided is a nested import - this isn't checked by the
2712     /// function. If this invariant is not upheld, this function's behaviour will be unexpected
2713     /// as characters expected by span manipulations won't be present.
2714     fn add_suggestion_for_duplicate_nested_use(
2715         &self,
2716         err: &mut DiagnosticBuilder<'_>,
2717         directive: &ImportDirective<'_>,
2718         binding_span: Span,
2719     ) {
2720         assert!(directive.is_nested());
2721         let message = "remove unnecessary import";
2722
2723         // Two examples will be used to illustrate the span manipulations we're doing:
2724         //
2725         // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is
2726         //   `a` and `directive.use_span` is `issue_52891::{d, a, e};`.
2727         // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is
2728         //   `a` and `directive.use_span` is `issue_52891::{d, e, a};`.
2729
2730         let (found_closing_brace, span) =
2731             find_span_of_binding_until_next_binding(self.session, binding_span, directive.use_span);
2732
2733         // If there was a closing brace then identify the span to remove any trailing commas from
2734         // previous imports.
2735         if found_closing_brace {
2736             if let Some(span) = extend_span_to_previous_binding(self.session, span) {
2737                 err.tool_only_span_suggestion(
2738                     span,
2739                     message,
2740                     String::new(),
2741                     Applicability::MaybeIncorrect,
2742                 );
2743             } else {
2744                 // Remove the entire line if we cannot extend the span back, this indicates a
2745                 // `issue_52891::{self}` case.
2746                 err.span_suggestion(
2747                     directive.use_span_with_attributes,
2748                     message,
2749                     String::new(),
2750                     Applicability::MaybeIncorrect,
2751                 );
2752             }
2753
2754             return;
2755         }
2756
2757         err.span_suggestion(span, message, String::new(), Applicability::MachineApplicable);
2758     }
2759
2760     fn extern_prelude_get(
2761         &mut self,
2762         ident: Ident,
2763         speculative: bool,
2764     ) -> Option<&'a NameBinding<'a>> {
2765         if ident.is_path_segment_keyword() {
2766             // Make sure `self`, `super` etc produce an error when passed to here.
2767             return None;
2768         }
2769         self.extern_prelude.get(&ident.modern()).cloned().and_then(|entry| {
2770             if let Some(binding) = entry.extern_crate_item {
2771                 if !speculative && entry.introduced_by_item {
2772                     self.record_use(ident, TypeNS, binding, false);
2773                 }
2774                 Some(binding)
2775             } else {
2776                 let crate_id = if !speculative {
2777                     self.crate_loader.process_path_extern(ident.name, ident.span)
2778                 } else if let Some(crate_id) =
2779                     self.crate_loader.maybe_process_path_extern(ident.name, ident.span)
2780                 {
2781                     crate_id
2782                 } else {
2783                     return None;
2784                 };
2785                 let crate_root = self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
2786                 Some(
2787                     (crate_root, ty::Visibility::Public, DUMMY_SP, ExpnId::root())
2788                         .to_name_binding(self.arenas),
2789                 )
2790             }
2791         })
2792     }
2793
2794     /// Rustdoc uses this to resolve things in a recoverable way. `ResolutionError<'a>`
2795     /// isn't something that can be returned because it can't be made to live that long,
2796     /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
2797     /// just that an error occurred.
2798     // FIXME(Manishearth): intra-doc links won't get warned of epoch changes.
2799     pub fn resolve_str_path_error(
2800         &mut self,
2801         span: Span,
2802         path_str: &str,
2803         ns: Namespace,
2804         module_id: NodeId,
2805     ) -> Result<(ast::Path, Res), ()> {
2806         let path = if path_str.starts_with("::") {
2807             ast::Path {
2808                 span,
2809                 segments: iter::once(Ident::with_dummy_span(kw::PathRoot))
2810                     .chain({ path_str.split("::").skip(1).map(Ident::from_str) })
2811                     .map(|i| self.new_ast_path_segment(i))
2812                     .collect(),
2813             }
2814         } else {
2815             ast::Path {
2816                 span,
2817                 segments: path_str
2818                     .split("::")
2819                     .map(Ident::from_str)
2820                     .map(|i| self.new_ast_path_segment(i))
2821                     .collect(),
2822             }
2823         };
2824         let module = self.block_map.get(&module_id).copied().unwrap_or_else(|| {
2825             let def_id = self.definitions.local_def_id(module_id);
2826             self.module_map.get(&def_id).copied().unwrap_or(self.graph_root)
2827         });
2828         let parent_scope = &ParentScope::module(module);
2829         let res = self.resolve_ast_path(&path, ns, parent_scope).map_err(|_| ())?;
2830         Ok((path, res))
2831     }
2832
2833     // Resolve a path passed from rustdoc or HIR lowering.
2834     fn resolve_ast_path(
2835         &mut self,
2836         path: &ast::Path,
2837         ns: Namespace,
2838         parent_scope: &ParentScope<'a>,
2839     ) -> Result<Res, (Span, ResolutionError<'a>)> {
2840         match self.resolve_path(
2841             &Segment::from_path(path),
2842             Some(ns),
2843             parent_scope,
2844             true,
2845             path.span,
2846             CrateLint::No,
2847         ) {
2848             PathResult::Module(ModuleOrUniformRoot::Module(module)) => Ok(module.res().unwrap()),
2849             PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
2850                 Ok(path_res.base_res())
2851             }
2852             PathResult::NonModule(..) => Err((
2853                 path.span,
2854                 ResolutionError::FailedToResolve {
2855                     label: String::from("type-relative paths are not supported in this context"),
2856                     suggestion: None,
2857                 },
2858             )),
2859             PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
2860             PathResult::Failed { span, label, suggestion, .. } => {
2861                 Err((span, ResolutionError::FailedToResolve { label, suggestion }))
2862             }
2863         }
2864     }
2865
2866     fn new_ast_path_segment(&mut self, ident: Ident) -> ast::PathSegment {
2867         let mut seg = ast::PathSegment::from_ident(ident);
2868         seg.id = self.next_node_id();
2869         seg
2870     }
2871
2872     // For rustdoc.
2873     pub fn graph_root(&self) -> Module<'a> {
2874         self.graph_root
2875     }
2876
2877     // For rustdoc.
2878     pub fn all_macros(&self) -> &FxHashMap<Name, Res> {
2879         &self.all_macros
2880     }
2881 }
2882
2883 fn names_to_string(names: &[Name]) -> String {
2884     let mut result = String::new();
2885     for (i, name) in names.iter().filter(|name| **name != kw::PathRoot).enumerate() {
2886         if i > 0 {
2887             result.push_str("::");
2888         }
2889         if Ident::with_dummy_span(*name).is_raw_guess() {
2890             result.push_str("r#");
2891         }
2892         result.push_str(&name.as_str());
2893     }
2894     result
2895 }
2896
2897 fn path_names_to_string(path: &Path) -> String {
2898     names_to_string(&path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>())
2899 }
2900
2901 /// A somewhat inefficient routine to obtain the name of a module.
2902 fn module_to_string(module: Module<'_>) -> Option<String> {
2903     let mut names = Vec::new();
2904
2905     fn collect_mod(names: &mut Vec<Name>, module: Module<'_>) {
2906         if let ModuleKind::Def(.., name) = module.kind {
2907             if let Some(parent) = module.parent {
2908                 names.push(name);
2909                 collect_mod(names, parent);
2910             }
2911         } else {
2912             names.push(Name::intern("<opaque>"));
2913             collect_mod(names, module.parent.unwrap());
2914         }
2915     }
2916     collect_mod(&mut names, module);
2917
2918     if names.is_empty() {
2919         return None;
2920     }
2921     names.reverse();
2922     Some(names_to_string(&names))
2923 }
2924
2925 #[derive(Copy, Clone, Debug)]
2926 enum CrateLint {
2927     /// Do not issue the lint.
2928     No,
2929
2930     /// This lint applies to some arbitrary path; e.g., `impl ::foo::Bar`.
2931     /// In this case, we can take the span of that path.
2932     SimplePath(NodeId),
2933
2934     /// This lint comes from a `use` statement. In this case, what we
2935     /// care about really is the *root* `use` statement; e.g., if we
2936     /// have nested things like `use a::{b, c}`, we care about the
2937     /// `use a` part.
2938     UsePath { root_id: NodeId, root_span: Span },
2939
2940     /// This is the "trait item" from a fully qualified path. For example,
2941     /// we might be resolving  `X::Y::Z` from a path like `<T as X::Y>::Z`.
2942     /// The `path_span` is the span of the to the trait itself (`X::Y`).
2943     QPathTrait { qpath_id: NodeId, qpath_span: Span },
2944 }
2945
2946 impl CrateLint {
2947     fn node_id(&self) -> Option<NodeId> {
2948         match *self {
2949             CrateLint::No => None,
2950             CrateLint::SimplePath(id)
2951             | CrateLint::UsePath { root_id: id, .. }
2952             | CrateLint::QPathTrait { qpath_id: id, .. } => Some(id),
2953         }
2954     }
2955 }
2956
2957 pub fn provide(providers: &mut Providers<'_>) {
2958     lifetimes::provide(providers);
2959 }