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