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::std_inject::injected_crate_name;
38 use syntax::symbol::{kw, sym};
39 use syntax::visit::{self, Visitor};
41 use syntax_pos::{Span, DUMMY_SP};
45 type Res = def::Res<NodeId>;
47 impl<'a> ToNameBinding<'a> for (Module<'a>, ty::Visibility, Span, ExpnId) {
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 (Res, ty::Visibility, Span, ExpnId) {
60 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
61 arenas.alloc_name_binding(NameBinding {
62 kind: NameBindingKind::Res(self.0, false),
71 pub(crate) struct IsMacroExport;
73 impl<'a> ToNameBinding<'a> for (Res, ty::Visibility, Span, ExpnId, IsMacroExport) {
74 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
75 arenas.alloc_name_binding(NameBinding {
76 kind: NameBindingKind::Res(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 let is_glob = if let ast::UseTreeKind::Glob = use_tree.kind { true } else { false };
135 let crate_root = match prefix_iter.peek() {
136 Some(seg) if !seg.ident.is_path_segment_keyword() && seg.ident.span.rust_2015() => {
137 Some(seg.ident.span.ctxt())
139 None if is_glob && use_tree.span.rust_2015() => {
140 Some(use_tree.span.ctxt())
143 }.map(|ctxt| Segment::from_ident(Ident::new(
144 kw::PathRoot, use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt)
147 let prefix = crate_root.into_iter().chain(prefix_iter).collect::<Vec<_>>();
148 debug!("build_reduced_graph_for_use_tree: prefix={:?}", prefix);
150 let empty_for_self = |prefix: &[Segment]| {
152 prefix.len() == 1 && prefix[0].ident.name == kw::PathRoot
154 match use_tree.kind {
155 ast::UseTreeKind::Simple(rename, ..) => {
156 let mut ident = use_tree.ident().gensym_if_underscore();
157 let mut module_path = prefix;
158 let mut source = module_path.pop().unwrap();
159 let mut type_ns_only = false;
162 // Correctly handle `self`
163 if source.ident.name == kw::SelfLower {
166 if empty_for_self(&module_path) {
171 SelfImportOnlyInImportListWithNonEmptyPrefix
176 // Replace `use foo::self;` with `use foo;`
177 source = module_path.pop().unwrap();
178 if rename.is_none() {
179 ident = source.ident;
184 if source.ident.name == kw::SelfLower {
187 ResolutionError::SelfImportsOnlyAllowedWithin);
190 // Disallow `use $crate;`
191 if source.ident.name == kw::DollarCrate && module_path.is_empty() {
192 let crate_root = self.resolve_crate_root(source.ident);
193 let crate_name = match crate_root.kind {
194 ModuleKind::Def(.., name) => name,
195 ModuleKind::Block(..) => unreachable!(),
197 // HACK(eddyb) unclear how good this is, but keeping `$crate`
198 // in `source` breaks `src/test/compile-fail/import-crate-var.rs`,
199 // while the current crate doesn't have a valid `crate_name`.
200 if crate_name != kw::Invalid {
201 // `crate_name` should not be interpreted as relative.
202 module_path.push(Segment {
205 span: source.ident.span,
207 id: Some(self.session.next_node_id()),
209 source.ident.name = crate_name;
211 if rename.is_none() {
212 ident.name = crate_name;
215 self.session.struct_span_warn(item.span, "`$crate` may not be imported")
216 .note("`use $crate;` was erroneously allowed and \
217 will become a hard error in a future release")
222 if ident.name == kw::Crate {
223 self.session.span_err(ident.span,
224 "crate root imports need to be explicitly named: \
225 `use crate as name;`");
228 let subclass = SingleImport {
229 source: source.ident,
231 source_bindings: PerNS {
232 type_ns: Cell::new(Err(Determinacy::Undetermined)),
233 value_ns: Cell::new(Err(Determinacy::Undetermined)),
234 macro_ns: Cell::new(Err(Determinacy::Undetermined)),
236 target_bindings: PerNS {
237 type_ns: Cell::new(None),
238 value_ns: Cell::new(None),
239 macro_ns: Cell::new(None),
244 self.add_import_directive(
256 ast::UseTreeKind::Glob => {
257 let subclass = GlobImport {
258 is_prelude: attr::contains_name(&item.attrs, sym::prelude_import),
259 max_vis: Cell::new(ty::Visibility::Invisible),
261 self.add_import_directive(
273 ast::UseTreeKind::Nested(ref items) => {
274 // Ensure there is at most one `self` in the list
275 let self_spans = items.iter().filter_map(|&(ref use_tree, _)| {
276 if let ast::UseTreeKind::Simple(..) = use_tree.kind {
277 if use_tree.ident().name == kw::SelfLower {
278 return Some(use_tree.span);
283 }).collect::<Vec<_>>();
284 if self_spans.len() > 1 {
285 let mut e = resolve_struct_error(self,
287 ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
289 for other_span in self_spans.iter().skip(1) {
290 e.span_label(*other_span, "another `self` import appears here");
296 for &(ref tree, id) in items {
297 self.build_reduced_graph_for_use_tree(
298 // This particular use tree
299 tree, id, &prefix, true,
300 // The whole `use` item
301 parent_scope.clone(), item, vis, root_span,
305 // Empty groups `a::b::{}` are turned into synthetic `self` imports
306 // `a::b::c::{self as _}`, so that their prefixes are correctly
307 // resolved and checked for privacy/stability/etc.
308 if items.is_empty() && !empty_for_self(&prefix) {
309 let new_span = prefix[prefix.len() - 1].ident.span;
310 let tree = ast::UseTree {
311 prefix: ast::Path::from_ident(
312 Ident::new(kw::SelfLower, new_span)
314 kind: ast::UseTreeKind::Simple(
315 Some(Ident::new(kw::Underscore, new_span)),
321 self.build_reduced_graph_for_use_tree(
322 // This particular use tree
323 &tree, id, &prefix, true,
324 // The whole `use` item
325 parent_scope, item, ty::Visibility::Invisible, root_span,
332 /// Constructs the reduced graph for one item.
333 fn build_reduced_graph_for_item(&mut self, item: &Item, parent_scope: ParentScope<'a>) {
334 let parent = parent_scope.module;
335 let expansion = parent_scope.expansion;
336 let ident = item.ident.gensym_if_underscore();
338 let vis = self.resolve_visibility(&item.vis);
341 ItemKind::Use(ref use_tree) => {
342 self.build_reduced_graph_for_use_tree(
343 // This particular use tree
344 use_tree, item.id, &[], false,
345 // The whole `use` item
346 parent_scope, item, vis, use_tree.span,
350 ItemKind::ExternCrate(orig_name) => {
351 let module = if orig_name.is_none() && ident.name == kw::SelfLower {
353 .struct_span_err(item.span, "`extern crate self;` requires renaming")
357 "extern crate self as name;".into(),
358 Applicability::HasPlaceholders,
362 } else if orig_name == Some(kw::SelfLower) {
365 let crate_id = self.crate_loader.process_extern_crate(item, &self.definitions);
366 self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX })
369 self.populate_module_if_necessary(module);
370 if injected_crate_name().map_or(false, |name| ident.name.as_str() == name) {
371 self.injected_crate = Some(module);
374 let used = self.process_legacy_macro_imports(item, module, &parent_scope);
376 (module, ty::Visibility::Public, sp, expansion).to_name_binding(self.arenas);
377 let directive = self.arenas.alloc_import_directive(ImportDirective {
381 imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
382 subclass: ImportDirectiveSubclass::ExternCrate {
386 has_attributes: !item.attrs.is_empty(),
387 use_span_with_attributes: item.span_with_attributes(),
389 root_span: item.span,
391 module_path: Vec::new(),
393 used: Cell::new(used),
395 self.potentially_unused_imports.push(directive);
396 let imported_binding = self.import(binding, directive);
397 if ptr::eq(self.current_module, self.graph_root) {
398 if let Some(entry) = self.extern_prelude.get(&ident.modern()) {
399 if expansion != ExpnId::root() && orig_name.is_some() &&
400 entry.extern_crate_item.is_none() {
401 self.session.span_err(item.span, "macro-expanded `extern crate` items \
402 cannot shadow names passed with \
406 let entry = self.extern_prelude.entry(ident.modern())
407 .or_insert(ExternPreludeEntry {
408 extern_crate_item: None,
409 introduced_by_item: true,
411 entry.extern_crate_item = Some(imported_binding);
412 if orig_name.is_some() {
413 entry.introduced_by_item = true;
416 self.define(parent, ident, TypeNS, imported_binding);
419 ItemKind::GlobalAsm(..) => {}
421 ItemKind::Mod(..) if ident.name == kw::Invalid => {} // Crate root
423 ItemKind::Mod(..) => {
424 let def_id = self.definitions.local_def_id(item.id);
425 let module_kind = ModuleKind::Def(DefKind::Mod, def_id, ident.name);
426 let module = self.arenas.alloc_module(ModuleData {
427 no_implicit_prelude: parent.no_implicit_prelude || {
428 attr::contains_name(&item.attrs, sym::no_implicit_prelude)
430 ..ModuleData::new(Some(parent), module_kind, def_id, expansion, item.span)
432 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
433 self.module_map.insert(def_id, module);
435 // Descend into the module.
436 self.current_module = module;
439 // Handled in `rustc_metadata::{native_libs,link_args}`
440 ItemKind::ForeignMod(..) => {}
442 // These items live in the value namespace.
443 ItemKind::Static(..) => {
444 let res = Res::Def(DefKind::Static, self.definitions.local_def_id(item.id));
445 self.define(parent, ident, ValueNS, (res, vis, sp, expansion));
447 ItemKind::Const(..) => {
448 let res = Res::Def(DefKind::Const, self.definitions.local_def_id(item.id));
449 self.define(parent, ident, ValueNS, (res, vis, sp, expansion));
451 ItemKind::Fn(..) => {
452 let res = Res::Def(DefKind::Fn, self.definitions.local_def_id(item.id));
453 self.define(parent, ident, ValueNS, (res, vis, sp, expansion));
455 // Functions introducing procedural macros reserve a slot
456 // in the macro namespace as well (see #52225).
457 self.define_macro(item, expansion, &mut LegacyScope::Empty);
460 // These items live in the type namespace.
461 ItemKind::Ty(..) => {
462 let res = Res::Def(DefKind::TyAlias, self.definitions.local_def_id(item.id));
463 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
466 ItemKind::Existential(_, _) => {
467 let res = Res::Def(DefKind::Existential, self.definitions.local_def_id(item.id));
468 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
471 ItemKind::Enum(ref enum_definition, _) => {
472 let module_kind = ModuleKind::Def(
474 self.definitions.local_def_id(item.id),
477 let module = self.new_module(parent,
479 parent.normal_ancestor_id,
482 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
484 for variant in &(*enum_definition).variants {
485 self.build_reduced_graph_for_variant(variant, module, vis, expansion);
489 ItemKind::TraitAlias(..) => {
490 let res = Res::Def(DefKind::TraitAlias, self.definitions.local_def_id(item.id));
491 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
494 // These items live in both the type and value namespaces.
495 ItemKind::Struct(ref struct_def, _) => {
496 // Define a name in the type namespace.
497 let def_id = self.definitions.local_def_id(item.id);
498 let res = Res::Def(DefKind::Struct, def_id);
499 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
501 let mut ctor_vis = vis;
503 let has_non_exhaustive = attr::contains_name(&item.attrs, sym::non_exhaustive);
505 // If the structure is marked as non_exhaustive then lower the visibility
506 // to within the crate.
507 if has_non_exhaustive && vis == ty::Visibility::Public {
508 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
511 // Record field names for error reporting.
512 let field_names = struct_def.fields().iter().filter_map(|field| {
513 let field_vis = self.resolve_visibility(&field.vis);
514 if ctor_vis.is_at_least(field_vis, &*self) {
515 ctor_vis = field_vis;
517 field.ident.map(|ident| ident.name)
519 let item_def_id = self.definitions.local_def_id(item.id);
520 self.insert_field_names(item_def_id, field_names);
522 // If this is a tuple or unit struct, define a name
523 // in the value namespace as well.
524 if let Some(ctor_node_id) = struct_def.ctor_id() {
525 let ctor_res = Res::Def(
526 DefKind::Ctor(CtorOf::Struct, CtorKind::from_ast(struct_def)),
527 self.definitions.local_def_id(ctor_node_id),
529 self.define(parent, ident, ValueNS, (ctor_res, ctor_vis, sp, expansion));
530 self.struct_constructors.insert(res.def_id(), (ctor_res, ctor_vis));
534 ItemKind::Union(ref vdata, _) => {
535 let res = Res::Def(DefKind::Union, self.definitions.local_def_id(item.id));
536 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
538 // Record field names for error reporting.
539 let field_names = vdata.fields().iter().filter_map(|field| {
540 self.resolve_visibility(&field.vis);
541 field.ident.map(|ident| ident.name)
543 let item_def_id = self.definitions.local_def_id(item.id);
544 self.insert_field_names(item_def_id, field_names);
547 ItemKind::Impl(..) => {}
549 ItemKind::Trait(..) => {
550 let def_id = self.definitions.local_def_id(item.id);
552 // Add all the items within to a new module.
553 let module_kind = ModuleKind::Def(DefKind::Trait, def_id, ident.name);
554 let module = self.new_module(parent,
556 parent.normal_ancestor_id,
559 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
560 self.current_module = module;
563 ItemKind::MacroDef(..) | ItemKind::Mac(_) => unreachable!(),
567 // Constructs the reduced graph for one variant. Variants exist in the
568 // type and value namespaces.
569 fn build_reduced_graph_for_variant(&mut self,
574 let ident = variant.node.ident;
576 // Define a name in the type namespace.
577 let def_id = self.definitions.local_def_id(variant.node.id);
578 let res = Res::Def(DefKind::Variant, def_id);
579 self.define(parent, ident, TypeNS, (res, vis, variant.span, expn_id));
581 // If the variant is marked as non_exhaustive then lower the visibility to within the
583 let mut ctor_vis = vis;
584 let has_non_exhaustive = attr::contains_name(&variant.node.attrs, sym::non_exhaustive);
585 if has_non_exhaustive && vis == ty::Visibility::Public {
586 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
589 // Define a constructor name in the value namespace.
590 // Braced variants, unlike structs, generate unusable names in
591 // value namespace, they are reserved for possible future use.
592 // It's ok to use the variant's id as a ctor id since an
593 // error will be reported on any use of such resolution anyway.
594 let ctor_node_id = variant.node.data.ctor_id().unwrap_or(variant.node.id);
595 let ctor_def_id = self.definitions.local_def_id(ctor_node_id);
596 let ctor_kind = CtorKind::from_ast(&variant.node.data);
597 let ctor_res = Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id);
598 self.define(parent, ident, ValueNS, (ctor_res, ctor_vis, variant.span, expn_id));
601 /// Constructs the reduced graph for one foreign item.
602 fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem, expn_id: ExpnId) {
603 let (res, ns) = match item.node {
604 ForeignItemKind::Fn(..) => {
605 (Res::Def(DefKind::Fn, self.definitions.local_def_id(item.id)), ValueNS)
607 ForeignItemKind::Static(..) => {
608 (Res::Def(DefKind::Static, self.definitions.local_def_id(item.id)), ValueNS)
610 ForeignItemKind::Ty => {
611 (Res::Def(DefKind::ForeignTy, self.definitions.local_def_id(item.id)), TypeNS)
613 ForeignItemKind::Macro(_) => unreachable!(),
615 let parent = self.current_module;
616 let vis = self.resolve_visibility(&item.vis);
617 self.define(parent, item.ident, ns, (res, vis, item.span, expn_id));
620 fn build_reduced_graph_for_block(&mut self, block: &Block, expn_id: ExpnId) {
621 let parent = self.current_module;
622 if self.block_needs_anonymous_module(block) {
623 let module = self.new_module(parent,
624 ModuleKind::Block(block.id),
625 parent.normal_ancestor_id,
628 self.block_map.insert(block.id, module);
629 self.current_module = module; // Descend into the block.
633 /// Builds the reduced graph for a single item in an external crate.
634 fn build_reduced_graph_for_external_crate_res(
637 child: Export<ast::NodeId>,
639 let Export { ident, res, vis, span } = child;
640 // FIXME: We shouldn't create the gensym here, it should come from metadata,
641 // but metadata cannot encode gensyms currently, so we create it here.
642 // This is only a guess, two equivalent idents may incorrectly get different gensyms here.
643 let ident = ident.gensym_if_underscore();
644 let expansion = ExpnId::root(); // FIXME(jseyfried) intercrate hygiene
646 Res::Def(kind @ DefKind::Mod, def_id)
647 | Res::Def(kind @ DefKind::Enum, def_id) => {
648 let module = self.new_module(parent,
649 ModuleKind::Def(kind, def_id, ident.name),
653 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
655 Res::Def(DefKind::Variant, _)
656 | Res::Def(DefKind::TyAlias, _)
657 | Res::Def(DefKind::ForeignTy, _)
658 | Res::Def(DefKind::Existential, _)
659 | Res::Def(DefKind::TraitAlias, _)
662 self.define(parent, ident, TypeNS, (res, vis, DUMMY_SP, expansion));
664 Res::Def(DefKind::Fn, _)
665 | Res::Def(DefKind::Static, _)
666 | Res::Def(DefKind::Const, _)
667 | Res::Def(DefKind::Ctor(CtorOf::Variant, ..), _) => {
668 self.define(parent, ident, ValueNS, (res, vis, DUMMY_SP, expansion));
670 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), def_id) => {
671 self.define(parent, ident, ValueNS, (res, vis, DUMMY_SP, expansion));
673 if let Some(struct_def_id) =
674 self.cstore.def_key(def_id).parent
675 .map(|index| DefId { krate: def_id.krate, index: index }) {
676 self.struct_constructors.insert(struct_def_id, (res, vis));
679 Res::Def(DefKind::Trait, def_id) => {
680 let module_kind = ModuleKind::Def(DefKind::Trait, def_id, ident.name);
681 let module = self.new_module(parent,
683 parent.normal_ancestor_id,
686 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
688 for child in self.cstore.item_children_untracked(def_id, self.session) {
689 let res = child.res.map_id(|_| panic!("unexpected id"));
690 let ns = if let Res::Def(DefKind::AssocTy, _) = res {
693 self.define(module, child.ident, ns,
694 (res, ty::Visibility::Public, DUMMY_SP, expansion));
696 if self.cstore.associated_item_cloned_untracked(child.res.def_id())
697 .method_has_self_argument {
698 self.has_self.insert(res.def_id());
701 module.populated.set(true);
703 Res::Def(DefKind::Struct, def_id) | Res::Def(DefKind::Union, def_id) => {
704 self.define(parent, ident, TypeNS, (res, vis, DUMMY_SP, expansion));
706 // Record field names for error reporting.
707 let field_names = self.cstore.struct_field_names_untracked(def_id);
708 self.insert_field_names(def_id, field_names);
710 Res::Def(DefKind::Macro(..), _) | Res::NonMacroAttr(..) => {
711 self.define(parent, ident, MacroNS, (res, vis, DUMMY_SP, expansion));
713 _ => bug!("unexpected resolution: {:?}", res)
717 pub fn get_module(&mut self, def_id: DefId) -> Module<'a> {
718 if def_id.krate == LOCAL_CRATE {
719 return self.module_map[&def_id]
722 let macros_only = self.cstore.dep_kind_untracked(def_id.krate).macros_only();
723 if let Some(&module) = self.extern_module_map.get(&(def_id, macros_only)) {
727 let (name, parent) = if def_id.index == CRATE_DEF_INDEX {
728 (self.cstore.crate_name_untracked(def_id.krate).as_interned_str(), None)
730 let def_key = self.cstore.def_key(def_id);
731 (def_key.disambiguated_data.data.get_opt_name().unwrap(),
732 Some(self.get_module(DefId { index: def_key.parent.unwrap(), ..def_id })))
735 let kind = ModuleKind::Def(DefKind::Mod, def_id, name.as_symbol());
736 let module = self.arenas.alloc_module(ModuleData::new(
737 parent, kind, def_id, ExpnId::root(), DUMMY_SP
739 self.extern_module_map.insert((def_id, macros_only), module);
743 pub fn macro_def_scope(&mut self, expn_id: ExpnId) -> Module<'a> {
744 let def_id = match self.macro_defs.get(&expn_id) {
745 Some(def_id) => *def_id,
746 None => return self.graph_root,
748 if let Some(id) = self.definitions.as_local_node_id(def_id) {
749 self.local_macro_def_scopes[&id]
750 } else if self.is_builtin_macro(Some(def_id)) {
751 self.injected_crate.unwrap_or(self.graph_root)
753 let module_def_id = ty::DefIdTree::parent(&*self, def_id).unwrap();
754 self.get_module(module_def_id)
758 crate fn get_macro(&mut self, res: Res) -> Option<Lrc<SyntaxExtension>> {
760 Res::Def(DefKind::Macro(..), def_id) => self.get_macro_by_def_id(def_id),
761 Res::NonMacroAttr(attr_kind) =>
762 Some(self.non_macro_attr(attr_kind == NonMacroAttrKind::Tool)),
767 crate fn get_macro_by_def_id(&mut self, def_id: DefId) -> Option<Lrc<SyntaxExtension>> {
768 if let Some(ext) = self.macro_map.get(&def_id) {
769 return Some(ext.clone());
772 let macro_def = match self.cstore.load_macro_untracked(def_id, &self.session) {
773 LoadedMacro::MacroDef(macro_def) => macro_def,
774 LoadedMacro::ProcMacro(ext) => return Some(ext),
777 let ext = self.compile_macro(¯o_def, self.cstore.crate_edition_untracked(def_id.krate));
778 self.macro_map.insert(def_id, ext.clone());
782 /// Ensures that the reduced graph rooted at the given external module
783 /// is built, building it if it is not.
784 pub fn populate_module_if_necessary(&mut self, module: Module<'a>) {
785 if module.populated.get() { return }
786 let def_id = module.def_id().unwrap();
787 for child in self.cstore.item_children_untracked(def_id, self.session) {
788 let child = child.map_id(|_| panic!("unexpected id"));
789 self.build_reduced_graph_for_external_crate_res(module, child);
791 module.populated.set(true)
794 fn legacy_import_macro(&mut self,
796 binding: &'a NameBinding<'a>,
798 allow_shadowing: bool) {
799 if self.macro_use_prelude.insert(name, binding).is_some() && !allow_shadowing {
800 let msg = format!("`{}` is already in scope", name);
802 "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)";
803 self.session.struct_span_err(span, &msg).note(note).emit();
807 /// Returns `true` if we should consider the underlying `extern crate` to be used.
808 fn process_legacy_macro_imports(&mut self, item: &Item, module: Module<'a>,
809 parent_scope: &ParentScope<'a>) -> bool {
810 let mut import_all = None;
811 let mut single_imports = Vec::new();
812 for attr in &item.attrs {
813 if attr.check_name(sym::macro_use) {
814 if self.current_module.parent.is_some() {
815 span_err!(self.session, item.span, E0468,
816 "an `extern crate` loading macros must be at the crate root");
818 if let ItemKind::ExternCrate(Some(orig_name)) = item.node {
819 if orig_name == kw::SelfLower {
820 self.session.span_err(attr.span,
821 "`macro_use` is not supported on `extern crate self`");
824 let ill_formed = |span| span_err!(self.session, span, E0466, "bad macro import");
826 Some(meta) => match meta.node {
827 MetaItemKind::Word => {
828 import_all = Some(meta.span);
831 MetaItemKind::List(nested_metas) => for nested_meta in nested_metas {
832 match nested_meta.ident() {
833 Some(ident) if nested_meta.is_word() => single_imports.push(ident),
834 _ => ill_formed(nested_meta.span()),
837 MetaItemKind::NameValue(..) => ill_formed(meta.span),
839 None => ill_formed(attr.span),
844 let arenas = self.arenas;
845 let macro_use_directive = |span| arenas.alloc_import_directive(ImportDirective {
848 parent_scope: parent_scope.clone(),
849 imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
850 subclass: ImportDirectiveSubclass::MacroUse,
851 use_span_with_attributes: item.span_with_attributes(),
852 has_attributes: !item.attrs.is_empty(),
856 module_path: Vec::new(),
857 vis: Cell::new(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))),
858 used: Cell::new(false),
861 let allow_shadowing = parent_scope.expansion == ExpnId::root();
862 if let Some(span) = import_all {
863 let directive = macro_use_directive(span);
864 self.potentially_unused_imports.push(directive);
865 module.for_each_child(|ident, ns, binding| if ns == MacroNS {
866 let imported_binding = self.import(binding, directive);
867 self.legacy_import_macro(ident.name, imported_binding, span, allow_shadowing);
870 for ident in single_imports.iter().cloned() {
871 let result = self.resolve_ident_in_module(
872 ModuleOrUniformRoot::Module(module),
879 if let Ok(binding) = result {
880 let directive = macro_use_directive(ident.span);
881 self.potentially_unused_imports.push(directive);
882 let imported_binding = self.import(binding, directive);
883 self.legacy_import_macro(ident.name, imported_binding,
884 ident.span, allow_shadowing);
886 span_err!(self.session, ident.span, E0469, "imported macro not found");
890 import_all.is_some() || !single_imports.is_empty()
893 /// Returns `true` if this attribute list contains `macro_use`.
894 fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool {
896 if attr.check_name(sym::macro_escape) {
897 let msg = "macro_escape is a deprecated synonym for macro_use";
898 let mut err = self.session.struct_span_warn(attr.span, msg);
899 if let ast::AttrStyle::Inner = attr.style {
900 err.help("consider an outer attribute, `#[macro_use]` mod ...").emit();
904 } else if !attr.check_name(sym::macro_use) {
909 self.session.span_err(attr.span, "arguments to macro_use are not allowed here");
918 pub struct BuildReducedGraphVisitor<'a, 'b> {
919 pub resolver: &'a mut Resolver<'b>,
920 pub current_legacy_scope: LegacyScope<'b>,
921 pub expansion: ExpnId,
924 impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
925 fn visit_invoc(&mut self, id: ast::NodeId) -> &'b InvocationData<'b> {
926 let invoc_id = id.placeholder_to_expn_id();
928 self.resolver.current_module.unresolved_invocations.borrow_mut().insert(invoc_id);
930 let invocation_data = self.resolver.arenas.alloc_invocation_data(InvocationData {
931 module: self.resolver.current_module,
932 parent_legacy_scope: self.current_legacy_scope,
933 output_legacy_scope: Cell::new(None),
935 let old_invocation_data = self.resolver.invocations.insert(invoc_id, invocation_data);
936 assert!(old_invocation_data.is_none(), "invocation data is reset for an invocation");
942 macro_rules! method {
943 ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
944 fn $visit(&mut self, node: &'a $ty) {
945 if let $invoc(..) = node.node {
946 self.visit_invoc(node.id);
948 visit::$walk(self, node);
954 impl<'a, 'b> Visitor<'a> for BuildReducedGraphVisitor<'a, 'b> {
955 method!(visit_impl_item: ast::ImplItem, ast::ImplItemKind::Macro, walk_impl_item);
956 method!(visit_expr: ast::Expr, ast::ExprKind::Mac, walk_expr);
957 method!(visit_pat: ast::Pat, ast::PatKind::Mac, walk_pat);
958 method!(visit_ty: ast::Ty, ast::TyKind::Mac, walk_ty);
960 fn visit_item(&mut self, item: &'a Item) {
961 let macro_use = match item.node {
962 ItemKind::MacroDef(..) => {
963 self.resolver.define_macro(item, self.expansion, &mut self.current_legacy_scope);
966 ItemKind::Mac(..) => {
967 self.current_legacy_scope = LegacyScope::Invocation(self.visit_invoc(item.id));
970 ItemKind::Mod(..) => self.resolver.contains_macro_use(&item.attrs),
974 let orig_current_module = self.resolver.current_module;
975 let orig_current_legacy_scope = self.current_legacy_scope;
976 let parent_scope = ParentScope {
977 module: self.resolver.current_module,
978 expansion: self.expansion,
979 legacy: self.current_legacy_scope,
982 self.resolver.build_reduced_graph_for_item(item, parent_scope);
983 visit::walk_item(self, item);
984 self.resolver.current_module = orig_current_module;
986 self.current_legacy_scope = orig_current_legacy_scope;
990 fn visit_stmt(&mut self, stmt: &'a ast::Stmt) {
991 if let ast::StmtKind::Mac(..) = stmt.node {
992 self.current_legacy_scope = LegacyScope::Invocation(self.visit_invoc(stmt.id));
994 visit::walk_stmt(self, stmt);
998 fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
999 if let ForeignItemKind::Macro(_) = foreign_item.node {
1000 self.visit_invoc(foreign_item.id);
1004 self.resolver.build_reduced_graph_for_foreign_item(foreign_item, self.expansion);
1005 visit::walk_foreign_item(self, foreign_item);
1008 fn visit_block(&mut self, block: &'a Block) {
1009 let orig_current_module = self.resolver.current_module;
1010 let orig_current_legacy_scope = self.current_legacy_scope;
1011 self.resolver.build_reduced_graph_for_block(block, self.expansion);
1012 visit::walk_block(self, block);
1013 self.resolver.current_module = orig_current_module;
1014 self.current_legacy_scope = orig_current_legacy_scope;
1017 fn visit_trait_item(&mut self, item: &'a TraitItem) {
1018 let parent = self.resolver.current_module;
1020 if let TraitItemKind::Macro(_) = item.node {
1021 self.visit_invoc(item.id);
1025 // Add the item to the trait info.
1026 let item_def_id = self.resolver.definitions.local_def_id(item.id);
1027 let (res, ns) = match item.node {
1028 TraitItemKind::Const(..) => (Res::Def(DefKind::AssocConst, item_def_id), ValueNS),
1029 TraitItemKind::Method(ref sig, _) => {
1030 if sig.decl.has_self() {
1031 self.resolver.has_self.insert(item_def_id);
1033 (Res::Def(DefKind::Method, item_def_id), ValueNS)
1035 TraitItemKind::Type(..) => (Res::Def(DefKind::AssocTy, item_def_id), TypeNS),
1036 TraitItemKind::Macro(_) => bug!(), // handled above
1039 let vis = ty::Visibility::Public;
1040 self.resolver.define(parent, item.ident, ns, (res, vis, item.span, self.expansion));
1042 self.resolver.current_module = parent.parent.unwrap(); // nearest normal ancestor
1043 visit::walk_trait_item(self, item);
1044 self.resolver.current_module = parent;
1047 fn visit_token(&mut self, t: Token) {
1048 if let token::Interpolated(nt) = t.kind {
1049 if let token::NtExpr(ref expr) = *nt {
1050 if let ast::ExprKind::Mac(..) = expr.node {
1051 self.visit_invoc(expr.id);
1057 fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1058 if !attr.is_sugared_doc && is_builtin_attr(attr) {
1059 let parent_scope = ParentScope {
1060 module: self.resolver.current_module.nearest_item_scope(),
1061 expansion: self.expansion,
1062 legacy: self.current_legacy_scope,
1063 // Let's hope discerning built-in attributes from derive helpers is not necessary
1064 derives: Vec::new(),
1066 parent_scope.module.builtin_attrs.borrow_mut().push((
1067 attr.path.segments[0].ident, parent_scope
1070 visit::walk_attribute(self, attr);