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