]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/build_reduced_graph.rs
Auto merge of #52997 - llogiq:tiny-list-opt, r=varkor
[rust.git] / src / librustc_resolve / build_reduced_graph.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Reduced graph building
12 //!
13 //! Here we build the "reduced graph": the graph of the module tree without
14 //! any imports resolved.
15
16 use macros::{InvocationData, LegacyScope};
17 use resolve_imports::ImportDirective;
18 use resolve_imports::ImportDirectiveSubclass::{self, GlobImport, SingleImport};
19 use {Module, ModuleData, ModuleKind, NameBinding, NameBindingKind, ToNameBinding};
20 use {PerNS, Resolver, ResolverArenas};
21 use Namespace::{self, TypeNS, ValueNS, MacroNS};
22 use {resolve_error, resolve_struct_error, ResolutionError};
23
24 use rustc::hir::def::*;
25 use rustc::hir::def_id::{BUILTIN_MACROS_CRATE, CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
26 use rustc::ty;
27 use rustc::middle::cstore::CrateStore;
28 use rustc_metadata::cstore::LoadedMacro;
29
30 use std::cell::Cell;
31 use rustc_data_structures::sync::Lrc;
32
33 use syntax::ast::{Name, Ident};
34 use syntax::attr;
35
36 use syntax::ast::{self, Block, ForeignItem, ForeignItemKind, Item, ItemKind, NodeId};
37 use syntax::ast::{Mutability, StmtKind, TraitItem, TraitItemKind, Variant};
38 use syntax::ext::base::{MacroKind, SyntaxExtension};
39 use syntax::ext::base::Determinacy::Undetermined;
40 use syntax::ext::hygiene::Mark;
41 use syntax::ext::tt::macro_rules;
42 use syntax::parse::token::{self, Token};
43 use syntax::std_inject::injected_crate_name;
44 use syntax::symbol::keywords;
45 use syntax::visit::{self, Visitor};
46
47 use syntax_pos::{Span, DUMMY_SP};
48
49 impl<'a> ToNameBinding<'a> for (Module<'a>, ty::Visibility, Span, Mark) {
50     fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
51         arenas.alloc_name_binding(NameBinding {
52             kind: NameBindingKind::Module(self.0),
53             vis: self.1,
54             span: self.2,
55             expansion: self.3,
56         })
57     }
58 }
59
60 impl<'a> ToNameBinding<'a> for (Def, ty::Visibility, Span, Mark) {
61     fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
62         arenas.alloc_name_binding(NameBinding {
63             kind: NameBindingKind::Def(self.0, false),
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 (Def, ty::Visibility, Span, Mark, IsMacroExport) {
74     fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
75         arenas.alloc_name_binding(NameBinding {
76             kind: NameBindingKind::Def(self.0, true),
77             vis: self.1,
78             span: self.2,
79             expansion: self.3,
80         })
81     }
82 }
83
84 #[derive(Default, PartialEq, Eq)]
85 struct LegacyMacroImports {
86     import_all: Option<Span>,
87     imports: Vec<(Name, Span)>,
88 }
89
90 impl<'a, 'cl> Resolver<'a, 'cl> {
91     /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
92     /// otherwise, reports an error.
93     pub fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T)
94         where T: ToNameBinding<'a>,
95     {
96         let binding = def.to_name_binding(self.arenas);
97         if let Err(old_binding) = self.try_define(parent, ident, ns, binding) {
98             self.report_conflict(parent, ident, ns, old_binding, &binding);
99         }
100     }
101
102     fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
103         // If any statements are items, we need to create an anonymous module
104         block.stmts.iter().any(|statement| match statement.node {
105             StmtKind::Item(_) | StmtKind::Mac(_) => true,
106             _ => false,
107         })
108     }
109
110     fn insert_field_names(&mut self, def_id: DefId, field_names: Vec<Name>) {
111         if !field_names.is_empty() {
112             self.field_names.insert(def_id, field_names);
113         }
114     }
115
116     fn build_reduced_graph_for_use_tree(&mut self,
117                                         root_use_tree: &ast::UseTree,
118                                         root_id: NodeId,
119                                         use_tree: &ast::UseTree,
120                                         id: NodeId,
121                                         vis: ty::Visibility,
122                                         prefix: &ast::Path,
123                                         nested: bool,
124                                         item: &Item,
125                                         expansion: Mark) {
126         let is_prelude = attr::contains_name(&item.attrs, "prelude_import");
127         let path = &use_tree.prefix;
128
129         let mut module_path: Vec<_> = prefix.segments.iter()
130             .chain(path.segments.iter())
131             .map(|seg| seg.ident)
132             .collect();
133
134         match use_tree.kind {
135             ast::UseTreeKind::Simple(rename, ..) => {
136                 let mut ident = use_tree.ident();
137                 let mut source = module_path.pop().unwrap();
138                 let mut type_ns_only = false;
139
140                 if nested {
141                     // Correctly handle `self`
142                     if source.name == keywords::SelfValue.name() {
143                         type_ns_only = true;
144
145                         let last_segment = *module_path.last().unwrap();
146                         if last_segment.name == keywords::CrateRoot.name() {
147                             resolve_error(
148                                 self,
149                                 use_tree.span,
150                                 ResolutionError::
151                                 SelfImportOnlyInImportListWithNonEmptyPrefix
152                             );
153                             return;
154                         }
155
156                         // Replace `use foo::self;` with `use foo;`
157                         let _ = module_path.pop();
158                         source = last_segment;
159                         if rename.is_none() {
160                             ident = last_segment;
161                         }
162                     }
163                 } else {
164                     // Disallow `self`
165                     if source.name == keywords::SelfValue.name() {
166                         resolve_error(self,
167                                       use_tree.span,
168                                       ResolutionError::SelfImportsOnlyAllowedWithin);
169                     }
170
171                     // Disallow `use $crate;`
172                     if source.name == keywords::DollarCrate.name() && path.segments.len() == 1 {
173                         let crate_root = self.resolve_crate_root(source);
174                         let crate_name = match crate_root.kind {
175                             ModuleKind::Def(_, name) => name,
176                             ModuleKind::Block(..) => unreachable!(),
177                         };
178                         source.name = crate_name;
179                         if rename.is_none() {
180                             ident.name = crate_name;
181                         }
182
183                         self.session.struct_span_warn(item.span, "`$crate` may not be imported")
184                             .note("`use $crate;` was erroneously allowed and \
185                                    will become a hard error in a future release")
186                             .emit();
187                     }
188                 }
189
190                 let subclass = SingleImport {
191                     target: ident,
192                     source,
193                     result: PerNS {
194                         type_ns: Cell::new(Err(Undetermined)),
195                         value_ns: Cell::new(Err(Undetermined)),
196                         macro_ns: Cell::new(Err(Undetermined)),
197                     },
198                     type_ns_only,
199                 };
200                 self.add_import_directive(
201                     module_path,
202                     subclass,
203                     use_tree.span,
204                     id,
205                     root_use_tree.span,
206                     root_id,
207                     vis,
208                     expansion,
209                 );
210             }
211             ast::UseTreeKind::Glob => {
212                 let subclass = GlobImport {
213                     is_prelude,
214                     max_vis: Cell::new(ty::Visibility::Invisible),
215                 };
216                 self.add_import_directive(
217                     module_path,
218                     subclass,
219                     use_tree.span,
220                     id,
221                     root_use_tree.span,
222                     root_id,
223                     vis,
224                     expansion,
225                 );
226             }
227             ast::UseTreeKind::Nested(ref items) => {
228                 let prefix = ast::Path {
229                     segments: module_path.into_iter()
230                         .map(|ident| ast::PathSegment::from_ident(ident))
231                         .collect(),
232                     span: path.span,
233                 };
234
235                 // Ensure there is at most one `self` in the list
236                 let self_spans = items.iter().filter_map(|&(ref use_tree, _)| {
237                     if let ast::UseTreeKind::Simple(..) = use_tree.kind {
238                         if use_tree.ident().name == keywords::SelfValue.name() {
239                             return Some(use_tree.span);
240                         }
241                     }
242
243                     None
244                 }).collect::<Vec<_>>();
245                 if self_spans.len() > 1 {
246                     let mut e = resolve_struct_error(self,
247                         self_spans[0],
248                         ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
249
250                     for other_span in self_spans.iter().skip(1) {
251                         e.span_label(*other_span, "another `self` import appears here");
252                     }
253
254                     e.emit();
255                 }
256
257                 for &(ref tree, id) in items {
258                     self.build_reduced_graph_for_use_tree(
259                         root_use_tree, root_id, tree, id, vis, &prefix, true, item, expansion
260                     );
261                 }
262             }
263         }
264     }
265
266     /// Constructs the reduced graph for one item.
267     fn build_reduced_graph_for_item(&mut self, item: &Item, expansion: Mark) {
268         let parent = self.current_module;
269         let ident = item.ident;
270         let sp = item.span;
271         let vis = self.resolve_visibility(&item.vis);
272
273         match item.node {
274             ItemKind::Use(ref use_tree) => {
275                 // Imports are resolved as global by default, add starting root segment.
276                 let prefix = ast::Path {
277                     segments: use_tree.prefix.make_root().into_iter().collect(),
278                     span: use_tree.span,
279                 };
280
281                 self.build_reduced_graph_for_use_tree(
282                     use_tree, item.id, use_tree, item.id, vis, &prefix, false, item, expansion,
283                 );
284             }
285
286             ItemKind::ExternCrate(orig_name) => {
287                 let crate_id = self.crate_loader.process_extern_crate(item, &self.definitions);
288                 let module =
289                     self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
290                 self.populate_module_if_necessary(module);
291                 if injected_crate_name().map_or(false, |name| item.ident.name == name) {
292                     self.injected_crate = Some(module);
293                 }
294
295                 let used = self.process_legacy_macro_imports(item, module, expansion);
296                 let binding =
297                     (module, ty::Visibility::Public, sp, expansion).to_name_binding(self.arenas);
298                 let directive = self.arenas.alloc_import_directive(ImportDirective {
299                     root_id: item.id,
300                     id: item.id,
301                     parent,
302                     imported_module: Cell::new(Some(module)),
303                     subclass: ImportDirectiveSubclass::ExternCrate(orig_name),
304                     root_span: item.span,
305                     span: item.span,
306                     module_path: Vec::new(),
307                     vis: Cell::new(vis),
308                     expansion,
309                     used: Cell::new(used),
310                 });
311                 self.potentially_unused_imports.push(directive);
312                 let imported_binding = self.import(binding, directive);
313                 self.define(parent, ident, TypeNS, imported_binding);
314             }
315
316             ItemKind::GlobalAsm(..) => {}
317
318             ItemKind::Mod(..) if item.ident == keywords::Invalid.ident() => {} // Crate root
319
320             ItemKind::Mod(..) => {
321                 let def_id = self.definitions.local_def_id(item.id);
322                 let module_kind = ModuleKind::Def(Def::Mod(def_id), ident.name);
323                 let module = self.arenas.alloc_module(ModuleData {
324                     no_implicit_prelude: parent.no_implicit_prelude || {
325                         attr::contains_name(&item.attrs, "no_implicit_prelude")
326                     },
327                     ..ModuleData::new(Some(parent), module_kind, def_id, expansion, item.span)
328                 });
329                 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
330                 self.module_map.insert(def_id, module);
331
332                 // Descend into the module.
333                 self.current_module = module;
334             }
335
336             // Handled in `rustc_metadata::{native_libs,link_args}`
337             ItemKind::ForeignMod(..) => {}
338
339             // These items live in the value namespace.
340             ItemKind::Static(_, m, _) => {
341                 let mutbl = m == Mutability::Mutable;
342                 let def = Def::Static(self.definitions.local_def_id(item.id), mutbl);
343                 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
344             }
345             ItemKind::Const(..) => {
346                 let def = Def::Const(self.definitions.local_def_id(item.id));
347                 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
348             }
349             ItemKind::Fn(..) => {
350                 let def = Def::Fn(self.definitions.local_def_id(item.id));
351                 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
352
353                 // Functions introducing procedural macros reserve a slot
354                 // in the macro namespace as well (see #52225).
355                 if attr::contains_name(&item.attrs, "proc_macro") ||
356                    attr::contains_name(&item.attrs, "proc_macro_attribute") {
357                     let def = Def::Macro(def.def_id(), MacroKind::ProcMacroStub);
358                     self.define(parent, ident, MacroNS, (def, vis, sp, expansion));
359                 }
360                 if let Some(attr) = attr::find_by_name(&item.attrs, "proc_macro_derive") {
361                     if let Some(trait_attr) =
362                             attr.meta_item_list().and_then(|list| list.get(0).cloned()) {
363                         if let Some(ident) = trait_attr.name().map(Ident::with_empty_ctxt) {
364                             let sp = trait_attr.span;
365                             let def = Def::Macro(def.def_id(), MacroKind::ProcMacroStub);
366                             self.define(parent, ident, MacroNS, (def, vis, sp, expansion));
367                         }
368                     }
369                 }
370             }
371
372             // These items live in the type namespace.
373             ItemKind::Ty(..) => {
374                 let def = Def::TyAlias(self.definitions.local_def_id(item.id));
375                 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
376             }
377
378             ItemKind::Existential(_, _) => {
379                 let def = Def::Existential(self.definitions.local_def_id(item.id));
380                 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
381             }
382
383             ItemKind::Enum(ref enum_definition, _) => {
384                 let def = Def::Enum(self.definitions.local_def_id(item.id));
385                 let module_kind = ModuleKind::Def(def, ident.name);
386                 let module = self.new_module(parent,
387                                              module_kind,
388                                              parent.normal_ancestor_id,
389                                              expansion,
390                                              item.span);
391                 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
392
393                 for variant in &(*enum_definition).variants {
394                     self.build_reduced_graph_for_variant(variant, module, vis, expansion);
395                 }
396             }
397
398             ItemKind::TraitAlias(..) => {
399                 let def = Def::TraitAlias(self.definitions.local_def_id(item.id));
400                 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
401             }
402
403             // These items live in both the type and value namespaces.
404             ItemKind::Struct(ref struct_def, _) => {
405                 // Define a name in the type namespace.
406                 let def_id = self.definitions.local_def_id(item.id);
407                 let def = Def::Struct(def_id);
408                 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
409
410                 let mut ctor_vis = vis;
411
412                 let has_non_exhaustive = attr::contains_name(&item.attrs, "non_exhaustive");
413
414                 // If the structure is marked as non_exhaustive then lower the visibility
415                 // to within the crate.
416                 if has_non_exhaustive && vis == ty::Visibility::Public {
417                     ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
418                 }
419
420                 // Record field names for error reporting.
421                 let field_names = struct_def.fields().iter().filter_map(|field| {
422                     let field_vis = self.resolve_visibility(&field.vis);
423                     if ctor_vis.is_at_least(field_vis, &*self) {
424                         ctor_vis = field_vis;
425                     }
426                     field.ident.map(|ident| ident.name)
427                 }).collect();
428                 let item_def_id = self.definitions.local_def_id(item.id);
429                 self.insert_field_names(item_def_id, field_names);
430
431                 // If this is a tuple or unit struct, define a name
432                 // in the value namespace as well.
433                 if !struct_def.is_struct() {
434                     let ctor_def = Def::StructCtor(self.definitions.local_def_id(struct_def.id()),
435                                                    CtorKind::from_ast(struct_def));
436                     self.define(parent, ident, ValueNS, (ctor_def, ctor_vis, sp, expansion));
437                     self.struct_constructors.insert(def.def_id(), (ctor_def, ctor_vis));
438                 }
439             }
440
441             ItemKind::Union(ref vdata, _) => {
442                 let def = Def::Union(self.definitions.local_def_id(item.id));
443                 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
444
445                 // Record field names for error reporting.
446                 let field_names = vdata.fields().iter().filter_map(|field| {
447                     self.resolve_visibility(&field.vis);
448                     field.ident.map(|ident| ident.name)
449                 }).collect();
450                 let item_def_id = self.definitions.local_def_id(item.id);
451                 self.insert_field_names(item_def_id, field_names);
452             }
453
454             ItemKind::Impl(..) => {}
455
456             ItemKind::Trait(..) => {
457                 let def_id = self.definitions.local_def_id(item.id);
458
459                 // Add all the items within to a new module.
460                 let module_kind = ModuleKind::Def(Def::Trait(def_id), ident.name);
461                 let module = self.new_module(parent,
462                                              module_kind,
463                                              parent.normal_ancestor_id,
464                                              expansion,
465                                              item.span);
466                 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
467                 self.current_module = module;
468             }
469
470             ItemKind::MacroDef(..) | ItemKind::Mac(_) => unreachable!(),
471         }
472     }
473
474     // Constructs the reduced graph for one variant. Variants exist in the
475     // type and value namespaces.
476     fn build_reduced_graph_for_variant(&mut self,
477                                        variant: &Variant,
478                                        parent: Module<'a>,
479                                        vis: ty::Visibility,
480                                        expansion: Mark) {
481         let ident = variant.node.ident;
482         let def_id = self.definitions.local_def_id(variant.node.data.id());
483
484         // Define a name in the type namespace.
485         let def = Def::Variant(def_id);
486         self.define(parent, ident, TypeNS, (def, vis, variant.span, expansion));
487
488         // Define a constructor name in the value namespace.
489         // Braced variants, unlike structs, generate unusable names in
490         // value namespace, they are reserved for possible future use.
491         let ctor_kind = CtorKind::from_ast(&variant.node.data);
492         let ctor_def = Def::VariantCtor(def_id, ctor_kind);
493
494         self.define(parent, ident, ValueNS, (ctor_def, vis, variant.span, expansion));
495     }
496
497     /// Constructs the reduced graph for one foreign item.
498     fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem, expansion: Mark) {
499         let (def, ns) = match item.node {
500             ForeignItemKind::Fn(..) => {
501                 (Def::Fn(self.definitions.local_def_id(item.id)), ValueNS)
502             }
503             ForeignItemKind::Static(_, m) => {
504                 (Def::Static(self.definitions.local_def_id(item.id), m), ValueNS)
505             }
506             ForeignItemKind::Ty => {
507                 (Def::TyForeign(self.definitions.local_def_id(item.id)), TypeNS)
508             }
509             ForeignItemKind::Macro(_) => unreachable!(),
510         };
511         let parent = self.current_module;
512         let vis = self.resolve_visibility(&item.vis);
513         self.define(parent, item.ident, ns, (def, vis, item.span, expansion));
514     }
515
516     fn build_reduced_graph_for_block(&mut self, block: &Block, expansion: Mark) {
517         let parent = self.current_module;
518         if self.block_needs_anonymous_module(block) {
519             let module = self.new_module(parent,
520                                          ModuleKind::Block(block.id),
521                                          parent.normal_ancestor_id,
522                                          expansion,
523                                          block.span);
524             self.block_map.insert(block.id, module);
525             self.current_module = module; // Descend into the block.
526         }
527     }
528
529     /// Builds the reduced graph for a single item in an external crate.
530     fn build_reduced_graph_for_external_crate_def(&mut self, parent: Module<'a>, child: Export) {
531         let Export { ident, def, vis, span, .. } = child;
532         let def_id = def.def_id();
533         let expansion = Mark::root(); // FIXME(jseyfried) intercrate hygiene
534         match def {
535             Def::Mod(..) | Def::Enum(..) => {
536                 let module = self.new_module(parent,
537                                              ModuleKind::Def(def, ident.name),
538                                              def_id,
539                                              expansion,
540                                              span);
541                 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
542             }
543             Def::Variant(..) | Def::TyAlias(..) | Def::TyForeign(..) => {
544                 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
545             }
546             Def::Fn(..) | Def::Static(..) | Def::Const(..) | Def::VariantCtor(..) => {
547                 self.define(parent, ident, ValueNS, (def, vis, DUMMY_SP, expansion));
548             }
549             Def::StructCtor(..) => {
550                 self.define(parent, ident, ValueNS, (def, vis, DUMMY_SP, expansion));
551
552                 if let Some(struct_def_id) =
553                         self.cstore.def_key(def_id).parent
554                             .map(|index| DefId { krate: def_id.krate, index: index }) {
555                     self.struct_constructors.insert(struct_def_id, (def, vis));
556                 }
557             }
558             Def::Trait(..) => {
559                 let module_kind = ModuleKind::Def(def, ident.name);
560                 let module = self.new_module(parent,
561                                              module_kind,
562                                              parent.normal_ancestor_id,
563                                              expansion,
564                                              span);
565                 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
566
567                 for child in self.cstore.item_children_untracked(def_id, self.session) {
568                     let ns = if let Def::AssociatedTy(..) = child.def { TypeNS } else { ValueNS };
569                     self.define(module, child.ident, ns,
570                                 (child.def, ty::Visibility::Public, DUMMY_SP, expansion));
571
572                     if self.cstore.associated_item_cloned_untracked(child.def.def_id())
573                            .method_has_self_argument {
574                         self.has_self.insert(child.def.def_id());
575                     }
576                 }
577                 module.populated.set(true);
578             }
579             Def::Struct(..) | Def::Union(..) => {
580                 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
581
582                 // Record field names for error reporting.
583                 let field_names = self.cstore.struct_field_names_untracked(def_id);
584                 self.insert_field_names(def_id, field_names);
585             }
586             Def::Macro(..) => {
587                 self.define(parent, ident, MacroNS, (def, vis, DUMMY_SP, expansion));
588             }
589             _ => bug!("unexpected definition: {:?}", def)
590         }
591     }
592
593     pub fn get_module(&mut self, def_id: DefId) -> Module<'a> {
594         if def_id.krate == LOCAL_CRATE {
595             return self.module_map[&def_id]
596         }
597
598         let macros_only = self.cstore.dep_kind_untracked(def_id.krate).macros_only();
599         if let Some(&module) = self.extern_module_map.get(&(def_id, macros_only)) {
600             return module;
601         }
602
603         let (name, parent) = if def_id.index == CRATE_DEF_INDEX {
604             (self.cstore.crate_name_untracked(def_id.krate).as_interned_str(), None)
605         } else {
606             let def_key = self.cstore.def_key(def_id);
607             (def_key.disambiguated_data.data.get_opt_name().unwrap(),
608              Some(self.get_module(DefId { index: def_key.parent.unwrap(), ..def_id })))
609         };
610
611         let kind = ModuleKind::Def(Def::Mod(def_id), name.as_symbol());
612         let module =
613             self.arenas.alloc_module(ModuleData::new(parent, kind, def_id, Mark::root(), DUMMY_SP));
614         self.extern_module_map.insert((def_id, macros_only), module);
615         module
616     }
617
618     pub fn macro_def_scope(&mut self, expansion: Mark) -> Module<'a> {
619         let def_id = self.macro_defs[&expansion];
620         if let Some(id) = self.definitions.as_local_node_id(def_id) {
621             self.local_macro_def_scopes[&id]
622         } else if def_id.krate == BUILTIN_MACROS_CRATE {
623             self.injected_crate.unwrap_or(self.graph_root)
624         } else {
625             let module_def_id = ty::DefIdTree::parent(&*self, def_id).unwrap();
626             self.get_module(module_def_id)
627         }
628     }
629
630     pub fn get_macro(&mut self, def: Def) -> Lrc<SyntaxExtension> {
631         let def_id = match def {
632             Def::Macro(def_id, ..) => def_id,
633             Def::NonMacroAttr => return Lrc::new(SyntaxExtension::NonMacroAttr),
634             _ => panic!("Expected Def::Macro(..) or Def::NonMacroAttr"),
635         };
636         if let Some(ext) = self.macro_map.get(&def_id) {
637             return ext.clone();
638         }
639
640         let macro_def = match self.cstore.load_macro_untracked(def_id, &self.session) {
641             LoadedMacro::MacroDef(macro_def) => macro_def,
642             LoadedMacro::ProcMacro(ext) => return ext,
643         };
644
645         let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
646                                                &self.session.features_untracked(),
647                                                &macro_def,
648                                                self.cstore.crate_edition_untracked(def_id.krate)));
649         self.macro_map.insert(def_id, ext.clone());
650         ext
651     }
652
653     /// Ensures that the reduced graph rooted at the given external module
654     /// is built, building it if it is not.
655     pub fn populate_module_if_necessary(&mut self, module: Module<'a>) {
656         if module.populated.get() { return }
657         let def_id = module.def_id().unwrap();
658         for child in self.cstore.item_children_untracked(def_id, self.session) {
659             self.build_reduced_graph_for_external_crate_def(module, child);
660         }
661         module.populated.set(true)
662     }
663
664     fn legacy_import_macro(&mut self,
665                            name: Name,
666                            binding: &'a NameBinding<'a>,
667                            span: Span,
668                            allow_shadowing: bool) {
669         if self.macro_prelude.insert(name, binding).is_some() && !allow_shadowing {
670             let msg = format!("`{}` is already in scope", name);
671             let note =
672                 "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)";
673             self.session.struct_span_err(span, &msg).note(note).emit();
674         }
675     }
676
677     // This returns true if we should consider the underlying `extern crate` to be used.
678     fn process_legacy_macro_imports(&mut self, item: &Item, module: Module<'a>, expansion: Mark)
679                                     -> bool {
680         let allow_shadowing = expansion == Mark::root();
681         let legacy_imports = self.legacy_macro_imports(&item.attrs);
682         let mut used = legacy_imports != LegacyMacroImports::default();
683
684         // `#[macro_use]` is only allowed at the crate root.
685         if self.current_module.parent.is_some() && used {
686             span_err!(self.session, item.span, E0468,
687                       "an `extern crate` loading macros must be at the crate root");
688         } else if !self.use_extern_macros && !used &&
689                   self.cstore.dep_kind_untracked(module.def_id().unwrap().krate)
690                       .macros_only() {
691             let msg = "proc macro crates and `#[no_link]` crates have no effect without \
692                        `#[macro_use]`";
693             self.session.span_warn(item.span, msg);
694             used = true; // Avoid the normal unused extern crate warning
695         }
696
697         let (graph_root, arenas) = (self.graph_root, self.arenas);
698         let macro_use_directive = |span| arenas.alloc_import_directive(ImportDirective {
699             root_id: item.id,
700             id: item.id,
701             parent: graph_root,
702             imported_module: Cell::new(Some(module)),
703             subclass: ImportDirectiveSubclass::MacroUse,
704             root_span: span,
705             span,
706             module_path: Vec::new(),
707             vis: Cell::new(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))),
708             expansion,
709             used: Cell::new(false),
710         });
711
712         if let Some(span) = legacy_imports.import_all {
713             let directive = macro_use_directive(span);
714             self.potentially_unused_imports.push(directive);
715             module.for_each_child(|ident, ns, binding| if ns == MacroNS {
716                 let imported_binding = self.import(binding, directive);
717                 self.legacy_import_macro(ident.name, imported_binding, span, allow_shadowing);
718             });
719         } else {
720             for (name, span) in legacy_imports.imports {
721                 let ident = Ident::with_empty_ctxt(name);
722                 let result = self.resolve_ident_in_module(module, ident, MacroNS, false, span);
723                 if let Ok(binding) = result {
724                     let directive = macro_use_directive(span);
725                     self.potentially_unused_imports.push(directive);
726                     let imported_binding = self.import(binding, directive);
727                     self.legacy_import_macro(name, imported_binding, span, allow_shadowing);
728                 } else {
729                     span_err!(self.session, span, E0469, "imported macro not found");
730                 }
731             }
732         }
733         used
734     }
735
736     // does this attribute list contain "macro_use"?
737     fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool {
738         for attr in attrs {
739             if attr.check_name("macro_escape") {
740                 let msg = "macro_escape is a deprecated synonym for macro_use";
741                 let mut err = self.session.struct_span_warn(attr.span, msg);
742                 if let ast::AttrStyle::Inner = attr.style {
743                     err.help("consider an outer attribute, #[macro_use] mod ...").emit();
744                 } else {
745                     err.emit();
746                 }
747             } else if !attr.check_name("macro_use") {
748                 continue;
749             }
750
751             if !attr.is_word() {
752                 self.session.span_err(attr.span, "arguments to macro_use are not allowed here");
753             }
754             return true;
755         }
756
757         false
758     }
759
760     fn legacy_macro_imports(&mut self, attrs: &[ast::Attribute]) -> LegacyMacroImports {
761         let mut imports = LegacyMacroImports::default();
762         for attr in attrs {
763             if attr.check_name("macro_use") {
764                 match attr.meta_item_list() {
765                     Some(names) => for attr in names {
766                         if let Some(word) = attr.word() {
767                             imports.imports.push((word.name(), attr.span()));
768                         } else {
769                             span_err!(self.session, attr.span(), E0466, "bad macro import");
770                         }
771                     },
772                     None => imports.import_all = Some(attr.span),
773                 }
774             }
775         }
776         imports
777     }
778 }
779
780 pub struct BuildReducedGraphVisitor<'a, 'b: 'a, 'c: 'b> {
781     pub resolver: &'a mut Resolver<'b, 'c>,
782     pub legacy_scope: LegacyScope<'b>,
783     pub expansion: Mark,
784 }
785
786 impl<'a, 'b, 'cl> BuildReducedGraphVisitor<'a, 'b, 'cl> {
787     fn visit_invoc(&mut self, id: ast::NodeId) -> &'b InvocationData<'b> {
788         let mark = id.placeholder_to_mark();
789         self.resolver.current_module.unresolved_invocations.borrow_mut().insert(mark);
790         self.resolver.unresolved_invocations_macro_export.insert(mark);
791         let invocation = self.resolver.invocations[&mark];
792         invocation.module.set(self.resolver.current_module);
793         invocation.legacy_scope.set(self.legacy_scope);
794         invocation
795     }
796 }
797
798 macro_rules! method {
799     ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
800         fn $visit(&mut self, node: &'a $ty) {
801             if let $invoc(..) = node.node {
802                 self.visit_invoc(node.id);
803             } else {
804                 visit::$walk(self, node);
805             }
806         }
807     }
808 }
809
810 impl<'a, 'b, 'cl> Visitor<'a> for BuildReducedGraphVisitor<'a, 'b, 'cl> {
811     method!(visit_impl_item: ast::ImplItem, ast::ImplItemKind::Macro, walk_impl_item);
812     method!(visit_expr:      ast::Expr,     ast::ExprKind::Mac,       walk_expr);
813     method!(visit_pat:       ast::Pat,      ast::PatKind::Mac,        walk_pat);
814     method!(visit_ty:        ast::Ty,       ast::TyKind::Mac,         walk_ty);
815
816     fn visit_item(&mut self, item: &'a Item) {
817         let macro_use = match item.node {
818             ItemKind::MacroDef(..) => {
819                 self.resolver.define_macro(item, self.expansion, &mut self.legacy_scope);
820                 return
821             }
822             ItemKind::Mac(..) => {
823                 self.legacy_scope = LegacyScope::Expansion(self.visit_invoc(item.id));
824                 return
825             }
826             ItemKind::Mod(..) => self.resolver.contains_macro_use(&item.attrs),
827             _ => false,
828         };
829
830         let (parent, legacy_scope) = (self.resolver.current_module, self.legacy_scope);
831         self.resolver.build_reduced_graph_for_item(item, self.expansion);
832         visit::walk_item(self, item);
833         self.resolver.current_module = parent;
834         if !macro_use {
835             self.legacy_scope = legacy_scope;
836         }
837     }
838
839     fn visit_stmt(&mut self, stmt: &'a ast::Stmt) {
840         if let ast::StmtKind::Mac(..) = stmt.node {
841             self.legacy_scope = LegacyScope::Expansion(self.visit_invoc(stmt.id));
842         } else {
843             visit::walk_stmt(self, stmt);
844         }
845     }
846
847     fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
848         if let ForeignItemKind::Macro(_) = foreign_item.node {
849             self.visit_invoc(foreign_item.id);
850             return;
851         }
852
853         self.resolver.build_reduced_graph_for_foreign_item(foreign_item, self.expansion);
854         visit::walk_foreign_item(self, foreign_item);
855     }
856
857     fn visit_block(&mut self, block: &'a Block) {
858         let (parent, legacy_scope) = (self.resolver.current_module, self.legacy_scope);
859         self.resolver.build_reduced_graph_for_block(block, self.expansion);
860         visit::walk_block(self, block);
861         self.resolver.current_module = parent;
862         self.legacy_scope = legacy_scope;
863     }
864
865     fn visit_trait_item(&mut self, item: &'a TraitItem) {
866         let parent = self.resolver.current_module;
867
868         if let TraitItemKind::Macro(_) = item.node {
869             self.visit_invoc(item.id);
870             return
871         }
872
873         // Add the item to the trait info.
874         let item_def_id = self.resolver.definitions.local_def_id(item.id);
875         let (def, ns) = match item.node {
876             TraitItemKind::Const(..) => (Def::AssociatedConst(item_def_id), ValueNS),
877             TraitItemKind::Method(ref sig, _) => {
878                 if sig.decl.has_self() {
879                     self.resolver.has_self.insert(item_def_id);
880                 }
881                 (Def::Method(item_def_id), ValueNS)
882             }
883             TraitItemKind::Type(..) => (Def::AssociatedTy(item_def_id), TypeNS),
884             TraitItemKind::Macro(_) => bug!(),  // handled above
885         };
886
887         let vis = ty::Visibility::Public;
888         self.resolver.define(parent, item.ident, ns, (def, vis, item.span, self.expansion));
889
890         self.resolver.current_module = parent.parent.unwrap(); // nearest normal ancestor
891         visit::walk_trait_item(self, item);
892         self.resolver.current_module = parent;
893     }
894
895     fn visit_token(&mut self, t: Token) {
896         if let Token::Interpolated(nt) = t {
897             match nt.0 {
898                 token::NtExpr(ref expr) => {
899                     if let ast::ExprKind::Mac(..) = expr.node {
900                         self.visit_invoc(expr.id);
901                     }
902                 }
903                 _ => {}
904             }
905         }
906     }
907 }