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