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