1
Fork 0

Rollup merge of #138924 - nnethercote:less-kw-Empty-3, r=compiler-errors

Reduce `kw::Empty` usage, part 3

Remove some more `kw::Empty` uses, in support of #137978.

r? `@davidtwco`
This commit is contained in:
Matthias Krüger 2025-03-25 18:09:07 +01:00 committed by GitHub
commit ffc571797b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 66 additions and 46 deletions

View file

@ -5,7 +5,7 @@ use rustc_attr_data_structures::{
StableSince, UnstableReason, VERSION_PLACEHOLDER, StableSince, UnstableReason, VERSION_PLACEHOLDER,
}; };
use rustc_errors::ErrorGuaranteed; use rustc_errors::ErrorGuaranteed;
use rustc_span::{Span, Symbol, kw, sym}; use rustc_span::{Span, Symbol, sym};
use super::util::parse_version; use super::util::parse_version;
use super::{AcceptMapping, AttributeParser, SingleAttributeParser}; use super::{AcceptMapping, AttributeParser, SingleAttributeParser};
@ -61,11 +61,7 @@ impl AttributeParser for StabilityParser {
}), }),
(&[sym::rustc_allowed_through_unstable_modules], |this, cx, args| { (&[sym::rustc_allowed_through_unstable_modules], |this, cx, args| {
reject_outside_std!(cx); reject_outside_std!(cx);
this.allowed_through_unstable_modules = this.allowed_through_unstable_modules = args.name_value().and_then(|i| i.value_as_str())
Some(match args.name_value().and_then(|i| i.value_as_str()) {
Some(msg) => msg,
None => kw::Empty,
});
}), }),
]; ];

View file

@ -103,7 +103,7 @@ impl MultiItemModifier for Expander {
fn dummy_annotatable() -> Annotatable { fn dummy_annotatable() -> Annotatable {
Annotatable::GenericParam(ast::GenericParam { Annotatable::GenericParam(ast::GenericParam {
id: ast::DUMMY_NODE_ID, id: ast::DUMMY_NODE_ID,
ident: Ident::empty(), ident: Ident::dummy(),
attrs: Default::default(), attrs: Default::default(),
bounds: Default::default(), bounds: Default::default(),
is_placeholder: false, is_placeholder: false,

View file

@ -14,7 +14,7 @@ Erroneous code example:
#![unstable(feature = "foo_module", reason = "...", issue = "123")] #![unstable(feature = "foo_module", reason = "...", issue = "123")]
#[rustc_allowed_through_unstable_modules] #[rustc_allowed_through_unstable_modules = "deprecation message"]
// #[stable(feature = "foo", since = "1.0")] // #[stable(feature = "foo", since = "1.0")]
struct Foo; struct Foo;
// ^^^ error: `rustc_allowed_through_unstable_modules` attribute must be // ^^^ error: `rustc_allowed_through_unstable_modules` attribute must be

View file

@ -7,7 +7,7 @@ use rustc_parse_format::{ParseMode, Parser, Piece};
use rustc_session::lint::FutureIncompatibilityReason; use rustc_session::lint::FutureIncompatibilityReason;
use rustc_session::{declare_lint, declare_lint_pass}; use rustc_session::{declare_lint, declare_lint_pass};
use rustc_span::edition::Edition; use rustc_span::edition::Edition;
use rustc_span::{InnerSpan, Span, Symbol, hygiene, kw, sym}; use rustc_span::{InnerSpan, Span, Symbol, hygiene, sym};
use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::infer::InferCtxtExt;
use crate::lints::{NonFmtPanicBraces, NonFmtPanicUnused}; use crate::lints::{NonFmtPanicBraces, NonFmtPanicUnused};
@ -167,7 +167,7 @@ fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tc
.get_diagnostic_item(sym::Debug) .get_diagnostic_item(sym::Debug)
.is_some_and(|t| infcx.type_implements_trait(t, [ty], param_env).may_apply()); .is_some_and(|t| infcx.type_implements_trait(t, [ty], param_env).may_apply());
let suggest_panic_any = !is_str && panic == sym::std_panic_macro; let suggest_panic_any = !is_str && panic == Some(sym::std_panic_macro);
let fmt_applicability = if suggest_panic_any { let fmt_applicability = if suggest_panic_any {
// If we can use panic_any, use that as the MachineApplicable suggestion. // If we can use panic_any, use that as the MachineApplicable suggestion.
@ -297,10 +297,13 @@ fn find_delimiters(cx: &LateContext<'_>, span: Span) -> Option<(Span, Span, char
)) ))
} }
fn panic_call<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>) -> (Span, Symbol, Symbol) { fn panic_call<'tcx>(
cx: &LateContext<'tcx>,
f: &'tcx hir::Expr<'tcx>,
) -> (Span, Option<Symbol>, Symbol) {
let mut expn = f.span.ctxt().outer_expn_data(); let mut expn = f.span.ctxt().outer_expn_data();
let mut panic_macro = kw::Empty; let mut panic_macro = None;
// Unwrap more levels of macro expansion, as panic_2015!() // Unwrap more levels of macro expansion, as panic_2015!()
// was likely expanded from panic!() and possibly from // was likely expanded from panic!() and possibly from
@ -320,7 +323,7 @@ fn panic_call<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>) -> (Span,
break; break;
} }
expn = parent; expn = parent;
panic_macro = name; panic_macro = Some(name);
} }
let macro_symbol = let macro_symbol =

View file

@ -2871,7 +2871,7 @@ impl<'a> Parser<'a> {
// Skip every token until next possible arg or end. // Skip every token until next possible arg or end.
p.eat_to_tokens(&[exp!(Comma), exp!(CloseParen)]); p.eat_to_tokens(&[exp!(Comma), exp!(CloseParen)]);
// Create a placeholder argument for proper arg count (issue #34264). // Create a placeholder argument for proper arg count (issue #34264).
Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span)), guar)) Ok(dummy_arg(Ident::new(sym::dummy, lo.to(p.prev_token.span)), guar))
}); });
// ...now that we've parsed the first argument, `self` is no longer allowed. // ...now that we've parsed the first argument, `self` is no longer allowed.
first_param = false; first_param = false;

View file

@ -1348,12 +1348,12 @@ pub(crate) struct DuplicateLangItem {
pub local_span: Option<Span>, pub local_span: Option<Span>,
pub lang_item_name: Symbol, pub lang_item_name: Symbol,
pub crate_name: Symbol, pub crate_name: Symbol,
pub dependency_of: Symbol, pub dependency_of: Option<Symbol>,
pub is_local: bool, pub is_local: bool,
pub path: String, pub path: String,
pub first_defined_span: Option<Span>, pub first_defined_span: Option<Span>,
pub orig_crate_name: Symbol, pub orig_crate_name: Option<Symbol>,
pub orig_dependency_of: Symbol, pub orig_dependency_of: Option<Symbol>,
pub orig_is_local: bool, pub orig_is_local: bool,
pub orig_path: String, pub orig_path: String,
pub(crate) duplicate: Duplicate, pub(crate) duplicate: Duplicate,
@ -1374,10 +1374,16 @@ impl<G: EmissionGuarantee> Diagnostic<'_, G> for DuplicateLangItem {
diag.code(E0152); diag.code(E0152);
diag.arg("lang_item_name", self.lang_item_name); diag.arg("lang_item_name", self.lang_item_name);
diag.arg("crate_name", self.crate_name); diag.arg("crate_name", self.crate_name);
diag.arg("dependency_of", self.dependency_of); if let Some(dependency_of) = self.dependency_of {
diag.arg("dependency_of", dependency_of);
}
diag.arg("path", self.path); diag.arg("path", self.path);
diag.arg("orig_crate_name", self.orig_crate_name); if let Some(orig_crate_name) = self.orig_crate_name {
diag.arg("orig_dependency_of", self.orig_dependency_of); diag.arg("orig_crate_name", orig_crate_name);
}
if let Some(orig_dependency_of) = self.orig_dependency_of {
diag.arg("orig_dependency_of", orig_dependency_of);
}
diag.arg("orig_path", self.orig_path); diag.arg("orig_path", self.orig_path);
if let Some(span) = self.local_span { if let Some(span) = self.local_span {
diag.span(span); diag.span(span);
@ -1385,7 +1391,7 @@ impl<G: EmissionGuarantee> Diagnostic<'_, G> for DuplicateLangItem {
if let Some(span) = self.first_defined_span { if let Some(span) = self.first_defined_span {
diag.span_note(span, fluent::passes_first_defined_span); diag.span_note(span, fluent::passes_first_defined_span);
} else { } else {
if self.orig_dependency_of.is_empty() { if self.orig_dependency_of.is_none() {
diag.note(fluent::passes_first_defined_crate); diag.note(fluent::passes_first_defined_crate);
} else { } else {
diag.note(fluent::passes_first_defined_crate_depends); diag.note(fluent::passes_first_defined_crate_depends);

View file

@ -16,7 +16,7 @@ use rustc_hir::{LangItem, LanguageItems, MethodKind, Target};
use rustc_middle::query::Providers; use rustc_middle::query::Providers;
use rustc_middle::ty::{ResolverAstLowering, TyCtxt}; use rustc_middle::ty::{ResolverAstLowering, TyCtxt};
use rustc_session::cstore::ExternCrate; use rustc_session::cstore::ExternCrate;
use rustc_span::{Span, kw}; use rustc_span::Span;
use crate::errors::{ use crate::errors::{
DuplicateLangItem, IncorrectTarget, LangItemOnIncorrectTarget, UnknownLangItem, DuplicateLangItem, IncorrectTarget, LangItemOnIncorrectTarget, UnknownLangItem,
@ -98,7 +98,7 @@ impl<'ast, 'tcx> LanguageItemCollector<'ast, 'tcx> {
{ {
let lang_item_name = lang_item.name(); let lang_item_name = lang_item.name();
let crate_name = self.tcx.crate_name(item_def_id.krate); let crate_name = self.tcx.crate_name(item_def_id.krate);
let mut dependency_of = kw::Empty; let mut dependency_of = None;
let is_local = item_def_id.is_local(); let is_local = item_def_id.is_local();
let path = if is_local { let path = if is_local {
String::new() String::new()
@ -112,8 +112,8 @@ impl<'ast, 'tcx> LanguageItemCollector<'ast, 'tcx> {
}; };
let first_defined_span = self.item_spans.get(&original_def_id).copied(); let first_defined_span = self.item_spans.get(&original_def_id).copied();
let mut orig_crate_name = kw::Empty; let mut orig_crate_name = None;
let mut orig_dependency_of = kw::Empty; let mut orig_dependency_of = None;
let orig_is_local = original_def_id.is_local(); let orig_is_local = original_def_id.is_local();
let orig_path = if orig_is_local { let orig_path = if orig_is_local {
String::new() String::new()
@ -127,11 +127,11 @@ impl<'ast, 'tcx> LanguageItemCollector<'ast, 'tcx> {
}; };
if first_defined_span.is_none() { if first_defined_span.is_none() {
orig_crate_name = self.tcx.crate_name(original_def_id.krate); orig_crate_name = Some(self.tcx.crate_name(original_def_id.krate));
if let Some(ExternCrate { dependency_of: inner_dependency_of, .. }) = if let Some(ExternCrate { dependency_of: inner_dependency_of, .. }) =
self.tcx.extern_crate(original_def_id.krate) self.tcx.extern_crate(original_def_id.krate)
{ {
orig_dependency_of = self.tcx.crate_name(*inner_dependency_of); orig_dependency_of = Some(self.tcx.crate_name(*inner_dependency_of));
} }
} }
@ -140,7 +140,7 @@ impl<'ast, 'tcx> LanguageItemCollector<'ast, 'tcx> {
} else { } else {
match self.tcx.extern_crate(item_def_id.krate) { match self.tcx.extern_crate(item_def_id.krate) {
Some(ExternCrate { dependency_of: inner_dependency_of, .. }) => { Some(ExternCrate { dependency_of: inner_dependency_of, .. }) => {
dependency_of = self.tcx.crate_name(*inner_dependency_of); dependency_of = Some(self.tcx.crate_name(*inner_dependency_of));
Duplicate::CrateDepends Duplicate::CrateDepends
} }
_ => Duplicate::Crate, _ => Duplicate::Crate,

View file

@ -131,7 +131,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
let expn_id = self.cstore().expn_that_defined_untracked(def_id, self.tcx.sess); let expn_id = self.cstore().expn_that_defined_untracked(def_id, self.tcx.sess);
return Some(self.new_module( return Some(self.new_module(
parent, parent,
ModuleKind::Def(def_kind, def_id, self.tcx.item_name(def_id)), ModuleKind::Def(def_kind, def_id, Some(self.tcx.item_name(def_id))),
expn_id, expn_id,
self.def_span(def_id), self.def_span(def_id),
// FIXME: Account for `#[no_implicit_prelude]` attributes. // FIXME: Account for `#[no_implicit_prelude]` attributes.
@ -594,7 +594,7 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> {
// HACK(eddyb) unclear how good this is, but keeping `$crate` // HACK(eddyb) unclear how good this is, but keeping `$crate`
// in `source` breaks `tests/ui/imports/import-crate-var.rs`, // in `source` breaks `tests/ui/imports/import-crate-var.rs`,
// while the current crate doesn't have a valid `crate_name`. // while the current crate doesn't have a valid `crate_name`.
if crate_name != kw::Empty { if let Some(crate_name) = crate_name {
// `crate_name` should not be interpreted as relative. // `crate_name` should not be interpreted as relative.
module_path.push(Segment::from_ident_and_id( module_path.push(Segment::from_ident_and_id(
Ident { name: kw::PathRoot, span: source.ident.span }, Ident { name: kw::PathRoot, span: source.ident.span },
@ -603,7 +603,7 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> {
source.ident.name = crate_name; source.ident.name = crate_name;
} }
if rename.is_none() { if rename.is_none() {
ident.name = crate_name; ident.name = sym::dummy;
} }
self.r.dcx().emit_err(errors::CrateImported { span: item.span }); self.r.dcx().emit_err(errors::CrateImported { span: item.span });
@ -775,7 +775,7 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> {
ItemKind::Mod(.., ref mod_kind) => { ItemKind::Mod(.., ref mod_kind) => {
let module = self.r.new_module( let module = self.r.new_module(
Some(parent), Some(parent),
ModuleKind::Def(def_kind, def_id, ident.name), ModuleKind::Def(def_kind, def_id, Some(ident.name)),
expansion.to_expn_id(), expansion.to_expn_id(),
item.span, item.span,
parent.no_implicit_prelude parent.no_implicit_prelude
@ -811,7 +811,7 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> {
ItemKind::Enum(_, _) | ItemKind::Trait(..) => { ItemKind::Enum(_, _) | ItemKind::Trait(..) => {
let module = self.r.new_module( let module = self.r.new_module(
Some(parent), Some(parent),
ModuleKind::Def(def_kind, def_id, ident.name), ModuleKind::Def(def_kind, def_id, Some(ident.name)),
expansion.to_expn_id(), expansion.to_expn_id(),
item.span, item.span,
parent.no_implicit_prelude, parent.no_implicit_prelude,

View file

@ -2438,7 +2438,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() else { let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() else {
return None; return None;
}; };
let module_name = crate_module.kind.name().unwrap(); let module_name = crate_module.kind.name().unwrap_or(kw::Empty);
let import_snippet = match import.kind { let import_snippet = match import.kind {
ImportKind::Single { source, target, .. } if source != target => { ImportKind::Single { source, target, .. } if source != target => {
format!("{source} as {target}") format!("{source} as {target}")

View file

@ -503,18 +503,18 @@ enum ModuleKind {
/// ///
/// * A normal module either `mod from_file;` or `mod from_block { }` /// * A normal module either `mod from_file;` or `mod from_block { }`
/// or the crate root (which is conceptually a top-level module). /// or the crate root (which is conceptually a top-level module).
/// Note that the crate root's [name][Self::name] will be [`kw::Empty`]. /// The crate root will have `None` for the symbol.
/// * A trait or an enum (it implicitly contains associated types, methods and variant /// * A trait or an enum (it implicitly contains associated types, methods and variant
/// constructors). /// constructors).
Def(DefKind, DefId, Symbol), Def(DefKind, DefId, Option<Symbol>),
} }
impl ModuleKind { impl ModuleKind {
/// Get name of the module. /// Get name of the module.
fn name(&self) -> Option<Symbol> { fn name(&self) -> Option<Symbol> {
match self { match *self {
ModuleKind::Block => None, ModuleKind::Block => None,
ModuleKind::Def(.., name) => Some(*name), ModuleKind::Def(.., name) => name,
} }
} }
} }
@ -1402,7 +1402,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
let mut module_self_bindings = FxHashMap::default(); let mut module_self_bindings = FxHashMap::default();
let graph_root = arenas.new_module( let graph_root = arenas.new_module(
None, None,
ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty), ModuleKind::Def(DefKind::Mod, root_def_id, None),
ExpnId::root(), ExpnId::root(),
crate_span, crate_span,
attr::contains_name(attrs, sym::no_implicit_prelude), attr::contains_name(attrs, sym::no_implicit_prelude),
@ -1411,7 +1411,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
); );
let empty_module = arenas.new_module( let empty_module = arenas.new_module(
None, None,
ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty), ModuleKind::Def(DefKind::Mod, root_def_id, None),
ExpnId::root(), ExpnId::root(),
DUMMY_SP, DUMMY_SP,
true, true,
@ -2286,7 +2286,8 @@ fn module_to_string(mut module: Module<'_>) -> Option<String> {
loop { loop {
if let ModuleKind::Def(.., name) = module.kind { if let ModuleKind::Def(.., name) = module.kind {
if let Some(parent) = module.parent { if let Some(parent) = module.parent {
names.push(name); // `unwrap` is safe: the presence of a parent means it's not the crate root.
names.push(name.unwrap());
module = parent module = parent
} else { } else {
break; break;

View file

@ -168,7 +168,7 @@ impl<'ra, 'tcx> ResolverExpand for Resolver<'ra, 'tcx> {
hygiene::update_dollar_crate_names(|ctxt| { hygiene::update_dollar_crate_names(|ctxt| {
let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt)); let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt));
match self.resolve_crate_root(ident).kind { match self.resolve_crate_root(ident).kind {
ModuleKind::Def(.., name) if name != kw::Empty => name, ModuleKind::Def(.., name) if let Some(name) = name => name,
_ => kw::Crate, _ => kw::Crate,
} }
}); });
@ -1067,11 +1067,12 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
); );
if fallback_binding.ok().and_then(|b| b.res().opt_def_id()) != Some(def_id) { if fallback_binding.ok().and_then(|b| b.res().opt_def_id()) != Some(def_id) {
let location = match parent_scope.module.kind { let location = match parent_scope.module.kind {
ModuleKind::Def(_, _, name) if name == kw::Empty => { ModuleKind::Def(kind, def_id, name) => {
if let Some(name) = name {
format!("{} `{name}`", kind.descr(def_id))
} else {
"the crate root".to_string() "the crate root".to_string()
} }
ModuleKind::Def(kind, def_id, name) => {
format!("{} `{name}`", kind.descr(def_id))
} }
ModuleKind::Block => "this scope".to_string(), ModuleKind::Block => "this scope".to_string(),
}; };

View file

@ -0,0 +1,5 @@
// Ensure we reject `#![crate_name = ""]`.
#![crate_name = ""] //~ ERROR crate name must not be empty
fn main() {}

View file

@ -0,0 +1,8 @@
error: crate name must not be empty
--> $DIR/crate-name-empty.rs:3:1
|
LL | #![crate_name = ""]
| ^^^^^^^^^^^^^^^^^^^
error: aborting due to 1 previous error