Importing rustc-1.48.0

Bug: 173721343
Change-Id: Ie8184d9a685086ca8a77266d6c608843f40dc9e1
diff --git a/compiler/rustc_resolve/Cargo.toml b/compiler/rustc_resolve/Cargo.toml
new file mode 100644
index 0000000..821f9ea
--- /dev/null
+++ b/compiler/rustc_resolve/Cargo.toml
@@ -0,0 +1,29 @@
+[package]
+authors = ["The Rust Project Developers"]
+name = "rustc_resolve"
+version = "0.0.0"
+edition = "2018"
+
+[lib]
+test = false
+doctest = false
+
+[dependencies]
+bitflags = "1.2.1"
+tracing = "0.1"
+rustc_ast = { path = "../rustc_ast" }
+rustc_arena = { path = "../rustc_arena" }
+rustc_middle = { path = "../rustc_middle" }
+rustc_ast_lowering = { path = "../rustc_ast_lowering" }
+rustc_ast_pretty = { path = "../rustc_ast_pretty" }
+rustc_attr = { path = "../rustc_attr" }
+rustc_data_structures = { path = "../rustc_data_structures" }
+rustc_errors = { path = "../rustc_errors" }
+rustc_expand = { path = "../rustc_expand" }
+rustc_feature = { path = "../rustc_feature" }
+rustc_hir = { path = "../rustc_hir" }
+rustc_index = { path = "../rustc_index" }
+rustc_metadata = { path = "../rustc_metadata" }
+rustc_session = { path = "../rustc_session" }
+rustc_span = { path = "../rustc_span" }
+smallvec = { version = "1.0", features = ["union", "may_dangle"] }
diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs
new file mode 100644
index 0000000..a48d002
--- /dev/null
+++ b/compiler/rustc_resolve/src/build_reduced_graph.rs
@@ -0,0 +1,1443 @@
+//! After we obtain a fresh AST fragment from a macro, code in this module helps to integrate
+//! that fragment into the module structures that are already partially built.
+//!
+//! Items from the fragment are placed into modules,
+//! unexpanded macros in the fragment are visited and registered.
+//! Imports are also considered items and placed into modules here, but not resolved yet.
+
+use crate::def_collector::collect_definitions;
+use crate::imports::{Import, ImportKind};
+use crate::macros::{MacroRulesBinding, MacroRulesScope};
+use crate::Namespace::{self, MacroNS, TypeNS, ValueNS};
+use crate::{CrateLint, Determinacy, PathResult, ResolutionError, VisResolutionError};
+use crate::{
+    ExternPreludeEntry, ModuleOrUniformRoot, ParentScope, PerNS, Resolver, ResolverArenas,
+};
+use crate::{Module, ModuleData, ModuleKind, NameBinding, NameBindingKind, Segment, ToNameBinding};
+
+use rustc_ast::token::{self, Token};
+use rustc_ast::visit::{self, AssocCtxt, Visitor};
+use rustc_ast::{self as ast, Block, ForeignItem, ForeignItemKind, Item, ItemKind, NodeId};
+use rustc_ast::{AssocItem, AssocItemKind, MetaItemKind, StmtKind};
+use rustc_ast_lowering::ResolverAstLowering;
+use rustc_attr as attr;
+use rustc_data_structures::sync::Lrc;
+use rustc_errors::{struct_span_err, Applicability};
+use rustc_expand::base::SyntaxExtension;
+use rustc_expand::expand::AstFragment;
+use rustc_hir::def::{self, *};
+use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_INDEX};
+use rustc_metadata::creader::LoadedMacro;
+use rustc_middle::bug;
+use rustc_middle::hir::exports::Export;
+use rustc_middle::middle::cstore::CrateStore;
+use rustc_middle::ty;
+use rustc_span::hygiene::{ExpnId, MacroKind};
+use rustc_span::source_map::{respan, Spanned};
+use rustc_span::symbol::{kw, sym, Ident, Symbol};
+use rustc_span::Span;
+
+use std::cell::Cell;
+use std::ptr;
+use tracing::debug;
+
+type Res = def::Res<NodeId>;
+
+impl<'a> ToNameBinding<'a> for (Module<'a>, ty::Visibility, Span, ExpnId) {
+    fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
+        arenas.alloc_name_binding(NameBinding {
+            kind: NameBindingKind::Module(self.0),
+            ambiguity: None,
+            vis: self.1,
+            span: self.2,
+            expansion: self.3,
+        })
+    }
+}
+
+impl<'a> ToNameBinding<'a> for (Res, ty::Visibility, Span, ExpnId) {
+    fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
+        arenas.alloc_name_binding(NameBinding {
+            kind: NameBindingKind::Res(self.0, false),
+            ambiguity: None,
+            vis: self.1,
+            span: self.2,
+            expansion: self.3,
+        })
+    }
+}
+
+struct IsMacroExport;
+
+impl<'a> ToNameBinding<'a> for (Res, ty::Visibility, Span, ExpnId, IsMacroExport) {
+    fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
+        arenas.alloc_name_binding(NameBinding {
+            kind: NameBindingKind::Res(self.0, true),
+            ambiguity: None,
+            vis: self.1,
+            span: self.2,
+            expansion: self.3,
+        })
+    }
+}
+
+impl<'a> Resolver<'a> {
+    /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
+    /// otherwise, reports an error.
+    crate fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T)
+    where
+        T: ToNameBinding<'a>,
+    {
+        let binding = def.to_name_binding(self.arenas);
+        let key = self.new_key(ident, ns);
+        if let Err(old_binding) = self.try_define(parent, key, binding) {
+            self.report_conflict(parent, ident, ns, old_binding, &binding);
+        }
+    }
+
+    crate fn get_module(&mut self, def_id: DefId) -> Module<'a> {
+        // If this is a local module, it will be in `module_map`, no need to recalculate it.
+        if let Some(def_id) = def_id.as_local() {
+            return self.module_map[&def_id];
+        }
+
+        // Cache module resolution
+        if let Some(&module) = self.extern_module_map.get(&def_id) {
+            return module;
+        }
+
+        let (name, parent) = if def_id.index == CRATE_DEF_INDEX {
+            // This is the crate root
+            (self.cstore().crate_name_untracked(def_id.krate), None)
+        } else {
+            let def_key = self.cstore().def_key(def_id);
+            let name = def_key
+                .disambiguated_data
+                .data
+                .get_opt_name()
+                .expect("given a DefId that wasn't a module");
+            // This unwrap is safe since we know this isn't the root
+            let parent = Some(self.get_module(DefId {
+                index: def_key.parent.expect("failed to get parent for module"),
+                ..def_id
+            }));
+            (name, parent)
+        };
+
+        // Allocate and return a new module with the information we found
+        let kind = ModuleKind::Def(DefKind::Mod, def_id, name);
+        let module = self.arenas.alloc_module(ModuleData::new(
+            parent,
+            kind,
+            def_id,
+            self.cstore().module_expansion_untracked(def_id, &self.session),
+            self.cstore().get_span_untracked(def_id, &self.session),
+        ));
+        self.extern_module_map.insert(def_id, module);
+        module
+    }
+
+    crate fn macro_def_scope(&mut self, expn_id: ExpnId) -> Module<'a> {
+        let def_id = match expn_id.expn_data().macro_def_id {
+            Some(def_id) => def_id,
+            None => return self.ast_transform_scopes.get(&expn_id).unwrap_or(&self.graph_root),
+        };
+        if let Some(id) = def_id.as_local() {
+            self.local_macro_def_scopes[&id]
+        } else {
+            let module_def_id = ty::DefIdTree::parent(&*self, def_id).unwrap();
+            self.get_module(module_def_id)
+        }
+    }
+
+    crate fn get_macro(&mut self, res: Res) -> Option<Lrc<SyntaxExtension>> {
+        match res {
+            Res::Def(DefKind::Macro(..), def_id) => self.get_macro_by_def_id(def_id),
+            Res::NonMacroAttr(attr_kind) => Some(self.non_macro_attr(attr_kind.is_used())),
+            _ => None,
+        }
+    }
+
+    crate fn get_macro_by_def_id(&mut self, def_id: DefId) -> Option<Lrc<SyntaxExtension>> {
+        if let Some(ext) = self.macro_map.get(&def_id) {
+            return Some(ext.clone());
+        }
+
+        let ext = Lrc::new(match self.cstore().load_macro_untracked(def_id, &self.session) {
+            LoadedMacro::MacroDef(item, edition) => self.compile_macro(&item, edition),
+            LoadedMacro::ProcMacro(ext) => ext,
+        });
+
+        self.macro_map.insert(def_id, ext.clone());
+        Some(ext)
+    }
+
+    crate fn build_reduced_graph(
+        &mut self,
+        fragment: &AstFragment,
+        parent_scope: ParentScope<'a>,
+    ) -> MacroRulesScope<'a> {
+        collect_definitions(self, fragment, parent_scope.expansion);
+        let mut visitor = BuildReducedGraphVisitor { r: self, parent_scope };
+        fragment.visit_with(&mut visitor);
+        visitor.parent_scope.macro_rules
+    }
+
+    crate fn build_reduced_graph_external(&mut self, module: Module<'a>) {
+        let def_id = module.def_id().expect("unpopulated module without a def-id");
+        for child in self.cstore().item_children_untracked(def_id, self.session) {
+            let child = child.map_id(|_| panic!("unexpected id"));
+            BuildReducedGraphVisitor { r: self, parent_scope: ParentScope::module(module) }
+                .build_reduced_graph_for_external_crate_res(child);
+        }
+    }
+}
+
+struct BuildReducedGraphVisitor<'a, 'b> {
+    r: &'b mut Resolver<'a>,
+    parent_scope: ParentScope<'a>,
+}
+
+impl<'a> AsMut<Resolver<'a>> for BuildReducedGraphVisitor<'a, '_> {
+    fn as_mut(&mut self) -> &mut Resolver<'a> {
+        self.r
+    }
+}
+
+impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
+    fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
+        self.resolve_visibility_speculative(vis, false).unwrap_or_else(|err| {
+            self.r.report_vis_error(err);
+            ty::Visibility::Public
+        })
+    }
+
+    fn resolve_visibility_speculative<'ast>(
+        &mut self,
+        vis: &'ast ast::Visibility,
+        speculative: bool,
+    ) -> Result<ty::Visibility, VisResolutionError<'ast>> {
+        let parent_scope = &self.parent_scope;
+        match vis.kind {
+            ast::VisibilityKind::Public => Ok(ty::Visibility::Public),
+            ast::VisibilityKind::Crate(..) => {
+                Ok(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)))
+            }
+            ast::VisibilityKind::Inherited => {
+                Ok(ty::Visibility::Restricted(parent_scope.module.normal_ancestor_id))
+            }
+            ast::VisibilityKind::Restricted { ref path, id, .. } => {
+                // For visibilities we are not ready to provide correct implementation of "uniform
+                // paths" right now, so on 2018 edition we only allow module-relative paths for now.
+                // On 2015 edition visibilities are resolved as crate-relative by default,
+                // so we are prepending a root segment if necessary.
+                let ident = path.segments.get(0).expect("empty path in visibility").ident;
+                let crate_root = if ident.is_path_segment_keyword() {
+                    None
+                } else if ident.span.rust_2015() {
+                    Some(Segment::from_ident(Ident::new(
+                        kw::PathRoot,
+                        path.span.shrink_to_lo().with_ctxt(ident.span.ctxt()),
+                    )))
+                } else {
+                    return Err(VisResolutionError::Relative2018(ident.span, path));
+                };
+
+                let segments = crate_root
+                    .into_iter()
+                    .chain(path.segments.iter().map(|seg| seg.into()))
+                    .collect::<Vec<_>>();
+                let expected_found_error = |res| {
+                    Err(VisResolutionError::ExpectedFound(
+                        path.span,
+                        Segment::names_to_string(&segments),
+                        res,
+                    ))
+                };
+                match self.r.resolve_path(
+                    &segments,
+                    Some(TypeNS),
+                    parent_scope,
+                    !speculative,
+                    path.span,
+                    CrateLint::SimplePath(id),
+                ) {
+                    PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
+                        let res = module.res().expect("visibility resolved to unnamed block");
+                        if !speculative {
+                            self.r.record_partial_res(id, PartialRes::new(res));
+                        }
+                        if module.is_normal() {
+                            if res == Res::Err {
+                                Ok(ty::Visibility::Public)
+                            } else {
+                                let vis = ty::Visibility::Restricted(res.def_id());
+                                if self.r.is_accessible_from(vis, parent_scope.module) {
+                                    Ok(vis)
+                                } else {
+                                    Err(VisResolutionError::AncestorOnly(path.span))
+                                }
+                            }
+                        } else {
+                            expected_found_error(res)
+                        }
+                    }
+                    PathResult::Module(..) => Err(VisResolutionError::ModuleOnly(path.span)),
+                    PathResult::NonModule(partial_res) => {
+                        expected_found_error(partial_res.base_res())
+                    }
+                    PathResult::Failed { span, label, suggestion, .. } => {
+                        Err(VisResolutionError::FailedToResolve(span, label, suggestion))
+                    }
+                    PathResult::Indeterminate => Err(VisResolutionError::Indeterminate(path.span)),
+                }
+            }
+        }
+    }
+
+    fn insert_field_names_local(&mut self, def_id: DefId, vdata: &ast::VariantData) {
+        let field_names = vdata
+            .fields()
+            .iter()
+            .map(|field| respan(field.span, field.ident.map_or(kw::Invalid, |ident| ident.name)))
+            .collect();
+        self.insert_field_names(def_id, field_names);
+    }
+
+    fn insert_field_names(&mut self, def_id: DefId, field_names: Vec<Spanned<Symbol>>) {
+        self.r.field_names.insert(def_id, field_names);
+    }
+
+    fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
+        // If any statements are items, we need to create an anonymous module
+        block.stmts.iter().any(|statement| match statement.kind {
+            StmtKind::Item(_) | StmtKind::MacCall(_) => true,
+            _ => false,
+        })
+    }
+
+    // Add an import to the current module.
+    fn add_import(
+        &mut self,
+        module_path: Vec<Segment>,
+        kind: ImportKind<'a>,
+        span: Span,
+        id: NodeId,
+        item: &ast::Item,
+        root_span: Span,
+        root_id: NodeId,
+        vis: ty::Visibility,
+    ) {
+        let current_module = self.parent_scope.module;
+        let import = self.r.arenas.alloc_import(Import {
+            kind,
+            parent_scope: self.parent_scope,
+            module_path,
+            imported_module: Cell::new(None),
+            span,
+            id,
+            use_span: item.span,
+            use_span_with_attributes: item.span_with_attributes(),
+            has_attributes: !item.attrs.is_empty(),
+            root_span,
+            root_id,
+            vis: Cell::new(vis),
+            used: Cell::new(false),
+        });
+
+        debug!("add_import({:?})", import);
+
+        self.r.indeterminate_imports.push(import);
+        match import.kind {
+            // Don't add unresolved underscore imports to modules
+            ImportKind::Single { target: Ident { name: kw::Underscore, .. }, .. } => {}
+            ImportKind::Single { target, type_ns_only, .. } => {
+                self.r.per_ns(|this, ns| {
+                    if !type_ns_only || ns == TypeNS {
+                        let key = this.new_key(target, ns);
+                        let mut resolution = this.resolution(current_module, key).borrow_mut();
+                        resolution.add_single_import(import);
+                    }
+                });
+            }
+            // We don't add prelude imports to the globs since they only affect lexical scopes,
+            // which are not relevant to import resolution.
+            ImportKind::Glob { is_prelude: true, .. } => {}
+            ImportKind::Glob { .. } => current_module.globs.borrow_mut().push(import),
+            _ => unreachable!(),
+        }
+    }
+
+    fn build_reduced_graph_for_use_tree(
+        &mut self,
+        // This particular use tree
+        use_tree: &ast::UseTree,
+        id: NodeId,
+        parent_prefix: &[Segment],
+        nested: bool,
+        // The whole `use` item
+        item: &Item,
+        vis: ty::Visibility,
+        root_span: Span,
+    ) {
+        debug!(
+            "build_reduced_graph_for_use_tree(parent_prefix={:?}, use_tree={:?}, nested={})",
+            parent_prefix, use_tree, nested
+        );
+
+        let mut prefix_iter = parent_prefix
+            .iter()
+            .cloned()
+            .chain(use_tree.prefix.segments.iter().map(|seg| seg.into()))
+            .peekable();
+
+        // On 2015 edition imports are resolved as crate-relative by default,
+        // so prefixes are prepended with crate root segment if necessary.
+        // The root is prepended lazily, when the first non-empty prefix or terminating glob
+        // appears, so imports in braced groups can have roots prepended independently.
+        let is_glob = matches!(use_tree.kind, ast::UseTreeKind::Glob);
+        let crate_root = match prefix_iter.peek() {
+            Some(seg) if !seg.ident.is_path_segment_keyword() && seg.ident.span.rust_2015() => {
+                Some(seg.ident.span.ctxt())
+            }
+            None if is_glob && use_tree.span.rust_2015() => Some(use_tree.span.ctxt()),
+            _ => None,
+        }
+        .map(|ctxt| {
+            Segment::from_ident(Ident::new(
+                kw::PathRoot,
+                use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt),
+            ))
+        });
+
+        let prefix = crate_root.into_iter().chain(prefix_iter).collect::<Vec<_>>();
+        debug!("build_reduced_graph_for_use_tree: prefix={:?}", prefix);
+
+        let empty_for_self = |prefix: &[Segment]| {
+            prefix.is_empty() || prefix.len() == 1 && prefix[0].ident.name == kw::PathRoot
+        };
+        match use_tree.kind {
+            ast::UseTreeKind::Simple(rename, ..) => {
+                let mut ident = use_tree.ident();
+                let mut module_path = prefix;
+                let mut source = module_path.pop().unwrap();
+                let mut type_ns_only = false;
+
+                if nested {
+                    // Correctly handle `self`
+                    if source.ident.name == kw::SelfLower {
+                        type_ns_only = true;
+
+                        if empty_for_self(&module_path) {
+                            self.r.report_error(
+                                use_tree.span,
+                                ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix,
+                            );
+                            return;
+                        }
+
+                        // Replace `use foo::{ self };` with `use foo;`
+                        source = module_path.pop().unwrap();
+                        if rename.is_none() {
+                            ident = source.ident;
+                        }
+                    }
+                } else {
+                    // Disallow `self`
+                    if source.ident.name == kw::SelfLower {
+                        let parent = module_path.last();
+
+                        let span = match parent {
+                            // only `::self` from `use foo::self as bar`
+                            Some(seg) => seg.ident.span.shrink_to_hi().to(source.ident.span),
+                            None => source.ident.span,
+                        };
+                        let span_with_rename = match rename {
+                            // only `self as bar` from `use foo::self as bar`
+                            Some(rename) => source.ident.span.to(rename.span),
+                            None => source.ident.span,
+                        };
+                        self.r.report_error(
+                            span,
+                            ResolutionError::SelfImportsOnlyAllowedWithin {
+                                root: parent.is_none(),
+                                span_with_rename,
+                            },
+                        );
+
+                        // Error recovery: replace `use foo::self;` with `use foo;`
+                        if let Some(parent) = module_path.pop() {
+                            source = parent;
+                            if rename.is_none() {
+                                ident = source.ident;
+                            }
+                        }
+                    }
+
+                    // Disallow `use $crate;`
+                    if source.ident.name == kw::DollarCrate && module_path.is_empty() {
+                        let crate_root = self.r.resolve_crate_root(source.ident);
+                        let crate_name = match crate_root.kind {
+                            ModuleKind::Def(.., name) => name,
+                            ModuleKind::Block(..) => unreachable!(),
+                        };
+                        // HACK(eddyb) unclear how good this is, but keeping `$crate`
+                        // in `source` breaks `src/test/compile-fail/import-crate-var.rs`,
+                        // while the current crate doesn't have a valid `crate_name`.
+                        if crate_name != kw::Invalid {
+                            // `crate_name` should not be interpreted as relative.
+                            module_path.push(Segment {
+                                ident: Ident { name: kw::PathRoot, span: source.ident.span },
+                                id: Some(self.r.next_node_id()),
+                                has_generic_args: false,
+                            });
+                            source.ident.name = crate_name;
+                        }
+                        if rename.is_none() {
+                            ident.name = crate_name;
+                        }
+
+                        self.r
+                            .session
+                            .struct_span_err(item.span, "`$crate` may not be imported")
+                            .emit();
+                    }
+                }
+
+                if ident.name == kw::Crate {
+                    self.r.session.span_err(
+                        ident.span,
+                        "crate root imports need to be explicitly named: \
+                         `use crate as name;`",
+                    );
+                }
+
+                let kind = ImportKind::Single {
+                    source: source.ident,
+                    target: ident,
+                    source_bindings: PerNS {
+                        type_ns: Cell::new(Err(Determinacy::Undetermined)),
+                        value_ns: Cell::new(Err(Determinacy::Undetermined)),
+                        macro_ns: Cell::new(Err(Determinacy::Undetermined)),
+                    },
+                    target_bindings: PerNS {
+                        type_ns: Cell::new(None),
+                        value_ns: Cell::new(None),
+                        macro_ns: Cell::new(None),
+                    },
+                    type_ns_only,
+                    nested,
+                };
+                self.add_import(
+                    module_path,
+                    kind,
+                    use_tree.span,
+                    id,
+                    item,
+                    root_span,
+                    item.id,
+                    vis,
+                );
+            }
+            ast::UseTreeKind::Glob => {
+                let kind = ImportKind::Glob {
+                    is_prelude: self.r.session.contains_name(&item.attrs, sym::prelude_import),
+                    max_vis: Cell::new(ty::Visibility::Invisible),
+                };
+                self.add_import(prefix, kind, use_tree.span, id, item, root_span, item.id, vis);
+            }
+            ast::UseTreeKind::Nested(ref items) => {
+                // Ensure there is at most one `self` in the list
+                let self_spans = items
+                    .iter()
+                    .filter_map(|&(ref use_tree, _)| {
+                        if let ast::UseTreeKind::Simple(..) = use_tree.kind {
+                            if use_tree.ident().name == kw::SelfLower {
+                                return Some(use_tree.span);
+                            }
+                        }
+
+                        None
+                    })
+                    .collect::<Vec<_>>();
+                if self_spans.len() > 1 {
+                    let mut e = self.r.into_struct_error(
+                        self_spans[0],
+                        ResolutionError::SelfImportCanOnlyAppearOnceInTheList,
+                    );
+
+                    for other_span in self_spans.iter().skip(1) {
+                        e.span_label(*other_span, "another `self` import appears here");
+                    }
+
+                    e.emit();
+                }
+
+                for &(ref tree, id) in items {
+                    self.build_reduced_graph_for_use_tree(
+                        // This particular use tree
+                        tree, id, &prefix, true, // The whole `use` item
+                        item, vis, root_span,
+                    );
+                }
+
+                // Empty groups `a::b::{}` are turned into synthetic `self` imports
+                // `a::b::c::{self as _}`, so that their prefixes are correctly
+                // resolved and checked for privacy/stability/etc.
+                if items.is_empty() && !empty_for_self(&prefix) {
+                    let new_span = prefix[prefix.len() - 1].ident.span;
+                    let tree = ast::UseTree {
+                        prefix: ast::Path::from_ident(Ident::new(kw::SelfLower, new_span)),
+                        kind: ast::UseTreeKind::Simple(
+                            Some(Ident::new(kw::Underscore, new_span)),
+                            ast::DUMMY_NODE_ID,
+                            ast::DUMMY_NODE_ID,
+                        ),
+                        span: use_tree.span,
+                    };
+                    self.build_reduced_graph_for_use_tree(
+                        // This particular use tree
+                        &tree,
+                        id,
+                        &prefix,
+                        true,
+                        // The whole `use` item
+                        item,
+                        ty::Visibility::Invisible,
+                        root_span,
+                    );
+                }
+            }
+        }
+    }
+
+    /// Constructs the reduced graph for one item.
+    fn build_reduced_graph_for_item(&mut self, item: &'b Item) {
+        let parent_scope = &self.parent_scope;
+        let parent = parent_scope.module;
+        let expansion = parent_scope.expansion;
+        let ident = item.ident;
+        let sp = item.span;
+        let vis = self.resolve_visibility(&item.vis);
+
+        match item.kind {
+            ItemKind::Use(ref use_tree) => {
+                self.build_reduced_graph_for_use_tree(
+                    // This particular use tree
+                    use_tree,
+                    item.id,
+                    &[],
+                    false,
+                    // The whole `use` item
+                    item,
+                    vis,
+                    use_tree.span,
+                );
+            }
+
+            ItemKind::ExternCrate(orig_name) => {
+                let module = if orig_name.is_none() && ident.name == kw::SelfLower {
+                    self.r
+                        .session
+                        .struct_span_err(item.span, "`extern crate self;` requires renaming")
+                        .span_suggestion(
+                            item.span,
+                            "try",
+                            "extern crate self as name;".into(),
+                            Applicability::HasPlaceholders,
+                        )
+                        .emit();
+                    return;
+                } else if orig_name == Some(kw::SelfLower) {
+                    self.r.graph_root
+                } else {
+                    let def_id = self.r.local_def_id(item.id);
+                    let crate_id =
+                        self.r.crate_loader.process_extern_crate(item, &self.r.definitions, def_id);
+                    self.r.extern_crate_map.insert(def_id, crate_id);
+                    self.r.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX })
+                };
+
+                let used = self.process_macro_use_imports(item, module);
+                let binding =
+                    (module, ty::Visibility::Public, sp, expansion).to_name_binding(self.r.arenas);
+                let import = self.r.arenas.alloc_import(Import {
+                    kind: ImportKind::ExternCrate { source: orig_name, target: ident },
+                    root_id: item.id,
+                    id: item.id,
+                    parent_scope: self.parent_scope,
+                    imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
+                    has_attributes: !item.attrs.is_empty(),
+                    use_span_with_attributes: item.span_with_attributes(),
+                    use_span: item.span,
+                    root_span: item.span,
+                    span: item.span,
+                    module_path: Vec::new(),
+                    vis: Cell::new(vis),
+                    used: Cell::new(used),
+                });
+                self.r.potentially_unused_imports.push(import);
+                let imported_binding = self.r.import(binding, import);
+                if ptr::eq(parent, self.r.graph_root) {
+                    if let Some(entry) = self.r.extern_prelude.get(&ident.normalize_to_macros_2_0())
+                    {
+                        if expansion != ExpnId::root()
+                            && orig_name.is_some()
+                            && entry.extern_crate_item.is_none()
+                        {
+                            let msg = "macro-expanded `extern crate` items cannot \
+                                       shadow names passed with `--extern`";
+                            self.r.session.span_err(item.span, msg);
+                        }
+                    }
+                    let entry =
+                        self.r.extern_prelude.entry(ident.normalize_to_macros_2_0()).or_insert(
+                            ExternPreludeEntry {
+                                extern_crate_item: None,
+                                introduced_by_item: true,
+                            },
+                        );
+                    entry.extern_crate_item = Some(imported_binding);
+                    if orig_name.is_some() {
+                        entry.introduced_by_item = true;
+                    }
+                }
+                self.r.define(parent, ident, TypeNS, imported_binding);
+            }
+
+            ItemKind::Mod(..) if ident.name == kw::Invalid => {} // Crate root
+
+            ItemKind::Mod(..) => {
+                let def_id = self.r.local_def_id(item.id);
+                let module_kind = ModuleKind::Def(DefKind::Mod, def_id.to_def_id(), ident.name);
+                let module = self.r.arenas.alloc_module(ModuleData {
+                    no_implicit_prelude: parent.no_implicit_prelude || {
+                        self.r.session.contains_name(&item.attrs, sym::no_implicit_prelude)
+                    },
+                    ..ModuleData::new(
+                        Some(parent),
+                        module_kind,
+                        def_id.to_def_id(),
+                        expansion,
+                        item.span,
+                    )
+                });
+                self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion));
+                self.r.module_map.insert(def_id, module);
+
+                // Descend into the module.
+                self.parent_scope.module = module;
+            }
+
+            // These items live in the value namespace.
+            ItemKind::Static(..) => {
+                let res = Res::Def(DefKind::Static, self.r.local_def_id(item.id).to_def_id());
+                self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion));
+            }
+            ItemKind::Const(..) => {
+                let res = Res::Def(DefKind::Const, self.r.local_def_id(item.id).to_def_id());
+                self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion));
+            }
+            ItemKind::Fn(..) => {
+                let res = Res::Def(DefKind::Fn, self.r.local_def_id(item.id).to_def_id());
+                self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion));
+
+                // Functions introducing procedural macros reserve a slot
+                // in the macro namespace as well (see #52225).
+                self.define_macro(item);
+            }
+
+            // These items live in the type namespace.
+            ItemKind::TyAlias(..) => {
+                let res = Res::Def(DefKind::TyAlias, self.r.local_def_id(item.id).to_def_id());
+                self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion));
+            }
+
+            ItemKind::Enum(_, _) => {
+                let def_id = self.r.local_def_id(item.id).to_def_id();
+                self.r.variant_vis.insert(def_id, vis);
+                let module_kind = ModuleKind::Def(DefKind::Enum, def_id, ident.name);
+                let module = self.r.new_module(
+                    parent,
+                    module_kind,
+                    parent.normal_ancestor_id,
+                    expansion,
+                    item.span,
+                );
+                self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion));
+                self.parent_scope.module = module;
+            }
+
+            ItemKind::TraitAlias(..) => {
+                let res = Res::Def(DefKind::TraitAlias, self.r.local_def_id(item.id).to_def_id());
+                self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion));
+            }
+
+            // These items live in both the type and value namespaces.
+            ItemKind::Struct(ref vdata, _) => {
+                // Define a name in the type namespace.
+                let def_id = self.r.local_def_id(item.id).to_def_id();
+                let res = Res::Def(DefKind::Struct, def_id);
+                self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion));
+
+                // Record field names for error reporting.
+                self.insert_field_names_local(def_id, vdata);
+
+                // If this is a tuple or unit struct, define a name
+                // in the value namespace as well.
+                if let Some(ctor_node_id) = vdata.ctor_id() {
+                    // If the structure is marked as non_exhaustive then lower the visibility
+                    // to within the crate.
+                    let mut ctor_vis = if vis == ty::Visibility::Public
+                        && self.r.session.contains_name(&item.attrs, sym::non_exhaustive)
+                    {
+                        ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
+                    } else {
+                        vis
+                    };
+
+                    let mut ret_fields = Vec::with_capacity(vdata.fields().len());
+
+                    for field in vdata.fields() {
+                        // NOTE: The field may be an expansion placeholder, but expansion sets
+                        // correct visibilities for unnamed field placeholders specifically, so the
+                        // constructor visibility should still be determined correctly.
+                        let field_vis = self
+                            .resolve_visibility_speculative(&field.vis, true)
+                            .unwrap_or(ty::Visibility::Public);
+                        if ctor_vis.is_at_least(field_vis, &*self.r) {
+                            ctor_vis = field_vis;
+                        }
+                        ret_fields.push(field_vis);
+                    }
+                    let ctor_res = Res::Def(
+                        DefKind::Ctor(CtorOf::Struct, CtorKind::from_ast(vdata)),
+                        self.r.local_def_id(ctor_node_id).to_def_id(),
+                    );
+                    self.r.define(parent, ident, ValueNS, (ctor_res, ctor_vis, sp, expansion));
+                    self.r.struct_constructors.insert(def_id, (ctor_res, ctor_vis, ret_fields));
+                }
+            }
+
+            ItemKind::Union(ref vdata, _) => {
+                let def_id = self.r.local_def_id(item.id).to_def_id();
+                let res = Res::Def(DefKind::Union, def_id);
+                self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion));
+
+                // Record field names for error reporting.
+                self.insert_field_names_local(def_id, vdata);
+            }
+
+            ItemKind::Trait(..) => {
+                let def_id = self.r.local_def_id(item.id).to_def_id();
+
+                // Add all the items within to a new module.
+                let module_kind = ModuleKind::Def(DefKind::Trait, def_id, ident.name);
+                let module = self.r.new_module(
+                    parent,
+                    module_kind,
+                    parent.normal_ancestor_id,
+                    expansion,
+                    item.span,
+                );
+                self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion));
+                self.parent_scope.module = module;
+            }
+
+            // These items do not add names to modules.
+            ItemKind::Impl { .. } | ItemKind::ForeignMod(..) | ItemKind::GlobalAsm(..) => {}
+
+            ItemKind::MacroDef(..) | ItemKind::MacCall(_) => unreachable!(),
+        }
+    }
+
+    /// Constructs the reduced graph for one foreign item.
+    fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem) {
+        let (res, ns) = match item.kind {
+            ForeignItemKind::Fn(..) => {
+                (Res::Def(DefKind::Fn, self.r.local_def_id(item.id).to_def_id()), ValueNS)
+            }
+            ForeignItemKind::Static(..) => {
+                (Res::Def(DefKind::Static, self.r.local_def_id(item.id).to_def_id()), ValueNS)
+            }
+            ForeignItemKind::TyAlias(..) => {
+                (Res::Def(DefKind::ForeignTy, self.r.local_def_id(item.id).to_def_id()), TypeNS)
+            }
+            ForeignItemKind::MacCall(_) => unreachable!(),
+        };
+        let parent = self.parent_scope.module;
+        let expansion = self.parent_scope.expansion;
+        let vis = self.resolve_visibility(&item.vis);
+        self.r.define(parent, item.ident, ns, (res, vis, item.span, expansion));
+    }
+
+    fn build_reduced_graph_for_block(&mut self, block: &Block) {
+        let parent = self.parent_scope.module;
+        let expansion = self.parent_scope.expansion;
+        if self.block_needs_anonymous_module(block) {
+            let module = self.r.new_module(
+                parent,
+                ModuleKind::Block(block.id),
+                parent.normal_ancestor_id,
+                expansion,
+                block.span,
+            );
+            self.r.block_map.insert(block.id, module);
+            self.parent_scope.module = module; // Descend into the block.
+        }
+    }
+
+    /// Builds the reduced graph for a single item in an external crate.
+    fn build_reduced_graph_for_external_crate_res(&mut self, child: Export<NodeId>) {
+        let parent = self.parent_scope.module;
+        let Export { ident, res, vis, span } = child;
+        let expansion = self.parent_scope.expansion;
+        // Record primary definitions.
+        match res {
+            Res::Def(kind @ (DefKind::Mod | DefKind::Enum | DefKind::Trait), def_id) => {
+                let module = self.r.new_module(
+                    parent,
+                    ModuleKind::Def(kind, def_id, ident.name),
+                    def_id,
+                    expansion,
+                    span,
+                );
+                self.r.define(parent, ident, TypeNS, (module, vis, span, expansion));
+            }
+            Res::Def(
+                DefKind::Struct
+                | DefKind::Union
+                | DefKind::Variant
+                | DefKind::TyAlias
+                | DefKind::ForeignTy
+                | DefKind::OpaqueTy
+                | DefKind::TraitAlias
+                | DefKind::AssocTy,
+                _,
+            )
+            | Res::PrimTy(..)
+            | Res::ToolMod => self.r.define(parent, ident, TypeNS, (res, vis, span, expansion)),
+            Res::Def(
+                DefKind::Fn
+                | DefKind::AssocFn
+                | DefKind::Static
+                | DefKind::Const
+                | DefKind::AssocConst
+                | DefKind::Ctor(..),
+                _,
+            ) => self.r.define(parent, ident, ValueNS, (res, vis, span, expansion)),
+            Res::Def(DefKind::Macro(..), _) | Res::NonMacroAttr(..) => {
+                self.r.define(parent, ident, MacroNS, (res, vis, span, expansion))
+            }
+            Res::Def(
+                DefKind::TyParam
+                | DefKind::ConstParam
+                | DefKind::ExternCrate
+                | DefKind::Use
+                | DefKind::ForeignMod
+                | DefKind::AnonConst
+                | DefKind::Field
+                | DefKind::LifetimeParam
+                | DefKind::GlobalAsm
+                | DefKind::Closure
+                | DefKind::Impl
+                | DefKind::Generator,
+                _,
+            )
+            | Res::Local(..)
+            | Res::SelfTy(..)
+            | Res::SelfCtor(..)
+            | Res::Err => bug!("unexpected resolution: {:?}", res),
+        }
+        // Record some extra data for better diagnostics.
+        let cstore = self.r.cstore();
+        match res {
+            Res::Def(DefKind::Struct | DefKind::Union, def_id) => {
+                let field_names = cstore.struct_field_names_untracked(def_id, self.r.session);
+                self.insert_field_names(def_id, field_names);
+            }
+            Res::Def(DefKind::AssocFn, def_id) => {
+                if cstore
+                    .associated_item_cloned_untracked(def_id, self.r.session)
+                    .fn_has_self_parameter
+                {
+                    self.r.has_self.insert(def_id);
+                }
+            }
+            Res::Def(DefKind::Ctor(CtorOf::Struct, ..), def_id) => {
+                let parent = cstore.def_key(def_id).parent;
+                if let Some(struct_def_id) = parent.map(|index| DefId { index, ..def_id }) {
+                    self.r.struct_constructors.insert(struct_def_id, (res, vis, vec![]));
+                }
+            }
+            _ => {}
+        }
+    }
+
+    fn add_macro_use_binding(
+        &mut self,
+        name: Symbol,
+        binding: &'a NameBinding<'a>,
+        span: Span,
+        allow_shadowing: bool,
+    ) {
+        if self.r.macro_use_prelude.insert(name, binding).is_some() && !allow_shadowing {
+            let msg = format!("`{}` is already in scope", name);
+            let note =
+                "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)";
+            self.r.session.struct_span_err(span, &msg).note(note).emit();
+        }
+    }
+
+    /// Returns `true` if we should consider the underlying `extern crate` to be used.
+    fn process_macro_use_imports(&mut self, item: &Item, module: Module<'a>) -> bool {
+        let mut import_all = None;
+        let mut single_imports = Vec::new();
+        for attr in &item.attrs {
+            if self.r.session.check_name(attr, sym::macro_use) {
+                if self.parent_scope.module.parent.is_some() {
+                    struct_span_err!(
+                        self.r.session,
+                        item.span,
+                        E0468,
+                        "an `extern crate` loading macros must be at the crate root"
+                    )
+                    .emit();
+                }
+                if let ItemKind::ExternCrate(Some(orig_name)) = item.kind {
+                    if orig_name == kw::SelfLower {
+                        self.r
+                            .session
+                            .struct_span_err(
+                                attr.span,
+                                "`#[macro_use]` is not supported on `extern crate self`",
+                            )
+                            .emit();
+                    }
+                }
+                let ill_formed =
+                    |span| struct_span_err!(self.r.session, span, E0466, "bad macro import").emit();
+                match attr.meta() {
+                    Some(meta) => match meta.kind {
+                        MetaItemKind::Word => {
+                            import_all = Some(meta.span);
+                            break;
+                        }
+                        MetaItemKind::List(nested_metas) => {
+                            for nested_meta in nested_metas {
+                                match nested_meta.ident() {
+                                    Some(ident) if nested_meta.is_word() => {
+                                        single_imports.push(ident)
+                                    }
+                                    _ => ill_formed(nested_meta.span()),
+                                }
+                            }
+                        }
+                        MetaItemKind::NameValue(..) => ill_formed(meta.span),
+                    },
+                    None => ill_formed(attr.span),
+                }
+            }
+        }
+
+        let macro_use_import = |this: &Self, span| {
+            this.r.arenas.alloc_import(Import {
+                kind: ImportKind::MacroUse,
+                root_id: item.id,
+                id: item.id,
+                parent_scope: this.parent_scope,
+                imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
+                use_span_with_attributes: item.span_with_attributes(),
+                has_attributes: !item.attrs.is_empty(),
+                use_span: item.span,
+                root_span: span,
+                span,
+                module_path: Vec::new(),
+                vis: Cell::new(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))),
+                used: Cell::new(false),
+            })
+        };
+
+        let allow_shadowing = self.parent_scope.expansion == ExpnId::root();
+        if let Some(span) = import_all {
+            let import = macro_use_import(self, span);
+            self.r.potentially_unused_imports.push(import);
+            module.for_each_child(self, |this, ident, ns, binding| {
+                if ns == MacroNS {
+                    let imported_binding = this.r.import(binding, import);
+                    this.add_macro_use_binding(ident.name, imported_binding, span, allow_shadowing);
+                }
+            });
+        } else {
+            for ident in single_imports.iter().cloned() {
+                let result = self.r.resolve_ident_in_module(
+                    ModuleOrUniformRoot::Module(module),
+                    ident,
+                    MacroNS,
+                    &self.parent_scope,
+                    false,
+                    ident.span,
+                );
+                if let Ok(binding) = result {
+                    let import = macro_use_import(self, ident.span);
+                    self.r.potentially_unused_imports.push(import);
+                    let imported_binding = self.r.import(binding, import);
+                    self.add_macro_use_binding(
+                        ident.name,
+                        imported_binding,
+                        ident.span,
+                        allow_shadowing,
+                    );
+                } else {
+                    struct_span_err!(self.r.session, ident.span, E0469, "imported macro not found")
+                        .emit();
+                }
+            }
+        }
+        import_all.is_some() || !single_imports.is_empty()
+    }
+
+    /// Returns `true` if this attribute list contains `macro_use`.
+    fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool {
+        for attr in attrs {
+            if self.r.session.check_name(attr, sym::macro_escape) {
+                let msg = "`#[macro_escape]` is a deprecated synonym for `#[macro_use]`";
+                let mut err = self.r.session.struct_span_warn(attr.span, msg);
+                if let ast::AttrStyle::Inner = attr.style {
+                    err.help("try an outer attribute: `#[macro_use]`").emit();
+                } else {
+                    err.emit();
+                }
+            } else if !self.r.session.check_name(attr, sym::macro_use) {
+                continue;
+            }
+
+            if !attr.is_word() {
+                self.r.session.span_err(attr.span, "arguments to `macro_use` are not allowed here");
+            }
+            return true;
+        }
+
+        false
+    }
+
+    fn visit_invoc(&mut self, id: NodeId) -> MacroRulesScope<'a> {
+        let invoc_id = id.placeholder_to_expn_id();
+
+        self.parent_scope.module.unexpanded_invocations.borrow_mut().insert(invoc_id);
+
+        let old_parent_scope = self.r.invocation_parent_scopes.insert(invoc_id, self.parent_scope);
+        assert!(old_parent_scope.is_none(), "invocation data is reset for an invocation");
+
+        MacroRulesScope::Invocation(invoc_id)
+    }
+
+    fn proc_macro_stub(&self, item: &ast::Item) -> Option<(MacroKind, Ident, Span)> {
+        if self.r.session.contains_name(&item.attrs, sym::proc_macro) {
+            return Some((MacroKind::Bang, item.ident, item.span));
+        } else if self.r.session.contains_name(&item.attrs, sym::proc_macro_attribute) {
+            return Some((MacroKind::Attr, item.ident, item.span));
+        } else if let Some(attr) = self.r.session.find_by_name(&item.attrs, sym::proc_macro_derive)
+        {
+            if let Some(nested_meta) = attr.meta_item_list().and_then(|list| list.get(0).cloned()) {
+                if let Some(ident) = nested_meta.ident() {
+                    return Some((MacroKind::Derive, ident, ident.span));
+                }
+            }
+        }
+        None
+    }
+
+    // Mark the given macro as unused unless its name starts with `_`.
+    // Macro uses will remove items from this set, and the remaining
+    // items will be reported as `unused_macros`.
+    fn insert_unused_macro(
+        &mut self,
+        ident: Ident,
+        def_id: LocalDefId,
+        node_id: NodeId,
+        span: Span,
+    ) {
+        if !ident.as_str().starts_with('_') {
+            self.r.unused_macros.insert(def_id, (node_id, span));
+        }
+    }
+
+    fn define_macro(&mut self, item: &ast::Item) -> MacroRulesScope<'a> {
+        let parent_scope = self.parent_scope;
+        let expansion = parent_scope.expansion;
+        let def_id = self.r.local_def_id(item.id);
+        let (ext, ident, span, macro_rules) = match &item.kind {
+            ItemKind::MacroDef(def) => {
+                let ext = Lrc::new(self.r.compile_macro(item, self.r.session.edition()));
+                (ext, item.ident, item.span, def.macro_rules)
+            }
+            ItemKind::Fn(..) => match self.proc_macro_stub(item) {
+                Some((macro_kind, ident, span)) => {
+                    self.r.proc_macro_stubs.insert(def_id);
+                    (self.r.dummy_ext(macro_kind), ident, span, false)
+                }
+                None => return parent_scope.macro_rules,
+            },
+            _ => unreachable!(),
+        };
+
+        let res = Res::Def(DefKind::Macro(ext.macro_kind()), def_id.to_def_id());
+        self.r.macro_map.insert(def_id.to_def_id(), ext);
+        self.r.local_macro_def_scopes.insert(def_id, parent_scope.module);
+
+        if macro_rules {
+            let ident = ident.normalize_to_macros_2_0();
+            self.r.macro_names.insert(ident);
+            let is_macro_export = self.r.session.contains_name(&item.attrs, sym::macro_export);
+            let vis = if is_macro_export {
+                ty::Visibility::Public
+            } else {
+                ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
+            };
+            let binding = (res, vis, span, expansion).to_name_binding(self.r.arenas);
+            self.r.set_binding_parent_module(binding, parent_scope.module);
+            self.r.all_macros.insert(ident.name, res);
+            if is_macro_export {
+                let module = self.r.graph_root;
+                self.r.define(module, ident, MacroNS, (res, vis, span, expansion, IsMacroExport));
+            } else {
+                self.r.check_reserved_macro_name(ident, res);
+                self.insert_unused_macro(ident, def_id, item.id, span);
+            }
+            MacroRulesScope::Binding(self.r.arenas.alloc_macro_rules_binding(MacroRulesBinding {
+                parent_macro_rules_scope: parent_scope.macro_rules,
+                binding,
+                ident,
+            }))
+        } else {
+            let module = parent_scope.module;
+            let vis = match item.kind {
+                // Visibilities must not be resolved non-speculatively twice
+                // and we already resolved this one as a `fn` item visibility.
+                ItemKind::Fn(..) => self
+                    .resolve_visibility_speculative(&item.vis, true)
+                    .unwrap_or(ty::Visibility::Public),
+                _ => self.resolve_visibility(&item.vis),
+            };
+            if vis != ty::Visibility::Public {
+                self.insert_unused_macro(ident, def_id, item.id, span);
+            }
+            self.r.define(module, ident, MacroNS, (res, vis, span, expansion));
+            self.parent_scope.macro_rules
+        }
+    }
+}
+
+macro_rules! method {
+    ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
+        fn $visit(&mut self, node: &'b $ty) {
+            if let $invoc(..) = node.kind {
+                self.visit_invoc(node.id);
+            } else {
+                visit::$walk(self, node);
+            }
+        }
+    };
+}
+
+impl<'a, 'b> Visitor<'b> for BuildReducedGraphVisitor<'a, 'b> {
+    method!(visit_expr: ast::Expr, ast::ExprKind::MacCall, walk_expr);
+    method!(visit_pat: ast::Pat, ast::PatKind::MacCall, walk_pat);
+    method!(visit_ty: ast::Ty, ast::TyKind::MacCall, walk_ty);
+
+    fn visit_item(&mut self, item: &'b Item) {
+        let macro_use = match item.kind {
+            ItemKind::MacroDef(..) => {
+                self.parent_scope.macro_rules = self.define_macro(item);
+                return;
+            }
+            ItemKind::MacCall(..) => {
+                self.parent_scope.macro_rules = self.visit_invoc(item.id);
+                return;
+            }
+            ItemKind::Mod(..) => self.contains_macro_use(&item.attrs),
+            _ => false,
+        };
+        let orig_current_module = self.parent_scope.module;
+        let orig_current_macro_rules_scope = self.parent_scope.macro_rules;
+        self.build_reduced_graph_for_item(item);
+        visit::walk_item(self, item);
+        self.parent_scope.module = orig_current_module;
+        if !macro_use {
+            self.parent_scope.macro_rules = orig_current_macro_rules_scope;
+        }
+    }
+
+    fn visit_stmt(&mut self, stmt: &'b ast::Stmt) {
+        if let ast::StmtKind::MacCall(..) = stmt.kind {
+            self.parent_scope.macro_rules = self.visit_invoc(stmt.id);
+        } else {
+            visit::walk_stmt(self, stmt);
+        }
+    }
+
+    fn visit_foreign_item(&mut self, foreign_item: &'b ForeignItem) {
+        if let ForeignItemKind::MacCall(_) = foreign_item.kind {
+            self.visit_invoc(foreign_item.id);
+            return;
+        }
+
+        self.build_reduced_graph_for_foreign_item(foreign_item);
+        visit::walk_foreign_item(self, foreign_item);
+    }
+
+    fn visit_block(&mut self, block: &'b Block) {
+        let orig_current_module = self.parent_scope.module;
+        let orig_current_macro_rules_scope = self.parent_scope.macro_rules;
+        self.build_reduced_graph_for_block(block);
+        visit::walk_block(self, block);
+        self.parent_scope.module = orig_current_module;
+        self.parent_scope.macro_rules = orig_current_macro_rules_scope;
+    }
+
+    fn visit_assoc_item(&mut self, item: &'b AssocItem, ctxt: AssocCtxt) {
+        let parent = self.parent_scope.module;
+
+        if let AssocItemKind::MacCall(_) = item.kind {
+            self.visit_invoc(item.id);
+            return;
+        }
+
+        if let AssocCtxt::Impl = ctxt {
+            self.resolve_visibility(&item.vis);
+            visit::walk_assoc_item(self, item, ctxt);
+            return;
+        }
+
+        // Add the item to the trait info.
+        let item_def_id = self.r.local_def_id(item.id).to_def_id();
+        let (res, ns) = match item.kind {
+            AssocItemKind::Const(..) => (Res::Def(DefKind::AssocConst, item_def_id), ValueNS),
+            AssocItemKind::Fn(_, ref sig, _, _) => {
+                if sig.decl.has_self() {
+                    self.r.has_self.insert(item_def_id);
+                }
+                (Res::Def(DefKind::AssocFn, item_def_id), ValueNS)
+            }
+            AssocItemKind::TyAlias(..) => (Res::Def(DefKind::AssocTy, item_def_id), TypeNS),
+            AssocItemKind::MacCall(_) => bug!(), // handled above
+        };
+
+        let vis = ty::Visibility::Public;
+        let expansion = self.parent_scope.expansion;
+        self.r.define(parent, item.ident, ns, (res, vis, item.span, expansion));
+
+        visit::walk_assoc_item(self, item, ctxt);
+    }
+
+    fn visit_token(&mut self, t: Token) {
+        if let token::Interpolated(nt) = t.kind {
+            if let token::NtExpr(ref expr) = *nt {
+                if let ast::ExprKind::MacCall(..) = expr.kind {
+                    self.visit_invoc(expr.id);
+                }
+            }
+        }
+    }
+
+    fn visit_attribute(&mut self, attr: &'b ast::Attribute) {
+        if !attr.is_doc_comment() && attr::is_builtin_attr(attr) {
+            self.r
+                .builtin_attrs
+                .push((attr.get_normal_item().path.segments[0].ident, self.parent_scope));
+        }
+        visit::walk_attribute(self, attr);
+    }
+
+    fn visit_arm(&mut self, arm: &'b ast::Arm) {
+        if arm.is_placeholder {
+            self.visit_invoc(arm.id);
+        } else {
+            visit::walk_arm(self, arm);
+        }
+    }
+
+    fn visit_field(&mut self, f: &'b ast::Field) {
+        if f.is_placeholder {
+            self.visit_invoc(f.id);
+        } else {
+            visit::walk_field(self, f);
+        }
+    }
+
+    fn visit_field_pattern(&mut self, fp: &'b ast::FieldPat) {
+        if fp.is_placeholder {
+            self.visit_invoc(fp.id);
+        } else {
+            visit::walk_field_pattern(self, fp);
+        }
+    }
+
+    fn visit_generic_param(&mut self, param: &'b ast::GenericParam) {
+        if param.is_placeholder {
+            self.visit_invoc(param.id);
+        } else {
+            visit::walk_generic_param(self, param);
+        }
+    }
+
+    fn visit_param(&mut self, p: &'b ast::Param) {
+        if p.is_placeholder {
+            self.visit_invoc(p.id);
+        } else {
+            visit::walk_param(self, p);
+        }
+    }
+
+    fn visit_struct_field(&mut self, sf: &'b ast::StructField) {
+        if sf.is_placeholder {
+            self.visit_invoc(sf.id);
+        } else {
+            self.resolve_visibility(&sf.vis);
+            visit::walk_struct_field(self, sf);
+        }
+    }
+
+    // Constructs the reduced graph for one variant. Variants exist in the
+    // type and value namespaces.
+    fn visit_variant(&mut self, variant: &'b ast::Variant) {
+        if variant.is_placeholder {
+            self.visit_invoc(variant.id);
+            return;
+        }
+
+        let parent = self.parent_scope.module;
+        let vis = self.r.variant_vis[&parent.def_id().expect("enum without def-id")];
+        let expn_id = self.parent_scope.expansion;
+        let ident = variant.ident;
+
+        // Define a name in the type namespace.
+        let def_id = self.r.local_def_id(variant.id).to_def_id();
+        let res = Res::Def(DefKind::Variant, def_id);
+        self.r.define(parent, ident, TypeNS, (res, vis, variant.span, expn_id));
+
+        // If the variant is marked as non_exhaustive then lower the visibility to within the
+        // crate.
+        let mut ctor_vis = vis;
+        let has_non_exhaustive = self.r.session.contains_name(&variant.attrs, sym::non_exhaustive);
+        if has_non_exhaustive && vis == ty::Visibility::Public {
+            ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
+        }
+
+        // Define a constructor name in the value namespace.
+        // Braced variants, unlike structs, generate unusable names in
+        // value namespace, they are reserved for possible future use.
+        // It's ok to use the variant's id as a ctor id since an
+        // error will be reported on any use of such resolution anyway.
+        let ctor_node_id = variant.data.ctor_id().unwrap_or(variant.id);
+        let ctor_def_id = self.r.local_def_id(ctor_node_id).to_def_id();
+        let ctor_kind = CtorKind::from_ast(&variant.data);
+        let ctor_res = Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id);
+        self.r.define(parent, ident, ValueNS, (ctor_res, ctor_vis, variant.span, expn_id));
+        // Record field names for error reporting.
+        self.insert_field_names_local(ctor_def_id, &variant.data);
+
+        visit::walk_variant(self, variant);
+    }
+}
diff --git a/compiler/rustc_resolve/src/check_unused.rs b/compiler/rustc_resolve/src/check_unused.rs
new file mode 100644
index 0000000..89ce89b
--- /dev/null
+++ b/compiler/rustc_resolve/src/check_unused.rs
@@ -0,0 +1,328 @@
+//
+// Unused import checking
+//
+// Although this is mostly a lint pass, it lives in here because it depends on
+// resolve data structures and because it finalises the privacy information for
+// `use` items.
+//
+// Unused trait imports can't be checked until the method resolution. We save
+// candidates here, and do the actual check in librustc_typeck/check_unused.rs.
+//
+// Checking for unused imports is split into three steps:
+//
+//  - `UnusedImportCheckVisitor` walks the AST to find all the unused imports
+//    inside of `UseTree`s, recording their `NodeId`s and grouping them by
+//    the parent `use` item
+//
+//  - `calc_unused_spans` then walks over all the `use` items marked in the
+//    previous step to collect the spans associated with the `NodeId`s and to
+//    calculate the spans that can be removed by rustfix; This is done in a
+//    separate step to be able to collapse the adjacent spans that rustfix
+//    will remove
+//
+//  - `check_crate` finally emits the diagnostics based on the data generated
+//    in the last step
+
+use crate::imports::ImportKind;
+use crate::Resolver;
+
+use rustc_ast as ast;
+use rustc_ast::node_id::NodeMap;
+use rustc_ast::visit::{self, Visitor};
+use rustc_ast_lowering::ResolverAstLowering;
+use rustc_data_structures::fx::FxHashSet;
+use rustc_errors::pluralize;
+use rustc_middle::ty;
+use rustc_session::lint::builtin::{MACRO_USE_EXTERN_CRATE, UNUSED_IMPORTS};
+use rustc_session::lint::BuiltinLintDiagnostics;
+use rustc_span::{MultiSpan, Span, DUMMY_SP};
+
+struct UnusedImport<'a> {
+    use_tree: &'a ast::UseTree,
+    use_tree_id: ast::NodeId,
+    item_span: Span,
+    unused: FxHashSet<ast::NodeId>,
+}
+
+impl<'a> UnusedImport<'a> {
+    fn add(&mut self, id: ast::NodeId) {
+        self.unused.insert(id);
+    }
+}
+
+struct UnusedImportCheckVisitor<'a, 'b> {
+    r: &'a mut Resolver<'b>,
+    /// All the (so far) unused imports, grouped path list
+    unused_imports: NodeMap<UnusedImport<'a>>,
+    base_use_tree: Option<&'a ast::UseTree>,
+    base_id: ast::NodeId,
+    item_span: Span,
+}
+
+impl<'a, 'b> UnusedImportCheckVisitor<'a, 'b> {
+    // We have information about whether `use` (import) items are actually
+    // used now. If an import is not used at all, we signal a lint error.
+    fn check_import(&mut self, id: ast::NodeId) {
+        let mut used = false;
+        self.r.per_ns(|this, ns| used |= this.used_imports.contains(&(id, ns)));
+        let def_id = self.r.local_def_id(id);
+        if !used {
+            if self.r.maybe_unused_trait_imports.contains(&def_id) {
+                // Check later.
+                return;
+            }
+            self.unused_import(self.base_id).add(id);
+        } else {
+            // This trait import is definitely used, in a way other than
+            // method resolution.
+            self.r.maybe_unused_trait_imports.remove(&def_id);
+            if let Some(i) = self.unused_imports.get_mut(&self.base_id) {
+                i.unused.remove(&id);
+            }
+        }
+    }
+
+    fn unused_import(&mut self, id: ast::NodeId) -> &mut UnusedImport<'a> {
+        let use_tree_id = self.base_id;
+        let use_tree = self.base_use_tree.unwrap();
+        let item_span = self.item_span;
+
+        self.unused_imports.entry(id).or_insert_with(|| UnusedImport {
+            use_tree,
+            use_tree_id,
+            item_span,
+            unused: FxHashSet::default(),
+        })
+    }
+}
+
+impl<'a, 'b> Visitor<'a> for UnusedImportCheckVisitor<'a, 'b> {
+    fn visit_item(&mut self, item: &'a ast::Item) {
+        self.item_span = item.span;
+
+        // Ignore is_public import statements because there's no way to be sure
+        // whether they're used or not. Also ignore imports with a dummy span
+        // because this means that they were generated in some fashion by the
+        // compiler and we don't need to consider them.
+        if let ast::ItemKind::Use(..) = item.kind {
+            if item.vis.kind.is_pub() || item.span.is_dummy() {
+                return;
+            }
+        }
+
+        visit::walk_item(self, item);
+    }
+
+    fn visit_use_tree(&mut self, use_tree: &'a ast::UseTree, id: ast::NodeId, nested: bool) {
+        // Use the base UseTree's NodeId as the item id
+        // This allows the grouping of all the lints in the same item
+        if !nested {
+            self.base_id = id;
+            self.base_use_tree = Some(use_tree);
+        }
+
+        if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
+            if items.is_empty() {
+                self.unused_import(self.base_id).add(id);
+            }
+        } else {
+            self.check_import(id);
+        }
+
+        visit::walk_use_tree(self, use_tree, id);
+    }
+}
+
+enum UnusedSpanResult {
+    Used,
+    FlatUnused(Span, Span),
+    NestedFullUnused(Vec<Span>, Span),
+    NestedPartialUnused(Vec<Span>, Vec<Span>),
+}
+
+fn calc_unused_spans(
+    unused_import: &UnusedImport<'_>,
+    use_tree: &ast::UseTree,
+    use_tree_id: ast::NodeId,
+) -> UnusedSpanResult {
+    // The full span is the whole item's span if this current tree is not nested inside another
+    // This tells rustfix to remove the whole item if all the imports are unused
+    let full_span = if unused_import.use_tree.span == use_tree.span {
+        unused_import.item_span
+    } else {
+        use_tree.span
+    };
+    match use_tree.kind {
+        ast::UseTreeKind::Simple(..) | ast::UseTreeKind::Glob => {
+            if unused_import.unused.contains(&use_tree_id) {
+                UnusedSpanResult::FlatUnused(use_tree.span, full_span)
+            } else {
+                UnusedSpanResult::Used
+            }
+        }
+        ast::UseTreeKind::Nested(ref nested) => {
+            if nested.is_empty() {
+                return UnusedSpanResult::FlatUnused(use_tree.span, full_span);
+            }
+
+            let mut unused_spans = Vec::new();
+            let mut to_remove = Vec::new();
+            let mut all_nested_unused = true;
+            let mut previous_unused = false;
+            for (pos, (use_tree, use_tree_id)) in nested.iter().enumerate() {
+                let remove = match calc_unused_spans(unused_import, use_tree, *use_tree_id) {
+                    UnusedSpanResult::Used => {
+                        all_nested_unused = false;
+                        None
+                    }
+                    UnusedSpanResult::FlatUnused(span, remove) => {
+                        unused_spans.push(span);
+                        Some(remove)
+                    }
+                    UnusedSpanResult::NestedFullUnused(mut spans, remove) => {
+                        unused_spans.append(&mut spans);
+                        Some(remove)
+                    }
+                    UnusedSpanResult::NestedPartialUnused(mut spans, mut to_remove_extra) => {
+                        all_nested_unused = false;
+                        unused_spans.append(&mut spans);
+                        to_remove.append(&mut to_remove_extra);
+                        None
+                    }
+                };
+                if let Some(remove) = remove {
+                    let remove_span = if nested.len() == 1 {
+                        remove
+                    } else if pos == nested.len() - 1 || !all_nested_unused {
+                        // Delete everything from the end of the last import, to delete the
+                        // previous comma
+                        nested[pos - 1].0.span.shrink_to_hi().to(use_tree.span)
+                    } else {
+                        // Delete everything until the next import, to delete the trailing commas
+                        use_tree.span.to(nested[pos + 1].0.span.shrink_to_lo())
+                    };
+
+                    // Try to collapse adjacent spans into a single one. This prevents all cases of
+                    // overlapping removals, which are not supported by rustfix
+                    if previous_unused && !to_remove.is_empty() {
+                        let previous = to_remove.pop().unwrap();
+                        to_remove.push(previous.to(remove_span));
+                    } else {
+                        to_remove.push(remove_span);
+                    }
+                }
+                previous_unused = remove.is_some();
+            }
+            if unused_spans.is_empty() {
+                UnusedSpanResult::Used
+            } else if all_nested_unused {
+                UnusedSpanResult::NestedFullUnused(unused_spans, full_span)
+            } else {
+                UnusedSpanResult::NestedPartialUnused(unused_spans, to_remove)
+            }
+        }
+    }
+}
+
+impl Resolver<'_> {
+    crate fn check_unused(&mut self, krate: &ast::Crate) {
+        for import in self.potentially_unused_imports.iter() {
+            match import.kind {
+                _ if import.used.get()
+                    || import.vis.get() == ty::Visibility::Public
+                    || import.span.is_dummy() =>
+                {
+                    if let ImportKind::MacroUse = import.kind {
+                        if !import.span.is_dummy() {
+                            self.lint_buffer.buffer_lint(
+                                MACRO_USE_EXTERN_CRATE,
+                                import.id,
+                                import.span,
+                                "deprecated `#[macro_use]` attribute used to \
+                                import macros should be replaced at use sites \
+                                with a `use` item to import the macro \
+                                instead",
+                            );
+                        }
+                    }
+                }
+                ImportKind::ExternCrate { .. } => {
+                    let def_id = self.local_def_id(import.id);
+                    self.maybe_unused_extern_crates.push((def_id, import.span));
+                }
+                ImportKind::MacroUse => {
+                    let msg = "unused `#[macro_use]` import";
+                    self.lint_buffer.buffer_lint(UNUSED_IMPORTS, import.id, import.span, msg);
+                }
+                _ => {}
+            }
+        }
+
+        let mut visitor = UnusedImportCheckVisitor {
+            r: self,
+            unused_imports: Default::default(),
+            base_use_tree: None,
+            base_id: ast::DUMMY_NODE_ID,
+            item_span: DUMMY_SP,
+        };
+        visit::walk_crate(&mut visitor, krate);
+
+        for unused in visitor.unused_imports.values() {
+            let mut fixes = Vec::new();
+            let mut spans = match calc_unused_spans(unused, unused.use_tree, unused.use_tree_id) {
+                UnusedSpanResult::Used => continue,
+                UnusedSpanResult::FlatUnused(span, remove) => {
+                    fixes.push((remove, String::new()));
+                    vec![span]
+                }
+                UnusedSpanResult::NestedFullUnused(spans, remove) => {
+                    fixes.push((remove, String::new()));
+                    spans
+                }
+                UnusedSpanResult::NestedPartialUnused(spans, remove) => {
+                    for fix in &remove {
+                        fixes.push((*fix, String::new()));
+                    }
+                    spans
+                }
+            };
+
+            let len = spans.len();
+            spans.sort();
+            let ms = MultiSpan::from_spans(spans.clone());
+            let mut span_snippets = spans
+                .iter()
+                .filter_map(|s| match visitor.r.session.source_map().span_to_snippet(*s) {
+                    Ok(s) => Some(format!("`{}`", s)),
+                    _ => None,
+                })
+                .collect::<Vec<String>>();
+            span_snippets.sort();
+            let msg = format!(
+                "unused import{}{}",
+                pluralize!(len),
+                if !span_snippets.is_empty() {
+                    format!(": {}", span_snippets.join(", "))
+                } else {
+                    String::new()
+                }
+            );
+
+            let fix_msg = if fixes.len() == 1 && fixes[0].0 == unused.item_span {
+                "remove the whole `use` item"
+            } else if spans.len() > 1 {
+                "remove the unused imports"
+            } else {
+                "remove the unused import"
+            };
+
+            visitor.r.lint_buffer.buffer_lint_with_diagnostic(
+                UNUSED_IMPORTS,
+                unused.use_tree_id,
+                ms,
+                &msg,
+                BuiltinLintDiagnostics::UnusedImports(fix_msg.into(), fixes),
+            );
+        }
+    }
+}
diff --git a/compiler/rustc_resolve/src/def_collector.rs b/compiler/rustc_resolve/src/def_collector.rs
new file mode 100644
index 0000000..5d5088d
--- /dev/null
+++ b/compiler/rustc_resolve/src/def_collector.rs
@@ -0,0 +1,293 @@
+use crate::Resolver;
+use rustc_ast::token::{self, Token};
+use rustc_ast::visit::{self, FnKind};
+use rustc_ast::walk_list;
+use rustc_ast::*;
+use rustc_ast_lowering::ResolverAstLowering;
+use rustc_expand::expand::AstFragment;
+use rustc_hir::def_id::LocalDefId;
+use rustc_hir::definitions::*;
+use rustc_span::hygiene::ExpnId;
+use rustc_span::symbol::{kw, sym};
+use rustc_span::Span;
+use tracing::debug;
+
+crate fn collect_definitions(
+    resolver: &mut Resolver<'_>,
+    fragment: &AstFragment,
+    expansion: ExpnId,
+) {
+    let parent_def = resolver.invocation_parents[&expansion];
+    fragment.visit_with(&mut DefCollector { resolver, parent_def, expansion });
+}
+
+/// Creates `DefId`s for nodes in the AST.
+struct DefCollector<'a, 'b> {
+    resolver: &'a mut Resolver<'b>,
+    parent_def: LocalDefId,
+    expansion: ExpnId,
+}
+
+impl<'a, 'b> DefCollector<'a, 'b> {
+    fn create_def(&mut self, node_id: NodeId, data: DefPathData, span: Span) -> LocalDefId {
+        let parent_def = self.parent_def;
+        debug!("create_def(node_id={:?}, data={:?}, parent_def={:?})", node_id, data, parent_def);
+        self.resolver.create_def(parent_def, node_id, data, self.expansion, span)
+    }
+
+    fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_def: LocalDefId, f: F) {
+        let orig_parent_def = std::mem::replace(&mut self.parent_def, parent_def);
+        f(self);
+        self.parent_def = orig_parent_def;
+    }
+
+    fn collect_field(&mut self, field: &'a StructField, index: Option<usize>) {
+        let index = |this: &Self| {
+            index.unwrap_or_else(|| {
+                let node_id = NodeId::placeholder_from_expn_id(this.expansion);
+                this.resolver.placeholder_field_indices[&node_id]
+            })
+        };
+
+        if field.is_placeholder {
+            let old_index = self.resolver.placeholder_field_indices.insert(field.id, index(self));
+            assert!(old_index.is_none(), "placeholder field index is reset for a node ID");
+            self.visit_macro_invoc(field.id);
+        } else {
+            let name = field.ident.map_or_else(|| sym::integer(index(self)), |ident| ident.name);
+            let def = self.create_def(field.id, DefPathData::ValueNs(name), field.span);
+            self.with_parent(def, |this| visit::walk_struct_field(this, field));
+        }
+    }
+
+    fn visit_macro_invoc(&mut self, id: NodeId) {
+        let old_parent =
+            self.resolver.invocation_parents.insert(id.placeholder_to_expn_id(), self.parent_def);
+        assert!(old_parent.is_none(), "parent `LocalDefId` is reset for an invocation");
+    }
+}
+
+impl<'a, 'b> visit::Visitor<'a> for DefCollector<'a, 'b> {
+    fn visit_item(&mut self, i: &'a Item) {
+        debug!("visit_item: {:?}", i);
+
+        // Pick the def data. This need not be unique, but the more
+        // information we encapsulate into, the better
+        let def_data = match &i.kind {
+            ItemKind::Impl { .. } => DefPathData::Impl,
+            ItemKind::Mod(..) if i.ident.name == kw::Invalid => {
+                return visit::walk_item(self, i);
+            }
+            ItemKind::Mod(..)
+            | ItemKind::Trait(..)
+            | ItemKind::TraitAlias(..)
+            | ItemKind::Enum(..)
+            | ItemKind::Struct(..)
+            | ItemKind::Union(..)
+            | ItemKind::ExternCrate(..)
+            | ItemKind::ForeignMod(..)
+            | ItemKind::TyAlias(..) => DefPathData::TypeNs(i.ident.name),
+            ItemKind::Static(..) | ItemKind::Const(..) | ItemKind::Fn(..) => {
+                DefPathData::ValueNs(i.ident.name)
+            }
+            ItemKind::MacroDef(..) => DefPathData::MacroNs(i.ident.name),
+            ItemKind::MacCall(..) => return self.visit_macro_invoc(i.id),
+            ItemKind::GlobalAsm(..) => DefPathData::Misc,
+            ItemKind::Use(..) => {
+                return visit::walk_item(self, i);
+            }
+        };
+        let def = self.create_def(i.id, def_data, i.span);
+
+        self.with_parent(def, |this| {
+            match i.kind {
+                ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => {
+                    // If this is a unit or tuple-like struct, register the constructor.
+                    if let Some(ctor_hir_id) = struct_def.ctor_id() {
+                        this.create_def(ctor_hir_id, DefPathData::Ctor, i.span);
+                    }
+                }
+                _ => {}
+            }
+            visit::walk_item(this, i);
+        });
+    }
+
+    fn visit_fn(&mut self, fn_kind: FnKind<'a>, span: Span, _: NodeId) {
+        if let FnKind::Fn(_, _, sig, _, body) = fn_kind {
+            if let Async::Yes { closure_id, return_impl_trait_id, .. } = sig.header.asyncness {
+                self.create_def(return_impl_trait_id, DefPathData::ImplTrait, span);
+
+                // For async functions, we need to create their inner defs inside of a
+                // closure to match their desugared representation. Besides that,
+                // we must mirror everything that `visit::walk_fn` below does.
+                self.visit_fn_header(&sig.header);
+                visit::walk_fn_decl(self, &sig.decl);
+                let closure_def = self.create_def(closure_id, DefPathData::ClosureExpr, span);
+                self.with_parent(closure_def, |this| walk_list!(this, visit_block, body));
+                return;
+            }
+        }
+
+        visit::walk_fn(self, fn_kind, span);
+    }
+
+    fn visit_use_tree(&mut self, use_tree: &'a UseTree, id: NodeId, _nested: bool) {
+        self.create_def(id, DefPathData::Misc, use_tree.span);
+        visit::walk_use_tree(self, use_tree, id);
+    }
+
+    fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
+        if let ForeignItemKind::MacCall(_) = foreign_item.kind {
+            return self.visit_macro_invoc(foreign_item.id);
+        }
+
+        let def = self.create_def(
+            foreign_item.id,
+            DefPathData::ValueNs(foreign_item.ident.name),
+            foreign_item.span,
+        );
+
+        self.with_parent(def, |this| {
+            visit::walk_foreign_item(this, foreign_item);
+        });
+    }
+
+    fn visit_variant(&mut self, v: &'a Variant) {
+        if v.is_placeholder {
+            return self.visit_macro_invoc(v.id);
+        }
+        let def = self.create_def(v.id, DefPathData::TypeNs(v.ident.name), v.span);
+        self.with_parent(def, |this| {
+            if let Some(ctor_hir_id) = v.data.ctor_id() {
+                this.create_def(ctor_hir_id, DefPathData::Ctor, v.span);
+            }
+            visit::walk_variant(this, v)
+        });
+    }
+
+    fn visit_variant_data(&mut self, data: &'a VariantData) {
+        // The assumption here is that non-`cfg` macro expansion cannot change field indices.
+        // It currently holds because only inert attributes are accepted on fields,
+        // and every such attribute expands into a single field after it's resolved.
+        for (index, field) in data.fields().iter().enumerate() {
+            self.collect_field(field, Some(index));
+        }
+    }
+
+    fn visit_generic_param(&mut self, param: &'a GenericParam) {
+        if param.is_placeholder {
+            self.visit_macro_invoc(param.id);
+            return;
+        }
+        let name = param.ident.name;
+        let def_path_data = match param.kind {
+            GenericParamKind::Lifetime { .. } => DefPathData::LifetimeNs(name),
+            GenericParamKind::Type { .. } => DefPathData::TypeNs(name),
+            GenericParamKind::Const { .. } => DefPathData::ValueNs(name),
+        };
+        self.create_def(param.id, def_path_data, param.ident.span);
+
+        visit::walk_generic_param(self, param);
+    }
+
+    fn visit_assoc_item(&mut self, i: &'a AssocItem, ctxt: visit::AssocCtxt) {
+        let def_data = match &i.kind {
+            AssocItemKind::Fn(..) | AssocItemKind::Const(..) => DefPathData::ValueNs(i.ident.name),
+            AssocItemKind::TyAlias(..) => DefPathData::TypeNs(i.ident.name),
+            AssocItemKind::MacCall(..) => return self.visit_macro_invoc(i.id),
+        };
+
+        let def = self.create_def(i.id, def_data, i.span);
+        self.with_parent(def, |this| visit::walk_assoc_item(this, i, ctxt));
+    }
+
+    fn visit_pat(&mut self, pat: &'a Pat) {
+        match pat.kind {
+            PatKind::MacCall(..) => self.visit_macro_invoc(pat.id),
+            _ => visit::walk_pat(self, pat),
+        }
+    }
+
+    fn visit_anon_const(&mut self, constant: &'a AnonConst) {
+        let def = self.create_def(constant.id, DefPathData::AnonConst, constant.value.span);
+        self.with_parent(def, |this| visit::walk_anon_const(this, constant));
+    }
+
+    fn visit_expr(&mut self, expr: &'a Expr) {
+        let parent_def = match expr.kind {
+            ExprKind::MacCall(..) => return self.visit_macro_invoc(expr.id),
+            ExprKind::Closure(_, asyncness, ..) => {
+                // Async closures desugar to closures inside of closures, so
+                // we must create two defs.
+                let closure_def = self.create_def(expr.id, DefPathData::ClosureExpr, expr.span);
+                match asyncness {
+                    Async::Yes { closure_id, .. } => {
+                        self.create_def(closure_id, DefPathData::ClosureExpr, expr.span)
+                    }
+                    Async::No => closure_def,
+                }
+            }
+            ExprKind::Async(_, async_id, _) => {
+                self.create_def(async_id, DefPathData::ClosureExpr, expr.span)
+            }
+            _ => self.parent_def,
+        };
+
+        self.with_parent(parent_def, |this| visit::walk_expr(this, expr));
+    }
+
+    fn visit_ty(&mut self, ty: &'a Ty) {
+        match ty.kind {
+            TyKind::MacCall(..) => return self.visit_macro_invoc(ty.id),
+            TyKind::ImplTrait(node_id, _) => {
+                self.create_def(node_id, DefPathData::ImplTrait, ty.span);
+            }
+            _ => {}
+        }
+        visit::walk_ty(self, ty);
+    }
+
+    fn visit_stmt(&mut self, stmt: &'a Stmt) {
+        match stmt.kind {
+            StmtKind::MacCall(..) => self.visit_macro_invoc(stmt.id),
+            _ => visit::walk_stmt(self, stmt),
+        }
+    }
+
+    fn visit_token(&mut self, t: Token) {
+        if let token::Interpolated(nt) = t.kind {
+            if let token::NtExpr(ref expr) = *nt {
+                if let ExprKind::MacCall(..) = expr.kind {
+                    self.visit_macro_invoc(expr.id);
+                }
+            }
+        }
+    }
+
+    fn visit_arm(&mut self, arm: &'a Arm) {
+        if arm.is_placeholder { self.visit_macro_invoc(arm.id) } else { visit::walk_arm(self, arm) }
+    }
+
+    fn visit_field(&mut self, f: &'a Field) {
+        if f.is_placeholder { self.visit_macro_invoc(f.id) } else { visit::walk_field(self, f) }
+    }
+
+    fn visit_field_pattern(&mut self, fp: &'a FieldPat) {
+        if fp.is_placeholder {
+            self.visit_macro_invoc(fp.id)
+        } else {
+            visit::walk_field_pattern(self, fp)
+        }
+    }
+
+    fn visit_param(&mut self, p: &'a Param) {
+        if p.is_placeholder { self.visit_macro_invoc(p.id) } else { visit::walk_param(self, p) }
+    }
+
+    // This method is called only when we are visiting an individual field
+    // after expanding an attribute on it.
+    fn visit_struct_field(&mut self, field: &'a StructField) {
+        self.collect_field(field, None);
+    }
+}
diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs
new file mode 100644
index 0000000..612bc3e
--- /dev/null
+++ b/compiler/rustc_resolve/src/diagnostics.rs
@@ -0,0 +1,1686 @@
+use std::cmp::Reverse;
+use std::ptr;
+
+use rustc_ast::util::lev_distance::find_best_match_for_name;
+use rustc_ast::{self as ast, Path};
+use rustc_ast_pretty::pprust;
+use rustc_data_structures::fx::FxHashSet;
+use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
+use rustc_feature::BUILTIN_ATTRIBUTES;
+use rustc_hir::def::Namespace::{self, *};
+use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind};
+use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
+use rustc_middle::bug;
+use rustc_middle::ty::{self, DefIdTree};
+use rustc_session::Session;
+use rustc_span::hygiene::MacroKind;
+use rustc_span::source_map::SourceMap;
+use rustc_span::symbol::{kw, sym, Ident, Symbol};
+use rustc_span::{BytePos, MultiSpan, Span};
+use tracing::debug;
+
+use crate::imports::{Import, ImportKind, ImportResolver};
+use crate::path_names_to_string;
+use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind};
+use crate::{
+    BindingError, CrateLint, HasGenericParams, MacroRulesScope, Module, ModuleOrUniformRoot,
+};
+use crate::{NameBinding, NameBindingKind, PrivacyError, VisResolutionError};
+use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet, Segment};
+
+type Res = def::Res<ast::NodeId>;
+
+/// A vector of spans and replacements, a message and applicability.
+crate type Suggestion = (Vec<(Span, String)>, String, Applicability);
+
+/// Potential candidate for an undeclared or out-of-scope label - contains the ident of a
+/// similarly named label and whether or not it is reachable.
+crate type LabelSuggestion = (Ident, bool);
+
+crate struct TypoSuggestion {
+    pub candidate: Symbol,
+    pub res: Res,
+}
+
+impl TypoSuggestion {
+    crate fn from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
+        TypoSuggestion { candidate, res }
+    }
+}
+
+/// A free importable items suggested in case of resolution failure.
+crate struct ImportSuggestion {
+    pub did: Option<DefId>,
+    pub descr: &'static str,
+    pub path: Path,
+    pub accessible: bool,
+}
+
+/// Adjust the impl span so that just the `impl` keyword is taken by removing
+/// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
+/// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
+///
+/// *Attention*: the method used is very fragile since it essentially duplicates the work of the
+/// parser. If you need to use this function or something similar, please consider updating the
+/// `source_map` functions and this function to something more robust.
+fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
+    let impl_span = sm.span_until_char(impl_span, '<');
+    sm.span_until_whitespace(impl_span)
+}
+
+impl<'a> Resolver<'a> {
+    crate fn add_module_candidates(
+        &mut self,
+        module: Module<'a>,
+        names: &mut Vec<TypoSuggestion>,
+        filter_fn: &impl Fn(Res) -> bool,
+    ) {
+        for (key, resolution) in self.resolutions(module).borrow().iter() {
+            if let Some(binding) = resolution.borrow().binding {
+                let res = binding.res();
+                if filter_fn(res) {
+                    names.push(TypoSuggestion::from_res(key.ident.name, res));
+                }
+            }
+        }
+    }
+
+    /// Combines an error with provided span and emits it.
+    ///
+    /// This takes the error provided, combines it with the span and any additional spans inside the
+    /// error and emits it.
+    crate fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) {
+        self.into_struct_error(span, resolution_error).emit();
+    }
+
+    crate fn into_struct_error(
+        &self,
+        span: Span,
+        resolution_error: ResolutionError<'_>,
+    ) -> DiagnosticBuilder<'_> {
+        match resolution_error {
+            ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0401,
+                    "can't use generic parameters from outer function",
+                );
+                err.span_label(span, "use of generic parameter from outer function".to_string());
+
+                let sm = self.session.source_map();
+                match outer_res {
+                    Res::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
+                        if let Some(impl_span) =
+                            maybe_impl_defid.and_then(|(def_id, _)| self.opt_span(def_id))
+                        {
+                            err.span_label(
+                                reduce_impl_span_to_impl_keyword(sm, impl_span),
+                                "`Self` type implicitly declared here, by this `impl`",
+                            );
+                        }
+                        match (maybe_trait_defid, maybe_impl_defid) {
+                            (Some(_), None) => {
+                                err.span_label(span, "can't use `Self` here");
+                            }
+                            (_, Some(_)) => {
+                                err.span_label(span, "use a type here instead");
+                            }
+                            (None, None) => bug!("`impl` without trait nor type?"),
+                        }
+                        return err;
+                    }
+                    Res::Def(DefKind::TyParam, def_id) => {
+                        if let Some(span) = self.opt_span(def_id) {
+                            err.span_label(span, "type parameter from outer function");
+                        }
+                    }
+                    Res::Def(DefKind::ConstParam, def_id) => {
+                        if let Some(span) = self.opt_span(def_id) {
+                            err.span_label(span, "const parameter from outer function");
+                        }
+                    }
+                    _ => {
+                        bug!(
+                            "GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
+                            DefKind::TyParam"
+                        );
+                    }
+                }
+
+                if has_generic_params == HasGenericParams::Yes {
+                    // Try to retrieve the span of the function signature and generate a new
+                    // message with a local type or const parameter.
+                    let sugg_msg = "try using a local generic parameter instead";
+                    if let Some((sugg_span, snippet)) = sm.generate_local_type_param_snippet(span) {
+                        // Suggest the modification to the user
+                        err.span_suggestion(
+                            sugg_span,
+                            sugg_msg,
+                            snippet,
+                            Applicability::MachineApplicable,
+                        );
+                    } else if let Some(sp) = sm.generate_fn_name_span(span) {
+                        err.span_label(
+                            sp,
+                            "try adding a local generic parameter in this method instead"
+                                .to_string(),
+                        );
+                    } else {
+                        err.help("try using a local generic parameter instead");
+                    }
+                }
+
+                err
+            }
+            ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0403,
+                    "the name `{}` is already used for a generic \
+                     parameter in this item's generic parameters",
+                    name,
+                );
+                err.span_label(span, "already used");
+                err.span_label(first_use_span, format!("first use of `{}`", name));
+                err
+            }
+            ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0407,
+                    "method `{}` is not a member of trait `{}`",
+                    method,
+                    trait_
+                );
+                err.span_label(span, format!("not a member of trait `{}`", trait_));
+                err
+            }
+            ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0437,
+                    "type `{}` is not a member of trait `{}`",
+                    type_,
+                    trait_
+                );
+                err.span_label(span, format!("not a member of trait `{}`", trait_));
+                err
+            }
+            ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0438,
+                    "const `{}` is not a member of trait `{}`",
+                    const_,
+                    trait_
+                );
+                err.span_label(span, format!("not a member of trait `{}`", trait_));
+                err
+            }
+            ResolutionError::VariableNotBoundInPattern(binding_error) => {
+                let BindingError { name, target, origin, could_be_path } = binding_error;
+
+                let target_sp = target.iter().copied().collect::<Vec<_>>();
+                let origin_sp = origin.iter().copied().collect::<Vec<_>>();
+
+                let msp = MultiSpan::from_spans(target_sp.clone());
+                let mut err = struct_span_err!(
+                    self.session,
+                    msp,
+                    E0408,
+                    "variable `{}` is not bound in all patterns",
+                    name,
+                );
+                for sp in target_sp {
+                    err.span_label(sp, format!("pattern doesn't bind `{}`", name));
+                }
+                for sp in origin_sp {
+                    err.span_label(sp, "variable not in all patterns");
+                }
+                if *could_be_path {
+                    let help_msg = format!(
+                        "if you meant to match on a variant or a `const` item, consider \
+                         making the path in the pattern qualified: `?::{}`",
+                        name,
+                    );
+                    err.span_help(span, &help_msg);
+                }
+                err
+            }
+            ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0409,
+                    "variable `{}` is bound inconsistently across alternatives separated by `|`",
+                    variable_name
+                );
+                err.span_label(span, "bound in different ways");
+                err.span_label(first_binding_span, "first binding");
+                err
+            }
+            ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0415,
+                    "identifier `{}` is bound more than once in this parameter list",
+                    identifier
+                );
+                err.span_label(span, "used as parameter more than once");
+                err
+            }
+            ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0416,
+                    "identifier `{}` is bound more than once in the same pattern",
+                    identifier
+                );
+                err.span_label(span, "used in a pattern more than once");
+                err
+            }
+            ResolutionError::UndeclaredLabel { name, suggestion } => {
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0426,
+                    "use of undeclared label `{}`",
+                    name
+                );
+
+                err.span_label(span, format!("undeclared label `{}`", name));
+
+                match suggestion {
+                    // A reachable label with a similar name exists.
+                    Some((ident, true)) => {
+                        err.span_label(ident.span, "a label with a similar name is reachable");
+                        err.span_suggestion(
+                            span,
+                            "try using similarly named label",
+                            ident.name.to_string(),
+                            Applicability::MaybeIncorrect,
+                        );
+                    }
+                    // An unreachable label with a similar name exists.
+                    Some((ident, false)) => {
+                        err.span_label(
+                            ident.span,
+                            "a label with a similar name exists but is unreachable",
+                        );
+                    }
+                    // No similarly-named labels exist.
+                    None => (),
+                }
+
+                err
+            }
+            ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0429,
+                    "{}",
+                    "`self` imports are only allowed within a { } list"
+                );
+
+                // None of the suggestions below would help with a case like `use self`.
+                if !root {
+                    // use foo::bar::self        -> foo::bar
+                    // use foo::bar::self as abc -> foo::bar as abc
+                    err.span_suggestion(
+                        span,
+                        "consider importing the module directly",
+                        "".to_string(),
+                        Applicability::MachineApplicable,
+                    );
+
+                    // use foo::bar::self        -> foo::bar::{self}
+                    // use foo::bar::self as abc -> foo::bar::{self as abc}
+                    let braces = vec![
+                        (span_with_rename.shrink_to_lo(), "{".to_string()),
+                        (span_with_rename.shrink_to_hi(), "}".to_string()),
+                    ];
+                    err.multipart_suggestion(
+                        "alternatively, use the multi-path `use` syntax to import `self`",
+                        braces,
+                        Applicability::MachineApplicable,
+                    );
+                }
+                err
+            }
+            ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0430,
+                    "`self` import can only appear once in an import list"
+                );
+                err.span_label(span, "can only appear once in an import list");
+                err
+            }
+            ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0431,
+                    "`self` import can only appear in an import list with \
+                                                a non-empty prefix"
+                );
+                err.span_label(span, "can only appear in an import list with a non-empty prefix");
+                err
+            }
+            ResolutionError::FailedToResolve { label, suggestion } => {
+                let mut err =
+                    struct_span_err!(self.session, span, E0433, "failed to resolve: {}", &label);
+                err.span_label(span, label);
+
+                if let Some((suggestions, msg, applicability)) = suggestion {
+                    err.multipart_suggestion(&msg, suggestions, applicability);
+                }
+
+                err
+            }
+            ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0434,
+                    "{}",
+                    "can't capture dynamic environment in a fn item"
+                );
+                err.help("use the `|| { ... }` closure form instead");
+                err
+            }
+            ResolutionError::AttemptToUseNonConstantValueInConstant => {
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0435,
+                    "attempt to use a non-constant value in a constant"
+                );
+                err.span_label(span, "non-constant value");
+                err
+            }
+            ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
+                let res = binding.res();
+                let shadows_what = res.descr();
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0530,
+                    "{}s cannot shadow {}s",
+                    what_binding,
+                    shadows_what
+                );
+                err.span_label(
+                    span,
+                    format!("cannot be named the same as {} {}", res.article(), shadows_what),
+                );
+                let participle = if binding.is_import() { "imported" } else { "defined" };
+                let msg = format!("the {} `{}` is {} here", shadows_what, name, participle);
+                err.span_label(binding.span, msg);
+                err
+            }
+            ResolutionError::ForwardDeclaredTyParam => {
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0128,
+                    "type parameters with a default cannot use \
+                                                forward declared identifiers"
+                );
+                err.span_label(
+                    span,
+                    "defaulted type parameters cannot be forward declared".to_string(),
+                );
+                err
+            }
+            ResolutionError::ParamInTyOfConstParam(name) => {
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0770,
+                    "the type of const parameters must not depend on other generic parameters"
+                );
+                err.span_label(
+                    span,
+                    format!("the type must not depend on the parameter `{}`", name),
+                );
+                err
+            }
+            ResolutionError::ParamInAnonConstInTyDefault(name) => {
+                let mut err = self.session.struct_span_err(
+                    span,
+                    "constant values inside of type parameter defaults must not depend on generic parameters",
+                );
+                err.span_label(
+                    span,
+                    format!("the anonymous constant must not depend on the parameter `{}`", name),
+                );
+                err
+            }
+            ResolutionError::ParamInNonTrivialAnonConst { name, is_type } => {
+                let mut err = self.session.struct_span_err(
+                    span,
+                    "generic parameters must not be used inside of non trivial constant values",
+                );
+                err.span_label(
+                    span,
+                    &format!(
+                        "non-trivial anonymous constants must not depend on the parameter `{}`",
+                        name
+                    ),
+                );
+
+                if is_type {
+                    err.note("type parameters are currently not permitted in anonymous constants");
+                } else {
+                    err.help(
+                        &format!("it is currently only allowed to use either `{0}` or `{{ {0} }}` as generic constants",
+                                 name
+                        )
+                    );
+                }
+
+                err
+            }
+            ResolutionError::SelfInTyParamDefault => {
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0735,
+                    "type parameters cannot use `Self` in their defaults"
+                );
+                err.span_label(span, "`Self` in type parameter default".to_string());
+                err
+            }
+            ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0767,
+                    "use of unreachable label `{}`",
+                    name,
+                );
+
+                err.span_label(definition_span, "unreachable label defined here");
+                err.span_label(span, format!("unreachable label `{}`", name));
+                err.note(
+                    "labels are unreachable through functions, closures, async blocks and modules",
+                );
+
+                match suggestion {
+                    // A reachable label with a similar name exists.
+                    Some((ident, true)) => {
+                        err.span_label(ident.span, "a label with a similar name is reachable");
+                        err.span_suggestion(
+                            span,
+                            "try using similarly named label",
+                            ident.name.to_string(),
+                            Applicability::MaybeIncorrect,
+                        );
+                    }
+                    // An unreachable label with a similar name exists.
+                    Some((ident, false)) => {
+                        err.span_label(
+                            ident.span,
+                            "a label with a similar name exists but is also unreachable",
+                        );
+                    }
+                    // No similarly-named labels exist.
+                    None => (),
+                }
+
+                err
+            }
+        }
+    }
+
+    crate fn report_vis_error(&self, vis_resolution_error: VisResolutionError<'_>) {
+        match vis_resolution_error {
+            VisResolutionError::Relative2018(span, path) => {
+                let mut err = self.session.struct_span_err(
+                    span,
+                    "relative paths are not supported in visibilities on 2018 edition",
+                );
+                err.span_suggestion(
+                    path.span,
+                    "try",
+                    format!("crate::{}", pprust::path_to_string(&path)),
+                    Applicability::MaybeIncorrect,
+                );
+                err
+            }
+            VisResolutionError::AncestorOnly(span) => struct_span_err!(
+                self.session,
+                span,
+                E0742,
+                "visibilities can only be restricted to ancestor modules"
+            ),
+            VisResolutionError::FailedToResolve(span, label, suggestion) => {
+                self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion })
+            }
+            VisResolutionError::ExpectedFound(span, path_str, res) => {
+                let mut err = struct_span_err!(
+                    self.session,
+                    span,
+                    E0577,
+                    "expected module, found {} `{}`",
+                    res.descr(),
+                    path_str
+                );
+                err.span_label(span, "not a module");
+                err
+            }
+            VisResolutionError::Indeterminate(span) => struct_span_err!(
+                self.session,
+                span,
+                E0578,
+                "cannot determine resolution for the visibility"
+            ),
+            VisResolutionError::ModuleOnly(span) => {
+                self.session.struct_span_err(span, "visibility must resolve to a module")
+            }
+        }
+        .emit()
+    }
+
+    /// Lookup typo candidate in scope for a macro or import.
+    fn early_lookup_typo_candidate(
+        &mut self,
+        scope_set: ScopeSet,
+        parent_scope: &ParentScope<'a>,
+        ident: Ident,
+        filter_fn: &impl Fn(Res) -> bool,
+    ) -> Option<TypoSuggestion> {
+        let mut suggestions = Vec::new();
+        self.visit_scopes(scope_set, parent_scope, ident, |this, scope, use_prelude, _| {
+            match scope {
+                Scope::DeriveHelpers(expn_id) => {
+                    let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
+                    if filter_fn(res) {
+                        suggestions.extend(
+                            this.helper_attrs
+                                .get(&expn_id)
+                                .into_iter()
+                                .flatten()
+                                .map(|ident| TypoSuggestion::from_res(ident.name, res)),
+                        );
+                    }
+                }
+                Scope::DeriveHelpersCompat => {
+                    let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
+                    if filter_fn(res) {
+                        for derive in parent_scope.derives {
+                            let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
+                            if let Ok((Some(ext), _)) = this.resolve_macro_path(
+                                derive,
+                                Some(MacroKind::Derive),
+                                parent_scope,
+                                false,
+                                false,
+                            ) {
+                                suggestions.extend(
+                                    ext.helper_attrs
+                                        .iter()
+                                        .map(|name| TypoSuggestion::from_res(*name, res)),
+                                );
+                            }
+                        }
+                    }
+                }
+                Scope::MacroRules(macro_rules_scope) => {
+                    if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope {
+                        let res = macro_rules_binding.binding.res();
+                        if filter_fn(res) {
+                            suggestions
+                                .push(TypoSuggestion::from_res(macro_rules_binding.ident.name, res))
+                        }
+                    }
+                }
+                Scope::CrateRoot => {
+                    let root_ident = Ident::new(kw::PathRoot, ident.span);
+                    let root_module = this.resolve_crate_root(root_ident);
+                    this.add_module_candidates(root_module, &mut suggestions, filter_fn);
+                }
+                Scope::Module(module) => {
+                    this.add_module_candidates(module, &mut suggestions, filter_fn);
+                }
+                Scope::RegisteredAttrs => {
+                    let res = Res::NonMacroAttr(NonMacroAttrKind::Registered);
+                    if filter_fn(res) {
+                        suggestions.extend(
+                            this.registered_attrs
+                                .iter()
+                                .map(|ident| TypoSuggestion::from_res(ident.name, res)),
+                        );
+                    }
+                }
+                Scope::MacroUsePrelude => {
+                    suggestions.extend(this.macro_use_prelude.iter().filter_map(
+                        |(name, binding)| {
+                            let res = binding.res();
+                            filter_fn(res).then_some(TypoSuggestion::from_res(*name, res))
+                        },
+                    ));
+                }
+                Scope::BuiltinAttrs => {
+                    let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin);
+                    if filter_fn(res) {
+                        suggestions.extend(
+                            BUILTIN_ATTRIBUTES
+                                .iter()
+                                .map(|(name, ..)| TypoSuggestion::from_res(*name, res)),
+                        );
+                    }
+                }
+                Scope::ExternPrelude => {
+                    suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
+                        let res = Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX));
+                        filter_fn(res).then_some(TypoSuggestion::from_res(ident.name, res))
+                    }));
+                }
+                Scope::ToolPrelude => {
+                    let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
+                    suggestions.extend(
+                        this.registered_tools
+                            .iter()
+                            .map(|ident| TypoSuggestion::from_res(ident.name, res)),
+                    );
+                }
+                Scope::StdLibPrelude => {
+                    if let Some(prelude) = this.prelude {
+                        let mut tmp_suggestions = Vec::new();
+                        this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
+                        suggestions.extend(
+                            tmp_suggestions
+                                .into_iter()
+                                .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
+                        );
+                    }
+                }
+                Scope::BuiltinTypes => {
+                    let primitive_types = &this.primitive_type_table.primitive_types;
+                    suggestions.extend(primitive_types.iter().flat_map(|(name, prim_ty)| {
+                        let res = Res::PrimTy(*prim_ty);
+                        filter_fn(res).then_some(TypoSuggestion::from_res(*name, res))
+                    }))
+                }
+            }
+
+            None::<()>
+        });
+
+        // Make sure error reporting is deterministic.
+        suggestions.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
+
+        match find_best_match_for_name(
+            suggestions.iter().map(|suggestion| &suggestion.candidate),
+            ident.name,
+            None,
+        ) {
+            Some(found) if found != ident.name => {
+                suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
+            }
+            _ => None,
+        }
+    }
+
+    fn lookup_import_candidates_from_module<FilterFn>(
+        &mut self,
+        lookup_ident: Ident,
+        namespace: Namespace,
+        parent_scope: &ParentScope<'a>,
+        start_module: Module<'a>,
+        crate_name: Ident,
+        filter_fn: FilterFn,
+    ) -> Vec<ImportSuggestion>
+    where
+        FilterFn: Fn(Res) -> bool,
+    {
+        let mut candidates = Vec::new();
+        let mut seen_modules = FxHashSet::default();
+        let not_local_module = crate_name.name != kw::Crate;
+        let mut worklist =
+            vec![(start_module, Vec::<ast::PathSegment>::new(), true, not_local_module)];
+        let mut worklist_via_import = vec![];
+
+        while let Some((in_module, path_segments, accessible, in_module_is_extern)) =
+            match worklist.pop() {
+                None => worklist_via_import.pop(),
+                Some(x) => Some(x),
+            }
+        {
+            // We have to visit module children in deterministic order to avoid
+            // instabilities in reported imports (#43552).
+            in_module.for_each_child(self, |this, ident, ns, name_binding| {
+                // avoid non-importable candidates
+                if !name_binding.is_importable() {
+                    return;
+                }
+
+                let child_accessible =
+                    accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
+
+                // do not venture inside inaccessible items of other crates
+                if in_module_is_extern && !child_accessible {
+                    return;
+                }
+
+                let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
+
+                // There is an assumption elsewhere that paths of variants are in the enum's
+                // declaration and not imported. With this assumption, the variant component is
+                // chopped and the rest of the path is assumed to be the enum's own path. For
+                // errors where a variant is used as the type instead of the enum, this causes
+                // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
+                if via_import && name_binding.is_possibly_imported_variant() {
+                    return;
+                }
+
+                // collect results based on the filter function
+                // avoid suggesting anything from the same module in which we are resolving
+                if ident.name == lookup_ident.name
+                    && ns == namespace
+                    && !ptr::eq(in_module, parent_scope.module)
+                {
+                    let res = name_binding.res();
+                    if filter_fn(res) {
+                        // create the path
+                        let mut segms = path_segments.clone();
+                        if lookup_ident.span.rust_2018() {
+                            // crate-local absolute paths start with `crate::` in edition 2018
+                            // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
+                            segms.insert(0, ast::PathSegment::from_ident(crate_name));
+                        }
+
+                        segms.push(ast::PathSegment::from_ident(ident));
+                        let path = Path { span: name_binding.span, segments: segms, tokens: None };
+                        let did = match res {
+                            Res::Def(DefKind::Ctor(..), did) => this.parent(did),
+                            _ => res.opt_def_id(),
+                        };
+
+                        if child_accessible {
+                            // Remove invisible match if exists
+                            if let Some(idx) = candidates
+                                .iter()
+                                .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
+                            {
+                                candidates.remove(idx);
+                            }
+                        }
+
+                        if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
+                            candidates.push(ImportSuggestion {
+                                did,
+                                descr: res.descr(),
+                                path,
+                                accessible: child_accessible,
+                            });
+                        }
+                    }
+                }
+
+                // collect submodules to explore
+                if let Some(module) = name_binding.module() {
+                    // form the path
+                    let mut path_segments = path_segments.clone();
+                    path_segments.push(ast::PathSegment::from_ident(ident));
+
+                    let is_extern_crate_that_also_appears_in_prelude =
+                        name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
+
+                    if !is_extern_crate_that_also_appears_in_prelude {
+                        let is_extern = in_module_is_extern || name_binding.is_extern_crate();
+                        // add the module to the lookup
+                        if seen_modules.insert(module.def_id().unwrap()) {
+                            if via_import { &mut worklist_via_import } else { &mut worklist }
+                                .push((module, path_segments, child_accessible, is_extern));
+                        }
+                    }
+                }
+            })
+        }
+
+        // If only some candidates are accessible, take just them
+        if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
+            candidates = candidates.into_iter().filter(|x| x.accessible).collect();
+        }
+
+        candidates
+    }
+
+    /// When name resolution fails, this method can be used to look up candidate
+    /// entities with the expected name. It allows filtering them using the
+    /// supplied predicate (which should be used to only accept the types of
+    /// definitions expected, e.g., traits). The lookup spans across all crates.
+    ///
+    /// N.B., the method does not look into imports, but this is not a problem,
+    /// since we report the definitions (thus, the de-aliased imports).
+    crate fn lookup_import_candidates<FilterFn>(
+        &mut self,
+        lookup_ident: Ident,
+        namespace: Namespace,
+        parent_scope: &ParentScope<'a>,
+        filter_fn: FilterFn,
+    ) -> Vec<ImportSuggestion>
+    where
+        FilterFn: Fn(Res) -> bool,
+    {
+        let mut suggestions = self.lookup_import_candidates_from_module(
+            lookup_ident,
+            namespace,
+            parent_scope,
+            self.graph_root,
+            Ident::with_dummy_span(kw::Crate),
+            &filter_fn,
+        );
+
+        if lookup_ident.span.rust_2018() {
+            let extern_prelude_names = self.extern_prelude.clone();
+            for (ident, _) in extern_prelude_names.into_iter() {
+                if ident.span.from_expansion() {
+                    // Idents are adjusted to the root context before being
+                    // resolved in the extern prelude, so reporting this to the
+                    // user is no help. This skips the injected
+                    // `extern crate std` in the 2018 edition, which would
+                    // otherwise cause duplicate suggestions.
+                    continue;
+                }
+                if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name) {
+                    let crate_root =
+                        self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
+                    suggestions.extend(self.lookup_import_candidates_from_module(
+                        lookup_ident,
+                        namespace,
+                        parent_scope,
+                        crate_root,
+                        ident,
+                        &filter_fn,
+                    ));
+                }
+            }
+        }
+
+        suggestions
+    }
+
+    crate fn unresolved_macro_suggestions(
+        &mut self,
+        err: &mut DiagnosticBuilder<'a>,
+        macro_kind: MacroKind,
+        parent_scope: &ParentScope<'a>,
+        ident: Ident,
+    ) {
+        let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
+        let suggestion = self.early_lookup_typo_candidate(
+            ScopeSet::Macro(macro_kind),
+            parent_scope,
+            ident,
+            is_expected,
+        );
+        self.add_typo_suggestion(err, suggestion, ident.span);
+
+        if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
+            let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
+            err.span_note(ident.span, &msg);
+        }
+        if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
+            err.help("have you added the `#[macro_use]` on the module/import?");
+        }
+    }
+
+    crate fn add_typo_suggestion(
+        &self,
+        err: &mut DiagnosticBuilder<'_>,
+        suggestion: Option<TypoSuggestion>,
+        span: Span,
+    ) -> bool {
+        let suggestion = match suggestion {
+            None => return false,
+            // We shouldn't suggest underscore.
+            Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
+            Some(suggestion) => suggestion,
+        };
+        let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
+            LOCAL_CRATE => self.opt_span(def_id),
+            _ => Some(
+                self.session
+                    .source_map()
+                    .guess_head_span(self.cstore().get_span_untracked(def_id, self.session)),
+            ),
+        });
+        if let Some(def_span) = def_span {
+            if span.overlaps(def_span) {
+                // Don't suggest typo suggestion for itself like in the followoing:
+                // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
+                //   --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
+                //    |
+                // LL | struct X {}
+                //    | ----------- `X` defined here
+                // LL |
+                // LL | const Y: X = X("ö");
+                //    | -------------^^^^^^- similarly named constant `Y` defined here
+                //    |
+                // help: use struct literal syntax instead
+                //    |
+                // LL | const Y: X = X {};
+                //    |              ^^^^
+                // help: a constant with a similar name exists
+                //    |
+                // LL | const Y: X = Y("ö");
+                //    |              ^
+                return false;
+            }
+            err.span_label(
+                self.session.source_map().guess_head_span(def_span),
+                &format!(
+                    "similarly named {} `{}` defined here",
+                    suggestion.res.descr(),
+                    suggestion.candidate.as_str(),
+                ),
+            );
+        }
+        let msg = format!(
+            "{} {} with a similar name exists",
+            suggestion.res.article(),
+            suggestion.res.descr()
+        );
+        err.span_suggestion(
+            span,
+            &msg,
+            suggestion.candidate.to_string(),
+            Applicability::MaybeIncorrect,
+        );
+        true
+    }
+
+    fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
+        let res = b.res();
+        if b.span.is_dummy() {
+            let add_built_in = match b.res() {
+                // These already contain the "built-in" prefix or look bad with it.
+                Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod => false,
+                _ => true,
+            };
+            let (built_in, from) = if from_prelude {
+                ("", " from prelude")
+            } else if b.is_extern_crate()
+                && !b.is_import()
+                && self.session.opts.externs.get(&ident.as_str()).is_some()
+            {
+                ("", " passed with `--extern`")
+            } else if add_built_in {
+                (" built-in", "")
+            } else {
+                ("", "")
+            };
+
+            let article = if built_in.is_empty() { res.article() } else { "a" };
+            format!(
+                "{a}{built_in} {thing}{from}",
+                a = article,
+                thing = res.descr(),
+                built_in = built_in,
+                from = from
+            )
+        } else {
+            let introduced = if b.is_import() { "imported" } else { "defined" };
+            format!("the {thing} {introduced} here", thing = res.descr(), introduced = introduced)
+        }
+    }
+
+    crate fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
+        let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
+        let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
+            // We have to print the span-less alternative first, otherwise formatting looks bad.
+            (b2, b1, misc2, misc1, true)
+        } else {
+            (b1, b2, misc1, misc2, false)
+        };
+
+        let mut err = struct_span_err!(
+            self.session,
+            ident.span,
+            E0659,
+            "`{ident}` is ambiguous ({why})",
+            ident = ident,
+            why = kind.descr()
+        );
+        err.span_label(ident.span, "ambiguous name");
+
+        let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
+            let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
+            let note_msg = format!(
+                "`{ident}` could{also} refer to {what}",
+                ident = ident,
+                also = also,
+                what = what
+            );
+
+            let thing = b.res().descr();
+            let mut help_msgs = Vec::new();
+            if b.is_glob_import()
+                && (kind == AmbiguityKind::GlobVsGlob
+                    || kind == AmbiguityKind::GlobVsExpanded
+                    || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
+            {
+                help_msgs.push(format!(
+                    "consider adding an explicit import of \
+                     `{ident}` to disambiguate",
+                    ident = ident
+                ))
+            }
+            if b.is_extern_crate() && ident.span.rust_2018() {
+                help_msgs.push(format!(
+                    "use `::{ident}` to refer to this {thing} unambiguously",
+                    ident = ident,
+                    thing = thing,
+                ))
+            }
+            if misc == AmbiguityErrorMisc::SuggestCrate {
+                help_msgs.push(format!(
+                    "use `crate::{ident}` to refer to this {thing} unambiguously",
+                    ident = ident,
+                    thing = thing,
+                ))
+            } else if misc == AmbiguityErrorMisc::SuggestSelf {
+                help_msgs.push(format!(
+                    "use `self::{ident}` to refer to this {thing} unambiguously",
+                    ident = ident,
+                    thing = thing,
+                ))
+            }
+
+            err.span_note(b.span, &note_msg);
+            for (i, help_msg) in help_msgs.iter().enumerate() {
+                let or = if i == 0 { "" } else { "or " };
+                err.help(&format!("{}{}", or, help_msg));
+            }
+        };
+
+        could_refer_to(b1, misc1, "");
+        could_refer_to(b2, misc2, " also");
+        err.emit();
+    }
+
+    /// If the binding refers to a tuple struct constructor with fields,
+    /// returns the span of its fields.
+    fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
+        if let NameBindingKind::Res(
+            Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id),
+            _,
+        ) = binding.kind
+        {
+            let def_id = (&*self).parent(ctor_def_id).expect("no parent for a constructor");
+            let fields = self.field_names.get(&def_id)?;
+            let first_field = fields.first()?; // Handle `struct Foo()`
+            return Some(fields.iter().fold(first_field.span, |acc, field| acc.to(field.span)));
+        }
+        None
+    }
+
+    crate fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
+        let PrivacyError { ident, binding, .. } = *privacy_error;
+
+        let res = binding.res();
+        let ctor_fields_span = self.ctor_fields_span(binding);
+        let plain_descr = res.descr().to_string();
+        let nonimport_descr =
+            if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
+        let import_descr = nonimport_descr.clone() + " import";
+        let get_descr =
+            |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
+
+        // Print the primary message.
+        let descr = get_descr(binding);
+        let mut err =
+            struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
+        err.span_label(ident.span, &format!("private {}", descr));
+        if let Some(span) = ctor_fields_span {
+            err.span_label(span, "a constructor is private if any of the fields is private");
+        }
+
+        // Print the whole import chain to make it easier to see what happens.
+        let first_binding = binding;
+        let mut next_binding = Some(binding);
+        let mut next_ident = ident;
+        while let Some(binding) = next_binding {
+            let name = next_ident;
+            next_binding = match binding.kind {
+                _ if res == Res::Err => None,
+                NameBindingKind::Import { binding, import, .. } => match import.kind {
+                    _ if binding.span.is_dummy() => None,
+                    ImportKind::Single { source, .. } => {
+                        next_ident = source;
+                        Some(binding)
+                    }
+                    ImportKind::Glob { .. } | ImportKind::MacroUse => Some(binding),
+                    ImportKind::ExternCrate { .. } => None,
+                },
+                _ => None,
+            };
+
+            let first = ptr::eq(binding, first_binding);
+            let descr = get_descr(binding);
+            let msg = format!(
+                "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
+                and_refers_to = if first { "" } else { "...and refers to " },
+                item = descr,
+                name = name,
+                which = if first { "" } else { " which" },
+                dots = if next_binding.is_some() { "..." } else { "" },
+            );
+            let def_span = self.session.source_map().guess_head_span(binding.span);
+            let mut note_span = MultiSpan::from_span(def_span);
+            if !first && binding.vis == ty::Visibility::Public {
+                note_span.push_span_label(def_span, "consider importing it directly".into());
+            }
+            err.span_note(note_span, &msg);
+        }
+
+        err.emit();
+    }
+}
+
+impl<'a, 'b> ImportResolver<'a, 'b> {
+    /// Adds suggestions for a path that cannot be resolved.
+    pub(crate) fn make_path_suggestion(
+        &mut self,
+        span: Span,
+        mut path: Vec<Segment>,
+        parent_scope: &ParentScope<'b>,
+    ) -> Option<(Vec<Segment>, Vec<String>)> {
+        debug!("make_path_suggestion: span={:?} path={:?}", span, path);
+
+        match (path.get(0), path.get(1)) {
+            // `{{root}}::ident::...` on both editions.
+            // On 2015 `{{root}}` is usually added implicitly.
+            (Some(fst), Some(snd))
+                if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
+            // `ident::...` on 2018.
+            (Some(fst), _)
+                if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
+            {
+                // Insert a placeholder that's later replaced by `self`/`super`/etc.
+                path.insert(0, Segment::from_ident(Ident::invalid()));
+            }
+            _ => return None,
+        }
+
+        self.make_missing_self_suggestion(span, path.clone(), parent_scope)
+            .or_else(|| self.make_missing_crate_suggestion(span, path.clone(), parent_scope))
+            .or_else(|| self.make_missing_super_suggestion(span, path.clone(), parent_scope))
+            .or_else(|| self.make_external_crate_suggestion(span, path, parent_scope))
+    }
+
+    /// Suggest a missing `self::` if that resolves to an correct module.
+    ///
+    /// ```text
+    ///    |
+    /// LL | use foo::Bar;
+    ///    |     ^^^ did you mean `self::foo`?
+    /// ```
+    fn make_missing_self_suggestion(
+        &mut self,
+        span: Span,
+        mut path: Vec<Segment>,
+        parent_scope: &ParentScope<'b>,
+    ) -> Option<(Vec<Segment>, Vec<String>)> {
+        // Replace first ident with `self` and check if that is valid.
+        path[0].ident.name = kw::SelfLower;
+        let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
+        debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
+        if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
+    }
+
+    /// Suggests a missing `crate::` if that resolves to an correct module.
+    ///
+    /// ```text
+    ///    |
+    /// LL | use foo::Bar;
+    ///    |     ^^^ did you mean `crate::foo`?
+    /// ```
+    fn make_missing_crate_suggestion(
+        &mut self,
+        span: Span,
+        mut path: Vec<Segment>,
+        parent_scope: &ParentScope<'b>,
+    ) -> Option<(Vec<Segment>, Vec<String>)> {
+        // Replace first ident with `crate` and check if that is valid.
+        path[0].ident.name = kw::Crate;
+        let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
+        debug!("make_missing_crate_suggestion:  path={:?} result={:?}", path, result);
+        if let PathResult::Module(..) = result {
+            Some((
+                path,
+                vec![
+                    "`use` statements changed in Rust 2018; read more at \
+                     <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
+                     clarity.html>"
+                        .to_string(),
+                ],
+            ))
+        } else {
+            None
+        }
+    }
+
+    /// Suggests a missing `super::` if that resolves to an correct module.
+    ///
+    /// ```text
+    ///    |
+    /// LL | use foo::Bar;
+    ///    |     ^^^ did you mean `super::foo`?
+    /// ```
+    fn make_missing_super_suggestion(
+        &mut self,
+        span: Span,
+        mut path: Vec<Segment>,
+        parent_scope: &ParentScope<'b>,
+    ) -> Option<(Vec<Segment>, Vec<String>)> {
+        // Replace first ident with `crate` and check if that is valid.
+        path[0].ident.name = kw::Super;
+        let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
+        debug!("make_missing_super_suggestion:  path={:?} result={:?}", path, result);
+        if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
+    }
+
+    /// Suggests a missing external crate name if that resolves to an correct module.
+    ///
+    /// ```text
+    ///    |
+    /// LL | use foobar::Baz;
+    ///    |     ^^^^^^ did you mean `baz::foobar`?
+    /// ```
+    ///
+    /// Used when importing a submodule of an external crate but missing that crate's
+    /// name as the first part of path.
+    fn make_external_crate_suggestion(
+        &mut self,
+        span: Span,
+        mut path: Vec<Segment>,
+        parent_scope: &ParentScope<'b>,
+    ) -> Option<(Vec<Segment>, Vec<String>)> {
+        if path[1].ident.span.rust_2015() {
+            return None;
+        }
+
+        // Sort extern crate names in reverse order to get
+        // 1) some consistent ordering for emitted diagnostics, and
+        // 2) `std` suggestions before `core` suggestions.
+        let mut extern_crate_names =
+            self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
+        extern_crate_names.sort_by_key(|name| Reverse(name.as_str()));
+
+        for name in extern_crate_names.into_iter() {
+            // Replace first ident with a crate name and check if that is valid.
+            path[0].ident.name = name;
+            let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
+            debug!(
+                "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
+                name, path, result
+            );
+            if let PathResult::Module(..) = result {
+                return Some((path, Vec::new()));
+            }
+        }
+
+        None
+    }
+
+    /// Suggests importing a macro from the root of the crate rather than a module within
+    /// the crate.
+    ///
+    /// ```text
+    /// help: a macro with this name exists at the root of the crate
+    ///    |
+    /// LL | use issue_59764::makro;
+    ///    |     ^^^^^^^^^^^^^^^^^^
+    ///    |
+    ///    = note: this could be because a macro annotated with `#[macro_export]` will be exported
+    ///            at the root of the crate instead of the module where it is defined
+    /// ```
+    pub(crate) fn check_for_module_export_macro(
+        &mut self,
+        import: &'b Import<'b>,
+        module: ModuleOrUniformRoot<'b>,
+        ident: Ident,
+    ) -> Option<(Option<Suggestion>, Vec<String>)> {
+        let mut crate_module = if let ModuleOrUniformRoot::Module(module) = module {
+            module
+        } else {
+            return None;
+        };
+
+        while let Some(parent) = crate_module.parent {
+            crate_module = parent;
+        }
+
+        if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
+            // Don't make a suggestion if the import was already from the root of the
+            // crate.
+            return None;
+        }
+
+        let resolutions = self.r.resolutions(crate_module).borrow();
+        let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
+        let binding = resolution.borrow().binding()?;
+        if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
+            let module_name = crate_module.kind.name().unwrap();
+            let import_snippet = match import.kind {
+                ImportKind::Single { source, target, .. } if source != target => {
+                    format!("{} as {}", source, target)
+                }
+                _ => format!("{}", ident),
+            };
+
+            let mut corrections: Vec<(Span, String)> = Vec::new();
+            if !import.is_nested() {
+                // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
+                // intermediate segments.
+                corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
+            } else {
+                // Find the binding span (and any trailing commas and spaces).
+                //   ie. `use a::b::{c, d, e};`
+                //                      ^^^
+                let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
+                    self.r.session,
+                    import.span,
+                    import.use_span,
+                );
+                debug!(
+                    "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
+                    found_closing_brace, binding_span
+                );
+
+                let mut removal_span = binding_span;
+                if found_closing_brace {
+                    // If the binding span ended with a closing brace, as in the below example:
+                    //   ie. `use a::b::{c, d};`
+                    //                      ^
+                    // Then expand the span of characters to remove to include the previous
+                    // binding's trailing comma.
+                    //   ie. `use a::b::{c, d};`
+                    //                    ^^^
+                    if let Some(previous_span) =
+                        extend_span_to_previous_binding(self.r.session, binding_span)
+                    {
+                        debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
+                        removal_span = removal_span.with_lo(previous_span.lo());
+                    }
+                }
+                debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
+
+                // Remove the `removal_span`.
+                corrections.push((removal_span, "".to_string()));
+
+                // Find the span after the crate name and if it has nested imports immediatately
+                // after the crate name already.
+                //   ie. `use a::b::{c, d};`
+                //               ^^^^^^^^^
+                //   or  `use a::{b, c, d}};`
+                //               ^^^^^^^^^^^
+                let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
+                    self.r.session,
+                    module_name,
+                    import.use_span,
+                );
+                debug!(
+                    "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
+                    has_nested, after_crate_name
+                );
+
+                let source_map = self.r.session.source_map();
+
+                // Add the import to the start, with a `{` if required.
+                let start_point = source_map.start_point(after_crate_name);
+                if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
+                    corrections.push((
+                        start_point,
+                        if has_nested {
+                            // In this case, `start_snippet` must equal '{'.
+                            format!("{}{}, ", start_snippet, import_snippet)
+                        } else {
+                            // In this case, add a `{`, then the moved import, then whatever
+                            // was there before.
+                            format!("{{{}, {}", import_snippet, start_snippet)
+                        },
+                    ));
+                }
+
+                // Add a `};` to the end if nested, matching the `{` added at the start.
+                if !has_nested {
+                    corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
+                }
+            }
+
+            let suggestion = Some((
+                corrections,
+                String::from("a macro with this name exists at the root of the crate"),
+                Applicability::MaybeIncorrect,
+            ));
+            let note = vec![
+                "this could be because a macro annotated with `#[macro_export]` will be exported \
+                 at the root of the crate instead of the module where it is defined"
+                    .to_string(),
+            ];
+            Some((suggestion, note))
+        } else {
+            None
+        }
+    }
+}
+
+/// Given a `binding_span` of a binding within a use statement:
+///
+/// ```
+/// use foo::{a, b, c};
+///              ^
+/// ```
+///
+/// then return the span until the next binding or the end of the statement:
+///
+/// ```
+/// use foo::{a, b, c};
+///              ^^^
+/// ```
+pub(crate) fn find_span_of_binding_until_next_binding(
+    sess: &Session,
+    binding_span: Span,
+    use_span: Span,
+) -> (bool, Span) {
+    let source_map = sess.source_map();
+
+    // Find the span of everything after the binding.
+    //   ie. `a, e};` or `a};`
+    let binding_until_end = binding_span.with_hi(use_span.hi());
+
+    // Find everything after the binding but not including the binding.
+    //   ie. `, e};` or `};`
+    let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
+
+    // Keep characters in the span until we encounter something that isn't a comma or
+    // whitespace.
+    //   ie. `, ` or ``.
+    //
+    // Also note whether a closing brace character was encountered. If there
+    // was, then later go backwards to remove any trailing commas that are left.
+    let mut found_closing_brace = false;
+    let after_binding_until_next_binding =
+        source_map.span_take_while(after_binding_until_end, |&ch| {
+            if ch == '}' {
+                found_closing_brace = true;
+            }
+            ch == ' ' || ch == ','
+        });
+
+    // Combine the two spans.
+    //   ie. `a, ` or `a`.
+    //
+    // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
+    let span = binding_span.with_hi(after_binding_until_next_binding.hi());
+
+    (found_closing_brace, span)
+}
+
+/// Given a `binding_span`, return the span through to the comma or opening brace of the previous
+/// binding.
+///
+/// ```
+/// use foo::a::{a, b, c};
+///               ^^--- binding span
+///               |
+///               returned span
+///
+/// use foo::{a, b, c};
+///           --- binding span
+/// ```
+pub(crate) fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
+    let source_map = sess.source_map();
+
+    // `prev_source` will contain all of the source that came before the span.
+    // Then split based on a command and take the first (ie. closest to our span)
+    // snippet. In the example, this is a space.
+    let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
+
+    let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
+    let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
+    if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
+        return None;
+    }
+
+    let prev_comma = prev_comma.first().unwrap();
+    let prev_starting_brace = prev_starting_brace.first().unwrap();
+
+    // If the amount of source code before the comma is greater than
+    // the amount of source code before the starting brace then we've only
+    // got one item in the nested item (eg. `issue_52891::{self}`).
+    if prev_comma.len() > prev_starting_brace.len() {
+        return None;
+    }
+
+    Some(binding_span.with_lo(BytePos(
+        // Take away the number of bytes for the characters we've found and an
+        // extra for the comma.
+        binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
+    )))
+}
+
+/// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
+/// it is a nested use tree.
+///
+/// ```
+/// use foo::a::{b, c};
+///          ^^^^^^^^^^ // false
+///
+/// use foo::{a, b, c};
+///          ^^^^^^^^^^ // true
+///
+/// use foo::{a, b::{c, d}};
+///          ^^^^^^^^^^^^^^^ // true
+/// ```
+fn find_span_immediately_after_crate_name(
+    sess: &Session,
+    module_name: Symbol,
+    use_span: Span,
+) -> (bool, Span) {
+    debug!(
+        "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
+        module_name, use_span
+    );
+    let source_map = sess.source_map();
+
+    // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
+    let mut num_colons = 0;
+    // Find second colon.. `use issue_59764:`
+    let until_second_colon = source_map.span_take_while(use_span, |c| {
+        if *c == ':' {
+            num_colons += 1;
+        }
+        match c {
+            ':' if num_colons == 2 => false,
+            _ => true,
+        }
+    });
+    // Find everything after the second colon.. `foo::{baz, makro};`
+    let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
+
+    let mut found_a_non_whitespace_character = false;
+    // Find the first non-whitespace character in `from_second_colon`.. `f`
+    let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
+        if found_a_non_whitespace_character {
+            return false;
+        }
+        if !c.is_whitespace() {
+            found_a_non_whitespace_character = true;
+        }
+        true
+    });
+
+    // Find the first `{` in from_second_colon.. `foo::{`
+    let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
+
+    (next_left_bracket == after_second_colon, from_second_colon)
+}
+
+/// When an entity with a given name is not available in scope, we search for
+/// entities with that name in all crates. This method allows outputting the
+/// results of this search in a programmer-friendly way
+crate fn show_candidates(
+    err: &mut DiagnosticBuilder<'_>,
+    // This is `None` if all placement locations are inside expansions
+    use_placement_span: Option<Span>,
+    candidates: &[ImportSuggestion],
+    instead: bool,
+    found_use: bool,
+) {
+    if candidates.is_empty() {
+        return;
+    }
+
+    // we want consistent results across executions, but candidates are produced
+    // by iterating through a hash map, so make sure they are ordered:
+    let mut path_strings: Vec<_> =
+        candidates.iter().map(|c| path_names_to_string(&c.path)).collect();
+
+    path_strings.sort();
+    path_strings.dedup();
+
+    let (determiner, kind) = if candidates.len() == 1 {
+        ("this", candidates[0].descr)
+    } else {
+        ("one of these", "items")
+    };
+
+    let instead = if instead { " instead" } else { "" };
+    let mut msg = format!("consider importing {} {}{}", determiner, kind, instead);
+
+    if let Some(span) = use_placement_span {
+        for candidate in &mut path_strings {
+            // produce an additional newline to separate the new use statement
+            // from the directly following item.
+            let additional_newline = if found_use { "" } else { "\n" };
+            *candidate = format!("use {};\n{}", candidate, additional_newline);
+        }
+
+        err.span_suggestions(span, &msg, path_strings.into_iter(), Applicability::Unspecified);
+    } else {
+        msg.push(':');
+
+        for candidate in path_strings {
+            msg.push('\n');
+            msg.push_str(&candidate);
+        }
+
+        err.note(&msg);
+    }
+}
diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs
new file mode 100644
index 0000000..bf8a2f2
--- /dev/null
+++ b/compiler/rustc_resolve/src/imports.rs
@@ -0,0 +1,1505 @@
+//! A bunch of methods and structures more or less related to resolving imports.
+
+use crate::diagnostics::Suggestion;
+use crate::Determinacy::{self, *};
+use crate::Namespace::{self, MacroNS, TypeNS};
+use crate::{module_to_string, names_to_string};
+use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind};
+use crate::{BindingKey, ModuleKind, ResolutionError, Resolver, Segment};
+use crate::{CrateLint, Module, ModuleOrUniformRoot, ParentScope, PerNS, ScopeSet, Weak};
+use crate::{NameBinding, NameBindingKind, PathResult, PrivacyError, ToNameBinding};
+
+use rustc_ast::unwrap_or;
+use rustc_ast::util::lev_distance::find_best_match_for_name;
+use rustc_ast::NodeId;
+use rustc_ast_lowering::ResolverAstLowering;
+use rustc_data_structures::fx::FxHashSet;
+use rustc_data_structures::ptr_key::PtrKey;
+use rustc_errors::{pluralize, struct_span_err, Applicability};
+use rustc_hir::def::{self, PartialRes};
+use rustc_hir::def_id::DefId;
+use rustc_middle::hir::exports::Export;
+use rustc_middle::ty;
+use rustc_middle::{bug, span_bug};
+use rustc_session::lint::builtin::{PUB_USE_OF_PRIVATE_EXTERN_CRATE, UNUSED_IMPORTS};
+use rustc_session::lint::BuiltinLintDiagnostics;
+use rustc_session::DiagnosticMessageId;
+use rustc_span::hygiene::ExpnId;
+use rustc_span::symbol::{kw, Ident, Symbol};
+use rustc_span::{MultiSpan, Span};
+
+use tracing::*;
+
+use std::cell::Cell;
+use std::{mem, ptr};
+
+type Res = def::Res<NodeId>;
+
+/// Contains data for specific kinds of imports.
+#[derive(Clone, Debug)]
+pub enum ImportKind<'a> {
+    Single {
+        /// `source` in `use prefix::source as target`.
+        source: Ident,
+        /// `target` in `use prefix::source as target`.
+        target: Ident,
+        /// Bindings to which `source` refers to.
+        source_bindings: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
+        /// Bindings introduced by `target`.
+        target_bindings: PerNS<Cell<Option<&'a NameBinding<'a>>>>,
+        /// `true` for `...::{self [as target]}` imports, `false` otherwise.
+        type_ns_only: bool,
+        /// Did this import result from a nested import? ie. `use foo::{bar, baz};`
+        nested: bool,
+    },
+    Glob {
+        is_prelude: bool,
+        max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
+                                       // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
+    },
+    ExternCrate {
+        source: Option<Symbol>,
+        target: Ident,
+    },
+    MacroUse,
+}
+
+/// One import.
+#[derive(Debug, Clone)]
+crate struct Import<'a> {
+    pub kind: ImportKind<'a>,
+
+    /// The ID of the `extern crate`, `UseTree` etc that imported this `Import`.
+    ///
+    /// In the case where the `Import` was expanded from a "nested" use tree,
+    /// this id is the ID of the leaf tree. For example:
+    ///
+    /// ```ignore (pacify the mercilous tidy)
+    /// use foo::bar::{a, b}
+    /// ```
+    ///
+    /// If this is the import for `foo::bar::a`, we would have the ID of the `UseTree`
+    /// for `a` in this field.
+    pub id: NodeId,
+
+    /// The `id` of the "root" use-kind -- this is always the same as
+    /// `id` except in the case of "nested" use trees, in which case
+    /// it will be the `id` of the root use tree. e.g., in the example
+    /// from `id`, this would be the ID of the `use foo::bar`
+    /// `UseTree` node.
+    pub root_id: NodeId,
+
+    /// Span of the entire use statement.
+    pub use_span: Span,
+
+    /// Span of the entire use statement with attributes.
+    pub use_span_with_attributes: Span,
+
+    /// Did the use statement have any attributes?
+    pub has_attributes: bool,
+
+    /// Span of this use tree.
+    pub span: Span,
+
+    /// Span of the *root* use tree (see `root_id`).
+    pub root_span: Span,
+
+    pub parent_scope: ParentScope<'a>,
+    pub module_path: Vec<Segment>,
+    /// The resolution of `module_path`.
+    pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>,
+    pub vis: Cell<ty::Visibility>,
+    pub used: Cell<bool>,
+}
+
+impl<'a> Import<'a> {
+    pub fn is_glob(&self) -> bool {
+        match self.kind {
+            ImportKind::Glob { .. } => true,
+            _ => false,
+        }
+    }
+
+    pub fn is_nested(&self) -> bool {
+        match self.kind {
+            ImportKind::Single { nested, .. } => nested,
+            _ => false,
+        }
+    }
+
+    crate fn crate_lint(&self) -> CrateLint {
+        CrateLint::UsePath { root_id: self.root_id, root_span: self.root_span }
+    }
+}
+
+#[derive(Clone, Default, Debug)]
+/// Records information about the resolution of a name in a namespace of a module.
+pub struct NameResolution<'a> {
+    /// Single imports that may define the name in the namespace.
+    /// Imports are arena-allocated, so it's ok to use pointers as keys.
+    single_imports: FxHashSet<PtrKey<'a, Import<'a>>>,
+    /// The least shadowable known binding for this name, or None if there are no known bindings.
+    pub binding: Option<&'a NameBinding<'a>>,
+    shadowed_glob: Option<&'a NameBinding<'a>>,
+}
+
+impl<'a> NameResolution<'a> {
+    // Returns the binding for the name if it is known or None if it not known.
+    pub(crate) fn binding(&self) -> Option<&'a NameBinding<'a>> {
+        self.binding.and_then(|binding| {
+            if !binding.is_glob_import() || self.single_imports.is_empty() {
+                Some(binding)
+            } else {
+                None
+            }
+        })
+    }
+
+    crate fn add_single_import(&mut self, import: &'a Import<'a>) {
+        self.single_imports.insert(PtrKey(import));
+    }
+}
+
+impl<'a> Resolver<'a> {
+    crate fn resolve_ident_in_module_unadjusted(
+        &mut self,
+        module: ModuleOrUniformRoot<'a>,
+        ident: Ident,
+        ns: Namespace,
+        parent_scope: &ParentScope<'a>,
+        record_used: bool,
+        path_span: Span,
+    ) -> Result<&'a NameBinding<'a>, Determinacy> {
+        self.resolve_ident_in_module_unadjusted_ext(
+            module,
+            ident,
+            ns,
+            parent_scope,
+            false,
+            record_used,
+            path_span,
+        )
+        .map_err(|(determinacy, _)| determinacy)
+    }
+
+    /// Attempts to resolve `ident` in namespaces `ns` of `module`.
+    /// Invariant: if `record_used` is `Some`, expansion and import resolution must be complete.
+    crate fn resolve_ident_in_module_unadjusted_ext(
+        &mut self,
+        module: ModuleOrUniformRoot<'a>,
+        ident: Ident,
+        ns: Namespace,
+        parent_scope: &ParentScope<'a>,
+        restricted_shadowing: bool,
+        record_used: bool,
+        path_span: Span,
+    ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
+        let module = match module {
+            ModuleOrUniformRoot::Module(module) => module,
+            ModuleOrUniformRoot::CrateRootAndExternPrelude => {
+                assert!(!restricted_shadowing);
+                let binding = self.early_resolve_ident_in_lexical_scope(
+                    ident,
+                    ScopeSet::AbsolutePath(ns),
+                    parent_scope,
+                    record_used,
+                    record_used,
+                    path_span,
+                );
+                return binding.map_err(|determinacy| (determinacy, Weak::No));
+            }
+            ModuleOrUniformRoot::ExternPrelude => {
+                assert!(!restricted_shadowing);
+                return if ns != TypeNS {
+                    Err((Determined, Weak::No))
+                } else if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
+                    Ok(binding)
+                } else if !self.graph_root.unexpanded_invocations.borrow().is_empty() {
+                    // Macro-expanded `extern crate` items can add names to extern prelude.
+                    Err((Undetermined, Weak::No))
+                } else {
+                    Err((Determined, Weak::No))
+                };
+            }
+            ModuleOrUniformRoot::CurrentScope => {
+                assert!(!restricted_shadowing);
+                if ns == TypeNS {
+                    if ident.name == kw::Crate || ident.name == kw::DollarCrate {
+                        let module = self.resolve_crate_root(ident);
+                        let binding = (module, ty::Visibility::Public, module.span, ExpnId::root())
+                            .to_name_binding(self.arenas);
+                        return Ok(binding);
+                    } else if ident.name == kw::Super || ident.name == kw::SelfLower {
+                        // FIXME: Implement these with renaming requirements so that e.g.
+                        // `use super;` doesn't work, but `use super as name;` does.
+                        // Fall through here to get an error from `early_resolve_...`.
+                    }
+                }
+
+                let scopes = ScopeSet::All(ns, true);
+                let binding = self.early_resolve_ident_in_lexical_scope(
+                    ident,
+                    scopes,
+                    parent_scope,
+                    record_used,
+                    record_used,
+                    path_span,
+                );
+                return binding.map_err(|determinacy| (determinacy, Weak::No));
+            }
+        };
+
+        let key = self.new_key(ident, ns);
+        let resolution =
+            self.resolution(module, key).try_borrow_mut().map_err(|_| (Determined, Weak::No))?; // This happens when there is a cycle of imports.
+
+        if let Some(binding) = resolution.binding {
+            if !restricted_shadowing && binding.expansion != ExpnId::root() {
+                if let NameBindingKind::Res(_, true) = binding.kind {
+                    self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
+                }
+            }
+        }
+
+        let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
+            if let Some(unusable_binding) = this.unusable_binding {
+                if ptr::eq(binding, unusable_binding) {
+                    return Err((Determined, Weak::No));
+                }
+            }
+            // `extern crate` are always usable for backwards compatibility, see issue #37020,
+            // remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`.
+            let usable = this.is_accessible_from(binding.vis, parent_scope.module)
+                || binding.is_extern_crate();
+            if usable { Ok(binding) } else { Err((Determined, Weak::No)) }
+        };
+
+        if record_used {
+            return resolution
+                .binding
+                .and_then(|binding| {
+                    // If the primary binding is unusable, search further and return the shadowed glob
+                    // binding if it exists. What we really want here is having two separate scopes in
+                    // a module - one for non-globs and one for globs, but until that's done use this
+                    // hack to avoid inconsistent resolution ICEs during import validation.
+                    if let Some(unusable_binding) = self.unusable_binding {
+                        if ptr::eq(binding, unusable_binding) {
+                            return resolution.shadowed_glob;
+                        }
+                    }
+                    Some(binding)
+                })
+                .ok_or((Determined, Weak::No))
+                .and_then(|binding| {
+                    if self.last_import_segment && check_usable(self, binding).is_err() {
+                        Err((Determined, Weak::No))
+                    } else {
+                        self.record_use(ident, ns, binding, restricted_shadowing);
+
+                        if let Some(shadowed_glob) = resolution.shadowed_glob {
+                            // Forbid expanded shadowing to avoid time travel.
+                            if restricted_shadowing
+                                && binding.expansion != ExpnId::root()
+                                && binding.res() != shadowed_glob.res()
+                            {
+                                self.ambiguity_errors.push(AmbiguityError {
+                                    kind: AmbiguityKind::GlobVsExpanded,
+                                    ident,
+                                    b1: binding,
+                                    b2: shadowed_glob,
+                                    misc1: AmbiguityErrorMisc::None,
+                                    misc2: AmbiguityErrorMisc::None,
+                                });
+                            }
+                        }
+
+                        if !(self.is_accessible_from(binding.vis, parent_scope.module) ||
+                       // Remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
+                       (self.last_import_segment && binding.is_extern_crate()))
+                        {
+                            self.privacy_errors.push(PrivacyError {
+                                ident,
+                                binding,
+                                dedup_span: path_span,
+                            });
+                        }
+
+                        Ok(binding)
+                    }
+                });
+        }
+
+        // Items and single imports are not shadowable, if we have one, then it's determined.
+        if let Some(binding) = resolution.binding {
+            if !binding.is_glob_import() {
+                return check_usable(self, binding);
+            }
+        }
+
+        // --- From now on we either have a glob resolution or no resolution. ---
+
+        // Check if one of single imports can still define the name,
+        // if it can then our result is not determined and can be invalidated.
+        for single_import in &resolution.single_imports {
+            if !self.is_accessible_from(single_import.vis.get(), parent_scope.module) {
+                continue;
+            }
+            let module = unwrap_or!(
+                single_import.imported_module.get(),
+                return Err((Undetermined, Weak::No))
+            );
+            let ident = match single_import.kind {
+                ImportKind::Single { source, .. } => source,
+                _ => unreachable!(),
+            };
+            match self.resolve_ident_in_module(
+                module,
+                ident,
+                ns,
+                &single_import.parent_scope,
+                false,
+                path_span,
+            ) {
+                Err(Determined) => continue,
+                Ok(binding)
+                    if !self.is_accessible_from(binding.vis, single_import.parent_scope.module) =>
+                {
+                    continue;
+                }
+                Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::No)),
+            }
+        }
+
+        // So we have a resolution that's from a glob import. This resolution is determined
+        // if it cannot be shadowed by some new item/import expanded from a macro.
+        // This happens either if there are no unexpanded macros, or expanded names cannot
+        // shadow globs (that happens in macro namespace or with restricted shadowing).
+        //
+        // Additionally, any macro in any module can plant names in the root module if it creates
+        // `macro_export` macros, so the root module effectively has unresolved invocations if any
+        // module has unresolved invocations.
+        // However, it causes resolution/expansion to stuck too often (#53144), so, to make
+        // progress, we have to ignore those potential unresolved invocations from other modules
+        // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
+        // shadowing is enabled, see `macro_expanded_macro_export_errors`).
+        let unexpanded_macros = !module.unexpanded_invocations.borrow().is_empty();
+        if let Some(binding) = resolution.binding {
+            if !unexpanded_macros || ns == MacroNS || restricted_shadowing {
+                return check_usable(self, binding);
+            } else {
+                return Err((Undetermined, Weak::No));
+            }
+        }
+
+        // --- From now on we have no resolution. ---
+
+        // Now we are in situation when new item/import can appear only from a glob or a macro
+        // expansion. With restricted shadowing names from globs and macro expansions cannot
+        // shadow names from outer scopes, so we can freely fallback from module search to search
+        // in outer scopes. For `early_resolve_ident_in_lexical_scope` to continue search in outer
+        // scopes we return `Undetermined` with `Weak::Yes`.
+
+        // Check if one of unexpanded macros can still define the name,
+        // if it can then our "no resolution" result is not determined and can be invalidated.
+        if unexpanded_macros {
+            return Err((Undetermined, Weak::Yes));
+        }
+
+        // Check if one of glob imports can still define the name,
+        // if it can then our "no resolution" result is not determined and can be invalidated.
+        for glob_import in module.globs.borrow().iter() {
+            if !self.is_accessible_from(glob_import.vis.get(), parent_scope.module) {
+                continue;
+            }
+            let module = match glob_import.imported_module.get() {
+                Some(ModuleOrUniformRoot::Module(module)) => module,
+                Some(_) => continue,
+                None => return Err((Undetermined, Weak::Yes)),
+            };
+            let tmp_parent_scope;
+            let (mut adjusted_parent_scope, mut ident) =
+                (parent_scope, ident.normalize_to_macros_2_0());
+            match ident.span.glob_adjust(module.expansion, glob_import.span) {
+                Some(Some(def)) => {
+                    tmp_parent_scope =
+                        ParentScope { module: self.macro_def_scope(def), ..*parent_scope };
+                    adjusted_parent_scope = &tmp_parent_scope;
+                }
+                Some(None) => {}
+                None => continue,
+            };
+            let result = self.resolve_ident_in_module_unadjusted(
+                ModuleOrUniformRoot::Module(module),
+                ident,
+                ns,
+                adjusted_parent_scope,
+                false,
+                path_span,
+            );
+
+            match result {
+                Err(Determined) => continue,
+                Ok(binding)
+                    if !self.is_accessible_from(binding.vis, glob_import.parent_scope.module) =>
+                {
+                    continue;
+                }
+                Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::Yes)),
+            }
+        }
+
+        // No resolution and no one else can define the name - determinate error.
+        Err((Determined, Weak::No))
+    }
+
+    // Given a binding and an import that resolves to it,
+    // return the corresponding binding defined by the import.
+    crate fn import(
+        &self,
+        binding: &'a NameBinding<'a>,
+        import: &'a Import<'a>,
+    ) -> &'a NameBinding<'a> {
+        let vis = if binding.pseudo_vis().is_at_least(import.vis.get(), self) ||
+                     // cf. `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
+                     !import.is_glob() && binding.is_extern_crate()
+        {
+            import.vis.get()
+        } else {
+            binding.pseudo_vis()
+        };
+
+        if let ImportKind::Glob { ref max_vis, .. } = import.kind {
+            if vis == import.vis.get() || vis.is_at_least(max_vis.get(), self) {
+                max_vis.set(vis)
+            }
+        }
+
+        self.arenas.alloc_name_binding(NameBinding {
+            kind: NameBindingKind::Import { binding, import, used: Cell::new(false) },
+            ambiguity: None,
+            span: import.span,
+            vis,
+            expansion: import.parent_scope.expansion,
+        })
+    }
+
+    // Define the name or return the existing binding if there is a collision.
+    crate fn try_define(
+        &mut self,
+        module: Module<'a>,
+        key: BindingKey,
+        binding: &'a NameBinding<'a>,
+    ) -> Result<(), &'a NameBinding<'a>> {
+        let res = binding.res();
+        self.check_reserved_macro_name(key.ident, res);
+        self.set_binding_parent_module(binding, module);
+        self.update_resolution(module, key, |this, resolution| {
+            if let Some(old_binding) = resolution.binding {
+                if res == Res::Err {
+                    // Do not override real bindings with `Res::Err`s from error recovery.
+                    return Ok(());
+                }
+                match (old_binding.is_glob_import(), binding.is_glob_import()) {
+                    (true, true) => {
+                        if res != old_binding.res() {
+                            resolution.binding = Some(this.ambiguity(
+                                AmbiguityKind::GlobVsGlob,
+                                old_binding,
+                                binding,
+                            ));
+                        } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
+                            // We are glob-importing the same item but with greater visibility.
+                            resolution.binding = Some(binding);
+                        }
+                    }
+                    (old_glob @ true, false) | (old_glob @ false, true) => {
+                        let (glob_binding, nonglob_binding) =
+                            if old_glob { (old_binding, binding) } else { (binding, old_binding) };
+                        if glob_binding.res() != nonglob_binding.res()
+                            && key.ns == MacroNS
+                            && nonglob_binding.expansion != ExpnId::root()
+                        {
+                            resolution.binding = Some(this.ambiguity(
+                                AmbiguityKind::GlobVsExpanded,
+                                nonglob_binding,
+                                glob_binding,
+                            ));
+                        } else {
+                            resolution.binding = Some(nonglob_binding);
+                        }
+                        resolution.shadowed_glob = Some(glob_binding);
+                    }
+                    (false, false) => {
+                        return Err(old_binding);
+                    }
+                }
+            } else {
+                resolution.binding = Some(binding);
+            }
+
+            Ok(())
+        })
+    }
+
+    fn ambiguity(
+        &self,
+        kind: AmbiguityKind,
+        primary_binding: &'a NameBinding<'a>,
+        secondary_binding: &'a NameBinding<'a>,
+    ) -> &'a NameBinding<'a> {
+        self.arenas.alloc_name_binding(NameBinding {
+            ambiguity: Some((secondary_binding, kind)),
+            ..primary_binding.clone()
+        })
+    }
+
+    // Use `f` to mutate the resolution of the name in the module.
+    // If the resolution becomes a success, define it in the module's glob importers.
+    fn update_resolution<T, F>(&mut self, module: Module<'a>, key: BindingKey, f: F) -> T
+    where
+        F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T,
+    {
+        // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
+        // during which the resolution might end up getting re-defined via a glob cycle.
+        let (binding, t) = {
+            let resolution = &mut *self.resolution(module, key).borrow_mut();
+            let old_binding = resolution.binding();
+
+            let t = f(self, resolution);
+
+            match resolution.binding() {
+                _ if old_binding.is_some() => return t,
+                None => return t,
+                Some(binding) => match old_binding {
+                    Some(old_binding) if ptr::eq(old_binding, binding) => return t,
+                    _ => (binding, t),
+                },
+            }
+        };
+
+        // Define `binding` in `module`s glob importers.
+        for import in module.glob_importers.borrow_mut().iter() {
+            let mut ident = key.ident;
+            let scope = match ident.span.reverse_glob_adjust(module.expansion, import.span) {
+                Some(Some(def)) => self.macro_def_scope(def),
+                Some(None) => import.parent_scope.module,
+                None => continue,
+            };
+            if self.is_accessible_from(binding.vis, scope) {
+                let imported_binding = self.import(binding, import);
+                let key = BindingKey { ident, ..key };
+                let _ = self.try_define(import.parent_scope.module, key, imported_binding);
+            }
+        }
+
+        t
+    }
+
+    // Define a "dummy" resolution containing a Res::Err as a placeholder for a
+    // failed resolution
+    fn import_dummy_binding(&mut self, import: &'a Import<'a>) {
+        if let ImportKind::Single { target, .. } = import.kind {
+            let dummy_binding = self.dummy_binding;
+            let dummy_binding = self.import(dummy_binding, import);
+            self.per_ns(|this, ns| {
+                let key = this.new_key(target, ns);
+                let _ = this.try_define(import.parent_scope.module, key, dummy_binding);
+                // Consider erroneous imports used to avoid duplicate diagnostics.
+                this.record_use(target, ns, dummy_binding, false);
+            });
+        }
+    }
+}
+
+/// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
+/// import errors within the same use tree into a single diagnostic.
+#[derive(Debug, Clone)]
+struct UnresolvedImportError {
+    span: Span,
+    label: Option<String>,
+    note: Vec<String>,
+    suggestion: Option<Suggestion>,
+}
+
+pub struct ImportResolver<'a, 'b> {
+    pub r: &'a mut Resolver<'b>,
+}
+
+impl<'a, 'b> ty::DefIdTree for &'a ImportResolver<'a, 'b> {
+    fn parent(self, id: DefId) -> Option<DefId> {
+        self.r.parent(id)
+    }
+}
+
+impl<'a, 'b> ImportResolver<'a, 'b> {
+    // Import resolution
+    //
+    // This is a fixed-point algorithm. We resolve imports until our efforts
+    // are stymied by an unresolved import; then we bail out of the current
+    // module and continue. We terminate successfully once no more imports
+    // remain or unsuccessfully when no forward progress in resolving imports
+    // is made.
+
+    /// Resolves all imports for the crate. This method performs the fixed-
+    /// point iteration.
+    pub fn resolve_imports(&mut self) {
+        let mut prev_num_indeterminates = self.r.indeterminate_imports.len() + 1;
+        while self.r.indeterminate_imports.len() < prev_num_indeterminates {
+            prev_num_indeterminates = self.r.indeterminate_imports.len();
+            for import in mem::take(&mut self.r.indeterminate_imports) {
+                match self.resolve_import(&import) {
+                    true => self.r.determined_imports.push(import),
+                    false => self.r.indeterminate_imports.push(import),
+                }
+            }
+        }
+    }
+
+    pub fn finalize_imports(&mut self) {
+        for module in self.r.arenas.local_modules().iter() {
+            self.finalize_resolutions_in(module);
+        }
+
+        let mut seen_spans = FxHashSet::default();
+        let mut errors = vec![];
+        let mut prev_root_id: NodeId = NodeId::from_u32(0);
+        let determined_imports = mem::take(&mut self.r.determined_imports);
+        let indeterminate_imports = mem::take(&mut self.r.indeterminate_imports);
+
+        for (is_indeterminate, import) in determined_imports
+            .into_iter()
+            .map(|i| (false, i))
+            .chain(indeterminate_imports.into_iter().map(|i| (true, i)))
+        {
+            if let Some(err) = self.finalize_import(import) {
+                if let ImportKind::Single { source, ref source_bindings, .. } = import.kind {
+                    if source.name == kw::SelfLower {
+                        // Silence `unresolved import` error if E0429 is already emitted
+                        if let Err(Determined) = source_bindings.value_ns.get() {
+                            continue;
+                        }
+                    }
+                }
+
+                // If the error is a single failed import then create a "fake" import
+                // resolution for it so that later resolve stages won't complain.
+                self.r.import_dummy_binding(import);
+                if prev_root_id.as_u32() != 0
+                    && prev_root_id.as_u32() != import.root_id.as_u32()
+                    && !errors.is_empty()
+                {
+                    // In the case of a new import line, throw a diagnostic message
+                    // for the previous line.
+                    self.throw_unresolved_import_error(errors, None);
+                    errors = vec![];
+                }
+                if seen_spans.insert(err.span) {
+                    let path = import_path_to_string(
+                        &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
+                        &import.kind,
+                        err.span,
+                    );
+                    errors.push((path, err));
+                    prev_root_id = import.root_id;
+                }
+            } else if is_indeterminate {
+                // Consider erroneous imports used to avoid duplicate diagnostics.
+                self.r.used_imports.insert((import.id, TypeNS));
+                let path = import_path_to_string(
+                    &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
+                    &import.kind,
+                    import.span,
+                );
+                let err = UnresolvedImportError {
+                    span: import.span,
+                    label: None,
+                    note: Vec::new(),
+                    suggestion: None,
+                };
+                errors.push((path, err));
+            }
+        }
+
+        if !errors.is_empty() {
+            self.throw_unresolved_import_error(errors, None);
+        }
+    }
+
+    fn throw_unresolved_import_error(
+        &self,
+        errors: Vec<(String, UnresolvedImportError)>,
+        span: Option<MultiSpan>,
+    ) {
+        /// Upper limit on the number of `span_label` messages.
+        const MAX_LABEL_COUNT: usize = 10;
+
+        let (span, msg) = if errors.is_empty() {
+            (span.unwrap(), "unresolved import".to_string())
+        } else {
+            let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
+
+            let paths = errors.iter().map(|(path, _)| format!("`{}`", path)).collect::<Vec<_>>();
+
+            let msg = format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);
+
+            (span, msg)
+        };
+
+        let mut diag = struct_span_err!(self.r.session, span, E0432, "{}", &msg);
+
+        if let Some((_, UnresolvedImportError { note, .. })) = errors.iter().last() {
+            for message in note {
+                diag.note(&message);
+            }
+        }
+
+        for (_, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
+            if let Some(label) = err.label {
+                diag.span_label(err.span, label);
+            }
+
+            if let Some((suggestions, msg, applicability)) = err.suggestion {
+                diag.multipart_suggestion(&msg, suggestions, applicability);
+            }
+        }
+
+        diag.emit();
+    }
+
+    /// Attempts to resolve the given import, returning true if its resolution is determined.
+    /// If successful, the resolved bindings are written into the module.
+    fn resolve_import(&mut self, import: &'b Import<'b>) -> bool {
+        debug!(
+            "(resolving import for module) resolving import `{}::...` in `{}`",
+            Segment::names_to_string(&import.module_path),
+            module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
+        );
+
+        let module = if let Some(module) = import.imported_module.get() {
+            module
+        } else {
+            // For better failure detection, pretend that the import will
+            // not define any names while resolving its module path.
+            let orig_vis = import.vis.replace(ty::Visibility::Invisible);
+            let path_res = self.r.resolve_path(
+                &import.module_path,
+                None,
+                &import.parent_scope,
+                false,
+                import.span,
+                import.crate_lint(),
+            );
+            import.vis.set(orig_vis);
+
+            match path_res {
+                PathResult::Module(module) => module,
+                PathResult::Indeterminate => return false,
+                PathResult::NonModule(..) | PathResult::Failed { .. } => return true,
+            }
+        };
+
+        import.imported_module.set(Some(module));
+        let (source, target, source_bindings, target_bindings, type_ns_only) = match import.kind {
+            ImportKind::Single {
+                source,
+                target,
+                ref source_bindings,
+                ref target_bindings,
+                type_ns_only,
+                ..
+            } => (source, target, source_bindings, target_bindings, type_ns_only),
+            ImportKind::Glob { .. } => {
+                self.resolve_glob_import(import);
+                return true;
+            }
+            _ => unreachable!(),
+        };
+
+        let mut indeterminate = false;
+        self.r.per_ns(|this, ns| {
+            if !type_ns_only || ns == TypeNS {
+                if let Err(Undetermined) = source_bindings[ns].get() {
+                    // For better failure detection, pretend that the import will
+                    // not define any names while resolving its module path.
+                    let orig_vis = import.vis.replace(ty::Visibility::Invisible);
+                    let binding = this.resolve_ident_in_module(
+                        module,
+                        source,
+                        ns,
+                        &import.parent_scope,
+                        false,
+                        import.span,
+                    );
+                    import.vis.set(orig_vis);
+
+                    source_bindings[ns].set(binding);
+                } else {
+                    return;
+                };
+
+                let parent = import.parent_scope.module;
+                match source_bindings[ns].get() {
+                    Err(Undetermined) => indeterminate = true,
+                    // Don't update the resolution, because it was never added.
+                    Err(Determined) if target.name == kw::Underscore => {}
+                    Err(Determined) => {
+                        let key = this.new_key(target, ns);
+                        this.update_resolution(parent, key, |_, resolution| {
+                            resolution.single_imports.remove(&PtrKey(import));
+                        });
+                    }
+                    Ok(binding) if !binding.is_importable() => {
+                        let msg = format!("`{}` is not directly importable", target);
+                        struct_span_err!(this.session, import.span, E0253, "{}", &msg)
+                            .span_label(import.span, "cannot be imported directly")
+                            .emit();
+                        // Do not import this illegal binding. Import a dummy binding and pretend
+                        // everything is fine
+                        this.import_dummy_binding(import);
+                    }
+                    Ok(binding) => {
+                        let imported_binding = this.import(binding, import);
+                        target_bindings[ns].set(Some(imported_binding));
+                        this.define(parent, target, ns, imported_binding);
+                    }
+                }
+            }
+        });
+
+        !indeterminate
+    }
+
+    /// Performs final import resolution, consistency checks and error reporting.
+    ///
+    /// Optionally returns an unresolved import error. This error is buffered and used to
+    /// consolidate multiple unresolved import errors into a single diagnostic.
+    fn finalize_import(&mut self, import: &'b Import<'b>) -> Option<UnresolvedImportError> {
+        let orig_vis = import.vis.replace(ty::Visibility::Invisible);
+        let orig_unusable_binding = match &import.kind {
+            ImportKind::Single { target_bindings, .. } => {
+                Some(mem::replace(&mut self.r.unusable_binding, target_bindings[TypeNS].get()))
+            }
+            _ => None,
+        };
+        let prev_ambiguity_errors_len = self.r.ambiguity_errors.len();
+        let path_res = self.r.resolve_path(
+            &import.module_path,
+            None,
+            &import.parent_scope,
+            true,
+            import.span,
+            import.crate_lint(),
+        );
+        let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len;
+        if let Some(orig_unusable_binding) = orig_unusable_binding {
+            self.r.unusable_binding = orig_unusable_binding;
+        }
+        import.vis.set(orig_vis);
+        if let PathResult::Failed { .. } | PathResult::NonModule(..) = path_res {
+            // Consider erroneous imports used to avoid duplicate diagnostics.
+            self.r.used_imports.insert((import.id, TypeNS));
+        }
+        let module = match path_res {
+            PathResult::Module(module) => {
+                // Consistency checks, analogous to `finalize_macro_resolutions`.
+                if let Some(initial_module) = import.imported_module.get() {
+                    if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
+                        span_bug!(import.span, "inconsistent resolution for an import");
+                    }
+                } else {
+                    if self.r.privacy_errors.is_empty() {
+                        let msg = "cannot determine resolution for the import";
+                        let msg_note = "import resolution is stuck, try simplifying other imports";
+                        self.r.session.struct_span_err(import.span, msg).note(msg_note).emit();
+                    }
+                }
+
+                module
+            }
+            PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
+                if no_ambiguity {
+                    assert!(import.imported_module.get().is_none());
+                    self.r
+                        .report_error(span, ResolutionError::FailedToResolve { label, suggestion });
+                }
+                return None;
+            }
+            PathResult::Failed { is_error_from_last_segment: true, span, label, suggestion } => {
+                if no_ambiguity {
+                    assert!(import.imported_module.get().is_none());
+                    let err = match self.make_path_suggestion(
+                        span,
+                        import.module_path.clone(),
+                        &import.parent_scope,
+                    ) {
+                        Some((suggestion, note)) => UnresolvedImportError {
+                            span,
+                            label: None,
+                            note,
+                            suggestion: Some((
+                                vec![(span, Segment::names_to_string(&suggestion))],
+                                String::from("a similar path exists"),
+                                Applicability::MaybeIncorrect,
+                            )),
+                        },
+                        None => UnresolvedImportError {
+                            span,
+                            label: Some(label),
+                            note: Vec::new(),
+                            suggestion,
+                        },
+                    };
+                    return Some(err);
+                }
+                return None;
+            }
+            PathResult::NonModule(path_res) if path_res.base_res() == Res::Err => {
+                if no_ambiguity {
+                    assert!(import.imported_module.get().is_none());
+                }
+                // The error was already reported earlier.
+                return None;
+            }
+            PathResult::Indeterminate | PathResult::NonModule(..) => unreachable!(),
+        };
+
+        let (ident, target, source_bindings, target_bindings, type_ns_only) = match import.kind {
+            ImportKind::Single {
+                source,
+                target,
+                ref source_bindings,
+                ref target_bindings,
+                type_ns_only,
+                ..
+            } => (source, target, source_bindings, target_bindings, type_ns_only),
+            ImportKind::Glob { is_prelude, ref max_vis } => {
+                if import.module_path.len() <= 1 {
+                    // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
+                    // 2 segments, so the `resolve_path` above won't trigger it.
+                    let mut full_path = import.module_path.clone();
+                    full_path.push(Segment::from_ident(Ident::invalid()));
+                    self.r.lint_if_path_starts_with_module(
+                        import.crate_lint(),
+                        &full_path,
+                        import.span,
+                        None,
+                    );
+                }
+
+                if let ModuleOrUniformRoot::Module(module) = module {
+                    if module.def_id() == import.parent_scope.module.def_id() {
+                        // Importing a module into itself is not allowed.
+                        return Some(UnresolvedImportError {
+                            span: import.span,
+                            label: Some(String::from("cannot glob-import a module into itself")),
+                            note: Vec::new(),
+                            suggestion: None,
+                        });
+                    }
+                }
+                if !is_prelude &&
+                   max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
+                   !max_vis.get().is_at_least(import.vis.get(), &*self)
+                {
+                    let msg = "glob import doesn't reexport anything because no candidate is public enough";
+                    self.r.lint_buffer.buffer_lint(UNUSED_IMPORTS, import.id, import.span, msg);
+                }
+                return None;
+            }
+            _ => unreachable!(),
+        };
+
+        let mut all_ns_err = true;
+        self.r.per_ns(|this, ns| {
+            if !type_ns_only || ns == TypeNS {
+                let orig_vis = import.vis.replace(ty::Visibility::Invisible);
+                let orig_unusable_binding =
+                    mem::replace(&mut this.unusable_binding, target_bindings[ns].get());
+                let orig_last_import_segment = mem::replace(&mut this.last_import_segment, true);
+                let binding = this.resolve_ident_in_module(
+                    module,
+                    ident,
+                    ns,
+                    &import.parent_scope,
+                    true,
+                    import.span,
+                );
+                this.last_import_segment = orig_last_import_segment;
+                this.unusable_binding = orig_unusable_binding;
+                import.vis.set(orig_vis);
+
+                match binding {
+                    Ok(binding) => {
+                        // Consistency checks, analogous to `finalize_macro_resolutions`.
+                        let initial_res = source_bindings[ns].get().map(|initial_binding| {
+                            all_ns_err = false;
+                            if let Some(target_binding) = target_bindings[ns].get() {
+                                if target.name == kw::Underscore
+                                    && initial_binding.is_extern_crate()
+                                    && !initial_binding.is_import()
+                                {
+                                    this.record_use(
+                                        ident,
+                                        ns,
+                                        target_binding,
+                                        import.module_path.is_empty(),
+                                    );
+                                }
+                            }
+                            initial_binding.res()
+                        });
+                        let res = binding.res();
+                        if let Ok(initial_res) = initial_res {
+                            if res != initial_res && this.ambiguity_errors.is_empty() {
+                                span_bug!(import.span, "inconsistent resolution for an import");
+                            }
+                        } else {
+                            if res != Res::Err
+                                && this.ambiguity_errors.is_empty()
+                                && this.privacy_errors.is_empty()
+                            {
+                                let msg = "cannot determine resolution for the import";
+                                let msg_note =
+                                    "import resolution is stuck, try simplifying other imports";
+                                this.session
+                                    .struct_span_err(import.span, msg)
+                                    .note(msg_note)
+                                    .emit();
+                            }
+                        }
+                    }
+                    Err(..) => {
+                        // FIXME: This assert may fire if public glob is later shadowed by a private
+                        // single import (see test `issue-55884-2.rs`). In theory single imports should
+                        // always block globs, even if they are not yet resolved, so that this kind of
+                        // self-inconsistent resolution never happens.
+                        // Re-enable the assert when the issue is fixed.
+                        // assert!(result[ns].get().is_err());
+                    }
+                }
+            }
+        });
+
+        if all_ns_err {
+            let mut all_ns_failed = true;
+            self.r.per_ns(|this, ns| {
+                if !type_ns_only || ns == TypeNS {
+                    let binding = this.resolve_ident_in_module(
+                        module,
+                        ident,
+                        ns,
+                        &import.parent_scope,
+                        true,
+                        import.span,
+                    );
+                    if binding.is_ok() {
+                        all_ns_failed = false;
+                    }
+                }
+            });
+
+            return if all_ns_failed {
+                let resolutions = match module {
+                    ModuleOrUniformRoot::Module(module) => {
+                        Some(self.r.resolutions(module).borrow())
+                    }
+                    _ => None,
+                };
+                let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
+                let names = resolutions.filter_map(|(BindingKey { ident: i, .. }, resolution)| {
+                    if *i == ident {
+                        return None;
+                    } // Never suggest the same name
+                    match *resolution.borrow() {
+                        NameResolution { binding: Some(name_binding), .. } => {
+                            match name_binding.kind {
+                                NameBindingKind::Import { binding, .. } => {
+                                    match binding.kind {
+                                        // Never suggest the name that has binding error
+                                        // i.e., the name that cannot be previously resolved
+                                        NameBindingKind::Res(Res::Err, _) => None,
+                                        _ => Some(&i.name),
+                                    }
+                                }
+                                _ => Some(&i.name),
+                            }
+                        }
+                        NameResolution { ref single_imports, .. } if single_imports.is_empty() => {
+                            None
+                        }
+                        _ => Some(&i.name),
+                    }
+                });
+
+                let lev_suggestion =
+                    find_best_match_for_name(names, ident.name, None).map(|suggestion| {
+                        (
+                            vec![(ident.span, suggestion.to_string())],
+                            String::from("a similar name exists in the module"),
+                            Applicability::MaybeIncorrect,
+                        )
+                    });
+
+                let (suggestion, note) =
+                    match self.check_for_module_export_macro(import, module, ident) {
+                        Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
+                        _ => (lev_suggestion, Vec::new()),
+                    };
+
+                let label = match module {
+                    ModuleOrUniformRoot::Module(module) => {
+                        let module_str = module_to_string(module);
+                        if let Some(module_str) = module_str {
+                            format!("no `{}` in `{}`", ident, module_str)
+                        } else {
+                            format!("no `{}` in the root", ident)
+                        }
+                    }
+                    _ => {
+                        if !ident.is_path_segment_keyword() {
+                            format!("no external crate `{}`", ident)
+                        } else {
+                            // HACK(eddyb) this shows up for `self` & `super`, which
+                            // should work instead - for now keep the same error message.
+                            format!("no `{}` in the root", ident)
+                        }
+                    }
+                };
+
+                Some(UnresolvedImportError {
+                    span: import.span,
+                    label: Some(label),
+                    note,
+                    suggestion,
+                })
+            } else {
+                // `resolve_ident_in_module` reported a privacy error.
+                self.r.import_dummy_binding(import);
+                None
+            };
+        }
+
+        let mut reexport_error = None;
+        let mut any_successful_reexport = false;
+        self.r.per_ns(|this, ns| {
+            if let Ok(binding) = source_bindings[ns].get() {
+                let vis = import.vis.get();
+                if !binding.pseudo_vis().is_at_least(vis, &*this) {
+                    reexport_error = Some((ns, binding));
+                } else {
+                    any_successful_reexport = true;
+                }
+            }
+        });
+
+        // All namespaces must be re-exported with extra visibility for an error to occur.
+        if !any_successful_reexport {
+            let (ns, binding) = reexport_error.unwrap();
+            if ns == TypeNS && binding.is_extern_crate() {
+                let msg = format!(
+                    "extern crate `{}` is private, and cannot be \
+                                   re-exported (error E0365), consider declaring with \
+                                   `pub`",
+                    ident
+                );
+                self.r.lint_buffer.buffer_lint(
+                    PUB_USE_OF_PRIVATE_EXTERN_CRATE,
+                    import.id,
+                    import.span,
+                    &msg,
+                );
+            } else if ns == TypeNS {
+                struct_span_err!(
+                    self.r.session,
+                    import.span,
+                    E0365,
+                    "`{}` is private, and cannot be re-exported",
+                    ident
+                )
+                .span_label(import.span, format!("re-export of private `{}`", ident))
+                .note(&format!("consider declaring type or module `{}` with `pub`", ident))
+                .emit();
+            } else {
+                let msg = format!("`{}` is private, and cannot be re-exported", ident);
+                let note_msg =
+                    format!("consider marking `{}` as `pub` in the imported module", ident,);
+                struct_span_err!(self.r.session, import.span, E0364, "{}", &msg)
+                    .span_note(import.span, &note_msg)
+                    .emit();
+            }
+        }
+
+        if import.module_path.len() <= 1 {
+            // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
+            // 2 segments, so the `resolve_path` above won't trigger it.
+            let mut full_path = import.module_path.clone();
+            full_path.push(Segment::from_ident(ident));
+            self.r.per_ns(|this, ns| {
+                if let Ok(binding) = source_bindings[ns].get() {
+                    this.lint_if_path_starts_with_module(
+                        import.crate_lint(),
+                        &full_path,
+                        import.span,
+                        Some(binding),
+                    );
+                }
+            });
+        }
+
+        // Record what this import resolves to for later uses in documentation,
+        // this may resolve to either a value or a type, but for documentation
+        // purposes it's good enough to just favor one over the other.
+        self.r.per_ns(|this, ns| {
+            if let Ok(binding) = source_bindings[ns].get() {
+                this.import_res_map.entry(import.id).or_default()[ns] = Some(binding.res());
+            }
+        });
+
+        self.check_for_redundant_imports(ident, import, source_bindings, target_bindings, target);
+
+        debug!("(resolving single import) successfully resolved import");
+        None
+    }
+
+    fn check_for_redundant_imports(
+        &mut self,
+        ident: Ident,
+        import: &'b Import<'b>,
+        source_bindings: &PerNS<Cell<Result<&'b NameBinding<'b>, Determinacy>>>,
+        target_bindings: &PerNS<Cell<Option<&'b NameBinding<'b>>>>,
+        target: Ident,
+    ) {
+        // Skip if the import was produced by a macro.
+        if import.parent_scope.expansion != ExpnId::root() {
+            return;
+        }
+
+        // Skip if we are inside a named module (in contrast to an anonymous
+        // module defined by a block).
+        if let ModuleKind::Def(..) = import.parent_scope.module.kind {
+            return;
+        }
+
+        let mut is_redundant = PerNS { value_ns: None, type_ns: None, macro_ns: None };
+
+        let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
+
+        self.r.per_ns(|this, ns| {
+            if let Ok(binding) = source_bindings[ns].get() {
+                if binding.res() == Res::Err {
+                    return;
+                }
+
+                let orig_unusable_binding =
+                    mem::replace(&mut this.unusable_binding, target_bindings[ns].get());
+
+                match this.early_resolve_ident_in_lexical_scope(
+                    target,
+                    ScopeSet::All(ns, false),
+                    &import.parent_scope,
+                    false,
+                    false,
+                    import.span,
+                ) {
+                    Ok(other_binding) => {
+                        is_redundant[ns] = Some(
+                            binding.res() == other_binding.res() && !other_binding.is_ambiguity(),
+                        );
+                        redundant_span[ns] = Some((other_binding.span, other_binding.is_import()));
+                    }
+                    Err(_) => is_redundant[ns] = Some(false),
+                }
+
+                this.unusable_binding = orig_unusable_binding;
+            }
+        });
+
+        if !is_redundant.is_empty() && is_redundant.present_items().all(|is_redundant| is_redundant)
+        {
+            let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
+            redundant_spans.sort();
+            redundant_spans.dedup();
+            self.r.lint_buffer.buffer_lint_with_diagnostic(
+                UNUSED_IMPORTS,
+                import.id,
+                import.span,
+                &format!("the item `{}` is imported redundantly", ident),
+                BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident),
+            );
+        }
+    }
+
+    fn resolve_glob_import(&mut self, import: &'b Import<'b>) {
+        let module = match import.imported_module.get().unwrap() {
+            ModuleOrUniformRoot::Module(module) => module,
+            _ => {
+                self.r.session.span_err(import.span, "cannot glob-import all possible crates");
+                return;
+            }
+        };
+
+        if module.is_trait() {
+            self.r.session.span_err(import.span, "items in traits are not importable.");
+            return;
+        } else if module.def_id() == import.parent_scope.module.def_id() {
+            return;
+        } else if let ImportKind::Glob { is_prelude: true, .. } = import.kind {
+            self.r.prelude = Some(module);
+            return;
+        }
+
+        // Add to module's glob_importers
+        module.glob_importers.borrow_mut().push(import);
+
+        // Ensure that `resolutions` isn't borrowed during `try_define`,
+        // since it might get updated via a glob cycle.
+        let bindings = self
+            .r
+            .resolutions(module)
+            .borrow()
+            .iter()
+            .filter_map(|(key, resolution)| {
+                resolution.borrow().binding().map(|binding| (*key, binding))
+            })
+            .collect::<Vec<_>>();
+        for (mut key, binding) in bindings {
+            let scope = match key.ident.span.reverse_glob_adjust(module.expansion, import.span) {
+                Some(Some(def)) => self.r.macro_def_scope(def),
+                Some(None) => import.parent_scope.module,
+                None => continue,
+            };
+            if self.r.is_accessible_from(binding.pseudo_vis(), scope) {
+                let imported_binding = self.r.import(binding, import);
+                let _ = self.r.try_define(import.parent_scope.module, key, imported_binding);
+            }
+        }
+
+        // Record the destination of this import
+        self.r.record_partial_res(import.id, PartialRes::new(module.res().unwrap()));
+    }
+
+    // Miscellaneous post-processing, including recording re-exports,
+    // reporting conflicts, and reporting unresolved imports.
+    fn finalize_resolutions_in(&mut self, module: Module<'b>) {
+        // Since import resolution is finished, globs will not define any more names.
+        *module.globs.borrow_mut() = Vec::new();
+
+        let mut reexports = Vec::new();
+
+        module.for_each_child(self.r, |this, ident, ns, binding| {
+            // Filter away ambiguous imports and anything that has def-site
+            // hygiene.
+            // FIXME: Implement actual cross-crate hygiene.
+            let is_good_import =
+                binding.is_import() && !binding.is_ambiguity() && !ident.span.from_expansion();
+            if is_good_import || binding.is_macro_def() {
+                let res = binding.res().map_id(|id| this.local_def_id(id));
+                if res != def::Res::Err {
+                    reexports.push(Export { ident, res, span: binding.span, vis: binding.vis });
+                }
+            }
+
+            if let NameBindingKind::Import { binding: orig_binding, import, .. } = binding.kind {
+                if ns == TypeNS
+                    && orig_binding.is_variant()
+                    && !orig_binding.vis.is_at_least(binding.vis, &*this)
+                {
+                    let msg = match import.kind {
+                        ImportKind::Single { .. } => {
+                            format!("variant `{}` is private and cannot be re-exported", ident)
+                        }
+                        ImportKind::Glob { .. } => {
+                            let msg = "enum is private and its variants \
+                                           cannot be re-exported"
+                                .to_owned();
+                            let error_id = (
+                                DiagnosticMessageId::ErrorId(0), // no code?!
+                                Some(binding.span),
+                                msg.clone(),
+                            );
+                            let fresh =
+                                this.session.one_time_diagnostics.borrow_mut().insert(error_id);
+                            if !fresh {
+                                return;
+                            }
+                            msg
+                        }
+                        ref s => bug!("unexpected import kind {:?}", s),
+                    };
+                    let mut err = this.session.struct_span_err(binding.span, &msg);
+
+                    let imported_module = match import.imported_module.get() {
+                        Some(ModuleOrUniformRoot::Module(module)) => module,
+                        _ => bug!("module should exist"),
+                    };
+                    let parent_module = imported_module.parent.expect("parent should exist");
+                    let resolutions = this.resolutions(parent_module).borrow();
+                    let enum_path_segment_index = import.module_path.len() - 1;
+                    let enum_ident = import.module_path[enum_path_segment_index].ident;
+
+                    let key = this.new_key(enum_ident, TypeNS);
+                    let enum_resolution = resolutions.get(&key).expect("resolution should exist");
+                    let enum_span =
+                        enum_resolution.borrow().binding.expect("binding should exist").span;
+                    let enum_def_span = this.session.source_map().guess_head_span(enum_span);
+                    let enum_def_snippet = this
+                        .session
+                        .source_map()
+                        .span_to_snippet(enum_def_span)
+                        .expect("snippet should exist");
+                    // potentially need to strip extant `crate`/`pub(path)` for suggestion
+                    let after_vis_index = enum_def_snippet
+                        .find("enum")
+                        .expect("`enum` keyword should exist in snippet");
+                    let suggestion = format!("pub {}", &enum_def_snippet[after_vis_index..]);
+
+                    this.session.diag_span_suggestion_once(
+                        &mut err,
+                        DiagnosticMessageId::ErrorId(0),
+                        enum_def_span,
+                        "consider making the enum public",
+                        suggestion,
+                    );
+                    err.emit();
+                }
+            }
+        });
+
+        if !reexports.is_empty() {
+            if let Some(def_id) = module.def_id() {
+                // Call to `expect_local` should be fine because current
+                // code is only called for local modules.
+                self.r.export_map.insert(def_id.expect_local(), reexports);
+            }
+        }
+    }
+}
+
+fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
+    let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
+    let global = !names.is_empty() && names[0].name == kw::PathRoot;
+    if let Some(pos) = pos {
+        let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
+        names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>())
+    } else {
+        let names = if global { &names[1..] } else { names };
+        if names.is_empty() {
+            import_kind_to_string(import_kind)
+        } else {
+            format!(
+                "{}::{}",
+                names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>()),
+                import_kind_to_string(import_kind),
+            )
+        }
+    }
+}
+
+fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
+    match import_kind {
+        ImportKind::Single { source, .. } => source.to_string(),
+        ImportKind::Glob { .. } => "*".to_string(),
+        ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
+        ImportKind::MacroUse => "#[macro_use]".to_string(),
+    }
+}
diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs
new file mode 100644
index 0000000..2c01934
--- /dev/null
+++ b/compiler/rustc_resolve/src/late.rs
@@ -0,0 +1,2395 @@
+//! "Late resolution" is the pass that resolves most of names in a crate beside imports and macros.
+//! It runs when the crate is fully expanded and its module structure is fully built.
+//! So it just walks through the crate and resolves all the expressions, types, etc.
+//!
+//! If you wonder why there's no `early.rs`, that's because it's split into three files -
+//! `build_reduced_graph.rs`, `macros.rs` and `imports.rs`.
+
+use RibKind::*;
+
+use crate::{path_names_to_string, BindingError, CrateLint, LexicalScopeBinding};
+use crate::{Module, ModuleOrUniformRoot, ParentScope, PathResult};
+use crate::{ResolutionError, Resolver, Segment, UseError};
+
+use rustc_ast::ptr::P;
+use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
+use rustc_ast::*;
+use rustc_ast::{unwrap_or, walk_list};
+use rustc_ast_lowering::ResolverAstLowering;
+use rustc_data_structures::fx::{FxHashMap, FxHashSet};
+use rustc_errors::DiagnosticId;
+use rustc_hir::def::Namespace::{self, *};
+use rustc_hir::def::{self, CtorKind, DefKind, PartialRes, PerNS};
+use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
+use rustc_hir::TraitCandidate;
+use rustc_middle::{bug, span_bug};
+use rustc_session::lint;
+use rustc_span::symbol::{kw, sym, Ident, Symbol};
+use rustc_span::Span;
+use smallvec::{smallvec, SmallVec};
+
+use rustc_span::source_map::{respan, Spanned};
+use std::collections::BTreeSet;
+use std::mem::{replace, take};
+use tracing::debug;
+
+mod diagnostics;
+crate mod lifetimes;
+
+type Res = def::Res<NodeId>;
+
+type IdentMap<T> = FxHashMap<Ident, T>;
+
+/// Map from the name in a pattern to its binding mode.
+type BindingMap = IdentMap<BindingInfo>;
+
+#[derive(Copy, Clone, Debug)]
+struct BindingInfo {
+    span: Span,
+    binding_mode: BindingMode,
+}
+
+#[derive(Copy, Clone, PartialEq, Eq, Debug)]
+enum PatternSource {
+    Match,
+    Let,
+    For,
+    FnParam,
+}
+
+impl PatternSource {
+    fn descr(self) -> &'static str {
+        match self {
+            PatternSource::Match => "match binding",
+            PatternSource::Let => "let binding",
+            PatternSource::For => "for binding",
+            PatternSource::FnParam => "function parameter",
+        }
+    }
+}
+
+/// Denotes whether the context for the set of already bound bindings is a `Product`
+/// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
+/// See those functions for more information.
+#[derive(PartialEq)]
+enum PatBoundCtx {
+    /// A product pattern context, e.g., `Variant(a, b)`.
+    Product,
+    /// An or-pattern context, e.g., `p_0 | ... | p_n`.
+    Or,
+}
+
+/// Does this the item (from the item rib scope) allow generic parameters?
+#[derive(Copy, Clone, Debug, Eq, PartialEq)]
+crate enum HasGenericParams {
+    Yes,
+    No,
+}
+
+/// The rib kind restricts certain accesses,
+/// e.g. to a `Res::Local` of an outer item.
+#[derive(Copy, Clone, Debug)]
+crate enum RibKind<'a> {
+    /// No restriction needs to be applied.
+    NormalRibKind,
+
+    /// We passed through an impl or trait and are now in one of its
+    /// methods or associated types. Allow references to ty params that impl or trait
+    /// binds. Disallow any other upvars (including other ty params that are
+    /// upvars).
+    AssocItemRibKind,
+
+    /// We passed through a closure. Disallow labels.
+    ClosureOrAsyncRibKind,
+
+    /// We passed through a function definition. Disallow upvars.
+    /// Permit only those const parameters that are specified in the function's generics.
+    FnItemRibKind,
+
+    /// We passed through an item scope. Disallow upvars.
+    ItemRibKind(HasGenericParams),
+
+    /// We're in a constant item. Can't refer to dynamic stuff.
+    ///
+    /// The `bool` indicates if this constant may reference generic parameters
+    /// and is used to only allow generic parameters to be used in trivial constant expressions.
+    ConstantItemRibKind(bool),
+
+    /// We passed through a module.
+    ModuleRibKind(Module<'a>),
+
+    /// We passed through a `macro_rules!` statement
+    MacroDefinition(DefId),
+
+    /// All bindings in this rib are type parameters that can't be used
+    /// from the default of a type parameter because they're not declared
+    /// before said type parameter. Also see the `visit_generics` override.
+    ForwardTyParamBanRibKind,
+
+    /// We are inside of the type of a const parameter. Can't refer to any
+    /// parameters.
+    ConstParamTyRibKind,
+}
+
+impl RibKind<'_> {
+    /// Whether this rib kind contains generic parameters, as opposed to local
+    /// variables.
+    crate fn contains_params(&self) -> bool {
+        match self {
+            NormalRibKind
+            | ClosureOrAsyncRibKind
+            | FnItemRibKind
+            | ConstantItemRibKind(_)
+            | ModuleRibKind(_)
+            | MacroDefinition(_)
+            | ConstParamTyRibKind => false,
+            AssocItemRibKind | ItemRibKind(_) | ForwardTyParamBanRibKind => true,
+        }
+    }
+}
+
+/// A single local scope.
+///
+/// A rib represents a scope names can live in. Note that these appear in many places, not just
+/// around braces. At any place where the list of accessible names (of the given namespace)
+/// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
+/// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
+/// etc.
+///
+/// Different [rib kinds](enum.RibKind) are transparent for different names.
+///
+/// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
+/// resolving, the name is looked up from inside out.
+#[derive(Debug)]
+crate struct Rib<'a, R = Res> {
+    pub bindings: IdentMap<R>,
+    pub kind: RibKind<'a>,
+}
+
+impl<'a, R> Rib<'a, R> {
+    fn new(kind: RibKind<'a>) -> Rib<'a, R> {
+        Rib { bindings: Default::default(), kind }
+    }
+}
+
+#[derive(Copy, Clone, PartialEq, Eq, Debug)]
+crate enum AliasPossibility {
+    No,
+    Maybe,
+}
+
+#[derive(Copy, Clone, Debug)]
+crate enum PathSource<'a> {
+    // Type paths `Path`.
+    Type,
+    // Trait paths in bounds or impls.
+    Trait(AliasPossibility),
+    // Expression paths `path`, with optional parent context.
+    Expr(Option<&'a Expr>),
+    // Paths in path patterns `Path`.
+    Pat,
+    // Paths in struct expressions and patterns `Path { .. }`.
+    Struct,
+    // Paths in tuple struct patterns `Path(..)`.
+    TupleStruct(Span, &'a [Span]),
+    // `m::A::B` in `<T as m::A>::B::C`.
+    TraitItem(Namespace),
+}
+
+impl<'a> PathSource<'a> {
+    fn namespace(self) -> Namespace {
+        match self {
+            PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
+            PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct(..) => ValueNS,
+            PathSource::TraitItem(ns) => ns,
+        }
+    }
+
+    fn defer_to_typeck(self) -> bool {
+        match self {
+            PathSource::Type
+            | PathSource::Expr(..)
+            | PathSource::Pat
+            | PathSource::Struct
+            | PathSource::TupleStruct(..) => true,
+            PathSource::Trait(_) | PathSource::TraitItem(..) => false,
+        }
+    }
+
+    fn descr_expected(self) -> &'static str {
+        match &self {
+            PathSource::Type => "type",
+            PathSource::Trait(_) => "trait",
+            PathSource::Pat => "unit struct, unit variant or constant",
+            PathSource::Struct => "struct, variant or union type",
+            PathSource::TupleStruct(..) => "tuple struct or tuple variant",
+            PathSource::TraitItem(ns) => match ns {
+                TypeNS => "associated type",
+                ValueNS => "method or associated constant",
+                MacroNS => bug!("associated macro"),
+            },
+            PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
+                // "function" here means "anything callable" rather than `DefKind::Fn`,
+                // this is not precise but usually more helpful than just "value".
+                Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
+                    ExprKind::Path(_, path) => {
+                        let mut msg = "function";
+                        if let Some(segment) = path.segments.iter().last() {
+                            if let Some(c) = segment.ident.to_string().chars().next() {
+                                if c.is_uppercase() {
+                                    msg = "function, tuple struct or tuple variant";
+                                }
+                            }
+                        }
+                        msg
+                    }
+                    _ => "function",
+                },
+                _ => "value",
+            },
+        }
+    }
+
+    fn is_call(self) -> bool {
+        match self {
+            PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })) => true,
+            _ => false,
+        }
+    }
+
+    crate fn is_expected(self, res: Res) -> bool {
+        match self {
+            PathSource::Type => match res {
+                Res::Def(
+                    DefKind::Struct
+                    | DefKind::Union
+                    | DefKind::Enum
+                    | DefKind::Trait
+                    | DefKind::TraitAlias
+                    | DefKind::TyAlias
+                    | DefKind::AssocTy
+                    | DefKind::TyParam
+                    | DefKind::OpaqueTy
+                    | DefKind::ForeignTy,
+                    _,
+                )
+                | Res::PrimTy(..)
+                | Res::SelfTy(..) => true,
+                _ => false,
+            },
+            PathSource::Trait(AliasPossibility::No) => match res {
+                Res::Def(DefKind::Trait, _) => true,
+                _ => false,
+            },
+            PathSource::Trait(AliasPossibility::Maybe) => match res {
+                Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => true,
+                _ => false,
+            },
+            PathSource::Expr(..) => match res {
+                Res::Def(
+                    DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
+                    | DefKind::Const
+                    | DefKind::Static
+                    | DefKind::Fn
+                    | DefKind::AssocFn
+                    | DefKind::AssocConst
+                    | DefKind::ConstParam,
+                    _,
+                )
+                | Res::Local(..)
+                | Res::SelfCtor(..) => true,
+                _ => false,
+            },
+            PathSource::Pat => match res {
+                Res::Def(
+                    DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst,
+                    _,
+                )
+                | Res::SelfCtor(..) => true,
+                _ => false,
+            },
+            PathSource::TupleStruct(..) => match res {
+                Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..) => true,
+                _ => false,
+            },
+            PathSource::Struct => match res {
+                Res::Def(
+                    DefKind::Struct
+                    | DefKind::Union
+                    | DefKind::Variant
+                    | DefKind::TyAlias
+                    | DefKind::AssocTy,
+                    _,
+                )
+                | Res::SelfTy(..) => true,
+                _ => false,
+            },
+            PathSource::TraitItem(ns) => match res {
+                Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
+                Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
+                _ => false,
+            },
+        }
+    }
+
+    fn error_code(self, has_unexpected_resolution: bool) -> DiagnosticId {
+        use rustc_errors::error_code;
+        match (self, has_unexpected_resolution) {
+            (PathSource::Trait(_), true) => error_code!(E0404),
+            (PathSource::Trait(_), false) => error_code!(E0405),
+            (PathSource::Type, true) => error_code!(E0573),
+            (PathSource::Type, false) => error_code!(E0412),
+            (PathSource::Struct, true) => error_code!(E0574),
+            (PathSource::Struct, false) => error_code!(E0422),
+            (PathSource::Expr(..), true) => error_code!(E0423),
+            (PathSource::Expr(..), false) => error_code!(E0425),
+            (PathSource::Pat | PathSource::TupleStruct(..), true) => error_code!(E0532),
+            (PathSource::Pat | PathSource::TupleStruct(..), false) => error_code!(E0531),
+            (PathSource::TraitItem(..), true) => error_code!(E0575),
+            (PathSource::TraitItem(..), false) => error_code!(E0576),
+        }
+    }
+}
+
+#[derive(Default)]
+struct DiagnosticMetadata<'ast> {
+    /// The current trait's associated types' ident, used for diagnostic suggestions.
+    current_trait_assoc_types: Vec<Ident>,
+
+    /// The current self type if inside an impl (used for better errors).
+    current_self_type: Option<Ty>,
+
+    /// The current self item if inside an ADT (used for better errors).
+    current_self_item: Option<NodeId>,
+
+    /// The current trait (used to suggest).
+    current_item: Option<&'ast Item>,
+
+    /// When processing generics and encountering a type not found, suggest introducing a type
+    /// param.
+    currently_processing_generics: bool,
+
+    /// The current enclosing function (used for better errors).
+    current_function: Option<(FnKind<'ast>, Span)>,
+
+    /// A list of labels as of yet unused. Labels will be removed from this map when
+    /// they are used (in a `break` or `continue` statement)
+    unused_labels: FxHashMap<NodeId, Span>,
+
+    /// Only used for better errors on `fn(): fn()`.
+    current_type_ascription: Vec<Span>,
+
+    /// Only used for better errors on `let <pat>: <expr, not type>;`.
+    current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
+
+    /// Used to detect possible `if let` written without `let` and to provide structured suggestion.
+    in_if_condition: Option<&'ast Expr>,
+}
+
+struct LateResolutionVisitor<'a, 'b, 'ast> {
+    r: &'b mut Resolver<'a>,
+
+    /// The module that represents the current item scope.
+    parent_scope: ParentScope<'a>,
+
+    /// The current set of local scopes for types and values.
+    /// FIXME #4948: Reuse ribs to avoid allocation.
+    ribs: PerNS<Vec<Rib<'a>>>,
+
+    /// The current set of local scopes, for labels.
+    label_ribs: Vec<Rib<'a, NodeId>>,
+
+    /// The trait that the current context can refer to.
+    current_trait_ref: Option<(Module<'a>, TraitRef)>,
+
+    /// Fields used to add information to diagnostic errors.
+    diagnostic_metadata: DiagnosticMetadata<'ast>,
+
+    /// State used to know whether to ignore resolution errors for function bodies.
+    ///
+    /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items.
+    /// In most cases this will be `None`, in which case errors will always be reported.
+    /// If it is `true`, then it will be updated when entering a nested function or trait body.
+    in_func_body: bool,
+}
+
+/// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
+impl<'a: 'ast, 'ast> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast> {
+    fn visit_item(&mut self, item: &'ast Item) {
+        let prev = replace(&mut self.diagnostic_metadata.current_item, Some(item));
+        // Always report errors in items we just entered.
+        let old_ignore = replace(&mut self.in_func_body, false);
+        self.resolve_item(item);
+        self.in_func_body = old_ignore;
+        self.diagnostic_metadata.current_item = prev;
+    }
+    fn visit_arm(&mut self, arm: &'ast Arm) {
+        self.resolve_arm(arm);
+    }
+    fn visit_block(&mut self, block: &'ast Block) {
+        self.resolve_block(block);
+    }
+    fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
+        debug!("visit_anon_const {:?}", constant);
+        self.with_constant_rib(constant.value.is_potential_trivial_const_param(), |this| {
+            visit::walk_anon_const(this, constant);
+        });
+    }
+    fn visit_expr(&mut self, expr: &'ast Expr) {
+        self.resolve_expr(expr, None);
+    }
+    fn visit_local(&mut self, local: &'ast Local) {
+        let local_spans = match local.pat.kind {
+            // We check for this to avoid tuple struct fields.
+            PatKind::Wild => None,
+            _ => Some((
+                local.pat.span,
+                local.ty.as_ref().map(|ty| ty.span),
+                local.init.as_ref().map(|init| init.span),
+            )),
+        };
+        let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans);
+        self.resolve_local(local);
+        self.diagnostic_metadata.current_let_binding = original;
+    }
+    fn visit_ty(&mut self, ty: &'ast Ty) {
+        match ty.kind {
+            TyKind::Path(ref qself, ref path) => {
+                self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
+            }
+            TyKind::ImplicitSelf => {
+                let self_ty = Ident::with_dummy_span(kw::SelfUpper);
+                let res = self
+                    .resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
+                    .map_or(Res::Err, |d| d.res());
+                self.r.record_partial_res(ty.id, PartialRes::new(res));
+            }
+            _ => (),
+        }
+        visit::walk_ty(self, ty);
+    }
+    fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef, m: &'ast TraitBoundModifier) {
+        self.smart_resolve_path(
+            tref.trait_ref.ref_id,
+            None,
+            &tref.trait_ref.path,
+            PathSource::Trait(AliasPossibility::Maybe),
+        );
+        visit::walk_poly_trait_ref(self, tref, m);
+    }
+    fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
+        match foreign_item.kind {
+            ForeignItemKind::Fn(_, _, ref generics, _)
+            | ForeignItemKind::TyAlias(_, ref generics, ..) => {
+                self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
+                    visit::walk_foreign_item(this, foreign_item);
+                });
+            }
+            ForeignItemKind::Static(..) => {
+                self.with_item_rib(HasGenericParams::No, |this| {
+                    visit::walk_foreign_item(this, foreign_item);
+                });
+            }
+            ForeignItemKind::MacCall(..) => {
+                visit::walk_foreign_item(self, foreign_item);
+            }
+        }
+    }
+    fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, _: NodeId) {
+        let rib_kind = match fn_kind {
+            // Bail if there's no body.
+            FnKind::Fn(.., None) => return visit::walk_fn(self, fn_kind, sp),
+            FnKind::Fn(FnCtxt::Free | FnCtxt::Foreign, ..) => FnItemRibKind,
+            FnKind::Fn(FnCtxt::Assoc(_), ..) => NormalRibKind,
+            FnKind::Closure(..) => ClosureOrAsyncRibKind,
+        };
+        let previous_value =
+            replace(&mut self.diagnostic_metadata.current_function, Some((fn_kind, sp)));
+        debug!("(resolving function) entering function");
+        let declaration = fn_kind.decl();
+
+        // Create a value rib for the function.
+        self.with_rib(ValueNS, rib_kind, |this| {
+            // Create a label rib for the function.
+            this.with_label_rib(rib_kind, |this| {
+                // Add each argument to the rib.
+                this.resolve_params(&declaration.inputs);
+
+                visit::walk_fn_ret_ty(this, &declaration.output);
+
+                // Ignore errors in function bodies if this is rustdoc
+                // Be sure not to set this until the function signature has been resolved.
+                let previous_state = replace(&mut this.in_func_body, true);
+                // Resolve the function body, potentially inside the body of an async closure
+                match fn_kind {
+                    FnKind::Fn(.., body) => walk_list!(this, visit_block, body),
+                    FnKind::Closure(_, body) => this.visit_expr(body),
+                };
+
+                debug!("(resolving function) leaving function");
+                this.in_func_body = previous_state;
+            })
+        });
+        self.diagnostic_metadata.current_function = previous_value;
+    }
+
+    fn visit_generics(&mut self, generics: &'ast Generics) {
+        // For type parameter defaults, we have to ban access
+        // to following type parameters, as the InternalSubsts can only
+        // provide previous type parameters as they're built. We
+        // put all the parameters on the ban list and then remove
+        // them one by one as they are processed and become available.
+        let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
+        let mut found_default = false;
+        default_ban_rib.bindings.extend(generics.params.iter().filter_map(
+            |param| match param.kind {
+                GenericParamKind::Const { .. } | GenericParamKind::Lifetime { .. } => None,
+                GenericParamKind::Type { ref default, .. } => {
+                    found_default |= default.is_some();
+                    found_default.then_some((Ident::with_dummy_span(param.ident.name), Res::Err))
+                }
+            },
+        ));
+
+        // rust-lang/rust#61631: The type `Self` is essentially
+        // another type parameter. For ADTs, we consider it
+        // well-defined only after all of the ADT type parameters have
+        // been provided. Therefore, we do not allow use of `Self`
+        // anywhere in ADT type parameter defaults.
+        //
+        // (We however cannot ban `Self` for defaults on *all* generic
+        // lists; e.g. trait generics can usefully refer to `Self`,
+        // such as in the case of `trait Add<Rhs = Self>`.)
+        if self.diagnostic_metadata.current_self_item.is_some() {
+            // (`Some` if + only if we are in ADT's generics.)
+            default_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
+        }
+
+        for param in &generics.params {
+            match param.kind {
+                GenericParamKind::Lifetime => self.visit_generic_param(param),
+                GenericParamKind::Type { ref default } => {
+                    for bound in &param.bounds {
+                        self.visit_param_bound(bound);
+                    }
+
+                    if let Some(ref ty) = default {
+                        self.ribs[TypeNS].push(default_ban_rib);
+                        self.with_rib(ValueNS, ForwardTyParamBanRibKind, |this| {
+                            // HACK: We use an empty `ForwardTyParamBanRibKind` here which
+                            // is only used to forbid the use of const parameters inside of
+                            // type defaults.
+                            //
+                            // While the rib name doesn't really fit here, it does allow us to use the same
+                            // code for both const and type parameters.
+                            this.visit_ty(ty);
+                        });
+                        default_ban_rib = self.ribs[TypeNS].pop().unwrap();
+                    }
+
+                    // Allow all following defaults to refer to this type parameter.
+                    default_ban_rib.bindings.remove(&Ident::with_dummy_span(param.ident.name));
+                }
+                GenericParamKind::Const { ref ty, kw_span: _ } => {
+                    for bound in &param.bounds {
+                        self.visit_param_bound(bound);
+                    }
+                    self.ribs[TypeNS].push(Rib::new(ConstParamTyRibKind));
+                    self.ribs[ValueNS].push(Rib::new(ConstParamTyRibKind));
+                    self.visit_ty(ty);
+                    self.ribs[TypeNS].pop().unwrap();
+                    self.ribs[ValueNS].pop().unwrap();
+                }
+            }
+        }
+        for p in &generics.where_clause.predicates {
+            self.visit_where_predicate(p);
+        }
+    }
+
+    fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
+        debug!("visit_generic_arg({:?})", arg);
+        let prev = replace(&mut self.diagnostic_metadata.currently_processing_generics, true);
+        match arg {
+            GenericArg::Type(ref ty) => {
+                // We parse const arguments as path types as we cannot distinguish them during
+                // parsing. We try to resolve that ambiguity by attempting resolution the type
+                // namespace first, and if that fails we try again in the value namespace. If
+                // resolution in the value namespace succeeds, we have an generic const argument on
+                // our hands.
+                if let TyKind::Path(ref qself, ref path) = ty.kind {
+                    // We cannot disambiguate multi-segment paths right now as that requires type
+                    // checking.
+                    if path.segments.len() == 1 && path.segments[0].args.is_none() {
+                        let mut check_ns = |ns| {
+                            self.resolve_ident_in_lexical_scope(
+                                path.segments[0].ident,
+                                ns,
+                                None,
+                                path.span,
+                            )
+                            .is_some()
+                        };
+                        if !check_ns(TypeNS) && check_ns(ValueNS) {
+                            // This must be equivalent to `visit_anon_const`, but we cannot call it
+                            // directly due to visitor lifetimes so we have to copy-paste some code.
+                            self.with_constant_rib(true, |this| {
+                                this.smart_resolve_path(
+                                    ty.id,
+                                    qself.as_ref(),
+                                    path,
+                                    PathSource::Expr(None),
+                                );
+
+                                if let Some(ref qself) = *qself {
+                                    this.visit_ty(&qself.ty);
+                                }
+                                this.visit_path(path, ty.id);
+                            });
+
+                            self.diagnostic_metadata.currently_processing_generics = prev;
+                            return;
+                        }
+                    }
+                }
+
+                self.visit_ty(ty);
+            }
+            GenericArg::Lifetime(lt) => self.visit_lifetime(lt),
+            GenericArg::Const(ct) => self.visit_anon_const(ct),
+        }
+        self.diagnostic_metadata.currently_processing_generics = prev;
+    }
+}
+
+impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
+    fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b, 'ast> {
+        // During late resolution we only track the module component of the parent scope,
+        // although it may be useful to track other components as well for diagnostics.
+        let graph_root = resolver.graph_root;
+        let parent_scope = ParentScope::module(graph_root);
+        let start_rib_kind = ModuleRibKind(graph_root);
+        LateResolutionVisitor {
+            r: resolver,
+            parent_scope,
+            ribs: PerNS {
+                value_ns: vec![Rib::new(start_rib_kind)],
+                type_ns: vec![Rib::new(start_rib_kind)],
+                macro_ns: vec![Rib::new(start_rib_kind)],
+            },
+            label_ribs: Vec::new(),
+            current_trait_ref: None,
+            diagnostic_metadata: DiagnosticMetadata::default(),
+            // errors at module scope should always be reported
+            in_func_body: false,
+        }
+    }
+
+    fn resolve_ident_in_lexical_scope(
+        &mut self,
+        ident: Ident,
+        ns: Namespace,
+        record_used_id: Option<NodeId>,
+        path_span: Span,
+    ) -> Option<LexicalScopeBinding<'a>> {
+        self.r.resolve_ident_in_lexical_scope(
+            ident,
+            ns,
+            &self.parent_scope,
+            record_used_id,
+            path_span,
+            &self.ribs[ns],
+        )
+    }
+
+    fn resolve_path(
+        &mut self,
+        path: &[Segment],
+        opt_ns: Option<Namespace>, // `None` indicates a module path in import
+        record_used: bool,
+        path_span: Span,
+        crate_lint: CrateLint,
+    ) -> PathResult<'a> {
+        self.r.resolve_path_with_ribs(
+            path,
+            opt_ns,
+            &self.parent_scope,
+            record_used,
+            path_span,
+            crate_lint,
+            Some(&self.ribs),
+        )
+    }
+
+    // AST resolution
+    //
+    // We maintain a list of value ribs and type ribs.
+    //
+    // Simultaneously, we keep track of the current position in the module
+    // graph in the `parent_scope.module` pointer. When we go to resolve a name in
+    // the value or type namespaces, we first look through all the ribs and
+    // then query the module graph. When we resolve a name in the module
+    // namespace, we can skip all the ribs (since nested modules are not
+    // allowed within blocks in Rust) and jump straight to the current module
+    // graph node.
+    //
+    // Named implementations are handled separately. When we find a method
+    // call, we consult the module node to find all of the implementations in
+    // scope. This information is lazily cached in the module node. We then
+    // generate a fake "implementation scope" containing all the
+    // implementations thus found, for compatibility with old resolve pass.
+
+    /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
+    fn with_rib<T>(
+        &mut self,
+        ns: Namespace,
+        kind: RibKind<'a>,
+        work: impl FnOnce(&mut Self) -> T,
+    ) -> T {
+        self.ribs[ns].push(Rib::new(kind));
+        let ret = work(self);
+        self.ribs[ns].pop();
+        ret
+    }
+
+    fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
+        let id = self.r.local_def_id(id);
+        let module = self.r.module_map.get(&id).cloned(); // clones a reference
+        if let Some(module) = module {
+            // Move down in the graph.
+            let orig_module = replace(&mut self.parent_scope.module, module);
+            self.with_rib(ValueNS, ModuleRibKind(module), |this| {
+                this.with_rib(TypeNS, ModuleRibKind(module), |this| {
+                    let ret = f(this);
+                    this.parent_scope.module = orig_module;
+                    ret
+                })
+            })
+        } else {
+            f(self)
+        }
+    }
+
+    /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
+    /// label and reports an error if the label is not found or is unreachable.
+    fn resolve_label(&self, mut label: Ident) -> Option<NodeId> {
+        let mut suggestion = None;
+
+        // Preserve the original span so that errors contain "in this macro invocation"
+        // information.
+        let original_span = label.span;
+
+        for i in (0..self.label_ribs.len()).rev() {
+            let rib = &self.label_ribs[i];
+
+            if let MacroDefinition(def) = rib.kind {
+                // If an invocation of this macro created `ident`, give up on `ident`
+                // and switch to `ident`'s source from the macro definition.
+                if def == self.r.macro_def(label.span.ctxt()) {
+                    label.span.remove_mark();
+                }
+            }
+
+            let ident = label.normalize_to_macro_rules();
+            if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
+                return if self.is_label_valid_from_rib(i) {
+                    Some(*id)
+                } else {
+                    self.report_error(
+                        original_span,
+                        ResolutionError::UnreachableLabel {
+                            name: label.name,
+                            definition_span: ident.span,
+                            suggestion,
+                        },
+                    );
+
+                    None
+                };
+            }
+
+            // Diagnostics: Check if this rib contains a label with a similar name, keep track of
+            // the first such label that is encountered.
+            suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
+        }
+
+        self.report_error(
+            original_span,
+            ResolutionError::UndeclaredLabel { name: label.name, suggestion },
+        );
+        None
+    }
+
+    /// Determine whether or not a label from the `rib_index`th label rib is reachable.
+    fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
+        let ribs = &self.label_ribs[rib_index + 1..];
+
+        for rib in ribs {
+            match rib.kind {
+                NormalRibKind | MacroDefinition(..) => {
+                    // Nothing to do. Continue.
+                }
+
+                AssocItemRibKind
+                | ClosureOrAsyncRibKind
+                | FnItemRibKind
+                | ItemRibKind(..)
+                | ConstantItemRibKind(_)
+                | ModuleRibKind(..)
+                | ForwardTyParamBanRibKind
+                | ConstParamTyRibKind => {
+                    return false;
+                }
+            }
+        }
+
+        true
+    }
+
+    fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
+        debug!("resolve_adt");
+        self.with_current_self_item(item, |this| {
+            this.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
+                let item_def_id = this.r.local_def_id(item.id).to_def_id();
+                this.with_self_rib(Res::SelfTy(None, Some((item_def_id, false))), |this| {
+                    visit::walk_item(this, item);
+                });
+            });
+        });
+    }
+
+    fn future_proof_import(&mut self, use_tree: &UseTree) {
+        let segments = &use_tree.prefix.segments;
+        if !segments.is_empty() {
+            let ident = segments[0].ident;
+            if ident.is_path_segment_keyword() || ident.span.rust_2015() {
+                return;
+            }
+
+            let nss = match use_tree.kind {
+                UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
+                _ => &[TypeNS],
+            };
+            let report_error = |this: &Self, ns| {
+                let what = if ns == TypeNS { "type parameters" } else { "local variables" };
+                if this.should_report_errs() {
+                    this.r
+                        .session
+                        .span_err(ident.span, &format!("imports cannot refer to {}", what));
+                }
+            };
+
+            for &ns in nss {
+                match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
+                    Some(LexicalScopeBinding::Res(..)) => {
+                        report_error(self, ns);
+                    }
+                    Some(LexicalScopeBinding::Item(binding)) => {
+                        let orig_unusable_binding =
+                            replace(&mut self.r.unusable_binding, Some(binding));
+                        if let Some(LexicalScopeBinding::Res(..)) = self
+                            .resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span)
+                        {
+                            report_error(self, ns);
+                        }
+                        self.r.unusable_binding = orig_unusable_binding;
+                    }
+                    None => {}
+                }
+            }
+        } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
+            for (use_tree, _) in use_trees {
+                self.future_proof_import(use_tree);
+            }
+        }
+    }
+
+    fn resolve_item(&mut self, item: &'ast Item) {
+        let name = item.ident.name;
+        debug!("(resolving item) resolving {} ({:?})", name, item.kind);
+
+        match item.kind {
+            ItemKind::TyAlias(_, ref generics, _, _) | ItemKind::Fn(_, _, ref generics, _) => {
+                self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
+                    visit::walk_item(this, item)
+                });
+            }
+
+            ItemKind::Enum(_, ref generics)
+            | ItemKind::Struct(_, ref generics)
+            | ItemKind::Union(_, ref generics) => {
+                self.resolve_adt(item, generics);
+            }
+
+            ItemKind::Impl {
+                ref generics,
+                ref of_trait,
+                ref self_ty,
+                items: ref impl_items,
+                ..
+            } => {
+                self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items);
+            }
+
+            ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
+                // Create a new rib for the trait-wide type parameters.
+                self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
+                    let local_def_id = this.r.local_def_id(item.id).to_def_id();
+                    this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
+                        this.visit_generics(generics);
+                        walk_list!(this, visit_param_bound, bounds);
+
+                        let walk_assoc_item = |this: &mut Self, generics, item| {
+                            this.with_generic_param_rib(generics, AssocItemRibKind, |this| {
+                                visit::walk_assoc_item(this, item, AssocCtxt::Trait)
+                            });
+                        };
+
+                        for item in trait_items {
+                            this.with_trait_items(trait_items, |this| {
+                                match &item.kind {
+                                    AssocItemKind::Const(_, ty, default) => {
+                                        this.visit_ty(ty);
+                                        // Only impose the restrictions of `ConstRibKind` for an
+                                        // actual constant expression in a provided default.
+                                        if let Some(expr) = default {
+                                            // We allow arbitrary const expressions inside of associated consts,
+                                            // even if they are potentially not const evaluatable.
+                                            //
+                                            // Type parameters can already be used and as associated consts are
+                                            // not used as part of the type system, this is far less surprising.
+                                            this.with_constant_rib(true, |this| {
+                                                this.visit_expr(expr)
+                                            });
+                                        }
+                                    }
+                                    AssocItemKind::Fn(_, _, generics, _) => {
+                                        walk_assoc_item(this, generics, item);
+                                    }
+                                    AssocItemKind::TyAlias(_, generics, _, _) => {
+                                        walk_assoc_item(this, generics, item);
+                                    }
+                                    AssocItemKind::MacCall(_) => {
+                                        panic!("unexpanded macro in resolve!")
+                                    }
+                                };
+                            });
+                        }
+                    });
+                });
+            }
+
+            ItemKind::TraitAlias(ref generics, ref bounds) => {
+                // Create a new rib for the trait-wide type parameters.
+                self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
+                    let local_def_id = this.r.local_def_id(item.id).to_def_id();
+                    this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
+                        this.visit_generics(generics);
+                        walk_list!(this, visit_param_bound, bounds);
+                    });
+                });
+            }
+
+            ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
+                self.with_scope(item.id, |this| {
+                    visit::walk_item(this, item);
+                });
+            }
+
+            ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(_, ref ty, ref expr) => {
+                debug!("resolve_item ItemKind::Const");
+                self.with_item_rib(HasGenericParams::No, |this| {
+                    this.visit_ty(ty);
+                    if let Some(expr) = expr {
+                        this.with_constant_rib(expr.is_potential_trivial_const_param(), |this| {
+                            this.visit_expr(expr)
+                        });
+                    }
+                });
+            }
+
+            ItemKind::Use(ref use_tree) => {
+                self.future_proof_import(use_tree);
+            }
+
+            ItemKind::ExternCrate(..) | ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
+                // do nothing, these are just around to be encoded
+            }
+
+            ItemKind::MacCall(_) => panic!("unexpanded macro in resolve!"),
+        }
+    }
+
+    fn with_generic_param_rib<'c, F>(&'c mut self, generics: &'c Generics, kind: RibKind<'a>, f: F)
+    where
+        F: FnOnce(&mut Self),
+    {
+        debug!("with_generic_param_rib");
+        let mut function_type_rib = Rib::new(kind);
+        let mut function_value_rib = Rib::new(kind);
+        let mut seen_bindings = FxHashMap::default();
+
+        // We also can't shadow bindings from the parent item
+        if let AssocItemRibKind = kind {
+            let mut add_bindings_for_ns = |ns| {
+                let parent_rib = self.ribs[ns]
+                    .iter()
+                    .rfind(|r| matches!(r.kind, ItemRibKind(_)))
+                    .expect("associated item outside of an item");
+                seen_bindings
+                    .extend(parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)));
+            };
+            add_bindings_for_ns(ValueNS);
+            add_bindings_for_ns(TypeNS);
+        }
+
+        for param in &generics.params {
+            if let GenericParamKind::Lifetime { .. } = param.kind {
+                continue;
+            }
+
+            let def_kind = match param.kind {
+                GenericParamKind::Type { .. } => DefKind::TyParam,
+                GenericParamKind::Const { .. } => DefKind::ConstParam,
+                _ => unreachable!(),
+            };
+
+            let ident = param.ident.normalize_to_macros_2_0();
+            debug!("with_generic_param_rib: {}", param.id);
+
+            if seen_bindings.contains_key(&ident) {
+                let span = seen_bindings.get(&ident).unwrap();
+                let err = ResolutionError::NameAlreadyUsedInParameterList(ident.name, *span);
+                self.report_error(param.ident.span, err);
+            }
+            seen_bindings.entry(ident).or_insert(param.ident.span);
+
+            // Plain insert (no renaming).
+            let res = Res::Def(def_kind, self.r.local_def_id(param.id).to_def_id());
+
+            match param.kind {
+                GenericParamKind::Type { .. } => {
+                    function_type_rib.bindings.insert(ident, res);
+                    self.r.record_partial_res(param.id, PartialRes::new(res));
+                }
+                GenericParamKind::Const { .. } => {
+                    function_value_rib.bindings.insert(ident, res);
+                    self.r.record_partial_res(param.id, PartialRes::new(res));
+                }
+                _ => unreachable!(),
+            }
+        }
+
+        self.ribs[ValueNS].push(function_value_rib);
+        self.ribs[TypeNS].push(function_type_rib);
+
+        f(self);
+
+        self.ribs[TypeNS].pop();
+        self.ribs[ValueNS].pop();
+    }
+
+    fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) {
+        self.label_ribs.push(Rib::new(kind));
+        f(self);
+        self.label_ribs.pop();
+    }
+
+    fn with_item_rib(&mut self, has_generic_params: HasGenericParams, f: impl FnOnce(&mut Self)) {
+        let kind = ItemRibKind(has_generic_params);
+        self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
+    }
+
+    fn with_constant_rib(&mut self, trivial: bool, f: impl FnOnce(&mut Self)) {
+        debug!("with_constant_rib");
+        self.with_rib(ValueNS, ConstantItemRibKind(trivial), |this| {
+            this.with_rib(TypeNS, ConstantItemRibKind(trivial), |this| {
+                this.with_label_rib(ConstantItemRibKind(trivial), f);
+            })
+        });
+    }
+
+    fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
+        // Handle nested impls (inside fn bodies)
+        let previous_value =
+            replace(&mut self.diagnostic_metadata.current_self_type, Some(self_type.clone()));
+        let result = f(self);
+        self.diagnostic_metadata.current_self_type = previous_value;
+        result
+    }
+
+    fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
+        let previous_value =
+            replace(&mut self.diagnostic_metadata.current_self_item, Some(self_item.id));
+        let result = f(self);
+        self.diagnostic_metadata.current_self_item = previous_value;
+        result
+    }
+
+    /// When evaluating a `trait` use its associated types' idents for suggestionsa in E0412.
+    fn with_trait_items<T>(
+        &mut self,
+        trait_items: &Vec<P<AssocItem>>,
+        f: impl FnOnce(&mut Self) -> T,
+    ) -> T {
+        let trait_assoc_types = replace(
+            &mut self.diagnostic_metadata.current_trait_assoc_types,
+            trait_items
+                .iter()
+                .filter_map(|item| match &item.kind {
+                    AssocItemKind::TyAlias(_, _, bounds, _) if bounds.is_empty() => {
+                        Some(item.ident)
+                    }
+                    _ => None,
+                })
+                .collect(),
+        );
+        let result = f(self);
+        self.diagnostic_metadata.current_trait_assoc_types = trait_assoc_types;
+        result
+    }
+
+    /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
+    fn with_optional_trait_ref<T>(
+        &mut self,
+        opt_trait_ref: Option<&TraitRef>,
+        f: impl FnOnce(&mut Self, Option<DefId>) -> T,
+    ) -> T {
+        let mut new_val = None;
+        let mut new_id = None;
+        if let Some(trait_ref) = opt_trait_ref {
+            let path: Vec<_> = Segment::from_path(&trait_ref.path);
+            let res = self.smart_resolve_path_fragment(
+                trait_ref.ref_id,
+                None,
+                &path,
+                trait_ref.path.span,
+                PathSource::Trait(AliasPossibility::No),
+                CrateLint::SimplePath(trait_ref.ref_id),
+            );
+            let res = res.base_res();
+            if res != Res::Err {
+                new_id = Some(res.def_id());
+                let span = trait_ref.path.span;
+                if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.resolve_path(
+                    &path,
+                    Some(TypeNS),
+                    false,
+                    span,
+                    CrateLint::SimplePath(trait_ref.ref_id),
+                ) {
+                    new_val = Some((module, trait_ref.clone()));
+                }
+            }
+        }
+        let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
+        let result = f(self, new_id);
+        self.current_trait_ref = original_trait_ref;
+        result
+    }
+
+    fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
+        let mut self_type_rib = Rib::new(NormalRibKind);
+
+        // Plain insert (no renaming, since types are not currently hygienic)
+        self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
+        self.ribs[ns].push(self_type_rib);
+        f(self);
+        self.ribs[ns].pop();
+    }
+
+    fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
+        self.with_self_rib_ns(TypeNS, self_res, f)
+    }
+
+    fn resolve_implementation(
+        &mut self,
+        generics: &'ast Generics,
+        opt_trait_reference: &'ast Option<TraitRef>,
+        self_type: &'ast Ty,
+        item_id: NodeId,
+        impl_items: &'ast [P<AssocItem>],
+    ) {
+        debug!("resolve_implementation");
+        // If applicable, create a rib for the type parameters.
+        self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
+            // Dummy self type for better errors if `Self` is used in the trait path.
+            this.with_self_rib(Res::SelfTy(None, None), |this| {
+                // Resolve the trait reference, if necessary.
+                this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
+                    let item_def_id = this.r.local_def_id(item_id).to_def_id();
+                    this.with_self_rib(Res::SelfTy(trait_id, Some((item_def_id, false))), |this| {
+                        if let Some(trait_ref) = opt_trait_reference.as_ref() {
+                            // Resolve type arguments in the trait path.
+                            visit::walk_trait_ref(this, trait_ref);
+                        }
+                        // Resolve the self type.
+                        this.visit_ty(self_type);
+                        // Resolve the generic parameters.
+                        this.visit_generics(generics);
+                        // Resolve the items within the impl.
+                        this.with_current_self_type(self_type, |this| {
+                            this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
+                                debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
+                                for item in impl_items {
+                                    use crate::ResolutionError::*;
+                                    match &item.kind {
+                                        AssocItemKind::Const(_default, _ty, _expr) => {
+                                            debug!("resolve_implementation AssocItemKind::Const",);
+                                            // If this is a trait impl, ensure the const
+                                            // exists in trait
+                                            this.check_trait_item(
+                                                item.ident,
+                                                ValueNS,
+                                                item.span,
+                                                |n, s| ConstNotMemberOfTrait(n, s),
+                                            );
+
+                                            // We allow arbitrary const expressions inside of associated consts,
+                                            // even if they are potentially not const evaluatable.
+                                            //
+                                            // Type parameters can already be used and as associated consts are
+                                            // not used as part of the type system, this is far less surprising.
+                                            this.with_constant_rib(true, |this| {
+                                                visit::walk_assoc_item(this, item, AssocCtxt::Impl)
+                                            });
+                                        }
+                                        AssocItemKind::Fn(_, _, generics, _) => {
+                                            // We also need a new scope for the impl item type parameters.
+                                            this.with_generic_param_rib(
+                                                generics,
+                                                AssocItemRibKind,
+                                                |this| {
+                                                    // If this is a trait impl, ensure the method
+                                                    // exists in trait
+                                                    this.check_trait_item(
+                                                        item.ident,
+                                                        ValueNS,
+                                                        item.span,
+                                                        |n, s| MethodNotMemberOfTrait(n, s),
+                                                    );
+
+                                                    visit::walk_assoc_item(
+                                                        this,
+                                                        item,
+                                                        AssocCtxt::Impl,
+                                                    )
+                                                },
+                                            );
+                                        }
+                                        AssocItemKind::TyAlias(_, generics, _, _) => {
+                                            // We also need a new scope for the impl item type parameters.
+                                            this.with_generic_param_rib(
+                                                generics,
+                                                AssocItemRibKind,
+                                                |this| {
+                                                    // If this is a trait impl, ensure the type
+                                                    // exists in trait
+                                                    this.check_trait_item(
+                                                        item.ident,
+                                                        TypeNS,
+                                                        item.span,
+                                                        |n, s| TypeNotMemberOfTrait(n, s),
+                                                    );
+
+                                                    visit::walk_assoc_item(
+                                                        this,
+                                                        item,
+                                                        AssocCtxt::Impl,
+                                                    )
+                                                },
+                                            );
+                                        }
+                                        AssocItemKind::MacCall(_) => {
+                                            panic!("unexpanded macro in resolve!")
+                                        }
+                                    }
+                                }
+                            });
+                        });
+                    });
+                });
+            });
+        });
+    }
+
+    fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
+    where
+        F: FnOnce(Symbol, &str) -> ResolutionError<'_>,
+    {
+        // If there is a TraitRef in scope for an impl, then the method must be in the
+        // trait.
+        if let Some((module, _)) = self.current_trait_ref {
+            if self
+                .r
+                .resolve_ident_in_module(
+                    ModuleOrUniformRoot::Module(module),
+                    ident,
+                    ns,
+                    &self.parent_scope,
+                    false,
+                    span,
+                )
+                .is_err()
+            {
+                let path = &self.current_trait_ref.as_ref().unwrap().1.path;
+                self.report_error(span, err(ident.name, &path_names_to_string(path)));
+            }
+        }
+    }
+
+    fn resolve_params(&mut self, params: &'ast [Param]) {
+        let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
+        for Param { pat, ty, .. } in params {
+            self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
+            self.visit_ty(ty);
+            debug!("(resolving function / closure) recorded parameter");
+        }
+    }
+
+    fn resolve_local(&mut self, local: &'ast Local) {
+        debug!("resolving local ({:?})", local);
+        // Resolve the type.
+        walk_list!(self, visit_ty, &local.ty);
+
+        // Resolve the initializer.
+        walk_list!(self, visit_expr, &local.init);
+
+        // Resolve the pattern.
+        self.resolve_pattern_top(&local.pat, PatternSource::Let);
+    }
+
+    /// build a map from pattern identifiers to binding-info's.
+    /// this is done hygienically. This could arise for a macro
+    /// that expands into an or-pattern where one 'x' was from the
+    /// user and one 'x' came from the macro.
+    fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
+        let mut binding_map = FxHashMap::default();
+
+        pat.walk(&mut |pat| {
+            match pat.kind {
+                PatKind::Ident(binding_mode, ident, ref sub_pat)
+                    if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
+                {
+                    binding_map.insert(ident, BindingInfo { span: ident.span, binding_mode });
+                }
+                PatKind::Or(ref ps) => {
+                    // Check the consistency of this or-pattern and
+                    // then add all bindings to the larger map.
+                    for bm in self.check_consistent_bindings(ps) {
+                        binding_map.extend(bm);
+                    }
+                    return false;
+                }
+                _ => {}
+            }
+
+            true
+        });
+
+        binding_map
+    }
+
+    fn is_base_res_local(&self, nid: NodeId) -> bool {
+        match self.r.partial_res_map.get(&nid).map(|res| res.base_res()) {
+            Some(Res::Local(..)) => true,
+            _ => false,
+        }
+    }
+
+    /// Checks that all of the arms in an or-pattern have exactly the
+    /// same set of bindings, with the same binding modes for each.
+    fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) -> Vec<BindingMap> {
+        let mut missing_vars = FxHashMap::default();
+        let mut inconsistent_vars = FxHashMap::default();
+
+        // 1) Compute the binding maps of all arms.
+        let maps = pats.iter().map(|pat| self.binding_mode_map(pat)).collect::<Vec<_>>();
+
+        // 2) Record any missing bindings or binding mode inconsistencies.
+        for (map_outer, pat_outer) in pats.iter().enumerate().map(|(idx, pat)| (&maps[idx], pat)) {
+            // Check against all arms except for the same pattern which is always self-consistent.
+            let inners = pats
+                .iter()
+                .enumerate()
+                .filter(|(_, pat)| pat.id != pat_outer.id)
+                .flat_map(|(idx, _)| maps[idx].iter())
+                .map(|(key, binding)| (key.name, map_outer.get(&key), binding));
+
+            for (name, info, &binding_inner) in inners {
+                match info {
+                    None => {
+                        // The inner binding is missing in the outer.
+                        let binding_error =
+                            missing_vars.entry(name).or_insert_with(|| BindingError {
+                                name,
+                                origin: BTreeSet::new(),
+                                target: BTreeSet::new(),
+                                could_be_path: name.as_str().starts_with(char::is_uppercase),
+                            });
+                        binding_error.origin.insert(binding_inner.span);
+                        binding_error.target.insert(pat_outer.span);
+                    }
+                    Some(binding_outer) => {
+                        if binding_outer.binding_mode != binding_inner.binding_mode {
+                            // The binding modes in the outer and inner bindings differ.
+                            inconsistent_vars
+                                .entry(name)
+                                .or_insert((binding_inner.span, binding_outer.span));
+                        }
+                    }
+                }
+            }
+        }
+
+        // 3) Report all missing variables we found.
+        let mut missing_vars = missing_vars.iter_mut().collect::<Vec<_>>();
+        missing_vars.sort_by_key(|(sym, _err)| sym.as_str());
+
+        for (name, mut v) in missing_vars {
+            if inconsistent_vars.contains_key(name) {
+                v.could_be_path = false;
+            }
+            self.report_error(
+                *v.origin.iter().next().unwrap(),
+                ResolutionError::VariableNotBoundInPattern(v),
+            );
+        }
+
+        // 4) Report all inconsistencies in binding modes we found.
+        let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
+        inconsistent_vars.sort();
+        for (name, v) in inconsistent_vars {
+            self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
+        }
+
+        // 5) Finally bubble up all the binding maps.
+        maps
+    }
+
+    /// Check the consistency of the outermost or-patterns.
+    fn check_consistent_bindings_top(&mut self, pat: &'ast Pat) {
+        pat.walk(&mut |pat| match pat.kind {
+            PatKind::Or(ref ps) => {
+                self.check_consistent_bindings(ps);
+                false
+            }
+            _ => true,
+        })
+    }
+
+    fn resolve_arm(&mut self, arm: &'ast Arm) {
+        self.with_rib(ValueNS, NormalRibKind, |this| {
+            this.resolve_pattern_top(&arm.pat, PatternSource::Match);
+            walk_list!(this, visit_expr, &arm.guard);
+            this.visit_expr(&arm.body);
+        });
+    }
+
+    /// Arising from `source`, resolve a top level pattern.
+    fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
+        let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
+        self.resolve_pattern(pat, pat_src, &mut bindings);
+    }
+
+    fn resolve_pattern(
+        &mut self,
+        pat: &'ast Pat,
+        pat_src: PatternSource,
+        bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
+    ) {
+        self.resolve_pattern_inner(pat, pat_src, bindings);
+        // This has to happen *after* we determine which pat_idents are variants:
+        self.check_consistent_bindings_top(pat);
+        visit::walk_pat(self, pat);
+    }
+
+    /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
+    ///
+    /// ### `bindings`
+    ///
+    /// A stack of sets of bindings accumulated.
+    ///
+    /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
+    /// be interpreted as re-binding an already bound binding. This results in an error.
+    /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
+    /// in reusing this binding rather than creating a fresh one.
+    ///
+    /// When called at the top level, the stack must have a single element
+    /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
+    /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
+    /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
+    /// When each `p_i` has been dealt with, the top set is merged with its parent.
+    /// When a whole or-pattern has been dealt with, the thing happens.
+    ///
+    /// See the implementation and `fresh_binding` for more details.
+    fn resolve_pattern_inner(
+        &mut self,
+        pat: &Pat,
+        pat_src: PatternSource,
+        bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
+    ) {
+        // Visit all direct subpatterns of this pattern.
+        pat.walk(&mut |pat| {
+            debug!("resolve_pattern pat={:?} node={:?}", pat, pat.kind);
+            match pat.kind {
+                PatKind::Ident(bmode, ident, ref sub) => {
+                    // First try to resolve the identifier as some existing entity,
+                    // then fall back to a fresh binding.
+                    let has_sub = sub.is_some();
+                    let res = self
+                        .try_resolve_as_non_binding(pat_src, pat, bmode, ident, has_sub)
+                        .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
+                    self.r.record_partial_res(pat.id, PartialRes::new(res));
+                }
+                PatKind::TupleStruct(ref path, ref sub_patterns) => {
+                    self.smart_resolve_path(
+                        pat.id,
+                        None,
+                        path,
+                        PathSource::TupleStruct(
+                            pat.span,
+                            self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
+                        ),
+                    );
+                }
+                PatKind::Path(ref qself, ref path) => {
+                    self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
+                }
+                PatKind::Struct(ref path, ..) => {
+                    self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
+                }
+                PatKind::Or(ref ps) => {
+                    // Add a new set of bindings to the stack. `Or` here records that when a
+                    // binding already exists in this set, it should not result in an error because
+                    // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
+                    bindings.push((PatBoundCtx::Or, Default::default()));
+                    for p in ps {
+                        // Now we need to switch back to a product context so that each
+                        // part of the or-pattern internally rejects already bound names.
+                        // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
+                        bindings.push((PatBoundCtx::Product, Default::default()));
+                        self.resolve_pattern_inner(p, pat_src, bindings);
+                        // Move up the non-overlapping bindings to the or-pattern.
+                        // Existing bindings just get "merged".
+                        let collected = bindings.pop().unwrap().1;
+                        bindings.last_mut().unwrap().1.extend(collected);
+                    }
+                    // This or-pattern itself can itself be part of a product,
+                    // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
+                    // Both cases bind `a` again in a product pattern and must be rejected.
+                    let collected = bindings.pop().unwrap().1;
+                    bindings.last_mut().unwrap().1.extend(collected);
+
+                    // Prevent visiting `ps` as we've already done so above.
+                    return false;
+                }
+                _ => {}
+            }
+            true
+        });
+    }
+
+    fn fresh_binding(
+        &mut self,
+        ident: Ident,
+        pat_id: NodeId,
+        pat_src: PatternSource,
+        bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
+    ) -> Res {
+        // Add the binding to the local ribs, if it doesn't already exist in the bindings map.
+        // (We must not add it if it's in the bindings map because that breaks the assumptions
+        // later passes make about or-patterns.)
+        let ident = ident.normalize_to_macro_rules();
+
+        let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident));
+        // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
+        let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product);
+        // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
+        // This is *required* for consistency which is checked later.
+        let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or);
+
+        if already_bound_and {
+            // Overlap in a product pattern somewhere; report an error.
+            use ResolutionError::*;
+            let error = match pat_src {
+                // `fn f(a: u8, a: u8)`:
+                PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
+                // `Variant(a, a)`:
+                _ => IdentifierBoundMoreThanOnceInSamePattern,
+            };
+            self.report_error(ident.span, error(ident.name));
+        }
+
+        // Record as bound if it's valid:
+        let ident_valid = ident.name != kw::Invalid;
+        if ident_valid {
+            bindings.last_mut().unwrap().1.insert(ident);
+        }
+
+        if already_bound_or {
+            // `Variant1(a) | Variant2(a)`, ok
+            // Reuse definition from the first `a`.
+            self.innermost_rib_bindings(ValueNS)[&ident]
+        } else {
+            let res = Res::Local(pat_id);
+            if ident_valid {
+                // A completely fresh binding add to the set if it's valid.
+                self.innermost_rib_bindings(ValueNS).insert(ident, res);
+            }
+            res
+        }
+    }
+
+    fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap<Res> {
+        &mut self.ribs[ns].last_mut().unwrap().bindings
+    }
+
+    fn try_resolve_as_non_binding(
+        &mut self,
+        pat_src: PatternSource,
+        pat: &Pat,
+        bm: BindingMode,
+        ident: Ident,
+        has_sub: bool,
+    ) -> Option<Res> {
+        // An immutable (no `mut`) by-value (no `ref`) binding pattern without
+        // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
+        // also be interpreted as a path to e.g. a constant, variant, etc.
+        let is_syntactic_ambiguity = !has_sub && bm == BindingMode::ByValue(Mutability::Not);
+
+        let ls_binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, pat.span)?;
+        let (res, binding) = match ls_binding {
+            LexicalScopeBinding::Item(binding)
+                if is_syntactic_ambiguity && binding.is_ambiguity() =>
+            {
+                // For ambiguous bindings we don't know all their definitions and cannot check
+                // whether they can be shadowed by fresh bindings or not, so force an error.
+                // issues/33118#issuecomment-233962221 (see below) still applies here,
+                // but we have to ignore it for backward compatibility.
+                self.r.record_use(ident, ValueNS, binding, false);
+                return None;
+            }
+            LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
+            LexicalScopeBinding::Res(res) => (res, None),
+        };
+
+        match res {
+            Res::SelfCtor(_) // See #70549.
+            | Res::Def(
+                DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::ConstParam,
+                _,
+            ) if is_syntactic_ambiguity => {
+                // Disambiguate in favor of a unit struct/variant or constant pattern.
+                if let Some(binding) = binding {
+                    self.r.record_use(ident, ValueNS, binding, false);
+                }
+                Some(res)
+            }
+            Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::Static, _) => {
+                // This is unambiguously a fresh binding, either syntactically
+                // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
+                // to something unusable as a pattern (e.g., constructor function),
+                // but we still conservatively report an error, see
+                // issues/33118#issuecomment-233962221 for one reason why.
+                self.report_error(
+                    ident.span,
+                    ResolutionError::BindingShadowsSomethingUnacceptable(
+                        pat_src.descr(),
+                        ident.name,
+                        binding.expect("no binding for a ctor or static"),
+                    ),
+                );
+                None
+            }
+            Res::Def(DefKind::Fn, _) | Res::Local(..) | Res::Err => {
+                // These entities are explicitly allowed to be shadowed by fresh bindings.
+                None
+            }
+            _ => span_bug!(
+                ident.span,
+                "unexpected resolution for an identifier in pattern: {:?}",
+                res,
+            ),
+        }
+    }
+
+    // High-level and context dependent path resolution routine.
+    // Resolves the path and records the resolution into definition map.
+    // If resolution fails tries several techniques to find likely
+    // resolution candidates, suggest imports or other help, and report
+    // errors in user friendly way.
+    fn smart_resolve_path(
+        &mut self,
+        id: NodeId,
+        qself: Option<&QSelf>,
+        path: &Path,
+        source: PathSource<'ast>,
+    ) {
+        self.smart_resolve_path_fragment(
+            id,
+            qself,
+            &Segment::from_path(path),
+            path.span,
+            source,
+            CrateLint::SimplePath(id),
+        );
+    }
+
+    fn smart_resolve_path_fragment(
+        &mut self,
+        id: NodeId,
+        qself: Option<&QSelf>,
+        path: &[Segment],
+        span: Span,
+        source: PathSource<'ast>,
+        crate_lint: CrateLint,
+    ) -> PartialRes {
+        tracing::debug!(
+            "smart_resolve_path_fragment(id={:?},qself={:?},path={:?}",
+            id,
+            qself,
+            path
+        );
+        let ns = source.namespace();
+        let is_expected = &|res| source.is_expected(res);
+
+        let report_errors = |this: &mut Self, res: Option<Res>| {
+            if this.should_report_errs() {
+                let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res);
+
+                let def_id = this.parent_scope.module.normal_ancestor_id;
+                let instead = res.is_some();
+                let suggestion =
+                    if res.is_none() { this.report_missing_type_error(path) } else { None };
+
+                this.r.use_injections.push(UseError {
+                    err,
+                    candidates,
+                    def_id,
+                    instead,
+                    suggestion,
+                });
+            }
+
+            PartialRes::new(Res::Err)
+        };
+
+        // For paths originating from calls (like in `HashMap::new()`), tries
+        // to enrich the plain `failed to resolve: ...` message with hints
+        // about possible missing imports.
+        //
+        // Similar thing, for types, happens in `report_errors` above.
+        let report_errors_for_call = |this: &mut Self, parent_err: Spanned<ResolutionError<'a>>| {
+            if !source.is_call() {
+                return Some(parent_err);
+            }
+
+            // Before we start looking for candidates, we have to get our hands
+            // on the type user is trying to perform invocation on; basically:
+            // we're transforming `HashMap::new` into just `HashMap`
+            let path = if let Some((_, path)) = path.split_last() {
+                path
+            } else {
+                return Some(parent_err);
+            };
+
+            let (mut err, candidates) =
+                this.smart_resolve_report_errors(path, span, PathSource::Type, None);
+
+            if candidates.is_empty() {
+                err.cancel();
+                return Some(parent_err);
+            }
+
+            // There are two different error messages user might receive at
+            // this point:
+            // - E0412 cannot find type `{}` in this scope
+            // - E0433 failed to resolve: use of undeclared type or module `{}`
+            //
+            // The first one is emitted for paths in type-position, and the
+            // latter one - for paths in expression-position.
+            //
+            // Thus (since we're in expression-position at this point), not to
+            // confuse the user, we want to keep the *message* from E0432 (so
+            // `parent_err`), but we want *hints* from E0412 (so `err`).
+            //
+            // And that's what happens below - we're just mixing both messages
+            // into a single one.
+            let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
+
+            parent_err.cancel();
+
+            err.message = take(&mut parent_err.message);
+            err.code = take(&mut parent_err.code);
+            err.children = take(&mut parent_err.children);
+
+            drop(parent_err);
+
+            let def_id = this.parent_scope.module.normal_ancestor_id;
+
+            if this.should_report_errs() {
+                this.r.use_injections.push(UseError {
+                    err,
+                    candidates,
+                    def_id,
+                    instead: false,
+                    suggestion: None,
+                });
+            } else {
+                err.cancel();
+            }
+
+            // We don't return `Some(parent_err)` here, because the error will
+            // be already printed as part of the `use` injections
+            None
+        };
+
+        let partial_res = match self.resolve_qpath_anywhere(
+            id,
+            qself,
+            path,
+            ns,
+            span,
+            source.defer_to_typeck(),
+            crate_lint,
+        ) {
+            Ok(Some(partial_res)) if partial_res.unresolved_segments() == 0 => {
+                if is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err {
+                    partial_res
+                } else {
+                    report_errors(self, Some(partial_res.base_res()))
+                }
+            }
+
+            Ok(Some(partial_res)) if source.defer_to_typeck() => {
+                // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
+                // or `<T>::A::B`. If `B` should be resolved in value namespace then
+                // it needs to be added to the trait map.
+                if ns == ValueNS {
+                    let item_name = path.last().unwrap().ident;
+                    let traits = self.get_traits_containing_item(item_name, ns);
+                    self.r.trait_map.insert(id, traits);
+                }
+
+                let mut std_path = vec![Segment::from_ident(Ident::with_dummy_span(sym::std))];
+
+                std_path.extend(path);
+
+                if self.r.primitive_type_table.primitive_types.contains_key(&path[0].ident.name) {
+                    if let PathResult::Module(_) | PathResult::NonModule(_) =
+                        self.resolve_path(&std_path, Some(ns), false, span, CrateLint::No)
+                    {
+                        // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
+                        let item_span =
+                            path.iter().last().map(|segment| segment.ident.span).unwrap_or(span);
+
+                        let mut hm = self.r.session.confused_type_with_std_module.borrow_mut();
+                        hm.insert(item_span, span);
+                        hm.insert(span, span);
+                    }
+                }
+
+                partial_res
+            }
+
+            Err(err) => {
+                if let Some(err) = report_errors_for_call(self, err) {
+                    self.report_error(err.span, err.node);
+                }
+
+                PartialRes::new(Res::Err)
+            }
+
+            _ => report_errors(self, None),
+        };
+
+        if let PathSource::TraitItem(..) = source {
+        } else {
+            // Avoid recording definition of `A::B` in `<T as A>::B::C`.
+            self.r.record_partial_res(id, partial_res);
+        }
+
+        partial_res
+    }
+
+    fn self_type_is_available(&mut self, span: Span) -> bool {
+        let binding = self.resolve_ident_in_lexical_scope(
+            Ident::with_dummy_span(kw::SelfUpper),
+            TypeNS,
+            None,
+            span,
+        );
+        if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
+    }
+
+    fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
+        let ident = Ident::new(kw::SelfLower, self_span);
+        let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
+        if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
+    }
+
+    /// A wrapper around [`Resolver::report_error`].
+    ///
+    /// This doesn't emit errors for function bodies if this is rustdoc.
+    fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) {
+        if self.should_report_errs() {
+            self.r.report_error(span, resolution_error);
+        }
+    }
+
+    #[inline]
+    /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items.
+    fn should_report_errs(&self) -> bool {
+        !(self.r.session.opts.actually_rustdoc && self.in_func_body)
+    }
+
+    // Resolve in alternative namespaces if resolution in the primary namespace fails.
+    fn resolve_qpath_anywhere(
+        &mut self,
+        id: NodeId,
+        qself: Option<&QSelf>,
+        path: &[Segment],
+        primary_ns: Namespace,
+        span: Span,
+        defer_to_typeck: bool,
+        crate_lint: CrateLint,
+    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
+        let mut fin_res = None;
+
+        for (i, ns) in [primary_ns, TypeNS, ValueNS].iter().cloned().enumerate() {
+            if i == 0 || ns != primary_ns {
+                match self.resolve_qpath(id, qself, path, ns, span, crate_lint)? {
+                    Some(partial_res)
+                        if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
+                    {
+                        return Ok(Some(partial_res));
+                    }
+                    partial_res => {
+                        if fin_res.is_none() {
+                            fin_res = partial_res
+                        }
+                    }
+                }
+            }
+        }
+
+        assert!(primary_ns != MacroNS);
+
+        if qself.is_none() {
+            let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
+            let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None };
+            if let Ok((_, res)) =
+                self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false)
+            {
+                return Ok(Some(PartialRes::new(res)));
+            }
+        }
+
+        Ok(fin_res)
+    }
+
+    /// Handles paths that may refer to associated items.
+    fn resolve_qpath(
+        &mut self,
+        id: NodeId,
+        qself: Option<&QSelf>,
+        path: &[Segment],
+        ns: Namespace,
+        span: Span,
+        crate_lint: CrateLint,
+    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
+        debug!(
+            "resolve_qpath(id={:?}, qself={:?}, path={:?}, ns={:?}, span={:?})",
+            id, qself, path, ns, span,
+        );
+
+        if let Some(qself) = qself {
+            if qself.position == 0 {
+                // This is a case like `<T>::B`, where there is no
+                // trait to resolve.  In that case, we leave the `B`
+                // segment to be resolved by type-check.
+                return Ok(Some(PartialRes::with_unresolved_segments(
+                    Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)),
+                    path.len(),
+                )));
+            }
+
+            // Make sure `A::B` in `<T as A::B>::C` is a trait item.
+            //
+            // Currently, `path` names the full item (`A::B::C`, in
+            // our example).  so we extract the prefix of that that is
+            // the trait (the slice upto and including
+            // `qself.position`). And then we recursively resolve that,
+            // but with `qself` set to `None`.
+            //
+            // However, setting `qself` to none (but not changing the
+            // span) loses the information about where this path
+            // *actually* appears, so for the purposes of the crate
+            // lint we pass along information that this is the trait
+            // name from a fully qualified path, and this also
+            // contains the full span (the `CrateLint::QPathTrait`).
+            let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
+            let partial_res = self.smart_resolve_path_fragment(
+                id,
+                None,
+                &path[..=qself.position],
+                span,
+                PathSource::TraitItem(ns),
+                CrateLint::QPathTrait { qpath_id: id, qpath_span: qself.path_span },
+            );
+
+            // The remaining segments (the `C` in our example) will
+            // have to be resolved by type-check, since that requires doing
+            // trait resolution.
+            return Ok(Some(PartialRes::with_unresolved_segments(
+                partial_res.base_res(),
+                partial_res.unresolved_segments() + path.len() - qself.position - 1,
+            )));
+        }
+
+        let result = match self.resolve_path(&path, Some(ns), true, span, crate_lint) {
+            PathResult::NonModule(path_res) => path_res,
+            PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
+                PartialRes::new(module.res().unwrap())
+            }
+            // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
+            // don't report an error right away, but try to fallback to a primitive type.
+            // So, we are still able to successfully resolve something like
+            //
+            // use std::u8; // bring module u8 in scope
+            // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
+            //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
+            //                     // not to non-existent std::u8::max_value
+            // }
+            //
+            // Such behavior is required for backward compatibility.
+            // The same fallback is used when `a` resolves to nothing.
+            PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
+                if (ns == TypeNS || path.len() > 1)
+                    && self
+                        .r
+                        .primitive_type_table
+                        .primitive_types
+                        .contains_key(&path[0].ident.name) =>
+            {
+                let prim = self.r.primitive_type_table.primitive_types[&path[0].ident.name];
+                PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
+            }
+            PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
+                PartialRes::new(module.res().unwrap())
+            }
+            PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
+                return Err(respan(span, ResolutionError::FailedToResolve { label, suggestion }));
+            }
+            PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
+            PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
+        };
+
+        if path.len() > 1
+            && result.base_res() != Res::Err
+            && path[0].ident.name != kw::PathRoot
+            && path[0].ident.name != kw::DollarCrate
+        {
+            let unqualified_result = {
+                match self.resolve_path(
+                    &[*path.last().unwrap()],
+                    Some(ns),
+                    false,
+                    span,
+                    CrateLint::No,
+                ) {
+                    PathResult::NonModule(path_res) => path_res.base_res(),
+                    PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
+                        module.res().unwrap()
+                    }
+                    _ => return Ok(Some(result)),
+                }
+            };
+            if result.base_res() == unqualified_result {
+                let lint = lint::builtin::UNUSED_QUALIFICATIONS;
+                self.r.lint_buffer.buffer_lint(lint, id, span, "unnecessary qualification")
+            }
+        }
+
+        Ok(Some(result))
+    }
+
+    fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
+        if let Some(label) = label {
+            if label.ident.as_str().as_bytes()[1] != b'_' {
+                self.diagnostic_metadata.unused_labels.insert(id, label.ident.span);
+            }
+            self.with_label_rib(NormalRibKind, |this| {
+                let ident = label.ident.normalize_to_macro_rules();
+                this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
+                f(this);
+            });
+        } else {
+            f(self);
+        }
+    }
+
+    fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
+        self.with_resolved_label(label, id, |this| this.visit_block(block));
+    }
+
+    fn resolve_block(&mut self, block: &'ast Block) {
+        debug!("(resolving block) entering block");
+        // Move down in the graph, if there's an anonymous module rooted here.
+        let orig_module = self.parent_scope.module;
+        let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
+
+        let mut num_macro_definition_ribs = 0;
+        if let Some(anonymous_module) = anonymous_module {
+            debug!("(resolving block) found anonymous module, moving down");
+            self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
+            self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
+            self.parent_scope.module = anonymous_module;
+        } else {
+            self.ribs[ValueNS].push(Rib::new(NormalRibKind));
+        }
+
+        // Descend into the block.
+        for stmt in &block.stmts {
+            if let StmtKind::Item(ref item) = stmt.kind {
+                if let ItemKind::MacroDef(..) = item.kind {
+                    num_macro_definition_ribs += 1;
+                    let res = self.r.local_def_id(item.id).to_def_id();
+                    self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
+                    self.label_ribs.push(Rib::new(MacroDefinition(res)));
+                }
+            }
+
+            self.visit_stmt(stmt);
+        }
+
+        // Move back up.
+        self.parent_scope.module = orig_module;
+        for _ in 0..num_macro_definition_ribs {
+            self.ribs[ValueNS].pop();
+            self.label_ribs.pop();
+        }
+        self.ribs[ValueNS].pop();
+        if anonymous_module.is_some() {
+            self.ribs[TypeNS].pop();
+        }
+        debug!("(resolving block) leaving block");
+    }
+
+    fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
+        // First, record candidate traits for this expression if it could
+        // result in the invocation of a method call.
+
+        self.record_candidate_traits_for_expr_if_necessary(expr);
+
+        // Next, resolve the node.
+        match expr.kind {
+            ExprKind::Path(ref qself, ref path) => {
+                self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
+                visit::walk_expr(self, expr);
+            }
+
+            ExprKind::Struct(ref path, ..) => {
+                self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
+                visit::walk_expr(self, expr);
+            }
+
+            ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
+                if let Some(node_id) = self.resolve_label(label.ident) {
+                    // Since this res is a label, it is never read.
+                    self.r.label_res_map.insert(expr.id, node_id);
+                    self.diagnostic_metadata.unused_labels.remove(&node_id);
+                }
+
+                // visit `break` argument if any
+                visit::walk_expr(self, expr);
+            }
+
+            ExprKind::Let(ref pat, ref scrutinee) => {
+                self.visit_expr(scrutinee);
+                self.resolve_pattern_top(pat, PatternSource::Let);
+            }
+
+            ExprKind::If(ref cond, ref then, ref opt_else) => {
+                self.with_rib(ValueNS, NormalRibKind, |this| {
+                    let old = this.diagnostic_metadata.in_if_condition.replace(cond);
+                    this.visit_expr(cond);
+                    this.diagnostic_metadata.in_if_condition = old;
+                    this.visit_block(then);
+                });
+                if let Some(expr) = opt_else {
+                    self.visit_expr(expr);
+                }
+            }
+
+            ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
+
+            ExprKind::While(ref cond, ref block, label) => {
+                self.with_resolved_label(label, expr.id, |this| {
+                    this.with_rib(ValueNS, NormalRibKind, |this| {
+                        this.visit_expr(cond);
+                        this.visit_block(block);
+                    })
+                });
+            }
+
+            ExprKind::ForLoop(ref pat, ref iter_expr, ref block, label) => {
+                self.visit_expr(iter_expr);
+                self.with_rib(ValueNS, NormalRibKind, |this| {
+                    this.resolve_pattern_top(pat, PatternSource::For);
+                    this.resolve_labeled_block(label, expr.id, block);
+                });
+            }
+
+            ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
+
+            // Equivalent to `visit::walk_expr` + passing some context to children.
+            ExprKind::Field(ref subexpression, _) => {
+                self.resolve_expr(subexpression, Some(expr));
+            }
+            ExprKind::MethodCall(ref segment, ref arguments, _) => {
+                let mut arguments = arguments.iter();
+                self.resolve_expr(arguments.next().unwrap(), Some(expr));
+                for argument in arguments {
+                    self.resolve_expr(argument, None);
+                }
+                self.visit_path_segment(expr.span, segment);
+            }
+
+            ExprKind::Call(ref callee, ref arguments) => {
+                self.resolve_expr(callee, Some(expr));
+                for argument in arguments {
+                    self.resolve_expr(argument, None);
+                }
+            }
+            ExprKind::Type(ref type_expr, ref ty) => {
+                // `ParseSess::type_ascription_path_suggestions` keeps spans of colon tokens in
+                // type ascription. Here we are trying to retrieve the span of the colon token as
+                // well, but only if it's written without spaces `expr:Ty` and therefore confusable
+                // with `expr::Ty`, only in this case it will match the span from
+                // `type_ascription_path_suggestions`.
+                self.diagnostic_metadata
+                    .current_type_ascription
+                    .push(type_expr.span.between(ty.span));
+                visit::walk_expr(self, expr);
+                self.diagnostic_metadata.current_type_ascription.pop();
+            }
+            // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
+            // resolve the arguments within the proper scopes so that usages of them inside the
+            // closure are detected as upvars rather than normal closure arg usages.
+            ExprKind::Closure(_, Async::Yes { .. }, _, ref fn_decl, ref body, _span) => {
+                self.with_rib(ValueNS, NormalRibKind, |this| {
+                    this.with_label_rib(ClosureOrAsyncRibKind, |this| {
+                        // Resolve arguments:
+                        this.resolve_params(&fn_decl.inputs);
+                        // No need to resolve return type --
+                        // the outer closure return type is `FnRetTy::Default`.
+
+                        // Now resolve the inner closure
+                        {
+                            // No need to resolve arguments: the inner closure has none.
+                            // Resolve the return type:
+                            visit::walk_fn_ret_ty(this, &fn_decl.output);
+                            // Resolve the body
+                            this.visit_expr(body);
+                        }
+                    })
+                });
+            }
+            ExprKind::Async(..) | ExprKind::Closure(..) => {
+                self.with_label_rib(ClosureOrAsyncRibKind, |this| visit::walk_expr(this, expr));
+            }
+            _ => {
+                visit::walk_expr(self, expr);
+            }
+        }
+    }
+
+    fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
+        match expr.kind {
+            ExprKind::Field(_, ident) => {
+                // FIXME(#6890): Even though you can't treat a method like a
+                // field, we need to add any trait methods we find that match
+                // the field name so that we can do some nice error reporting
+                // later on in typeck.
+                let traits = self.get_traits_containing_item(ident, ValueNS);
+                self.r.trait_map.insert(expr.id, traits);
+            }
+            ExprKind::MethodCall(ref segment, ..) => {
+                debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
+                let traits = self.get_traits_containing_item(segment.ident, ValueNS);
+                self.r.trait_map.insert(expr.id, traits);
+            }
+            _ => {
+                // Nothing to do.
+            }
+        }
+    }
+
+    fn get_traits_containing_item(
+        &mut self,
+        mut ident: Ident,
+        ns: Namespace,
+    ) -> Vec<TraitCandidate> {
+        debug!("(getting traits containing item) looking for '{}'", ident.name);
+
+        let mut found_traits = Vec::new();
+        // Look for the current trait.
+        if let Some((module, _)) = self.current_trait_ref {
+            if self
+                .r
+                .resolve_ident_in_module(
+                    ModuleOrUniformRoot::Module(module),
+                    ident,
+                    ns,
+                    &self.parent_scope,
+                    false,
+                    module.span,
+                )
+                .is_ok()
+            {
+                let def_id = module.def_id().unwrap();
+                found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
+            }
+        }
+
+        ident.span = ident.span.normalize_to_macros_2_0();
+        let mut search_module = self.parent_scope.module;
+        loop {
+            self.r.get_traits_in_module_containing_item(
+                ident,
+                ns,
+                search_module,
+                &mut found_traits,
+                &self.parent_scope,
+            );
+            search_module =
+                unwrap_or!(self.r.hygienic_lexical_parent(search_module, &mut ident.span), break);
+        }
+
+        if let Some(prelude) = self.r.prelude {
+            if !search_module.no_implicit_prelude {
+                self.r.get_traits_in_module_containing_item(
+                    ident,
+                    ns,
+                    prelude,
+                    &mut found_traits,
+                    &self.parent_scope,
+                );
+            }
+        }
+
+        found_traits
+    }
+}
+
+impl<'a> Resolver<'a> {
+    pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
+        let mut late_resolution_visitor = LateResolutionVisitor::new(self);
+        visit::walk_crate(&mut late_resolution_visitor, krate);
+        for (id, span) in late_resolution_visitor.diagnostic_metadata.unused_labels.iter() {
+            self.lint_buffer.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");
+        }
+    }
+}
diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs
new file mode 100644
index 0000000..521ea7a
--- /dev/null
+++ b/compiler/rustc_resolve/src/late/diagnostics.rs
@@ -0,0 +1,1631 @@
+use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
+use crate::late::lifetimes::{ElisionFailureInfo, LifetimeContext};
+use crate::late::{LateResolutionVisitor, RibKind};
+use crate::path_names_to_string;
+use crate::{CrateLint, Module, ModuleKind, ModuleOrUniformRoot};
+use crate::{PathResult, PathSource, Segment};
+
+use rustc_ast::util::lev_distance::find_best_match_for_name;
+use rustc_ast::visit::FnKind;
+use rustc_ast::{self as ast, Expr, ExprKind, Item, ItemKind, NodeId, Path, Ty, TyKind};
+use rustc_data_structures::fx::FxHashSet;
+use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder};
+use rustc_hir as hir;
+use rustc_hir::def::Namespace::{self, *};
+use rustc_hir::def::{self, CtorKind, DefKind};
+use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
+use rustc_hir::PrimTy;
+use rustc_session::config::nightly_options;
+use rustc_session::parse::feature_err;
+use rustc_span::hygiene::MacroKind;
+use rustc_span::symbol::{kw, sym, Ident, Symbol};
+use rustc_span::{BytePos, Span, DUMMY_SP};
+
+use tracing::debug;
+
+type Res = def::Res<ast::NodeId>;
+
+/// A field or associated item from self type suggested in case of resolution failure.
+enum AssocSuggestion {
+    Field,
+    MethodWithSelf,
+    AssocItem,
+}
+
+crate enum MissingLifetimeSpot<'tcx> {
+    Generics(&'tcx hir::Generics<'tcx>),
+    HigherRanked { span: Span, span_type: ForLifetimeSpanType },
+    Static,
+}
+
+crate enum ForLifetimeSpanType {
+    BoundEmpty,
+    BoundTail,
+    TypeEmpty,
+    TypeTail,
+}
+
+impl ForLifetimeSpanType {
+    crate fn descr(&self) -> &'static str {
+        match self {
+            Self::BoundEmpty | Self::BoundTail => "bound",
+            Self::TypeEmpty | Self::TypeTail => "type",
+        }
+    }
+
+    crate fn suggestion(&self, sugg: &str) -> String {
+        match self {
+            Self::BoundEmpty | Self::TypeEmpty => format!("for<{}> ", sugg),
+            Self::BoundTail | Self::TypeTail => format!(", {}", sugg),
+        }
+    }
+}
+
+impl<'tcx> Into<MissingLifetimeSpot<'tcx>> for &'tcx hir::Generics<'tcx> {
+    fn into(self) -> MissingLifetimeSpot<'tcx> {
+        MissingLifetimeSpot::Generics(self)
+    }
+}
+
+fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
+    namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
+}
+
+fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
+    namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
+}
+
+/// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
+fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
+    let variant_path = &suggestion.path;
+    let variant_path_string = path_names_to_string(variant_path);
+
+    let path_len = suggestion.path.segments.len();
+    let enum_path = ast::Path {
+        span: suggestion.path.span,
+        segments: suggestion.path.segments[0..path_len - 1].to_vec(),
+        tokens: None,
+    };
+    let enum_path_string = path_names_to_string(&enum_path);
+
+    (variant_path_string, enum_path_string)
+}
+
+impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
+    fn def_span(&self, def_id: DefId) -> Option<Span> {
+        match def_id.krate {
+            LOCAL_CRATE => self.r.opt_span(def_id),
+            _ => Some(
+                self.r
+                    .session
+                    .source_map()
+                    .guess_head_span(self.r.cstore().get_span_untracked(def_id, self.r.session)),
+            ),
+        }
+    }
+
+    /// Handles error reporting for `smart_resolve_path_fragment` function.
+    /// Creates base error and amends it with one short label and possibly some longer helps/notes.
+    pub(crate) fn smart_resolve_report_errors(
+        &mut self,
+        path: &[Segment],
+        span: Span,
+        source: PathSource<'_>,
+        res: Option<Res>,
+    ) -> (DiagnosticBuilder<'a>, Vec<ImportSuggestion>) {
+        let ident_span = path.last().map_or(span, |ident| ident.ident.span);
+        let ns = source.namespace();
+        let is_expected = &|res| source.is_expected(res);
+        let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
+
+        // Make the base error.
+        let expected = source.descr_expected();
+        let path_str = Segment::names_to_string(path);
+        let item_str = path.last().unwrap().ident;
+        let (base_msg, fallback_label, base_span, could_be_expr) = if let Some(res) = res {
+            (
+                format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
+                format!("not a {}", expected),
+                span,
+                match res {
+                    Res::Def(DefKind::Fn, _) => {
+                        // Verify whether this is a fn call or an Fn used as a type.
+                        self.r
+                            .session
+                            .source_map()
+                            .span_to_snippet(span)
+                            .map(|snippet| snippet.ends_with(')'))
+                            .unwrap_or(false)
+                    }
+                    Res::Def(
+                        DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
+                        _,
+                    )
+                    | Res::SelfCtor(_)
+                    | Res::PrimTy(_)
+                    | Res::Local(_) => true,
+                    _ => false,
+                },
+            )
+        } else {
+            let item_span = path.last().unwrap().ident.span;
+            let (mod_prefix, mod_str) = if path.len() == 1 {
+                (String::new(), "this scope".to_string())
+            } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
+                (String::new(), "the crate root".to_string())
+            } else {
+                let mod_path = &path[..path.len() - 1];
+                let mod_prefix =
+                    match self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No) {
+                        PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
+                        _ => None,
+                    }
+                    .map_or(String::new(), |res| format!("{} ", res.descr()));
+                (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
+            };
+            (
+                format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
+                if path_str == "async" && expected.starts_with("struct") {
+                    "`async` blocks are only allowed in the 2018 edition".to_string()
+                } else {
+                    format!("not found in {}", mod_str)
+                },
+                item_span,
+                false,
+            )
+        };
+
+        let code = source.error_code(res.is_some());
+        let mut err = self.r.session.struct_span_err_with_code(base_span, &base_msg, code);
+
+        match (source, self.diagnostic_metadata.in_if_condition) {
+            (PathSource::Expr(_), Some(Expr { span, kind: ExprKind::Assign(..), .. })) => {
+                err.span_suggestion_verbose(
+                    span.shrink_to_lo(),
+                    "you might have meant to use pattern matching",
+                    "let ".to_string(),
+                    Applicability::MaybeIncorrect,
+                );
+                self.r.session.if_let_suggestions.borrow_mut().insert(*span);
+            }
+            _ => {}
+        }
+
+        let is_assoc_fn = self.self_type_is_available(span);
+        // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
+        if ["this", "my"].contains(&&*item_str.as_str()) && is_assoc_fn {
+            err.span_suggestion_short(
+                span,
+                "you might have meant to use `self` here instead",
+                "self".to_string(),
+                Applicability::MaybeIncorrect,
+            );
+            if !self.self_value_is_available(path[0].ident.span, span) {
+                if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
+                    &self.diagnostic_metadata.current_function
+                {
+                    let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
+                        (param.span.shrink_to_lo(), "&self, ")
+                    } else {
+                        (
+                            self.r
+                                .session
+                                .source_map()
+                                .span_through_char(*fn_span, '(')
+                                .shrink_to_hi(),
+                            "&self",
+                        )
+                    };
+                    err.span_suggestion_verbose(
+                        span,
+                        "if you meant to use `self`, you are also missing a `self` receiver \
+                         argument",
+                        sugg.to_string(),
+                        Applicability::MaybeIncorrect,
+                    );
+                }
+            }
+        }
+
+        // Emit special messages for unresolved `Self` and `self`.
+        if is_self_type(path, ns) {
+            err.code(rustc_errors::error_code!(E0411));
+            err.span_label(
+                span,
+                "`Self` is only available in impls, traits, and type definitions".to_string(),
+            );
+            return (err, Vec::new());
+        }
+        if is_self_value(path, ns) {
+            debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
+
+            err.code(rustc_errors::error_code!(E0424));
+            err.span_label(span, match source {
+                PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed"
+                                   .to_string(),
+                _ => "`self` value is a keyword only available in methods with a `self` parameter"
+                     .to_string(),
+            });
+            if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
+                // The current function has a `self' parameter, but we were unable to resolve
+                // a reference to `self`. This can only happen if the `self` identifier we
+                // are resolving came from a different hygiene context.
+                if fn_kind.decl().inputs.get(0).map(|p| p.is_self()).unwrap_or(false) {
+                    err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
+                } else {
+                    let doesnt = if is_assoc_fn {
+                        let (span, sugg) = fn_kind
+                            .decl()
+                            .inputs
+                            .get(0)
+                            .map(|p| (p.span.shrink_to_lo(), "&self, "))
+                            .unwrap_or_else(|| {
+                                (
+                                    self.r
+                                        .session
+                                        .source_map()
+                                        .span_through_char(*span, '(')
+                                        .shrink_to_hi(),
+                                    "&self",
+                                )
+                            });
+                        err.span_suggestion_verbose(
+                            span,
+                            "add a `self` receiver parameter to make the associated `fn` a method",
+                            sugg.to_string(),
+                            Applicability::MaybeIncorrect,
+                        );
+                        "doesn't"
+                    } else {
+                        "can't"
+                    };
+                    if let Some(ident) = fn_kind.ident() {
+                        err.span_label(
+                            ident.span,
+                            &format!("this function {} have a `self` parameter", doesnt),
+                        );
+                    }
+                }
+            }
+            return (err, Vec::new());
+        }
+
+        // Try to lookup name in more relaxed fashion for better error reporting.
+        let ident = path.last().unwrap().ident;
+        let candidates = self
+            .r
+            .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
+            .drain(..)
+            .filter(|ImportSuggestion { did, .. }| {
+                match (did, res.and_then(|res| res.opt_def_id())) {
+                    (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
+                    _ => true,
+                }
+            })
+            .collect::<Vec<_>>();
+        let crate_def_id = DefId::local(CRATE_DEF_INDEX);
+        if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
+            let enum_candidates =
+                self.r.lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant);
+
+            if !enum_candidates.is_empty() {
+                if let (PathSource::Type, Some(span)) =
+                    (source, self.diagnostic_metadata.current_type_ascription.last())
+                {
+                    if self
+                        .r
+                        .session
+                        .parse_sess
+                        .type_ascription_path_suggestions
+                        .borrow()
+                        .contains(span)
+                    {
+                        // Already reported this issue on the lhs of the type ascription.
+                        err.delay_as_bug();
+                        return (err, candidates);
+                    }
+                }
+
+                let mut enum_candidates = enum_candidates
+                    .iter()
+                    .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
+                    .collect::<Vec<_>>();
+                enum_candidates.sort();
+
+                // Contextualize for E0412 "cannot find type", but don't belabor the point
+                // (that it's a variant) for E0573 "expected type, found variant".
+                let preamble = if res.is_none() {
+                    let others = match enum_candidates.len() {
+                        1 => String::new(),
+                        2 => " and 1 other".to_owned(),
+                        n => format!(" and {} others", n),
+                    };
+                    format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
+                } else {
+                    String::new()
+                };
+                let msg = format!("{}try using the variant's enum", preamble);
+
+                err.span_suggestions(
+                    span,
+                    &msg,
+                    enum_candidates
+                        .into_iter()
+                        .map(|(_variant_path, enum_ty_path)| enum_ty_path)
+                        // Variants re-exported in prelude doesn't mean `prelude::v1` is the
+                        // type name!
+                        // FIXME: is there a more principled way to do this that
+                        // would work for other re-exports?
+                        .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
+                        // Also write `Option` rather than `std::prelude::v1::Option`.
+                        .map(|enum_ty_path| {
+                            // FIXME #56861: DRY-er prelude filtering.
+                            enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
+                        }),
+                    Applicability::MachineApplicable,
+                );
+            }
+        }
+        if path.len() == 1 && self.self_type_is_available(span) {
+            if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
+                let self_is_available = self.self_value_is_available(path[0].ident.span, span);
+                match candidate {
+                    AssocSuggestion::Field => {
+                        if self_is_available {
+                            err.span_suggestion(
+                                span,
+                                "you might have meant to use the available field",
+                                format!("self.{}", path_str),
+                                Applicability::MachineApplicable,
+                            );
+                        } else {
+                            err.span_label(span, "a field by this name exists in `Self`");
+                        }
+                    }
+                    AssocSuggestion::MethodWithSelf if self_is_available => {
+                        err.span_suggestion(
+                            span,
+                            "try",
+                            format!("self.{}", path_str),
+                            Applicability::MachineApplicable,
+                        );
+                    }
+                    AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
+                        err.span_suggestion(
+                            span,
+                            "try",
+                            format!("Self::{}", path_str),
+                            Applicability::MachineApplicable,
+                        );
+                    }
+                }
+                return (err, candidates);
+            }
+
+            // If the first argument in call is `self` suggest calling a method.
+            if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
+                let mut args_snippet = String::new();
+                if let Some(args_span) = args_span {
+                    if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
+                        args_snippet = snippet;
+                    }
+                }
+
+                err.span_suggestion(
+                    call_span,
+                    &format!("try calling `{}` as a method", ident),
+                    format!("self.{}({})", path_str, args_snippet),
+                    Applicability::MachineApplicable,
+                );
+                return (err, candidates);
+            }
+        }
+
+        // Try Levenshtein algorithm.
+        let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected, span);
+        // Try context-dependent help if relaxed lookup didn't work.
+        if let Some(res) = res {
+            if self.smart_resolve_context_dependent_help(
+                &mut err,
+                span,
+                source,
+                res,
+                &path_str,
+                &fallback_label,
+            ) {
+                // We do this to avoid losing a secondary span when we override the main error span.
+                self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
+                return (err, candidates);
+            }
+        }
+
+        if !self.type_ascription_suggestion(&mut err, base_span)
+            && !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span)
+        {
+            // Fallback label.
+            err.span_label(base_span, fallback_label);
+
+            match self.diagnostic_metadata.current_let_binding {
+                Some((pat_sp, Some(ty_sp), None)) if ty_sp.contains(base_span) && could_be_expr => {
+                    err.span_suggestion_short(
+                        pat_sp.between(ty_sp),
+                        "use `=` if you meant to assign",
+                        " = ".to_string(),
+                        Applicability::MaybeIncorrect,
+                    );
+                }
+                _ => {}
+            }
+        }
+        (err, candidates)
+    }
+
+    /// Check if the source is call expression and the first argument is `self`. If true,
+    /// return the span of whole call and the span for all arguments expect the first one (`self`).
+    fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
+        let mut has_self_arg = None;
+        if let PathSource::Expr(Some(parent)) = source {
+            match &parent.kind {
+                ExprKind::Call(_, args) if !args.is_empty() => {
+                    let mut expr_kind = &args[0].kind;
+                    loop {
+                        match expr_kind {
+                            ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
+                                if arg_name.segments[0].ident.name == kw::SelfLower {
+                                    let call_span = parent.span;
+                                    let tail_args_span = if args.len() > 1 {
+                                        Some(Span::new(
+                                            args[1].span.lo(),
+                                            args.last().unwrap().span.hi(),
+                                            call_span.ctxt(),
+                                        ))
+                                    } else {
+                                        None
+                                    };
+                                    has_self_arg = Some((call_span, tail_args_span));
+                                }
+                                break;
+                            }
+                            ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
+                            _ => break,
+                        }
+                    }
+                }
+                _ => (),
+            }
+        };
+        has_self_arg
+    }
+
+    fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
+        // HACK(estebank): find a better way to figure out that this was a
+        // parser issue where a struct literal is being used on an expression
+        // where a brace being opened means a block is being started. Look
+        // ahead for the next text to see if `span` is followed by a `{`.
+        let sm = self.r.session.source_map();
+        let mut sp = span;
+        loop {
+            sp = sm.next_point(sp);
+            match sm.span_to_snippet(sp) {
+                Ok(ref snippet) => {
+                    if snippet.chars().any(|c| !c.is_whitespace()) {
+                        break;
+                    }
+                }
+                _ => break,
+            }
+        }
+        let followed_by_brace = match sm.span_to_snippet(sp) {
+            Ok(ref snippet) if snippet == "{" => true,
+            _ => false,
+        };
+        // In case this could be a struct literal that needs to be surrounded
+        // by parentheses, find the appropriate span.
+        let mut i = 0;
+        let mut closing_brace = None;
+        loop {
+            sp = sm.next_point(sp);
+            match sm.span_to_snippet(sp) {
+                Ok(ref snippet) => {
+                    if snippet == "}" {
+                        closing_brace = Some(span.to(sp));
+                        break;
+                    }
+                }
+                _ => break,
+            }
+            i += 1;
+            // The bigger the span, the more likely we're incorrect --
+            // bound it to 100 chars long.
+            if i > 100 {
+                break;
+            }
+        }
+        (followed_by_brace, closing_brace)
+    }
+
+    /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
+    /// function.
+    /// Returns `true` if able to provide context-dependent help.
+    fn smart_resolve_context_dependent_help(
+        &mut self,
+        err: &mut DiagnosticBuilder<'a>,
+        span: Span,
+        source: PathSource<'_>,
+        res: Res,
+        path_str: &str,
+        fallback_label: &str,
+    ) -> bool {
+        let ns = source.namespace();
+        let is_expected = &|res| source.is_expected(res);
+
+        let path_sep = |err: &mut DiagnosticBuilder<'_>, expr: &Expr| match expr.kind {
+            ExprKind::Field(_, ident) => {
+                err.span_suggestion(
+                    expr.span,
+                    "use the path separator to refer to an item",
+                    format!("{}::{}", path_str, ident),
+                    Applicability::MaybeIncorrect,
+                );
+                true
+            }
+            ExprKind::MethodCall(ref segment, ..) => {
+                let span = expr.span.with_hi(segment.ident.span.hi());
+                err.span_suggestion(
+                    span,
+                    "use the path separator to refer to an item",
+                    format!("{}::{}", path_str, segment.ident),
+                    Applicability::MaybeIncorrect,
+                );
+                true
+            }
+            _ => false,
+        };
+
+        let mut bad_struct_syntax_suggestion = |def_id: DefId| {
+            let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
+
+            match source {
+                PathSource::Expr(Some(
+                    parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
+                )) if path_sep(err, &parent) => {}
+                PathSource::Expr(
+                    None
+                    | Some(Expr {
+                        kind:
+                            ExprKind::Path(..)
+                            | ExprKind::Binary(..)
+                            | ExprKind::Unary(..)
+                            | ExprKind::If(..)
+                            | ExprKind::While(..)
+                            | ExprKind::ForLoop(..)
+                            | ExprKind::Match(..),
+                        ..
+                    }),
+                ) if followed_by_brace => {
+                    if let Some(sp) = closing_brace {
+                        err.span_label(span, fallback_label);
+                        err.multipart_suggestion(
+                            "surround the struct literal with parentheses",
+                            vec![
+                                (sp.shrink_to_lo(), "(".to_string()),
+                                (sp.shrink_to_hi(), ")".to_string()),
+                            ],
+                            Applicability::MaybeIncorrect,
+                        );
+                    } else {
+                        err.span_label(
+                            span, // Note the parentheses surrounding the suggestion below
+                            format!(
+                                "you might want to surround a struct literal with parentheses: \
+                                 `({} {{ /* fields */ }})`?",
+                                path_str
+                            ),
+                        );
+                    }
+                }
+                PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
+                    let span = match &source {
+                        PathSource::Expr(Some(Expr {
+                            span, kind: ExprKind::Call(_, _), ..
+                        }))
+                        | PathSource::TupleStruct(span, _) => {
+                            // We want the main underline to cover the suggested code as well for
+                            // cleaner output.
+                            err.set_span(*span);
+                            *span
+                        }
+                        _ => span,
+                    };
+                    if let Some(span) = self.def_span(def_id) {
+                        err.span_label(span, &format!("`{}` defined here", path_str));
+                    }
+                    let (tail, descr, applicability) = match source {
+                        PathSource::Pat | PathSource::TupleStruct(..) => {
+                            ("", "pattern", Applicability::MachineApplicable)
+                        }
+                        _ => (": val", "literal", Applicability::HasPlaceholders),
+                    };
+                    let (fields, applicability) = match self.r.field_names.get(&def_id) {
+                        Some(fields) => (
+                            fields
+                                .iter()
+                                .map(|f| format!("{}{}", f.node, tail))
+                                .collect::<Vec<String>>()
+                                .join(", "),
+                            applicability,
+                        ),
+                        None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
+                    };
+                    let pad = match self.r.field_names.get(&def_id) {
+                        Some(fields) if fields.is_empty() => "",
+                        _ => " ",
+                    };
+                    err.span_suggestion(
+                        span,
+                        &format!("use struct {} syntax instead", descr),
+                        format!("{} {{{pad}{}{pad}}}", path_str, fields, pad = pad),
+                        applicability,
+                    );
+                }
+                _ => {
+                    err.span_label(span, fallback_label);
+                }
+            }
+        };
+
+        match (res, source) {
+            (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
+                err.span_label(span, fallback_label);
+                err.span_suggestion_verbose(
+                    span.shrink_to_hi(),
+                    "use `!` to invoke the macro",
+                    "!".to_string(),
+                    Applicability::MaybeIncorrect,
+                );
+                if path_str == "try" && span.rust_2015() {
+                    err.note("if you want the `try` keyword, you need to be in the 2018 edition");
+                }
+            }
+            (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
+                err.span_label(span, "type aliases cannot be used as traits");
+                if nightly_options::is_nightly_build() {
+                    let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
+                               `type` alias";
+                    if let Some(span) = self.def_span(def_id) {
+                        err.span_help(span, msg);
+                    } else {
+                        err.help(msg);
+                    }
+                }
+            }
+            (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
+                if !path_sep(err, &parent) {
+                    return false;
+                }
+            }
+            (
+                Res::Def(DefKind::Enum, def_id),
+                PathSource::TupleStruct(..) | PathSource::Expr(..),
+            ) => {
+                if self
+                    .diagnostic_metadata
+                    .current_type_ascription
+                    .last()
+                    .map(|sp| {
+                        self.r
+                            .session
+                            .parse_sess
+                            .type_ascription_path_suggestions
+                            .borrow()
+                            .contains(&sp)
+                    })
+                    .unwrap_or(false)
+                {
+                    err.delay_as_bug();
+                    // We already suggested changing `:` into `::` during parsing.
+                    return false;
+                }
+                if let Some(variants) = self.collect_enum_variants(def_id) {
+                    if !variants.is_empty() {
+                        let msg = if variants.len() == 1 {
+                            "try using the enum's variant"
+                        } else {
+                            "try using one of the enum's variants"
+                        };
+
+                        err.span_suggestions(
+                            span,
+                            msg,
+                            variants.iter().map(path_names_to_string),
+                            Applicability::MaybeIncorrect,
+                        );
+                    }
+                } else {
+                    err.note("you might have meant to use one of the enum's variants");
+                }
+            }
+            (Res::Def(DefKind::Struct, def_id), _) if ns == ValueNS => {
+                if let Some((ctor_def, ctor_vis, fields)) =
+                    self.r.struct_constructors.get(&def_id).cloned()
+                {
+                    let accessible_ctor =
+                        self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
+                    if is_expected(ctor_def) && !accessible_ctor {
+                        let mut better_diag = false;
+                        if let PathSource::TupleStruct(_, pattern_spans) = source {
+                            if pattern_spans.len() > 0 && fields.len() == pattern_spans.len() {
+                                let non_visible_spans: Vec<Span> = fields
+                                    .iter()
+                                    .zip(pattern_spans.iter())
+                                    .filter_map(|(vis, span)| {
+                                        match self
+                                            .r
+                                            .is_accessible_from(*vis, self.parent_scope.module)
+                                        {
+                                            true => None,
+                                            false => Some(*span),
+                                        }
+                                    })
+                                    .collect();
+                                // Extra check to be sure
+                                if non_visible_spans.len() > 0 {
+                                    let mut m: rustc_span::MultiSpan =
+                                        non_visible_spans.clone().into();
+                                    non_visible_spans.into_iter().for_each(|s| {
+                                        m.push_span_label(s, "private field".to_string())
+                                    });
+                                    err.span_note(
+                                        m,
+                                        "constructor is not visible here due to private fields",
+                                    );
+                                    better_diag = true;
+                                }
+                            }
+                        }
+
+                        if !better_diag {
+                            err.span_label(
+                                span,
+                                "constructor is not visible here due to private fields".to_string(),
+                            );
+                        }
+                    }
+                } else {
+                    bad_struct_syntax_suggestion(def_id);
+                }
+            }
+            (
+                Res::Def(
+                    DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
+                    def_id,
+                ),
+                _,
+            ) if ns == ValueNS => {
+                bad_struct_syntax_suggestion(def_id);
+            }
+            (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
+                if let Some(span) = self.def_span(def_id) {
+                    err.span_label(span, &format!("`{}` defined here", path_str));
+                }
+                let fields =
+                    self.r.field_names.get(&def_id).map_or("/* fields */".to_string(), |fields| {
+                        vec!["_"; fields.len()].join(", ")
+                    });
+                err.span_suggestion(
+                    span,
+                    "use the tuple variant pattern syntax instead",
+                    format!("{}({})", path_str, fields),
+                    Applicability::HasPlaceholders,
+                );
+            }
+            (Res::SelfTy(..), _) if ns == ValueNS => {
+                err.span_label(span, fallback_label);
+                err.note("can't use `Self` as a constructor, you must use the implemented struct");
+            }
+            (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
+                err.note("can't use a type alias as a constructor");
+            }
+            _ => return false,
+        }
+        true
+    }
+
+    fn lookup_assoc_candidate<FilterFn>(
+        &mut self,
+        ident: Ident,
+        ns: Namespace,
+        filter_fn: FilterFn,
+    ) -> Option<AssocSuggestion>
+    where
+        FilterFn: Fn(Res) -> bool,
+    {
+        fn extract_node_id(t: &Ty) -> Option<NodeId> {
+            match t.kind {
+                TyKind::Path(None, _) => Some(t.id),
+                TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
+                // This doesn't handle the remaining `Ty` variants as they are not
+                // that commonly the self_type, it might be interesting to provide
+                // support for those in future.
+                _ => None,
+            }
+        }
+
+        // Fields are generally expected in the same contexts as locals.
+        if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
+            if let Some(node_id) =
+                self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
+            {
+                // Look for a field with the same name in the current self_type.
+                if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
+                    match resolution.base_res() {
+                        Res::Def(DefKind::Struct | DefKind::Union, did)
+                            if resolution.unresolved_segments() == 0 =>
+                        {
+                            if let Some(field_names) = self.r.field_names.get(&did) {
+                                if field_names
+                                    .iter()
+                                    .any(|&field_name| ident.name == field_name.node)
+                                {
+                                    return Some(AssocSuggestion::Field);
+                                }
+                            }
+                        }
+                        _ => {}
+                    }
+                }
+            }
+        }
+
+        for assoc_type_ident in &self.diagnostic_metadata.current_trait_assoc_types {
+            if *assoc_type_ident == ident {
+                return Some(AssocSuggestion::AssocItem);
+            }
+        }
+
+        // Look for associated items in the current trait.
+        if let Some((module, _)) = self.current_trait_ref {
+            if let Ok(binding) = self.r.resolve_ident_in_module(
+                ModuleOrUniformRoot::Module(module),
+                ident,
+                ns,
+                &self.parent_scope,
+                false,
+                module.span,
+            ) {
+                let res = binding.res();
+                if filter_fn(res) {
+                    return Some(if self.r.has_self.contains(&res.def_id()) {
+                        AssocSuggestion::MethodWithSelf
+                    } else {
+                        AssocSuggestion::AssocItem
+                    });
+                }
+            }
+        }
+
+        None
+    }
+
+    fn lookup_typo_candidate(
+        &mut self,
+        path: &[Segment],
+        ns: Namespace,
+        filter_fn: &impl Fn(Res) -> bool,
+        span: Span,
+    ) -> Option<TypoSuggestion> {
+        let mut names = Vec::new();
+        if path.len() == 1 {
+            // Search in lexical scope.
+            // Walk backwards up the ribs in scope and collect candidates.
+            for rib in self.ribs[ns].iter().rev() {
+                // Locals and type parameters
+                for (ident, &res) in &rib.bindings {
+                    if filter_fn(res) {
+                        names.push(TypoSuggestion::from_res(ident.name, res));
+                    }
+                }
+                // Items in scope
+                if let RibKind::ModuleRibKind(module) = rib.kind {
+                    // Items from this module
+                    self.r.add_module_candidates(module, &mut names, &filter_fn);
+
+                    if let ModuleKind::Block(..) = module.kind {
+                        // We can see through blocks
+                    } else {
+                        // Items from the prelude
+                        if !module.no_implicit_prelude {
+                            let extern_prelude = self.r.extern_prelude.clone();
+                            names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
+                                self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
+                                    |crate_id| {
+                                        let crate_mod = Res::Def(
+                                            DefKind::Mod,
+                                            DefId { krate: crate_id, index: CRATE_DEF_INDEX },
+                                        );
+
+                                        if filter_fn(crate_mod) {
+                                            Some(TypoSuggestion::from_res(ident.name, crate_mod))
+                                        } else {
+                                            None
+                                        }
+                                    },
+                                )
+                            }));
+
+                            if let Some(prelude) = self.r.prelude {
+                                self.r.add_module_candidates(prelude, &mut names, &filter_fn);
+                            }
+                        }
+                        break;
+                    }
+                }
+            }
+            // Add primitive types to the mix
+            if filter_fn(Res::PrimTy(PrimTy::Bool)) {
+                names.extend(
+                    self.r.primitive_type_table.primitive_types.iter().map(|(name, prim_ty)| {
+                        TypoSuggestion::from_res(*name, Res::PrimTy(*prim_ty))
+                    }),
+                )
+            }
+        } else {
+            // Search in module.
+            let mod_path = &path[..path.len() - 1];
+            if let PathResult::Module(module) =
+                self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No)
+            {
+                if let ModuleOrUniformRoot::Module(module) = module {
+                    self.r.add_module_candidates(module, &mut names, &filter_fn);
+                }
+            }
+        }
+
+        let name = path[path.len() - 1].ident.name;
+        // Make sure error reporting is deterministic.
+        names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
+
+        match find_best_match_for_name(
+            names.iter().map(|suggestion| &suggestion.candidate),
+            name,
+            None,
+        ) {
+            Some(found) if found != name => {
+                names.into_iter().find(|suggestion| suggestion.candidate == found)
+            }
+            _ => None,
+        }
+    }
+
+    /// Only used in a specific case of type ascription suggestions
+    fn get_colon_suggestion_span(&self, start: Span) -> Span {
+        let sm = self.r.session.source_map();
+        start.to(sm.next_point(start))
+    }
+
+    fn type_ascription_suggestion(&self, err: &mut DiagnosticBuilder<'_>, base_span: Span) -> bool {
+        let sm = self.r.session.source_map();
+        let base_snippet = sm.span_to_snippet(base_span);
+        if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
+            if let Ok(snippet) = sm.span_to_snippet(sp) {
+                let len = snippet.trim_end().len() as u32;
+                if snippet.trim() == ":" {
+                    let colon_sp =
+                        sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
+                    let mut show_label = true;
+                    if sm.is_multiline(sp) {
+                        err.span_suggestion_short(
+                            colon_sp,
+                            "maybe you meant to write `;` here",
+                            ";".to_string(),
+                            Applicability::MaybeIncorrect,
+                        );
+                    } else {
+                        let after_colon_sp =
+                            self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
+                        if snippet.len() == 1 {
+                            // `foo:bar`
+                            err.span_suggestion(
+                                colon_sp,
+                                "maybe you meant to write a path separator here",
+                                "::".to_string(),
+                                Applicability::MaybeIncorrect,
+                            );
+                            show_label = false;
+                            if !self
+                                .r
+                                .session
+                                .parse_sess
+                                .type_ascription_path_suggestions
+                                .borrow_mut()
+                                .insert(colon_sp)
+                            {
+                                err.delay_as_bug();
+                            }
+                        }
+                        if let Ok(base_snippet) = base_snippet {
+                            let mut sp = after_colon_sp;
+                            for _ in 0..100 {
+                                // Try to find an assignment
+                                sp = sm.next_point(sp);
+                                let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
+                                match snippet {
+                                    Ok(ref x) if x.as_str() == "=" => {
+                                        err.span_suggestion(
+                                            base_span,
+                                            "maybe you meant to write an assignment here",
+                                            format!("let {}", base_snippet),
+                                            Applicability::MaybeIncorrect,
+                                        );
+                                        show_label = false;
+                                        break;
+                                    }
+                                    Ok(ref x) if x.as_str() == "\n" => break,
+                                    Err(_) => break,
+                                    Ok(_) => {}
+                                }
+                            }
+                        }
+                    }
+                    if show_label {
+                        err.span_label(
+                            base_span,
+                            "expecting a type here because of type ascription",
+                        );
+                    }
+                    return show_label;
+                }
+            }
+        }
+        false
+    }
+
+    fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
+        let mut result = None;
+        let mut seen_modules = FxHashSet::default();
+        let mut worklist = vec![(self.r.graph_root, Vec::new())];
+
+        while let Some((in_module, path_segments)) = worklist.pop() {
+            // abort if the module is already found
+            if result.is_some() {
+                break;
+            }
+
+            in_module.for_each_child(self.r, |_, ident, _, name_binding| {
+                // abort if the module is already found or if name_binding is private external
+                if result.is_some() || !name_binding.vis.is_visible_locally() {
+                    return;
+                }
+                if let Some(module) = name_binding.module() {
+                    // form the path
+                    let mut path_segments = path_segments.clone();
+                    path_segments.push(ast::PathSegment::from_ident(ident));
+                    let module_def_id = module.def_id().unwrap();
+                    if module_def_id == def_id {
+                        let path =
+                            Path { span: name_binding.span, segments: path_segments, tokens: None };
+                        result = Some((
+                            module,
+                            ImportSuggestion {
+                                did: Some(def_id),
+                                descr: "module",
+                                path,
+                                accessible: true,
+                            },
+                        ));
+                    } else {
+                        // add the module to the lookup
+                        if seen_modules.insert(module_def_id) {
+                            worklist.push((module, path_segments));
+                        }
+                    }
+                }
+            });
+        }
+
+        result
+    }
+
+    fn collect_enum_variants(&mut self, def_id: DefId) -> Option<Vec<Path>> {
+        self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
+            let mut variants = Vec::new();
+            enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
+                if let Res::Def(DefKind::Variant, _) = name_binding.res() {
+                    let mut segms = enum_import_suggestion.path.segments.clone();
+                    segms.push(ast::PathSegment::from_ident(ident));
+                    variants.push(Path { span: name_binding.span, segments: segms, tokens: None });
+                }
+            });
+            variants
+        })
+    }
+
+    crate fn report_missing_type_error(
+        &self,
+        path: &[Segment],
+    ) -> Option<(Span, &'static str, String, Applicability)> {
+        let (ident, span) = match path {
+            [segment] if !segment.has_generic_args => {
+                (segment.ident.to_string(), segment.ident.span)
+            }
+            _ => return None,
+        };
+        let mut iter = ident.chars().map(|c| c.is_uppercase());
+        let single_uppercase_char =
+            matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
+        if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
+            return None;
+        }
+        match (self.diagnostic_metadata.current_item, single_uppercase_char) {
+            (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _) if ident.name == sym::main => {
+                // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
+            }
+            (
+                Some(Item {
+                    kind:
+                        kind @ ItemKind::Fn(..)
+                        | kind @ ItemKind::Enum(..)
+                        | kind @ ItemKind::Struct(..)
+                        | kind @ ItemKind::Union(..),
+                    ..
+                }),
+                true,
+            )
+            | (Some(Item { kind, .. }), false) => {
+                // Likely missing type parameter.
+                if let Some(generics) = kind.generics() {
+                    if span.overlaps(generics.span) {
+                        // Avoid the following:
+                        // error[E0405]: cannot find trait `A` in this scope
+                        //  --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
+                        //   |
+                        // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
+                        //   |           ^- help: you might be missing a type parameter: `, A`
+                        //   |           |
+                        //   |           not found in this scope
+                        return None;
+                    }
+                    let msg = "you might be missing a type parameter";
+                    let (span, sugg) = if let [.., param] = &generics.params[..] {
+                        let span = if let [.., bound] = &param.bounds[..] {
+                            bound.span()
+                        } else {
+                            param.ident.span
+                        };
+                        (span, format!(", {}", ident))
+                    } else {
+                        (generics.span, format!("<{}>", ident))
+                    };
+                    // Do not suggest if this is coming from macro expansion.
+                    if !span.from_expansion() {
+                        return Some((
+                            span.shrink_to_hi(),
+                            msg,
+                            sugg,
+                            Applicability::MaybeIncorrect,
+                        ));
+                    }
+                }
+            }
+            _ => {}
+        }
+        None
+    }
+
+    /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
+    /// optionally returning the closest match and whether it is reachable.
+    crate fn suggestion_for_label_in_rib(
+        &self,
+        rib_index: usize,
+        label: Ident,
+    ) -> Option<LabelSuggestion> {
+        // Are ribs from this `rib_index` within scope?
+        let within_scope = self.is_label_valid_from_rib(rib_index);
+
+        let rib = &self.label_ribs[rib_index];
+        let names = rib
+            .bindings
+            .iter()
+            .filter(|(id, _)| id.span.ctxt() == label.span.ctxt())
+            .map(|(id, _)| &id.name);
+
+        find_best_match_for_name(names, label.name, None).map(|symbol| {
+            // Upon finding a similar name, get the ident that it was from - the span
+            // contained within helps make a useful diagnostic. In addition, determine
+            // whether this candidate is within scope.
+            let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
+            (*ident, within_scope)
+        })
+    }
+}
+
+impl<'tcx> LifetimeContext<'_, 'tcx> {
+    crate fn report_missing_lifetime_specifiers(
+        &self,
+        span: Span,
+        count: usize,
+    ) -> DiagnosticBuilder<'tcx> {
+        struct_span_err!(
+            self.tcx.sess,
+            span,
+            E0106,
+            "missing lifetime specifier{}",
+            pluralize!(count)
+        )
+    }
+
+    crate fn emit_undeclared_lifetime_error(&self, lifetime_ref: &hir::Lifetime) {
+        let mut err = struct_span_err!(
+            self.tcx.sess,
+            lifetime_ref.span,
+            E0261,
+            "use of undeclared lifetime name `{}`",
+            lifetime_ref
+        );
+        err.span_label(lifetime_ref.span, "undeclared lifetime");
+        let mut suggests_in_band = false;
+        for missing in &self.missing_named_lifetime_spots {
+            match missing {
+                MissingLifetimeSpot::Generics(generics) => {
+                    let (span, sugg) = if let Some(param) =
+                        generics.params.iter().find(|p| match p.kind {
+                            hir::GenericParamKind::Type {
+                                synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
+                                ..
+                            } => false,
+                            hir::GenericParamKind::Lifetime {
+                                kind: hir::LifetimeParamKind::Elided,
+                            } => false,
+                            _ => true,
+                        }) {
+                        (param.span.shrink_to_lo(), format!("{}, ", lifetime_ref))
+                    } else {
+                        suggests_in_band = true;
+                        (generics.span, format!("<{}>", lifetime_ref))
+                    };
+                    err.span_suggestion(
+                        span,
+                        &format!("consider introducing lifetime `{}` here", lifetime_ref),
+                        sugg,
+                        Applicability::MaybeIncorrect,
+                    );
+                }
+                MissingLifetimeSpot::HigherRanked { span, span_type } => {
+                    err.span_suggestion(
+                        *span,
+                        &format!(
+                            "consider making the {} lifetime-generic with a new `{}` lifetime",
+                            span_type.descr(),
+                            lifetime_ref
+                        ),
+                        span_type.suggestion(&lifetime_ref.to_string()),
+                        Applicability::MaybeIncorrect,
+                    );
+                    err.note(
+                        "for more information on higher-ranked polymorphism, visit \
+                            https://doc.rust-lang.org/nomicon/hrtb.html",
+                    );
+                }
+                _ => {}
+            }
+        }
+        if nightly_options::is_nightly_build()
+            && !self.tcx.features().in_band_lifetimes
+            && suggests_in_band
+        {
+            err.help(
+                "if you want to experiment with in-band lifetime bindings, \
+                    add `#![feature(in_band_lifetimes)]` to the crate attributes",
+            );
+        }
+        err.emit();
+    }
+
+    // FIXME(const_generics): This patches over a ICE caused by non-'static lifetimes in const
+    // generics. We are disallowing this until we can decide on how we want to handle non-'static
+    // lifetimes in const generics. See issue #74052 for discussion.
+    crate fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &hir::Lifetime) {
+        let mut err = struct_span_err!(
+            self.tcx.sess,
+            lifetime_ref.span,
+            E0771,
+            "use of non-static lifetime `{}` in const generic",
+            lifetime_ref
+        );
+        err.note(
+            "for more information, see issue #74052 \
+            <https://github.com/rust-lang/rust/issues/74052>",
+        );
+        err.emit();
+    }
+
+    crate fn is_trait_ref_fn_scope(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) -> bool {
+        if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
+            if [
+                self.tcx.lang_items().fn_once_trait(),
+                self.tcx.lang_items().fn_trait(),
+                self.tcx.lang_items().fn_mut_trait(),
+            ]
+            .contains(&Some(did))
+            {
+                let (span, span_type) = match &trait_ref.bound_generic_params {
+                    [] => (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty),
+                    [.., bound] => (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail),
+                };
+                self.missing_named_lifetime_spots
+                    .push(MissingLifetimeSpot::HigherRanked { span, span_type });
+                return true;
+            }
+        };
+        false
+    }
+
+    crate fn add_missing_lifetime_specifiers_label(
+        &self,
+        err: &mut DiagnosticBuilder<'_>,
+        span: Span,
+        count: usize,
+        lifetime_names: &FxHashSet<Symbol>,
+        lifetime_spans: Vec<Span>,
+        params: &[ElisionFailureInfo],
+    ) {
+        let snippet = self.tcx.sess.source_map().span_to_snippet(span).ok();
+
+        err.span_label(
+            span,
+            &format!(
+                "expected {} lifetime parameter{}",
+                if count == 1 { "named".to_string() } else { count.to_string() },
+                pluralize!(count)
+            ),
+        );
+
+        let suggest_existing = |err: &mut DiagnosticBuilder<'_>,
+                                name: &str,
+                                formatter: &dyn Fn(&str) -> String| {
+            if let Some(MissingLifetimeSpot::HigherRanked { span: for_span, span_type }) =
+                self.missing_named_lifetime_spots.iter().rev().next()
+            {
+                // When we have `struct S<'a>(&'a dyn Fn(&X) -> &X);` we want to not only suggest
+                // using `'a`, but also introduce the concept of HRLTs by suggesting
+                // `struct S<'a>(&'a dyn for<'b> Fn(&X) -> &'b X);`. (#72404)
+                let mut introduce_suggestion = vec![];
+
+                let a_to_z_repeat_n = |n| {
+                    (b'a'..=b'z').map(move |c| {
+                        let mut s = '\''.to_string();
+                        s.extend(std::iter::repeat(char::from(c)).take(n));
+                        s
+                    })
+                };
+
+                // If all single char lifetime names are present, we wrap around and double the chars.
+                let lt_name = (1..)
+                    .flat_map(a_to_z_repeat_n)
+                    .find(|lt| !lifetime_names.contains(&Symbol::intern(&lt)))
+                    .unwrap();
+                let msg = format!(
+                    "consider making the {} lifetime-generic with a new `{}` lifetime",
+                    span_type.descr(),
+                    lt_name,
+                );
+                err.note(
+                    "for more information on higher-ranked polymorphism, visit \
+                    https://doc.rust-lang.org/nomicon/hrtb.html",
+                );
+                let for_sugg = span_type.suggestion(&lt_name);
+                for param in params {
+                    if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
+                        if snippet.starts_with('&') && !snippet.starts_with("&'") {
+                            introduce_suggestion
+                                .push((param.span, format!("&{} {}", lt_name, &snippet[1..])));
+                        } else if let Some(stripped) = snippet.strip_prefix("&'_ ") {
+                            introduce_suggestion
+                                .push((param.span, format!("&{} {}", lt_name, stripped)));
+                        }
+                    }
+                }
+                introduce_suggestion.push((*for_span, for_sugg));
+                introduce_suggestion.push((span, formatter(&lt_name)));
+                err.multipart_suggestion(&msg, introduce_suggestion, Applicability::MaybeIncorrect);
+            }
+
+            err.span_suggestion_verbose(
+                span,
+                &format!("consider using the `{}` lifetime", lifetime_names.iter().next().unwrap()),
+                formatter(name),
+                Applicability::MaybeIncorrect,
+            );
+        };
+        let suggest_new = |err: &mut DiagnosticBuilder<'_>, sugg: &str| {
+            for missing in self.missing_named_lifetime_spots.iter().rev() {
+                let mut introduce_suggestion = vec![];
+                let msg;
+                let should_break;
+                introduce_suggestion.push(match missing {
+                    MissingLifetimeSpot::Generics(generics) => {
+                        if generics.span == DUMMY_SP {
+                            // Account for malformed generics in the HIR. This shouldn't happen,
+                            // but if we make a mistake elsewhere, mainly by keeping something in
+                            // `missing_named_lifetime_spots` that we shouldn't, like associated
+                            // `const`s or making a mistake in the AST lowering we would provide
+                            // non-sensical suggestions. Guard against that by skipping these.
+                            // (#74264)
+                            continue;
+                        }
+                        msg = "consider introducing a named lifetime parameter".to_string();
+                        should_break = true;
+                        if let Some(param) = generics.params.iter().find(|p| match p.kind {
+                            hir::GenericParamKind::Type {
+                                synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
+                                ..
+                            } => false,
+                            _ => true,
+                        }) {
+                            (param.span.shrink_to_lo(), "'a, ".to_string())
+                        } else {
+                            (generics.span, "<'a>".to_string())
+                        }
+                    }
+                    MissingLifetimeSpot::HigherRanked { span, span_type } => {
+                        msg = format!(
+                            "consider making the {} lifetime-generic with a new `'a` lifetime",
+                            span_type.descr(),
+                        );
+                        should_break = false;
+                        err.note(
+                            "for more information on higher-ranked polymorphism, visit \
+                            https://doc.rust-lang.org/nomicon/hrtb.html",
+                        );
+                        (*span, span_type.suggestion("'a"))
+                    }
+                    MissingLifetimeSpot::Static => {
+                        let (span, sugg) = match snippet.as_deref() {
+                            Some("&") => (span.shrink_to_hi(), "'static ".to_owned()),
+                            Some("'_") => (span, "'static".to_owned()),
+                            Some(snippet) if !snippet.ends_with('>') => {
+                                if snippet == "" {
+                                    (
+                                        span,
+                                        std::iter::repeat("'static")
+                                            .take(count)
+                                            .collect::<Vec<_>>()
+                                            .join(", "),
+                                    )
+                                } else {
+                                    (
+                                        span.shrink_to_hi(),
+                                        format!(
+                                            "<{}>",
+                                            std::iter::repeat("'static")
+                                                .take(count)
+                                                .collect::<Vec<_>>()
+                                                .join(", ")
+                                        ),
+                                    )
+                                }
+                            }
+                            _ => continue,
+                        };
+                        err.span_suggestion_verbose(
+                            span,
+                            "consider using the `'static` lifetime",
+                            sugg.to_string(),
+                            Applicability::MaybeIncorrect,
+                        );
+                        continue;
+                    }
+                });
+                for param in params {
+                    if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
+                        if snippet.starts_with('&') && !snippet.starts_with("&'") {
+                            introduce_suggestion
+                                .push((param.span, format!("&'a {}", &snippet[1..])));
+                        } else if snippet.starts_with("&'_ ") {
+                            introduce_suggestion
+                                .push((param.span, format!("&'a {}", &snippet[4..])));
+                        }
+                    }
+                }
+                introduce_suggestion.push((span, sugg.to_string()));
+                err.multipart_suggestion(&msg, introduce_suggestion, Applicability::MaybeIncorrect);
+                if should_break {
+                    break;
+                }
+            }
+        };
+
+        let lifetime_names: Vec<_> = lifetime_names.iter().collect();
+        match (&lifetime_names[..], snippet.as_deref()) {
+            ([name], Some("&")) => {
+                suggest_existing(err, &name.as_str()[..], &|name| format!("&{} ", name));
+            }
+            ([name], Some("'_")) => {
+                suggest_existing(err, &name.as_str()[..], &|n| n.to_string());
+            }
+            ([name], Some("")) => {
+                suggest_existing(err, &name.as_str()[..], &|n| format!("{}, ", n).repeat(count));
+            }
+            ([name], Some(snippet)) if !snippet.ends_with('>') => {
+                let f = |name: &str| {
+                    format!(
+                        "{}<{}>",
+                        snippet,
+                        std::iter::repeat(name.to_string())
+                            .take(count)
+                            .collect::<Vec<_>>()
+                            .join(", ")
+                    )
+                };
+                suggest_existing(err, &name.as_str()[..], &f);
+            }
+            ([], Some("&")) if count == 1 => {
+                suggest_new(err, "&'a ");
+            }
+            ([], Some("'_")) if count == 1 => {
+                suggest_new(err, "'a");
+            }
+            ([], Some(snippet)) if !snippet.ends_with('>') => {
+                if snippet == "" {
+                    // This happens when we have `type Bar<'a> = Foo<T>` where we point at the space
+                    // before `T`. We will suggest `type Bar<'a> = Foo<'a, T>`.
+                    suggest_new(
+                        err,
+                        &std::iter::repeat("'a, ").take(count).collect::<Vec<_>>().join(""),
+                    );
+                } else {
+                    suggest_new(
+                        err,
+                        &format!(
+                            "{}<{}>",
+                            snippet,
+                            std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", ")
+                        ),
+                    );
+                }
+            }
+            (lts, ..) if lts.len() > 1 => {
+                err.span_note(lifetime_spans, "these named lifetimes are available to use");
+                if Some("") == snippet.as_deref() {
+                    // This happens when we have `Foo<T>` where we point at the space before `T`,
+                    // but this can be confusing so we give a suggestion with placeholders.
+                    err.span_suggestion_verbose(
+                        span,
+                        "consider using one of the available lifetimes here",
+                        "'lifetime, ".repeat(count),
+                        Applicability::HasPlaceholders,
+                    );
+                }
+            }
+            _ => {}
+        }
+    }
+
+    /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics` so
+    /// this function will emit an error if `min_const_generics` is enabled, the body identified by
+    /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
+    crate fn maybe_emit_forbidden_non_static_lifetime_error(
+        &self,
+        body_id: hir::BodyId,
+        lifetime_ref: &'tcx hir::Lifetime,
+    ) {
+        let is_anon_const = matches!(
+            self.tcx.def_kind(self.tcx.hir().body_owner_def_id(body_id)),
+            hir::def::DefKind::AnonConst
+        );
+        let is_allowed_lifetime = matches!(
+            lifetime_ref.name,
+            hir::LifetimeName::Implicit | hir::LifetimeName::Static | hir::LifetimeName::Underscore
+        );
+
+        if self.tcx.features().min_const_generics && is_anon_const && !is_allowed_lifetime {
+            feature_err(
+                &self.tcx.sess.parse_sess,
+                sym::const_generics,
+                lifetime_ref.span,
+                "a non-static lifetime is not allowed in a `const`",
+            )
+            .emit();
+        }
+    }
+}
diff --git a/compiler/rustc_resolve/src/late/lifetimes.rs b/compiler/rustc_resolve/src/late/lifetimes.rs
new file mode 100644
index 0000000..072fb50
--- /dev/null
+++ b/compiler/rustc_resolve/src/late/lifetimes.rs
@@ -0,0 +1,2910 @@
+//! Name resolution for lifetimes.
+//!
+//! Name resolution for lifetimes follows *much* simpler rules than the
+//! full resolve. For example, lifetime names are never exported or
+//! used between functions, and they operate in a purely top-down
+//! way. Therefore, we break lifetime name resolution into a separate pass.
+
+use crate::late::diagnostics::{ForLifetimeSpanType, MissingLifetimeSpot};
+use rustc_ast::walk_list;
+use rustc_data_structures::fx::{FxHashMap, FxHashSet};
+use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
+use rustc_hir as hir;
+use rustc_hir::def::{DefKind, Res};
+use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LOCAL_CRATE};
+use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
+use rustc_hir::{GenericArg, GenericParam, LifetimeName, Node, ParamName, QPath};
+use rustc_hir::{GenericParamKind, HirIdMap, HirIdSet, LifetimeParamKind};
+use rustc_middle::hir::map::Map;
+use rustc_middle::middle::resolve_lifetime::*;
+use rustc_middle::ty::{self, DefIdTree, GenericParamDefKind, TyCtxt};
+use rustc_middle::{bug, span_bug};
+use rustc_session::lint;
+use rustc_span::symbol::{kw, sym, Ident, Symbol};
+use rustc_span::Span;
+use std::borrow::Cow;
+use std::cell::Cell;
+use std::mem::take;
+
+use tracing::debug;
+
+// This counts the no of times a lifetime is used
+#[derive(Clone, Copy, Debug)]
+pub enum LifetimeUseSet<'tcx> {
+    One(&'tcx hir::Lifetime),
+    Many,
+}
+
+trait RegionExt {
+    fn early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (ParamName, Region);
+
+    fn late(hir_map: &Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region);
+
+    fn late_anon(index: &Cell<u32>) -> Region;
+
+    fn id(&self) -> Option<DefId>;
+
+    fn shifted(self, amount: u32) -> Region;
+
+    fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region;
+
+    fn subst<'a, L>(self, params: L, map: &NamedRegionMap) -> Option<Region>
+    where
+        L: Iterator<Item = &'a hir::Lifetime>;
+}
+
+impl RegionExt for Region {
+    fn early(hir_map: &Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (ParamName, Region) {
+        let i = *index;
+        *index += 1;
+        let def_id = hir_map.local_def_id(param.hir_id);
+        let origin = LifetimeDefOrigin::from_param(param);
+        debug!("Region::early: index={} def_id={:?}", i, def_id);
+        (param.name.normalize_to_macros_2_0(), Region::EarlyBound(i, def_id.to_def_id(), origin))
+    }
+
+    fn late(hir_map: &Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region) {
+        let depth = ty::INNERMOST;
+        let def_id = hir_map.local_def_id(param.hir_id);
+        let origin = LifetimeDefOrigin::from_param(param);
+        debug!(
+            "Region::late: param={:?} depth={:?} def_id={:?} origin={:?}",
+            param, depth, def_id, origin,
+        );
+        (param.name.normalize_to_macros_2_0(), Region::LateBound(depth, def_id.to_def_id(), origin))
+    }
+
+    fn late_anon(index: &Cell<u32>) -> Region {
+        let i = index.get();
+        index.set(i + 1);
+        let depth = ty::INNERMOST;
+        Region::LateBoundAnon(depth, i)
+    }
+
+    fn id(&self) -> Option<DefId> {
+        match *self {
+            Region::Static | Region::LateBoundAnon(..) => None,
+
+            Region::EarlyBound(_, id, _) | Region::LateBound(_, id, _) | Region::Free(_, id) => {
+                Some(id)
+            }
+        }
+    }
+
+    fn shifted(self, amount: u32) -> Region {
+        match self {
+            Region::LateBound(debruijn, id, origin) => {
+                Region::LateBound(debruijn.shifted_in(amount), id, origin)
+            }
+            Region::LateBoundAnon(debruijn, index) => {
+                Region::LateBoundAnon(debruijn.shifted_in(amount), index)
+            }
+            _ => self,
+        }
+    }
+
+    fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region {
+        match self {
+            Region::LateBound(debruijn, id, origin) => {
+                Region::LateBound(debruijn.shifted_out_to_binder(binder), id, origin)
+            }
+            Region::LateBoundAnon(debruijn, index) => {
+                Region::LateBoundAnon(debruijn.shifted_out_to_binder(binder), index)
+            }
+            _ => self,
+        }
+    }
+
+    fn subst<'a, L>(self, mut params: L, map: &NamedRegionMap) -> Option<Region>
+    where
+        L: Iterator<Item = &'a hir::Lifetime>,
+    {
+        if let Region::EarlyBound(index, _, _) = self {
+            params.nth(index as usize).and_then(|lifetime| map.defs.get(&lifetime.hir_id).cloned())
+        } else {
+            Some(self)
+        }
+    }
+}
+
+/// Maps the id of each lifetime reference to the lifetime decl
+/// that it corresponds to.
+///
+/// FIXME. This struct gets converted to a `ResolveLifetimes` for
+/// actual use. It has the same data, but indexed by `LocalDefId`.  This
+/// is silly.
+#[derive(Default)]
+struct NamedRegionMap {
+    // maps from every use of a named (not anonymous) lifetime to a
+    // `Region` describing how that region is bound
+    defs: HirIdMap<Region>,
+
+    // the set of lifetime def ids that are late-bound; a region can
+    // be late-bound if (a) it does NOT appear in a where-clause and
+    // (b) it DOES appear in the arguments.
+    late_bound: HirIdSet,
+
+    // For each type and trait definition, maps type parameters
+    // to the trait object lifetime defaults computed from them.
+    object_lifetime_defaults: HirIdMap<Vec<ObjectLifetimeDefault>>,
+}
+
+crate struct LifetimeContext<'a, 'tcx> {
+    crate tcx: TyCtxt<'tcx>,
+    map: &'a mut NamedRegionMap,
+    scope: ScopeRef<'a>,
+
+    /// This is slightly complicated. Our representation for poly-trait-refs contains a single
+    /// binder and thus we only allow a single level of quantification. However,
+    /// the syntax of Rust permits quantification in two places, e.g., `T: for <'a> Foo<'a>`
+    /// and `for <'a, 'b> &'b T: Foo<'a>`. In order to get the De Bruijn indices
+    /// correct when representing these constraints, we should only introduce one
+    /// scope. However, we want to support both locations for the quantifier and
+    /// during lifetime resolution we want precise information (so we can't
+    /// desugar in an earlier phase).
+    ///
+    /// So, if we encounter a quantifier at the outer scope, we set
+    /// `trait_ref_hack` to `true` (and introduce a scope), and then if we encounter
+    /// a quantifier at the inner scope, we error. If `trait_ref_hack` is `false`,
+    /// then we introduce the scope at the inner quantifier.
+    trait_ref_hack: bool,
+
+    /// Used to disallow the use of in-band lifetimes in `fn` or `Fn` syntax.
+    is_in_fn_syntax: bool,
+
+    is_in_const_generic: bool,
+
+    /// List of labels in the function/method currently under analysis.
+    labels_in_fn: Vec<Ident>,
+
+    /// Cache for cross-crate per-definition object lifetime defaults.
+    xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>,
+
+    lifetime_uses: &'a mut DefIdMap<LifetimeUseSet<'tcx>>,
+
+    /// When encountering an undefined named lifetime, we will suggest introducing it in these
+    /// places.
+    crate missing_named_lifetime_spots: Vec<MissingLifetimeSpot<'tcx>>,
+}
+
+#[derive(Debug)]
+enum Scope<'a> {
+    /// Declares lifetimes, and each can be early-bound or late-bound.
+    /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
+    /// it should be shifted by the number of `Binder`s in between the
+    /// declaration `Binder` and the location it's referenced from.
+    Binder {
+        lifetimes: FxHashMap<hir::ParamName, Region>,
+
+        /// if we extend this scope with another scope, what is the next index
+        /// we should use for an early-bound region?
+        next_early_index: u32,
+
+        /// Flag is set to true if, in this binder, `'_` would be
+        /// equivalent to a "single-use region". This is true on
+        /// impls, but not other kinds of items.
+        track_lifetime_uses: bool,
+
+        /// Whether or not this binder would serve as the parent
+        /// binder for opaque types introduced within. For example:
+        ///
+        /// ```text
+        ///     fn foo<'a>() -> impl for<'b> Trait<Item = impl Trait2<'a>>
+        /// ```
+        ///
+        /// Here, the opaque types we create for the `impl Trait`
+        /// and `impl Trait2` references will both have the `foo` item
+        /// as their parent. When we get to `impl Trait2`, we find
+        /// that it is nested within the `for<>` binder -- this flag
+        /// allows us to skip that when looking for the parent binder
+        /// of the resulting opaque type.
+        opaque_type_parent: bool,
+
+        s: ScopeRef<'a>,
+    },
+
+    /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
+    /// if this is a fn body, otherwise the original definitions are used.
+    /// Unspecified lifetimes are inferred, unless an elision scope is nested,
+    /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
+    Body {
+        id: hir::BodyId,
+        s: ScopeRef<'a>,
+    },
+
+    /// A scope which either determines unspecified lifetimes or errors
+    /// on them (e.g., due to ambiguity). For more details, see `Elide`.
+    Elision {
+        elide: Elide,
+        s: ScopeRef<'a>,
+    },
+
+    /// Use a specific lifetime (if `Some`) or leave it unset (to be
+    /// inferred in a function body or potentially error outside one),
+    /// for the default choice of lifetime in a trait object type.
+    ObjectLifetimeDefault {
+        lifetime: Option<Region>,
+        s: ScopeRef<'a>,
+    },
+
+    Root,
+}
+
+#[derive(Clone, Debug)]
+enum Elide {
+    /// Use a fresh anonymous late-bound lifetime each time, by
+    /// incrementing the counter to generate sequential indices.
+    FreshLateAnon(Cell<u32>),
+    /// Always use this one lifetime.
+    Exact(Region),
+    /// Less or more than one lifetime were found, error on unspecified.
+    Error(Vec<ElisionFailureInfo>),
+    /// Forbid lifetime elision inside of a larger scope where it would be
+    /// permitted. For example, in let position impl trait.
+    Forbid,
+}
+
+#[derive(Clone, Debug)]
+crate struct ElisionFailureInfo {
+    /// Where we can find the argument pattern.
+    parent: Option<hir::BodyId>,
+    /// The index of the argument in the original definition.
+    index: usize,
+    lifetime_count: usize,
+    have_bound_regions: bool,
+    crate span: Span,
+}
+
+type ScopeRef<'a> = &'a Scope<'a>;
+
+const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
+
+pub fn provide(providers: &mut ty::query::Providers) {
+    *providers = ty::query::Providers {
+        resolve_lifetimes,
+
+        named_region_map: |tcx, id| tcx.resolve_lifetimes(LOCAL_CRATE).defs.get(&id),
+        is_late_bound_map: |tcx, id| tcx.resolve_lifetimes(LOCAL_CRATE).late_bound.get(&id),
+        object_lifetime_defaults_map: |tcx, id| {
+            tcx.resolve_lifetimes(LOCAL_CRATE).object_lifetime_defaults.get(&id)
+        },
+
+        ..*providers
+    };
+}
+
+/// Computes the `ResolveLifetimes` map that contains data for the
+/// entire crate. You should not read the result of this query
+/// directly, but rather use `named_region_map`, `is_late_bound_map`,
+/// etc.
+fn resolve_lifetimes(tcx: TyCtxt<'_>, for_krate: CrateNum) -> ResolveLifetimes {
+    assert_eq!(for_krate, LOCAL_CRATE);
+
+    let named_region_map = krate(tcx);
+
+    let mut rl = ResolveLifetimes::default();
+
+    for (hir_id, v) in named_region_map.defs {
+        let map = rl.defs.entry(hir_id.owner).or_default();
+        map.insert(hir_id.local_id, v);
+    }
+    for hir_id in named_region_map.late_bound {
+        let map = rl.late_bound.entry(hir_id.owner).or_default();
+        map.insert(hir_id.local_id);
+    }
+    for (hir_id, v) in named_region_map.object_lifetime_defaults {
+        let map = rl.object_lifetime_defaults.entry(hir_id.owner).or_default();
+        map.insert(hir_id.local_id, v);
+    }
+
+    rl
+}
+
+fn krate(tcx: TyCtxt<'_>) -> NamedRegionMap {
+    let krate = tcx.hir().krate();
+    let mut map = NamedRegionMap {
+        defs: Default::default(),
+        late_bound: Default::default(),
+        object_lifetime_defaults: compute_object_lifetime_defaults(tcx),
+    };
+    {
+        let mut visitor = LifetimeContext {
+            tcx,
+            map: &mut map,
+            scope: ROOT_SCOPE,
+            trait_ref_hack: false,
+            is_in_fn_syntax: false,
+            is_in_const_generic: false,
+            labels_in_fn: vec![],
+            xcrate_object_lifetime_defaults: Default::default(),
+            lifetime_uses: &mut Default::default(),
+            missing_named_lifetime_spots: vec![],
+        };
+        for item in krate.items.values() {
+            visitor.visit_item(item);
+        }
+    }
+    map
+}
+
+/// In traits, there is an implicit `Self` type parameter which comes before the generics.
+/// We have to account for this when computing the index of the other generic parameters.
+/// This function returns whether there is such an implicit parameter defined on the given item.
+fn sub_items_have_self_param(node: &hir::ItemKind<'_>) -> bool {
+    match *node {
+        hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => true,
+        _ => false,
+    }
+}
+
+impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
+    type Map = Map<'tcx>;
+
+    fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+        NestedVisitorMap::All(self.tcx.hir())
+    }
+
+    // We want to nest trait/impl items in their parent, but nothing else.
+    fn visit_nested_item(&mut self, _: hir::ItemId) {}
+
+    fn visit_nested_body(&mut self, body: hir::BodyId) {
+        // Each body has their own set of labels, save labels.
+        let saved = take(&mut self.labels_in_fn);
+        let body = self.tcx.hir().body(body);
+        extract_labels(self, body);
+        self.with(Scope::Body { id: body.id(), s: self.scope }, |_, this| {
+            this.visit_body(body);
+        });
+        self.labels_in_fn = saved;
+    }
+
+    fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
+        match item.kind {
+            hir::ItemKind::Fn(ref sig, ref generics, _) => {
+                self.missing_named_lifetime_spots.push(generics.into());
+                self.visit_early_late(None, &sig.decl, generics, |this| {
+                    intravisit::walk_item(this, item);
+                });
+                self.missing_named_lifetime_spots.pop();
+            }
+
+            hir::ItemKind::ExternCrate(_)
+            | hir::ItemKind::Use(..)
+            | hir::ItemKind::Mod(..)
+            | hir::ItemKind::ForeignMod(..)
+            | hir::ItemKind::GlobalAsm(..) => {
+                // These sorts of items have no lifetime parameters at all.
+                intravisit::walk_item(self, item);
+            }
+            hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
+                // No lifetime parameters, but implied 'static.
+                let scope = Scope::Elision { elide: Elide::Exact(Region::Static), s: ROOT_SCOPE };
+                self.with(scope, |_, this| intravisit::walk_item(this, item));
+            }
+            hir::ItemKind::OpaqueTy(hir::OpaqueTy { .. }) => {
+                // Opaque types are visited when we visit the
+                // `TyKind::OpaqueDef`, so that they have the lifetimes from
+                // their parent opaque_ty in scope.
+            }
+            hir::ItemKind::TyAlias(_, ref generics)
+            | hir::ItemKind::Enum(_, ref generics)
+            | hir::ItemKind::Struct(_, ref generics)
+            | hir::ItemKind::Union(_, ref generics)
+            | hir::ItemKind::Trait(_, _, ref generics, ..)
+            | hir::ItemKind::TraitAlias(ref generics, ..)
+            | hir::ItemKind::Impl { ref generics, .. } => {
+                self.missing_named_lifetime_spots.push(generics.into());
+
+                // Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name".
+                // This is not true for other kinds of items.x
+                let track_lifetime_uses = match item.kind {
+                    hir::ItemKind::Impl { .. } => true,
+                    _ => false,
+                };
+                // These kinds of items have only early-bound lifetime parameters.
+                let mut index = if sub_items_have_self_param(&item.kind) {
+                    1 // Self comes before lifetimes
+                } else {
+                    0
+                };
+                let mut non_lifetime_count = 0;
+                let lifetimes = generics
+                    .params
+                    .iter()
+                    .filter_map(|param| match param.kind {
+                        GenericParamKind::Lifetime { .. } => {
+                            Some(Region::early(&self.tcx.hir(), &mut index, param))
+                        }
+                        GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
+                            non_lifetime_count += 1;
+                            None
+                        }
+                    })
+                    .collect();
+                let scope = Scope::Binder {
+                    lifetimes,
+                    next_early_index: index + non_lifetime_count,
+                    opaque_type_parent: true,
+                    track_lifetime_uses,
+                    s: ROOT_SCOPE,
+                };
+                self.with(scope, |old_scope, this| {
+                    this.check_lifetime_params(old_scope, &generics.params);
+                    intravisit::walk_item(this, item);
+                });
+                self.missing_named_lifetime_spots.pop();
+            }
+        }
+    }
+
+    fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
+        match item.kind {
+            hir::ForeignItemKind::Fn(ref decl, _, ref generics) => {
+                self.visit_early_late(None, decl, generics, |this| {
+                    intravisit::walk_foreign_item(this, item);
+                })
+            }
+            hir::ForeignItemKind::Static(..) => {
+                intravisit::walk_foreign_item(self, item);
+            }
+            hir::ForeignItemKind::Type => {
+                intravisit::walk_foreign_item(self, item);
+            }
+        }
+    }
+
+    fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
+        debug!("visit_ty: id={:?} ty={:?}", ty.hir_id, ty);
+        debug!("visit_ty: ty.kind={:?}", ty.kind);
+        match ty.kind {
+            hir::TyKind::BareFn(ref c) => {
+                let next_early_index = self.next_early_index();
+                let was_in_fn_syntax = self.is_in_fn_syntax;
+                self.is_in_fn_syntax = true;
+                let lifetime_span: Option<Span> =
+                    c.generic_params.iter().rev().find_map(|param| match param.kind {
+                        GenericParamKind::Lifetime { .. } => Some(param.span),
+                        _ => None,
+                    });
+                let (span, span_type) = if let Some(span) = lifetime_span {
+                    (span.shrink_to_hi(), ForLifetimeSpanType::TypeTail)
+                } else {
+                    (ty.span.shrink_to_lo(), ForLifetimeSpanType::TypeEmpty)
+                };
+                self.missing_named_lifetime_spots
+                    .push(MissingLifetimeSpot::HigherRanked { span, span_type });
+                let scope = Scope::Binder {
+                    lifetimes: c
+                        .generic_params
+                        .iter()
+                        .filter_map(|param| match param.kind {
+                            GenericParamKind::Lifetime { .. } => {
+                                Some(Region::late(&self.tcx.hir(), param))
+                            }
+                            _ => None,
+                        })
+                        .collect(),
+                    s: self.scope,
+                    next_early_index,
+                    track_lifetime_uses: true,
+                    opaque_type_parent: false,
+                };
+                self.with(scope, |old_scope, this| {
+                    // a bare fn has no bounds, so everything
+                    // contained within is scoped within its binder.
+                    this.check_lifetime_params(old_scope, &c.generic_params);
+                    intravisit::walk_ty(this, ty);
+                });
+                self.missing_named_lifetime_spots.pop();
+                self.is_in_fn_syntax = was_in_fn_syntax;
+            }
+            hir::TyKind::TraitObject(bounds, ref lifetime) => {
+                debug!("visit_ty: TraitObject(bounds={:?}, lifetime={:?})", bounds, lifetime);
+                for bound in bounds {
+                    self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
+                }
+                match lifetime.name {
+                    LifetimeName::Implicit => {
+                        // For types like `dyn Foo`, we should
+                        // generate a special form of elided.
+                        span_bug!(ty.span, "object-lifetime-default expected, not implicit",);
+                    }
+                    LifetimeName::ImplicitObjectLifetimeDefault => {
+                        // If the user does not write *anything*, we
+                        // use the object lifetime defaulting
+                        // rules. So e.g., `Box<dyn Debug>` becomes
+                        // `Box<dyn Debug + 'static>`.
+                        self.resolve_object_lifetime_default(lifetime)
+                    }
+                    LifetimeName::Underscore => {
+                        // If the user writes `'_`, we use the *ordinary* elision
+                        // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
+                        // resolved the same as the `'_` in `&'_ Foo`.
+                        //
+                        // cc #48468
+                        self.resolve_elided_lifetimes(vec![lifetime])
+                    }
+                    LifetimeName::Param(_) | LifetimeName::Static => {
+                        // If the user wrote an explicit name, use that.
+                        self.visit_lifetime(lifetime);
+                    }
+                    LifetimeName::Error => {}
+                }
+            }
+            hir::TyKind::Rptr(ref lifetime_ref, ref mt) => {
+                self.visit_lifetime(lifetime_ref);
+                let scope = Scope::ObjectLifetimeDefault {
+                    lifetime: self.map.defs.get(&lifetime_ref.hir_id).cloned(),
+                    s: self.scope,
+                };
+                self.with(scope, |_, this| this.visit_ty(&mt.ty));
+            }
+            hir::TyKind::OpaqueDef(item_id, lifetimes) => {
+                // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
+                // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
+                // `type MyAnonTy<'b> = impl MyTrait<'b>;`
+                //                 ^                  ^ this gets resolved in the scope of
+                //                                      the opaque_ty generics
+                let opaque_ty = self.tcx.hir().expect_item(item_id.id);
+                let (generics, bounds) = match opaque_ty.kind {
+                    // Named opaque `impl Trait` types are reached via `TyKind::Path`.
+                    // This arm is for `impl Trait` in the types of statics, constants and locals.
+                    hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: None, .. }) => {
+                        intravisit::walk_ty(self, ty);
+
+                        // Elided lifetimes are not allowed in non-return
+                        // position impl Trait
+                        let scope = Scope::Elision { elide: Elide::Forbid, s: self.scope };
+                        self.with(scope, |_, this| {
+                            intravisit::walk_item(this, opaque_ty);
+                        });
+
+                        return;
+                    }
+                    // RPIT (return position impl trait)
+                    hir::ItemKind::OpaqueTy(hir::OpaqueTy {
+                        impl_trait_fn: Some(_),
+                        ref generics,
+                        bounds,
+                        ..
+                    }) => (generics, bounds),
+                    ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
+                };
+
+                // Resolve the lifetimes that are applied to the opaque type.
+                // These are resolved in the current scope.
+                // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
+                // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
+                //          ^                 ^this gets resolved in the current scope
+                for lifetime in lifetimes {
+                    if let hir::GenericArg::Lifetime(lifetime) = lifetime {
+                        self.visit_lifetime(lifetime);
+
+                        // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
+                        // and ban them. Type variables instantiated inside binders aren't
+                        // well-supported at the moment, so this doesn't work.
+                        // In the future, this should be fixed and this error should be removed.
+                        let def = self.map.defs.get(&lifetime.hir_id).cloned();
+                        if let Some(Region::LateBound(_, def_id, _)) = def {
+                            if let Some(def_id) = def_id.as_local() {
+                                let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
+                                // Ensure that the parent of the def is an item, not HRTB
+                                let parent_id = self.tcx.hir().get_parent_node(hir_id);
+                                let parent_impl_id = hir::ImplItemId { hir_id: parent_id };
+                                let parent_trait_id = hir::TraitItemId { hir_id: parent_id };
+                                let krate = self.tcx.hir().krate();
+
+                                if !(krate.items.contains_key(&parent_id)
+                                    || krate.impl_items.contains_key(&parent_impl_id)
+                                    || krate.trait_items.contains_key(&parent_trait_id))
+                                {
+                                    struct_span_err!(
+                                        self.tcx.sess,
+                                        lifetime.span,
+                                        E0657,
+                                        "`impl Trait` can only capture lifetimes \
+                                         bound at the fn or impl level"
+                                    )
+                                    .emit();
+                                    self.uninsert_lifetime_on_error(lifetime, def.unwrap());
+                                }
+                            }
+                        }
+                    }
+                }
+
+                // We want to start our early-bound indices at the end of the parent scope,
+                // not including any parent `impl Trait`s.
+                let mut index = self.next_early_index_for_opaque_type();
+                debug!("visit_ty: index = {}", index);
+
+                let mut elision = None;
+                let mut lifetimes = FxHashMap::default();
+                let mut non_lifetime_count = 0;
+                for param in generics.params {
+                    match param.kind {
+                        GenericParamKind::Lifetime { .. } => {
+                            let (name, reg) = Region::early(&self.tcx.hir(), &mut index, &param);
+                            let def_id = if let Region::EarlyBound(_, def_id, _) = reg {
+                                def_id
+                            } else {
+                                bug!();
+                            };
+                            if let hir::ParamName::Plain(param_name) = name {
+                                if param_name.name == kw::UnderscoreLifetime {
+                                    // Pick the elided lifetime "definition" if one exists
+                                    // and use it to make an elision scope.
+                                    self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
+                                    elision = Some(reg);
+                                } else {
+                                    lifetimes.insert(name, reg);
+                                }
+                            } else {
+                                self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
+                                lifetimes.insert(name, reg);
+                            }
+                        }
+                        GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
+                            non_lifetime_count += 1;
+                        }
+                    }
+                }
+                let next_early_index = index + non_lifetime_count;
+
+                if let Some(elision_region) = elision {
+                    let scope =
+                        Scope::Elision { elide: Elide::Exact(elision_region), s: self.scope };
+                    self.with(scope, |_old_scope, this| {
+                        let scope = Scope::Binder {
+                            lifetimes,
+                            next_early_index,
+                            s: this.scope,
+                            track_lifetime_uses: true,
+                            opaque_type_parent: false,
+                        };
+                        this.with(scope, |_old_scope, this| {
+                            this.visit_generics(generics);
+                            for bound in bounds {
+                                this.visit_param_bound(bound);
+                            }
+                        });
+                    });
+                } else {
+                    let scope = Scope::Binder {
+                        lifetimes,
+                        next_early_index,
+                        s: self.scope,
+                        track_lifetime_uses: true,
+                        opaque_type_parent: false,
+                    };
+                    self.with(scope, |_old_scope, this| {
+                        this.visit_generics(generics);
+                        for bound in bounds {
+                            this.visit_param_bound(bound);
+                        }
+                    });
+                }
+            }
+            _ => intravisit::walk_ty(self, ty),
+        }
+    }
+
+    fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
+        use self::hir::TraitItemKind::*;
+        match trait_item.kind {
+            Fn(ref sig, _) => {
+                self.missing_named_lifetime_spots.push((&trait_item.generics).into());
+                let tcx = self.tcx;
+                self.visit_early_late(
+                    Some(tcx.hir().get_parent_item(trait_item.hir_id)),
+                    &sig.decl,
+                    &trait_item.generics,
+                    |this| intravisit::walk_trait_item(this, trait_item),
+                );
+                self.missing_named_lifetime_spots.pop();
+            }
+            Type(bounds, ref ty) => {
+                self.missing_named_lifetime_spots.push((&trait_item.generics).into());
+                let generics = &trait_item.generics;
+                let mut index = self.next_early_index();
+                debug!("visit_ty: index = {}", index);
+                let mut non_lifetime_count = 0;
+                let lifetimes = generics
+                    .params
+                    .iter()
+                    .filter_map(|param| match param.kind {
+                        GenericParamKind::Lifetime { .. } => {
+                            Some(Region::early(&self.tcx.hir(), &mut index, param))
+                        }
+                        GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
+                            non_lifetime_count += 1;
+                            None
+                        }
+                    })
+                    .collect();
+                let scope = Scope::Binder {
+                    lifetimes,
+                    next_early_index: index + non_lifetime_count,
+                    s: self.scope,
+                    track_lifetime_uses: true,
+                    opaque_type_parent: true,
+                };
+                self.with(scope, |old_scope, this| {
+                    this.check_lifetime_params(old_scope, &generics.params);
+                    this.visit_generics(generics);
+                    for bound in bounds {
+                        this.visit_param_bound(bound);
+                    }
+                    if let Some(ty) = ty {
+                        this.visit_ty(ty);
+                    }
+                });
+                self.missing_named_lifetime_spots.pop();
+            }
+            Const(_, _) => {
+                // Only methods and types support generics.
+                assert!(trait_item.generics.params.is_empty());
+                self.missing_named_lifetime_spots.push(MissingLifetimeSpot::Static);
+                intravisit::walk_trait_item(self, trait_item);
+                self.missing_named_lifetime_spots.pop();
+            }
+        }
+    }
+
+    fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
+        use self::hir::ImplItemKind::*;
+        match impl_item.kind {
+            Fn(ref sig, _) => {
+                self.missing_named_lifetime_spots.push((&impl_item.generics).into());
+                let tcx = self.tcx;
+                self.visit_early_late(
+                    Some(tcx.hir().get_parent_item(impl_item.hir_id)),
+                    &sig.decl,
+                    &impl_item.generics,
+                    |this| intravisit::walk_impl_item(this, impl_item),
+                );
+                self.missing_named_lifetime_spots.pop();
+            }
+            TyAlias(ref ty) => {
+                let generics = &impl_item.generics;
+                self.missing_named_lifetime_spots.push(generics.into());
+                let mut index = self.next_early_index();
+                let mut non_lifetime_count = 0;
+                debug!("visit_ty: index = {}", index);
+                let lifetimes = generics
+                    .params
+                    .iter()
+                    .filter_map(|param| match param.kind {
+                        GenericParamKind::Lifetime { .. } => {
+                            Some(Region::early(&self.tcx.hir(), &mut index, param))
+                        }
+                        GenericParamKind::Const { .. } | GenericParamKind::Type { .. } => {
+                            non_lifetime_count += 1;
+                            None
+                        }
+                    })
+                    .collect();
+                let scope = Scope::Binder {
+                    lifetimes,
+                    next_early_index: index + non_lifetime_count,
+                    s: self.scope,
+                    track_lifetime_uses: true,
+                    opaque_type_parent: true,
+                };
+                self.with(scope, |old_scope, this| {
+                    this.check_lifetime_params(old_scope, &generics.params);
+                    this.visit_generics(generics);
+                    this.visit_ty(ty);
+                });
+                self.missing_named_lifetime_spots.pop();
+            }
+            Const(_, _) => {
+                // Only methods and types support generics.
+                assert!(impl_item.generics.params.is_empty());
+                self.missing_named_lifetime_spots.push(MissingLifetimeSpot::Static);
+                intravisit::walk_impl_item(self, impl_item);
+                self.missing_named_lifetime_spots.pop();
+            }
+        }
+    }
+
+    fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
+        debug!("visit_lifetime(lifetime_ref={:?})", lifetime_ref);
+        if lifetime_ref.is_elided() {
+            self.resolve_elided_lifetimes(vec![lifetime_ref]);
+            return;
+        }
+        if lifetime_ref.is_static() {
+            self.insert_lifetime(lifetime_ref, Region::Static);
+            return;
+        }
+        if self.is_in_const_generic && lifetime_ref.name != LifetimeName::Error {
+            self.emit_non_static_lt_in_const_generic_error(lifetime_ref);
+            return;
+        }
+        self.resolve_lifetime_ref(lifetime_ref);
+    }
+
+    fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
+        for (i, segment) in path.segments.iter().enumerate() {
+            let depth = path.segments.len() - i - 1;
+            if let Some(ref args) = segment.args {
+                self.visit_segment_args(path.res, depth, args);
+            }
+        }
+    }
+
+    fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>) {
+        let output = match fd.output {
+            hir::FnRetTy::DefaultReturn(_) => None,
+            hir::FnRetTy::Return(ref ty) => Some(&**ty),
+        };
+        self.visit_fn_like_elision(&fd.inputs, output);
+    }
+
+    fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
+        check_mixed_explicit_and_in_band_defs(self.tcx, &generics.params);
+        for param in generics.params {
+            match param.kind {
+                GenericParamKind::Lifetime { .. } => {}
+                GenericParamKind::Type { ref default, .. } => {
+                    walk_list!(self, visit_param_bound, param.bounds);
+                    if let Some(ref ty) = default {
+                        self.visit_ty(&ty);
+                    }
+                }
+                GenericParamKind::Const { ref ty, .. } => {
+                    let was_in_const_generic = self.is_in_const_generic;
+                    self.is_in_const_generic = true;
+                    walk_list!(self, visit_param_bound, param.bounds);
+                    self.visit_ty(&ty);
+                    self.is_in_const_generic = was_in_const_generic;
+                }
+            }
+        }
+        for predicate in generics.where_clause.predicates {
+            match predicate {
+                &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
+                    ref bounded_ty,
+                    bounds,
+                    ref bound_generic_params,
+                    ..
+                }) => {
+                    let lifetimes: FxHashMap<_, _> = bound_generic_params
+                        .iter()
+                        .filter_map(|param| match param.kind {
+                            GenericParamKind::Lifetime { .. } => {
+                                Some(Region::late(&self.tcx.hir(), param))
+                            }
+                            _ => None,
+                        })
+                        .collect();
+                    if !lifetimes.is_empty() {
+                        let next_early_index = self.next_early_index();
+                        let scope = Scope::Binder {
+                            lifetimes,
+                            s: self.scope,
+                            next_early_index,
+                            track_lifetime_uses: true,
+                            opaque_type_parent: false,
+                        };
+                        let result = self.with(scope, |old_scope, this| {
+                            this.check_lifetime_params(old_scope, &bound_generic_params);
+                            this.visit_ty(&bounded_ty);
+                            this.trait_ref_hack = true;
+                            walk_list!(this, visit_param_bound, bounds);
+                            this.trait_ref_hack = false;
+                        });
+                        result
+                    } else {
+                        self.visit_ty(&bounded_ty);
+                        walk_list!(self, visit_param_bound, bounds);
+                    }
+                }
+                &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
+                    ref lifetime,
+                    bounds,
+                    ..
+                }) => {
+                    self.visit_lifetime(lifetime);
+                    walk_list!(self, visit_param_bound, bounds);
+                }
+                &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
+                    ref lhs_ty,
+                    ref rhs_ty,
+                    ..
+                }) => {
+                    self.visit_ty(lhs_ty);
+                    self.visit_ty(rhs_ty);
+                }
+            }
+        }
+    }
+
+    fn visit_param_bound(&mut self, bound: &'tcx hir::GenericBound<'tcx>) {
+        match bound {
+            hir::GenericBound::LangItemTrait { .. } if !self.trait_ref_hack => {
+                let scope = Scope::Binder {
+                    lifetimes: FxHashMap::default(),
+                    s: self.scope,
+                    next_early_index: self.next_early_index(),
+                    track_lifetime_uses: true,
+                    opaque_type_parent: false,
+                };
+                self.with(scope, |_, this| {
+                    intravisit::walk_param_bound(this, bound);
+                });
+            }
+            _ => intravisit::walk_param_bound(self, bound),
+        }
+    }
+
+    fn visit_poly_trait_ref(
+        &mut self,
+        trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
+        _modifier: hir::TraitBoundModifier,
+    ) {
+        debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref);
+
+        let should_pop_missing_lt = self.is_trait_ref_fn_scope(trait_ref);
+
+        let trait_ref_hack = take(&mut self.trait_ref_hack);
+        if !trait_ref_hack
+            || trait_ref.bound_generic_params.iter().any(|param| match param.kind {
+                GenericParamKind::Lifetime { .. } => true,
+                _ => false,
+            })
+        {
+            if trait_ref_hack {
+                struct_span_err!(
+                    self.tcx.sess,
+                    trait_ref.span,
+                    E0316,
+                    "nested quantification of lifetimes"
+                )
+                .emit();
+            }
+            let next_early_index = self.next_early_index();
+            let scope = Scope::Binder {
+                lifetimes: trait_ref
+                    .bound_generic_params
+                    .iter()
+                    .filter_map(|param| match param.kind {
+                        GenericParamKind::Lifetime { .. } => {
+                            Some(Region::late(&self.tcx.hir(), param))
+                        }
+                        _ => None,
+                    })
+                    .collect(),
+                s: self.scope,
+                next_early_index,
+                track_lifetime_uses: true,
+                opaque_type_parent: false,
+            };
+            self.with(scope, |old_scope, this| {
+                this.check_lifetime_params(old_scope, &trait_ref.bound_generic_params);
+                walk_list!(this, visit_generic_param, trait_ref.bound_generic_params);
+                this.visit_trait_ref(&trait_ref.trait_ref);
+            });
+        } else {
+            self.visit_trait_ref(&trait_ref.trait_ref);
+        }
+        self.trait_ref_hack = trait_ref_hack;
+        if should_pop_missing_lt {
+            self.missing_named_lifetime_spots.pop();
+        }
+    }
+}
+
+#[derive(Copy, Clone, PartialEq)]
+enum ShadowKind {
+    Label,
+    Lifetime,
+}
+struct Original {
+    kind: ShadowKind,
+    span: Span,
+}
+struct Shadower {
+    kind: ShadowKind,
+    span: Span,
+}
+
+fn original_label(span: Span) -> Original {
+    Original { kind: ShadowKind::Label, span }
+}
+fn shadower_label(span: Span) -> Shadower {
+    Shadower { kind: ShadowKind::Label, span }
+}
+fn original_lifetime(span: Span) -> Original {
+    Original { kind: ShadowKind::Lifetime, span }
+}
+fn shadower_lifetime(param: &hir::GenericParam<'_>) -> Shadower {
+    Shadower { kind: ShadowKind::Lifetime, span: param.span }
+}
+
+impl ShadowKind {
+    fn desc(&self) -> &'static str {
+        match *self {
+            ShadowKind::Label => "label",
+            ShadowKind::Lifetime => "lifetime",
+        }
+    }
+}
+
+fn check_mixed_explicit_and_in_band_defs(tcx: TyCtxt<'_>, params: &[hir::GenericParam<'_>]) {
+    let lifetime_params: Vec<_> = params
+        .iter()
+        .filter_map(|param| match param.kind {
+            GenericParamKind::Lifetime { kind, .. } => Some((kind, param.span)),
+            _ => None,
+        })
+        .collect();
+    let explicit = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::Explicit);
+    let in_band = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::InBand);
+
+    if let (Some((_, explicit_span)), Some((_, in_band_span))) = (explicit, in_band) {
+        struct_span_err!(
+            tcx.sess,
+            *in_band_span,
+            E0688,
+            "cannot mix in-band and explicit lifetime definitions"
+        )
+        .span_label(*in_band_span, "in-band lifetime definition here")
+        .span_label(*explicit_span, "explicit lifetime definition here")
+        .emit();
+    }
+}
+
+fn signal_shadowing_problem(tcx: TyCtxt<'_>, name: Symbol, orig: Original, shadower: Shadower) {
+    let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
+        // lifetime/lifetime shadowing is an error
+        struct_span_err!(
+            tcx.sess,
+            shadower.span,
+            E0496,
+            "{} name `{}` shadows a \
+             {} name that is already in scope",
+            shadower.kind.desc(),
+            name,
+            orig.kind.desc()
+        )
+    } else {
+        // shadowing involving a label is only a warning, due to issues with
+        // labels and lifetimes not being macro-hygienic.
+        tcx.sess.struct_span_warn(
+            shadower.span,
+            &format!(
+                "{} name `{}` shadows a \
+                 {} name that is already in scope",
+                shadower.kind.desc(),
+                name,
+                orig.kind.desc()
+            ),
+        )
+    };
+    err.span_label(orig.span, "first declared here");
+    err.span_label(shadower.span, format!("lifetime {} already in scope", name));
+    err.emit();
+}
+
+// Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
+// if one of the label shadows a lifetime or another label.
+fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body<'_>) {
+    struct GatherLabels<'a, 'tcx> {
+        tcx: TyCtxt<'tcx>,
+        scope: ScopeRef<'a>,
+        labels_in_fn: &'a mut Vec<Ident>,
+    }
+
+    let mut gather =
+        GatherLabels { tcx: ctxt.tcx, scope: ctxt.scope, labels_in_fn: &mut ctxt.labels_in_fn };
+    gather.visit_body(body);
+
+    impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> {
+        type Map = intravisit::ErasedMap<'v>;
+
+        fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+            NestedVisitorMap::None
+        }
+
+        fn visit_expr(&mut self, ex: &hir::Expr<'_>) {
+            if let Some(label) = expression_label(ex) {
+                for prior_label in &self.labels_in_fn[..] {
+                    // FIXME (#24278): non-hygienic comparison
+                    if label.name == prior_label.name {
+                        signal_shadowing_problem(
+                            self.tcx,
+                            label.name,
+                            original_label(prior_label.span),
+                            shadower_label(label.span),
+                        );
+                    }
+                }
+
+                check_if_label_shadows_lifetime(self.tcx, self.scope, label);
+
+                self.labels_in_fn.push(label);
+            }
+            intravisit::walk_expr(self, ex)
+        }
+    }
+
+    fn expression_label(ex: &hir::Expr<'_>) -> Option<Ident> {
+        if let hir::ExprKind::Loop(_, Some(label), _) = ex.kind { Some(label.ident) } else { None }
+    }
+
+    fn check_if_label_shadows_lifetime(tcx: TyCtxt<'_>, mut scope: ScopeRef<'_>, label: Ident) {
+        loop {
+            match *scope {
+                Scope::Body { s, .. }
+                | Scope::Elision { s, .. }
+                | Scope::ObjectLifetimeDefault { s, .. } => {
+                    scope = s;
+                }
+
+                Scope::Root => {
+                    return;
+                }
+
+                Scope::Binder { ref lifetimes, s, .. } => {
+                    // FIXME (#24278): non-hygienic comparison
+                    if let Some(def) =
+                        lifetimes.get(&hir::ParamName::Plain(label.normalize_to_macros_2_0()))
+                    {
+                        let hir_id =
+                            tcx.hir().local_def_id_to_hir_id(def.id().unwrap().expect_local());
+
+                        signal_shadowing_problem(
+                            tcx,
+                            label.name,
+                            original_lifetime(tcx.hir().span(hir_id)),
+                            shadower_label(label.span),
+                        );
+                        return;
+                    }
+                    scope = s;
+                }
+            }
+        }
+    }
+}
+
+fn compute_object_lifetime_defaults(tcx: TyCtxt<'_>) -> HirIdMap<Vec<ObjectLifetimeDefault>> {
+    let mut map = HirIdMap::default();
+    for item in tcx.hir().krate().items.values() {
+        match item.kind {
+            hir::ItemKind::Struct(_, ref generics)
+            | hir::ItemKind::Union(_, ref generics)
+            | hir::ItemKind::Enum(_, ref generics)
+            | hir::ItemKind::OpaqueTy(hir::OpaqueTy {
+                ref generics, impl_trait_fn: None, ..
+            })
+            | hir::ItemKind::TyAlias(_, ref generics)
+            | hir::ItemKind::Trait(_, _, ref generics, ..) => {
+                let result = object_lifetime_defaults_for_item(tcx, generics);
+
+                // Debugging aid.
+                if tcx.sess.contains_name(&item.attrs, sym::rustc_object_lifetime_default) {
+                    let object_lifetime_default_reprs: String = result
+                        .iter()
+                        .map(|set| match *set {
+                            Set1::Empty => "BaseDefault".into(),
+                            Set1::One(Region::Static) => "'static".into(),
+                            Set1::One(Region::EarlyBound(mut i, _, _)) => generics
+                                .params
+                                .iter()
+                                .find_map(|param| match param.kind {
+                                    GenericParamKind::Lifetime { .. } => {
+                                        if i == 0 {
+                                            return Some(param.name.ident().to_string().into());
+                                        }
+                                        i -= 1;
+                                        None
+                                    }
+                                    _ => None,
+                                })
+                                .unwrap(),
+                            Set1::One(_) => bug!(),
+                            Set1::Many => "Ambiguous".into(),
+                        })
+                        .collect::<Vec<Cow<'static, str>>>()
+                        .join(",");
+                    tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
+                }
+
+                map.insert(item.hir_id, result);
+            }
+            _ => {}
+        }
+    }
+    map
+}
+
+/// Scan the bounds and where-clauses on parameters to extract bounds
+/// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
+/// for each type parameter.
+fn object_lifetime_defaults_for_item(
+    tcx: TyCtxt<'_>,
+    generics: &hir::Generics<'_>,
+) -> Vec<ObjectLifetimeDefault> {
+    fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound<'_>]) {
+        for bound in bounds {
+            if let hir::GenericBound::Outlives(ref lifetime) = *bound {
+                set.insert(lifetime.name.normalize_to_macros_2_0());
+            }
+        }
+    }
+
+    generics
+        .params
+        .iter()
+        .filter_map(|param| match param.kind {
+            GenericParamKind::Lifetime { .. } => None,
+            GenericParamKind::Type { .. } => {
+                let mut set = Set1::Empty;
+
+                add_bounds(&mut set, &param.bounds);
+
+                let param_def_id = tcx.hir().local_def_id(param.hir_id);
+                for predicate in generics.where_clause.predicates {
+                    // Look for `type: ...` where clauses.
+                    let data = match *predicate {
+                        hir::WherePredicate::BoundPredicate(ref data) => data,
+                        _ => continue,
+                    };
+
+                    // Ignore `for<'a> type: ...` as they can change what
+                    // lifetimes mean (although we could "just" handle it).
+                    if !data.bound_generic_params.is_empty() {
+                        continue;
+                    }
+
+                    let res = match data.bounded_ty.kind {
+                        hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.res,
+                        _ => continue,
+                    };
+
+                    if res == Res::Def(DefKind::TyParam, param_def_id.to_def_id()) {
+                        add_bounds(&mut set, &data.bounds);
+                    }
+                }
+
+                Some(match set {
+                    Set1::Empty => Set1::Empty,
+                    Set1::One(name) => {
+                        if name == hir::LifetimeName::Static {
+                            Set1::One(Region::Static)
+                        } else {
+                            generics
+                                .params
+                                .iter()
+                                .filter_map(|param| match param.kind {
+                                    GenericParamKind::Lifetime { .. } => Some((
+                                        param.hir_id,
+                                        hir::LifetimeName::Param(param.name),
+                                        LifetimeDefOrigin::from_param(param),
+                                    )),
+                                    _ => None,
+                                })
+                                .enumerate()
+                                .find(|&(_, (_, lt_name, _))| lt_name == name)
+                                .map_or(Set1::Many, |(i, (id, _, origin))| {
+                                    let def_id = tcx.hir().local_def_id(id);
+                                    Set1::One(Region::EarlyBound(
+                                        i as u32,
+                                        def_id.to_def_id(),
+                                        origin,
+                                    ))
+                                })
+                        }
+                    }
+                    Set1::Many => Set1::Many,
+                })
+            }
+            GenericParamKind::Const { .. } => {
+                // Generic consts don't impose any constraints.
+                //
+                // We still store a dummy value here to allow generic parameters
+                // in an arbitrary order.
+                Some(Set1::Empty)
+            }
+        })
+        .collect()
+}
+
+impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
+    // FIXME(#37666) this works around a limitation in the region inferencer
+    fn hack<F>(&mut self, f: F)
+    where
+        F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
+    {
+        f(self)
+    }
+
+    fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
+    where
+        F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>),
+    {
+        let LifetimeContext { tcx, map, lifetime_uses, .. } = self;
+        let labels_in_fn = take(&mut self.labels_in_fn);
+        let xcrate_object_lifetime_defaults = take(&mut self.xcrate_object_lifetime_defaults);
+        let missing_named_lifetime_spots = take(&mut self.missing_named_lifetime_spots);
+        let mut this = LifetimeContext {
+            tcx: *tcx,
+            map,
+            scope: &wrap_scope,
+            trait_ref_hack: self.trait_ref_hack,
+            is_in_fn_syntax: self.is_in_fn_syntax,
+            is_in_const_generic: self.is_in_const_generic,
+            labels_in_fn,
+            xcrate_object_lifetime_defaults,
+            lifetime_uses,
+            missing_named_lifetime_spots,
+        };
+        debug!("entering scope {:?}", this.scope);
+        f(self.scope, &mut this);
+        this.check_uses_for_lifetimes_defined_by_scope();
+        debug!("exiting scope {:?}", this.scope);
+        self.labels_in_fn = this.labels_in_fn;
+        self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
+        self.missing_named_lifetime_spots = this.missing_named_lifetime_spots;
+    }
+
+    /// helper method to determine the span to remove when suggesting the
+    /// deletion of a lifetime
+    fn lifetime_deletion_span(&self, name: Ident, generics: &hir::Generics<'_>) -> Option<Span> {
+        generics.params.iter().enumerate().find_map(|(i, param)| {
+            if param.name.ident() == name {
+                let mut in_band = false;
+                if let hir::GenericParamKind::Lifetime { kind } = param.kind {
+                    if let hir::LifetimeParamKind::InBand = kind {
+                        in_band = true;
+                    }
+                }
+                if in_band {
+                    Some(param.span)
+                } else {
+                    if generics.params.len() == 1 {
+                        // if sole lifetime, remove the entire `<>` brackets
+                        Some(generics.span)
+                    } else {
+                        // if removing within `<>` brackets, we also want to
+                        // delete a leading or trailing comma as appropriate
+                        if i >= generics.params.len() - 1 {
+                            Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
+                        } else {
+                            Some(param.span.to(generics.params[i + 1].span.shrink_to_lo()))
+                        }
+                    }
+                }
+            } else {
+                None
+            }
+        })
+    }
+
+    // helper method to issue suggestions from `fn rah<'a>(&'a T)` to `fn rah(&T)`
+    // or from `fn rah<'a>(T<'a>)` to `fn rah(T<'_>)`
+    fn suggest_eliding_single_use_lifetime(
+        &self,
+        err: &mut DiagnosticBuilder<'_>,
+        def_id: DefId,
+        lifetime: &hir::Lifetime,
+    ) {
+        let name = lifetime.name.ident();
+        let mut remove_decl = None;
+        if let Some(parent_def_id) = self.tcx.parent(def_id) {
+            if let Some(generics) = self.tcx.hir().get_generics(parent_def_id) {
+                remove_decl = self.lifetime_deletion_span(name, generics);
+            }
+        }
+
+        let mut remove_use = None;
+        let mut elide_use = None;
+        let mut find_arg_use_span = |inputs: &[hir::Ty<'_>]| {
+            for input in inputs {
+                match input.kind {
+                    hir::TyKind::Rptr(lt, _) => {
+                        if lt.name.ident() == name {
+                            // include the trailing whitespace between the lifetime and type names
+                            let lt_through_ty_span = lifetime.span.to(input.span.shrink_to_hi());
+                            remove_use = Some(
+                                self.tcx
+                                    .sess
+                                    .source_map()
+                                    .span_until_non_whitespace(lt_through_ty_span),
+                            );
+                            break;
+                        }
+                    }
+                    hir::TyKind::Path(ref qpath) => {
+                        if let QPath::Resolved(_, path) = qpath {
+                            let last_segment = &path.segments[path.segments.len() - 1];
+                            let generics = last_segment.generic_args();
+                            for arg in generics.args.iter() {
+                                if let GenericArg::Lifetime(lt) = arg {
+                                    if lt.name.ident() == name {
+                                        elide_use = Some(lt.span);
+                                        break;
+                                    }
+                                }
+                            }
+                            break;
+                        }
+                    }
+                    _ => {}
+                }
+            }
+        };
+        if let Node::Lifetime(hir_lifetime) = self.tcx.hir().get(lifetime.hir_id) {
+            if let Some(parent) =
+                self.tcx.hir().find(self.tcx.hir().get_parent_item(hir_lifetime.hir_id))
+            {
+                match parent {
+                    Node::Item(item) => {
+                        if let hir::ItemKind::Fn(sig, _, _) = &item.kind {
+                            find_arg_use_span(sig.decl.inputs);
+                        }
+                    }
+                    Node::ImplItem(impl_item) => {
+                        if let hir::ImplItemKind::Fn(sig, _) = &impl_item.kind {
+                            find_arg_use_span(sig.decl.inputs);
+                        }
+                    }
+                    _ => {}
+                }
+            }
+        }
+
+        let msg = "elide the single-use lifetime";
+        match (remove_decl, remove_use, elide_use) {
+            (Some(decl_span), Some(use_span), None) => {
+                // if both declaration and use deletion spans start at the same
+                // place ("start at" because the latter includes trailing
+                // whitespace), then this is an in-band lifetime
+                if decl_span.shrink_to_lo() == use_span.shrink_to_lo() {
+                    err.span_suggestion(
+                        use_span,
+                        msg,
+                        String::new(),
+                        Applicability::MachineApplicable,
+                    );
+                } else {
+                    err.multipart_suggestion(
+                        msg,
+                        vec![(decl_span, String::new()), (use_span, String::new())],
+                        Applicability::MachineApplicable,
+                    );
+                }
+            }
+            (Some(decl_span), None, Some(use_span)) => {
+                err.multipart_suggestion(
+                    msg,
+                    vec![(decl_span, String::new()), (use_span, "'_".to_owned())],
+                    Applicability::MachineApplicable,
+                );
+            }
+            _ => {}
+        }
+    }
+
+    fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
+        let defined_by = match self.scope {
+            Scope::Binder { lifetimes, .. } => lifetimes,
+            _ => {
+                debug!("check_uses_for_lifetimes_defined_by_scope: not in a binder scope");
+                return;
+            }
+        };
+
+        let mut def_ids: Vec<_> = defined_by
+            .values()
+            .flat_map(|region| match region {
+                Region::EarlyBound(_, def_id, _)
+                | Region::LateBound(_, def_id, _)
+                | Region::Free(_, def_id) => Some(*def_id),
+
+                Region::LateBoundAnon(..) | Region::Static => None,
+            })
+            .collect();
+
+        // ensure that we issue lints in a repeatable order
+        def_ids.sort_by_cached_key(|&def_id| self.tcx.def_path_hash(def_id));
+
+        for def_id in def_ids {
+            debug!("check_uses_for_lifetimes_defined_by_scope: def_id = {:?}", def_id);
+
+            let lifetimeuseset = self.lifetime_uses.remove(&def_id);
+
+            debug!(
+                "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
+                lifetimeuseset
+            );
+
+            match lifetimeuseset {
+                Some(LifetimeUseSet::One(lifetime)) => {
+                    let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
+                    debug!("hir id first={:?}", hir_id);
+                    if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
+                        Node::Lifetime(hir_lifetime) => Some((
+                            hir_lifetime.hir_id,
+                            hir_lifetime.span,
+                            hir_lifetime.name.ident(),
+                        )),
+                        Node::GenericParam(param) => {
+                            Some((param.hir_id, param.span, param.name.ident()))
+                        }
+                        _ => None,
+                    } {
+                        debug!("id = {:?} span = {:?} name = {:?}", id, span, name);
+                        if name.name == kw::UnderscoreLifetime {
+                            continue;
+                        }
+
+                        if let Some(parent_def_id) = self.tcx.parent(def_id) {
+                            if let Some(def_id) = parent_def_id.as_local() {
+                                let parent_hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
+                                // lifetimes in `derive` expansions don't count (Issue #53738)
+                                if self.tcx.hir().attrs(parent_hir_id).iter().any(|attr| {
+                                    self.tcx.sess.check_name(attr, sym::automatically_derived)
+                                }) {
+                                    continue;
+                                }
+                            }
+                        }
+
+                        self.tcx.struct_span_lint_hir(
+                            lint::builtin::SINGLE_USE_LIFETIMES,
+                            id,
+                            span,
+                            |lint| {
+                                let mut err = lint.build(&format!(
+                                    "lifetime parameter `{}` only used once",
+                                    name
+                                ));
+                                if span == lifetime.span {
+                                    // spans are the same for in-band lifetime declarations
+                                    err.span_label(span, "this lifetime is only used here");
+                                } else {
+                                    err.span_label(span, "this lifetime...");
+                                    err.span_label(lifetime.span, "...is used only here");
+                                }
+                                self.suggest_eliding_single_use_lifetime(
+                                    &mut err, def_id, lifetime,
+                                );
+                                err.emit();
+                            },
+                        );
+                    }
+                }
+                Some(LifetimeUseSet::Many) => {
+                    debug!("not one use lifetime");
+                }
+                None => {
+                    let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
+                    if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
+                        Node::Lifetime(hir_lifetime) => Some((
+                            hir_lifetime.hir_id,
+                            hir_lifetime.span,
+                            hir_lifetime.name.ident(),
+                        )),
+                        Node::GenericParam(param) => {
+                            Some((param.hir_id, param.span, param.name.ident()))
+                        }
+                        _ => None,
+                    } {
+                        debug!("id ={:?} span = {:?} name = {:?}", id, span, name);
+                        self.tcx.struct_span_lint_hir(
+                            lint::builtin::UNUSED_LIFETIMES,
+                            id,
+                            span,
+                            |lint| {
+                                let mut err = lint
+                                    .build(&format!("lifetime parameter `{}` never used", name));
+                                if let Some(parent_def_id) = self.tcx.parent(def_id) {
+                                    if let Some(generics) =
+                                        self.tcx.hir().get_generics(parent_def_id)
+                                    {
+                                        let unused_lt_span =
+                                            self.lifetime_deletion_span(name, generics);
+                                        if let Some(span) = unused_lt_span {
+                                            err.span_suggestion(
+                                                span,
+                                                "elide the unused lifetime",
+                                                String::new(),
+                                                Applicability::MachineApplicable,
+                                            );
+                                        }
+                                    }
+                                }
+                                err.emit();
+                            },
+                        );
+                    }
+                }
+            }
+        }
+    }
+
+    /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
+    ///
+    /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
+    /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
+    /// within type bounds; those are early bound lifetimes, and the rest are late bound.
+    ///
+    /// For example:
+    ///
+    ///    fn foo<'a,'b,'c,T:Trait<'b>>(...)
+    ///
+    /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
+    /// lifetimes may be interspersed together.
+    ///
+    /// If early bound lifetimes are present, we separate them into their own list (and likewise
+    /// for late bound). They will be numbered sequentially, starting from the lowest index that is
+    /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
+    /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
+    /// ordering is not important there.
+    fn visit_early_late<F>(
+        &mut self,
+        parent_id: Option<hir::HirId>,
+        decl: &'tcx hir::FnDecl<'tcx>,
+        generics: &'tcx hir::Generics<'tcx>,
+        walk: F,
+    ) where
+        F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
+    {
+        insert_late_bound_lifetimes(self.map, decl, generics);
+
+        // Find the start of nested early scopes, e.g., in methods.
+        let mut index = 0;
+        if let Some(parent_id) = parent_id {
+            let parent = self.tcx.hir().expect_item(parent_id);
+            if sub_items_have_self_param(&parent.kind) {
+                index += 1; // Self comes before lifetimes
+            }
+            match parent.kind {
+                hir::ItemKind::Trait(_, _, ref generics, ..)
+                | hir::ItemKind::Impl { ref generics, .. } => {
+                    index += generics.params.len() as u32;
+                }
+                _ => {}
+            }
+        }
+
+        let mut non_lifetime_count = 0;
+        let lifetimes = generics
+            .params
+            .iter()
+            .filter_map(|param| match param.kind {
+                GenericParamKind::Lifetime { .. } => {
+                    if self.map.late_bound.contains(&param.hir_id) {
+                        Some(Region::late(&self.tcx.hir(), param))
+                    } else {
+                        Some(Region::early(&self.tcx.hir(), &mut index, param))
+                    }
+                }
+                GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
+                    non_lifetime_count += 1;
+                    None
+                }
+            })
+            .collect();
+        let next_early_index = index + non_lifetime_count;
+
+        let scope = Scope::Binder {
+            lifetimes,
+            next_early_index,
+            s: self.scope,
+            opaque_type_parent: true,
+            track_lifetime_uses: false,
+        };
+        self.with(scope, move |old_scope, this| {
+            this.check_lifetime_params(old_scope, &generics.params);
+            this.hack(walk); // FIXME(#37666) workaround in place of `walk(this)`
+        });
+    }
+
+    fn next_early_index_helper(&self, only_opaque_type_parent: bool) -> u32 {
+        let mut scope = self.scope;
+        loop {
+            match *scope {
+                Scope::Root => return 0,
+
+                Scope::Binder { next_early_index, opaque_type_parent, .. }
+                    if (!only_opaque_type_parent || opaque_type_parent) =>
+                {
+                    return next_early_index;
+                }
+
+                Scope::Binder { s, .. }
+                | Scope::Body { s, .. }
+                | Scope::Elision { s, .. }
+                | Scope::ObjectLifetimeDefault { s, .. } => scope = s,
+            }
+        }
+    }
+
+    /// Returns the next index one would use for an early-bound-region
+    /// if extending the current scope.
+    fn next_early_index(&self) -> u32 {
+        self.next_early_index_helper(true)
+    }
+
+    /// Returns the next index one would use for an `impl Trait` that
+    /// is being converted into an opaque type alias `impl Trait`. This will be the
+    /// next early index from the enclosing item, for the most
+    /// part. See the `opaque_type_parent` field for more info.
+    fn next_early_index_for_opaque_type(&self) -> u32 {
+        self.next_early_index_helper(false)
+    }
+
+    fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
+        debug!("resolve_lifetime_ref(lifetime_ref={:?})", lifetime_ref);
+
+        // If we've already reported an error, just ignore `lifetime_ref`.
+        if let LifetimeName::Error = lifetime_ref.name {
+            return;
+        }
+
+        // Walk up the scope chain, tracking the number of fn scopes
+        // that we pass through, until we find a lifetime with the
+        // given name or we run out of scopes.
+        // search.
+        let mut late_depth = 0;
+        let mut scope = self.scope;
+        let mut outermost_body = None;
+        let result = loop {
+            match *scope {
+                Scope::Body { id, s } => {
+                    // Non-static lifetimes are prohibited in anonymous constants under
+                    // `min_const_generics`.
+                    self.maybe_emit_forbidden_non_static_lifetime_error(id, lifetime_ref);
+
+                    outermost_body = Some(id);
+                    scope = s;
+                }
+
+                Scope::Root => {
+                    break None;
+                }
+
+                Scope::Binder { ref lifetimes, s, .. } => {
+                    match lifetime_ref.name {
+                        LifetimeName::Param(param_name) => {
+                            if let Some(&def) = lifetimes.get(&param_name.normalize_to_macros_2_0())
+                            {
+                                break Some(def.shifted(late_depth));
+                            }
+                        }
+                        _ => bug!("expected LifetimeName::Param"),
+                    }
+
+                    late_depth += 1;
+                    scope = s;
+                }
+
+                Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
+                    scope = s;
+                }
+            }
+        };
+
+        if let Some(mut def) = result {
+            if let Region::EarlyBound(..) = def {
+                // Do not free early-bound regions, only late-bound ones.
+            } else if let Some(body_id) = outermost_body {
+                let fn_id = self.tcx.hir().body_owner(body_id);
+                match self.tcx.hir().get(fn_id) {
+                    Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. })
+                    | Node::TraitItem(&hir::TraitItem {
+                        kind: hir::TraitItemKind::Fn(..), ..
+                    })
+                    | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => {
+                        let scope = self.tcx.hir().local_def_id(fn_id);
+                        def = Region::Free(scope.to_def_id(), def.id().unwrap());
+                    }
+                    _ => {}
+                }
+            }
+
+            // Check for fn-syntax conflicts with in-band lifetime definitions
+            if self.is_in_fn_syntax {
+                match def {
+                    Region::EarlyBound(_, _, LifetimeDefOrigin::InBand)
+                    | Region::LateBound(_, _, LifetimeDefOrigin::InBand) => {
+                        struct_span_err!(
+                            self.tcx.sess,
+                            lifetime_ref.span,
+                            E0687,
+                            "lifetimes used in `fn` or `Fn` syntax must be \
+                             explicitly declared using `<...>` binders"
+                        )
+                        .span_label(lifetime_ref.span, "in-band lifetime definition")
+                        .emit();
+                    }
+
+                    Region::Static
+                    | Region::EarlyBound(
+                        _,
+                        _,
+                        LifetimeDefOrigin::ExplicitOrElided | LifetimeDefOrigin::Error,
+                    )
+                    | Region::LateBound(
+                        _,
+                        _,
+                        LifetimeDefOrigin::ExplicitOrElided | LifetimeDefOrigin::Error,
+                    )
+                    | Region::LateBoundAnon(..)
+                    | Region::Free(..) => {}
+                }
+            }
+
+            self.insert_lifetime(lifetime_ref, def);
+        } else {
+            self.emit_undeclared_lifetime_error(lifetime_ref);
+        }
+    }
+
+    fn visit_segment_args(
+        &mut self,
+        res: Res,
+        depth: usize,
+        generic_args: &'tcx hir::GenericArgs<'tcx>,
+    ) {
+        debug!(
+            "visit_segment_args(res={:?}, depth={:?}, generic_args={:?})",
+            res, depth, generic_args,
+        );
+
+        if generic_args.parenthesized {
+            let was_in_fn_syntax = self.is_in_fn_syntax;
+            self.is_in_fn_syntax = true;
+            self.visit_fn_like_elision(generic_args.inputs(), Some(generic_args.bindings[0].ty()));
+            self.is_in_fn_syntax = was_in_fn_syntax;
+            return;
+        }
+
+        let mut elide_lifetimes = true;
+        let lifetimes = generic_args
+            .args
+            .iter()
+            .filter_map(|arg| match arg {
+                hir::GenericArg::Lifetime(lt) => {
+                    if !lt.is_elided() {
+                        elide_lifetimes = false;
+                    }
+                    Some(lt)
+                }
+                _ => None,
+            })
+            .collect();
+        if elide_lifetimes {
+            self.resolve_elided_lifetimes(lifetimes);
+        } else {
+            lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
+        }
+
+        // Figure out if this is a type/trait segment,
+        // which requires object lifetime defaults.
+        let parent_def_id = |this: &mut Self, def_id: DefId| {
+            let def_key = this.tcx.def_key(def_id);
+            DefId { krate: def_id.krate, index: def_key.parent.expect("missing parent") }
+        };
+        let type_def_id = match res {
+            Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(parent_def_id(self, def_id)),
+            Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(parent_def_id(self, def_id)),
+            Res::Def(
+                DefKind::Struct
+                | DefKind::Union
+                | DefKind::Enum
+                | DefKind::TyAlias
+                | DefKind::Trait,
+                def_id,
+            ) if depth == 0 => Some(def_id),
+            _ => None,
+        };
+
+        debug!("visit_segment_args: type_def_id={:?}", type_def_id);
+
+        // Compute a vector of defaults, one for each type parameter,
+        // per the rules given in RFCs 599 and 1156. Example:
+        //
+        // ```rust
+        // struct Foo<'a, T: 'a, U> { }
+        // ```
+        //
+        // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default
+        // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound)
+        // and `dyn Baz` to `dyn Baz + 'static` (because there is no
+        // such bound).
+        //
+        // Therefore, we would compute `object_lifetime_defaults` to a
+        // vector like `['x, 'static]`. Note that the vector only
+        // includes type parameters.
+        let object_lifetime_defaults = type_def_id.map_or(vec![], |def_id| {
+            let in_body = {
+                let mut scope = self.scope;
+                loop {
+                    match *scope {
+                        Scope::Root => break false,
+
+                        Scope::Body { .. } => break true,
+
+                        Scope::Binder { s, .. }
+                        | Scope::Elision { s, .. }
+                        | Scope::ObjectLifetimeDefault { s, .. } => {
+                            scope = s;
+                        }
+                    }
+                }
+            };
+
+            let map = &self.map;
+            let unsubst = if let Some(def_id) = def_id.as_local() {
+                let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
+                &map.object_lifetime_defaults[&id]
+            } else {
+                let tcx = self.tcx;
+                self.xcrate_object_lifetime_defaults.entry(def_id).or_insert_with(|| {
+                    tcx.generics_of(def_id)
+                        .params
+                        .iter()
+                        .filter_map(|param| match param.kind {
+                            GenericParamDefKind::Type { object_lifetime_default, .. } => {
+                                Some(object_lifetime_default)
+                            }
+                            GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None,
+                        })
+                        .collect()
+                })
+            };
+            debug!("visit_segment_args: unsubst={:?}", unsubst);
+            unsubst
+                .iter()
+                .map(|set| match *set {
+                    Set1::Empty => {
+                        if in_body {
+                            None
+                        } else {
+                            Some(Region::Static)
+                        }
+                    }
+                    Set1::One(r) => {
+                        let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
+                            GenericArg::Lifetime(lt) => Some(lt),
+                            _ => None,
+                        });
+                        r.subst(lifetimes, map)
+                    }
+                    Set1::Many => None,
+                })
+                .collect()
+        });
+
+        debug!("visit_segment_args: object_lifetime_defaults={:?}", object_lifetime_defaults);
+
+        let mut i = 0;
+        for arg in generic_args.args {
+            match arg {
+                GenericArg::Lifetime(_) => {}
+                GenericArg::Type(ty) => {
+                    if let Some(&lt) = object_lifetime_defaults.get(i) {
+                        let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
+                        self.with(scope, |_, this| this.visit_ty(ty));
+                    } else {
+                        self.visit_ty(ty);
+                    }
+                    i += 1;
+                }
+                GenericArg::Const(ct) => {
+                    self.visit_anon_const(&ct.value);
+                }
+            }
+        }
+
+        // Hack: when resolving the type `XX` in binding like `dyn
+        // Foo<'b, Item = XX>`, the current object-lifetime default
+        // would be to examine the trait `Foo` to check whether it has
+        // a lifetime bound declared on `Item`. e.g., if `Foo` is
+        // declared like so, then the default object lifetime bound in
+        // `XX` should be `'b`:
+        //
+        // ```rust
+        // trait Foo<'a> {
+        //   type Item: 'a;
+        // }
+        // ```
+        //
+        // but if we just have `type Item;`, then it would be
+        // `'static`. However, we don't get all of this logic correct.
+        //
+        // Instead, we do something hacky: if there are no lifetime parameters
+        // to the trait, then we simply use a default object lifetime
+        // bound of `'static`, because there is no other possibility. On the other hand,
+        // if there ARE lifetime parameters, then we require the user to give an
+        // explicit bound for now.
+        //
+        // This is intended to leave room for us to implement the
+        // correct behavior in the future.
+        let has_lifetime_parameter = generic_args.args.iter().any(|arg| match arg {
+            GenericArg::Lifetime(_) => true,
+            _ => false,
+        });
+
+        // Resolve lifetimes found in the type `XX` from `Item = XX` bindings.
+        for b in generic_args.bindings {
+            let scope = Scope::ObjectLifetimeDefault {
+                lifetime: if has_lifetime_parameter { None } else { Some(Region::Static) },
+                s: self.scope,
+            };
+            self.with(scope, |_, this| this.visit_assoc_type_binding(b));
+        }
+    }
+
+    fn visit_fn_like_elision(
+        &mut self,
+        inputs: &'tcx [hir::Ty<'tcx>],
+        output: Option<&'tcx hir::Ty<'tcx>>,
+    ) {
+        debug!("visit_fn_like_elision: enter");
+        let mut arg_elide = Elide::FreshLateAnon(Cell::new(0));
+        let arg_scope = Scope::Elision { elide: arg_elide.clone(), s: self.scope };
+        self.with(arg_scope, |_, this| {
+            for input in inputs {
+                this.visit_ty(input);
+            }
+            match *this.scope {
+                Scope::Elision { ref elide, .. } => {
+                    arg_elide = elide.clone();
+                }
+                _ => bug!(),
+            }
+        });
+
+        let output = match output {
+            Some(ty) => ty,
+            None => return,
+        };
+
+        debug!("visit_fn_like_elision: determine output");
+
+        // Figure out if there's a body we can get argument names from,
+        // and whether there's a `self` argument (treated specially).
+        let mut assoc_item_kind = None;
+        let mut impl_self = None;
+        let parent = self.tcx.hir().get_parent_node(output.hir_id);
+        let body = match self.tcx.hir().get(parent) {
+            // `fn` definitions and methods.
+            Node::Item(&hir::Item { kind: hir::ItemKind::Fn(.., body), .. }) => Some(body),
+
+            Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Fn(_, ref m), .. }) => {
+                if let hir::ItemKind::Trait(.., ref trait_items) =
+                    self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
+                {
+                    assoc_item_kind =
+                        trait_items.iter().find(|ti| ti.id.hir_id == parent).map(|ti| ti.kind);
+                }
+                match *m {
+                    hir::TraitFn::Required(_) => None,
+                    hir::TraitFn::Provided(body) => Some(body),
+                }
+            }
+
+            Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body), .. }) => {
+                if let hir::ItemKind::Impl { ref self_ty, ref items, .. } =
+                    self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind
+                {
+                    impl_self = Some(self_ty);
+                    assoc_item_kind =
+                        items.iter().find(|ii| ii.id.hir_id == parent).map(|ii| ii.kind);
+                }
+                Some(body)
+            }
+
+            // Foreign functions, `fn(...) -> R` and `Trait(...) -> R` (both types and bounds).
+            Node::ForeignItem(_) | Node::Ty(_) | Node::TraitRef(_) => None,
+            // Everything else (only closures?) doesn't
+            // actually enjoy elision in return types.
+            _ => {
+                self.visit_ty(output);
+                return;
+            }
+        };
+
+        let has_self = match assoc_item_kind {
+            Some(hir::AssocItemKind::Fn { has_self }) => has_self,
+            _ => false,
+        };
+
+        // In accordance with the rules for lifetime elision, we can determine
+        // what region to use for elision in the output type in two ways.
+        // First (determined here), if `self` is by-reference, then the
+        // implied output region is the region of the self parameter.
+        if has_self {
+            struct SelfVisitor<'a> {
+                map: &'a NamedRegionMap,
+                impl_self: Option<&'a hir::TyKind<'a>>,
+                lifetime: Set1<Region>,
+            }
+
+            impl SelfVisitor<'_> {
+                // Look for `self: &'a Self` - also desugared from `&'a self`,
+                // and if that matches, use it for elision and return early.
+                fn is_self_ty(&self, res: Res) -> bool {
+                    if let Res::SelfTy(..) = res {
+                        return true;
+                    }
+
+                    // Can't always rely on literal (or implied) `Self` due
+                    // to the way elision rules were originally specified.
+                    if let Some(&hir::TyKind::Path(hir::QPath::Resolved(None, ref path))) =
+                        self.impl_self
+                    {
+                        match path.res {
+                            // Permit the types that unambiguously always
+                            // result in the same type constructor being used
+                            // (it can't differ between `Self` and `self`).
+                            Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _)
+                            | Res::PrimTy(_) => return res == path.res,
+                            _ => {}
+                        }
+                    }
+
+                    false
+                }
+            }
+
+            impl<'a> Visitor<'a> for SelfVisitor<'a> {
+                type Map = intravisit::ErasedMap<'a>;
+
+                fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+                    NestedVisitorMap::None
+                }
+
+                fn visit_ty(&mut self, ty: &'a hir::Ty<'a>) {
+                    if let hir::TyKind::Rptr(lifetime_ref, ref mt) = ty.kind {
+                        if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = mt.ty.kind
+                        {
+                            if self.is_self_ty(path.res) {
+                                if let Some(lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
+                                    self.lifetime.insert(*lifetime);
+                                }
+                            }
+                        }
+                    }
+                    intravisit::walk_ty(self, ty)
+                }
+            }
+
+            let mut visitor = SelfVisitor {
+                map: self.map,
+                impl_self: impl_self.map(|ty| &ty.kind),
+                lifetime: Set1::Empty,
+            };
+            visitor.visit_ty(&inputs[0]);
+            if let Set1::One(lifetime) = visitor.lifetime {
+                let scope = Scope::Elision { elide: Elide::Exact(lifetime), s: self.scope };
+                self.with(scope, |_, this| this.visit_ty(output));
+                return;
+            }
+        }
+
+        // Second, if there was exactly one lifetime (either a substitution or a
+        // reference) in the arguments, then any anonymous regions in the output
+        // have that lifetime.
+        let mut possible_implied_output_region = None;
+        let mut lifetime_count = 0;
+        let arg_lifetimes = inputs
+            .iter()
+            .enumerate()
+            .skip(has_self as usize)
+            .map(|(i, input)| {
+                let mut gather = GatherLifetimes {
+                    map: self.map,
+                    outer_index: ty::INNERMOST,
+                    have_bound_regions: false,
+                    lifetimes: Default::default(),
+                };
+                gather.visit_ty(input);
+
+                lifetime_count += gather.lifetimes.len();
+
+                if lifetime_count == 1 && gather.lifetimes.len() == 1 {
+                    // there's a chance that the unique lifetime of this
+                    // iteration will be the appropriate lifetime for output
+                    // parameters, so lets store it.
+                    possible_implied_output_region = gather.lifetimes.iter().cloned().next();
+                }
+
+                ElisionFailureInfo {
+                    parent: body,
+                    index: i,
+                    lifetime_count: gather.lifetimes.len(),
+                    have_bound_regions: gather.have_bound_regions,
+                    span: input.span,
+                }
+            })
+            .collect();
+
+        let elide = if lifetime_count == 1 {
+            Elide::Exact(possible_implied_output_region.unwrap())
+        } else {
+            Elide::Error(arg_lifetimes)
+        };
+
+        debug!("visit_fn_like_elision: elide={:?}", elide);
+
+        let scope = Scope::Elision { elide, s: self.scope };
+        self.with(scope, |_, this| this.visit_ty(output));
+        debug!("visit_fn_like_elision: exit");
+
+        struct GatherLifetimes<'a> {
+            map: &'a NamedRegionMap,
+            outer_index: ty::DebruijnIndex,
+            have_bound_regions: bool,
+            lifetimes: FxHashSet<Region>,
+        }
+
+        impl<'v, 'a> Visitor<'v> for GatherLifetimes<'a> {
+            type Map = intravisit::ErasedMap<'v>;
+
+            fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+                NestedVisitorMap::None
+            }
+
+            fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
+                if let hir::TyKind::BareFn(_) = ty.kind {
+                    self.outer_index.shift_in(1);
+                }
+                match ty.kind {
+                    hir::TyKind::TraitObject(bounds, ref lifetime) => {
+                        for bound in bounds {
+                            self.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
+                        }
+
+                        // Stay on the safe side and don't include the object
+                        // lifetime default (which may not end up being used).
+                        if !lifetime.is_elided() {
+                            self.visit_lifetime(lifetime);
+                        }
+                    }
+                    _ => {
+                        intravisit::walk_ty(self, ty);
+                    }
+                }
+                if let hir::TyKind::BareFn(_) = ty.kind {
+                    self.outer_index.shift_out(1);
+                }
+            }
+
+            fn visit_generic_param(&mut self, param: &hir::GenericParam<'_>) {
+                if let hir::GenericParamKind::Lifetime { .. } = param.kind {
+                    // FIXME(eddyb) Do we want this? It only makes a difference
+                    // if this `for<'a>` lifetime parameter is never used.
+                    self.have_bound_regions = true;
+                }
+
+                intravisit::walk_generic_param(self, param);
+            }
+
+            fn visit_poly_trait_ref(
+                &mut self,
+                trait_ref: &hir::PolyTraitRef<'_>,
+                modifier: hir::TraitBoundModifier,
+            ) {
+                self.outer_index.shift_in(1);
+                intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
+                self.outer_index.shift_out(1);
+            }
+
+            fn visit_param_bound(&mut self, bound: &hir::GenericBound<'_>) {
+                if let hir::GenericBound::LangItemTrait { .. } = bound {
+                    self.outer_index.shift_in(1);
+                    intravisit::walk_param_bound(self, bound);
+                    self.outer_index.shift_out(1);
+                } else {
+                    intravisit::walk_param_bound(self, bound);
+                }
+            }
+
+            fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
+                if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.hir_id) {
+                    match lifetime {
+                        Region::LateBound(debruijn, _, _) | Region::LateBoundAnon(debruijn, _)
+                            if debruijn < self.outer_index =>
+                        {
+                            self.have_bound_regions = true;
+                        }
+                        _ => {
+                            self.lifetimes.insert(lifetime.shifted_out_to_binder(self.outer_index));
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    fn resolve_elided_lifetimes(&mut self, lifetime_refs: Vec<&'tcx hir::Lifetime>) {
+        debug!("resolve_elided_lifetimes(lifetime_refs={:?})", lifetime_refs);
+
+        if lifetime_refs.is_empty() {
+            return;
+        }
+
+        let span = lifetime_refs[0].span;
+        let mut late_depth = 0;
+        let mut scope = self.scope;
+        let mut lifetime_names = FxHashSet::default();
+        let mut lifetime_spans = vec![];
+        let error = loop {
+            match *scope {
+                // Do not assign any resolution, it will be inferred.
+                Scope::Body { .. } => return,
+
+                Scope::Root => break None,
+
+                Scope::Binder { s, ref lifetimes, .. } => {
+                    // collect named lifetimes for suggestions
+                    for name in lifetimes.keys() {
+                        if let hir::ParamName::Plain(name) = name {
+                            lifetime_names.insert(name.name);
+                            lifetime_spans.push(name.span);
+                        }
+                    }
+                    late_depth += 1;
+                    scope = s;
+                }
+
+                Scope::Elision { ref elide, ref s, .. } => {
+                    let lifetime = match *elide {
+                        Elide::FreshLateAnon(ref counter) => {
+                            for lifetime_ref in lifetime_refs {
+                                let lifetime = Region::late_anon(counter).shifted(late_depth);
+                                self.insert_lifetime(lifetime_ref, lifetime);
+                            }
+                            return;
+                        }
+                        Elide::Exact(l) => l.shifted(late_depth),
+                        Elide::Error(ref e) => {
+                            let mut scope = s;
+                            loop {
+                                match scope {
+                                    Scope::Binder { ref lifetimes, s, .. } => {
+                                        // Collect named lifetimes for suggestions.
+                                        for name in lifetimes.keys() {
+                                            if let hir::ParamName::Plain(name) = name {
+                                                lifetime_names.insert(name.name);
+                                                lifetime_spans.push(name.span);
+                                            }
+                                        }
+                                        scope = s;
+                                    }
+                                    Scope::ObjectLifetimeDefault { ref s, .. }
+                                    | Scope::Elision { ref s, .. } => {
+                                        scope = s;
+                                    }
+                                    _ => break,
+                                }
+                            }
+                            break Some(e);
+                        }
+                        Elide::Forbid => break None,
+                    };
+                    for lifetime_ref in lifetime_refs {
+                        self.insert_lifetime(lifetime_ref, lifetime);
+                    }
+                    return;
+                }
+
+                Scope::ObjectLifetimeDefault { s, .. } => {
+                    scope = s;
+                }
+            }
+        };
+
+        let mut err = self.report_missing_lifetime_specifiers(span, lifetime_refs.len());
+
+        if let Some(params) = error {
+            // If there's no lifetime available, suggest `'static`.
+            if self.report_elision_failure(&mut err, params) && lifetime_names.is_empty() {
+                lifetime_names.insert(kw::StaticLifetime);
+            }
+        }
+        self.add_missing_lifetime_specifiers_label(
+            &mut err,
+            span,
+            lifetime_refs.len(),
+            &lifetime_names,
+            lifetime_spans,
+            error.map(|p| &p[..]).unwrap_or(&[]),
+        );
+        err.emit();
+    }
+
+    fn report_elision_failure(
+        &mut self,
+        db: &mut DiagnosticBuilder<'_>,
+        params: &[ElisionFailureInfo],
+    ) -> bool /* add `'static` lifetime to lifetime list */ {
+        let mut m = String::new();
+        let len = params.len();
+
+        let elided_params: Vec<_> =
+            params.iter().cloned().filter(|info| info.lifetime_count > 0).collect();
+
+        let elided_len = elided_params.len();
+
+        for (i, info) in elided_params.into_iter().enumerate() {
+            let ElisionFailureInfo { parent, index, lifetime_count: n, have_bound_regions, span } =
+                info;
+
+            db.span_label(span, "");
+            let help_name = if let Some(ident) =
+                parent.and_then(|body| self.tcx.hir().body(body).params[index].pat.simple_ident())
+            {
+                format!("`{}`", ident)
+            } else {
+                format!("argument {}", index + 1)
+            };
+
+            m.push_str(
+                &(if n == 1 {
+                    help_name
+                } else {
+                    format!(
+                        "one of {}'s {} {}lifetimes",
+                        help_name,
+                        n,
+                        if have_bound_regions { "free " } else { "" }
+                    )
+                })[..],
+            );
+
+            if elided_len == 2 && i == 0 {
+                m.push_str(" or ");
+            } else if i + 2 == elided_len {
+                m.push_str(", or ");
+            } else if i != elided_len - 1 {
+                m.push_str(", ");
+            }
+        }
+
+        if len == 0 {
+            db.help(
+                "this function's return type contains a borrowed value, \
+                 but there is no value for it to be borrowed from",
+            );
+            true
+        } else if elided_len == 0 {
+            db.help(
+                "this function's return type contains a borrowed value with \
+                 an elided lifetime, but the lifetime cannot be derived from \
+                 the arguments",
+            );
+            true
+        } else if elided_len == 1 {
+            db.help(&format!(
+                "this function's return type contains a borrowed value, \
+                 but the signature does not say which {} it is borrowed from",
+                m
+            ));
+            false
+        } else {
+            db.help(&format!(
+                "this function's return type contains a borrowed value, \
+                 but the signature does not say whether it is borrowed from {}",
+                m
+            ));
+            false
+        }
+    }
+
+    fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
+        debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref);
+        let mut late_depth = 0;
+        let mut scope = self.scope;
+        let lifetime = loop {
+            match *scope {
+                Scope::Binder { s, .. } => {
+                    late_depth += 1;
+                    scope = s;
+                }
+
+                Scope::Root | Scope::Elision { .. } => break Region::Static,
+
+                Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
+
+                Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l,
+            }
+        };
+        self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
+    }
+
+    fn check_lifetime_params(
+        &mut self,
+        old_scope: ScopeRef<'_>,
+        params: &'tcx [hir::GenericParam<'tcx>],
+    ) {
+        let lifetimes: Vec<_> = params
+            .iter()
+            .filter_map(|param| match param.kind {
+                GenericParamKind::Lifetime { .. } => {
+                    Some((param, param.name.normalize_to_macros_2_0()))
+                }
+                _ => None,
+            })
+            .collect();
+        for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() {
+            if let hir::ParamName::Plain(_) = lifetime_i_name {
+                let name = lifetime_i_name.ident().name;
+                if name == kw::UnderscoreLifetime || name == kw::StaticLifetime {
+                    let mut err = struct_span_err!(
+                        self.tcx.sess,
+                        lifetime_i.span,
+                        E0262,
+                        "invalid lifetime parameter name: `{}`",
+                        lifetime_i.name.ident(),
+                    );
+                    err.span_label(
+                        lifetime_i.span,
+                        format!("{} is a reserved lifetime name", name),
+                    );
+                    err.emit();
+                }
+            }
+
+            // It is a hard error to shadow a lifetime within the same scope.
+            for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) {
+                if lifetime_i_name == lifetime_j_name {
+                    struct_span_err!(
+                        self.tcx.sess,
+                        lifetime_j.span,
+                        E0263,
+                        "lifetime name `{}` declared twice in the same scope",
+                        lifetime_j.name.ident()
+                    )
+                    .span_label(lifetime_j.span, "declared twice")
+                    .span_label(lifetime_i.span, "previous declaration here")
+                    .emit();
+                }
+            }
+
+            // It is a soft error to shadow a lifetime within a parent scope.
+            self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i);
+
+            for bound in lifetime_i.bounds {
+                match bound {
+                    hir::GenericBound::Outlives(ref lt) => match lt.name {
+                        hir::LifetimeName::Underscore => self.tcx.sess.delay_span_bug(
+                            lt.span,
+                            "use of `'_` in illegal place, but not caught by lowering",
+                        ),
+                        hir::LifetimeName::Static => {
+                            self.insert_lifetime(lt, Region::Static);
+                            self.tcx
+                                .sess
+                                .struct_span_warn(
+                                    lifetime_i.span.to(lt.span),
+                                    &format!(
+                                        "unnecessary lifetime parameter `{}`",
+                                        lifetime_i.name.ident(),
+                                    ),
+                                )
+                                .help(&format!(
+                                    "you can use the `'static` lifetime directly, in place of `{}`",
+                                    lifetime_i.name.ident(),
+                                ))
+                                .emit();
+                        }
+                        hir::LifetimeName::Param(_) | hir::LifetimeName::Implicit => {
+                            self.resolve_lifetime_ref(lt);
+                        }
+                        hir::LifetimeName::ImplicitObjectLifetimeDefault => {
+                            self.tcx.sess.delay_span_bug(
+                                lt.span,
+                                "lowering generated `ImplicitObjectLifetimeDefault` \
+                                 outside of an object type",
+                            )
+                        }
+                        hir::LifetimeName::Error => {
+                            // No need to do anything, error already reported.
+                        }
+                    },
+                    _ => bug!(),
+                }
+            }
+        }
+    }
+
+    fn check_lifetime_param_for_shadowing(
+        &self,
+        mut old_scope: ScopeRef<'_>,
+        param: &'tcx hir::GenericParam<'tcx>,
+    ) {
+        for label in &self.labels_in_fn {
+            // FIXME (#24278): non-hygienic comparison
+            if param.name.ident().name == label.name {
+                signal_shadowing_problem(
+                    self.tcx,
+                    label.name,
+                    original_label(label.span),
+                    shadower_lifetime(&param),
+                );
+                return;
+            }
+        }
+
+        loop {
+            match *old_scope {
+                Scope::Body { s, .. }
+                | Scope::Elision { s, .. }
+                | Scope::ObjectLifetimeDefault { s, .. } => {
+                    old_scope = s;
+                }
+
+                Scope::Root => {
+                    return;
+                }
+
+                Scope::Binder { ref lifetimes, s, .. } => {
+                    if let Some(&def) = lifetimes.get(&param.name.normalize_to_macros_2_0()) {
+                        let hir_id =
+                            self.tcx.hir().local_def_id_to_hir_id(def.id().unwrap().expect_local());
+
+                        signal_shadowing_problem(
+                            self.tcx,
+                            param.name.ident().name,
+                            original_lifetime(self.tcx.hir().span(hir_id)),
+                            shadower_lifetime(&param),
+                        );
+                        return;
+                    }
+
+                    old_scope = s;
+                }
+            }
+        }
+    }
+
+    /// Returns `true` if, in the current scope, replacing `'_` would be
+    /// equivalent to a single-use lifetime.
+    fn track_lifetime_uses(&self) -> bool {
+        let mut scope = self.scope;
+        loop {
+            match *scope {
+                Scope::Root => break false,
+
+                // Inside of items, it depends on the kind of item.
+                Scope::Binder { track_lifetime_uses, .. } => break track_lifetime_uses,
+
+                // Inside a body, `'_` will use an inference variable,
+                // should be fine.
+                Scope::Body { .. } => break true,
+
+                // A lifetime only used in a fn argument could as well
+                // be replaced with `'_`, as that would generate a
+                // fresh name, too.
+                Scope::Elision { elide: Elide::FreshLateAnon(_), .. } => break true,
+
+                // In the return type or other such place, `'_` is not
+                // going to make a fresh name, so we cannot
+                // necessarily replace a single-use lifetime with
+                // `'_`.
+                Scope::Elision {
+                    elide: Elide::Exact(_) | Elide::Error(_) | Elide::Forbid, ..
+                } => break false,
+
+                Scope::ObjectLifetimeDefault { s, .. } => scope = s,
+            }
+        }
+    }
+
+    fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
+        debug!(
+            "insert_lifetime: {} resolved to {:?} span={:?}",
+            self.tcx.hir().node_to_string(lifetime_ref.hir_id),
+            def,
+            self.tcx.sess.source_map().span_to_string(lifetime_ref.span)
+        );
+        self.map.defs.insert(lifetime_ref.hir_id, def);
+
+        match def {
+            Region::LateBoundAnon(..) | Region::Static => {
+                // These are anonymous lifetimes or lifetimes that are not declared.
+            }
+
+            Region::Free(_, def_id)
+            | Region::LateBound(_, def_id, _)
+            | Region::EarlyBound(_, def_id, _) => {
+                // A lifetime declared by the user.
+                let track_lifetime_uses = self.track_lifetime_uses();
+                debug!("insert_lifetime: track_lifetime_uses={}", track_lifetime_uses);
+                if track_lifetime_uses && !self.lifetime_uses.contains_key(&def_id) {
+                    debug!("insert_lifetime: first use of {:?}", def_id);
+                    self.lifetime_uses.insert(def_id, LifetimeUseSet::One(lifetime_ref));
+                } else {
+                    debug!("insert_lifetime: many uses of {:?}", def_id);
+                    self.lifetime_uses.insert(def_id, LifetimeUseSet::Many);
+                }
+            }
+        }
+    }
+
+    /// Sometimes we resolve a lifetime, but later find that it is an
+    /// error (esp. around impl trait). In that case, we remove the
+    /// entry into `map.defs` so as not to confuse later code.
+    fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
+        let old_value = self.map.defs.remove(&lifetime_ref.hir_id);
+        assert_eq!(old_value, Some(bad_def));
+    }
+}
+
+/// Detects late-bound lifetimes and inserts them into
+/// `map.late_bound`.
+///
+/// A region declared on a fn is **late-bound** if:
+/// - it is constrained by an argument type;
+/// - it does not appear in a where-clause.
+///
+/// "Constrained" basically means that it appears in any type but
+/// not amongst the inputs to a projection. In other words, `<&'a
+/// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
+fn insert_late_bound_lifetimes(
+    map: &mut NamedRegionMap,
+    decl: &hir::FnDecl<'_>,
+    generics: &hir::Generics<'_>,
+) {
+    debug!("insert_late_bound_lifetimes(decl={:?}, generics={:?})", decl, generics);
+
+    let mut constrained_by_input = ConstrainedCollector::default();
+    for arg_ty in decl.inputs {
+        constrained_by_input.visit_ty(arg_ty);
+    }
+
+    let mut appears_in_output = AllCollector::default();
+    intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
+
+    debug!("insert_late_bound_lifetimes: constrained_by_input={:?}", constrained_by_input.regions);
+
+    // Walk the lifetimes that appear in where clauses.
+    //
+    // Subtle point: because we disallow nested bindings, we can just
+    // ignore binders here and scrape up all names we see.
+    let mut appears_in_where_clause = AllCollector::default();
+    appears_in_where_clause.visit_generics(generics);
+
+    for param in generics.params {
+        if let hir::GenericParamKind::Lifetime { .. } = param.kind {
+            if !param.bounds.is_empty() {
+                // `'a: 'b` means both `'a` and `'b` are referenced
+                appears_in_where_clause
+                    .regions
+                    .insert(hir::LifetimeName::Param(param.name.normalize_to_macros_2_0()));
+            }
+        }
+    }
+
+    debug!(
+        "insert_late_bound_lifetimes: appears_in_where_clause={:?}",
+        appears_in_where_clause.regions
+    );
+
+    // Late bound regions are those that:
+    // - appear in the inputs
+    // - do not appear in the where-clauses
+    // - are not implicitly captured by `impl Trait`
+    for param in generics.params {
+        match param.kind {
+            hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
+
+            // Neither types nor consts are late-bound.
+            hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue,
+        }
+
+        let lt_name = hir::LifetimeName::Param(param.name.normalize_to_macros_2_0());
+        // appears in the where clauses? early-bound.
+        if appears_in_where_clause.regions.contains(&lt_name) {
+            continue;
+        }
+
+        // does not appear in the inputs, but appears in the return type? early-bound.
+        if !constrained_by_input.regions.contains(&lt_name)
+            && appears_in_output.regions.contains(&lt_name)
+        {
+            continue;
+        }
+
+        debug!(
+            "insert_late_bound_lifetimes: lifetime {:?} with id {:?} is late-bound",
+            param.name.ident(),
+            param.hir_id
+        );
+
+        let inserted = map.late_bound.insert(param.hir_id);
+        assert!(inserted, "visited lifetime {:?} twice", param.hir_id);
+    }
+
+    return;
+
+    #[derive(Default)]
+    struct ConstrainedCollector {
+        regions: FxHashSet<hir::LifetimeName>,
+    }
+
+    impl<'v> Visitor<'v> for ConstrainedCollector {
+        type Map = intravisit::ErasedMap<'v>;
+
+        fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+            NestedVisitorMap::None
+        }
+
+        fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
+            match ty.kind {
+                hir::TyKind::Path(
+                    hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..),
+                ) => {
+                    // ignore lifetimes appearing in associated type
+                    // projections, as they are not *constrained*
+                    // (defined above)
+                }
+
+                hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
+                    // consider only the lifetimes on the final
+                    // segment; I am not sure it's even currently
+                    // valid to have them elsewhere, but even if it
+                    // is, those would be potentially inputs to
+                    // projections
+                    if let Some(last_segment) = path.segments.last() {
+                        self.visit_path_segment(path.span, last_segment);
+                    }
+                }
+
+                _ => {
+                    intravisit::walk_ty(self, ty);
+                }
+            }
+        }
+
+        fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
+            self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());
+        }
+    }
+
+    #[derive(Default)]
+    struct AllCollector {
+        regions: FxHashSet<hir::LifetimeName>,
+    }
+
+    impl<'v> Visitor<'v> for AllCollector {
+        type Map = intravisit::ErasedMap<'v>;
+
+        fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+            NestedVisitorMap::None
+        }
+
+        fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
+            self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());
+        }
+    }
+}
diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs
new file mode 100644
index 0000000..283db14
--- /dev/null
+++ b/compiler/rustc_resolve/src/lib.rs
@@ -0,0 +1,3358 @@
+// ignore-tidy-filelength
+
+//! This crate is responsible for the part of name resolution that doesn't require type checker.
+//!
+//! Module structure of the crate is built here.
+//! Paths in macros, imports, expressions, types, patterns are resolved here.
+//! Label and lifetime names are resolved here as well.
+//!
+//! Type-relative name resolution (methods, fields, associated items) happens in `librustc_typeck`.
+
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
+#![feature(bool_to_option)]
+#![feature(crate_visibility_modifier)]
+#![feature(nll)]
+#![feature(or_patterns)]
+#![recursion_limit = "256"]
+
+pub use rustc_hir::def::{Namespace, PerNS};
+
+use Determinacy::*;
+
+use rustc_arena::TypedArena;
+use rustc_ast::node_id::NodeMap;
+use rustc_ast::unwrap_or;
+use rustc_ast::visit::{self, Visitor};
+use rustc_ast::{self as ast, FloatTy, IntTy, NodeId, UintTy};
+use rustc_ast::{Crate, CRATE_NODE_ID};
+use rustc_ast::{ItemKind, Path};
+use rustc_ast_lowering::ResolverAstLowering;
+use rustc_ast_pretty::pprust;
+use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
+use rustc_data_structures::ptr_key::PtrKey;
+use rustc_data_structures::sync::Lrc;
+use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
+use rustc_expand::base::SyntaxExtension;
+use rustc_hir::def::Namespace::*;
+use rustc_hir::def::{self, CtorOf, DefKind, NonMacroAttrKind, PartialRes};
+use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX};
+use rustc_hir::definitions::{DefKey, DefPathData, Definitions};
+use rustc_hir::PrimTy::{self, Bool, Char, Float, Int, Str, Uint};
+use rustc_hir::TraitCandidate;
+use rustc_index::vec::IndexVec;
+use rustc_metadata::creader::{CStore, CrateLoader};
+use rustc_middle::hir::exports::ExportMap;
+use rustc_middle::middle::cstore::{CrateStore, MetadataLoaderDyn};
+use rustc_middle::ty::query::Providers;
+use rustc_middle::ty::{self, DefIdTree, ResolverOutputs};
+use rustc_middle::{bug, span_bug};
+use rustc_session::lint;
+use rustc_session::lint::{BuiltinLintDiagnostics, LintBuffer};
+use rustc_session::Session;
+use rustc_span::hygiene::{ExpnId, ExpnKind, MacroKind, SyntaxContext, Transparency};
+use rustc_span::source_map::Spanned;
+use rustc_span::symbol::{kw, sym, Ident, Symbol};
+use rustc_span::{Span, DUMMY_SP};
+
+use smallvec::{smallvec, SmallVec};
+use std::cell::{Cell, RefCell};
+use std::collections::BTreeSet;
+use std::{cmp, fmt, iter, ptr};
+use tracing::debug;
+
+use diagnostics::{extend_span_to_previous_binding, find_span_of_binding_until_next_binding};
+use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion};
+use imports::{Import, ImportKind, ImportResolver, NameResolution};
+use late::{HasGenericParams, PathSource, Rib, RibKind::*};
+use macros::{MacroRulesBinding, MacroRulesScope};
+
+type Res = def::Res<NodeId>;
+
+mod build_reduced_graph;
+mod check_unused;
+mod def_collector;
+mod diagnostics;
+mod imports;
+mod late;
+mod macros;
+
+enum Weak {
+    Yes,
+    No,
+}
+
+#[derive(Copy, Clone, PartialEq, Debug)]
+pub enum Determinacy {
+    Determined,
+    Undetermined,
+}
+
+impl Determinacy {
+    fn determined(determined: bool) -> Determinacy {
+        if determined { Determinacy::Determined } else { Determinacy::Undetermined }
+    }
+}
+
+/// A specific scope in which a name can be looked up.
+/// This enum is currently used only for early resolution (imports and macros),
+/// but not for late resolution yet.
+#[derive(Clone, Copy)]
+enum Scope<'a> {
+    DeriveHelpers(ExpnId),
+    DeriveHelpersCompat,
+    MacroRules(MacroRulesScope<'a>),
+    CrateRoot,
+    Module(Module<'a>),
+    RegisteredAttrs,
+    MacroUsePrelude,
+    BuiltinAttrs,
+    ExternPrelude,
+    ToolPrelude,
+    StdLibPrelude,
+    BuiltinTypes,
+}
+
+/// Names from different contexts may want to visit different subsets of all specific scopes
+/// with different restrictions when looking up the resolution.
+/// This enum is currently used only for early resolution (imports and macros),
+/// but not for late resolution yet.
+enum ScopeSet {
+    /// All scopes with the given namespace.
+    All(Namespace, /*is_import*/ bool),
+    /// Crate root, then extern prelude (used for mixed 2015-2018 mode in macros).
+    AbsolutePath(Namespace),
+    /// All scopes with macro namespace and the given macro kind restriction.
+    Macro(MacroKind),
+}
+
+/// Everything you need to know about a name's location to resolve it.
+/// Serves as a starting point for the scope visitor.
+/// This struct is currently used only for early resolution (imports and macros),
+/// but not for late resolution yet.
+#[derive(Clone, Copy, Debug)]
+pub struct ParentScope<'a> {
+    module: Module<'a>,
+    expansion: ExpnId,
+    macro_rules: MacroRulesScope<'a>,
+    derives: &'a [ast::Path],
+}
+
+impl<'a> ParentScope<'a> {
+    /// Creates a parent scope with the passed argument used as the module scope component,
+    /// and other scope components set to default empty values.
+    pub fn module(module: Module<'a>) -> ParentScope<'a> {
+        ParentScope {
+            module,
+            expansion: ExpnId::root(),
+            macro_rules: MacroRulesScope::Empty,
+            derives: &[],
+        }
+    }
+}
+
+#[derive(Eq)]
+struct BindingError {
+    name: Symbol,
+    origin: BTreeSet<Span>,
+    target: BTreeSet<Span>,
+    could_be_path: bool,
+}
+
+impl PartialOrd for BindingError {
+    fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> {
+        Some(self.cmp(other))
+    }
+}
+
+impl PartialEq for BindingError {
+    fn eq(&self, other: &BindingError) -> bool {
+        self.name == other.name
+    }
+}
+
+impl Ord for BindingError {
+    fn cmp(&self, other: &BindingError) -> cmp::Ordering {
+        self.name.cmp(&other.name)
+    }
+}
+
+enum ResolutionError<'a> {
+    /// Error E0401: can't use type or const parameters from outer function.
+    GenericParamsFromOuterFunction(Res, HasGenericParams),
+    /// Error E0403: the name is already used for a type or const parameter in this generic
+    /// parameter list.
+    NameAlreadyUsedInParameterList(Symbol, Span),
+    /// Error E0407: method is not a member of trait.
+    MethodNotMemberOfTrait(Symbol, &'a str),
+    /// Error E0437: type is not a member of trait.
+    TypeNotMemberOfTrait(Symbol, &'a str),
+    /// Error E0438: const is not a member of trait.
+    ConstNotMemberOfTrait(Symbol, &'a str),
+    /// Error E0408: variable `{}` is not bound in all patterns.
+    VariableNotBoundInPattern(&'a BindingError),
+    /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
+    VariableBoundWithDifferentMode(Symbol, Span),
+    /// Error E0415: identifier is bound more than once in this parameter list.
+    IdentifierBoundMoreThanOnceInParameterList(Symbol),
+    /// Error E0416: identifier is bound more than once in the same pattern.
+    IdentifierBoundMoreThanOnceInSamePattern(Symbol),
+    /// Error E0426: use of undeclared label.
+    UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
+    /// Error E0429: `self` imports are only allowed within a `{ }` list.
+    SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span },
+    /// Error E0430: `self` import can only appear once in the list.
+    SelfImportCanOnlyAppearOnceInTheList,
+    /// Error E0431: `self` import can only appear in an import list with a non-empty prefix.
+    SelfImportOnlyInImportListWithNonEmptyPrefix,
+    /// Error E0433: failed to resolve.
+    FailedToResolve { label: String, suggestion: Option<Suggestion> },
+    /// Error E0434: can't capture dynamic environment in a fn item.
+    CannotCaptureDynamicEnvironmentInFnItem,
+    /// Error E0435: attempt to use a non-constant value in a constant.
+    AttemptToUseNonConstantValueInConstant,
+    /// Error E0530: `X` bindings cannot shadow `Y`s.
+    BindingShadowsSomethingUnacceptable(&'static str, Symbol, &'a NameBinding<'a>),
+    /// Error E0128: type parameters with a default cannot use forward-declared identifiers.
+    ForwardDeclaredTyParam, // FIXME(const_generics:defaults)
+    /// ERROR E0770: the type of const parameters must not depend on other generic parameters.
+    ParamInTyOfConstParam(Symbol),
+    /// constant values inside of type parameter defaults must not depend on generic parameters.
+    ParamInAnonConstInTyDefault(Symbol),
+    /// generic parameters must not be used inside of non trivial constant values.
+    ///
+    /// This error is only emitted when using `min_const_generics`.
+    ParamInNonTrivialAnonConst { name: Symbol, is_type: bool },
+    /// Error E0735: type parameters with a default cannot use `Self`
+    SelfInTyParamDefault,
+    /// Error E0767: use of unreachable label
+    UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
+}
+
+enum VisResolutionError<'a> {
+    Relative2018(Span, &'a ast::Path),
+    AncestorOnly(Span),
+    FailedToResolve(Span, String, Option<Suggestion>),
+    ExpectedFound(Span, String, Res),
+    Indeterminate(Span),
+    ModuleOnly(Span),
+}
+
+/// A minimal representation of a path segment. We use this in resolve because we synthesize 'path
+/// segments' which don't have the rest of an AST or HIR `PathSegment`.
+#[derive(Clone, Copy, Debug)]
+pub struct Segment {
+    ident: Ident,
+    id: Option<NodeId>,
+    /// Signals whether this `PathSegment` has generic arguments. Used to avoid providing
+    /// nonsensical suggestions.
+    has_generic_args: bool,
+}
+
+impl Segment {
+    fn from_path(path: &Path) -> Vec<Segment> {
+        path.segments.iter().map(|s| s.into()).collect()
+    }
+
+    fn from_ident(ident: Ident) -> Segment {
+        Segment { ident, id: None, has_generic_args: false }
+    }
+
+    fn names_to_string(segments: &[Segment]) -> String {
+        names_to_string(&segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>())
+    }
+}
+
+impl<'a> From<&'a ast::PathSegment> for Segment {
+    fn from(seg: &'a ast::PathSegment) -> Segment {
+        Segment { ident: seg.ident, id: Some(seg.id), has_generic_args: seg.args.is_some() }
+    }
+}
+
+struct UsePlacementFinder {
+    target_module: NodeId,
+    span: Option<Span>,
+    found_use: bool,
+}
+
+impl UsePlacementFinder {
+    fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, bool) {
+        let mut finder = UsePlacementFinder { target_module, span: None, found_use: false };
+        visit::walk_crate(&mut finder, krate);
+        (finder.span, finder.found_use)
+    }
+}
+
+impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
+    fn visit_mod(
+        &mut self,
+        module: &'tcx ast::Mod,
+        _: Span,
+        _: &[ast::Attribute],
+        node_id: NodeId,
+    ) {
+        if self.span.is_some() {
+            return;
+        }
+        if node_id != self.target_module {
+            visit::walk_mod(self, module);
+            return;
+        }
+        // find a use statement
+        for item in &module.items {
+            match item.kind {
+                ItemKind::Use(..) => {
+                    // don't suggest placing a use before the prelude
+                    // import or other generated ones
+                    if !item.span.from_expansion() {
+                        self.span = Some(item.span.shrink_to_lo());
+                        self.found_use = true;
+                        return;
+                    }
+                }
+                // don't place use before extern crate
+                ItemKind::ExternCrate(_) => {}
+                // but place them before the first other item
+                _ => {
+                    if self.span.map_or(true, |span| item.span < span) {
+                        if !item.span.from_expansion() {
+                            // don't insert between attributes and an item
+                            if item.attrs.is_empty() {
+                                self.span = Some(item.span.shrink_to_lo());
+                            } else {
+                                // find the first attribute on the item
+                                for attr in &item.attrs {
+                                    if self.span.map_or(true, |span| attr.span < span) {
+                                        self.span = Some(attr.span.shrink_to_lo());
+                                    }
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+        }
+    }
+}
+
+/// An intermediate resolution result.
+///
+/// This refers to the thing referred by a name. The difference between `Res` and `Item` is that
+/// items are visible in their whole block, while `Res`es only from the place they are defined
+/// forward.
+#[derive(Debug)]
+enum LexicalScopeBinding<'a> {
+    Item(&'a NameBinding<'a>),
+    Res(Res),
+}
+
+impl<'a> LexicalScopeBinding<'a> {
+    fn res(self) -> Res {
+        match self {
+            LexicalScopeBinding::Item(binding) => binding.res(),
+            LexicalScopeBinding::Res(res) => res,
+        }
+    }
+}
+
+#[derive(Copy, Clone, Debug)]
+enum ModuleOrUniformRoot<'a> {
+    /// Regular module.
+    Module(Module<'a>),
+
+    /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
+    CrateRootAndExternPrelude,
+
+    /// Virtual module that denotes resolution in extern prelude.
+    /// Used for paths starting with `::` on 2018 edition.
+    ExternPrelude,
+
+    /// Virtual module that denotes resolution in current scope.
+    /// Used only for resolving single-segment imports. The reason it exists is that import paths
+    /// are always split into two parts, the first of which should be some kind of module.
+    CurrentScope,
+}
+
+impl ModuleOrUniformRoot<'_> {
+    fn same_def(lhs: Self, rhs: Self) -> bool {
+        match (lhs, rhs) {
+            (ModuleOrUniformRoot::Module(lhs), ModuleOrUniformRoot::Module(rhs)) => {
+                lhs.def_id() == rhs.def_id()
+            }
+            (
+                ModuleOrUniformRoot::CrateRootAndExternPrelude,
+                ModuleOrUniformRoot::CrateRootAndExternPrelude,
+            )
+            | (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude)
+            | (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true,
+            _ => false,
+        }
+    }
+}
+
+#[derive(Clone, Debug)]
+enum PathResult<'a> {
+    Module(ModuleOrUniformRoot<'a>),
+    NonModule(PartialRes),
+    Indeterminate,
+    Failed {
+        span: Span,
+        label: String,
+        suggestion: Option<Suggestion>,
+        is_error_from_last_segment: bool,
+    },
+}
+
+enum ModuleKind {
+    /// An anonymous module; e.g., just a block.
+    ///
+    /// ```
+    /// fn main() {
+    ///     fn f() {} // (1)
+    ///     { // This is an anonymous module
+    ///         f(); // This resolves to (2) as we are inside the block.
+    ///         fn f() {} // (2)
+    ///     }
+    ///     f(); // Resolves to (1)
+    /// }
+    /// ```
+    Block(NodeId),
+    /// Any module with a name.
+    ///
+    /// This could be:
+    ///
+    /// * A normal module ā€’ either `mod from_file;` or `mod from_block { }`.
+    /// * A trait or an enum (it implicitly contains associated types, methods and variant
+    ///   constructors).
+    Def(DefKind, DefId, Symbol),
+}
+
+impl ModuleKind {
+    /// Get name of the module.
+    pub fn name(&self) -> Option<Symbol> {
+        match self {
+            ModuleKind::Block(..) => None,
+            ModuleKind::Def(.., name) => Some(*name),
+        }
+    }
+}
+
+/// A key that identifies a binding in a given `Module`.
+///
+/// Multiple bindings in the same module can have the same key (in a valid
+/// program) if all but one of them come from glob imports.
+#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
+struct BindingKey {
+    /// The identifier for the binding, aways the `normalize_to_macros_2_0` version of the
+    /// identifier.
+    ident: Ident,
+    ns: Namespace,
+    /// 0 if ident is not `_`, otherwise a value that's unique to the specific
+    /// `_` in the expanded AST that introduced this binding.
+    disambiguator: u32,
+}
+
+type Resolutions<'a> = RefCell<FxIndexMap<BindingKey, &'a RefCell<NameResolution<'a>>>>;
+
+/// One node in the tree of modules.
+pub struct ModuleData<'a> {
+    parent: Option<Module<'a>>,
+    kind: ModuleKind,
+
+    // The def id of the closest normal module (`mod`) ancestor (including this module).
+    normal_ancestor_id: DefId,
+
+    // Mapping between names and their (possibly in-progress) resolutions in this module.
+    // Resolutions in modules from other crates are not populated until accessed.
+    lazy_resolutions: Resolutions<'a>,
+    // True if this is a module from other crate that needs to be populated on access.
+    populate_on_access: Cell<bool>,
+
+    // Macro invocations that can expand into items in this module.
+    unexpanded_invocations: RefCell<FxHashSet<ExpnId>>,
+
+    no_implicit_prelude: bool,
+
+    glob_importers: RefCell<Vec<&'a Import<'a>>>,
+    globs: RefCell<Vec<&'a Import<'a>>>,
+
+    // Used to memoize the traits in this module for faster searches through all traits in scope.
+    traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
+
+    /// Span of the module itself. Used for error reporting.
+    span: Span,
+
+    expansion: ExpnId,
+}
+
+type Module<'a> = &'a ModuleData<'a>;
+
+impl<'a> ModuleData<'a> {
+    fn new(
+        parent: Option<Module<'a>>,
+        kind: ModuleKind,
+        normal_ancestor_id: DefId,
+        expansion: ExpnId,
+        span: Span,
+    ) -> Self {
+        ModuleData {
+            parent,
+            kind,
+            normal_ancestor_id,
+            lazy_resolutions: Default::default(),
+            populate_on_access: Cell::new(!normal_ancestor_id.is_local()),
+            unexpanded_invocations: Default::default(),
+            no_implicit_prelude: false,
+            glob_importers: RefCell::new(Vec::new()),
+            globs: RefCell::new(Vec::new()),
+            traits: RefCell::new(None),
+            span,
+            expansion,
+        }
+    }
+
+    fn for_each_child<R, F>(&'a self, resolver: &mut R, mut f: F)
+    where
+        R: AsMut<Resolver<'a>>,
+        F: FnMut(&mut R, Ident, Namespace, &'a NameBinding<'a>),
+    {
+        for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
+            if let Some(binding) = name_resolution.borrow().binding {
+                f(resolver, key.ident, key.ns, binding);
+            }
+        }
+    }
+
+    /// This modifies `self` in place. The traits will be stored in `self.traits`.
+    fn ensure_traits<R>(&'a self, resolver: &mut R)
+    where
+        R: AsMut<Resolver<'a>>,
+    {
+        let mut traits = self.traits.borrow_mut();
+        if traits.is_none() {
+            let mut collected_traits = Vec::new();
+            self.for_each_child(resolver, |_, name, ns, binding| {
+                if ns != TypeNS {
+                    return;
+                }
+                if let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = binding.res() {
+                    collected_traits.push((name, binding))
+                }
+            });
+            *traits = Some(collected_traits.into_boxed_slice());
+        }
+    }
+
+    fn res(&self) -> Option<Res> {
+        match self.kind {
+            ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
+            _ => None,
+        }
+    }
+
+    fn def_id(&self) -> Option<DefId> {
+        match self.kind {
+            ModuleKind::Def(_, def_id, _) => Some(def_id),
+            _ => None,
+        }
+    }
+
+    // `self` resolves to the first module ancestor that `is_normal`.
+    fn is_normal(&self) -> bool {
+        match self.kind {
+            ModuleKind::Def(DefKind::Mod, _, _) => true,
+            _ => false,
+        }
+    }
+
+    fn is_trait(&self) -> bool {
+        match self.kind {
+            ModuleKind::Def(DefKind::Trait, _, _) => true,
+            _ => false,
+        }
+    }
+
+    fn nearest_item_scope(&'a self) -> Module<'a> {
+        match self.kind {
+            ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => {
+                self.parent.expect("enum or trait module without a parent")
+            }
+            _ => self,
+        }
+    }
+
+    fn is_ancestor_of(&self, mut other: &Self) -> bool {
+        while !ptr::eq(self, other) {
+            if let Some(parent) = other.parent {
+                other = parent;
+            } else {
+                return false;
+            }
+        }
+        true
+    }
+}
+
+impl<'a> fmt::Debug for ModuleData<'a> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        write!(f, "{:?}", self.res())
+    }
+}
+
+/// Records a possibly-private value, type, or module definition.
+#[derive(Clone, Debug)]
+pub struct NameBinding<'a> {
+    kind: NameBindingKind<'a>,
+    ambiguity: Option<(&'a NameBinding<'a>, AmbiguityKind)>,
+    expansion: ExpnId,
+    span: Span,
+    vis: ty::Visibility,
+}
+
+pub trait ToNameBinding<'a> {
+    fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
+}
+
+impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
+    fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
+        self
+    }
+}
+
+#[derive(Clone, Debug)]
+enum NameBindingKind<'a> {
+    Res(Res, /* is_macro_export */ bool),
+    Module(Module<'a>),
+    Import { binding: &'a NameBinding<'a>, import: &'a Import<'a>, used: Cell<bool> },
+}
+
+impl<'a> NameBindingKind<'a> {
+    /// Is this a name binding of a import?
+    fn is_import(&self) -> bool {
+        match *self {
+            NameBindingKind::Import { .. } => true,
+            _ => false,
+        }
+    }
+}
+
+struct PrivacyError<'a> {
+    ident: Ident,
+    binding: &'a NameBinding<'a>,
+    dedup_span: Span,
+}
+
+struct UseError<'a> {
+    err: DiagnosticBuilder<'a>,
+    /// Candidates which user could `use` to access the missing type.
+    candidates: Vec<ImportSuggestion>,
+    /// The `DefId` of the module to place the use-statements in.
+    def_id: DefId,
+    /// Whether the diagnostic should say "instead" (as in `consider importing ... instead`).
+    instead: bool,
+    /// Extra free-form suggestion.
+    suggestion: Option<(Span, &'static str, String, Applicability)>,
+}
+
+#[derive(Clone, Copy, PartialEq, Debug)]
+enum AmbiguityKind {
+    Import,
+    BuiltinAttr,
+    DeriveHelper,
+    MacroRulesVsModularized,
+    GlobVsOuter,
+    GlobVsGlob,
+    GlobVsExpanded,
+    MoreExpandedVsOuter,
+}
+
+impl AmbiguityKind {
+    fn descr(self) -> &'static str {
+        match self {
+            AmbiguityKind::Import => "name vs any other name during import resolution",
+            AmbiguityKind::BuiltinAttr => "built-in attribute vs any other name",
+            AmbiguityKind::DeriveHelper => "derive helper attribute vs any other name",
+            AmbiguityKind::MacroRulesVsModularized => {
+                "`macro_rules` vs non-`macro_rules` from other module"
+            }
+            AmbiguityKind::GlobVsOuter => {
+                "glob import vs any other name from outer scope during import/macro resolution"
+            }
+            AmbiguityKind::GlobVsGlob => "glob import vs glob import in the same module",
+            AmbiguityKind::GlobVsExpanded => {
+                "glob import vs macro-expanded name in the same \
+                 module during import/macro resolution"
+            }
+            AmbiguityKind::MoreExpandedVsOuter => {
+                "macro-expanded name vs less macro-expanded name \
+                 from outer scope during import/macro resolution"
+            }
+        }
+    }
+}
+
+/// Miscellaneous bits of metadata for better ambiguity error reporting.
+#[derive(Clone, Copy, PartialEq)]
+enum AmbiguityErrorMisc {
+    SuggestCrate,
+    SuggestSelf,
+    FromPrelude,
+    None,
+}
+
+struct AmbiguityError<'a> {
+    kind: AmbiguityKind,
+    ident: Ident,
+    b1: &'a NameBinding<'a>,
+    b2: &'a NameBinding<'a>,
+    misc1: AmbiguityErrorMisc,
+    misc2: AmbiguityErrorMisc,
+}
+
+impl<'a> NameBinding<'a> {
+    fn module(&self) -> Option<Module<'a>> {
+        match self.kind {
+            NameBindingKind::Module(module) => Some(module),
+            NameBindingKind::Import { binding, .. } => binding.module(),
+            _ => None,
+        }
+    }
+
+    fn res(&self) -> Res {
+        match self.kind {
+            NameBindingKind::Res(res, _) => res,
+            NameBindingKind::Module(module) => module.res().unwrap(),
+            NameBindingKind::Import { binding, .. } => binding.res(),
+        }
+    }
+
+    fn is_ambiguity(&self) -> bool {
+        self.ambiguity.is_some()
+            || match self.kind {
+                NameBindingKind::Import { binding, .. } => binding.is_ambiguity(),
+                _ => false,
+            }
+    }
+
+    fn is_possibly_imported_variant(&self) -> bool {
+        match self.kind {
+            NameBindingKind::Import { binding, .. } => binding.is_possibly_imported_variant(),
+            _ => self.is_variant(),
+        }
+    }
+
+    // We sometimes need to treat variants as `pub` for backwards compatibility.
+    fn pseudo_vis(&self) -> ty::Visibility {
+        if self.is_variant() && self.res().def_id().is_local() {
+            ty::Visibility::Public
+        } else {
+            self.vis
+        }
+    }
+
+    fn is_variant(&self) -> bool {
+        match self.kind {
+            NameBindingKind::Res(
+                Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _),
+                _,
+            ) => true,
+            _ => false,
+        }
+    }
+
+    fn is_extern_crate(&self) -> bool {
+        match self.kind {
+            NameBindingKind::Import {
+                import: &Import { kind: ImportKind::ExternCrate { .. }, .. },
+                ..
+            } => true,
+            NameBindingKind::Module(&ModuleData {
+                kind: ModuleKind::Def(DefKind::Mod, def_id, _),
+                ..
+            }) => def_id.index == CRATE_DEF_INDEX,
+            _ => false,
+        }
+    }
+
+    fn is_import(&self) -> bool {
+        match self.kind {
+            NameBindingKind::Import { .. } => true,
+            _ => false,
+        }
+    }
+
+    fn is_glob_import(&self) -> bool {
+        match self.kind {
+            NameBindingKind::Import { import, .. } => import.is_glob(),
+            _ => false,
+        }
+    }
+
+    fn is_importable(&self) -> bool {
+        match self.res() {
+            Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _) => false,
+            _ => true,
+        }
+    }
+
+    fn is_macro_def(&self) -> bool {
+        match self.kind {
+            NameBindingKind::Res(Res::Def(DefKind::Macro(..), _), _) => true,
+            _ => false,
+        }
+    }
+
+    fn macro_kind(&self) -> Option<MacroKind> {
+        self.res().macro_kind()
+    }
+
+    // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
+    // at some expansion round `max(invoc, binding)` when they both emerged from macros.
+    // Then this function returns `true` if `self` may emerge from a macro *after* that
+    // in some later round and screw up our previously found resolution.
+    // See more detailed explanation in
+    // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
+    fn may_appear_after(&self, invoc_parent_expansion: ExpnId, binding: &NameBinding<'_>) -> bool {
+        // self > max(invoc, binding) => !(self <= invoc || self <= binding)
+        // Expansions are partially ordered, so "may appear after" is an inversion of
+        // "certainly appears before or simultaneously" and includes unordered cases.
+        let self_parent_expansion = self.expansion;
+        let other_parent_expansion = binding.expansion;
+        let certainly_before_other_or_simultaneously =
+            other_parent_expansion.is_descendant_of(self_parent_expansion);
+        let certainly_before_invoc_or_simultaneously =
+            invoc_parent_expansion.is_descendant_of(self_parent_expansion);
+        !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
+    }
+}
+
+/// Interns the names of the primitive types.
+///
+/// All other types are defined somewhere and possibly imported, but the primitive ones need
+/// special handling, since they have no place of origin.
+struct PrimitiveTypeTable {
+    primitive_types: FxHashMap<Symbol, PrimTy>,
+}
+
+impl PrimitiveTypeTable {
+    fn new() -> PrimitiveTypeTable {
+        let mut table = FxHashMap::default();
+
+        table.insert(sym::bool, Bool);
+        table.insert(sym::char, Char);
+        table.insert(sym::f32, Float(FloatTy::F32));
+        table.insert(sym::f64, Float(FloatTy::F64));
+        table.insert(sym::isize, Int(IntTy::Isize));
+        table.insert(sym::i8, Int(IntTy::I8));
+        table.insert(sym::i16, Int(IntTy::I16));
+        table.insert(sym::i32, Int(IntTy::I32));
+        table.insert(sym::i64, Int(IntTy::I64));
+        table.insert(sym::i128, Int(IntTy::I128));
+        table.insert(sym::str, Str);
+        table.insert(sym::usize, Uint(UintTy::Usize));
+        table.insert(sym::u8, Uint(UintTy::U8));
+        table.insert(sym::u16, Uint(UintTy::U16));
+        table.insert(sym::u32, Uint(UintTy::U32));
+        table.insert(sym::u64, Uint(UintTy::U64));
+        table.insert(sym::u128, Uint(UintTy::U128));
+        Self { primitive_types: table }
+    }
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct ExternPreludeEntry<'a> {
+    extern_crate_item: Option<&'a NameBinding<'a>>,
+    pub introduced_by_item: bool,
+}
+
+/// Used for better errors for E0773
+enum BuiltinMacroState {
+    NotYetSeen(SyntaxExtension),
+    AlreadySeen(Span),
+}
+
+/// The main resolver class.
+///
+/// This is the visitor that walks the whole crate.
+pub struct Resolver<'a> {
+    session: &'a Session,
+
+    definitions: Definitions,
+
+    graph_root: Module<'a>,
+
+    prelude: Option<Module<'a>>,
+    extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
+
+    /// N.B., this is used only for better diagnostics, not name resolution itself.
+    has_self: FxHashSet<DefId>,
+
+    /// Names of fields of an item `DefId` accessible with dot syntax.
+    /// Used for hints during error reporting.
+    field_names: FxHashMap<DefId, Vec<Spanned<Symbol>>>,
+
+    /// All imports known to succeed or fail.
+    determined_imports: Vec<&'a Import<'a>>,
+
+    /// All non-determined imports.
+    indeterminate_imports: Vec<&'a Import<'a>>,
+
+    /// FIXME: Refactor things so that these fields are passed through arguments and not resolver.
+    /// We are resolving a last import segment during import validation.
+    last_import_segment: bool,
+    /// This binding should be ignored during in-module resolution, so that we don't get
+    /// "self-confirming" import resolutions during import validation.
+    unusable_binding: Option<&'a NameBinding<'a>>,
+
+    /// The idents for the primitive types.
+    primitive_type_table: PrimitiveTypeTable,
+
+    /// Resolutions for nodes that have a single resolution.
+    partial_res_map: NodeMap<PartialRes>,
+    /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
+    import_res_map: NodeMap<PerNS<Option<Res>>>,
+    /// Resolutions for labels (node IDs of their corresponding blocks or loops).
+    label_res_map: NodeMap<NodeId>,
+
+    /// `CrateNum` resolutions of `extern crate` items.
+    extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
+    export_map: ExportMap<LocalDefId>,
+    trait_map: NodeMap<Vec<TraitCandidate>>,
+
+    /// A map from nodes to anonymous modules.
+    /// Anonymous modules are pseudo-modules that are implicitly created around items
+    /// contained within blocks.
+    ///
+    /// For example, if we have this:
+    ///
+    ///  fn f() {
+    ///      fn g() {
+    ///          ...
+    ///      }
+    ///  }
+    ///
+    /// There will be an anonymous module created around `g` with the ID of the
+    /// entry block for `f`.
+    block_map: NodeMap<Module<'a>>,
+    /// A fake module that contains no definition and no prelude. Used so that
+    /// some AST passes can generate identifiers that only resolve to local or
+    /// language items.
+    empty_module: Module<'a>,
+    module_map: FxHashMap<LocalDefId, Module<'a>>,
+    extern_module_map: FxHashMap<DefId, Module<'a>>,
+    binding_parent_modules: FxHashMap<PtrKey<'a, NameBinding<'a>>, Module<'a>>,
+    underscore_disambiguator: u32,
+
+    /// Maps glob imports to the names of items actually imported.
+    glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
+
+    used_imports: FxHashSet<(NodeId, Namespace)>,
+    maybe_unused_trait_imports: FxHashSet<LocalDefId>,
+    maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
+
+    /// Privacy errors are delayed until the end in order to deduplicate them.
+    privacy_errors: Vec<PrivacyError<'a>>,
+    /// Ambiguity errors are delayed for deduplication.
+    ambiguity_errors: Vec<AmbiguityError<'a>>,
+    /// `use` injections are delayed for better placement and deduplication.
+    use_injections: Vec<UseError<'a>>,
+    /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
+    macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
+
+    arenas: &'a ResolverArenas<'a>,
+    dummy_binding: &'a NameBinding<'a>,
+
+    crate_loader: CrateLoader<'a>,
+    macro_names: FxHashSet<Ident>,
+    builtin_macros: FxHashMap<Symbol, BuiltinMacroState>,
+    registered_attrs: FxHashSet<Ident>,
+    registered_tools: FxHashSet<Ident>,
+    macro_use_prelude: FxHashMap<Symbol, &'a NameBinding<'a>>,
+    all_macros: FxHashMap<Symbol, Res>,
+    macro_map: FxHashMap<DefId, Lrc<SyntaxExtension>>,
+    dummy_ext_bang: Lrc<SyntaxExtension>,
+    dummy_ext_derive: Lrc<SyntaxExtension>,
+    non_macro_attrs: [Lrc<SyntaxExtension>; 2],
+    local_macro_def_scopes: FxHashMap<LocalDefId, Module<'a>>,
+    ast_transform_scopes: FxHashMap<ExpnId, Module<'a>>,
+    unused_macros: FxHashMap<LocalDefId, (NodeId, Span)>,
+    proc_macro_stubs: FxHashSet<LocalDefId>,
+    /// Traces collected during macro resolution and validated when it's complete.
+    single_segment_macro_resolutions:
+        Vec<(Ident, MacroKind, ParentScope<'a>, Option<&'a NameBinding<'a>>)>,
+    multi_segment_macro_resolutions:
+        Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>, Option<Res>)>,
+    builtin_attrs: Vec<(Ident, ParentScope<'a>)>,
+    /// `derive(Copy)` marks items they are applied to so they are treated specially later.
+    /// Derive macros cannot modify the item themselves and have to store the markers in the global
+    /// context, so they attach the markers to derive container IDs using this resolver table.
+    containers_deriving_copy: FxHashSet<ExpnId>,
+    /// Parent scopes in which the macros were invoked.
+    /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere.
+    invocation_parent_scopes: FxHashMap<ExpnId, ParentScope<'a>>,
+    /// `macro_rules` scopes *produced* by expanding the macro invocations,
+    /// include all the `macro_rules` items and other invocations generated by them.
+    output_macro_rules_scopes: FxHashMap<ExpnId, MacroRulesScope<'a>>,
+    /// Helper attributes that are in scope for the given expansion.
+    helper_attrs: FxHashMap<ExpnId, Vec<Ident>>,
+
+    /// Avoid duplicated errors for "name already defined".
+    name_already_seen: FxHashMap<Symbol, Span>,
+
+    potentially_unused_imports: Vec<&'a Import<'a>>,
+
+    /// Table for mapping struct IDs into struct constructor IDs,
+    /// it's not used during normal resolution, only for better error reporting.
+    /// Also includes of list of each fields visibility
+    struct_constructors: DefIdMap<(Res, ty::Visibility, Vec<ty::Visibility>)>,
+
+    /// Features enabled for this crate.
+    active_features: FxHashSet<Symbol>,
+
+    /// Stores enum visibilities to properly build a reduced graph
+    /// when visiting the correspondent variants.
+    variant_vis: DefIdMap<ty::Visibility>,
+
+    lint_buffer: LintBuffer,
+
+    next_node_id: NodeId,
+
+    def_id_to_span: IndexVec<LocalDefId, Span>,
+
+    node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>,
+    def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>,
+
+    /// Indices of unnamed struct or variant fields with unresolved attributes.
+    placeholder_field_indices: FxHashMap<NodeId, usize>,
+    /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
+    /// we know what parent node that fragment should be attached to thanks to this table.
+    invocation_parents: FxHashMap<ExpnId, LocalDefId>,
+
+    next_disambiguator: FxHashMap<(LocalDefId, DefPathData), u32>,
+}
+
+/// Nothing really interesting here; it just provides memory for the rest of the crate.
+#[derive(Default)]
+pub struct ResolverArenas<'a> {
+    modules: TypedArena<ModuleData<'a>>,
+    local_modules: RefCell<Vec<Module<'a>>>,
+    name_bindings: TypedArena<NameBinding<'a>>,
+    imports: TypedArena<Import<'a>>,
+    name_resolutions: TypedArena<RefCell<NameResolution<'a>>>,
+    macro_rules_bindings: TypedArena<MacroRulesBinding<'a>>,
+    ast_paths: TypedArena<ast::Path>,
+    pattern_spans: TypedArena<Span>,
+}
+
+impl<'a> ResolverArenas<'a> {
+    fn alloc_module(&'a self, module: ModuleData<'a>) -> Module<'a> {
+        let module = self.modules.alloc(module);
+        if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) {
+            self.local_modules.borrow_mut().push(module);
+        }
+        module
+    }
+    fn local_modules(&'a self) -> std::cell::Ref<'a, Vec<Module<'a>>> {
+        self.local_modules.borrow()
+    }
+    fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
+        self.name_bindings.alloc(name_binding)
+    }
+    fn alloc_import(&'a self, import: Import<'a>) -> &'a Import<'_> {
+        self.imports.alloc(import)
+    }
+    fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
+        self.name_resolutions.alloc(Default::default())
+    }
+    fn alloc_macro_rules_binding(
+        &'a self,
+        binding: MacroRulesBinding<'a>,
+    ) -> &'a MacroRulesBinding<'a> {
+        self.macro_rules_bindings.alloc(binding)
+    }
+    fn alloc_ast_paths(&'a self, paths: &[ast::Path]) -> &'a [ast::Path] {
+        self.ast_paths.alloc_from_iter(paths.iter().cloned())
+    }
+    fn alloc_pattern_spans(&'a self, spans: impl Iterator<Item = Span>) -> &'a [Span] {
+        self.pattern_spans.alloc_from_iter(spans)
+    }
+}
+
+impl<'a> AsMut<Resolver<'a>> for Resolver<'a> {
+    fn as_mut(&mut self) -> &mut Resolver<'a> {
+        self
+    }
+}
+
+impl<'a, 'b> DefIdTree for &'a Resolver<'b> {
+    fn parent(self, id: DefId) -> Option<DefId> {
+        match id.as_local() {
+            Some(id) => self.definitions.def_key(id).parent,
+            None => self.cstore().def_key(id).parent,
+        }
+        .map(|index| DefId { index, ..id })
+    }
+}
+
+/// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that
+/// the resolver is no longer needed as all the relevant information is inline.
+impl ResolverAstLowering for Resolver<'_> {
+    fn def_key(&mut self, id: DefId) -> DefKey {
+        if let Some(id) = id.as_local() {
+            self.definitions().def_key(id)
+        } else {
+            self.cstore().def_key(id)
+        }
+    }
+
+    fn item_generics_num_lifetimes(&self, def_id: DefId, sess: &Session) -> usize {
+        self.cstore().item_generics_num_lifetimes(def_id, sess)
+    }
+
+    fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes> {
+        self.partial_res_map.get(&id).cloned()
+    }
+
+    fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res>> {
+        self.import_res_map.get(&id).cloned().unwrap_or_default()
+    }
+
+    fn get_label_res(&mut self, id: NodeId) -> Option<NodeId> {
+        self.label_res_map.get(&id).cloned()
+    }
+
+    fn definitions(&mut self) -> &mut Definitions {
+        &mut self.definitions
+    }
+
+    fn lint_buffer(&mut self) -> &mut LintBuffer {
+        &mut self.lint_buffer
+    }
+
+    fn next_node_id(&mut self) -> NodeId {
+        self.next_node_id()
+    }
+
+    fn trait_map(&self) -> &NodeMap<Vec<TraitCandidate>> {
+        &self.trait_map
+    }
+
+    fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
+        self.node_id_to_def_id.get(&node).copied()
+    }
+
+    fn local_def_id(&self, node: NodeId) -> LocalDefId {
+        self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node))
+    }
+
+    /// Adds a definition with a parent definition.
+    fn create_def(
+        &mut self,
+        parent: LocalDefId,
+        node_id: ast::NodeId,
+        data: DefPathData,
+        expn_id: ExpnId,
+        span: Span,
+    ) -> LocalDefId {
+        assert!(
+            !self.node_id_to_def_id.contains_key(&node_id),
+            "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
+            node_id,
+            data,
+            self.definitions.def_key(self.node_id_to_def_id[&node_id]),
+        );
+
+        // Find the next free disambiguator for this key.
+        let next_disambiguator = &mut self.next_disambiguator;
+        let next_disambiguator = |parent, data| {
+            let next_disamb = next_disambiguator.entry((parent, data)).or_insert(0);
+            let disambiguator = *next_disamb;
+            *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow");
+            disambiguator
+        };
+
+        let def_id = self.definitions.create_def(parent, data, expn_id, next_disambiguator);
+
+        assert_eq!(self.def_id_to_span.push(span), def_id);
+
+        // Some things for which we allocate `LocalDefId`s don't correspond to
+        // anything in the AST, so they don't have a `NodeId`. For these cases
+        // we don't need a mapping from `NodeId` to `LocalDefId`.
+        if node_id != ast::DUMMY_NODE_ID {
+            debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
+            self.node_id_to_def_id.insert(node_id, def_id);
+        }
+        assert_eq!(self.def_id_to_node_id.push(node_id), def_id);
+
+        def_id
+    }
+}
+
+impl<'a> Resolver<'a> {
+    pub fn new(
+        session: &'a Session,
+        krate: &Crate,
+        crate_name: &str,
+        metadata_loader: &'a MetadataLoaderDyn,
+        arenas: &'a ResolverArenas<'a>,
+    ) -> Resolver<'a> {
+        let root_def_id = DefId::local(CRATE_DEF_INDEX);
+        let root_module_kind = ModuleKind::Def(DefKind::Mod, root_def_id, kw::Invalid);
+        let graph_root = arenas.alloc_module(ModuleData {
+            no_implicit_prelude: session.contains_name(&krate.attrs, sym::no_implicit_prelude),
+            ..ModuleData::new(None, root_module_kind, root_def_id, ExpnId::root(), krate.span)
+        });
+        let empty_module_kind = ModuleKind::Def(DefKind::Mod, root_def_id, kw::Invalid);
+        let empty_module = arenas.alloc_module(ModuleData {
+            no_implicit_prelude: true,
+            ..ModuleData::new(
+                Some(graph_root),
+                empty_module_kind,
+                root_def_id,
+                ExpnId::root(),
+                DUMMY_SP,
+            )
+        });
+        let mut module_map = FxHashMap::default();
+        module_map.insert(LocalDefId { local_def_index: CRATE_DEF_INDEX }, graph_root);
+
+        let definitions = Definitions::new(crate_name, session.local_crate_disambiguator());
+        let root = definitions.get_root_def();
+
+        let mut def_id_to_span = IndexVec::default();
+        assert_eq!(def_id_to_span.push(rustc_span::DUMMY_SP), root);
+        let mut def_id_to_node_id = IndexVec::default();
+        assert_eq!(def_id_to_node_id.push(CRATE_NODE_ID), root);
+        let mut node_id_to_def_id = FxHashMap::default();
+        node_id_to_def_id.insert(CRATE_NODE_ID, root);
+
+        let mut invocation_parents = FxHashMap::default();
+        invocation_parents.insert(ExpnId::root(), root);
+
+        let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'_>> = session
+            .opts
+            .externs
+            .iter()
+            .filter(|(_, entry)| entry.add_prelude)
+            .map(|(name, _)| (Ident::from_str(name), Default::default()))
+            .collect();
+
+        if !session.contains_name(&krate.attrs, sym::no_core) {
+            extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default());
+            if !session.contains_name(&krate.attrs, sym::no_std) {
+                extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default());
+                if session.rust_2018() {
+                    extern_prelude.insert(Ident::with_dummy_span(sym::meta), Default::default());
+                }
+            }
+        }
+
+        let (registered_attrs, registered_tools) =
+            macros::registered_attrs_and_tools(session, &krate.attrs);
+
+        let mut invocation_parent_scopes = FxHashMap::default();
+        invocation_parent_scopes.insert(ExpnId::root(), ParentScope::module(graph_root));
+
+        let features = session.features_untracked();
+        let non_macro_attr =
+            |mark_used| Lrc::new(SyntaxExtension::non_macro_attr(mark_used, session.edition()));
+
+        Resolver {
+            session,
+
+            definitions,
+
+            // The outermost module has def ID 0; this is not reflected in the
+            // AST.
+            graph_root,
+            prelude: None,
+            extern_prelude,
+
+            has_self: FxHashSet::default(),
+            field_names: FxHashMap::default(),
+
+            determined_imports: Vec::new(),
+            indeterminate_imports: Vec::new(),
+
+            last_import_segment: false,
+            unusable_binding: None,
+
+            primitive_type_table: PrimitiveTypeTable::new(),
+
+            partial_res_map: Default::default(),
+            import_res_map: Default::default(),
+            label_res_map: Default::default(),
+            extern_crate_map: Default::default(),
+            export_map: FxHashMap::default(),
+            trait_map: Default::default(),
+            underscore_disambiguator: 0,
+            empty_module,
+            module_map,
+            block_map: Default::default(),
+            extern_module_map: FxHashMap::default(),
+            binding_parent_modules: FxHashMap::default(),
+            ast_transform_scopes: FxHashMap::default(),
+
+            glob_map: Default::default(),
+
+            used_imports: FxHashSet::default(),
+            maybe_unused_trait_imports: Default::default(),
+            maybe_unused_extern_crates: Vec::new(),
+
+            privacy_errors: Vec::new(),
+            ambiguity_errors: Vec::new(),
+            use_injections: Vec::new(),
+            macro_expanded_macro_export_errors: BTreeSet::new(),
+
+            arenas,
+            dummy_binding: arenas.alloc_name_binding(NameBinding {
+                kind: NameBindingKind::Res(Res::Err, false),
+                ambiguity: None,
+                expansion: ExpnId::root(),
+                span: DUMMY_SP,
+                vis: ty::Visibility::Public,
+            }),
+
+            crate_loader: CrateLoader::new(session, metadata_loader, crate_name),
+            macro_names: FxHashSet::default(),
+            builtin_macros: Default::default(),
+            registered_attrs,
+            registered_tools,
+            macro_use_prelude: FxHashMap::default(),
+            all_macros: FxHashMap::default(),
+            macro_map: FxHashMap::default(),
+            dummy_ext_bang: Lrc::new(SyntaxExtension::dummy_bang(session.edition())),
+            dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(session.edition())),
+            non_macro_attrs: [non_macro_attr(false), non_macro_attr(true)],
+            invocation_parent_scopes,
+            output_macro_rules_scopes: Default::default(),
+            helper_attrs: Default::default(),
+            local_macro_def_scopes: FxHashMap::default(),
+            name_already_seen: FxHashMap::default(),
+            potentially_unused_imports: Vec::new(),
+            struct_constructors: Default::default(),
+            unused_macros: Default::default(),
+            proc_macro_stubs: Default::default(),
+            single_segment_macro_resolutions: Default::default(),
+            multi_segment_macro_resolutions: Default::default(),
+            builtin_attrs: Default::default(),
+            containers_deriving_copy: Default::default(),
+            active_features: features
+                .declared_lib_features
+                .iter()
+                .map(|(feat, ..)| *feat)
+                .chain(features.declared_lang_features.iter().map(|(feat, ..)| *feat))
+                .collect(),
+            variant_vis: Default::default(),
+            lint_buffer: LintBuffer::default(),
+            next_node_id: NodeId::from_u32(1),
+            def_id_to_span,
+            node_id_to_def_id,
+            def_id_to_node_id,
+            placeholder_field_indices: Default::default(),
+            invocation_parents,
+            next_disambiguator: Default::default(),
+        }
+    }
+
+    pub fn next_node_id(&mut self) -> NodeId {
+        let next = self
+            .next_node_id
+            .as_usize()
+            .checked_add(1)
+            .expect("input too large; ran out of NodeIds");
+        self.next_node_id = ast::NodeId::from_usize(next);
+        self.next_node_id
+    }
+
+    pub fn lint_buffer(&mut self) -> &mut LintBuffer {
+        &mut self.lint_buffer
+    }
+
+    pub fn arenas() -> ResolverArenas<'a> {
+        Default::default()
+    }
+
+    pub fn into_outputs(self) -> ResolverOutputs {
+        let definitions = self.definitions;
+        let extern_crate_map = self.extern_crate_map;
+        let export_map = self.export_map;
+        let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
+        let maybe_unused_extern_crates = self.maybe_unused_extern_crates;
+        let glob_map = self.glob_map;
+        ResolverOutputs {
+            definitions: definitions,
+            cstore: Box::new(self.crate_loader.into_cstore()),
+            extern_crate_map,
+            export_map,
+            glob_map,
+            maybe_unused_trait_imports,
+            maybe_unused_extern_crates,
+            extern_prelude: self
+                .extern_prelude
+                .iter()
+                .map(|(ident, entry)| (ident.name, entry.introduced_by_item))
+                .collect(),
+        }
+    }
+
+    pub fn clone_outputs(&self) -> ResolverOutputs {
+        ResolverOutputs {
+            definitions: self.definitions.clone(),
+            cstore: Box::new(self.cstore().clone()),
+            extern_crate_map: self.extern_crate_map.clone(),
+            export_map: self.export_map.clone(),
+            glob_map: self.glob_map.clone(),
+            maybe_unused_trait_imports: self.maybe_unused_trait_imports.clone(),
+            maybe_unused_extern_crates: self.maybe_unused_extern_crates.clone(),
+            extern_prelude: self
+                .extern_prelude
+                .iter()
+                .map(|(ident, entry)| (ident.name, entry.introduced_by_item))
+                .collect(),
+        }
+    }
+
+    pub fn cstore(&self) -> &CStore {
+        self.crate_loader.cstore()
+    }
+
+    fn non_macro_attr(&self, mark_used: bool) -> Lrc<SyntaxExtension> {
+        self.non_macro_attrs[mark_used as usize].clone()
+    }
+
+    fn dummy_ext(&self, macro_kind: MacroKind) -> Lrc<SyntaxExtension> {
+        match macro_kind {
+            MacroKind::Bang => self.dummy_ext_bang.clone(),
+            MacroKind::Derive => self.dummy_ext_derive.clone(),
+            MacroKind::Attr => self.non_macro_attr(true),
+        }
+    }
+
+    /// Runs the function on each namespace.
+    fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
+        f(self, TypeNS);
+        f(self, ValueNS);
+        f(self, MacroNS);
+    }
+
+    fn is_builtin_macro(&mut self, res: Res) -> bool {
+        self.get_macro(res).map_or(false, |ext| ext.is_builtin)
+    }
+
+    fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
+        loop {
+            match ctxt.outer_expn().expn_data().macro_def_id {
+                Some(def_id) => return def_id,
+                None => ctxt.remove_mark(),
+            };
+        }
+    }
+
+    /// Entry point to crate resolution.
+    pub fn resolve_crate(&mut self, krate: &Crate) {
+        let _prof_timer = self.session.prof.generic_activity("resolve_crate");
+
+        ImportResolver { r: self }.finalize_imports();
+        self.finalize_macro_resolutions();
+
+        self.late_resolve_crate(krate);
+
+        self.check_unused(krate);
+        self.report_errors(krate);
+        self.crate_loader.postprocess(krate);
+    }
+
+    fn get_traits_in_module_containing_item(
+        &mut self,
+        ident: Ident,
+        ns: Namespace,
+        module: Module<'a>,
+        found_traits: &mut Vec<TraitCandidate>,
+        parent_scope: &ParentScope<'a>,
+    ) {
+        assert!(ns == TypeNS || ns == ValueNS);
+        module.ensure_traits(self);
+        let traits = module.traits.borrow();
+
+        for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
+            // Traits have pseudo-modules that can be used to search for the given ident.
+            if let Some(module) = binding.module() {
+                let mut ident = ident;
+                if ident.span.glob_adjust(module.expansion, binding.span).is_none() {
+                    continue;
+                }
+                if self
+                    .resolve_ident_in_module_unadjusted(
+                        ModuleOrUniformRoot::Module(module),
+                        ident,
+                        ns,
+                        parent_scope,
+                        false,
+                        module.span,
+                    )
+                    .is_ok()
+                {
+                    let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
+                    let trait_def_id = module.def_id().unwrap();
+                    found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
+                }
+            } else if let Res::Def(DefKind::TraitAlias, _) = binding.res() {
+                // For now, just treat all trait aliases as possible candidates, since we don't
+                // know if the ident is somewhere in the transitive bounds.
+                let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
+                let trait_def_id = binding.res().def_id();
+                found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
+            } else {
+                bug!("candidate is not trait or trait alias?")
+            }
+        }
+    }
+
+    fn find_transitive_imports(
+        &mut self,
+        mut kind: &NameBindingKind<'_>,
+        trait_name: Ident,
+    ) -> SmallVec<[LocalDefId; 1]> {
+        let mut import_ids = smallvec![];
+        while let NameBindingKind::Import { import, binding, .. } = kind {
+            let id = self.local_def_id(import.id);
+            self.maybe_unused_trait_imports.insert(id);
+            self.add_to_glob_map(&import, trait_name);
+            import_ids.push(id);
+            kind = &binding.kind;
+        }
+        import_ids
+    }
+
+    fn new_module(
+        &self,
+        parent: Module<'a>,
+        kind: ModuleKind,
+        normal_ancestor_id: DefId,
+        expn_id: ExpnId,
+        span: Span,
+    ) -> Module<'a> {
+        let module = ModuleData::new(Some(parent), kind, normal_ancestor_id, expn_id, span);
+        self.arenas.alloc_module(module)
+    }
+
+    fn new_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey {
+        let ident = ident.normalize_to_macros_2_0();
+        let disambiguator = if ident.name == kw::Underscore {
+            self.underscore_disambiguator += 1;
+            self.underscore_disambiguator
+        } else {
+            0
+        };
+        BindingKey { ident, ns, disambiguator }
+    }
+
+    fn resolutions(&mut self, module: Module<'a>) -> &'a Resolutions<'a> {
+        if module.populate_on_access.get() {
+            module.populate_on_access.set(false);
+            self.build_reduced_graph_external(module);
+        }
+        &module.lazy_resolutions
+    }
+
+    fn resolution(
+        &mut self,
+        module: Module<'a>,
+        key: BindingKey,
+    ) -> &'a RefCell<NameResolution<'a>> {
+        *self
+            .resolutions(module)
+            .borrow_mut()
+            .entry(key)
+            .or_insert_with(|| self.arenas.alloc_name_resolution())
+    }
+
+    fn record_use(
+        &mut self,
+        ident: Ident,
+        ns: Namespace,
+        used_binding: &'a NameBinding<'a>,
+        is_lexical_scope: bool,
+    ) {
+        if let Some((b2, kind)) = used_binding.ambiguity {
+            self.ambiguity_errors.push(AmbiguityError {
+                kind,
+                ident,
+                b1: used_binding,
+                b2,
+                misc1: AmbiguityErrorMisc::None,
+                misc2: AmbiguityErrorMisc::None,
+            });
+        }
+        if let NameBindingKind::Import { import, binding, ref used } = used_binding.kind {
+            // Avoid marking `extern crate` items that refer to a name from extern prelude,
+            // but not introduce it, as used if they are accessed from lexical scope.
+            if is_lexical_scope {
+                if let Some(entry) = self.extern_prelude.get(&ident.normalize_to_macros_2_0()) {
+                    if let Some(crate_item) = entry.extern_crate_item {
+                        if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
+                            return;
+                        }
+                    }
+                }
+            }
+            used.set(true);
+            import.used.set(true);
+            self.used_imports.insert((import.id, ns));
+            self.add_to_glob_map(&import, ident);
+            self.record_use(ident, ns, binding, false);
+        }
+    }
+
+    #[inline]
+    fn add_to_glob_map(&mut self, import: &Import<'_>, ident: Ident) {
+        if import.is_glob() {
+            let def_id = self.local_def_id(import.id);
+            self.glob_map.entry(def_id).or_default().insert(ident.name);
+        }
+    }
+
+    /// A generic scope visitor.
+    /// Visits scopes in order to resolve some identifier in them or perform other actions.
+    /// If the callback returns `Some` result, we stop visiting scopes and return it.
+    fn visit_scopes<T>(
+        &mut self,
+        scope_set: ScopeSet,
+        parent_scope: &ParentScope<'a>,
+        ident: Ident,
+        mut visitor: impl FnMut(&mut Self, Scope<'a>, /*use_prelude*/ bool, Ident) -> Option<T>,
+    ) -> Option<T> {
+        // General principles:
+        // 1. Not controlled (user-defined) names should have higher priority than controlled names
+        //    built into the language or standard library. This way we can add new names into the
+        //    language or standard library without breaking user code.
+        // 2. "Closed set" below means new names cannot appear after the current resolution attempt.
+        // Places to search (in order of decreasing priority):
+        // (Type NS)
+        // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
+        //    (open set, not controlled).
+        // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
+        //    (open, not controlled).
+        // 3. Extern prelude (open, the open part is from macro expansions, not controlled).
+        // 4. Tool modules (closed, controlled right now, but not in the future).
+        // 5. Standard library prelude (de-facto closed, controlled).
+        // 6. Language prelude (closed, controlled).
+        // (Value NS)
+        // 1. FIXME: Ribs (local variables), there's no necessary infrastructure yet
+        //    (open set, not controlled).
+        // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
+        //    (open, not controlled).
+        // 3. Standard library prelude (de-facto closed, controlled).
+        // (Macro NS)
+        // 1-3. Derive helpers (open, not controlled). All ambiguities with other names
+        //    are currently reported as errors. They should be higher in priority than preludes
+        //    and probably even names in modules according to the "general principles" above. They
+        //    also should be subject to restricted shadowing because are effectively produced by
+        //    derives (you need to resolve the derive first to add helpers into scope), but they
+        //    should be available before the derive is expanded for compatibility.
+        //    It's mess in general, so we are being conservative for now.
+        // 1-3. `macro_rules` (open, not controlled), loop through `macro_rules` scopes. Have higher
+        //    priority than prelude macros, but create ambiguities with macros in modules.
+        // 1-3. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
+        //    (open, not controlled). Have higher priority than prelude macros, but create
+        //    ambiguities with `macro_rules`.
+        // 4. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
+        // 4a. User-defined prelude from macro-use
+        //    (open, the open part is from macro expansions, not controlled).
+        // 4b. "Standard library prelude" part implemented through `macro-use` (closed, controlled).
+        // 4c. Standard library prelude (de-facto closed, controlled).
+        // 6. Language prelude: builtin attributes (closed, controlled).
+
+        let rust_2015 = ident.span.rust_2015();
+        let (ns, macro_kind, is_absolute_path) = match scope_set {
+            ScopeSet::All(ns, _) => (ns, None, false),
+            ScopeSet::AbsolutePath(ns) => (ns, None, true),
+            ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false),
+        };
+        // Jump out of trait or enum modules, they do not act as scopes.
+        let module = parent_scope.module.nearest_item_scope();
+        let mut scope = match ns {
+            _ if is_absolute_path => Scope::CrateRoot,
+            TypeNS | ValueNS => Scope::Module(module),
+            MacroNS => Scope::DeriveHelpers(parent_scope.expansion),
+        };
+        let mut ident = ident.normalize_to_macros_2_0();
+        let mut use_prelude = !module.no_implicit_prelude;
+
+        loop {
+            let visit = match scope {
+                // Derive helpers are not in scope when resolving derives in the same container.
+                Scope::DeriveHelpers(expn_id) => {
+                    !(expn_id == parent_scope.expansion && macro_kind == Some(MacroKind::Derive))
+                }
+                Scope::DeriveHelpersCompat => true,
+                Scope::MacroRules(..) => true,
+                Scope::CrateRoot => true,
+                Scope::Module(..) => true,
+                Scope::RegisteredAttrs => use_prelude,
+                Scope::MacroUsePrelude => use_prelude || rust_2015,
+                Scope::BuiltinAttrs => true,
+                Scope::ExternPrelude => use_prelude || is_absolute_path,
+                Scope::ToolPrelude => use_prelude,
+                Scope::StdLibPrelude => use_prelude || ns == MacroNS,
+                Scope::BuiltinTypes => true,
+            };
+
+            if visit {
+                if let break_result @ Some(..) = visitor(self, scope, use_prelude, ident) {
+                    return break_result;
+                }
+            }
+
+            scope = match scope {
+                Scope::DeriveHelpers(expn_id) if expn_id != ExpnId::root() => {
+                    // Derive helpers are not visible to code generated by bang or derive macros.
+                    let expn_data = expn_id.expn_data();
+                    match expn_data.kind {
+                        ExpnKind::Root
+                        | ExpnKind::Macro(MacroKind::Bang | MacroKind::Derive, _) => {
+                            Scope::DeriveHelpersCompat
+                        }
+                        _ => Scope::DeriveHelpers(expn_data.parent),
+                    }
+                }
+                Scope::DeriveHelpers(..) => Scope::DeriveHelpersCompat,
+                Scope::DeriveHelpersCompat => Scope::MacroRules(parent_scope.macro_rules),
+                Scope::MacroRules(macro_rules_scope) => match macro_rules_scope {
+                    MacroRulesScope::Binding(binding) => {
+                        Scope::MacroRules(binding.parent_macro_rules_scope)
+                    }
+                    MacroRulesScope::Invocation(invoc_id) => Scope::MacroRules(
+                        self.output_macro_rules_scopes
+                            .get(&invoc_id)
+                            .cloned()
+                            .unwrap_or(self.invocation_parent_scopes[&invoc_id].macro_rules),
+                    ),
+                    MacroRulesScope::Empty => Scope::Module(module),
+                },
+                Scope::CrateRoot => match ns {
+                    TypeNS => {
+                        ident.span.adjust(ExpnId::root());
+                        Scope::ExternPrelude
+                    }
+                    ValueNS | MacroNS => break,
+                },
+                Scope::Module(module) => {
+                    use_prelude = !module.no_implicit_prelude;
+                    match self.hygienic_lexical_parent(module, &mut ident.span) {
+                        Some(parent_module) => Scope::Module(parent_module),
+                        None => {
+                            ident.span.adjust(ExpnId::root());
+                            match ns {
+                                TypeNS => Scope::ExternPrelude,
+                                ValueNS => Scope::StdLibPrelude,
+                                MacroNS => Scope::RegisteredAttrs,
+                            }
+                        }
+                    }
+                }
+                Scope::RegisteredAttrs => Scope::MacroUsePrelude,
+                Scope::MacroUsePrelude => Scope::StdLibPrelude,
+                Scope::BuiltinAttrs => break, // nowhere else to search
+                Scope::ExternPrelude if is_absolute_path => break,
+                Scope::ExternPrelude => Scope::ToolPrelude,
+                Scope::ToolPrelude => Scope::StdLibPrelude,
+                Scope::StdLibPrelude => match ns {
+                    TypeNS => Scope::BuiltinTypes,
+                    ValueNS => break, // nowhere else to search
+                    MacroNS => Scope::BuiltinAttrs,
+                },
+                Scope::BuiltinTypes => break, // nowhere else to search
+            };
+        }
+
+        None
+    }
+
+    /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
+    /// More specifically, we proceed up the hierarchy of scopes and return the binding for
+    /// `ident` in the first scope that defines it (or None if no scopes define it).
+    ///
+    /// A block's items are above its local variables in the scope hierarchy, regardless of where
+    /// the items are defined in the block. For example,
+    /// ```rust
+    /// fn f() {
+    ///    g(); // Since there are no local variables in scope yet, this resolves to the item.
+    ///    let g = || {};
+    ///    fn g() {}
+    ///    g(); // This resolves to the local variable `g` since it shadows the item.
+    /// }
+    /// ```
+    ///
+    /// Invariant: This must only be called during main resolution, not during
+    /// import resolution.
+    fn resolve_ident_in_lexical_scope(
+        &mut self,
+        mut ident: Ident,
+        ns: Namespace,
+        parent_scope: &ParentScope<'a>,
+        record_used_id: Option<NodeId>,
+        path_span: Span,
+        ribs: &[Rib<'a>],
+    ) -> Option<LexicalScopeBinding<'a>> {
+        assert!(ns == TypeNS || ns == ValueNS);
+        if ident.name == kw::Invalid {
+            return Some(LexicalScopeBinding::Res(Res::Err));
+        }
+        let (general_span, normalized_span) = if ident.name == kw::SelfUpper {
+            // FIXME(jseyfried) improve `Self` hygiene
+            let empty_span = ident.span.with_ctxt(SyntaxContext::root());
+            (empty_span, empty_span)
+        } else if ns == TypeNS {
+            let normalized_span = ident.span.normalize_to_macros_2_0();
+            (normalized_span, normalized_span)
+        } else {
+            (ident.span.normalize_to_macro_rules(), ident.span.normalize_to_macros_2_0())
+        };
+        ident.span = general_span;
+        let normalized_ident = Ident { span: normalized_span, ..ident };
+
+        // Walk backwards up the ribs in scope.
+        let record_used = record_used_id.is_some();
+        let mut module = self.graph_root;
+        for i in (0..ribs.len()).rev() {
+            debug!("walk rib\n{:?}", ribs[i].bindings);
+            // Use the rib kind to determine whether we are resolving parameters
+            // (macro 2.0 hygiene) or local variables (`macro_rules` hygiene).
+            let rib_ident = if ribs[i].kind.contains_params() { normalized_ident } else { ident };
+            if let Some(res) = ribs[i].bindings.get(&rib_ident).cloned() {
+                // The ident resolves to a type parameter or local variable.
+                return Some(LexicalScopeBinding::Res(self.validate_res_from_ribs(
+                    i,
+                    rib_ident,
+                    res,
+                    record_used,
+                    path_span,
+                    ribs,
+                )));
+            }
+
+            module = match ribs[i].kind {
+                ModuleRibKind(module) => module,
+                MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => {
+                    // If an invocation of this macro created `ident`, give up on `ident`
+                    // and switch to `ident`'s source from the macro definition.
+                    ident.span.remove_mark();
+                    continue;
+                }
+                _ => continue,
+            };
+
+            let item = self.resolve_ident_in_module_unadjusted(
+                ModuleOrUniformRoot::Module(module),
+                ident,
+                ns,
+                parent_scope,
+                record_used,
+                path_span,
+            );
+            if let Ok(binding) = item {
+                // The ident resolves to an item.
+                return Some(LexicalScopeBinding::Item(binding));
+            }
+
+            match module.kind {
+                ModuleKind::Block(..) => {} // We can see through blocks
+                _ => break,
+            }
+        }
+
+        ident = normalized_ident;
+        let mut poisoned = None;
+        loop {
+            let opt_module = if let Some(node_id) = record_used_id {
+                self.hygienic_lexical_parent_with_compatibility_fallback(
+                    module,
+                    &mut ident.span,
+                    node_id,
+                    &mut poisoned,
+                )
+            } else {
+                self.hygienic_lexical_parent(module, &mut ident.span)
+            };
+            module = unwrap_or!(opt_module, break);
+            let adjusted_parent_scope = &ParentScope { module, ..*parent_scope };
+            let result = self.resolve_ident_in_module_unadjusted(
+                ModuleOrUniformRoot::Module(module),
+                ident,
+                ns,
+                adjusted_parent_scope,
+                record_used,
+                path_span,
+            );
+
+            match result {
+                Ok(binding) => {
+                    if let Some(node_id) = poisoned {
+                        self.lint_buffer.buffer_lint_with_diagnostic(
+                            lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
+                            node_id,
+                            ident.span,
+                            &format!("cannot find {} `{}` in this scope", ns.descr(), ident),
+                            BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(ident.span),
+                        );
+                    }
+                    return Some(LexicalScopeBinding::Item(binding));
+                }
+                Err(Determined) => continue,
+                Err(Undetermined) => {
+                    span_bug!(ident.span, "undetermined resolution during main resolution pass")
+                }
+            }
+        }
+
+        if !module.no_implicit_prelude {
+            ident.span.adjust(ExpnId::root());
+            if ns == TypeNS {
+                if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
+                    return Some(LexicalScopeBinding::Item(binding));
+                }
+                if let Some(ident) = self.registered_tools.get(&ident) {
+                    let binding =
+                        (Res::ToolMod, ty::Visibility::Public, ident.span, ExpnId::root())
+                            .to_name_binding(self.arenas);
+                    return Some(LexicalScopeBinding::Item(binding));
+                }
+            }
+            if let Some(prelude) = self.prelude {
+                if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
+                    ModuleOrUniformRoot::Module(prelude),
+                    ident,
+                    ns,
+                    parent_scope,
+                    false,
+                    path_span,
+                ) {
+                    return Some(LexicalScopeBinding::Item(binding));
+                }
+            }
+        }
+
+        if ns == TypeNS {
+            if let Some(prim_ty) = self.primitive_type_table.primitive_types.get(&ident.name) {
+                let binding =
+                    (Res::PrimTy(*prim_ty), ty::Visibility::Public, DUMMY_SP, ExpnId::root())
+                        .to_name_binding(self.arenas);
+                return Some(LexicalScopeBinding::Item(binding));
+            }
+        }
+
+        None
+    }
+
+    fn hygienic_lexical_parent(
+        &mut self,
+        module: Module<'a>,
+        span: &mut Span,
+    ) -> Option<Module<'a>> {
+        if !module.expansion.outer_expn_is_descendant_of(span.ctxt()) {
+            return Some(self.macro_def_scope(span.remove_mark()));
+        }
+
+        if let ModuleKind::Block(..) = module.kind {
+            return Some(module.parent.unwrap().nearest_item_scope());
+        }
+
+        None
+    }
+
+    fn hygienic_lexical_parent_with_compatibility_fallback(
+        &mut self,
+        module: Module<'a>,
+        span: &mut Span,
+        node_id: NodeId,
+        poisoned: &mut Option<NodeId>,
+    ) -> Option<Module<'a>> {
+        if let module @ Some(..) = self.hygienic_lexical_parent(module, span) {
+            return module;
+        }
+
+        // We need to support the next case under a deprecation warning
+        // ```
+        // struct MyStruct;
+        // ---- begin: this comes from a proc macro derive
+        // mod implementation_details {
+        //     // Note that `MyStruct` is not in scope here.
+        //     impl SomeTrait for MyStruct { ... }
+        // }
+        // ---- end
+        // ```
+        // So we have to fall back to the module's parent during lexical resolution in this case.
+        if let Some(parent) = module.parent {
+            // Inner module is inside the macro, parent module is outside of the macro.
+            if module.expansion != parent.expansion
+                && module.expansion.is_descendant_of(parent.expansion)
+            {
+                // The macro is a proc macro derive
+                if let Some(def_id) = module.expansion.expn_data().macro_def_id {
+                    if let Some(ext) = self.get_macro_by_def_id(def_id) {
+                        if !ext.is_builtin && ext.macro_kind() == MacroKind::Derive {
+                            if parent.expansion.outer_expn_is_descendant_of(span.ctxt()) {
+                                *poisoned = Some(node_id);
+                                return module.parent;
+                            }
+                        }
+                    }
+                }
+            }
+        }
+
+        None
+    }
+
+    fn resolve_ident_in_module(
+        &mut self,
+        module: ModuleOrUniformRoot<'a>,
+        ident: Ident,
+        ns: Namespace,
+        parent_scope: &ParentScope<'a>,
+        record_used: bool,
+        path_span: Span,
+    ) -> Result<&'a NameBinding<'a>, Determinacy> {
+        self.resolve_ident_in_module_ext(module, ident, ns, parent_scope, record_used, path_span)
+            .map_err(|(determinacy, _)| determinacy)
+    }
+
+    fn resolve_ident_in_module_ext(
+        &mut self,
+        module: ModuleOrUniformRoot<'a>,
+        mut ident: Ident,
+        ns: Namespace,
+        parent_scope: &ParentScope<'a>,
+        record_used: bool,
+        path_span: Span,
+    ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
+        let tmp_parent_scope;
+        let mut adjusted_parent_scope = parent_scope;
+        match module {
+            ModuleOrUniformRoot::Module(m) => {
+                if let Some(def) = ident.span.normalize_to_macros_2_0_and_adjust(m.expansion) {
+                    tmp_parent_scope =
+                        ParentScope { module: self.macro_def_scope(def), ..*parent_scope };
+                    adjusted_parent_scope = &tmp_parent_scope;
+                }
+            }
+            ModuleOrUniformRoot::ExternPrelude => {
+                ident.span.normalize_to_macros_2_0_and_adjust(ExpnId::root());
+            }
+            ModuleOrUniformRoot::CrateRootAndExternPrelude | ModuleOrUniformRoot::CurrentScope => {
+                // No adjustments
+            }
+        }
+        self.resolve_ident_in_module_unadjusted_ext(
+            module,
+            ident,
+            ns,
+            adjusted_parent_scope,
+            false,
+            record_used,
+            path_span,
+        )
+    }
+
+    fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> {
+        debug!("resolve_crate_root({:?})", ident);
+        let mut ctxt = ident.span.ctxt();
+        let mark = if ident.name == kw::DollarCrate {
+            // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
+            // we don't want to pretend that the `macro_rules!` definition is in the `macro`
+            // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks.
+            // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
+            // definitions actually produced by `macro` and `macro` definitions produced by
+            // `macro_rules!`, but at least such configurations are not stable yet.
+            ctxt = ctxt.normalize_to_macro_rules();
+            debug!(
+                "resolve_crate_root: marks={:?}",
+                ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
+            );
+            let mut iter = ctxt.marks().into_iter().rev().peekable();
+            let mut result = None;
+            // Find the last opaque mark from the end if it exists.
+            while let Some(&(mark, transparency)) = iter.peek() {
+                if transparency == Transparency::Opaque {
+                    result = Some(mark);
+                    iter.next();
+                } else {
+                    break;
+                }
+            }
+            debug!(
+                "resolve_crate_root: found opaque mark {:?} {:?}",
+                result,
+                result.map(|r| r.expn_data())
+            );
+            // Then find the last semi-transparent mark from the end if it exists.
+            for (mark, transparency) in iter {
+                if transparency == Transparency::SemiTransparent {
+                    result = Some(mark);
+                } else {
+                    break;
+                }
+            }
+            debug!(
+                "resolve_crate_root: found semi-transparent mark {:?} {:?}",
+                result,
+                result.map(|r| r.expn_data())
+            );
+            result
+        } else {
+            debug!("resolve_crate_root: not DollarCrate");
+            ctxt = ctxt.normalize_to_macros_2_0();
+            ctxt.adjust(ExpnId::root())
+        };
+        let module = match mark {
+            Some(def) => self.macro_def_scope(def),
+            None => {
+                debug!(
+                    "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
+                    ident, ident.span
+                );
+                return self.graph_root;
+            }
+        };
+        let module = self.get_module(DefId { index: CRATE_DEF_INDEX, ..module.normal_ancestor_id });
+        debug!(
+            "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
+            ident,
+            module,
+            module.kind.name(),
+            ident.span
+        );
+        module
+    }
+
+    fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
+        let mut module = self.get_module(module.normal_ancestor_id);
+        while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
+            let parent = module.parent.unwrap_or_else(|| self.macro_def_scope(ctxt.remove_mark()));
+            module = self.get_module(parent.normal_ancestor_id);
+        }
+        module
+    }
+
+    fn resolve_path(
+        &mut self,
+        path: &[Segment],
+        opt_ns: Option<Namespace>, // `None` indicates a module path in import
+        parent_scope: &ParentScope<'a>,
+        record_used: bool,
+        path_span: Span,
+        crate_lint: CrateLint,
+    ) -> PathResult<'a> {
+        self.resolve_path_with_ribs(
+            path,
+            opt_ns,
+            parent_scope,
+            record_used,
+            path_span,
+            crate_lint,
+            None,
+        )
+    }
+
+    fn resolve_path_with_ribs(
+        &mut self,
+        path: &[Segment],
+        opt_ns: Option<Namespace>, // `None` indicates a module path in import
+        parent_scope: &ParentScope<'a>,
+        record_used: bool,
+        path_span: Span,
+        crate_lint: CrateLint,
+        ribs: Option<&PerNS<Vec<Rib<'a>>>>,
+    ) -> PathResult<'a> {
+        let mut module = None;
+        let mut allow_super = true;
+        let mut second_binding = None;
+
+        debug!(
+            "resolve_path(path={:?}, opt_ns={:?}, record_used={:?}, \
+             path_span={:?}, crate_lint={:?})",
+            path, opt_ns, record_used, path_span, crate_lint,
+        );
+
+        for (i, &Segment { ident, id, has_generic_args: _ }) in path.iter().enumerate() {
+            debug!("resolve_path ident {} {:?} {:?}", i, ident, id);
+            let record_segment_res = |this: &mut Self, res| {
+                if record_used {
+                    if let Some(id) = id {
+                        if !this.partial_res_map.contains_key(&id) {
+                            assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id");
+                            this.record_partial_res(id, PartialRes::new(res));
+                        }
+                    }
+                }
+            };
+
+            let is_last = i == path.len() - 1;
+            let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
+            let name = ident.name;
+
+            allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super);
+
+            if ns == TypeNS {
+                if allow_super && name == kw::Super {
+                    let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
+                    let self_module = match i {
+                        0 => Some(self.resolve_self(&mut ctxt, parent_scope.module)),
+                        _ => match module {
+                            Some(ModuleOrUniformRoot::Module(module)) => Some(module),
+                            _ => None,
+                        },
+                    };
+                    if let Some(self_module) = self_module {
+                        if let Some(parent) = self_module.parent {
+                            module = Some(ModuleOrUniformRoot::Module(
+                                self.resolve_self(&mut ctxt, parent),
+                            ));
+                            continue;
+                        }
+                    }
+                    let msg = "there are too many leading `super` keywords".to_string();
+                    return PathResult::Failed {
+                        span: ident.span,
+                        label: msg,
+                        suggestion: None,
+                        is_error_from_last_segment: false,
+                    };
+                }
+                if i == 0 {
+                    if name == kw::SelfLower {
+                        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
+                        module = Some(ModuleOrUniformRoot::Module(
+                            self.resolve_self(&mut ctxt, parent_scope.module),
+                        ));
+                        continue;
+                    }
+                    if name == kw::PathRoot && ident.span.rust_2018() {
+                        module = Some(ModuleOrUniformRoot::ExternPrelude);
+                        continue;
+                    }
+                    if name == kw::PathRoot && ident.span.rust_2015() && self.session.rust_2018() {
+                        // `::a::b` from 2015 macro on 2018 global edition
+                        module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude);
+                        continue;
+                    }
+                    if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate {
+                        // `::a::b`, `crate::a::b` or `$crate::a::b`
+                        module = Some(ModuleOrUniformRoot::Module(self.resolve_crate_root(ident)));
+                        continue;
+                    }
+                }
+            }
+
+            // Report special messages for path segment keywords in wrong positions.
+            if ident.is_path_segment_keyword() && i != 0 {
+                let name_str = if name == kw::PathRoot {
+                    "crate root".to_string()
+                } else {
+                    format!("`{}`", name)
+                };
+                let label = if i == 1 && path[0].ident.name == kw::PathRoot {
+                    format!("global paths cannot start with {}", name_str)
+                } else {
+                    format!("{} in paths can only be used in start position", name_str)
+                };
+                return PathResult::Failed {
+                    span: ident.span,
+                    label,
+                    suggestion: None,
+                    is_error_from_last_segment: false,
+                };
+            }
+
+            enum FindBindingResult<'a> {
+                Binding(Result<&'a NameBinding<'a>, Determinacy>),
+                PathResult(PathResult<'a>),
+            }
+            let find_binding_in_ns = |this: &mut Self, ns| {
+                let binding = if let Some(module) = module {
+                    this.resolve_ident_in_module(
+                        module,
+                        ident,
+                        ns,
+                        parent_scope,
+                        record_used,
+                        path_span,
+                    )
+                } else if ribs.is_none() || opt_ns.is_none() || opt_ns == Some(MacroNS) {
+                    let scopes = ScopeSet::All(ns, opt_ns.is_none());
+                    this.early_resolve_ident_in_lexical_scope(
+                        ident,
+                        scopes,
+                        parent_scope,
+                        record_used,
+                        record_used,
+                        path_span,
+                    )
+                } else {
+                    let record_used_id = if record_used {
+                        crate_lint.node_id().or(Some(CRATE_NODE_ID))
+                    } else {
+                        None
+                    };
+                    match this.resolve_ident_in_lexical_scope(
+                        ident,
+                        ns,
+                        parent_scope,
+                        record_used_id,
+                        path_span,
+                        &ribs.unwrap()[ns],
+                    ) {
+                        // we found a locally-imported or available item/module
+                        Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
+                        // we found a local variable or type param
+                        Some(LexicalScopeBinding::Res(res))
+                            if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) =>
+                        {
+                            record_segment_res(this, res);
+                            return FindBindingResult::PathResult(PathResult::NonModule(
+                                PartialRes::with_unresolved_segments(res, path.len() - 1),
+                            ));
+                        }
+                        _ => Err(Determinacy::determined(record_used)),
+                    }
+                };
+                FindBindingResult::Binding(binding)
+            };
+            let binding = match find_binding_in_ns(self, ns) {
+                FindBindingResult::PathResult(x) => return x,
+                FindBindingResult::Binding(binding) => binding,
+            };
+            match binding {
+                Ok(binding) => {
+                    if i == 1 {
+                        second_binding = Some(binding);
+                    }
+                    let res = binding.res();
+                    let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res);
+                    if let Some(next_module) = binding.module() {
+                        module = Some(ModuleOrUniformRoot::Module(next_module));
+                        record_segment_res(self, res);
+                    } else if res == Res::ToolMod && i + 1 != path.len() {
+                        if binding.is_import() {
+                            self.session
+                                .struct_span_err(
+                                    ident.span,
+                                    "cannot use a tool module through an import",
+                                )
+                                .span_note(binding.span, "the tool module imported here")
+                                .emit();
+                        }
+                        let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
+                        return PathResult::NonModule(PartialRes::new(res));
+                    } else if res == Res::Err {
+                        return PathResult::NonModule(PartialRes::new(Res::Err));
+                    } else if opt_ns.is_some() && (is_last || maybe_assoc) {
+                        self.lint_if_path_starts_with_module(
+                            crate_lint,
+                            path,
+                            path_span,
+                            second_binding,
+                        );
+                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
+                            res,
+                            path.len() - i - 1,
+                        ));
+                    } else {
+                        let label = format!(
+                            "`{}` is {} {}, not a module",
+                            ident,
+                            res.article(),
+                            res.descr(),
+                        );
+
+                        return PathResult::Failed {
+                            span: ident.span,
+                            label,
+                            suggestion: None,
+                            is_error_from_last_segment: is_last,
+                        };
+                    }
+                }
+                Err(Undetermined) => return PathResult::Indeterminate,
+                Err(Determined) => {
+                    if let Some(ModuleOrUniformRoot::Module(module)) = module {
+                        if opt_ns.is_some() && !module.is_normal() {
+                            return PathResult::NonModule(PartialRes::with_unresolved_segments(
+                                module.res().unwrap(),
+                                path.len() - i,
+                            ));
+                        }
+                    }
+                    let module_res = match module {
+                        Some(ModuleOrUniformRoot::Module(module)) => module.res(),
+                        _ => None,
+                    };
+                    let (label, suggestion) = if module_res == self.graph_root.res() {
+                        let is_mod = |res| match res {
+                            Res::Def(DefKind::Mod, _) => true,
+                            _ => false,
+                        };
+                        // Don't look up import candidates if this is a speculative resolve
+                        let mut candidates = if record_used {
+                            self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod)
+                        } else {
+                            Vec::new()
+                        };
+                        candidates.sort_by_cached_key(|c| {
+                            (c.path.segments.len(), pprust::path_to_string(&c.path))
+                        });
+                        if let Some(candidate) = candidates.get(0) {
+                            (
+                                String::from("unresolved import"),
+                                Some((
+                                    vec![(ident.span, pprust::path_to_string(&candidate.path))],
+                                    String::from("a similar path exists"),
+                                    Applicability::MaybeIncorrect,
+                                )),
+                            )
+                        } else {
+                            (format!("maybe a missing crate `{}`?", ident), None)
+                        }
+                    } else if i == 0 {
+                        if ident
+                            .name
+                            .with(|n| n.chars().next().map_or(false, |c| c.is_ascii_uppercase()))
+                        {
+                            (format!("use of undeclared type `{}`", ident), None)
+                        } else {
+                            (format!("use of undeclared crate or module `{}`", ident), None)
+                        }
+                    } else {
+                        let mut msg =
+                            format!("could not find `{}` in `{}`", ident, path[i - 1].ident);
+                        if ns == TypeNS || ns == ValueNS {
+                            let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
+                            if let FindBindingResult::Binding(Ok(binding)) =
+                                find_binding_in_ns(self, ns_to_try)
+                            {
+                                let mut found = |what| {
+                                    msg = format!(
+                                        "expected {}, found {} `{}` in `{}`",
+                                        ns.descr(),
+                                        what,
+                                        ident,
+                                        path[i - 1].ident
+                                    )
+                                };
+                                if binding.module().is_some() {
+                                    found("module")
+                                } else {
+                                    match binding.res() {
+                                        def::Res::<NodeId>::Def(kind, id) => found(kind.descr(id)),
+                                        _ => found(ns_to_try.descr()),
+                                    }
+                                }
+                            };
+                        }
+                        (msg, None)
+                    };
+                    return PathResult::Failed {
+                        span: ident.span,
+                        label,
+                        suggestion,
+                        is_error_from_last_segment: is_last,
+                    };
+                }
+            }
+        }
+
+        self.lint_if_path_starts_with_module(crate_lint, path, path_span, second_binding);
+
+        PathResult::Module(match module {
+            Some(module) => module,
+            None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
+            _ => span_bug!(path_span, "resolve_path: non-empty path `{:?}` has no module", path),
+        })
+    }
+
+    fn lint_if_path_starts_with_module(
+        &mut self,
+        crate_lint: CrateLint,
+        path: &[Segment],
+        path_span: Span,
+        second_binding: Option<&NameBinding<'_>>,
+    ) {
+        let (diag_id, diag_span) = match crate_lint {
+            CrateLint::No => return,
+            CrateLint::SimplePath(id) => (id, path_span),
+            CrateLint::UsePath { root_id, root_span } => (root_id, root_span),
+            CrateLint::QPathTrait { qpath_id, qpath_span } => (qpath_id, qpath_span),
+        };
+
+        let first_name = match path.get(0) {
+            // In the 2018 edition this lint is a hard error, so nothing to do
+            Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name,
+            _ => return,
+        };
+
+        // We're only interested in `use` paths which should start with
+        // `{{root}}` currently.
+        if first_name != kw::PathRoot {
+            return;
+        }
+
+        match path.get(1) {
+            // If this import looks like `crate::...` it's already good
+            Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
+            // Otherwise go below to see if it's an extern crate
+            Some(_) => {}
+            // If the path has length one (and it's `PathRoot` most likely)
+            // then we don't know whether we're gonna be importing a crate or an
+            // item in our crate. Defer this lint to elsewhere
+            None => return,
+        }
+
+        // If the first element of our path was actually resolved to an
+        // `ExternCrate` (also used for `crate::...`) then no need to issue a
+        // warning, this looks all good!
+        if let Some(binding) = second_binding {
+            if let NameBindingKind::Import { import, .. } = binding.kind {
+                // Careful: we still want to rewrite paths from renamed extern crates.
+                if let ImportKind::ExternCrate { source: None, .. } = import.kind {
+                    return;
+                }
+            }
+        }
+
+        let diag = BuiltinLintDiagnostics::AbsPathWithModule(diag_span);
+        self.lint_buffer.buffer_lint_with_diagnostic(
+            lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
+            diag_id,
+            diag_span,
+            "absolute paths must start with `self`, `super`, \
+             `crate`, or an external crate name in the 2018 edition",
+            diag,
+        );
+    }
+
+    // Validate a local resolution (from ribs).
+    fn validate_res_from_ribs(
+        &mut self,
+        rib_index: usize,
+        rib_ident: Ident,
+        mut res: Res,
+        record_used: bool,
+        span: Span,
+        all_ribs: &[Rib<'a>],
+    ) -> Res {
+        debug!("validate_res_from_ribs({:?})", res);
+        let ribs = &all_ribs[rib_index + 1..];
+
+        // An invalid forward use of a type parameter from a previous default.
+        if let ForwardTyParamBanRibKind = all_ribs[rib_index].kind {
+            if record_used {
+                let res_error = if rib_ident.name == kw::SelfUpper {
+                    ResolutionError::SelfInTyParamDefault
+                } else {
+                    ResolutionError::ForwardDeclaredTyParam
+                };
+                self.report_error(span, res_error);
+            }
+            assert_eq!(res, Res::Err);
+            return Res::Err;
+        }
+
+        match res {
+            Res::Local(_) => {
+                use ResolutionError::*;
+                let mut res_err = None;
+
+                for rib in ribs {
+                    match rib.kind {
+                        NormalRibKind
+                        | ClosureOrAsyncRibKind
+                        | ModuleRibKind(..)
+                        | MacroDefinition(..)
+                        | ForwardTyParamBanRibKind => {
+                            // Nothing to do. Continue.
+                        }
+                        ItemRibKind(_) | FnItemRibKind | AssocItemRibKind => {
+                            // This was an attempt to access an upvar inside a
+                            // named function item. This is not allowed, so we
+                            // report an error.
+                            if record_used {
+                                // We don't immediately trigger a resolve error, because
+                                // we want certain other resolution errors (namely those
+                                // emitted for `ConstantItemRibKind` below) to take
+                                // precedence.
+                                res_err = Some(CannotCaptureDynamicEnvironmentInFnItem);
+                            }
+                        }
+                        ConstantItemRibKind(_) => {
+                            // Still doesn't deal with upvars
+                            if record_used {
+                                self.report_error(span, AttemptToUseNonConstantValueInConstant);
+                            }
+                            return Res::Err;
+                        }
+                        ConstParamTyRibKind => {
+                            if record_used {
+                                self.report_error(span, ParamInTyOfConstParam(rib_ident.name));
+                            }
+                            return Res::Err;
+                        }
+                    }
+                }
+                if let Some(res_err) = res_err {
+                    self.report_error(span, res_err);
+                    return Res::Err;
+                }
+            }
+            Res::Def(DefKind::TyParam, _) | Res::SelfTy(..) => {
+                let mut in_ty_param_default = false;
+                for rib in ribs {
+                    let has_generic_params = match rib.kind {
+                        NormalRibKind
+                        | ClosureOrAsyncRibKind
+                        | AssocItemRibKind
+                        | ModuleRibKind(..)
+                        | MacroDefinition(..) => {
+                            // Nothing to do. Continue.
+                            continue;
+                        }
+
+                        // We only forbid constant items if we are inside of type defaults,
+                        // for example `struct Foo<T, U = [u8; std::mem::size_of::<T>()]>`
+                        ForwardTyParamBanRibKind => {
+                            in_ty_param_default = true;
+                            continue;
+                        }
+                        ConstantItemRibKind(trivial) => {
+                            // HACK(min_const_generics): We currently only allow `N` or `{ N }`.
+                            if !trivial && self.session.features_untracked().min_const_generics {
+                                // HACK(min_const_generics): If we encounter `Self` in an anonymous constant
+                                // we can't easily tell if it's generic at this stage, so we instead remember
+                                // this and then enforce the self type to be concrete later on.
+                                if let Res::SelfTy(trait_def, Some((impl_def, _))) = res {
+                                    res = Res::SelfTy(trait_def, Some((impl_def, true)));
+                                } else {
+                                    if record_used {
+                                        self.report_error(
+                                            span,
+                                            ResolutionError::ParamInNonTrivialAnonConst {
+                                                name: rib_ident.name,
+                                                is_type: true,
+                                            },
+                                        );
+                                    }
+                                    return Res::Err;
+                                }
+                            }
+
+                            if in_ty_param_default {
+                                if record_used {
+                                    self.report_error(
+                                        span,
+                                        ResolutionError::ParamInAnonConstInTyDefault(
+                                            rib_ident.name,
+                                        ),
+                                    );
+                                }
+                                return Res::Err;
+                            } else {
+                                continue;
+                            }
+                        }
+
+                        // This was an attempt to use a type parameter outside its scope.
+                        ItemRibKind(has_generic_params) => has_generic_params,
+                        FnItemRibKind => HasGenericParams::Yes,
+                        ConstParamTyRibKind => {
+                            if record_used {
+                                self.report_error(
+                                    span,
+                                    ResolutionError::ParamInTyOfConstParam(rib_ident.name),
+                                );
+                            }
+                            return Res::Err;
+                        }
+                    };
+
+                    if record_used {
+                        self.report_error(
+                            span,
+                            ResolutionError::GenericParamsFromOuterFunction(
+                                res,
+                                has_generic_params,
+                            ),
+                        );
+                    }
+                    return Res::Err;
+                }
+            }
+            Res::Def(DefKind::ConstParam, _) => {
+                let mut ribs = ribs.iter().peekable();
+                if let Some(Rib { kind: FnItemRibKind, .. }) = ribs.peek() {
+                    // When declaring const parameters inside function signatures, the first rib
+                    // is always a `FnItemRibKind`. In this case, we can skip it, to avoid it
+                    // (spuriously) conflicting with the const param.
+                    ribs.next();
+                }
+
+                let mut in_ty_param_default = false;
+                for rib in ribs {
+                    let has_generic_params = match rib.kind {
+                        NormalRibKind
+                        | ClosureOrAsyncRibKind
+                        | AssocItemRibKind
+                        | ModuleRibKind(..)
+                        | MacroDefinition(..) => continue,
+
+                        // We only forbid constant items if we are inside of type defaults,
+                        // for example `struct Foo<T, U = [u8; std::mem::size_of::<T>()]>`
+                        ForwardTyParamBanRibKind => {
+                            in_ty_param_default = true;
+                            continue;
+                        }
+                        ConstantItemRibKind(trivial) => {
+                            // HACK(min_const_generics): We currently only allow `N` or `{ N }`.
+                            if !trivial && self.session.features_untracked().min_const_generics {
+                                if record_used {
+                                    self.report_error(
+                                        span,
+                                        ResolutionError::ParamInNonTrivialAnonConst {
+                                            name: rib_ident.name,
+                                            is_type: false,
+                                        },
+                                    );
+                                }
+                                return Res::Err;
+                            }
+
+                            if in_ty_param_default {
+                                if record_used {
+                                    self.report_error(
+                                        span,
+                                        ResolutionError::ParamInAnonConstInTyDefault(
+                                            rib_ident.name,
+                                        ),
+                                    );
+                                }
+                                return Res::Err;
+                            } else {
+                                continue;
+                            }
+                        }
+
+                        ItemRibKind(has_generic_params) => has_generic_params,
+                        FnItemRibKind => HasGenericParams::Yes,
+                        ConstParamTyRibKind => {
+                            if record_used {
+                                self.report_error(
+                                    span,
+                                    ResolutionError::ParamInTyOfConstParam(rib_ident.name),
+                                );
+                            }
+                            return Res::Err;
+                        }
+                    };
+
+                    // This was an attempt to use a const parameter outside its scope.
+                    if record_used {
+                        self.report_error(
+                            span,
+                            ResolutionError::GenericParamsFromOuterFunction(
+                                res,
+                                has_generic_params,
+                            ),
+                        );
+                    }
+                    return Res::Err;
+                }
+            }
+            _ => {}
+        }
+        res
+    }
+
+    fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
+        debug!("(recording res) recording {:?} for {}", resolution, node_id);
+        if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
+            panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
+        }
+    }
+
+    fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
+        vis.is_accessible_from(module.normal_ancestor_id, self)
+    }
+
+    fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) {
+        if let Some(old_module) = self.binding_parent_modules.insert(PtrKey(binding), module) {
+            if !ptr::eq(module, old_module) {
+                span_bug!(binding.span, "parent module is reset for binding");
+            }
+        }
+    }
+
+    fn disambiguate_macro_rules_vs_modularized(
+        &self,
+        macro_rules: &'a NameBinding<'a>,
+        modularized: &'a NameBinding<'a>,
+    ) -> bool {
+        // Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules"
+        // is disambiguated to mitigate regressions from macro modularization.
+        // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
+        match (
+            self.binding_parent_modules.get(&PtrKey(macro_rules)),
+            self.binding_parent_modules.get(&PtrKey(modularized)),
+        ) {
+            (Some(macro_rules), Some(modularized)) => {
+                macro_rules.normal_ancestor_id == modularized.normal_ancestor_id
+                    && modularized.is_ancestor_of(macro_rules)
+            }
+            _ => false,
+        }
+    }
+
+    fn report_errors(&mut self, krate: &Crate) {
+        self.report_with_use_injections(krate);
+
+        for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
+            let msg = "macro-expanded `macro_export` macros from the current crate \
+                       cannot be referred to by absolute paths";
+            self.lint_buffer.buffer_lint_with_diagnostic(
+                lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
+                CRATE_NODE_ID,
+                span_use,
+                msg,
+                BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
+            );
+        }
+
+        for ambiguity_error in &self.ambiguity_errors {
+            self.report_ambiguity_error(ambiguity_error);
+        }
+
+        let mut reported_spans = FxHashSet::default();
+        for error in &self.privacy_errors {
+            if reported_spans.insert(error.dedup_span) {
+                self.report_privacy_error(error);
+            }
+        }
+    }
+
+    fn report_with_use_injections(&mut self, krate: &Crate) {
+        for UseError { mut err, candidates, def_id, instead, suggestion } in
+            self.use_injections.drain(..)
+        {
+            let (span, found_use) = if let Some(def_id) = def_id.as_local() {
+                UsePlacementFinder::check(krate, self.def_id_to_node_id[def_id])
+            } else {
+                (None, false)
+            };
+            if !candidates.is_empty() {
+                diagnostics::show_candidates(&mut err, span, &candidates, instead, found_use);
+            } else if let Some((span, msg, sugg, appl)) = suggestion {
+                err.span_suggestion(span, msg, sugg, appl);
+            }
+            err.emit();
+        }
+    }
+
+    fn report_conflict<'b>(
+        &mut self,
+        parent: Module<'_>,
+        ident: Ident,
+        ns: Namespace,
+        new_binding: &NameBinding<'b>,
+        old_binding: &NameBinding<'b>,
+    ) {
+        // Error on the second of two conflicting names
+        if old_binding.span.lo() > new_binding.span.lo() {
+            return self.report_conflict(parent, ident, ns, old_binding, new_binding);
+        }
+
+        let container = match parent.kind {
+            ModuleKind::Def(kind, _, _) => kind.descr(parent.def_id().unwrap()),
+            ModuleKind::Block(..) => "block",
+        };
+
+        let old_noun = match old_binding.is_import() {
+            true => "import",
+            false => "definition",
+        };
+
+        let new_participle = match new_binding.is_import() {
+            true => "imported",
+            false => "defined",
+        };
+
+        let (name, span) =
+            (ident.name, self.session.source_map().guess_head_span(new_binding.span));
+
+        if let Some(s) = self.name_already_seen.get(&name) {
+            if s == &span {
+                return;
+            }
+        }
+
+        let old_kind = match (ns, old_binding.module()) {
+            (ValueNS, _) => "value",
+            (MacroNS, _) => "macro",
+            (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
+            (TypeNS, Some(module)) if module.is_normal() => "module",
+            (TypeNS, Some(module)) if module.is_trait() => "trait",
+            (TypeNS, _) => "type",
+        };
+
+        let msg = format!("the name `{}` is defined multiple times", name);
+
+        let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
+            (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
+            (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
+                true => struct_span_err!(self.session, span, E0254, "{}", msg),
+                false => struct_span_err!(self.session, span, E0260, "{}", msg),
+            },
+            _ => match (old_binding.is_import(), new_binding.is_import()) {
+                (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
+                (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
+                _ => struct_span_err!(self.session, span, E0255, "{}", msg),
+            },
+        };
+
+        err.note(&format!(
+            "`{}` must be defined only once in the {} namespace of this {}",
+            name,
+            ns.descr(),
+            container
+        ));
+
+        err.span_label(span, format!("`{}` re{} here", name, new_participle));
+        err.span_label(
+            self.session.source_map().guess_head_span(old_binding.span),
+            format!("previous {} of the {} `{}` here", old_noun, old_kind, name),
+        );
+
+        // See https://github.com/rust-lang/rust/issues/32354
+        use NameBindingKind::Import;
+        let import = match (&new_binding.kind, &old_binding.kind) {
+            // If there are two imports where one or both have attributes then prefer removing the
+            // import without attributes.
+            (Import { import: new, .. }, Import { import: old, .. })
+                if {
+                    !new_binding.span.is_dummy()
+                        && !old_binding.span.is_dummy()
+                        && (new.has_attributes || old.has_attributes)
+                } =>
+            {
+                if old.has_attributes {
+                    Some((new, new_binding.span, true))
+                } else {
+                    Some((old, old_binding.span, true))
+                }
+            }
+            // Otherwise prioritize the new binding.
+            (Import { import, .. }, other) if !new_binding.span.is_dummy() => {
+                Some((import, new_binding.span, other.is_import()))
+            }
+            (other, Import { import, .. }) if !old_binding.span.is_dummy() => {
+                Some((import, old_binding.span, other.is_import()))
+            }
+            _ => None,
+        };
+
+        // Check if the target of the use for both bindings is the same.
+        let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
+        let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
+        let from_item =
+            self.extern_prelude.get(&ident).map(|entry| entry.introduced_by_item).unwrap_or(true);
+        // Only suggest removing an import if both bindings are to the same def, if both spans
+        // aren't dummy spans. Further, if both bindings are imports, then the ident must have
+        // been introduced by a item.
+        let should_remove_import = duplicate
+            && !has_dummy_span
+            && ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
+
+        match import {
+            Some((import, span, true)) if should_remove_import && import.is_nested() => {
+                self.add_suggestion_for_duplicate_nested_use(&mut err, import, span)
+            }
+            Some((import, _, true)) if should_remove_import && !import.is_glob() => {
+                // Simple case - remove the entire import. Due to the above match arm, this can
+                // only be a single use so just remove it entirely.
+                err.tool_only_span_suggestion(
+                    import.use_span_with_attributes,
+                    "remove unnecessary import",
+                    String::new(),
+                    Applicability::MaybeIncorrect,
+                );
+            }
+            Some((import, span, _)) => {
+                self.add_suggestion_for_rename_of_use(&mut err, name, import, span)
+            }
+            _ => {}
+        }
+
+        err.emit();
+        self.name_already_seen.insert(name, span);
+    }
+
+    /// This function adds a suggestion to change the binding name of a new import that conflicts
+    /// with an existing import.
+    ///
+    /// ```text,ignore (diagnostic)
+    /// help: you can use `as` to change the binding name of the import
+    ///    |
+    /// LL | use foo::bar as other_bar;
+    ///    |     ^^^^^^^^^^^^^^^^^^^^^
+    /// ```
+    fn add_suggestion_for_rename_of_use(
+        &self,
+        err: &mut DiagnosticBuilder<'_>,
+        name: Symbol,
+        import: &Import<'_>,
+        binding_span: Span,
+    ) {
+        let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
+            format!("Other{}", name)
+        } else {
+            format!("other_{}", name)
+        };
+
+        let mut suggestion = None;
+        match import.kind {
+            ImportKind::Single { type_ns_only: true, .. } => {
+                suggestion = Some(format!("self as {}", suggested_name))
+            }
+            ImportKind::Single { source, .. } => {
+                if let Some(pos) =
+                    source.span.hi().0.checked_sub(binding_span.lo().0).map(|pos| pos as usize)
+                {
+                    if let Ok(snippet) = self.session.source_map().span_to_snippet(binding_span) {
+                        if pos <= snippet.len() {
+                            suggestion = Some(format!(
+                                "{} as {}{}",
+                                &snippet[..pos],
+                                suggested_name,
+                                if snippet.ends_with(';') { ";" } else { "" }
+                            ))
+                        }
+                    }
+                }
+            }
+            ImportKind::ExternCrate { source, target, .. } => {
+                suggestion = Some(format!(
+                    "extern crate {} as {};",
+                    source.unwrap_or(target.name),
+                    suggested_name,
+                ))
+            }
+            _ => unreachable!(),
+        }
+
+        let rename_msg = "you can use `as` to change the binding name of the import";
+        if let Some(suggestion) = suggestion {
+            err.span_suggestion(
+                binding_span,
+                rename_msg,
+                suggestion,
+                Applicability::MaybeIncorrect,
+            );
+        } else {
+            err.span_label(binding_span, rename_msg);
+        }
+    }
+
+    /// This function adds a suggestion to remove a unnecessary binding from an import that is
+    /// nested. In the following example, this function will be invoked to remove the `a` binding
+    /// in the second use statement:
+    ///
+    /// ```ignore (diagnostic)
+    /// use issue_52891::a;
+    /// use issue_52891::{d, a, e};
+    /// ```
+    ///
+    /// The following suggestion will be added:
+    ///
+    /// ```ignore (diagnostic)
+    /// use issue_52891::{d, a, e};
+    ///                      ^-- help: remove unnecessary import
+    /// ```
+    ///
+    /// If the nested use contains only one import then the suggestion will remove the entire
+    /// line.
+    ///
+    /// It is expected that the provided import is nested - this isn't checked by the
+    /// function. If this invariant is not upheld, this function's behaviour will be unexpected
+    /// as characters expected by span manipulations won't be present.
+    fn add_suggestion_for_duplicate_nested_use(
+        &self,
+        err: &mut DiagnosticBuilder<'_>,
+        import: &Import<'_>,
+        binding_span: Span,
+    ) {
+        assert!(import.is_nested());
+        let message = "remove unnecessary import";
+
+        // Two examples will be used to illustrate the span manipulations we're doing:
+        //
+        // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is
+        //   `a` and `import.use_span` is `issue_52891::{d, a, e};`.
+        // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is
+        //   `a` and `import.use_span` is `issue_52891::{d, e, a};`.
+
+        let (found_closing_brace, span) =
+            find_span_of_binding_until_next_binding(self.session, binding_span, import.use_span);
+
+        // If there was a closing brace then identify the span to remove any trailing commas from
+        // previous imports.
+        if found_closing_brace {
+            if let Some(span) = extend_span_to_previous_binding(self.session, span) {
+                err.tool_only_span_suggestion(
+                    span,
+                    message,
+                    String::new(),
+                    Applicability::MaybeIncorrect,
+                );
+            } else {
+                // Remove the entire line if we cannot extend the span back, this indicates a
+                // `issue_52891::{self}` case.
+                err.span_suggestion(
+                    import.use_span_with_attributes,
+                    message,
+                    String::new(),
+                    Applicability::MaybeIncorrect,
+                );
+            }
+
+            return;
+        }
+
+        err.span_suggestion(span, message, String::new(), Applicability::MachineApplicable);
+    }
+
+    fn extern_prelude_get(
+        &mut self,
+        ident: Ident,
+        speculative: bool,
+    ) -> Option<&'a NameBinding<'a>> {
+        if ident.is_path_segment_keyword() {
+            // Make sure `self`, `super` etc produce an error when passed to here.
+            return None;
+        }
+        self.extern_prelude.get(&ident.normalize_to_macros_2_0()).cloned().and_then(|entry| {
+            if let Some(binding) = entry.extern_crate_item {
+                if !speculative && entry.introduced_by_item {
+                    self.record_use(ident, TypeNS, binding, false);
+                }
+                Some(binding)
+            } else {
+                let crate_id = if !speculative {
+                    self.crate_loader.process_path_extern(ident.name, ident.span)
+                } else {
+                    self.crate_loader.maybe_process_path_extern(ident.name)?
+                };
+                let crate_root = self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
+                Some(
+                    (crate_root, ty::Visibility::Public, DUMMY_SP, ExpnId::root())
+                        .to_name_binding(self.arenas),
+                )
+            }
+        })
+    }
+
+    /// This is equivalent to `get_traits_in_module_containing_item`, but without filtering by the associated item.
+    ///
+    /// This is used by rustdoc for intra-doc links.
+    pub fn traits_in_scope(&mut self, module_id: DefId) -> Vec<TraitCandidate> {
+        let module = self.get_module(module_id);
+        module.ensure_traits(self);
+        let traits = module.traits.borrow();
+        let to_candidate =
+            |this: &mut Self, &(trait_name, binding): &(Ident, &NameBinding<'_>)| TraitCandidate {
+                def_id: binding.res().def_id(),
+                import_ids: this.find_transitive_imports(&binding.kind, trait_name),
+            };
+
+        let mut candidates: Vec<_> =
+            traits.as_ref().unwrap().iter().map(|x| to_candidate(self, x)).collect();
+
+        if let Some(prelude) = self.prelude {
+            if !module.no_implicit_prelude {
+                prelude.ensure_traits(self);
+                candidates.extend(
+                    prelude.traits.borrow().as_ref().unwrap().iter().map(|x| to_candidate(self, x)),
+                );
+            }
+        }
+
+        candidates
+    }
+
+    /// Rustdoc uses this to resolve things in a recoverable way. `ResolutionError<'a>`
+    /// isn't something that can be returned because it can't be made to live that long,
+    /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
+    /// just that an error occurred.
+    // FIXME(Manishearth): intra-doc links won't get warned of epoch changes.
+    pub fn resolve_str_path_error(
+        &mut self,
+        span: Span,
+        path_str: &str,
+        ns: Namespace,
+        module_id: DefId,
+    ) -> Result<(ast::Path, Res), ()> {
+        let path = if path_str.starts_with("::") {
+            ast::Path {
+                span,
+                segments: iter::once(Ident::with_dummy_span(kw::PathRoot))
+                    .chain(path_str.split("::").skip(1).map(Ident::from_str))
+                    .map(|i| self.new_ast_path_segment(i))
+                    .collect(),
+                tokens: None,
+            }
+        } else {
+            ast::Path {
+                span,
+                segments: path_str
+                    .split("::")
+                    .map(Ident::from_str)
+                    .map(|i| self.new_ast_path_segment(i))
+                    .collect(),
+                tokens: None,
+            }
+        };
+        let module = self.get_module(module_id);
+        let parent_scope = &ParentScope::module(module);
+        let res = self.resolve_ast_path(&path, ns, parent_scope).map_err(|_| ())?;
+        Ok((path, res))
+    }
+
+    // Resolve a path passed from rustdoc or HIR lowering.
+    fn resolve_ast_path(
+        &mut self,
+        path: &ast::Path,
+        ns: Namespace,
+        parent_scope: &ParentScope<'a>,
+    ) -> Result<Res, (Span, ResolutionError<'a>)> {
+        match self.resolve_path(
+            &Segment::from_path(path),
+            Some(ns),
+            parent_scope,
+            false,
+            path.span,
+            CrateLint::No,
+        ) {
+            PathResult::Module(ModuleOrUniformRoot::Module(module)) => Ok(module.res().unwrap()),
+            PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
+                Ok(path_res.base_res())
+            }
+            PathResult::NonModule(..) => Err((
+                path.span,
+                ResolutionError::FailedToResolve {
+                    label: String::from("type-relative paths are not supported in this context"),
+                    suggestion: None,
+                },
+            )),
+            PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
+            PathResult::Failed { span, label, suggestion, .. } => {
+                Err((span, ResolutionError::FailedToResolve { label, suggestion }))
+            }
+        }
+    }
+
+    fn new_ast_path_segment(&mut self, ident: Ident) -> ast::PathSegment {
+        let mut seg = ast::PathSegment::from_ident(ident);
+        seg.id = self.next_node_id();
+        seg
+    }
+
+    // For rustdoc.
+    pub fn graph_root(&self) -> Module<'a> {
+        self.graph_root
+    }
+
+    // For rustdoc.
+    pub fn all_macros(&self) -> &FxHashMap<Symbol, Res> {
+        &self.all_macros
+    }
+
+    /// Retrieves the span of the given `DefId` if `DefId` is in the local crate.
+    #[inline]
+    pub fn opt_span(&self, def_id: DefId) -> Option<Span> {
+        if let Some(def_id) = def_id.as_local() { Some(self.def_id_to_span[def_id]) } else { None }
+    }
+}
+
+fn names_to_string(names: &[Symbol]) -> String {
+    let mut result = String::new();
+    for (i, name) in names.iter().filter(|name| **name != kw::PathRoot).enumerate() {
+        if i > 0 {
+            result.push_str("::");
+        }
+        if Ident::with_dummy_span(*name).is_raw_guess() {
+            result.push_str("r#");
+        }
+        result.push_str(&name.as_str());
+    }
+    result
+}
+
+fn path_names_to_string(path: &Path) -> String {
+    names_to_string(&path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>())
+}
+
+/// A somewhat inefficient routine to obtain the name of a module.
+fn module_to_string(module: Module<'_>) -> Option<String> {
+    let mut names = Vec::new();
+
+    fn collect_mod(names: &mut Vec<Symbol>, module: Module<'_>) {
+        if let ModuleKind::Def(.., name) = module.kind {
+            if let Some(parent) = module.parent {
+                names.push(name);
+                collect_mod(names, parent);
+            }
+        } else {
+            names.push(Symbol::intern("<opaque>"));
+            collect_mod(names, module.parent.unwrap());
+        }
+    }
+    collect_mod(&mut names, module);
+
+    if names.is_empty() {
+        return None;
+    }
+    names.reverse();
+    Some(names_to_string(&names))
+}
+
+#[derive(Copy, Clone, Debug)]
+enum CrateLint {
+    /// Do not issue the lint.
+    No,
+
+    /// This lint applies to some arbitrary path; e.g., `impl ::foo::Bar`.
+    /// In this case, we can take the span of that path.
+    SimplePath(NodeId),
+
+    /// This lint comes from a `use` statement. In this case, what we
+    /// care about really is the *root* `use` statement; e.g., if we
+    /// have nested things like `use a::{b, c}`, we care about the
+    /// `use a` part.
+    UsePath { root_id: NodeId, root_span: Span },
+
+    /// This is the "trait item" from a fully qualified path. For example,
+    /// we might be resolving  `X::Y::Z` from a path like `<T as X::Y>::Z`.
+    /// The `path_span` is the span of the to the trait itself (`X::Y`).
+    QPathTrait { qpath_id: NodeId, qpath_span: Span },
+}
+
+impl CrateLint {
+    fn node_id(&self) -> Option<NodeId> {
+        match *self {
+            CrateLint::No => None,
+            CrateLint::SimplePath(id)
+            | CrateLint::UsePath { root_id: id, .. }
+            | CrateLint::QPathTrait { qpath_id: id, .. } => Some(id),
+        }
+    }
+}
+
+pub fn provide(providers: &mut Providers) {
+    late::lifetimes::provide(providers);
+}
diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs
new file mode 100644
index 0000000..bea7138
--- /dev/null
+++ b/compiler/rustc_resolve/src/macros.rs
@@ -0,0 +1,1105 @@
+//! A bunch of methods and structures more or less related to resolving macros and
+//! interface provided by `Resolver` to macro expander.
+
+use crate::imports::ImportResolver;
+use crate::Namespace::*;
+use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BuiltinMacroState, Determinacy};
+use crate::{CrateLint, ParentScope, ResolutionError, Resolver, Scope, ScopeSet, Weak};
+use crate::{ModuleKind, ModuleOrUniformRoot, NameBinding, PathResult, Segment, ToNameBinding};
+use rustc_ast::{self as ast, NodeId};
+use rustc_ast_lowering::ResolverAstLowering;
+use rustc_ast_pretty::pprust;
+use rustc_attr::StabilityLevel;
+use rustc_data_structures::fx::FxHashSet;
+use rustc_errors::struct_span_err;
+use rustc_expand::base::{Indeterminate, InvocationRes, ResolverExpand, SyntaxExtension};
+use rustc_expand::compile_declarative_macro;
+use rustc_expand::expand::{AstFragment, AstFragmentKind, Invocation, InvocationKind};
+use rustc_feature::is_builtin_attr_name;
+use rustc_hir::def::{self, DefKind, NonMacroAttrKind};
+use rustc_hir::def_id;
+use rustc_middle::middle::stability;
+use rustc_middle::{span_bug, ty};
+use rustc_session::lint::builtin::UNUSED_MACROS;
+use rustc_session::Session;
+use rustc_span::edition::Edition;
+use rustc_span::hygiene::{self, ExpnData, ExpnId, ExpnKind};
+use rustc_span::symbol::{kw, sym, Ident, Symbol};
+use rustc_span::{Span, DUMMY_SP};
+
+use rustc_data_structures::sync::Lrc;
+use rustc_span::hygiene::{AstPass, MacroKind};
+use std::{mem, ptr};
+
+type Res = def::Res<NodeId>;
+
+/// Binding produced by a `macro_rules` item.
+/// Not modularized, can shadow previous `macro_rules` bindings, etc.
+#[derive(Debug)]
+pub struct MacroRulesBinding<'a> {
+    crate binding: &'a NameBinding<'a>,
+    /// `macro_rules` scope into which the `macro_rules` item was planted.
+    crate parent_macro_rules_scope: MacroRulesScope<'a>,
+    crate ident: Ident,
+}
+
+/// The scope introduced by a `macro_rules!` macro.
+/// This starts at the macro's definition and ends at the end of the macro's parent
+/// module (named or unnamed), or even further if it escapes with `#[macro_use]`.
+/// Some macro invocations need to introduce `macro_rules` scopes too because they
+/// can potentially expand into macro definitions.
+#[derive(Copy, Clone, Debug)]
+pub enum MacroRulesScope<'a> {
+    /// Empty "root" scope at the crate start containing no names.
+    Empty,
+    /// The scope introduced by a `macro_rules!` macro definition.
+    Binding(&'a MacroRulesBinding<'a>),
+    /// The scope introduced by a macro invocation that can potentially
+    /// create a `macro_rules!` macro definition.
+    Invocation(ExpnId),
+}
+
+// Macro namespace is separated into two sub-namespaces, one for bang macros and
+// one for attribute-like macros (attributes, derives).
+// We ignore resolutions from one sub-namespace when searching names in scope for another.
+fn sub_namespace_match(candidate: Option<MacroKind>, requirement: Option<MacroKind>) -> bool {
+    #[derive(PartialEq)]
+    enum SubNS {
+        Bang,
+        AttrLike,
+    }
+    let sub_ns = |kind| match kind {
+        MacroKind::Bang => SubNS::Bang,
+        MacroKind::Attr | MacroKind::Derive => SubNS::AttrLike,
+    };
+    let candidate = candidate.map(sub_ns);
+    let requirement = requirement.map(sub_ns);
+    // "No specific sub-namespace" means "matches anything" for both requirements and candidates.
+    candidate.is_none() || requirement.is_none() || candidate == requirement
+}
+
+// We don't want to format a path using pretty-printing,
+// `format!("{}", path)`, because that tries to insert
+// line-breaks and is slow.
+fn fast_print_path(path: &ast::Path) -> Symbol {
+    if path.segments.len() == 1 {
+        path.segments[0].ident.name
+    } else {
+        let mut path_str = String::with_capacity(64);
+        for (i, segment) in path.segments.iter().enumerate() {
+            if i != 0 {
+                path_str.push_str("::");
+            }
+            if segment.ident.name != kw::PathRoot {
+                path_str.push_str(&segment.ident.as_str())
+            }
+        }
+        Symbol::intern(&path_str)
+    }
+}
+
+/// The code common between processing `#![register_tool]` and `#![register_attr]`.
+fn registered_idents(
+    sess: &Session,
+    attrs: &[ast::Attribute],
+    attr_name: Symbol,
+    descr: &str,
+) -> FxHashSet<Ident> {
+    let mut registered = FxHashSet::default();
+    for attr in sess.filter_by_name(attrs, attr_name) {
+        for nested_meta in attr.meta_item_list().unwrap_or_default() {
+            match nested_meta.ident() {
+                Some(ident) => {
+                    if let Some(old_ident) = registered.replace(ident) {
+                        let msg = format!("{} `{}` was already registered", descr, ident);
+                        sess.struct_span_err(ident.span, &msg)
+                            .span_label(old_ident.span, "already registered here")
+                            .emit();
+                    }
+                }
+                None => {
+                    let msg = format!("`{}` only accepts identifiers", attr_name);
+                    let span = nested_meta.span();
+                    sess.struct_span_err(span, &msg).span_label(span, "not an identifier").emit();
+                }
+            }
+        }
+    }
+    registered
+}
+
+crate fn registered_attrs_and_tools(
+    sess: &Session,
+    attrs: &[ast::Attribute],
+) -> (FxHashSet<Ident>, FxHashSet<Ident>) {
+    let registered_attrs = registered_idents(sess, attrs, sym::register_attr, "attribute");
+    let mut registered_tools = registered_idents(sess, attrs, sym::register_tool, "tool");
+    // We implicitly add `rustfmt` and `clippy` to known tools,
+    // but it's not an error to register them explicitly.
+    let predefined_tools = [sym::clippy, sym::rustfmt];
+    registered_tools.extend(predefined_tools.iter().cloned().map(Ident::with_dummy_span));
+    (registered_attrs, registered_tools)
+}
+
+impl<'a> ResolverExpand for Resolver<'a> {
+    fn next_node_id(&mut self) -> NodeId {
+        self.next_node_id()
+    }
+
+    fn resolve_dollar_crates(&mut self) {
+        hygiene::update_dollar_crate_names(|ctxt| {
+            let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt));
+            match self.resolve_crate_root(ident).kind {
+                ModuleKind::Def(.., name) if name != kw::Invalid => name,
+                _ => kw::Crate,
+            }
+        });
+    }
+
+    fn visit_ast_fragment_with_placeholders(&mut self, expansion: ExpnId, fragment: &AstFragment) {
+        // Integrate the new AST fragment into all the definition and module structures.
+        // We are inside the `expansion` now, but other parent scope components are still the same.
+        let parent_scope = ParentScope { expansion, ..self.invocation_parent_scopes[&expansion] };
+        let output_macro_rules_scope = self.build_reduced_graph(fragment, parent_scope);
+        self.output_macro_rules_scopes.insert(expansion, output_macro_rules_scope);
+
+        parent_scope.module.unexpanded_invocations.borrow_mut().remove(&expansion);
+    }
+
+    fn register_builtin_macro(&mut self, ident: Ident, ext: SyntaxExtension) {
+        if self.builtin_macros.insert(ident.name, BuiltinMacroState::NotYetSeen(ext)).is_some() {
+            self.session
+                .span_err(ident.span, &format!("built-in macro `{}` was already defined", ident));
+        }
+    }
+
+    // Create a new Expansion with a definition site of the provided module, or
+    // a fake empty `#[no_implicit_prelude]` module if no module is provided.
+    fn expansion_for_ast_pass(
+        &mut self,
+        call_site: Span,
+        pass: AstPass,
+        features: &[Symbol],
+        parent_module_id: Option<NodeId>,
+    ) -> ExpnId {
+        let expn_id = ExpnId::fresh(Some(ExpnData::allow_unstable(
+            ExpnKind::AstPass(pass),
+            call_site,
+            self.session.edition(),
+            features.into(),
+            None,
+        )));
+
+        let parent_scope = if let Some(module_id) = parent_module_id {
+            let parent_def_id = self.local_def_id(module_id);
+            self.definitions.add_parent_module_of_macro_def(expn_id, parent_def_id.to_def_id());
+            self.module_map[&parent_def_id]
+        } else {
+            self.definitions.add_parent_module_of_macro_def(
+                expn_id,
+                def_id::DefId::local(def_id::CRATE_DEF_INDEX),
+            );
+            self.empty_module
+        };
+        self.ast_transform_scopes.insert(expn_id, parent_scope);
+        expn_id
+    }
+
+    fn resolve_imports(&mut self) {
+        ImportResolver { r: self }.resolve_imports()
+    }
+
+    fn resolve_macro_invocation(
+        &mut self,
+        invoc: &Invocation,
+        eager_expansion_root: ExpnId,
+        force: bool,
+    ) -> Result<InvocationRes, Indeterminate> {
+        let invoc_id = invoc.expansion_data.id;
+        let parent_scope = match self.invocation_parent_scopes.get(&invoc_id) {
+            Some(parent_scope) => *parent_scope,
+            None => {
+                // If there's no entry in the table, then we are resolving an eagerly expanded
+                // macro, which should inherit its parent scope from its eager expansion root -
+                // the macro that requested this eager expansion.
+                let parent_scope = *self
+                    .invocation_parent_scopes
+                    .get(&eager_expansion_root)
+                    .expect("non-eager expansion without a parent scope");
+                self.invocation_parent_scopes.insert(invoc_id, parent_scope);
+                parent_scope
+            }
+        };
+
+        let (path, kind, derives, after_derive) = match invoc.kind {
+            InvocationKind::Attr { ref attr, ref derives, after_derive, .. } => (
+                &attr.get_normal_item().path,
+                MacroKind::Attr,
+                self.arenas.alloc_ast_paths(derives),
+                after_derive,
+            ),
+            InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang, &[][..], false),
+            InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive, &[][..], false),
+            InvocationKind::DeriveContainer { ref derives, .. } => {
+                // Block expansion of the container until we resolve all derives in it.
+                // This is required for two reasons:
+                // - Derive helper attributes are in scope for the item to which the `#[derive]`
+                //   is applied, so they have to be produced by the container's expansion rather
+                //   than by individual derives.
+                // - Derives in the container need to know whether one of them is a built-in `Copy`.
+                // FIXME: Try to avoid repeated resolutions for derives here and in expansion.
+                let mut exts = Vec::new();
+                let mut helper_attrs = Vec::new();
+                for path in derives {
+                    exts.push(
+                        match self.resolve_macro_path(
+                            path,
+                            Some(MacroKind::Derive),
+                            &parent_scope,
+                            true,
+                            force,
+                        ) {
+                            Ok((Some(ext), _)) => {
+                                let span = path
+                                    .segments
+                                    .last()
+                                    .unwrap()
+                                    .ident
+                                    .span
+                                    .normalize_to_macros_2_0();
+                                helper_attrs.extend(
+                                    ext.helper_attrs.iter().map(|name| Ident::new(*name, span)),
+                                );
+                                if ext.is_derive_copy {
+                                    self.add_derive_copy(invoc_id);
+                                }
+                                ext
+                            }
+                            Ok(_) | Err(Determinacy::Determined) => {
+                                self.dummy_ext(MacroKind::Derive)
+                            }
+                            Err(Determinacy::Undetermined) => return Err(Indeterminate),
+                        },
+                    )
+                }
+                self.helper_attrs.insert(invoc_id, helper_attrs);
+                return Ok(InvocationRes::DeriveContainer(exts));
+            }
+        };
+
+        // Derives are not included when `invocations` are collected, so we have to add them here.
+        let parent_scope = &ParentScope { derives, ..parent_scope };
+        let node_id = self.lint_node_id(eager_expansion_root);
+        let (ext, res) = self.smart_resolve_macro_path(path, kind, parent_scope, node_id, force)?;
+
+        let span = invoc.span();
+        invoc_id.set_expn_data(ext.expn_data(
+            parent_scope.expansion,
+            span,
+            fast_print_path(path),
+            res.opt_def_id(),
+        ));
+
+        if let Res::Def(_, _) = res {
+            if after_derive {
+                self.session.span_err(span, "macro attributes must be placed before `#[derive]`");
+            }
+            let normal_module_def_id = self.macro_def_scope(invoc_id).normal_ancestor_id;
+            self.definitions.add_parent_module_of_macro_def(invoc_id, normal_module_def_id);
+        }
+
+        match invoc.fragment_kind {
+            AstFragmentKind::Arms
+            | AstFragmentKind::Fields
+            | AstFragmentKind::FieldPats
+            | AstFragmentKind::GenericParams
+            | AstFragmentKind::Params
+            | AstFragmentKind::StructFields
+            | AstFragmentKind::Variants => {
+                if let Res::Def(..) = res {
+                    self.session.span_err(
+                        span,
+                        &format!(
+                            "expected an inert attribute, found {} {}",
+                            res.article(),
+                            res.descr()
+                        ),
+                    );
+                    return Ok(InvocationRes::Single(self.dummy_ext(kind)));
+                }
+            }
+            _ => {}
+        }
+
+        Ok(InvocationRes::Single(ext))
+    }
+
+    fn check_unused_macros(&mut self) {
+        for (_, &(node_id, span)) in self.unused_macros.iter() {
+            self.lint_buffer.buffer_lint(UNUSED_MACROS, node_id, span, "unused macro definition");
+        }
+    }
+
+    fn lint_node_id(&mut self, expn_id: ExpnId) -> NodeId {
+        self.invocation_parents
+            .get(&expn_id)
+            .map_or(ast::CRATE_NODE_ID, |id| self.def_id_to_node_id[*id])
+    }
+
+    fn has_derive_copy(&self, expn_id: ExpnId) -> bool {
+        self.containers_deriving_copy.contains(&expn_id)
+    }
+
+    fn add_derive_copy(&mut self, expn_id: ExpnId) {
+        self.containers_deriving_copy.insert(expn_id);
+    }
+
+    // The function that implements the resolution logic of `#[cfg_accessible(path)]`.
+    // Returns true if the path can certainly be resolved in one of three namespaces,
+    // returns false if the path certainly cannot be resolved in any of the three namespaces.
+    // Returns `Indeterminate` if we cannot give a certain answer yet.
+    fn cfg_accessible(&mut self, expn_id: ExpnId, path: &ast::Path) -> Result<bool, Indeterminate> {
+        let span = path.span;
+        let path = &Segment::from_path(path);
+        let parent_scope = self.invocation_parent_scopes[&expn_id];
+
+        let mut indeterminate = false;
+        for ns in [TypeNS, ValueNS, MacroNS].iter().copied() {
+            match self.resolve_path(path, Some(ns), &parent_scope, false, span, CrateLint::No) {
+                PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
+                PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
+                    return Ok(true);
+                }
+                PathResult::Indeterminate => indeterminate = true,
+                // FIXME: `resolve_path` is not ready to report partially resolved paths
+                // correctly, so we just report an error if the path was reported as unresolved.
+                // This needs to be fixed for `cfg_accessible` to be useful.
+                PathResult::NonModule(..) | PathResult::Failed { .. } => {}
+                PathResult::Module(_) => panic!("unexpected path resolution"),
+            }
+        }
+
+        if indeterminate {
+            return Err(Indeterminate);
+        }
+
+        self.session
+            .struct_span_err(span, "not sure whether the path is accessible or not")
+            .span_note(span, "`cfg_accessible` is not fully implemented")
+            .emit();
+        Ok(false)
+    }
+}
+
+impl<'a> Resolver<'a> {
+    /// Resolve macro path with error reporting and recovery.
+    fn smart_resolve_macro_path(
+        &mut self,
+        path: &ast::Path,
+        kind: MacroKind,
+        parent_scope: &ParentScope<'a>,
+        node_id: NodeId,
+        force: bool,
+    ) -> Result<(Lrc<SyntaxExtension>, Res), Indeterminate> {
+        let (ext, res) = match self.resolve_macro_path(path, Some(kind), parent_scope, true, force)
+        {
+            Ok((Some(ext), res)) => (ext, res),
+            // Use dummy syntax extensions for unresolved macros for better recovery.
+            Ok((None, res)) => (self.dummy_ext(kind), res),
+            Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err),
+            Err(Determinacy::Undetermined) => return Err(Indeterminate),
+        };
+
+        // Report errors for the resolved macro.
+        for segment in &path.segments {
+            if let Some(args) = &segment.args {
+                self.session.span_err(args.span(), "generic arguments in macro path");
+            }
+            if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") {
+                self.session.span_err(
+                    segment.ident.span,
+                    "attributes starting with `rustc` are reserved for use by the `rustc` compiler",
+                );
+            }
+        }
+
+        match res {
+            Res::Def(DefKind::Macro(_), def_id) => {
+                if let Some(def_id) = def_id.as_local() {
+                    self.unused_macros.remove(&def_id);
+                    if self.proc_macro_stubs.contains(&def_id) {
+                        self.session.span_err(
+                            path.span,
+                            "can't use a procedural macro from the same crate that defines it",
+                        );
+                    }
+                }
+            }
+            Res::NonMacroAttr(..) | Res::Err => {}
+            _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
+        };
+
+        self.check_stability_and_deprecation(&ext, path, node_id);
+
+        Ok(if ext.macro_kind() != kind {
+            let expected = kind.descr_expected();
+            let path_str = pprust::path_to_string(path);
+            let msg = format!("expected {}, found {} `{}`", expected, res.descr(), path_str);
+            self.session
+                .struct_span_err(path.span, &msg)
+                .span_label(path.span, format!("not {} {}", kind.article(), expected))
+                .emit();
+            // Use dummy syntax extensions for unexpected macro kinds for better recovery.
+            (self.dummy_ext(kind), Res::Err)
+        } else {
+            (ext, res)
+        })
+    }
+
+    pub fn resolve_macro_path(
+        &mut self,
+        path: &ast::Path,
+        kind: Option<MacroKind>,
+        parent_scope: &ParentScope<'a>,
+        trace: bool,
+        force: bool,
+    ) -> Result<(Option<Lrc<SyntaxExtension>>, Res), Determinacy> {
+        let path_span = path.span;
+        let mut path = Segment::from_path(path);
+
+        // Possibly apply the macro helper hack
+        if kind == Some(MacroKind::Bang)
+            && path.len() == 1
+            && path[0].ident.span.ctxt().outer_expn_data().local_inner_macros
+        {
+            let root = Ident::new(kw::DollarCrate, path[0].ident.span);
+            path.insert(0, Segment::from_ident(root));
+        }
+
+        let res = if path.len() > 1 {
+            let res = match self.resolve_path(
+                &path,
+                Some(MacroNS),
+                parent_scope,
+                false,
+                path_span,
+                CrateLint::No,
+            ) {
+                PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
+                    Ok(path_res.base_res())
+                }
+                PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
+                PathResult::NonModule(..)
+                | PathResult::Indeterminate
+                | PathResult::Failed { .. } => Err(Determinacy::Determined),
+                PathResult::Module(..) => unreachable!(),
+            };
+
+            if trace {
+                let kind = kind.expect("macro kind must be specified if tracing is enabled");
+                self.multi_segment_macro_resolutions.push((
+                    path,
+                    path_span,
+                    kind,
+                    *parent_scope,
+                    res.ok(),
+                ));
+            }
+
+            self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
+            res
+        } else {
+            let scope_set = kind.map_or(ScopeSet::All(MacroNS, false), ScopeSet::Macro);
+            let binding = self.early_resolve_ident_in_lexical_scope(
+                path[0].ident,
+                scope_set,
+                parent_scope,
+                false,
+                force,
+                path_span,
+            );
+            if let Err(Determinacy::Undetermined) = binding {
+                return Err(Determinacy::Undetermined);
+            }
+
+            if trace {
+                let kind = kind.expect("macro kind must be specified if tracing is enabled");
+                self.single_segment_macro_resolutions.push((
+                    path[0].ident,
+                    kind,
+                    *parent_scope,
+                    binding.ok(),
+                ));
+            }
+
+            let res = binding.map(|binding| binding.res());
+            self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
+            res
+        };
+
+        res.map(|res| (self.get_macro(res), res))
+    }
+
+    // Resolve an identifier in lexical scope.
+    // This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
+    // expansion and import resolution (perhaps they can be merged in the future).
+    // The function is used for resolving initial segments of macro paths (e.g., `foo` in
+    // `foo::bar!(); or `foo!();`) and also for import paths on 2018 edition.
+    crate fn early_resolve_ident_in_lexical_scope(
+        &mut self,
+        orig_ident: Ident,
+        scope_set: ScopeSet,
+        parent_scope: &ParentScope<'a>,
+        record_used: bool,
+        force: bool,
+        path_span: Span,
+    ) -> Result<&'a NameBinding<'a>, Determinacy> {
+        bitflags::bitflags! {
+            struct Flags: u8 {
+                const MACRO_RULES          = 1 << 0;
+                const MODULE               = 1 << 1;
+                const DERIVE_HELPER_COMPAT = 1 << 2;
+                const MISC_SUGGEST_CRATE   = 1 << 3;
+                const MISC_SUGGEST_SELF    = 1 << 4;
+                const MISC_FROM_PRELUDE    = 1 << 5;
+            }
+        }
+
+        assert!(force || !record_used); // `record_used` implies `force`
+
+        // Make sure `self`, `super` etc produce an error when passed to here.
+        if orig_ident.is_path_segment_keyword() {
+            return Err(Determinacy::Determined);
+        }
+
+        let (ns, macro_kind, is_import) = match scope_set {
+            ScopeSet::All(ns, is_import) => (ns, None, is_import),
+            ScopeSet::AbsolutePath(ns) => (ns, None, false),
+            ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false),
+        };
+
+        // This is *the* result, resolution from the scope closest to the resolved identifier.
+        // However, sometimes this result is "weak" because it comes from a glob import or
+        // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
+        // mod m { ... } // solution in outer scope
+        // {
+        //     use prefix::*; // imports another `m` - innermost solution
+        //                    // weak, cannot shadow the outer `m`, need to report ambiguity error
+        //     m::mac!();
+        // }
+        // So we have to save the innermost solution and continue searching in outer scopes
+        // to detect potential ambiguities.
+        let mut innermost_result: Option<(&NameBinding<'_>, Flags)> = None;
+        let mut determinacy = Determinacy::Determined;
+
+        // Go through all the scopes and try to resolve the name.
+        let break_result = self.visit_scopes(
+            scope_set,
+            parent_scope,
+            orig_ident,
+            |this, scope, use_prelude, ident| {
+                let ok = |res, span, arenas| {
+                    Ok((
+                        (res, ty::Visibility::Public, span, ExpnId::root()).to_name_binding(arenas),
+                        Flags::empty(),
+                    ))
+                };
+                let result = match scope {
+                    Scope::DeriveHelpers(expn_id) => {
+                        if let Some(attr) = this
+                            .helper_attrs
+                            .get(&expn_id)
+                            .and_then(|attrs| attrs.iter().rfind(|i| ident == **i))
+                        {
+                            let binding = (
+                                Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
+                                ty::Visibility::Public,
+                                attr.span,
+                                expn_id,
+                            )
+                                .to_name_binding(this.arenas);
+                            Ok((binding, Flags::empty()))
+                        } else {
+                            Err(Determinacy::Determined)
+                        }
+                    }
+                    Scope::DeriveHelpersCompat => {
+                        let mut result = Err(Determinacy::Determined);
+                        for derive in parent_scope.derives {
+                            let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
+                            match this.resolve_macro_path(
+                                derive,
+                                Some(MacroKind::Derive),
+                                parent_scope,
+                                true,
+                                force,
+                            ) {
+                                Ok((Some(ext), _)) => {
+                                    if ext.helper_attrs.contains(&ident.name) {
+                                        let binding = (
+                                            Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
+                                            ty::Visibility::Public,
+                                            derive.span,
+                                            ExpnId::root(),
+                                        )
+                                            .to_name_binding(this.arenas);
+                                        result = Ok((binding, Flags::DERIVE_HELPER_COMPAT));
+                                        break;
+                                    }
+                                }
+                                Ok(_) | Err(Determinacy::Determined) => {}
+                                Err(Determinacy::Undetermined) => {
+                                    result = Err(Determinacy::Undetermined)
+                                }
+                            }
+                        }
+                        result
+                    }
+                    Scope::MacroRules(macro_rules_scope) => match macro_rules_scope {
+                        MacroRulesScope::Binding(macro_rules_binding)
+                            if ident == macro_rules_binding.ident =>
+                        {
+                            Ok((macro_rules_binding.binding, Flags::MACRO_RULES))
+                        }
+                        MacroRulesScope::Invocation(invoc_id)
+                            if !this.output_macro_rules_scopes.contains_key(&invoc_id) =>
+                        {
+                            Err(Determinacy::Undetermined)
+                        }
+                        _ => Err(Determinacy::Determined),
+                    },
+                    Scope::CrateRoot => {
+                        let root_ident = Ident::new(kw::PathRoot, ident.span);
+                        let root_module = this.resolve_crate_root(root_ident);
+                        let binding = this.resolve_ident_in_module_ext(
+                            ModuleOrUniformRoot::Module(root_module),
+                            ident,
+                            ns,
+                            parent_scope,
+                            record_used,
+                            path_span,
+                        );
+                        match binding {
+                            Ok(binding) => Ok((binding, Flags::MODULE | Flags::MISC_SUGGEST_CRATE)),
+                            Err((Determinacy::Undetermined, Weak::No)) => {
+                                return Some(Err(Determinacy::determined(force)));
+                            }
+                            Err((Determinacy::Undetermined, Weak::Yes)) => {
+                                Err(Determinacy::Undetermined)
+                            }
+                            Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
+                        }
+                    }
+                    Scope::Module(module) => {
+                        let adjusted_parent_scope = &ParentScope { module, ..*parent_scope };
+                        let binding = this.resolve_ident_in_module_unadjusted_ext(
+                            ModuleOrUniformRoot::Module(module),
+                            ident,
+                            ns,
+                            adjusted_parent_scope,
+                            true,
+                            record_used,
+                            path_span,
+                        );
+                        match binding {
+                            Ok(binding) => {
+                                let misc_flags = if ptr::eq(module, this.graph_root) {
+                                    Flags::MISC_SUGGEST_CRATE
+                                } else if module.is_normal() {
+                                    Flags::MISC_SUGGEST_SELF
+                                } else {
+                                    Flags::empty()
+                                };
+                                Ok((binding, Flags::MODULE | misc_flags))
+                            }
+                            Err((Determinacy::Undetermined, Weak::No)) => {
+                                return Some(Err(Determinacy::determined(force)));
+                            }
+                            Err((Determinacy::Undetermined, Weak::Yes)) => {
+                                Err(Determinacy::Undetermined)
+                            }
+                            Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
+                        }
+                    }
+                    Scope::RegisteredAttrs => match this.registered_attrs.get(&ident).cloned() {
+                        Some(ident) => ok(
+                            Res::NonMacroAttr(NonMacroAttrKind::Registered),
+                            ident.span,
+                            this.arenas,
+                        ),
+                        None => Err(Determinacy::Determined),
+                    },
+                    Scope::MacroUsePrelude => {
+                        match this.macro_use_prelude.get(&ident.name).cloned() {
+                            Some(binding) => Ok((binding, Flags::MISC_FROM_PRELUDE)),
+                            None => Err(Determinacy::determined(
+                                this.graph_root.unexpanded_invocations.borrow().is_empty(),
+                            )),
+                        }
+                    }
+                    Scope::BuiltinAttrs => {
+                        if is_builtin_attr_name(ident.name) {
+                            ok(Res::NonMacroAttr(NonMacroAttrKind::Builtin), DUMMY_SP, this.arenas)
+                        } else {
+                            Err(Determinacy::Determined)
+                        }
+                    }
+                    Scope::ExternPrelude => match this.extern_prelude_get(ident, !record_used) {
+                        Some(binding) => Ok((binding, Flags::empty())),
+                        None => Err(Determinacy::determined(
+                            this.graph_root.unexpanded_invocations.borrow().is_empty(),
+                        )),
+                    },
+                    Scope::ToolPrelude => match this.registered_tools.get(&ident).cloned() {
+                        Some(ident) => ok(Res::ToolMod, ident.span, this.arenas),
+                        None => Err(Determinacy::Determined),
+                    },
+                    Scope::StdLibPrelude => {
+                        let mut result = Err(Determinacy::Determined);
+                        if let Some(prelude) = this.prelude {
+                            if let Ok(binding) = this.resolve_ident_in_module_unadjusted(
+                                ModuleOrUniformRoot::Module(prelude),
+                                ident,
+                                ns,
+                                parent_scope,
+                                false,
+                                path_span,
+                            ) {
+                                if use_prelude || this.is_builtin_macro(binding.res()) {
+                                    result = Ok((binding, Flags::MISC_FROM_PRELUDE));
+                                }
+                            }
+                        }
+                        result
+                    }
+                    Scope::BuiltinTypes => {
+                        match this.primitive_type_table.primitive_types.get(&ident.name).cloned() {
+                            Some(prim_ty) => ok(Res::PrimTy(prim_ty), DUMMY_SP, this.arenas),
+                            None => Err(Determinacy::Determined),
+                        }
+                    }
+                };
+
+                match result {
+                    Ok((binding, flags))
+                        if sub_namespace_match(binding.macro_kind(), macro_kind) =>
+                    {
+                        if !record_used {
+                            return Some(Ok(binding));
+                        }
+
+                        if let Some((innermost_binding, innermost_flags)) = innermost_result {
+                            // Found another solution, if the first one was "weak", report an error.
+                            let (res, innermost_res) = (binding.res(), innermost_binding.res());
+                            if res != innermost_res {
+                                let builtin = Res::NonMacroAttr(NonMacroAttrKind::Builtin);
+                                let is_derive_helper_compat = |res, flags: Flags| {
+                                    res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper)
+                                        && flags.contains(Flags::DERIVE_HELPER_COMPAT)
+                                };
+
+                                let ambiguity_error_kind = if is_import {
+                                    Some(AmbiguityKind::Import)
+                                } else if innermost_res == builtin || res == builtin {
+                                    Some(AmbiguityKind::BuiltinAttr)
+                                } else if is_derive_helper_compat(innermost_res, innermost_flags)
+                                    || is_derive_helper_compat(res, flags)
+                                {
+                                    Some(AmbiguityKind::DeriveHelper)
+                                } else if innermost_flags.contains(Flags::MACRO_RULES)
+                                    && flags.contains(Flags::MODULE)
+                                    && !this.disambiguate_macro_rules_vs_modularized(
+                                        innermost_binding,
+                                        binding,
+                                    )
+                                    || flags.contains(Flags::MACRO_RULES)
+                                        && innermost_flags.contains(Flags::MODULE)
+                                        && !this.disambiguate_macro_rules_vs_modularized(
+                                            binding,
+                                            innermost_binding,
+                                        )
+                                {
+                                    Some(AmbiguityKind::MacroRulesVsModularized)
+                                } else if innermost_binding.is_glob_import() {
+                                    Some(AmbiguityKind::GlobVsOuter)
+                                } else if innermost_binding
+                                    .may_appear_after(parent_scope.expansion, binding)
+                                {
+                                    Some(AmbiguityKind::MoreExpandedVsOuter)
+                                } else {
+                                    None
+                                };
+                                if let Some(kind) = ambiguity_error_kind {
+                                    let misc = |f: Flags| {
+                                        if f.contains(Flags::MISC_SUGGEST_CRATE) {
+                                            AmbiguityErrorMisc::SuggestCrate
+                                        } else if f.contains(Flags::MISC_SUGGEST_SELF) {
+                                            AmbiguityErrorMisc::SuggestSelf
+                                        } else if f.contains(Flags::MISC_FROM_PRELUDE) {
+                                            AmbiguityErrorMisc::FromPrelude
+                                        } else {
+                                            AmbiguityErrorMisc::None
+                                        }
+                                    };
+                                    this.ambiguity_errors.push(AmbiguityError {
+                                        kind,
+                                        ident: orig_ident,
+                                        b1: innermost_binding,
+                                        b2: binding,
+                                        misc1: misc(innermost_flags),
+                                        misc2: misc(flags),
+                                    });
+                                    return Some(Ok(innermost_binding));
+                                }
+                            }
+                        } else {
+                            // Found the first solution.
+                            innermost_result = Some((binding, flags));
+                        }
+                    }
+                    Ok(..) | Err(Determinacy::Determined) => {}
+                    Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
+                }
+
+                None
+            },
+        );
+
+        if let Some(break_result) = break_result {
+            return break_result;
+        }
+
+        // The first found solution was the only one, return it.
+        if let Some((binding, _)) = innermost_result {
+            return Ok(binding);
+        }
+
+        Err(Determinacy::determined(determinacy == Determinacy::Determined || force))
+    }
+
+    crate fn finalize_macro_resolutions(&mut self) {
+        let check_consistency = |this: &mut Self,
+                                 path: &[Segment],
+                                 span,
+                                 kind: MacroKind,
+                                 initial_res: Option<Res>,
+                                 res: Res| {
+            if let Some(initial_res) = initial_res {
+                if res != initial_res && res != Res::Err && this.ambiguity_errors.is_empty() {
+                    // Make sure compilation does not succeed if preferred macro resolution
+                    // has changed after the macro had been expanded. In theory all such
+                    // situations should be reported as ambiguity errors, so this is a bug.
+                    span_bug!(span, "inconsistent resolution for a macro");
+                }
+            } else {
+                // It's possible that the macro was unresolved (indeterminate) and silently
+                // expanded into a dummy fragment for recovery during expansion.
+                // Now, post-expansion, the resolution may succeed, but we can't change the
+                // past and need to report an error.
+                // However, non-speculative `resolve_path` can successfully return private items
+                // even if speculative `resolve_path` returned nothing previously, so we skip this
+                // less informative error if the privacy error is reported elsewhere.
+                if this.privacy_errors.is_empty() {
+                    let msg = format!(
+                        "cannot determine resolution for the {} `{}`",
+                        kind.descr(),
+                        Segment::names_to_string(path)
+                    );
+                    let msg_note = "import resolution is stuck, try simplifying macro imports";
+                    this.session.struct_span_err(span, &msg).note(msg_note).emit();
+                }
+            }
+        };
+
+        let macro_resolutions = mem::take(&mut self.multi_segment_macro_resolutions);
+        for (mut path, path_span, kind, parent_scope, initial_res) in macro_resolutions {
+            // FIXME: Path resolution will ICE if segment IDs present.
+            for seg in &mut path {
+                seg.id = None;
+            }
+            match self.resolve_path(
+                &path,
+                Some(MacroNS),
+                &parent_scope,
+                true,
+                path_span,
+                CrateLint::No,
+            ) {
+                PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
+                    let res = path_res.base_res();
+                    check_consistency(self, &path, path_span, kind, initial_res, res);
+                }
+                path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed { .. } => {
+                    let (span, label) = if let PathResult::Failed { span, label, .. } = path_res {
+                        (span, label)
+                    } else {
+                        (
+                            path_span,
+                            format!(
+                                "partially resolved path in {} {}",
+                                kind.article(),
+                                kind.descr()
+                            ),
+                        )
+                    };
+                    self.report_error(
+                        span,
+                        ResolutionError::FailedToResolve { label, suggestion: None },
+                    );
+                }
+                PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
+            }
+        }
+
+        let macro_resolutions = mem::take(&mut self.single_segment_macro_resolutions);
+        for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
+            match self.early_resolve_ident_in_lexical_scope(
+                ident,
+                ScopeSet::Macro(kind),
+                &parent_scope,
+                true,
+                true,
+                ident.span,
+            ) {
+                Ok(binding) => {
+                    let initial_res = initial_binding.map(|initial_binding| {
+                        self.record_use(ident, MacroNS, initial_binding, false);
+                        initial_binding.res()
+                    });
+                    let res = binding.res();
+                    let seg = Segment::from_ident(ident);
+                    check_consistency(self, &[seg], ident.span, kind, initial_res, res);
+                }
+                Err(..) => {
+                    let expected = kind.descr_expected();
+                    let msg = format!("cannot find {} `{}` in this scope", expected, ident);
+                    let mut err = self.session.struct_span_err(ident.span, &msg);
+                    self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident);
+                    err.emit();
+                }
+            }
+        }
+
+        let builtin_attrs = mem::take(&mut self.builtin_attrs);
+        for (ident, parent_scope) in builtin_attrs {
+            let _ = self.early_resolve_ident_in_lexical_scope(
+                ident,
+                ScopeSet::Macro(MacroKind::Attr),
+                &parent_scope,
+                true,
+                true,
+                ident.span,
+            );
+        }
+    }
+
+    fn check_stability_and_deprecation(
+        &mut self,
+        ext: &SyntaxExtension,
+        path: &ast::Path,
+        node_id: NodeId,
+    ) {
+        let span = path.span;
+        if let Some(stability) = &ext.stability {
+            if let StabilityLevel::Unstable { reason, issue, is_soft } = stability.level {
+                let feature = stability.feature;
+                if !self.active_features.contains(&feature) && !span.allows_unstable(feature) {
+                    let lint_buffer = &mut self.lint_buffer;
+                    let soft_handler =
+                        |lint, span, msg: &_| lint_buffer.buffer_lint(lint, node_id, span, msg);
+                    stability::report_unstable(
+                        self.session,
+                        feature,
+                        reason,
+                        issue,
+                        is_soft,
+                        span,
+                        soft_handler,
+                    );
+                }
+            }
+        }
+        if let Some(depr) = &ext.deprecation {
+            let path = pprust::path_to_string(&path);
+            let (message, lint) = stability::deprecation_message(depr, "macro", &path);
+            stability::early_report_deprecation(
+                &mut self.lint_buffer,
+                &message,
+                depr.suggestion,
+                lint,
+                span,
+            );
+        }
+    }
+
+    fn prohibit_imported_non_macro_attrs(
+        &self,
+        binding: Option<&'a NameBinding<'a>>,
+        res: Option<Res>,
+        span: Span,
+    ) {
+        if let Some(Res::NonMacroAttr(kind)) = res {
+            if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
+                let msg =
+                    format!("cannot use {} {} through an import", kind.article(), kind.descr());
+                let mut err = self.session.struct_span_err(span, &msg);
+                if let Some(binding) = binding {
+                    err.span_note(binding.span, &format!("the {} imported here", kind.descr()));
+                }
+                err.emit();
+            }
+        }
+    }
+
+    crate fn check_reserved_macro_name(&mut self, ident: Ident, res: Res) {
+        // Reserve some names that are not quite covered by the general check
+        // performed on `Resolver::builtin_attrs`.
+        if ident.name == sym::cfg || ident.name == sym::cfg_attr || ident.name == sym::derive {
+            let macro_kind = self.get_macro(res).map(|ext| ext.macro_kind());
+            if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) {
+                self.session.span_err(
+                    ident.span,
+                    &format!("name `{}` is reserved in attribute namespace", ident),
+                );
+            }
+        }
+    }
+
+    /// Compile the macro into a `SyntaxExtension` and possibly replace
+    /// its expander to a pre-defined one for built-in macros.
+    crate fn compile_macro(&mut self, item: &ast::Item, edition: Edition) -> SyntaxExtension {
+        let mut result = compile_declarative_macro(
+            &self.session,
+            self.session.features_untracked(),
+            item,
+            edition,
+        );
+
+        if result.is_builtin {
+            // The macro was marked with `#[rustc_builtin_macro]`.
+            if let Some(builtin_macro) = self.builtin_macros.get_mut(&item.ident.name) {
+                // The macro is a built-in, replace its expander function
+                // while still taking everything else from the source code.
+                // If we already loaded this builtin macro, give a better error message than 'no such builtin macro'.
+                match mem::replace(builtin_macro, BuiltinMacroState::AlreadySeen(item.span)) {
+                    BuiltinMacroState::NotYetSeen(ext) => result.kind = ext.kind,
+                    BuiltinMacroState::AlreadySeen(span) => {
+                        struct_span_err!(
+                            self.session,
+                            item.span,
+                            E0773,
+                            "attempted to define built-in macro more than once"
+                        )
+                        .span_note(span, "previously defined here")
+                        .emit();
+                    }
+                }
+            } else {
+                let msg = format!("cannot find a built-in macro with name `{}`", item.ident);
+                self.session.span_err(item.span, &msg);
+            }
+        }
+
+        result
+    }
+}