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, 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, ParentScope, PerNS, Resolver, ResolverArenas, ExternPreludeEntry};
11 use crate::Namespace::{self, TypeNS, ValueNS, MacroNS};
12 use crate::{resolve_error, resolve_struct_error, ResolutionError, Determinacy};
15 use rustc::hir::def::{self, *};
16 use rustc::hir::def_id::{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, StmtKind, TraitItem, TraitItemKind, Variant};
32 use syntax::ext::base::SyntaxExtension;
33 use syntax::ext::hygiene::ExpnId;
34 use syntax::feature_gate::is_builtin_attr;
35 use syntax::parse::token::{self, Token};
37 use syntax::symbol::{kw, sym};
38 use syntax::visit::{self, Visitor};
40 use syntax_pos::{Span, DUMMY_SP};
44 type Res = def::Res<NodeId>;
46 impl<'a> ToNameBinding<'a> for (Module<'a>, ty::Visibility, Span, ExpnId) {
47 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
48 arenas.alloc_name_binding(NameBinding {
49 kind: NameBindingKind::Module(self.0),
58 impl<'a> ToNameBinding<'a> for (Res, ty::Visibility, Span, ExpnId) {
59 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
60 arenas.alloc_name_binding(NameBinding {
61 kind: NameBindingKind::Res(self.0, false),
70 pub(crate) struct IsMacroExport;
72 impl<'a> ToNameBinding<'a> for (Res, ty::Visibility, Span, ExpnId, IsMacroExport) {
73 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
74 arenas.alloc_name_binding(NameBinding {
75 kind: NameBindingKind::Res(self.0, true),
84 impl<'a> Resolver<'a> {
85 /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
86 /// otherwise, reports an error.
87 pub fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T)
88 where T: ToNameBinding<'a>,
90 let binding = def.to_name_binding(self.arenas);
91 if let Err(old_binding) = self.try_define(parent, ident, ns, binding) {
92 self.report_conflict(parent, ident, ns, old_binding, &binding);
96 fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
97 // If any statements are items, we need to create an anonymous module
98 block.stmts.iter().any(|statement| match statement.node {
99 StmtKind::Item(_) | StmtKind::Mac(_) => true,
104 fn insert_field_names(&mut self, def_id: DefId, field_names: Vec<Name>) {
105 if !field_names.is_empty() {
106 self.field_names.insert(def_id, field_names);
110 fn build_reduced_graph_for_use_tree(
112 // This particular use tree
113 use_tree: &ast::UseTree,
115 parent_prefix: &[Segment],
117 // The whole `use` item
118 parent_scope: ParentScope<'a>,
123 debug!("build_reduced_graph_for_use_tree(parent_prefix={:?}, use_tree={:?}, nested={})",
124 parent_prefix, use_tree, nested);
126 let mut prefix_iter = parent_prefix.iter().cloned()
127 .chain(use_tree.prefix.segments.iter().map(|seg| seg.into())).peekable();
129 // On 2015 edition imports are resolved as crate-relative by default,
130 // so prefixes are prepended with crate root segment if necessary.
131 // The root is prepended lazily, when the first non-empty prefix or terminating glob
132 // appears, so imports in braced groups can have roots prepended independently.
133 let is_glob = if let ast::UseTreeKind::Glob = use_tree.kind { true } else { false };
134 let crate_root = match prefix_iter.peek() {
135 Some(seg) if !seg.ident.is_path_segment_keyword() && seg.ident.span.rust_2015() => {
136 Some(seg.ident.span.ctxt())
138 None if is_glob && use_tree.span.rust_2015() => {
139 Some(use_tree.span.ctxt())
142 }.map(|ctxt| Segment::from_ident(Ident::new(
143 kw::PathRoot, use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt)
146 let prefix = crate_root.into_iter().chain(prefix_iter).collect::<Vec<_>>();
147 debug!("build_reduced_graph_for_use_tree: prefix={:?}", prefix);
149 let empty_for_self = |prefix: &[Segment]| {
151 prefix.len() == 1 && prefix[0].ident.name == kw::PathRoot
153 match use_tree.kind {
154 ast::UseTreeKind::Simple(rename, ..) => {
155 let mut ident = use_tree.ident().gensym_if_underscore();
156 let mut module_path = prefix;
157 let mut source = module_path.pop().unwrap();
158 let mut type_ns_only = false;
161 // Correctly handle `self`
162 if source.ident.name == kw::SelfLower {
165 if empty_for_self(&module_path) {
170 SelfImportOnlyInImportListWithNonEmptyPrefix
175 // Replace `use foo::self;` with `use foo;`
176 source = module_path.pop().unwrap();
177 if rename.is_none() {
178 ident = source.ident;
183 if source.ident.name == kw::SelfLower {
186 ResolutionError::SelfImportsOnlyAllowedWithin);
189 // Disallow `use $crate;`
190 if source.ident.name == kw::DollarCrate && module_path.is_empty() {
191 let crate_root = self.resolve_crate_root(source.ident);
192 let crate_name = match crate_root.kind {
193 ModuleKind::Def(.., name) => name,
194 ModuleKind::Block(..) => unreachable!(),
196 // HACK(eddyb) unclear how good this is, but keeping `$crate`
197 // in `source` breaks `src/test/compile-fail/import-crate-var.rs`,
198 // while the current crate doesn't have a valid `crate_name`.
199 if crate_name != kw::Invalid {
200 // `crate_name` should not be interpreted as relative.
201 module_path.push(Segment {
204 span: source.ident.span,
206 id: Some(self.session.next_node_id()),
208 source.ident.name = crate_name;
210 if rename.is_none() {
211 ident.name = crate_name;
214 self.session.struct_span_warn(item.span, "`$crate` may not be imported")
215 .note("`use $crate;` was erroneously allowed and \
216 will become a hard error in a future release")
221 if ident.name == kw::Crate {
222 self.session.span_err(ident.span,
223 "crate root imports need to be explicitly named: \
224 `use crate as name;`");
227 let subclass = SingleImport {
228 source: source.ident,
230 source_bindings: PerNS {
231 type_ns: Cell::new(Err(Determinacy::Undetermined)),
232 value_ns: Cell::new(Err(Determinacy::Undetermined)),
233 macro_ns: Cell::new(Err(Determinacy::Undetermined)),
235 target_bindings: PerNS {
236 type_ns: Cell::new(None),
237 value_ns: Cell::new(None),
238 macro_ns: Cell::new(None),
243 self.add_import_directive(
255 ast::UseTreeKind::Glob => {
256 let subclass = GlobImport {
257 is_prelude: attr::contains_name(&item.attrs, sym::prelude_import),
258 max_vis: Cell::new(ty::Visibility::Invisible),
260 self.add_import_directive(
272 ast::UseTreeKind::Nested(ref items) => {
273 // Ensure there is at most one `self` in the list
274 let self_spans = items.iter().filter_map(|&(ref use_tree, _)| {
275 if let ast::UseTreeKind::Simple(..) = use_tree.kind {
276 if use_tree.ident().name == kw::SelfLower {
277 return Some(use_tree.span);
282 }).collect::<Vec<_>>();
283 if self_spans.len() > 1 {
284 let mut e = resolve_struct_error(self,
286 ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
288 for other_span in self_spans.iter().skip(1) {
289 e.span_label(*other_span, "another `self` import appears here");
295 for &(ref tree, id) in items {
296 self.build_reduced_graph_for_use_tree(
297 // This particular use tree
298 tree, id, &prefix, true,
299 // The whole `use` item
300 parent_scope.clone(), item, vis, root_span,
304 // Empty groups `a::b::{}` are turned into synthetic `self` imports
305 // `a::b::c::{self as _}`, so that their prefixes are correctly
306 // resolved and checked for privacy/stability/etc.
307 if items.is_empty() && !empty_for_self(&prefix) {
308 let new_span = prefix[prefix.len() - 1].ident.span;
309 let tree = ast::UseTree {
310 prefix: ast::Path::from_ident(
311 Ident::new(kw::SelfLower, new_span)
313 kind: ast::UseTreeKind::Simple(
314 Some(Ident::new(kw::Underscore, new_span)),
320 self.build_reduced_graph_for_use_tree(
321 // This particular use tree
322 &tree, id, &prefix, true,
323 // The whole `use` item
324 parent_scope, item, ty::Visibility::Invisible, root_span,
331 /// Constructs the reduced graph for one item.
332 fn build_reduced_graph_for_item(&mut self, item: &Item, parent_scope: ParentScope<'a>) {
333 let parent = parent_scope.module;
334 let expansion = parent_scope.expansion;
335 let ident = item.ident.gensym_if_underscore();
337 let vis = self.resolve_visibility(&item.vis);
340 ItemKind::Use(ref use_tree) => {
341 self.build_reduced_graph_for_use_tree(
342 // This particular use tree
343 use_tree, item.id, &[], false,
344 // The whole `use` item
345 parent_scope, item, vis, use_tree.span,
349 ItemKind::ExternCrate(orig_name) => {
350 let module = if orig_name.is_none() && ident.name == kw::SelfLower {
352 .struct_span_err(item.span, "`extern crate self;` requires renaming")
356 "extern crate self as name;".into(),
357 Applicability::HasPlaceholders,
361 } else if orig_name == Some(kw::SelfLower) {
364 let crate_id = self.crate_loader.process_extern_crate(item, &self.definitions);
365 self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX })
368 self.populate_module_if_necessary(module);
369 if let Some(name) = self.session.parse_sess.injected_crate_name.try_get() {
370 if name.as_str() == ident.name.as_str() {
371 self.injected_crate = Some(module);
375 let used = self.process_legacy_macro_imports(item, module, &parent_scope);
377 (module, ty::Visibility::Public, sp, expansion).to_name_binding(self.arenas);
378 let directive = self.arenas.alloc_import_directive(ImportDirective {
382 imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
383 subclass: ImportDirectiveSubclass::ExternCrate {
387 has_attributes: !item.attrs.is_empty(),
388 use_span_with_attributes: item.span_with_attributes(),
390 root_span: item.span,
392 module_path: Vec::new(),
394 used: Cell::new(used),
396 self.potentially_unused_imports.push(directive);
397 let imported_binding = self.import(binding, directive);
398 if ptr::eq(self.current_module, self.graph_root) {
399 if let Some(entry) = self.extern_prelude.get(&ident.modern()) {
400 if expansion != ExpnId::root() && orig_name.is_some() &&
401 entry.extern_crate_item.is_none() {
402 self.session.span_err(item.span, "macro-expanded `extern crate` items \
403 cannot shadow names passed with \
407 let entry = self.extern_prelude.entry(ident.modern())
408 .or_insert(ExternPreludeEntry {
409 extern_crate_item: None,
410 introduced_by_item: true,
412 entry.extern_crate_item = Some(imported_binding);
413 if orig_name.is_some() {
414 entry.introduced_by_item = true;
417 self.define(parent, ident, TypeNS, imported_binding);
420 ItemKind::GlobalAsm(..) => {}
422 ItemKind::Mod(..) if ident.name == kw::Invalid => {} // Crate root
424 ItemKind::Mod(..) => {
425 let def_id = self.definitions.local_def_id(item.id);
426 let module_kind = ModuleKind::Def(DefKind::Mod, def_id, ident.name);
427 let module = self.arenas.alloc_module(ModuleData {
428 no_implicit_prelude: parent.no_implicit_prelude || {
429 attr::contains_name(&item.attrs, sym::no_implicit_prelude)
431 ..ModuleData::new(Some(parent), module_kind, def_id, expansion, item.span)
433 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
434 self.module_map.insert(def_id, module);
436 // Descend into the module.
437 self.current_module = module;
440 // Handled in `rustc_metadata::{native_libs,link_args}`
441 ItemKind::ForeignMod(..) => {}
443 // These items live in the value namespace.
444 ItemKind::Static(..) => {
445 let res = Res::Def(DefKind::Static, self.definitions.local_def_id(item.id));
446 self.define(parent, ident, ValueNS, (res, vis, sp, expansion));
448 ItemKind::Const(..) => {
449 let res = Res::Def(DefKind::Const, self.definitions.local_def_id(item.id));
450 self.define(parent, ident, ValueNS, (res, vis, sp, expansion));
452 ItemKind::Fn(..) => {
453 let res = Res::Def(DefKind::Fn, self.definitions.local_def_id(item.id));
454 self.define(parent, ident, ValueNS, (res, vis, sp, expansion));
456 // Functions introducing procedural macros reserve a slot
457 // in the macro namespace as well (see #52225).
458 self.define_macro(item, expansion, &mut LegacyScope::Empty);
461 // These items live in the type namespace.
462 ItemKind::Ty(..) => {
463 let res = Res::Def(DefKind::TyAlias, self.definitions.local_def_id(item.id));
464 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
467 ItemKind::OpaqueTy(_, _) => {
468 let res = Res::Def(DefKind::OpaqueTy, self.definitions.local_def_id(item.id));
469 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
472 ItemKind::Enum(ref enum_definition, _) => {
473 let module_kind = ModuleKind::Def(
475 self.definitions.local_def_id(item.id),
478 let module = self.new_module(parent,
480 parent.normal_ancestor_id,
483 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
485 for variant in &(*enum_definition).variants {
486 self.build_reduced_graph_for_variant(variant, module, vis, expansion);
490 ItemKind::TraitAlias(..) => {
491 let res = Res::Def(DefKind::TraitAlias, self.definitions.local_def_id(item.id));
492 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
495 // These items live in both the type and value namespaces.
496 ItemKind::Struct(ref struct_def, _) => {
497 // Define a name in the type namespace.
498 let def_id = self.definitions.local_def_id(item.id);
499 let res = Res::Def(DefKind::Struct, def_id);
500 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
502 let mut ctor_vis = vis;
504 let has_non_exhaustive = attr::contains_name(&item.attrs, sym::non_exhaustive);
506 // If the structure is marked as non_exhaustive then lower the visibility
507 // to within the crate.
508 if has_non_exhaustive && vis == ty::Visibility::Public {
509 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
512 // Record field names for error reporting.
513 let field_names = struct_def.fields().iter().filter_map(|field| {
514 let field_vis = self.resolve_visibility(&field.vis);
515 if ctor_vis.is_at_least(field_vis, &*self) {
516 ctor_vis = field_vis;
518 field.ident.map(|ident| ident.name)
520 let item_def_id = self.definitions.local_def_id(item.id);
521 self.insert_field_names(item_def_id, field_names);
523 // If this is a tuple or unit struct, define a name
524 // in the value namespace as well.
525 if let Some(ctor_node_id) = struct_def.ctor_id() {
526 let ctor_res = Res::Def(
527 DefKind::Ctor(CtorOf::Struct, CtorKind::from_ast(struct_def)),
528 self.definitions.local_def_id(ctor_node_id),
530 self.define(parent, ident, ValueNS, (ctor_res, ctor_vis, sp, expansion));
531 self.struct_constructors.insert(res.def_id(), (ctor_res, ctor_vis));
535 ItemKind::Union(ref vdata, _) => {
536 let res = Res::Def(DefKind::Union, self.definitions.local_def_id(item.id));
537 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
539 // Record field names for error reporting.
540 let field_names = vdata.fields().iter().filter_map(|field| {
541 self.resolve_visibility(&field.vis);
542 field.ident.map(|ident| ident.name)
544 let item_def_id = self.definitions.local_def_id(item.id);
545 self.insert_field_names(item_def_id, field_names);
548 ItemKind::Impl(..) => {}
550 ItemKind::Trait(..) => {
551 let def_id = self.definitions.local_def_id(item.id);
553 // Add all the items within to a new module.
554 let module_kind = ModuleKind::Def(DefKind::Trait, def_id, ident.name);
555 let module = self.new_module(parent,
557 parent.normal_ancestor_id,
560 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
561 self.current_module = module;
564 ItemKind::MacroDef(..) | ItemKind::Mac(_) => unreachable!(),
568 // Constructs the reduced graph for one variant. Variants exist in the
569 // type and value namespaces.
570 fn build_reduced_graph_for_variant(&mut self,
575 let ident = variant.node.ident;
577 // Define a name in the type namespace.
578 let def_id = self.definitions.local_def_id(variant.node.id);
579 let res = Res::Def(DefKind::Variant, def_id);
580 self.define(parent, ident, TypeNS, (res, vis, variant.span, expn_id));
582 // If the variant is marked as non_exhaustive then lower the visibility to within the
584 let mut ctor_vis = vis;
585 let has_non_exhaustive = attr::contains_name(&variant.node.attrs, sym::non_exhaustive);
586 if has_non_exhaustive && vis == ty::Visibility::Public {
587 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
590 // Define a constructor name in the value namespace.
591 // Braced variants, unlike structs, generate unusable names in
592 // value namespace, they are reserved for possible future use.
593 // It's ok to use the variant's id as a ctor id since an
594 // error will be reported on any use of such resolution anyway.
595 let ctor_node_id = variant.node.data.ctor_id().unwrap_or(variant.node.id);
596 let ctor_def_id = self.definitions.local_def_id(ctor_node_id);
597 let ctor_kind = CtorKind::from_ast(&variant.node.data);
598 let ctor_res = Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id);
599 self.define(parent, ident, ValueNS, (ctor_res, ctor_vis, variant.span, expn_id));
602 /// Constructs the reduced graph for one foreign item.
603 fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem, expn_id: ExpnId) {
604 let (res, ns) = match item.node {
605 ForeignItemKind::Fn(..) => {
606 (Res::Def(DefKind::Fn, self.definitions.local_def_id(item.id)), ValueNS)
608 ForeignItemKind::Static(..) => {
609 (Res::Def(DefKind::Static, self.definitions.local_def_id(item.id)), ValueNS)
611 ForeignItemKind::Ty => {
612 (Res::Def(DefKind::ForeignTy, self.definitions.local_def_id(item.id)), TypeNS)
614 ForeignItemKind::Macro(_) => unreachable!(),
616 let parent = self.current_module;
617 let vis = self.resolve_visibility(&item.vis);
618 self.define(parent, item.ident, ns, (res, vis, item.span, expn_id));
621 fn build_reduced_graph_for_block(&mut self, block: &Block, expn_id: ExpnId) {
622 let parent = self.current_module;
623 if self.block_needs_anonymous_module(block) {
624 let module = self.new_module(parent,
625 ModuleKind::Block(block.id),
626 parent.normal_ancestor_id,
629 self.block_map.insert(block.id, module);
630 self.current_module = module; // Descend into the block.
634 /// Builds the reduced graph for a single item in an external crate.
635 fn build_reduced_graph_for_external_crate_res(
638 child: Export<ast::NodeId>,
640 let Export { ident, res, vis, span } = child;
641 // FIXME: We shouldn't create the gensym here, it should come from metadata,
642 // but metadata cannot encode gensyms currently, so we create it here.
643 // This is only a guess, two equivalent idents may incorrectly get different gensyms here.
644 let ident = ident.gensym_if_underscore();
645 let expansion = ExpnId::root(); // FIXME(jseyfried) intercrate hygiene
647 Res::Def(kind @ DefKind::Mod, def_id)
648 | Res::Def(kind @ DefKind::Enum, def_id) => {
649 let module = self.new_module(parent,
650 ModuleKind::Def(kind, def_id, ident.name),
654 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
656 Res::Def(DefKind::Variant, _)
657 | Res::Def(DefKind::TyAlias, _)
658 | Res::Def(DefKind::ForeignTy, _)
659 | Res::Def(DefKind::OpaqueTy, _)
660 | Res::Def(DefKind::TraitAlias, _)
663 self.define(parent, ident, TypeNS, (res, vis, DUMMY_SP, expansion));
665 Res::Def(DefKind::Fn, _)
666 | Res::Def(DefKind::Static, _)
667 | Res::Def(DefKind::Const, _)
668 | Res::Def(DefKind::Ctor(CtorOf::Variant, ..), _) => {
669 self.define(parent, ident, ValueNS, (res, vis, DUMMY_SP, expansion));
671 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), def_id) => {
672 self.define(parent, ident, ValueNS, (res, vis, DUMMY_SP, expansion));
674 if let Some(struct_def_id) =
675 self.cstore.def_key(def_id).parent
676 .map(|index| DefId { krate: def_id.krate, index: index }) {
677 self.struct_constructors.insert(struct_def_id, (res, vis));
680 Res::Def(DefKind::Trait, def_id) => {
681 let module_kind = ModuleKind::Def(DefKind::Trait, def_id, ident.name);
682 let module = self.new_module(parent,
684 parent.normal_ancestor_id,
687 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
689 for child in self.cstore.item_children_untracked(def_id, self.session) {
690 let res = child.res.map_id(|_| panic!("unexpected id"));
691 let ns = if let Res::Def(DefKind::AssocTy, _) = res {
694 self.define(module, child.ident, ns,
695 (res, ty::Visibility::Public, DUMMY_SP, expansion));
697 if self.cstore.associated_item_cloned_untracked(child.res.def_id())
698 .method_has_self_argument {
699 self.has_self.insert(res.def_id());
702 module.populated.set(true);
704 Res::Def(DefKind::Struct, def_id) | Res::Def(DefKind::Union, def_id) => {
705 self.define(parent, ident, TypeNS, (res, vis, DUMMY_SP, expansion));
707 // Record field names for error reporting.
708 let field_names = self.cstore.struct_field_names_untracked(def_id);
709 self.insert_field_names(def_id, field_names);
711 Res::Def(DefKind::Macro(..), _) | Res::NonMacroAttr(..) => {
712 self.define(parent, ident, MacroNS, (res, vis, DUMMY_SP, expansion));
714 _ => bug!("unexpected resolution: {:?}", res)
718 pub fn get_module(&mut self, def_id: DefId) -> Module<'a> {
719 if def_id.krate == LOCAL_CRATE {
720 return self.module_map[&def_id]
723 let macros_only = self.cstore.dep_kind_untracked(def_id.krate).macros_only();
724 if let Some(&module) = self.extern_module_map.get(&(def_id, macros_only)) {
728 let (name, parent) = if def_id.index == CRATE_DEF_INDEX {
729 (self.cstore.crate_name_untracked(def_id.krate).as_interned_str(), None)
731 let def_key = self.cstore.def_key(def_id);
732 (def_key.disambiguated_data.data.get_opt_name().unwrap(),
733 Some(self.get_module(DefId { index: def_key.parent.unwrap(), ..def_id })))
736 let kind = ModuleKind::Def(DefKind::Mod, def_id, name.as_symbol());
737 let module = self.arenas.alloc_module(ModuleData::new(
738 parent, kind, def_id, ExpnId::root(), DUMMY_SP
740 self.extern_module_map.insert((def_id, macros_only), module);
744 pub fn macro_def_scope(&mut self, expn_id: ExpnId) -> Module<'a> {
745 let def_id = match self.macro_defs.get(&expn_id) {
746 Some(def_id) => *def_id,
747 None => return self.graph_root,
749 if let Some(id) = self.definitions.as_local_node_id(def_id) {
750 self.local_macro_def_scopes[&id]
751 } else if self.is_builtin_macro(Some(def_id)) {
752 self.injected_crate.unwrap_or(self.graph_root)
754 let module_def_id = ty::DefIdTree::parent(&*self, def_id).unwrap();
755 self.get_module(module_def_id)
759 crate fn get_macro(&mut self, res: Res) -> Option<Lrc<SyntaxExtension>> {
761 Res::Def(DefKind::Macro(..), def_id) => self.get_macro_by_def_id(def_id),
762 Res::NonMacroAttr(attr_kind) =>
763 Some(self.non_macro_attr(attr_kind == NonMacroAttrKind::Tool)),
768 crate fn get_macro_by_def_id(&mut self, def_id: DefId) -> Option<Lrc<SyntaxExtension>> {
769 if let Some(ext) = self.macro_map.get(&def_id) {
770 return Some(ext.clone());
773 let macro_def = match self.cstore.load_macro_untracked(def_id, &self.session) {
774 LoadedMacro::MacroDef(macro_def) => macro_def,
775 LoadedMacro::ProcMacro(ext) => return Some(ext),
778 let ext = self.compile_macro(¯o_def, self.cstore.crate_edition_untracked(def_id.krate));
779 self.macro_map.insert(def_id, ext.clone());
783 /// Ensures that the reduced graph rooted at the given external module
784 /// is built, building it if it is not.
785 pub fn populate_module_if_necessary(&mut self, module: Module<'a>) {
786 if module.populated.get() { return }
787 let def_id = module.def_id().unwrap();
788 for child in self.cstore.item_children_untracked(def_id, self.session) {
789 let child = child.map_id(|_| panic!("unexpected id"));
790 self.build_reduced_graph_for_external_crate_res(module, child);
792 module.populated.set(true)
795 fn legacy_import_macro(&mut self,
797 binding: &'a NameBinding<'a>,
799 allow_shadowing: bool) {
800 if self.macro_use_prelude.insert(name, binding).is_some() && !allow_shadowing {
801 let msg = format!("`{}` is already in scope", name);
803 "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)";
804 self.session.struct_span_err(span, &msg).note(note).emit();
808 /// Returns `true` if we should consider the underlying `extern crate` to be used.
809 fn process_legacy_macro_imports(&mut self, item: &Item, module: Module<'a>,
810 parent_scope: &ParentScope<'a>) -> bool {
811 let mut import_all = None;
812 let mut single_imports = Vec::new();
813 for attr in &item.attrs {
814 if attr.check_name(sym::macro_use) {
815 if self.current_module.parent.is_some() {
816 span_err!(self.session, item.span, E0468,
817 "an `extern crate` loading macros must be at the crate root");
819 if let ItemKind::ExternCrate(Some(orig_name)) = item.node {
820 if orig_name == kw::SelfLower {
821 self.session.span_err(attr.span,
822 "`macro_use` is not supported on `extern crate self`");
825 let ill_formed = |span| span_err!(self.session, span, E0466, "bad macro import");
827 Some(meta) => match meta.node {
828 MetaItemKind::Word => {
829 import_all = Some(meta.span);
832 MetaItemKind::List(nested_metas) => for nested_meta in nested_metas {
833 match nested_meta.ident() {
834 Some(ident) if nested_meta.is_word() => single_imports.push(ident),
835 _ => ill_formed(nested_meta.span()),
838 MetaItemKind::NameValue(..) => ill_formed(meta.span),
840 None => ill_formed(attr.span),
845 let arenas = self.arenas;
846 let macro_use_directive = |span| arenas.alloc_import_directive(ImportDirective {
849 parent_scope: parent_scope.clone(),
850 imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
851 subclass: ImportDirectiveSubclass::MacroUse,
852 use_span_with_attributes: item.span_with_attributes(),
853 has_attributes: !item.attrs.is_empty(),
857 module_path: Vec::new(),
858 vis: Cell::new(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))),
859 used: Cell::new(false),
862 let allow_shadowing = parent_scope.expansion == ExpnId::root();
863 if let Some(span) = import_all {
864 let directive = macro_use_directive(span);
865 self.potentially_unused_imports.push(directive);
866 module.for_each_child(|ident, ns, binding| if ns == MacroNS {
867 let imported_binding = self.import(binding, directive);
868 self.legacy_import_macro(ident.name, imported_binding, span, allow_shadowing);
871 for ident in single_imports.iter().cloned() {
872 let result = self.resolve_ident_in_module(
873 ModuleOrUniformRoot::Module(module),
880 if let Ok(binding) = result {
881 let directive = macro_use_directive(ident.span);
882 self.potentially_unused_imports.push(directive);
883 let imported_binding = self.import(binding, directive);
884 self.legacy_import_macro(ident.name, imported_binding,
885 ident.span, allow_shadowing);
887 span_err!(self.session, ident.span, E0469, "imported macro not found");
891 import_all.is_some() || !single_imports.is_empty()
894 /// Returns `true` if this attribute list contains `macro_use`.
895 fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool {
897 if attr.check_name(sym::macro_escape) {
898 let msg = "macro_escape is a deprecated synonym for macro_use";
899 let mut err = self.session.struct_span_warn(attr.span, msg);
900 if let ast::AttrStyle::Inner = attr.style {
901 err.help("consider an outer attribute, `#[macro_use]` mod ...").emit();
905 } else if !attr.check_name(sym::macro_use) {
910 self.session.span_err(attr.span, "arguments to macro_use are not allowed here");
919 pub struct BuildReducedGraphVisitor<'a, 'b> {
920 pub resolver: &'a mut Resolver<'b>,
921 pub current_legacy_scope: LegacyScope<'b>,
922 pub expansion: ExpnId,
925 impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
926 fn visit_invoc(&mut self, id: ast::NodeId) -> &'b InvocationData<'b> {
927 let invoc_id = id.placeholder_to_expn_id();
929 self.resolver.current_module.unresolved_invocations.borrow_mut().insert(invoc_id);
931 let invocation_data = self.resolver.arenas.alloc_invocation_data(InvocationData {
932 module: self.resolver.current_module,
933 parent_legacy_scope: self.current_legacy_scope,
934 output_legacy_scope: Cell::new(None),
936 let old_invocation_data = self.resolver.invocations.insert(invoc_id, invocation_data);
937 assert!(old_invocation_data.is_none(), "invocation data is reset for an invocation");
943 macro_rules! method {
944 ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
945 fn $visit(&mut self, node: &'a $ty) {
946 if let $invoc(..) = node.node {
947 self.visit_invoc(node.id);
949 visit::$walk(self, node);
955 impl<'a, 'b> Visitor<'a> for BuildReducedGraphVisitor<'a, 'b> {
956 method!(visit_impl_item: ast::ImplItem, ast::ImplItemKind::Macro, walk_impl_item);
957 method!(visit_expr: ast::Expr, ast::ExprKind::Mac, walk_expr);
958 method!(visit_pat: ast::Pat, ast::PatKind::Mac, walk_pat);
959 method!(visit_ty: ast::Ty, ast::TyKind::Mac, walk_ty);
961 fn visit_item(&mut self, item: &'a Item) {
962 let macro_use = match item.node {
963 ItemKind::MacroDef(..) => {
964 self.resolver.define_macro(item, self.expansion, &mut self.current_legacy_scope);
967 ItemKind::Mac(..) => {
968 self.current_legacy_scope = LegacyScope::Invocation(self.visit_invoc(item.id));
971 ItemKind::Mod(..) => self.resolver.contains_macro_use(&item.attrs),
975 let orig_current_module = self.resolver.current_module;
976 let orig_current_legacy_scope = self.current_legacy_scope;
977 let parent_scope = ParentScope {
978 module: self.resolver.current_module,
979 expansion: self.expansion,
980 legacy: self.current_legacy_scope,
983 self.resolver.build_reduced_graph_for_item(item, parent_scope);
984 visit::walk_item(self, item);
985 self.resolver.current_module = orig_current_module;
987 self.current_legacy_scope = orig_current_legacy_scope;
991 fn visit_stmt(&mut self, stmt: &'a ast::Stmt) {
992 if let ast::StmtKind::Mac(..) = stmt.node {
993 self.current_legacy_scope = LegacyScope::Invocation(self.visit_invoc(stmt.id));
995 visit::walk_stmt(self, stmt);
999 fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
1000 if let ForeignItemKind::Macro(_) = foreign_item.node {
1001 self.visit_invoc(foreign_item.id);
1005 self.resolver.build_reduced_graph_for_foreign_item(foreign_item, self.expansion);
1006 visit::walk_foreign_item(self, foreign_item);
1009 fn visit_block(&mut self, block: &'a Block) {
1010 let orig_current_module = self.resolver.current_module;
1011 let orig_current_legacy_scope = self.current_legacy_scope;
1012 self.resolver.build_reduced_graph_for_block(block, self.expansion);
1013 visit::walk_block(self, block);
1014 self.resolver.current_module = orig_current_module;
1015 self.current_legacy_scope = orig_current_legacy_scope;
1018 fn visit_trait_item(&mut self, item: &'a TraitItem) {
1019 let parent = self.resolver.current_module;
1021 if let TraitItemKind::Macro(_) = item.node {
1022 self.visit_invoc(item.id);
1026 // Add the item to the trait info.
1027 let item_def_id = self.resolver.definitions.local_def_id(item.id);
1028 let (res, ns) = match item.node {
1029 TraitItemKind::Const(..) => (Res::Def(DefKind::AssocConst, item_def_id), ValueNS),
1030 TraitItemKind::Method(ref sig, _) => {
1031 if sig.decl.has_self() {
1032 self.resolver.has_self.insert(item_def_id);
1034 (Res::Def(DefKind::Method, item_def_id), ValueNS)
1036 TraitItemKind::Type(..) => (Res::Def(DefKind::AssocTy, item_def_id), TypeNS),
1037 TraitItemKind::Macro(_) => bug!(), // handled above
1040 let vis = ty::Visibility::Public;
1041 self.resolver.define(parent, item.ident, ns, (res, vis, item.span, self.expansion));
1043 self.resolver.current_module = parent.parent.unwrap(); // nearest normal ancestor
1044 visit::walk_trait_item(self, item);
1045 self.resolver.current_module = parent;
1048 fn visit_token(&mut self, t: Token) {
1049 if let token::Interpolated(nt) = t.kind {
1050 if let token::NtExpr(ref expr) = *nt {
1051 if let ast::ExprKind::Mac(..) = expr.node {
1052 self.visit_invoc(expr.id);
1058 fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1059 if !attr.is_sugared_doc && is_builtin_attr(attr) {
1060 let parent_scope = ParentScope {
1061 module: self.resolver.current_module.nearest_item_scope(),
1062 expansion: self.expansion,
1063 legacy: self.current_legacy_scope,
1064 // Let's hope discerning built-in attributes from derive helpers is not necessary
1065 derives: Vec::new(),
1067 parent_scope.module.builtin_attrs.borrow_mut().push((
1068 attr.path.segments[0].ident, parent_scope
1071 visit::walk_attribute(self, attr);