Skip to content

Commit 04bafec

Browse files
committed
add test to reproduce #137687 and fix it
1 parent 96cfc75 commit 04bafec

36 files changed

+340
-170
lines changed

compiler/rustc_attr_data_structures/src/attributes.rs

+25
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,23 @@ 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(..) | AttributeKind::AllowInternalUnstable(..) |
208+
AttributeKind::BodyStability {..} |
209+
AttributeKind::Confusables {..} |
210+
AttributeKind::ConstStability {..} |
211+
AttributeKind::ConstStabilityIndirect |
212+
AttributeKind::Deprecation {..} |
213+
AttributeKind::Diagnostic(..) |
214+
AttributeKind::DocComment {..} |
215+
AttributeKind::MacroTransparency(..) |
216+
AttributeKind::Repr(..)|
217+
AttributeKind::Stability { .. } => None,
218+
219+
AttributeKind::CrateName { style, name_span, .. } => Some((*style, *name_span)),
220+
}
221+
}
222+
}

compiler/rustc_attr_parsing/messages.ftl

+3
Original file line numberDiff line numberDiff line change
@@ -135,3 +135,6 @@ attr_parsing_unused_multiple =
135135
multiple `{$name}` attributes
136136
.suggestion = remove this attribute
137137
.note = attribute also specified here
138+
139+
attr_parsing_name_value = malformed `{$name}` attribute: expected to be of the form `#[{$name} = ...]`
140+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
use rustc_attr_data_structures::AttributeKind;
2+
use rustc_span::{sym, Span, Symbol};
3+
4+
use crate::{context::AcceptContext, parser::ArgParser, session_diagnostics::{ExpectedNameValue, IncorrectMetaItem, UnusedMultiple}};
5+
6+
use super::SingleAttributeParser;
7+
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 {
33+
span: cx.attr_span,
34+
suggestion: None
35+
});
36+
37+
None
38+
}
39+
} else {
40+
cx.emit_err(ExpectedNameValue {
41+
span: cx.attr_span,
42+
name: sym::crate_name,
43+
});
44+
45+
None
46+
}
47+
}
48+
}

compiler/rustc_attr_parsing/src/attributes/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ pub(crate) mod deprecation;
3030
pub(crate) mod repr;
3131
pub(crate) mod stability;
3232
pub(crate) mod transparency;
33+
pub(crate) mod crate_name;
3334
pub(crate) mod util;
3435

3536
type AcceptFn<T> = fn(&mut T, &AcceptContext<'_>, &ArgParser<'_>);

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

+18-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,23 @@ 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 = |attrs| {
621+
*crate_name.get_or_insert_with(|| passes::get_crate_name(sess, attrs))
622+
};
623+
618624
// NativeStaticLibs and LinkArgs are special - printed during linking
619625
// (empty iterator returns true)
620626
if sess.opts.prints.iter().all(|p| p.kind == NativeStaticLibs || p.kind == LinkArgs) {
621-
return Compilation::Continue;
627+
return (Compilation::Continue, crate_name);
622628
}
623629

624630
let attrs = if parse_attrs {
@@ -627,7 +633,7 @@ fn print_crate_info(
627633
Ok(attrs) => Some(attrs),
628634
Err(parse_error) => {
629635
parse_error.emit();
630-
return Compilation::Stop;
636+
return (Compilation::Stop, crate_name);
631637
}
632638
}
633639
} else {
@@ -664,24 +670,23 @@ fn print_crate_info(
664670
FileNames => {
665671
let Some(attrs) = attrs.as_ref() else {
666672
// no crate attributes, print out an error and exit
667-
return Compilation::Continue;
673+
return (Compilation::Continue, crate_name);
668674
};
669675
let t_outputs = rustc_interface::util::build_output_filenames(attrs, sess);
670-
let crate_name = passes::get_crate_name(sess, attrs);
671676
let crate_types = collect_crate_types(sess, attrs);
672677
for &style in &crate_types {
673678
let fname = rustc_session::output::filename_for_input(
674-
sess, style, crate_name, &t_outputs,
679+
sess, style, get_crate_name(attrs), &t_outputs,
675680
);
676681
println_info!("{}", fname.as_path().file_name().unwrap().to_string_lossy());
677682
}
678683
}
679684
CrateName => {
680685
let Some(attrs) = attrs.as_ref() else {
681686
// no crate attributes, print out an error and exit
682-
return Compilation::Continue;
687+
return (Compilation::Continue, crate_name);
683688
};
684-
println_info!("{}", passes::get_crate_name(sess, attrs));
689+
println_info!("{}", get_crate_name(attrs));
685690
}
686691
Cfg => {
687692
let mut cfgs = sess
@@ -786,7 +791,7 @@ fn print_crate_info(
786791

787792
req.out.overwrite(&crate_info, sess);
788793
}
789-
Compilation::Stop
794+
(Compilation::Stop, crate_name)
790795
}
791796

792797
/// Prints version information

compiler/rustc_interface/src/passes.rs

+13-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+
sym, ErrorGuaranteed, FileName, SourceFileHash, SourceFileHashAlgorithm, Span, Symbol, DUMMY_SP
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,14 @@ pub(crate) fn start_codegen<'tcx>(
11191121
codegen
11201122
}
11211123

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

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

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

compiler/rustc_interface/src/util.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,12 @@ use rustc_session::{EarlyDiagCtxt, Session, filesearch};
1818
use rustc_span::edit_distance::find_best_match_for_name;
1919
use rustc_span::edition::Edition;
2020
use rustc_span::source_map::SourceMapInputs;
21-
use rustc_span::{Symbol, sym};
21+
use rustc_span::{sym, Symbol};
2222
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>;
@@ -481,11 +482,9 @@ pub fn build_output_filenames(attrs: &[ast::Attribute], sess: &Session) -> Outpu
481482
sess.dcx().emit_fatal(errors::MultipleOutputTypesToStdout);
482483
}
483484

484-
let crate_name = sess
485-
.opts
486-
.crate_name
485+
let crate_name = sess.opts.crate_name
487486
.clone()
488-
.or_else(|| rustc_attr_parsing::find_crate_name(attrs).map(|n| n.to_string()));
487+
.or_else(|| parse_crate_name(sess, attrs, true).map(|i| i.0.to_string()));
489488

490489
match sess.io.output_file {
491490
None => {

0 commit comments

Comments
 (0)