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