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