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