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, false),
70 pub(crate) struct IsMacroExport;
72 impl<'a> ToNameBinding<'a> for (Def, ty::Visibility, Span, Mark, IsMacroExport) {
73 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
74 arenas.alloc_name_binding(NameBinding {
75 kind: NameBindingKind::Def(self.0, true),
83 #[derive(Default, PartialEq, Eq)]
84 struct LegacyMacroImports {
85 import_all: Option<Span>,
86 imports: Vec<(Name, Span)>,
89 impl<'a> Resolver<'a> {
90 /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
91 /// otherwise, reports an error.
92 pub fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T)
93 where T: ToNameBinding<'a>,
95 let binding = def.to_name_binding(self.arenas);
96 if let Err(old_binding) = self.try_define(parent, ident, ns, binding) {
97 self.report_conflict(parent, ident, ns, old_binding, &binding);
101 fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
102 // If any statements are items, we need to create an anonymous module
103 block.stmts.iter().any(|statement| match statement.node {
104 StmtKind::Item(_) | StmtKind::Mac(_) => true,
109 fn insert_field_names(&mut self, def_id: DefId, field_names: Vec<Name>) {
110 if !field_names.is_empty() {
111 self.field_names.insert(def_id, field_names);
115 fn build_reduced_graph_for_use_tree(&mut self,
116 root_use_tree: &ast::UseTree,
118 use_tree: &ast::UseTree,
125 let is_prelude = attr::contains_name(&item.attrs, "prelude_import");
126 let path = &use_tree.prefix;
128 let mut module_path: Vec<_> = prefix.segments.iter()
129 .chain(path.segments.iter())
130 .map(|seg| seg.ident)
133 match use_tree.kind {
134 ast::UseTreeKind::Simple(rename, ..) => {
135 let mut ident = use_tree.ident();
136 let mut source = module_path.pop().unwrap();
137 let mut type_ns_only = false;
140 // Correctly handle `self`
141 if source.name == keywords::SelfValue.name() {
144 let last_segment = *module_path.last().unwrap();
145 if last_segment.name == keywords::CrateRoot.name() {
150 SelfImportOnlyInImportListWithNonEmptyPrefix
155 // Replace `use foo::self;` with `use foo;`
156 let _ = module_path.pop();
157 source = last_segment;
158 if rename.is_none() {
159 ident = last_segment;
164 if source.name == keywords::SelfValue.name() {
167 ResolutionError::SelfImportsOnlyAllowedWithin);
170 // Disallow `use $crate;`
171 if source.name == keywords::DollarCrate.name() && path.segments.len() == 1 {
172 let crate_root = self.resolve_crate_root(source);
173 let crate_name = match crate_root.kind {
174 ModuleKind::Def(_, name) => name,
175 ModuleKind::Block(..) => unreachable!(),
177 source.name = crate_name;
178 if rename.is_none() {
179 ident.name = crate_name;
182 self.session.struct_span_warn(item.span, "`$crate` may not be imported")
183 .note("`use $crate;` was erroneously allowed and \
184 will become a hard error in a future release")
189 let subclass = SingleImport {
193 type_ns: Cell::new(Err(Undetermined)),
194 value_ns: Cell::new(Err(Undetermined)),
195 macro_ns: Cell::new(Err(Undetermined)),
199 self.add_import_directive(
210 ast::UseTreeKind::Glob => {
211 let subclass = GlobImport {
213 max_vis: Cell::new(ty::Visibility::Invisible),
215 self.add_import_directive(
226 ast::UseTreeKind::Nested(ref items) => {
227 let prefix = ast::Path {
228 segments: module_path.into_iter()
229 .map(|ident| ast::PathSegment::from_ident(ident))
234 // Ensure there is at most one `self` in the list
235 let self_spans = items.iter().filter_map(|&(ref use_tree, _)| {
236 if let ast::UseTreeKind::Simple(..) = use_tree.kind {
237 if use_tree.ident().name == keywords::SelfValue.name() {
238 return Some(use_tree.span);
243 }).collect::<Vec<_>>();
244 if self_spans.len() > 1 {
245 let mut e = resolve_struct_error(self,
247 ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
249 for other_span in self_spans.iter().skip(1) {
250 e.span_label(*other_span, "another `self` import appears here");
256 for &(ref tree, id) in items {
257 self.build_reduced_graph_for_use_tree(
258 root_use_tree, root_id, tree, id, vis, &prefix, true, item, expansion
265 /// Constructs the reduced graph for one item.
266 fn build_reduced_graph_for_item(&mut self, item: &Item, expansion: Mark) {
267 let parent = self.current_module;
268 let ident = item.ident;
270 let vis = self.resolve_visibility(&item.vis);
273 ItemKind::Use(ref use_tree) => {
274 // Imports are resolved as global by default, add starting root segment.
275 let prefix = ast::Path {
276 segments: use_tree.prefix.make_root().into_iter().collect(),
280 self.build_reduced_graph_for_use_tree(
281 use_tree, item.id, use_tree, item.id, vis, &prefix, false, item, expansion,
285 ItemKind::ExternCrate(orig_name) => {
286 let crate_id = self.crate_loader.process_extern_crate(item, &self.definitions);
288 self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
289 self.populate_module_if_necessary(module);
290 if injected_crate_name().map_or(false, |name| item.ident.name == name) {
291 self.injected_crate = Some(module);
294 let used = self.process_legacy_macro_imports(item, module, expansion);
296 (module, ty::Visibility::Public, sp, expansion).to_name_binding(self.arenas);
297 let directive = self.arenas.alloc_import_directive(ImportDirective {
301 imported_module: Cell::new(Some(module)),
302 subclass: ImportDirectiveSubclass::ExternCrate(orig_name),
303 root_span: item.span,
305 module_path: Vec::new(),
308 used: Cell::new(used),
310 self.potentially_unused_imports.push(directive);
311 let imported_binding = self.import(binding, directive);
312 self.define(parent, ident, TypeNS, imported_binding);
315 ItemKind::GlobalAsm(..) => {}
317 ItemKind::Mod(..) if item.ident == keywords::Invalid.ident() => {} // Crate root
319 ItemKind::Mod(..) => {
320 let def_id = self.definitions.local_def_id(item.id);
321 let module_kind = ModuleKind::Def(Def::Mod(def_id), ident.name);
322 let module = self.arenas.alloc_module(ModuleData {
323 no_implicit_prelude: parent.no_implicit_prelude || {
324 attr::contains_name(&item.attrs, "no_implicit_prelude")
326 ..ModuleData::new(Some(parent), module_kind, def_id, expansion, item.span)
328 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
329 self.module_map.insert(def_id, module);
331 // Descend into the module.
332 self.current_module = module;
335 // Handled in `rustc_metadata::{native_libs,link_args}`
336 ItemKind::ForeignMod(..) => {}
338 // These items live in the value namespace.
339 ItemKind::Static(_, m, _) => {
340 let mutbl = m == Mutability::Mutable;
341 let def = Def::Static(self.definitions.local_def_id(item.id), mutbl);
342 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
344 ItemKind::Const(..) => {
345 let def = Def::Const(self.definitions.local_def_id(item.id));
346 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
348 ItemKind::Fn(..) => {
349 let def = Def::Fn(self.definitions.local_def_id(item.id));
350 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
352 // Functions introducing procedural macros reserve a slot
353 // in the macro namespace as well (see #52225).
354 if attr::contains_name(&item.attrs, "proc_macro") ||
355 attr::contains_name(&item.attrs, "proc_macro_attribute") {
356 let def = Def::Macro(def.def_id(), MacroKind::ProcMacroStub);
357 self.define(parent, ident, MacroNS, (def, vis, sp, expansion));
359 if let Some(attr) = attr::find_by_name(&item.attrs, "proc_macro_derive") {
360 if let Some(trait_attr) =
361 attr.meta_item_list().and_then(|list| list.get(0).cloned()) {
362 if let Some(ident) = trait_attr.name().map(Ident::with_empty_ctxt) {
363 let sp = trait_attr.span;
364 let def = Def::Macro(def.def_id(), MacroKind::ProcMacroStub);
365 self.define(parent, ident, MacroNS, (def, vis, sp, expansion));
371 // These items live in the type namespace.
372 ItemKind::Ty(..) => {
373 let def = Def::TyAlias(self.definitions.local_def_id(item.id));
374 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
377 ItemKind::Existential(_, _) => {
378 let def = Def::Existential(self.definitions.local_def_id(item.id));
379 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
382 ItemKind::Enum(ref enum_definition, _) => {
383 let def = Def::Enum(self.definitions.local_def_id(item.id));
384 let module_kind = ModuleKind::Def(def, ident.name);
385 let module = self.new_module(parent,
387 parent.normal_ancestor_id,
390 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
392 for variant in &(*enum_definition).variants {
393 self.build_reduced_graph_for_variant(variant, module, vis, expansion);
397 ItemKind::TraitAlias(..) => {
398 let def = Def::TraitAlias(self.definitions.local_def_id(item.id));
399 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
402 // These items live in both the type and value namespaces.
403 ItemKind::Struct(ref struct_def, _) => {
404 // Define a name in the type namespace.
405 let def_id = self.definitions.local_def_id(item.id);
406 let def = Def::Struct(def_id);
407 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
409 let mut ctor_vis = vis;
411 let has_non_exhaustive = attr::contains_name(&item.attrs, "non_exhaustive");
413 // If the structure is marked as non_exhaustive then lower the visibility
414 // to within the crate.
415 if has_non_exhaustive && vis == ty::Visibility::Public {
416 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
419 // Record field names for error reporting.
420 let field_names = struct_def.fields().iter().filter_map(|field| {
421 let field_vis = self.resolve_visibility(&field.vis);
422 if ctor_vis.is_at_least(field_vis, &*self) {
423 ctor_vis = field_vis;
425 field.ident.map(|ident| ident.name)
427 let item_def_id = self.definitions.local_def_id(item.id);
428 self.insert_field_names(item_def_id, field_names);
430 // If this is a tuple or unit struct, define a name
431 // in the value namespace as well.
432 if !struct_def.is_struct() {
433 let ctor_def = Def::StructCtor(self.definitions.local_def_id(struct_def.id()),
434 CtorKind::from_ast(struct_def));
435 self.define(parent, ident, ValueNS, (ctor_def, ctor_vis, sp, expansion));
436 self.struct_constructors.insert(def.def_id(), (ctor_def, ctor_vis));
440 ItemKind::Union(ref vdata, _) => {
441 let def = Def::Union(self.definitions.local_def_id(item.id));
442 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
444 // Record field names for error reporting.
445 let field_names = vdata.fields().iter().filter_map(|field| {
446 self.resolve_visibility(&field.vis);
447 field.ident.map(|ident| ident.name)
449 let item_def_id = self.definitions.local_def_id(item.id);
450 self.insert_field_names(item_def_id, field_names);
453 ItemKind::Impl(..) => {}
455 ItemKind::Trait(..) => {
456 let def_id = self.definitions.local_def_id(item.id);
458 // Add all the items within to a new module.
459 let module_kind = ModuleKind::Def(Def::Trait(def_id), ident.name);
460 let module = self.new_module(parent,
462 parent.normal_ancestor_id,
465 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
466 self.current_module = module;
469 ItemKind::MacroDef(..) | ItemKind::Mac(_) => unreachable!(),
473 // Constructs the reduced graph for one variant. Variants exist in the
474 // type and value namespaces.
475 fn build_reduced_graph_for_variant(&mut self,
480 let ident = variant.node.ident;
481 let def_id = self.definitions.local_def_id(variant.node.data.id());
483 // Define a name in the type namespace.
484 let def = Def::Variant(def_id);
485 self.define(parent, ident, TypeNS, (def, vis, variant.span, expansion));
487 // Define a constructor name in the value namespace.
488 // Braced variants, unlike structs, generate unusable names in
489 // value namespace, they are reserved for possible future use.
490 let ctor_kind = CtorKind::from_ast(&variant.node.data);
491 let ctor_def = Def::VariantCtor(def_id, ctor_kind);
493 self.define(parent, ident, ValueNS, (ctor_def, vis, variant.span, expansion));
496 /// Constructs the reduced graph for one foreign item.
497 fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem, expansion: Mark) {
498 let (def, ns) = match item.node {
499 ForeignItemKind::Fn(..) => {
500 (Def::Fn(self.definitions.local_def_id(item.id)), ValueNS)
502 ForeignItemKind::Static(_, m) => {
503 (Def::Static(self.definitions.local_def_id(item.id), m), ValueNS)
505 ForeignItemKind::Ty => {
506 (Def::TyForeign(self.definitions.local_def_id(item.id)), TypeNS)
508 ForeignItemKind::Macro(_) => unreachable!(),
510 let parent = self.current_module;
511 let vis = self.resolve_visibility(&item.vis);
512 self.define(parent, item.ident, ns, (def, vis, item.span, expansion));
515 fn build_reduced_graph_for_block(&mut self, block: &Block, expansion: Mark) {
516 let parent = self.current_module;
517 if self.block_needs_anonymous_module(block) {
518 let module = self.new_module(parent,
519 ModuleKind::Block(block.id),
520 parent.normal_ancestor_id,
523 self.block_map.insert(block.id, module);
524 self.current_module = module; // Descend into the block.
528 /// Builds the reduced graph for a single item in an external crate.
529 fn build_reduced_graph_for_external_crate_def(&mut self, parent: Module<'a>, child: Export) {
530 let Export { ident, def, vis, span, .. } = child;
531 let def_id = def.def_id();
532 let expansion = Mark::root(); // FIXME(jseyfried) intercrate hygiene
534 Def::Mod(..) | Def::Enum(..) => {
535 let module = self.new_module(parent,
536 ModuleKind::Def(def, ident.name),
540 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
542 Def::Variant(..) | Def::TyAlias(..) | Def::TyForeign(..) => {
543 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
545 Def::Fn(..) | Def::Static(..) | Def::Const(..) | Def::VariantCtor(..) => {
546 self.define(parent, ident, ValueNS, (def, vis, DUMMY_SP, expansion));
548 Def::StructCtor(..) => {
549 self.define(parent, ident, ValueNS, (def, vis, DUMMY_SP, expansion));
551 if let Some(struct_def_id) =
552 self.cstore.def_key(def_id).parent
553 .map(|index| DefId { krate: def_id.krate, index: index }) {
554 self.struct_constructors.insert(struct_def_id, (def, vis));
558 let module_kind = ModuleKind::Def(def, ident.name);
559 let module = self.new_module(parent,
561 parent.normal_ancestor_id,
564 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
566 for child in self.cstore.item_children_untracked(def_id, self.session) {
567 let ns = if let Def::AssociatedTy(..) = child.def { TypeNS } else { ValueNS };
568 self.define(module, child.ident, ns,
569 (child.def, ty::Visibility::Public, DUMMY_SP, expansion));
571 if self.cstore.associated_item_cloned_untracked(child.def.def_id())
572 .method_has_self_argument {
573 self.has_self.insert(child.def.def_id());
576 module.populated.set(true);
578 Def::Struct(..) | Def::Union(..) => {
579 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
581 // Record field names for error reporting.
582 let field_names = self.cstore.struct_field_names_untracked(def_id);
583 self.insert_field_names(def_id, field_names);
586 self.define(parent, ident, MacroNS, (def, vis, DUMMY_SP, expansion));
588 _ => bug!("unexpected definition: {:?}", def)
592 pub fn get_module(&mut self, def_id: DefId) -> Module<'a> {
593 if def_id.krate == LOCAL_CRATE {
594 return self.module_map[&def_id]
597 let macros_only = self.cstore.dep_kind_untracked(def_id.krate).macros_only();
598 if let Some(&module) = self.extern_module_map.get(&(def_id, macros_only)) {
602 let (name, parent) = if def_id.index == CRATE_DEF_INDEX {
603 (self.cstore.crate_name_untracked(def_id.krate).as_interned_str(), None)
605 let def_key = self.cstore.def_key(def_id);
606 (def_key.disambiguated_data.data.get_opt_name().unwrap(),
607 Some(self.get_module(DefId { index: def_key.parent.unwrap(), ..def_id })))
610 let kind = ModuleKind::Def(Def::Mod(def_id), name.as_symbol());
612 self.arenas.alloc_module(ModuleData::new(parent, kind, def_id, Mark::root(), DUMMY_SP));
613 self.extern_module_map.insert((def_id, macros_only), module);
617 pub fn macro_def_scope(&mut self, expansion: Mark) -> Module<'a> {
618 let def_id = self.macro_defs[&expansion];
619 if let Some(id) = self.definitions.as_local_node_id(def_id) {
620 self.local_macro_def_scopes[&id]
621 } else if def_id.krate == BUILTIN_MACROS_CRATE {
622 self.injected_crate.unwrap_or(self.graph_root)
624 let module_def_id = ty::DefIdTree::parent(&*self, def_id).unwrap();
625 self.get_module(module_def_id)
629 pub fn get_macro(&mut self, def: Def) -> Lrc<SyntaxExtension> {
630 let def_id = match def {
631 Def::Macro(def_id, ..) => def_id,
632 Def::NonMacroAttr => return Lrc::new(SyntaxExtension::NonMacroAttr),
633 _ => panic!("Expected Def::Macro(..) or Def::NonMacroAttr"),
635 if let Some(ext) = self.macro_map.get(&def_id) {
639 let macro_def = match self.cstore.load_macro_untracked(def_id, &self.session) {
640 LoadedMacro::MacroDef(macro_def) => macro_def,
641 LoadedMacro::ProcMacro(ext) => return ext,
644 let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
645 &self.session.features_untracked(),
647 self.cstore.crate_edition_untracked(def_id.krate)));
648 self.macro_map.insert(def_id, ext.clone());
652 /// Ensures that the reduced graph rooted at the given external module
653 /// is built, building it if it is not.
654 pub fn populate_module_if_necessary(&mut self, module: Module<'a>) {
655 if module.populated.get() { return }
656 let def_id = module.def_id().unwrap();
657 for child in self.cstore.item_children_untracked(def_id, self.session) {
658 self.build_reduced_graph_for_external_crate_def(module, child);
660 module.populated.set(true)
663 fn legacy_import_macro(&mut self,
665 binding: &'a NameBinding<'a>,
667 allow_shadowing: bool) {
668 if self.macro_prelude.insert(name, binding).is_some() && !allow_shadowing {
669 let msg = format!("`{}` is already in scope", name);
671 "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)";
672 self.session.struct_span_err(span, &msg).note(note).emit();
676 // This returns true if we should consider the underlying `extern crate` to be used.
677 fn process_legacy_macro_imports(&mut self, item: &Item, module: Module<'a>, expansion: Mark)
679 let allow_shadowing = expansion == Mark::root();
680 let legacy_imports = self.legacy_macro_imports(&item.attrs);
681 let mut used = legacy_imports != LegacyMacroImports::default();
683 // `#[macro_use]` is only allowed at the crate root.
684 if self.current_module.parent.is_some() && used {
685 span_err!(self.session, item.span, E0468,
686 "an `extern crate` loading macros must be at the crate root");
687 } else if !self.use_extern_macros && !used &&
688 self.cstore.dep_kind_untracked(module.def_id().unwrap().krate)
690 let msg = "proc macro crates and `#[no_link]` crates have no effect without \
692 self.session.span_warn(item.span, msg);
693 used = true; // Avoid the normal unused extern crate warning
696 let (graph_root, arenas) = (self.graph_root, self.arenas);
697 let macro_use_directive = |span| arenas.alloc_import_directive(ImportDirective {
701 imported_module: Cell::new(Some(module)),
702 subclass: ImportDirectiveSubclass::MacroUse,
705 module_path: Vec::new(),
706 vis: Cell::new(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))),
708 used: Cell::new(false),
711 if let Some(span) = legacy_imports.import_all {
712 let directive = macro_use_directive(span);
713 self.potentially_unused_imports.push(directive);
714 module.for_each_child(|ident, ns, binding| if ns == MacroNS {
715 let imported_binding = self.import(binding, directive);
716 self.legacy_import_macro(ident.name, imported_binding, span, allow_shadowing);
719 for (name, span) in legacy_imports.imports {
720 let ident = Ident::with_empty_ctxt(name);
721 let result = self.resolve_ident_in_module(module, ident, MacroNS, false, span);
722 if let Ok(binding) = result {
723 let directive = macro_use_directive(span);
724 self.potentially_unused_imports.push(directive);
725 let imported_binding = self.import(binding, directive);
726 self.legacy_import_macro(name, imported_binding, span, allow_shadowing);
728 span_err!(self.session, span, E0469, "imported macro not found");
735 // does this attribute list contain "macro_use"?
736 fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool {
738 if attr.check_name("macro_escape") {
739 let msg = "macro_escape is a deprecated synonym for macro_use";
740 let mut err = self.session.struct_span_warn(attr.span, msg);
741 if let ast::AttrStyle::Inner = attr.style {
742 err.help("consider an outer attribute, #[macro_use] mod ...").emit();
746 } else if !attr.check_name("macro_use") {
751 self.session.span_err(attr.span, "arguments to macro_use are not allowed here");
759 fn legacy_macro_imports(&mut self, attrs: &[ast::Attribute]) -> LegacyMacroImports {
760 let mut imports = LegacyMacroImports::default();
762 if attr.check_name("macro_use") {
763 match attr.meta_item_list() {
764 Some(names) => for attr in names {
765 if let Some(word) = attr.word() {
766 imports.imports.push((word.name(), attr.span()));
768 span_err!(self.session, attr.span(), E0466, "bad macro import");
771 None => imports.import_all = Some(attr.span),
779 pub struct BuildReducedGraphVisitor<'a, 'b: 'a> {
780 pub resolver: &'a mut Resolver<'b>,
781 pub legacy_scope: LegacyScope<'b>,
785 impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
786 fn visit_invoc(&mut self, id: ast::NodeId) -> &'b InvocationData<'b> {
787 let mark = id.placeholder_to_mark();
788 self.resolver.current_module.unresolved_invocations.borrow_mut().insert(mark);
789 self.resolver.unresolved_invocations_macro_export.insert(mark);
790 let invocation = self.resolver.invocations[&mark];
791 invocation.module.set(self.resolver.current_module);
792 invocation.legacy_scope.set(self.legacy_scope);
797 macro_rules! method {
798 ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
799 fn $visit(&mut self, node: &'a $ty) {
800 if let $invoc(..) = node.node {
801 self.visit_invoc(node.id);
803 visit::$walk(self, node);
809 impl<'a, 'b> Visitor<'a> for BuildReducedGraphVisitor<'a, 'b> {
810 method!(visit_impl_item: ast::ImplItem, ast::ImplItemKind::Macro, walk_impl_item);
811 method!(visit_expr: ast::Expr, ast::ExprKind::Mac, walk_expr);
812 method!(visit_pat: ast::Pat, ast::PatKind::Mac, walk_pat);
813 method!(visit_ty: ast::Ty, ast::TyKind::Mac, walk_ty);
815 fn visit_item(&mut self, item: &'a Item) {
816 let macro_use = match item.node {
817 ItemKind::MacroDef(..) => {
818 self.resolver.define_macro(item, self.expansion, &mut self.legacy_scope);
821 ItemKind::Mac(..) => {
822 self.legacy_scope = LegacyScope::Expansion(self.visit_invoc(item.id));
825 ItemKind::Mod(..) => self.resolver.contains_macro_use(&item.attrs),
829 let (parent, legacy_scope) = (self.resolver.current_module, self.legacy_scope);
830 self.resolver.build_reduced_graph_for_item(item, self.expansion);
831 visit::walk_item(self, item);
832 self.resolver.current_module = parent;
834 self.legacy_scope = legacy_scope;
838 fn visit_stmt(&mut self, stmt: &'a ast::Stmt) {
839 if let ast::StmtKind::Mac(..) = stmt.node {
840 self.legacy_scope = LegacyScope::Expansion(self.visit_invoc(stmt.id));
842 visit::walk_stmt(self, stmt);
846 fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
847 if let ForeignItemKind::Macro(_) = foreign_item.node {
848 self.visit_invoc(foreign_item.id);
852 self.resolver.build_reduced_graph_for_foreign_item(foreign_item, self.expansion);
853 visit::walk_foreign_item(self, foreign_item);
856 fn visit_block(&mut self, block: &'a Block) {
857 let (parent, legacy_scope) = (self.resolver.current_module, self.legacy_scope);
858 self.resolver.build_reduced_graph_for_block(block, self.expansion);
859 visit::walk_block(self, block);
860 self.resolver.current_module = parent;
861 self.legacy_scope = legacy_scope;
864 fn visit_trait_item(&mut self, item: &'a TraitItem) {
865 let parent = self.resolver.current_module;
867 if let TraitItemKind::Macro(_) = item.node {
868 self.visit_invoc(item.id);
872 // Add the item to the trait info.
873 let item_def_id = self.resolver.definitions.local_def_id(item.id);
874 let (def, ns) = match item.node {
875 TraitItemKind::Const(..) => (Def::AssociatedConst(item_def_id), ValueNS),
876 TraitItemKind::Method(ref sig, _) => {
877 if sig.decl.has_self() {
878 self.resolver.has_self.insert(item_def_id);
880 (Def::Method(item_def_id), ValueNS)
882 TraitItemKind::Type(..) => (Def::AssociatedTy(item_def_id), TypeNS),
883 TraitItemKind::Macro(_) => bug!(), // handled above
886 let vis = ty::Visibility::Public;
887 self.resolver.define(parent, item.ident, ns, (def, vis, item.span, self.expansion));
889 self.resolver.current_module = parent.parent.unwrap(); // nearest normal ancestor
890 visit::walk_trait_item(self, item);
891 self.resolver.current_module = parent;
894 fn visit_token(&mut self, t: Token) {
895 if let Token::Interpolated(nt) = t {
897 token::NtExpr(ref expr) => {
898 if let ast::ExprKind::Mac(..) = expr.node {
899 self.visit_invoc(expr.id);