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. 3 //! 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. 7 8 use crate::def_collector::collect_definitions; 9 use crate::imports::{ImportData, ImportKind}; 10 use crate::macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef}; 11 use crate::Namespace::{self, MacroNS, TypeNS, ValueNS}; 12 use crate::{errors, BindingKey, MacroData, NameBindingData}; 13 use crate::{Determinacy, ExternPreludeEntry, Finalize, Module, ModuleKind, ModuleOrUniformRoot}; 14 use crate::{NameBinding, NameBindingKind, ParentScope, PathResult, PerNS, ResolutionError}; 15 use crate::{Resolver, ResolverArenas, Segment, ToNameBinding, VisResolutionError}; 16 17 use rustc_ast::visit::{self, AssocCtxt, Visitor}; 18 use rustc_ast::{self as ast, AssocItem, AssocItemKind, MetaItemKind, StmtKind}; 19 use rustc_ast::{Block, Fn, ForeignItem, ForeignItemKind, Impl, Item, ItemKind, NodeId}; 20 use rustc_attr as attr; 21 use rustc_data_structures::sync::Lrc; 22 use rustc_errors::{struct_span_err, Applicability}; 23 use rustc_expand::expand::AstFragment; 24 use rustc_hir::def::{self, *}; 25 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; 26 use rustc_metadata::creader::LoadedMacro; 27 use rustc_middle::metadata::ModChild; 28 use rustc_middle::{bug, ty}; 29 use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind}; 30 use rustc_span::symbol::{kw, sym, Ident, Symbol}; 31 use rustc_span::Span; 32 33 use std::cell::Cell; 34 35 type Res = def::Res<NodeId>; 36 37 impl<'a, Id: Into<DefId>> ToNameBinding<'a> 38 for (Module<'a>, ty::Visibility<Id>, Span, LocalExpnId) 39 { to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> NameBinding<'a>40 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> NameBinding<'a> { 41 arenas.alloc_name_binding(NameBindingData { 42 kind: NameBindingKind::Module(self.0), 43 ambiguity: None, 44 vis: self.1.to_def_id(), 45 span: self.2, 46 expansion: self.3, 47 }) 48 } 49 } 50 51 impl<'a, Id: Into<DefId>> ToNameBinding<'a> for (Res, ty::Visibility<Id>, Span, LocalExpnId) { to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> NameBinding<'a>52 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> NameBinding<'a> { 53 arenas.alloc_name_binding(NameBindingData { 54 kind: NameBindingKind::Res(self.0), 55 ambiguity: None, 56 vis: self.1.to_def_id(), 57 span: self.2, 58 expansion: self.3, 59 }) 60 } 61 } 62 63 impl<'a, 'tcx> Resolver<'a, 'tcx> { 64 /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined; 65 /// otherwise, reports an error. define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T) where T: ToNameBinding<'a>,66 pub(crate) fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T) 67 where 68 T: ToNameBinding<'a>, 69 { 70 let binding = def.to_name_binding(self.arenas); 71 let key = self.new_disambiguated_key(ident, ns); 72 if let Err(old_binding) = self.try_define(parent, key, binding) { 73 self.report_conflict(parent, ident, ns, old_binding, binding); 74 } 75 } 76 77 /// Walks up the tree of definitions starting at `def_id`, 78 /// stopping at the first encountered module. 79 /// Parent block modules for arbitrary def-ids are not recorded for the local crate, 80 /// and are not preserved in metadata for foreign crates, so block modules are never 81 /// returned by this function. 82 /// 83 /// For the local crate ignoring block modules may be incorrect, so use this method with care. 84 /// 85 /// For foreign crates block modules can be ignored without introducing observable differences, 86 /// moreover they has to be ignored right now because they are not kept in metadata. 87 /// Foreign parent modules are used for resolving names used by foreign macros with def-site 88 /// hygiene, therefore block module ignorability relies on macros with def-site hygiene and 89 /// block module parents being unreachable from other crates. 90 /// Reachable macros with block module parents exist due to `#[macro_export] macro_rules!`, 91 /// but they cannot use def-site hygiene, so the assumption holds 92 /// (<https://github.com/rust-lang/rust/pull/77984#issuecomment-712445508>). get_nearest_non_block_module(&mut self, mut def_id: DefId) -> Module<'a>93 pub(crate) fn get_nearest_non_block_module(&mut self, mut def_id: DefId) -> Module<'a> { 94 loop { 95 match self.get_module(def_id) { 96 Some(module) => return module, 97 None => def_id = self.tcx.parent(def_id), 98 } 99 } 100 } 101 expect_module(&mut self, def_id: DefId) -> Module<'a>102 pub(crate) fn expect_module(&mut self, def_id: DefId) -> Module<'a> { 103 self.get_module(def_id).expect("argument `DefId` is not a module") 104 } 105 106 /// If `def_id` refers to a module (in resolver's sense, i.e. a module item, crate root, enum, 107 /// or trait), then this function returns that module's resolver representation, otherwise it 108 /// returns `None`. get_module(&mut self, def_id: DefId) -> Option<Module<'a>>109 pub(crate) fn get_module(&mut self, def_id: DefId) -> Option<Module<'a>> { 110 if let module @ Some(..) = self.module_map.get(&def_id) { 111 return module.copied(); 112 } 113 114 if !def_id.is_local() { 115 // Query `def_kind` is not used because query system overhead is too expensive here. 116 let def_kind = self.cstore().def_kind_untracked(def_id); 117 if let DefKind::Mod | DefKind::Enum | DefKind::Trait = def_kind { 118 let parent = self 119 .tcx 120 .opt_parent(def_id) 121 .map(|parent_id| self.get_nearest_non_block_module(parent_id)); 122 // Query `expn_that_defined` is not used because 123 // hashing spans in its result is expensive. 124 let expn_id = self.cstore().expn_that_defined_untracked(def_id, &self.tcx.sess); 125 return Some(self.new_module( 126 parent, 127 ModuleKind::Def(def_kind, def_id, self.tcx.item_name(def_id)), 128 expn_id, 129 self.def_span(def_id), 130 // FIXME: Account for `#[no_implicit_prelude]` attributes. 131 parent.is_some_and(|module| module.no_implicit_prelude), 132 )); 133 } 134 } 135 136 None 137 } 138 expn_def_scope(&mut self, expn_id: ExpnId) -> Module<'a>139 pub(crate) fn expn_def_scope(&mut self, expn_id: ExpnId) -> Module<'a> { 140 match expn_id.expn_data().macro_def_id { 141 Some(def_id) => self.macro_def_scope(def_id), 142 None => expn_id 143 .as_local() 144 .and_then(|expn_id| self.ast_transform_scopes.get(&expn_id).copied()) 145 .unwrap_or(self.graph_root), 146 } 147 } 148 macro_def_scope(&mut self, def_id: DefId) -> Module<'a>149 pub(crate) fn macro_def_scope(&mut self, def_id: DefId) -> Module<'a> { 150 if let Some(id) = def_id.as_local() { 151 self.local_macro_def_scopes[&id] 152 } else { 153 self.get_nearest_non_block_module(def_id) 154 } 155 } 156 get_macro(&mut self, res: Res) -> Option<MacroData>157 pub(crate) fn get_macro(&mut self, res: Res) -> Option<MacroData> { 158 match res { 159 Res::Def(DefKind::Macro(..), def_id) => Some(self.get_macro_by_def_id(def_id)), 160 Res::NonMacroAttr(_) => { 161 Some(MacroData { ext: self.non_macro_attr.clone(), macro_rules: false }) 162 } 163 _ => None, 164 } 165 } 166 get_macro_by_def_id(&mut self, def_id: DefId) -> MacroData167 pub(crate) fn get_macro_by_def_id(&mut self, def_id: DefId) -> MacroData { 168 if let Some(macro_data) = self.macro_map.get(&def_id) { 169 return macro_data.clone(); 170 } 171 172 let load_macro_untracked = self.cstore().load_macro_untracked(def_id, &self.tcx.sess); 173 let (ext, macro_rules) = match load_macro_untracked { 174 LoadedMacro::MacroDef(item, edition) => ( 175 Lrc::new(self.compile_macro(&item, edition).0), 176 matches!(item.kind, ItemKind::MacroDef(def) if def.macro_rules), 177 ), 178 LoadedMacro::ProcMacro(extz) => (Lrc::new(extz), false), 179 }; 180 181 let macro_data = MacroData { ext, macro_rules }; 182 self.macro_map.insert(def_id, macro_data.clone()); 183 macro_data 184 } 185 build_reduced_graph( &mut self, fragment: &AstFragment, parent_scope: ParentScope<'a>, ) -> MacroRulesScopeRef<'a>186 pub(crate) fn build_reduced_graph( 187 &mut self, 188 fragment: &AstFragment, 189 parent_scope: ParentScope<'a>, 190 ) -> MacroRulesScopeRef<'a> { 191 collect_definitions(self, fragment, parent_scope.expansion); 192 let mut visitor = BuildReducedGraphVisitor { r: self, parent_scope }; 193 fragment.visit_with(&mut visitor); 194 visitor.parent_scope.macro_rules 195 } 196 build_reduced_graph_external(&mut self, module: Module<'a>)197 pub(crate) fn build_reduced_graph_external(&mut self, module: Module<'a>) { 198 for child in self.tcx.module_children(module.def_id()) { 199 let parent_scope = ParentScope::module(module, self); 200 BuildReducedGraphVisitor { r: self, parent_scope } 201 .build_reduced_graph_for_external_crate_res(child); 202 } 203 } 204 } 205 206 struct BuildReducedGraphVisitor<'a, 'b, 'tcx> { 207 r: &'b mut Resolver<'a, 'tcx>, 208 parent_scope: ParentScope<'a>, 209 } 210 211 impl<'a, 'tcx> AsMut<Resolver<'a, 'tcx>> for BuildReducedGraphVisitor<'a, '_, 'tcx> { as_mut(&mut self) -> &mut Resolver<'a, 'tcx>212 fn as_mut(&mut self) -> &mut Resolver<'a, 'tcx> { 213 self.r 214 } 215 } 216 217 impl<'a, 'b, 'tcx> BuildReducedGraphVisitor<'a, 'b, 'tcx> { resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility218 fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility { 219 self.try_resolve_visibility(vis, true).unwrap_or_else(|err| { 220 self.r.report_vis_error(err); 221 ty::Visibility::Public 222 }) 223 } 224 try_resolve_visibility<'ast>( &mut self, vis: &'ast ast::Visibility, finalize: bool, ) -> Result<ty::Visibility, VisResolutionError<'ast>>225 fn try_resolve_visibility<'ast>( 226 &mut self, 227 vis: &'ast ast::Visibility, 228 finalize: bool, 229 ) -> Result<ty::Visibility, VisResolutionError<'ast>> { 230 let parent_scope = &self.parent_scope; 231 match vis.kind { 232 ast::VisibilityKind::Public => Ok(ty::Visibility::Public), 233 ast::VisibilityKind::Inherited => { 234 Ok(match self.parent_scope.module.kind { 235 // Any inherited visibility resolved directly inside an enum or trait 236 // (i.e. variants, fields, and trait items) inherits from the visibility 237 // of the enum or trait. 238 ModuleKind::Def(DefKind::Enum | DefKind::Trait, def_id, _) => { 239 self.r.visibilities[&def_id.expect_local()] 240 } 241 // Otherwise, the visibility is restricted to the nearest parent `mod` item. 242 _ => ty::Visibility::Restricted( 243 self.parent_scope.module.nearest_parent_mod().expect_local(), 244 ), 245 }) 246 } 247 ast::VisibilityKind::Restricted { ref path, id, .. } => { 248 // Make `PRIVATE_IN_PUBLIC` lint a hard error. 249 self.r.has_pub_restricted = true; 250 // For visibilities we are not ready to provide correct implementation of "uniform 251 // paths" right now, so on 2018 edition we only allow module-relative paths for now. 252 // On 2015 edition visibilities are resolved as crate-relative by default, 253 // so we are prepending a root segment if necessary. 254 let ident = path.segments.get(0).expect("empty path in visibility").ident; 255 let crate_root = if ident.is_path_segment_keyword() { 256 None 257 } else if ident.span.is_rust_2015() { 258 Some(Segment::from_ident(Ident::new( 259 kw::PathRoot, 260 path.span.shrink_to_lo().with_ctxt(ident.span.ctxt()), 261 ))) 262 } else { 263 return Err(VisResolutionError::Relative2018(ident.span, path)); 264 }; 265 266 let segments = crate_root 267 .into_iter() 268 .chain(path.segments.iter().map(|seg| seg.into())) 269 .collect::<Vec<_>>(); 270 let expected_found_error = |res| { 271 Err(VisResolutionError::ExpectedFound( 272 path.span, 273 Segment::names_to_string(&segments), 274 res, 275 )) 276 }; 277 match self.r.resolve_path( 278 &segments, 279 Some(TypeNS), 280 parent_scope, 281 finalize.then(|| Finalize::new(id, path.span)), 282 None, 283 ) { 284 PathResult::Module(ModuleOrUniformRoot::Module(module)) => { 285 let res = module.res().expect("visibility resolved to unnamed block"); 286 if finalize { 287 self.r.record_partial_res(id, PartialRes::new(res)); 288 } 289 if module.is_normal() { 290 match res { 291 Res::Err => Ok(ty::Visibility::Public), 292 _ => { 293 let vis = ty::Visibility::Restricted(res.def_id()); 294 if self.r.is_accessible_from(vis, parent_scope.module) { 295 Ok(vis.expect_local()) 296 } else { 297 Err(VisResolutionError::AncestorOnly(path.span)) 298 } 299 } 300 } 301 } else { 302 expected_found_error(res) 303 } 304 } 305 PathResult::Module(..) => Err(VisResolutionError::ModuleOnly(path.span)), 306 PathResult::NonModule(partial_res) => { 307 expected_found_error(partial_res.expect_full_res()) 308 } 309 PathResult::Failed { span, label, suggestion, .. } => { 310 Err(VisResolutionError::FailedToResolve(span, label, suggestion)) 311 } 312 PathResult::Indeterminate => Err(VisResolutionError::Indeterminate(path.span)), 313 } 314 } 315 } 316 } 317 insert_field_def_ids(&mut self, def_id: LocalDefId, vdata: &ast::VariantData)318 fn insert_field_def_ids(&mut self, def_id: LocalDefId, vdata: &ast::VariantData) { 319 if vdata.fields().iter().any(|field| field.is_placeholder) { 320 // The fields are not expanded yet. 321 return; 322 } 323 let def_ids = vdata.fields().iter().map(|field| self.r.local_def_id(field.id).to_def_id()); 324 self.r.field_def_ids.insert(def_id, self.r.tcx.arena.alloc_from_iter(def_ids)); 325 } 326 insert_field_visibilities_local(&mut self, def_id: DefId, vdata: &ast::VariantData)327 fn insert_field_visibilities_local(&mut self, def_id: DefId, vdata: &ast::VariantData) { 328 let field_vis = vdata 329 .fields() 330 .iter() 331 .map(|field| field.vis.span.until(field.ident.map_or(field.ty.span, |i| i.span))) 332 .collect(); 333 self.r.field_visibility_spans.insert(def_id, field_vis); 334 } 335 block_needs_anonymous_module(&mut self, block: &Block) -> bool336 fn block_needs_anonymous_module(&mut self, block: &Block) -> bool { 337 // If any statements are items, we need to create an anonymous module 338 block 339 .stmts 340 .iter() 341 .any(|statement| matches!(statement.kind, StmtKind::Item(_) | StmtKind::MacCall(_))) 342 } 343 344 // Add an import to the current module. add_import( &mut self, module_path: Vec<Segment>, kind: ImportKind<'a>, span: Span, item: &ast::Item, root_span: Span, root_id: NodeId, vis: ty::Visibility, )345 fn add_import( 346 &mut self, 347 module_path: Vec<Segment>, 348 kind: ImportKind<'a>, 349 span: Span, 350 item: &ast::Item, 351 root_span: Span, 352 root_id: NodeId, 353 vis: ty::Visibility, 354 ) { 355 let current_module = self.parent_scope.module; 356 let import = self.r.arenas.alloc_import(ImportData { 357 kind, 358 parent_scope: self.parent_scope, 359 module_path, 360 imported_module: Cell::new(None), 361 span, 362 use_span: item.span, 363 use_span_with_attributes: item.span_with_attributes(), 364 has_attributes: !item.attrs.is_empty(), 365 root_span, 366 root_id, 367 vis: Cell::new(Some(vis)), 368 used: Cell::new(false), 369 }); 370 371 self.r.indeterminate_imports.push(import); 372 match import.kind { 373 // Don't add unresolved underscore imports to modules 374 ImportKind::Single { target: Ident { name: kw::Underscore, .. }, .. } => {} 375 ImportKind::Single { target, type_ns_only, .. } => { 376 self.r.per_ns(|this, ns| { 377 if !type_ns_only || ns == TypeNS { 378 let key = BindingKey::new(target, ns); 379 let mut resolution = this.resolution(current_module, key).borrow_mut(); 380 resolution.single_imports.insert(import); 381 } 382 }); 383 } 384 // We don't add prelude imports to the globs since they only affect lexical scopes, 385 // which are not relevant to import resolution. 386 ImportKind::Glob { is_prelude: true, .. } => {} 387 ImportKind::Glob { .. } => current_module.globs.borrow_mut().push(import), 388 _ => unreachable!(), 389 } 390 } 391 build_reduced_graph_for_use_tree( &mut self, use_tree: &ast::UseTree, id: NodeId, parent_prefix: &[Segment], nested: bool, item: &Item, vis: ty::Visibility, root_span: Span, )392 fn build_reduced_graph_for_use_tree( 393 &mut self, 394 // This particular use tree 395 use_tree: &ast::UseTree, 396 id: NodeId, 397 parent_prefix: &[Segment], 398 nested: bool, 399 // The whole `use` item 400 item: &Item, 401 vis: ty::Visibility, 402 root_span: Span, 403 ) { 404 debug!( 405 "build_reduced_graph_for_use_tree(parent_prefix={:?}, use_tree={:?}, nested={})", 406 parent_prefix, use_tree, nested 407 ); 408 409 let mut prefix_iter = parent_prefix 410 .iter() 411 .cloned() 412 .chain(use_tree.prefix.segments.iter().map(|seg| seg.into())) 413 .peekable(); 414 415 // On 2015 edition imports are resolved as crate-relative by default, 416 // so prefixes are prepended with crate root segment if necessary. 417 // The root is prepended lazily, when the first non-empty prefix or terminating glob 418 // appears, so imports in braced groups can have roots prepended independently. 419 let is_glob = matches!(use_tree.kind, ast::UseTreeKind::Glob); 420 let crate_root = match prefix_iter.peek() { 421 Some(seg) if !seg.ident.is_path_segment_keyword() && seg.ident.span.is_rust_2015() => { 422 Some(seg.ident.span.ctxt()) 423 } 424 None if is_glob && use_tree.span.is_rust_2015() => Some(use_tree.span.ctxt()), 425 _ => None, 426 } 427 .map(|ctxt| { 428 Segment::from_ident(Ident::new( 429 kw::PathRoot, 430 use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt), 431 )) 432 }); 433 434 let prefix = crate_root.into_iter().chain(prefix_iter).collect::<Vec<_>>(); 435 debug!("build_reduced_graph_for_use_tree: prefix={:?}", prefix); 436 437 let empty_for_self = |prefix: &[Segment]| { 438 prefix.is_empty() || prefix.len() == 1 && prefix[0].ident.name == kw::PathRoot 439 }; 440 match use_tree.kind { 441 ast::UseTreeKind::Simple(rename) => { 442 let mut ident = use_tree.ident(); 443 let mut module_path = prefix; 444 let mut source = module_path.pop().unwrap(); 445 let mut type_ns_only = false; 446 447 self.r.visibilities.insert(self.r.local_def_id(id), vis); 448 449 if nested { 450 // Correctly handle `self` 451 if source.ident.name == kw::SelfLower { 452 type_ns_only = true; 453 454 if empty_for_self(&module_path) { 455 self.r.report_error( 456 use_tree.span, 457 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix, 458 ); 459 return; 460 } 461 462 // Replace `use foo::{ self };` with `use foo;` 463 let self_span = source.ident.span; 464 source = module_path.pop().unwrap(); 465 if rename.is_none() { 466 // Keep the span of `self`, but the name of `foo` 467 ident = Ident { name: source.ident.name, span: self_span }; 468 } 469 } 470 } else { 471 // Disallow `self` 472 if source.ident.name == kw::SelfLower { 473 let parent = module_path.last(); 474 475 let span = match parent { 476 // only `::self` from `use foo::self as bar` 477 Some(seg) => seg.ident.span.shrink_to_hi().to(source.ident.span), 478 None => source.ident.span, 479 }; 480 let span_with_rename = match rename { 481 // only `self as bar` from `use foo::self as bar` 482 Some(rename) => source.ident.span.to(rename.span), 483 None => source.ident.span, 484 }; 485 self.r.report_error( 486 span, 487 ResolutionError::SelfImportsOnlyAllowedWithin { 488 root: parent.is_none(), 489 span_with_rename, 490 }, 491 ); 492 493 // Error recovery: replace `use foo::self;` with `use foo;` 494 if let Some(parent) = module_path.pop() { 495 source = parent; 496 if rename.is_none() { 497 ident = source.ident; 498 } 499 } 500 } 501 502 // Disallow `use $crate;` 503 if source.ident.name == kw::DollarCrate && module_path.is_empty() { 504 let crate_root = self.r.resolve_crate_root(source.ident); 505 let crate_name = match crate_root.kind { 506 ModuleKind::Def(.., name) => name, 507 ModuleKind::Block => unreachable!(), 508 }; 509 // HACK(eddyb) unclear how good this is, but keeping `$crate` 510 // in `source` breaks `tests/ui/imports/import-crate-var.rs`, 511 // while the current crate doesn't have a valid `crate_name`. 512 if crate_name != kw::Empty { 513 // `crate_name` should not be interpreted as relative. 514 module_path.push(Segment::from_ident_and_id( 515 Ident { name: kw::PathRoot, span: source.ident.span }, 516 self.r.next_node_id(), 517 )); 518 source.ident.name = crate_name; 519 } 520 if rename.is_none() { 521 ident.name = crate_name; 522 } 523 524 self.r.tcx.sess.emit_err(errors::CrateImported { span: item.span }); 525 } 526 } 527 528 if ident.name == kw::Crate { 529 self.r.tcx.sess.span_err( 530 ident.span, 531 "crate root imports need to be explicitly named: \ 532 `use crate as name;`", 533 ); 534 } 535 536 let kind = ImportKind::Single { 537 source: source.ident, 538 target: ident, 539 source_bindings: PerNS { 540 type_ns: Cell::new(Err(Determinacy::Undetermined)), 541 value_ns: Cell::new(Err(Determinacy::Undetermined)), 542 macro_ns: Cell::new(Err(Determinacy::Undetermined)), 543 }, 544 target_bindings: PerNS { 545 type_ns: Cell::new(None), 546 value_ns: Cell::new(None), 547 macro_ns: Cell::new(None), 548 }, 549 type_ns_only, 550 nested, 551 id, 552 }; 553 554 self.add_import(module_path, kind, use_tree.span, item, root_span, item.id, vis); 555 } 556 ast::UseTreeKind::Glob => { 557 let kind = ImportKind::Glob { 558 is_prelude: attr::contains_name(&item.attrs, sym::prelude_import), 559 max_vis: Cell::new(None), 560 id, 561 }; 562 self.r.visibilities.insert(self.r.local_def_id(id), vis); 563 self.add_import(prefix, kind, use_tree.span, item, root_span, item.id, vis); 564 } 565 ast::UseTreeKind::Nested(ref items) => { 566 // Ensure there is at most one `self` in the list 567 let self_spans = items 568 .iter() 569 .filter_map(|(use_tree, _)| { 570 if let ast::UseTreeKind::Simple(..) = use_tree.kind { 571 if use_tree.ident().name == kw::SelfLower { 572 return Some(use_tree.span); 573 } 574 } 575 576 None 577 }) 578 .collect::<Vec<_>>(); 579 if self_spans.len() > 1 { 580 let mut e = self.r.into_struct_error( 581 self_spans[0], 582 ResolutionError::SelfImportCanOnlyAppearOnceInTheList, 583 ); 584 585 for other_span in self_spans.iter().skip(1) { 586 e.span_label(*other_span, "another `self` import appears here"); 587 } 588 589 e.emit(); 590 } 591 592 for &(ref tree, id) in items { 593 self.build_reduced_graph_for_use_tree( 594 // This particular use tree 595 tree, id, &prefix, true, // The whole `use` item 596 item, vis, root_span, 597 ); 598 } 599 600 // Empty groups `a::b::{}` are turned into synthetic `self` imports 601 // `a::b::c::{self as _}`, so that their prefixes are correctly 602 // resolved and checked for privacy/stability/etc. 603 if items.is_empty() && !empty_for_self(&prefix) { 604 let new_span = prefix[prefix.len() - 1].ident.span; 605 let tree = ast::UseTree { 606 prefix: ast::Path::from_ident(Ident::new(kw::SelfLower, new_span)), 607 kind: ast::UseTreeKind::Simple(Some(Ident::new(kw::Underscore, new_span))), 608 span: use_tree.span, 609 }; 610 self.build_reduced_graph_for_use_tree( 611 // This particular use tree 612 &tree, 613 id, 614 &prefix, 615 true, 616 // The whole `use` item 617 item, 618 ty::Visibility::Restricted( 619 self.parent_scope.module.nearest_parent_mod().expect_local(), 620 ), 621 root_span, 622 ); 623 } 624 } 625 } 626 } 627 628 /// Constructs the reduced graph for one item. build_reduced_graph_for_item(&mut self, item: &'b Item)629 fn build_reduced_graph_for_item(&mut self, item: &'b Item) { 630 let parent_scope = &self.parent_scope; 631 let parent = parent_scope.module; 632 let expansion = parent_scope.expansion; 633 let ident = item.ident; 634 let sp = item.span; 635 let vis = self.resolve_visibility(&item.vis); 636 let local_def_id = self.r.local_def_id(item.id); 637 let def_id = local_def_id.to_def_id(); 638 639 self.r.visibilities.insert(local_def_id, vis); 640 641 match item.kind { 642 ItemKind::Use(ref use_tree) => { 643 self.build_reduced_graph_for_use_tree( 644 // This particular use tree 645 use_tree, 646 item.id, 647 &[], 648 false, 649 // The whole `use` item 650 item, 651 vis, 652 use_tree.span, 653 ); 654 } 655 656 ItemKind::ExternCrate(orig_name) => { 657 self.build_reduced_graph_for_extern_crate( 658 orig_name, 659 item, 660 local_def_id, 661 vis, 662 parent, 663 ); 664 } 665 666 ItemKind::Mod(..) => { 667 let module = self.r.new_module( 668 Some(parent), 669 ModuleKind::Def(DefKind::Mod, def_id, ident.name), 670 expansion.to_expn_id(), 671 item.span, 672 parent.no_implicit_prelude 673 || attr::contains_name(&item.attrs, sym::no_implicit_prelude), 674 ); 675 self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion)); 676 677 // Descend into the module. 678 self.parent_scope.module = module; 679 } 680 681 // These items live in the value namespace. 682 ItemKind::Static(box ast::StaticItem { mutability, .. }) => { 683 let res = Res::Def(DefKind::Static(mutability), def_id); 684 self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion)); 685 } 686 ItemKind::Const(..) => { 687 let res = Res::Def(DefKind::Const, def_id); 688 self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion)); 689 } 690 ItemKind::Fn(..) => { 691 let res = Res::Def(DefKind::Fn, def_id); 692 self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion)); 693 694 // Functions introducing procedural macros reserve a slot 695 // in the macro namespace as well (see #52225). 696 self.define_macro(item); 697 } 698 699 // These items live in the type namespace. 700 ItemKind::TyAlias(..) => { 701 let res = Res::Def(DefKind::TyAlias, def_id); 702 self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion)); 703 } 704 705 ItemKind::Enum(_, _) => { 706 let module = self.r.new_module( 707 Some(parent), 708 ModuleKind::Def(DefKind::Enum, def_id, ident.name), 709 expansion.to_expn_id(), 710 item.span, 711 parent.no_implicit_prelude, 712 ); 713 self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion)); 714 self.parent_scope.module = module; 715 } 716 717 ItemKind::TraitAlias(..) => { 718 let res = Res::Def(DefKind::TraitAlias, def_id); 719 self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion)); 720 } 721 722 // These items live in both the type and value namespaces. 723 ItemKind::Struct(ref vdata, _) => { 724 // Define a name in the type namespace. 725 let res = Res::Def(DefKind::Struct, def_id); 726 self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion)); 727 728 // Record field names for error reporting. 729 self.insert_field_def_ids(local_def_id, vdata); 730 self.insert_field_visibilities_local(def_id, vdata); 731 732 // If this is a tuple or unit struct, define a name 733 // in the value namespace as well. 734 if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(vdata) { 735 // If the structure is marked as non_exhaustive then lower the visibility 736 // to within the crate. 737 let mut ctor_vis = if vis.is_public() 738 && attr::contains_name(&item.attrs, sym::non_exhaustive) 739 { 740 ty::Visibility::Restricted(CRATE_DEF_ID) 741 } else { 742 vis 743 }; 744 745 let mut ret_fields = Vec::with_capacity(vdata.fields().len()); 746 747 for field in vdata.fields() { 748 // NOTE: The field may be an expansion placeholder, but expansion sets 749 // correct visibilities for unnamed field placeholders specifically, so the 750 // constructor visibility should still be determined correctly. 751 let field_vis = self 752 .try_resolve_visibility(&field.vis, false) 753 .unwrap_or(ty::Visibility::Public); 754 if ctor_vis.is_at_least(field_vis, self.r.tcx) { 755 ctor_vis = field_vis; 756 } 757 ret_fields.push(field_vis.to_def_id()); 758 } 759 let ctor_def_id = self.r.local_def_id(ctor_node_id); 760 let ctor_res = 761 Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id.to_def_id()); 762 self.r.define(parent, ident, ValueNS, (ctor_res, ctor_vis, sp, expansion)); 763 self.r.visibilities.insert(ctor_def_id, ctor_vis); 764 // We need the field visibility spans also for the constructor for E0603. 765 self.insert_field_visibilities_local(ctor_def_id.to_def_id(), vdata); 766 767 self.r 768 .struct_constructors 769 .insert(local_def_id, (ctor_res, ctor_vis.to_def_id(), ret_fields)); 770 } 771 } 772 773 ItemKind::Union(ref vdata, _) => { 774 let res = Res::Def(DefKind::Union, def_id); 775 self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion)); 776 777 // Record field names for error reporting. 778 self.insert_field_def_ids(local_def_id, vdata); 779 self.insert_field_visibilities_local(def_id, vdata); 780 } 781 782 ItemKind::Trait(..) => { 783 // Add all the items within to a new module. 784 let module = self.r.new_module( 785 Some(parent), 786 ModuleKind::Def(DefKind::Trait, def_id, ident.name), 787 expansion.to_expn_id(), 788 item.span, 789 parent.no_implicit_prelude, 790 ); 791 self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion)); 792 self.parent_scope.module = module; 793 } 794 795 // These items do not add names to modules. 796 ItemKind::Impl(box Impl { of_trait: Some(..), .. }) => { 797 self.r.trait_impl_items.insert(local_def_id); 798 } 799 ItemKind::Impl { .. } | ItemKind::ForeignMod(..) | ItemKind::GlobalAsm(..) => {} 800 801 ItemKind::MacroDef(..) | ItemKind::MacCall(_) => unreachable!(), 802 } 803 } 804 build_reduced_graph_for_extern_crate( &mut self, orig_name: Option<Symbol>, item: &Item, local_def_id: LocalDefId, vis: ty::Visibility, parent: Module<'a>, )805 fn build_reduced_graph_for_extern_crate( 806 &mut self, 807 orig_name: Option<Symbol>, 808 item: &Item, 809 local_def_id: LocalDefId, 810 vis: ty::Visibility, 811 parent: Module<'a>, 812 ) { 813 let ident = item.ident; 814 let sp = item.span; 815 let parent_scope = self.parent_scope; 816 let expansion = parent_scope.expansion; 817 818 let (used, module, binding) = if orig_name.is_none() && ident.name == kw::SelfLower { 819 self.r 820 .tcx 821 .sess 822 .struct_span_err(item.span, "`extern crate self;` requires renaming") 823 .span_suggestion( 824 item.span, 825 "rename the `self` crate to be able to import it", 826 "extern crate self as name;", 827 Applicability::HasPlaceholders, 828 ) 829 .emit(); 830 return; 831 } else if orig_name == Some(kw::SelfLower) { 832 Some(self.r.graph_root) 833 } else { 834 let tcx = self.r.tcx; 835 let crate_id = self.r.crate_loader(|c| { 836 c.process_extern_crate(item, local_def_id, &tcx.definitions_untracked()) 837 }); 838 crate_id.map(|crate_id| { 839 self.r.extern_crate_map.insert(local_def_id, crate_id); 840 self.r.expect_module(crate_id.as_def_id()) 841 }) 842 } 843 .map(|module| { 844 let used = self.process_macro_use_imports(item, module); 845 let vis = ty::Visibility::<LocalDefId>::Public; 846 let binding = (module, vis, sp, expansion).to_name_binding(self.r.arenas); 847 (used, Some(ModuleOrUniformRoot::Module(module)), binding) 848 }) 849 .unwrap_or((true, None, self.r.dummy_binding)); 850 let import = self.r.arenas.alloc_import(ImportData { 851 kind: ImportKind::ExternCrate { source: orig_name, target: ident, id: item.id }, 852 root_id: item.id, 853 parent_scope: self.parent_scope, 854 imported_module: Cell::new(module), 855 has_attributes: !item.attrs.is_empty(), 856 use_span_with_attributes: item.span_with_attributes(), 857 use_span: item.span, 858 root_span: item.span, 859 span: item.span, 860 module_path: Vec::new(), 861 vis: Cell::new(Some(vis)), 862 used: Cell::new(used), 863 }); 864 self.r.potentially_unused_imports.push(import); 865 let imported_binding = self.r.import(binding, import); 866 if parent == self.r.graph_root { 867 if let Some(entry) = self.r.extern_prelude.get(&ident.normalize_to_macros_2_0()) { 868 if expansion != LocalExpnId::ROOT 869 && orig_name.is_some() 870 && entry.extern_crate_item.is_none() 871 { 872 let msg = "macro-expanded `extern crate` items cannot \ 873 shadow names passed with `--extern`"; 874 self.r.tcx.sess.span_err(item.span, msg); 875 // `return` is intended to discard this binding because it's an 876 // unregistered ambiguity error which would result in a panic 877 // caused by inconsistency `path_res` 878 // more details: https://github.com/rust-lang/rust/pull/111761 879 return; 880 } 881 } 882 let entry = self.r.extern_prelude.entry(ident.normalize_to_macros_2_0()).or_insert( 883 ExternPreludeEntry { extern_crate_item: None, introduced_by_item: true }, 884 ); 885 entry.extern_crate_item = Some(imported_binding); 886 if orig_name.is_some() { 887 entry.introduced_by_item = true; 888 } 889 } 890 self.r.define(parent, ident, TypeNS, imported_binding); 891 } 892 893 /// Constructs the reduced graph for one foreign item. build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem)894 fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem) { 895 let local_def_id = self.r.local_def_id(item.id); 896 let def_id = local_def_id.to_def_id(); 897 let (def_kind, ns) = match item.kind { 898 ForeignItemKind::Fn(..) => (DefKind::Fn, ValueNS), 899 ForeignItemKind::Static(_, mt, _) => (DefKind::Static(mt), ValueNS), 900 ForeignItemKind::TyAlias(..) => (DefKind::ForeignTy, TypeNS), 901 ForeignItemKind::MacCall(_) => unreachable!(), 902 }; 903 let parent = self.parent_scope.module; 904 let expansion = self.parent_scope.expansion; 905 let vis = self.resolve_visibility(&item.vis); 906 let res = Res::Def(def_kind, def_id); 907 self.r.define(parent, item.ident, ns, (res, vis, item.span, expansion)); 908 self.r.visibilities.insert(local_def_id, vis); 909 } 910 build_reduced_graph_for_block(&mut self, block: &Block)911 fn build_reduced_graph_for_block(&mut self, block: &Block) { 912 let parent = self.parent_scope.module; 913 let expansion = self.parent_scope.expansion; 914 if self.block_needs_anonymous_module(block) { 915 let module = self.r.new_module( 916 Some(parent), 917 ModuleKind::Block, 918 expansion.to_expn_id(), 919 block.span, 920 parent.no_implicit_prelude, 921 ); 922 self.r.block_map.insert(block.id, module); 923 self.parent_scope.module = module; // Descend into the block. 924 } 925 } 926 927 /// Builds the reduced graph for a single item in an external crate. build_reduced_graph_for_external_crate_res(&mut self, child: &ModChild)928 fn build_reduced_graph_for_external_crate_res(&mut self, child: &ModChild) { 929 let parent = self.parent_scope.module; 930 let ModChild { ident, res, vis, ref reexport_chain } = *child; 931 let span = self.r.def_span( 932 reexport_chain 933 .first() 934 .and_then(|reexport| reexport.id()) 935 .unwrap_or_else(|| res.def_id()), 936 ); 937 let res = res.expect_non_local(); 938 let expansion = self.parent_scope.expansion; 939 // Record primary definitions. 940 match res { 941 Res::Def(DefKind::Mod | DefKind::Enum | DefKind::Trait, def_id) => { 942 let module = self.r.expect_module(def_id); 943 self.r.define(parent, ident, TypeNS, (module, vis, span, expansion)); 944 } 945 Res::Def( 946 DefKind::Struct 947 | DefKind::Union 948 | DefKind::Variant 949 | DefKind::TyAlias 950 | DefKind::ForeignTy 951 | DefKind::OpaqueTy 952 | DefKind::ImplTraitPlaceholder 953 | DefKind::TraitAlias 954 | DefKind::AssocTy, 955 _, 956 ) 957 | Res::PrimTy(..) 958 | Res::ToolMod => self.r.define(parent, ident, TypeNS, (res, vis, span, expansion)), 959 Res::Def( 960 DefKind::Fn 961 | DefKind::AssocFn 962 | DefKind::Static(_) 963 | DefKind::Const 964 | DefKind::AssocConst 965 | DefKind::Ctor(..), 966 _, 967 ) => self.r.define(parent, ident, ValueNS, (res, vis, span, expansion)), 968 Res::Def(DefKind::Macro(..), _) | Res::NonMacroAttr(..) => { 969 self.r.define(parent, ident, MacroNS, (res, vis, span, expansion)) 970 } 971 Res::Def( 972 DefKind::TyParam 973 | DefKind::ConstParam 974 | DefKind::ExternCrate 975 | DefKind::Use 976 | DefKind::ForeignMod 977 | DefKind::AnonConst 978 | DefKind::InlineConst 979 | DefKind::Field 980 | DefKind::LifetimeParam 981 | DefKind::GlobalAsm 982 | DefKind::Closure 983 | DefKind::Impl { .. } 984 | DefKind::Generator, 985 _, 986 ) 987 | Res::Local(..) 988 | Res::SelfTyParam { .. } 989 | Res::SelfTyAlias { .. } 990 | Res::SelfCtor(..) 991 | Res::Err => bug!("unexpected resolution: {:?}", res), 992 } 993 } 994 add_macro_use_binding( &mut self, name: Symbol, binding: NameBinding<'a>, span: Span, allow_shadowing: bool, )995 fn add_macro_use_binding( 996 &mut self, 997 name: Symbol, 998 binding: NameBinding<'a>, 999 span: Span, 1000 allow_shadowing: bool, 1001 ) { 1002 if self.r.macro_use_prelude.insert(name, binding).is_some() && !allow_shadowing { 1003 let msg = format!("`{}` is already in scope", name); 1004 let note = 1005 "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)"; 1006 self.r.tcx.sess.struct_span_err(span, msg).note(note).emit(); 1007 } 1008 } 1009 1010 /// Returns `true` if we should consider the underlying `extern crate` to be used. process_macro_use_imports(&mut self, item: &Item, module: Module<'a>) -> bool1011 fn process_macro_use_imports(&mut self, item: &Item, module: Module<'a>) -> bool { 1012 let mut import_all = None; 1013 let mut single_imports = Vec::new(); 1014 for attr in &item.attrs { 1015 if attr.has_name(sym::macro_use) { 1016 if self.parent_scope.module.parent.is_some() { 1017 struct_span_err!( 1018 self.r.tcx.sess, 1019 item.span, 1020 E0468, 1021 "an `extern crate` loading macros must be at the crate root" 1022 ) 1023 .emit(); 1024 } 1025 if let ItemKind::ExternCrate(Some(orig_name)) = item.kind { 1026 if orig_name == kw::SelfLower { 1027 self.r 1028 .tcx 1029 .sess 1030 .emit_err(errors::MacroUseExternCrateSelf { span: attr.span }); 1031 } 1032 } 1033 let ill_formed = |span| { 1034 struct_span_err!(self.r.tcx.sess, span, E0466, "bad macro import").emit(); 1035 }; 1036 match attr.meta() { 1037 Some(meta) => match meta.kind { 1038 MetaItemKind::Word => { 1039 import_all = Some(meta.span); 1040 break; 1041 } 1042 MetaItemKind::List(nested_metas) => { 1043 for nested_meta in nested_metas { 1044 match nested_meta.ident() { 1045 Some(ident) if nested_meta.is_word() => { 1046 single_imports.push(ident) 1047 } 1048 _ => ill_formed(nested_meta.span()), 1049 } 1050 } 1051 } 1052 MetaItemKind::NameValue(..) => ill_formed(meta.span), 1053 }, 1054 None => ill_formed(attr.span), 1055 } 1056 } 1057 } 1058 1059 let macro_use_import = |this: &Self, span| { 1060 this.r.arenas.alloc_import(ImportData { 1061 kind: ImportKind::MacroUse, 1062 root_id: item.id, 1063 parent_scope: this.parent_scope, 1064 imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))), 1065 use_span_with_attributes: item.span_with_attributes(), 1066 has_attributes: !item.attrs.is_empty(), 1067 use_span: item.span, 1068 root_span: span, 1069 span, 1070 module_path: Vec::new(), 1071 vis: Cell::new(Some(ty::Visibility::Restricted(CRATE_DEF_ID))), 1072 used: Cell::new(false), 1073 }) 1074 }; 1075 1076 let allow_shadowing = self.parent_scope.expansion == LocalExpnId::ROOT; 1077 if let Some(span) = import_all { 1078 let import = macro_use_import(self, span); 1079 self.r.potentially_unused_imports.push(import); 1080 module.for_each_child(self, |this, ident, ns, binding| { 1081 if ns == MacroNS { 1082 let imported_binding = this.r.import(binding, import); 1083 this.add_macro_use_binding(ident.name, imported_binding, span, allow_shadowing); 1084 } 1085 }); 1086 } else { 1087 for ident in single_imports.iter().cloned() { 1088 let result = self.r.maybe_resolve_ident_in_module( 1089 ModuleOrUniformRoot::Module(module), 1090 ident, 1091 MacroNS, 1092 &self.parent_scope, 1093 ); 1094 if let Ok(binding) = result { 1095 let import = macro_use_import(self, ident.span); 1096 self.r.potentially_unused_imports.push(import); 1097 let imported_binding = self.r.import(binding, import); 1098 self.add_macro_use_binding( 1099 ident.name, 1100 imported_binding, 1101 ident.span, 1102 allow_shadowing, 1103 ); 1104 } else { 1105 struct_span_err!( 1106 self.r.tcx.sess, 1107 ident.span, 1108 E0469, 1109 "imported macro not found" 1110 ) 1111 .emit(); 1112 } 1113 } 1114 } 1115 import_all.is_some() || !single_imports.is_empty() 1116 } 1117 1118 /// Returns `true` if this attribute list contains `macro_use`. contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool1119 fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool { 1120 for attr in attrs { 1121 if attr.has_name(sym::macro_escape) { 1122 let msg = "`#[macro_escape]` is a deprecated synonym for `#[macro_use]`"; 1123 let mut err = self.r.tcx.sess.struct_span_warn(attr.span, msg); 1124 if let ast::AttrStyle::Inner = attr.style { 1125 err.help("try an outer attribute: `#[macro_use]`").emit(); 1126 } else { 1127 err.emit(); 1128 } 1129 } else if !attr.has_name(sym::macro_use) { 1130 continue; 1131 } 1132 1133 if !attr.is_word() { 1134 self.r 1135 .tcx 1136 .sess 1137 .span_err(attr.span, "arguments to `macro_use` are not allowed here"); 1138 } 1139 return true; 1140 } 1141 1142 false 1143 } 1144 visit_invoc(&mut self, id: NodeId) -> LocalExpnId1145 fn visit_invoc(&mut self, id: NodeId) -> LocalExpnId { 1146 let invoc_id = id.placeholder_to_expn_id(); 1147 let old_parent_scope = self.r.invocation_parent_scopes.insert(invoc_id, self.parent_scope); 1148 assert!(old_parent_scope.is_none(), "invocation data is reset for an invocation"); 1149 invoc_id 1150 } 1151 1152 /// Visit invocation in context in which it can emit a named item (possibly `macro_rules`) 1153 /// directly into its parent scope's module. visit_invoc_in_module(&mut self, id: NodeId) -> MacroRulesScopeRef<'a>1154 fn visit_invoc_in_module(&mut self, id: NodeId) -> MacroRulesScopeRef<'a> { 1155 let invoc_id = self.visit_invoc(id); 1156 self.parent_scope.module.unexpanded_invocations.borrow_mut().insert(invoc_id); 1157 self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Invocation(invoc_id)) 1158 } 1159 proc_macro_stub(&self, item: &ast::Item) -> Option<(MacroKind, Ident, Span)>1160 fn proc_macro_stub(&self, item: &ast::Item) -> Option<(MacroKind, Ident, Span)> { 1161 if attr::contains_name(&item.attrs, sym::proc_macro) { 1162 return Some((MacroKind::Bang, item.ident, item.span)); 1163 } else if attr::contains_name(&item.attrs, sym::proc_macro_attribute) { 1164 return Some((MacroKind::Attr, item.ident, item.span)); 1165 } else if let Some(attr) = attr::find_by_name(&item.attrs, sym::proc_macro_derive) { 1166 if let Some(nested_meta) = attr.meta_item_list().and_then(|list| list.get(0).cloned()) { 1167 if let Some(ident) = nested_meta.ident() { 1168 return Some((MacroKind::Derive, ident, ident.span)); 1169 } 1170 } 1171 } 1172 None 1173 } 1174 1175 // Mark the given macro as unused unless its name starts with `_`. 1176 // Macro uses will remove items from this set, and the remaining 1177 // items will be reported as `unused_macros`. insert_unused_macro( &mut self, ident: Ident, def_id: LocalDefId, node_id: NodeId, rule_spans: &[(usize, Span)], )1178 fn insert_unused_macro( 1179 &mut self, 1180 ident: Ident, 1181 def_id: LocalDefId, 1182 node_id: NodeId, 1183 rule_spans: &[(usize, Span)], 1184 ) { 1185 if !ident.as_str().starts_with('_') { 1186 self.r.unused_macros.insert(def_id, (node_id, ident)); 1187 for (rule_i, rule_span) in rule_spans.iter() { 1188 self.r.unused_macro_rules.insert((def_id, *rule_i), (ident, *rule_span)); 1189 } 1190 } 1191 } 1192 define_macro(&mut self, item: &ast::Item) -> MacroRulesScopeRef<'a>1193 fn define_macro(&mut self, item: &ast::Item) -> MacroRulesScopeRef<'a> { 1194 let parent_scope = self.parent_scope; 1195 let expansion = parent_scope.expansion; 1196 let def_id = self.r.local_def_id(item.id); 1197 let (ext, ident, span, macro_rules, rule_spans) = match &item.kind { 1198 ItemKind::MacroDef(def) => { 1199 let (ext, rule_spans) = self.r.compile_macro(item, self.r.tcx.sess.edition()); 1200 let ext = Lrc::new(ext); 1201 (ext, item.ident, item.span, def.macro_rules, rule_spans) 1202 } 1203 ItemKind::Fn(..) => match self.proc_macro_stub(item) { 1204 Some((macro_kind, ident, span)) => { 1205 self.r.proc_macro_stubs.insert(def_id); 1206 (self.r.dummy_ext(macro_kind), ident, span, false, Vec::new()) 1207 } 1208 None => return parent_scope.macro_rules, 1209 }, 1210 _ => unreachable!(), 1211 }; 1212 1213 let res = Res::Def(DefKind::Macro(ext.macro_kind()), def_id.to_def_id()); 1214 self.r.macro_map.insert(def_id.to_def_id(), MacroData { ext, macro_rules }); 1215 self.r.local_macro_def_scopes.insert(def_id, parent_scope.module); 1216 1217 if macro_rules { 1218 let ident = ident.normalize_to_macros_2_0(); 1219 self.r.macro_names.insert(ident); 1220 let is_macro_export = attr::contains_name(&item.attrs, sym::macro_export); 1221 let vis = if is_macro_export { 1222 ty::Visibility::Public 1223 } else { 1224 ty::Visibility::Restricted(CRATE_DEF_ID) 1225 }; 1226 let binding = (res, vis, span, expansion).to_name_binding(self.r.arenas); 1227 self.r.set_binding_parent_module(binding, parent_scope.module); 1228 self.r.all_macro_rules.insert(ident.name, res); 1229 if is_macro_export { 1230 let import = self.r.arenas.alloc_import(ImportData { 1231 kind: ImportKind::MacroExport, 1232 root_id: item.id, 1233 parent_scope: self.parent_scope, 1234 imported_module: Cell::new(None), 1235 has_attributes: false, 1236 use_span_with_attributes: span, 1237 use_span: span, 1238 root_span: span, 1239 span: span, 1240 module_path: Vec::new(), 1241 vis: Cell::new(Some(vis)), 1242 used: Cell::new(true), 1243 }); 1244 let import_binding = self.r.import(binding, import); 1245 self.r.define(self.r.graph_root, ident, MacroNS, import_binding); 1246 } else { 1247 self.r.check_reserved_macro_name(ident, res); 1248 self.insert_unused_macro(ident, def_id, item.id, &rule_spans); 1249 } 1250 self.r.visibilities.insert(def_id, vis); 1251 let scope = self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Binding( 1252 self.r.arenas.alloc_macro_rules_binding(MacroRulesBinding { 1253 parent_macro_rules_scope: parent_scope.macro_rules, 1254 binding, 1255 ident, 1256 }), 1257 )); 1258 self.r.macro_rules_scopes.insert(def_id, scope); 1259 scope 1260 } else { 1261 let module = parent_scope.module; 1262 let vis = match item.kind { 1263 // Visibilities must not be resolved non-speculatively twice 1264 // and we already resolved this one as a `fn` item visibility. 1265 ItemKind::Fn(..) => { 1266 self.try_resolve_visibility(&item.vis, false).unwrap_or(ty::Visibility::Public) 1267 } 1268 _ => self.resolve_visibility(&item.vis), 1269 }; 1270 if !vis.is_public() { 1271 self.insert_unused_macro(ident, def_id, item.id, &rule_spans); 1272 } 1273 self.r.define(module, ident, MacroNS, (res, vis, span, expansion)); 1274 self.r.visibilities.insert(def_id, vis); 1275 self.parent_scope.macro_rules 1276 } 1277 } 1278 } 1279 1280 macro_rules! method { 1281 ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => { 1282 fn $visit(&mut self, node: &'b $ty) { 1283 if let $invoc(..) = node.kind { 1284 self.visit_invoc(node.id); 1285 } else { 1286 visit::$walk(self, node); 1287 } 1288 } 1289 }; 1290 } 1291 1292 impl<'a, 'b, 'tcx> Visitor<'b> for BuildReducedGraphVisitor<'a, 'b, 'tcx> { 1293 method!(visit_expr: ast::Expr, ast::ExprKind::MacCall, walk_expr); 1294 method!(visit_pat: ast::Pat, ast::PatKind::MacCall, walk_pat); 1295 method!(visit_ty: ast::Ty, ast::TyKind::MacCall, walk_ty); 1296 visit_item(&mut self, item: &'b Item)1297 fn visit_item(&mut self, item: &'b Item) { 1298 let orig_module_scope = self.parent_scope.module; 1299 self.parent_scope.macro_rules = match item.kind { 1300 ItemKind::MacroDef(..) => { 1301 let macro_rules_scope = self.define_macro(item); 1302 visit::walk_item(self, item); 1303 macro_rules_scope 1304 } 1305 ItemKind::MacCall(..) => { 1306 let macro_rules_scope = self.visit_invoc_in_module(item.id); 1307 visit::walk_item(self, item); 1308 macro_rules_scope 1309 } 1310 _ => { 1311 let orig_macro_rules_scope = self.parent_scope.macro_rules; 1312 self.build_reduced_graph_for_item(item); 1313 visit::walk_item(self, item); 1314 match item.kind { 1315 ItemKind::Mod(..) if self.contains_macro_use(&item.attrs) => { 1316 self.parent_scope.macro_rules 1317 } 1318 _ => orig_macro_rules_scope, 1319 } 1320 } 1321 }; 1322 self.parent_scope.module = orig_module_scope; 1323 } 1324 visit_stmt(&mut self, stmt: &'b ast::Stmt)1325 fn visit_stmt(&mut self, stmt: &'b ast::Stmt) { 1326 if let ast::StmtKind::MacCall(..) = stmt.kind { 1327 self.parent_scope.macro_rules = self.visit_invoc_in_module(stmt.id); 1328 } else { 1329 visit::walk_stmt(self, stmt); 1330 } 1331 } 1332 visit_foreign_item(&mut self, foreign_item: &'b ForeignItem)1333 fn visit_foreign_item(&mut self, foreign_item: &'b ForeignItem) { 1334 if let ForeignItemKind::MacCall(_) = foreign_item.kind { 1335 self.visit_invoc_in_module(foreign_item.id); 1336 return; 1337 } 1338 1339 self.build_reduced_graph_for_foreign_item(foreign_item); 1340 visit::walk_foreign_item(self, foreign_item); 1341 } 1342 visit_block(&mut self, block: &'b Block)1343 fn visit_block(&mut self, block: &'b Block) { 1344 let orig_current_module = self.parent_scope.module; 1345 let orig_current_macro_rules_scope = self.parent_scope.macro_rules; 1346 self.build_reduced_graph_for_block(block); 1347 visit::walk_block(self, block); 1348 self.parent_scope.module = orig_current_module; 1349 self.parent_scope.macro_rules = orig_current_macro_rules_scope; 1350 } 1351 visit_assoc_item(&mut self, item: &'b AssocItem, ctxt: AssocCtxt)1352 fn visit_assoc_item(&mut self, item: &'b AssocItem, ctxt: AssocCtxt) { 1353 if let AssocItemKind::MacCall(_) = item.kind { 1354 match ctxt { 1355 AssocCtxt::Trait => { 1356 self.visit_invoc_in_module(item.id); 1357 } 1358 AssocCtxt::Impl => { 1359 self.visit_invoc(item.id); 1360 } 1361 } 1362 return; 1363 } 1364 1365 let vis = self.resolve_visibility(&item.vis); 1366 let local_def_id = self.r.local_def_id(item.id); 1367 let def_id = local_def_id.to_def_id(); 1368 1369 if !(ctxt == AssocCtxt::Impl 1370 && matches!(item.vis.kind, ast::VisibilityKind::Inherited) 1371 && self.r.trait_impl_items.contains(&self.r.tcx.local_parent(local_def_id))) 1372 { 1373 // Trait impl item visibility is inherited from its trait when not specified 1374 // explicitly. In that case we cannot determine it here in early resolve, 1375 // so we leave a hole in the visibility table to be filled later. 1376 self.r.visibilities.insert(local_def_id, vis); 1377 } 1378 1379 if ctxt == AssocCtxt::Trait { 1380 let (def_kind, ns) = match item.kind { 1381 AssocItemKind::Const(..) => (DefKind::AssocConst, ValueNS), 1382 AssocItemKind::Fn(box Fn { ref sig, .. }) => { 1383 if sig.decl.has_self() { 1384 self.r.has_self.insert(local_def_id); 1385 } 1386 (DefKind::AssocFn, ValueNS) 1387 } 1388 AssocItemKind::Type(..) => (DefKind::AssocTy, TypeNS), 1389 AssocItemKind::MacCall(_) => bug!(), // handled above 1390 }; 1391 1392 let parent = self.parent_scope.module; 1393 let expansion = self.parent_scope.expansion; 1394 let res = Res::Def(def_kind, def_id); 1395 self.r.define(parent, item.ident, ns, (res, vis, item.span, expansion)); 1396 } 1397 1398 visit::walk_assoc_item(self, item, ctxt); 1399 } 1400 visit_attribute(&mut self, attr: &'b ast::Attribute)1401 fn visit_attribute(&mut self, attr: &'b ast::Attribute) { 1402 if !attr.is_doc_comment() && attr::is_builtin_attr(attr) { 1403 self.r 1404 .builtin_attrs 1405 .push((attr.get_normal_item().path.segments[0].ident, self.parent_scope)); 1406 } 1407 visit::walk_attribute(self, attr); 1408 } 1409 visit_arm(&mut self, arm: &'b ast::Arm)1410 fn visit_arm(&mut self, arm: &'b ast::Arm) { 1411 if arm.is_placeholder { 1412 self.visit_invoc(arm.id); 1413 } else { 1414 visit::walk_arm(self, arm); 1415 } 1416 } 1417 visit_expr_field(&mut self, f: &'b ast::ExprField)1418 fn visit_expr_field(&mut self, f: &'b ast::ExprField) { 1419 if f.is_placeholder { 1420 self.visit_invoc(f.id); 1421 } else { 1422 visit::walk_expr_field(self, f); 1423 } 1424 } 1425 visit_pat_field(&mut self, fp: &'b ast::PatField)1426 fn visit_pat_field(&mut self, fp: &'b ast::PatField) { 1427 if fp.is_placeholder { 1428 self.visit_invoc(fp.id); 1429 } else { 1430 visit::walk_pat_field(self, fp); 1431 } 1432 } 1433 visit_generic_param(&mut self, param: &'b ast::GenericParam)1434 fn visit_generic_param(&mut self, param: &'b ast::GenericParam) { 1435 if param.is_placeholder { 1436 self.visit_invoc(param.id); 1437 } else { 1438 visit::walk_generic_param(self, param); 1439 } 1440 } 1441 visit_param(&mut self, p: &'b ast::Param)1442 fn visit_param(&mut self, p: &'b ast::Param) { 1443 if p.is_placeholder { 1444 self.visit_invoc(p.id); 1445 } else { 1446 visit::walk_param(self, p); 1447 } 1448 } 1449 visit_field_def(&mut self, sf: &'b ast::FieldDef)1450 fn visit_field_def(&mut self, sf: &'b ast::FieldDef) { 1451 if sf.is_placeholder { 1452 self.visit_invoc(sf.id); 1453 } else { 1454 let vis = self.resolve_visibility(&sf.vis); 1455 self.r.visibilities.insert(self.r.local_def_id(sf.id), vis); 1456 visit::walk_field_def(self, sf); 1457 } 1458 } 1459 1460 // Constructs the reduced graph for one variant. Variants exist in the 1461 // type and value namespaces. visit_variant(&mut self, variant: &'b ast::Variant)1462 fn visit_variant(&mut self, variant: &'b ast::Variant) { 1463 if variant.is_placeholder { 1464 self.visit_invoc_in_module(variant.id); 1465 return; 1466 } 1467 1468 let parent = self.parent_scope.module; 1469 let expn_id = self.parent_scope.expansion; 1470 let ident = variant.ident; 1471 1472 // Define a name in the type namespace. 1473 let def_id = self.r.local_def_id(variant.id); 1474 let res = Res::Def(DefKind::Variant, def_id.to_def_id()); 1475 let vis = self.resolve_visibility(&variant.vis); 1476 self.r.define(parent, ident, TypeNS, (res, vis, variant.span, expn_id)); 1477 self.r.visibilities.insert(def_id, vis); 1478 1479 // If the variant is marked as non_exhaustive then lower the visibility to within the crate. 1480 let ctor_vis = 1481 if vis.is_public() && attr::contains_name(&variant.attrs, sym::non_exhaustive) { 1482 ty::Visibility::Restricted(CRATE_DEF_ID) 1483 } else { 1484 vis 1485 }; 1486 1487 // Define a constructor name in the value namespace. 1488 if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(&variant.data) { 1489 let ctor_def_id = self.r.local_def_id(ctor_node_id); 1490 let ctor_res = 1491 Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id.to_def_id()); 1492 self.r.define(parent, ident, ValueNS, (ctor_res, ctor_vis, variant.span, expn_id)); 1493 self.r.visibilities.insert(ctor_def_id, ctor_vis); 1494 } 1495 1496 // Record field names for error reporting. 1497 self.insert_field_def_ids(def_id, &variant.data); 1498 self.insert_field_visibilities_local(def_id.to_def_id(), &variant.data); 1499 1500 visit::walk_variant(self, variant); 1501 } 1502 visit_crate(&mut self, krate: &'b ast::Crate)1503 fn visit_crate(&mut self, krate: &'b ast::Crate) { 1504 if krate.is_placeholder { 1505 self.visit_invoc_in_module(krate.id); 1506 } else { 1507 visit::walk_crate(self, krate); 1508 self.contains_macro_use(&krate.attrs); 1509 } 1510 } 1511 } 1512