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