Skip to content

Commit c91c91e

Browse files
committed
c_variadic: Add future-incompatibility warning for ... arguments without a pattern outside of extern blocks
1 parent 2f8eeb2 commit c91c91e

27 files changed

+401
-166
lines changed

compiler/rustc_lint/messages.ftl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1018,5 +1018,8 @@ lint_useless_ptr_null_checks_ref = references are not nullable, so checking them
10181018
10191019
lint_uses_power_alignment = repr(C) does not follow the power alignment rule. This may affect platform C ABI compatibility for this type
10201020
1021+
lint_varargs_without_pattern = missing pattern for `...` argument
1022+
.suggestion = name the argument, or use `_` to continue ignoring it
1023+
10211024
lint_variant_size_differences =
10221025
enum variant is more than three times larger ({$largest} bytes) than the next largest

compiler/rustc_lint/src/early/diagnostics.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -468,5 +468,8 @@ pub fn decorate_builtin_lint(
468468
BuiltinLintDiag::UnexpectedBuiltinCfg { cfg, cfg_name, controlled_by } => {
469469
lints::UnexpectedBuiltinCfg { cfg, cfg_name, controlled_by }.decorate_lint(diag)
470470
}
471+
BuiltinLintDiag::VarargsWithoutPattern { span } => {
472+
lints::VarargsWithoutPattern { span }.decorate_lint(diag)
473+
}
471474
}
472475
}

compiler/rustc_lint/src/lints.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3193,6 +3193,13 @@ pub(crate) struct ReservedMultihash {
31933193
pub suggestion: Span,
31943194
}
31953195

3196+
#[derive(LintDiagnostic)]
3197+
#[diag(lint_varargs_without_pattern)]
3198+
pub(crate) struct VarargsWithoutPattern {
3199+
#[suggestion(code = "_: ...", applicability = "machine-applicable")]
3200+
pub span: Span,
3201+
}
3202+
31963203
#[derive(Debug)]
31973204
pub(crate) struct MismatchedLifetimeSyntaxes {
31983205
pub lifetime_name: String,

compiler/rustc_lint_defs/src/builtin.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@ declare_lint_pass! {
138138
UNUSED_UNSAFE,
139139
UNUSED_VARIABLES,
140140
USELESS_DEPRECATED,
141+
VARARGS_WITHOUT_PATTERN,
141142
WARNINGS,
142143
// tidy-alphabetical-end
143144
]
@@ -5021,3 +5022,50 @@ declare_lint! {
50215022
report_in_deps: true,
50225023
};
50235024
}
5025+
5026+
declare_lint! {
5027+
/// The `varargs_without_pattern` lint detects when `...` is used as an argument to a
5028+
/// non-foreign function without any pattern being specified.
5029+
///
5030+
/// ### Example
5031+
///
5032+
/// ```rust
5033+
/// // Using `...` in non-foreign function definitions is unstable, however stability is
5034+
/// // currently only checked after attributes are expanded, so using `#[cfg(false)]` here will
5035+
/// // allow this to compile on stable Rust.
5036+
/// #[cfg(false)]
5037+
/// fn foo(...) {
5038+
///
5039+
/// }
5040+
/// ```
5041+
///
5042+
/// {{produces}}
5043+
///
5044+
/// ### Explanation
5045+
///
5046+
/// Patterns are currently required for all non-`...` arguments in function definitions (with
5047+
/// some exceptions in the 2015 edition). Requiring `...` arguments to have patterns in
5048+
/// non-foreign function defitions makes the language more consistent, and removes a source of
5049+
/// confusion for the unstable C variadic feature. `...` arguments without a pattern are already
5050+
/// stable and widely used in foreign function definitions; this lint only affects non-foreign
5051+
/// function defitions.
5052+
///
5053+
/// Using `...` (C varargs) in a non-foreign function definition is currently unstable. However,
5054+
/// stability checking for the `...` syntax in non-foreign function definitions is currently
5055+
/// implemented after attributes have been expanded, meaning that if the attribute removes the
5056+
/// use of the unstable syntax (e.g. `#[cfg(false)]`, or a procedural macro), the code will
5057+
/// compile on stable Rust; this is the only situtation where this lint affects code that
5058+
/// compiles on stable Rust.
5059+
///
5060+
/// This is a [future-incompatible] lint to transition this to a hard error in the future.
5061+
///
5062+
/// [future-incompatible]: ../index.md#future-incompatible-lints
5063+
pub VARARGS_WITHOUT_PATTERN,
5064+
Warn,
5065+
"detects usage of `...` arguments without a pattern in non-foreign items",
5066+
@future_incompatible = FutureIncompatibleInfo {
5067+
reason: FutureIncompatibilityReason::FutureReleaseError,
5068+
reference: "issue #FIXME <https://github.com/rust-lang/rust/issues/FIXME>",
5069+
report_in_deps: false,
5070+
};
5071+
}

compiler/rustc_lint_defs/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -802,6 +802,9 @@ pub enum BuiltinLintDiag {
802802
cfg_name: Symbol,
803803
controlled_by: &'static str,
804804
},
805+
VarargsWithoutPattern {
806+
span: Span,
807+
},
805808
}
806809

807810
/// Lints that are buffered up early on in the `Session` before the

compiler/rustc_parse/src/parser/attr.rs

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

compiler/rustc_parse/src/parser/item.rs

Lines changed: 41 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ use rustc_ast::{self as ast};
1111
use rustc_ast_pretty::pprust;
1212
use rustc_errors::codes::*;
1313
use rustc_errors::{Applicability, PResult, StashKey, struct_span_code_err};
14+
use rustc_session::lint::BuiltinLintDiag;
15+
use rustc_session::lint::builtin::VARARGS_WITHOUT_PATTERN;
1416
use rustc_span::edit_distance::edit_distance;
1517
use rustc_span::edition::Edition;
1618
use rustc_span::{DUMMY_SP, ErrorGuaranteed, Ident, Span, Symbol, kw, source_map, sym};
@@ -117,7 +119,7 @@ impl<'a> Parser<'a> {
117119

118120
impl<'a> Parser<'a> {
119121
pub fn parse_item(&mut self, force_collect: ForceCollect) -> PResult<'a, Option<P<Item>>> {
120-
let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
122+
let fn_parse_mode = FnParseMode { req_name: |_, _| true, req_body: true };
121123
self.parse_item_(fn_parse_mode, force_collect).map(|i| i.map(P))
122124
}
123125

@@ -935,7 +937,7 @@ impl<'a> Parser<'a> {
935937
&mut self,
936938
force_collect: ForceCollect,
937939
) -> PResult<'a, Option<Option<P<AssocItem>>>> {
938-
let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
940+
let fn_parse_mode = FnParseMode { req_name: |_, _| true, req_body: true };
939941
self.parse_assoc_item(fn_parse_mode, force_collect)
940942
}
941943

@@ -944,7 +946,7 @@ impl<'a> Parser<'a> {
944946
force_collect: ForceCollect,
945947
) -> PResult<'a, Option<Option<P<AssocItem>>>> {
946948
let fn_parse_mode =
947-
FnParseMode { req_name: |edition| edition >= Edition::Edition2018, req_body: false };
949+
FnParseMode { req_name: |edition, _| edition >= Edition::Edition2018, req_body: false };
948950
self.parse_assoc_item(fn_parse_mode, force_collect)
949951
}
950952

@@ -1221,7 +1223,10 @@ impl<'a> Parser<'a> {
12211223
&mut self,
12221224
force_collect: ForceCollect,
12231225
) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
1224-
let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: false };
1226+
let fn_parse_mode = FnParseMode {
1227+
req_name: |_, is_dot_dot_dot| is_dot_dot_dot == IsDotDotDot::No,
1228+
req_body: false,
1229+
};
12251230
Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
12261231
|Item { attrs, id, span, vis, kind, tokens }| {
12271232
let kind = match ForeignItemKind::try_from(kind) {
@@ -2093,7 +2098,7 @@ impl<'a> Parser<'a> {
20932098
let inherited_vis =
20942099
Visibility { span: DUMMY_SP, kind: VisibilityKind::Inherited, tokens: None };
20952100
// We use `parse_fn` to get a span for the function
2096-
let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
2101+
let fn_parse_mode = FnParseMode { req_name: |_, _| true, req_body: true };
20972102
match self.parse_fn(
20982103
&mut AttrVec::new(),
20992104
fn_parse_mode,
@@ -2326,8 +2331,16 @@ impl<'a> Parser<'a> {
23262331
/// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
23272332
///
23282333
/// This function pointer accepts an edition, because in edition 2015, trait declarations
2329-
/// were allowed to omit parameter names. In 2018, they became required.
2330-
type ReqName = fn(Edition) -> bool;
2334+
/// were allowed to omit parameter names. In 2018, they became required. It also accepts an
2335+
/// `IsDotDotDot` parameter, as `extern` function declarations and function pointer types are
2336+
/// allowed to omit the name of the `...` but regular function items are not.
2337+
type ReqName = fn(Edition, IsDotDotDot) -> bool;
2338+
2339+
#[derive(Copy, Clone, PartialEq)]
2340+
pub(crate) enum IsDotDotDot {
2341+
Yes,
2342+
No,
2343+
}
23312344

23322345
/// Parsing configuration for functions.
23332346
///
@@ -2360,6 +2373,8 @@ pub(crate) struct FnParseMode {
23602373
/// to true.
23612374
/// * The span is from Edition 2015. In particular, you can get a
23622375
/// 2015 span inside a 2021 crate using macros.
2376+
///
2377+
/// Or if `IsDotDotDot::Yes`, this function will also return `false` with an `extern` block.
23632378
pub(super) req_name: ReqName,
23642379
/// If this flag is set to `true`, then plain, semicolon-terminated function
23652380
/// prototypes are not allowed here.
@@ -2991,9 +3006,25 @@ impl<'a> Parser<'a> {
29913006
return Ok((res?, Trailing::No, UsePreAttrPos::No));
29923007
}
29933008

2994-
let is_name_required = match this.token.kind {
2995-
token::DotDotDot => false,
2996-
_ => req_name(this.token.span.with_neighbor(this.prev_token.span).edition()),
3009+
let is_dot_dot_dot = if this.token.kind == token::DotDotDot {
3010+
IsDotDotDot::Yes
3011+
} else {
3012+
IsDotDotDot::No
3013+
};
3014+
let is_name_required = req_name(
3015+
this.token.span.with_neighbor(this.prev_token.span).edition(),
3016+
is_dot_dot_dot,
3017+
);
3018+
let is_name_required = if is_name_required && is_dot_dot_dot == IsDotDotDot::Yes {
3019+
this.psess.buffer_lint(
3020+
VARARGS_WITHOUT_PATTERN,
3021+
this.token.span,
3022+
ast::CRATE_NODE_ID,
3023+
BuiltinLintDiag::VarargsWithoutPattern { span: this.token.span },
3024+
);
3025+
false
3026+
} else {
3027+
is_name_required
29973028
};
29983029
let (pat, ty) = if is_name_required || this.is_named_param() {
29993030
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
@@ -400,7 +400,7 @@ impl<'a> Parser<'a> {
400400

401401
let dcx = self.dcx();
402402
let parse_params_result = self.parse_paren_comma_seq(|p| {
403-
let param = p.parse_param_general(|_| false, false, false);
403+
let param = p.parse_param_general(|_, _| false, false, false);
404404
param.map(move |param| {
405405
if !matches!(param.pat.kind, PatKind::Missing) {
406406
dcx.emit_err(FnPathFoundNamedParams {

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, req_body: true },
157+
FnParseMode { req_name: |_, _| true, req_body: true },
158158
force_collect,
159159
)? {
160160
self.mk_stmt(lo.to(item.span), StmtKind::Item(P(item)))

compiler/rustc_parse/src/parser/ty.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -695,7 +695,7 @@ impl<'a> Parser<'a> {
695695
if self.may_recover() && self.token == TokenKind::Lt {
696696
self.recover_fn_ptr_with_generics(lo, &mut params, param_insertion_point)?;
697697
}
698-
let decl = self.parse_fn_decl(|_| false, AllowPlus::No, recover_return_sign)?;
698+
let decl = self.parse_fn_decl(|_, _| false, AllowPlus::No, recover_return_sign)?;
699699

700700
let decl_span = span_start.to(self.prev_token.span);
701701
Ok(TyKind::FnPtr(P(FnPtrTy { ext, safety, generic_params: params, decl, decl_span })))
@@ -1234,7 +1234,7 @@ impl<'a> Parser<'a> {
12341234
self.bump();
12351235
let args_lo = self.token.span;
12361236
let snapshot = self.create_snapshot_for_diagnostic();
1237-
match self.parse_fn_decl(|_| false, AllowPlus::No, RecoverReturnSign::OnlyFatArrow) {
1237+
match self.parse_fn_decl(|_, _| false, AllowPlus::No, RecoverReturnSign::OnlyFatArrow) {
12381238
Ok(decl) => {
12391239
self.dcx().emit_err(ExpectedFnPathFoundFnKeyword { fn_token_span });
12401240
Some(ast::Path {
@@ -1319,7 +1319,7 @@ impl<'a> Parser<'a> {
13191319
// Parse `(T, U) -> R`.
13201320
let inputs_lo = self.token.span;
13211321
let inputs: ThinVec<_> =
1322-
self.parse_fn_params(|_| false)?.into_iter().map(|input| input.ty).collect();
1322+
self.parse_fn_params(|_, _| false)?.into_iter().map(|input| input.ty).collect();
13231323
let inputs_span = inputs_lo.to(self.prev_token.span);
13241324
let output = self.parse_ret_ty(AllowPlus::No, RecoverQPath::No, RecoverReturnSign::No)?;
13251325
let args = ast::ParenthesizedArgs {

0 commit comments

Comments
 (0)