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