Skip to content

Commit 67d735c

Browse files
authored
Rollup merge of #69736 - matthiaskrgr:even_more_clippy, r=Dylan-DPC
even more clippy cleanups * Don't pass &mut where immutable reference (&) is sufficient (clippy::unnecessary_mut_passed) * Use more efficient &&str to String conversion (clippy::inefficient_to_string) * Don't always eval arguments inside .expect(), use unwrap_or_else and closure. (clippy::expect_fun_call) * Use righthand '&' instead of lefthand "ref". (clippy::toplevel_ref_arg) * Use simple 'for i in x' loops instead of 'while let Some(i) = x.next()' loops on iterators. (clippy::while_let_on_iterator) * Const items have by default a static lifetime, there's no need to annotate it. (clippy::redundant_static_lifetimes) * Remove redundant patterns when matching ( x @ _ to x) (clippy::redundant_pattern)
2 parents 558115b + 84577c8 commit 67d735c

File tree

26 files changed

+56
-60
lines changed

26 files changed

+56
-60
lines changed

src/librustc/mir/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1198,7 +1198,7 @@ impl<'tcx> TerminatorKind<'tcx> {
11981198
t: BasicBlock,
11991199
f: BasicBlock,
12001200
) -> TerminatorKind<'tcx> {
1201-
static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1201+
static BOOL_SWITCH_FALSE: &[u128] = &[0];
12021202
TerminatorKind::SwitchInt {
12031203
discr: cond,
12041204
switch_ty: tcx.types.bool,

src/librustc_builtin_macros/format.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,7 @@ impl<'a, 'b> Context<'a, 'b> {
284284
err.tool_only_span_suggestion(
285285
sp,
286286
&format!("use the `{}` trait", name),
287-
fmt.to_string(),
287+
(*fmt).to_string(),
288288
Applicability::MaybeIncorrect,
289289
);
290290
}
@@ -476,7 +476,7 @@ impl<'a, 'b> Context<'a, 'b> {
476476
match ty {
477477
Placeholder(_) => {
478478
// record every (position, type) combination only once
479-
let ref mut seen_ty = self.arg_unique_types[arg];
479+
let seen_ty = &mut self.arg_unique_types[arg];
480480
let i = seen_ty.iter().position(|x| *x == ty).unwrap_or_else(|| {
481481
let i = seen_ty.len();
482482
seen_ty.push(ty);
@@ -526,7 +526,7 @@ impl<'a, 'b> Context<'a, 'b> {
526526

527527
// Map the arguments
528528
for i in 0..args_len {
529-
let ref arg_types = self.arg_types[i];
529+
let arg_types = &self.arg_types[i];
530530
let arg_offsets = arg_types.iter().map(|offset| sofar + *offset).collect::<Vec<_>>();
531531
self.arg_index_map.push(arg_offsets);
532532
sofar += self.arg_unique_types[i].len();
@@ -597,7 +597,7 @@ impl<'a, 'b> Context<'a, 'b> {
597597
let arg_idx = match arg_index_consumed.get_mut(i) {
598598
None => 0, // error already emitted elsewhere
599599
Some(offset) => {
600-
let ref idx_map = self.arg_index_map[i];
600+
let idx_map = &self.arg_index_map[i];
601601
// unwrap_or branch: error already emitted elsewhere
602602
let arg_idx = *idx_map.get(*offset).unwrap_or(&0);
603603
*offset += 1;
@@ -721,7 +721,7 @@ impl<'a, 'b> Context<'a, 'b> {
721721
let name = names_pos[i];
722722
let span = self.ecx.with_def_site_ctxt(e.span);
723723
pats.push(self.ecx.pat_ident(span, name));
724-
for ref arg_ty in self.arg_unique_types[i].iter() {
724+
for arg_ty in self.arg_unique_types[i].iter() {
725725
locals.push(Context::format_arg(self.ecx, self.macsp, e.span, arg_ty, name));
726726
}
727727
heads.push(self.ecx.expr_addr_of(e.span, e));

src/librustc_builtin_macros/global_allocator.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -57,12 +57,12 @@ impl AllocFnFactory<'_, '_> {
5757
fn allocator_fn(&self, method: &AllocatorMethod) -> Stmt {
5858
let mut abi_args = Vec::new();
5959
let mut i = 0;
60-
let ref mut mk = || {
60+
let mut mk = || {
6161
let name = self.cx.ident_of(&format!("arg{}", i), self.span);
6262
i += 1;
6363
name
6464
};
65-
let args = method.inputs.iter().map(|ty| self.arg_ty(ty, &mut abi_args, mk)).collect();
65+
let args = method.inputs.iter().map(|ty| self.arg_ty(ty, &mut abi_args, &mut mk)).collect();
6666
let result = self.call_allocator(method.name, args);
6767
let (output_ty, output_expr) = self.ret_ty(&method.output, result);
6868
let decl = self.cx.fn_decl(abi_args, ast::FnRetTy::Ty(output_ty));

src/librustc_builtin_macros/test.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -313,7 +313,7 @@ fn should_fail(i: &ast::Item) -> bool {
313313
fn should_panic(cx: &ExtCtxt<'_>, i: &ast::Item) -> ShouldPanic {
314314
match attr::find_by_name(&i.attrs, sym::should_panic) {
315315
Some(attr) => {
316-
let ref sd = cx.parse_sess.span_diagnostic;
316+
let sd = &cx.parse_sess.span_diagnostic;
317317

318318
match attr.meta_item_list() {
319319
// Handle #[should_panic(expected = "foo")]
@@ -378,7 +378,7 @@ fn test_type(cx: &ExtCtxt<'_>) -> TestType {
378378

379379
fn has_test_signature(cx: &ExtCtxt<'_>, i: &ast::Item) -> bool {
380380
let has_should_panic_attr = attr::contains_name(&i.attrs, sym::should_panic);
381-
let ref sd = cx.parse_sess.span_diagnostic;
381+
let sd = &cx.parse_sess.span_diagnostic;
382382
if let ast::ItemKind::Fn(_, ref sig, ref generics, _) = i.kind {
383383
if let ast::Unsafe::Yes(span) = sig.header.unsafety {
384384
sd.struct_span_err(i.span, "unsafe functions cannot be used for tests")

src/librustc_builtin_macros/test_harness.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -326,7 +326,7 @@ fn mk_main(cx: &mut TestCtxt<'_>) -> P<ast::Item> {
326326
/// &[&test1, &test2]
327327
fn mk_tests_slice(cx: &TestCtxt<'_>, sp: Span) -> P<ast::Expr> {
328328
debug!("building test vector from {} tests", cx.test_cases.len());
329-
let ref ecx = cx.ext_cx;
329+
let ecx = &cx.ext_cx;
330330

331331
ecx.expr_vec_slice(
332332
sp,

src/librustc_codegen_llvm/asm.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ impl AsmBuilderMethods<'tcx> for Builder<'a, 'll, 'tcx> {
6060
.chain(ia.inputs.iter().map(|s| s.to_string()))
6161
.chain(ext_constraints)
6262
.chain(clobbers)
63-
.chain(arch_clobbers.iter().map(|s| s.to_string()))
63+
.chain(arch_clobbers.iter().map(|s| (*s).to_string()))
6464
.collect::<Vec<String>>()
6565
.join(",");
6666

src/librustc_incremental/persist/dirty_clean.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -343,7 +343,8 @@ impl DirtyCleanVisitor<'tcx> {
343343
&format!("clean/dirty auto-assertions not yet defined for {:?}", node),
344344
),
345345
};
346-
let labels = Labels::from_iter(labels.iter().flat_map(|s| s.iter().map(|l| l.to_string())));
346+
let labels =
347+
Labels::from_iter(labels.iter().flat_map(|s| s.iter().map(|l| (*l).to_string())));
347348
(name, labels)
348349
}
349350

src/librustc_infer/traits/auto_trait.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ impl<'tcx> AutoTraitFinder<'tcx> {
150150
// SelectionContext to return it back to us.
151151

152152
let (new_env, user_env) = match self.evaluate_predicates(
153-
&mut infcx,
153+
&infcx,
154154
trait_did,
155155
ty,
156156
orig_env,

src/librustc_infer/traits/select.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1341,7 +1341,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
13411341
stack: &TraitObligationStack<'o, 'tcx>,
13421342
) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
13431343
let TraitObligationStack { obligation, .. } = *stack;
1344-
let ref obligation = Obligation {
1344+
let obligation = &Obligation {
13451345
param_env: obligation.param_env,
13461346
cause: obligation.cause.clone(),
13471347
recursion_depth: obligation.recursion_depth,

src/librustc_lint/context.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,7 @@ impl LintStore {
369369
return if *silent {
370370
CheckLintNameResult::Ok(&lint_ids)
371371
} else {
372-
CheckLintNameResult::Tool(Err((Some(&lint_ids), name.to_string())))
372+
CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
373373
};
374374
}
375375
CheckLintNameResult::Ok(&lint_ids)
@@ -404,7 +404,7 @@ impl LintStore {
404404
return if *silent {
405405
CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
406406
} else {
407-
CheckLintNameResult::Tool(Err((Some(&lint_ids), name.to_string())))
407+
CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
408408
};
409409
}
410410
CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))

src/librustc_mir/dataflow/generic/graphviz.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -604,8 +604,8 @@ fn write_diff<A: Analysis<'tcx>>(
604604
Ok(())
605605
}
606606

607-
const BR_LEFT: &'static str = r#"<br align="left"/>"#;
608-
const BR_LEFT_SPACE: &'static str = r#"<br align="left"/> "#;
607+
const BR_LEFT: &str = r#"<br align="left"/>"#;
608+
const BR_LEFT_SPACE: &str = r#"<br align="left"/> "#;
609609

610610
/// Line break policy that breaks at 40 characters and starts the next line with a single space.
611611
const LIMIT_30_ALIGN_1: Option<LineBreak> = Some(LineBreak { sequence: BR_LEFT_SPACE, limit: 30 });

src/librustc_mir/dataflow/generic/visitor.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -22,20 +22,20 @@ pub fn visit_results<F>(
2222
let loc = Location { block, statement_index };
2323

2424
results.reconstruct_before_statement_effect(&mut state, stmt, loc);
25-
vis.visit_statement(&mut state, stmt, loc);
25+
vis.visit_statement(&state, stmt, loc);
2626

2727
results.reconstruct_statement_effect(&mut state, stmt, loc);
28-
vis.visit_statement_exit(&mut state, stmt, loc);
28+
vis.visit_statement_exit(&state, stmt, loc);
2929
}
3030

3131
let loc = body.terminator_loc(block);
3232
let term = block_data.terminator();
3333

3434
results.reconstruct_before_terminator_effect(&mut state, term, loc);
35-
vis.visit_terminator(&mut state, term, loc);
35+
vis.visit_terminator(&state, term, loc);
3636

3737
results.reconstruct_terminator_effect(&mut state, term, loc);
38-
vis.visit_terminator_exit(&mut state, term, loc);
38+
vis.visit_terminator_exit(&state, term, loc);
3939
}
4040
}
4141

src/librustc_mir/interpret/terminator.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -311,9 +311,8 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
311311
// taking into account the `spread_arg`. If we could write
312312
// this is a single iterator (that handles `spread_arg`), then
313313
// `pass_argument` would be the loop body. It takes care to
314-
// not advance `caller_iter` for ZSTs.
315-
let mut locals_iter = body.args_iter();
316-
while let Some(local) = locals_iter.next() {
314+
// not advance `caller_iter` for ZSTs
315+
for local in body.args_iter() {
317316
let dest = self.eval_place(&mir::Place::from(local))?;
318317
if Some(local) == body.spread_arg {
319318
// Must be a tuple

src/librustc_mir/transform/promote_consts.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -920,7 +920,7 @@ impl<'a, 'tcx> Promoter<'a, 'tcx> {
920920
let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
921921
match candidate {
922922
Candidate::Ref(loc) => {
923-
let ref mut statement = blocks[loc.block].statements[loc.statement_index];
923+
let statement = &mut blocks[loc.block].statements[loc.statement_index];
924924
match statement.kind {
925925
StatementKind::Assign(box (
926926
_,
@@ -971,7 +971,7 @@ impl<'a, 'tcx> Promoter<'a, 'tcx> {
971971
}
972972
}
973973
Candidate::Repeat(loc) => {
974-
let ref mut statement = blocks[loc.block].statements[loc.statement_index];
974+
let statement = &mut blocks[loc.block].statements[loc.statement_index];
975975
match statement.kind {
976976
StatementKind::Assign(box (_, Rvalue::Repeat(ref mut operand, _))) => {
977977
let ty = operand.ty(local_decls, self.tcx);

src/librustc_mir_build/hair/pattern/_match.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2331,7 +2331,7 @@ fn specialize_one_pattern<'p, 'tcx>(
23312331
PatKind::Binding { .. } | PatKind::Wild => Some(ctor_wild_subpatterns.iter().collect()),
23322332

23332333
PatKind::Variant { adt_def, variant_index, ref subpatterns, .. } => {
2334-
let ref variant = adt_def.variants[variant_index];
2334+
let variant = &adt_def.variants[variant_index];
23352335
let is_non_exhaustive = cx.is_foreign_non_exhaustive_variant(pat.ty, variant);
23362336
Some(Variant(variant.def_id))
23372337
.filter(|variant_constructor| variant_constructor == constructor)

src/librustc_parse/parser/diagnostics.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use rustc_span::{MultiSpan, Span, SpanSnippetError, DUMMY_SP};
1919
use log::{debug, trace};
2020
use std::mem;
2121

22-
const TURBOFISH: &'static str = "use `::<...>` instead of `<...>` to specify type arguments";
22+
const TURBOFISH: &str = "use `::<...>` instead of `<...>` to specify type arguments";
2323

2424
/// Creates a placeholder argument.
2525
pub(super) fn dummy_arg(ident: Ident) -> Param {

src/librustc_resolve/imports.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1432,7 +1432,7 @@ impl<'a, 'b> ImportResolver<'a, 'b> {
14321432
}
14331433
msg
14341434
}
1435-
ref s @ _ => bug!("unexpected import subclass {:?}", s),
1435+
ref s => bug!("unexpected import subclass {:?}", s),
14361436
};
14371437
let mut err = this.session.struct_span_err(binding.span, &msg);
14381438

src/librustc_typeck/check/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -737,8 +737,8 @@ impl ItemLikeVisitor<'tcx> for CheckItemTypesVisitor<'tcx> {
737737
}
738738

739739
pub fn check_wf_new(tcx: TyCtxt<'_>) {
740-
let mut visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx);
741-
tcx.hir().krate().par_visit_all_item_likes(&mut visit);
740+
let visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx);
741+
tcx.hir().krate().par_visit_all_item_likes(&visit);
742742
}
743743

744744
fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: DefId) {

src/librustc_typeck/collect.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ crate fn placeholder_type_error(
151151
.unwrap_or(&"ParamName");
152152

153153
let mut sugg: Vec<_> =
154-
placeholder_types.iter().map(|sp| (*sp, type_name.to_string())).collect();
154+
placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
155155
if generics.is_empty() {
156156
sugg.push((span, format!("<{}>", type_name)));
157157
} else if let Some(arg) = generics.iter().find(|arg| match arg.name {
@@ -160,7 +160,7 @@ crate fn placeholder_type_error(
160160
}) {
161161
// Account for `_` already present in cases like `struct S<_>(_);` and suggest
162162
// `struct S<T>(T);` instead of `struct S<_, T>(T);`.
163-
sugg.push((arg.span, type_name.to_string()));
163+
sugg.push((arg.span, (*type_name).to_string()));
164164
} else {
165165
sugg.push((
166166
generics.iter().last().unwrap().span.shrink_to_hi(),

src/librustdoc/clean/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ pub use self::types::Type::*;
5050
pub use self::types::Visibility::{Inherited, Public};
5151
pub use self::types::*;
5252

53-
const FN_OUTPUT_NAME: &'static str = "Output";
53+
const FN_OUTPUT_NAME: &str = "Output";
5454

5555
pub trait Clean<T> {
5656
fn clean(&self, cx: &DocContext<'_>) -> T;

src/librustdoc/docfs.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -90,14 +90,14 @@ impl DocFS {
9090
let sender = self.errors.sender.clone().unwrap();
9191
rayon::spawn(move || match fs::write(&path, &contents) {
9292
Ok(_) => {
93-
sender
94-
.send(None)
95-
.expect(&format!("failed to send error on \"{}\"", path.display()));
93+
sender.send(None).unwrap_or_else(|_| {
94+
panic!("failed to send error on \"{}\"", path.display())
95+
});
9696
}
9797
Err(e) => {
98-
sender
99-
.send(Some(format!("\"{}\": {}", path.display(), e)))
100-
.expect(&format!("failed to send non-error on \"{}\"", path.display()));
98+
sender.send(Some(format!("\"{}\": {}", path.display(), e))).unwrap_or_else(
99+
|_| panic!("failed to send non-error on \"{}\"", path.display()),
100+
);
101101
}
102102
});
103103
Ok(())

src/librustdoc/html/item_type.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ impl<'a> From<&'a clean::Item> for ItemType {
6262
fn from(item: &'a clean::Item) -> ItemType {
6363
let inner = match item.inner {
6464
clean::StrippedItem(box ref item) => item,
65-
ref inner @ _ => inner,
65+
ref inner => inner,
6666
};
6767

6868
match *inner {
@@ -194,7 +194,7 @@ impl fmt::Display for ItemType {
194194
}
195195
}
196196

197-
pub const NAMESPACE_TYPE: &'static str = "t";
198-
pub const NAMESPACE_VALUE: &'static str = "v";
199-
pub const NAMESPACE_MACRO: &'static str = "m";
200-
pub const NAMESPACE_KEYWORD: &'static str = "k";
197+
pub const NAMESPACE_TYPE: &str = "t";
198+
pub const NAMESPACE_VALUE: &str = "v";
199+
pub const NAMESPACE_MACRO: &str = "m";
200+
pub const NAMESPACE_KEYWORD: &str = "k";

src/librustdoc/html/markdown.rs

+2-6
Original file line numberDiff line numberDiff line change
@@ -869,12 +869,8 @@ pub fn plain_summary_line(md: &str) -> String {
869869
}
870870
}
871871
let mut s = String::with_capacity(md.len() * 3 / 2);
872-
let mut p = ParserWrapper { inner: Parser::new(md), is_in: 0, is_first: true };
873-
while let Some(t) = p.next() {
874-
if !t.is_empty() {
875-
s.push_str(&t);
876-
}
877-
}
872+
let p = ParserWrapper { inner: Parser::new(md), is_in: 0, is_first: true };
873+
p.into_iter().filter(|t| !t.is_empty()).for_each(|i| s.push_str(&i));
878874
s
879875
}
880876

src/librustdoc/html/render.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -2727,7 +2727,7 @@ fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
27272727
let name = it.name.as_ref().unwrap();
27282728
let ty = match it.type_() {
27292729
Typedef | AssocType => AssocType,
2730-
s @ _ => s,
2730+
s => s,
27312731
};
27322732

27332733
let anchor = format!("#{}.{}", ty, name);
@@ -3150,7 +3150,7 @@ fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
31503150
}
31513151
}
31523152

3153-
const ATTRIBUTE_WHITELIST: &'static [Symbol] = &[
3153+
const ATTRIBUTE_WHITELIST: &[Symbol] = &[
31543154
sym::export_name,
31553155
sym::lang,
31563156
sym::link_section,
@@ -4610,7 +4610,7 @@ fn item_keyword(w: &mut Buffer, cx: &Context, it: &clean::Item) {
46104610
document(w, cx, it)
46114611
}
46124612

4613-
crate const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4613+
crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
46144614

46154615
fn make_item_keywords(it: &clean::Item) -> String {
46164616
format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())

src/libstd/sys/unix/process/process_common.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@ cfg_if::cfg_if! {
1919
if #[cfg(target_os = "fuchsia")] {
2020
// fuchsia doesn't have /dev/null
2121
} else if #[cfg(target_os = "redox")] {
22-
const DEV_NULL: &'static str = "null:\0";
22+
const DEV_NULL: &str = "null:\0";
2323
} else {
24-
const DEV_NULL: &'static str = "/dev/null\0";
24+
const DEV_NULL: &str = "/dev/null\0";
2525
}
2626
}
2727

src/libtest/lib.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ use time::TestExecTime;
9696
// Process exit code to be used to indicate test failures.
9797
const ERROR_EXIT_CODE: i32 = 101;
9898

99-
const SECONDARY_TEST_INVOKER_VAR: &'static str = "__RUST_TEST_INVOKE";
99+
const SECONDARY_TEST_INVOKER_VAR: &str = "__RUST_TEST_INVOKE";
100100

101101
// The default console test runner. It accepts the command line
102102
// arguments and a vector of test_descs.
@@ -158,7 +158,7 @@ pub fn test_main_static_abort(tests: &[&TestDescAndFn]) {
158158
.filter(|test| test.desc.name.as_slice() == name)
159159
.map(make_owned_test)
160160
.next()
161-
.expect(&format!("couldn't find a test with the provided name '{}'", name));
161+
.unwrap_or_else(|| panic!("couldn't find a test with the provided name '{}'", name));
162162
let TestDescAndFn { desc, testfn } = test;
163163
let testfn = match testfn {
164164
StaticTestFn(f) => f,

0 commit comments

Comments
 (0)