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