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