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