Skip to content

Commit f6e6ddc

Browse files
committed
Auto merge of #88680 - ehuss:more-attr-validation, r=petrochenkov
Validate builtin attributes for macro args. This adds some validation for `path`, `crate_type`, and `recursion_limit` attributes so that they will now return an error if you attempt to pass a macro into them (such as `#[path = foo!()]`). Previously, the attribute would be completely ignored. These attributes are special because their values need to be known before/during expansion. cc #87681
2 parents 4da89a1 + 75f058d commit f6e6ddc

21 files changed

+211
-76
lines changed

compiler/rustc_expand/src/module.rs

+20-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use rustc_ast::ptr::P;
33
use rustc_ast::{token, Attribute, Inline, Item};
44
use rustc_errors::{struct_span_err, DiagnosticBuilder};
55
use rustc_parse::new_parser_from_file;
6+
use rustc_parse::validate_attr;
67
use rustc_session::parse::ParseSess;
78
use rustc_session::Session;
89
use rustc_span::symbol::{sym, Ident};
@@ -168,7 +169,25 @@ fn mod_file_path_from_attr(
168169
dir_path: &Path,
169170
) -> Option<PathBuf> {
170171
// Extract path string from first `#[path = "path_string"]` attribute.
171-
let path_string = sess.first_attr_value_str_by_name(attrs, sym::path)?.as_str();
172+
let first_path = attrs.iter().find(|at| at.has_name(sym::path))?;
173+
let path_string = match first_path.value_str() {
174+
Some(s) => s.as_str(),
175+
None => {
176+
// This check is here mainly to catch attempting to use a macro,
177+
// such as #[path = concat!(...)]. This isn't currently supported
178+
// because otherwise the InvocationCollector would need to defer
179+
// loading a module until the #[path] attribute was expanded, and
180+
// it doesn't support that (and would likely add a bit of
181+
// complexity). Usually bad forms are checked in AstValidator (via
182+
// `check_builtin_attribute`), but by the time that runs the macro
183+
// is expanded, and it doesn't give an error.
184+
validate_attr::emit_fatal_malformed_builtin_attribute(
185+
&sess.parse_sess,
186+
first_path,
187+
sym::path,
188+
);
189+
}
190+
};
172191

173192
// On windows, the base path might have the form
174193
// `\\?\foo\bar` in which case it does not tolerate

compiler/rustc_interface/src/passes.rs

+25-5
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ use rustc_middle::middle::cstore::{MetadataLoader, MetadataLoaderDyn};
2323
use rustc_middle::ty::query::Providers;
2424
use rustc_middle::ty::{self, GlobalCtxt, ResolverOutputs, TyCtxt};
2525
use rustc_mir_build as mir_build;
26-
use rustc_parse::{parse_crate_from_file, parse_crate_from_source_str};
26+
use rustc_parse::{parse_crate_from_file, parse_crate_from_source_str, validate_attr};
2727
use rustc_passes::{self, hir_stats, layout_test};
2828
use rustc_plugin_impl as plugin;
2929
use rustc_query_impl::{OnDiskCache, Queries as TcxQueries};
@@ -33,8 +33,8 @@ use rustc_session::config::{CrateType, Input, OutputFilenames, OutputType, PpMod
3333
use rustc_session::lint;
3434
use rustc_session::output::{filename_for_input, filename_for_metadata};
3535
use rustc_session::search_paths::PathKind;
36-
use rustc_session::Session;
37-
use rustc_span::symbol::{Ident, Symbol};
36+
use rustc_session::{Limit, Session};
37+
use rustc_span::symbol::{sym, Ident, Symbol};
3838
use rustc_span::FileName;
3939
use rustc_trait_selection::traits;
4040
use rustc_typeck as typeck;
@@ -311,8 +311,7 @@ pub fn configure_and_expand(
311311

312312
// Create the config for macro expansion
313313
let features = sess.features_untracked();
314-
let recursion_limit =
315-
rustc_middle::middle::limits::get_recursion_limit(&krate.attrs, &sess);
314+
let recursion_limit = get_recursion_limit(&krate.attrs, &sess);
316315
let cfg = rustc_expand::expand::ExpansionConfig {
317316
features: Some(&features),
318317
recursion_limit,
@@ -1070,3 +1069,24 @@ pub fn start_codegen<'tcx>(
10701069

10711070
codegen
10721071
}
1072+
1073+
fn get_recursion_limit(krate_attrs: &[ast::Attribute], sess: &Session) -> Limit {
1074+
if let Some(attr) = krate_attrs
1075+
.iter()
1076+
.find(|attr| attr.has_name(sym::recursion_limit) && attr.value_str().is_none())
1077+
{
1078+
// This is here mainly to check for using a macro, such as
1079+
// #![recursion_limit = foo!()]. That is not supported since that
1080+
// would require expanding this while in the middle of expansion,
1081+
// which needs to know the limit before expanding. Otherwise,
1082+
// validation would normally be caught in AstValidator (via
1083+
// `check_builtin_attribute`), but by the time that runs the macro
1084+
// is expanded, and it doesn't give an error.
1085+
validate_attr::emit_fatal_malformed_builtin_attribute(
1086+
&sess.parse_sess,
1087+
attr,
1088+
sym::recursion_limit,
1089+
);
1090+
}
1091+
rustc_middle::middle::limits::get_recursion_limit(krate_attrs, sess)
1092+
}

compiler/rustc_interface/src/util.rs

+15-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use rustc_errors::registry::Registry;
1010
use rustc_metadata::dynamic_lib::DynamicLibrary;
1111
#[cfg(parallel_compiler)]
1212
use rustc_middle::ty::tls;
13+
use rustc_parse::validate_attr;
1314
#[cfg(parallel_compiler)]
1415
use rustc_query_impl::QueryCtxt;
1516
use rustc_resolve::{self, Resolver};
@@ -475,7 +476,7 @@ pub fn get_codegen_sysroot(
475476
}
476477

477478
pub(crate) fn check_attr_crate_type(
478-
_sess: &Session,
479+
sess: &Session,
479480
attrs: &[ast::Attribute],
480481
lint_buffer: &mut LintBuffer,
481482
) {
@@ -515,6 +516,19 @@ pub(crate) fn check_attr_crate_type(
515516
);
516517
}
517518
}
519+
} else {
520+
// This is here mainly to check for using a macro, such as
521+
// #![crate_type = foo!()]. That is not supported since the
522+
// crate type needs to be known very early in compilation long
523+
// before expansion. Otherwise, validation would normally be
524+
// caught in AstValidator (via `check_builtin_attribute`), but
525+
// by the time that runs the macro is expanded, and it doesn't
526+
// give an error.
527+
validate_attr::emit_fatal_malformed_builtin_attribute(
528+
&sess.parse_sess,
529+
a,
530+
sym::crate_type,
531+
);
518532
}
519533
}
520534
}

compiler/rustc_parse/src/validate_attr.rs

+73-60
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use crate::parse_in;
44

55
use rustc_ast::tokenstream::{DelimSpan, TokenTree};
66
use rustc_ast::{self as ast, Attribute, MacArgs, MacDelimiter, MetaItem, MetaItemKind};
7-
use rustc_errors::{Applicability, PResult};
7+
use rustc_errors::{Applicability, FatalError, PResult};
88
use rustc_feature::{AttributeTemplate, BUILTIN_ATTRIBUTE_MAP};
99
use rustc_session::lint::builtin::ILL_FORMED_ATTRIBUTE_INPUT;
1010
use rustc_session::parse::ParseSess;
@@ -91,73 +91,86 @@ pub fn check_builtin_attribute(
9191
// Some special attributes like `cfg` must be checked
9292
// before the generic check, so we skip them here.
9393
let should_skip = |name| name == sym::cfg;
94-
// Some of previously accepted forms were used in practice,
95-
// report them as warnings for now.
96-
let should_warn = |name| {
97-
name == sym::doc
98-
|| name == sym::ignore
99-
|| name == sym::inline
100-
|| name == sym::link
101-
|| name == sym::test
102-
|| name == sym::bench
103-
};
10494

10595
match parse_meta(sess, attr) {
10696
Ok(meta) => {
10797
if !should_skip(name) && !is_attr_template_compatible(&template, &meta.kind) {
108-
let error_msg = format!("malformed `{}` attribute input", name);
109-
let mut msg = "attribute must be of the form ".to_owned();
110-
let mut suggestions = vec![];
111-
let mut first = true;
112-
if template.word {
113-
first = false;
114-
let code = format!("#[{}]", name);
115-
msg.push_str(&format!("`{}`", &code));
116-
suggestions.push(code);
117-
}
118-
if let Some(descr) = template.list {
119-
if !first {
120-
msg.push_str(" or ");
121-
}
122-
first = false;
123-
let code = format!("#[{}({})]", name, descr);
124-
msg.push_str(&format!("`{}`", &code));
125-
suggestions.push(code);
126-
}
127-
if let Some(descr) = template.name_value_str {
128-
if !first {
129-
msg.push_str(" or ");
130-
}
131-
let code = format!("#[{} = \"{}\"]", name, descr);
132-
msg.push_str(&format!("`{}`", &code));
133-
suggestions.push(code);
134-
}
135-
if should_warn(name) {
136-
sess.buffer_lint(
137-
&ILL_FORMED_ATTRIBUTE_INPUT,
138-
meta.span,
139-
ast::CRATE_NODE_ID,
140-
&msg,
141-
);
142-
} else {
143-
sess.span_diagnostic
144-
.struct_span_err(meta.span, &error_msg)
145-
.span_suggestions(
146-
meta.span,
147-
if suggestions.len() == 1 {
148-
"must be of the form"
149-
} else {
150-
"the following are the possible correct uses"
151-
},
152-
suggestions.into_iter(),
153-
Applicability::HasPlaceholders,
154-
)
155-
.emit();
156-
}
98+
emit_malformed_attribute(sess, attr, name, template);
15799
}
158100
}
159101
Err(mut err) => {
160102
err.emit();
161103
}
162104
}
163105
}
106+
107+
fn emit_malformed_attribute(
108+
sess: &ParseSess,
109+
attr: &Attribute,
110+
name: Symbol,
111+
template: AttributeTemplate,
112+
) {
113+
// Some of previously accepted forms were used in practice,
114+
// report them as warnings for now.
115+
let should_warn = |name| {
116+
matches!(name, sym::doc | sym::ignore | sym::inline | sym::link | sym::test | sym::bench)
117+
};
118+
119+
let error_msg = format!("malformed `{}` attribute input", name);
120+
let mut msg = "attribute must be of the form ".to_owned();
121+
let mut suggestions = vec![];
122+
let mut first = true;
123+
let inner = if attr.style == ast::AttrStyle::Inner { "!" } else { "" };
124+
if template.word {
125+
first = false;
126+
let code = format!("#{}[{}]", inner, name);
127+
msg.push_str(&format!("`{}`", &code));
128+
suggestions.push(code);
129+
}
130+
if let Some(descr) = template.list {
131+
if !first {
132+
msg.push_str(" or ");
133+
}
134+
first = false;
135+
let code = format!("#{}[{}({})]", inner, name, descr);
136+
msg.push_str(&format!("`{}`", &code));
137+
suggestions.push(code);
138+
}
139+
if let Some(descr) = template.name_value_str {
140+
if !first {
141+
msg.push_str(" or ");
142+
}
143+
let code = format!("#{}[{} = \"{}\"]", inner, name, descr);
144+
msg.push_str(&format!("`{}`", &code));
145+
suggestions.push(code);
146+
}
147+
if should_warn(name) {
148+
sess.buffer_lint(&ILL_FORMED_ATTRIBUTE_INPUT, attr.span, ast::CRATE_NODE_ID, &msg);
149+
} else {
150+
sess.span_diagnostic
151+
.struct_span_err(attr.span, &error_msg)
152+
.span_suggestions(
153+
attr.span,
154+
if suggestions.len() == 1 {
155+
"must be of the form"
156+
} else {
157+
"the following are the possible correct uses"
158+
},
159+
suggestions.into_iter(),
160+
Applicability::HasPlaceholders,
161+
)
162+
.emit();
163+
}
164+
}
165+
166+
pub fn emit_fatal_malformed_builtin_attribute(
167+
sess: &ParseSess,
168+
attr: &Attribute,
169+
name: Symbol,
170+
) -> ! {
171+
let template = BUILTIN_ATTRIBUTE_MAP.get(&name).expect("builtin attr defined").2;
172+
emit_malformed_attribute(sess, attr, name, template);
173+
// This is fatal, otherwise it will likely cause a cascade of other errors
174+
// (and an error here is expected to be very rare).
175+
FatalError.raise()
176+
}

src/test/ui/attributes/register-attr-tool-fail.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,13 @@ error: malformed `register_attr` attribute input
3030
--> $DIR/register-attr-tool-fail.rs:4:1
3131
|
3232
LL | #![register_attr]
33-
| ^^^^^^^^^^^^^^^^^ help: must be of the form: `#[register_attr(attr1, attr2, ...)]`
33+
| ^^^^^^^^^^^^^^^^^ help: must be of the form: `#![register_attr(attr1, attr2, ...)]`
3434

3535
error: malformed `register_tool` attribute input
3636
--> $DIR/register-attr-tool-fail.rs:5:1
3737
|
3838
LL | #![register_tool]
39-
| ^^^^^^^^^^^^^^^^^ help: must be of the form: `#[register_tool(tool1, tool2, ...)]`
39+
| ^^^^^^^^^^^^^^^^^ help: must be of the form: `#![register_tool(tool1, tool2, ...)]`
4040

4141
error: aborting due to 6 previous errors
4242

src/test/ui/gated-bad-feature.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,13 @@ error: malformed `feature` attribute input
2020
--> $DIR/gated-bad-feature.rs:5:1
2121
|
2222
LL | #![feature]
23-
| ^^^^^^^^^^^ help: must be of the form: `#[feature(name1, name1, ...)]`
23+
| ^^^^^^^^^^^ help: must be of the form: `#![feature(name1, name1, ...)]`
2424

2525
error: malformed `feature` attribute input
2626
--> $DIR/gated-bad-feature.rs:6:1
2727
|
2828
LL | #![feature = "foo"]
29-
| ^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#[feature(name1, name1, ...)]`
29+
| ^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#![feature(name1, name1, ...)]`
3030

3131
error: aborting due to 5 previous errors
3232

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#![crate_type = foo!()] //~ ERROR malformed `crate_type` attribute
2+
3+
macro_rules! foo {
4+
() => {"rlib"};
5+
}
6+
7+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
error: malformed `crate_type` attribute input
2+
--> $DIR/invalid-crate-type-macro.rs:1:1
3+
|
4+
LL | #![crate_type = foo!()]
5+
| ^^^^^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#![crate_type = "bin|lib|..."]`
6+
7+
error: aborting due to previous error
8+

src/test/ui/invalid_crate_type_syntax.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ error: malformed `crate_type` attribute input
22
--> $DIR/invalid_crate_type_syntax.rs:2:1
33
|
44
LL | #![crate_type(lib)]
5-
| ^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#[crate_type = "bin|lib|..."]`
5+
| ^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#![crate_type = "bin|lib|..."]`
66

77
error: aborting due to previous error
88

src/test/ui/lint/lint-malformed.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ error: malformed `deny` attribute input
1414
--> $DIR/lint-malformed.rs:1:1
1515
|
1616
LL | #![deny = "foo"]
17-
| ^^^^^^^^^^^^^^^^ help: must be of the form: `#[deny(lint1, lint2, ..., /*opt*/ reason = "...")]`
17+
| ^^^^^^^^^^^^^^^^ help: must be of the form: `#![deny(lint1, lint2, ..., /*opt*/ reason = "...")]`
1818

1919
error[E0452]: malformed lint attribute input
2020
--> $DIR/lint-malformed.rs:2:10

src/test/ui/malformed/malformed-plugin-1.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ error: malformed `plugin` attribute input
22
--> $DIR/malformed-plugin-1.rs:2:1
33
|
44
LL | #![plugin]
5-
| ^^^^^^^^^^ help: must be of the form: `#[plugin(name)]`
5+
| ^^^^^^^^^^ help: must be of the form: `#![plugin(name)]`
66

77
warning: use of deprecated attribute `plugin`: compiler plugins are deprecated. See https://github.com/rust-lang/rust/pull/64675
88
--> $DIR/malformed-plugin-1.rs:2:1

src/test/ui/malformed/malformed-plugin-2.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ error: malformed `plugin` attribute input
22
--> $DIR/malformed-plugin-2.rs:2:1
33
|
44
LL | #![plugin="bleh"]
5-
| ^^^^^^^^^^^^^^^^^ help: must be of the form: `#[plugin(name)]`
5+
| ^^^^^^^^^^^^^^^^^ help: must be of the form: `#![plugin(name)]`
66

77
warning: use of deprecated attribute `plugin`: compiler plugins are deprecated. See https://github.com/rust-lang/rust/pull/64675
88
--> $DIR/malformed-plugin-2.rs:2:1
+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
#[path = 123] //~ ERROR malformed `path` attribute
2+
mod foo;
3+
4+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
error: malformed `path` attribute input
2+
--> $DIR/path-invalid-form.rs:1:1
3+
|
4+
LL | #[path = 123]
5+
| ^^^^^^^^^^^^^ help: must be of the form: `#[path = "file"]`
6+
7+
error: aborting due to previous error
8+

src/test/ui/modules/path-macro.rs

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
macro_rules! foo {
2+
() => {"bar.rs"};
3+
}
4+
5+
#[path = foo!()] //~ ERROR malformed `path` attribute
6+
mod abc;
7+
8+
fn main() {}

src/test/ui/modules/path-macro.stderr

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
error: malformed `path` attribute input
2+
--> $DIR/path-macro.rs:5:1
3+
|
4+
LL | #[path = foo!()]
5+
| ^^^^^^^^^^^^^^^^ help: must be of the form: `#[path = "file"]`
6+
7+
error: aborting due to previous error
8+

0 commit comments

Comments
 (0)