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