Skip to content

Commit bfedb97

Browse files
committed
Reject macro calls inside of #![crate_name]
1 parent 197c7e2 commit bfedb97

21 files changed

+193
-114
lines changed

Diff for: compiler/rustc_driver_impl/src/lib.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -760,11 +760,12 @@ fn print_crate_info(
760760
return Compilation::Continue;
761761
};
762762
let t_outputs = rustc_interface::util::build_output_filenames(attrs, sess);
763-
let id = rustc_session::output::find_crate_name(sess, attrs);
763+
let crate_name = passes::get_crate_name(sess, attrs);
764764
let crate_types = collect_crate_types(sess, attrs);
765765
for &style in &crate_types {
766-
let fname =
767-
rustc_session::output::filename_for_input(sess, style, id, &t_outputs);
766+
let fname = rustc_session::output::filename_for_input(
767+
sess, style, crate_name, &t_outputs,
768+
);
768769
println_info!("{}", fname.as_path().file_name().unwrap().to_string_lossy());
769770
}
770771
}
@@ -773,8 +774,7 @@ fn print_crate_info(
773774
// no crate attributes, print out an error and exit
774775
return Compilation::Continue;
775776
};
776-
let id = rustc_session::output::find_crate_name(sess, attrs);
777-
println_info!("{id}");
777+
println_info!("{}", passes::get_crate_name(sess, attrs));
778778
}
779779
Cfg => {
780780
let mut cfgs = sess

Diff for: compiler/rustc_expand/src/module.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -179,12 +179,12 @@ fn mod_file_path_from_attr(
179179
let first_path = attrs.iter().find(|at| at.has_name(sym::path))?;
180180
let Some(path_sym) = first_path.value_str() else {
181181
// This check is here mainly to catch attempting to use a macro,
182-
// such as #[path = concat!(...)]. This isn't currently supported
182+
// such as `#[path = concat!(...)]`. This isn't currently supported
183183
// because otherwise the InvocationCollector would need to defer
184-
// loading a module until the #[path] attribute was expanded, and
185-
// it doesn't support that (and would likely add a bit of
186-
// complexity). Usually bad forms are checked in AstValidator (via
187-
// `check_builtin_attribute`), but by the time that runs the macro
184+
// loading a module until the `#[path]` attribute was expanded, and
185+
// it doesn't support that (and would likely add a bit of complexity).
186+
// Usually bad forms are checked during semantic analysis via
187+
// `TyCtxt::check_mod_attrs`), but by the time that runs the macro
188188
// is expanded, and it doesn't give an error.
189189
validate_attr::emit_fatal_malformed_builtin_attribute(&sess.psess, first_path, sym::path);
190190
};

Diff for: compiler/rustc_incremental/src/persist/fs.rs

+8-5
Original file line numberDiff line numberDiff line change
@@ -116,8 +116,9 @@ use rustc_errors::ErrorGuaranteed;
116116
use rustc_fs_util::{link_or_copy, try_canonicalize, LinkOrCopy};
117117
use rustc_middle::bug;
118118
use rustc_session::config::CrateType;
119-
use rustc_session::output::{collect_crate_types, find_crate_name};
119+
use rustc_session::output::collect_crate_types;
120120
use rustc_session::{Session, StableCrateId};
121+
use rustc_span::Symbol;
121122

122123
use std::fs as std_fs;
123124
use std::io::{self, ErrorKind};
@@ -215,7 +216,10 @@ pub fn in_incr_comp_dir(incr_comp_session_dir: &Path, file_name: &str) -> PathBu
215216
/// The garbage collection will take care of it.
216217
///
217218
/// [`rustc_interface::queries::dep_graph`]: ../../rustc_interface/struct.Queries.html#structfield.dep_graph
218-
pub(crate) fn prepare_session_directory(sess: &Session) -> Result<(), ErrorGuaranteed> {
219+
pub(crate) fn prepare_session_directory(
220+
sess: &Session,
221+
crate_name: Symbol,
222+
) -> Result<(), ErrorGuaranteed> {
219223
if sess.opts.incremental.is_none() {
220224
return Ok(());
221225
}
@@ -225,7 +229,7 @@ pub(crate) fn prepare_session_directory(sess: &Session) -> Result<(), ErrorGuara
225229
debug!("prepare_session_directory");
226230

227231
// {incr-comp-dir}/{crate-name-and-disambiguator}
228-
let crate_dir = crate_path(sess);
232+
let crate_dir = crate_path(sess, crate_name);
229233
debug!("crate-dir: {}", crate_dir.display());
230234
create_dir(sess, &crate_dir, "crate")?;
231235

@@ -608,10 +612,9 @@ fn string_to_timestamp(s: &str) -> Result<SystemTime, &'static str> {
608612
Ok(UNIX_EPOCH + duration)
609613
}
610614

611-
fn crate_path(sess: &Session) -> PathBuf {
615+
fn crate_path(sess: &Session, crate_name: Symbol) -> PathBuf {
612616
let incr_dir = sess.opts.incremental.as_ref().unwrap().clone();
613617

614-
let crate_name = find_crate_name(sess, &[]);
615618
let crate_types = collect_crate_types(sess, &[]);
616619
let stable_crate_id = StableCrateId::new(
617620
crate_name,

Diff for: compiler/rustc_incremental/src/persist/load.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use rustc_serialize::opaque::MemDecoder;
99
use rustc_serialize::Decodable;
1010
use rustc_session::config::IncrementalStateAssertion;
1111
use rustc_session::Session;
12-
use rustc_span::ErrorGuaranteed;
12+
use rustc_span::{ErrorGuaranteed, Symbol};
1313
use std::path::{Path, PathBuf};
1414
use std::sync::Arc;
1515
use tracing::{debug, warn};
@@ -204,9 +204,9 @@ pub fn load_query_result_cache(sess: &Session) -> Option<OnDiskCache<'_>> {
204204

205205
/// Setups the dependency graph by loading an existing graph from disk and set up streaming of a
206206
/// new graph to an incremental session directory.
207-
pub fn setup_dep_graph(sess: &Session) -> Result<DepGraph, ErrorGuaranteed> {
207+
pub fn setup_dep_graph(sess: &Session, crate_name: Symbol) -> Result<DepGraph, ErrorGuaranteed> {
208208
// `load_dep_graph` can only be called after `prepare_session_directory`.
209-
prepare_session_directory(sess)?;
209+
prepare_session_directory(sess, crate_name)?;
210210

211211
let res = sess.opts.build_dep_graph().then(|| load_dep_graph(sess));
212212

Diff for: compiler/rustc_interface/messages.ftl

+4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
interface_cant_emit_mir =
22
could not emit MIR: {$error}
33
4+
interface_crate_name_does_not_match = `--crate-name` and `#[crate_name]` are required to match, but `{$crate_name}` != `{$attr_crate_name}`
5+
6+
interface_crate_name_invalid = crate names cannot start with a `-`, but `{$s}` has a leading hyphen
7+
48
interface_emoji_identifier =
59
identifiers cannot contain emoji: `{$ident}`
610

Diff for: compiler/rustc_interface/src/errors.rs

+15
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,21 @@ use rustc_span::{Span, Symbol};
44
use std::io;
55
use std::path::Path;
66

7+
#[derive(Diagnostic)]
8+
#[diag(interface_crate_name_does_not_match)]
9+
pub(crate) struct CrateNameDoesNotMatch {
10+
#[primary_span]
11+
pub(crate) span: Span,
12+
pub(crate) crate_name: Symbol,
13+
pub(crate) attr_crate_name: Symbol,
14+
}
15+
16+
#[derive(Diagnostic)]
17+
#[diag(interface_crate_name_invalid)]
18+
pub(crate) struct CrateNameInvalid<'a> {
19+
pub(crate) crate_name: &'a str,
20+
}
21+
722
#[derive(Diagnostic)]
823
#[diag(interface_ferris_identifier)]
924
pub struct FerrisIdentifier {

Diff for: compiler/rustc_interface/src/passes.rs

+80-21
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,12 @@ use rustc_resolve::Resolver;
2727
use rustc_session::code_stats::VTableSizeInfo;
2828
use rustc_session::config::{CrateType, Input, OutFileName, OutputFilenames, OutputType};
2929
use rustc_session::cstore::Untracked;
30+
use rustc_session::output::collect_crate_types;
3031
use rustc_session::output::filename_for_input;
31-
use rustc_session::output::{collect_crate_types, find_crate_name};
3232
use rustc_session::search_paths::PathKind;
3333
use rustc_session::{Limit, Session};
34-
use rustc_span::symbol::{sym, Symbol};
3534
use rustc_span::FileName;
35+
use rustc_span::{sym, Span, Symbol};
3636
use rustc_target::spec::PanicStrategy;
3737
use rustc_trait_selection::traits;
3838

@@ -660,8 +660,7 @@ pub(crate) fn create_global_ctxt<'tcx>(
660660

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

663-
// parse `#[crate_name]` even if `--crate-name` was passed, to make sure it matches.
664-
let crate_name = find_crate_name(sess, &pre_configured_attrs);
663+
let crate_name = get_crate_name(sess, &pre_configured_attrs);
665664
let crate_types = collect_crate_types(sess, &pre_configured_attrs);
666665
let stable_crate_id = StableCrateId::new(
667666
crate_name,
@@ -670,7 +669,7 @@ pub(crate) fn create_global_ctxt<'tcx>(
670669
sess.cfg_version,
671670
);
672671
let outputs = util::build_output_filenames(&pre_configured_attrs, sess);
673-
let dep_graph = setup_dep_graph(sess)?;
672+
let dep_graph = setup_dep_graph(sess, crate_name)?;
674673

675674
let cstore =
676675
FreezeLock::new(Box::new(CStore::new(compiler.codegen_backend.metadata_loader())) as _);
@@ -1044,23 +1043,83 @@ pub(crate) fn start_codegen<'tcx>(
10441043
Ok(codegen)
10451044
}
10461045

1047-
fn get_recursion_limit(krate_attrs: &[ast::Attribute], sess: &Session) -> Limit {
1048-
if let Some(attr) = krate_attrs
1049-
.iter()
1050-
.find(|attr| attr.has_name(sym::recursion_limit) && attr.value_str().is_none())
1046+
/// Compute and validate the crate name.
1047+
pub fn get_crate_name(sess: &Session, krate_attrs: &[ast::Attribute]) -> Symbol {
1048+
// We unconditionally validate all `#![crate_name]`s even if a crate name was
1049+
// set on the command line via `--crate-name` which we prioritize over the
1050+
// crate attributes. We perform the validation here instead of later to ensure
1051+
// it gets run in all code paths requiring the crate name very early on.
1052+
// Namely, print requests (`--print`).
1053+
let attr_crate_name =
1054+
validate_and_find_value_str_builtin_attr(sym::crate_name, sess, krate_attrs);
1055+
1056+
let validate = |name, span| {
1057+
rustc_session::output::validate_crate_name(sess, name, span);
1058+
name
1059+
};
1060+
1061+
if let Some(crate_name) = &sess.opts.crate_name {
1062+
let crate_name = Symbol::intern(crate_name);
1063+
if let Some((attr_crate_name, span)) = attr_crate_name
1064+
&& attr_crate_name != crate_name
1065+
{
1066+
sess.dcx().emit_err(errors::CrateNameDoesNotMatch {
1067+
span,
1068+
crate_name,
1069+
attr_crate_name,
1070+
});
1071+
}
1072+
return validate(crate_name, None);
1073+
}
1074+
1075+
if let Some((crate_name, span)) = attr_crate_name {
1076+
return validate(crate_name, Some(span));
1077+
}
1078+
1079+
if let Input::File(ref path) = sess.io.input
1080+
&& let Some(file_stem) = path.file_stem().and_then(|s| s.to_str())
10511081
{
1052-
// This is here mainly to check for using a macro, such as
1053-
// #![recursion_limit = foo!()]. That is not supported since that
1054-
// would require expanding this while in the middle of expansion,
1055-
// which needs to know the limit before expanding. Otherwise,
1056-
// validation would normally be caught in AstValidator (via
1057-
// `check_builtin_attribute`), but by the time that runs the macro
1058-
// is expanded, and it doesn't give an error.
1059-
validate_attr::emit_fatal_malformed_builtin_attribute(
1060-
&sess.psess,
1061-
attr,
1062-
sym::recursion_limit,
1063-
);
1082+
if file_stem.starts_with('-') {
1083+
sess.dcx().emit_err(errors::CrateNameInvalid { crate_name: file_stem });
1084+
} else {
1085+
return validate(Symbol::intern(&file_stem.replace('-', "_")), None);
1086+
}
10641087
}
1088+
1089+
Symbol::intern("rust_out")
1090+
}
1091+
1092+
fn get_recursion_limit(krate_attrs: &[ast::Attribute], sess: &Session) -> Limit {
1093+
// We don't permit macro calls inside of the attribute (e.g., #![recursion_limit = `expand!()`])
1094+
// because that would require expanding this while in the middle of expansion, which needs to
1095+
// know the limit before expanding.
1096+
let _ = validate_and_find_value_str_builtin_attr(sym::recursion_limit, sess, krate_attrs);
10651097
rustc_middle::middle::limits::get_recursion_limit(krate_attrs, sess)
10661098
}
1099+
1100+
/// Validate *all* occurrences of the given "[value-str]" built-in attribute and return the first find.
1101+
///
1102+
/// This validator is intended for built-in attributes whose value needs to be known very early
1103+
/// during compilation (namely, before macro expansion) and it mainly exists to reject macro calls
1104+
/// inside of the attributes, such as in `#![name = expand!()]`. Normal attribute validation happens
1105+
/// during semantic analysis via [`TyCtxt::check_mod_attrs`] which happens *after* macro expansion
1106+
/// when such macro calls (here: `expand`) have already been expanded and we can no longer check for
1107+
/// their presence.
1108+
///
1109+
/// [value-str]: ast::Attribute::value_str
1110+
fn validate_and_find_value_str_builtin_attr(
1111+
name: Symbol,
1112+
sess: &Session,
1113+
krate_attrs: &[ast::Attribute],
1114+
) -> Option<(Symbol, Span)> {
1115+
let mut result = None;
1116+
// Validate *all* relevant attributes, not just the first occurrence.
1117+
for attr in ast::attr::filter_by_name(krate_attrs, name) {
1118+
let Some(value) = attr.value_str() else {
1119+
validate_attr::emit_fatal_malformed_builtin_attribute(&sess.psess, attr, name)
1120+
};
1121+
// Choose the first occurrence as our result.
1122+
result.get_or_insert((value, attr.span));
1123+
}
1124+
result
1125+
}

Diff for: compiler/rustc_interface/src/util.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -413,11 +413,11 @@ pub(crate) fn check_attr_crate_type(
413413
}
414414
} else {
415415
// This is here mainly to check for using a macro, such as
416-
// #![crate_type = foo!()]. That is not supported since the
416+
// `#![crate_type = foo!()]`. That is not supported since the
417417
// crate type needs to be known very early in compilation long
418418
// before expansion. Otherwise, validation would normally be
419-
// caught in AstValidator (via `check_builtin_attribute`), but
420-
// by the time that runs the macro is expanded, and it doesn't
419+
// caught during semantic analysis via `TyCtxt::check_mod_attrs`,
420+
// but by the time that runs the macro is expanded, and it doesn't
421421
// give an error.
422422
validate_attr::emit_fatal_malformed_builtin_attribute(
423423
&sess.psess,

Diff for: compiler/rustc_session/messages.ftl

-4
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,8 @@ session_cannot_mix_and_match_sanitizers = `-Zsanitizer={$first}` is incompatible
88
session_cli_feature_diagnostic_help =
99
add `-Zcrate-attr="feature({$feature})"` to the command-line options to enable
1010
11-
session_crate_name_does_not_match = `--crate-name` and `#[crate_name]` are required to match, but `{$crate_name}` != `{$attr_crate_name}`
12-
1311
session_crate_name_empty = crate name must not be empty
1412
15-
session_crate_name_invalid = crate names cannot start with a `-`, but `{$s}` has a leading hyphen
16-
1713
session_expr_parentheses_needed = parentheses are required to parse this as an expression
1814
1915
session_failed_to_create_profiler = failed to create profiler: {$err}

Diff for: compiler/rustc_session/src/errors.rs

-15
Original file line numberDiff line numberDiff line change
@@ -193,21 +193,6 @@ pub(crate) struct FileWriteFail<'a> {
193193
pub(crate) err: String,
194194
}
195195

196-
#[derive(Diagnostic)]
197-
#[diag(session_crate_name_does_not_match)]
198-
pub(crate) struct CrateNameDoesNotMatch {
199-
#[primary_span]
200-
pub(crate) span: Span,
201-
pub(crate) crate_name: Symbol,
202-
pub(crate) attr_crate_name: Symbol,
203-
}
204-
205-
#[derive(Diagnostic)]
206-
#[diag(session_crate_name_invalid)]
207-
pub(crate) struct CrateNameInvalid<'a> {
208-
pub(crate) s: &'a str,
209-
}
210-
211196
#[derive(Diagnostic)]
212197
#[diag(session_crate_name_empty)]
213198
pub(crate) struct CrateNameEmpty {

Diff for: compiler/rustc_session/src/output.rs

+3-53
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,9 @@
11
//! Related to out filenames of compilation (e.g. binaries).
22
3-
use crate::config::{self, CrateType, Input, OutFileName, OutputFilenames, OutputType};
4-
use crate::errors::{
5-
self, CrateNameDoesNotMatch, CrateNameEmpty, CrateNameInvalid, FileIsNotWriteable,
6-
InvalidCharacterInCrateName,
7-
};
3+
use crate::config::{self, CrateType, OutFileName, OutputFilenames, OutputType};
4+
use crate::errors::{self, CrateNameEmpty, FileIsNotWriteable, InvalidCharacterInCrateName};
85
use crate::Session;
9-
use rustc_ast::{self as ast, attr};
6+
use rustc_ast as ast;
107
use rustc_errors::FatalError;
118
use rustc_span::symbol::sym;
129
use rustc_span::{Span, Symbol};
@@ -49,53 +46,6 @@ fn is_writeable(p: &Path) -> bool {
4946
}
5047
}
5148

52-
/// Find and [validate] the crate name.
53-
///
54-
/// [validate]: validate_crate_name
55-
pub fn find_crate_name(sess: &Session, attrs: &[ast::Attribute]) -> Symbol {
56-
let validate = |name, span| {
57-
validate_crate_name(sess, name, span);
58-
name
59-
};
60-
61-
// Look in attributes 100% of the time to make sure the attribute is marked
62-
// as used. After doing this, however, we still prioritize a crate name from
63-
// the command line over one found in the #[crate_name] attribute. If we
64-
// find both we ensure that they're the same later on as well.
65-
let attr_crate_name =
66-
attr::find_by_name(attrs, sym::crate_name).and_then(|at| at.value_str().map(|s| (at, s)));
67-
68-
if let Some(crate_name) = &sess.opts.crate_name {
69-
let crate_name = Symbol::intern(crate_name);
70-
if let Some((attr, attr_crate_name)) = attr_crate_name
71-
&& attr_crate_name != crate_name
72-
{
73-
sess.dcx().emit_err(CrateNameDoesNotMatch {
74-
span: attr.span,
75-
crate_name,
76-
attr_crate_name,
77-
});
78-
}
79-
return validate(crate_name, None);
80-
}
81-
82-
if let Some((attr, crate_name)) = attr_crate_name {
83-
return validate(crate_name, Some(attr.span));
84-
}
85-
86-
if let Input::File(ref path) = sess.io.input
87-
&& let Some(s) = path.file_stem().and_then(|s| s.to_str())
88-
{
89-
if s.starts_with('-') {
90-
sess.dcx().emit_err(CrateNameInvalid { s });
91-
} else {
92-
return validate(Symbol::intern(&s.replace('-', "_")), None);
93-
}
94-
}
95-
96-
Symbol::intern("rust_out")
97-
}
98-
9949
/// Validate the given crate name.
10050
///
10151
/// Note that this validation is more permissive than identifier parsing. It considers

0 commit comments

Comments
 (0)