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