Skip to content

Commit 32e0fe1

Browse files
authored
Rollup merge of rust-lang#128762 - fmease:use-more-slice-pats, r=compiler-errors
Use more slice patterns inside the compiler Nothing super noteworthy. Just replacing the common 'fragile' pattern of "length check followed by indexing or unwrap" with slice patterns for legibility and 'robustness'. r? ghost
2 parents bd7075c + c4c518d commit 32e0fe1

File tree

40 files changed

+191
-221
lines changed

40 files changed

+191
-221
lines changed

compiler/rustc_ast/src/ast.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -585,7 +585,9 @@ impl Pat {
585585
}
586586
// A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
587587
// when `P` can be reparsed as a type `T`.
588-
PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
588+
PatKind::Slice(pats) if let [pat] = pats.as_slice() => {
589+
pat.to_ty().map(TyKind::Slice)?
590+
}
589591
// A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
590592
// assuming `T0` to `Tn` are all syntactically valid as types.
591593
PatKind::Tuple(pats) => {
@@ -1187,8 +1189,8 @@ impl Expr {
11871189
/// Does not ensure that the path resolves to a const param, the caller should check this.
11881190
pub fn is_potential_trivial_const_arg(&self) -> bool {
11891191
let this = if let ExprKind::Block(block, None) = &self.kind
1190-
&& block.stmts.len() == 1
1191-
&& let StmtKind::Expr(expr) = &block.stmts[0].kind
1192+
&& let [stmt] = block.stmts.as_slice()
1193+
&& let StmtKind::Expr(expr) = &stmt.kind
11921194
{
11931195
expr
11941196
} else {
@@ -1248,7 +1250,9 @@ impl Expr {
12481250
expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
12491251
}
12501252

1251-
ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1253+
ExprKind::Array(exprs) if let [expr] = exprs.as_slice() => {
1254+
expr.to_ty().map(TyKind::Slice)?
1255+
}
12521256

12531257
ExprKind::Tup(exprs) => {
12541258
let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<ThinVec<_>>>()?;

compiler/rustc_ast_lowering/src/delegation.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -275,8 +275,8 @@ impl<'hir> LoweringContext<'_, 'hir> {
275275
// FIXME(fn_delegation): Alternatives for target expression lowering:
276276
// https://github.com/rust-lang/rfcs/pull/3530#issuecomment-2197170600.
277277
fn lower_target_expr(&mut self, block: &Block) -> hir::Expr<'hir> {
278-
if block.stmts.len() == 1
279-
&& let StmtKind::Expr(expr) = &block.stmts[0].kind
278+
if let [stmt] = block.stmts.as_slice()
279+
&& let StmtKind::Expr(expr) = &stmt.kind
280280
{
281281
return self.lower_expr_mut(expr);
282282
}

compiler/rustc_ast_pretty/src/pprust/state.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -502,8 +502,8 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
502502
if !self.is_beginning_of_line() {
503503
self.word(" ");
504504
}
505-
if cmnt.lines.len() == 1 {
506-
self.word(cmnt.lines[0].clone());
505+
if let [line] = cmnt.lines.as_slice() {
506+
self.word(line.clone());
507507
self.hardbreak()
508508
} else {
509509
self.visual_align();

compiler/rustc_ast_pretty/src/pprust/state/item.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -783,8 +783,8 @@ impl<'a> State<'a> {
783783
}
784784
if items.is_empty() {
785785
self.word("{}");
786-
} else if items.len() == 1 {
787-
self.print_use_tree(&items[0].0);
786+
} else if let [(item, _)] = items.as_slice() {
787+
self.print_use_tree(item);
788788
} else {
789789
self.cbox(INDENT_UNIT);
790790
self.word("{");

compiler/rustc_attr/src/builtin.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -665,12 +665,12 @@ pub fn eval_condition(
665665
res & eval_condition(mi.meta_item().unwrap(), sess, features, eval)
666666
}),
667667
sym::not => {
668-
if mis.len() != 1 {
668+
let [mi] = mis.as_slice() else {
669669
dcx.emit_err(session_diagnostics::ExpectedOneCfgPattern { span: cfg.span });
670670
return false;
671-
}
671+
};
672672

673-
!eval_condition(mis[0].meta_item().unwrap(), sess, features, eval)
673+
!eval_condition(mi.meta_item().unwrap(), sess, features, eval)
674674
}
675675
sym::target => {
676676
if let Some(features) = features
@@ -1051,10 +1051,10 @@ pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
10511051
MetaItemKind::List(nested_items) => {
10521052
if meta_item.has_name(sym::align) {
10531053
recognised = true;
1054-
if nested_items.len() == 1 {
1054+
if let [nested_item] = nested_items.as_slice() {
10551055
sess.dcx().emit_err(
10561056
session_diagnostics::IncorrectReprFormatExpectInteger {
1057-
span: nested_items[0].span(),
1057+
span: nested_item.span(),
10581058
},
10591059
);
10601060
} else {
@@ -1066,10 +1066,10 @@ pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
10661066
}
10671067
} else if meta_item.has_name(sym::packed) {
10681068
recognised = true;
1069-
if nested_items.len() == 1 {
1069+
if let [nested_item] = nested_items.as_slice() {
10701070
sess.dcx().emit_err(
10711071
session_diagnostics::IncorrectReprFormatPackedExpectInteger {
1072-
span: nested_items[0].span(),
1072+
span: nested_item.span(),
10731073
},
10741074
);
10751075
} else {

compiler/rustc_borrowck/src/diagnostics/outlives_suggestion.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -206,8 +206,8 @@ impl OutlivesSuggestionBuilder {
206206

207207
// If there is exactly one suggestable constraints, then just suggest it. Otherwise, emit a
208208
// list of diagnostics.
209-
let mut diag = if suggested.len() == 1 {
210-
mbcx.dcx().struct_help(match suggested.last().unwrap() {
209+
let mut diag = if let [constraint] = suggested.as_slice() {
210+
mbcx.dcx().struct_help(match constraint {
211211
SuggestedConstraint::Outlives(a, bs) => {
212212
let bs: SmallVec<[String; 2]> = bs.iter().map(|r| r.to_string()).collect();
213213
format!("add bound `{a}: {}`", bs.join(" + "))

compiler/rustc_builtin_macros/src/asm.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -745,10 +745,9 @@ fn expand_preparsed_asm(
745745
unused_operands.push((args.operands[idx].1, msg));
746746
}
747747
}
748-
match unused_operands.len() {
749-
0 => {}
750-
1 => {
751-
let (sp, msg) = unused_operands.into_iter().next().unwrap();
748+
match unused_operands[..] {
749+
[] => {}
750+
[(sp, msg)] => {
752751
ecx.dcx()
753752
.struct_span_err(sp, msg)
754753
.with_span_label(sp, msg)

compiler/rustc_builtin_macros/src/deriving/generic/mod.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -378,8 +378,8 @@ impl BlockOrExpr {
378378
None => cx.expr_block(cx.block(span, ThinVec::new())),
379379
Some(expr) => expr,
380380
}
381-
} else if self.0.len() == 1
382-
&& let ast::StmtKind::Expr(expr) = &self.0[0].kind
381+
} else if let [stmt] = self.0.as_slice()
382+
&& let ast::StmtKind::Expr(expr) = &stmt.kind
383383
&& self.1.is_none()
384384
{
385385
// There's only a single statement expression. Pull it out.
@@ -1273,15 +1273,15 @@ impl<'a> MethodDef<'a> {
12731273
}
12741274
FieldlessVariantsStrategy::Default => (),
12751275
}
1276-
} else if variants.len() == 1 {
1276+
} else if let [variant] = variants.as_slice() {
12771277
// If there is a single variant, we don't need an operation on
12781278
// the discriminant(s). Just use the most degenerate result.
12791279
return self.call_substructure_method(
12801280
cx,
12811281
trait_,
12821282
type_ident,
12831283
nonselflike_args,
1284-
&EnumMatching(0, &variants[0], Vec::new()),
1284+
&EnumMatching(0, variant, Vec::new()),
12851285
);
12861286
}
12871287
}

compiler/rustc_builtin_macros/src/format.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -180,8 +180,8 @@ fn make_format_args(
180180
Ok((mut err, suggested)) => {
181181
if !suggested {
182182
if let ExprKind::Block(block, None) = &efmt.kind
183-
&& block.stmts.len() == 1
184-
&& let StmtKind::Expr(expr) = &block.stmts[0].kind
183+
&& let [stmt] = block.stmts.as_slice()
184+
&& let StmtKind::Expr(expr) = &stmt.kind
185185
&& let ExprKind::Path(None, path) = &expr.kind
186186
&& path.is_potential_trivial_const_arg()
187187
{
@@ -196,8 +196,8 @@ fn make_format_args(
196196
} else {
197197
let sugg_fmt = match args.explicit_args().len() {
198198
0 => "{}".to_string(),
199-
_ => {
200-
format!("{}{{}}", "{} ".repeat(args.explicit_args().len()))
199+
count => {
200+
format!("{}{{}}", "{} ".repeat(count))
201201
}
202202
};
203203
err.span_suggestion(

compiler/rustc_data_structures/src/transitive_relation.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -203,9 +203,9 @@ impl<T: Eq + Hash + Copy> TransitiveRelation<T> {
203203
/// exists). See `postdom_upper_bound` for details.
204204
pub fn mutual_immediate_postdominator(&self, mut mubs: Vec<T>) -> Option<T> {
205205
loop {
206-
match mubs.len() {
207-
0 => return None,
208-
1 => return Some(mubs[0]),
206+
match mubs[..] {
207+
[] => return None,
208+
[mub] => return Some(mub),
209209
_ => {
210210
let m = mubs.pop().unwrap();
211211
let n = mubs.pop().unwrap();

0 commit comments

Comments
 (0)