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