]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/build_reduced_graph.rs
Rollup merge of #63055 - Mark-Simulacrum:save-analysis-clean-2, r=Xanewok
[rust.git] / src / librustc_resolve / build_reduced_graph.rs
1 //! Reduced graph building.
2 //!
3 //! Here we build the "reduced graph": the graph of the module tree without
4 //! any imports resolved.
5
6 use crate::macros::{InvocationData, LegacyScope};
7 use crate::resolve_imports::ImportDirective;
8 use crate::resolve_imports::ImportDirectiveSubclass::{self, GlobImport, SingleImport};
9 use crate::{Module, ModuleData, ModuleKind, NameBinding, NameBindingKind, Segment, ToNameBinding};
10 use crate::{ModuleOrUniformRoot, ParentScope, PerNS, Resolver, ResolverArenas, ExternPreludeEntry};
11 use crate::Namespace::{self, TypeNS, ValueNS, MacroNS};
12 use crate::{resolve_error, resolve_struct_error, ResolutionError, Determinacy};
13
14 use rustc::bug;
15 use rustc::hir::def::{self, *};
16 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
17 use rustc::ty;
18 use rustc::middle::cstore::CrateStore;
19 use rustc_metadata::cstore::LoadedMacro;
20
21 use std::cell::Cell;
22 use std::ptr;
23 use rustc_data_structures::sync::Lrc;
24
25 use errors::Applicability;
26
27 use syntax::ast::{Name, Ident};
28 use syntax::attr;
29
30 use syntax::ast::{self, Block, ForeignItem, ForeignItemKind, Item, ItemKind, NodeId};
31 use syntax::ast::{MetaItemKind, StmtKind, TraitItem, TraitItemKind, Variant};
32 use syntax::ext::base::SyntaxExtension;
33 use syntax::ext::hygiene::ExpnId;
34 use syntax::feature_gate::is_builtin_attr;
35 use syntax::parse::token::{self, Token};
36 use syntax::span_err;
37 use syntax::symbol::{kw, sym};
38 use syntax::visit::{self, Visitor};
39
40 use syntax_pos::{Span, DUMMY_SP};
41
42 use log::debug;
43
44 type Res = def::Res<NodeId>;
45
46 impl<'a> ToNameBinding<'a> for (Module<'a>, ty::Visibility, Span, ExpnId) {
47     fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
48         arenas.alloc_name_binding(NameBinding {
49             kind: NameBindingKind::Module(self.0),
50             ambiguity: None,
51             vis: self.1,
52             span: self.2,
53             expansion: self.3,
54         })
55     }
56 }
57
58 impl<'a> ToNameBinding<'a> for (Res, ty::Visibility, Span, ExpnId) {
59     fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
60         arenas.alloc_name_binding(NameBinding {
61             kind: NameBindingKind::Res(self.0, false),
62             ambiguity: None,
63             vis: self.1,
64             span: self.2,
65             expansion: self.3,
66         })
67     }
68 }
69
70 pub(crate) struct IsMacroExport;
71
72 impl<'a> ToNameBinding<'a> for (Res, ty::Visibility, Span, ExpnId, IsMacroExport) {
73     fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
74         arenas.alloc_name_binding(NameBinding {
75             kind: NameBindingKind::Res(self.0, true),
76             ambiguity: None,
77             vis: self.1,
78             span: self.2,
79             expansion: self.3,
80         })
81     }
82 }
83
84 impl<'a> Resolver<'a> {
85     /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
86     /// otherwise, reports an error.
87     pub fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T)
88         where T: ToNameBinding<'a>,
89     {
90         let binding = def.to_name_binding(self.arenas);
91         if let Err(old_binding) = self.try_define(parent, ident, ns, binding) {
92             self.report_conflict(parent, ident, ns, old_binding, &binding);
93         }
94     }
95
96     fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
97         // If any statements are items, we need to create an anonymous module
98         block.stmts.iter().any(|statement| match statement.node {
99             StmtKind::Item(_) | StmtKind::Mac(_) => true,
100             _ => false,
101         })
102     }
103
104     fn insert_field_names(&mut self, def_id: DefId, field_names: Vec<Name>) {
105         if !field_names.is_empty() {
106             self.field_names.insert(def_id, field_names);
107         }
108     }
109
110     fn build_reduced_graph_for_use_tree(
111         &mut self,
112         // This particular use tree
113         use_tree: &ast::UseTree,
114         id: NodeId,
115         parent_prefix: &[Segment],
116         nested: bool,
117         // The whole `use` item
118         parent_scope: ParentScope<'a>,
119         item: &Item,
120         vis: ty::Visibility,
121         root_span: Span,
122     ) {
123         debug!("build_reduced_graph_for_use_tree(parent_prefix={:?}, use_tree={:?}, nested={})",
124                parent_prefix, use_tree, nested);
125
126         let mut prefix_iter = parent_prefix.iter().cloned()
127             .chain(use_tree.prefix.segments.iter().map(|seg| seg.into())).peekable();
128
129         // On 2015 edition imports are resolved as crate-relative by default,
130         // so prefixes are prepended with crate root segment if necessary.
131         // The root is prepended lazily, when the first non-empty prefix or terminating glob
132         // appears, so imports in braced groups can have roots prepended independently.
133         let is_glob = if let ast::UseTreeKind::Glob = use_tree.kind { true } else { false };
134         let crate_root = match prefix_iter.peek() {
135             Some(seg) if !seg.ident.is_path_segment_keyword() && seg.ident.span.rust_2015() => {
136                 Some(seg.ident.span.ctxt())
137             }
138             None if is_glob && use_tree.span.rust_2015() => {
139                 Some(use_tree.span.ctxt())
140             }
141             _ => None,
142         }.map(|ctxt| Segment::from_ident(Ident::new(
143             kw::PathRoot, use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt)
144         )));
145
146         let prefix = crate_root.into_iter().chain(prefix_iter).collect::<Vec<_>>();
147         debug!("build_reduced_graph_for_use_tree: prefix={:?}", prefix);
148
149         let empty_for_self = |prefix: &[Segment]| {
150             prefix.is_empty() ||
151             prefix.len() == 1 && prefix[0].ident.name == kw::PathRoot
152         };
153         match use_tree.kind {
154             ast::UseTreeKind::Simple(rename, ..) => {
155                 let mut ident = use_tree.ident().gensym_if_underscore();
156                 let mut module_path = prefix;
157                 let mut source = module_path.pop().unwrap();
158                 let mut type_ns_only = false;
159
160                 if nested {
161                     // Correctly handle `self`
162                     if source.ident.name == kw::SelfLower {
163                         type_ns_only = true;
164
165                         if empty_for_self(&module_path) {
166                             resolve_error(
167                                 self,
168                                 use_tree.span,
169                                 ResolutionError::
170                                 SelfImportOnlyInImportListWithNonEmptyPrefix
171                             );
172                             return;
173                         }
174
175                         // Replace `use foo::self;` with `use foo;`
176                         source = module_path.pop().unwrap();
177                         if rename.is_none() {
178                             ident = source.ident;
179                         }
180                     }
181                 } else {
182                     // Disallow `self`
183                     if source.ident.name == kw::SelfLower {
184                         resolve_error(self,
185                                       use_tree.span,
186                                       ResolutionError::SelfImportsOnlyAllowedWithin);
187                     }
188
189                     // Disallow `use $crate;`
190                     if source.ident.name == kw::DollarCrate && module_path.is_empty() {
191                         let crate_root = self.resolve_crate_root(source.ident);
192                         let crate_name = match crate_root.kind {
193                             ModuleKind::Def(.., name) => name,
194                             ModuleKind::Block(..) => unreachable!(),
195                         };
196                         // HACK(eddyb) unclear how good this is, but keeping `$crate`
197                         // in `source` breaks `src/test/compile-fail/import-crate-var.rs`,
198                         // while the current crate doesn't have a valid `crate_name`.
199                         if crate_name != kw::Invalid {
200                             // `crate_name` should not be interpreted as relative.
201                             module_path.push(Segment {
202                                 ident: Ident {
203                                     name: kw::PathRoot,
204                                     span: source.ident.span,
205                                 },
206                                 id: Some(self.session.next_node_id()),
207                             });
208                             source.ident.name = crate_name;
209                         }
210                         if rename.is_none() {
211                             ident.name = crate_name;
212                         }
213
214                         self.session.struct_span_warn(item.span, "`$crate` may not be imported")
215                             .note("`use $crate;` was erroneously allowed and \
216                                    will become a hard error in a future release")
217                             .emit();
218                     }
219                 }
220
221                 if ident.name == kw::Crate {
222                     self.session.span_err(ident.span,
223                         "crate root imports need to be explicitly named: \
224                          `use crate as name;`");
225                 }
226
227                 let subclass = SingleImport {
228                     source: source.ident,
229                     target: ident,
230                     source_bindings: PerNS {
231                         type_ns: Cell::new(Err(Determinacy::Undetermined)),
232                         value_ns: Cell::new(Err(Determinacy::Undetermined)),
233                         macro_ns: Cell::new(Err(Determinacy::Undetermined)),
234                     },
235                     target_bindings: PerNS {
236                         type_ns: Cell::new(None),
237                         value_ns: Cell::new(None),
238                         macro_ns: Cell::new(None),
239                     },
240                     type_ns_only,
241                     nested,
242                 };
243                 self.add_import_directive(
244                     module_path,
245                     subclass,
246                     use_tree.span,
247                     id,
248                     item,
249                     root_span,
250                     item.id,
251                     vis,
252                     parent_scope,
253                 );
254             }
255             ast::UseTreeKind::Glob => {
256                 let subclass = GlobImport {
257                     is_prelude: attr::contains_name(&item.attrs, sym::prelude_import),
258                     max_vis: Cell::new(ty::Visibility::Invisible),
259                 };
260                 self.add_import_directive(
261                     prefix,
262                     subclass,
263                     use_tree.span,
264                     id,
265                     item,
266                     root_span,
267                     item.id,
268                     vis,
269                     parent_scope,
270                 );
271             }
272             ast::UseTreeKind::Nested(ref items) => {
273                 // Ensure there is at most one `self` in the list
274                 let self_spans = items.iter().filter_map(|&(ref use_tree, _)| {
275                     if let ast::UseTreeKind::Simple(..) = use_tree.kind {
276                         if use_tree.ident().name == kw::SelfLower {
277                             return Some(use_tree.span);
278                         }
279                     }
280
281                     None
282                 }).collect::<Vec<_>>();
283                 if self_spans.len() > 1 {
284                     let mut e = resolve_struct_error(self,
285                         self_spans[0],
286                         ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
287
288                     for other_span in self_spans.iter().skip(1) {
289                         e.span_label(*other_span, "another `self` import appears here");
290                     }
291
292                     e.emit();
293                 }
294
295                 for &(ref tree, id) in items {
296                     self.build_reduced_graph_for_use_tree(
297                         // This particular use tree
298                         tree, id, &prefix, true,
299                         // The whole `use` item
300                         parent_scope.clone(), item, vis, root_span,
301                     );
302                 }
303
304                 // Empty groups `a::b::{}` are turned into synthetic `self` imports
305                 // `a::b::c::{self as _}`, so that their prefixes are correctly
306                 // resolved and checked for privacy/stability/etc.
307                 if items.is_empty() && !empty_for_self(&prefix) {
308                     let new_span = prefix[prefix.len() - 1].ident.span;
309                     let tree = ast::UseTree {
310                         prefix: ast::Path::from_ident(
311                             Ident::new(kw::SelfLower, new_span)
312                         ),
313                         kind: ast::UseTreeKind::Simple(
314                             Some(Ident::new(kw::Underscore, new_span)),
315                             ast::DUMMY_NODE_ID,
316                             ast::DUMMY_NODE_ID,
317                         ),
318                         span: use_tree.span,
319                     };
320                     self.build_reduced_graph_for_use_tree(
321                         // This particular use tree
322                         &tree, id, &prefix, true,
323                         // The whole `use` item
324                         parent_scope, item, ty::Visibility::Invisible, root_span,
325                     );
326                 }
327             }
328         }
329     }
330
331     /// Constructs the reduced graph for one item.
332     fn build_reduced_graph_for_item(&mut self, item: &Item, parent_scope: ParentScope<'a>) {
333         let parent = parent_scope.module;
334         let expansion = parent_scope.expansion;
335         let ident = item.ident.gensym_if_underscore();
336         let sp = item.span;
337         let vis = self.resolve_visibility(&item.vis);
338
339         match item.node {
340             ItemKind::Use(ref use_tree) => {
341                 self.build_reduced_graph_for_use_tree(
342                     // This particular use tree
343                     use_tree, item.id, &[], false,
344                     // The whole `use` item
345                     parent_scope, item, vis, use_tree.span,
346                 );
347             }
348
349             ItemKind::ExternCrate(orig_name) => {
350                 let module = if orig_name.is_none() && ident.name == kw::SelfLower {
351                     self.session
352                         .struct_span_err(item.span, "`extern crate self;` requires renaming")
353                         .span_suggestion(
354                             item.span,
355                             "try",
356                             "extern crate self as name;".into(),
357                             Applicability::HasPlaceholders,
358                         )
359                         .emit();
360                     return;
361                 } else if orig_name == Some(kw::SelfLower) {
362                     self.graph_root
363                 } else {
364                     let crate_id = self.crate_loader.process_extern_crate(item, &self.definitions);
365                     self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX })
366                 };
367
368                 self.populate_module_if_necessary(module);
369                 if let Some(name) = self.session.parse_sess.injected_crate_name.try_get() {
370                     if name.as_str() == ident.name.as_str() {
371                         self.injected_crate = Some(module);
372                     }
373                 }
374
375                 let used = self.process_legacy_macro_imports(item, module, &parent_scope);
376                 let binding =
377                     (module, ty::Visibility::Public, sp, expansion).to_name_binding(self.arenas);
378                 let directive = self.arenas.alloc_import_directive(ImportDirective {
379                     root_id: item.id,
380                     id: item.id,
381                     parent_scope,
382                     imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
383                     subclass: ImportDirectiveSubclass::ExternCrate {
384                         source: orig_name,
385                         target: ident,
386                     },
387                     has_attributes: !item.attrs.is_empty(),
388                     use_span_with_attributes: item.span_with_attributes(),
389                     use_span: item.span,
390                     root_span: item.span,
391                     span: item.span,
392                     module_path: Vec::new(),
393                     vis: Cell::new(vis),
394                     used: Cell::new(used),
395                 });
396                 self.potentially_unused_imports.push(directive);
397                 let imported_binding = self.import(binding, directive);
398                 if ptr::eq(self.current_module, self.graph_root) {
399                     if let Some(entry) = self.extern_prelude.get(&ident.modern()) {
400                         if expansion != ExpnId::root() && orig_name.is_some() &&
401                            entry.extern_crate_item.is_none() {
402                             self.session.span_err(item.span, "macro-expanded `extern crate` items \
403                                                               cannot shadow names passed with \
404                                                               `--extern`");
405                         }
406                     }
407                     let entry = self.extern_prelude.entry(ident.modern())
408                                                    .or_insert(ExternPreludeEntry {
409                         extern_crate_item: None,
410                         introduced_by_item: true,
411                     });
412                     entry.extern_crate_item = Some(imported_binding);
413                     if orig_name.is_some() {
414                         entry.introduced_by_item = true;
415                     }
416                 }
417                 self.define(parent, ident, TypeNS, imported_binding);
418             }
419
420             ItemKind::GlobalAsm(..) => {}
421
422             ItemKind::Mod(..) if ident.name == kw::Invalid => {} // Crate root
423
424             ItemKind::Mod(..) => {
425                 let def_id = self.definitions.local_def_id(item.id);
426                 let module_kind = ModuleKind::Def(DefKind::Mod, def_id, ident.name);
427                 let module = self.arenas.alloc_module(ModuleData {
428                     no_implicit_prelude: parent.no_implicit_prelude || {
429                         attr::contains_name(&item.attrs, sym::no_implicit_prelude)
430                     },
431                     ..ModuleData::new(Some(parent), module_kind, def_id, expansion, item.span)
432                 });
433                 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
434                 self.module_map.insert(def_id, module);
435
436                 // Descend into the module.
437                 self.current_module = module;
438             }
439
440             // Handled in `rustc_metadata::{native_libs,link_args}`
441             ItemKind::ForeignMod(..) => {}
442
443             // These items live in the value namespace.
444             ItemKind::Static(..) => {
445                 let res = Res::Def(DefKind::Static, self.definitions.local_def_id(item.id));
446                 self.define(parent, ident, ValueNS, (res, vis, sp, expansion));
447             }
448             ItemKind::Const(..) => {
449                 let res = Res::Def(DefKind::Const, self.definitions.local_def_id(item.id));
450                 self.define(parent, ident, ValueNS, (res, vis, sp, expansion));
451             }
452             ItemKind::Fn(..) => {
453                 let res = Res::Def(DefKind::Fn, self.definitions.local_def_id(item.id));
454                 self.define(parent, ident, ValueNS, (res, vis, sp, expansion));
455
456                 // Functions introducing procedural macros reserve a slot
457                 // in the macro namespace as well (see #52225).
458                 self.define_macro(item, expansion, &mut LegacyScope::Empty);
459             }
460
461             // These items live in the type namespace.
462             ItemKind::Ty(..) => {
463                 let res = Res::Def(DefKind::TyAlias, self.definitions.local_def_id(item.id));
464                 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
465             }
466
467             ItemKind::Existential(_, _) => {
468                 let res = Res::Def(DefKind::Existential, self.definitions.local_def_id(item.id));
469                 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
470             }
471
472             ItemKind::Enum(ref enum_definition, _) => {
473                 let module_kind = ModuleKind::Def(
474                     DefKind::Enum,
475                     self.definitions.local_def_id(item.id),
476                     ident.name,
477                 );
478                 let module = self.new_module(parent,
479                                              module_kind,
480                                              parent.normal_ancestor_id,
481                                              expansion,
482                                              item.span);
483                 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
484
485                 for variant in &(*enum_definition).variants {
486                     self.build_reduced_graph_for_variant(variant, module, vis, expansion);
487                 }
488             }
489
490             ItemKind::TraitAlias(..) => {
491                 let res = Res::Def(DefKind::TraitAlias, self.definitions.local_def_id(item.id));
492                 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
493             }
494
495             // These items live in both the type and value namespaces.
496             ItemKind::Struct(ref struct_def, _) => {
497                 // Define a name in the type namespace.
498                 let def_id = self.definitions.local_def_id(item.id);
499                 let res = Res::Def(DefKind::Struct, def_id);
500                 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
501
502                 let mut ctor_vis = vis;
503
504                 let has_non_exhaustive = attr::contains_name(&item.attrs, sym::non_exhaustive);
505
506                 // If the structure is marked as non_exhaustive then lower the visibility
507                 // to within the crate.
508                 if has_non_exhaustive && vis == ty::Visibility::Public {
509                     ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
510                 }
511
512                 // Record field names for error reporting.
513                 let field_names = struct_def.fields().iter().filter_map(|field| {
514                     let field_vis = self.resolve_visibility(&field.vis);
515                     if ctor_vis.is_at_least(field_vis, &*self) {
516                         ctor_vis = field_vis;
517                     }
518                     field.ident.map(|ident| ident.name)
519                 }).collect();
520                 let item_def_id = self.definitions.local_def_id(item.id);
521                 self.insert_field_names(item_def_id, field_names);
522
523                 // If this is a tuple or unit struct, define a name
524                 // in the value namespace as well.
525                 if let Some(ctor_node_id) = struct_def.ctor_id() {
526                     let ctor_res = Res::Def(
527                         DefKind::Ctor(CtorOf::Struct, CtorKind::from_ast(struct_def)),
528                         self.definitions.local_def_id(ctor_node_id),
529                     );
530                     self.define(parent, ident, ValueNS, (ctor_res, ctor_vis, sp, expansion));
531                     self.struct_constructors.insert(res.def_id(), (ctor_res, ctor_vis));
532                 }
533             }
534
535             ItemKind::Union(ref vdata, _) => {
536                 let res = Res::Def(DefKind::Union, self.definitions.local_def_id(item.id));
537                 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
538
539                 // Record field names for error reporting.
540                 let field_names = vdata.fields().iter().filter_map(|field| {
541                     self.resolve_visibility(&field.vis);
542                     field.ident.map(|ident| ident.name)
543                 }).collect();
544                 let item_def_id = self.definitions.local_def_id(item.id);
545                 self.insert_field_names(item_def_id, field_names);
546             }
547
548             ItemKind::Impl(..) => {}
549
550             ItemKind::Trait(..) => {
551                 let def_id = self.definitions.local_def_id(item.id);
552
553                 // Add all the items within to a new module.
554                 let module_kind = ModuleKind::Def(DefKind::Trait, def_id, ident.name);
555                 let module = self.new_module(parent,
556                                              module_kind,
557                                              parent.normal_ancestor_id,
558                                              expansion,
559                                              item.span);
560                 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
561                 self.current_module = module;
562             }
563
564             ItemKind::MacroDef(..) | ItemKind::Mac(_) => unreachable!(),
565         }
566     }
567
568     // Constructs the reduced graph for one variant. Variants exist in the
569     // type and value namespaces.
570     fn build_reduced_graph_for_variant(&mut self,
571                                        variant: &Variant,
572                                        parent: Module<'a>,
573                                        vis: ty::Visibility,
574                                        expn_id: ExpnId) {
575         let ident = variant.node.ident;
576
577         // Define a name in the type namespace.
578         let def_id = self.definitions.local_def_id(variant.node.id);
579         let res = Res::Def(DefKind::Variant, def_id);
580         self.define(parent, ident, TypeNS, (res, vis, variant.span, expn_id));
581
582         // If the variant is marked as non_exhaustive then lower the visibility to within the
583         // crate.
584         let mut ctor_vis = vis;
585         let has_non_exhaustive = attr::contains_name(&variant.node.attrs, sym::non_exhaustive);
586         if has_non_exhaustive && vis == ty::Visibility::Public {
587             ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
588         }
589
590         // Define a constructor name in the value namespace.
591         // Braced variants, unlike structs, generate unusable names in
592         // value namespace, they are reserved for possible future use.
593         // It's ok to use the variant's id as a ctor id since an
594         // error will be reported on any use of such resolution anyway.
595         let ctor_node_id = variant.node.data.ctor_id().unwrap_or(variant.node.id);
596         let ctor_def_id = self.definitions.local_def_id(ctor_node_id);
597         let ctor_kind = CtorKind::from_ast(&variant.node.data);
598         let ctor_res = Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id);
599         self.define(parent, ident, ValueNS, (ctor_res, ctor_vis, variant.span, expn_id));
600     }
601
602     /// Constructs the reduced graph for one foreign item.
603     fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem, expn_id: ExpnId) {
604         let (res, ns) = match item.node {
605             ForeignItemKind::Fn(..) => {
606                 (Res::Def(DefKind::Fn, self.definitions.local_def_id(item.id)), ValueNS)
607             }
608             ForeignItemKind::Static(..) => {
609                 (Res::Def(DefKind::Static, self.definitions.local_def_id(item.id)), ValueNS)
610             }
611             ForeignItemKind::Ty => {
612                 (Res::Def(DefKind::ForeignTy, self.definitions.local_def_id(item.id)), TypeNS)
613             }
614             ForeignItemKind::Macro(_) => unreachable!(),
615         };
616         let parent = self.current_module;
617         let vis = self.resolve_visibility(&item.vis);
618         self.define(parent, item.ident, ns, (res, vis, item.span, expn_id));
619     }
620
621     fn build_reduced_graph_for_block(&mut self, block: &Block, expn_id: ExpnId) {
622         let parent = self.current_module;
623         if self.block_needs_anonymous_module(block) {
624             let module = self.new_module(parent,
625                                          ModuleKind::Block(block.id),
626                                          parent.normal_ancestor_id,
627                                          expn_id,
628                                          block.span);
629             self.block_map.insert(block.id, module);
630             self.current_module = module; // Descend into the block.
631         }
632     }
633
634     /// Builds the reduced graph for a single item in an external crate.
635     fn build_reduced_graph_for_external_crate_res(
636         &mut self,
637         parent: Module<'a>,
638         child: Export<ast::NodeId>,
639     ) {
640         let Export { ident, res, vis, span } = child;
641         // FIXME: We shouldn't create the gensym here, it should come from metadata,
642         // but metadata cannot encode gensyms currently, so we create it here.
643         // This is only a guess, two equivalent idents may incorrectly get different gensyms here.
644         let ident = ident.gensym_if_underscore();
645         let expansion = ExpnId::root(); // FIXME(jseyfried) intercrate hygiene
646         match res {
647             Res::Def(kind @ DefKind::Mod, def_id)
648             | Res::Def(kind @ DefKind::Enum, def_id) => {
649                 let module = self.new_module(parent,
650                                              ModuleKind::Def(kind, def_id, ident.name),
651                                              def_id,
652                                              expansion,
653                                              span);
654                 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
655             }
656             Res::Def(DefKind::Variant, _)
657             | Res::Def(DefKind::TyAlias, _)
658             | Res::Def(DefKind::ForeignTy, _)
659             | Res::Def(DefKind::Existential, _)
660             | Res::Def(DefKind::TraitAlias, _)
661             | Res::PrimTy(..)
662             | Res::ToolMod => {
663                 self.define(parent, ident, TypeNS, (res, vis, DUMMY_SP, expansion));
664             }
665             Res::Def(DefKind::Fn, _)
666             | Res::Def(DefKind::Static, _)
667             | Res::Def(DefKind::Const, _)
668             | Res::Def(DefKind::Ctor(CtorOf::Variant, ..), _) => {
669                 self.define(parent, ident, ValueNS, (res, vis, DUMMY_SP, expansion));
670             }
671             Res::Def(DefKind::Ctor(CtorOf::Struct, ..), def_id) => {
672                 self.define(parent, ident, ValueNS, (res, vis, DUMMY_SP, expansion));
673
674                 if let Some(struct_def_id) =
675                         self.cstore.def_key(def_id).parent
676                             .map(|index| DefId { krate: def_id.krate, index: index }) {
677                     self.struct_constructors.insert(struct_def_id, (res, vis));
678                 }
679             }
680             Res::Def(DefKind::Trait, def_id) => {
681                 let module_kind = ModuleKind::Def(DefKind::Trait, def_id, ident.name);
682                 let module = self.new_module(parent,
683                                              module_kind,
684                                              parent.normal_ancestor_id,
685                                              expansion,
686                                              span);
687                 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
688
689                 for child in self.cstore.item_children_untracked(def_id, self.session) {
690                     let res = child.res.map_id(|_| panic!("unexpected id"));
691                     let ns = if let Res::Def(DefKind::AssocTy, _) = res {
692                         TypeNS
693                     } else { ValueNS };
694                     self.define(module, child.ident, ns,
695                                 (res, ty::Visibility::Public, DUMMY_SP, expansion));
696
697                     if self.cstore.associated_item_cloned_untracked(child.res.def_id())
698                            .method_has_self_argument {
699                         self.has_self.insert(res.def_id());
700                     }
701                 }
702                 module.populated.set(true);
703             }
704             Res::Def(DefKind::Struct, def_id) | Res::Def(DefKind::Union, def_id) => {
705                 self.define(parent, ident, TypeNS, (res, vis, DUMMY_SP, expansion));
706
707                 // Record field names for error reporting.
708                 let field_names = self.cstore.struct_field_names_untracked(def_id);
709                 self.insert_field_names(def_id, field_names);
710             }
711             Res::Def(DefKind::Macro(..), _) | Res::NonMacroAttr(..) => {
712                 self.define(parent, ident, MacroNS, (res, vis, DUMMY_SP, expansion));
713             }
714             _ => bug!("unexpected resolution: {:?}", res)
715         }
716     }
717
718     pub fn get_module(&mut self, def_id: DefId) -> Module<'a> {
719         if def_id.krate == LOCAL_CRATE {
720             return self.module_map[&def_id]
721         }
722
723         let macros_only = self.cstore.dep_kind_untracked(def_id.krate).macros_only();
724         if let Some(&module) = self.extern_module_map.get(&(def_id, macros_only)) {
725             return module;
726         }
727
728         let (name, parent) = if def_id.index == CRATE_DEF_INDEX {
729             (self.cstore.crate_name_untracked(def_id.krate).as_interned_str(), None)
730         } else {
731             let def_key = self.cstore.def_key(def_id);
732             (def_key.disambiguated_data.data.get_opt_name().unwrap(),
733              Some(self.get_module(DefId { index: def_key.parent.unwrap(), ..def_id })))
734         };
735
736         let kind = ModuleKind::Def(DefKind::Mod, def_id, name.as_symbol());
737         let module = self.arenas.alloc_module(ModuleData::new(
738             parent, kind, def_id, ExpnId::root(), DUMMY_SP
739         ));
740         self.extern_module_map.insert((def_id, macros_only), module);
741         module
742     }
743
744     pub fn macro_def_scope(&mut self, expn_id: ExpnId) -> Module<'a> {
745         let def_id = match self.macro_defs.get(&expn_id) {
746             Some(def_id) => *def_id,
747             None => return self.graph_root,
748         };
749         if let Some(id) = self.definitions.as_local_node_id(def_id) {
750             self.local_macro_def_scopes[&id]
751         } else if self.is_builtin_macro(Some(def_id)) {
752             self.injected_crate.unwrap_or(self.graph_root)
753         } else {
754             let module_def_id = ty::DefIdTree::parent(&*self, def_id).unwrap();
755             self.get_module(module_def_id)
756         }
757     }
758
759     crate fn get_macro(&mut self, res: Res) -> Option<Lrc<SyntaxExtension>> {
760         match res {
761             Res::Def(DefKind::Macro(..), def_id) => self.get_macro_by_def_id(def_id),
762             Res::NonMacroAttr(attr_kind) =>
763                 Some(self.non_macro_attr(attr_kind == NonMacroAttrKind::Tool)),
764             _ => None,
765         }
766     }
767
768     crate fn get_macro_by_def_id(&mut self, def_id: DefId) -> Option<Lrc<SyntaxExtension>> {
769         if let Some(ext) = self.macro_map.get(&def_id) {
770             return Some(ext.clone());
771         }
772
773         let macro_def = match self.cstore.load_macro_untracked(def_id, &self.session) {
774             LoadedMacro::MacroDef(macro_def) => macro_def,
775             LoadedMacro::ProcMacro(ext) => return Some(ext),
776         };
777
778         let ext = self.compile_macro(&macro_def, self.cstore.crate_edition_untracked(def_id.krate));
779         self.macro_map.insert(def_id, ext.clone());
780         Some(ext)
781     }
782
783     /// Ensures that the reduced graph rooted at the given external module
784     /// is built, building it if it is not.
785     pub fn populate_module_if_necessary(&mut self, module: Module<'a>) {
786         if module.populated.get() { return }
787         let def_id = module.def_id().unwrap();
788         for child in self.cstore.item_children_untracked(def_id, self.session) {
789             let child = child.map_id(|_| panic!("unexpected id"));
790             self.build_reduced_graph_for_external_crate_res(module, child);
791         }
792         module.populated.set(true)
793     }
794
795     fn legacy_import_macro(&mut self,
796                            name: Name,
797                            binding: &'a NameBinding<'a>,
798                            span: Span,
799                            allow_shadowing: bool) {
800         if self.macro_use_prelude.insert(name, binding).is_some() && !allow_shadowing {
801             let msg = format!("`{}` is already in scope", name);
802             let note =
803                 "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)";
804             self.session.struct_span_err(span, &msg).note(note).emit();
805         }
806     }
807
808     /// Returns `true` if we should consider the underlying `extern crate` to be used.
809     fn process_legacy_macro_imports(&mut self, item: &Item, module: Module<'a>,
810                                     parent_scope: &ParentScope<'a>) -> bool {
811         let mut import_all = None;
812         let mut single_imports = Vec::new();
813         for attr in &item.attrs {
814             if attr.check_name(sym::macro_use) {
815                 if self.current_module.parent.is_some() {
816                     span_err!(self.session, item.span, E0468,
817                         "an `extern crate` loading macros must be at the crate root");
818                 }
819                 if let ItemKind::ExternCrate(Some(orig_name)) = item.node {
820                     if orig_name == kw::SelfLower {
821                         self.session.span_err(attr.span,
822                             "`macro_use` is not supported on `extern crate self`");
823                     }
824                 }
825                 let ill_formed = |span| span_err!(self.session, span, E0466, "bad macro import");
826                 match attr.meta() {
827                     Some(meta) => match meta.node {
828                         MetaItemKind::Word => {
829                             import_all = Some(meta.span);
830                             break;
831                         }
832                         MetaItemKind::List(nested_metas) => for nested_meta in nested_metas {
833                             match nested_meta.ident() {
834                                 Some(ident) if nested_meta.is_word() => single_imports.push(ident),
835                                 _ => ill_formed(nested_meta.span()),
836                             }
837                         }
838                         MetaItemKind::NameValue(..) => ill_formed(meta.span),
839                     }
840                     None => ill_formed(attr.span),
841                 }
842             }
843         }
844
845         let arenas = self.arenas;
846         let macro_use_directive = |span| arenas.alloc_import_directive(ImportDirective {
847             root_id: item.id,
848             id: item.id,
849             parent_scope: parent_scope.clone(),
850             imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
851             subclass: ImportDirectiveSubclass::MacroUse,
852             use_span_with_attributes: item.span_with_attributes(),
853             has_attributes: !item.attrs.is_empty(),
854             use_span: item.span,
855             root_span: span,
856             span,
857             module_path: Vec::new(),
858             vis: Cell::new(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))),
859             used: Cell::new(false),
860         });
861
862         let allow_shadowing = parent_scope.expansion == ExpnId::root();
863         if let Some(span) = import_all {
864             let directive = macro_use_directive(span);
865             self.potentially_unused_imports.push(directive);
866             module.for_each_child(|ident, ns, binding| if ns == MacroNS {
867                 let imported_binding = self.import(binding, directive);
868                 self.legacy_import_macro(ident.name, imported_binding, span, allow_shadowing);
869             });
870         } else {
871             for ident in single_imports.iter().cloned() {
872                 let result = self.resolve_ident_in_module(
873                     ModuleOrUniformRoot::Module(module),
874                     ident,
875                     MacroNS,
876                     None,
877                     false,
878                     ident.span,
879                 );
880                 if let Ok(binding) = result {
881                     let directive = macro_use_directive(ident.span);
882                     self.potentially_unused_imports.push(directive);
883                     let imported_binding = self.import(binding, directive);
884                     self.legacy_import_macro(ident.name, imported_binding,
885                                              ident.span, allow_shadowing);
886                 } else {
887                     span_err!(self.session, ident.span, E0469, "imported macro not found");
888                 }
889             }
890         }
891         import_all.is_some() || !single_imports.is_empty()
892     }
893
894     /// Returns `true` if this attribute list contains `macro_use`.
895     fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool {
896         for attr in attrs {
897             if attr.check_name(sym::macro_escape) {
898                 let msg = "macro_escape is a deprecated synonym for macro_use";
899                 let mut err = self.session.struct_span_warn(attr.span, msg);
900                 if let ast::AttrStyle::Inner = attr.style {
901                     err.help("consider an outer attribute, `#[macro_use]` mod ...").emit();
902                 } else {
903                     err.emit();
904                 }
905             } else if !attr.check_name(sym::macro_use) {
906                 continue;
907             }
908
909             if !attr.is_word() {
910                 self.session.span_err(attr.span, "arguments to macro_use are not allowed here");
911             }
912             return true;
913         }
914
915         false
916     }
917 }
918
919 pub struct BuildReducedGraphVisitor<'a, 'b> {
920     pub resolver: &'a mut Resolver<'b>,
921     pub current_legacy_scope: LegacyScope<'b>,
922     pub expansion: ExpnId,
923 }
924
925 impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
926     fn visit_invoc(&mut self, id: ast::NodeId) -> &'b InvocationData<'b> {
927         let invoc_id = id.placeholder_to_expn_id();
928
929         self.resolver.current_module.unresolved_invocations.borrow_mut().insert(invoc_id);
930
931         let invocation_data = self.resolver.arenas.alloc_invocation_data(InvocationData {
932             module: self.resolver.current_module,
933             parent_legacy_scope: self.current_legacy_scope,
934             output_legacy_scope: Cell::new(None),
935         });
936         let old_invocation_data = self.resolver.invocations.insert(invoc_id, invocation_data);
937         assert!(old_invocation_data.is_none(), "invocation data is reset for an invocation");
938
939         invocation_data
940     }
941 }
942
943 macro_rules! method {
944     ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
945         fn $visit(&mut self, node: &'a $ty) {
946             if let $invoc(..) = node.node {
947                 self.visit_invoc(node.id);
948             } else {
949                 visit::$walk(self, node);
950             }
951         }
952     }
953 }
954
955 impl<'a, 'b> Visitor<'a> for BuildReducedGraphVisitor<'a, 'b> {
956     method!(visit_impl_item: ast::ImplItem, ast::ImplItemKind::Macro, walk_impl_item);
957     method!(visit_expr:      ast::Expr,     ast::ExprKind::Mac,       walk_expr);
958     method!(visit_pat:       ast::Pat,      ast::PatKind::Mac,        walk_pat);
959     method!(visit_ty:        ast::Ty,       ast::TyKind::Mac,         walk_ty);
960
961     fn visit_item(&mut self, item: &'a Item) {
962         let macro_use = match item.node {
963             ItemKind::MacroDef(..) => {
964                 self.resolver.define_macro(item, self.expansion, &mut self.current_legacy_scope);
965                 return
966             }
967             ItemKind::Mac(..) => {
968                 self.current_legacy_scope = LegacyScope::Invocation(self.visit_invoc(item.id));
969                 return
970             }
971             ItemKind::Mod(..) => self.resolver.contains_macro_use(&item.attrs),
972             _ => false,
973         };
974
975         let orig_current_module = self.resolver.current_module;
976         let orig_current_legacy_scope = self.current_legacy_scope;
977         let parent_scope = ParentScope {
978             module: self.resolver.current_module,
979             expansion: self.expansion,
980             legacy: self.current_legacy_scope,
981             derives: Vec::new(),
982         };
983         self.resolver.build_reduced_graph_for_item(item, parent_scope);
984         visit::walk_item(self, item);
985         self.resolver.current_module = orig_current_module;
986         if !macro_use {
987             self.current_legacy_scope = orig_current_legacy_scope;
988         }
989     }
990
991     fn visit_stmt(&mut self, stmt: &'a ast::Stmt) {
992         if let ast::StmtKind::Mac(..) = stmt.node {
993             self.current_legacy_scope = LegacyScope::Invocation(self.visit_invoc(stmt.id));
994         } else {
995             visit::walk_stmt(self, stmt);
996         }
997     }
998
999     fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
1000         if let ForeignItemKind::Macro(_) = foreign_item.node {
1001             self.visit_invoc(foreign_item.id);
1002             return;
1003         }
1004
1005         self.resolver.build_reduced_graph_for_foreign_item(foreign_item, self.expansion);
1006         visit::walk_foreign_item(self, foreign_item);
1007     }
1008
1009     fn visit_block(&mut self, block: &'a Block) {
1010         let orig_current_module = self.resolver.current_module;
1011         let orig_current_legacy_scope = self.current_legacy_scope;
1012         self.resolver.build_reduced_graph_for_block(block, self.expansion);
1013         visit::walk_block(self, block);
1014         self.resolver.current_module = orig_current_module;
1015         self.current_legacy_scope = orig_current_legacy_scope;
1016     }
1017
1018     fn visit_trait_item(&mut self, item: &'a TraitItem) {
1019         let parent = self.resolver.current_module;
1020
1021         if let TraitItemKind::Macro(_) = item.node {
1022             self.visit_invoc(item.id);
1023             return
1024         }
1025
1026         // Add the item to the trait info.
1027         let item_def_id = self.resolver.definitions.local_def_id(item.id);
1028         let (res, ns) = match item.node {
1029             TraitItemKind::Const(..) => (Res::Def(DefKind::AssocConst, item_def_id), ValueNS),
1030             TraitItemKind::Method(ref sig, _) => {
1031                 if sig.decl.has_self() {
1032                     self.resolver.has_self.insert(item_def_id);
1033                 }
1034                 (Res::Def(DefKind::Method, item_def_id), ValueNS)
1035             }
1036             TraitItemKind::Type(..) => (Res::Def(DefKind::AssocTy, item_def_id), TypeNS),
1037             TraitItemKind::Macro(_) => bug!(),  // handled above
1038         };
1039
1040         let vis = ty::Visibility::Public;
1041         self.resolver.define(parent, item.ident, ns, (res, vis, item.span, self.expansion));
1042
1043         self.resolver.current_module = parent.parent.unwrap(); // nearest normal ancestor
1044         visit::walk_trait_item(self, item);
1045         self.resolver.current_module = parent;
1046     }
1047
1048     fn visit_token(&mut self, t: Token) {
1049         if let token::Interpolated(nt) = t.kind {
1050             if let token::NtExpr(ref expr) = *nt {
1051                 if let ast::ExprKind::Mac(..) = expr.node {
1052                     self.visit_invoc(expr.id);
1053                 }
1054             }
1055         }
1056     }
1057
1058     fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1059         if !attr.is_sugared_doc && is_builtin_attr(attr) {
1060             let parent_scope = ParentScope {
1061                 module: self.resolver.current_module.nearest_item_scope(),
1062                 expansion: self.expansion,
1063                 legacy: self.current_legacy_scope,
1064                 // Let's hope discerning built-in attributes from derive helpers is not necessary
1065                 derives: Vec::new(),
1066             };
1067             parent_scope.module.builtin_attrs.borrow_mut().push((
1068                 attr.path.segments[0].ident, parent_scope
1069             ));
1070         }
1071         visit::walk_attribute(self, attr);
1072     }
1073 }