]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/build_reduced_graph.rs
e10314a11fc1bbacd6e83a378f10aecc774fb686
[rust.git] / compiler / rustc_resolve / src / build_reduced_graph.rs
1 //! After we obtain a fresh AST fragment from a macro, code in this module helps to integrate
2 //! that fragment into the module structures that are already partially built.
3 //!
4 //! Items from the fragment are placed into modules,
5 //! unexpanded macros in the fragment are visited and registered.
6 //! Imports are also considered items and placed into modules here, but not resolved yet.
7
8 use crate::def_collector::collect_definitions;
9 use crate::imports::{Import, ImportKind};
10 use crate::macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef};
11 use crate::Namespace::{self, MacroNS, TypeNS, ValueNS};
12 use crate::{CrateLint, Determinacy, PathResult, ResolutionError, VisResolutionError};
13 use crate::{
14     ExternPreludeEntry, ModuleOrUniformRoot, ParentScope, PerNS, Resolver, ResolverArenas,
15 };
16 use crate::{Module, ModuleData, ModuleKind, NameBinding, NameBindingKind, Segment, ToNameBinding};
17
18 use rustc_ast::visit::{self, AssocCtxt, Visitor};
19 use rustc_ast::{self as ast, AssocItem, AssocItemKind, MetaItemKind, StmtKind};
20 use rustc_ast::{Block, FnKind, ForeignItem, ForeignItemKind, ImplKind, Item, ItemKind, NodeId};
21 use rustc_ast_lowering::ResolverAstLowering;
22 use rustc_attr as attr;
23 use rustc_data_structures::sync::Lrc;
24 use rustc_errors::{struct_span_err, Applicability};
25 use rustc_expand::base::SyntaxExtension;
26 use rustc_expand::expand::AstFragment;
27 use rustc_hir::def::{self, *};
28 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_INDEX};
29 use rustc_metadata::creader::LoadedMacro;
30 use rustc_middle::bug;
31 use rustc_middle::hir::exports::Export;
32 use rustc_middle::middle::cstore::CrateStore;
33 use rustc_middle::ty;
34 use rustc_span::hygiene::{ExpnId, MacroKind};
35 use rustc_span::source_map::{respan, Spanned};
36 use rustc_span::symbol::{kw, sym, Ident, Symbol};
37 use rustc_span::Span;
38
39 use std::cell::Cell;
40 use std::ptr;
41 use tracing::debug;
42
43 type Res = def::Res<NodeId>;
44
45 impl<'a> ToNameBinding<'a> for (Module<'a>, ty::Visibility, Span, ExpnId) {
46     fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
47         arenas.alloc_name_binding(NameBinding {
48             kind: NameBindingKind::Module(self.0),
49             ambiguity: None,
50             vis: self.1,
51             span: self.2,
52             expansion: self.3,
53         })
54     }
55 }
56
57 impl<'a> ToNameBinding<'a> for (Res, ty::Visibility, Span, ExpnId) {
58     fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
59         arenas.alloc_name_binding(NameBinding {
60             kind: NameBindingKind::Res(self.0, false),
61             ambiguity: None,
62             vis: self.1,
63             span: self.2,
64             expansion: self.3,
65         })
66     }
67 }
68
69 struct IsMacroExport;
70
71 impl<'a> ToNameBinding<'a> for (Res, ty::Visibility, Span, ExpnId, IsMacroExport) {
72     fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
73         arenas.alloc_name_binding(NameBinding {
74             kind: NameBindingKind::Res(self.0, true),
75             ambiguity: None,
76             vis: self.1,
77             span: self.2,
78             expansion: self.3,
79         })
80     }
81 }
82
83 impl<'a> Resolver<'a> {
84     /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
85     /// otherwise, reports an error.
86     crate fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T)
87     where
88         T: ToNameBinding<'a>,
89     {
90         let binding = def.to_name_binding(self.arenas);
91         let key = self.new_key(ident, ns);
92         if let Err(old_binding) = self.try_define(parent, key, binding) {
93             self.report_conflict(parent, ident, ns, old_binding, &binding);
94         }
95     }
96
97     /// Walks up the tree of definitions starting at `def_id`,
98     /// stopping at the first `DefKind::Mod` encountered
99     fn nearest_parent_mod(&mut self, def_id: DefId) -> Module<'a> {
100         let def_key = self.cstore().def_key(def_id);
101
102         let mut parent_id = DefId {
103             krate: def_id.krate,
104             index: def_key.parent.expect("failed to get parent for module"),
105         };
106         // The immediate parent may not be a module
107         // (e.g. `const _: () =  { #[path = "foo.rs"] mod foo; };`)
108         // Walk up the tree until we hit a module or the crate root.
109         while parent_id.index != CRATE_DEF_INDEX
110             && self.cstore().def_kind(parent_id) != DefKind::Mod
111         {
112             let parent_def_key = self.cstore().def_key(parent_id);
113             parent_id.index = parent_def_key.parent.expect("failed to get parent for module");
114         }
115         self.get_module(parent_id)
116     }
117
118     pub fn get_module(&mut self, def_id: DefId) -> Module<'a> {
119         // If this is a local module, it will be in `module_map`, no need to recalculate it.
120         if let Some(def_id) = def_id.as_local() {
121             return self.module_map[&def_id];
122         }
123
124         // Cache module resolution
125         if let Some(&module) = self.extern_module_map.get(&def_id) {
126             return module;
127         }
128
129         let (name, parent) = if def_id.index == CRATE_DEF_INDEX {
130             // This is the crate root
131             (self.cstore().crate_name_untracked(def_id.krate), None)
132         } else {
133             let def_key = self.cstore().def_key(def_id);
134             let name = def_key
135                 .disambiguated_data
136                 .data
137                 .get_opt_name()
138                 .expect("given a DefId that wasn't a module");
139
140             let parent = Some(self.nearest_parent_mod(def_id));
141             (name, parent)
142         };
143
144         // Allocate and return a new module with the information we found
145         let kind = ModuleKind::Def(DefKind::Mod, def_id, name);
146         let module = self.arenas.alloc_module(ModuleData::new(
147             parent,
148             kind,
149             def_id,
150             self.cstore().module_expansion_untracked(def_id, &self.session),
151             self.cstore().get_span_untracked(def_id, &self.session),
152         ));
153         self.extern_module_map.insert(def_id, module);
154         module
155     }
156
157     crate fn macro_def_scope(&mut self, expn_id: ExpnId) -> Module<'a> {
158         let def_id = match expn_id.expn_data().macro_def_id {
159             Some(def_id) => def_id,
160             None => return self.ast_transform_scopes.get(&expn_id).unwrap_or(&self.graph_root),
161         };
162         if let Some(id) = def_id.as_local() {
163             self.local_macro_def_scopes[&id]
164         } else {
165             // This is not entirely correct - a `macro_rules!` macro may occur
166             // inside a 'block' module:
167             //
168             // ```rust
169             // const _: () = {
170             // #[macro_export]
171             // macro_rules! my_macro {
172             //     () => {};
173             // }
174             // `
175             // We don't record this information for external crates, so
176             // the module we compute here will be the closest 'mod' item
177             // (not necesssarily the actual parent of the `macro_rules!`
178             // macro). `macro_rules!` macros can't use def-site hygiene,
179             // so this hopefully won't be a problem.
180             //
181             // See https://github.com/rust-lang/rust/pull/77984#issuecomment-712445508
182             self.nearest_parent_mod(def_id)
183         }
184     }
185
186     crate fn get_macro(&mut self, res: Res) -> Option<Lrc<SyntaxExtension>> {
187         match res {
188             Res::Def(DefKind::Macro(..), def_id) => Some(self.get_macro_by_def_id(def_id)),
189             Res::NonMacroAttr(attr_kind) => Some(self.non_macro_attr(attr_kind.is_used())),
190             _ => None,
191         }
192     }
193
194     crate fn get_macro_by_def_id(&mut self, def_id: DefId) -> Lrc<SyntaxExtension> {
195         if let Some(ext) = self.macro_map.get(&def_id) {
196             return ext.clone();
197         }
198
199         let ext = Lrc::new(match self.cstore().load_macro_untracked(def_id, &self.session) {
200             LoadedMacro::MacroDef(item, edition) => self.compile_macro(&item, edition),
201             LoadedMacro::ProcMacro(ext) => ext,
202         });
203
204         self.macro_map.insert(def_id, ext.clone());
205         ext
206     }
207
208     crate fn build_reduced_graph(
209         &mut self,
210         fragment: &AstFragment,
211         parent_scope: ParentScope<'a>,
212     ) -> MacroRulesScopeRef<'a> {
213         collect_definitions(self, fragment, parent_scope.expansion);
214         let mut visitor = BuildReducedGraphVisitor { r: self, parent_scope };
215         fragment.visit_with(&mut visitor);
216         visitor.parent_scope.macro_rules
217     }
218
219     crate fn build_reduced_graph_external(&mut self, module: Module<'a>) {
220         let def_id = module.def_id().expect("unpopulated module without a def-id");
221         for child in self.cstore().item_children_untracked(def_id, self.session) {
222             let child = child.map_id(|_| panic!("unexpected id"));
223             let parent_scope = ParentScope::module(module, self);
224             BuildReducedGraphVisitor { r: self, parent_scope }
225                 .build_reduced_graph_for_external_crate_res(child);
226         }
227     }
228 }
229
230 struct BuildReducedGraphVisitor<'a, 'b> {
231     r: &'b mut Resolver<'a>,
232     parent_scope: ParentScope<'a>,
233 }
234
235 impl<'a> AsMut<Resolver<'a>> for BuildReducedGraphVisitor<'a, '_> {
236     fn as_mut(&mut self) -> &mut Resolver<'a> {
237         self.r
238     }
239 }
240
241 impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
242     fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
243         self.resolve_visibility_speculative(vis, false).unwrap_or_else(|err| {
244             self.r.report_vis_error(err);
245             ty::Visibility::Public
246         })
247     }
248
249     fn resolve_visibility_speculative<'ast>(
250         &mut self,
251         vis: &'ast ast::Visibility,
252         speculative: bool,
253     ) -> Result<ty::Visibility, VisResolutionError<'ast>> {
254         let parent_scope = &self.parent_scope;
255         match vis.kind {
256             ast::VisibilityKind::Public => Ok(ty::Visibility::Public),
257             ast::VisibilityKind::Crate(..) => {
258                 Ok(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)))
259             }
260             ast::VisibilityKind::Inherited => {
261                 Ok(match self.parent_scope.module.kind {
262                     // Any inherited visibility resolved directly inside an enum or trait
263                     // (i.e. variants, fields, and trait items) inherits from the visibility
264                     // of the enum or trait.
265                     ModuleKind::Def(DefKind::Enum | DefKind::Trait, def_id, _) => {
266                         self.r.visibilities[&def_id.expect_local()]
267                     }
268                     // Otherwise, the visibility is restricted to the nearest parent `mod` item.
269                     _ => ty::Visibility::Restricted(self.parent_scope.module.nearest_parent_mod),
270                 })
271             }
272             ast::VisibilityKind::Restricted { ref path, id, .. } => {
273                 // For visibilities we are not ready to provide correct implementation of "uniform
274                 // paths" right now, so on 2018 edition we only allow module-relative paths for now.
275                 // On 2015 edition visibilities are resolved as crate-relative by default,
276                 // so we are prepending a root segment if necessary.
277                 let ident = path.segments.get(0).expect("empty path in visibility").ident;
278                 let crate_root = if ident.is_path_segment_keyword() {
279                     None
280                 } else if ident.span.rust_2015() {
281                     Some(Segment::from_ident(Ident::new(
282                         kw::PathRoot,
283                         path.span.shrink_to_lo().with_ctxt(ident.span.ctxt()),
284                     )))
285                 } else {
286                     return Err(VisResolutionError::Relative2018(ident.span, path));
287                 };
288
289                 let segments = crate_root
290                     .into_iter()
291                     .chain(path.segments.iter().map(|seg| seg.into()))
292                     .collect::<Vec<_>>();
293                 let expected_found_error = |res| {
294                     Err(VisResolutionError::ExpectedFound(
295                         path.span,
296                         Segment::names_to_string(&segments),
297                         res,
298                     ))
299                 };
300                 match self.r.resolve_path(
301                     &segments,
302                     Some(TypeNS),
303                     parent_scope,
304                     !speculative,
305                     path.span,
306                     CrateLint::SimplePath(id),
307                 ) {
308                     PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
309                         let res = module.res().expect("visibility resolved to unnamed block");
310                         if !speculative {
311                             self.r.record_partial_res(id, PartialRes::new(res));
312                         }
313                         if module.is_normal() {
314                             if res == Res::Err {
315                                 Ok(ty::Visibility::Public)
316                             } else {
317                                 let vis = ty::Visibility::Restricted(res.def_id());
318                                 if self.r.is_accessible_from(vis, parent_scope.module) {
319                                     Ok(vis)
320                                 } else {
321                                     Err(VisResolutionError::AncestorOnly(path.span))
322                                 }
323                             }
324                         } else {
325                             expected_found_error(res)
326                         }
327                     }
328                     PathResult::Module(..) => Err(VisResolutionError::ModuleOnly(path.span)),
329                     PathResult::NonModule(partial_res) => {
330                         expected_found_error(partial_res.base_res())
331                     }
332                     PathResult::Failed { span, label, suggestion, .. } => {
333                         Err(VisResolutionError::FailedToResolve(span, label, suggestion))
334                     }
335                     PathResult::Indeterminate => Err(VisResolutionError::Indeterminate(path.span)),
336                 }
337             }
338         }
339     }
340
341     fn insert_field_names_local(&mut self, def_id: DefId, vdata: &ast::VariantData) {
342         let field_names = vdata
343             .fields()
344             .iter()
345             .map(|field| respan(field.span, field.ident.map_or(kw::Empty, |ident| ident.name)))
346             .collect();
347         self.insert_field_names(def_id, field_names);
348     }
349
350     fn insert_field_names(&mut self, def_id: DefId, field_names: Vec<Spanned<Symbol>>) {
351         self.r.field_names.insert(def_id, field_names);
352     }
353
354     fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
355         // If any statements are items, we need to create an anonymous module
356         block
357             .stmts
358             .iter()
359             .any(|statement| matches!(statement.kind, StmtKind::Item(_) | StmtKind::MacCall(_)))
360     }
361
362     // Add an import to the current module.
363     fn add_import(
364         &mut self,
365         module_path: Vec<Segment>,
366         kind: ImportKind<'a>,
367         span: Span,
368         id: NodeId,
369         item: &ast::Item,
370         root_span: Span,
371         root_id: NodeId,
372         vis: ty::Visibility,
373     ) {
374         let current_module = self.parent_scope.module;
375         let import = self.r.arenas.alloc_import(Import {
376             kind,
377             parent_scope: self.parent_scope,
378             module_path,
379             imported_module: Cell::new(None),
380             span,
381             id,
382             use_span: item.span,
383             use_span_with_attributes: item.span_with_attributes(),
384             has_attributes: !item.attrs.is_empty(),
385             root_span,
386             root_id,
387             vis: Cell::new(vis),
388             used: Cell::new(false),
389         });
390
391         debug!("add_import({:?})", import);
392
393         self.r.indeterminate_imports.push(import);
394         match import.kind {
395             // Don't add unresolved underscore imports to modules
396             ImportKind::Single { target: Ident { name: kw::Underscore, .. }, .. } => {}
397             ImportKind::Single { target, type_ns_only, .. } => {
398                 self.r.per_ns(|this, ns| {
399                     if !type_ns_only || ns == TypeNS {
400                         let key = this.new_key(target, ns);
401                         let mut resolution = this.resolution(current_module, key).borrow_mut();
402                         resolution.add_single_import(import);
403                     }
404                 });
405             }
406             // We don't add prelude imports to the globs since they only affect lexical scopes,
407             // which are not relevant to import resolution.
408             ImportKind::Glob { is_prelude: true, .. } => {}
409             ImportKind::Glob { .. } => current_module.globs.borrow_mut().push(import),
410             _ => unreachable!(),
411         }
412     }
413
414     fn build_reduced_graph_for_use_tree(
415         &mut self,
416         // This particular use tree
417         use_tree: &ast::UseTree,
418         id: NodeId,
419         parent_prefix: &[Segment],
420         nested: bool,
421         // The whole `use` item
422         item: &Item,
423         vis: ty::Visibility,
424         root_span: Span,
425     ) {
426         debug!(
427             "build_reduced_graph_for_use_tree(parent_prefix={:?}, use_tree={:?}, nested={})",
428             parent_prefix, use_tree, nested
429         );
430
431         let mut prefix_iter = parent_prefix
432             .iter()
433             .cloned()
434             .chain(use_tree.prefix.segments.iter().map(|seg| seg.into()))
435             .peekable();
436
437         // On 2015 edition imports are resolved as crate-relative by default,
438         // so prefixes are prepended with crate root segment if necessary.
439         // The root is prepended lazily, when the first non-empty prefix or terminating glob
440         // appears, so imports in braced groups can have roots prepended independently.
441         let is_glob = matches!(use_tree.kind, ast::UseTreeKind::Glob);
442         let crate_root = match prefix_iter.peek() {
443             Some(seg) if !seg.ident.is_path_segment_keyword() && seg.ident.span.rust_2015() => {
444                 Some(seg.ident.span.ctxt())
445             }
446             None if is_glob && use_tree.span.rust_2015() => Some(use_tree.span.ctxt()),
447             _ => None,
448         }
449         .map(|ctxt| {
450             Segment::from_ident(Ident::new(
451                 kw::PathRoot,
452                 use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt),
453             ))
454         });
455
456         let prefix = crate_root.into_iter().chain(prefix_iter).collect::<Vec<_>>();
457         debug!("build_reduced_graph_for_use_tree: prefix={:?}", prefix);
458
459         let empty_for_self = |prefix: &[Segment]| {
460             prefix.is_empty() || prefix.len() == 1 && prefix[0].ident.name == kw::PathRoot
461         };
462         match use_tree.kind {
463             ast::UseTreeKind::Simple(rename, ..) => {
464                 let mut ident = use_tree.ident();
465                 let mut module_path = prefix;
466                 let mut source = module_path.pop().unwrap();
467                 let mut type_ns_only = false;
468
469                 if nested {
470                     // Correctly handle `self`
471                     if source.ident.name == kw::SelfLower {
472                         type_ns_only = true;
473
474                         if empty_for_self(&module_path) {
475                             self.r.report_error(
476                                 use_tree.span,
477                                 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix,
478                             );
479                             return;
480                         }
481
482                         // Replace `use foo::{ self };` with `use foo;`
483                         source = module_path.pop().unwrap();
484                         if rename.is_none() {
485                             ident = source.ident;
486                         }
487                     }
488                 } else {
489                     // Disallow `self`
490                     if source.ident.name == kw::SelfLower {
491                         let parent = module_path.last();
492
493                         let span = match parent {
494                             // only `::self` from `use foo::self as bar`
495                             Some(seg) => seg.ident.span.shrink_to_hi().to(source.ident.span),
496                             None => source.ident.span,
497                         };
498                         let span_with_rename = match rename {
499                             // only `self as bar` from `use foo::self as bar`
500                             Some(rename) => source.ident.span.to(rename.span),
501                             None => source.ident.span,
502                         };
503                         self.r.report_error(
504                             span,
505                             ResolutionError::SelfImportsOnlyAllowedWithin {
506                                 root: parent.is_none(),
507                                 span_with_rename,
508                             },
509                         );
510
511                         // Error recovery: replace `use foo::self;` with `use foo;`
512                         if let Some(parent) = module_path.pop() {
513                             source = parent;
514                             if rename.is_none() {
515                                 ident = source.ident;
516                             }
517                         }
518                     }
519
520                     // Disallow `use $crate;`
521                     if source.ident.name == kw::DollarCrate && module_path.is_empty() {
522                         let crate_root = self.r.resolve_crate_root(source.ident);
523                         let crate_name = match crate_root.kind {
524                             ModuleKind::Def(.., name) => name,
525                             ModuleKind::Block(..) => unreachable!(),
526                         };
527                         // HACK(eddyb) unclear how good this is, but keeping `$crate`
528                         // in `source` breaks `src/test/ui/imports/import-crate-var.rs`,
529                         // while the current crate doesn't have a valid `crate_name`.
530                         if crate_name != kw::Empty {
531                             // `crate_name` should not be interpreted as relative.
532                             module_path.push(Segment {
533                                 ident: Ident { name: kw::PathRoot, span: source.ident.span },
534                                 id: Some(self.r.next_node_id()),
535                                 has_generic_args: false,
536                             });
537                             source.ident.name = crate_name;
538                         }
539                         if rename.is_none() {
540                             ident.name = crate_name;
541                         }
542
543                         self.r
544                             .session
545                             .struct_span_err(item.span, "`$crate` may not be imported")
546                             .emit();
547                     }
548                 }
549
550                 if ident.name == kw::Crate {
551                     self.r.session.span_err(
552                         ident.span,
553                         "crate root imports need to be explicitly named: \
554                          `use crate as name;`",
555                     );
556                 }
557
558                 let kind = ImportKind::Single {
559                     source: source.ident,
560                     target: ident,
561                     source_bindings: PerNS {
562                         type_ns: Cell::new(Err(Determinacy::Undetermined)),
563                         value_ns: Cell::new(Err(Determinacy::Undetermined)),
564                         macro_ns: Cell::new(Err(Determinacy::Undetermined)),
565                     },
566                     target_bindings: PerNS {
567                         type_ns: Cell::new(None),
568                         value_ns: Cell::new(None),
569                         macro_ns: Cell::new(None),
570                     },
571                     type_ns_only,
572                     nested,
573                 };
574                 self.add_import(
575                     module_path,
576                     kind,
577                     use_tree.span,
578                     id,
579                     item,
580                     root_span,
581                     item.id,
582                     vis,
583                 );
584             }
585             ast::UseTreeKind::Glob => {
586                 let kind = ImportKind::Glob {
587                     is_prelude: self.r.session.contains_name(&item.attrs, sym::prelude_import),
588                     max_vis: Cell::new(ty::Visibility::Invisible),
589                 };
590                 self.add_import(prefix, kind, use_tree.span, id, item, root_span, item.id, vis);
591             }
592             ast::UseTreeKind::Nested(ref items) => {
593                 // Ensure there is at most one `self` in the list
594                 let self_spans = items
595                     .iter()
596                     .filter_map(|&(ref use_tree, _)| {
597                         if let ast::UseTreeKind::Simple(..) = use_tree.kind {
598                             if use_tree.ident().name == kw::SelfLower {
599                                 return Some(use_tree.span);
600                             }
601                         }
602
603                         None
604                     })
605                     .collect::<Vec<_>>();
606                 if self_spans.len() > 1 {
607                     let mut e = self.r.into_struct_error(
608                         self_spans[0],
609                         ResolutionError::SelfImportCanOnlyAppearOnceInTheList,
610                     );
611
612                     for other_span in self_spans.iter().skip(1) {
613                         e.span_label(*other_span, "another `self` import appears here");
614                     }
615
616                     e.emit();
617                 }
618
619                 for &(ref tree, id) in items {
620                     self.build_reduced_graph_for_use_tree(
621                         // This particular use tree
622                         tree, id, &prefix, true, // The whole `use` item
623                         item, vis, root_span,
624                     );
625                 }
626
627                 // Empty groups `a::b::{}` are turned into synthetic `self` imports
628                 // `a::b::c::{self as _}`, so that their prefixes are correctly
629                 // resolved and checked for privacy/stability/etc.
630                 if items.is_empty() && !empty_for_self(&prefix) {
631                     let new_span = prefix[prefix.len() - 1].ident.span;
632                     let tree = ast::UseTree {
633                         prefix: ast::Path::from_ident(Ident::new(kw::SelfLower, new_span)),
634                         kind: ast::UseTreeKind::Simple(
635                             Some(Ident::new(kw::Underscore, new_span)),
636                             ast::DUMMY_NODE_ID,
637                             ast::DUMMY_NODE_ID,
638                         ),
639                         span: use_tree.span,
640                     };
641                     self.build_reduced_graph_for_use_tree(
642                         // This particular use tree
643                         &tree,
644                         id,
645                         &prefix,
646                         true,
647                         // The whole `use` item
648                         item,
649                         ty::Visibility::Invisible,
650                         root_span,
651                     );
652                 }
653             }
654         }
655     }
656
657     /// Constructs the reduced graph for one item.
658     fn build_reduced_graph_for_item(&mut self, item: &'b Item) {
659         if matches!(item.kind, ItemKind::Mod(..)) && item.ident.name == kw::Empty {
660             // Fake crate root item from expand.
661             return;
662         }
663
664         let parent_scope = &self.parent_scope;
665         let parent = parent_scope.module;
666         let expansion = parent_scope.expansion;
667         let ident = item.ident;
668         let sp = item.span;
669         let vis = self.resolve_visibility(&item.vis);
670         let local_def_id = self.r.local_def_id(item.id);
671         let def_id = local_def_id.to_def_id();
672
673         self.r.visibilities.insert(local_def_id, vis);
674
675         match item.kind {
676             ItemKind::Use(ref use_tree) => {
677                 self.build_reduced_graph_for_use_tree(
678                     // This particular use tree
679                     use_tree,
680                     item.id,
681                     &[],
682                     false,
683                     // The whole `use` item
684                     item,
685                     vis,
686                     use_tree.span,
687                 );
688             }
689
690             ItemKind::ExternCrate(orig_name) => {
691                 let module = if orig_name.is_none() && ident.name == kw::SelfLower {
692                     self.r
693                         .session
694                         .struct_span_err(item.span, "`extern crate self;` requires renaming")
695                         .span_suggestion(
696                             item.span,
697                             "try",
698                             "extern crate self as name;".into(),
699                             Applicability::HasPlaceholders,
700                         )
701                         .emit();
702                     return;
703                 } else if orig_name == Some(kw::SelfLower) {
704                     self.r.graph_root
705                 } else {
706                     let crate_id = self.r.crate_loader.process_extern_crate(
707                         item,
708                         &self.r.definitions,
709                         local_def_id,
710                     );
711                     self.r.extern_crate_map.insert(local_def_id, crate_id);
712                     self.r.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX })
713                 };
714
715                 let used = self.process_macro_use_imports(item, module);
716                 let binding =
717                     (module, ty::Visibility::Public, sp, expansion).to_name_binding(self.r.arenas);
718                 let import = self.r.arenas.alloc_import(Import {
719                     kind: ImportKind::ExternCrate { source: orig_name, target: ident },
720                     root_id: item.id,
721                     id: item.id,
722                     parent_scope: self.parent_scope,
723                     imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
724                     has_attributes: !item.attrs.is_empty(),
725                     use_span_with_attributes: item.span_with_attributes(),
726                     use_span: item.span,
727                     root_span: item.span,
728                     span: item.span,
729                     module_path: Vec::new(),
730                     vis: Cell::new(vis),
731                     used: Cell::new(used),
732                 });
733                 self.r.potentially_unused_imports.push(import);
734                 let imported_binding = self.r.import(binding, import);
735                 if ptr::eq(parent, self.r.graph_root) {
736                     if let Some(entry) = self.r.extern_prelude.get(&ident.normalize_to_macros_2_0())
737                     {
738                         if expansion != ExpnId::root()
739                             && orig_name.is_some()
740                             && entry.extern_crate_item.is_none()
741                         {
742                             let msg = "macro-expanded `extern crate` items cannot \
743                                        shadow names passed with `--extern`";
744                             self.r.session.span_err(item.span, msg);
745                         }
746                     }
747                     let entry =
748                         self.r.extern_prelude.entry(ident.normalize_to_macros_2_0()).or_insert(
749                             ExternPreludeEntry {
750                                 extern_crate_item: None,
751                                 introduced_by_item: true,
752                             },
753                         );
754                     entry.extern_crate_item = Some(imported_binding);
755                     if orig_name.is_some() {
756                         entry.introduced_by_item = true;
757                     }
758                 }
759                 self.r.define(parent, ident, TypeNS, imported_binding);
760             }
761
762             ItemKind::Mod(..) => {
763                 let module_kind = ModuleKind::Def(DefKind::Mod, def_id, ident.name);
764                 let module = self.r.arenas.alloc_module(ModuleData {
765                     no_implicit_prelude: parent.no_implicit_prelude || {
766                         self.r.session.contains_name(&item.attrs, sym::no_implicit_prelude)
767                     },
768                     ..ModuleData::new(Some(parent), module_kind, def_id, expansion, item.span)
769                 });
770                 self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion));
771                 self.r.module_map.insert(local_def_id, module);
772
773                 // Descend into the module.
774                 self.parent_scope.module = module;
775             }
776
777             // These items live in the value namespace.
778             ItemKind::Static(..) => {
779                 let res = Res::Def(DefKind::Static, def_id);
780                 self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion));
781             }
782             ItemKind::Const(..) => {
783                 let res = Res::Def(DefKind::Const, def_id);
784                 self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion));
785             }
786             ItemKind::Fn(..) => {
787                 let res = Res::Def(DefKind::Fn, def_id);
788                 self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion));
789
790                 // Functions introducing procedural macros reserve a slot
791                 // in the macro namespace as well (see #52225).
792                 self.define_macro(item);
793             }
794
795             // These items live in the type namespace.
796             ItemKind::TyAlias(..) => {
797                 let res = Res::Def(DefKind::TyAlias, def_id);
798                 self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion));
799             }
800
801             ItemKind::Enum(_, _) => {
802                 let module_kind = ModuleKind::Def(DefKind::Enum, def_id, ident.name);
803                 let module = self.r.new_module(
804                     parent,
805                     module_kind,
806                     parent.nearest_parent_mod,
807                     expansion,
808                     item.span,
809                 );
810                 self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion));
811                 self.parent_scope.module = module;
812             }
813
814             ItemKind::TraitAlias(..) => {
815                 let res = Res::Def(DefKind::TraitAlias, def_id);
816                 self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion));
817             }
818
819             // These items live in both the type and value namespaces.
820             ItemKind::Struct(ref vdata, _) => {
821                 // Define a name in the type namespace.
822                 let res = Res::Def(DefKind::Struct, def_id);
823                 self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion));
824
825                 // Record field names for error reporting.
826                 self.insert_field_names_local(def_id, vdata);
827
828                 // If this is a tuple or unit struct, define a name
829                 // in the value namespace as well.
830                 if let Some(ctor_node_id) = vdata.ctor_id() {
831                     // If the structure is marked as non_exhaustive then lower the visibility
832                     // to within the crate.
833                     let mut ctor_vis = if vis == ty::Visibility::Public
834                         && self.r.session.contains_name(&item.attrs, sym::non_exhaustive)
835                     {
836                         ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
837                     } else {
838                         vis
839                     };
840
841                     let mut ret_fields = Vec::with_capacity(vdata.fields().len());
842
843                     for field in vdata.fields() {
844                         // NOTE: The field may be an expansion placeholder, but expansion sets
845                         // correct visibilities for unnamed field placeholders specifically, so the
846                         // constructor visibility should still be determined correctly.
847                         let field_vis = self
848                             .resolve_visibility_speculative(&field.vis, true)
849                             .unwrap_or(ty::Visibility::Public);
850                         if ctor_vis.is_at_least(field_vis, &*self.r) {
851                             ctor_vis = field_vis;
852                         }
853                         ret_fields.push(field_vis);
854                     }
855                     let ctor_def_id = self.r.local_def_id(ctor_node_id);
856                     let ctor_res = Res::Def(
857                         DefKind::Ctor(CtorOf::Struct, CtorKind::from_ast(vdata)),
858                         ctor_def_id.to_def_id(),
859                     );
860                     self.r.define(parent, ident, ValueNS, (ctor_res, ctor_vis, sp, expansion));
861                     self.r.visibilities.insert(ctor_def_id, ctor_vis);
862
863                     self.r.struct_constructors.insert(def_id, (ctor_res, ctor_vis, ret_fields));
864                 }
865             }
866
867             ItemKind::Union(ref vdata, _) => {
868                 let res = Res::Def(DefKind::Union, def_id);
869                 self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion));
870
871                 // Record field names for error reporting.
872                 self.insert_field_names_local(def_id, vdata);
873             }
874
875             ItemKind::Trait(..) => {
876                 // Add all the items within to a new module.
877                 let module_kind = ModuleKind::Def(DefKind::Trait, def_id, ident.name);
878                 let module = self.r.new_module(
879                     parent,
880                     module_kind,
881                     parent.nearest_parent_mod,
882                     expansion,
883                     item.span,
884                 );
885                 self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion));
886                 self.parent_scope.module = module;
887             }
888
889             // These items do not add names to modules.
890             ItemKind::Impl(box ImplKind { of_trait: Some(..), .. }) => {
891                 self.r.trait_impl_items.insert(local_def_id);
892             }
893             ItemKind::Impl { .. } | ItemKind::ForeignMod(..) | ItemKind::GlobalAsm(..) => {}
894
895             ItemKind::MacroDef(..) | ItemKind::MacCall(_) => unreachable!(),
896         }
897     }
898
899     /// Constructs the reduced graph for one foreign item.
900     fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem) {
901         let local_def_id = self.r.local_def_id(item.id);
902         let def_id = local_def_id.to_def_id();
903         let (def_kind, ns) = match item.kind {
904             ForeignItemKind::Fn(..) => (DefKind::Fn, ValueNS),
905             ForeignItemKind::Static(..) => (DefKind::Static, ValueNS),
906             ForeignItemKind::TyAlias(..) => (DefKind::ForeignTy, TypeNS),
907             ForeignItemKind::MacCall(_) => unreachable!(),
908         };
909         let parent = self.parent_scope.module;
910         let expansion = self.parent_scope.expansion;
911         let vis = self.resolve_visibility(&item.vis);
912         let res = Res::Def(def_kind, def_id);
913         self.r.define(parent, item.ident, ns, (res, vis, item.span, expansion));
914         self.r.visibilities.insert(local_def_id, vis);
915     }
916
917     fn build_reduced_graph_for_block(&mut self, block: &Block) {
918         let parent = self.parent_scope.module;
919         let expansion = self.parent_scope.expansion;
920         if self.block_needs_anonymous_module(block) {
921             let module = self.r.new_module(
922                 parent,
923                 ModuleKind::Block(block.id),
924                 parent.nearest_parent_mod,
925                 expansion,
926                 block.span,
927             );
928             self.r.block_map.insert(block.id, module);
929             self.parent_scope.module = module; // Descend into the block.
930         }
931     }
932
933     /// Builds the reduced graph for a single item in an external crate.
934     fn build_reduced_graph_for_external_crate_res(&mut self, child: Export<NodeId>) {
935         let parent = self.parent_scope.module;
936         let Export { ident, res, vis, span } = child;
937         let expansion = self.parent_scope.expansion;
938         // Record primary definitions.
939         match res {
940             Res::Def(kind @ (DefKind::Mod | DefKind::Enum | DefKind::Trait), def_id) => {
941                 let module = self.r.new_module(
942                     parent,
943                     ModuleKind::Def(kind, def_id, ident.name),
944                     def_id,
945                     expansion,
946                     span,
947                 );
948                 self.r.define(parent, ident, TypeNS, (module, vis, span, expansion));
949             }
950             Res::Def(
951                 DefKind::Struct
952                 | DefKind::Union
953                 | DefKind::Variant
954                 | DefKind::TyAlias
955                 | DefKind::ForeignTy
956                 | DefKind::OpaqueTy
957                 | DefKind::TraitAlias
958                 | DefKind::AssocTy,
959                 _,
960             )
961             | Res::PrimTy(..)
962             | Res::ToolMod => self.r.define(parent, ident, TypeNS, (res, vis, span, expansion)),
963             Res::Def(
964                 DefKind::Fn
965                 | DefKind::AssocFn
966                 | DefKind::Static
967                 | DefKind::Const
968                 | DefKind::AssocConst
969                 | DefKind::Ctor(..),
970                 _,
971             ) => self.r.define(parent, ident, ValueNS, (res, vis, span, expansion)),
972             Res::Def(DefKind::Macro(..), _) | Res::NonMacroAttr(..) => {
973                 self.r.define(parent, ident, MacroNS, (res, vis, span, expansion))
974             }
975             Res::Def(
976                 DefKind::TyParam
977                 | DefKind::ConstParam
978                 | DefKind::ExternCrate
979                 | DefKind::Use
980                 | DefKind::ForeignMod
981                 | DefKind::AnonConst
982                 | DefKind::Field
983                 | DefKind::LifetimeParam
984                 | DefKind::GlobalAsm
985                 | DefKind::Closure
986                 | DefKind::Impl
987                 | DefKind::Generator,
988                 _,
989             )
990             | Res::Local(..)
991             | Res::SelfTy(..)
992             | Res::SelfCtor(..)
993             | Res::Err => bug!("unexpected resolution: {:?}", res),
994         }
995         // Record some extra data for better diagnostics.
996         let cstore = self.r.cstore();
997         match res {
998             Res::Def(DefKind::Struct, def_id) => {
999                 let field_names = cstore.struct_field_names_untracked(def_id, self.r.session);
1000                 let ctor = cstore.ctor_def_id_and_kind_untracked(def_id);
1001                 if let Some((ctor_def_id, ctor_kind)) = ctor {
1002                     let ctor_res = Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id);
1003                     let ctor_vis = cstore.visibility_untracked(ctor_def_id);
1004                     let field_visibilities = cstore.struct_field_visibilities_untracked(def_id);
1005                     self.r
1006                         .struct_constructors
1007                         .insert(def_id, (ctor_res, ctor_vis, field_visibilities));
1008                 }
1009                 self.insert_field_names(def_id, field_names);
1010             }
1011             Res::Def(DefKind::Union, def_id) => {
1012                 let field_names = cstore.struct_field_names_untracked(def_id, self.r.session);
1013                 self.insert_field_names(def_id, field_names);
1014             }
1015             Res::Def(DefKind::AssocFn, def_id) => {
1016                 if cstore
1017                     .associated_item_cloned_untracked(def_id, self.r.session)
1018                     .fn_has_self_parameter
1019                 {
1020                     self.r.has_self.insert(def_id);
1021                 }
1022             }
1023             _ => {}
1024         }
1025     }
1026
1027     fn add_macro_use_binding(
1028         &mut self,
1029         name: Symbol,
1030         binding: &'a NameBinding<'a>,
1031         span: Span,
1032         allow_shadowing: bool,
1033     ) {
1034         if self.r.macro_use_prelude.insert(name, binding).is_some() && !allow_shadowing {
1035             let msg = format!("`{}` is already in scope", name);
1036             let note =
1037                 "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)";
1038             self.r.session.struct_span_err(span, &msg).note(note).emit();
1039         }
1040     }
1041
1042     /// Returns `true` if we should consider the underlying `extern crate` to be used.
1043     fn process_macro_use_imports(&mut self, item: &Item, module: Module<'a>) -> bool {
1044         let mut import_all = None;
1045         let mut single_imports = Vec::new();
1046         for attr in &item.attrs {
1047             if self.r.session.check_name(attr, sym::macro_use) {
1048                 if self.parent_scope.module.parent.is_some() {
1049                     struct_span_err!(
1050                         self.r.session,
1051                         item.span,
1052                         E0468,
1053                         "an `extern crate` loading macros must be at the crate root"
1054                     )
1055                     .emit();
1056                 }
1057                 if let ItemKind::ExternCrate(Some(orig_name)) = item.kind {
1058                     if orig_name == kw::SelfLower {
1059                         self.r
1060                             .session
1061                             .struct_span_err(
1062                                 attr.span,
1063                                 "`#[macro_use]` is not supported on `extern crate self`",
1064                             )
1065                             .emit();
1066                     }
1067                 }
1068                 let ill_formed =
1069                     |span| struct_span_err!(self.r.session, span, E0466, "bad macro import").emit();
1070                 match attr.meta() {
1071                     Some(meta) => match meta.kind {
1072                         MetaItemKind::Word => {
1073                             import_all = Some(meta.span);
1074                             break;
1075                         }
1076                         MetaItemKind::List(nested_metas) => {
1077                             for nested_meta in nested_metas {
1078                                 match nested_meta.ident() {
1079                                     Some(ident) if nested_meta.is_word() => {
1080                                         single_imports.push(ident)
1081                                     }
1082                                     _ => ill_formed(nested_meta.span()),
1083                                 }
1084                             }
1085                         }
1086                         MetaItemKind::NameValue(..) => ill_formed(meta.span),
1087                     },
1088                     None => ill_formed(attr.span),
1089                 }
1090             }
1091         }
1092
1093         let macro_use_import = |this: &Self, span| {
1094             this.r.arenas.alloc_import(Import {
1095                 kind: ImportKind::MacroUse,
1096                 root_id: item.id,
1097                 id: item.id,
1098                 parent_scope: this.parent_scope,
1099                 imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
1100                 use_span_with_attributes: item.span_with_attributes(),
1101                 has_attributes: !item.attrs.is_empty(),
1102                 use_span: item.span,
1103                 root_span: span,
1104                 span,
1105                 module_path: Vec::new(),
1106                 vis: Cell::new(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))),
1107                 used: Cell::new(false),
1108             })
1109         };
1110
1111         let allow_shadowing = self.parent_scope.expansion == ExpnId::root();
1112         if let Some(span) = import_all {
1113             let import = macro_use_import(self, span);
1114             self.r.potentially_unused_imports.push(import);
1115             module.for_each_child(self, |this, ident, ns, binding| {
1116                 if ns == MacroNS {
1117                     let imported_binding = this.r.import(binding, import);
1118                     this.add_macro_use_binding(ident.name, imported_binding, span, allow_shadowing);
1119                 }
1120             });
1121         } else {
1122             for ident in single_imports.iter().cloned() {
1123                 let result = self.r.resolve_ident_in_module(
1124                     ModuleOrUniformRoot::Module(module),
1125                     ident,
1126                     MacroNS,
1127                     &self.parent_scope,
1128                     false,
1129                     ident.span,
1130                 );
1131                 if let Ok(binding) = result {
1132                     let import = macro_use_import(self, ident.span);
1133                     self.r.potentially_unused_imports.push(import);
1134                     let imported_binding = self.r.import(binding, import);
1135                     self.add_macro_use_binding(
1136                         ident.name,
1137                         imported_binding,
1138                         ident.span,
1139                         allow_shadowing,
1140                     );
1141                 } else {
1142                     struct_span_err!(self.r.session, ident.span, E0469, "imported macro not found")
1143                         .emit();
1144                 }
1145             }
1146         }
1147         import_all.is_some() || !single_imports.is_empty()
1148     }
1149
1150     /// Returns `true` if this attribute list contains `macro_use`.
1151     fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool {
1152         for attr in attrs {
1153             if self.r.session.check_name(attr, sym::macro_escape) {
1154                 let msg = "`#[macro_escape]` is a deprecated synonym for `#[macro_use]`";
1155                 let mut err = self.r.session.struct_span_warn(attr.span, msg);
1156                 if let ast::AttrStyle::Inner = attr.style {
1157                     err.help("try an outer attribute: `#[macro_use]`").emit();
1158                 } else {
1159                     err.emit();
1160                 }
1161             } else if !self.r.session.check_name(attr, sym::macro_use) {
1162                 continue;
1163             }
1164
1165             if !attr.is_word() {
1166                 self.r.session.span_err(attr.span, "arguments to `macro_use` are not allowed here");
1167             }
1168             return true;
1169         }
1170
1171         false
1172     }
1173
1174     fn visit_invoc(&mut self, id: NodeId) -> ExpnId {
1175         let invoc_id = id.placeholder_to_expn_id();
1176         let old_parent_scope = self.r.invocation_parent_scopes.insert(invoc_id, self.parent_scope);
1177         assert!(old_parent_scope.is_none(), "invocation data is reset for an invocation");
1178         invoc_id
1179     }
1180
1181     /// Visit invocation in context in which it can emit a named item (possibly `macro_rules`)
1182     /// directly into its parent scope's module.
1183     fn visit_invoc_in_module(&mut self, id: NodeId) -> MacroRulesScopeRef<'a> {
1184         let invoc_id = self.visit_invoc(id);
1185         self.parent_scope.module.unexpanded_invocations.borrow_mut().insert(invoc_id);
1186         self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Invocation(invoc_id))
1187     }
1188
1189     fn proc_macro_stub(&self, item: &ast::Item) -> Option<(MacroKind, Ident, Span)> {
1190         if self.r.session.contains_name(&item.attrs, sym::proc_macro) {
1191             return Some((MacroKind::Bang, item.ident, item.span));
1192         } else if self.r.session.contains_name(&item.attrs, sym::proc_macro_attribute) {
1193             return Some((MacroKind::Attr, item.ident, item.span));
1194         } else if let Some(attr) = self.r.session.find_by_name(&item.attrs, sym::proc_macro_derive)
1195         {
1196             if let Some(nested_meta) = attr.meta_item_list().and_then(|list| list.get(0).cloned()) {
1197                 if let Some(ident) = nested_meta.ident() {
1198                     return Some((MacroKind::Derive, ident, ident.span));
1199                 }
1200             }
1201         }
1202         None
1203     }
1204
1205     // Mark the given macro as unused unless its name starts with `_`.
1206     // Macro uses will remove items from this set, and the remaining
1207     // items will be reported as `unused_macros`.
1208     fn insert_unused_macro(
1209         &mut self,
1210         ident: Ident,
1211         def_id: LocalDefId,
1212         node_id: NodeId,
1213         span: Span,
1214     ) {
1215         if !ident.as_str().starts_with('_') {
1216             self.r.unused_macros.insert(def_id, (node_id, span));
1217         }
1218     }
1219
1220     fn define_macro(&mut self, item: &ast::Item) -> MacroRulesScopeRef<'a> {
1221         let parent_scope = self.parent_scope;
1222         let expansion = parent_scope.expansion;
1223         let def_id = self.r.local_def_id(item.id);
1224         let (ext, ident, span, macro_rules) = match &item.kind {
1225             ItemKind::MacroDef(def) => {
1226                 let ext = Lrc::new(self.r.compile_macro(item, self.r.session.edition()));
1227                 (ext, item.ident, item.span, def.macro_rules)
1228             }
1229             ItemKind::Fn(..) => match self.proc_macro_stub(item) {
1230                 Some((macro_kind, ident, span)) => {
1231                     self.r.proc_macro_stubs.insert(def_id);
1232                     (self.r.dummy_ext(macro_kind), ident, span, false)
1233                 }
1234                 None => return parent_scope.macro_rules,
1235             },
1236             _ => unreachable!(),
1237         };
1238
1239         let res = Res::Def(DefKind::Macro(ext.macro_kind()), def_id.to_def_id());
1240         self.r.macro_map.insert(def_id.to_def_id(), ext);
1241         self.r.local_macro_def_scopes.insert(def_id, parent_scope.module);
1242
1243         if macro_rules {
1244             let ident = ident.normalize_to_macros_2_0();
1245             self.r.macro_names.insert(ident);
1246             let is_macro_export = self.r.session.contains_name(&item.attrs, sym::macro_export);
1247             let vis = if is_macro_export {
1248                 ty::Visibility::Public
1249             } else {
1250                 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
1251             };
1252             let binding = (res, vis, span, expansion).to_name_binding(self.r.arenas);
1253             self.r.set_binding_parent_module(binding, parent_scope.module);
1254             self.r.all_macros.insert(ident.name, res);
1255             if is_macro_export {
1256                 let module = self.r.graph_root;
1257                 self.r.define(module, ident, MacroNS, (res, vis, span, expansion, IsMacroExport));
1258             } else {
1259                 self.r.check_reserved_macro_name(ident, res);
1260                 self.insert_unused_macro(ident, def_id, item.id, span);
1261             }
1262             self.r.visibilities.insert(def_id, vis);
1263             self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Binding(
1264                 self.r.arenas.alloc_macro_rules_binding(MacroRulesBinding {
1265                     parent_macro_rules_scope: parent_scope.macro_rules,
1266                     binding,
1267                     ident,
1268                 }),
1269             ))
1270         } else {
1271             let module = parent_scope.module;
1272             let vis = match item.kind {
1273                 // Visibilities must not be resolved non-speculatively twice
1274                 // and we already resolved this one as a `fn` item visibility.
1275                 ItemKind::Fn(..) => self
1276                     .resolve_visibility_speculative(&item.vis, true)
1277                     .unwrap_or(ty::Visibility::Public),
1278                 _ => self.resolve_visibility(&item.vis),
1279             };
1280             if vis != ty::Visibility::Public {
1281                 self.insert_unused_macro(ident, def_id, item.id, span);
1282             }
1283             self.r.define(module, ident, MacroNS, (res, vis, span, expansion));
1284             self.r.visibilities.insert(def_id, vis);
1285             self.parent_scope.macro_rules
1286         }
1287     }
1288 }
1289
1290 macro_rules! method {
1291     ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
1292         fn $visit(&mut self, node: &'b $ty) {
1293             if let $invoc(..) = node.kind {
1294                 self.visit_invoc(node.id);
1295             } else {
1296                 visit::$walk(self, node);
1297             }
1298         }
1299     };
1300 }
1301
1302 impl<'a, 'b> Visitor<'b> for BuildReducedGraphVisitor<'a, 'b> {
1303     method!(visit_expr: ast::Expr, ast::ExprKind::MacCall, walk_expr);
1304     method!(visit_pat: ast::Pat, ast::PatKind::MacCall, walk_pat);
1305     method!(visit_ty: ast::Ty, ast::TyKind::MacCall, walk_ty);
1306
1307     fn visit_item(&mut self, item: &'b Item) {
1308         let orig_module_scope = self.parent_scope.module;
1309         self.parent_scope.macro_rules = match item.kind {
1310             ItemKind::MacroDef(..) => {
1311                 let macro_rules_scope = self.define_macro(item);
1312                 visit::walk_item(self, item);
1313                 macro_rules_scope
1314             }
1315             ItemKind::MacCall(..) => {
1316                 let macro_rules_scope = self.visit_invoc_in_module(item.id);
1317                 visit::walk_item(self, item);
1318                 macro_rules_scope
1319             }
1320             _ => {
1321                 let orig_macro_rules_scope = self.parent_scope.macro_rules;
1322                 self.build_reduced_graph_for_item(item);
1323                 visit::walk_item(self, item);
1324                 match item.kind {
1325                     ItemKind::Mod(..) if self.contains_macro_use(&item.attrs) => {
1326                         self.parent_scope.macro_rules
1327                     }
1328                     _ => orig_macro_rules_scope,
1329                 }
1330             }
1331         };
1332         self.parent_scope.module = orig_module_scope;
1333     }
1334
1335     fn visit_stmt(&mut self, stmt: &'b ast::Stmt) {
1336         if let ast::StmtKind::MacCall(..) = stmt.kind {
1337             self.parent_scope.macro_rules = self.visit_invoc_in_module(stmt.id);
1338         } else {
1339             visit::walk_stmt(self, stmt);
1340         }
1341     }
1342
1343     fn visit_foreign_item(&mut self, foreign_item: &'b ForeignItem) {
1344         if let ForeignItemKind::MacCall(_) = foreign_item.kind {
1345             self.visit_invoc_in_module(foreign_item.id);
1346             return;
1347         }
1348
1349         self.build_reduced_graph_for_foreign_item(foreign_item);
1350         visit::walk_foreign_item(self, foreign_item);
1351     }
1352
1353     fn visit_block(&mut self, block: &'b Block) {
1354         let orig_current_module = self.parent_scope.module;
1355         let orig_current_macro_rules_scope = self.parent_scope.macro_rules;
1356         self.build_reduced_graph_for_block(block);
1357         visit::walk_block(self, block);
1358         self.parent_scope.module = orig_current_module;
1359         self.parent_scope.macro_rules = orig_current_macro_rules_scope;
1360     }
1361
1362     fn visit_assoc_item(&mut self, item: &'b AssocItem, ctxt: AssocCtxt) {
1363         if let AssocItemKind::MacCall(_) = item.kind {
1364             match ctxt {
1365                 AssocCtxt::Trait => {
1366                     self.visit_invoc_in_module(item.id);
1367                 }
1368                 AssocCtxt::Impl => {
1369                     self.visit_invoc(item.id);
1370                 }
1371             }
1372             return;
1373         }
1374
1375         let vis = self.resolve_visibility(&item.vis);
1376         let local_def_id = self.r.local_def_id(item.id);
1377         let def_id = local_def_id.to_def_id();
1378
1379         if !(ctxt == AssocCtxt::Impl
1380             && matches!(item.vis.kind, ast::VisibilityKind::Inherited)
1381             && self
1382                 .r
1383                 .trait_impl_items
1384                 .contains(&ty::DefIdTree::parent(&*self.r, def_id).unwrap().expect_local()))
1385         {
1386             // Trait impl item visibility is inherited from its trait when not specified
1387             // explicitly. In that case we cannot determine it here in early resolve,
1388             // so we leave a hole in the visibility table to be filled later.
1389             self.r.visibilities.insert(local_def_id, vis);
1390         }
1391
1392         if ctxt == AssocCtxt::Trait {
1393             let (def_kind, ns) = match item.kind {
1394                 AssocItemKind::Const(..) => (DefKind::AssocConst, ValueNS),
1395                 AssocItemKind::Fn(box FnKind(_, ref sig, _, _)) => {
1396                     if sig.decl.has_self() {
1397                         self.r.has_self.insert(def_id);
1398                     }
1399                     (DefKind::AssocFn, ValueNS)
1400                 }
1401                 AssocItemKind::TyAlias(..) => (DefKind::AssocTy, TypeNS),
1402                 AssocItemKind::MacCall(_) => bug!(), // handled above
1403             };
1404
1405             let parent = self.parent_scope.module;
1406             let expansion = self.parent_scope.expansion;
1407             let res = Res::Def(def_kind, def_id);
1408             self.r.define(parent, item.ident, ns, (res, vis, item.span, expansion));
1409         }
1410
1411         visit::walk_assoc_item(self, item, ctxt);
1412     }
1413
1414     fn visit_attribute(&mut self, attr: &'b ast::Attribute) {
1415         if !attr.is_doc_comment() && attr::is_builtin_attr(attr) {
1416             self.r
1417                 .builtin_attrs
1418                 .push((attr.get_normal_item().path.segments[0].ident, self.parent_scope));
1419         }
1420         visit::walk_attribute(self, attr);
1421     }
1422
1423     fn visit_arm(&mut self, arm: &'b ast::Arm) {
1424         if arm.is_placeholder {
1425             self.visit_invoc(arm.id);
1426         } else {
1427             visit::walk_arm(self, arm);
1428         }
1429     }
1430
1431     fn visit_expr_field(&mut self, f: &'b ast::ExprField) {
1432         if f.is_placeholder {
1433             self.visit_invoc(f.id);
1434         } else {
1435             visit::walk_expr_field(self, f);
1436         }
1437     }
1438
1439     fn visit_pat_field(&mut self, fp: &'b ast::PatField) {
1440         if fp.is_placeholder {
1441             self.visit_invoc(fp.id);
1442         } else {
1443             visit::walk_pat_field(self, fp);
1444         }
1445     }
1446
1447     fn visit_generic_param(&mut self, param: &'b ast::GenericParam) {
1448         if param.is_placeholder {
1449             self.visit_invoc(param.id);
1450         } else {
1451             visit::walk_generic_param(self, param);
1452         }
1453     }
1454
1455     fn visit_param(&mut self, p: &'b ast::Param) {
1456         if p.is_placeholder {
1457             self.visit_invoc(p.id);
1458         } else {
1459             visit::walk_param(self, p);
1460         }
1461     }
1462
1463     fn visit_field_def(&mut self, sf: &'b ast::FieldDef) {
1464         if sf.is_placeholder {
1465             self.visit_invoc(sf.id);
1466         } else {
1467             let vis = self.resolve_visibility(&sf.vis);
1468             self.r.visibilities.insert(self.r.local_def_id(sf.id), vis);
1469             visit::walk_field_def(self, sf);
1470         }
1471     }
1472
1473     // Constructs the reduced graph for one variant. Variants exist in the
1474     // type and value namespaces.
1475     fn visit_variant(&mut self, variant: &'b ast::Variant) {
1476         if variant.is_placeholder {
1477             self.visit_invoc_in_module(variant.id);
1478             return;
1479         }
1480
1481         let parent = self.parent_scope.module;
1482         let expn_id = self.parent_scope.expansion;
1483         let ident = variant.ident;
1484
1485         // Define a name in the type namespace.
1486         let def_id = self.r.local_def_id(variant.id);
1487         let res = Res::Def(DefKind::Variant, def_id.to_def_id());
1488         let vis = self.resolve_visibility(&variant.vis);
1489         self.r.define(parent, ident, TypeNS, (res, vis, variant.span, expn_id));
1490         self.r.visibilities.insert(def_id, vis);
1491
1492         // If the variant is marked as non_exhaustive then lower the visibility to within the crate.
1493         let ctor_vis = if vis == ty::Visibility::Public
1494             && self.r.session.contains_name(&variant.attrs, sym::non_exhaustive)
1495         {
1496             ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
1497         } else {
1498             vis
1499         };
1500
1501         // Define a constructor name in the value namespace.
1502         // Braced variants, unlike structs, generate unusable names in
1503         // value namespace, they are reserved for possible future use.
1504         // It's ok to use the variant's id as a ctor id since an
1505         // error will be reported on any use of such resolution anyway.
1506         let ctor_node_id = variant.data.ctor_id().unwrap_or(variant.id);
1507         let ctor_def_id = self.r.local_def_id(ctor_node_id);
1508         let ctor_kind = CtorKind::from_ast(&variant.data);
1509         let ctor_res = Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id.to_def_id());
1510         self.r.define(parent, ident, ValueNS, (ctor_res, ctor_vis, variant.span, expn_id));
1511         if ctor_def_id != def_id {
1512             self.r.visibilities.insert(ctor_def_id, ctor_vis);
1513         }
1514         // Record field names for error reporting.
1515         self.insert_field_names_local(ctor_def_id.to_def_id(), &variant.data);
1516
1517         visit::walk_variant(self, variant);
1518     }
1519 }