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