1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Reduced graph building
13 //! Here we build the "reduced graph": the graph of the module tree without
14 //! any imports resolved.
16 use macros::{InvocationData, ParentScope, LegacyScope};
17 use resolve_imports::ImportDirective;
18 use resolve_imports::ImportDirectiveSubclass::{self, GlobImport, SingleImport};
19 use {Module, ModuleData, ModuleKind, NameBinding, NameBindingKind, Segment, ToNameBinding};
20 use {ModuleOrUniformRoot, PerNS, Resolver, ResolverArenas, ExternPreludeEntry};
21 use Namespace::{self, TypeNS, ValueNS, MacroNS};
22 use {resolve_error, resolve_struct_error, ResolutionError};
24 use rustc::hir::def::*;
25 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
27 use rustc::middle::cstore::CrateStore;
28 use rustc_metadata::cstore::LoadedMacro;
32 use rustc_data_structures::sync::Lrc;
34 use syntax::ast::{Name, Ident};
37 use syntax::ast::{self, Block, ForeignItem, ForeignItemKind, Item, ItemKind, NodeId};
38 use syntax::ast::{MetaItemKind, Mutability, StmtKind, TraitItem, TraitItemKind, Variant};
39 use syntax::ext::base::{MacroKind, SyntaxExtension};
40 use syntax::ext::base::Determinacy::Undetermined;
41 use syntax::ext::hygiene::Mark;
42 use syntax::ext::tt::macro_rules;
43 use syntax::feature_gate::{is_builtin_attr, emit_feature_err, GateIssue};
44 use syntax::parse::token::{self, Token};
45 use syntax::std_inject::injected_crate_name;
46 use syntax::symbol::keywords;
47 use syntax::visit::{self, Visitor};
49 use syntax_pos::{Span, DUMMY_SP};
51 impl<'a> ToNameBinding<'a> for (Module<'a>, ty::Visibility, Span, Mark) {
52 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
53 arenas.alloc_name_binding(NameBinding {
54 kind: NameBindingKind::Module(self.0),
62 impl<'a> ToNameBinding<'a> for (Def, ty::Visibility, Span, Mark) {
63 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
64 arenas.alloc_name_binding(NameBinding {
65 kind: NameBindingKind::Def(self.0, false),
73 pub(crate) struct IsMacroExport;
75 impl<'a> ToNameBinding<'a> for (Def, 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::Def(self.0, true),
86 impl<'a> Resolver<'a> {
87 /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
88 /// otherwise, reports an error.
89 pub fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T)
90 where T: ToNameBinding<'a>,
92 let binding = def.to_name_binding(self.arenas);
93 if let Err(old_binding) = self.try_define(parent, ident, ns, binding) {
94 self.report_conflict(parent, ident, ns, old_binding, &binding);
98 fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
99 // If any statements are items, we need to create an anonymous module
100 block.stmts.iter().any(|statement| match statement.node {
101 StmtKind::Item(_) | StmtKind::Mac(_) => true,
106 fn insert_field_names(&mut self, def_id: DefId, field_names: Vec<Name>) {
107 if !field_names.is_empty() {
108 self.field_names.insert(def_id, field_names);
112 fn build_reduced_graph_for_use_tree(
114 // This particular use tree
115 use_tree: &ast::UseTree,
117 parent_prefix: &[Segment],
119 // The whole `use` item
120 parent_scope: ParentScope<'a>,
125 debug!("build_reduced_graph_for_use_tree(parent_prefix={:?}, use_tree={:?}, nested={})",
126 parent_prefix, use_tree, nested);
128 let mut prefix_iter = parent_prefix.iter().cloned()
129 .chain(use_tree.prefix.segments.iter().map(|seg| seg.into())).peekable();
131 // On 2015 edition imports are resolved as crate-relative by default,
132 // so prefixes are prepended with crate root segment if necessary.
133 // The root is prepended lazily, when the first non-empty prefix or terminating glob
134 // appears, so imports in braced groups can have roots prepended independently.
135 // 2015 identifiers used on global 2018 edition enter special "virtual 2015 mode", don't
136 // get crate root prepended, but get special treatment during in-scope resolution instead.
137 let is_glob = if let ast::UseTreeKind::Glob = use_tree.kind { true } else { false };
138 let crate_root = match prefix_iter.peek() {
139 Some(seg) if !seg.ident.is_path_segment_keyword() &&
140 seg.ident.span.rust_2015() && self.session.rust_2015() => {
141 Some(seg.ident.span.ctxt())
143 None if is_glob && use_tree.span.rust_2015() => {
144 Some(use_tree.span.ctxt())
147 }.map(|ctxt| Segment::from_ident(Ident::new(
148 keywords::PathRoot.name(), use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt)
151 let prefix = crate_root.into_iter().chain(prefix_iter).collect::<Vec<_>>();
152 debug!("build_reduced_graph_for_use_tree: prefix={:?}", prefix);
154 let empty_for_self = |prefix: &[Segment]| {
156 prefix.len() == 1 && prefix[0].ident.name == keywords::PathRoot.name()
158 match use_tree.kind {
159 ast::UseTreeKind::Simple(rename, ..) => {
160 let mut ident = use_tree.ident().gensym_if_underscore();
161 let mut module_path = prefix;
162 let mut source = module_path.pop().unwrap();
163 let mut type_ns_only = false;
166 // Correctly handle `self`
167 if source.ident.name == keywords::SelfLower.name() {
170 if empty_for_self(&module_path) {
175 SelfImportOnlyInImportListWithNonEmptyPrefix
180 // Replace `use foo::self;` with `use foo;`
181 source = module_path.pop().unwrap();
182 if rename.is_none() {
183 ident = source.ident;
188 if source.ident.name == keywords::SelfLower.name() {
191 ResolutionError::SelfImportsOnlyAllowedWithin);
194 // Disallow `use $crate;`
195 if source.ident.name == keywords::DollarCrate.name() && module_path.is_empty() {
196 let crate_root = self.resolve_crate_root(source.ident);
197 let crate_name = match crate_root.kind {
198 ModuleKind::Def(_, name) => name,
199 ModuleKind::Block(..) => unreachable!(),
201 // HACK(eddyb) unclear how good this is, but keeping `$crate`
202 // in `source` breaks `src/test/compile-fail/import-crate-var.rs`,
203 // while the current crate doesn't have a valid `crate_name`.
204 if crate_name != keywords::Invalid.name() {
205 // `crate_name` should not be interpreted as relative.
206 module_path.push(Segment {
208 name: keywords::PathRoot.name(),
209 span: source.ident.span,
211 id: Some(self.session.next_node_id()),
213 source.ident.name = crate_name;
215 if rename.is_none() {
216 ident.name = crate_name;
219 self.session.struct_span_warn(item.span, "`$crate` may not be imported")
220 .note("`use $crate;` was erroneously allowed and \
221 will become a hard error in a future release")
226 if ident.name == keywords::Crate.name() {
227 self.session.span_err(ident.span,
228 "crate root imports need to be explicitly named: \
229 `use crate as name;`");
232 let subclass = SingleImport {
233 source: source.ident,
235 source_bindings: PerNS {
236 type_ns: Cell::new(Err(Undetermined)),
237 value_ns: Cell::new(Err(Undetermined)),
238 macro_ns: Cell::new(Err(Undetermined)),
240 target_bindings: PerNS {
241 type_ns: Cell::new(None),
242 value_ns: Cell::new(None),
243 macro_ns: Cell::new(None),
247 self.add_import_directive(
258 ast::UseTreeKind::Glob => {
259 let subclass = GlobImport {
260 is_prelude: attr::contains_name(&item.attrs, "prelude_import"),
261 max_vis: Cell::new(ty::Visibility::Invisible),
263 self.add_import_directive(
274 ast::UseTreeKind::Nested(ref items) => {
275 // Ensure there is at most one `self` in the list
276 let self_spans = items.iter().filter_map(|&(ref use_tree, _)| {
277 if let ast::UseTreeKind::Simple(..) = use_tree.kind {
278 if use_tree.ident().name == keywords::SelfLower.name() {
279 return Some(use_tree.span);
284 }).collect::<Vec<_>>();
285 if self_spans.len() > 1 {
286 let mut e = resolve_struct_error(self,
288 ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
290 for other_span in self_spans.iter().skip(1) {
291 e.span_label(*other_span, "another `self` import appears here");
297 for &(ref tree, id) in items {
298 self.build_reduced_graph_for_use_tree(
299 // This particular use tree
300 tree, id, &prefix, true,
301 // The whole `use` item
302 parent_scope.clone(), item, vis, root_span,
306 // Empty groups `a::b::{}` are turned into synthetic `self` imports
307 // `a::b::c::{self as _}`, so that their prefixes are correctly
308 // resolved and checked for privacy/stability/etc.
309 if items.is_empty() && !empty_for_self(&prefix) {
310 let new_span = prefix[prefix.len() - 1].ident.span;
311 let tree = ast::UseTree {
312 prefix: ast::Path::from_ident(
313 Ident::new(keywords::SelfLower.name(), new_span)
315 kind: ast::UseTreeKind::Simple(
316 Some(Ident::new(keywords::Underscore.name().gensymed(), new_span)),
322 self.build_reduced_graph_for_use_tree(
323 // This particular use tree
324 &tree, id, &prefix, true,
325 // The whole `use` item
326 parent_scope, item, ty::Visibility::Invisible, root_span,
333 /// Constructs the reduced graph for one item.
334 fn build_reduced_graph_for_item(&mut self, item: &Item, parent_scope: ParentScope<'a>) {
335 let parent = parent_scope.module;
336 let expansion = parent_scope.expansion;
337 let ident = item.ident.gensym_if_underscore();
339 let vis = self.resolve_visibility(&item.vis);
342 ItemKind::Use(ref use_tree) => {
343 self.build_reduced_graph_for_use_tree(
344 // This particular use tree
345 use_tree, item.id, &[], false,
346 // The whole `use` item
347 parent_scope, item, vis, use_tree.span,
351 ItemKind::ExternCrate(orig_name) => {
352 let module = if orig_name.is_none() && ident.name == keywords::SelfLower.name() {
354 .struct_span_err(item.span, "`extern crate self;` requires renaming")
355 .span_suggestion(item.span, "try", "extern crate self as name;".into())
358 } else if orig_name == Some(keywords::SelfLower.name()) {
359 if !self.session.features_untracked().extern_crate_self {
360 emit_feature_err(&self.session.parse_sess, "extern_crate_self", item.span,
361 GateIssue::Language, "`extern crate self` is unstable");
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 == 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 root_span: item.span,
388 module_path: Vec::new(),
390 used: Cell::new(used),
392 self.potentially_unused_imports.push(directive);
393 let imported_binding = self.import(binding, directive);
394 if ptr::eq(self.current_module, self.graph_root) {
395 if let Some(entry) = self.extern_prelude.get(&ident.modern()) {
396 if expansion != Mark::root() && orig_name.is_some() &&
397 entry.extern_crate_item.is_none() {
398 self.session.span_err(item.span, "macro-expanded `extern crate` items \
399 cannot shadow names passed with \
403 let entry = self.extern_prelude.entry(ident.modern())
404 .or_insert(ExternPreludeEntry {
405 extern_crate_item: None,
406 introduced_by_item: true,
408 entry.extern_crate_item = Some(imported_binding);
409 if orig_name.is_some() {
410 entry.introduced_by_item = true;
413 self.define(parent, ident, TypeNS, imported_binding);
416 ItemKind::GlobalAsm(..) => {}
418 ItemKind::Mod(..) if ident == keywords::Invalid.ident() => {} // Crate root
420 ItemKind::Mod(..) => {
421 let def_id = self.definitions.local_def_id(item.id);
422 let module_kind = ModuleKind::Def(Def::Mod(def_id), ident.name);
423 let module = self.arenas.alloc_module(ModuleData {
424 no_implicit_prelude: parent.no_implicit_prelude || {
425 attr::contains_name(&item.attrs, "no_implicit_prelude")
427 ..ModuleData::new(Some(parent), module_kind, def_id, expansion, item.span)
429 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
430 self.module_map.insert(def_id, module);
432 // Descend into the module.
433 self.current_module = module;
436 // Handled in `rustc_metadata::{native_libs,link_args}`
437 ItemKind::ForeignMod(..) => {}
439 // These items live in the value namespace.
440 ItemKind::Static(_, m, _) => {
441 let mutbl = m == Mutability::Mutable;
442 let def = Def::Static(self.definitions.local_def_id(item.id), mutbl);
443 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
445 ItemKind::Const(..) => {
446 let def = Def::Const(self.definitions.local_def_id(item.id));
447 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
449 ItemKind::Fn(..) => {
450 let def = Def::Fn(self.definitions.local_def_id(item.id));
451 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
453 // Functions introducing procedural macros reserve a slot
454 // in the macro namespace as well (see #52225).
455 if attr::contains_name(&item.attrs, "proc_macro") ||
456 attr::contains_name(&item.attrs, "proc_macro_attribute") {
457 let def = Def::Macro(def.def_id(), MacroKind::ProcMacroStub);
458 self.define(parent, ident, MacroNS, (def, vis, sp, expansion));
460 if let Some(attr) = attr::find_by_name(&item.attrs, "proc_macro_derive") {
461 if let Some(trait_attr) =
462 attr.meta_item_list().and_then(|list| list.get(0).cloned()) {
463 if let Some(ident) = trait_attr.name().map(Ident::with_empty_ctxt) {
464 let sp = trait_attr.span;
465 let def = Def::Macro(def.def_id(), MacroKind::ProcMacroStub);
466 self.define(parent, ident, MacroNS, (def, vis, sp, expansion));
472 // These items live in the type namespace.
473 ItemKind::Ty(..) => {
474 let def = Def::TyAlias(self.definitions.local_def_id(item.id));
475 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
478 ItemKind::Existential(_, _) => {
479 let def = Def::Existential(self.definitions.local_def_id(item.id));
480 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
483 ItemKind::Enum(ref enum_definition, _) => {
484 let def = Def::Enum(self.definitions.local_def_id(item.id));
485 let module_kind = ModuleKind::Def(def, ident.name);
486 let module = self.new_module(parent,
488 parent.normal_ancestor_id,
491 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
493 for variant in &(*enum_definition).variants {
494 self.build_reduced_graph_for_variant(variant, module, vis, expansion);
498 ItemKind::TraitAlias(..) => {
499 let def = Def::TraitAlias(self.definitions.local_def_id(item.id));
500 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
503 // These items live in both the type and value namespaces.
504 ItemKind::Struct(ref struct_def, _) => {
505 // Define a name in the type namespace.
506 let def_id = self.definitions.local_def_id(item.id);
507 let def = Def::Struct(def_id);
508 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
510 let mut ctor_vis = vis;
512 let has_non_exhaustive = attr::contains_name(&item.attrs, "non_exhaustive");
514 // If the structure is marked as non_exhaustive then lower the visibility
515 // to within the crate.
516 if has_non_exhaustive && vis == ty::Visibility::Public {
517 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
520 // Record field names for error reporting.
521 let field_names = struct_def.fields().iter().filter_map(|field| {
522 let field_vis = self.resolve_visibility(&field.vis);
523 if ctor_vis.is_at_least(field_vis, &*self) {
524 ctor_vis = field_vis;
526 field.ident.map(|ident| ident.name)
528 let item_def_id = self.definitions.local_def_id(item.id);
529 self.insert_field_names(item_def_id, field_names);
531 // If this is a tuple or unit struct, define a name
532 // in the value namespace as well.
533 if !struct_def.is_struct() {
534 let ctor_def = Def::StructCtor(self.definitions.local_def_id(struct_def.id()),
535 CtorKind::from_ast(struct_def));
536 self.define(parent, ident, ValueNS, (ctor_def, ctor_vis, sp, expansion));
537 self.struct_constructors.insert(def.def_id(), (ctor_def, ctor_vis));
541 ItemKind::Union(ref vdata, _) => {
542 let def = Def::Union(self.definitions.local_def_id(item.id));
543 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
545 // Record field names for error reporting.
546 let field_names = vdata.fields().iter().filter_map(|field| {
547 self.resolve_visibility(&field.vis);
548 field.ident.map(|ident| ident.name)
550 let item_def_id = self.definitions.local_def_id(item.id);
551 self.insert_field_names(item_def_id, field_names);
554 ItemKind::Impl(..) => {}
556 ItemKind::Trait(..) => {
557 let def_id = self.definitions.local_def_id(item.id);
559 // Add all the items within to a new module.
560 let module_kind = ModuleKind::Def(Def::Trait(def_id), ident.name);
561 let module = self.new_module(parent,
563 parent.normal_ancestor_id,
566 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
567 self.current_module = module;
570 ItemKind::MacroDef(..) | ItemKind::Mac(_) => unreachable!(),
574 // Constructs the reduced graph for one variant. Variants exist in the
575 // type and value namespaces.
576 fn build_reduced_graph_for_variant(&mut self,
581 let ident = variant.node.ident;
582 let def_id = self.definitions.local_def_id(variant.node.data.id());
584 // Define a name in the type namespace.
585 let def = Def::Variant(def_id);
586 self.define(parent, ident, TypeNS, (def, vis, variant.span, expansion));
588 // Define a constructor name in the value namespace.
589 // Braced variants, unlike structs, generate unusable names in
590 // value namespace, they are reserved for possible future use.
591 let ctor_kind = CtorKind::from_ast(&variant.node.data);
592 let ctor_def = Def::VariantCtor(def_id, ctor_kind);
594 self.define(parent, ident, ValueNS, (ctor_def, vis, variant.span, expansion));
597 /// Constructs the reduced graph for one foreign item.
598 fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem, expansion: Mark) {
599 let (def, ns) = match item.node {
600 ForeignItemKind::Fn(..) => {
601 (Def::Fn(self.definitions.local_def_id(item.id)), ValueNS)
603 ForeignItemKind::Static(_, m) => {
604 (Def::Static(self.definitions.local_def_id(item.id), m), ValueNS)
606 ForeignItemKind::Ty => {
607 (Def::ForeignTy(self.definitions.local_def_id(item.id)), TypeNS)
609 ForeignItemKind::Macro(_) => unreachable!(),
611 let parent = self.current_module;
612 let vis = self.resolve_visibility(&item.vis);
613 self.define(parent, item.ident, ns, (def, vis, item.span, expansion));
616 fn build_reduced_graph_for_block(&mut self, block: &Block, expansion: Mark) {
617 let parent = self.current_module;
618 if self.block_needs_anonymous_module(block) {
619 let module = self.new_module(parent,
620 ModuleKind::Block(block.id),
621 parent.normal_ancestor_id,
624 self.block_map.insert(block.id, module);
625 self.current_module = module; // Descend into the block.
629 /// Builds the reduced graph for a single item in an external crate.
630 fn build_reduced_graph_for_external_crate_def(&mut self, parent: Module<'a>, child: Export) {
631 let Export { ident, def, vis, span } = child;
632 // FIXME: We shouldn't create the gensym here, it should come from metadata,
633 // but metadata cannot encode gensyms currently, so we create it here.
634 // This is only a guess, two equivalent idents may incorrectly get different gensyms here.
635 let ident = ident.gensym_if_underscore();
636 let def_id = def.def_id();
637 let expansion = Mark::root(); // FIXME(jseyfried) intercrate hygiene
639 Def::Mod(..) | Def::Enum(..) => {
640 let module = self.new_module(parent,
641 ModuleKind::Def(def, ident.name),
645 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
647 Def::Variant(..) | Def::TyAlias(..) | Def::ForeignTy(..) => {
648 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
650 Def::Fn(..) | Def::Static(..) | Def::Const(..) | Def::VariantCtor(..) => {
651 self.define(parent, ident, ValueNS, (def, vis, DUMMY_SP, expansion));
653 Def::StructCtor(..) => {
654 self.define(parent, ident, ValueNS, (def, vis, DUMMY_SP, expansion));
656 if let Some(struct_def_id) =
657 self.cstore.def_key(def_id).parent
658 .map(|index| DefId { krate: def_id.krate, index: index }) {
659 self.struct_constructors.insert(struct_def_id, (def, vis));
663 let module_kind = ModuleKind::Def(def, ident.name);
664 let module = self.new_module(parent,
666 parent.normal_ancestor_id,
669 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
671 for child in self.cstore.item_children_untracked(def_id, self.session) {
672 let ns = if let Def::AssociatedTy(..) = child.def { TypeNS } else { ValueNS };
673 self.define(module, child.ident, ns,
674 (child.def, ty::Visibility::Public, DUMMY_SP, expansion));
676 if self.cstore.associated_item_cloned_untracked(child.def.def_id())
677 .method_has_self_argument {
678 self.has_self.insert(child.def.def_id());
681 module.populated.set(true);
683 Def::Struct(..) | Def::Union(..) => {
684 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
686 // Record field names for error reporting.
687 let field_names = self.cstore.struct_field_names_untracked(def_id);
688 self.insert_field_names(def_id, field_names);
691 self.define(parent, ident, MacroNS, (def, vis, DUMMY_SP, expansion));
693 _ => bug!("unexpected definition: {:?}", def)
697 pub fn get_module(&mut self, def_id: DefId) -> Module<'a> {
698 if def_id.krate == LOCAL_CRATE {
699 return self.module_map[&def_id]
702 let macros_only = self.cstore.dep_kind_untracked(def_id.krate).macros_only();
703 if let Some(&module) = self.extern_module_map.get(&(def_id, macros_only)) {
707 let (name, parent) = if def_id.index == CRATE_DEF_INDEX {
708 (self.cstore.crate_name_untracked(def_id.krate).as_interned_str(), None)
710 let def_key = self.cstore.def_key(def_id);
711 (def_key.disambiguated_data.data.get_opt_name().unwrap(),
712 Some(self.get_module(DefId { index: def_key.parent.unwrap(), ..def_id })))
715 let kind = ModuleKind::Def(Def::Mod(def_id), name.as_symbol());
717 self.arenas.alloc_module(ModuleData::new(parent, kind, def_id, Mark::root(), DUMMY_SP));
718 self.extern_module_map.insert((def_id, macros_only), module);
722 pub fn macro_def_scope(&mut self, expansion: Mark) -> Module<'a> {
723 let def_id = self.macro_defs[&expansion];
724 if let Some(id) = self.definitions.as_local_node_id(def_id) {
725 self.local_macro_def_scopes[&id]
726 } else if def_id.krate == CrateNum::BuiltinMacros {
727 self.injected_crate.unwrap_or(self.graph_root)
729 let module_def_id = ty::DefIdTree::parent(&*self, def_id).unwrap();
730 self.get_module(module_def_id)
734 pub fn get_macro(&mut self, def: Def) -> Lrc<SyntaxExtension> {
735 let def_id = match def {
736 Def::Macro(def_id, ..) => def_id,
737 Def::NonMacroAttr(attr_kind) => return Lrc::new(SyntaxExtension::NonMacroAttr {
738 mark_used: attr_kind == NonMacroAttrKind::Tool,
740 _ => panic!("expected `Def::Macro` or `Def::NonMacroAttr`"),
742 if let Some(ext) = self.macro_map.get(&def_id) {
746 let macro_def = match self.cstore.load_macro_untracked(def_id, &self.session) {
747 LoadedMacro::MacroDef(macro_def) => macro_def,
748 LoadedMacro::ProcMacro(ext) => return ext,
751 let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
752 &self.session.features_untracked(),
754 self.cstore.crate_edition_untracked(def_id.krate)));
755 self.macro_map.insert(def_id, ext.clone());
759 /// Ensures that the reduced graph rooted at the given external module
760 /// is built, building it if it is not.
761 pub fn populate_module_if_necessary(&mut self, module: Module<'a>) {
762 if module.populated.get() { return }
763 let def_id = module.def_id().unwrap();
764 for child in self.cstore.item_children_untracked(def_id, self.session) {
765 self.build_reduced_graph_for_external_crate_def(module, child);
767 module.populated.set(true)
770 fn legacy_import_macro(&mut self,
772 binding: &'a NameBinding<'a>,
774 allow_shadowing: bool) {
775 if self.macro_use_prelude.insert(name, binding).is_some() && !allow_shadowing {
776 let msg = format!("`{}` is already in scope", name);
778 "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)";
779 self.session.struct_span_err(span, &msg).note(note).emit();
783 // This returns true if we should consider the underlying `extern crate` to be used.
784 fn process_legacy_macro_imports(&mut self, item: &Item, module: Module<'a>,
785 parent_scope: &ParentScope<'a>) -> bool {
786 let mut import_all = None;
787 let mut single_imports = Vec::new();
788 for attr in &item.attrs {
789 if attr.check_name("macro_use") {
790 if self.current_module.parent.is_some() {
791 span_err!(self.session, item.span, E0468,
792 "an `extern crate` loading macros must be at the crate root");
794 if let ItemKind::ExternCrate(Some(orig_name)) = item.node {
795 if orig_name == keywords::SelfLower.name() {
796 self.session.span_err(attr.span,
797 "`macro_use` is not supported on `extern crate self`");
800 let ill_formed = |span| span_err!(self.session, span, E0466, "bad macro import");
802 Some(meta) => match meta.node {
803 MetaItemKind::Word => {
804 import_all = Some(meta.span);
807 MetaItemKind::List(nested_metas) => for nested_meta in nested_metas {
808 match nested_meta.word() {
809 Some(word) => single_imports.push((word.name(), word.span)),
810 None => ill_formed(nested_meta.span),
813 MetaItemKind::NameValue(..) => ill_formed(meta.span),
815 None => ill_formed(attr.span()),
820 let arenas = self.arenas;
821 let macro_use_directive = |span| arenas.alloc_import_directive(ImportDirective {
824 parent_scope: parent_scope.clone(),
825 imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
826 subclass: ImportDirectiveSubclass::MacroUse,
829 module_path: Vec::new(),
830 vis: Cell::new(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))),
831 used: Cell::new(false),
834 let allow_shadowing = parent_scope.expansion == Mark::root();
835 if let Some(span) = import_all {
836 let directive = macro_use_directive(span);
837 self.potentially_unused_imports.push(directive);
838 module.for_each_child(|ident, ns, binding| if ns == MacroNS {
839 let imported_binding = self.import(binding, directive);
840 self.legacy_import_macro(ident.name, imported_binding, span, allow_shadowing);
843 for (name, span) in single_imports.iter().cloned() {
844 let ident = Ident::with_empty_ctxt(name);
845 let result = self.resolve_ident_in_module(
846 ModuleOrUniformRoot::Module(module),
853 if let Ok(binding) = result {
854 let directive = macro_use_directive(span);
855 self.potentially_unused_imports.push(directive);
856 let imported_binding = self.import(binding, directive);
857 self.legacy_import_macro(name, imported_binding, span, allow_shadowing);
859 span_err!(self.session, span, E0469, "imported macro not found");
863 import_all.is_some() || !single_imports.is_empty()
866 // does this attribute list contain "macro_use"?
867 fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool {
869 if attr.check_name("macro_escape") {
870 let msg = "macro_escape is a deprecated synonym for macro_use";
871 let mut err = self.session.struct_span_warn(attr.span, msg);
872 if let ast::AttrStyle::Inner = attr.style {
873 err.help("consider an outer attribute, #[macro_use] mod ...").emit();
877 } else if !attr.check_name("macro_use") {
882 self.session.span_err(attr.span, "arguments to macro_use are not allowed here");
891 pub struct BuildReducedGraphVisitor<'a, 'b: 'a> {
892 pub resolver: &'a mut Resolver<'b>,
893 pub current_legacy_scope: LegacyScope<'b>,
897 impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
898 fn visit_invoc(&mut self, id: ast::NodeId) -> &'b InvocationData<'b> {
899 let mark = id.placeholder_to_mark();
900 self.resolver.current_module.unresolved_invocations.borrow_mut().insert(mark);
901 let invocation = self.resolver.invocations[&mark];
902 invocation.module.set(self.resolver.current_module);
903 invocation.parent_legacy_scope.set(self.current_legacy_scope);
908 macro_rules! method {
909 ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
910 fn $visit(&mut self, node: &'a $ty) {
911 if let $invoc(..) = node.node {
912 self.visit_invoc(node.id);
914 visit::$walk(self, node);
920 impl<'a, 'b> Visitor<'a> for BuildReducedGraphVisitor<'a, 'b> {
921 method!(visit_impl_item: ast::ImplItem, ast::ImplItemKind::Macro, walk_impl_item);
922 method!(visit_expr: ast::Expr, ast::ExprKind::Mac, walk_expr);
923 method!(visit_pat: ast::Pat, ast::PatKind::Mac, walk_pat);
924 method!(visit_ty: ast::Ty, ast::TyKind::Mac, walk_ty);
926 fn visit_item(&mut self, item: &'a Item) {
927 let macro_use = match item.node {
928 ItemKind::MacroDef(..) => {
929 self.resolver.define_macro(item, self.expansion, &mut self.current_legacy_scope);
932 ItemKind::Mac(..) => {
933 self.current_legacy_scope = LegacyScope::Invocation(self.visit_invoc(item.id));
936 ItemKind::Mod(..) => self.resolver.contains_macro_use(&item.attrs),
940 let orig_current_module = self.resolver.current_module;
941 let orig_current_legacy_scope = self.current_legacy_scope;
942 let parent_scope = ParentScope {
943 module: self.resolver.current_module,
944 expansion: self.expansion,
945 legacy: self.current_legacy_scope,
948 self.resolver.build_reduced_graph_for_item(item, parent_scope);
949 visit::walk_item(self, item);
950 self.resolver.current_module = orig_current_module;
952 self.current_legacy_scope = orig_current_legacy_scope;
956 fn visit_stmt(&mut self, stmt: &'a ast::Stmt) {
957 if let ast::StmtKind::Mac(..) = stmt.node {
958 self.current_legacy_scope = LegacyScope::Invocation(self.visit_invoc(stmt.id));
960 visit::walk_stmt(self, stmt);
964 fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
965 if let ForeignItemKind::Macro(_) = foreign_item.node {
966 self.visit_invoc(foreign_item.id);
970 self.resolver.build_reduced_graph_for_foreign_item(foreign_item, self.expansion);
971 visit::walk_foreign_item(self, foreign_item);
974 fn visit_block(&mut self, block: &'a Block) {
975 let orig_current_module = self.resolver.current_module;
976 let orig_current_legacy_scope = self.current_legacy_scope;
977 self.resolver.build_reduced_graph_for_block(block, self.expansion);
978 visit::walk_block(self, block);
979 self.resolver.current_module = orig_current_module;
980 self.current_legacy_scope = orig_current_legacy_scope;
983 fn visit_trait_item(&mut self, item: &'a TraitItem) {
984 let parent = self.resolver.current_module;
986 if let TraitItemKind::Macro(_) = item.node {
987 self.visit_invoc(item.id);
991 // Add the item to the trait info.
992 let item_def_id = self.resolver.definitions.local_def_id(item.id);
993 let (def, ns) = match item.node {
994 TraitItemKind::Const(..) => (Def::AssociatedConst(item_def_id), ValueNS),
995 TraitItemKind::Method(ref sig, _) => {
996 if sig.decl.has_self() {
997 self.resolver.has_self.insert(item_def_id);
999 (Def::Method(item_def_id), ValueNS)
1001 TraitItemKind::Type(..) => (Def::AssociatedTy(item_def_id), TypeNS),
1002 TraitItemKind::Macro(_) => bug!(), // handled above
1005 let vis = ty::Visibility::Public;
1006 self.resolver.define(parent, item.ident, ns, (def, vis, item.span, self.expansion));
1008 self.resolver.current_module = parent.parent.unwrap(); // nearest normal ancestor
1009 visit::walk_trait_item(self, item);
1010 self.resolver.current_module = parent;
1013 fn visit_token(&mut self, t: Token) {
1014 if let Token::Interpolated(nt) = t {
1015 if let token::NtExpr(ref expr) = nt.0 {
1016 if let ast::ExprKind::Mac(..) = expr.node {
1017 self.visit_invoc(expr.id);
1023 fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1024 if !attr.is_sugared_doc && is_builtin_attr(attr) {
1025 let parent_scope = ParentScope {
1026 module: self.resolver.current_module.nearest_item_scope(),
1027 expansion: self.expansion,
1028 legacy: self.current_legacy_scope,
1029 // Let's hope discerning built-in attributes from derive helpers is not necessary
1030 derives: Vec::new(),
1032 parent_scope.module.builtin_attrs.borrow_mut().push((
1033 attr.path.segments[0].ident, parent_scope
1036 visit::walk_attribute(self, attr);