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