1 //! Reduced graph building.
3 //! Here we build the "reduced graph": the graph of the module tree without
4 //! any imports resolved.
6 use crate::macros::{InvocationData, ParentScope, LegacyScope};
7 use crate::resolve_imports::ImportDirective;
8 use crate::resolve_imports::ImportDirectiveSubclass::{self, GlobImport, SingleImport};
9 use crate::{Module, ModuleData, ModuleKind, NameBinding, NameBindingKind, Segment, ToNameBinding};
10 use crate::{ModuleOrUniformRoot, PerNS, Resolver, ResolverArenas, ExternPreludeEntry};
11 use crate::Namespace::{self, TypeNS, ValueNS, MacroNS};
12 use crate::{resolve_error, resolve_struct_error, ResolutionError};
15 use rustc::hir::def::*;
16 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
18 use rustc::middle::cstore::CrateStore;
19 use rustc_metadata::cstore::LoadedMacro;
23 use rustc_data_structures::sync::Lrc;
25 use errors::Applicability;
27 use syntax::ast::{Name, Ident};
30 use syntax::ast::{self, Block, ForeignItem, ForeignItemKind, Item, ItemKind, NodeId};
31 use syntax::ast::{MetaItemKind, Mutability, StmtKind, TraitItem, TraitItemKind, Variant};
32 use syntax::ext::base::{MacroKind, SyntaxExtension};
33 use syntax::ext::base::Determinacy::Undetermined;
34 use syntax::ext::hygiene::Mark;
35 use syntax::ext::tt::macro_rules;
36 use syntax::feature_gate::is_builtin_attr;
37 use syntax::parse::token::{self, Token};
39 use syntax::std_inject::injected_crate_name;
40 use syntax::symbol::keywords;
41 use syntax::visit::{self, Visitor};
43 use syntax_pos::{Span, DUMMY_SP};
47 impl<'a> ToNameBinding<'a> for (Module<'a>, ty::Visibility, Span, Mark) {
48 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
49 arenas.alloc_name_binding(NameBinding {
50 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),
71 pub(crate) struct IsMacroExport;
73 impl<'a> ToNameBinding<'a> for (Def, ty::Visibility, Span, Mark, IsMacroExport) {
74 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
75 arenas.alloc_name_binding(NameBinding {
76 kind: NameBindingKind::Def(self.0, true),
85 impl<'a> Resolver<'a> {
86 /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
87 /// otherwise, reports an error.
88 pub fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T)
89 where T: ToNameBinding<'a>,
91 let binding = def.to_name_binding(self.arenas);
92 if let Err(old_binding) = self.try_define(parent, ident, ns, binding) {
93 self.report_conflict(parent, ident, ns, old_binding, &binding);
97 fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
98 // If any statements are items, we need to create an anonymous module
99 block.stmts.iter().any(|statement| match statement.node {
100 StmtKind::Item(_) | StmtKind::Mac(_) => true,
105 fn insert_field_names(&mut self, def_id: DefId, field_names: Vec<Name>) {
106 if !field_names.is_empty() {
107 self.field_names.insert(def_id, field_names);
111 fn build_reduced_graph_for_use_tree(
113 // This particular use tree
114 use_tree: &ast::UseTree,
116 parent_prefix: &[Segment],
118 // The whole `use` item
119 parent_scope: ParentScope<'a>,
124 debug!("build_reduced_graph_for_use_tree(parent_prefix={:?}, use_tree={:?}, nested={})",
125 parent_prefix, use_tree, nested);
127 let mut prefix_iter = parent_prefix.iter().cloned()
128 .chain(use_tree.prefix.segments.iter().map(|seg| seg.into())).peekable();
130 // On 2015 edition imports are resolved as crate-relative by default,
131 // so prefixes are prepended with crate root segment if necessary.
132 // The root is prepended lazily, when the first non-empty prefix or terminating glob
133 // appears, so imports in braced groups can have roots prepended independently.
134 // 2015 identifiers used on global 2018 edition enter special "virtual 2015 mode", don't
135 // get crate root prepended, but get special treatment during in-scope resolution instead.
136 let is_glob = if let ast::UseTreeKind::Glob = use_tree.kind { true } else { false };
137 let crate_root = match prefix_iter.peek() {
138 Some(seg) if !seg.ident.is_path_segment_keyword() &&
139 seg.ident.span.rust_2015() && self.session.rust_2015() => {
140 Some(seg.ident.span.ctxt())
142 None if is_glob && use_tree.span.rust_2015() => {
143 Some(use_tree.span.ctxt())
146 }.map(|ctxt| Segment::from_ident(Ident::new(
147 keywords::PathRoot.name(), use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt)
150 let prefix = crate_root.into_iter().chain(prefix_iter).collect::<Vec<_>>();
151 debug!("build_reduced_graph_for_use_tree: prefix={:?}", prefix);
153 let empty_for_self = |prefix: &[Segment]| {
155 prefix.len() == 1 && prefix[0].ident.name == keywords::PathRoot.name()
157 match use_tree.kind {
158 ast::UseTreeKind::Simple(rename, ..) => {
159 let mut ident = use_tree.ident().gensym_if_underscore();
160 let mut module_path = prefix;
161 let mut source = module_path.pop().unwrap();
162 let mut type_ns_only = false;
165 // Correctly handle `self`
166 if source.ident.name == keywords::SelfLower.name() {
169 if empty_for_self(&module_path) {
174 SelfImportOnlyInImportListWithNonEmptyPrefix
179 // Replace `use foo::self;` with `use foo;`
180 source = module_path.pop().unwrap();
181 if rename.is_none() {
182 ident = source.ident;
187 if source.ident.name == keywords::SelfLower.name() {
190 ResolutionError::SelfImportsOnlyAllowedWithin);
193 // Disallow `use $crate;`
194 if source.ident.name == keywords::DollarCrate.name() && module_path.is_empty() {
195 let crate_root = self.resolve_crate_root(source.ident);
196 let crate_name = match crate_root.kind {
197 ModuleKind::Def(_, name) => name,
198 ModuleKind::Block(..) => unreachable!(),
200 // HACK(eddyb) unclear how good this is, but keeping `$crate`
201 // in `source` breaks `src/test/compile-fail/import-crate-var.rs`,
202 // while the current crate doesn't have a valid `crate_name`.
203 if crate_name != keywords::Invalid.name() {
204 // `crate_name` should not be interpreted as relative.
205 module_path.push(Segment {
207 name: keywords::PathRoot.name(),
208 span: source.ident.span,
210 id: Some(self.session.next_node_id()),
212 source.ident.name = crate_name;
214 if rename.is_none() {
215 ident.name = crate_name;
218 self.session.struct_span_warn(item.span, "`$crate` may not be imported")
219 .note("`use $crate;` was erroneously allowed and \
220 will become a hard error in a future release")
225 if ident.name == keywords::Crate.name() {
226 self.session.span_err(ident.span,
227 "crate root imports need to be explicitly named: \
228 `use crate as name;`");
231 let subclass = SingleImport {
232 source: source.ident,
234 source_bindings: PerNS {
235 type_ns: Cell::new(Err(Undetermined)),
236 value_ns: Cell::new(Err(Undetermined)),
237 macro_ns: Cell::new(Err(Undetermined)),
239 target_bindings: PerNS {
240 type_ns: Cell::new(None),
241 value_ns: Cell::new(None),
242 macro_ns: Cell::new(None),
247 self.add_import_directive(
259 ast::UseTreeKind::Glob => {
260 let subclass = GlobImport {
261 is_prelude: attr::contains_name(&item.attrs, "prelude_import"),
262 max_vis: Cell::new(ty::Visibility::Invisible),
264 self.add_import_directive(
276 ast::UseTreeKind::Nested(ref items) => {
277 // Ensure there is at most one `self` in the list
278 let self_spans = items.iter().filter_map(|&(ref use_tree, _)| {
279 if let ast::UseTreeKind::Simple(..) = use_tree.kind {
280 if use_tree.ident().name == keywords::SelfLower.name() {
281 return Some(use_tree.span);
286 }).collect::<Vec<_>>();
287 if self_spans.len() > 1 {
288 let mut e = resolve_struct_error(self,
290 ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
292 for other_span in self_spans.iter().skip(1) {
293 e.span_label(*other_span, "another `self` import appears here");
299 for &(ref tree, id) in items {
300 self.build_reduced_graph_for_use_tree(
301 // This particular use tree
302 tree, id, &prefix, true,
303 // The whole `use` item
304 parent_scope.clone(), item, vis, root_span,
308 // Empty groups `a::b::{}` are turned into synthetic `self` imports
309 // `a::b::c::{self as _}`, so that their prefixes are correctly
310 // resolved and checked for privacy/stability/etc.
311 if items.is_empty() && !empty_for_self(&prefix) {
312 let new_span = prefix[prefix.len() - 1].ident.span;
313 let tree = ast::UseTree {
314 prefix: ast::Path::from_ident(
315 Ident::new(keywords::SelfLower.name(), new_span)
317 kind: ast::UseTreeKind::Simple(
318 Some(Ident::new(keywords::Underscore.name().gensymed(), new_span)),
324 self.build_reduced_graph_for_use_tree(
325 // This particular use tree
326 &tree, id, &prefix, true,
327 // The whole `use` item
328 parent_scope, item, ty::Visibility::Invisible, root_span,
335 /// Constructs the reduced graph for one item.
336 fn build_reduced_graph_for_item(&mut self, item: &Item, parent_scope: ParentScope<'a>) {
337 let parent = parent_scope.module;
338 let expansion = parent_scope.expansion;
339 let ident = item.ident.gensym_if_underscore();
341 let vis = self.resolve_visibility(&item.vis);
344 ItemKind::Use(ref use_tree) => {
345 self.build_reduced_graph_for_use_tree(
346 // This particular use tree
347 use_tree, item.id, &[], false,
348 // The whole `use` item
349 parent_scope, item, vis, use_tree.span,
353 ItemKind::ExternCrate(orig_name) => {
354 let module = if orig_name.is_none() && ident.name == keywords::SelfLower.name() {
356 .struct_span_err(item.span, "`extern crate self;` requires renaming")
360 "extern crate self as name;".into(),
361 Applicability::HasPlaceholders,
365 } else if orig_name == Some(keywords::SelfLower.name()) {
368 let crate_id = self.crate_loader.process_extern_crate(item, &self.definitions);
369 self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX })
372 self.populate_module_if_necessary(module);
373 if injected_crate_name().map_or(false, |name| ident.name == name) {
374 self.injected_crate = Some(module);
377 let used = self.process_legacy_macro_imports(item, module, &parent_scope);
379 (module, ty::Visibility::Public, sp, expansion).to_name_binding(self.arenas);
380 let directive = self.arenas.alloc_import_directive(ImportDirective {
384 imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
385 subclass: ImportDirectiveSubclass::ExternCrate {
389 has_attributes: !item.attrs.is_empty(),
390 use_span_with_attributes: item.span_with_attributes(),
392 root_span: item.span,
394 module_path: Vec::new(),
396 used: Cell::new(used),
398 self.potentially_unused_imports.push(directive);
399 let imported_binding = self.import(binding, directive);
400 if ptr::eq(self.current_module, self.graph_root) {
401 if let Some(entry) = self.extern_prelude.get(&ident.modern()) {
402 if expansion != Mark::root() && orig_name.is_some() &&
403 entry.extern_crate_item.is_none() {
404 self.session.span_err(item.span, "macro-expanded `extern crate` items \
405 cannot shadow names passed with \
409 let entry = self.extern_prelude.entry(ident.modern())
410 .or_insert(ExternPreludeEntry {
411 extern_crate_item: None,
412 introduced_by_item: true,
414 entry.extern_crate_item = Some(imported_binding);
415 if orig_name.is_some() {
416 entry.introduced_by_item = true;
419 self.define(parent, ident, TypeNS, imported_binding);
422 ItemKind::GlobalAsm(..) => {}
424 ItemKind::Mod(..) if ident == keywords::Invalid.ident() => {} // Crate root
426 ItemKind::Mod(..) => {
427 let def_id = self.definitions.local_def_id(item.id);
428 let module_kind = ModuleKind::Def(Def::Mod(def_id), ident.name);
429 let module = self.arenas.alloc_module(ModuleData {
430 no_implicit_prelude: parent.no_implicit_prelude || {
431 attr::contains_name(&item.attrs, "no_implicit_prelude")
433 ..ModuleData::new(Some(parent), module_kind, def_id, expansion, item.span)
435 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
436 self.module_map.insert(def_id, module);
438 // Descend into the module.
439 self.current_module = module;
442 // Handled in `rustc_metadata::{native_libs,link_args}`
443 ItemKind::ForeignMod(..) => {}
445 // These items live in the value namespace.
446 ItemKind::Static(_, m, _) => {
447 let mutbl = m == Mutability::Mutable;
448 let def = Def::Static(self.definitions.local_def_id(item.id), mutbl);
449 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
451 ItemKind::Const(..) => {
452 let def = Def::Const(self.definitions.local_def_id(item.id));
453 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
455 ItemKind::Fn(..) => {
456 let def = Def::Fn(self.definitions.local_def_id(item.id));
457 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
459 // Functions introducing procedural macros reserve a slot
460 // in the macro namespace as well (see #52225).
461 if attr::contains_name(&item.attrs, "proc_macro") ||
462 attr::contains_name(&item.attrs, "proc_macro_attribute") {
463 let def = Def::Macro(def.def_id(), MacroKind::ProcMacroStub);
464 self.define(parent, ident, MacroNS, (def, vis, sp, expansion));
466 if let Some(attr) = attr::find_by_name(&item.attrs, "proc_macro_derive") {
467 if let Some(trait_attr) =
468 attr.meta_item_list().and_then(|list| list.get(0).cloned()) {
469 if let Some(ident) = trait_attr.name().map(Ident::with_empty_ctxt) {
470 let sp = trait_attr.span;
471 let def = Def::Macro(def.def_id(), MacroKind::ProcMacroStub);
472 self.define(parent, ident, MacroNS, (def, vis, sp, expansion));
478 // These items live in the type namespace.
479 ItemKind::Ty(..) => {
480 let def = Def::TyAlias(self.definitions.local_def_id(item.id));
481 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
484 ItemKind::Existential(_, _) => {
485 let def = Def::Existential(self.definitions.local_def_id(item.id));
486 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
489 ItemKind::Enum(ref enum_definition, _) => {
490 let def = Def::Enum(self.definitions.local_def_id(item.id));
491 let module_kind = ModuleKind::Def(def, ident.name);
492 let module = self.new_module(parent,
494 parent.normal_ancestor_id,
497 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
499 for variant in &(*enum_definition).variants {
500 self.build_reduced_graph_for_variant(variant, module, vis, expansion);
504 ItemKind::TraitAlias(..) => {
505 let def = Def::TraitAlias(self.definitions.local_def_id(item.id));
506 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
509 // These items live in both the type and value namespaces.
510 ItemKind::Struct(ref struct_def, _) => {
511 // Define a name in the type namespace.
512 let def_id = self.definitions.local_def_id(item.id);
513 let def = Def::Struct(def_id);
514 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
516 let mut ctor_vis = vis;
518 let has_non_exhaustive = attr::contains_name(&item.attrs, "non_exhaustive");
520 // If the structure is marked as non_exhaustive then lower the visibility
521 // to within the crate.
522 if has_non_exhaustive && vis == ty::Visibility::Public {
523 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
526 // Record field names for error reporting.
527 let field_names = struct_def.fields().iter().filter_map(|field| {
528 let field_vis = self.resolve_visibility(&field.vis);
529 if ctor_vis.is_at_least(field_vis, &*self) {
530 ctor_vis = field_vis;
532 field.ident.map(|ident| ident.name)
534 let item_def_id = self.definitions.local_def_id(item.id);
535 self.insert_field_names(item_def_id, field_names);
537 // If this is a tuple or unit struct, define a name
538 // in the value namespace as well.
539 if !struct_def.is_struct() {
540 let ctor_def = Def::StructCtor(self.definitions.local_def_id(struct_def.id()),
541 CtorKind::from_ast(struct_def));
542 self.define(parent, ident, ValueNS, (ctor_def, ctor_vis, sp, expansion));
543 self.struct_constructors.insert(def.def_id(), (ctor_def, ctor_vis));
547 ItemKind::Union(ref vdata, _) => {
548 let def = Def::Union(self.definitions.local_def_id(item.id));
549 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
551 // Record field names for error reporting.
552 let field_names = vdata.fields().iter().filter_map(|field| {
553 self.resolve_visibility(&field.vis);
554 field.ident.map(|ident| ident.name)
556 let item_def_id = self.definitions.local_def_id(item.id);
557 self.insert_field_names(item_def_id, field_names);
560 ItemKind::Impl(..) => {}
562 ItemKind::Trait(..) => {
563 let def_id = self.definitions.local_def_id(item.id);
565 // Add all the items within to a new module.
566 let module_kind = ModuleKind::Def(Def::Trait(def_id), ident.name);
567 let module = self.new_module(parent,
569 parent.normal_ancestor_id,
572 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
573 self.current_module = module;
576 ItemKind::MacroDef(..) | ItemKind::Mac(_) => unreachable!(),
580 // Constructs the reduced graph for one variant. Variants exist in the
581 // type and value namespaces.
582 fn build_reduced_graph_for_variant(&mut self,
587 let ident = variant.node.ident;
588 let def_id = self.definitions.local_def_id(variant.node.data.id());
590 // Define a name in the type namespace.
591 let def = Def::Variant(def_id);
592 self.define(parent, ident, TypeNS, (def, vis, variant.span, expansion));
594 // Define a constructor name in the value namespace.
595 // Braced variants, unlike structs, generate unusable names in
596 // value namespace, they are reserved for possible future use.
597 let ctor_kind = CtorKind::from_ast(&variant.node.data);
598 let ctor_def = Def::VariantCtor(def_id, ctor_kind);
600 self.define(parent, ident, ValueNS, (ctor_def, vis, variant.span, expansion));
603 /// Constructs the reduced graph for one foreign item.
604 fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem, expansion: Mark) {
605 let (def, ns) = match item.node {
606 ForeignItemKind::Fn(..) => {
607 (Def::Fn(self.definitions.local_def_id(item.id)), ValueNS)
609 ForeignItemKind::Static(_, m) => {
610 (Def::Static(self.definitions.local_def_id(item.id), m), ValueNS)
612 ForeignItemKind::Ty => {
613 (Def::ForeignTy(self.definitions.local_def_id(item.id)), TypeNS)
615 ForeignItemKind::Macro(_) => unreachable!(),
617 let parent = self.current_module;
618 let vis = self.resolve_visibility(&item.vis);
619 self.define(parent, item.ident, ns, (def, vis, item.span, expansion));
622 fn build_reduced_graph_for_block(&mut self, block: &Block, expansion: Mark) {
623 let parent = self.current_module;
624 if self.block_needs_anonymous_module(block) {
625 let module = self.new_module(parent,
626 ModuleKind::Block(block.id),
627 parent.normal_ancestor_id,
630 self.block_map.insert(block.id, module);
631 self.current_module = module; // Descend into the block.
635 /// Builds the reduced graph for a single item in an external crate.
636 fn build_reduced_graph_for_external_crate_def(&mut self, parent: Module<'a>, child: Export) {
637 let Export { ident, def, vis, span } = child;
638 // FIXME: We shouldn't create the gensym here, it should come from metadata,
639 // but metadata cannot encode gensyms currently, so we create it here.
640 // This is only a guess, two equivalent idents may incorrectly get different gensyms here.
641 let ident = ident.gensym_if_underscore();
642 let def_id = def.def_id();
643 let expansion = Mark::root(); // FIXME(jseyfried) intercrate hygiene
645 Def::Mod(..) | Def::Enum(..) => {
646 let module = self.new_module(parent,
647 ModuleKind::Def(def, ident.name),
651 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
653 Def::Variant(..) | Def::TyAlias(..) | Def::ForeignTy(..) => {
654 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
656 Def::Fn(..) | Def::Static(..) | Def::Const(..) | Def::VariantCtor(..) => {
657 self.define(parent, ident, ValueNS, (def, vis, DUMMY_SP, expansion));
659 Def::StructCtor(..) => {
660 self.define(parent, ident, ValueNS, (def, vis, DUMMY_SP, expansion));
662 if let Some(struct_def_id) =
663 self.cstore.def_key(def_id).parent
664 .map(|index| DefId { krate: def_id.krate, index: index }) {
665 self.struct_constructors.insert(struct_def_id, (def, vis));
669 let module_kind = ModuleKind::Def(def, ident.name);
670 let module = self.new_module(parent,
672 parent.normal_ancestor_id,
675 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
677 for child in self.cstore.item_children_untracked(def_id, self.session) {
678 let ns = if let Def::AssociatedTy(..) = child.def { TypeNS } else { ValueNS };
679 self.define(module, child.ident, ns,
680 (child.def, ty::Visibility::Public, DUMMY_SP, expansion));
682 if self.cstore.associated_item_cloned_untracked(child.def.def_id())
683 .method_has_self_argument {
684 self.has_self.insert(child.def.def_id());
687 module.populated.set(true);
689 Def::Existential(..) |
690 Def::TraitAlias(..) => {
691 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
693 Def::Struct(..) | Def::Union(..) => {
694 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
696 // Record field names for error reporting.
697 let field_names = self.cstore.struct_field_names_untracked(def_id);
698 self.insert_field_names(def_id, field_names);
701 self.define(parent, ident, MacroNS, (def, vis, DUMMY_SP, expansion));
703 _ => bug!("unexpected definition: {:?}", def)
707 pub fn get_module(&mut self, def_id: DefId) -> Module<'a> {
708 if def_id.krate == LOCAL_CRATE {
709 return self.module_map[&def_id]
712 let macros_only = self.cstore.dep_kind_untracked(def_id.krate).macros_only();
713 if let Some(&module) = self.extern_module_map.get(&(def_id, macros_only)) {
717 let (name, parent) = if def_id.index == CRATE_DEF_INDEX {
718 (self.cstore.crate_name_untracked(def_id.krate).as_interned_str(), None)
720 let def_key = self.cstore.def_key(def_id);
721 (def_key.disambiguated_data.data.get_opt_name().unwrap(),
722 Some(self.get_module(DefId { index: def_key.parent.unwrap(), ..def_id })))
725 let kind = ModuleKind::Def(Def::Mod(def_id), name.as_symbol());
727 self.arenas.alloc_module(ModuleData::new(parent, kind, def_id, Mark::root(), DUMMY_SP));
728 self.extern_module_map.insert((def_id, macros_only), module);
732 pub fn macro_def_scope(&mut self, expansion: Mark) -> Module<'a> {
733 let def_id = self.macro_defs[&expansion];
734 if let Some(id) = self.definitions.as_local_node_id(def_id) {
735 self.local_macro_def_scopes[&id]
736 } else if def_id.krate == CrateNum::BuiltinMacros {
737 self.injected_crate.unwrap_or(self.graph_root)
739 let module_def_id = ty::DefIdTree::parent(&*self, def_id).unwrap();
740 self.get_module(module_def_id)
744 pub fn get_macro(&mut self, def: Def) -> Lrc<SyntaxExtension> {
745 let def_id = match def {
746 Def::Macro(def_id, ..) => def_id,
747 Def::NonMacroAttr(attr_kind) => return Lrc::new(SyntaxExtension::NonMacroAttr {
748 mark_used: attr_kind == NonMacroAttrKind::Tool,
750 _ => panic!("expected `Def::Macro` or `Def::NonMacroAttr`"),
752 if let Some(ext) = self.macro_map.get(&def_id) {
756 let macro_def = match self.cstore.load_macro_untracked(def_id, &self.session) {
757 LoadedMacro::MacroDef(macro_def) => macro_def,
758 LoadedMacro::ProcMacro(ext) => return ext,
761 let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
762 &self.session.features_untracked(),
764 self.cstore.crate_edition_untracked(def_id.krate)));
765 self.macro_map.insert(def_id, ext.clone());
769 /// Ensures that the reduced graph rooted at the given external module
770 /// is built, building it if it is not.
771 pub fn populate_module_if_necessary(&mut self, module: Module<'a>) {
772 if module.populated.get() { return }
773 let def_id = module.def_id().unwrap();
774 for child in self.cstore.item_children_untracked(def_id, self.session) {
775 self.build_reduced_graph_for_external_crate_def(module, child);
777 module.populated.set(true)
780 fn legacy_import_macro(&mut self,
782 binding: &'a NameBinding<'a>,
784 allow_shadowing: bool) {
785 if self.macro_use_prelude.insert(name, binding).is_some() && !allow_shadowing {
786 let msg = format!("`{}` is already in scope", name);
788 "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)";
789 self.session.struct_span_err(span, &msg).note(note).emit();
793 /// Returns `true` if we should consider the underlying `extern crate` to be used.
794 fn process_legacy_macro_imports(&mut self, item: &Item, module: Module<'a>,
795 parent_scope: &ParentScope<'a>) -> bool {
796 let mut import_all = None;
797 let mut single_imports = Vec::new();
798 for attr in &item.attrs {
799 if attr.check_name("macro_use") {
800 if self.current_module.parent.is_some() {
801 span_err!(self.session, item.span, E0468,
802 "an `extern crate` loading macros must be at the crate root");
804 if let ItemKind::ExternCrate(Some(orig_name)) = item.node {
805 if orig_name == keywords::SelfLower.name() {
806 self.session.span_err(attr.span,
807 "`macro_use` is not supported on `extern crate self`");
810 let ill_formed = |span| span_err!(self.session, span, E0466, "bad macro import");
812 Some(meta) => match meta.node {
813 MetaItemKind::Word => {
814 import_all = Some(meta.span);
817 MetaItemKind::List(nested_metas) => for nested_meta in nested_metas {
818 match nested_meta.word() {
819 Some(word) => single_imports.push((word.name(), word.span)),
820 None => ill_formed(nested_meta.span),
823 MetaItemKind::NameValue(..) => ill_formed(meta.span),
825 None => ill_formed(attr.span()),
830 let arenas = self.arenas;
831 let macro_use_directive = |span| arenas.alloc_import_directive(ImportDirective {
834 parent_scope: parent_scope.clone(),
835 imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
836 subclass: ImportDirectiveSubclass::MacroUse,
837 use_span_with_attributes: item.span_with_attributes(),
838 has_attributes: !item.attrs.is_empty(),
842 module_path: Vec::new(),
843 vis: Cell::new(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))),
844 used: Cell::new(false),
847 let allow_shadowing = parent_scope.expansion == Mark::root();
848 if let Some(span) = import_all {
849 let directive = macro_use_directive(span);
850 self.potentially_unused_imports.push(directive);
851 module.for_each_child(|ident, ns, binding| if ns == MacroNS {
852 let imported_binding = self.import(binding, directive);
853 self.legacy_import_macro(ident.name, imported_binding, span, allow_shadowing);
856 for (name, span) in single_imports.iter().cloned() {
857 let ident = Ident::with_empty_ctxt(name);
858 let result = self.resolve_ident_in_module(
859 ModuleOrUniformRoot::Module(module),
866 if let Ok(binding) = result {
867 let directive = macro_use_directive(span);
868 self.potentially_unused_imports.push(directive);
869 let imported_binding = self.import(binding, directive);
870 self.legacy_import_macro(name, imported_binding, span, allow_shadowing);
872 span_err!(self.session, span, E0469, "imported macro not found");
876 import_all.is_some() || !single_imports.is_empty()
879 /// Returns `true` if this attribute list contains `macro_use`.
880 fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool {
882 if attr.check_name("macro_escape") {
883 let msg = "macro_escape is a deprecated synonym for macro_use";
884 let mut err = self.session.struct_span_warn(attr.span, msg);
885 if let ast::AttrStyle::Inner = attr.style {
886 err.help("consider an outer attribute, #[macro_use] mod ...").emit();
890 } else if !attr.check_name("macro_use") {
895 self.session.span_err(attr.span, "arguments to macro_use are not allowed here");
904 pub struct BuildReducedGraphVisitor<'a, 'b: 'a> {
905 pub resolver: &'a mut Resolver<'b>,
906 pub current_legacy_scope: LegacyScope<'b>,
910 impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
911 fn visit_invoc(&mut self, id: ast::NodeId) -> &'b InvocationData<'b> {
912 let mark = id.placeholder_to_mark();
913 self.resolver.current_module.unresolved_invocations.borrow_mut().insert(mark);
914 let invocation = self.resolver.invocations[&mark];
915 invocation.module.set(self.resolver.current_module);
916 invocation.parent_legacy_scope.set(self.current_legacy_scope);
921 macro_rules! method {
922 ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
923 fn $visit(&mut self, node: &'a $ty) {
924 if let $invoc(..) = node.node {
925 self.visit_invoc(node.id);
927 visit::$walk(self, node);
933 impl<'a, 'b> Visitor<'a> for BuildReducedGraphVisitor<'a, 'b> {
934 method!(visit_impl_item: ast::ImplItem, ast::ImplItemKind::Macro, walk_impl_item);
935 method!(visit_expr: ast::Expr, ast::ExprKind::Mac, walk_expr);
936 method!(visit_pat: ast::Pat, ast::PatKind::Mac, walk_pat);
937 method!(visit_ty: ast::Ty, ast::TyKind::Mac, walk_ty);
939 fn visit_item(&mut self, item: &'a Item) {
940 let macro_use = match item.node {
941 ItemKind::MacroDef(..) => {
942 self.resolver.define_macro(item, self.expansion, &mut self.current_legacy_scope);
945 ItemKind::Mac(..) => {
946 self.current_legacy_scope = LegacyScope::Invocation(self.visit_invoc(item.id));
949 ItemKind::Mod(..) => self.resolver.contains_macro_use(&item.attrs),
953 let orig_current_module = self.resolver.current_module;
954 let orig_current_legacy_scope = self.current_legacy_scope;
955 let parent_scope = ParentScope {
956 module: self.resolver.current_module,
957 expansion: self.expansion,
958 legacy: self.current_legacy_scope,
961 self.resolver.build_reduced_graph_for_item(item, parent_scope);
962 visit::walk_item(self, item);
963 self.resolver.current_module = orig_current_module;
965 self.current_legacy_scope = orig_current_legacy_scope;
969 fn visit_stmt(&mut self, stmt: &'a ast::Stmt) {
970 if let ast::StmtKind::Mac(..) = stmt.node {
971 self.current_legacy_scope = LegacyScope::Invocation(self.visit_invoc(stmt.id));
973 visit::walk_stmt(self, stmt);
977 fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
978 if let ForeignItemKind::Macro(_) = foreign_item.node {
979 self.visit_invoc(foreign_item.id);
983 self.resolver.build_reduced_graph_for_foreign_item(foreign_item, self.expansion);
984 visit::walk_foreign_item(self, foreign_item);
987 fn visit_block(&mut self, block: &'a Block) {
988 let orig_current_module = self.resolver.current_module;
989 let orig_current_legacy_scope = self.current_legacy_scope;
990 self.resolver.build_reduced_graph_for_block(block, self.expansion);
991 visit::walk_block(self, block);
992 self.resolver.current_module = orig_current_module;
993 self.current_legacy_scope = orig_current_legacy_scope;
996 fn visit_trait_item(&mut self, item: &'a TraitItem) {
997 let parent = self.resolver.current_module;
999 if let TraitItemKind::Macro(_) = item.node {
1000 self.visit_invoc(item.id);
1004 // Add the item to the trait info.
1005 let item_def_id = self.resolver.definitions.local_def_id(item.id);
1006 let (def, ns) = match item.node {
1007 TraitItemKind::Const(..) => (Def::AssociatedConst(item_def_id), ValueNS),
1008 TraitItemKind::Method(ref sig, _) => {
1009 if sig.decl.has_self() {
1010 self.resolver.has_self.insert(item_def_id);
1012 (Def::Method(item_def_id), ValueNS)
1014 TraitItemKind::Type(..) => (Def::AssociatedTy(item_def_id), TypeNS),
1015 TraitItemKind::Macro(_) => bug!(), // handled above
1018 let vis = ty::Visibility::Public;
1019 self.resolver.define(parent, item.ident, ns, (def, vis, item.span, self.expansion));
1021 self.resolver.current_module = parent.parent.unwrap(); // nearest normal ancestor
1022 visit::walk_trait_item(self, item);
1023 self.resolver.current_module = parent;
1026 fn visit_token(&mut self, t: Token) {
1027 if let Token::Interpolated(nt) = t {
1028 if let token::NtExpr(ref expr) = nt.0 {
1029 if let ast::ExprKind::Mac(..) = expr.node {
1030 self.visit_invoc(expr.id);
1036 fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1037 if !attr.is_sugared_doc && is_builtin_attr(attr) {
1038 let parent_scope = ParentScope {
1039 module: self.resolver.current_module.nearest_item_scope(),
1040 expansion: self.expansion,
1041 legacy: self.current_legacy_scope,
1042 // Let's hope discerning built-in attributes from derive helpers is not necessary
1043 derives: Vec::new(),
1045 parent_scope.module.builtin_attrs.borrow_mut().push((
1046 attr.path.segments[0].ident, parent_scope
1049 visit::walk_attribute(self, attr);