Skip to content

Commit 3898182

Browse files
committed
add test to reproduce rust-lang#137687 and fix it
1 parent 96cfc75 commit 3898182

36 files changed

+338
-165
lines changed

compiler/rustc_attr_data_structures/src/attributes.rs

+26
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,11 @@ pub enum AttributeKind {
175175
span: Span,
176176
},
177177
ConstStabilityIndirect,
178+
CrateName {
179+
name: Symbol,
180+
name_span: Span,
181+
style: AttrStyle,
182+
},
178183
Deprecation {
179184
deprecation: Deprecation,
180185
span: Span,
@@ -195,3 +200,24 @@ pub enum AttributeKind {
195200
},
196201
// tidy-alphabetical-end
197202
}
203+
204+
impl AttributeKind {
205+
pub fn crate_level(&self) -> Option<(AttrStyle, Span)> {
206+
match self {
207+
AttributeKind::AllowConstFnUnstable(..)
208+
| AttributeKind::AllowInternalUnstable(..)
209+
| AttributeKind::BodyStability { .. }
210+
| AttributeKind::Confusables { .. }
211+
| AttributeKind::ConstStability { .. }
212+
| AttributeKind::ConstStabilityIndirect
213+
| AttributeKind::Deprecation { .. }
214+
| AttributeKind::Diagnostic(..)
215+
| AttributeKind::DocComment { .. }
216+
| AttributeKind::MacroTransparency(..)
217+
| AttributeKind::Repr(..)
218+
| AttributeKind::Stability { .. } => None,
219+
220+
AttributeKind::CrateName { style, name_span, .. } => Some((*style, *name_span)),
221+
}
222+
}
223+
}

compiler/rustc_attr_parsing/messages.ftl

+2
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@ attr_parsing_multiple_item =
8787
attr_parsing_multiple_stability_levels =
8888
multiple stability levels
8989
90+
attr_parsing_name_value = malformed `{$name}` attribute: expected to be of the form `#[{$name} = ...]`
91+
9092
attr_parsing_non_ident_feature =
9193
'feature' is not an identifier
9294
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
use rustc_attr_data_structures::AttributeKind;
2+
use rustc_span::{Span, Symbol, sym};
3+
4+
use super::SingleAttributeParser;
5+
use crate::context::AcceptContext;
6+
use crate::parser::ArgParser;
7+
use crate::session_diagnostics::{ExpectedNameValue, IncorrectMetaItem, UnusedMultiple};
8+
9+
pub(crate) struct CratenameParser;
10+
11+
impl SingleAttributeParser for CratenameParser {
12+
const PATH: &'static [Symbol] = &[sym::crate_name];
13+
14+
fn on_duplicate(cx: &AcceptContext<'_>, first_span: Span) {
15+
// FIXME(jdonszelmann): better duplicate reporting (WIP)
16+
cx.emit_err(UnusedMultiple {
17+
this: cx.attr_span,
18+
other: first_span,
19+
name: sym::crate_name,
20+
});
21+
}
22+
23+
fn convert(cx: &AcceptContext<'_>, args: &ArgParser<'_>) -> Option<AttributeKind> {
24+
if let ArgParser::NameValue(n) = args {
25+
if let Some(name) = n.value_as_str() {
26+
Some(AttributeKind::CrateName {
27+
name,
28+
name_span: n.value_span,
29+
style: cx.attr_style,
30+
})
31+
} else {
32+
cx.emit_err(IncorrectMetaItem { span: cx.attr_span, suggestion: None });
33+
34+
None
35+
}
36+
} else {
37+
cx.emit_err(ExpectedNameValue { span: cx.attr_span, name: sym::crate_name });
38+
39+
None
40+
}
41+
}
42+
}

compiler/rustc_attr_parsing/src/attributes/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ use crate::parser::ArgParser;
2626
pub(crate) mod allow_unstable;
2727
pub(crate) mod cfg;
2828
pub(crate) mod confusables;
29+
pub(crate) mod crate_name;
2930
pub(crate) mod deprecation;
3031
pub(crate) mod repr;
3132
pub(crate) mod stability;

compiler/rustc_attr_parsing/src/attributes/util.rs

+2-6
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
use rustc_ast::attr::{AttributeExt, first_attr_value_str_by_name};
1+
use rustc_ast::attr::AttributeExt;
22
use rustc_attr_data_structures::RustcVersion;
33
use rustc_feature::is_builtin_attr_name;
4-
use rustc_span::{Symbol, sym};
4+
use rustc_span::Symbol;
55

66
/// Parse a rustc version number written inside string literal in an attribute,
77
/// like appears in `since = "1.0.0"`. Suffixes like "-dev" and "-nightly" are
@@ -22,7 +22,3 @@ pub fn parse_version(s: Symbol) -> Option<RustcVersion> {
2222
pub fn is_builtin_attr(attr: &impl AttributeExt) -> bool {
2323
attr.is_doc_comment() || attr.ident().is_some_and(|ident| is_builtin_attr_name(ident.name))
2424
}
25-
26-
pub fn find_crate_name(attrs: &[impl AttributeExt]) -> Option<Symbol> {
27-
first_attr_value_str_by_name(attrs, sym::crate_name)
28-
}

compiler/rustc_attr_parsing/src/context.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use std::collections::BTreeMap;
33
use std::ops::Deref;
44
use std::sync::LazyLock;
55

6-
use rustc_ast::{self as ast, DelimArgs};
6+
use rustc_ast::{self as ast, AttrStyle, DelimArgs};
77
use rustc_attr_data_structures::AttributeKind;
88
use rustc_errors::{DiagCtxtHandle, Diagnostic};
99
use rustc_feature::Features;
@@ -14,6 +14,7 @@ use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym};
1414

1515
use crate::attributes::allow_unstable::{AllowConstFnUnstableParser, AllowInternalUnstableParser};
1616
use crate::attributes::confusables::ConfusablesParser;
17+
use crate::attributes::crate_name::CratenameParser;
1718
use crate::attributes::deprecation::DeprecationParser;
1819
use crate::attributes::repr::ReprParser;
1920
use crate::attributes::stability::{
@@ -76,6 +77,7 @@ attribute_groups!(
7677

7778
// tidy-alphabetical-start
7879
Single<ConstStabilityIndirectParser>,
80+
Single<CratenameParser>,
7981
Single<DeprecationParser>,
8082
Single<TransparencyParser>,
8183
// tidy-alphabetical-end
@@ -89,6 +91,7 @@ pub(crate) struct AcceptContext<'a> {
8991
pub(crate) group_cx: &'a FinalizeContext<'a>,
9092
/// The span of the attribute currently being parsed
9193
pub(crate) attr_span: Span,
94+
pub(crate) attr_style: AttrStyle,
9295
}
9396

9497
impl<'a> AcceptContext<'a> {
@@ -269,6 +272,7 @@ impl<'sess> AttributeParser<'sess> {
269272
let cx = AcceptContext {
270273
group_cx: &group_cx,
271274
attr_span: lower_span(attr.span),
275+
attr_style: attr.style,
272276
};
273277

274278
f(&cx, &args)

compiler/rustc_attr_parsing/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ pub mod parser;
9090
mod session_diagnostics;
9191

9292
pub use attributes::cfg::*;
93-
pub use attributes::util::{find_crate_name, is_builtin_attr, parse_version};
93+
pub use attributes::util::{is_builtin_attr, parse_version};
9494
pub use context::{AttributeParser, OmitDoc};
9595
pub use rustc_attr_data_structures::*;
9696

compiler/rustc_attr_parsing/src/session_diagnostics.rs

+8
Original file line numberDiff line numberDiff line change
@@ -479,3 +479,11 @@ pub(crate) struct UnrecognizedReprHint {
479479
#[primary_span]
480480
pub span: Span,
481481
}
482+
483+
#[derive(Diagnostic)]
484+
#[diag(attr_parsing_name_value, code = E0539)]
485+
pub(crate) struct ExpectedNameValue {
486+
#[primary_span]
487+
pub span: Span,
488+
pub name: Symbol,
489+
}

compiler/rustc_driver_impl/src/lib.rs

+20-13
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ use rustc_session::getopts::{self, Matches};
5959
use rustc_session::lint::{Lint, LintId};
6060
use rustc_session::output::collect_crate_types;
6161
use rustc_session::{EarlyDiagCtxt, Session, config, filesearch};
62-
use rustc_span::FileName;
62+
use rustc_span::{FileName, Symbol};
6363
use rustc_target::json::ToJson;
6464
use rustc_target::spec::{Target, TargetTuple};
6565
use time::OffsetDateTime;
@@ -290,7 +290,8 @@ pub fn run_compiler(at_args: &[String], callbacks: &mut (dyn Callbacks + Send))
290290
return early_exit();
291291
}
292292

293-
if print_crate_info(codegen_backend, sess, has_input) == Compilation::Stop {
293+
let (c, crate_name) = print_crate_info(codegen_backend, sess, has_input);
294+
if c == Compilation::Stop {
294295
return early_exit();
295296
}
296297

@@ -316,7 +317,7 @@ pub fn run_compiler(at_args: &[String], callbacks: &mut (dyn Callbacks + Send))
316317
// If pretty printing is requested: Figure out the representation, print it and exit
317318
if let Some(pp_mode) = sess.opts.pretty {
318319
if pp_mode.needs_ast_map() {
319-
create_and_enter_global_ctxt(compiler, krate, |tcx| {
320+
create_and_enter_global_ctxt(compiler, krate, crate_name, |tcx| {
320321
tcx.ensure_ok().early_lint_checks(());
321322
pretty::print(sess, pp_mode, pretty::PrintExtra::NeedsAstMap { tcx });
322323
passes::write_dep_info(tcx);
@@ -336,7 +337,7 @@ pub fn run_compiler(at_args: &[String], callbacks: &mut (dyn Callbacks + Send))
336337
return early_exit();
337338
}
338339

339-
let linker = create_and_enter_global_ctxt(compiler, krate, |tcx| {
340+
let linker = create_and_enter_global_ctxt(compiler, krate, crate_name, |tcx| {
340341
let early_exit = || {
341342
sess.dcx().abort_if_errors();
342343
None
@@ -607,18 +608,22 @@ fn print_crate_info(
607608
codegen_backend: &dyn CodegenBackend,
608609
sess: &Session,
609610
parse_attrs: bool,
610-
) -> Compilation {
611+
) -> (Compilation, Option<Symbol>) {
611612
use rustc_session::config::PrintKind::*;
612613
// This import prevents the following code from using the printing macros
613614
// used by the rest of the module. Within this function, we only write to
614615
// the output specified by `sess.io.output_file`.
615616
#[allow(unused_imports)]
616617
use {do_not_use_safe_print as safe_print, do_not_use_safe_print as safe_println};
617618

619+
let mut crate_name = None;
620+
let mut get_crate_name =
621+
|attrs| *crate_name.get_or_insert_with(|| passes::get_crate_name(sess, attrs));
622+
618623
// NativeStaticLibs and LinkArgs are special - printed during linking
619624
// (empty iterator returns true)
620625
if sess.opts.prints.iter().all(|p| p.kind == NativeStaticLibs || p.kind == LinkArgs) {
621-
return Compilation::Continue;
626+
return (Compilation::Continue, crate_name);
622627
}
623628

624629
let attrs = if parse_attrs {
@@ -627,7 +632,7 @@ fn print_crate_info(
627632
Ok(attrs) => Some(attrs),
628633
Err(parse_error) => {
629634
parse_error.emit();
630-
return Compilation::Stop;
635+
return (Compilation::Stop, crate_name);
631636
}
632637
}
633638
} else {
@@ -664,24 +669,26 @@ fn print_crate_info(
664669
FileNames => {
665670
let Some(attrs) = attrs.as_ref() else {
666671
// no crate attributes, print out an error and exit
667-
return Compilation::Continue;
672+
return (Compilation::Continue, crate_name);
668673
};
669674
let t_outputs = rustc_interface::util::build_output_filenames(attrs, sess);
670-
let crate_name = passes::get_crate_name(sess, attrs);
671675
let crate_types = collect_crate_types(sess, attrs);
672676
for &style in &crate_types {
673677
let fname = rustc_session::output::filename_for_input(
674-
sess, style, crate_name, &t_outputs,
678+
sess,
679+
style,
680+
get_crate_name(attrs),
681+
&t_outputs,
675682
);
676683
println_info!("{}", fname.as_path().file_name().unwrap().to_string_lossy());
677684
}
678685
}
679686
CrateName => {
680687
let Some(attrs) = attrs.as_ref() else {
681688
// no crate attributes, print out an error and exit
682-
return Compilation::Continue;
689+
return (Compilation::Continue, crate_name);
683690
};
684-
println_info!("{}", passes::get_crate_name(sess, attrs));
691+
println_info!("{}", get_crate_name(attrs));
685692
}
686693
Cfg => {
687694
let mut cfgs = sess
@@ -786,7 +793,7 @@ fn print_crate_info(
786793

787794
req.out.overwrite(&crate_info, sess);
788795
}
789-
Compilation::Stop
796+
(Compilation::Stop, crate_name)
790797
}
791798

792799
/// Prints version information

compiler/rustc_interface/src/passes.rs

+19-4
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use std::sync::{Arc, LazyLock};
66
use std::{env, fs, iter};
77

88
use rustc_ast as ast;
9+
use rustc_attr_parsing::{AttributeKind, AttributeParser};
910
use rustc_codegen_ssa::traits::CodegenBackend;
1011
use rustc_data_structures::parallel;
1112
use rustc_data_structures::steal::Steal;
@@ -32,7 +33,7 @@ use rustc_session::output::{collect_crate_types, filename_for_input};
3233
use rustc_session::search_paths::PathKind;
3334
use rustc_session::{Limit, Session};
3435
use rustc_span::{
35-
ErrorGuaranteed, FileName, SourceFileHash, SourceFileHashAlgorithm, Span, Symbol, sym,
36+
DUMMY_SP, ErrorGuaranteed, FileName, SourceFileHash, SourceFileHashAlgorithm, Span, Symbol, sym,
3637
};
3738
use rustc_target::spec::PanicStrategy;
3839
use rustc_trait_selection::traits;
@@ -753,6 +754,7 @@ pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
753754
pub fn create_and_enter_global_ctxt<T, F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> T>(
754755
compiler: &Compiler,
755756
mut krate: rustc_ast::Crate,
757+
crate_name: Option<Symbol>,
756758
f: F,
757759
) -> T {
758760
let sess = &compiler.sess;
@@ -765,7 +767,7 @@ pub fn create_and_enter_global_ctxt<T, F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> T>(
765767

766768
let pre_configured_attrs = rustc_expand::config::pre_configure_attrs(sess, &krate.attrs);
767769

768-
let crate_name = get_crate_name(sess, &pre_configured_attrs);
770+
let crate_name = crate_name.unwrap_or_else(|| get_crate_name(sess, &pre_configured_attrs));
769771
let crate_types = collect_crate_types(sess, &pre_configured_attrs);
770772
let stable_crate_id = StableCrateId::new(
771773
crate_name,
@@ -1119,6 +1121,20 @@ pub(crate) fn start_codegen<'tcx>(
11191121
codegen
11201122
}
11211123

1124+
pub(crate) fn parse_crate_name(
1125+
sess: &Session,
1126+
attrs: &[ast::Attribute],
1127+
limit_diagnostics: bool,
1128+
) -> Option<(Symbol, Span)> {
1129+
let rustc_hir::Attribute::Parsed(AttributeKind::CrateName { name, name_span, .. }) =
1130+
AttributeParser::parse_limited(sess, &attrs, sym::crate_name, DUMMY_SP, limit_diagnostics)?
1131+
else {
1132+
unreachable!("crate_name is the only attr we could've parsed here");
1133+
};
1134+
1135+
Some((name, name_span))
1136+
}
1137+
11221138
/// Compute and validate the crate name.
11231139
pub fn get_crate_name(sess: &Session, krate_attrs: &[ast::Attribute]) -> Symbol {
11241140
// We validate *all* occurrences of `#![crate_name]`, pick the first find and
@@ -1128,8 +1144,7 @@ pub fn get_crate_name(sess: &Session, krate_attrs: &[ast::Attribute]) -> Symbol
11281144
// in all code paths that require the crate name very early on, namely before
11291145
// macro expansion.
11301146

1131-
let attr_crate_name =
1132-
validate_and_find_value_str_builtin_attr(sym::crate_name, sess, krate_attrs);
1147+
let attr_crate_name = parse_crate_name(sess, krate_attrs, false);
11331148

11341149
let validate = |name, span| {
11351150
rustc_session::output::validate_crate_name(sess, name, span);

compiler/rustc_interface/src/util.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ use rustc_target::spec::Target;
2323
use tracing::info;
2424

2525
use crate::errors;
26+
use crate::passes::parse_crate_name;
2627

2728
/// Function pointer type that constructs a new CodegenBackend.
2829
type MakeBackendFn = fn() -> Box<dyn CodegenBackend>;
@@ -485,7 +486,7 @@ pub fn build_output_filenames(attrs: &[ast::Attribute], sess: &Session) -> Outpu
485486
.opts
486487
.crate_name
487488
.clone()
488-
.or_else(|| rustc_attr_parsing::find_crate_name(attrs).map(|n| n.to_string()));
489+
.or_else(|| parse_crate_name(sess, attrs, true).map(|i| i.0.to_string()));
489490

490491
match sess.io.output_file {
491492
None => {

0 commit comments

Comments
 (0)