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