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 {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::codemap::respan;
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::{self, Token};
43 use syntax::std_inject::injected_crate_name;
44 use syntax::symbol::keywords;
45 use syntax::symbol::Symbol;
46 use syntax::visit::{self, Visitor};
48 use syntax_pos::{Span, DUMMY_SP};
50 impl<'a> ToNameBinding<'a> for (Module<'a>, ty::Visibility, Span, Mark) {
51 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
52 arenas.alloc_name_binding(NameBinding {
53 kind: NameBindingKind::Module(self.0),
61 impl<'a> ToNameBinding<'a> for (Def, ty::Visibility, Span, Mark) {
62 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
63 arenas.alloc_name_binding(NameBinding {
64 kind: NameBindingKind::Def(self.0),
72 #[derive(Default, PartialEq, Eq)]
73 struct LegacyMacroImports {
74 import_all: Option<Span>,
75 imports: Vec<(Name, Span)>,
76 reexports: Vec<(Name, Span)>,
79 impl<'a> Resolver<'a> {
80 /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
81 /// otherwise, reports an error.
82 pub fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T)
83 where T: ToNameBinding<'a>,
85 let binding = def.to_name_binding(self.arenas);
86 if let Err(old_binding) = self.try_define(parent, ident, ns, binding) {
87 self.report_conflict(parent, ident, ns, old_binding, &binding);
91 fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
92 // If any statements are items, we need to create an anonymous module
93 block.stmts.iter().any(|statement| match statement.node {
94 StmtKind::Item(_) | StmtKind::Mac(_) => true,
99 fn insert_field_names(&mut self, def_id: DefId, field_names: Vec<Name>) {
100 if !field_names.is_empty() {
101 self.field_names.insert(def_id, field_names);
105 fn build_reduced_graph_for_use_tree(&mut self,
106 use_tree: &ast::UseTree,
113 let is_prelude = attr::contains_name(&item.attrs, "prelude_import");
114 let path = &use_tree.prefix;
116 let mut module_path: Vec<_> = prefix.segments.iter()
117 .chain(path.segments.iter())
118 .map(|seg| respan(seg.span, seg.ident))
121 match use_tree.kind {
122 ast::UseTreeKind::Simple(rename) => {
123 let mut ident = use_tree.ident();
124 let mut source = module_path.pop().unwrap().node;
125 let mut type_ns_only = false;
128 // Correctly handle `self`
129 if source.name == keywords::SelfValue.name() {
132 let last_segment = *module_path.last().unwrap();
133 if last_segment.node.name == keywords::CrateRoot.name() {
138 SelfImportOnlyInImportListWithNonEmptyPrefix
143 // Replace `use foo::self;` with `use foo;`
144 let _ = module_path.pop();
145 source = last_segment.node;
146 if rename.is_none() {
147 ident = last_segment.node;
152 if source.name == keywords::SelfValue.name() {
155 ResolutionError::SelfImportsOnlyAllowedWithin);
158 // Disallow `use $crate;`
159 if source.name == keywords::DollarCrate.name() && path.segments.len() == 1 {
160 let crate_root = self.resolve_crate_root(source.span.ctxt(), true);
161 let crate_name = match crate_root.kind {
162 ModuleKind::Def(_, name) => name,
163 ModuleKind::Block(..) => unreachable!(),
165 source.name = crate_name;
166 if rename.is_none() {
167 ident.name = crate_name;
170 self.session.struct_span_warn(item.span, "`$crate` may not be imported")
171 .note("`use $crate;` was erroneously allowed and \
172 will become a hard error in a future release")
177 let subclass = SingleImport {
180 result: self.per_ns(|_, _| Cell::new(Err(Undetermined))),
183 self.add_import_directive(
184 module_path, subclass, use_tree.span, id, vis, expansion,
187 ast::UseTreeKind::Glob => {
188 let subclass = GlobImport {
190 max_vis: Cell::new(ty::Visibility::Invisible),
192 self.add_import_directive(
193 module_path, subclass, use_tree.span, id, vis, expansion,
196 ast::UseTreeKind::Nested(ref items) => {
197 let prefix = ast::Path {
198 segments: module_path.iter()
199 .map(|s| ast::PathSegment::from_ident(s.node, s.span))
204 // Ensure there is at most one `self` in the list
205 let self_spans = items.iter().filter_map(|&(ref use_tree, _)| {
206 if let ast::UseTreeKind::Simple(..) = use_tree.kind {
207 if use_tree.ident().name == keywords::SelfValue.name() {
208 return Some(use_tree.span);
213 }).collect::<Vec<_>>();
214 if self_spans.len() > 1 {
215 let mut e = resolve_struct_error(self,
217 ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
219 for other_span in self_spans.iter().skip(1) {
220 e.span_label(*other_span, "another `self` import appears here");
226 for &(ref tree, id) in items {
227 self.build_reduced_graph_for_use_tree(
228 tree, id, vis, &prefix, true, item, expansion
235 /// Constructs the reduced graph for one item.
236 fn build_reduced_graph_for_item(&mut self, item: &Item, expansion: Mark) {
237 let parent = self.current_module;
238 let ident = item.ident;
240 let vis = self.resolve_visibility(&item.vis);
243 ItemKind::Use(ref use_tree) => {
244 // Imports are resolved as global by default, add starting root segment.
245 let prefix = ast::Path {
246 segments: use_tree.prefix.make_root().into_iter().collect(),
250 self.build_reduced_graph_for_use_tree(
251 use_tree, item.id, vis, &prefix, false, item, expansion,
255 ItemKind::ExternCrate(orig_name) => {
256 self.crate_loader.process_item(item, &self.definitions);
258 // n.b. we don't need to look at the path option here, because cstore already did
259 let crate_id = self.cstore.extern_mod_stmt_cnum_untracked(item.id).unwrap();
261 self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
262 self.populate_module_if_necessary(module);
263 if injected_crate_name().map_or(false, |name| item.ident.name == name) {
264 self.injected_crate = Some(module);
267 let used = self.process_legacy_macro_imports(item, module, expansion);
269 (module, ty::Visibility::Public, sp, expansion).to_name_binding(self.arenas);
270 let directive = self.arenas.alloc_import_directive(ImportDirective {
273 imported_module: Cell::new(Some(module)),
274 subclass: ImportDirectiveSubclass::ExternCrate(orig_name),
276 module_path: Vec::new(),
279 used: Cell::new(used),
281 self.potentially_unused_imports.push(directive);
282 let imported_binding = self.import(binding, directive);
283 self.define(parent, ident, TypeNS, imported_binding);
286 ItemKind::GlobalAsm(..) => {}
288 ItemKind::Mod(..) if item.ident == keywords::Invalid.ident() => {} // Crate root
290 ItemKind::Mod(..) => {
291 let def_id = self.definitions.local_def_id(item.id);
292 let module_kind = ModuleKind::Def(Def::Mod(def_id), ident.name);
293 let module = self.arenas.alloc_module(ModuleData {
294 no_implicit_prelude: parent.no_implicit_prelude || {
295 attr::contains_name(&item.attrs, "no_implicit_prelude")
297 ..ModuleData::new(Some(parent), module_kind, def_id, expansion, item.span)
299 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
300 self.module_map.insert(def_id, module);
302 // Descend into the module.
303 self.current_module = module;
306 ItemKind::ForeignMod(..) => self.crate_loader.process_item(item, &self.definitions),
308 // These items live in the value namespace.
309 ItemKind::Static(_, m, _) => {
310 let mutbl = m == Mutability::Mutable;
311 let def = Def::Static(self.definitions.local_def_id(item.id), mutbl);
312 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
314 ItemKind::Const(..) => {
315 let def = Def::Const(self.definitions.local_def_id(item.id));
316 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
318 ItemKind::Fn(..) => {
319 let def = Def::Fn(self.definitions.local_def_id(item.id));
320 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
323 // These items live in the type namespace.
324 ItemKind::Ty(..) => {
325 let def = Def::TyAlias(self.definitions.local_def_id(item.id));
326 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
329 ItemKind::Enum(ref enum_definition, _) => {
330 let def = Def::Enum(self.definitions.local_def_id(item.id));
331 let module_kind = ModuleKind::Def(def, ident.name);
332 let module = self.new_module(parent,
334 parent.normal_ancestor_id,
337 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
339 for variant in &(*enum_definition).variants {
340 self.build_reduced_graph_for_variant(variant, module, vis, expansion);
344 ItemKind::TraitAlias(..) => {
345 let def = Def::TraitAlias(self.definitions.local_def_id(item.id));
346 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
349 // These items live in both the type and value namespaces.
350 ItemKind::Struct(ref struct_def, _) => {
351 // Define a name in the type namespace.
352 let def_id = self.definitions.local_def_id(item.id);
353 let def = Def::Struct(def_id);
354 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
356 let mut ctor_vis = vis;
358 let has_non_exhaustive = attr::contains_name(&item.attrs, "non_exhaustive");
360 // If the structure is marked as non_exhaustive then lower the visibility
361 // to within the crate.
362 if has_non_exhaustive && vis == ty::Visibility::Public {
363 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
366 // Record field names for error reporting.
367 let field_names = struct_def.fields().iter().filter_map(|field| {
368 let field_vis = self.resolve_visibility(&field.vis);
369 if ctor_vis.is_at_least(field_vis, &*self) {
370 ctor_vis = field_vis;
372 field.ident.map(|ident| ident.name)
374 let item_def_id = self.definitions.local_def_id(item.id);
375 self.insert_field_names(item_def_id, field_names);
377 // If this is a tuple or unit struct, define a name
378 // in the value namespace as well.
379 if !struct_def.is_struct() {
380 let ctor_def = Def::StructCtor(self.definitions.local_def_id(struct_def.id()),
381 CtorKind::from_ast(struct_def));
382 self.define(parent, ident, ValueNS, (ctor_def, ctor_vis, sp, expansion));
383 self.struct_constructors.insert(def.def_id(), (ctor_def, ctor_vis));
387 ItemKind::Union(ref vdata, _) => {
388 let def = Def::Union(self.definitions.local_def_id(item.id));
389 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
391 // Record field names for error reporting.
392 let field_names = vdata.fields().iter().filter_map(|field| {
393 self.resolve_visibility(&field.vis);
394 field.ident.map(|ident| ident.name)
396 let item_def_id = self.definitions.local_def_id(item.id);
397 self.insert_field_names(item_def_id, field_names);
400 ItemKind::Impl(..) => {}
402 ItemKind::Trait(..) => {
403 let def_id = self.definitions.local_def_id(item.id);
405 // Add all the items within to a new module.
406 let module_kind = ModuleKind::Def(Def::Trait(def_id), ident.name);
407 let module = self.new_module(parent,
409 parent.normal_ancestor_id,
412 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
413 self.current_module = module;
416 ItemKind::MacroDef(..) | ItemKind::Mac(_) => unreachable!(),
420 // Constructs the reduced graph for one variant. Variants exist in the
421 // type and value namespaces.
422 fn build_reduced_graph_for_variant(&mut self,
427 let ident = variant.node.name;
428 let def_id = self.definitions.local_def_id(variant.node.data.id());
430 // Define a name in the type namespace.
431 let def = Def::Variant(def_id);
432 self.define(parent, ident, TypeNS, (def, vis, variant.span, expansion));
434 // Define a constructor name in the value namespace.
435 // Braced variants, unlike structs, generate unusable names in
436 // value namespace, they are reserved for possible future use.
437 let ctor_kind = CtorKind::from_ast(&variant.node.data);
438 let ctor_def = Def::VariantCtor(def_id, ctor_kind);
440 self.define(parent, ident, ValueNS, (ctor_def, vis, variant.span, expansion));
443 /// Constructs the reduced graph for one foreign item.
444 fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem, expansion: Mark) {
445 let (def, ns) = match item.node {
446 ForeignItemKind::Fn(..) => {
447 (Def::Fn(self.definitions.local_def_id(item.id)), ValueNS)
449 ForeignItemKind::Static(_, m) => {
450 (Def::Static(self.definitions.local_def_id(item.id), m), ValueNS)
452 ForeignItemKind::Ty => {
453 (Def::TyForeign(self.definitions.local_def_id(item.id)), TypeNS)
455 ForeignItemKind::Macro(_) => unreachable!(),
457 let parent = self.current_module;
458 let vis = self.resolve_visibility(&item.vis);
459 self.define(parent, item.ident, ns, (def, vis, item.span, expansion));
462 fn build_reduced_graph_for_block(&mut self, block: &Block, expansion: Mark) {
463 let parent = self.current_module;
464 if self.block_needs_anonymous_module(block) {
465 let module = self.new_module(parent,
466 ModuleKind::Block(block.id),
467 parent.normal_ancestor_id,
470 self.block_map.insert(block.id, module);
471 self.current_module = module; // Descend into the block.
475 /// Builds the reduced graph for a single item in an external crate.
476 fn build_reduced_graph_for_external_crate_def(&mut self, parent: Module<'a>, child: Export) {
477 let Export { ident, def, vis, span, .. } = child;
478 let def_id = def.def_id();
479 let expansion = Mark::root(); // FIXME(jseyfried) intercrate hygiene
481 Def::Mod(..) | Def::Enum(..) => {
482 let module = self.new_module(parent,
483 ModuleKind::Def(def, ident.name),
487 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
489 Def::Variant(..) | Def::TyAlias(..) | Def::TyForeign(..) => {
490 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
492 Def::Fn(..) | Def::Static(..) | Def::Const(..) | Def::VariantCtor(..) => {
493 self.define(parent, ident, ValueNS, (def, vis, DUMMY_SP, expansion));
495 Def::StructCtor(..) => {
496 self.define(parent, ident, ValueNS, (def, vis, DUMMY_SP, expansion));
498 if let Some(struct_def_id) =
499 self.cstore.def_key(def_id).parent
500 .map(|index| DefId { krate: def_id.krate, index: index }) {
501 self.struct_constructors.insert(struct_def_id, (def, vis));
505 let module_kind = ModuleKind::Def(def, ident.name);
506 let module = self.new_module(parent,
508 parent.normal_ancestor_id,
511 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
513 for child in self.cstore.item_children_untracked(def_id, self.session) {
514 let ns = if let Def::AssociatedTy(..) = child.def { TypeNS } else { ValueNS };
515 self.define(module, child.ident, ns,
516 (child.def, ty::Visibility::Public, DUMMY_SP, expansion));
518 if self.cstore.associated_item_cloned_untracked(child.def.def_id())
519 .method_has_self_argument {
520 self.has_self.insert(child.def.def_id());
523 module.populated.set(true);
525 Def::Struct(..) | Def::Union(..) => {
526 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
528 // Record field names for error reporting.
529 let field_names = self.cstore.struct_field_names_untracked(def_id);
530 self.insert_field_names(def_id, field_names);
533 self.define(parent, ident, MacroNS, (def, vis, DUMMY_SP, expansion));
535 _ => bug!("unexpected definition: {:?}", def)
539 pub fn get_module(&mut self, def_id: DefId) -> Module<'a> {
540 if def_id.krate == LOCAL_CRATE {
541 return self.module_map[&def_id]
544 let macros_only = self.cstore.dep_kind_untracked(def_id.krate).macros_only();
545 if let Some(&module) = self.extern_module_map.get(&(def_id, macros_only)) {
549 let (name, parent) = if def_id.index == CRATE_DEF_INDEX {
550 (self.cstore.crate_name_untracked(def_id.krate).as_str(), None)
552 let def_key = self.cstore.def_key(def_id);
553 (def_key.disambiguated_data.data.get_opt_name().unwrap(),
554 Some(self.get_module(DefId { index: def_key.parent.unwrap(), ..def_id })))
557 let kind = ModuleKind::Def(Def::Mod(def_id), Symbol::intern(&name));
559 self.arenas.alloc_module(ModuleData::new(parent, kind, def_id, Mark::root(), DUMMY_SP));
560 self.extern_module_map.insert((def_id, macros_only), module);
564 pub fn macro_def_scope(&mut self, expansion: Mark) -> Module<'a> {
565 let def_id = self.macro_defs[&expansion];
566 if let Some(id) = self.definitions.as_local_node_id(def_id) {
567 self.local_macro_def_scopes[&id]
568 } else if def_id.krate == BUILTIN_MACROS_CRATE {
569 self.injected_crate.unwrap_or(self.graph_root)
571 let module_def_id = ty::DefIdTree::parent(&*self, def_id).unwrap();
572 self.get_module(module_def_id)
576 pub fn get_macro(&mut self, def: Def) -> Lrc<SyntaxExtension> {
577 let def_id = match def {
578 Def::Macro(def_id, ..) => def_id,
579 _ => panic!("Expected Def::Macro(..)"),
581 if let Some(ext) = self.macro_map.get(&def_id) {
585 let macro_def = match self.cstore.load_macro_untracked(def_id, &self.session) {
586 LoadedMacro::MacroDef(macro_def) => macro_def,
587 LoadedMacro::ProcMacro(ext) => return ext,
590 let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
591 &self.session.features_untracked(),
593 self.macro_map.insert(def_id, ext.clone());
597 /// Ensures that the reduced graph rooted at the given external module
598 /// is built, building it if it is not.
599 pub fn populate_module_if_necessary(&mut self, module: Module<'a>) {
600 if module.populated.get() { return }
601 let def_id = module.def_id().unwrap();
602 for child in self.cstore.item_children_untracked(def_id, self.session) {
603 self.build_reduced_graph_for_external_crate_def(module, child);
605 module.populated.set(true)
608 fn legacy_import_macro(&mut self,
610 binding: &'a NameBinding<'a>,
612 allow_shadowing: bool) {
613 if self.global_macros.insert(name, binding).is_some() && !allow_shadowing {
614 let msg = format!("`{}` is already in scope", name);
616 "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)";
617 self.session.struct_span_err(span, &msg).note(note).emit();
621 // This returns true if we should consider the underlying `extern crate` to be used.
622 fn process_legacy_macro_imports(&mut self, item: &Item, module: Module<'a>, expansion: Mark)
624 let allow_shadowing = expansion == Mark::root();
625 let legacy_imports = self.legacy_macro_imports(&item.attrs);
626 let mut used = legacy_imports != LegacyMacroImports::default();
628 // `#[macro_use]` and `#[macro_reexport]` are only allowed at the crate root.
629 if self.current_module.parent.is_some() && used {
630 span_err!(self.session, item.span, E0468,
631 "an `extern crate` loading macros must be at the crate root");
632 } else if !self.use_extern_macros && !used &&
633 self.cstore.dep_kind_untracked(module.def_id().unwrap().krate)
635 let msg = "proc macro crates and `#[no_link]` crates have no effect without \
637 self.session.span_warn(item.span, msg);
638 used = true; // Avoid the normal unused extern crate warning
641 let (graph_root, arenas) = (self.graph_root, self.arenas);
642 let macro_use_directive = |span| arenas.alloc_import_directive(ImportDirective {
645 imported_module: Cell::new(Some(module)),
646 subclass: ImportDirectiveSubclass::MacroUse,
648 module_path: Vec::new(),
649 vis: Cell::new(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))),
651 used: Cell::new(false),
654 if let Some(span) = legacy_imports.import_all {
655 let directive = macro_use_directive(span);
656 self.potentially_unused_imports.push(directive);
657 module.for_each_child(|ident, ns, binding| if ns == MacroNS {
658 let imported_binding = self.import(binding, directive);
659 self.legacy_import_macro(ident.name, imported_binding, span, allow_shadowing);
662 for (name, span) in legacy_imports.imports {
663 let ident = Ident::with_empty_ctxt(name);
664 let result = self.resolve_ident_in_module(module, ident, MacroNS,
666 if let Ok(binding) = result {
667 let directive = macro_use_directive(span);
668 self.potentially_unused_imports.push(directive);
669 let imported_binding = self.import(binding, directive);
670 self.legacy_import_macro(name, imported_binding, span, allow_shadowing);
672 span_err!(self.session, span, E0469, "imported macro not found");
676 for (name, span) in legacy_imports.reexports {
677 self.cstore.export_macros_untracked(module.def_id().unwrap().krate);
678 let ident = Ident::with_empty_ctxt(name);
679 let result = self.resolve_ident_in_module(module, ident, MacroNS, false, false, span);
680 if let Ok(binding) = result {
681 let (def, vis) = (binding.def(), binding.vis);
682 self.macro_exports.push(Export { ident, def, vis, span, is_import: true });
684 span_err!(self.session, span, E0470, "re-exported macro not found");
690 // does this attribute list contain "macro_use"?
691 fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool {
693 if attr.check_name("macro_escape") {
694 let msg = "macro_escape is a deprecated synonym for macro_use";
695 let mut err = self.session.struct_span_warn(attr.span, msg);
696 if let ast::AttrStyle::Inner = attr.style {
697 err.help("consider an outer attribute, #[macro_use] mod ...").emit();
701 } else if !attr.check_name("macro_use") {
706 self.session.span_err(attr.span, "arguments to macro_use are not allowed here");
714 fn legacy_macro_imports(&mut self, attrs: &[ast::Attribute]) -> LegacyMacroImports {
715 let mut imports = LegacyMacroImports::default();
717 if attr.check_name("macro_use") {
718 match attr.meta_item_list() {
719 Some(names) => for attr in names {
720 if let Some(word) = attr.word() {
721 imports.imports.push((word.name(), attr.span()));
723 span_err!(self.session, attr.span(), E0466, "bad macro import");
726 None => imports.import_all = Some(attr.span),
728 } else if attr.check_name("macro_reexport") {
729 let bad_macro_reexport = |this: &mut Self, span| {
730 span_err!(this.session, span, E0467, "bad macro re-export");
732 if let Some(names) = attr.meta_item_list() {
734 if let Some(word) = attr.word() {
735 imports.reexports.push((word.name(), attr.span()));
737 bad_macro_reexport(self, attr.span());
741 bad_macro_reexport(self, attr.span());
749 pub struct BuildReducedGraphVisitor<'a, 'b: 'a> {
750 pub resolver: &'a mut Resolver<'b>,
751 pub legacy_scope: LegacyScope<'b>,
755 impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
756 fn visit_invoc(&mut self, id: ast::NodeId) -> &'b InvocationData<'b> {
757 let mark = id.placeholder_to_mark();
758 self.resolver.current_module.unresolved_invocations.borrow_mut().insert(mark);
759 let invocation = self.resolver.invocations[&mark];
760 invocation.module.set(self.resolver.current_module);
761 invocation.legacy_scope.set(self.legacy_scope);
766 macro_rules! method {
767 ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
768 fn $visit(&mut self, node: &'a $ty) {
769 if let $invoc(..) = node.node {
770 self.visit_invoc(node.id);
772 visit::$walk(self, node);
778 impl<'a, 'b> Visitor<'a> for BuildReducedGraphVisitor<'a, 'b> {
779 method!(visit_impl_item: ast::ImplItem, ast::ImplItemKind::Macro, walk_impl_item);
780 method!(visit_expr: ast::Expr, ast::ExprKind::Mac, walk_expr);
781 method!(visit_pat: ast::Pat, ast::PatKind::Mac, walk_pat);
782 method!(visit_ty: ast::Ty, ast::TyKind::Mac, walk_ty);
784 fn visit_item(&mut self, item: &'a Item) {
785 let macro_use = match item.node {
786 ItemKind::MacroDef(..) => {
787 self.resolver.define_macro(item, self.expansion, &mut self.legacy_scope);
790 ItemKind::Mac(..) => {
791 self.legacy_scope = LegacyScope::Expansion(self.visit_invoc(item.id));
794 ItemKind::Mod(..) => self.resolver.contains_macro_use(&item.attrs),
798 let (parent, legacy_scope) = (self.resolver.current_module, self.legacy_scope);
799 self.resolver.build_reduced_graph_for_item(item, self.expansion);
800 visit::walk_item(self, item);
801 self.resolver.current_module = parent;
803 self.legacy_scope = legacy_scope;
807 fn visit_stmt(&mut self, stmt: &'a ast::Stmt) {
808 if let ast::StmtKind::Mac(..) = stmt.node {
809 self.legacy_scope = LegacyScope::Expansion(self.visit_invoc(stmt.id));
811 visit::walk_stmt(self, stmt);
815 fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
816 if let ForeignItemKind::Macro(_) = foreign_item.node {
817 self.visit_invoc(foreign_item.id);
821 self.resolver.build_reduced_graph_for_foreign_item(foreign_item, self.expansion);
822 visit::walk_foreign_item(self, foreign_item);
825 fn visit_block(&mut self, block: &'a Block) {
826 let (parent, legacy_scope) = (self.resolver.current_module, self.legacy_scope);
827 self.resolver.build_reduced_graph_for_block(block, self.expansion);
828 visit::walk_block(self, block);
829 self.resolver.current_module = parent;
830 self.legacy_scope = legacy_scope;
833 fn visit_trait_item(&mut self, item: &'a TraitItem) {
834 let parent = self.resolver.current_module;
836 if let TraitItemKind::Macro(_) = item.node {
837 self.visit_invoc(item.id);
841 // Add the item to the trait info.
842 let item_def_id = self.resolver.definitions.local_def_id(item.id);
843 let (def, ns) = match item.node {
844 TraitItemKind::Const(..) => (Def::AssociatedConst(item_def_id), ValueNS),
845 TraitItemKind::Method(ref sig, _) => {
846 if sig.decl.has_self() {
847 self.resolver.has_self.insert(item_def_id);
849 (Def::Method(item_def_id), ValueNS)
851 TraitItemKind::Type(..) => (Def::AssociatedTy(item_def_id), TypeNS),
852 TraitItemKind::Macro(_) => bug!(), // handled above
855 let vis = ty::Visibility::Public;
856 self.resolver.define(parent, item.ident, ns, (def, vis, item.span, self.expansion));
858 self.resolver.current_module = parent.parent.unwrap(); // nearest normal ancestor
859 visit::walk_trait_item(self, item);
860 self.resolver.current_module = parent;
863 fn visit_token(&mut self, t: Token) {
864 if let Token::Interpolated(nt) = t {
866 token::NtExpr(ref expr) => {
867 if let ast::ExprKind::Mac(..) = expr.node {
868 self.visit_invoc(expr.id);