Skip to content

Commit 7530b9b

Browse files
committed
c_variadic: Add future-incompatibility warning for ... arguments without a pattern outside of extern blocks
1 parent 565a9ca commit 7530b9b

28 files changed

+469
-166
lines changed

compiler/rustc_lint_defs/src/builtin.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@ declare_lint_pass! {
142142
UNUSED_UNSAFE,
143143
UNUSED_VARIABLES,
144144
USELESS_DEPRECATED,
145+
VARARGS_WITHOUT_PATTERN,
145146
WARNINGS,
146147
// tidy-alphabetical-end
147148
]
@@ -5195,3 +5196,50 @@ declare_lint! {
51955196
Warn,
51965197
r#"detects when a function annotated with `#[inline(always)]` and `#[target_feature(enable = "..")]` is inlined into a caller without the required target feature"#,
51975198
}
5199+
5200+
declare_lint! {
5201+
/// The `varargs_without_pattern` lint detects when `...` is used as an argument to a
5202+
/// non-foreign function without any pattern being specified.
5203+
///
5204+
/// ### Example
5205+
///
5206+
/// ```rust
5207+
/// // Using `...` in non-foreign function definitions is unstable, however stability is
5208+
/// // currently only checked after attributes are expanded, so using `#[cfg(false)]` here will
5209+
/// // allow this to compile on stable Rust.
5210+
/// #[cfg(false)]
5211+
/// fn foo(...) {
5212+
///
5213+
/// }
5214+
/// ```
5215+
///
5216+
/// {{produces}}
5217+
///
5218+
/// ### Explanation
5219+
///
5220+
/// Patterns are currently required for all non-`...` arguments in function definitions (with
5221+
/// some exceptions in the 2015 edition). Requiring `...` arguments to have patterns in
5222+
/// non-foreign function definitions makes the language more consistent, and removes a source of
5223+
/// confusion for the unstable C variadic feature. `...` arguments without a pattern are already
5224+
/// stable and widely used in foreign function definitions; this lint only affects non-foreign
5225+
/// function definitions.
5226+
///
5227+
/// Using `...` (C varargs) in a non-foreign function definition is currently unstable. However,
5228+
/// stability checking for the `...` syntax in non-foreign function definitions is currently
5229+
/// implemented after attributes have been expanded, meaning that if the attribute removes the
5230+
/// use of the unstable syntax (e.g. `#[cfg(false)]`, or a procedural macro), the code will
5231+
/// compile on stable Rust; this is the only situation where this lint affects code that
5232+
/// compiles on stable Rust.
5233+
///
5234+
/// This is a [future-incompatible] lint to transition this to a hard error in the future.
5235+
///
5236+
/// [future-incompatible]: ../index.md#future-incompatible-lints
5237+
pub VARARGS_WITHOUT_PATTERN,
5238+
Warn,
5239+
"detects usage of `...` arguments without a pattern in non-foreign items",
5240+
@future_incompatible = FutureIncompatibleInfo {
5241+
reason: FutureIncompatibilityReason::FutureReleaseError,
5242+
reference: "issue #145544 <https://github.com/rust-lang/rust/issues/145544>",
5243+
report_in_deps: false,
5244+
};
5245+
}

compiler/rustc_parse/messages.ftl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1009,6 +1009,9 @@ parse_use_if_else = use an `if-else` expression instead
10091009
parse_use_let_not_auto = write `let` instead of `auto` to introduce a new variable
10101010
parse_use_let_not_var = write `let` instead of `var` to introduce a new variable
10111011
1012+
parse_varargs_without_pattern = missing pattern for `...` argument
1013+
.suggestion = name the argument, or use `_` to continue ignoring it
1014+
10121015
parse_visibility_not_followed_by_item = visibility `{$vis}` is not followed by an item
10131016
.label = the visibility
10141017
.help = you likely meant to define an item, e.g., `{$vis} fn foo() {"{}"}`

compiler/rustc_parse/src/errors.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3671,3 +3671,10 @@ impl Subdiagnostic for HiddenUnicodeCodepointsDiagSub {
36713671
}
36723672
}
36733673
}
3674+
3675+
#[derive(LintDiagnostic)]
3676+
#[diag(parse_varargs_without_pattern)]
3677+
pub(crate) struct VarargsWithoutPattern {
3678+
#[suggestion(code = "_: ...", applicability = "machine-applicable")]
3679+
pub span: Span,
3680+
}

compiler/rustc_parse/src/parser/attr.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ impl<'a> Parser<'a> {
201201
AttrWrapper::empty(),
202202
true,
203203
false,
204-
FnParseMode { req_name: |_| true, context: FnContext::Free, req_body: true },
204+
FnParseMode { req_name: |_, _| true, context: FnContext::Free, req_body: true },
205205
ForceCollect::No,
206206
) {
207207
Ok(Some(item)) => {

compiler/rustc_parse/src/parser/diagnostics.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ use crate::errors::{
4646
};
4747
use crate::parser::FnContext;
4848
use crate::parser::attr::InnerAttrPolicy;
49+
use crate::parser::item::IsDotDotDot;
4950
use crate::{exp, fluent_generated as fluent};
5051

5152
/// Creates a placeholder argument.
@@ -2273,7 +2274,7 @@ impl<'a> Parser<'a> {
22732274
let maybe_emit_anon_params_note = |this: &mut Self, err: &mut Diag<'_>| {
22742275
let ed = this.token.span.with_neighbor(this.prev_token.span).edition();
22752276
if matches!(fn_parse_mode.context, crate::parser::item::FnContext::Trait)
2276-
&& (fn_parse_mode.req_name)(ed)
2277+
&& (fn_parse_mode.req_name)(ed, IsDotDotDot::No)
22772278
{
22782279
err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
22792280
}

compiler/rustc_parse/src/parser/item.rs

Lines changed: 42 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use rustc_ast::{self as ast};
1010
use rustc_ast_pretty::pprust;
1111
use rustc_errors::codes::*;
1212
use rustc_errors::{Applicability, PResult, StashKey, struct_span_code_err};
13+
use rustc_session::lint::builtin::VARARGS_WITHOUT_PATTERN;
1314
use rustc_span::edit_distance::edit_distance;
1415
use rustc_span::edition::Edition;
1516
use rustc_span::{DUMMY_SP, ErrorGuaranteed, Ident, Span, Symbol, kw, source_map, sym};
@@ -117,7 +118,7 @@ impl<'a> Parser<'a> {
117118
impl<'a> Parser<'a> {
118119
pub fn parse_item(&mut self, force_collect: ForceCollect) -> PResult<'a, Option<Box<Item>>> {
119120
let fn_parse_mode =
120-
FnParseMode { req_name: |_| true, context: FnContext::Free, req_body: true };
121+
FnParseMode { req_name: |_, _| true, context: FnContext::Free, req_body: true };
121122
self.parse_item_(fn_parse_mode, force_collect).map(|i| i.map(Box::new))
122123
}
123124

@@ -977,7 +978,7 @@ impl<'a> Parser<'a> {
977978
force_collect: ForceCollect,
978979
) -> PResult<'a, Option<Option<Box<AssocItem>>>> {
979980
let fn_parse_mode =
980-
FnParseMode { req_name: |_| true, context: FnContext::Impl, req_body: true };
981+
FnParseMode { req_name: |_, _| true, context: FnContext::Impl, req_body: true };
981982
self.parse_assoc_item(fn_parse_mode, force_collect)
982983
}
983984

@@ -986,7 +987,7 @@ impl<'a> Parser<'a> {
986987
force_collect: ForceCollect,
987988
) -> PResult<'a, Option<Option<Box<AssocItem>>>> {
988989
let fn_parse_mode = FnParseMode {
989-
req_name: |edition| edition >= Edition::Edition2018,
990+
req_name: |edition, _| edition >= Edition::Edition2018,
990991
context: FnContext::Trait,
991992
req_body: false,
992993
};
@@ -1266,8 +1267,11 @@ impl<'a> Parser<'a> {
12661267
&mut self,
12671268
force_collect: ForceCollect,
12681269
) -> PResult<'a, Option<Option<Box<ForeignItem>>>> {
1269-
let fn_parse_mode =
1270-
FnParseMode { req_name: |_| true, context: FnContext::Free, req_body: false };
1270+
let fn_parse_mode = FnParseMode {
1271+
req_name: |_, is_dot_dot_dot| is_dot_dot_dot == IsDotDotDot::No,
1272+
context: FnContext::Free,
1273+
req_body: false,
1274+
};
12711275
Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
12721276
|Item { attrs, id, span, vis, kind, tokens }| {
12731277
let kind = match ForeignItemKind::try_from(kind) {
@@ -2142,7 +2146,7 @@ impl<'a> Parser<'a> {
21422146
Visibility { span: DUMMY_SP, kind: VisibilityKind::Inherited, tokens: None };
21432147
// We use `parse_fn` to get a span for the function
21442148
let fn_parse_mode =
2145-
FnParseMode { req_name: |_| true, context: FnContext::Free, req_body: true };
2149+
FnParseMode { req_name: |_, _| true, context: FnContext::Free, req_body: true };
21462150
match self.parse_fn(
21472151
&mut AttrVec::new(),
21482152
fn_parse_mode,
@@ -2375,8 +2379,16 @@ impl<'a> Parser<'a> {
23752379
/// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
23762380
///
23772381
/// This function pointer accepts an edition, because in edition 2015, trait declarations
2378-
/// were allowed to omit parameter names. In 2018, they became required.
2379-
type ReqName = fn(Edition) -> bool;
2382+
/// were allowed to omit parameter names. In 2018, they became required. It also accepts an
2383+
/// `IsDotDotDot` parameter, as `extern` function declarations and function pointer types are
2384+
/// allowed to omit the name of the `...` but regular function items are not.
2385+
type ReqName = fn(Edition, IsDotDotDot) -> bool;
2386+
2387+
#[derive(Copy, Clone, PartialEq)]
2388+
pub(crate) enum IsDotDotDot {
2389+
Yes,
2390+
No,
2391+
}
23802392

23812393
/// Parsing configuration for functions.
23822394
///
@@ -2409,6 +2421,9 @@ pub(crate) struct FnParseMode {
24092421
/// to true.
24102422
/// * The span is from Edition 2015. In particular, you can get a
24112423
/// 2015 span inside a 2021 crate using macros.
2424+
///
2425+
/// Or if `IsDotDotDot::Yes`, this function will also return `false` if the item being parsed
2426+
/// is inside an `extern` block.
24122427
pub(super) req_name: ReqName,
24132428
/// The context in which this function is parsed, used for diagnostics.
24142429
/// This indicates the fn is a free function or method and so on.
@@ -3055,11 +3070,25 @@ impl<'a> Parser<'a> {
30553070
return Ok((res?, Trailing::No, UsePreAttrPos::No));
30563071
}
30573072

3058-
let is_name_required = match this.token.kind {
3059-
token::DotDotDot => false,
3060-
_ => (fn_parse_mode.req_name)(
3061-
this.token.span.with_neighbor(this.prev_token.span).edition(),
3062-
),
3073+
let is_dot_dot_dot = if this.token.kind == token::DotDotDot {
3074+
IsDotDotDot::Yes
3075+
} else {
3076+
IsDotDotDot::No
3077+
};
3078+
let is_name_required = (fn_parse_mode.req_name)(
3079+
this.token.span.with_neighbor(this.prev_token.span).edition(),
3080+
is_dot_dot_dot,
3081+
);
3082+
let is_name_required = if is_name_required && is_dot_dot_dot == IsDotDotDot::Yes {
3083+
this.psess.buffer_lint(
3084+
VARARGS_WITHOUT_PATTERN,
3085+
this.token.span,
3086+
ast::CRATE_NODE_ID,
3087+
errors::VarargsWithoutPattern { span: this.token.span },
3088+
);
3089+
false
3090+
} else {
3091+
is_name_required
30633092
};
30643093
let (pat, ty) = if is_name_required || this.is_named_param() {
30653094
debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);

compiler/rustc_parse/src/parser/path.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,7 @@ impl<'a> Parser<'a> {
404404
// Inside parenthesized type arguments, we want types only, not names.
405405
let mode = FnParseMode {
406406
context: FnContext::Free,
407-
req_name: |_| false,
407+
req_name: |_, _| false,
408408
req_body: false,
409409
};
410410
let param = p.parse_param_general(&mode, false, false);

compiler/rustc_parse/src/parser/stmt.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ impl<'a> Parser<'a> {
154154
attrs.clone(), // FIXME: unwanted clone of attrs
155155
false,
156156
true,
157-
FnParseMode { req_name: |_| true, context: FnContext::Free, req_body: true },
157+
FnParseMode { req_name: |_, _| true, context: FnContext::Free, req_body: true },
158158
force_collect,
159159
)? {
160160
self.mk_stmt(lo.to(item.span), StmtKind::Item(Box::new(item)))

compiler/rustc_parse/src/parser/ty.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -794,7 +794,7 @@ impl<'a> Parser<'a> {
794794
self.recover_fn_ptr_with_generics(lo, &mut params, param_insertion_point)?;
795795
}
796796
let mode = crate::parser::item::FnParseMode {
797-
req_name: |_| false,
797+
req_name: |_, _| false,
798798
context: FnContext::Free,
799799
req_body: false,
800800
};
@@ -1352,7 +1352,8 @@ impl<'a> Parser<'a> {
13521352
self.bump();
13531353
let args_lo = self.token.span;
13541354
let snapshot = self.create_snapshot_for_diagnostic();
1355-
let mode = FnParseMode { req_name: |_| false, context: FnContext::Free, req_body: false };
1355+
let mode =
1356+
FnParseMode { req_name: |_, _| false, context: FnContext::Free, req_body: false };
13561357
match self.parse_fn_decl(&mode, AllowPlus::No, RecoverReturnSign::OnlyFatArrow) {
13571358
Ok(decl) => {
13581359
self.dcx().emit_err(ExpectedFnPathFoundFnKeyword { fn_token_span });
@@ -1443,7 +1444,8 @@ impl<'a> Parser<'a> {
14431444

14441445
// Parse `(T, U) -> R`.
14451446
let inputs_lo = self.token.span;
1446-
let mode = FnParseMode { req_name: |_| false, context: FnContext::Free, req_body: false };
1447+
let mode =
1448+
FnParseMode { req_name: |_, _| false, context: FnContext::Free, req_body: false };
14471449
let inputs: ThinVec<_> =
14481450
self.parse_fn_params(&mode)?.into_iter().map(|input| input.ty).collect();
14491451
let inputs_span = inputs_lo.to(self.prev_token.span);

tests/crashes/132142.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
//@ known-bug: #132142
22

3-
async extern "cmse-nonsecure-entry" fn fun(...) {}
3+
async extern "cmse-nonsecure-entry" fn fun(_: ...) {}

0 commit comments

Comments
 (0)