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.
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.
11 //! Reduced graph building
13 //! Here we build the "reduced graph": the graph of the module tree without
14 //! any imports resolved.
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};
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};
30 use rustc_data_structures::sync::Lrc;
32 use syntax::ast::{Name, Ident};
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};
46 use syntax_pos::{Span, DUMMY_SP};
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),
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),
70 #[derive(Default, PartialEq, Eq)]
71 struct LegacyMacroImports {
72 import_all: Option<Span>,
73 imports: Vec<(Name, Span)>,
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>,
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);
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,
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);
102 fn build_reduced_graph_for_use_tree(&mut self,
103 root_use_tree: &ast::UseTree,
105 use_tree: &ast::UseTree,
112 let is_prelude = attr::contains_name(&item.attrs, "prelude_import");
113 let path = &use_tree.prefix;
115 let mut module_path: Vec<_> = prefix.segments.iter()
116 .chain(path.segments.iter())
117 .map(|seg| seg.ident)
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;
127 // Correctly handle `self`
128 if source.name == keywords::SelfValue.name() {
131 let last_segment = *module_path.last().unwrap();
132 if last_segment.name == keywords::CrateRoot.name() {
137 SelfImportOnlyInImportListWithNonEmptyPrefix
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;
151 if source.name == keywords::SelfValue.name() {
154 ResolutionError::SelfImportsOnlyAllowedWithin);
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!(),
164 source.name = crate_name;
165 if rename.is_none() {
166 ident.name = crate_name;
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")
176 let subclass = SingleImport {
180 type_ns: Cell::new(Err(Undetermined)),
181 value_ns: Cell::new(Err(Undetermined)),
182 macro_ns: Cell::new(Err(Undetermined)),
186 self.add_import_directive(
197 ast::UseTreeKind::Glob => {
198 let subclass = GlobImport {
200 max_vis: Cell::new(ty::Visibility::Invisible),
202 self.add_import_directive(
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))
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);
230 }).collect::<Vec<_>>();
231 if self_spans.len() > 1 {
232 let mut e = resolve_struct_error(self,
234 ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
236 for other_span in self_spans.iter().skip(1) {
237 e.span_label(*other_span, "another `self` import appears here");
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
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;
257 let vis = self.resolve_visibility(&item.vis);
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(),
267 self.build_reduced_graph_for_use_tree(
268 use_tree, item.id, use_tree, item.id, vis, &prefix, false, item, expansion,
272 ItemKind::ExternCrate(orig_name) => {
273 let crate_id = self.crate_loader.process_extern_crate(item, &self.definitions);
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);
281 let used = self.process_legacy_macro_imports(item, module, expansion);
283 (module, ty::Visibility::Public, sp, expansion).to_name_binding(self.arenas);
284 let directive = self.arenas.alloc_import_directive(ImportDirective {
288 imported_module: Cell::new(Some(module)),
289 subclass: ImportDirectiveSubclass::ExternCrate(orig_name),
290 root_span: item.span,
292 module_path: Vec::new(),
295 used: Cell::new(used),
297 self.potentially_unused_imports.push(directive);
298 let imported_binding = self.import(binding, directive);
299 self.define(parent, ident, TypeNS, imported_binding);
302 ItemKind::GlobalAsm(..) => {}
304 ItemKind::Mod(..) if item.ident == keywords::Invalid.ident() => {} // Crate root
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")
313 ..ModuleData::new(Some(parent), module_kind, def_id, expansion, item.span)
315 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
316 self.module_map.insert(def_id, module);
318 // Descend into the module.
319 self.current_module = module;
322 // Handled in `rustc_metadata::{native_libs,link_args}`
323 ItemKind::ForeignMod(..) => {}
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));
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));
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));
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));
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));
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));
364 ItemKind::Enum(ref enum_definition, _) => {
365 let def = Def::Enum(self.definitions.local_def_id(item.id));
366 let module_kind = ModuleKind::Def(def, ident.name);
367 let module = self.new_module(parent,
369 parent.normal_ancestor_id,
372 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
374 for variant in &(*enum_definition).variants {
375 self.build_reduced_graph_for_variant(variant, module, vis, expansion);
379 ItemKind::TraitAlias(..) => {
380 let def = Def::TraitAlias(self.definitions.local_def_id(item.id));
381 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
384 // These items live in both the type and value namespaces.
385 ItemKind::Struct(ref struct_def, _) => {
386 // Define a name in the type namespace.
387 let def_id = self.definitions.local_def_id(item.id);
388 let def = Def::Struct(def_id);
389 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
391 let mut ctor_vis = vis;
393 let has_non_exhaustive = attr::contains_name(&item.attrs, "non_exhaustive");
395 // If the structure is marked as non_exhaustive then lower the visibility
396 // to within the crate.
397 if has_non_exhaustive && vis == ty::Visibility::Public {
398 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
401 // Record field names for error reporting.
402 let field_names = struct_def.fields().iter().filter_map(|field| {
403 let field_vis = self.resolve_visibility(&field.vis);
404 if ctor_vis.is_at_least(field_vis, &*self) {
405 ctor_vis = field_vis;
407 field.ident.map(|ident| ident.name)
409 let item_def_id = self.definitions.local_def_id(item.id);
410 self.insert_field_names(item_def_id, field_names);
412 // If this is a tuple or unit struct, define a name
413 // in the value namespace as well.
414 if !struct_def.is_struct() {
415 let ctor_def = Def::StructCtor(self.definitions.local_def_id(struct_def.id()),
416 CtorKind::from_ast(struct_def));
417 self.define(parent, ident, ValueNS, (ctor_def, ctor_vis, sp, expansion));
418 self.struct_constructors.insert(def.def_id(), (ctor_def, ctor_vis));
422 ItemKind::Union(ref vdata, _) => {
423 let def = Def::Union(self.definitions.local_def_id(item.id));
424 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
426 // Record field names for error reporting.
427 let field_names = vdata.fields().iter().filter_map(|field| {
428 self.resolve_visibility(&field.vis);
429 field.ident.map(|ident| ident.name)
431 let item_def_id = self.definitions.local_def_id(item.id);
432 self.insert_field_names(item_def_id, field_names);
435 ItemKind::Impl(..) => {}
437 ItemKind::Trait(..) => {
438 let def_id = self.definitions.local_def_id(item.id);
440 // Add all the items within to a new module.
441 let module_kind = ModuleKind::Def(Def::Trait(def_id), ident.name);
442 let module = self.new_module(parent,
444 parent.normal_ancestor_id,
447 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
448 self.current_module = module;
451 ItemKind::MacroDef(..) | ItemKind::Mac(_) => unreachable!(),
455 // Constructs the reduced graph for one variant. Variants exist in the
456 // type and value namespaces.
457 fn build_reduced_graph_for_variant(&mut self,
462 let ident = variant.node.ident;
463 let def_id = self.definitions.local_def_id(variant.node.data.id());
465 // Define a name in the type namespace.
466 let def = Def::Variant(def_id);
467 self.define(parent, ident, TypeNS, (def, vis, variant.span, expansion));
469 // Define a constructor name in the value namespace.
470 // Braced variants, unlike structs, generate unusable names in
471 // value namespace, they are reserved for possible future use.
472 let ctor_kind = CtorKind::from_ast(&variant.node.data);
473 let ctor_def = Def::VariantCtor(def_id, ctor_kind);
475 self.define(parent, ident, ValueNS, (ctor_def, vis, variant.span, expansion));
478 /// Constructs the reduced graph for one foreign item.
479 fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem, expansion: Mark) {
480 let (def, ns) = match item.node {
481 ForeignItemKind::Fn(..) => {
482 (Def::Fn(self.definitions.local_def_id(item.id)), ValueNS)
484 ForeignItemKind::Static(_, m) => {
485 (Def::Static(self.definitions.local_def_id(item.id), m), ValueNS)
487 ForeignItemKind::Ty => {
488 (Def::TyForeign(self.definitions.local_def_id(item.id)), TypeNS)
490 ForeignItemKind::Macro(_) => unreachable!(),
492 let parent = self.current_module;
493 let vis = self.resolve_visibility(&item.vis);
494 self.define(parent, item.ident, ns, (def, vis, item.span, expansion));
497 fn build_reduced_graph_for_block(&mut self, block: &Block, expansion: Mark) {
498 let parent = self.current_module;
499 if self.block_needs_anonymous_module(block) {
500 let module = self.new_module(parent,
501 ModuleKind::Block(block.id),
502 parent.normal_ancestor_id,
505 self.block_map.insert(block.id, module);
506 self.current_module = module; // Descend into the block.
510 /// Builds the reduced graph for a single item in an external crate.
511 fn build_reduced_graph_for_external_crate_def(&mut self, parent: Module<'a>, child: Export) {
512 let Export { ident, def, vis, span, .. } = child;
513 let def_id = def.def_id();
514 let expansion = Mark::root(); // FIXME(jseyfried) intercrate hygiene
516 Def::Mod(..) | Def::Enum(..) => {
517 let module = self.new_module(parent,
518 ModuleKind::Def(def, ident.name),
522 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
524 Def::Variant(..) | Def::TyAlias(..) | Def::TyForeign(..) => {
525 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
527 Def::Fn(..) | Def::Static(..) | Def::Const(..) | Def::VariantCtor(..) => {
528 self.define(parent, ident, ValueNS, (def, vis, DUMMY_SP, expansion));
530 Def::StructCtor(..) => {
531 self.define(parent, ident, ValueNS, (def, vis, DUMMY_SP, expansion));
533 if let Some(struct_def_id) =
534 self.cstore.def_key(def_id).parent
535 .map(|index| DefId { krate: def_id.krate, index: index }) {
536 self.struct_constructors.insert(struct_def_id, (def, vis));
540 let module_kind = ModuleKind::Def(def, ident.name);
541 let module = self.new_module(parent,
543 parent.normal_ancestor_id,
546 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
548 for child in self.cstore.item_children_untracked(def_id, self.session) {
549 let ns = if let Def::AssociatedTy(..) = child.def { TypeNS } else { ValueNS };
550 self.define(module, child.ident, ns,
551 (child.def, ty::Visibility::Public, DUMMY_SP, expansion));
553 if self.cstore.associated_item_cloned_untracked(child.def.def_id())
554 .method_has_self_argument {
555 self.has_self.insert(child.def.def_id());
558 module.populated.set(true);
560 Def::Struct(..) | Def::Union(..) => {
561 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
563 // Record field names for error reporting.
564 let field_names = self.cstore.struct_field_names_untracked(def_id);
565 self.insert_field_names(def_id, field_names);
568 self.define(parent, ident, MacroNS, (def, vis, DUMMY_SP, expansion));
570 _ => bug!("unexpected definition: {:?}", def)
574 pub fn get_module(&mut self, def_id: DefId) -> Module<'a> {
575 if def_id.krate == LOCAL_CRATE {
576 return self.module_map[&def_id]
579 let macros_only = self.cstore.dep_kind_untracked(def_id.krate).macros_only();
580 if let Some(&module) = self.extern_module_map.get(&(def_id, macros_only)) {
584 let (name, parent) = if def_id.index == CRATE_DEF_INDEX {
585 (self.cstore.crate_name_untracked(def_id.krate).as_interned_str(), None)
587 let def_key = self.cstore.def_key(def_id);
588 (def_key.disambiguated_data.data.get_opt_name().unwrap(),
589 Some(self.get_module(DefId { index: def_key.parent.unwrap(), ..def_id })))
592 let kind = ModuleKind::Def(Def::Mod(def_id), name.as_symbol());
594 self.arenas.alloc_module(ModuleData::new(parent, kind, def_id, Mark::root(), DUMMY_SP));
595 self.extern_module_map.insert((def_id, macros_only), module);
599 pub fn macro_def_scope(&mut self, expansion: Mark) -> Module<'a> {
600 let def_id = self.macro_defs[&expansion];
601 if let Some(id) = self.definitions.as_local_node_id(def_id) {
602 self.local_macro_def_scopes[&id]
603 } else if def_id.krate == BUILTIN_MACROS_CRATE {
604 self.injected_crate.unwrap_or(self.graph_root)
606 let module_def_id = ty::DefIdTree::parent(&*self, def_id).unwrap();
607 self.get_module(module_def_id)
611 pub fn get_macro(&mut self, def: Def) -> Lrc<SyntaxExtension> {
612 let def_id = match def {
613 Def::Macro(def_id, ..) => def_id,
614 _ => panic!("Expected Def::Macro(..)"),
616 if let Some(ext) = self.macro_map.get(&def_id) {
620 let macro_def = match self.cstore.load_macro_untracked(def_id, &self.session) {
621 LoadedMacro::MacroDef(macro_def) => macro_def,
622 LoadedMacro::ProcMacro(ext) => return ext,
625 let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
626 &self.session.features_untracked(),
628 self.cstore.crate_edition_untracked(def_id.krate)));
629 self.macro_map.insert(def_id, ext.clone());
633 /// Ensures that the reduced graph rooted at the given external module
634 /// is built, building it if it is not.
635 pub fn populate_module_if_necessary(&mut self, module: Module<'a>) {
636 if module.populated.get() { return }
637 let def_id = module.def_id().unwrap();
638 for child in self.cstore.item_children_untracked(def_id, self.session) {
639 self.build_reduced_graph_for_external_crate_def(module, child);
641 module.populated.set(true)
644 fn legacy_import_macro(&mut self,
646 binding: &'a NameBinding<'a>,
648 allow_shadowing: bool) {
649 if self.global_macros.insert(name, binding).is_some() && !allow_shadowing {
650 let msg = format!("`{}` is already in scope", name);
652 "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)";
653 self.session.struct_span_err(span, &msg).note(note).emit();
657 // This returns true if we should consider the underlying `extern crate` to be used.
658 fn process_legacy_macro_imports(&mut self, item: &Item, module: Module<'a>, expansion: Mark)
660 let allow_shadowing = expansion == Mark::root();
661 let legacy_imports = self.legacy_macro_imports(&item.attrs);
662 let mut used = legacy_imports != LegacyMacroImports::default();
664 // `#[macro_use]` is only allowed at the crate root.
665 if self.current_module.parent.is_some() && used {
666 span_err!(self.session, item.span, E0468,
667 "an `extern crate` loading macros must be at the crate root");
668 } else if !self.use_extern_macros && !used &&
669 self.cstore.dep_kind_untracked(module.def_id().unwrap().krate)
671 let msg = "proc macro crates and `#[no_link]` crates have no effect without \
673 self.session.span_warn(item.span, msg);
674 used = true; // Avoid the normal unused extern crate warning
677 let (graph_root, arenas) = (self.graph_root, self.arenas);
678 let macro_use_directive = |span| arenas.alloc_import_directive(ImportDirective {
682 imported_module: Cell::new(Some(module)),
683 subclass: ImportDirectiveSubclass::MacroUse,
686 module_path: Vec::new(),
687 vis: Cell::new(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))),
689 used: Cell::new(false),
692 if let Some(span) = legacy_imports.import_all {
693 let directive = macro_use_directive(span);
694 self.potentially_unused_imports.push(directive);
695 module.for_each_child(|ident, ns, binding| if ns == MacroNS {
696 let imported_binding = self.import(binding, directive);
697 self.legacy_import_macro(ident.name, imported_binding, span, allow_shadowing);
700 for (name, span) in legacy_imports.imports {
701 let ident = Ident::with_empty_ctxt(name);
702 let result = self.resolve_ident_in_module(module, ident, MacroNS,
704 if let Ok(binding) = result {
705 let directive = macro_use_directive(span);
706 self.potentially_unused_imports.push(directive);
707 let imported_binding = self.import(binding, directive);
708 self.legacy_import_macro(name, imported_binding, span, allow_shadowing);
710 span_err!(self.session, span, E0469, "imported macro not found");
717 // does this attribute list contain "macro_use"?
718 fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool {
720 if attr.check_name("macro_escape") {
721 let msg = "macro_escape is a deprecated synonym for macro_use";
722 let mut err = self.session.struct_span_warn(attr.span, msg);
723 if let ast::AttrStyle::Inner = attr.style {
724 err.help("consider an outer attribute, #[macro_use] mod ...").emit();
728 } else if !attr.check_name("macro_use") {
733 self.session.span_err(attr.span, "arguments to macro_use are not allowed here");
741 fn legacy_macro_imports(&mut self, attrs: &[ast::Attribute]) -> LegacyMacroImports {
742 let mut imports = LegacyMacroImports::default();
744 if attr.check_name("macro_use") {
745 match attr.meta_item_list() {
746 Some(names) => for attr in names {
747 if let Some(word) = attr.word() {
748 imports.imports.push((word.name(), attr.span()));
750 span_err!(self.session, attr.span(), E0466, "bad macro import");
753 None => imports.import_all = Some(attr.span),
761 pub struct BuildReducedGraphVisitor<'a, 'b: 'a> {
762 pub resolver: &'a mut Resolver<'b>,
763 pub legacy_scope: LegacyScope<'b>,
767 impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
768 fn visit_invoc(&mut self, id: ast::NodeId) -> &'b InvocationData<'b> {
769 let mark = id.placeholder_to_mark();
770 self.resolver.current_module.unresolved_invocations.borrow_mut().insert(mark);
771 let invocation = self.resolver.invocations[&mark];
772 invocation.module.set(self.resolver.current_module);
773 invocation.legacy_scope.set(self.legacy_scope);
778 macro_rules! method {
779 ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
780 fn $visit(&mut self, node: &'a $ty) {
781 if let $invoc(..) = node.node {
782 self.visit_invoc(node.id);
784 visit::$walk(self, node);
790 impl<'a, 'b> Visitor<'a> for BuildReducedGraphVisitor<'a, 'b> {
791 method!(visit_impl_item: ast::ImplItem, ast::ImplItemKind::Macro, walk_impl_item);
792 method!(visit_expr: ast::Expr, ast::ExprKind::Mac, walk_expr);
793 method!(visit_pat: ast::Pat, ast::PatKind::Mac, walk_pat);
794 method!(visit_ty: ast::Ty, ast::TyKind::Mac, walk_ty);
796 fn visit_item(&mut self, item: &'a Item) {
797 let macro_use = match item.node {
798 ItemKind::MacroDef(..) => {
799 self.resolver.define_macro(item, self.expansion, &mut self.legacy_scope);
802 ItemKind::Mac(..) => {
803 self.legacy_scope = LegacyScope::Expansion(self.visit_invoc(item.id));
806 ItemKind::Mod(..) => self.resolver.contains_macro_use(&item.attrs),
810 let (parent, legacy_scope) = (self.resolver.current_module, self.legacy_scope);
811 self.resolver.build_reduced_graph_for_item(item, self.expansion);
812 visit::walk_item(self, item);
813 self.resolver.current_module = parent;
815 self.legacy_scope = legacy_scope;
819 fn visit_stmt(&mut self, stmt: &'a ast::Stmt) {
820 if let ast::StmtKind::Mac(..) = stmt.node {
821 self.legacy_scope = LegacyScope::Expansion(self.visit_invoc(stmt.id));
823 visit::walk_stmt(self, stmt);
827 fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
828 if let ForeignItemKind::Macro(_) = foreign_item.node {
829 self.visit_invoc(foreign_item.id);
833 self.resolver.build_reduced_graph_for_foreign_item(foreign_item, self.expansion);
834 visit::walk_foreign_item(self, foreign_item);
837 fn visit_block(&mut self, block: &'a Block) {
838 let (parent, legacy_scope) = (self.resolver.current_module, self.legacy_scope);
839 self.resolver.build_reduced_graph_for_block(block, self.expansion);
840 visit::walk_block(self, block);
841 self.resolver.current_module = parent;
842 self.legacy_scope = legacy_scope;
845 fn visit_trait_item(&mut self, item: &'a TraitItem) {
846 let parent = self.resolver.current_module;
848 if let TraitItemKind::Macro(_) = item.node {
849 self.visit_invoc(item.id);
853 // Add the item to the trait info.
854 let item_def_id = self.resolver.definitions.local_def_id(item.id);
855 let (def, ns) = match item.node {
856 TraitItemKind::Const(..) => (Def::AssociatedConst(item_def_id), ValueNS),
857 TraitItemKind::Method(ref sig, _) => {
858 if sig.decl.has_self() {
859 self.resolver.has_self.insert(item_def_id);
861 (Def::Method(item_def_id), ValueNS)
863 TraitItemKind::Type(..) => (Def::AssociatedTy(item_def_id), TypeNS),
864 TraitItemKind::Macro(_) => bug!(), // handled above
867 let vis = ty::Visibility::Public;
868 self.resolver.define(parent, item.ident, ns, (def, vis, item.span, self.expansion));
870 self.resolver.current_module = parent.parent.unwrap(); // nearest normal ancestor
871 visit::walk_trait_item(self, item);
872 self.resolver.current_module = parent;
875 fn visit_token(&mut self, t: Token) {
876 if let Token::Interpolated(nt) = t {
878 token::NtExpr(ref expr) => {
879 if let ast::ExprKind::Mac(..) = expr.node {
880 self.visit_invoc(expr.id);