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