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, 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::{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;
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 #[derive(Default, PartialEq, Eq)]
87 struct LegacyMacroImports {
88 import_all: Option<Span>,
89 imports: Vec<(Name, Span)>,
92 impl<'a, 'cl> Resolver<'a, 'cl> {
93 /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
94 /// otherwise, reports an error.
95 pub fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T)
96 where T: ToNameBinding<'a>,
98 let binding = def.to_name_binding(self.arenas);
99 if let Err(old_binding) = self.try_define(parent, ident, ns, binding) {
100 self.report_conflict(parent, ident, ns, old_binding, &binding);
104 fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
105 // If any statements are items, we need to create an anonymous module
106 block.stmts.iter().any(|statement| match statement.node {
107 StmtKind::Item(_) | StmtKind::Mac(_) => true,
112 fn insert_field_names(&mut self, def_id: DefId, field_names: Vec<Name>) {
113 if !field_names.is_empty() {
114 self.field_names.insert(def_id, field_names);
118 fn build_reduced_graph_for_use_tree(
120 root_use_tree: &ast::UseTree,
122 use_tree: &ast::UseTree,
125 parent_prefix: &[Ident],
126 mut uniform_paths_canary_emitted: bool,
131 debug!("build_reduced_graph_for_use_tree(parent_prefix={:?}, \
132 uniform_paths_canary_emitted={}, \
133 use_tree={:?}, nested={})",
134 parent_prefix, uniform_paths_canary_emitted, use_tree, nested);
136 let is_prelude = attr::contains_name(&item.attrs, "prelude_import");
138 self.session.rust_2018() &&
139 self.session.features_untracked().uniform_paths;
141 let prefix_iter = || parent_prefix.iter().cloned()
142 .chain(use_tree.prefix.segments.iter().map(|seg| seg.ident));
143 let prefix_start = prefix_iter().next();
144 let starts_with_non_keyword = prefix_start.map_or(false, |ident| {
145 !ident.is_path_segment_keyword()
148 // Imports are resolved as global by default, prepend `CrateRoot`,
149 // unless `#![feature(uniform_paths)]` is enabled.
150 let inject_crate_root =
152 match use_tree.kind {
153 // HACK(eddyb) special-case `use *` to mean `use ::*`.
154 ast::UseTreeKind::Glob if prefix_start.is_none() => true,
155 _ => starts_with_non_keyword,
157 let root = if inject_crate_root {
158 let span = use_tree.prefix.span.shrink_to_lo();
159 Some(Ident::new(keywords::CrateRoot.name(), span))
164 let prefix: Vec<_> = root.into_iter().chain(prefix_iter()).collect();
166 debug!("build_reduced_graph_for_use_tree: prefix={:?}", prefix);
168 // `#[feature(uniform_paths)]` allows an unqualified import path,
169 // e.g. `use x::...;` to resolve not just globally (`use ::x::...;`)
170 // but also relatively (`use self::x::...;`). To catch ambiguities
171 // that might arise from both of these being available and resolution
172 // silently picking one of them, an artificial `use self::x as _;`
173 // import is injected as a "canary", and an error is emitted if it
174 // successfully resolves while an `x` external crate exists.
176 // For each block scope around the `use` item, one special canary
177 // import of the form `use x as _;` is also injected, having its
178 // parent set to that scope; `resolve_imports` will only resolve
179 // it within its appropriate scope; if any of them successfully
180 // resolve, an ambiguity error is emitted, since the original
181 // import can't see the item in the block scope (`self::x` only
182 // looks in the enclosing module), but a non-`use` path could.
184 // Additionally, the canary might be able to catch limitations of the
185 // current implementation, where `::x` may be chosen due to `self::x`
186 // not existing, but `self::x` could appear later, from macro expansion.
188 // NB. The canary currently only errors if the `x::...` path *could*
189 // resolve as a relative path through the extern crate, i.e. `x` is
190 // in `extern_prelude`, *even though* `::x` might still forcefully
191 // load a non-`extern_prelude` crate.
192 // While always producing an ambiguity errors if `self::x` exists and
193 // a crate *could* be loaded, would be more conservative, imports for
194 // local modules named `test` (or less commonly, `syntax` or `log`),
195 // would need to be qualified (e.g. `self::test`), which is considered
196 // ergonomically unacceptable.
197 let emit_uniform_paths_canary =
198 !uniform_paths_canary_emitted &&
199 self.session.rust_2018() &&
200 starts_with_non_keyword;
201 if emit_uniform_paths_canary {
202 let source = prefix_start.unwrap();
204 // Helper closure to emit a canary with the given base path.
205 let emit = |this: &mut Self, base: Option<Ident>| {
206 let subclass = SingleImport {
208 name: keywords::Underscore.name().gensymed(),
213 type_ns: Cell::new(Err(Undetermined)),
214 value_ns: Cell::new(Err(Undetermined)),
215 macro_ns: Cell::new(Err(Undetermined)),
219 this.add_import_directive(
220 base.into_iter().collect(),
226 ty::Visibility::Invisible,
228 true, // is_uniform_paths_canary
232 // A single simple `self::x` canary.
233 emit(self, Some(Ident {
234 name: keywords::SelfValue.name(),
238 // One special unprefixed canary per block scope around
239 // the import, to detect items unreachable by `self::x`.
240 let orig_current_module = self.current_module;
241 let mut span = source.span.modern();
243 match self.current_module.kind {
244 ModuleKind::Block(..) => emit(self, None),
245 ModuleKind::Def(..) => break,
247 match self.hygienic_lexical_parent(self.current_module, &mut span) {
249 self.current_module = module;
254 self.current_module = orig_current_module;
256 uniform_paths_canary_emitted = true;
259 match use_tree.kind {
260 ast::UseTreeKind::Simple(rename, ..) => {
261 let mut ident = use_tree.ident();
262 let mut module_path = prefix;
263 let mut source = module_path.pop().unwrap();
264 let mut type_ns_only = false;
267 // Correctly handle `self`
268 if source.name == keywords::SelfValue.name() {
271 let empty_prefix = module_path.last().map_or(true, |ident| {
272 ident.name == keywords::CrateRoot.name()
279 SelfImportOnlyInImportListWithNonEmptyPrefix
284 // Replace `use foo::self;` with `use foo;`
285 source = module_path.pop().unwrap();
286 if rename.is_none() {
292 if source.name == keywords::SelfValue.name() {
295 ResolutionError::SelfImportsOnlyAllowedWithin);
298 // Disallow `use $crate;`
299 if source.name == keywords::DollarCrate.name() && module_path.is_empty() {
300 let crate_root = self.resolve_crate_root(source);
301 let crate_name = match crate_root.kind {
302 ModuleKind::Def(_, name) => name,
303 ModuleKind::Block(..) => unreachable!(),
305 // HACK(eddyb) unclear how good this is, but keeping `$crate`
306 // in `source` breaks `src/test/compile-fail/import-crate-var.rs`,
307 // while the current crate doesn't have a valid `crate_name`.
308 if crate_name != keywords::Invalid.name() {
309 // `crate_name` should not be interpreted as relative.
310 module_path.push(Ident {
311 name: keywords::CrateRoot.name(),
314 source.name = crate_name;
316 if rename.is_none() {
317 ident.name = crate_name;
320 self.session.struct_span_warn(item.span, "`$crate` may not be imported")
321 .note("`use $crate;` was erroneously allowed and \
322 will become a hard error in a future release")
327 if ident.name == keywords::Crate.name() {
328 self.session.span_err(ident.span,
329 "crate root imports need to be explicitly named: \
330 `use crate as name;`");
333 let subclass = SingleImport {
337 type_ns: Cell::new(Err(Undetermined)),
338 value_ns: Cell::new(Err(Undetermined)),
339 macro_ns: Cell::new(Err(Undetermined)),
343 self.add_import_directive(
352 false, // is_uniform_paths_canary
355 ast::UseTreeKind::Glob => {
356 let subclass = GlobImport {
358 max_vis: Cell::new(ty::Visibility::Invisible),
360 self.add_import_directive(
369 false, // is_uniform_paths_canary
372 ast::UseTreeKind::Nested(ref items) => {
373 // Ensure there is at most one `self` in the list
374 let self_spans = items.iter().filter_map(|&(ref use_tree, _)| {
375 if let ast::UseTreeKind::Simple(..) = use_tree.kind {
376 if use_tree.ident().name == keywords::SelfValue.name() {
377 return Some(use_tree.span);
382 }).collect::<Vec<_>>();
383 if self_spans.len() > 1 {
384 let mut e = resolve_struct_error(self,
386 ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
388 for other_span in self_spans.iter().skip(1) {
389 e.span_label(*other_span, "another `self` import appears here");
395 for &(ref tree, id) in items {
396 self.build_reduced_graph_for_use_tree(
403 uniform_paths_canary_emitted,
413 /// Constructs the reduced graph for one item.
414 fn build_reduced_graph_for_item(&mut self, item: &Item, expansion: Mark) {
415 let parent = self.current_module;
416 let ident = item.ident;
418 let vis = self.resolve_visibility(&item.vis);
421 ItemKind::Use(ref use_tree) => {
422 self.build_reduced_graph_for_use_tree(
429 false, // uniform_paths_canary_emitted
436 ItemKind::ExternCrate(orig_name) => {
437 let crate_id = self.crate_loader.process_extern_crate(item, &self.definitions);
439 self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
440 self.populate_module_if_necessary(module);
441 if injected_crate_name().map_or(false, |name| ident.name == name) {
442 self.injected_crate = Some(module);
445 let used = self.process_legacy_macro_imports(item, module, expansion);
447 (module, ty::Visibility::Public, sp, expansion).to_name_binding(self.arenas);
448 if ptr::eq(self.current_module, self.graph_root) {
449 self.extern_prelude.entry(ident.modern()).or_insert(ExternPreludeEntry {
450 extern_crate_item: None,
451 introduced_by_item: true,
452 }).extern_crate_item = Some(binding);
454 let directive = self.arenas.alloc_import_directive(ImportDirective {
458 imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
459 subclass: ImportDirectiveSubclass::ExternCrate {
463 root_span: item.span,
465 module_path: Vec::new(),
468 used: Cell::new(used),
469 is_uniform_paths_canary: false,
471 self.potentially_unused_imports.push(directive);
472 let imported_binding = self.import(binding, directive);
473 self.define(parent, ident, TypeNS, imported_binding);
476 ItemKind::GlobalAsm(..) => {}
478 ItemKind::Mod(..) if ident == keywords::Invalid.ident() => {} // Crate root
480 ItemKind::Mod(..) => {
481 let def_id = self.definitions.local_def_id(item.id);
482 let module_kind = ModuleKind::Def(Def::Mod(def_id), ident.name);
483 let module = self.arenas.alloc_module(ModuleData {
484 no_implicit_prelude: parent.no_implicit_prelude || {
485 attr::contains_name(&item.attrs, "no_implicit_prelude")
487 ..ModuleData::new(Some(parent), module_kind, def_id, expansion, item.span)
489 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
490 self.module_map.insert(def_id, module);
492 // Descend into the module.
493 self.current_module = module;
496 // Handled in `rustc_metadata::{native_libs,link_args}`
497 ItemKind::ForeignMod(..) => {}
499 // These items live in the value namespace.
500 ItemKind::Static(_, m, _) => {
501 let mutbl = m == Mutability::Mutable;
502 let def = Def::Static(self.definitions.local_def_id(item.id), mutbl);
503 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
505 ItemKind::Const(..) => {
506 let def = Def::Const(self.definitions.local_def_id(item.id));
507 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
509 ItemKind::Fn(..) => {
510 let def = Def::Fn(self.definitions.local_def_id(item.id));
511 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
513 // Functions introducing procedural macros reserve a slot
514 // in the macro namespace as well (see #52225).
515 if attr::contains_name(&item.attrs, "proc_macro") ||
516 attr::contains_name(&item.attrs, "proc_macro_attribute") {
517 let def = Def::Macro(def.def_id(), MacroKind::ProcMacroStub);
518 self.define(parent, ident, MacroNS, (def, vis, sp, expansion));
520 if let Some(attr) = attr::find_by_name(&item.attrs, "proc_macro_derive") {
521 if let Some(trait_attr) =
522 attr.meta_item_list().and_then(|list| list.get(0).cloned()) {
523 if let Some(ident) = trait_attr.name().map(Ident::with_empty_ctxt) {
524 let sp = trait_attr.span;
525 let def = Def::Macro(def.def_id(), MacroKind::ProcMacroStub);
526 self.define(parent, ident, MacroNS, (def, vis, sp, expansion));
532 // These items live in the type namespace.
533 ItemKind::Ty(..) => {
534 let def = Def::TyAlias(self.definitions.local_def_id(item.id));
535 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
538 ItemKind::Existential(_, _) => {
539 let def = Def::Existential(self.definitions.local_def_id(item.id));
540 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
543 ItemKind::Enum(ref enum_definition, _) => {
544 let def = Def::Enum(self.definitions.local_def_id(item.id));
545 let module_kind = ModuleKind::Def(def, ident.name);
546 let module = self.new_module(parent,
548 parent.normal_ancestor_id,
551 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
553 for variant in &(*enum_definition).variants {
554 self.build_reduced_graph_for_variant(variant, module, vis, expansion);
558 ItemKind::TraitAlias(..) => {
559 let def = Def::TraitAlias(self.definitions.local_def_id(item.id));
560 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
563 // These items live in both the type and value namespaces.
564 ItemKind::Struct(ref struct_def, _) => {
565 // Define a name in the type namespace.
566 let def_id = self.definitions.local_def_id(item.id);
567 let def = Def::Struct(def_id);
568 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
570 let mut ctor_vis = vis;
572 let has_non_exhaustive = attr::contains_name(&item.attrs, "non_exhaustive");
574 // If the structure is marked as non_exhaustive then lower the visibility
575 // to within the crate.
576 if has_non_exhaustive && vis == ty::Visibility::Public {
577 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
580 // Record field names for error reporting.
581 let field_names = struct_def.fields().iter().filter_map(|field| {
582 let field_vis = self.resolve_visibility(&field.vis);
583 if ctor_vis.is_at_least(field_vis, &*self) {
584 ctor_vis = field_vis;
586 field.ident.map(|ident| ident.name)
588 let item_def_id = self.definitions.local_def_id(item.id);
589 self.insert_field_names(item_def_id, field_names);
591 // If this is a tuple or unit struct, define a name
592 // in the value namespace as well.
593 if !struct_def.is_struct() {
594 let ctor_def = Def::StructCtor(self.definitions.local_def_id(struct_def.id()),
595 CtorKind::from_ast(struct_def));
596 self.define(parent, ident, ValueNS, (ctor_def, ctor_vis, sp, expansion));
597 self.struct_constructors.insert(def.def_id(), (ctor_def, ctor_vis));
601 ItemKind::Union(ref vdata, _) => {
602 let def = Def::Union(self.definitions.local_def_id(item.id));
603 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
605 // Record field names for error reporting.
606 let field_names = vdata.fields().iter().filter_map(|field| {
607 self.resolve_visibility(&field.vis);
608 field.ident.map(|ident| ident.name)
610 let item_def_id = self.definitions.local_def_id(item.id);
611 self.insert_field_names(item_def_id, field_names);
614 ItemKind::Impl(..) => {}
616 ItemKind::Trait(..) => {
617 let def_id = self.definitions.local_def_id(item.id);
619 // Add all the items within to a new module.
620 let module_kind = ModuleKind::Def(Def::Trait(def_id), ident.name);
621 let module = self.new_module(parent,
623 parent.normal_ancestor_id,
626 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
627 self.current_module = module;
630 ItemKind::MacroDef(..) | ItemKind::Mac(_) => unreachable!(),
634 // Constructs the reduced graph for one variant. Variants exist in the
635 // type and value namespaces.
636 fn build_reduced_graph_for_variant(&mut self,
641 let ident = variant.node.ident;
642 let def_id = self.definitions.local_def_id(variant.node.data.id());
644 // Define a name in the type namespace.
645 let def = Def::Variant(def_id);
646 self.define(parent, ident, TypeNS, (def, vis, variant.span, expansion));
648 // Define a constructor name in the value namespace.
649 // Braced variants, unlike structs, generate unusable names in
650 // value namespace, they are reserved for possible future use.
651 let ctor_kind = CtorKind::from_ast(&variant.node.data);
652 let ctor_def = Def::VariantCtor(def_id, ctor_kind);
654 self.define(parent, ident, ValueNS, (ctor_def, vis, variant.span, expansion));
657 /// Constructs the reduced graph for one foreign item.
658 fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem, expansion: Mark) {
659 let (def, ns) = match item.node {
660 ForeignItemKind::Fn(..) => {
661 (Def::Fn(self.definitions.local_def_id(item.id)), ValueNS)
663 ForeignItemKind::Static(_, m) => {
664 (Def::Static(self.definitions.local_def_id(item.id), m), ValueNS)
666 ForeignItemKind::Ty => {
667 (Def::ForeignTy(self.definitions.local_def_id(item.id)), TypeNS)
669 ForeignItemKind::Macro(_) => unreachable!(),
671 let parent = self.current_module;
672 let vis = self.resolve_visibility(&item.vis);
673 self.define(parent, item.ident, ns, (def, vis, item.span, expansion));
676 fn build_reduced_graph_for_block(&mut self, block: &Block, expansion: Mark) {
677 let parent = self.current_module;
678 if self.block_needs_anonymous_module(block) {
679 let module = self.new_module(parent,
680 ModuleKind::Block(block.id),
681 parent.normal_ancestor_id,
684 self.block_map.insert(block.id, module);
685 self.current_module = module; // Descend into the block.
689 /// Builds the reduced graph for a single item in an external crate.
690 fn build_reduced_graph_for_external_crate_def(&mut self, parent: Module<'a>, child: Export) {
691 let Export { ident, def, vis, span, .. } = child;
692 let def_id = def.def_id();
693 let expansion = Mark::root(); // FIXME(jseyfried) intercrate hygiene
695 Def::Mod(..) | Def::Enum(..) => {
696 let module = self.new_module(parent,
697 ModuleKind::Def(def, ident.name),
701 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
703 Def::Variant(..) | Def::TyAlias(..) | Def::ForeignTy(..) => {
704 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
706 Def::Fn(..) | Def::Static(..) | Def::Const(..) | Def::VariantCtor(..) => {
707 self.define(parent, ident, ValueNS, (def, vis, DUMMY_SP, expansion));
709 Def::StructCtor(..) => {
710 self.define(parent, ident, ValueNS, (def, vis, DUMMY_SP, expansion));
712 if let Some(struct_def_id) =
713 self.cstore.def_key(def_id).parent
714 .map(|index| DefId { krate: def_id.krate, index: index }) {
715 self.struct_constructors.insert(struct_def_id, (def, vis));
719 let module_kind = ModuleKind::Def(def, ident.name);
720 let module = self.new_module(parent,
722 parent.normal_ancestor_id,
725 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
727 for child in self.cstore.item_children_untracked(def_id, self.session) {
728 let ns = if let Def::AssociatedTy(..) = child.def { TypeNS } else { ValueNS };
729 self.define(module, child.ident, ns,
730 (child.def, ty::Visibility::Public, DUMMY_SP, expansion));
732 if self.cstore.associated_item_cloned_untracked(child.def.def_id())
733 .method_has_self_argument {
734 self.has_self.insert(child.def.def_id());
737 module.populated.set(true);
739 Def::Struct(..) | Def::Union(..) => {
740 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
742 // Record field names for error reporting.
743 let field_names = self.cstore.struct_field_names_untracked(def_id);
744 self.insert_field_names(def_id, field_names);
747 self.define(parent, ident, MacroNS, (def, vis, DUMMY_SP, expansion));
749 _ => bug!("unexpected definition: {:?}", def)
753 pub fn get_module(&mut self, def_id: DefId) -> Module<'a> {
754 if def_id.krate == LOCAL_CRATE {
755 return self.module_map[&def_id]
758 let macros_only = self.cstore.dep_kind_untracked(def_id.krate).macros_only();
759 if let Some(&module) = self.extern_module_map.get(&(def_id, macros_only)) {
763 let (name, parent) = if def_id.index == CRATE_DEF_INDEX {
764 (self.cstore.crate_name_untracked(def_id.krate).as_interned_str(), None)
766 let def_key = self.cstore.def_key(def_id);
767 (def_key.disambiguated_data.data.get_opt_name().unwrap(),
768 Some(self.get_module(DefId { index: def_key.parent.unwrap(), ..def_id })))
771 let kind = ModuleKind::Def(Def::Mod(def_id), name.as_symbol());
773 self.arenas.alloc_module(ModuleData::new(parent, kind, def_id, Mark::root(), DUMMY_SP));
774 self.extern_module_map.insert((def_id, macros_only), module);
778 pub fn macro_def_scope(&mut self, expansion: Mark) -> Module<'a> {
779 let def_id = self.macro_defs[&expansion];
780 if let Some(id) = self.definitions.as_local_node_id(def_id) {
781 self.local_macro_def_scopes[&id]
782 } else if def_id.krate == CrateNum::BuiltinMacros {
783 self.injected_crate.unwrap_or(self.graph_root)
785 let module_def_id = ty::DefIdTree::parent(&*self, def_id).unwrap();
786 self.get_module(module_def_id)
790 pub fn get_macro(&mut self, def: Def) -> Lrc<SyntaxExtension> {
791 let def_id = match def {
792 Def::Macro(def_id, ..) => def_id,
793 Def::NonMacroAttr(attr_kind) => return Lrc::new(SyntaxExtension::NonMacroAttr {
794 mark_used: attr_kind == NonMacroAttrKind::Tool,
796 _ => panic!("expected `Def::Macro` or `Def::NonMacroAttr`"),
798 if let Some(ext) = self.macro_map.get(&def_id) {
802 let macro_def = match self.cstore.load_macro_untracked(def_id, &self.session) {
803 LoadedMacro::MacroDef(macro_def) => macro_def,
804 LoadedMacro::ProcMacro(ext) => return ext,
807 let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
808 &self.session.features_untracked(),
810 self.cstore.crate_edition_untracked(def_id.krate)));
811 self.macro_map.insert(def_id, ext.clone());
815 /// Ensures that the reduced graph rooted at the given external module
816 /// is built, building it if it is not.
817 pub fn populate_module_if_necessary(&mut self, module: Module<'a>) {
818 if module.populated.get() { return }
819 let def_id = module.def_id().unwrap();
820 for child in self.cstore.item_children_untracked(def_id, self.session) {
821 self.build_reduced_graph_for_external_crate_def(module, child);
823 module.populated.set(true)
826 fn legacy_import_macro(&mut self,
828 binding: &'a NameBinding<'a>,
830 allow_shadowing: bool) {
831 if self.macro_use_prelude.insert(name, binding).is_some() && !allow_shadowing {
832 let msg = format!("`{}` is already in scope", name);
834 "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)";
835 self.session.struct_span_err(span, &msg).note(note).emit();
839 // This returns true if we should consider the underlying `extern crate` to be used.
840 fn process_legacy_macro_imports(&mut self, item: &Item, module: Module<'a>, expansion: Mark)
842 let allow_shadowing = expansion == Mark::root();
843 let legacy_imports = self.legacy_macro_imports(&item.attrs);
844 let used = legacy_imports != LegacyMacroImports::default();
846 // `#[macro_use]` is only allowed at the crate root.
847 if self.current_module.parent.is_some() && used {
848 span_err!(self.session, item.span, E0468,
849 "an `extern crate` loading macros must be at the crate root");
852 let (graph_root, arenas) = (self.graph_root, self.arenas);
853 let macro_use_directive = |span| arenas.alloc_import_directive(ImportDirective {
857 imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
858 subclass: ImportDirectiveSubclass::MacroUse,
861 module_path: Vec::new(),
862 vis: Cell::new(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))),
864 used: Cell::new(false),
865 is_uniform_paths_canary: false,
868 if let Some(span) = legacy_imports.import_all {
869 let directive = macro_use_directive(span);
870 self.potentially_unused_imports.push(directive);
871 module.for_each_child(|ident, ns, binding| if ns == MacroNS {
872 let imported_binding = self.import(binding, directive);
873 self.legacy_import_macro(ident.name, imported_binding, span, allow_shadowing);
876 for (name, span) in legacy_imports.imports {
877 let ident = Ident::with_empty_ctxt(name);
878 let result = self.resolve_ident_in_module(
879 ModuleOrUniformRoot::Module(module),
885 if let Ok(binding) = result {
886 let directive = macro_use_directive(span);
887 self.potentially_unused_imports.push(directive);
888 let imported_binding = self.import(binding, directive);
889 self.legacy_import_macro(name, imported_binding, span, allow_shadowing);
891 span_err!(self.session, span, E0469, "imported macro not found");
898 // does this attribute list contain "macro_use"?
899 fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool {
901 if attr.check_name("macro_escape") {
902 let msg = "macro_escape is a deprecated synonym for macro_use";
903 let mut err = self.session.struct_span_warn(attr.span, msg);
904 if let ast::AttrStyle::Inner = attr.style {
905 err.help("consider an outer attribute, #[macro_use] mod ...").emit();
909 } else if !attr.check_name("macro_use") {
914 self.session.span_err(attr.span, "arguments to macro_use are not allowed here");
922 fn legacy_macro_imports(&mut self, attrs: &[ast::Attribute]) -> LegacyMacroImports {
923 let mut imports = LegacyMacroImports::default();
925 if attr.check_name("macro_use") {
926 match attr.meta_item_list() {
927 Some(names) => for attr in names {
928 if let Some(word) = attr.word() {
929 imports.imports.push((word.name(), attr.span()));
931 span_err!(self.session, attr.span(), E0466, "bad macro import");
934 None => imports.import_all = Some(attr.span),
942 pub struct BuildReducedGraphVisitor<'a, 'b: 'a, 'c: 'b> {
943 pub resolver: &'a mut Resolver<'b, 'c>,
944 pub current_legacy_scope: LegacyScope<'b>,
948 impl<'a, 'b, 'cl> BuildReducedGraphVisitor<'a, 'b, 'cl> {
949 fn visit_invoc(&mut self, id: ast::NodeId) -> &'b InvocationData<'b> {
950 let mark = id.placeholder_to_mark();
951 self.resolver.current_module.unresolved_invocations.borrow_mut().insert(mark);
952 let invocation = self.resolver.invocations[&mark];
953 invocation.module.set(self.resolver.current_module);
954 invocation.parent_legacy_scope.set(self.current_legacy_scope);
955 invocation.output_legacy_scope.set(self.current_legacy_scope);
960 macro_rules! method {
961 ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
962 fn $visit(&mut self, node: &'a $ty) {
963 if let $invoc(..) = node.node {
964 self.visit_invoc(node.id);
966 visit::$walk(self, node);
972 impl<'a, 'b, 'cl> Visitor<'a> for BuildReducedGraphVisitor<'a, 'b, 'cl> {
973 method!(visit_impl_item: ast::ImplItem, ast::ImplItemKind::Macro, walk_impl_item);
974 method!(visit_expr: ast::Expr, ast::ExprKind::Mac, walk_expr);
975 method!(visit_pat: ast::Pat, ast::PatKind::Mac, walk_pat);
976 method!(visit_ty: ast::Ty, ast::TyKind::Mac, walk_ty);
978 fn visit_item(&mut self, item: &'a Item) {
979 let macro_use = match item.node {
980 ItemKind::MacroDef(..) => {
981 self.resolver.define_macro(item, self.expansion, &mut self.current_legacy_scope);
984 ItemKind::Mac(..) => {
985 self.current_legacy_scope = LegacyScope::Invocation(self.visit_invoc(item.id));
988 ItemKind::Mod(..) => self.resolver.contains_macro_use(&item.attrs),
992 let orig_current_module = self.resolver.current_module;
993 let orig_current_legacy_scope = self.current_legacy_scope;
994 self.resolver.build_reduced_graph_for_item(item, self.expansion);
995 visit::walk_item(self, item);
996 self.resolver.current_module = orig_current_module;
998 self.current_legacy_scope = orig_current_legacy_scope;
1002 fn visit_stmt(&mut self, stmt: &'a ast::Stmt) {
1003 if let ast::StmtKind::Mac(..) = stmt.node {
1004 self.current_legacy_scope = LegacyScope::Invocation(self.visit_invoc(stmt.id));
1006 visit::walk_stmt(self, stmt);
1010 fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
1011 if let ForeignItemKind::Macro(_) = foreign_item.node {
1012 self.visit_invoc(foreign_item.id);
1016 self.resolver.build_reduced_graph_for_foreign_item(foreign_item, self.expansion);
1017 visit::walk_foreign_item(self, foreign_item);
1020 fn visit_block(&mut self, block: &'a Block) {
1021 let orig_current_module = self.resolver.current_module;
1022 let orig_current_legacy_scope = self.current_legacy_scope;
1023 self.resolver.build_reduced_graph_for_block(block, self.expansion);
1024 visit::walk_block(self, block);
1025 self.resolver.current_module = orig_current_module;
1026 self.current_legacy_scope = orig_current_legacy_scope;
1029 fn visit_trait_item(&mut self, item: &'a TraitItem) {
1030 let parent = self.resolver.current_module;
1032 if let TraitItemKind::Macro(_) = item.node {
1033 self.visit_invoc(item.id);
1037 // Add the item to the trait info.
1038 let item_def_id = self.resolver.definitions.local_def_id(item.id);
1039 let (def, ns) = match item.node {
1040 TraitItemKind::Const(..) => (Def::AssociatedConst(item_def_id), ValueNS),
1041 TraitItemKind::Method(ref sig, _) => {
1042 if sig.decl.has_self() {
1043 self.resolver.has_self.insert(item_def_id);
1045 (Def::Method(item_def_id), ValueNS)
1047 TraitItemKind::Type(..) => (Def::AssociatedTy(item_def_id), TypeNS),
1048 TraitItemKind::Macro(_) => bug!(), // handled above
1051 let vis = ty::Visibility::Public;
1052 self.resolver.define(parent, item.ident, ns, (def, vis, item.span, self.expansion));
1054 self.resolver.current_module = parent.parent.unwrap(); // nearest normal ancestor
1055 visit::walk_trait_item(self, item);
1056 self.resolver.current_module = parent;
1059 fn visit_token(&mut self, t: Token) {
1060 if let Token::Interpolated(nt) = t {
1061 if let token::NtExpr(ref expr) = nt.0 {
1062 if let ast::ExprKind::Mac(..) = expr.node {
1063 self.visit_invoc(expr.id);
1069 fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1070 if !attr.is_sugared_doc && is_builtin_attr(attr) {
1071 let parent_scope = ParentScope {
1072 module: self.resolver.current_module.nearest_item_scope(),
1073 expansion: self.expansion,
1074 legacy: self.current_legacy_scope,
1075 // Let's hope discerning built-in attributes from derive helpers is not necessary
1076 derives: Vec::new(),
1078 parent_scope.module.builtin_attrs.borrow_mut().push((
1079 attr.path.segments[0].ident, parent_scope
1082 visit::walk_attribute(self, attr);