Skip to content

Commit b6070a0

Browse files
committed
Use more slice patterns inside the compiler
1 parent 60d1465 commit b6070a0

File tree

41 files changed

+191
-224
lines changed

Some content is hidden

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

41 files changed

+191
-224
lines changed

Diff for: compiler/rustc_ast/src/ast.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -585,7 +585,7 @@ 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 => pat.to_ty().map(TyKind::Slice)?,
589589
// A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
590590
// assuming `T0` to `Tn` are all syntactically valid as types.
591591
PatKind::Tuple(pats) => {
@@ -1187,8 +1187,8 @@ impl Expr {
11871187
/// Does not ensure that the path resolves to a const param, the caller should check this.
11881188
pub fn is_potential_trivial_const_arg(&self) -> bool {
11891189
let this = if let ExprKind::Block(block, None) = &self.kind
1190-
&& block.stmts.len() == 1
1191-
&& let StmtKind::Expr(expr) = &block.stmts[0].kind
1190+
&& let [stmt] = &*block.stmts
1191+
&& let StmtKind::Expr(expr) = &stmt.kind
11921192
{
11931193
expr
11941194
} else {
@@ -1248,7 +1248,7 @@ impl Expr {
12481248
expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
12491249
}
12501250

1251-
ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1251+
ExprKind::Array(exprs) if let [expr] = &**exprs => expr.to_ty().map(TyKind::Slice)?,
12521252

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

Diff for: 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
279+
&& let StmtKind::Expr(expr) = &stmt.kind
280280
{
281281
return self.lower_expr_mut(expr);
282282
}

Diff for: 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 {
506+
self.word(line.clone());
507507
self.hardbreak()
508508
} else {
509509
self.visual_align();

Diff for: 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 {
787+
self.print_use_tree(item);
788788
} else {
789789
self.cbox(INDENT_UNIT);
790790
self.word("{");

Diff for: 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 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 {
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 {
10701070
sess.dcx().emit_err(
10711071
session_diagnostics::IncorrectReprFormatPackedExpectInteger {
1072-
span: nested_items[0].span(),
1072+
span: nested_item.span(),
10731073
},
10741074
);
10751075
} else {

Diff for: 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 {
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(" + "))

Diff for: 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.as_slice() {
749+
[] => {}
750+
[(sp, msg)] => {
752751
ecx.dcx()
753752
.struct_span_err(sp, msg)
754753
.with_span_label(sp, msg)

Diff for: compiler/rustc_builtin_macros/src/deriving/default.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -181,20 +181,20 @@ fn validate_default_attribute(
181181
attr::filter_by_name(&default_variant.attrs, kw::Default).collect();
182182

183183
let attr = match attrs.as_slice() {
184-
[attr] => attr,
185184
[] => cx.dcx().bug(
186185
"this method must only be called with a variant that has a `#[default]` attribute",
187186
),
188-
[first, rest @ ..] => {
187+
[attr] => attr,
188+
[first, first_rest, rest @ ..] => {
189189
let sugg = errors::MultipleDefaultAttrsSugg {
190190
spans: rest.iter().map(|attr| attr.span).collect(),
191191
};
192192
let guar = cx.dcx().emit_err(errors::MultipleDefaultAttrs {
193193
span: default_variant.ident.span,
194194
first: first.span,
195-
first_rest: rest[0].span,
195+
first_rest: first_rest.span,
196196
rest: rest.iter().map(|attr| attr.span).collect::<Vec<_>>().into(),
197-
only_one: rest.len() == 1,
197+
only_one: rest.is_empty(),
198198
sugg,
199199
});
200200

Diff for: 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
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 {
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
}

Diff for: 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
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(

Diff for: 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.as_slice() {
207+
[] => return None,
208+
[mub] => return Some(mub),
209209
_ => {
210210
let m = mubs.pop().unwrap();
211211
let n = mubs.pop().unwrap();

Diff for: compiler/rustc_driver_impl/src/lib.rs

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

Diff for: compiler/rustc_errors/src/emitter.rs

+14-15
Original file line numberDiff line numberDiff line change
@@ -231,17 +231,17 @@ pub trait Emitter: Translate {
231231
) {
232232
if let Some((sugg, rest)) = suggestions.split_first() {
233233
let msg = self.translate_message(&sugg.msg, fluent_args).map_err(Report::new).unwrap();
234-
if rest.is_empty() &&
234+
if rest.is_empty()
235235
// ^ if there is only one suggestion
236236
// don't display multi-suggestions as labels
237-
sugg.substitutions.len() == 1 &&
237+
&& let [substitution] = &*sugg.substitutions
238238
// don't display multipart suggestions as labels
239-
sugg.substitutions[0].parts.len() == 1 &&
239+
&& let [part] = &*substitution.parts
240240
// don't display long messages as labels
241-
msg.split_whitespace().count() < 10 &&
241+
&& msg.split_whitespace().count() < 10
242242
// don't display multiline suggestions as labels
243-
!sugg.substitutions[0].parts[0].snippet.contains('\n') &&
244-
![
243+
&& !part.snippet.contains('\n')
244+
&& ![
245245
// when this style is set we want the suggestion to be a message, not inline
246246
SuggestionStyle::HideCodeAlways,
247247
// trivial suggestion for tooling's sake, never shown
@@ -250,8 +250,8 @@ pub trait Emitter: Translate {
250250
SuggestionStyle::ShowAlways,
251251
].contains(&sugg.style)
252252
{
253-
let substitution = &sugg.substitutions[0].parts[0].snippet.trim();
254-
let msg = if substitution.is_empty() || sugg.style.hide_inline() {
253+
let snippet = part.snippet.trim();
254+
let msg = if snippet.is_empty() || sugg.style.hide_inline() {
255255
// This substitution is only removal OR we explicitly don't want to show the
256256
// code inline (`hide_inline`). Therefore, we don't show the substitution.
257257
format!("help: {msg}")
@@ -260,19 +260,18 @@ pub trait Emitter: Translate {
260260
format!(
261261
"help: {}{}: `{}`",
262262
msg,
263-
if self.source_map().is_some_and(|sm| is_case_difference(
264-
sm,
265-
substitution,
266-
sugg.substitutions[0].parts[0].span,
267-
)) {
263+
if self
264+
.source_map()
265+
.is_some_and(|sm| is_case_difference(sm, snippet, part.span,))
266+
{
268267
" (notice the capitalization)"
269268
} else {
270269
""
271270
},
272-
substitution,
271+
snippet,
273272
)
274273
};
275-
primary_span.push_span_label(sugg.substitutions[0].parts[0].span, msg);
274+
primary_span.push_span_label(part.span, msg);
276275

277276
// We return only the modified primary_span
278277
suggestions.clear();

Diff for: 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

Diff for: 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 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() {

0 commit comments

Comments
 (0)