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