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