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::def_collector::collect_definitions;
9 use crate::imports::{Import, ImportKind};
10 use crate::macros::{MacroRulesBinding, MacroRulesScope};
11 use crate::Namespace::{self, MacroNS, TypeNS, ValueNS};
12 use crate::{CrateLint, Determinacy, PathResult, ResolutionError, VisResolutionError};
14 ExternPreludeEntry, ModuleOrUniformRoot, ParentScope, PerNS, Resolver, ResolverArenas,
16 use crate::{Module, ModuleData, ModuleKind, NameBinding, NameBindingKind, Segment, ToNameBinding};
18 use rustc_ast::ast::{self, Block, ForeignItem, ForeignItemKind, Item, ItemKind, NodeId};
19 use rustc_ast::ast::{AssocItem, AssocItemKind, MetaItemKind, StmtKind};
20 use rustc_ast::token::{self, Token};
21 use rustc_ast::visit::{self, AssocCtxt, Visitor};
22 use rustc_attr as attr;
23 use rustc_data_structures::sync::Lrc;
24 use rustc_errors::{struct_span_err, Applicability};
25 use rustc_expand::base::SyntaxExtension;
26 use rustc_expand::expand::AstFragment;
27 use rustc_hir::def::{self, *};
28 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_INDEX};
29 use rustc_metadata::creader::LoadedMacro;
30 use rustc_middle::bug;
31 use rustc_middle::hir::exports::Export;
32 use rustc_middle::middle::cstore::CrateStore;
34 use rustc_span::hygiene::{ExpnId, MacroKind};
35 use rustc_span::source_map::{respan, Spanned};
36 use rustc_span::symbol::{kw, sym, Ident, Symbol};
37 use rustc_span::{Span, DUMMY_SP};
43 type Res = def::Res<NodeId>;
45 impl<'a> ToNameBinding<'a> for (Module<'a>, ty::Visibility, Span, ExpnId) {
46 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
47 arenas.alloc_name_binding(NameBinding {
48 kind: NameBindingKind::Module(self.0),
57 impl<'a> ToNameBinding<'a> for (Res, ty::Visibility, Span, ExpnId) {
58 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
59 arenas.alloc_name_binding(NameBinding {
60 kind: NameBindingKind::Res(self.0, false),
71 impl<'a> ToNameBinding<'a> for (Res, ty::Visibility, Span, ExpnId, IsMacroExport) {
72 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
73 arenas.alloc_name_binding(NameBinding {
74 kind: NameBindingKind::Res(self.0, true),
83 impl<'a> Resolver<'a> {
84 /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
85 /// otherwise, reports an error.
86 crate fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T)
90 let binding = def.to_name_binding(self.arenas);
91 let key = self.new_key(ident, ns);
92 if let Err(old_binding) = self.try_define(parent, key, binding) {
93 self.report_conflict(parent, ident, ns, old_binding, &binding);
97 crate fn get_module(&mut self, def_id: DefId) -> Module<'a> {
98 // If this is a local module, it will be in `module_map`, no need to recalculate it.
99 if let Some(def_id) = def_id.as_local() {
100 return self.module_map[&def_id];
103 // Cache module resolution
104 if let Some(&module) = self.extern_module_map.get(&def_id) {
108 let (name, parent) = if def_id.index == CRATE_DEF_INDEX {
109 // This is the crate root
110 (self.cstore().crate_name_untracked(def_id.krate), None)
112 let def_key = self.cstore().def_key(def_id);
114 // This unwrap is safe: crates must always have a name
115 def_key.disambiguated_data.data.get_opt_name().unwrap(),
116 // This unwrap is safe since we know this isn't the root
117 Some(self.get_module(DefId { index: def_key.parent.unwrap(), ..def_id })),
121 // Allocate and return a new module with the information we found
122 let kind = ModuleKind::Def(DefKind::Mod, def_id, name);
123 let module = self.arenas.alloc_module(ModuleData::new(
130 self.extern_module_map.insert(def_id, module);
134 crate fn macro_def_scope(&mut self, expn_id: ExpnId) -> Module<'a> {
135 let def_id = match expn_id.expn_data().macro_def_id {
136 Some(def_id) => def_id,
137 None => return self.ast_transform_scopes.get(&expn_id).unwrap_or(&self.graph_root),
139 if let Some(id) = def_id.as_local() {
140 self.local_macro_def_scopes[&id]
142 let module_def_id = ty::DefIdTree::parent(&*self, def_id).unwrap();
143 self.get_module(module_def_id)
147 crate fn get_macro(&mut self, res: Res) -> Option<Lrc<SyntaxExtension>> {
149 Res::Def(DefKind::Macro(..), def_id) => self.get_macro_by_def_id(def_id),
150 Res::NonMacroAttr(attr_kind) => Some(self.non_macro_attr(attr_kind.is_used())),
155 crate fn get_macro_by_def_id(&mut self, def_id: DefId) -> Option<Lrc<SyntaxExtension>> {
156 if let Some(ext) = self.macro_map.get(&def_id) {
157 return Some(ext.clone());
160 let ext = Lrc::new(match self.cstore().load_macro_untracked(def_id, &self.session) {
161 LoadedMacro::MacroDef(item, edition) => self.compile_macro(&item, edition),
162 LoadedMacro::ProcMacro(ext) => ext,
165 self.macro_map.insert(def_id, ext.clone());
169 crate fn build_reduced_graph(
171 fragment: &AstFragment,
172 parent_scope: ParentScope<'a>,
173 ) -> MacroRulesScope<'a> {
174 collect_definitions(&mut self.definitions, fragment, parent_scope.expansion);
175 let mut visitor = BuildReducedGraphVisitor { r: self, parent_scope };
176 fragment.visit_with(&mut visitor);
177 visitor.parent_scope.macro_rules
180 crate fn build_reduced_graph_external(&mut self, module: Module<'a>) {
181 let def_id = module.def_id().expect("unpopulated module without a def-id");
182 for child in self.cstore().item_children_untracked(def_id, self.session) {
183 let child = child.map_id(|_| panic!("unexpected id"));
184 BuildReducedGraphVisitor { r: self, parent_scope: ParentScope::module(module) }
185 .build_reduced_graph_for_external_crate_res(child);
190 struct BuildReducedGraphVisitor<'a, 'b> {
191 r: &'b mut Resolver<'a>,
192 parent_scope: ParentScope<'a>,
195 impl<'a> AsMut<Resolver<'a>> for BuildReducedGraphVisitor<'a, '_> {
196 fn as_mut(&mut self) -> &mut Resolver<'a> {
201 impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
202 fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
203 self.resolve_visibility_speculative(vis, false).unwrap_or_else(|err| {
204 self.r.report_vis_error(err);
205 ty::Visibility::Public
209 fn resolve_visibility_speculative<'ast>(
211 vis: &'ast ast::Visibility,
213 ) -> Result<ty::Visibility, VisResolutionError<'ast>> {
214 let parent_scope = &self.parent_scope;
216 ast::VisibilityKind::Public => Ok(ty::Visibility::Public),
217 ast::VisibilityKind::Crate(..) => {
218 Ok(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)))
220 ast::VisibilityKind::Inherited => {
221 Ok(ty::Visibility::Restricted(parent_scope.module.normal_ancestor_id))
223 ast::VisibilityKind::Restricted { ref path, id, .. } => {
224 // For visibilities we are not ready to provide correct implementation of "uniform
225 // paths" right now, so on 2018 edition we only allow module-relative paths for now.
226 // On 2015 edition visibilities are resolved as crate-relative by default,
227 // so we are prepending a root segment if necessary.
228 let ident = path.segments.get(0).expect("empty path in visibility").ident;
229 let crate_root = if ident.is_path_segment_keyword() {
231 } else if ident.span.rust_2015() {
232 Some(Segment::from_ident(Ident::new(
234 path.span.shrink_to_lo().with_ctxt(ident.span.ctxt()),
237 return Err(VisResolutionError::Relative2018(ident.span, path));
240 let segments = crate_root
242 .chain(path.segments.iter().map(|seg| seg.into()))
243 .collect::<Vec<_>>();
244 let expected_found_error = |res| {
245 Err(VisResolutionError::ExpectedFound(
247 Segment::names_to_string(&segments),
251 match self.r.resolve_path(
257 CrateLint::SimplePath(id),
259 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
260 let res = module.res().expect("visibility resolved to unnamed block");
262 self.r.record_partial_res(id, PartialRes::new(res));
264 if module.is_normal() {
266 Ok(ty::Visibility::Public)
268 let vis = ty::Visibility::Restricted(res.def_id());
269 if self.r.is_accessible_from(vis, parent_scope.module) {
272 Err(VisResolutionError::AncestorOnly(path.span))
276 expected_found_error(res)
279 PathResult::Module(..) => Err(VisResolutionError::ModuleOnly(path.span)),
280 PathResult::NonModule(partial_res) => {
281 expected_found_error(partial_res.base_res())
283 PathResult::Failed { span, label, suggestion, .. } => {
284 Err(VisResolutionError::FailedToResolve(span, label, suggestion))
286 PathResult::Indeterminate => Err(VisResolutionError::Indeterminate(path.span)),
292 fn insert_field_names_local(&mut self, def_id: DefId, vdata: &ast::VariantData) {
293 let field_names = vdata
296 .map(|field| respan(field.span, field.ident.map_or(kw::Invalid, |ident| ident.name)))
298 self.insert_field_names(def_id, field_names);
301 fn insert_field_names(&mut self, def_id: DefId, field_names: Vec<Spanned<Symbol>>) {
302 if !field_names.is_empty() {
303 self.r.field_names.insert(def_id, field_names);
307 fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
308 // If any statements are items, we need to create an anonymous module
309 block.stmts.iter().any(|statement| match statement.kind {
310 StmtKind::Item(_) | StmtKind::MacCall(_) => true,
315 // Add an import to the current module.
318 module_path: Vec<Segment>,
319 kind: ImportKind<'a>,
327 let current_module = self.parent_scope.module;
328 let import = self.r.arenas.alloc_import(Import {
330 parent_scope: self.parent_scope,
332 imported_module: Cell::new(None),
336 use_span_with_attributes: item.span_with_attributes(),
337 has_attributes: !item.attrs.is_empty(),
341 used: Cell::new(false),
344 debug!("add_import({:?})", import);
346 self.r.indeterminate_imports.push(import);
348 // Don't add unresolved underscore imports to modules
349 ImportKind::Single { target: Ident { name: kw::Underscore, .. }, .. } => {}
350 ImportKind::Single { target, type_ns_only, .. } => {
351 self.r.per_ns(|this, ns| {
352 if !type_ns_only || ns == TypeNS {
353 let key = this.new_key(target, ns);
354 let mut resolution = this.resolution(current_module, key).borrow_mut();
355 resolution.add_single_import(import);
359 // We don't add prelude imports to the globs since they only affect lexical scopes,
360 // which are not relevant to import resolution.
361 ImportKind::Glob { is_prelude: true, .. } => {}
362 ImportKind::Glob { .. } => current_module.globs.borrow_mut().push(import),
367 fn build_reduced_graph_for_use_tree(
369 // This particular use tree
370 use_tree: &ast::UseTree,
372 parent_prefix: &[Segment],
374 // The whole `use` item
380 "build_reduced_graph_for_use_tree(parent_prefix={:?}, use_tree={:?}, nested={})",
381 parent_prefix, use_tree, nested
384 let mut prefix_iter = parent_prefix
387 .chain(use_tree.prefix.segments.iter().map(|seg| seg.into()))
390 // On 2015 edition imports are resolved as crate-relative by default,
391 // so prefixes are prepended with crate root segment if necessary.
392 // The root is prepended lazily, when the first non-empty prefix or terminating glob
393 // appears, so imports in braced groups can have roots prepended independently.
394 let is_glob = if let ast::UseTreeKind::Glob = use_tree.kind { true } else { false };
395 let crate_root = match prefix_iter.peek() {
396 Some(seg) if !seg.ident.is_path_segment_keyword() && seg.ident.span.rust_2015() => {
397 Some(seg.ident.span.ctxt())
399 None if is_glob && use_tree.span.rust_2015() => Some(use_tree.span.ctxt()),
403 Segment::from_ident(Ident::new(
405 use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt),
409 let prefix = crate_root.into_iter().chain(prefix_iter).collect::<Vec<_>>();
410 debug!("build_reduced_graph_for_use_tree: prefix={:?}", prefix);
412 let empty_for_self = |prefix: &[Segment]| {
413 prefix.is_empty() || prefix.len() == 1 && prefix[0].ident.name == kw::PathRoot
415 match use_tree.kind {
416 ast::UseTreeKind::Simple(rename, ..) => {
417 let mut ident = use_tree.ident();
418 let mut module_path = prefix;
419 let mut source = module_path.pop().unwrap();
420 let mut type_ns_only = false;
423 // Correctly handle `self`
424 if source.ident.name == kw::SelfLower {
427 if empty_for_self(&module_path) {
430 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix,
435 // Replace `use foo::{ self };` with `use foo;`
436 source = module_path.pop().unwrap();
437 if rename.is_none() {
438 ident = source.ident;
443 if source.ident.name == kw::SelfLower {
444 let parent = module_path.last();
446 let span = match parent {
447 // only `::self` from `use foo::self as bar`
448 Some(seg) => seg.ident.span.shrink_to_hi().to(source.ident.span),
449 None => source.ident.span,
451 let span_with_rename = match rename {
452 // only `self as bar` from `use foo::self as bar`
453 Some(rename) => source.ident.span.to(rename.span),
454 None => source.ident.span,
458 ResolutionError::SelfImportsOnlyAllowedWithin {
459 root: parent.is_none(),
464 // Error recovery: replace `use foo::self;` with `use foo;`
465 if let Some(parent) = module_path.pop() {
467 if rename.is_none() {
468 ident = source.ident;
473 // Disallow `use $crate;`
474 if source.ident.name == kw::DollarCrate && module_path.is_empty() {
475 let crate_root = self.r.resolve_crate_root(source.ident);
476 let crate_name = match crate_root.kind {
477 ModuleKind::Def(.., name) => name,
478 ModuleKind::Block(..) => unreachable!(),
480 // HACK(eddyb) unclear how good this is, but keeping `$crate`
481 // in `source` breaks `src/test/compile-fail/import-crate-var.rs`,
482 // while the current crate doesn't have a valid `crate_name`.
483 if crate_name != kw::Invalid {
484 // `crate_name` should not be interpreted as relative.
485 module_path.push(Segment {
486 ident: Ident { name: kw::PathRoot, span: source.ident.span },
487 id: Some(self.r.next_node_id()),
489 source.ident.name = crate_name;
491 if rename.is_none() {
492 ident.name = crate_name;
497 .struct_span_err(item.span, "`$crate` may not be imported")
502 if ident.name == kw::Crate {
503 self.r.session.span_err(
505 "crate root imports need to be explicitly named: \
506 `use crate as name;`",
510 let kind = ImportKind::Single {
511 source: source.ident,
513 source_bindings: PerNS {
514 type_ns: Cell::new(Err(Determinacy::Undetermined)),
515 value_ns: Cell::new(Err(Determinacy::Undetermined)),
516 macro_ns: Cell::new(Err(Determinacy::Undetermined)),
518 target_bindings: PerNS {
519 type_ns: Cell::new(None),
520 value_ns: Cell::new(None),
521 macro_ns: Cell::new(None),
537 ast::UseTreeKind::Glob => {
538 let kind = ImportKind::Glob {
539 is_prelude: attr::contains_name(&item.attrs, sym::prelude_import),
540 max_vis: Cell::new(ty::Visibility::Invisible),
542 self.add_import(prefix, kind, use_tree.span, id, item, root_span, item.id, vis);
544 ast::UseTreeKind::Nested(ref items) => {
545 // Ensure there is at most one `self` in the list
546 let self_spans = items
548 .filter_map(|&(ref use_tree, _)| {
549 if let ast::UseTreeKind::Simple(..) = use_tree.kind {
550 if use_tree.ident().name == kw::SelfLower {
551 return Some(use_tree.span);
557 .collect::<Vec<_>>();
558 if self_spans.len() > 1 {
559 let mut e = self.r.into_struct_error(
561 ResolutionError::SelfImportCanOnlyAppearOnceInTheList,
564 for other_span in self_spans.iter().skip(1) {
565 e.span_label(*other_span, "another `self` import appears here");
571 for &(ref tree, id) in items {
572 self.build_reduced_graph_for_use_tree(
573 // This particular use tree
574 tree, id, &prefix, true, // The whole `use` item
575 item, vis, root_span,
579 // Empty groups `a::b::{}` are turned into synthetic `self` imports
580 // `a::b::c::{self as _}`, so that their prefixes are correctly
581 // resolved and checked for privacy/stability/etc.
582 if items.is_empty() && !empty_for_self(&prefix) {
583 let new_span = prefix[prefix.len() - 1].ident.span;
584 let tree = ast::UseTree {
585 prefix: ast::Path::from_ident(Ident::new(kw::SelfLower, new_span)),
586 kind: ast::UseTreeKind::Simple(
587 Some(Ident::new(kw::Underscore, new_span)),
593 self.build_reduced_graph_for_use_tree(
594 // This particular use tree
599 // The whole `use` item
601 ty::Visibility::Invisible,
609 /// Constructs the reduced graph for one item.
610 fn build_reduced_graph_for_item(&mut self, item: &'b Item) {
611 let parent_scope = &self.parent_scope;
612 let parent = parent_scope.module;
613 let expansion = parent_scope.expansion;
614 let ident = item.ident;
616 let vis = self.resolve_visibility(&item.vis);
619 ItemKind::Use(ref use_tree) => {
620 self.build_reduced_graph_for_use_tree(
621 // This particular use tree
626 // The whole `use` item
633 ItemKind::ExternCrate(orig_name) => {
634 let module = if orig_name.is_none() && ident.name == kw::SelfLower {
637 .struct_span_err(item.span, "`extern crate self;` requires renaming")
641 "extern crate self as name;".into(),
642 Applicability::HasPlaceholders,
646 } else if orig_name == Some(kw::SelfLower) {
649 let def_id = self.r.definitions.local_def_id(item.id);
651 self.r.crate_loader.process_extern_crate(item, &self.r.definitions);
652 self.r.extern_crate_map.insert(def_id, crate_id);
653 self.r.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX })
656 let used = self.process_macro_use_imports(item, module);
658 (module, ty::Visibility::Public, sp, expansion).to_name_binding(self.r.arenas);
659 let import = self.r.arenas.alloc_import(Import {
660 kind: ImportKind::ExternCrate { source: orig_name, target: ident },
663 parent_scope: self.parent_scope,
664 imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
665 has_attributes: !item.attrs.is_empty(),
666 use_span_with_attributes: item.span_with_attributes(),
668 root_span: item.span,
670 module_path: Vec::new(),
672 used: Cell::new(used),
674 self.r.potentially_unused_imports.push(import);
675 let imported_binding = self.r.import(binding, import);
676 if ptr::eq(parent, self.r.graph_root) {
677 if let Some(entry) = self.r.extern_prelude.get(&ident.normalize_to_macros_2_0())
679 if expansion != ExpnId::root()
680 && orig_name.is_some()
681 && entry.extern_crate_item.is_none()
683 let msg = "macro-expanded `extern crate` items cannot \
684 shadow names passed with `--extern`";
685 self.r.session.span_err(item.span, msg);
689 self.r.extern_prelude.entry(ident.normalize_to_macros_2_0()).or_insert(
691 extern_crate_item: None,
692 introduced_by_item: true,
695 entry.extern_crate_item = Some(imported_binding);
696 if orig_name.is_some() {
697 entry.introduced_by_item = true;
700 self.r.define(parent, ident, TypeNS, imported_binding);
703 ItemKind::Mod(..) if ident.name == kw::Invalid => {} // Crate root
705 ItemKind::Mod(..) => {
706 let def_id = self.r.definitions.local_def_id(item.id);
707 let module_kind = ModuleKind::Def(DefKind::Mod, def_id.to_def_id(), ident.name);
708 let module = self.r.arenas.alloc_module(ModuleData {
709 no_implicit_prelude: parent.no_implicit_prelude || {
710 attr::contains_name(&item.attrs, sym::no_implicit_prelude)
720 self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion));
721 self.r.module_map.insert(def_id, module);
723 // Descend into the module.
724 self.parent_scope.module = module;
727 // These items live in the value namespace.
728 ItemKind::Static(..) => {
730 Res::Def(DefKind::Static, self.r.definitions.local_def_id(item.id).to_def_id());
731 self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion));
733 ItemKind::Const(..) => {
735 Res::Def(DefKind::Const, self.r.definitions.local_def_id(item.id).to_def_id());
736 self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion));
738 ItemKind::Fn(..) => {
740 Res::Def(DefKind::Fn, self.r.definitions.local_def_id(item.id).to_def_id());
741 self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion));
743 // Functions introducing procedural macros reserve a slot
744 // in the macro namespace as well (see #52225).
745 self.define_macro(item);
748 // These items live in the type namespace.
749 ItemKind::TyAlias(_, _, _, ref ty) => {
750 let def_kind = match ty.as_deref().and_then(|ty| ty.kind.opaque_top_hack()) {
751 None => DefKind::TyAlias,
752 Some(_) => DefKind::OpaqueTy,
754 let res = Res::Def(def_kind, self.r.definitions.local_def_id(item.id).to_def_id());
755 self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion));
758 ItemKind::Enum(_, _) => {
759 let def_id = self.r.definitions.local_def_id(item.id).to_def_id();
760 self.r.variant_vis.insert(def_id, vis);
761 let module_kind = ModuleKind::Def(DefKind::Enum, def_id, ident.name);
762 let module = self.r.new_module(
765 parent.normal_ancestor_id,
769 self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion));
770 self.parent_scope.module = module;
773 ItemKind::TraitAlias(..) => {
776 self.r.definitions.local_def_id(item.id).to_def_id(),
778 self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion));
781 // These items live in both the type and value namespaces.
782 ItemKind::Struct(ref vdata, _) => {
783 // Define a name in the type namespace.
784 let def_id = self.r.definitions.local_def_id(item.id).to_def_id();
785 let res = Res::Def(DefKind::Struct, def_id);
786 self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion));
788 // Record field names for error reporting.
789 self.insert_field_names_local(def_id, vdata);
791 // If this is a tuple or unit struct, define a name
792 // in the value namespace as well.
793 if let Some(ctor_node_id) = vdata.ctor_id() {
794 // If the structure is marked as non_exhaustive then lower the visibility
795 // to within the crate.
796 let mut ctor_vis = if vis == ty::Visibility::Public
797 && attr::contains_name(&item.attrs, sym::non_exhaustive)
799 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
804 for field in vdata.fields() {
805 // NOTE: The field may be an expansion placeholder, but expansion sets
806 // correct visibilities for unnamed field placeholders specifically, so the
807 // constructor visibility should still be determined correctly.
808 if let Ok(field_vis) = self.resolve_visibility_speculative(&field.vis, true)
810 if ctor_vis.is_at_least(field_vis, &*self.r) {
811 ctor_vis = field_vis;
815 let ctor_res = Res::Def(
816 DefKind::Ctor(CtorOf::Struct, CtorKind::from_ast(vdata)),
817 self.r.definitions.local_def_id(ctor_node_id).to_def_id(),
819 self.r.define(parent, ident, ValueNS, (ctor_res, ctor_vis, sp, expansion));
820 self.r.struct_constructors.insert(def_id, (ctor_res, ctor_vis));
824 ItemKind::Union(ref vdata, _) => {
825 let def_id = self.r.definitions.local_def_id(item.id).to_def_id();
826 let res = Res::Def(DefKind::Union, def_id);
827 self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion));
829 // Record field names for error reporting.
830 self.insert_field_names_local(def_id, vdata);
833 ItemKind::Trait(..) => {
834 let def_id = self.r.definitions.local_def_id(item.id).to_def_id();
836 // Add all the items within to a new module.
837 let module_kind = ModuleKind::Def(DefKind::Trait, def_id, ident.name);
838 let module = self.r.new_module(
841 parent.normal_ancestor_id,
845 self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion));
846 self.parent_scope.module = module;
849 // These items do not add names to modules.
850 ItemKind::Impl { .. } | ItemKind::ForeignMod(..) | ItemKind::GlobalAsm(..) => {}
852 ItemKind::MacroDef(..) | ItemKind::MacCall(_) => unreachable!(),
856 /// Constructs the reduced graph for one foreign item.
857 fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem) {
858 let (res, ns) = match item.kind {
859 ForeignItemKind::Fn(..) => (
860 Res::Def(DefKind::Fn, self.r.definitions.local_def_id(item.id).to_def_id()),
863 ForeignItemKind::Static(..) => (
864 Res::Def(DefKind::Static, self.r.definitions.local_def_id(item.id).to_def_id()),
867 ForeignItemKind::TyAlias(..) => (
868 Res::Def(DefKind::ForeignTy, self.r.definitions.local_def_id(item.id).to_def_id()),
871 ForeignItemKind::MacCall(_) => unreachable!(),
873 let parent = self.parent_scope.module;
874 let expansion = self.parent_scope.expansion;
875 let vis = self.resolve_visibility(&item.vis);
876 self.r.define(parent, item.ident, ns, (res, vis, item.span, expansion));
879 fn build_reduced_graph_for_block(&mut self, block: &Block) {
880 let parent = self.parent_scope.module;
881 let expansion = self.parent_scope.expansion;
882 if self.block_needs_anonymous_module(block) {
883 let module = self.r.new_module(
885 ModuleKind::Block(block.id),
886 parent.normal_ancestor_id,
890 self.r.block_map.insert(block.id, module);
891 self.parent_scope.module = module; // Descend into the block.
895 /// Builds the reduced graph for a single item in an external crate.
896 fn build_reduced_graph_for_external_crate_res(&mut self, child: Export<NodeId>) {
897 let parent = self.parent_scope.module;
898 let Export { ident, res, vis, span } = child;
899 let expansion = ExpnId::root(); // FIXME(jseyfried) intercrate hygiene
900 // Record primary definitions.
902 Res::Def(kind @ (DefKind::Mod | DefKind::Enum | DefKind::Trait), def_id) => {
903 let module = self.r.new_module(
905 ModuleKind::Def(kind, def_id, ident.name),
910 self.r.define(parent, ident, TypeNS, (module, vis, span, expansion));
919 | DefKind::TraitAlias
921 | DefKind::AssocOpaqueTy,
925 | Res::ToolMod => self.r.define(parent, ident, TypeNS, (res, vis, span, expansion)),
931 | DefKind::AssocConst
934 ) => self.r.define(parent, ident, ValueNS, (res, vis, span, expansion)),
935 Res::Def(DefKind::Macro(..), _) | Res::NonMacroAttr(..) => {
936 self.r.define(parent, ident, MacroNS, (res, vis, span, expansion))
940 | DefKind::ConstParam
941 | DefKind::ExternCrate
943 | DefKind::ForeignMod
946 | DefKind::LifetimeParam
950 | DefKind::Generator,
956 | Res::Err => bug!("unexpected resolution: {:?}", res),
958 // Record some extra data for better diagnostics.
959 let cstore = self.r.cstore();
961 Res::Def(DefKind::Struct | DefKind::Union, def_id) => {
962 let field_names = cstore.struct_field_names_untracked(def_id, self.r.session);
963 self.insert_field_names(def_id, field_names);
965 Res::Def(DefKind::AssocFn, def_id) => {
967 .associated_item_cloned_untracked(def_id, self.r.session)
968 .fn_has_self_parameter
970 self.r.has_self.insert(def_id);
973 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), def_id) => {
974 let parent = cstore.def_key(def_id).parent;
975 if let Some(struct_def_id) = parent.map(|index| DefId { index, ..def_id }) {
976 self.r.struct_constructors.insert(struct_def_id, (res, vis));
983 fn add_macro_use_binding(
986 binding: &'a NameBinding<'a>,
988 allow_shadowing: bool,
990 if self.r.macro_use_prelude.insert(name, binding).is_some() && !allow_shadowing {
991 let msg = format!("`{}` is already in scope", name);
993 "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)";
994 self.r.session.struct_span_err(span, &msg).note(note).emit();
998 /// Returns `true` if we should consider the underlying `extern crate` to be used.
999 fn process_macro_use_imports(&mut self, item: &Item, module: Module<'a>) -> bool {
1000 let mut import_all = None;
1001 let mut single_imports = Vec::new();
1002 for attr in &item.attrs {
1003 if attr.check_name(sym::macro_use) {
1004 if self.parent_scope.module.parent.is_some() {
1009 "an `extern crate` loading macros must be at the crate root"
1013 if let ItemKind::ExternCrate(Some(orig_name)) = item.kind {
1014 if orig_name == kw::SelfLower {
1019 "`#[macro_use]` is not supported on `extern crate self`",
1025 |span| struct_span_err!(self.r.session, span, E0466, "bad macro import").emit();
1027 Some(meta) => match meta.kind {
1028 MetaItemKind::Word => {
1029 import_all = Some(meta.span);
1032 MetaItemKind::List(nested_metas) => {
1033 for nested_meta in nested_metas {
1034 match nested_meta.ident() {
1035 Some(ident) if nested_meta.is_word() => {
1036 single_imports.push(ident)
1038 _ => ill_formed(nested_meta.span()),
1042 MetaItemKind::NameValue(..) => ill_formed(meta.span),
1044 None => ill_formed(attr.span),
1049 let macro_use_import = |this: &Self, span| {
1050 this.r.arenas.alloc_import(Import {
1051 kind: ImportKind::MacroUse,
1054 parent_scope: this.parent_scope,
1055 imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
1056 use_span_with_attributes: item.span_with_attributes(),
1057 has_attributes: !item.attrs.is_empty(),
1058 use_span: item.span,
1061 module_path: Vec::new(),
1062 vis: Cell::new(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))),
1063 used: Cell::new(false),
1067 let allow_shadowing = self.parent_scope.expansion == ExpnId::root();
1068 if let Some(span) = import_all {
1069 let import = macro_use_import(self, span);
1070 self.r.potentially_unused_imports.push(import);
1071 module.for_each_child(self, |this, ident, ns, binding| {
1073 let imported_binding = this.r.import(binding, import);
1074 this.add_macro_use_binding(ident.name, imported_binding, span, allow_shadowing);
1078 for ident in single_imports.iter().cloned() {
1079 let result = self.r.resolve_ident_in_module(
1080 ModuleOrUniformRoot::Module(module),
1087 if let Ok(binding) = result {
1088 let import = macro_use_import(self, ident.span);
1089 self.r.potentially_unused_imports.push(import);
1090 let imported_binding = self.r.import(binding, import);
1091 self.add_macro_use_binding(
1098 struct_span_err!(self.r.session, ident.span, E0469, "imported macro not found")
1103 import_all.is_some() || !single_imports.is_empty()
1106 /// Returns `true` if this attribute list contains `macro_use`.
1107 fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool {
1109 if attr.check_name(sym::macro_escape) {
1110 let msg = "`#[macro_escape]` is a deprecated synonym for `#[macro_use]`";
1111 let mut err = self.r.session.struct_span_warn(attr.span, msg);
1112 if let ast::AttrStyle::Inner = attr.style {
1113 err.help("try an outer attribute: `#[macro_use]`").emit();
1117 } else if !attr.check_name(sym::macro_use) {
1121 if !attr.is_word() {
1122 self.r.session.span_err(attr.span, "arguments to `macro_use` are not allowed here");
1130 fn visit_invoc(&mut self, id: NodeId) -> MacroRulesScope<'a> {
1131 let invoc_id = id.placeholder_to_expn_id();
1133 self.parent_scope.module.unexpanded_invocations.borrow_mut().insert(invoc_id);
1135 let old_parent_scope = self.r.invocation_parent_scopes.insert(invoc_id, self.parent_scope);
1136 assert!(old_parent_scope.is_none(), "invocation data is reset for an invocation");
1138 MacroRulesScope::Invocation(invoc_id)
1141 fn proc_macro_stub(item: &ast::Item) -> Option<(MacroKind, Ident, Span)> {
1142 if attr::contains_name(&item.attrs, sym::proc_macro) {
1143 return Some((MacroKind::Bang, item.ident, item.span));
1144 } else if attr::contains_name(&item.attrs, sym::proc_macro_attribute) {
1145 return Some((MacroKind::Attr, item.ident, item.span));
1146 } else if let Some(attr) = attr::find_by_name(&item.attrs, sym::proc_macro_derive) {
1147 if let Some(nested_meta) = attr.meta_item_list().and_then(|list| list.get(0).cloned()) {
1148 if let Some(ident) = nested_meta.ident() {
1149 return Some((MacroKind::Derive, ident, ident.span));
1156 // Mark the given macro as unused unless its name starts with `_`.
1157 // Macro uses will remove items from this set, and the remaining
1158 // items will be reported as `unused_macros`.
1159 fn insert_unused_macro(
1166 if !ident.as_str().starts_with('_') {
1167 self.r.unused_macros.insert(def_id, (node_id, span));
1171 fn define_macro(&mut self, item: &ast::Item) -> MacroRulesScope<'a> {
1172 let parent_scope = self.parent_scope;
1173 let expansion = parent_scope.expansion;
1174 let def_id = self.r.definitions.local_def_id(item.id);
1175 let (ext, ident, span, macro_rules) = match &item.kind {
1176 ItemKind::MacroDef(def) => {
1177 let ext = Lrc::new(self.r.compile_macro(item, self.r.session.edition()));
1178 (ext, item.ident, item.span, def.macro_rules)
1180 ItemKind::Fn(..) => match Self::proc_macro_stub(item) {
1181 Some((macro_kind, ident, span)) => {
1182 self.r.proc_macro_stubs.insert(def_id);
1183 (self.r.dummy_ext(macro_kind), ident, span, false)
1185 None => return parent_scope.macro_rules,
1187 _ => unreachable!(),
1190 let res = Res::Def(DefKind::Macro(ext.macro_kind()), def_id.to_def_id());
1191 self.r.macro_map.insert(def_id.to_def_id(), ext);
1192 self.r.local_macro_def_scopes.insert(def_id, parent_scope.module);
1195 let ident = ident.normalize_to_macros_2_0();
1196 self.r.macro_names.insert(ident);
1197 let is_macro_export = attr::contains_name(&item.attrs, sym::macro_export);
1198 let vis = if is_macro_export {
1199 ty::Visibility::Public
1201 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
1203 let binding = (res, vis, span, expansion).to_name_binding(self.r.arenas);
1204 self.r.set_binding_parent_module(binding, parent_scope.module);
1205 self.r.all_macros.insert(ident.name, res);
1206 if is_macro_export {
1207 let module = self.r.graph_root;
1208 self.r.define(module, ident, MacroNS, (res, vis, span, expansion, IsMacroExport));
1210 self.r.check_reserved_macro_name(ident, res);
1211 self.insert_unused_macro(ident, def_id, item.id, span);
1213 MacroRulesScope::Binding(self.r.arenas.alloc_macro_rules_binding(MacroRulesBinding {
1214 parent_macro_rules_scope: parent_scope.macro_rules,
1219 let module = parent_scope.module;
1220 let vis = match item.kind {
1221 // Visibilities must not be resolved non-speculatively twice
1222 // and we already resolved this one as a `fn` item visibility.
1223 ItemKind::Fn(..) => self
1224 .resolve_visibility_speculative(&item.vis, true)
1225 .unwrap_or(ty::Visibility::Public),
1226 _ => self.resolve_visibility(&item.vis),
1228 if vis != ty::Visibility::Public {
1229 self.insert_unused_macro(ident, def_id, item.id, span);
1231 self.r.define(module, ident, MacroNS, (res, vis, span, expansion));
1232 self.parent_scope.macro_rules
1237 macro_rules! method {
1238 ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
1239 fn $visit(&mut self, node: &'b $ty) {
1240 if let $invoc(..) = node.kind {
1241 self.visit_invoc(node.id);
1243 visit::$walk(self, node);
1249 impl<'a, 'b> Visitor<'b> for BuildReducedGraphVisitor<'a, 'b> {
1250 method!(visit_expr: ast::Expr, ast::ExprKind::MacCall, walk_expr);
1251 method!(visit_pat: ast::Pat, ast::PatKind::MacCall, walk_pat);
1252 method!(visit_ty: ast::Ty, ast::TyKind::MacCall, walk_ty);
1254 fn visit_item(&mut self, item: &'b Item) {
1255 let macro_use = match item.kind {
1256 ItemKind::MacroDef(..) => {
1257 self.parent_scope.macro_rules = self.define_macro(item);
1260 ItemKind::MacCall(..) => {
1261 self.parent_scope.macro_rules = self.visit_invoc(item.id);
1264 ItemKind::Mod(..) => self.contains_macro_use(&item.attrs),
1267 let orig_current_module = self.parent_scope.module;
1268 let orig_current_macro_rules_scope = self.parent_scope.macro_rules;
1269 self.build_reduced_graph_for_item(item);
1270 visit::walk_item(self, item);
1271 self.parent_scope.module = orig_current_module;
1273 self.parent_scope.macro_rules = orig_current_macro_rules_scope;
1277 fn visit_stmt(&mut self, stmt: &'b ast::Stmt) {
1278 if let ast::StmtKind::MacCall(..) = stmt.kind {
1279 self.parent_scope.macro_rules = self.visit_invoc(stmt.id);
1281 visit::walk_stmt(self, stmt);
1285 fn visit_foreign_item(&mut self, foreign_item: &'b ForeignItem) {
1286 if let ForeignItemKind::MacCall(_) = foreign_item.kind {
1287 self.visit_invoc(foreign_item.id);
1291 self.build_reduced_graph_for_foreign_item(foreign_item);
1292 visit::walk_foreign_item(self, foreign_item);
1295 fn visit_block(&mut self, block: &'b Block) {
1296 let orig_current_module = self.parent_scope.module;
1297 let orig_current_macro_rules_scope = self.parent_scope.macro_rules;
1298 self.build_reduced_graph_for_block(block);
1299 visit::walk_block(self, block);
1300 self.parent_scope.module = orig_current_module;
1301 self.parent_scope.macro_rules = orig_current_macro_rules_scope;
1304 fn visit_assoc_item(&mut self, item: &'b AssocItem, ctxt: AssocCtxt) {
1305 let parent = self.parent_scope.module;
1307 if let AssocItemKind::MacCall(_) = item.kind {
1308 self.visit_invoc(item.id);
1312 if let AssocCtxt::Impl = ctxt {
1313 self.resolve_visibility(&item.vis);
1314 visit::walk_assoc_item(self, item, ctxt);
1318 // Add the item to the trait info.
1319 let item_def_id = self.r.definitions.local_def_id(item.id).to_def_id();
1320 let (res, ns) = match item.kind {
1321 AssocItemKind::Const(..) => (Res::Def(DefKind::AssocConst, item_def_id), ValueNS),
1322 AssocItemKind::Fn(_, ref sig, _, _) => {
1323 if sig.decl.has_self() {
1324 self.r.has_self.insert(item_def_id);
1326 (Res::Def(DefKind::AssocFn, item_def_id), ValueNS)
1328 AssocItemKind::TyAlias(..) => (Res::Def(DefKind::AssocTy, item_def_id), TypeNS),
1329 AssocItemKind::MacCall(_) => bug!(), // handled above
1332 let vis = ty::Visibility::Public;
1333 let expansion = self.parent_scope.expansion;
1334 self.r.define(parent, item.ident, ns, (res, vis, item.span, expansion));
1336 visit::walk_assoc_item(self, item, ctxt);
1339 fn visit_token(&mut self, t: Token) {
1340 if let token::Interpolated(nt) = t.kind {
1341 if let token::NtExpr(ref expr) = *nt {
1342 if let ast::ExprKind::MacCall(..) = expr.kind {
1343 self.visit_invoc(expr.id);
1349 fn visit_attribute(&mut self, attr: &'b ast::Attribute) {
1350 if !attr.is_doc_comment() && attr::is_builtin_attr(attr) {
1353 .push((attr.get_normal_item().path.segments[0].ident, self.parent_scope));
1355 visit::walk_attribute(self, attr);
1358 fn visit_arm(&mut self, arm: &'b ast::Arm) {
1359 if arm.is_placeholder {
1360 self.visit_invoc(arm.id);
1362 visit::walk_arm(self, arm);
1366 fn visit_field(&mut self, f: &'b ast::Field) {
1367 if f.is_placeholder {
1368 self.visit_invoc(f.id);
1370 visit::walk_field(self, f);
1374 fn visit_field_pattern(&mut self, fp: &'b ast::FieldPat) {
1375 if fp.is_placeholder {
1376 self.visit_invoc(fp.id);
1378 visit::walk_field_pattern(self, fp);
1382 fn visit_generic_param(&mut self, param: &'b ast::GenericParam) {
1383 if param.is_placeholder {
1384 self.visit_invoc(param.id);
1386 visit::walk_generic_param(self, param);
1390 fn visit_param(&mut self, p: &'b ast::Param) {
1391 if p.is_placeholder {
1392 self.visit_invoc(p.id);
1394 visit::walk_param(self, p);
1398 fn visit_struct_field(&mut self, sf: &'b ast::StructField) {
1399 if sf.is_placeholder {
1400 self.visit_invoc(sf.id);
1402 self.resolve_visibility(&sf.vis);
1403 visit::walk_struct_field(self, sf);
1407 // Constructs the reduced graph for one variant. Variants exist in the
1408 // type and value namespaces.
1409 fn visit_variant(&mut self, variant: &'b ast::Variant) {
1410 if variant.is_placeholder {
1411 self.visit_invoc(variant.id);
1415 let parent = self.parent_scope.module;
1416 let vis = self.r.variant_vis[&parent.def_id().expect("enum without def-id")];
1417 let expn_id = self.parent_scope.expansion;
1418 let ident = variant.ident;
1420 // Define a name in the type namespace.
1421 let def_id = self.r.definitions.local_def_id(variant.id).to_def_id();
1422 let res = Res::Def(DefKind::Variant, def_id);
1423 self.r.define(parent, ident, TypeNS, (res, vis, variant.span, expn_id));
1425 // If the variant is marked as non_exhaustive then lower the visibility to within the
1427 let mut ctor_vis = vis;
1428 let has_non_exhaustive = attr::contains_name(&variant.attrs, sym::non_exhaustive);
1429 if has_non_exhaustive && vis == ty::Visibility::Public {
1430 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
1433 // Define a constructor name in the value namespace.
1434 // Braced variants, unlike structs, generate unusable names in
1435 // value namespace, they are reserved for possible future use.
1436 // It's ok to use the variant's id as a ctor id since an
1437 // error will be reported on any use of such resolution anyway.
1438 let ctor_node_id = variant.data.ctor_id().unwrap_or(variant.id);
1439 let ctor_def_id = self.r.definitions.local_def_id(ctor_node_id).to_def_id();
1440 let ctor_kind = CtorKind::from_ast(&variant.data);
1441 let ctor_res = Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id);
1442 self.r.define(parent, ident, ValueNS, (ctor_res, ctor_vis, variant.span, expn_id));
1444 visit::walk_variant(self, variant);