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