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::ext::base::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::symbol::Symbol;
45 use syntax::visit::{self, Visitor};
47 use syntax_pos::{Span, DUMMY_SP};
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),
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),
71 #[derive(Default, PartialEq, Eq)]
72 struct LegacyMacroImports {
73 import_all: Option<Span>,
74 imports: Vec<(Name, Span)>,
75 reexports: Vec<(Name, Span)>,
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 pub fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T)
82 where T: ToNameBinding<'a>,
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);
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,
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);
104 fn build_reduced_graph_for_use_tree(&mut self,
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.span.ctxt(), true);
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 {
179 result: self.per_ns(|_, _| Cell::new(Err(Undetermined))),
182 self.add_import_directive(
183 module_path, subclass, use_tree.span, id, vis, expansion,
186 ast::UseTreeKind::Glob => {
187 let subclass = GlobImport {
189 max_vis: Cell::new(ty::Visibility::Invisible),
191 self.add_import_directive(
192 module_path, subclass, use_tree.span, id, vis, expansion,
195 ast::UseTreeKind::Nested(ref items) => {
196 let prefix = ast::Path {
197 segments: module_path.into_iter()
198 .map(|ident| ast::PathSegment::from_ident(ident))
203 // Ensure there is at most one `self` in the list
204 let self_spans = items.iter().filter_map(|&(ref use_tree, _)| {
205 if let ast::UseTreeKind::Simple(..) = use_tree.kind {
206 if use_tree.ident().name == keywords::SelfValue.name() {
207 return Some(use_tree.span);
212 }).collect::<Vec<_>>();
213 if self_spans.len() > 1 {
214 let mut e = resolve_struct_error(self,
216 ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
218 for other_span in self_spans.iter().skip(1) {
219 e.span_label(*other_span, "another `self` import appears here");
225 for &(ref tree, id) in items {
226 self.build_reduced_graph_for_use_tree(
227 tree, id, vis, &prefix, true, item, expansion
234 /// Constructs the reduced graph for one item.
235 fn build_reduced_graph_for_item(&mut self, item: &Item, expansion: Mark) {
236 let parent = self.current_module;
237 let ident = item.ident;
239 let vis = self.resolve_visibility(&item.vis);
242 ItemKind::Use(ref use_tree) => {
243 // Imports are resolved as global by default, add starting root segment.
244 let prefix = ast::Path {
245 segments: use_tree.prefix.make_root().into_iter().collect(),
249 self.build_reduced_graph_for_use_tree(
250 use_tree, item.id, vis, &prefix, false, item, expansion,
254 ItemKind::ExternCrate(orig_name) => {
255 self.crate_loader.process_item(item, &self.definitions);
257 // n.b. we don't need to look at the path option here, because cstore already did
258 let crate_id = self.cstore.extern_mod_stmt_cnum_untracked(item.id).unwrap();
260 self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
261 self.populate_module_if_necessary(module);
262 if injected_crate_name().map_or(false, |name| item.ident.name == name) {
263 self.injected_crate = Some(module);
266 let used = self.process_legacy_macro_imports(item, module, expansion);
268 (module, ty::Visibility::Public, sp, expansion).to_name_binding(self.arenas);
269 let directive = self.arenas.alloc_import_directive(ImportDirective {
272 imported_module: Cell::new(Some(module)),
273 subclass: ImportDirectiveSubclass::ExternCrate(orig_name),
275 module_path: Vec::new(),
278 used: Cell::new(used),
280 self.potentially_unused_imports.push(directive);
281 let imported_binding = self.import(binding, directive);
282 self.define(parent, ident, TypeNS, imported_binding);
285 ItemKind::GlobalAsm(..) => {}
287 ItemKind::Mod(..) if item.ident == keywords::Invalid.ident() => {} // Crate root
289 ItemKind::Mod(..) => {
290 let def_id = self.definitions.local_def_id(item.id);
291 let module_kind = ModuleKind::Def(Def::Mod(def_id), ident.name);
292 let module = self.arenas.alloc_module(ModuleData {
293 no_implicit_prelude: parent.no_implicit_prelude || {
294 attr::contains_name(&item.attrs, "no_implicit_prelude")
296 ..ModuleData::new(Some(parent), module_kind, def_id, expansion, item.span)
298 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
299 self.module_map.insert(def_id, module);
301 // Descend into the module.
302 self.current_module = module;
305 ItemKind::ForeignMod(..) => self.crate_loader.process_item(item, &self.definitions),
307 // These items live in the value namespace.
308 ItemKind::Static(_, m, _) => {
309 let mutbl = m == Mutability::Mutable;
310 let def = Def::Static(self.definitions.local_def_id(item.id), mutbl);
311 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
313 ItemKind::Const(..) => {
314 let def = Def::Const(self.definitions.local_def_id(item.id));
315 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
317 ItemKind::Fn(..) => {
318 let def = Def::Fn(self.definitions.local_def_id(item.id));
319 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
322 // These items live in the type namespace.
323 ItemKind::Ty(..) => {
324 let def = Def::TyAlias(self.definitions.local_def_id(item.id));
325 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
328 ItemKind::Enum(ref enum_definition, _) => {
329 let def = Def::Enum(self.definitions.local_def_id(item.id));
330 let module_kind = ModuleKind::Def(def, ident.name);
331 let module = self.new_module(parent,
333 parent.normal_ancestor_id,
336 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
338 for variant in &(*enum_definition).variants {
339 self.build_reduced_graph_for_variant(variant, module, vis, expansion);
343 ItemKind::TraitAlias(..) => {
344 let def = Def::TraitAlias(self.definitions.local_def_id(item.id));
345 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
348 // These items live in both the type and value namespaces.
349 ItemKind::Struct(ref struct_def, _) => {
350 // Define a name in the type namespace.
351 let def_id = self.definitions.local_def_id(item.id);
352 let def = Def::Struct(def_id);
353 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
355 let mut ctor_vis = vis;
357 let has_non_exhaustive = attr::contains_name(&item.attrs, "non_exhaustive");
359 // If the structure is marked as non_exhaustive then lower the visibility
360 // to within the crate.
361 if has_non_exhaustive && vis == ty::Visibility::Public {
362 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
365 // Record field names for error reporting.
366 let field_names = struct_def.fields().iter().filter_map(|field| {
367 let field_vis = self.resolve_visibility(&field.vis);
368 if ctor_vis.is_at_least(field_vis, &*self) {
369 ctor_vis = field_vis;
371 field.ident.map(|ident| ident.name)
373 let item_def_id = self.definitions.local_def_id(item.id);
374 self.insert_field_names(item_def_id, field_names);
376 // If this is a tuple or unit struct, define a name
377 // in the value namespace as well.
378 if !struct_def.is_struct() {
379 let ctor_def = Def::StructCtor(self.definitions.local_def_id(struct_def.id()),
380 CtorKind::from_ast(struct_def));
381 self.define(parent, ident, ValueNS, (ctor_def, ctor_vis, sp, expansion));
382 self.struct_constructors.insert(def.def_id(), (ctor_def, ctor_vis));
386 ItemKind::Union(ref vdata, _) => {
387 let def = Def::Union(self.definitions.local_def_id(item.id));
388 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
390 // Record field names for error reporting.
391 let field_names = vdata.fields().iter().filter_map(|field| {
392 self.resolve_visibility(&field.vis);
393 field.ident.map(|ident| ident.name)
395 let item_def_id = self.definitions.local_def_id(item.id);
396 self.insert_field_names(item_def_id, field_names);
399 ItemKind::Impl(..) => {}
401 ItemKind::Trait(..) => {
402 let def_id = self.definitions.local_def_id(item.id);
404 // Add all the items within to a new module.
405 let module_kind = ModuleKind::Def(Def::Trait(def_id), ident.name);
406 let module = self.new_module(parent,
408 parent.normal_ancestor_id,
411 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
412 self.current_module = module;
415 ItemKind::MacroDef(..) | ItemKind::Mac(_) => unreachable!(),
419 // Constructs the reduced graph for one variant. Variants exist in the
420 // type and value namespaces.
421 fn build_reduced_graph_for_variant(&mut self,
426 let ident = variant.node.ident;
427 let def_id = self.definitions.local_def_id(variant.node.data.id());
429 // Define a name in the type namespace.
430 let def = Def::Variant(def_id);
431 self.define(parent, ident, TypeNS, (def, vis, variant.span, expansion));
433 // Define a constructor name in the value namespace.
434 // Braced variants, unlike structs, generate unusable names in
435 // value namespace, they are reserved for possible future use.
436 let ctor_kind = CtorKind::from_ast(&variant.node.data);
437 let ctor_def = Def::VariantCtor(def_id, ctor_kind);
439 self.define(parent, ident, ValueNS, (ctor_def, vis, variant.span, expansion));
442 /// Constructs the reduced graph for one foreign item.
443 fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem, expansion: Mark) {
444 let (def, ns) = match item.node {
445 ForeignItemKind::Fn(..) => {
446 (Def::Fn(self.definitions.local_def_id(item.id)), ValueNS)
448 ForeignItemKind::Static(_, m) => {
449 (Def::Static(self.definitions.local_def_id(item.id), m), ValueNS)
451 ForeignItemKind::Ty => {
452 (Def::TyForeign(self.definitions.local_def_id(item.id)), TypeNS)
454 ForeignItemKind::Macro(_) => unreachable!(),
456 let parent = self.current_module;
457 let vis = self.resolve_visibility(&item.vis);
458 self.define(parent, item.ident, ns, (def, vis, item.span, expansion));
461 fn build_reduced_graph_for_block(&mut self, block: &Block, expansion: Mark) {
462 let parent = self.current_module;
463 if self.block_needs_anonymous_module(block) {
464 let module = self.new_module(parent,
465 ModuleKind::Block(block.id),
466 parent.normal_ancestor_id,
469 self.block_map.insert(block.id, module);
470 self.current_module = module; // Descend into the block.
474 /// Builds the reduced graph for a single item in an external crate.
475 fn build_reduced_graph_for_external_crate_def(&mut self, parent: Module<'a>, child: Export) {
476 let Export { ident, def, vis, span, .. } = child;
477 let def_id = def.def_id();
478 let expansion = Mark::root(); // FIXME(jseyfried) intercrate hygiene
480 Def::Mod(..) | Def::Enum(..) => {
481 let module = self.new_module(parent,
482 ModuleKind::Def(def, ident.name),
486 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
488 Def::Variant(..) | Def::TyAlias(..) | Def::TyForeign(..) => {
489 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
491 Def::Fn(..) | Def::Static(..) | Def::Const(..) | Def::VariantCtor(..) => {
492 self.define(parent, ident, ValueNS, (def, vis, DUMMY_SP, expansion));
494 Def::StructCtor(..) => {
495 self.define(parent, ident, ValueNS, (def, vis, DUMMY_SP, expansion));
497 if let Some(struct_def_id) =
498 self.cstore.def_key(def_id).parent
499 .map(|index| DefId { krate: def_id.krate, index: index }) {
500 self.struct_constructors.insert(struct_def_id, (def, vis));
504 let module_kind = ModuleKind::Def(def, ident.name);
505 let module = self.new_module(parent,
507 parent.normal_ancestor_id,
510 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
512 for child in self.cstore.item_children_untracked(def_id, self.session) {
513 let ns = if let Def::AssociatedTy(..) = child.def { TypeNS } else { ValueNS };
514 self.define(module, child.ident, ns,
515 (child.def, ty::Visibility::Public, DUMMY_SP, expansion));
517 if self.cstore.associated_item_cloned_untracked(child.def.def_id())
518 .method_has_self_argument {
519 self.has_self.insert(child.def.def_id());
522 module.populated.set(true);
524 Def::Struct(..) | Def::Union(..) => {
525 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
527 // Record field names for error reporting.
528 let field_names = self.cstore.struct_field_names_untracked(def_id);
529 self.insert_field_names(def_id, field_names);
532 self.define(parent, ident, MacroNS, (def, vis, DUMMY_SP, expansion));
534 _ => bug!("unexpected definition: {:?}", def)
538 pub fn get_module(&mut self, def_id: DefId) -> Module<'a> {
539 if def_id.krate == LOCAL_CRATE {
540 return self.module_map[&def_id]
543 let macros_only = self.cstore.dep_kind_untracked(def_id.krate).macros_only();
544 if let Some(&module) = self.extern_module_map.get(&(def_id, macros_only)) {
548 let (name, parent) = if def_id.index == CRATE_DEF_INDEX {
549 (self.cstore.crate_name_untracked(def_id.krate).as_str(), None)
551 let def_key = self.cstore.def_key(def_id);
552 (def_key.disambiguated_data.data.get_opt_name().unwrap(),
553 Some(self.get_module(DefId { index: def_key.parent.unwrap(), ..def_id })))
556 let kind = ModuleKind::Def(Def::Mod(def_id), Symbol::intern(&name));
558 self.arenas.alloc_module(ModuleData::new(parent, kind, def_id, Mark::root(), DUMMY_SP));
559 self.extern_module_map.insert((def_id, macros_only), module);
563 pub fn macro_def_scope(&mut self, expansion: Mark) -> Module<'a> {
564 let def_id = self.macro_defs[&expansion];
565 if let Some(id) = self.definitions.as_local_node_id(def_id) {
566 self.local_macro_def_scopes[&id]
567 } else if def_id.krate == BUILTIN_MACROS_CRATE {
568 self.injected_crate.unwrap_or(self.graph_root)
570 let module_def_id = ty::DefIdTree::parent(&*self, def_id).unwrap();
571 self.get_module(module_def_id)
575 pub fn get_macro(&mut self, def: Def) -> Lrc<SyntaxExtension> {
576 let def_id = match def {
577 Def::Macro(def_id, ..) => def_id,
578 _ => panic!("Expected Def::Macro(..)"),
580 if let Some(ext) = self.macro_map.get(&def_id) {
584 let macro_def = match self.cstore.load_macro_untracked(def_id, &self.session) {
585 LoadedMacro::MacroDef(macro_def) => macro_def,
586 LoadedMacro::ProcMacro(ext) => return ext,
589 let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
590 &self.session.features_untracked(),
592 self.macro_map.insert(def_id, ext.clone());
596 /// Ensures that the reduced graph rooted at the given external module
597 /// is built, building it if it is not.
598 pub fn populate_module_if_necessary(&mut self, module: Module<'a>) {
599 if module.populated.get() { return }
600 let def_id = module.def_id().unwrap();
601 for child in self.cstore.item_children_untracked(def_id, self.session) {
602 self.build_reduced_graph_for_external_crate_def(module, child);
604 module.populated.set(true)
607 fn legacy_import_macro(&mut self,
609 binding: &'a NameBinding<'a>,
611 allow_shadowing: bool) {
612 if self.global_macros.insert(name, binding).is_some() && !allow_shadowing {
613 let msg = format!("`{}` is already in scope", name);
615 "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)";
616 self.session.struct_span_err(span, &msg).note(note).emit();
620 // This returns true if we should consider the underlying `extern crate` to be used.
621 fn process_legacy_macro_imports(&mut self, item: &Item, module: Module<'a>, expansion: Mark)
623 let allow_shadowing = expansion == Mark::root();
624 let legacy_imports = self.legacy_macro_imports(&item.attrs);
625 let mut used = legacy_imports != LegacyMacroImports::default();
627 // `#[macro_use]` and `#[macro_reexport]` are only allowed at the crate root.
628 if self.current_module.parent.is_some() && used {
629 span_err!(self.session, item.span, E0468,
630 "an `extern crate` loading macros must be at the crate root");
631 } else if !self.use_extern_macros && !used &&
632 self.cstore.dep_kind_untracked(module.def_id().unwrap().krate)
634 let msg = "proc macro crates and `#[no_link]` crates have no effect without \
636 self.session.span_warn(item.span, msg);
637 used = true; // Avoid the normal unused extern crate warning
640 let (graph_root, arenas) = (self.graph_root, self.arenas);
641 let macro_use_directive = |span| arenas.alloc_import_directive(ImportDirective {
644 imported_module: Cell::new(Some(module)),
645 subclass: ImportDirectiveSubclass::MacroUse,
647 module_path: Vec::new(),
648 vis: Cell::new(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))),
650 used: Cell::new(false),
653 if let Some(span) = legacy_imports.import_all {
654 let directive = macro_use_directive(span);
655 self.potentially_unused_imports.push(directive);
656 module.for_each_child(|ident, ns, binding| if ns == MacroNS {
657 let imported_binding = self.import(binding, directive);
658 self.legacy_import_macro(ident.name, imported_binding, span, allow_shadowing);
661 for (name, span) in legacy_imports.imports {
662 let ident = Ident::with_empty_ctxt(name);
663 let result = self.resolve_ident_in_module(module, ident, MacroNS,
665 if let Ok(binding) = result {
666 let directive = macro_use_directive(span);
667 self.potentially_unused_imports.push(directive);
668 let imported_binding = self.import(binding, directive);
669 self.legacy_import_macro(name, imported_binding, span, allow_shadowing);
671 span_err!(self.session, span, E0469, "imported macro not found");
675 for (name, span) in legacy_imports.reexports {
676 self.cstore.export_macros_untracked(module.def_id().unwrap().krate);
677 let ident = Ident::with_empty_ctxt(name);
678 let result = self.resolve_ident_in_module(module, ident, MacroNS, false, false, span);
679 if let Ok(binding) = result {
680 let (def, vis) = (binding.def(), binding.vis);
681 self.macro_exports.push(Export { ident, def, vis, span, is_import: true });
683 span_err!(self.session, span, E0470, "re-exported macro not found");
689 // does this attribute list contain "macro_use"?
690 fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool {
692 if attr.check_name("macro_escape") {
693 let msg = "macro_escape is a deprecated synonym for macro_use";
694 let mut err = self.session.struct_span_warn(attr.span, msg);
695 if let ast::AttrStyle::Inner = attr.style {
696 err.help("consider an outer attribute, #[macro_use] mod ...").emit();
700 } else if !attr.check_name("macro_use") {
705 self.session.span_err(attr.span, "arguments to macro_use are not allowed here");
713 fn legacy_macro_imports(&mut self, attrs: &[ast::Attribute]) -> LegacyMacroImports {
714 let mut imports = LegacyMacroImports::default();
716 if attr.check_name("macro_use") {
717 match attr.meta_item_list() {
718 Some(names) => for attr in names {
719 if let Some(word) = attr.word() {
720 imports.imports.push((word.name(), attr.span()));
722 span_err!(self.session, attr.span(), E0466, "bad macro import");
725 None => imports.import_all = Some(attr.span),
727 } else if attr.check_name("macro_reexport") {
728 let bad_macro_reexport = |this: &mut Self, span| {
729 span_err!(this.session, span, E0467, "bad macro re-export");
731 if let Some(names) = attr.meta_item_list() {
733 if let Some(word) = attr.word() {
734 imports.reexports.push((word.name(), attr.span()));
736 bad_macro_reexport(self, attr.span());
740 bad_macro_reexport(self, attr.span());
748 pub struct BuildReducedGraphVisitor<'a, 'b: 'a> {
749 pub resolver: &'a mut Resolver<'b>,
750 pub legacy_scope: LegacyScope<'b>,
754 impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
755 fn visit_invoc(&mut self, id: ast::NodeId) -> &'b InvocationData<'b> {
756 let mark = id.placeholder_to_mark();
757 self.resolver.current_module.unresolved_invocations.borrow_mut().insert(mark);
758 let invocation = self.resolver.invocations[&mark];
759 invocation.module.set(self.resolver.current_module);
760 invocation.legacy_scope.set(self.legacy_scope);
765 macro_rules! method {
766 ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
767 fn $visit(&mut self, node: &'a $ty) {
768 if let $invoc(..) = node.node {
769 self.visit_invoc(node.id);
771 visit::$walk(self, node);
777 impl<'a, 'b> Visitor<'a> for BuildReducedGraphVisitor<'a, 'b> {
778 method!(visit_impl_item: ast::ImplItem, ast::ImplItemKind::Macro, walk_impl_item);
779 method!(visit_expr: ast::Expr, ast::ExprKind::Mac, walk_expr);
780 method!(visit_pat: ast::Pat, ast::PatKind::Mac, walk_pat);
781 method!(visit_ty: ast::Ty, ast::TyKind::Mac, walk_ty);
783 fn visit_item(&mut self, item: &'a Item) {
784 let macro_use = match item.node {
785 ItemKind::MacroDef(..) => {
786 self.resolver.define_macro(item, self.expansion, &mut self.legacy_scope);
789 ItemKind::Mac(..) => {
790 self.legacy_scope = LegacyScope::Expansion(self.visit_invoc(item.id));
793 ItemKind::Mod(..) => self.resolver.contains_macro_use(&item.attrs),
797 let (parent, legacy_scope) = (self.resolver.current_module, self.legacy_scope);
798 self.resolver.build_reduced_graph_for_item(item, self.expansion);
799 visit::walk_item(self, item);
800 self.resolver.current_module = parent;
802 self.legacy_scope = legacy_scope;
806 fn visit_stmt(&mut self, stmt: &'a ast::Stmt) {
807 if let ast::StmtKind::Mac(..) = stmt.node {
808 self.legacy_scope = LegacyScope::Expansion(self.visit_invoc(stmt.id));
810 visit::walk_stmt(self, stmt);
814 fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
815 if let ForeignItemKind::Macro(_) = foreign_item.node {
816 self.visit_invoc(foreign_item.id);
820 self.resolver.build_reduced_graph_for_foreign_item(foreign_item, self.expansion);
821 visit::walk_foreign_item(self, foreign_item);
824 fn visit_block(&mut self, block: &'a Block) {
825 let (parent, legacy_scope) = (self.resolver.current_module, self.legacy_scope);
826 self.resolver.build_reduced_graph_for_block(block, self.expansion);
827 visit::walk_block(self, block);
828 self.resolver.current_module = parent;
829 self.legacy_scope = legacy_scope;
832 fn visit_trait_item(&mut self, item: &'a TraitItem) {
833 let parent = self.resolver.current_module;
835 if let TraitItemKind::Macro(_) = item.node {
836 self.visit_invoc(item.id);
840 // Add the item to the trait info.
841 let item_def_id = self.resolver.definitions.local_def_id(item.id);
842 let (def, ns) = match item.node {
843 TraitItemKind::Const(..) => (Def::AssociatedConst(item_def_id), ValueNS),
844 TraitItemKind::Method(ref sig, _) => {
845 if sig.decl.has_self() {
846 self.resolver.has_self.insert(item_def_id);
848 (Def::Method(item_def_id), ValueNS)
850 TraitItemKind::Type(..) => (Def::AssociatedTy(item_def_id), TypeNS),
851 TraitItemKind::Macro(_) => bug!(), // handled above
854 let vis = ty::Visibility::Public;
855 self.resolver.define(parent, item.ident, ns, (def, vis, item.span, self.expansion));
857 self.resolver.current_module = parent.parent.unwrap(); // nearest normal ancestor
858 visit::walk_trait_item(self, item);
859 self.resolver.current_module = parent;
862 fn visit_token(&mut self, t: Token) {
863 if let Token::Interpolated(nt) = t {
865 token::NtExpr(ref expr) => {
866 if let ast::ExprKind::Mac(..) = expr.node {
867 self.visit_invoc(expr.id);