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::{self, *};
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, 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, TokenKind};
39 use syntax::std_inject::injected_crate_name;
40 use syntax::symbol::{kw, sym};
41 use syntax::visit::{self, Visitor};
43 use syntax_pos::{Span, DUMMY_SP};
47 type Res = def::Res<NodeId>;
49 impl<'a> ToNameBinding<'a> for (Module<'a>, ty::Visibility, Span, Mark) {
50 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
51 arenas.alloc_name_binding(NameBinding {
52 kind: NameBindingKind::Module(self.0),
61 impl<'a> ToNameBinding<'a> for (Res, ty::Visibility, Span, Mark) {
62 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
63 arenas.alloc_name_binding(NameBinding {
64 kind: NameBindingKind::Res(self.0, false),
73 pub(crate) struct IsMacroExport;
75 impl<'a> ToNameBinding<'a> for (Res, ty::Visibility, Span, Mark, IsMacroExport) {
76 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
77 arenas.alloc_name_binding(NameBinding {
78 kind: NameBindingKind::Res(self.0, true),
87 impl<'a> Resolver<'a> {
88 /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
89 /// otherwise, reports an error.
90 pub fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T)
91 where T: ToNameBinding<'a>,
93 let binding = def.to_name_binding(self.arenas);
94 if let Err(old_binding) = self.try_define(parent, ident, ns, binding) {
95 self.report_conflict(parent, ident, ns, old_binding, &binding);
99 fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
100 // If any statements are items, we need to create an anonymous module
101 block.stmts.iter().any(|statement| match statement.node {
102 StmtKind::Item(_) | StmtKind::Mac(_) => true,
107 fn insert_field_names(&mut self, def_id: DefId, field_names: Vec<Name>) {
108 if !field_names.is_empty() {
109 self.field_names.insert(def_id, field_names);
113 fn build_reduced_graph_for_use_tree(
115 // This particular use tree
116 use_tree: &ast::UseTree,
118 parent_prefix: &[Segment],
120 // The whole `use` item
121 parent_scope: ParentScope<'a>,
126 debug!("build_reduced_graph_for_use_tree(parent_prefix={:?}, use_tree={:?}, nested={})",
127 parent_prefix, use_tree, nested);
129 let mut prefix_iter = parent_prefix.iter().cloned()
130 .chain(use_tree.prefix.segments.iter().map(|seg| seg.into())).peekable();
132 // On 2015 edition imports are resolved as crate-relative by default,
133 // so prefixes are prepended with crate root segment if necessary.
134 // The root is prepended lazily, when the first non-empty prefix or terminating glob
135 // appears, so imports in braced groups can have roots prepended independently.
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() && seg.ident.span.rust_2015() => {
139 Some(seg.ident.span.ctxt())
141 None if is_glob && use_tree.span.rust_2015() => {
142 Some(use_tree.span.ctxt())
145 }.map(|ctxt| Segment::from_ident(Ident::new(
146 kw::PathRoot, use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt)
149 let prefix = crate_root.into_iter().chain(prefix_iter).collect::<Vec<_>>();
150 debug!("build_reduced_graph_for_use_tree: prefix={:?}", prefix);
152 let empty_for_self = |prefix: &[Segment]| {
154 prefix.len() == 1 && prefix[0].ident.name == kw::PathRoot
156 match use_tree.kind {
157 ast::UseTreeKind::Simple(rename, ..) => {
158 let mut ident = use_tree.ident().gensym_if_underscore();
159 let mut module_path = prefix;
160 let mut source = module_path.pop().unwrap();
161 let mut type_ns_only = false;
164 // Correctly handle `self`
165 if source.ident.name == kw::SelfLower {
168 if empty_for_self(&module_path) {
173 SelfImportOnlyInImportListWithNonEmptyPrefix
178 // Replace `use foo::self;` with `use foo;`
179 source = module_path.pop().unwrap();
180 if rename.is_none() {
181 ident = source.ident;
186 if source.ident.name == kw::SelfLower {
189 ResolutionError::SelfImportsOnlyAllowedWithin);
192 // Disallow `use $crate;`
193 if source.ident.name == kw::DollarCrate && module_path.is_empty() {
194 let crate_root = self.resolve_crate_root(source.ident);
195 let crate_name = match crate_root.kind {
196 ModuleKind::Def(.., name) => name,
197 ModuleKind::Block(..) => unreachable!(),
199 // HACK(eddyb) unclear how good this is, but keeping `$crate`
200 // in `source` breaks `src/test/compile-fail/import-crate-var.rs`,
201 // while the current crate doesn't have a valid `crate_name`.
202 if crate_name != kw::Invalid {
203 // `crate_name` should not be interpreted as relative.
204 module_path.push(Segment {
207 span: source.ident.span,
209 id: Some(self.session.next_node_id()),
211 source.ident.name = crate_name;
213 if rename.is_none() {
214 ident.name = crate_name;
217 self.session.struct_span_warn(item.span, "`$crate` may not be imported")
218 .note("`use $crate;` was erroneously allowed and \
219 will become a hard error in a future release")
224 if ident.name == kw::Crate {
225 self.session.span_err(ident.span,
226 "crate root imports need to be explicitly named: \
227 `use crate as name;`");
230 let subclass = SingleImport {
231 source: source.ident,
233 source_bindings: PerNS {
234 type_ns: Cell::new(Err(Undetermined)),
235 value_ns: Cell::new(Err(Undetermined)),
236 macro_ns: Cell::new(Err(Undetermined)),
238 target_bindings: PerNS {
239 type_ns: Cell::new(None),
240 value_ns: Cell::new(None),
241 macro_ns: Cell::new(None),
246 self.add_import_directive(
258 ast::UseTreeKind::Glob => {
259 let subclass = GlobImport {
260 is_prelude: attr::contains_name(&item.attrs, sym::prelude_import),
261 max_vis: Cell::new(ty::Visibility::Invisible),
263 self.add_import_directive(
275 ast::UseTreeKind::Nested(ref items) => {
276 // Ensure there is at most one `self` in the list
277 let self_spans = items.iter().filter_map(|&(ref use_tree, _)| {
278 if let ast::UseTreeKind::Simple(..) = use_tree.kind {
279 if use_tree.ident().name == kw::SelfLower {
280 return Some(use_tree.span);
285 }).collect::<Vec<_>>();
286 if self_spans.len() > 1 {
287 let mut e = resolve_struct_error(self,
289 ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
291 for other_span in self_spans.iter().skip(1) {
292 e.span_label(*other_span, "another `self` import appears here");
298 for &(ref tree, id) in items {
299 self.build_reduced_graph_for_use_tree(
300 // This particular use tree
301 tree, id, &prefix, true,
302 // The whole `use` item
303 parent_scope.clone(), item, vis, root_span,
307 // Empty groups `a::b::{}` are turned into synthetic `self` imports
308 // `a::b::c::{self as __dummy}`, so that their prefixes are correctly
309 // resolved and checked for privacy/stability/etc.
310 if items.is_empty() && !empty_for_self(&prefix) {
311 let new_span = prefix[prefix.len() - 1].ident.span;
312 let tree = ast::UseTree {
313 prefix: ast::Path::from_ident(
314 Ident::new(kw::SelfLower, new_span)
316 kind: ast::UseTreeKind::Simple(
317 Some(Ident::from_str_and_span("__dummy", new_span).gensym()),
323 self.build_reduced_graph_for_use_tree(
324 // This particular use tree
325 &tree, id, &prefix, true,
326 // The whole `use` item
327 parent_scope, item, ty::Visibility::Invisible, root_span,
334 /// Constructs the reduced graph for one item.
335 fn build_reduced_graph_for_item(&mut self, item: &Item, parent_scope: ParentScope<'a>) {
336 let parent = parent_scope.module;
337 let expansion = parent_scope.expansion;
338 let ident = item.ident.gensym_if_underscore();
340 let vis = self.resolve_visibility(&item.vis);
343 ItemKind::Use(ref use_tree) => {
344 self.build_reduced_graph_for_use_tree(
345 // This particular use tree
346 use_tree, item.id, &[], false,
347 // The whole `use` item
348 parent_scope, item, vis, use_tree.span,
352 ItemKind::ExternCrate(orig_name) => {
353 let module = if orig_name.is_none() && ident.name == kw::SelfLower {
355 .struct_span_err(item.span, "`extern crate self;` requires renaming")
359 "extern crate self as name;".into(),
360 Applicability::HasPlaceholders,
364 } else if orig_name == Some(kw::SelfLower) {
367 let crate_id = self.crate_loader.process_extern_crate(item, &self.definitions);
368 self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX })
371 self.populate_module_if_necessary(module);
372 if injected_crate_name().map_or(false, |name| ident.name.as_str() == name) {
373 self.injected_crate = Some(module);
376 let used = self.process_legacy_macro_imports(item, module, &parent_scope);
378 (module, ty::Visibility::Public, sp, expansion).to_name_binding(self.arenas);
379 let directive = self.arenas.alloc_import_directive(ImportDirective {
383 imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
384 subclass: ImportDirectiveSubclass::ExternCrate {
388 has_attributes: !item.attrs.is_empty(),
389 use_span_with_attributes: item.span_with_attributes(),
391 root_span: item.span,
393 module_path: Vec::new(),
395 used: Cell::new(used),
397 self.potentially_unused_imports.push(directive);
398 let imported_binding = self.import(binding, directive);
399 if ptr::eq(self.current_module, self.graph_root) {
400 if let Some(entry) = self.extern_prelude.get(&ident.modern()) {
401 if expansion != Mark::root() && orig_name.is_some() &&
402 entry.extern_crate_item.is_none() {
403 self.session.span_err(item.span, "macro-expanded `extern crate` items \
404 cannot shadow names passed with \
408 let entry = self.extern_prelude.entry(ident.modern())
409 .or_insert(ExternPreludeEntry {
410 extern_crate_item: None,
411 introduced_by_item: true,
413 entry.extern_crate_item = Some(imported_binding);
414 if orig_name.is_some() {
415 entry.introduced_by_item = true;
418 self.define(parent, ident, TypeNS, imported_binding);
421 ItemKind::GlobalAsm(..) => {}
423 ItemKind::Mod(..) if ident.name == kw::Invalid => {} // Crate root
425 ItemKind::Mod(..) => {
426 let def_id = self.definitions.local_def_id(item.id);
427 let module_kind = ModuleKind::Def(DefKind::Mod, def_id, ident.name);
428 let module = self.arenas.alloc_module(ModuleData {
429 no_implicit_prelude: parent.no_implicit_prelude || {
430 attr::contains_name(&item.attrs, sym::no_implicit_prelude)
432 ..ModuleData::new(Some(parent), module_kind, def_id, expansion, item.span)
434 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
435 self.module_map.insert(def_id, module);
437 // Descend into the module.
438 self.current_module = module;
441 // Handled in `rustc_metadata::{native_libs,link_args}`
442 ItemKind::ForeignMod(..) => {}
444 // These items live in the value namespace.
445 ItemKind::Static(..) => {
446 let res = Res::Def(DefKind::Static, self.definitions.local_def_id(item.id));
447 self.define(parent, ident, ValueNS, (res, vis, sp, expansion));
449 ItemKind::Const(..) => {
450 let res = Res::Def(DefKind::Const, self.definitions.local_def_id(item.id));
451 self.define(parent, ident, ValueNS, (res, vis, sp, expansion));
453 ItemKind::Fn(..) => {
454 let res = Res::Def(DefKind::Fn, self.definitions.local_def_id(item.id));
455 self.define(parent, ident, ValueNS, (res, vis, sp, expansion));
457 // Functions introducing procedural macros reserve a slot
458 // in the macro namespace as well (see #52225).
459 if attr::contains_name(&item.attrs, sym::proc_macro) ||
460 attr::contains_name(&item.attrs, sym::proc_macro_attribute) {
461 let res = Res::Def(DefKind::Macro(MacroKind::ProcMacroStub), res.def_id());
462 self.define(parent, ident, MacroNS, (res, vis, sp, expansion));
464 if let Some(attr) = attr::find_by_name(&item.attrs, sym::proc_macro_derive) {
465 if let Some(trait_attr) =
466 attr.meta_item_list().and_then(|list| list.get(0).cloned()) {
467 if let Some(ident) = trait_attr.ident() {
469 DefKind::Macro(MacroKind::ProcMacroStub),
472 self.define(parent, ident, MacroNS, (res, vis, ident.span, expansion));
478 // These items live in the type namespace.
479 ItemKind::Ty(..) => {
480 let res = Res::Def(DefKind::TyAlias, self.definitions.local_def_id(item.id));
481 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
484 ItemKind::Existential(_, _) => {
485 let res = Res::Def(DefKind::Existential, self.definitions.local_def_id(item.id));
486 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
489 ItemKind::Enum(ref enum_definition, _) => {
490 let module_kind = ModuleKind::Def(
492 self.definitions.local_def_id(item.id),
495 let module = self.new_module(parent,
497 parent.normal_ancestor_id,
500 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
502 for variant in &(*enum_definition).variants {
503 self.build_reduced_graph_for_variant(variant, module, vis, expansion);
507 ItemKind::TraitAlias(..) => {
508 let res = Res::Def(DefKind::TraitAlias, self.definitions.local_def_id(item.id));
509 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
512 // These items live in both the type and value namespaces.
513 ItemKind::Struct(ref struct_def, _) => {
514 // Define a name in the type namespace.
515 let def_id = self.definitions.local_def_id(item.id);
516 let res = Res::Def(DefKind::Struct, def_id);
517 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
519 let mut ctor_vis = vis;
521 let has_non_exhaustive = attr::contains_name(&item.attrs, sym::non_exhaustive);
523 // If the structure is marked as non_exhaustive then lower the visibility
524 // to within the crate.
525 if has_non_exhaustive && vis == ty::Visibility::Public {
526 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
529 // Record field names for error reporting.
530 let field_names = struct_def.fields().iter().filter_map(|field| {
531 let field_vis = self.resolve_visibility(&field.vis);
532 if ctor_vis.is_at_least(field_vis, &*self) {
533 ctor_vis = field_vis;
535 field.ident.map(|ident| ident.name)
537 let item_def_id = self.definitions.local_def_id(item.id);
538 self.insert_field_names(item_def_id, field_names);
540 // If this is a tuple or unit struct, define a name
541 // in the value namespace as well.
542 if let Some(ctor_node_id) = struct_def.ctor_id() {
543 let ctor_res = Res::Def(
544 DefKind::Ctor(CtorOf::Struct, CtorKind::from_ast(struct_def)),
545 self.definitions.local_def_id(ctor_node_id),
547 self.define(parent, ident, ValueNS, (ctor_res, ctor_vis, sp, expansion));
548 self.struct_constructors.insert(res.def_id(), (ctor_res, ctor_vis));
552 ItemKind::Union(ref vdata, _) => {
553 let res = Res::Def(DefKind::Union, self.definitions.local_def_id(item.id));
554 self.define(parent, ident, TypeNS, (res, vis, sp, expansion));
556 // Record field names for error reporting.
557 let field_names = vdata.fields().iter().filter_map(|field| {
558 self.resolve_visibility(&field.vis);
559 field.ident.map(|ident| ident.name)
561 let item_def_id = self.definitions.local_def_id(item.id);
562 self.insert_field_names(item_def_id, field_names);
565 ItemKind::Impl(..) => {}
567 ItemKind::Trait(..) => {
568 let def_id = self.definitions.local_def_id(item.id);
570 // Add all the items within to a new module.
571 let module_kind = ModuleKind::Def(DefKind::Trait, def_id, ident.name);
572 let module = self.new_module(parent,
574 parent.normal_ancestor_id,
577 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
578 self.current_module = module;
581 ItemKind::MacroDef(..) | ItemKind::Mac(_) => unreachable!(),
585 // Constructs the reduced graph for one variant. Variants exist in the
586 // type and value namespaces.
587 fn build_reduced_graph_for_variant(&mut self,
592 let ident = variant.node.ident;
594 // Define a name in the type namespace.
595 let def_id = self.definitions.local_def_id(variant.node.id);
596 let res = Res::Def(DefKind::Variant, def_id);
597 self.define(parent, ident, TypeNS, (res, vis, variant.span, expansion));
599 // If the variant is marked as non_exhaustive then lower the visibility to within the
601 let mut ctor_vis = vis;
602 let has_non_exhaustive = attr::contains_name(&variant.node.attrs, sym::non_exhaustive);
603 if has_non_exhaustive && vis == ty::Visibility::Public {
604 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
607 // Define a constructor name in the value namespace.
608 // Braced variants, unlike structs, generate unusable names in
609 // value namespace, they are reserved for possible future use.
610 // It's ok to use the variant's id as a ctor id since an
611 // error will be reported on any use of such resolution anyway.
612 let ctor_node_id = variant.node.data.ctor_id().unwrap_or(variant.node.id);
613 let ctor_def_id = self.definitions.local_def_id(ctor_node_id);
614 let ctor_kind = CtorKind::from_ast(&variant.node.data);
615 let ctor_res = Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id);
616 self.define(parent, ident, ValueNS, (ctor_res, ctor_vis, variant.span, expansion));
619 /// Constructs the reduced graph for one foreign item.
620 fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem, expansion: Mark) {
621 let (res, ns) = match item.node {
622 ForeignItemKind::Fn(..) => {
623 (Res::Def(DefKind::Fn, self.definitions.local_def_id(item.id)), ValueNS)
625 ForeignItemKind::Static(..) => {
626 (Res::Def(DefKind::Static, self.definitions.local_def_id(item.id)), ValueNS)
628 ForeignItemKind::Ty => {
629 (Res::Def(DefKind::ForeignTy, self.definitions.local_def_id(item.id)), TypeNS)
631 ForeignItemKind::Macro(_) => unreachable!(),
633 let parent = self.current_module;
634 let vis = self.resolve_visibility(&item.vis);
635 self.define(parent, item.ident, ns, (res, vis, item.span, expansion));
638 fn build_reduced_graph_for_block(&mut self, block: &Block, expansion: Mark) {
639 let parent = self.current_module;
640 if self.block_needs_anonymous_module(block) {
641 let module = self.new_module(parent,
642 ModuleKind::Block(block.id),
643 parent.normal_ancestor_id,
646 self.block_map.insert(block.id, module);
647 self.current_module = module; // Descend into the block.
651 /// Builds the reduced graph for a single item in an external crate.
652 fn build_reduced_graph_for_external_crate_res(
655 child: Export<ast::NodeId>,
657 let Export { ident, res, vis, span } = child;
658 // FIXME: We shouldn't create the gensym here, it should come from metadata,
659 // but metadata cannot encode gensyms currently, so we create it here.
660 // This is only a guess, two equivalent idents may incorrectly get different gensyms here.
661 let ident = ident.gensym_if_underscore();
662 let expansion = Mark::root(); // FIXME(jseyfried) intercrate hygiene
664 Res::Def(kind @ DefKind::Mod, def_id)
665 | Res::Def(kind @ DefKind::Enum, def_id) => {
666 let module = self.new_module(parent,
667 ModuleKind::Def(kind, def_id, ident.name),
671 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
673 Res::Def(DefKind::Variant, _)
674 | Res::Def(DefKind::TyAlias, _)
675 | Res::Def(DefKind::ForeignTy, _)
676 | Res::Def(DefKind::Existential, _)
677 | Res::Def(DefKind::TraitAlias, _)
680 self.define(parent, ident, TypeNS, (res, vis, DUMMY_SP, expansion));
682 Res::Def(DefKind::Fn, _)
683 | Res::Def(DefKind::Static, _)
684 | Res::Def(DefKind::Const, _)
685 | Res::Def(DefKind::Ctor(CtorOf::Variant, ..), _) => {
686 self.define(parent, ident, ValueNS, (res, vis, DUMMY_SP, expansion));
688 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), def_id) => {
689 self.define(parent, ident, ValueNS, (res, vis, DUMMY_SP, expansion));
691 if let Some(struct_def_id) =
692 self.cstore.def_key(def_id).parent
693 .map(|index| DefId { krate: def_id.krate, index: index }) {
694 self.struct_constructors.insert(struct_def_id, (res, vis));
697 Res::Def(DefKind::Trait, def_id) => {
698 let module_kind = ModuleKind::Def(DefKind::Trait, def_id, ident.name);
699 let module = self.new_module(parent,
701 parent.normal_ancestor_id,
704 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
706 for child in self.cstore.item_children_untracked(def_id, self.session) {
707 let res = child.res.map_id(|_| panic!("unexpected id"));
708 let ns = if let Res::Def(DefKind::AssocTy, _) = res {
711 self.define(module, child.ident, ns,
712 (res, ty::Visibility::Public, DUMMY_SP, expansion));
714 if self.cstore.associated_item_cloned_untracked(child.res.def_id())
715 .method_has_self_argument {
716 self.has_self.insert(res.def_id());
719 module.populated.set(true);
721 Res::Def(DefKind::Struct, def_id) | Res::Def(DefKind::Union, def_id) => {
722 self.define(parent, ident, TypeNS, (res, vis, DUMMY_SP, expansion));
724 // Record field names for error reporting.
725 let field_names = self.cstore.struct_field_names_untracked(def_id);
726 self.insert_field_names(def_id, field_names);
728 Res::Def(DefKind::Macro(..), _) | Res::NonMacroAttr(..) => {
729 self.define(parent, ident, MacroNS, (res, vis, DUMMY_SP, expansion));
731 _ => bug!("unexpected resolution: {:?}", res)
735 pub fn get_module(&mut self, def_id: DefId) -> Module<'a> {
736 if def_id.krate == LOCAL_CRATE {
737 return self.module_map[&def_id]
740 let macros_only = self.cstore.dep_kind_untracked(def_id.krate).macros_only();
741 if let Some(&module) = self.extern_module_map.get(&(def_id, macros_only)) {
745 let (name, parent) = if def_id.index == CRATE_DEF_INDEX {
746 (self.cstore.crate_name_untracked(def_id.krate).as_interned_str(), None)
748 let def_key = self.cstore.def_key(def_id);
749 (def_key.disambiguated_data.data.get_opt_name().unwrap(),
750 Some(self.get_module(DefId { index: def_key.parent.unwrap(), ..def_id })))
753 let kind = ModuleKind::Def(DefKind::Mod, def_id, name.as_symbol());
755 self.arenas.alloc_module(ModuleData::new(parent, kind, def_id, Mark::root(), DUMMY_SP));
756 self.extern_module_map.insert((def_id, macros_only), module);
760 pub fn macro_def_scope(&mut self, expansion: Mark) -> Module<'a> {
761 let def_id = self.macro_defs[&expansion];
762 if let Some(id) = self.definitions.as_local_node_id(def_id) {
763 self.local_macro_def_scopes[&id]
764 } else if def_id.krate == CrateNum::BuiltinMacros {
765 self.injected_crate.unwrap_or(self.graph_root)
767 let module_def_id = ty::DefIdTree::parent(&*self, def_id).unwrap();
768 self.get_module(module_def_id)
772 pub fn get_macro(&mut self, res: Res) -> Lrc<SyntaxExtension> {
773 let def_id = match res {
774 Res::Def(DefKind::Macro(..), def_id) => def_id,
775 Res::NonMacroAttr(attr_kind) => return Lrc::new(SyntaxExtension::NonMacroAttr {
776 mark_used: attr_kind == NonMacroAttrKind::Tool,
778 _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
780 if let Some(ext) = self.macro_map.get(&def_id) {
784 let macro_def = match self.cstore.load_macro_untracked(def_id, &self.session) {
785 LoadedMacro::MacroDef(macro_def) => macro_def,
786 LoadedMacro::ProcMacro(ext) => return ext,
789 let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
790 &self.session.features_untracked(),
792 self.cstore.crate_edition_untracked(def_id.krate)));
793 self.macro_map.insert(def_id, ext.clone());
797 /// Ensures that the reduced graph rooted at the given external module
798 /// is built, building it if it is not.
799 pub fn populate_module_if_necessary(&mut self, module: Module<'a>) {
800 if module.populated.get() { return }
801 let def_id = module.def_id().unwrap();
802 for child in self.cstore.item_children_untracked(def_id, self.session) {
803 let child = child.map_id(|_| panic!("unexpected id"));
804 self.build_reduced_graph_for_external_crate_res(module, child);
806 module.populated.set(true)
809 fn legacy_import_macro(&mut self,
811 binding: &'a NameBinding<'a>,
813 allow_shadowing: bool) {
814 if self.macro_use_prelude.insert(name, binding).is_some() && !allow_shadowing {
815 let msg = format!("`{}` is already in scope", name);
817 "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)";
818 self.session.struct_span_err(span, &msg).note(note).emit();
822 /// Returns `true` if we should consider the underlying `extern crate` to be used.
823 fn process_legacy_macro_imports(&mut self, item: &Item, module: Module<'a>,
824 parent_scope: &ParentScope<'a>) -> bool {
825 let mut import_all = None;
826 let mut single_imports = Vec::new();
827 for attr in &item.attrs {
828 if attr.check_name(sym::macro_use) {
829 if self.current_module.parent.is_some() {
830 span_err!(self.session, item.span, E0468,
831 "an `extern crate` loading macros must be at the crate root");
833 if let ItemKind::ExternCrate(Some(orig_name)) = item.node {
834 if orig_name == kw::SelfLower {
835 self.session.span_err(attr.span,
836 "`macro_use` is not supported on `extern crate self`");
839 let ill_formed = |span| span_err!(self.session, span, E0466, "bad macro import");
841 Some(meta) => match meta.node {
842 MetaItemKind::Word => {
843 import_all = Some(meta.span);
846 MetaItemKind::List(nested_metas) => for nested_meta in nested_metas {
847 match nested_meta.ident() {
848 Some(ident) if nested_meta.is_word() => single_imports.push(ident),
849 _ => ill_formed(nested_meta.span()),
852 MetaItemKind::NameValue(..) => ill_formed(meta.span),
854 None => ill_formed(attr.span),
859 let arenas = self.arenas;
860 let macro_use_directive = |span| arenas.alloc_import_directive(ImportDirective {
863 parent_scope: parent_scope.clone(),
864 imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
865 subclass: ImportDirectiveSubclass::MacroUse,
866 use_span_with_attributes: item.span_with_attributes(),
867 has_attributes: !item.attrs.is_empty(),
871 module_path: Vec::new(),
872 vis: Cell::new(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))),
873 used: Cell::new(false),
876 let allow_shadowing = parent_scope.expansion == Mark::root();
877 if let Some(span) = import_all {
878 let directive = macro_use_directive(span);
879 self.potentially_unused_imports.push(directive);
880 module.for_each_child(|ident, ns, binding| if ns == MacroNS {
881 let imported_binding = self.import(binding, directive);
882 self.legacy_import_macro(ident.name, imported_binding, span, allow_shadowing);
885 for ident in single_imports.iter().cloned() {
886 let result = self.resolve_ident_in_module(
887 ModuleOrUniformRoot::Module(module),
894 if let Ok(binding) = result {
895 let directive = macro_use_directive(ident.span);
896 self.potentially_unused_imports.push(directive);
897 let imported_binding = self.import(binding, directive);
898 self.legacy_import_macro(ident.name, imported_binding,
899 ident.span, allow_shadowing);
901 span_err!(self.session, ident.span, E0469, "imported macro not found");
905 import_all.is_some() || !single_imports.is_empty()
908 /// Returns `true` if this attribute list contains `macro_use`.
909 fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool {
911 if attr.check_name(sym::macro_escape) {
912 let msg = "macro_escape is a deprecated synonym for macro_use";
913 let mut err = self.session.struct_span_warn(attr.span, msg);
914 if let ast::AttrStyle::Inner = attr.style {
915 err.help("consider an outer attribute, #[macro_use] mod ...").emit();
919 } else if !attr.check_name(sym::macro_use) {
924 self.session.span_err(attr.span, "arguments to macro_use are not allowed here");
933 pub struct BuildReducedGraphVisitor<'a, 'b: 'a> {
934 pub resolver: &'a mut Resolver<'b>,
935 pub current_legacy_scope: LegacyScope<'b>,
939 impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
940 fn visit_invoc(&mut self, id: ast::NodeId) -> &'b InvocationData<'b> {
941 let mark = id.placeholder_to_mark();
942 self.resolver.current_module.unresolved_invocations.borrow_mut().insert(mark);
943 let invocation = self.resolver.invocations[&mark];
944 invocation.module.set(self.resolver.current_module);
945 invocation.parent_legacy_scope.set(self.current_legacy_scope);
950 macro_rules! method {
951 ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
952 fn $visit(&mut self, node: &'a $ty) {
953 if let $invoc(..) = node.node {
954 self.visit_invoc(node.id);
956 visit::$walk(self, node);
962 impl<'a, 'b> Visitor<'a> for BuildReducedGraphVisitor<'a, 'b> {
963 method!(visit_impl_item: ast::ImplItem, ast::ImplItemKind::Macro, walk_impl_item);
964 method!(visit_expr: ast::Expr, ast::ExprKind::Mac, walk_expr);
965 method!(visit_pat: ast::Pat, ast::PatKind::Mac, walk_pat);
966 method!(visit_ty: ast::Ty, ast::TyKind::Mac, walk_ty);
968 fn visit_item(&mut self, item: &'a Item) {
969 let macro_use = match item.node {
970 ItemKind::MacroDef(..) => {
971 self.resolver.define_macro(item, self.expansion, &mut self.current_legacy_scope);
974 ItemKind::Mac(..) => {
975 self.current_legacy_scope = LegacyScope::Invocation(self.visit_invoc(item.id));
978 ItemKind::Mod(..) => self.resolver.contains_macro_use(&item.attrs),
982 let orig_current_module = self.resolver.current_module;
983 let orig_current_legacy_scope = self.current_legacy_scope;
984 let parent_scope = ParentScope {
985 module: self.resolver.current_module,
986 expansion: self.expansion,
987 legacy: self.current_legacy_scope,
990 self.resolver.build_reduced_graph_for_item(item, parent_scope);
991 visit::walk_item(self, item);
992 self.resolver.current_module = orig_current_module;
994 self.current_legacy_scope = orig_current_legacy_scope;
998 fn visit_stmt(&mut self, stmt: &'a ast::Stmt) {
999 if let ast::StmtKind::Mac(..) = stmt.node {
1000 self.current_legacy_scope = LegacyScope::Invocation(self.visit_invoc(stmt.id));
1002 visit::walk_stmt(self, stmt);
1006 fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
1007 if let ForeignItemKind::Macro(_) = foreign_item.node {
1008 self.visit_invoc(foreign_item.id);
1012 self.resolver.build_reduced_graph_for_foreign_item(foreign_item, self.expansion);
1013 visit::walk_foreign_item(self, foreign_item);
1016 fn visit_block(&mut self, block: &'a Block) {
1017 let orig_current_module = self.resolver.current_module;
1018 let orig_current_legacy_scope = self.current_legacy_scope;
1019 self.resolver.build_reduced_graph_for_block(block, self.expansion);
1020 visit::walk_block(self, block);
1021 self.resolver.current_module = orig_current_module;
1022 self.current_legacy_scope = orig_current_legacy_scope;
1025 fn visit_trait_item(&mut self, item: &'a TraitItem) {
1026 let parent = self.resolver.current_module;
1028 if let TraitItemKind::Macro(_) = item.node {
1029 self.visit_invoc(item.id);
1033 // Add the item to the trait info.
1034 let item_def_id = self.resolver.definitions.local_def_id(item.id);
1035 let (res, ns) = match item.node {
1036 TraitItemKind::Const(..) => (Res::Def(DefKind::AssocConst, item_def_id), ValueNS),
1037 TraitItemKind::Method(ref sig, _) => {
1038 if sig.decl.has_self() {
1039 self.resolver.has_self.insert(item_def_id);
1041 (Res::Def(DefKind::Method, item_def_id), ValueNS)
1043 TraitItemKind::Type(..) => (Res::Def(DefKind::AssocTy, item_def_id), TypeNS),
1044 TraitItemKind::Macro(_) => bug!(), // handled above
1047 let vis = ty::Visibility::Public;
1048 self.resolver.define(parent, item.ident, ns, (res, vis, item.span, self.expansion));
1050 self.resolver.current_module = parent.parent.unwrap(); // nearest normal ancestor
1051 visit::walk_trait_item(self, item);
1052 self.resolver.current_module = parent;
1055 fn visit_token(&mut self, t: TokenKind) {
1056 if let token::Interpolated(nt) = t {
1057 if let token::NtExpr(ref expr) = *nt {
1058 if let ast::ExprKind::Mac(..) = expr.node {
1059 self.visit_invoc(expr.id);
1065 fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1066 if !attr.is_sugared_doc && is_builtin_attr(attr) {
1067 let parent_scope = ParentScope {
1068 module: self.resolver.current_module.nearest_item_scope(),
1069 expansion: self.expansion,
1070 legacy: self.current_legacy_scope,
1071 // Let's hope discerning built-in attributes from derive helpers is not necessary
1072 derives: Vec::new(),
1074 parent_scope.module.builtin_attrs.borrow_mut().push((
1075 attr.path.segments[0].ident, parent_scope
1078 visit::walk_attribute(self, attr);