Skip to content

Commit 5d61561

Browse files
authored
Unrolled build for rust-lang#128762
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 730d5d4 + c4c518d commit 5d61561

File tree

40 files changed

+191
-221
lines changed

40 files changed

+191
-221
lines changed

compiler/rustc_ast/src/ast.rs

+8-4
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

+2-2
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

+2-2
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

+2-2
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

+7-7
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

+2-2
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

+3-4
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

+4-4
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

+4-4
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

+3-3
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();

compiler/rustc_driver_impl/src/lib.rs

+25-30
Original file line numberDiff line numberDiff line change
@@ -338,12 +338,11 @@ fn run_compiler(
338338
config.input = input;
339339
true // has input: normal compilation
340340
}
341-
Ok(None) => match matches.free.len() {
342-
0 => false, // no input: we will exit early
343-
1 => panic!("make_input should have provided valid inputs"),
344-
_ => default_early_dcx.early_fatal(format!(
345-
"multiple input filenames provided (first two filenames are `{}` and `{}`)",
346-
matches.free[0], matches.free[1],
341+
Ok(None) => match matches.free.as_slice() {
342+
[] => false, // no input: we will exit early
343+
[_] => panic!("make_input should have provided valid inputs"),
344+
[fst, snd, ..] => default_early_dcx.early_fatal(format!(
345+
"multiple input filenames provided (first two filenames are `{fst}` and `{snd}`)"
347346
)),
348347
},
349348
};
@@ -491,34 +490,30 @@ fn make_input(
491490
early_dcx: &EarlyDiagCtxt,
492491
free_matches: &[String],
493492
) -> Result<Option<Input>, ErrorGuaranteed> {
494-
if free_matches.len() == 1 {
495-
let ifile = &free_matches[0];
496-
if ifile == "-" {
497-
let mut src = String::new();
498-
if io::stdin().read_to_string(&mut src).is_err() {
499-
// Immediately stop compilation if there was an issue reading
500-
// the input (for example if the input stream is not UTF-8).
501-
let reported = early_dcx
502-
.early_err("couldn't read from stdin, as it did not contain valid UTF-8");
503-
return Err(reported);
504-
}
505-
if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
506-
let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
507-
"when UNSTABLE_RUSTDOC_TEST_PATH is set \
493+
let [ifile] = free_matches else { return Ok(None) };
494+
if ifile == "-" {
495+
let mut src = String::new();
496+
if io::stdin().read_to_string(&mut src).is_err() {
497+
// Immediately stop compilation if there was an issue reading
498+
// the input (for example if the input stream is not UTF-8).
499+
let reported =
500+
early_dcx.early_err("couldn't read from stdin, as it did not contain valid UTF-8");
501+
return Err(reported);
502+
}
503+
if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
504+
let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
505+
"when UNSTABLE_RUSTDOC_TEST_PATH is set \
508506
UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
509-
);
510-
let line = isize::from_str_radix(&line, 10)
511-
.expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
512-
let file_name = FileName::doc_test_source_code(PathBuf::from(path), line);
513-
Ok(Some(Input::Str { name: file_name, input: src }))
514-
} else {
515-
Ok(Some(Input::Str { name: FileName::anon_source_code(&src), input: src }))
516-
}
507+
);
508+
let line = isize::from_str_radix(&line, 10)
509+
.expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
510+
let file_name = FileName::doc_test_source_code(PathBuf::from(path), line);
511+
Ok(Some(Input::Str { name: file_name, input: src }))
517512
} else {
518-
Ok(Some(Input::File(PathBuf::from(ifile))))
513+
Ok(Some(Input::Str { name: FileName::anon_source_code(&src), input: src }))
519514
}
520515
} else {
521-
Ok(None)
516+
Ok(Some(Input::File(PathBuf::from(ifile))))
522517
}
523518
}
524519

compiler/rustc_errors/src/emitter.rs

+14-15
Original file line numberDiff line numberDiff line change
@@ -226,17 +226,17 @@ pub trait Emitter: Translate {
226226
) {
227227
if let Some((sugg, rest)) = suggestions.split_first() {
228228
let msg = self.translate_message(&sugg.msg, fluent_args).map_err(Report::new).unwrap();
229-
if rest.is_empty() &&
229+
if rest.is_empty()
230230
// ^ if there is only one suggestion
231231
// don't display multi-suggestions as labels
232-
sugg.substitutions.len() == 1 &&
232+
&& let [substitution] = sugg.substitutions.as_slice()
233233
// don't display multipart suggestions as labels
234-
sugg.substitutions[0].parts.len() == 1 &&
234+
&& let [part] = substitution.parts.as_slice()
235235
// don't display long messages as labels
236-
msg.split_whitespace().count() < 10 &&
236+
&& msg.split_whitespace().count() < 10
237237
// don't display multiline suggestions as labels
238-
!sugg.substitutions[0].parts[0].snippet.contains('\n') &&
239-
![
238+
&& !part.snippet.contains('\n')
239+
&& ![
240240
// when this style is set we want the suggestion to be a message, not inline
241241
SuggestionStyle::HideCodeAlways,
242242
// trivial suggestion for tooling's sake, never shown
@@ -245,8 +245,8 @@ pub trait Emitter: Translate {
245245
SuggestionStyle::ShowAlways,
246246
].contains(&sugg.style)
247247
{
248-
let substitution = &sugg.substitutions[0].parts[0].snippet.trim();
249-
let msg = if substitution.is_empty() || sugg.style.hide_inline() {
248+
let snippet = part.snippet.trim();
249+
let msg = if snippet.is_empty() || sugg.style.hide_inline() {
250250
// This substitution is only removal OR we explicitly don't want to show the
251251
// code inline (`hide_inline`). Therefore, we don't show the substitution.
252252
format!("help: {msg}")
@@ -255,19 +255,18 @@ pub trait Emitter: Translate {
255255
format!(
256256
"help: {}{}: `{}`",
257257
msg,
258-
if self.source_map().is_some_and(|sm| is_case_difference(
259-
sm,
260-
substitution,
261-
sugg.substitutions[0].parts[0].span,
262-
)) {
258+
if self
259+
.source_map()
260+
.is_some_and(|sm| is_case_difference(sm, snippet, part.span,))
261+
{
263262
" (notice the capitalization)"
264263
} else {
265264
""
266265
},
267-
substitution,
266+
snippet,
268267
)
269268
};
270-
primary_span.push_span_label(sugg.substitutions[0].parts[0].span, msg);
269+
primary_span.push_span_label(part.span, msg);
271270

272271
// We return only the modified primary_span
273272
suggestions.clear();

compiler/rustc_errors/src/lib.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -2024,11 +2024,11 @@ pub fn a_or_an(s: &str) -> &'static str {
20242024
///
20252025
/// Take a list ["a", "b", "c"] and output a display friendly version "a, b and c"
20262026
pub fn display_list_with_comma_and<T: std::fmt::Display>(v: &[T]) -> String {
2027-
match v.len() {
2028-
0 => "".to_string(),
2029-
1 => v[0].to_string(),
2030-
2 => format!("{} and {}", v[0], v[1]),
2031-
_ => format!("{}, {}", v[0], display_list_with_comma_and(&v[1..])),
2027+
match v {
2028+
[] => "".to_string(),
2029+
[a] => a.to_string(),
2030+
[a, b] => format!("{a} and {b}"),
2031+
[a, v @ ..] => format!("{a}, {}", display_list_with_comma_and(v)),
20322032
}
20332033
}
20342034

compiler/rustc_expand/src/base.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -1306,12 +1306,12 @@ pub fn parse_macro_name_and_helper_attrs(
13061306
// that it's of the form `#[proc_macro_derive(Foo)]` or
13071307
// `#[proc_macro_derive(Foo, attributes(A, ..))]`
13081308
let list = attr.meta_item_list()?;
1309-
if list.len() != 1 && list.len() != 2 {
1309+
let ([trait_attr] | [trait_attr, _]) = list.as_slice() else {
13101310
dcx.emit_err(errors::AttrNoArguments { span: attr.span });
13111311
return None;
1312-
}
1313-
let Some(trait_attr) = list[0].meta_item() else {
1314-
dcx.emit_err(errors::NotAMetaItem { span: list[0].span() });
1312+
};
1313+
let Some(trait_attr) = trait_attr.meta_item() else {
1314+
dcx.emit_err(errors::NotAMetaItem { span: trait_attr.span() });
13151315
return None;
13161316
};
13171317
let trait_ident = match trait_attr.ident() {

compiler/rustc_hir_typeck/src/expr.rs

+2-9
Original file line numberDiff line numberDiff line change
@@ -2743,15 +2743,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
27432743
} else if let ty::RawPtr(ptr_ty, _) = expr_t.kind()
27442744
&& let ty::Adt(adt_def, _) = ptr_ty.kind()
27452745
&& let ExprKind::Field(base_expr, _) = expr.kind
2746-
&& adt_def.variants().len() == 1
2747-
&& adt_def
2748-
.variants()
2749-
.iter()
2750-
.next()
2751-
.unwrap()
2752-
.fields
2753-
.iter()
2754-
.any(|f| f.ident(self.tcx) == field)
2746+
&& let [variant] = &adt_def.variants().raw
2747+
&& variant.fields.iter().any(|f| f.ident(self.tcx) == field)
27552748
{
27562749
err.multipart_suggestion(
27572750
"to access the field, dereference first",

0 commit comments

Comments
 (0)