1 //! After we obtain a fresh AST fragment from a macro, code in this module helps to integrate
2 //! that fragment into the module structures that are already partially built.
4 //! Items from the fragment are placed into modules,
5 //! unexpanded macros in the fragment are visited and registered.
6 //! Imports are also considered items and placed into modules here, but not resolved yet.
8 use crate::macros::{LegacyBinding, LegacyScope};
9 use crate::resolve_imports::ImportDirective;
10 use crate::resolve_imports::ImportDirectiveSubclass::{self, GlobImport, SingleImport};
11 use crate::{Module, ModuleData, ModuleKind, NameBinding, NameBindingKind, Segment, ToNameBinding};
12 use crate::{ModuleOrUniformRoot, ParentScope, PerNS, Resolver, ResolverArenas, ExternPreludeEntry};
13 use crate::Namespace::{self, TypeNS, ValueNS, MacroNS};
14 use crate::{ResolutionError, Determinacy, PathResult, CrateLint};
17 use rustc::hir::def::{self, *};
18 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
19 use rustc::hir::map::DefCollector;
21 use rustc::middle::cstore::CrateStore;
22 use rustc_metadata::cstore::LoadedMacro;
26 use rustc_data_structures::sync::Lrc;
28 use errors::Applicability;
30 use syntax::ast::{Name, Ident};
33 use syntax::ast::{self, Block, ForeignItem, ForeignItemKind, Item, ItemKind, NodeId};
34 use syntax::ast::{MetaItemKind, StmtKind, TraitItem, TraitItemKind, Variant};
35 use syntax::ext::base::{MacroKind, SyntaxExtension};
36 use syntax::ext::expand::AstFragment;
37 use syntax::ext::hygiene::ExpnId;
38 use syntax::feature_gate::is_builtin_attr;
39 use syntax::parse::token::{self, Token};
40 use syntax::{span_err, struct_span_err};
41 use syntax::symbol::{kw, sym};
42 use syntax::visit::{self, Visitor};
44 use syntax_pos::{Span, DUMMY_SP};
48 type Res = def::Res<NodeId>;
50 impl<'a> ToNameBinding<'a> for (Module<'a>, ty::Visibility, Span, ExpnId) {
51 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
52 arenas.alloc_name_binding(NameBinding {
53 kind: NameBindingKind::Module(self.0),
62 impl<'a> ToNameBinding<'a> for (Res, ty::Visibility, Span, ExpnId) {
63 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
64 arenas.alloc_name_binding(NameBinding {
65 kind: NameBindingKind::Res(self.0, false),
76 impl<'a> ToNameBinding<'a> for (Res, ty::Visibility, Span, ExpnId, IsMacroExport) {
77 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
78 arenas.alloc_name_binding(NameBinding {
79 kind: NameBindingKind::Res(self.0, true),
88 impl<'a> Resolver<'a> {
89 /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
90 /// otherwise, reports an error.
91 crate fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T)
92 where T: ToNameBinding<'a>,
94 let binding = def.to_name_binding(self.arenas);
95 if let Err(old_binding) = self.try_define(parent, ident, ns, binding) {
96 self.report_conflict(parent, ident, ns, old_binding, &binding);
100 crate fn get_module(&mut self, def_id: DefId) -> Module<'a> {
101 if def_id.krate == LOCAL_CRATE {
102 return self.module_map[&def_id]
105 let macros_only = self.cstore.dep_kind_untracked(def_id.krate).macros_only();
106 if let Some(&module) = self.extern_module_map.get(&(def_id, macros_only)) {
110 let (name, parent) = if def_id.index == CRATE_DEF_INDEX {
111 (self.cstore.crate_name_untracked(def_id.krate).as_interned_str(), None)
113 let def_key = self.cstore.def_key(def_id);
114 (def_key.disambiguated_data.data.get_opt_name().unwrap(),
115 Some(self.get_module(DefId { index: def_key.parent.unwrap(), ..def_id })))
118 let kind = ModuleKind::Def(DefKind::Mod, def_id, name.as_symbol());
119 let module = self.arenas.alloc_module(ModuleData::new(
120 parent, kind, def_id, ExpnId::root(), DUMMY_SP
122 self.extern_module_map.insert((def_id, macros_only), module);
126 crate fn macro_def_scope(&mut self, expn_id: ExpnId) -> Module<'a> {
127 let def_id = match self.macro_defs.get(&expn_id) {
128 Some(def_id) => *def_id,
129 None => return self.graph_root,
131 if let Some(id) = self.definitions.as_local_node_id(def_id) {
132 self.local_macro_def_scopes[&id]
134 let module_def_id = ty::DefIdTree::parent(&*self, def_id).unwrap();
135 self.get_module(module_def_id)
139 crate fn get_macro(&mut self, res: Res) -> Option<Lrc<SyntaxExtension>> {
141 Res::Def(DefKind::Macro(..), def_id) => self.get_macro_by_def_id(def_id),
142 Res::NonMacroAttr(attr_kind) =>
143 Some(self.non_macro_attr(attr_kind == NonMacroAttrKind::Tool)),
148 fn get_macro_by_def_id(&mut self, def_id: DefId) -> Option<Lrc<SyntaxExtension>> {
149 if let Some(ext) = self.macro_map.get(&def_id) {
150 return Some(ext.clone());
153 let macro_def = match self.cstore.load_macro_untracked(def_id, &self.session) {
154 LoadedMacro::MacroDef(macro_def) => macro_def,
155 LoadedMacro::ProcMacro(ext) => return Some(ext),
158 let ext = self.compile_macro(¯o_def, self.cstore.crate_edition_untracked(def_id.krate));
159 self.macro_map.insert(def_id, ext.clone());
163 // FIXME: `extra_placeholders` should be included into the `fragment` as regular placeholders.
164 crate fn build_reduced_graph(
166 fragment: &AstFragment,
167 extra_placeholders: &[NodeId],
168 parent_scope: ParentScope<'a>,
169 ) -> LegacyScope<'a> {
170 let mut def_collector = DefCollector::new(&mut self.definitions, parent_scope.expansion);
171 fragment.visit_with(&mut def_collector);
172 for placeholder in extra_placeholders {
173 def_collector.visit_macro_invoc(*placeholder);
176 let mut visitor = BuildReducedGraphVisitor { r: self, parent_scope };
177 fragment.visit_with(&mut visitor);
178 for placeholder in extra_placeholders {
179 visitor.parent_scope.legacy = visitor.visit_invoc(*placeholder);
182 visitor.parent_scope.legacy
185 crate fn build_reduced_graph_external(&mut self, module: Module<'a>) {
186 let def_id = module.def_id().expect("unpopulated module without a def-id");
187 for child in self.cstore.item_children_untracked(def_id, self.session) {
188 let child = child.map_id(|_| panic!("unexpected id"));
189 BuildReducedGraphVisitor { r: self, parent_scope: ParentScope::module(module) }
190 .build_reduced_graph_for_external_crate_res(child);
195 struct BuildReducedGraphVisitor<'a, 'b> {
196 r: &'b mut Resolver<'a>,
197 parent_scope: ParentScope<'a>,
200 impl<'a> AsMut<Resolver<'a>> for BuildReducedGraphVisitor<'a, '_> {
201 fn as_mut(&mut self) -> &mut Resolver<'a> { self.r }
204 impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
205 fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
206 let parent_scope = &self.parent_scope;
208 ast::VisibilityKind::Public => ty::Visibility::Public,
209 ast::VisibilityKind::Crate(..) => {
210 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
212 ast::VisibilityKind::Inherited => {
213 ty::Visibility::Restricted(parent_scope.module.normal_ancestor_id)
215 ast::VisibilityKind::Restricted { ref path, id, .. } => {
216 // For visibilities we are not ready to provide correct implementation of "uniform
217 // paths" right now, so on 2018 edition we only allow module-relative paths for now.
218 // On 2015 edition visibilities are resolved as crate-relative by default,
219 // so we are prepending a root segment if necessary.
220 let ident = path.segments.get(0).expect("empty path in visibility").ident;
221 let crate_root = if ident.is_path_segment_keyword() {
223 } else if ident.span.rust_2018() {
224 let msg = "relative paths are not supported in visibilities on 2018 edition";
225 self.r.session.struct_span_err(ident.span, msg)
229 format!("crate::{}", path),
230 Applicability::MaybeIncorrect,
233 return ty::Visibility::Public;
235 let ctxt = ident.span.ctxt();
236 Some(Segment::from_ident(Ident::new(
237 kw::PathRoot, path.span.shrink_to_lo().with_ctxt(ctxt)
241 let segments = crate_root.into_iter()
242 .chain(path.segments.iter().map(|seg| seg.into())).collect::<Vec<_>>();
243 let expected_found_error = |this: &Self, res: Res| {
244 let path_str = Segment::names_to_string(&segments);
245 struct_span_err!(this.r.session, path.span, E0577,
246 "expected module, found {} `{}`", res.descr(), path_str)
247 .span_label(path.span, "not a module").emit();
249 match self.r.resolve_path(
255 CrateLint::SimplePath(id),
257 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
258 let res = module.res().expect("visibility resolved to unnamed block");
259 self.r.record_partial_res(id, PartialRes::new(res));
260 if module.is_normal() {
262 ty::Visibility::Public
264 let vis = ty::Visibility::Restricted(res.def_id());
265 if self.r.is_accessible_from(vis, parent_scope.module) {
269 "visibilities can only be restricted to ancestor modules";
270 self.r.session.span_err(path.span, msg);
271 ty::Visibility::Public
275 expected_found_error(self, res);
276 ty::Visibility::Public
279 PathResult::Module(..) => {
280 self.r.session.span_err(path.span, "visibility must resolve to a module");
281 ty::Visibility::Public
283 PathResult::NonModule(partial_res) => {
284 expected_found_error(self, partial_res.base_res());
285 ty::Visibility::Public
287 PathResult::Failed { span, label, suggestion, .. } => {
289 span, ResolutionError::FailedToResolve { label, suggestion }
291 ty::Visibility::Public
293 PathResult::Indeterminate => {
294 span_err!(self.r.session, path.span, E0578,
295 "cannot determine resolution for the visibility");
296 ty::Visibility::Public
303 fn insert_field_names(&mut self, def_id: DefId, field_names: Vec<Name>) {
304 if !field_names.is_empty() {
305 self.r.field_names.insert(def_id, field_names);
309 fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
310 // If any statements are items, we need to create an anonymous module
311 block.stmts.iter().any(|statement| match statement.node {
312 StmtKind::Item(_) | StmtKind::Mac(_) => true,
317 // Add an import directive to the current module.
318 fn add_import_directive(
320 module_path: Vec<Segment>,
321 subclass: ImportDirectiveSubclass<'a>,
329 let current_module = self.parent_scope.module;
330 let directive = self.r.arenas.alloc_import_directive(ImportDirective {
331 parent_scope: self.parent_scope,
333 imported_module: Cell::new(None),
338 use_span_with_attributes: item.span_with_attributes(),
339 has_attributes: !item.attrs.is_empty(),
343 used: Cell::new(false),
346 debug!("add_import_directive({:?})", directive);
348 self.r.indeterminate_imports.push(directive);
349 match directive.subclass {
350 SingleImport { target, type_ns_only, .. } => {
351 self.r.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
352 let mut resolution = this.resolution(current_module, target, ns).borrow_mut();
353 resolution.add_single_import(directive);
356 // We don't add prelude imports to the globs since they only affect lexical scopes,
357 // which are not relevant to import resolution.
358 GlobImport { is_prelude: true, .. } => {}
359 GlobImport { .. } => current_module.globs.borrow_mut().push(directive),
364 fn build_reduced_graph_for_use_tree(
366 // This particular use tree
367 use_tree: &ast::UseTree,
369 parent_prefix: &[Segment],
371 // The whole `use` item
376 debug!("build_reduced_graph_for_use_tree(parent_prefix={:?}, use_tree={:?}, nested={})",
377 parent_prefix, use_tree, nested);
379 let mut prefix_iter = parent_prefix.iter().cloned()
380 .chain(use_tree.prefix.segments.iter().map(|seg| seg.into())).peekable();
382 // On 2015 edition imports are resolved as crate-relative by default,
383 // so prefixes are prepended with crate root segment if necessary.
384 // The root is prepended lazily, when the first non-empty prefix or terminating glob
385 // appears, so imports in braced groups can have roots prepended independently.
386 let is_glob = if let ast::UseTreeKind::Glob = use_tree.kind { true } else { false };
387 let crate_root = match prefix_iter.peek() {
388 Some(seg) if !seg.ident.is_path_segment_keyword() && seg.ident.span.rust_2015() => {
389 Some(seg.ident.span.ctxt())
391 None if is_glob && use_tree.span.rust_2015() => {
392 Some(use_tree.span.ctxt())
395 }.map(|ctxt| Segment::from_ident(Ident::new(
396 kw::PathRoot, use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt)
399 let prefix = crate_root.into_iter().chain(prefix_iter).collect::<Vec<_>>();
400 debug!("build_reduced_graph_for_use_tree: prefix={:?}", prefix);
402 let empty_for_self = |prefix: &[Segment]| {
404 prefix.len() == 1 && prefix[0].ident.name == kw::PathRoot
406 match use_tree.kind {
407 ast::UseTreeKind::Simple(rename, ..) => {
408 let mut ident = use_tree.ident().gensym_if_underscore();
409 let mut module_path = prefix;
410 let mut source = module_path.pop().unwrap();
411 let mut type_ns_only = false;
414 // Correctly handle `self`
415 if source.ident.name == kw::SelfLower {
418 if empty_for_self(&module_path) {
422 SelfImportOnlyInImportListWithNonEmptyPrefix
427 // Replace `use foo::self;` with `use foo;`
428 source = module_path.pop().unwrap();
429 if rename.is_none() {
430 ident = source.ident;
435 if source.ident.name == kw::SelfLower {
437 use_tree.span, ResolutionError::SelfImportsOnlyAllowedWithin
441 // Disallow `use $crate;`
442 if source.ident.name == kw::DollarCrate && module_path.is_empty() {
443 let crate_root = self.r.resolve_crate_root(source.ident);
444 let crate_name = match crate_root.kind {
445 ModuleKind::Def(.., name) => name,
446 ModuleKind::Block(..) => unreachable!(),
448 // HACK(eddyb) unclear how good this is, but keeping `$crate`
449 // in `source` breaks `src/test/compile-fail/import-crate-var.rs`,
450 // while the current crate doesn't have a valid `crate_name`.
451 if crate_name != kw::Invalid {
452 // `crate_name` should not be interpreted as relative.
453 module_path.push(Segment {
456 span: source.ident.span,
458 id: Some(self.r.session.next_node_id()),
460 source.ident.name = crate_name;
462 if rename.is_none() {
463 ident.name = crate_name;
466 self.r.session.struct_span_warn(item.span, "`$crate` may not be imported")
467 .note("`use $crate;` was erroneously allowed and \
468 will become a hard error in a future release")
473 if ident.name == kw::Crate {
474 self.r.session.span_err(ident.span,
475 "crate root imports need to be explicitly named: \
476 `use crate as name;`");
479 let subclass = SingleImport {
480 source: source.ident,
482 source_bindings: PerNS {
483 type_ns: Cell::new(Err(Determinacy::Undetermined)),
484 value_ns: Cell::new(Err(Determinacy::Undetermined)),
485 macro_ns: Cell::new(Err(Determinacy::Undetermined)),
487 target_bindings: PerNS {
488 type_ns: Cell::new(None),
489 value_ns: Cell::new(None),
490 macro_ns: Cell::new(None),
495 self.add_import_directive(
506 ast::UseTreeKind::Glob => {
507 let subclass = GlobImport {
508 is_prelude: attr::contains_name(&item.attrs, sym::prelude_import),
509 max_vis: Cell::new(ty::Visibility::Invisible),
511 self.add_import_directive(
522 ast::UseTreeKind::Nested(ref items) => {
523 // Ensure there is at most one `self` in the list
524 let self_spans = items.iter().filter_map(|&(ref use_tree, _)| {
525 if let ast::UseTreeKind::Simple(..) = use_tree.kind {
526 if use_tree.ident().name == kw::SelfLower {
527 return Some(use_tree.span);
532 }).collect::<Vec<_>>();
533 if self_spans.len() > 1 {
534 let mut e = self.r.into_struct_error(
536 ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
538 for other_span in self_spans.iter().skip(1) {
539 e.span_label(*other_span, "another `self` import appears here");
545 for &(ref tree, id) in items {
546 self.build_reduced_graph_for_use_tree(
547 // This particular use tree
548 tree, id, &prefix, true,
549 // The whole `use` item
550 item, vis, root_span,
554 // Empty groups `a::b::{}` are turned into synthetic `self` imports
555 // `a::b::c::{self as _}`, so that their prefixes are correctly
556 // resolved and checked for privacy/stability/etc.
557 if items.is_empty() && !empty_for_self(&prefix) {
558 let new_span = prefix[prefix.len() - 1].ident.span;
559 let tree = ast::UseTree {
560 prefix: ast::Path::from_ident(
561 Ident::new(kw::SelfLower, new_span)
563 kind: ast::UseTreeKind::Simple(
564 Some(Ident::new(kw::Underscore, new_span)),
570 self.build_reduced_graph_for_use_tree(
571 // This particular use tree
572 &tree, id, &prefix, true,
573 // The whole `use` item
574 item, ty::Visibility::Invisible, root_span,
581 /// Constructs the reduced graph for one item.
582 fn build_reduced_graph_for_item(&mut self, item: &Item) {
583 let parent_scope = &self.parent_scope;
584 let parent = parent_scope.module;
585 let expansion = parent_scope.expansion;
586 let ident = item.ident.gensym_if_underscore();
588 let vis = self.resolve_visibility(&item.vis);
591 ItemKind::Use(ref use_tree) => {
592 self.build_reduced_graph_for_use_tree(
593 // This particular use tree
594 use_tree, item.id, &[], false,
595 // The whole `use` item
596 item, vis, use_tree.span,
600 ItemKind::ExternCrate(orig_name) => {
601 let module = if orig_name.is_none() && ident.name == kw::SelfLower {
603 .struct_span_err(item.span, "`extern crate self;` requires renaming")
607 "extern crate self as name;".into(),
608 Applicability::HasPlaceholders,
612 } else if orig_name == Some(kw::SelfLower) {
615 let crate_id = self.r.crate_loader.process_extern_crate(
616 item, &self.r.definitions
618 self.r.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX })
621 let used = self.process_legacy_macro_imports(item, module);
623 (module, ty::Visibility::Public, sp, expansion).to_name_binding(self.r.arenas);
624 let directive = self.r.arenas.alloc_import_directive(ImportDirective {
627 parent_scope: self.parent_scope,
628 imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
629 subclass: ImportDirectiveSubclass::ExternCrate {
633 has_attributes: !item.attrs.is_empty(),
634 use_span_with_attributes: item.span_with_attributes(),
636 root_span: item.span,
638 module_path: Vec::new(),
640 used: Cell::new(used),
642 self.r.potentially_unused_imports.push(directive);
643 let imported_binding = self.r.import(binding, directive);
644 if ptr::eq(parent, self.r.graph_root) {
645 if let Some(entry) = self.r.extern_prelude.get(&ident.modern()) {
646 if expansion != ExpnId::root() && orig_name.is_some() &&
647 entry.extern_crate_item.is_none() {
648 let msg = "macro-expanded `extern crate` items cannot \
649 shadow names passed with `--extern`";
650 self.r.session.span_err(item.span, msg);
653 let entry = self.r.extern_prelude.entry(ident.modern())
654 .or_insert(ExternPreludeEntry {
655 extern_crate_item: None,
656 introduced_by_item: true,
658 entry.extern_crate_item = Some(imported_binding);
659 if orig_name.is_some() {
660 entry.introduced_by_item = true;
663 self.r.define(parent, ident, TypeNS, imported_binding);
666 ItemKind::GlobalAsm(..) => {}
668 ItemKind::Mod(..) if ident.name == kw::Invalid => {} // Crate root
670 ItemKind::Mod(..) => {
671 let def_id = self.r.definitions.local_def_id(item.id);
672 let module_kind = ModuleKind::Def(DefKind::Mod, def_id, ident.name);
673 let module = self.r.arenas.alloc_module(ModuleData {
674 no_implicit_prelude: parent.no_implicit_prelude || {
675 attr::contains_name(&item.attrs, sym::no_implicit_prelude)
677 ..ModuleData::new(Some(parent), module_kind, def_id, expansion, item.span)
679 self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion));
680 self.r.module_map.insert(def_id, module);
682 // Descend into the module.
683 self.parent_scope.module = module;
686 // Handled in `rustc_metadata::{native_libs,link_args}`
687 ItemKind::ForeignMod(..) => {}
689 // These items live in the value namespace.
690 ItemKind::Static(..) => {
691 let res = Res::Def(DefKind::Static, self.r.definitions.local_def_id(item.id));
692 self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion));
694 ItemKind::Const(..) => {
695 let res = Res::Def(DefKind::Const, self.r.definitions.local_def_id(item.id));
696 self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion));
698 ItemKind::Fn(..) => {
699 let res = Res::Def(DefKind::Fn, self.r.definitions.local_def_id(item.id));
700 self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion));
702 // Functions introducing procedural macros reserve a slot
703 // in the macro namespace as well (see #52225).
704 self.define_macro(item);
707 // These items live in the type namespace.
708 ItemKind::TyAlias(..) => {
709 let res = Res::Def(DefKind::TyAlias, self.r.definitions.local_def_id(item.id));
710 self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion));
713 ItemKind::OpaqueTy(_, _) => {
714 let res = Res::Def(DefKind::OpaqueTy, self.r.definitions.local_def_id(item.id));
715 self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion));
718 ItemKind::Enum(ref enum_definition, _) => {
719 let module_kind = ModuleKind::Def(
721 self.r.definitions.local_def_id(item.id),
724 let module = self.r.new_module(parent,
726 parent.normal_ancestor_id,
729 self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion));
731 for variant in &(*enum_definition).variants {
732 self.build_reduced_graph_for_variant(variant, module, vis);
736 ItemKind::TraitAlias(..) => {
737 let res = Res::Def(DefKind::TraitAlias, self.r.definitions.local_def_id(item.id));
738 self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion));
741 // These items live in both the type and value namespaces.
742 ItemKind::Struct(ref struct_def, _) => {
743 // Define a name in the type namespace.
744 let def_id = self.r.definitions.local_def_id(item.id);
745 let res = Res::Def(DefKind::Struct, def_id);
746 self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion));
748 let mut ctor_vis = vis;
750 let has_non_exhaustive = attr::contains_name(&item.attrs, sym::non_exhaustive);
752 // If the structure is marked as non_exhaustive then lower the visibility
753 // to within the crate.
754 if has_non_exhaustive && vis == ty::Visibility::Public {
755 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
758 // Record field names for error reporting.
759 let field_names = struct_def.fields().iter().filter_map(|field| {
760 let field_vis = self.resolve_visibility(&field.vis);
761 if ctor_vis.is_at_least(field_vis, &*self.r) {
762 ctor_vis = field_vis;
764 field.ident.map(|ident| ident.name)
766 let item_def_id = self.r.definitions.local_def_id(item.id);
767 self.insert_field_names(item_def_id, field_names);
769 // If this is a tuple or unit struct, define a name
770 // in the value namespace as well.
771 if let Some(ctor_node_id) = struct_def.ctor_id() {
772 let ctor_res = Res::Def(
773 DefKind::Ctor(CtorOf::Struct, CtorKind::from_ast(struct_def)),
774 self.r.definitions.local_def_id(ctor_node_id),
776 self.r.define(parent, ident, ValueNS, (ctor_res, ctor_vis, sp, expansion));
777 self.r.struct_constructors.insert(res.def_id(), (ctor_res, ctor_vis));
781 ItemKind::Union(ref vdata, _) => {
782 let res = Res::Def(DefKind::Union, self.r.definitions.local_def_id(item.id));
783 self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion));
785 // Record field names for error reporting.
786 let field_names = vdata.fields().iter().filter_map(|field| {
787 self.resolve_visibility(&field.vis);
788 field.ident.map(|ident| ident.name)
790 let item_def_id = self.r.definitions.local_def_id(item.id);
791 self.insert_field_names(item_def_id, field_names);
794 ItemKind::Impl(.., ref impl_items) => {
795 for impl_item in impl_items {
796 self.resolve_visibility(&impl_item.vis);
800 ItemKind::Trait(..) => {
801 let def_id = self.r.definitions.local_def_id(item.id);
803 // Add all the items within to a new module.
804 let module_kind = ModuleKind::Def(DefKind::Trait, def_id, ident.name);
805 let module = self.r.new_module(parent,
807 parent.normal_ancestor_id,
810 self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion));
811 self.parent_scope.module = module;
814 ItemKind::MacroDef(..) | ItemKind::Mac(_) => unreachable!(),
818 // Constructs the reduced graph for one variant. Variants exist in the
819 // type and value namespaces.
820 fn build_reduced_graph_for_variant(&mut self,
823 vis: ty::Visibility) {
824 let expn_id = self.parent_scope.expansion;
825 let ident = variant.ident;
827 // Define a name in the type namespace.
828 let def_id = self.r.definitions.local_def_id(variant.id);
829 let res = Res::Def(DefKind::Variant, def_id);
830 self.r.define(parent, ident, TypeNS, (res, vis, variant.span, expn_id));
832 // If the variant is marked as non_exhaustive then lower the visibility to within the
834 let mut ctor_vis = vis;
835 let has_non_exhaustive = attr::contains_name(&variant.attrs, sym::non_exhaustive);
836 if has_non_exhaustive && vis == ty::Visibility::Public {
837 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
840 // Define a constructor name in the value namespace.
841 // Braced variants, unlike structs, generate unusable names in
842 // value namespace, they are reserved for possible future use.
843 // It's ok to use the variant's id as a ctor id since an
844 // error will be reported on any use of such resolution anyway.
845 let ctor_node_id = variant.data.ctor_id().unwrap_or(variant.id);
846 let ctor_def_id = self.r.definitions.local_def_id(ctor_node_id);
847 let ctor_kind = CtorKind::from_ast(&variant.data);
848 let ctor_res = Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id);
849 self.r.define(parent, ident, ValueNS, (ctor_res, ctor_vis, variant.span, expn_id));
852 /// Constructs the reduced graph for one foreign item.
853 fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem) {
854 let (res, ns) = match item.node {
855 ForeignItemKind::Fn(..) => {
856 (Res::Def(DefKind::Fn, self.r.definitions.local_def_id(item.id)), ValueNS)
858 ForeignItemKind::Static(..) => {
859 (Res::Def(DefKind::Static, self.r.definitions.local_def_id(item.id)), ValueNS)
861 ForeignItemKind::Ty => {
862 (Res::Def(DefKind::ForeignTy, self.r.definitions.local_def_id(item.id)), TypeNS)
864 ForeignItemKind::Macro(_) => unreachable!(),
866 let parent = self.parent_scope.module;
867 let expansion = self.parent_scope.expansion;
868 let vis = self.resolve_visibility(&item.vis);
869 self.r.define(parent, item.ident, ns, (res, vis, item.span, expansion));
872 fn build_reduced_graph_for_block(&mut self, block: &Block) {
873 let parent = self.parent_scope.module;
874 let expansion = self.parent_scope.expansion;
875 if self.block_needs_anonymous_module(block) {
876 let module = self.r.new_module(parent,
877 ModuleKind::Block(block.id),
878 parent.normal_ancestor_id,
881 self.r.block_map.insert(block.id, module);
882 self.parent_scope.module = module; // Descend into the block.
886 /// Builds the reduced graph for a single item in an external crate.
887 fn build_reduced_graph_for_external_crate_res(&mut self, child: Export<NodeId>) {
888 let parent = self.parent_scope.module;
889 let Export { ident, res, vis, span } = child;
890 // FIXME: We shouldn't create the gensym here, it should come from metadata,
891 // but metadata cannot encode gensyms currently, so we create it here.
892 // This is only a guess, two equivalent idents may incorrectly get different gensyms here.
893 let ident = ident.gensym_if_underscore();
894 let expansion = ExpnId::root(); // FIXME(jseyfried) intercrate hygiene
895 // Record primary definitions.
897 Res::Def(kind @ DefKind::Mod, def_id)
898 | Res::Def(kind @ DefKind::Enum, def_id)
899 | Res::Def(kind @ DefKind::Trait, def_id) => {
900 let module = self.r.new_module(parent,
901 ModuleKind::Def(kind, def_id, ident.name),
905 self.r.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
907 Res::Def(DefKind::Struct, _)
908 | Res::Def(DefKind::Union, _)
909 | Res::Def(DefKind::Variant, _)
910 | Res::Def(DefKind::TyAlias, _)
911 | Res::Def(DefKind::ForeignTy, _)
912 | Res::Def(DefKind::OpaqueTy, _)
913 | Res::Def(DefKind::TraitAlias, _)
914 | Res::Def(DefKind::AssocTy, _)
915 | Res::Def(DefKind::AssocOpaqueTy, _)
918 self.r.define(parent, ident, TypeNS, (res, vis, DUMMY_SP, expansion)),
919 Res::Def(DefKind::Fn, _)
920 | Res::Def(DefKind::Method, _)
921 | Res::Def(DefKind::Static, _)
922 | Res::Def(DefKind::Const, _)
923 | Res::Def(DefKind::AssocConst, _)
924 | Res::Def(DefKind::Ctor(..), _) =>
925 self.r.define(parent, ident, ValueNS, (res, vis, DUMMY_SP, expansion)),
926 Res::Def(DefKind::Macro(..), _)
927 | Res::NonMacroAttr(..) =>
928 self.r.define(parent, ident, MacroNS, (res, vis, DUMMY_SP, expansion)),
929 Res::Def(DefKind::TyParam, _) | Res::Def(DefKind::ConstParam, _)
930 | Res::Local(..) | Res::SelfTy(..) | Res::SelfCtor(..) | Res::Err =>
931 bug!("unexpected resolution: {:?}", res)
933 // Record some extra data for better diagnostics.
935 Res::Def(DefKind::Struct, def_id) | Res::Def(DefKind::Union, def_id) => {
936 let field_names = self.r.cstore.struct_field_names_untracked(def_id);
937 self.insert_field_names(def_id, field_names);
939 Res::Def(DefKind::Method, def_id) => {
940 if self.r.cstore.associated_item_cloned_untracked(def_id).method_has_self_argument {
941 self.r.has_self.insert(def_id);
944 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), def_id) => {
945 let parent = self.r.cstore.def_key(def_id).parent;
946 if let Some(struct_def_id) = parent.map(|index| DefId { index, ..def_id }) {
947 self.r.struct_constructors.insert(struct_def_id, (res, vis));
954 fn legacy_import_macro(&mut self,
956 binding: &'a NameBinding<'a>,
958 allow_shadowing: bool) {
959 if self.r.macro_use_prelude.insert(name, binding).is_some() && !allow_shadowing {
960 let msg = format!("`{}` is already in scope", name);
962 "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)";
963 self.r.session.struct_span_err(span, &msg).note(note).emit();
967 /// Returns `true` if we should consider the underlying `extern crate` to be used.
968 fn process_legacy_macro_imports(&mut self, item: &Item, module: Module<'a>) -> bool {
969 let mut import_all = None;
970 let mut single_imports = Vec::new();
971 for attr in &item.attrs {
972 if attr.check_name(sym::macro_use) {
973 if self.parent_scope.module.parent.is_some() {
974 span_err!(self.r.session, item.span, E0468,
975 "an `extern crate` loading macros must be at the crate root");
977 if let ItemKind::ExternCrate(Some(orig_name)) = item.node {
978 if orig_name == kw::SelfLower {
979 self.r.session.span_err(attr.span,
980 "`macro_use` is not supported on `extern crate self`");
983 let ill_formed = |span| span_err!(self.r.session, span, E0466, "bad macro import");
985 Some(meta) => match meta.node {
986 MetaItemKind::Word => {
987 import_all = Some(meta.span);
990 MetaItemKind::List(nested_metas) => for nested_meta in nested_metas {
991 match nested_meta.ident() {
992 Some(ident) if nested_meta.is_word() => single_imports.push(ident),
993 _ => ill_formed(nested_meta.span()),
996 MetaItemKind::NameValue(..) => ill_formed(meta.span),
998 None => ill_formed(attr.span),
1003 let macro_use_directive =
1004 |this: &Self, span| this.r.arenas.alloc_import_directive(ImportDirective {
1007 parent_scope: this.parent_scope,
1008 imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
1009 subclass: ImportDirectiveSubclass::MacroUse,
1010 use_span_with_attributes: item.span_with_attributes(),
1011 has_attributes: !item.attrs.is_empty(),
1012 use_span: item.span,
1015 module_path: Vec::new(),
1016 vis: Cell::new(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))),
1017 used: Cell::new(false),
1020 let allow_shadowing = self.parent_scope.expansion == ExpnId::root();
1021 if let Some(span) = import_all {
1022 let directive = macro_use_directive(self, span);
1023 self.r.potentially_unused_imports.push(directive);
1024 module.for_each_child(self, |this, ident, ns, binding| if ns == MacroNS {
1025 let imported_binding = this.r.import(binding, directive);
1026 this.legacy_import_macro(ident.name, imported_binding, span, allow_shadowing);
1029 for ident in single_imports.iter().cloned() {
1030 let result = self.r.resolve_ident_in_module(
1031 ModuleOrUniformRoot::Module(module),
1038 if let Ok(binding) = result {
1039 let directive = macro_use_directive(self, ident.span);
1040 self.r.potentially_unused_imports.push(directive);
1041 let imported_binding = self.r.import(binding, directive);
1042 self.legacy_import_macro(ident.name, imported_binding,
1043 ident.span, allow_shadowing);
1045 span_err!(self.r.session, ident.span, E0469, "imported macro not found");
1049 import_all.is_some() || !single_imports.is_empty()
1052 /// Returns `true` if this attribute list contains `macro_use`.
1053 fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool {
1055 if attr.check_name(sym::macro_escape) {
1056 let msg = "macro_escape is a deprecated synonym for macro_use";
1057 let mut err = self.r.session.struct_span_warn(attr.span, msg);
1058 if let ast::AttrStyle::Inner = attr.style {
1059 err.help("consider an outer attribute, `#[macro_use]` mod ...").emit();
1063 } else if !attr.check_name(sym::macro_use) {
1067 if !attr.is_word() {
1068 self.r.session.span_err(attr.span, "arguments to macro_use are not allowed here");
1076 fn visit_invoc(&mut self, id: NodeId) -> LegacyScope<'a> {
1077 let invoc_id = id.placeholder_to_expn_id();
1079 self.parent_scope.module.unexpanded_invocations.borrow_mut().insert(invoc_id);
1081 let old_parent_scope = self.r.invocation_parent_scopes.insert(invoc_id, self.parent_scope);
1082 assert!(old_parent_scope.is_none(), "invocation data is reset for an invocation");
1084 LegacyScope::Invocation(invoc_id)
1087 fn proc_macro_stub(item: &ast::Item) -> Option<(MacroKind, Ident, Span)> {
1088 if attr::contains_name(&item.attrs, sym::proc_macro) {
1089 return Some((MacroKind::Bang, item.ident, item.span));
1090 } else if attr::contains_name(&item.attrs, sym::proc_macro_attribute) {
1091 return Some((MacroKind::Attr, item.ident, item.span));
1092 } else if let Some(attr) = attr::find_by_name(&item.attrs, sym::proc_macro_derive) {
1093 if let Some(nested_meta) = attr.meta_item_list().and_then(|list| list.get(0).cloned()) {
1094 if let Some(ident) = nested_meta.ident() {
1095 return Some((MacroKind::Derive, ident, ident.span));
1102 fn define_macro(&mut self, item: &ast::Item) -> LegacyScope<'a> {
1103 let parent_scope = &self.parent_scope;
1104 let expansion = parent_scope.expansion;
1105 let (ext, ident, span, is_legacy) = match &item.node {
1106 ItemKind::MacroDef(def) => {
1107 let ext = self.r.compile_macro(item, self.r.session.edition());
1108 (ext, item.ident, item.span, def.legacy)
1110 ItemKind::Fn(..) => match Self::proc_macro_stub(item) {
1111 Some((macro_kind, ident, span)) => {
1112 self.r.proc_macro_stubs.insert(item.id);
1113 (self.r.dummy_ext(macro_kind), ident, span, false)
1115 None => return parent_scope.legacy,
1117 _ => unreachable!(),
1120 let def_id = self.r.definitions.local_def_id(item.id);
1121 let res = Res::Def(DefKind::Macro(ext.macro_kind()), def_id);
1122 self.r.macro_map.insert(def_id, ext);
1123 self.r.local_macro_def_scopes.insert(item.id, parent_scope.module);
1126 let ident = ident.modern();
1127 self.r.macro_names.insert(ident);
1128 let is_macro_export = attr::contains_name(&item.attrs, sym::macro_export);
1129 let vis = if is_macro_export {
1130 ty::Visibility::Public
1132 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
1134 let binding = (res, vis, span, expansion).to_name_binding(self.r.arenas);
1135 self.r.set_binding_parent_module(binding, parent_scope.module);
1136 self.r.all_macros.insert(ident.name, res);
1137 if is_macro_export {
1138 let module = self.r.graph_root;
1139 self.r.define(module, ident, MacroNS,
1140 (res, vis, span, expansion, IsMacroExport));
1142 self.r.check_reserved_macro_name(ident, res);
1143 self.r.unused_macros.insert(item.id, span);
1145 LegacyScope::Binding(self.r.arenas.alloc_legacy_binding(LegacyBinding {
1146 parent_legacy_scope: parent_scope.legacy, binding, ident
1149 let module = parent_scope.module;
1150 let vis = self.resolve_visibility(&item.vis);
1151 if vis != ty::Visibility::Public {
1152 self.r.unused_macros.insert(item.id, span);
1154 self.r.define(module, ident, MacroNS, (res, vis, span, expansion));
1155 self.parent_scope.legacy
1160 macro_rules! method {
1161 ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
1162 fn $visit(&mut self, node: &'b $ty) {
1163 if let $invoc(..) = node.node {
1164 self.visit_invoc(node.id);
1166 visit::$walk(self, node);
1172 impl<'a, 'b> Visitor<'b> for BuildReducedGraphVisitor<'a, 'b> {
1173 method!(visit_impl_item: ast::ImplItem, ast::ImplItemKind::Macro, walk_impl_item);
1174 method!(visit_expr: ast::Expr, ast::ExprKind::Mac, walk_expr);
1175 method!(visit_pat: ast::Pat, ast::PatKind::Mac, walk_pat);
1176 method!(visit_ty: ast::Ty, ast::TyKind::Mac, walk_ty);
1178 fn visit_item(&mut self, item: &'b Item) {
1179 let macro_use = match item.node {
1180 ItemKind::MacroDef(..) => {
1181 self.parent_scope.legacy = self.define_macro(item);
1184 ItemKind::Mac(..) => {
1185 self.parent_scope.legacy = self.visit_invoc(item.id);
1188 ItemKind::Mod(..) => self.contains_macro_use(&item.attrs),
1192 let orig_current_module = self.parent_scope.module;
1193 let orig_current_legacy_scope = self.parent_scope.legacy;
1194 self.build_reduced_graph_for_item(item);
1195 visit::walk_item(self, item);
1196 self.parent_scope.module = orig_current_module;
1198 self.parent_scope.legacy = orig_current_legacy_scope;
1202 fn visit_stmt(&mut self, stmt: &'b ast::Stmt) {
1203 if let ast::StmtKind::Mac(..) = stmt.node {
1204 self.parent_scope.legacy = self.visit_invoc(stmt.id);
1206 visit::walk_stmt(self, stmt);
1210 fn visit_foreign_item(&mut self, foreign_item: &'b ForeignItem) {
1211 if let ForeignItemKind::Macro(_) = foreign_item.node {
1212 self.visit_invoc(foreign_item.id);
1216 self.build_reduced_graph_for_foreign_item(foreign_item);
1217 visit::walk_foreign_item(self, foreign_item);
1220 fn visit_block(&mut self, block: &'b Block) {
1221 let orig_current_module = self.parent_scope.module;
1222 let orig_current_legacy_scope = self.parent_scope.legacy;
1223 self.build_reduced_graph_for_block(block);
1224 visit::walk_block(self, block);
1225 self.parent_scope.module = orig_current_module;
1226 self.parent_scope.legacy = orig_current_legacy_scope;
1229 fn visit_trait_item(&mut self, item: &'b TraitItem) {
1230 let parent = self.parent_scope.module;
1232 if let TraitItemKind::Macro(_) = item.node {
1233 self.visit_invoc(item.id);
1237 // Add the item to the trait info.
1238 let item_def_id = self.r.definitions.local_def_id(item.id);
1239 let (res, ns) = match item.node {
1240 TraitItemKind::Const(..) => (Res::Def(DefKind::AssocConst, item_def_id), ValueNS),
1241 TraitItemKind::Method(ref sig, _) => {
1242 if sig.decl.has_self() {
1243 self.r.has_self.insert(item_def_id);
1245 (Res::Def(DefKind::Method, item_def_id), ValueNS)
1247 TraitItemKind::Type(..) => (Res::Def(DefKind::AssocTy, item_def_id), TypeNS),
1248 TraitItemKind::Macro(_) => bug!(), // handled above
1251 let vis = ty::Visibility::Public;
1252 let expansion = self.parent_scope.expansion;
1253 self.r.define(parent, item.ident, ns, (res, vis, item.span, expansion));
1255 self.parent_scope.module = parent.parent.unwrap(); // nearest normal ancestor
1256 visit::walk_trait_item(self, item);
1257 self.parent_scope.module = parent;
1260 fn visit_token(&mut self, t: Token) {
1261 if let token::Interpolated(nt) = t.kind {
1262 if let token::NtExpr(ref expr) = *nt {
1263 if let ast::ExprKind::Mac(..) = expr.node {
1264 self.visit_invoc(expr.id);
1270 fn visit_attribute(&mut self, attr: &'b ast::Attribute) {
1271 if !attr.is_sugared_doc && is_builtin_attr(attr) {
1272 self.r.builtin_attrs.push((attr.path.segments[0].ident, self.parent_scope));
1274 visit::walk_attribute(self, attr);