Skip to content

Commit 5545959

Browse files
committed
Auto merge of rust-lang#136116 - fmease:rollup-c8pk3mj, r=fmease
Rollup of 8 pull requests Successful merges: - rust-lang#126604 (Uplift `clippy::double_neg` lint as `double_negations`) - rust-lang#135158 (Add `TooGeneric` variant to `LayoutError` and emit `Unknown`) - rust-lang#135635 (Move `std::io::pipe` code into its own file) - rust-lang#136072 (add two old crash tests) - rust-lang#136079 (compiler_fence: fix example) - rust-lang#136091 (Add some tracing to core bootstrap logic) - rust-lang#136097 (rustc_ast: replace some len-checks + indexing with slice patterns etc.) - rust-lang#136101 (triagebot: set myself on vacation) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 633a3fe + 03cc387 commit 5545959

File tree

67 files changed

+974
-576
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

67 files changed

+974
-576
lines changed

compiler/rustc_ast/src/ast.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ pub struct Path {
100100
impl PartialEq<Symbol> for Path {
101101
#[inline]
102102
fn eq(&self, symbol: &Symbol) -> bool {
103-
self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
103+
matches!(&self.segments[..], [segment] if segment.ident.name == *symbol)
104104
}
105105
}
106106

@@ -121,13 +121,13 @@ impl Path {
121121
}
122122

123123
pub fn is_global(&self) -> bool {
124-
!self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
124+
self.segments.first().is_some_and(|segment| segment.ident.name == kw::PathRoot)
125125
}
126126

127127
/// If this path is a single identifier with no arguments, does not ensure
128128
/// that the path resolves to a const param, the caller should check this.
129129
pub fn is_potential_trivial_const_arg(&self) -> bool {
130-
self.segments.len() == 1 && self.segments[0].args.is_none()
130+
matches!(self.segments[..], [PathSegment { args: None, .. }])
131131
}
132132
}
133133

compiler/rustc_ast/src/attr/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,7 @@ impl AttrItem {
302302
impl MetaItem {
303303
/// For a single-segment meta item, returns its name; otherwise, returns `None`.
304304
pub fn ident(&self) -> Option<Ident> {
305-
if self.path.segments.len() == 1 { Some(self.path.segments[0].ident) } else { None }
305+
if let [PathSegment { ident, .. }] = self.path.segments[..] { Some(ident) } else { None }
306306
}
307307

308308
pub fn name_or_empty(&self) -> Symbol {

compiler/rustc_ast/src/mut_visit.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -1813,10 +1813,10 @@ pub fn walk_flat_map_stmt<T: MutVisitor>(
18131813
.into_iter()
18141814
.map(|kind| Stmt { id, kind, span })
18151815
.collect();
1816-
match stmts.len() {
1817-
0 => {}
1818-
1 => vis.visit_span(&mut stmts[0].span),
1819-
2.. => panic!(
1816+
match &mut stmts[..] {
1817+
[] => {}
1818+
[stmt] => vis.visit_span(&mut stmt.span),
1819+
_ => panic!(
18201820
"cloning statement `NodeId`s is prohibited by default, \
18211821
the visitor should implement custom statement visiting"
18221822
),

compiler/rustc_ast/src/util/comments.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ pub fn beautify_doc_string(data: Symbol, kind: CommentKind) -> Symbol {
3939
let mut i = 0;
4040
let mut j = lines.len();
4141
// first line of all-stars should be omitted
42-
if !lines.is_empty() && lines[0].chars().all(|c| c == '*') {
42+
if lines.first().is_some_and(|line| line.chars().all(|c| c == '*')) {
4343
i += 1;
4444
}
4545

@@ -97,7 +97,7 @@ pub fn beautify_doc_string(data: Symbol, kind: CommentKind) -> Symbol {
9797
return None;
9898
}
9999
}
100-
if lines.is_empty() { None } else { Some(lines[0][..i].into()) }
100+
Some(lines.first()?[..i].to_string())
101101
}
102102

103103
let data_s = data.as_str();

compiler/rustc_const_eval/src/const_eval/error.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ where
140140
// Don't emit a new diagnostic for these errors, they are already reported elsewhere or
141141
// should remain silent.
142142
err_inval!(AlreadyReported(info)) => ErrorHandled::Reported(info, span),
143-
err_inval!(Layout(LayoutError::Unknown(_))) | err_inval!(TooGeneric) => {
143+
err_inval!(Layout(LayoutError::TooGeneric(_))) | err_inval!(TooGeneric) => {
144144
ErrorHandled::TooGeneric(span)
145145
}
146146
err_inval!(Layout(LayoutError::ReferencesError(guar))) => {

compiler/rustc_hir_analysis/src/hir_ty_lowering/cmse.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ fn should_emit_generic_error<'tcx>(abi: ExternAbi, layout_err: &'tcx LayoutError
201201
use LayoutError::*;
202202

203203
match layout_err {
204-
Unknown(ty) => {
204+
TooGeneric(ty) => {
205205
match abi {
206206
ExternAbi::CCmseNonSecureCall => {
207207
// prevent double reporting of this error
@@ -211,7 +211,11 @@ fn should_emit_generic_error<'tcx>(abi: ExternAbi, layout_err: &'tcx LayoutError
211211
_ => bug!("invalid ABI: {abi}"),
212212
}
213213
}
214-
SizeOverflow(..) | NormalizationFailure(..) | ReferencesError(..) | Cycle(..) => {
214+
Unknown(..)
215+
| SizeOverflow(..)
216+
| NormalizationFailure(..)
217+
| ReferencesError(..)
218+
| Cycle(..) => {
215219
false // not our job to report these
216220
}
217221
}

compiler/rustc_hir_typeck/src/intrinsicck.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
122122
format!("generic size {size}")
123123
}
124124
}
125-
Err(LayoutError::Unknown(bad)) => {
125+
Err(LayoutError::TooGeneric(bad)) => {
126126
if *bad == ty {
127127
"this type does not have a fixed size".to_owned()
128128
} else {

compiler/rustc_lint/messages.ftl

+5
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,11 @@ lint_builtin_deprecated_attr_link = use of deprecated attribute `{$name}`: {$rea
7676
lint_builtin_deref_nullptr = dereferencing a null pointer
7777
.label = this code causes undefined behavior when executed
7878
79+
lint_builtin_double_negations = use of a double negation
80+
.note = the prefix `--` could be misinterpreted as a decrement operator which exists in other languages
81+
.note_decrement = use `-= 1` if you meant to decrement the value
82+
.add_parens_suggestion = add parentheses for clarity
83+
7984
lint_builtin_ellipsis_inclusive_range_patterns = `...` range patterns are deprecated
8085
.suggestion = use `..=` for an inclusive range
8186

compiler/rustc_lint/src/builtin.rs

+66-21
Original file line numberDiff line numberDiff line change
@@ -49,16 +49,16 @@ use rustc_trait_selection::traits::{self};
4949
use crate::errors::BuiltinEllipsisInclusiveRangePatterns;
5050
use crate::lints::{
5151
BuiltinAnonymousParams, BuiltinConstNoMangle, BuiltinDeprecatedAttrLink,
52-
BuiltinDeprecatedAttrLinkSuggestion, BuiltinDerefNullptr,
53-
BuiltinEllipsisInclusiveRangePatternsLint, BuiltinExplicitOutlives,
54-
BuiltinExplicitOutlivesSuggestion, BuiltinFeatureIssueNote, BuiltinIncompleteFeatures,
55-
BuiltinIncompleteFeaturesHelp, BuiltinInternalFeatures, BuiltinKeywordIdents,
56-
BuiltinMissingCopyImpl, BuiltinMissingDebugImpl, BuiltinMissingDoc, BuiltinMutablesTransmutes,
57-
BuiltinNoMangleGeneric, BuiltinNonShorthandFieldPatterns, BuiltinSpecialModuleNameUsed,
58-
BuiltinTrivialBounds, BuiltinTypeAliasBounds, BuiltinUngatedAsyncFnTrackCaller,
59-
BuiltinUnpermittedTypeInit, BuiltinUnpermittedTypeInitSub, BuiltinUnreachablePub,
60-
BuiltinUnsafe, BuiltinUnstableFeatures, BuiltinUnusedDocComment, BuiltinUnusedDocCommentSub,
61-
BuiltinWhileTrue, InvalidAsmLabel,
52+
BuiltinDeprecatedAttrLinkSuggestion, BuiltinDerefNullptr, BuiltinDoubleNegations,
53+
BuiltinDoubleNegationsAddParens, BuiltinEllipsisInclusiveRangePatternsLint,
54+
BuiltinExplicitOutlives, BuiltinExplicitOutlivesSuggestion, BuiltinFeatureIssueNote,
55+
BuiltinIncompleteFeatures, BuiltinIncompleteFeaturesHelp, BuiltinInternalFeatures,
56+
BuiltinKeywordIdents, BuiltinMissingCopyImpl, BuiltinMissingDebugImpl, BuiltinMissingDoc,
57+
BuiltinMutablesTransmutes, BuiltinNoMangleGeneric, BuiltinNonShorthandFieldPatterns,
58+
BuiltinSpecialModuleNameUsed, BuiltinTrivialBounds, BuiltinTypeAliasBounds,
59+
BuiltinUngatedAsyncFnTrackCaller, BuiltinUnpermittedTypeInit, BuiltinUnpermittedTypeInitSub,
60+
BuiltinUnreachablePub, BuiltinUnsafe, BuiltinUnstableFeatures, BuiltinUnusedDocComment,
61+
BuiltinUnusedDocCommentSub, BuiltinWhileTrue, InvalidAsmLabel,
6262
};
6363
use crate::nonstandard_style::{MethodLateContext, method_context};
6464
use crate::{
@@ -90,19 +90,11 @@ declare_lint! {
9090

9191
declare_lint_pass!(WhileTrue => [WHILE_TRUE]);
9292

93-
/// Traverse through any amount of parenthesis and return the first non-parens expression.
94-
fn pierce_parens(mut expr: &ast::Expr) -> &ast::Expr {
95-
while let ast::ExprKind::Paren(sub) = &expr.kind {
96-
expr = sub;
97-
}
98-
expr
99-
}
100-
10193
impl EarlyLintPass for WhileTrue {
10294
#[inline]
10395
fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
10496
if let ast::ExprKind::While(cond, _, label) = &e.kind
105-
&& let ast::ExprKind::Lit(token_lit) = pierce_parens(cond).kind
97+
&& let ast::ExprKind::Lit(token_lit) = cond.peel_parens().kind
10698
&& let token::Lit { kind: token::Bool, symbol: kw::True, .. } = token_lit
10799
&& !cond.span.from_expansion()
108100
{
@@ -1576,6 +1568,58 @@ impl<'tcx> LateLintPass<'tcx> for TrivialConstraints {
15761568
}
15771569
}
15781570

1571+
declare_lint! {
1572+
/// The `double_negations` lint detects expressions of the form `--x`.
1573+
///
1574+
/// ### Example
1575+
///
1576+
/// ```rust
1577+
/// fn main() {
1578+
/// let x = 1;
1579+
/// let _b = --x;
1580+
/// }
1581+
/// ```
1582+
///
1583+
/// {{produces}}
1584+
///
1585+
/// ### Explanation
1586+
///
1587+
/// Negating something twice is usually the same as not negating it at all.
1588+
/// However, a double negation in Rust can easily be confused with the
1589+
/// prefix decrement operator that exists in many languages derived from C.
1590+
/// Use `-(-x)` if you really wanted to negate the value twice.
1591+
///
1592+
/// To decrement a value, use `x -= 1` instead.
1593+
pub DOUBLE_NEGATIONS,
1594+
Warn,
1595+
"detects expressions of the form `--x`"
1596+
}
1597+
1598+
declare_lint_pass!(
1599+
/// Lint for expressions of the form `--x` that can be confused with C's
1600+
/// prefix decrement operator.
1601+
DoubleNegations => [DOUBLE_NEGATIONS]
1602+
);
1603+
1604+
impl EarlyLintPass for DoubleNegations {
1605+
#[inline]
1606+
fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
1607+
// only lint on the innermost `--` in a chain of `-` operators,
1608+
// even if there are 3 or more negations
1609+
if let ExprKind::Unary(UnOp::Neg, ref inner) = expr.kind
1610+
&& let ExprKind::Unary(UnOp::Neg, ref inner2) = inner.kind
1611+
&& !matches!(inner2.kind, ExprKind::Unary(UnOp::Neg, _))
1612+
{
1613+
cx.emit_span_lint(DOUBLE_NEGATIONS, expr.span, BuiltinDoubleNegations {
1614+
add_parens: BuiltinDoubleNegationsAddParens {
1615+
start_span: inner.span.shrink_to_lo(),
1616+
end_span: inner.span.shrink_to_hi(),
1617+
},
1618+
});
1619+
}
1620+
}
1621+
}
1622+
15791623
declare_lint_pass!(
15801624
/// Does nothing as a lint pass, but registers some `Lint`s
15811625
/// which are used by other parts of the compiler.
@@ -1594,7 +1638,8 @@ declare_lint_pass!(
15941638
UNSTABLE_FEATURES,
15951639
UNREACHABLE_PUB,
15961640
TYPE_ALIAS_BOUNDS,
1597-
TRIVIAL_BOUNDS
1641+
TRIVIAL_BOUNDS,
1642+
DOUBLE_NEGATIONS
15981643
]
15991644
);
16001645

@@ -2651,7 +2696,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue {
26512696
}
26522697

26532698
declare_lint! {
2654-
/// The `deref_nullptr` lint detects when an null pointer is dereferenced,
2699+
/// The `deref_nullptr` lint detects when a null pointer is dereferenced,
26552700
/// which causes [undefined behavior].
26562701
///
26572702
/// ### Example

compiler/rustc_lint/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,7 @@ early_lint_methods!(
181181
UnusedDocComment: UnusedDocComment,
182182
Expr2024: Expr2024,
183183
Precedence: Precedence,
184+
DoubleNegations: DoubleNegations,
184185
]
185186
]
186187
);

compiler/rustc_lint/src/lints.rs

+18
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,24 @@ pub(crate) struct BuiltinTrivialBounds<'a> {
331331
pub predicate: Clause<'a>,
332332
}
333333

334+
#[derive(LintDiagnostic)]
335+
#[diag(lint_builtin_double_negations)]
336+
#[note(lint_note)]
337+
#[note(lint_note_decrement)]
338+
pub(crate) struct BuiltinDoubleNegations {
339+
#[subdiagnostic]
340+
pub add_parens: BuiltinDoubleNegationsAddParens,
341+
}
342+
343+
#[derive(Subdiagnostic)]
344+
#[multipart_suggestion(lint_add_parens_suggestion, applicability = "maybe-incorrect")]
345+
pub(crate) struct BuiltinDoubleNegationsAddParens {
346+
#[suggestion_part(code = "(")]
347+
pub start_span: Span,
348+
#[suggestion_part(code = ")")]
349+
pub end_span: Span,
350+
}
351+
334352
#[derive(LintDiagnostic)]
335353
pub(crate) enum BuiltinEllipsisInclusiveRangePatternsLint {
336354
#[diag(lint_builtin_ellipsis_inclusive_range_patterns)]

compiler/rustc_middle/messages.ftl

+3
Original file line numberDiff line numberDiff line change
@@ -100,11 +100,14 @@ middle_strict_coherence_needs_negative_coherence =
100100
to use `strict_coherence` on this trait, the `with_negative_coherence` feature must be enabled
101101
.label = due to this attribute
102102
103+
middle_too_generic = `{$ty}` does not have a fixed size
104+
103105
middle_type_length_limit = reached the type-length limit while instantiating `{$shrunk}`
104106
105107
middle_unknown_layout =
106108
the type `{$ty}` has an unknown layout
107109
108110
middle_values_too_big =
109111
values of the type `{$ty}` are too big for the target architecture
112+
110113
middle_written_to_path = the full type name has been written to '{$path}'

compiler/rustc_middle/src/error.rs

+3
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,9 @@ pub enum LayoutError<'tcx> {
129129
#[diag(middle_unknown_layout)]
130130
Unknown { ty: Ty<'tcx> },
131131

132+
#[diag(middle_too_generic)]
133+
TooGeneric { ty: Ty<'tcx> },
134+
132135
#[diag(middle_values_too_big)]
133136
Overflow { ty: Ty<'tcx> },
134137

compiler/rustc_middle/src/ty/layout.rs

+10-4
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,7 @@ impl fmt::Display for ValidityRequirement {
231231
pub enum LayoutError<'tcx> {
232232
Unknown(Ty<'tcx>),
233233
SizeOverflow(Ty<'tcx>),
234+
TooGeneric(Ty<'tcx>),
234235
NormalizationFailure(Ty<'tcx>, NormalizationError<'tcx>),
235236
ReferencesError(ErrorGuaranteed),
236237
Cycle(ErrorGuaranteed),
@@ -244,6 +245,7 @@ impl<'tcx> LayoutError<'tcx> {
244245
match self {
245246
Unknown(_) => middle_unknown_layout,
246247
SizeOverflow(_) => middle_values_too_big,
248+
TooGeneric(_) => middle_too_generic,
247249
NormalizationFailure(_, _) => middle_cannot_be_normalized,
248250
Cycle(_) => middle_cycle,
249251
ReferencesError(_) => middle_layout_references_error,
@@ -257,6 +259,7 @@ impl<'tcx> LayoutError<'tcx> {
257259
match self {
258260
Unknown(ty) => E::Unknown { ty },
259261
SizeOverflow(ty) => E::Overflow { ty },
262+
TooGeneric(ty) => E::TooGeneric { ty },
260263
NormalizationFailure(ty, e) => {
261264
E::NormalizationFailure { ty, failure_ty: e.get_type_for_failure() }
262265
}
@@ -272,6 +275,9 @@ impl<'tcx> fmt::Display for LayoutError<'tcx> {
272275
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273276
match *self {
274277
LayoutError::Unknown(ty) => write!(f, "the type `{ty}` has an unknown layout"),
278+
LayoutError::TooGeneric(ty) => {
279+
write!(f, "`{ty}` does not have a fixed size")
280+
}
275281
LayoutError::SizeOverflow(ty) => {
276282
write!(f, "values of the type `{ty}` are too big for the target architecture")
277283
}
@@ -350,10 +356,11 @@ impl<'tcx> SizeSkeleton<'tcx> {
350356
return Err(tcx.arena.alloc(LayoutError::Unknown(ty)));
351357
}
352358
}
353-
Err(err @ LayoutError::Unknown(_)) => err,
359+
Err(err @ LayoutError::TooGeneric(_)) => err,
354360
// We can't extract SizeSkeleton info from other layout errors
355361
Err(
356362
e @ LayoutError::Cycle(_)
363+
| e @ LayoutError::Unknown(_)
357364
| e @ LayoutError::SizeOverflow(_)
358365
| e @ LayoutError::NormalizationFailure(..)
359366
| e @ LayoutError::ReferencesError(_),
@@ -413,10 +420,9 @@ impl<'tcx> SizeSkeleton<'tcx> {
413420
// Alignment is unchanged by arrays.
414421
return Ok(SizeSkeleton::Known(Size::from_bytes(size), a));
415422
}
416-
Err(tcx.arena.alloc(LayoutError::Unknown(ty)))
423+
Err(err)
417424
}
418-
SizeSkeleton::Pointer { .. } => Err(err),
419-
SizeSkeleton::Generic(_) => Err(tcx.arena.alloc(LayoutError::Unknown(ty))),
425+
SizeSkeleton::Pointer { .. } | SizeSkeleton::Generic(_) => Err(err),
420426
}
421427
}
422428

compiler/rustc_transmute/src/layout/tree.rs

+1
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,7 @@ pub(crate) mod rustc {
197197
match err {
198198
LayoutError::Unknown(..)
199199
| LayoutError::ReferencesError(..)
200+
| LayoutError::TooGeneric(..)
200201
| LayoutError::NormalizationFailure(..) => Self::UnknownLayout,
201202
LayoutError::SizeOverflow(..) => Self::SizeOverflow,
202203
LayoutError::Cycle(err) => Self::TypeError(*err),

0 commit comments

Comments
 (0)