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