mirror of
https://github.com/rust-lang/rust-clippy
synced 2024-11-24 13:43:17 +00:00
Apply uninlined_format-args to clippy_lints
This change is needed for the uninlined_format-args lint to be merged. See https://github.com/rust-lang/rust-clippy/pull/9233
This commit is contained in:
parent
ff65eec801
commit
e67b2bf732
225 changed files with 557 additions and 842 deletions
|
@ -92,7 +92,7 @@ impl ApproxConstant {
|
||||||
cx,
|
cx,
|
||||||
APPROX_CONSTANT,
|
APPROX_CONSTANT,
|
||||||
e.span,
|
e.span,
|
||||||
&format!("approximate value of `{}::consts::{}` found", module, &name),
|
&format!("approximate value of `{module}::consts::{}` found", &name),
|
||||||
None,
|
None,
|
||||||
"consider using the constant directly",
|
"consider using the constant directly",
|
||||||
);
|
);
|
||||||
|
@ -126,7 +126,7 @@ fn is_approx_const(constant: f64, value: &str, min_digits: usize) -> bool {
|
||||||
// The value is a truncated constant
|
// The value is a truncated constant
|
||||||
true
|
true
|
||||||
} else {
|
} else {
|
||||||
let round_const = format!("{:.*}", value.len() - 2, constant);
|
let round_const = format!("{constant:.*}", value.len() - 2);
|
||||||
value == round_const
|
value == round_const
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -44,7 +44,7 @@ fn check_expr_asm_syntax(lint: &'static Lint, cx: &EarlyContext<'_>, expr: &Expr
|
||||||
cx,
|
cx,
|
||||||
lint,
|
lint,
|
||||||
expr.span,
|
expr.span,
|
||||||
&format!("{} x86 assembly syntax used", style),
|
&format!("{style} x86 assembly syntax used"),
|
||||||
None,
|
None,
|
||||||
&format!("use {} x86 assembly syntax", !style),
|
&format!("use {} x86 assembly syntax", !style),
|
||||||
);
|
);
|
||||||
|
|
|
@ -60,9 +60,9 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnConstants {
|
||||||
cx,
|
cx,
|
||||||
ASSERTIONS_ON_CONSTANTS,
|
ASSERTIONS_ON_CONSTANTS,
|
||||||
macro_call.span,
|
macro_call.span,
|
||||||
&format!("`assert!(false{})` should probably be replaced", assert_arg),
|
&format!("`assert!(false{assert_arg})` should probably be replaced"),
|
||||||
None,
|
None,
|
||||||
&format!("use `panic!({})` or `unreachable!({0})`", panic_arg),
|
&format!("use `panic!({panic_arg})` or `unreachable!({panic_arg})`"),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -69,9 +69,8 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnResultStates {
|
||||||
"called `assert!` with `Result::is_ok`",
|
"called `assert!` with `Result::is_ok`",
|
||||||
"replace with",
|
"replace with",
|
||||||
format!(
|
format!(
|
||||||
"{}.unwrap(){}",
|
"{}.unwrap(){semicolon}",
|
||||||
snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0,
|
snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0
|
||||||
semicolon
|
|
||||||
),
|
),
|
||||||
app,
|
app,
|
||||||
);
|
);
|
||||||
|
@ -84,9 +83,8 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnResultStates {
|
||||||
"called `assert!` with `Result::is_err`",
|
"called `assert!` with `Result::is_err`",
|
||||||
"replace with",
|
"replace with",
|
||||||
format!(
|
format!(
|
||||||
"{}.unwrap_err(){}",
|
"{}.unwrap_err(){semicolon}",
|
||||||
snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0,
|
snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0
|
||||||
semicolon
|
|
||||||
),
|
),
|
||||||
app,
|
app,
|
||||||
);
|
);
|
||||||
|
|
|
@ -541,10 +541,7 @@ fn check_attrs(cx: &LateContext<'_>, span: Span, name: Symbol, attrs: &[Attribut
|
||||||
cx,
|
cx,
|
||||||
INLINE_ALWAYS,
|
INLINE_ALWAYS,
|
||||||
attr.span,
|
attr.span,
|
||||||
&format!(
|
&format!("you have declared `#[inline(always)]` on `{name}`. This is usually a bad idea"),
|
||||||
"you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
|
|
||||||
name
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -720,7 +717,7 @@ fn check_mismatched_target_os(cx: &EarlyContext<'_>, attr: &Attribute) {
|
||||||
let mut unix_suggested = false;
|
let mut unix_suggested = false;
|
||||||
|
|
||||||
for (os, span) in mismatched {
|
for (os, span) in mismatched {
|
||||||
let sugg = format!("target_os = \"{}\"", os);
|
let sugg = format!("target_os = \"{os}\"");
|
||||||
diag.span_suggestion(span, "try", sugg, Applicability::MaybeIncorrect);
|
diag.span_suggestion(span, "try", sugg, Applicability::MaybeIncorrect);
|
||||||
|
|
||||||
if !unix_suggested && is_unix(os) {
|
if !unix_suggested && is_unix(os) {
|
||||||
|
|
|
@ -98,9 +98,9 @@ impl<'tcx> LateLintPass<'tcx> for BoolAssertComparison {
|
||||||
cx,
|
cx,
|
||||||
BOOL_ASSERT_COMPARISON,
|
BOOL_ASSERT_COMPARISON,
|
||||||
macro_call.span,
|
macro_call.span,
|
||||||
&format!("used `{}!` with a literal bool", macro_name),
|
&format!("used `{macro_name}!` with a literal bool"),
|
||||||
"replace it with",
|
"replace it with",
|
||||||
format!("{}!(..)", non_eq_mac),
|
format!("{non_eq_mac}!(..)"),
|
||||||
Applicability::MaybeIncorrect,
|
Applicability::MaybeIncorrect,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -263,9 +263,8 @@ fn simplify_not(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<String> {
|
||||||
}
|
}
|
||||||
.and_then(|op| {
|
.and_then(|op| {
|
||||||
Some(format!(
|
Some(format!(
|
||||||
"{}{}{}",
|
"{}{op}{}",
|
||||||
snippet_opt(cx, lhs.span)?,
|
snippet_opt(cx, lhs.span)?,
|
||||||
op,
|
|
||||||
snippet_opt(cx, rhs.span)?
|
snippet_opt(cx, rhs.span)?
|
||||||
))
|
))
|
||||||
})
|
})
|
||||||
|
@ -285,7 +284,7 @@ fn simplify_not(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<String> {
|
||||||
let path: &str = path.ident.name.as_str();
|
let path: &str = path.ident.name.as_str();
|
||||||
a == path
|
a == path
|
||||||
})
|
})
|
||||||
.and_then(|(_, neg_method)| Some(format!("{}.{}()", snippet_opt(cx, receiver.span)?, neg_method)))
|
.and_then(|(_, neg_method)| Some(format!("{}.{neg_method}()", snippet_opt(cx, receiver.span)?)))
|
||||||
},
|
},
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
|
|
|
@ -40,7 +40,7 @@ pub(super) fn check(cx: &LateContext<'_>, metadata: &Metadata, ignore_publish: b
|
||||||
}
|
}
|
||||||
|
|
||||||
fn missing_warning(cx: &LateContext<'_>, package: &cargo_metadata::Package, field: &str) {
|
fn missing_warning(cx: &LateContext<'_>, package: &cargo_metadata::Package, field: &str) {
|
||||||
let message = format!("package `{}` is missing `{}` metadata", package.name, field);
|
let message = format!("package `{}` is missing `{field}` metadata", package.name);
|
||||||
span_lint(cx, CARGO_COMMON_METADATA, DUMMY_SP, &message);
|
span_lint(cx, CARGO_COMMON_METADATA, DUMMY_SP, &message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -57,10 +57,8 @@ fn lint(cx: &LateContext<'_>, feature: &str, substring: &str, is_prefix: bool) {
|
||||||
},
|
},
|
||||||
DUMMY_SP,
|
DUMMY_SP,
|
||||||
&format!(
|
&format!(
|
||||||
"the \"{}\" {} in the feature name \"{}\" is {}",
|
"the \"{substring}\" {} in the feature name \"{feature}\" is {}",
|
||||||
substring,
|
|
||||||
if is_prefix { "prefix" } else { "suffix" },
|
if is_prefix { "prefix" } else { "suffix" },
|
||||||
feature,
|
|
||||||
if is_negative { "negative" } else { "redundant" }
|
if is_negative { "negative" } else { "redundant" }
|
||||||
),
|
),
|
||||||
None,
|
None,
|
||||||
|
|
|
@ -196,7 +196,7 @@ impl LateLintPass<'_> for Cargo {
|
||||||
},
|
},
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
for lint in NO_DEPS_LINTS {
|
for lint in NO_DEPS_LINTS {
|
||||||
span_lint(cx, lint, DUMMY_SP, &format!("could not read cargo metadata: {}", e));
|
span_lint(cx, lint, DUMMY_SP, &format!("could not read cargo metadata: {e}"));
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
@ -212,7 +212,7 @@ impl LateLintPass<'_> for Cargo {
|
||||||
},
|
},
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
for lint in WITH_DEPS_LINTS {
|
for lint in WITH_DEPS_LINTS {
|
||||||
span_lint(cx, lint, DUMMY_SP, &format!("could not read cargo metadata: {}", e));
|
span_lint(cx, lint, DUMMY_SP, &format!("could not read cargo metadata: {e}"));
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
|
@ -37,7 +37,7 @@ pub(super) fn check(cx: &LateContext<'_>, metadata: &Metadata) {
|
||||||
cx,
|
cx,
|
||||||
MULTIPLE_CRATE_VERSIONS,
|
MULTIPLE_CRATE_VERSIONS,
|
||||||
DUMMY_SP,
|
DUMMY_SP,
|
||||||
&format!("multiple versions for dependency `{}`: {}", name, versions),
|
&format!("multiple versions for dependency `{name}`: {versions}"),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -30,7 +30,7 @@ pub(super) fn check<'tcx>(
|
||||||
expr.span,
|
expr.span,
|
||||||
"borrow as raw pointer",
|
"borrow as raw pointer",
|
||||||
"try",
|
"try",
|
||||||
format!("{}::ptr::{}!({})", core_or_std, macro_name, snip),
|
format!("{core_or_std}::ptr::{macro_name}!({snip})"),
|
||||||
Applicability::MachineApplicable,
|
Applicability::MachineApplicable,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -41,15 +41,9 @@ pub(super) fn check(
|
||||||
);
|
);
|
||||||
|
|
||||||
let message = if cast_from.is_bool() {
|
let message = if cast_from.is_bool() {
|
||||||
format!(
|
format!("casting `{cast_from:}` to `{cast_to:}` is more cleanly stated with `{cast_to:}::from(_)`")
|
||||||
"casting `{0:}` to `{1:}` is more cleanly stated with `{1:}::from(_)`",
|
|
||||||
cast_from, cast_to
|
|
||||||
)
|
|
||||||
} else {
|
} else {
|
||||||
format!(
|
format!("casting `{cast_from}` to `{cast_to}` may become silently lossy if you later change the type")
|
||||||
"casting `{}` to `{}` may become silently lossy if you later change the type",
|
|
||||||
cast_from, cast_to
|
|
||||||
)
|
|
||||||
};
|
};
|
||||||
|
|
||||||
span_lint_and_sugg(
|
span_lint_and_sugg(
|
||||||
|
@ -58,7 +52,7 @@ pub(super) fn check(
|
||||||
expr.span,
|
expr.span,
|
||||||
&message,
|
&message,
|
||||||
"try",
|
"try",
|
||||||
format!("{}::from({})", cast_to, sugg),
|
format!("{cast_to}::from({sugg})"),
|
||||||
applicability,
|
applicability,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -103,10 +103,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>,
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
format!(
|
format!("casting `{cast_from}` to `{cast_to}` may truncate the value{suffix}",)
|
||||||
"casting `{}` to `{}` may truncate the value{}",
|
|
||||||
cast_from, cast_to, suffix,
|
|
||||||
)
|
|
||||||
},
|
},
|
||||||
|
|
||||||
(ty::Adt(def, _), true) if def.is_enum() => {
|
(ty::Adt(def, _), true) if def.is_enum() => {
|
||||||
|
@ -142,20 +139,17 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>,
|
||||||
CAST_ENUM_TRUNCATION,
|
CAST_ENUM_TRUNCATION,
|
||||||
expr.span,
|
expr.span,
|
||||||
&format!(
|
&format!(
|
||||||
"casting `{}::{}` to `{}` will truncate the value{}",
|
"casting `{cast_from}::{}` to `{cast_to}` will truncate the value{suffix}",
|
||||||
cast_from, variant.name, cast_to, suffix,
|
variant.name,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
format!(
|
format!("casting `{cast_from}` to `{cast_to}` may truncate the value{suffix}",)
|
||||||
"casting `{}` to `{}` may truncate the value{}",
|
|
||||||
cast_from, cast_to, suffix,
|
|
||||||
)
|
|
||||||
},
|
},
|
||||||
|
|
||||||
(ty::Float(_), true) => {
|
(ty::Float(_), true) => {
|
||||||
format!("casting `{}` to `{}` may truncate the value", cast_from, cast_to)
|
format!("casting `{cast_from}` to `{cast_to}` may truncate the value")
|
||||||
},
|
},
|
||||||
|
|
||||||
(ty::Float(FloatTy::F64), false) if matches!(cast_to.kind(), &ty::Float(FloatTy::F32)) => {
|
(ty::Float(FloatTy::F64), false) if matches!(cast_to.kind(), &ty::Float(FloatTy::F32)) => {
|
||||||
|
|
|
@ -35,10 +35,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, ca
|
||||||
cx,
|
cx,
|
||||||
CAST_POSSIBLE_WRAP,
|
CAST_POSSIBLE_WRAP,
|
||||||
expr.span,
|
expr.span,
|
||||||
&format!(
|
&format!("casting `{cast_from}` to `{cast_to}` may wrap around the value{suffix}",),
|
||||||
"casting `{}` to `{}` may wrap around the value{}",
|
|
||||||
cast_from, cast_to, suffix,
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -49,9 +49,7 @@ fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, cast_f
|
||||||
CAST_PTR_ALIGNMENT,
|
CAST_PTR_ALIGNMENT,
|
||||||
expr.span,
|
expr.span,
|
||||||
&format!(
|
&format!(
|
||||||
"casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)",
|
"casting from `{cast_from}` to a more-strictly-aligned pointer (`{cast_to}`) ({} < {} bytes)",
|
||||||
cast_from,
|
|
||||||
cast_to,
|
|
||||||
from_layout.align.abi.bytes(),
|
from_layout.align.abi.bytes(),
|
||||||
to_layout.align.abi.bytes(),
|
to_layout.align.abi.bytes(),
|
||||||
),
|
),
|
||||||
|
|
|
@ -14,10 +14,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_op: &Expr<'_>, c
|
||||||
cx,
|
cx,
|
||||||
CAST_SIGN_LOSS,
|
CAST_SIGN_LOSS,
|
||||||
expr.span,
|
expr.span,
|
||||||
&format!(
|
&format!("casting `{cast_from}` to `{cast_to}` may lose the sign of the value"),
|
||||||
"casting `{}` to `{}` may lose the sign of the value",
|
|
||||||
cast_from, cast_to
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -35,8 +35,8 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>, msrv: Optio
|
||||||
CAST_SLICE_DIFFERENT_SIZES,
|
CAST_SLICE_DIFFERENT_SIZES,
|
||||||
expr.span,
|
expr.span,
|
||||||
&format!(
|
&format!(
|
||||||
"casting between raw pointers to `[{}]` (element size {}) and `[{}]` (element size {}) does not adjust the count",
|
"casting between raw pointers to `[{}]` (element size {from_size}) and `[{}]` (element size {to_size}) does not adjust the count",
|
||||||
start_ty.ty, from_size, end_ty.ty, to_size,
|
start_ty.ty, end_ty.ty,
|
||||||
),
|
),
|
||||||
|diag| {
|
|diag| {
|
||||||
let ptr_snippet = source::snippet(cx, left_cast.span, "..");
|
let ptr_snippet = source::snippet(cx, left_cast.span, "..");
|
||||||
|
|
|
@ -31,7 +31,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>) {
|
||||||
diag.span_suggestion(
|
diag.span_suggestion(
|
||||||
expr.span,
|
expr.span,
|
||||||
"use a byte literal instead",
|
"use a byte literal instead",
|
||||||
format!("b{}", snippet),
|
format!("b{snippet}"),
|
||||||
applicability,
|
applicability,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -25,9 +25,9 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>,
|
||||||
cx,
|
cx,
|
||||||
FN_TO_NUMERIC_CAST,
|
FN_TO_NUMERIC_CAST,
|
||||||
expr.span,
|
expr.span,
|
||||||
&format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
|
&format!("casting function pointer `{from_snippet}` to `{cast_to}`"),
|
||||||
"try",
|
"try",
|
||||||
format!("{} as usize", from_snippet),
|
format!("{from_snippet} as usize"),
|
||||||
applicability,
|
applicability,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -23,9 +23,9 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>,
|
||||||
cx,
|
cx,
|
||||||
FN_TO_NUMERIC_CAST_ANY,
|
FN_TO_NUMERIC_CAST_ANY,
|
||||||
expr.span,
|
expr.span,
|
||||||
&format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
|
&format!("casting function pointer `{from_snippet}` to `{cast_to}`"),
|
||||||
"did you mean to invoke the function?",
|
"did you mean to invoke the function?",
|
||||||
format!("{}() as {}", from_snippet, cast_to),
|
format!("{from_snippet}() as {cast_to}"),
|
||||||
applicability,
|
applicability,
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
|
|
@ -24,12 +24,9 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>,
|
||||||
cx,
|
cx,
|
||||||
FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
|
FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
|
||||||
expr.span,
|
expr.span,
|
||||||
&format!(
|
&format!("casting function pointer `{from_snippet}` to `{cast_to}`, which truncates the value"),
|
||||||
"casting function pointer `{}` to `{}`, which truncates the value",
|
|
||||||
from_snippet, cast_to
|
|
||||||
),
|
|
||||||
"try",
|
"try",
|
||||||
format!("{} as usize", from_snippet),
|
format!("{from_snippet} as usize"),
|
||||||
applicability,
|
applicability,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,7 +33,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, msrv: Option<RustcVer
|
||||||
let turbofish = match &cast_to_hir_ty.kind {
|
let turbofish = match &cast_to_hir_ty.kind {
|
||||||
TyKind::Infer => Cow::Borrowed(""),
|
TyKind::Infer => Cow::Borrowed(""),
|
||||||
TyKind::Ptr(mut_ty) if matches!(mut_ty.ty.kind, TyKind::Infer) => Cow::Borrowed(""),
|
TyKind::Ptr(mut_ty) if matches!(mut_ty.ty.kind, TyKind::Infer) => Cow::Borrowed(""),
|
||||||
_ => Cow::Owned(format!("::<{}>", to_pointee_ty)),
|
_ => Cow::Owned(format!("::<{to_pointee_ty}>")),
|
||||||
};
|
};
|
||||||
span_lint_and_sugg(
|
span_lint_and_sugg(
|
||||||
cx,
|
cx,
|
||||||
|
@ -41,7 +41,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, msrv: Option<RustcVer
|
||||||
expr.span,
|
expr.span,
|
||||||
"`as` casting between raw pointers without changing its mutability",
|
"`as` casting between raw pointers without changing its mutability",
|
||||||
"try `pointer::cast`, a safer alternative",
|
"try `pointer::cast`, a safer alternative",
|
||||||
format!("{}.cast{}()", cast_expr_sugg.maybe_par(), turbofish),
|
format!("{}.cast{turbofish}()", cast_expr_sugg.maybe_par()),
|
||||||
applicability,
|
applicability,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -71,10 +71,7 @@ pub(super) fn check<'tcx>(
|
||||||
cx,
|
cx,
|
||||||
UNNECESSARY_CAST,
|
UNNECESSARY_CAST,
|
||||||
expr.span,
|
expr.span,
|
||||||
&format!(
|
&format!("casting to the same type is unnecessary (`{cast_from}` -> `{cast_to}`)"),
|
||||||
"casting to the same type is unnecessary (`{}` -> `{}`)",
|
|
||||||
cast_from, cast_to
|
|
||||||
),
|
|
||||||
"try",
|
"try",
|
||||||
literal_str,
|
literal_str,
|
||||||
Applicability::MachineApplicable,
|
Applicability::MachineApplicable,
|
||||||
|
@ -101,9 +98,9 @@ fn lint_unnecessary_cast(cx: &LateContext<'_>, expr: &Expr<'_>, literal_str: &st
|
||||||
cx,
|
cx,
|
||||||
UNNECESSARY_CAST,
|
UNNECESSARY_CAST,
|
||||||
expr.span,
|
expr.span,
|
||||||
&format!("casting {} literal to `{}` is unnecessary", literal_kind_name, cast_to),
|
&format!("casting {literal_kind_name} literal to `{cast_to}` is unnecessary"),
|
||||||
"try",
|
"try",
|
||||||
format!("{}_{}", matchless.trim_end_matches('.'), cast_to),
|
format!("{}_{cast_to}", matchless.trim_end_matches('.')),
|
||||||
Applicability::MachineApplicable,
|
Applicability::MachineApplicable,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -82,7 +82,7 @@ impl<'tcx> LateLintPass<'tcx> for CheckedConversions {
|
||||||
item.span,
|
item.span,
|
||||||
"checked cast can be simplified",
|
"checked cast can be simplified",
|
||||||
"try",
|
"try",
|
||||||
format!("{}::try_from({}).is_ok()", to_type, snippet),
|
format!("{to_type}::try_from({snippet}).is_ok()"),
|
||||||
applicability,
|
applicability,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -107,8 +107,7 @@ impl CognitiveComplexity {
|
||||||
COGNITIVE_COMPLEXITY,
|
COGNITIVE_COMPLEXITY,
|
||||||
fn_span,
|
fn_span,
|
||||||
&format!(
|
&format!(
|
||||||
"the function has a cognitive complexity of ({}/{})",
|
"the function has a cognitive complexity of ({rust_cc}/{})",
|
||||||
rust_cc,
|
|
||||||
self.limit.limit()
|
self.limit.limit()
|
||||||
),
|
),
|
||||||
None,
|
None,
|
||||||
|
|
|
@ -105,7 +105,7 @@ impl<'tcx> LateLintPass<'tcx> for Default {
|
||||||
cx,
|
cx,
|
||||||
DEFAULT_TRAIT_ACCESS,
|
DEFAULT_TRAIT_ACCESS,
|
||||||
expr.span,
|
expr.span,
|
||||||
&format!("calling `{}` is more clear than this expression", replacement),
|
&format!("calling `{replacement}` is more clear than this expression"),
|
||||||
"try",
|
"try",
|
||||||
replacement,
|
replacement,
|
||||||
Applicability::Unspecified, // First resolve the TODO above
|
Applicability::Unspecified, // First resolve the TODO above
|
||||||
|
@ -210,7 +210,7 @@ impl<'tcx> LateLintPass<'tcx> for Default {
|
||||||
.map(|(field, rhs)| {
|
.map(|(field, rhs)| {
|
||||||
// extract and store the assigned value for help message
|
// extract and store the assigned value for help message
|
||||||
let value_snippet = snippet_with_macro_callsite(cx, rhs.span, "..");
|
let value_snippet = snippet_with_macro_callsite(cx, rhs.span, "..");
|
||||||
format!("{}: {}", field, value_snippet)
|
format!("{field}: {value_snippet}")
|
||||||
})
|
})
|
||||||
.collect::<Vec<String>>()
|
.collect::<Vec<String>>()
|
||||||
.join(", ");
|
.join(", ");
|
||||||
|
@ -227,7 +227,7 @@ impl<'tcx> LateLintPass<'tcx> for Default {
|
||||||
.map(ToString::to_string)
|
.map(ToString::to_string)
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
.join(", ");
|
.join(", ");
|
||||||
format!("{}::<{}>", adt_def_ty_name, &tys_str)
|
format!("{adt_def_ty_name}::<{}>", &tys_str)
|
||||||
} else {
|
} else {
|
||||||
binding_type.to_string()
|
binding_type.to_string()
|
||||||
}
|
}
|
||||||
|
@ -235,12 +235,12 @@ impl<'tcx> LateLintPass<'tcx> for Default {
|
||||||
|
|
||||||
let sugg = if ext_with_default {
|
let sugg = if ext_with_default {
|
||||||
if field_list.is_empty() {
|
if field_list.is_empty() {
|
||||||
format!("{}::default()", binding_type)
|
format!("{binding_type}::default()")
|
||||||
} else {
|
} else {
|
||||||
format!("{} {{ {}, ..Default::default() }}", binding_type, field_list)
|
format!("{binding_type} {{ {field_list}, ..Default::default() }}")
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
format!("{} {{ {} }}", binding_type, field_list)
|
format!("{binding_type} {{ {field_list} }}")
|
||||||
};
|
};
|
||||||
|
|
||||||
// span lint once per statement that binds default
|
// span lint once per statement that binds default
|
||||||
|
@ -250,10 +250,7 @@ impl<'tcx> LateLintPass<'tcx> for Default {
|
||||||
first_assign.unwrap().span,
|
first_assign.unwrap().span,
|
||||||
"field assignment outside of initializer for an instance created with Default::default()",
|
"field assignment outside of initializer for an instance created with Default::default()",
|
||||||
Some(local.span),
|
Some(local.span),
|
||||||
&format!(
|
&format!("consider initializing the variable with `{sugg}` and removing relevant reassignments"),
|
||||||
"consider initializing the variable with `{}` and removing relevant reassignments",
|
|
||||||
sugg
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
self.reassigned_linted.insert(span);
|
self.reassigned_linted.insert(span);
|
||||||
}
|
}
|
||||||
|
|
|
@ -95,8 +95,8 @@ impl<'a, 'tcx> NumericFallbackVisitor<'a, 'tcx> {
|
||||||
src
|
src
|
||||||
} else {
|
} else {
|
||||||
match lit.node {
|
match lit.node {
|
||||||
LitKind::Int(src, _) => format!("{}", src),
|
LitKind::Int(src, _) => format!("{src}"),
|
||||||
LitKind::Float(src, _) => format!("{}", src),
|
LitKind::Float(src, _) => format!("{src}"),
|
||||||
_ => return,
|
_ => return,
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
|
@ -1308,7 +1308,7 @@ fn report<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, state: State, data
|
||||||
};
|
};
|
||||||
|
|
||||||
let expr_str = if !expr_is_macro_call && is_final_ufcs && expr.precedence().order() < PREC_PREFIX {
|
let expr_str = if !expr_is_macro_call && is_final_ufcs && expr.precedence().order() < PREC_PREFIX {
|
||||||
format!("({})", expr_str)
|
format!("({expr_str})")
|
||||||
} else {
|
} else {
|
||||||
expr_str.into_owned()
|
expr_str.into_owned()
|
||||||
};
|
};
|
||||||
|
@ -1322,7 +1322,7 @@ fn report<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, state: State, data
|
||||||
Mutability::Mut => "explicit `deref_mut` method call",
|
Mutability::Mut => "explicit `deref_mut` method call",
|
||||||
},
|
},
|
||||||
"try this",
|
"try this",
|
||||||
format!("{}{}{}", addr_of_str, deref_str, expr_str),
|
format!("{addr_of_str}{deref_str}{expr_str}"),
|
||||||
app,
|
app,
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
@ -1336,7 +1336,7 @@ fn report<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, state: State, data
|
||||||
&& !has_enclosing_paren(&snip)
|
&& !has_enclosing_paren(&snip)
|
||||||
&& (expr.precedence().order() < data.position.precedence() || calls_field)
|
&& (expr.precedence().order() < data.position.precedence() || calls_field)
|
||||||
{
|
{
|
||||||
format!("({})", snip)
|
format!("({snip})")
|
||||||
} else {
|
} else {
|
||||||
snip.into()
|
snip.into()
|
||||||
};
|
};
|
||||||
|
@ -1379,9 +1379,9 @@ fn report<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, state: State, data
|
||||||
let (snip, snip_is_macro) = snippet_with_context(cx, expr.span, data.span.ctxt(), "..", &mut app);
|
let (snip, snip_is_macro) = snippet_with_context(cx, expr.span, data.span.ctxt(), "..", &mut app);
|
||||||
let sugg =
|
let sugg =
|
||||||
if !snip_is_macro && expr.precedence().order() < precedence && !has_enclosing_paren(&snip) {
|
if !snip_is_macro && expr.precedence().order() < precedence && !has_enclosing_paren(&snip) {
|
||||||
format!("{}({})", prefix, snip)
|
format!("{prefix}({snip})")
|
||||||
} else {
|
} else {
|
||||||
format!("{}{}", prefix, snip)
|
format!("{prefix}{snip}")
|
||||||
};
|
};
|
||||||
diag.span_suggestion(data.span, "try this", sugg, app);
|
diag.span_suggestion(data.span, "try this", sugg, app);
|
||||||
},
|
},
|
||||||
|
@ -1460,14 +1460,14 @@ impl Dereferencing {
|
||||||
} else {
|
} else {
|
||||||
pat.always_deref = false;
|
pat.always_deref = false;
|
||||||
let snip = snippet_with_context(cx, e.span, parent.span.ctxt(), "..", &mut pat.app).0;
|
let snip = snippet_with_context(cx, e.span, parent.span.ctxt(), "..", &mut pat.app).0;
|
||||||
pat.replacements.push((e.span, format!("&{}", snip)));
|
pat.replacements.push((e.span, format!("&{snip}")));
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
_ if !e.span.from_expansion() => {
|
_ if !e.span.from_expansion() => {
|
||||||
// Double reference might be needed at this point.
|
// Double reference might be needed at this point.
|
||||||
pat.always_deref = false;
|
pat.always_deref = false;
|
||||||
let snip = snippet_with_applicability(cx, e.span, "..", &mut pat.app);
|
let snip = snippet_with_applicability(cx, e.span, "..", &mut pat.app);
|
||||||
pat.replacements.push((e.span, format!("&{}", snip)));
|
pat.replacements.push((e.span, format!("&{snip}")));
|
||||||
},
|
},
|
||||||
// Edge case for macros. The span of the identifier will usually match the context of the
|
// Edge case for macros. The span of the identifier will usually match the context of the
|
||||||
// binding, but not if the identifier was created in a macro. e.g. `concat_idents` and proc
|
// binding, but not if the identifier was created in a macro. e.g. `concat_idents` and proc
|
||||||
|
|
|
@ -106,7 +106,7 @@ impl<'tcx> LateLintPass<'tcx> for DisallowedMethods {
|
||||||
reason: Some(reason), ..
|
reason: Some(reason), ..
|
||||||
} = conf
|
} = conf
|
||||||
{
|
{
|
||||||
diag.note(&format!("{} (from clippy.toml)", reason));
|
diag.note(&format!("{reason} (from clippy.toml)"));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
@ -99,8 +99,7 @@ impl EarlyLintPass for DisallowedScriptIdents {
|
||||||
DISALLOWED_SCRIPT_IDENTS,
|
DISALLOWED_SCRIPT_IDENTS,
|
||||||
span,
|
span,
|
||||||
&format!(
|
&format!(
|
||||||
"identifier `{}` has a Unicode script that is not allowed by configuration: {}",
|
"identifier `{symbol_str}` has a Unicode script that is not allowed by configuration: {}",
|
||||||
symbol_str,
|
|
||||||
script.full_name()
|
script.full_name()
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
|
@ -92,7 +92,7 @@ impl<'tcx> LateLintPass<'tcx> for DisallowedTypes {
|
||||||
conf::DisallowedType::Simple(path) => (path, None),
|
conf::DisallowedType::Simple(path) => (path, None),
|
||||||
conf::DisallowedType::WithReason { path, reason } => (
|
conf::DisallowedType::WithReason { path, reason } => (
|
||||||
path,
|
path,
|
||||||
reason.as_ref().map(|reason| format!("{} (from clippy.toml)", reason)),
|
reason.as_ref().map(|reason| format!("{reason} (from clippy.toml)")),
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
let segs: Vec<_> = path.split("::").collect();
|
let segs: Vec<_> = path.split("::").collect();
|
||||||
|
@ -130,7 +130,7 @@ fn emit(cx: &LateContext<'_>, name: &str, span: Span, reason: Option<&str>) {
|
||||||
cx,
|
cx,
|
||||||
DISALLOWED_TYPES,
|
DISALLOWED_TYPES,
|
||||||
span,
|
span,
|
||||||
&format!("`{}` is not allowed according to config", name),
|
&format!("`{name}` is not allowed according to config"),
|
||||||
|diag| {
|
|diag| {
|
||||||
if let Some(reason) = reason {
|
if let Some(reason) = reason {
|
||||||
diag.note(reason);
|
diag.note(reason);
|
||||||
|
|
|
@ -790,7 +790,7 @@ fn check_word(cx: &LateContext<'_>, word: &str, span: Span) {
|
||||||
diag.span_suggestion_with_style(
|
diag.span_suggestion_with_style(
|
||||||
span,
|
span,
|
||||||
"try",
|
"try",
|
||||||
format!("`{}`", snippet),
|
format!("`{snippet}`"),
|
||||||
applicability,
|
applicability,
|
||||||
// always show the suggestion in a separate line, since the
|
// always show the suggestion in a separate line, since the
|
||||||
// inline presentation adds another pair of backticks
|
// inline presentation adds another pair of backticks
|
||||||
|
|
|
@ -236,7 +236,7 @@ impl<'tcx> LateLintPass<'tcx> for DropForgetRef {
|
||||||
expr.span,
|
expr.span,
|
||||||
msg,
|
msg,
|
||||||
Some(arg.span),
|
Some(arg.span),
|
||||||
&format!("argument has type `{}`", arg_ty),
|
&format!("argument has type `{arg_ty}`"),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -113,13 +113,8 @@ impl<'tcx> LateLintPass<'tcx> for HashMapPass {
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
format!(
|
format!(
|
||||||
"if let {}::{} = {}.entry({}) {} else {}",
|
"if let {}::{entry_kind} = {map_str}.entry({key_str}) {then_str} else {else_str}",
|
||||||
map_ty.entry_path(),
|
map_ty.entry_path(),
|
||||||
entry_kind,
|
|
||||||
map_str,
|
|
||||||
key_str,
|
|
||||||
then_str,
|
|
||||||
else_str,
|
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
// if .. { insert } else { insert }
|
// if .. { insert } else { insert }
|
||||||
|
@ -137,16 +132,11 @@ impl<'tcx> LateLintPass<'tcx> for HashMapPass {
|
||||||
let indent_str = snippet_indent(cx, expr.span);
|
let indent_str = snippet_indent(cx, expr.span);
|
||||||
let indent_str = indent_str.as_deref().unwrap_or("");
|
let indent_str = indent_str.as_deref().unwrap_or("");
|
||||||
format!(
|
format!(
|
||||||
"match {}.entry({}) {{\n{indent} {entry}::{} => {}\n\
|
"match {map_str}.entry({key_str}) {{\n{indent_str} {entry}::{then_entry} => {}\n\
|
||||||
{indent} {entry}::{} => {}\n{indent}}}",
|
{indent_str} {entry}::{else_entry} => {}\n{indent_str}}}",
|
||||||
map_str,
|
|
||||||
key_str,
|
|
||||||
then_entry,
|
|
||||||
reindent_multiline(then_str.into(), true, Some(4 + indent_str.len())),
|
reindent_multiline(then_str.into(), true, Some(4 + indent_str.len())),
|
||||||
else_entry,
|
|
||||||
reindent_multiline(else_str.into(), true, Some(4 + indent_str.len())),
|
reindent_multiline(else_str.into(), true, Some(4 + indent_str.len())),
|
||||||
entry = map_ty.entry_path(),
|
entry = map_ty.entry_path(),
|
||||||
indent = indent_str,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
@ -163,20 +153,16 @@ impl<'tcx> LateLintPass<'tcx> for HashMapPass {
|
||||||
then_search.snippet_occupied(cx, then_expr.span, &mut app)
|
then_search.snippet_occupied(cx, then_expr.span, &mut app)
|
||||||
};
|
};
|
||||||
format!(
|
format!(
|
||||||
"if let {}::{} = {}.entry({}) {}",
|
"if let {}::{entry_kind} = {map_str}.entry({key_str}) {body_str}",
|
||||||
map_ty.entry_path(),
|
map_ty.entry_path(),
|
||||||
entry_kind,
|
|
||||||
map_str,
|
|
||||||
key_str,
|
|
||||||
body_str,
|
|
||||||
)
|
)
|
||||||
} else if let Some(insertion) = then_search.as_single_insertion() {
|
} else if let Some(insertion) = then_search.as_single_insertion() {
|
||||||
let value_str = snippet_with_context(cx, insertion.value.span, then_expr.span.ctxt(), "..", &mut app).0;
|
let value_str = snippet_with_context(cx, insertion.value.span, then_expr.span.ctxt(), "..", &mut app).0;
|
||||||
if contains_expr.negated {
|
if contains_expr.negated {
|
||||||
if insertion.value.can_have_side_effects() {
|
if insertion.value.can_have_side_effects() {
|
||||||
format!("{}.entry({}).or_insert_with(|| {});", map_str, key_str, value_str)
|
format!("{map_str}.entry({key_str}).or_insert_with(|| {value_str});")
|
||||||
} else {
|
} else {
|
||||||
format!("{}.entry({}).or_insert({});", map_str, key_str, value_str)
|
format!("{map_str}.entry({key_str}).or_insert({value_str});")
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// TODO: suggest using `if let Some(v) = map.get_mut(k) { .. }` here.
|
// TODO: suggest using `if let Some(v) = map.get_mut(k) { .. }` here.
|
||||||
|
@ -186,7 +172,7 @@ impl<'tcx> LateLintPass<'tcx> for HashMapPass {
|
||||||
} else {
|
} else {
|
||||||
let block_str = then_search.snippet_closure(cx, then_expr.span, &mut app);
|
let block_str = then_search.snippet_closure(cx, then_expr.span, &mut app);
|
||||||
if contains_expr.negated {
|
if contains_expr.negated {
|
||||||
format!("{}.entry({}).or_insert_with(|| {});", map_str, key_str, block_str)
|
format!("{map_str}.entry({key_str}).or_insert_with(|| {block_str});")
|
||||||
} else {
|
} else {
|
||||||
// TODO: suggest using `if let Some(v) = map.get_mut(k) { .. }` here.
|
// TODO: suggest using `if let Some(v) = map.get_mut(k) { .. }` here.
|
||||||
// This would need to be a different lint.
|
// This would need to be a different lint.
|
||||||
|
|
|
@ -202,12 +202,11 @@ fn check_variant(cx: &LateContext<'_>, threshold: u64, def: &EnumDef<'_>, item_n
|
||||||
cx,
|
cx,
|
||||||
ENUM_VARIANT_NAMES,
|
ENUM_VARIANT_NAMES,
|
||||||
span,
|
span,
|
||||||
&format!("all variants have the same {}fix: `{}`", what, value),
|
&format!("all variants have the same {what}fix: `{value}`"),
|
||||||
None,
|
None,
|
||||||
&format!(
|
&format!(
|
||||||
"remove the {}fixes and use full paths to \
|
"remove the {what}fixes and use full paths to \
|
||||||
the variants instead of glob imports",
|
the variants instead of glob imports"
|
||||||
what
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -91,9 +91,8 @@ impl<'tcx> LateLintPass<'tcx> for PatternEquality {
|
||||||
"this pattern matching can be expressed using equality",
|
"this pattern matching can be expressed using equality",
|
||||||
"try",
|
"try",
|
||||||
format!(
|
format!(
|
||||||
"{} == {}",
|
"{} == {pat_str}",
|
||||||
snippet_with_context(cx, let_expr.init.span, expr.span.ctxt(), "..", &mut applicability).0,
|
snippet_with_context(cx, let_expr.init.span, expr.span.ctxt(), "..", &mut applicability).0,
|
||||||
pat_str,
|
|
||||||
),
|
),
|
||||||
applicability,
|
applicability,
|
||||||
);
|
);
|
||||||
|
|
|
@ -130,7 +130,7 @@ impl<'tcx> LateLintPass<'tcx> for EtaReduction {
|
||||||
|
|
||||||
then {
|
then {
|
||||||
// Mutable closure is used after current expr; we cannot consume it.
|
// Mutable closure is used after current expr; we cannot consume it.
|
||||||
snippet = format!("&mut {}", snippet);
|
snippet = format!("&mut {snippet}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
diag.span_suggestion(
|
diag.span_suggestion(
|
||||||
|
@ -158,7 +158,7 @@ impl<'tcx> LateLintPass<'tcx> for EtaReduction {
|
||||||
diag.span_suggestion(
|
diag.span_suggestion(
|
||||||
expr.span,
|
expr.span,
|
||||||
"replace the closure with the method itself",
|
"replace the closure with the method itself",
|
||||||
format!("{}::{}", name, path.ident.name),
|
format!("{name}::{}", path.ident.name),
|
||||||
Applicability::MachineApplicable,
|
Applicability::MachineApplicable,
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
|
|
|
@ -97,7 +97,7 @@ impl LateLintPass<'_> for ExhaustiveItems {
|
||||||
item.span,
|
item.span,
|
||||||
msg,
|
msg,
|
||||||
|diag| {
|
|diag| {
|
||||||
let sugg = format!("#[non_exhaustive]\n{}", indent);
|
let sugg = format!("#[non_exhaustive]\n{indent}");
|
||||||
diag.span_suggestion(suggestion_span,
|
diag.span_suggestion(suggestion_span,
|
||||||
"try adding #[non_exhaustive]",
|
"try adding #[non_exhaustive]",
|
||||||
sugg,
|
sugg,
|
||||||
|
|
|
@ -80,12 +80,12 @@ impl<'tcx> LateLintPass<'tcx> for ExplicitWrite {
|
||||||
// used.
|
// used.
|
||||||
let (used, sugg_mac) = if let Some(macro_name) = calling_macro {
|
let (used, sugg_mac) = if let Some(macro_name) = calling_macro {
|
||||||
(
|
(
|
||||||
format!("{}!({}(), ...)", macro_name, dest_name),
|
format!("{macro_name}!({dest_name}(), ...)"),
|
||||||
macro_name.replace("write", "print"),
|
macro_name.replace("write", "print"),
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
(
|
(
|
||||||
format!("{}().write_fmt(...)", dest_name),
|
format!("{dest_name}().write_fmt(...)"),
|
||||||
"print".into(),
|
"print".into(),
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
@ -100,9 +100,9 @@ impl<'tcx> LateLintPass<'tcx> for ExplicitWrite {
|
||||||
cx,
|
cx,
|
||||||
EXPLICIT_WRITE,
|
EXPLICIT_WRITE,
|
||||||
expr.span,
|
expr.span,
|
||||||
&format!("use of `{}.unwrap()`", used),
|
&format!("use of `{used}.unwrap()`"),
|
||||||
"try this",
|
"try this",
|
||||||
format!("{}{}!({})", prefix, sugg_mac, inputs_snippet),
|
format!("{prefix}{sugg_mac}!({inputs_snippet})"),
|
||||||
applicability,
|
applicability,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
@ -173,9 +173,9 @@ impl FloatFormat {
|
||||||
T: fmt::UpperExp + fmt::LowerExp + fmt::Display,
|
T: fmt::UpperExp + fmt::LowerExp + fmt::Display,
|
||||||
{
|
{
|
||||||
match self {
|
match self {
|
||||||
Self::LowerExp => format!("{:e}", f),
|
Self::LowerExp => format!("{f:e}"),
|
||||||
Self::UpperExp => format!("{:E}", f),
|
Self::UpperExp => format!("{f:E}"),
|
||||||
Self::Normal => format!("{}", f),
|
Self::Normal => format!("{f}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -142,8 +142,7 @@ fn prepare_receiver_sugg<'a>(cx: &LateContext<'_>, mut expr: &'a Expr<'a>) -> Su
|
||||||
if let ast::LitKind::Float(sym, ast::LitFloatType::Unsuffixed) = lit.node;
|
if let ast::LitKind::Float(sym, ast::LitFloatType::Unsuffixed) = lit.node;
|
||||||
then {
|
then {
|
||||||
let op = format!(
|
let op = format!(
|
||||||
"{}{}{}",
|
"{suggestion}{}{}",
|
||||||
suggestion,
|
|
||||||
// Check for float literals without numbers following the decimal
|
// Check for float literals without numbers following the decimal
|
||||||
// separator such as `2.` and adds a trailing zero
|
// separator such as `2.` and adds a trailing zero
|
||||||
if sym.as_str().ends_with('.') {
|
if sym.as_str().ends_with('.') {
|
||||||
|
@ -172,7 +171,7 @@ fn check_log_base(cx: &LateContext<'_>, expr: &Expr<'_>, receiver: &Expr<'_>, ar
|
||||||
expr.span,
|
expr.span,
|
||||||
"logarithm for bases 2, 10 and e can be computed more accurately",
|
"logarithm for bases 2, 10 and e can be computed more accurately",
|
||||||
"consider using",
|
"consider using",
|
||||||
format!("{}.{}()", Sugg::hir(cx, receiver, "..").maybe_par(), method),
|
format!("{}.{method}()", Sugg::hir(cx, receiver, "..").maybe_par()),
|
||||||
Applicability::MachineApplicable,
|
Applicability::MachineApplicable,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -251,7 +250,7 @@ fn check_powf(cx: &LateContext<'_>, expr: &Expr<'_>, receiver: &Expr<'_>, args:
|
||||||
expr.span,
|
expr.span,
|
||||||
"exponent for bases 2 and e can be computed more accurately",
|
"exponent for bases 2 and e can be computed more accurately",
|
||||||
"consider using",
|
"consider using",
|
||||||
format!("{}.{}()", prepare_receiver_sugg(cx, &args[0]), method),
|
format!("{}.{method}()", prepare_receiver_sugg(cx, &args[0])),
|
||||||
Applicability::MachineApplicable,
|
Applicability::MachineApplicable,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -62,7 +62,7 @@ impl<'tcx> LateLintPass<'tcx> for UselessFormat {
|
||||||
[_] => {
|
[_] => {
|
||||||
// Simulate macro expansion, converting {{ and }} to { and }.
|
// Simulate macro expansion, converting {{ and }} to { and }.
|
||||||
let s_expand = format_args.format_string.snippet.replace("{{", "{").replace("}}", "}");
|
let s_expand = format_args.format_string.snippet.replace("{{", "{").replace("}}", "}");
|
||||||
let sugg = format!("{}.to_string()", s_expand);
|
let sugg = format!("{s_expand}.to_string()");
|
||||||
span_useless_format(cx, call_site, sugg, applicability);
|
span_useless_format(cx, call_site, sugg, applicability);
|
||||||
},
|
},
|
||||||
[..] => {},
|
[..] => {},
|
||||||
|
|
|
@ -112,11 +112,10 @@ fn check_format_in_format_args(cx: &LateContext<'_>, call_site: Span, name: Symb
|
||||||
cx,
|
cx,
|
||||||
FORMAT_IN_FORMAT_ARGS,
|
FORMAT_IN_FORMAT_ARGS,
|
||||||
call_site,
|
call_site,
|
||||||
&format!("`format!` in `{}!` args", name),
|
&format!("`format!` in `{name}!` args"),
|
||||||
|diag| {
|
|diag| {
|
||||||
diag.help(&format!(
|
diag.help(&format!(
|
||||||
"combine the `format!(..)` arguments with the outer `{}!(..)` call",
|
"combine the `format!(..)` arguments with the outer `{name}!(..)` call"
|
||||||
name
|
|
||||||
));
|
));
|
||||||
diag.help("or consider changing `format!` to `format_args!`");
|
diag.help("or consider changing `format!` to `format_args!`");
|
||||||
},
|
},
|
||||||
|
@ -144,8 +143,7 @@ fn check_to_string_in_format_args(cx: &LateContext<'_>, name: Symbol, value: &Ex
|
||||||
TO_STRING_IN_FORMAT_ARGS,
|
TO_STRING_IN_FORMAT_ARGS,
|
||||||
value.span.with_lo(receiver.span.hi()),
|
value.span.with_lo(receiver.span.hi()),
|
||||||
&format!(
|
&format!(
|
||||||
"`to_string` applied to a type that implements `Display` in `{}!` args",
|
"`to_string` applied to a type that implements `Display` in `{name}!` args"
|
||||||
name
|
|
||||||
),
|
),
|
||||||
"remove this",
|
"remove this",
|
||||||
String::new(),
|
String::new(),
|
||||||
|
@ -157,16 +155,13 @@ fn check_to_string_in_format_args(cx: &LateContext<'_>, name: Symbol, value: &Ex
|
||||||
TO_STRING_IN_FORMAT_ARGS,
|
TO_STRING_IN_FORMAT_ARGS,
|
||||||
value.span,
|
value.span,
|
||||||
&format!(
|
&format!(
|
||||||
"`to_string` applied to a type that implements `Display` in `{}!` args",
|
"`to_string` applied to a type that implements `Display` in `{name}!` args"
|
||||||
name
|
|
||||||
),
|
),
|
||||||
"use this",
|
"use this",
|
||||||
format!(
|
format!(
|
||||||
"{}{:*>width$}{}",
|
"{}{:*>n_needed_derefs$}{receiver_snippet}",
|
||||||
if needs_ref { "&" } else { "" },
|
if needs_ref { "&" } else { "" },
|
||||||
"",
|
""
|
||||||
receiver_snippet,
|
|
||||||
width = n_needed_derefs
|
|
||||||
),
|
),
|
||||||
Applicability::MachineApplicable,
|
Applicability::MachineApplicable,
|
||||||
);
|
);
|
||||||
|
|
|
@ -214,12 +214,12 @@ fn check_print_in_format_impl(cx: &LateContext<'_>, expr: &Expr<'_>, impl_trait:
|
||||||
cx,
|
cx,
|
||||||
PRINT_IN_FORMAT_IMPL,
|
PRINT_IN_FORMAT_IMPL,
|
||||||
macro_call.span,
|
macro_call.span,
|
||||||
&format!("use of `{}!` in `{}` impl", name, impl_trait.name),
|
&format!("use of `{name}!` in `{}` impl", impl_trait.name),
|
||||||
"replace with",
|
"replace with",
|
||||||
if let Some(formatter_name) = impl_trait.formatter_name {
|
if let Some(formatter_name) = impl_trait.formatter_name {
|
||||||
format!("{}!({}, ..)", replacement, formatter_name)
|
format!("{replacement}!({formatter_name}, ..)")
|
||||||
} else {
|
} else {
|
||||||
format!("{}!(..)", replacement)
|
format!("{replacement}!(..)")
|
||||||
},
|
},
|
||||||
Applicability::HasPlaceholders,
|
Applicability::HasPlaceholders,
|
||||||
);
|
);
|
||||||
|
|
|
@ -154,11 +154,10 @@ fn check_assign(cx: &EarlyContext<'_>, expr: &Expr) {
|
||||||
eqop_span,
|
eqop_span,
|
||||||
&format!(
|
&format!(
|
||||||
"this looks like you are trying to use `.. {op}= ..`, but you \
|
"this looks like you are trying to use `.. {op}= ..`, but you \
|
||||||
really are doing `.. = ({op} ..)`",
|
really are doing `.. = ({op} ..)`"
|
||||||
op = op
|
|
||||||
),
|
),
|
||||||
None,
|
None,
|
||||||
&format!("to remove this lint, use either `{op}=` or `= {op}`", op = op),
|
&format!("to remove this lint, use either `{op}=` or `= {op}`"),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -191,16 +190,12 @@ fn check_unop(cx: &EarlyContext<'_>, expr: &Expr) {
|
||||||
SUSPICIOUS_UNARY_OP_FORMATTING,
|
SUSPICIOUS_UNARY_OP_FORMATTING,
|
||||||
eqop_span,
|
eqop_span,
|
||||||
&format!(
|
&format!(
|
||||||
"by not having a space between `{binop}` and `{unop}` it looks like \
|
"by not having a space between `{binop_str}` and `{unop_str}` it looks like \
|
||||||
`{binop}{unop}` is a single operator",
|
`{binop_str}{unop_str}` is a single operator"
|
||||||
binop = binop_str,
|
|
||||||
unop = unop_str
|
|
||||||
),
|
),
|
||||||
None,
|
None,
|
||||||
&format!(
|
&format!(
|
||||||
"put a space between `{binop}` and `{unop}` and remove the space after `{unop}`",
|
"put a space between `{binop_str}` and `{unop_str}` and remove the space after `{unop_str}`"
|
||||||
binop = binop_str,
|
|
||||||
unop = unop_str
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -246,12 +241,11 @@ fn check_else(cx: &EarlyContext<'_>, expr: &Expr) {
|
||||||
cx,
|
cx,
|
||||||
SUSPICIOUS_ELSE_FORMATTING,
|
SUSPICIOUS_ELSE_FORMATTING,
|
||||||
else_span,
|
else_span,
|
||||||
&format!("this is an `else {}` but the formatting might hide it", else_desc),
|
&format!("this is an `else {else_desc}` but the formatting might hide it"),
|
||||||
None,
|
None,
|
||||||
&format!(
|
&format!(
|
||||||
"to remove this lint, remove the `else` or remove the new line between \
|
"to remove this lint, remove the `else` or remove the new line between \
|
||||||
`else` and `{}`",
|
`else` and `{else_desc}`",
|
||||||
else_desc,
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -320,11 +314,10 @@ fn check_missing_else(cx: &EarlyContext<'_>, first: &Expr, second: &Expr) {
|
||||||
cx,
|
cx,
|
||||||
SUSPICIOUS_ELSE_FORMATTING,
|
SUSPICIOUS_ELSE_FORMATTING,
|
||||||
else_span,
|
else_span,
|
||||||
&format!("this looks like {} but the `else` is missing", looks_like),
|
&format!("this looks like {looks_like} but the `else` is missing"),
|
||||||
None,
|
None,
|
||||||
&format!(
|
&format!(
|
||||||
"to remove this lint, add the missing `else` or add a new line before {}",
|
"to remove this lint, add the missing `else` or add a new line before {next_thing}",
|
||||||
next_thing,
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -88,7 +88,7 @@ impl<'tcx> LateLintPass<'tcx> for FromStrRadix10 {
|
||||||
exp.span,
|
exp.span,
|
||||||
"this call to `from_str_radix` can be replaced with a call to `str::parse`",
|
"this call to `from_str_radix` can be replaced with a call to `str::parse`",
|
||||||
"try",
|
"try",
|
||||||
format!("{}.parse::<{}>()", sugg, prim_ty.name_str()),
|
format!("{sugg}.parse::<{}>()", prim_ty.name_str()),
|
||||||
Applicability::MaybeIncorrect
|
Applicability::MaybeIncorrect
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -143,7 +143,7 @@ fn check_must_use_candidate<'tcx>(
|
||||||
diag.span_suggestion(
|
diag.span_suggestion(
|
||||||
fn_span,
|
fn_span,
|
||||||
"add the attribute",
|
"add the attribute",
|
||||||
format!("#[must_use] {}", snippet),
|
format!("#[must_use] {snippet}"),
|
||||||
Applicability::MachineApplicable,
|
Applicability::MachineApplicable,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -59,10 +59,7 @@ fn check_arg_number(cx: &LateContext<'_>, decl: &hir::FnDecl<'_>, fn_span: Span,
|
||||||
cx,
|
cx,
|
||||||
TOO_MANY_ARGUMENTS,
|
TOO_MANY_ARGUMENTS,
|
||||||
fn_span,
|
fn_span,
|
||||||
&format!(
|
&format!("this function has too many arguments ({args}/{too_many_arguments_threshold})"),
|
||||||
"this function has too many arguments ({}/{})",
|
|
||||||
args, too_many_arguments_threshold
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -78,10 +78,7 @@ pub(super) fn check_fn(
|
||||||
cx,
|
cx,
|
||||||
TOO_MANY_LINES,
|
TOO_MANY_LINES,
|
||||||
span,
|
span,
|
||||||
&format!(
|
&format!("this function has too many lines ({line_count}/{too_many_lines_threshold})"),
|
||||||
"this function has too many lines ({}/{})",
|
|
||||||
line_count, too_many_lines_threshold
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -84,7 +84,7 @@ impl<'tcx> LateLintPass<'tcx> for IfThenSomeElseNone {
|
||||||
{
|
{
|
||||||
let cond_snip = snippet_with_macro_callsite(cx, cond.span, "[condition]");
|
let cond_snip = snippet_with_macro_callsite(cx, cond.span, "[condition]");
|
||||||
let cond_snip = if matches!(cond.kind, ExprKind::Unary(_, _) | ExprKind::Binary(_, _, _)) {
|
let cond_snip = if matches!(cond.kind, ExprKind::Unary(_, _) | ExprKind::Binary(_, _, _)) {
|
||||||
format!("({})", cond_snip)
|
format!("({cond_snip})")
|
||||||
} else {
|
} else {
|
||||||
cond_snip.into_owned()
|
cond_snip.into_owned()
|
||||||
};
|
};
|
||||||
|
@ -92,7 +92,7 @@ impl<'tcx> LateLintPass<'tcx> for IfThenSomeElseNone {
|
||||||
let mut method_body = if then_block.stmts.is_empty() {
|
let mut method_body = if then_block.stmts.is_empty() {
|
||||||
arg_snip.into_owned()
|
arg_snip.into_owned()
|
||||||
} else {
|
} else {
|
||||||
format!("{{ /* snippet */ {} }}", arg_snip)
|
format!("{{ /* snippet */ {arg_snip} }}")
|
||||||
};
|
};
|
||||||
let method_name = if switch_to_eager_eval(cx, expr) && meets_msrv(self.msrv, msrvs::BOOL_THEN_SOME) {
|
let method_name = if switch_to_eager_eval(cx, expr) && meets_msrv(self.msrv, msrvs::BOOL_THEN_SOME) {
|
||||||
"then_some"
|
"then_some"
|
||||||
|
@ -102,14 +102,13 @@ impl<'tcx> LateLintPass<'tcx> for IfThenSomeElseNone {
|
||||||
};
|
};
|
||||||
|
|
||||||
let help = format!(
|
let help = format!(
|
||||||
"consider using `bool::{}` like: `{}.{}({})`",
|
"consider using `bool::{method_name}` like: `{cond_snip}.{method_name}({method_body})`",
|
||||||
method_name, cond_snip, method_name, method_body,
|
|
||||||
);
|
);
|
||||||
span_lint_and_help(
|
span_lint_and_help(
|
||||||
cx,
|
cx,
|
||||||
IF_THEN_SOME_ELSE_NONE,
|
IF_THEN_SOME_ELSE_NONE,
|
||||||
expr.span,
|
expr.span,
|
||||||
&format!("this could be simplified with `bool::{}`", method_name),
|
&format!("this could be simplified with `bool::{method_name}`"),
|
||||||
None,
|
None,
|
||||||
&help,
|
&help,
|
||||||
);
|
);
|
||||||
|
|
|
@ -89,8 +89,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitHasher {
|
||||||
(
|
(
|
||||||
generics_suggestion_span,
|
generics_suggestion_span,
|
||||||
format!(
|
format!(
|
||||||
"<{}{}S: ::std::hash::BuildHasher{}>",
|
"<{generics_snip}{}S: ::std::hash::BuildHasher{}>",
|
||||||
generics_snip,
|
|
||||||
if generics_snip.is_empty() { "" } else { ", " },
|
if generics_snip.is_empty() { "" } else { ", " },
|
||||||
if vis.suggestions.is_empty() {
|
if vis.suggestions.is_empty() {
|
||||||
""
|
""
|
||||||
|
@ -263,8 +262,8 @@ impl<'tcx> ImplicitHasherType<'tcx> {
|
||||||
|
|
||||||
fn type_arguments(&self) -> String {
|
fn type_arguments(&self) -> String {
|
||||||
match *self {
|
match *self {
|
||||||
ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
|
ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{k}, {v}"),
|
||||||
ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
|
ImplicitHasherType::HashSet(.., ref t) => format!("{t}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -53,7 +53,7 @@ fn lint_return(cx: &LateContext<'_>, emission_place: HirId, span: Span) {
|
||||||
span,
|
span,
|
||||||
"missing `return` statement",
|
"missing `return` statement",
|
||||||
|diag| {
|
|diag| {
|
||||||
diag.span_suggestion(span, "add `return` as shown", format!("return {}", snip), app);
|
diag.span_suggestion(span, "add `return` as shown", format!("return {snip}"), app);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -71,7 +71,7 @@ fn lint_break(cx: &LateContext<'_>, emission_place: HirId, break_span: Span, exp
|
||||||
diag.span_suggestion(
|
diag.span_suggestion(
|
||||||
break_span,
|
break_span,
|
||||||
"change `break` to `return` as shown",
|
"change `break` to `return` as shown",
|
||||||
format!("return {}", snip),
|
format!("return {snip}"),
|
||||||
app,
|
app,
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
|
|
@ -170,7 +170,7 @@ fn print_lint_and_sugg(cx: &LateContext<'_>, var_name: &str, expr: &Expr<'_>) {
|
||||||
expr.span,
|
expr.span,
|
||||||
"implicitly performing saturating subtraction",
|
"implicitly performing saturating subtraction",
|
||||||
"try",
|
"try",
|
||||||
format!("{} = {}.saturating_sub({});", var_name, var_name, '1'),
|
format!("{var_name} = {var_name}.saturating_sub({});", '1'),
|
||||||
Applicability::MachineApplicable,
|
Applicability::MachineApplicable,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -90,7 +90,7 @@ impl<'tcx> LateLintPass<'tcx> for InconsistentStructConstructor {
|
||||||
let mut fields_snippet = String::new();
|
let mut fields_snippet = String::new();
|
||||||
let (last_ident, idents) = ordered_fields.split_last().unwrap();
|
let (last_ident, idents) = ordered_fields.split_last().unwrap();
|
||||||
for ident in idents {
|
for ident in idents {
|
||||||
let _ = write!(fields_snippet, "{}, ", ident);
|
let _ = write!(fields_snippet, "{ident}, ");
|
||||||
}
|
}
|
||||||
fields_snippet.push_str(&last_ident.to_string());
|
fields_snippet.push_str(&last_ident.to_string());
|
||||||
|
|
||||||
|
@ -100,10 +100,8 @@ impl<'tcx> LateLintPass<'tcx> for InconsistentStructConstructor {
|
||||||
String::new()
|
String::new()
|
||||||
};
|
};
|
||||||
|
|
||||||
let sugg = format!("{} {{ {}{} }}",
|
let sugg = format!("{} {{ {fields_snippet}{base_snippet} }}",
|
||||||
snippet(cx, qpath.span(), ".."),
|
snippet(cx, qpath.span(), ".."),
|
||||||
fields_snippet,
|
|
||||||
base_snippet,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
span_lint_and_sugg(
|
span_lint_and_sugg(
|
||||||
|
|
|
@ -139,14 +139,14 @@ fn lint_slice(cx: &LateContext<'_>, slice: &SliceLintInformation) {
|
||||||
.map(|(index, _)| *index)
|
.map(|(index, _)| *index)
|
||||||
.collect::<FxHashSet<_>>();
|
.collect::<FxHashSet<_>>();
|
||||||
|
|
||||||
let value_name = |index| format!("{}_{}", slice.ident.name, index);
|
let value_name = |index| format!("{}_{index}", slice.ident.name);
|
||||||
|
|
||||||
if let Some(max_index) = used_indices.iter().max() {
|
if let Some(max_index) = used_indices.iter().max() {
|
||||||
let opt_ref = if slice.needs_ref { "ref " } else { "" };
|
let opt_ref = if slice.needs_ref { "ref " } else { "" };
|
||||||
let pat_sugg_idents = (0..=*max_index)
|
let pat_sugg_idents = (0..=*max_index)
|
||||||
.map(|index| {
|
.map(|index| {
|
||||||
if used_indices.contains(&index) {
|
if used_indices.contains(&index) {
|
||||||
format!("{}{}", opt_ref, value_name(index))
|
format!("{opt_ref}{}", value_name(index))
|
||||||
} else {
|
} else {
|
||||||
"_".to_string()
|
"_".to_string()
|
||||||
}
|
}
|
||||||
|
|
|
@ -131,23 +131,19 @@ fn show_lint(cx: &LateContext<'_>, item: &ImplItem<'_>) {
|
||||||
INHERENT_TO_STRING_SHADOW_DISPLAY,
|
INHERENT_TO_STRING_SHADOW_DISPLAY,
|
||||||
item.span,
|
item.span,
|
||||||
&format!(
|
&format!(
|
||||||
"type `{}` implements inherent method `to_string(&self) -> String` which shadows the implementation of `Display`",
|
"type `{self_type}` implements inherent method `to_string(&self) -> String` which shadows the implementation of `Display`"
|
||||||
self_type
|
|
||||||
),
|
),
|
||||||
None,
|
None,
|
||||||
&format!("remove the inherent method from type `{}`", self_type),
|
&format!("remove the inherent method from type `{self_type}`"),
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
span_lint_and_help(
|
span_lint_and_help(
|
||||||
cx,
|
cx,
|
||||||
INHERENT_TO_STRING,
|
INHERENT_TO_STRING,
|
||||||
item.span,
|
item.span,
|
||||||
&format!(
|
&format!("implementation of inherent method `to_string(&self) -> String` for type `{self_type}`"),
|
||||||
"implementation of inherent method `to_string(&self) -> String` for type `{}`",
|
|
||||||
self_type
|
|
||||||
),
|
|
||||||
None,
|
None,
|
||||||
&format!("implement trait `Display` for type `{}` instead", self_type),
|
&format!("implement trait `Display` for type `{self_type}` instead"),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -51,7 +51,7 @@ fn check_attrs(cx: &LateContext<'_>, name: Symbol, attrs: &[Attribute]) {
|
||||||
cx,
|
cx,
|
||||||
INLINE_FN_WITHOUT_BODY,
|
INLINE_FN_WITHOUT_BODY,
|
||||||
attr.span,
|
attr.span,
|
||||||
&format!("use of `#[inline]` on trait method `{}` which has no body", name),
|
&format!("use of `#[inline]` on trait method `{name}` which has no body"),
|
||||||
|diag| {
|
|diag| {
|
||||||
diag.suggest_remove_item(cx, attr.span, "remove", Applicability::MachineApplicable);
|
diag.suggest_remove_item(cx, attr.span, "remove", Applicability::MachineApplicable);
|
||||||
},
|
},
|
||||||
|
|
|
@ -138,8 +138,8 @@ impl IntPlusOne {
|
||||||
if let Some(snippet) = snippet_opt(cx, node.span) {
|
if let Some(snippet) = snippet_opt(cx, node.span) {
|
||||||
if let Some(other_side_snippet) = snippet_opt(cx, other_side.span) {
|
if let Some(other_side_snippet) = snippet_opt(cx, other_side.span) {
|
||||||
let rec = match side {
|
let rec = match side {
|
||||||
Side::Lhs => Some(format!("{} {} {}", snippet, binop_string, other_side_snippet)),
|
Side::Lhs => Some(format!("{snippet} {binop_string} {other_side_snippet}")),
|
||||||
Side::Rhs => Some(format!("{} {} {}", other_side_snippet, binop_string, snippet)),
|
Side::Rhs => Some(format!("{other_side_snippet} {binop_string} {snippet}")),
|
||||||
};
|
};
|
||||||
return rec;
|
return rec;
|
||||||
}
|
}
|
||||||
|
|
|
@ -80,10 +80,7 @@ fn check_sig(cx: &LateContext<'_>, name: &str, sig: &FnSig<'_>, fn_id: LocalDefI
|
||||||
cx,
|
cx,
|
||||||
ITER_NOT_RETURNING_ITERATOR,
|
ITER_NOT_RETURNING_ITERATOR,
|
||||||
sig.span,
|
sig.span,
|
||||||
&format!(
|
&format!("this method is named `{name}` but its return type does not implement `Iterator`"),
|
||||||
"this method is named `{}` but its return type does not implement `Iterator`",
|
|
||||||
name
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -278,15 +278,13 @@ impl<'tcx> LenOutput<'tcx> {
|
||||||
_ => "",
|
_ => "",
|
||||||
};
|
};
|
||||||
match self {
|
match self {
|
||||||
Self::Integral => format!("expected signature: `({}self) -> bool`", self_ref),
|
Self::Integral => format!("expected signature: `({self_ref}self) -> bool`"),
|
||||||
Self::Option(_) => format!(
|
Self::Option(_) => {
|
||||||
"expected signature: `({}self) -> bool` or `({}self) -> Option<bool>",
|
format!("expected signature: `({self_ref}self) -> bool` or `({self_ref}self) -> Option<bool>")
|
||||||
self_ref, self_ref
|
},
|
||||||
),
|
Self::Result(..) => {
|
||||||
Self::Result(..) => format!(
|
format!("expected signature: `({self_ref}self) -> bool` or `({self_ref}self) -> Result<bool>")
|
||||||
"expected signature: `({}self) -> bool` or `({}self) -> Result<bool>",
|
},
|
||||||
self_ref, self_ref
|
|
||||||
),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -326,8 +324,7 @@ fn check_for_is_empty<'tcx>(
|
||||||
let (msg, is_empty_span, self_kind) = match is_empty {
|
let (msg, is_empty_span, self_kind) = match is_empty {
|
||||||
None => (
|
None => (
|
||||||
format!(
|
format!(
|
||||||
"{} `{}` has a public `len` method, but no `is_empty` method",
|
"{item_kind} `{}` has a public `len` method, but no `is_empty` method",
|
||||||
item_kind,
|
|
||||||
item_name.as_str(),
|
item_name.as_str(),
|
||||||
),
|
),
|
||||||
None,
|
None,
|
||||||
|
@ -335,8 +332,7 @@ fn check_for_is_empty<'tcx>(
|
||||||
),
|
),
|
||||||
Some(is_empty) if !cx.access_levels.is_exported(is_empty.def_id.expect_local()) => (
|
Some(is_empty) if !cx.access_levels.is_exported(is_empty.def_id.expect_local()) => (
|
||||||
format!(
|
format!(
|
||||||
"{} `{}` has a public `len` method, but a private `is_empty` method",
|
"{item_kind} `{}` has a public `len` method, but a private `is_empty` method",
|
||||||
item_kind,
|
|
||||||
item_name.as_str(),
|
item_name.as_str(),
|
||||||
),
|
),
|
||||||
Some(cx.tcx.def_span(is_empty.def_id)),
|
Some(cx.tcx.def_span(is_empty.def_id)),
|
||||||
|
@ -348,8 +344,7 @@ fn check_for_is_empty<'tcx>(
|
||||||
{
|
{
|
||||||
(
|
(
|
||||||
format!(
|
format!(
|
||||||
"{} `{}` has a public `len` method, but the `is_empty` method has an unexpected signature",
|
"{item_kind} `{}` has a public `len` method, but the `is_empty` method has an unexpected signature",
|
||||||
item_kind,
|
|
||||||
item_name.as_str(),
|
item_name.as_str(),
|
||||||
),
|
),
|
||||||
Some(cx.tcx.def_span(is_empty.def_id)),
|
Some(cx.tcx.def_span(is_empty.def_id)),
|
||||||
|
@ -419,10 +414,9 @@ fn check_len(
|
||||||
LEN_ZERO,
|
LEN_ZERO,
|
||||||
span,
|
span,
|
||||||
&format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }),
|
&format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }),
|
||||||
&format!("using `{}is_empty` is clearer and more explicit", op),
|
&format!("using `{op}is_empty` is clearer and more explicit"),
|
||||||
format!(
|
format!(
|
||||||
"{}{}.is_empty()",
|
"{op}{}.is_empty()",
|
||||||
op,
|
|
||||||
snippet_with_applicability(cx, receiver.span, "_", &mut applicability)
|
snippet_with_applicability(cx, receiver.span, "_", &mut applicability)
|
||||||
),
|
),
|
||||||
applicability,
|
applicability,
|
||||||
|
@ -439,10 +433,9 @@ fn check_empty_expr(cx: &LateContext<'_>, span: Span, lit1: &Expr<'_>, lit2: &Ex
|
||||||
COMPARISON_TO_EMPTY,
|
COMPARISON_TO_EMPTY,
|
||||||
span,
|
span,
|
||||||
"comparison to empty slice",
|
"comparison to empty slice",
|
||||||
&format!("using `{}is_empty` is clearer and more explicit", op),
|
&format!("using `{op}is_empty` is clearer and more explicit"),
|
||||||
format!(
|
format!(
|
||||||
"{}{}.is_empty()",
|
"{op}{}.is_empty()",
|
||||||
op,
|
|
||||||
snippet_with_applicability(cx, lit1.span, "_", &mut applicability)
|
snippet_with_applicability(cx, lit1.span, "_", &mut applicability)
|
||||||
),
|
),
|
||||||
applicability,
|
applicability,
|
||||||
|
|
|
@ -106,8 +106,7 @@ impl<'tcx> LateLintPass<'tcx> for LetIfSeq {
|
||||||
// use mutably after the `if`
|
// use mutably after the `if`
|
||||||
|
|
||||||
let sug = format!(
|
let sug = format!(
|
||||||
"let {mut}{name} = if {cond} {{{then} {value} }} else {{{else} {default} }};",
|
"let {mutability}{name} = if {cond} {{{then} {value} }} else {{{else} {default} }};",
|
||||||
mut=mutability,
|
|
||||||
name=ident.name,
|
name=ident.name,
|
||||||
cond=snippet(cx, cond.span, "_"),
|
cond=snippet(cx, cond.span, "_"),
|
||||||
then=if then.stmts.len() > 1 { " ..;" } else { "" },
|
then=if then.stmts.len() > 1 { " ..;" } else { "" },
|
||||||
|
|
|
@ -417,8 +417,7 @@ pub fn register_pre_expansion_lints(store: &mut rustc_lint::LintStore, sess: &Se
|
||||||
let msrv = conf.msrv.as_ref().and_then(|s| {
|
let msrv = conf.msrv.as_ref().and_then(|s| {
|
||||||
parse_msrv(s, None, None).or_else(|| {
|
parse_msrv(s, None, None).or_else(|| {
|
||||||
sess.err(&format!(
|
sess.err(&format!(
|
||||||
"error reading Clippy's configuration file. `{}` is not a valid Rust version",
|
"error reading Clippy's configuration file. `{s}` is not a valid Rust version"
|
||||||
s
|
|
||||||
));
|
));
|
||||||
None
|
None
|
||||||
})
|
})
|
||||||
|
@ -434,8 +433,7 @@ fn read_msrv(conf: &Conf, sess: &Session) -> Option<RustcVersion> {
|
||||||
let clippy_msrv = conf.msrv.as_ref().and_then(|s| {
|
let clippy_msrv = conf.msrv.as_ref().and_then(|s| {
|
||||||
parse_msrv(s, None, None).or_else(|| {
|
parse_msrv(s, None, None).or_else(|| {
|
||||||
sess.err(&format!(
|
sess.err(&format!(
|
||||||
"error reading Clippy's configuration file. `{}` is not a valid Rust version",
|
"error reading Clippy's configuration file. `{s}` is not a valid Rust version"
|
||||||
s
|
|
||||||
));
|
));
|
||||||
None
|
None
|
||||||
})
|
})
|
||||||
|
@ -446,8 +444,7 @@ fn read_msrv(conf: &Conf, sess: &Session) -> Option<RustcVersion> {
|
||||||
// if both files have an msrv, let's compare them and emit a warning if they differ
|
// if both files have an msrv, let's compare them and emit a warning if they differ
|
||||||
if clippy_msrv != cargo_msrv {
|
if clippy_msrv != cargo_msrv {
|
||||||
sess.warn(&format!(
|
sess.warn(&format!(
|
||||||
"the MSRV in `clippy.toml` and `Cargo.toml` differ; using `{}` from `clippy.toml`",
|
"the MSRV in `clippy.toml` and `Cargo.toml` differ; using `{clippy_msrv}` from `clippy.toml`"
|
||||||
clippy_msrv
|
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -466,7 +463,7 @@ pub fn read_conf(sess: &Session) -> Conf {
|
||||||
Ok(Some(path)) => path,
|
Ok(Some(path)) => path,
|
||||||
Ok(None) => return Conf::default(),
|
Ok(None) => return Conf::default(),
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
sess.struct_err(&format!("error finding Clippy's configuration file: {}", error))
|
sess.struct_err(&format!("error finding Clippy's configuration file: {error}"))
|
||||||
.emit();
|
.emit();
|
||||||
return Conf::default();
|
return Conf::default();
|
||||||
},
|
},
|
||||||
|
|
|
@ -478,7 +478,7 @@ impl DecimalLiteralRepresentation {
|
||||||
if num_lit.radix == Radix::Decimal;
|
if num_lit.radix == Radix::Decimal;
|
||||||
if val >= u128::from(self.threshold);
|
if val >= u128::from(self.threshold);
|
||||||
then {
|
then {
|
||||||
let hex = format!("{:#X}", val);
|
let hex = format!("{val:#X}");
|
||||||
let num_lit = NumericLiteral::new(&hex, num_lit.suffix, false);
|
let num_lit = NumericLiteral::new(&hex, num_lit.suffix, false);
|
||||||
let _ = Self::do_lint(num_lit.integer).map_err(|warning_type| {
|
let _ = Self::do_lint(num_lit.integer).map_err(|warning_type| {
|
||||||
warning_type.display(num_lit.format(), cx, lit.span);
|
warning_type.display(num_lit.format(), cx, lit.span);
|
||||||
|
|
|
@ -44,11 +44,10 @@ pub(super) fn check<'tcx>(
|
||||||
cx,
|
cx,
|
||||||
EXPLICIT_COUNTER_LOOP,
|
EXPLICIT_COUNTER_LOOP,
|
||||||
span,
|
span,
|
||||||
&format!("the variable `{}` is used as a loop counter", name),
|
&format!("the variable `{name}` is used as a loop counter"),
|
||||||
"consider using",
|
"consider using",
|
||||||
format!(
|
format!(
|
||||||
"for ({}, {}) in {}.enumerate()",
|
"for ({name}, {}) in {}.enumerate()",
|
||||||
name,
|
|
||||||
snippet_with_applicability(cx, pat.span, "item", &mut applicability),
|
snippet_with_applicability(cx, pat.span, "item", &mut applicability),
|
||||||
make_iterator_snippet(cx, arg, &mut applicability),
|
make_iterator_snippet(cx, arg, &mut applicability),
|
||||||
),
|
),
|
||||||
|
@ -65,24 +64,21 @@ pub(super) fn check<'tcx>(
|
||||||
cx,
|
cx,
|
||||||
EXPLICIT_COUNTER_LOOP,
|
EXPLICIT_COUNTER_LOOP,
|
||||||
span,
|
span,
|
||||||
&format!("the variable `{}` is used as a loop counter", name),
|
&format!("the variable `{name}` is used as a loop counter"),
|
||||||
|diag| {
|
|diag| {
|
||||||
diag.span_suggestion(
|
diag.span_suggestion(
|
||||||
span,
|
span,
|
||||||
"consider using",
|
"consider using",
|
||||||
format!(
|
format!(
|
||||||
"for ({}, {}) in (0_{}..).zip({})",
|
"for ({name}, {}) in (0_{int_name}..).zip({})",
|
||||||
name,
|
|
||||||
snippet_with_applicability(cx, pat.span, "item", &mut applicability),
|
snippet_with_applicability(cx, pat.span, "item", &mut applicability),
|
||||||
int_name,
|
|
||||||
make_iterator_snippet(cx, arg, &mut applicability),
|
make_iterator_snippet(cx, arg, &mut applicability),
|
||||||
),
|
),
|
||||||
applicability,
|
applicability,
|
||||||
);
|
);
|
||||||
|
|
||||||
diag.note(&format!(
|
diag.note(&format!(
|
||||||
"`{}` is of type `{}`, making it ineligible for `Iterator::enumerate`",
|
"`{name}` is of type `{int_name}`, making it ineligible for `Iterator::enumerate`"
|
||||||
name, int_name
|
|
||||||
));
|
));
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
|
@ -41,7 +41,7 @@ pub(super) fn check(cx: &LateContext<'_>, self_arg: &Expr<'_>, arg: &Expr<'_>, m
|
||||||
"it is more concise to loop over references to containers instead of using explicit \
|
"it is more concise to loop over references to containers instead of using explicit \
|
||||||
iteration methods",
|
iteration methods",
|
||||||
"to write this more concisely, try",
|
"to write this more concisely, try",
|
||||||
format!("&{}{}", muta, object),
|
format!("&{muta}{object}"),
|
||||||
applicability,
|
applicability,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -38,7 +38,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, arg: &'tcx
|
||||||
cx,
|
cx,
|
||||||
FOR_KV_MAP,
|
FOR_KV_MAP,
|
||||||
arg_span,
|
arg_span,
|
||||||
&format!("you seem to want to iterate on a map's {}s", kind),
|
&format!("you seem to want to iterate on a map's {kind}s"),
|
||||||
|diag| {
|
|diag| {
|
||||||
let map = sugg::Sugg::hir(cx, arg, "map");
|
let map = sugg::Sugg::hir(cx, arg, "map");
|
||||||
multispan_sugg(
|
multispan_sugg(
|
||||||
|
@ -46,7 +46,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, arg: &'tcx
|
||||||
"use the corresponding method",
|
"use the corresponding method",
|
||||||
vec![
|
vec![
|
||||||
(pat_span, snippet(cx, new_pat_span, kind).into_owned()),
|
(pat_span, snippet(cx, new_pat_span, kind).into_owned()),
|
||||||
(arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl)),
|
(arg_span, format!("{}.{kind}s{mutbl}()", map.maybe_par())),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
|
|
@ -38,7 +38,7 @@ pub(super) fn check<'tcx>(
|
||||||
then {
|
then {
|
||||||
let if_let_type = if some_ctor { "Some" } else { "Ok" };
|
let if_let_type = if some_ctor { "Some" } else { "Ok" };
|
||||||
// Prepare the error message
|
// Prepare the error message
|
||||||
let msg = format!("unnecessary `if let` since only the `{}` variant of the iterator element is used", if_let_type);
|
let msg = format!("unnecessary `if let` since only the `{if_let_type}` variant of the iterator element is used");
|
||||||
|
|
||||||
// Prepare the help message
|
// Prepare the help message
|
||||||
let mut applicability = Applicability::MaybeIncorrect;
|
let mut applicability = Applicability::MaybeIncorrect;
|
||||||
|
|
|
@ -177,13 +177,7 @@ fn build_manual_memcpy_suggestion<'tcx>(
|
||||||
let dst = if dst_offset == sugg::EMPTY && dst_limit == sugg::EMPTY {
|
let dst = if dst_offset == sugg::EMPTY && dst_limit == sugg::EMPTY {
|
||||||
dst_base_str
|
dst_base_str
|
||||||
} else {
|
} else {
|
||||||
format!(
|
format!("{dst_base_str}[{}..{}]", dst_offset.maybe_par(), dst_limit.maybe_par()).into()
|
||||||
"{}[{}..{}]",
|
|
||||||
dst_base_str,
|
|
||||||
dst_offset.maybe_par(),
|
|
||||||
dst_limit.maybe_par()
|
|
||||||
)
|
|
||||||
.into()
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let method_str = if is_copy(cx, elem_ty) {
|
let method_str = if is_copy(cx, elem_ty) {
|
||||||
|
@ -193,10 +187,7 @@ fn build_manual_memcpy_suggestion<'tcx>(
|
||||||
};
|
};
|
||||||
|
|
||||||
format!(
|
format!(
|
||||||
"{}.{}(&{}[{}..{}]);",
|
"{dst}.{method_str}(&{src_base_str}[{}..{}]);",
|
||||||
dst,
|
|
||||||
method_str,
|
|
||||||
src_base_str,
|
|
||||||
src_offset.maybe_par(),
|
src_offset.maybe_par(),
|
||||||
src_limit.maybe_par()
|
src_limit.maybe_par()
|
||||||
)
|
)
|
||||||
|
|
|
@ -45,7 +45,7 @@ fn check_needless_collect_direct_usage<'tcx>(expr: &'tcx Expr<'_>, cx: &LateCont
|
||||||
let (arg, pred) = contains_arg
|
let (arg, pred) = contains_arg
|
||||||
.strip_prefix('&')
|
.strip_prefix('&')
|
||||||
.map_or(("&x", &*contains_arg), |s| ("x", s));
|
.map_or(("&x", &*contains_arg), |s| ("x", s));
|
||||||
format!("any(|{}| x == {})", arg, pred)
|
format!("any(|{arg}| x == {pred})")
|
||||||
}
|
}
|
||||||
_ => return,
|
_ => return,
|
||||||
}
|
}
|
||||||
|
@ -141,9 +141,9 @@ impl IterFunction {
|
||||||
IterFunctionKind::Contains(span) => {
|
IterFunctionKind::Contains(span) => {
|
||||||
let s = snippet(cx, *span, "..");
|
let s = snippet(cx, *span, "..");
|
||||||
if let Some(stripped) = s.strip_prefix('&') {
|
if let Some(stripped) = s.strip_prefix('&') {
|
||||||
format!(".any(|x| x == {})", stripped)
|
format!(".any(|x| x == {stripped})")
|
||||||
} else {
|
} else {
|
||||||
format!(".any(|x| x == *{})", s)
|
format!(".any(|x| x == *{s})")
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
|
@ -145,7 +145,7 @@ pub(super) fn check<'tcx>(
|
||||||
cx,
|
cx,
|
||||||
NEEDLESS_RANGE_LOOP,
|
NEEDLESS_RANGE_LOOP,
|
||||||
arg.span,
|
arg.span,
|
||||||
&format!("the loop variable `{}` is used to index `{}`", ident.name, indexed),
|
&format!("the loop variable `{}` is used to index `{indexed}`", ident.name),
|
||||||
|diag| {
|
|diag| {
|
||||||
multispan_sugg(
|
multispan_sugg(
|
||||||
diag,
|
diag,
|
||||||
|
@ -154,7 +154,7 @@ pub(super) fn check<'tcx>(
|
||||||
(pat.span, format!("({}, <item>)", ident.name)),
|
(pat.span, format!("({}, <item>)", ident.name)),
|
||||||
(
|
(
|
||||||
arg.span,
|
arg.span,
|
||||||
format!("{}.{}().enumerate(){}{}", indexed, method, method_1, method_2),
|
format!("{indexed}.{method}().enumerate(){method_1}{method_2}"),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
@ -162,16 +162,16 @@ pub(super) fn check<'tcx>(
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
let repl = if starts_at_zero && take_is_empty {
|
let repl = if starts_at_zero && take_is_empty {
|
||||||
format!("&{}{}", ref_mut, indexed)
|
format!("&{ref_mut}{indexed}")
|
||||||
} else {
|
} else {
|
||||||
format!("{}.{}(){}{}", indexed, method, method_1, method_2)
|
format!("{indexed}.{method}(){method_1}{method_2}")
|
||||||
};
|
};
|
||||||
|
|
||||||
span_lint_and_then(
|
span_lint_and_then(
|
||||||
cx,
|
cx,
|
||||||
NEEDLESS_RANGE_LOOP,
|
NEEDLESS_RANGE_LOOP,
|
||||||
arg.span,
|
arg.span,
|
||||||
&format!("the loop variable `{}` is only used to index `{}`", ident.name, indexed),
|
&format!("the loop variable `{}` is only used to index `{indexed}`", ident.name),
|
||||||
|diag| {
|
|diag| {
|
||||||
multispan_sugg(
|
multispan_sugg(
|
||||||
diag,
|
diag,
|
||||||
|
|
|
@ -222,9 +222,5 @@ fn for_to_if_let_sugg(cx: &LateContext<'_>, iterator: &Expr<'_>, pat: &Pat<'_>)
|
||||||
let pat_snippet = snippet(cx, pat.span, "_");
|
let pat_snippet = snippet(cx, pat.span, "_");
|
||||||
let iter_snippet = make_iterator_snippet(cx, iterator, &mut Applicability::Unspecified);
|
let iter_snippet = make_iterator_snippet(cx, iterator, &mut Applicability::Unspecified);
|
||||||
|
|
||||||
format!(
|
format!("if let Some({pat_snippet}) = {iter_snippet}.next()")
|
||||||
"if let Some({pat}) = {iter}.next()",
|
|
||||||
pat = pat_snippet,
|
|
||||||
iter = iter_snippet
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -30,10 +30,7 @@ pub(super) fn check<'tcx>(
|
||||||
vec.span,
|
vec.span,
|
||||||
"it looks like the same item is being pushed into this Vec",
|
"it looks like the same item is being pushed into this Vec",
|
||||||
None,
|
None,
|
||||||
&format!(
|
&format!("try using vec![{item_str};SIZE] or {vec_str}.resize(NEW_SIZE, {item_str})"),
|
||||||
"try using vec![{};SIZE] or {}.resize(NEW_SIZE, {})",
|
|
||||||
item_str, vec_str, item_str
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -344,9 +344,8 @@ pub(super) fn make_iterator_snippet(cx: &LateContext<'_>, arg: &Expr<'_>, applic
|
||||||
_ => arg,
|
_ => arg,
|
||||||
};
|
};
|
||||||
format!(
|
format!(
|
||||||
"{}.{}()",
|
"{}.{method_name}()",
|
||||||
sugg::Sugg::hir_with_applicability(cx, caller, "_", applic_ref).maybe_par(),
|
sugg::Sugg::hir_with_applicability(cx, caller, "_", applic_ref).maybe_par(),
|
||||||
method_name,
|
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
_ => format!(
|
_ => format!(
|
||||||
|
|
|
@ -67,7 +67,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
|
||||||
expr.span.with_hi(scrutinee_expr.span.hi()),
|
expr.span.with_hi(scrutinee_expr.span.hi()),
|
||||||
"this loop could be written as a `for` loop",
|
"this loop could be written as a `for` loop",
|
||||||
"try",
|
"try",
|
||||||
format!("for {} in {}{}", loop_var, iterator, by_ref),
|
format!("for {loop_var} in {iterator}{by_ref}"),
|
||||||
applicability,
|
applicability,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -190,9 +190,9 @@ impl<'tcx> LateLintPass<'tcx> for MacroUseImports {
|
||||||
let mut suggestions = vec![];
|
let mut suggestions = vec![];
|
||||||
for ((root, span, hir_id), path) in used {
|
for ((root, span, hir_id), path) in used {
|
||||||
if path.len() == 1 {
|
if path.len() == 1 {
|
||||||
suggestions.push((span, format!("{}::{}", root, path[0]), hir_id));
|
suggestions.push((span, format!("{root}::{}", path[0]), hir_id));
|
||||||
} else {
|
} else {
|
||||||
suggestions.push((span, format!("{}::{{{}}}", root, path.join(", ")), hir_id));
|
suggestions.push((span, format!("{root}::{{{}}}", path.join(", ")), hir_id));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -200,7 +200,7 @@ impl<'tcx> LateLintPass<'tcx> for MacroUseImports {
|
||||||
// such as `std::prelude::v1::foo` or some other macro that expands to an import.
|
// such as `std::prelude::v1::foo` or some other macro that expands to an import.
|
||||||
if self.mac_refs.is_empty() {
|
if self.mac_refs.is_empty() {
|
||||||
for (span, import, hir_id) in suggestions {
|
for (span, import, hir_id) in suggestions {
|
||||||
let help = format!("use {};", import);
|
let help = format!("use {import};");
|
||||||
span_lint_hir_and_then(
|
span_lint_hir_and_then(
|
||||||
cx,
|
cx,
|
||||||
MACRO_USE_IMPORTS,
|
MACRO_USE_IMPORTS,
|
||||||
|
|
|
@ -74,11 +74,11 @@ impl<'tcx> LateLintPass<'tcx> for ManualAsyncFn {
|
||||||
if let Some(ret_pos) = position_before_rarrow(&header_snip);
|
if let Some(ret_pos) = position_before_rarrow(&header_snip);
|
||||||
if let Some((ret_sugg, ret_snip)) = suggested_ret(cx, output);
|
if let Some((ret_sugg, ret_snip)) = suggested_ret(cx, output);
|
||||||
then {
|
then {
|
||||||
let help = format!("make the function `async` and {}", ret_sugg);
|
let help = format!("make the function `async` and {ret_sugg}");
|
||||||
diag.span_suggestion(
|
diag.span_suggestion(
|
||||||
header_span,
|
header_span,
|
||||||
&help,
|
&help,
|
||||||
format!("async {}{}", &header_snip[..ret_pos], ret_snip),
|
format!("async {}{ret_snip}", &header_snip[..ret_pos]),
|
||||||
Applicability::MachineApplicable
|
Applicability::MachineApplicable
|
||||||
);
|
);
|
||||||
|
|
||||||
|
@ -196,7 +196,7 @@ fn suggested_ret(cx: &LateContext<'_>, output: &Ty<'_>) -> Option<(&'static str,
|
||||||
},
|
},
|
||||||
_ => {
|
_ => {
|
||||||
let sugg = "return the output of the future directly";
|
let sugg = "return the output of the future directly";
|
||||||
snippet_opt(cx, output.span).map(|snip| (sugg, format!(" -> {}", snip)))
|
snippet_opt(cx, output.span).map(|snip| (sugg, format!(" -> {snip}")))
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -133,7 +133,7 @@ impl EarlyLintPass for ManualNonExhaustiveStruct {
|
||||||
diag.span_suggestion(
|
diag.span_suggestion(
|
||||||
header_span,
|
header_span,
|
||||||
"add the attribute",
|
"add the attribute",
|
||||||
format!("#[non_exhaustive] {}", snippet),
|
format!("#[non_exhaustive] {snippet}"),
|
||||||
Applicability::Unspecified,
|
Applicability::Unspecified,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -207,7 +207,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualNonExhaustiveEnum {
|
||||||
diag.span_suggestion(
|
diag.span_suggestion(
|
||||||
header_span,
|
header_span,
|
||||||
"add the attribute",
|
"add the attribute",
|
||||||
format!("#[non_exhaustive] {}", snippet),
|
format!("#[non_exhaustive] {snippet}"),
|
||||||
Applicability::Unspecified,
|
Applicability::Unspecified,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -153,7 +153,7 @@ fn suggest(cx: &LateContext<'_>, parent_expr: &hir::Expr<'_>, left_expr: &hir::E
|
||||||
&& let [filter_params] = filter_body.params
|
&& let [filter_params] = filter_body.params
|
||||||
&& let Some(sugg) = match filter_params.pat.kind {
|
&& let Some(sugg) = match filter_params.pat.kind {
|
||||||
hir::PatKind::Binding(_, _, filter_param_ident, None) => {
|
hir::PatKind::Binding(_, _, filter_param_ident, None) => {
|
||||||
Some(format!("{}.retain(|{}| {})", snippet(cx, left_expr.span, ".."), filter_param_ident, snippet(cx, filter_body.value.span, "..")))
|
Some(format!("{}.retain(|{filter_param_ident}| {})", snippet(cx, left_expr.span, ".."), snippet(cx, filter_body.value.span, "..")))
|
||||||
},
|
},
|
||||||
hir::PatKind::Tuple([key_pat, value_pat], _) => {
|
hir::PatKind::Tuple([key_pat, value_pat], _) => {
|
||||||
make_sugg(cx, key_pat, value_pat, left_expr, filter_body)
|
make_sugg(cx, key_pat, value_pat, left_expr, filter_body)
|
||||||
|
@ -161,7 +161,7 @@ fn suggest(cx: &LateContext<'_>, parent_expr: &hir::Expr<'_>, left_expr: &hir::E
|
||||||
hir::PatKind::Ref(pat, _) => {
|
hir::PatKind::Ref(pat, _) => {
|
||||||
match pat.kind {
|
match pat.kind {
|
||||||
hir::PatKind::Binding(_, _, filter_param_ident, None) => {
|
hir::PatKind::Binding(_, _, filter_param_ident, None) => {
|
||||||
Some(format!("{}.retain(|{}| {})", snippet(cx, left_expr.span, ".."), filter_param_ident, snippet(cx, filter_body.value.span, "..")))
|
Some(format!("{}.retain(|{filter_param_ident}| {})", snippet(cx, left_expr.span, ".."), snippet(cx, filter_body.value.span, "..")))
|
||||||
},
|
},
|
||||||
_ => None
|
_ => None
|
||||||
}
|
}
|
||||||
|
@ -190,23 +190,19 @@ fn make_sugg(
|
||||||
match (&key_pat.kind, &value_pat.kind) {
|
match (&key_pat.kind, &value_pat.kind) {
|
||||||
(hir::PatKind::Binding(_, _, key_param_ident, None), hir::PatKind::Binding(_, _, value_param_ident, None)) => {
|
(hir::PatKind::Binding(_, _, key_param_ident, None), hir::PatKind::Binding(_, _, value_param_ident, None)) => {
|
||||||
Some(format!(
|
Some(format!(
|
||||||
"{}.retain(|{}, &mut {}| {})",
|
"{}.retain(|{key_param_ident}, &mut {value_param_ident}| {})",
|
||||||
snippet(cx, left_expr.span, ".."),
|
snippet(cx, left_expr.span, ".."),
|
||||||
key_param_ident,
|
|
||||||
value_param_ident,
|
|
||||||
snippet(cx, filter_body.value.span, "..")
|
snippet(cx, filter_body.value.span, "..")
|
||||||
))
|
))
|
||||||
},
|
},
|
||||||
(hir::PatKind::Binding(_, _, key_param_ident, None), hir::PatKind::Wild) => Some(format!(
|
(hir::PatKind::Binding(_, _, key_param_ident, None), hir::PatKind::Wild) => Some(format!(
|
||||||
"{}.retain(|{}, _| {})",
|
"{}.retain(|{key_param_ident}, _| {})",
|
||||||
snippet(cx, left_expr.span, ".."),
|
snippet(cx, left_expr.span, ".."),
|
||||||
key_param_ident,
|
|
||||||
snippet(cx, filter_body.value.span, "..")
|
snippet(cx, filter_body.value.span, "..")
|
||||||
)),
|
)),
|
||||||
(hir::PatKind::Wild, hir::PatKind::Binding(_, _, value_param_ident, None)) => Some(format!(
|
(hir::PatKind::Wild, hir::PatKind::Binding(_, _, value_param_ident, None)) => Some(format!(
|
||||||
"{}.retain(|_, &mut {}| {})",
|
"{}.retain(|_, &mut {value_param_ident}| {})",
|
||||||
snippet(cx, left_expr.span, ".."),
|
snippet(cx, left_expr.span, ".."),
|
||||||
value_param_ident,
|
|
||||||
snippet(cx, filter_body.value.span, "..")
|
snippet(cx, filter_body.value.span, "..")
|
||||||
)),
|
)),
|
||||||
_ => None,
|
_ => None,
|
||||||
|
|
|
@ -108,15 +108,14 @@ impl<'tcx> LateLintPass<'tcx> for ManualStrip {
|
||||||
};
|
};
|
||||||
|
|
||||||
let test_span = expr.span.until(then.span);
|
let test_span = expr.span.until(then.span);
|
||||||
span_lint_and_then(cx, MANUAL_STRIP, strippings[0], &format!("stripping a {} manually", kind_word), |diag| {
|
span_lint_and_then(cx, MANUAL_STRIP, strippings[0], &format!("stripping a {kind_word} manually"), |diag| {
|
||||||
diag.span_note(test_span, &format!("the {} was tested here", kind_word));
|
diag.span_note(test_span, &format!("the {kind_word} was tested here"));
|
||||||
multispan_sugg(
|
multispan_sugg(
|
||||||
diag,
|
diag,
|
||||||
&format!("try using the `strip_{}` method", kind_word),
|
&format!("try using the `strip_{kind_word}` method"),
|
||||||
vec![(test_span,
|
vec![(test_span,
|
||||||
format!("if let Some(<stripped>) = {}.strip_{}({}) ",
|
format!("if let Some(<stripped>) = {}.strip_{kind_word}({}) ",
|
||||||
snippet(cx, target_arg.span, ".."),
|
snippet(cx, target_arg.span, ".."),
|
||||||
kind_word,
|
|
||||||
snippet(cx, pattern.span, "..")))]
|
snippet(cx, pattern.span, "..")))]
|
||||||
.into_iter().chain(strippings.into_iter().map(|span| (span, "<stripped>".into()))),
|
.into_iter().chain(strippings.into_iter().map(|span| (span, "<stripped>".into()))),
|
||||||
);
|
);
|
||||||
|
|
|
@ -194,10 +194,7 @@ fn let_binding_name(cx: &LateContext<'_>, var_arg: &hir::Expr<'_>) -> String {
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
fn suggestion_msg(function_type: &str, map_type: &str) -> String {
|
fn suggestion_msg(function_type: &str, map_type: &str) -> String {
|
||||||
format!(
|
format!("called `map(f)` on an `{map_type}` value where `f` is a {function_type} that returns the unit type `()`")
|
||||||
"called `map(f)` on an `{0}` value where `f` is a {1} that returns the unit type `()`",
|
|
||||||
map_type, function_type
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn lint_map_unit_fn(
|
fn lint_map_unit_fn(
|
||||||
|
|
|
@ -70,9 +70,7 @@ impl<'tcx> LateLintPass<'tcx> for MatchResultOk {
|
||||||
let some_expr_string = snippet_with_applicability(cx, y[0].span, "", &mut applicability);
|
let some_expr_string = snippet_with_applicability(cx, y[0].span, "", &mut applicability);
|
||||||
let trimmed_ok = snippet_with_applicability(cx, let_expr.span.until(ok_path.ident.span), "", &mut applicability);
|
let trimmed_ok = snippet_with_applicability(cx, let_expr.span.until(ok_path.ident.span), "", &mut applicability);
|
||||||
let sugg = format!(
|
let sugg = format!(
|
||||||
"{} let Ok({}) = {}",
|
"{ifwhile} let Ok({some_expr_string}) = {}",
|
||||||
ifwhile,
|
|
||||||
some_expr_string,
|
|
||||||
trimmed_ok.trim().trim_end_matches('.'),
|
trimmed_ok.trim().trim_end_matches('.'),
|
||||||
);
|
);
|
||||||
span_lint_and_sugg(
|
span_lint_and_sugg(
|
||||||
|
@ -80,7 +78,7 @@ impl<'tcx> LateLintPass<'tcx> for MatchResultOk {
|
||||||
MATCH_RESULT_OK,
|
MATCH_RESULT_OK,
|
||||||
expr.span.with_hi(let_expr.span.hi()),
|
expr.span.with_hi(let_expr.span.hi()),
|
||||||
"matching on `Some` with `ok()` is redundant",
|
"matching on `Some` with `ok()` is redundant",
|
||||||
&format!("consider matching on `Ok({})` and removing the call to `ok` instead", some_expr_string),
|
&format!("consider matching on `Ok({some_expr_string})` and removing the call to `ok` instead"),
|
||||||
sugg,
|
sugg,
|
||||||
applicability,
|
applicability,
|
||||||
);
|
);
|
||||||
|
|
|
@ -144,7 +144,7 @@ fn check<'tcx>(
|
||||||
let scrutinee = peel_hir_expr_refs(scrutinee).0;
|
let scrutinee = peel_hir_expr_refs(scrutinee).0;
|
||||||
let (scrutinee_str, _) = snippet_with_context(cx, scrutinee.span, expr_ctxt, "..", &mut app);
|
let (scrutinee_str, _) = snippet_with_context(cx, scrutinee.span, expr_ctxt, "..", &mut app);
|
||||||
let scrutinee_str = if scrutinee.span.ctxt() == expr.span.ctxt() && scrutinee.precedence().order() < PREC_POSTFIX {
|
let scrutinee_str = if scrutinee.span.ctxt() == expr.span.ctxt() && scrutinee.precedence().order() < PREC_POSTFIX {
|
||||||
format!("({})", scrutinee_str)
|
format!("({scrutinee_str})")
|
||||||
} else {
|
} else {
|
||||||
scrutinee_str.into()
|
scrutinee_str.into()
|
||||||
};
|
};
|
||||||
|
@ -172,9 +172,9 @@ fn check<'tcx>(
|
||||||
};
|
};
|
||||||
let expr_snip = snippet_with_context(cx, some_expr.expr.span, expr_ctxt, "..", &mut app).0;
|
let expr_snip = snippet_with_context(cx, some_expr.expr.span, expr_ctxt, "..", &mut app).0;
|
||||||
if some_expr.needs_unsafe_block {
|
if some_expr.needs_unsafe_block {
|
||||||
format!("|{}{}| unsafe {{ {} }}", annotation, some_binding, expr_snip)
|
format!("|{annotation}{some_binding}| unsafe {{ {expr_snip} }}")
|
||||||
} else {
|
} else {
|
||||||
format!("|{}{}| {}", annotation, some_binding, expr_snip)
|
format!("|{annotation}{some_binding}| {expr_snip}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -183,9 +183,9 @@ fn check<'tcx>(
|
||||||
let pat_snip = snippet_with_context(cx, some_pat.span, expr_ctxt, "..", &mut app).0;
|
let pat_snip = snippet_with_context(cx, some_pat.span, expr_ctxt, "..", &mut app).0;
|
||||||
let expr_snip = snippet_with_context(cx, some_expr.expr.span, expr_ctxt, "..", &mut app).0;
|
let expr_snip = snippet_with_context(cx, some_expr.expr.span, expr_ctxt, "..", &mut app).0;
|
||||||
if some_expr.needs_unsafe_block {
|
if some_expr.needs_unsafe_block {
|
||||||
format!("|{}| unsafe {{ {} }}", pat_snip, expr_snip)
|
format!("|{pat_snip}| unsafe {{ {expr_snip} }}")
|
||||||
} else {
|
} else {
|
||||||
format!("|{}| {}", pat_snip, expr_snip)
|
format!("|{pat_snip}| {expr_snip}")
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Refutable bindings and mixed reference annotations can't be handled by `map`.
|
// Refutable bindings and mixed reference annotations can't be handled by `map`.
|
||||||
|
@ -199,9 +199,9 @@ fn check<'tcx>(
|
||||||
"manual implementation of `Option::map`",
|
"manual implementation of `Option::map`",
|
||||||
"try this",
|
"try this",
|
||||||
if else_pat.is_none() && is_else_clause(cx.tcx, expr) {
|
if else_pat.is_none() && is_else_clause(cx.tcx, expr) {
|
||||||
format!("{{ {}{}.map({}) }}", scrutinee_str, as_ref_str, body_str)
|
format!("{{ {scrutinee_str}{as_ref_str}.map({body_str}) }}")
|
||||||
} else {
|
} else {
|
||||||
format!("{}{}.map({})", scrutinee_str, as_ref_str, body_str)
|
format!("{scrutinee_str}{as_ref_str}.map({body_str})")
|
||||||
},
|
},
|
||||||
app,
|
app,
|
||||||
);
|
);
|
||||||
|
|
|
@ -42,12 +42,10 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>, scrutinee:
|
||||||
span_lint_and_sugg(
|
span_lint_and_sugg(
|
||||||
cx,
|
cx,
|
||||||
MANUAL_UNWRAP_OR, expr.span,
|
MANUAL_UNWRAP_OR, expr.span,
|
||||||
&format!("this pattern reimplements `{}::unwrap_or`", ty_name),
|
&format!("this pattern reimplements `{ty_name}::unwrap_or`"),
|
||||||
"replace with",
|
"replace with",
|
||||||
format!(
|
format!(
|
||||||
"{}.unwrap_or({})",
|
"{suggestion}.unwrap_or({reindented_or_body})",
|
||||||
suggestion,
|
|
||||||
reindented_or_body,
|
|
||||||
),
|
),
|
||||||
Applicability::MachineApplicable,
|
Applicability::MachineApplicable,
|
||||||
);
|
);
|
||||||
|
|
|
@ -45,13 +45,11 @@ pub(crate) fn check(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr:
|
||||||
cx,
|
cx,
|
||||||
MATCH_AS_REF,
|
MATCH_AS_REF,
|
||||||
expr.span,
|
expr.span,
|
||||||
&format!("use `{}()` instead", suggestion),
|
&format!("use `{suggestion}()` instead"),
|
||||||
"try this",
|
"try this",
|
||||||
format!(
|
format!(
|
||||||
"{}.{}(){}",
|
"{}.{suggestion}(){cast}",
|
||||||
snippet_with_applicability(cx, ex.span, "_", &mut applicability),
|
snippet_with_applicability(cx, ex.span, "_", &mut applicability),
|
||||||
suggestion,
|
|
||||||
cast,
|
|
||||||
),
|
),
|
||||||
applicability,
|
applicability,
|
||||||
);
|
);
|
||||||
|
|
|
@ -112,7 +112,7 @@ where
|
||||||
.join(" | ")
|
.join(" | ")
|
||||||
};
|
};
|
||||||
let pat_and_guard = if let Some(Guard::If(g)) = first_guard {
|
let pat_and_guard = if let Some(Guard::If(g)) = first_guard {
|
||||||
format!("{} if {}", pat, snippet_with_applicability(cx, g.span, "..", &mut applicability))
|
format!("{pat} if {}", snippet_with_applicability(cx, g.span, "..", &mut applicability))
|
||||||
} else {
|
} else {
|
||||||
pat
|
pat
|
||||||
};
|
};
|
||||||
|
@ -131,10 +131,9 @@ where
|
||||||
&format!("{} expression looks like `matches!` macro", if is_if_let { "if let .. else" } else { "match" }),
|
&format!("{} expression looks like `matches!` macro", if is_if_let { "if let .. else" } else { "match" }),
|
||||||
"try this",
|
"try this",
|
||||||
format!(
|
format!(
|
||||||
"{}matches!({}, {})",
|
"{}matches!({}, {pat_and_guard})",
|
||||||
if b0 { "" } else { "!" },
|
if b0 { "" } else { "!" },
|
||||||
snippet_with_applicability(cx, ex_new.span, "..", &mut applicability),
|
snippet_with_applicability(cx, ex_new.span, "..", &mut applicability),
|
||||||
pat_and_guard,
|
|
||||||
),
|
),
|
||||||
applicability,
|
applicability,
|
||||||
);
|
);
|
||||||
|
|
|
@ -135,7 +135,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>]) {
|
||||||
diag.span_suggestion(
|
diag.span_suggestion(
|
||||||
keep_arm.pat.span,
|
keep_arm.pat.span,
|
||||||
"try merging the arm patterns",
|
"try merging the arm patterns",
|
||||||
format!("{} | {}", keep_pat_snip, move_pat_snip),
|
format!("{keep_pat_snip} | {move_pat_snip}"),
|
||||||
Applicability::MaybeIncorrect,
|
Applicability::MaybeIncorrect,
|
||||||
)
|
)
|
||||||
.help("or try changing either arm body")
|
.help("or try changing either arm body")
|
||||||
|
|
|
@ -75,12 +75,11 @@ pub(crate) fn check<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], e
|
||||||
Some(AssignmentExpr::Local { span, pat_span }) => (
|
Some(AssignmentExpr::Local { span, pat_span }) => (
|
||||||
span,
|
span,
|
||||||
format!(
|
format!(
|
||||||
"let {} = {};\n{}let {} = {};",
|
"let {} = {};\n{}let {} = {snippet_body};",
|
||||||
snippet_with_applicability(cx, bind_names, "..", &mut applicability),
|
snippet_with_applicability(cx, bind_names, "..", &mut applicability),
|
||||||
snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
|
snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
|
||||||
" ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
|
" ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
|
||||||
snippet_with_applicability(cx, pat_span, "..", &mut applicability),
|
snippet_with_applicability(cx, pat_span, "..", &mut applicability)
|
||||||
snippet_body
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
None => {
|
None => {
|
||||||
|
@ -110,10 +109,8 @@ pub(crate) fn check<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], e
|
||||||
if ex.can_have_side_effects() {
|
if ex.can_have_side_effects() {
|
||||||
let indent = " ".repeat(indent_of(cx, expr.span).unwrap_or(0));
|
let indent = " ".repeat(indent_of(cx, expr.span).unwrap_or(0));
|
||||||
let sugg = format!(
|
let sugg = format!(
|
||||||
"{};\n{}{}",
|
"{};\n{indent}{snippet_body}",
|
||||||
snippet_with_applicability(cx, ex.span, "..", &mut applicability),
|
snippet_with_applicability(cx, ex.span, "..", &mut applicability)
|
||||||
indent,
|
|
||||||
snippet_body
|
|
||||||
);
|
);
|
||||||
|
|
||||||
span_lint_and_sugg(
|
span_lint_and_sugg(
|
||||||
|
@ -178,10 +175,10 @@ fn sugg_with_curlies<'a>(
|
||||||
let (mut cbrace_start, mut cbrace_end) = (String::new(), String::new());
|
let (mut cbrace_start, mut cbrace_end) = (String::new(), String::new());
|
||||||
if let Some(parent_expr) = get_parent_expr(cx, match_expr) {
|
if let Some(parent_expr) = get_parent_expr(cx, match_expr) {
|
||||||
if let ExprKind::Closure { .. } = parent_expr.kind {
|
if let ExprKind::Closure { .. } = parent_expr.kind {
|
||||||
cbrace_end = format!("\n{}}}", indent);
|
cbrace_end = format!("\n{indent}}}");
|
||||||
// Fix body indent due to the closure
|
// Fix body indent due to the closure
|
||||||
indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
|
indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
|
||||||
cbrace_start = format!("{{\n{}", indent);
|
cbrace_start = format!("{{\n{indent}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -190,10 +187,10 @@ fn sugg_with_curlies<'a>(
|
||||||
let parent_node_id = cx.tcx.hir().get_parent_node(match_expr.hir_id);
|
let parent_node_id = cx.tcx.hir().get_parent_node(match_expr.hir_id);
|
||||||
if let Node::Arm(arm) = &cx.tcx.hir().get(parent_node_id) {
|
if let Node::Arm(arm) = &cx.tcx.hir().get(parent_node_id) {
|
||||||
if let ExprKind::Match(..) = arm.body.kind {
|
if let ExprKind::Match(..) = arm.body.kind {
|
||||||
cbrace_end = format!("\n{}}}", indent);
|
cbrace_end = format!("\n{indent}}}");
|
||||||
// Fix body indent due to the match
|
// Fix body indent due to the match
|
||||||
indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
|
indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
|
||||||
cbrace_start = format!("{{\n{}", indent);
|
cbrace_start = format!("{{\n{indent}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -204,13 +201,8 @@ fn sugg_with_curlies<'a>(
|
||||||
});
|
});
|
||||||
|
|
||||||
format!(
|
format!(
|
||||||
"{}let {} = {};\n{}{}{}{}",
|
"{cbrace_start}let {} = {};\n{indent}{assignment_str}{snippet_body}{cbrace_end}",
|
||||||
cbrace_start,
|
|
||||||
snippet_with_applicability(cx, bind_names, "..", applicability),
|
snippet_with_applicability(cx, bind_names, "..", applicability),
|
||||||
snippet_with_applicability(cx, matched_vars, "..", applicability),
|
snippet_with_applicability(cx, matched_vars, "..", applicability)
|
||||||
indent,
|
|
||||||
assignment_str,
|
|
||||||
snippet_body,
|
|
||||||
cbrace_end
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
@ -118,8 +118,8 @@ fn lint(cx: &LateContext<'_>, case_method: &CaseMethod, bad_case_span: Span, bad
|
||||||
MATCH_STR_CASE_MISMATCH,
|
MATCH_STR_CASE_MISMATCH,
|
||||||
bad_case_span,
|
bad_case_span,
|
||||||
"this `match` arm has a differing case than its expression",
|
"this `match` arm has a differing case than its expression",
|
||||||
&format!("consider changing the case of this arm to respect `{}`", method_str),
|
&format!("consider changing the case of this arm to respect `{method_str}`"),
|
||||||
format!("\"{}\"", suggestion),
|
format!("\"{suggestion}\""),
|
||||||
Applicability::MachineApplicable,
|
Applicability::MachineApplicable,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -38,7 +38,7 @@ pub(crate) fn check<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm<'
|
||||||
span_lint_and_note(cx,
|
span_lint_and_note(cx,
|
||||||
MATCH_WILD_ERR_ARM,
|
MATCH_WILD_ERR_ARM,
|
||||||
arm.pat.span,
|
arm.pat.span,
|
||||||
&format!("`Err({})` matches all errors", ident_bind_name),
|
&format!("`Err({ident_bind_name})` matches all errors"),
|
||||||
None,
|
None,
|
||||||
"match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable",
|
"match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable",
|
||||||
);
|
);
|
||||||
|
|
|
@ -138,7 +138,7 @@ fn find_sugg_for_if_let<'tcx>(
|
||||||
cx,
|
cx,
|
||||||
REDUNDANT_PATTERN_MATCHING,
|
REDUNDANT_PATTERN_MATCHING,
|
||||||
let_pat.span,
|
let_pat.span,
|
||||||
&format!("redundant pattern matching, consider using `{}`", good_method),
|
&format!("redundant pattern matching, consider using `{good_method}`"),
|
||||||
|diag| {
|
|diag| {
|
||||||
// if/while let ... = ... { ... }
|
// if/while let ... = ... { ... }
|
||||||
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||||
|
@ -162,7 +162,7 @@ fn find_sugg_for_if_let<'tcx>(
|
||||||
.maybe_par()
|
.maybe_par()
|
||||||
.to_string();
|
.to_string();
|
||||||
|
|
||||||
diag.span_suggestion(span, "try this", format!("{} {}.{}", keyword, sugg, good_method), app);
|
diag.span_suggestion(span, "try this", format!("{keyword} {sugg}.{good_method}"), app);
|
||||||
|
|
||||||
if needs_drop {
|
if needs_drop {
|
||||||
diag.note("this will change drop order of the result, as well as all temporaries");
|
diag.note("this will change drop order of the result, as well as all temporaries");
|
||||||
|
@ -252,12 +252,12 @@ pub(super) fn check_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op
|
||||||
cx,
|
cx,
|
||||||
REDUNDANT_PATTERN_MATCHING,
|
REDUNDANT_PATTERN_MATCHING,
|
||||||
expr.span,
|
expr.span,
|
||||||
&format!("redundant pattern matching, consider using `{}`", good_method),
|
&format!("redundant pattern matching, consider using `{good_method}`"),
|
||||||
|diag| {
|
|diag| {
|
||||||
diag.span_suggestion(
|
diag.span_suggestion(
|
||||||
span,
|
span,
|
||||||
"try this",
|
"try this",
|
||||||
format!("{}.{}", snippet(cx, result_expr.span, "_"), good_method),
|
format!("{}.{good_method}", snippet(cx, result_expr.span, "_")),
|
||||||
Applicability::MaybeIncorrect, // snippet
|
Applicability::MaybeIncorrect, // snippet
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
|
|
@ -50,13 +50,13 @@ fn set_diagnostic<'tcx>(diag: &mut Diagnostic, cx: &LateContext<'tcx>, expr: &'t
|
||||||
let trailing_indent = " ".repeat(indent_of(cx, found.found_span).unwrap_or(0));
|
let trailing_indent = " ".repeat(indent_of(cx, found.found_span).unwrap_or(0));
|
||||||
|
|
||||||
let replacement = if found.lint_suggestion == LintSuggestion::MoveAndDerefToCopy {
|
let replacement = if found.lint_suggestion == LintSuggestion::MoveAndDerefToCopy {
|
||||||
format!("let value = *{};\n{}", original, trailing_indent)
|
format!("let value = *{original};\n{trailing_indent}")
|
||||||
} else if found.is_unit_return_val {
|
} else if found.is_unit_return_val {
|
||||||
// If the return value of the expression to be moved is unit, then we don't need to
|
// If the return value of the expression to be moved is unit, then we don't need to
|
||||||
// capture the result in a temporary -- we can just replace it completely with `()`.
|
// capture the result in a temporary -- we can just replace it completely with `()`.
|
||||||
format!("{};\n{}", original, trailing_indent)
|
format!("{original};\n{trailing_indent}")
|
||||||
} else {
|
} else {
|
||||||
format!("let value = {};\n{}", original, trailing_indent)
|
format!("let value = {original};\n{trailing_indent}")
|
||||||
};
|
};
|
||||||
|
|
||||||
let suggestion_message = if found.lint_suggestion == LintSuggestion::MoveOnly {
|
let suggestion_message = if found.lint_suggestion == LintSuggestion::MoveOnly {
|
||||||
|
|
|
@ -99,23 +99,21 @@ fn report_single_pattern(
|
||||||
|
|
||||||
let msg = "you seem to be trying to use `match` for an equality check. Consider using `if`";
|
let msg = "you seem to be trying to use `match` for an equality check. Consider using `if`";
|
||||||
let sugg = format!(
|
let sugg = format!(
|
||||||
"if {} == {}{} {}{}",
|
"if {} == {}{} {}{els_str}",
|
||||||
snippet(cx, ex.span, ".."),
|
snippet(cx, ex.span, ".."),
|
||||||
// PartialEq for different reference counts may not exist.
|
// PartialEq for different reference counts may not exist.
|
||||||
"&".repeat(ref_count_diff),
|
"&".repeat(ref_count_diff),
|
||||||
snippet(cx, arms[0].pat.span, ".."),
|
snippet(cx, arms[0].pat.span, ".."),
|
||||||
expr_block(cx, arms[0].body, None, "..", Some(expr.span)),
|
expr_block(cx, arms[0].body, None, "..", Some(expr.span)),
|
||||||
els_str,
|
|
||||||
);
|
);
|
||||||
(msg, sugg)
|
(msg, sugg)
|
||||||
} else {
|
} else {
|
||||||
let msg = "you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let`";
|
let msg = "you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let`";
|
||||||
let sugg = format!(
|
let sugg = format!(
|
||||||
"if let {} = {} {}{}",
|
"if let {} = {} {}{els_str}",
|
||||||
snippet(cx, arms[0].pat.span, ".."),
|
snippet(cx, arms[0].pat.span, ".."),
|
||||||
snippet(cx, ex.span, ".."),
|
snippet(cx, ex.span, ".."),
|
||||||
expr_block(cx, arms[0].body, None, "..", Some(expr.span)),
|
expr_block(cx, arms[0].body, None, "..", Some(expr.span)),
|
||||||
els_str,
|
|
||||||
);
|
);
|
||||||
(msg, sugg)
|
(msg, sugg)
|
||||||
}
|
}
|
||||||
|
|
|
@ -61,9 +61,9 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, scrutine
|
||||||
"return "
|
"return "
|
||||||
};
|
};
|
||||||
let suggestion = if err_ty == expr_err_ty {
|
let suggestion = if err_ty == expr_err_ty {
|
||||||
format!("{}{}{}{}", ret_prefix, prefix, origin_snippet, suffix)
|
format!("{ret_prefix}{prefix}{origin_snippet}{suffix}")
|
||||||
} else {
|
} else {
|
||||||
format!("{}{}{}.into(){}", ret_prefix, prefix, origin_snippet, suffix)
|
format!("{ret_prefix}{prefix}{origin_snippet}.into(){suffix}")
|
||||||
};
|
};
|
||||||
|
|
||||||
span_lint_and_sugg(
|
span_lint_and_sugg(
|
||||||
|
|
|
@ -85,7 +85,7 @@ pub(crate) trait BindInsteadOfMap {
|
||||||
|
|
||||||
let closure_args_snip = snippet(cx, closure_args_span, "..");
|
let closure_args_snip = snippet(cx, closure_args_span, "..");
|
||||||
let option_snip = snippet(cx, recv.span, "..");
|
let option_snip = snippet(cx, recv.span, "..");
|
||||||
let note = format!("{}.{}({} {})", option_snip, Self::GOOD_METHOD_NAME, closure_args_snip, some_inner_snip);
|
let note = format!("{option_snip}.{}({closure_args_snip} {some_inner_snip})", Self::GOOD_METHOD_NAME);
|
||||||
span_lint_and_sugg(
|
span_lint_and_sugg(
|
||||||
cx,
|
cx,
|
||||||
BIND_INSTEAD_OF_MAP,
|
BIND_INSTEAD_OF_MAP,
|
||||||
|
|
|
@ -22,7 +22,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, recv: &'tcx E
|
||||||
cx,
|
cx,
|
||||||
BYTES_NTH,
|
BYTES_NTH,
|
||||||
expr.span,
|
expr.span,
|
||||||
&format!("called `.bytes().nth()` on a `{}`", caller_type),
|
&format!("called `.bytes().nth()` on a `{caller_type}`"),
|
||||||
"try",
|
"try",
|
||||||
format!(
|
format!(
|
||||||
"{}.as_bytes().get({})",
|
"{}.as_bytes().get({})",
|
||||||
|
|
|
@ -33,12 +33,11 @@ pub(super) fn check(
|
||||||
cx,
|
cx,
|
||||||
lint,
|
lint,
|
||||||
info.expr.span,
|
info.expr.span,
|
||||||
&format!("you should use the `{}` method", suggest),
|
&format!("you should use the `{suggest}` method"),
|
||||||
"like this",
|
"like this",
|
||||||
format!("{}{}.{}({})",
|
format!("{}{}.{suggest}({})",
|
||||||
if info.eq { "" } else { "!" },
|
if info.eq { "" } else { "!" },
|
||||||
snippet_with_applicability(cx, args[0].0.span, "..", &mut applicability),
|
snippet_with_applicability(cx, args[0].0.span, "..", &mut applicability),
|
||||||
suggest,
|
|
||||||
snippet_with_applicability(cx, arg_char.span, "..", &mut applicability)),
|
snippet_with_applicability(cx, arg_char.span, "..", &mut applicability)),
|
||||||
applicability,
|
applicability,
|
||||||
);
|
);
|
||||||
|
|
|
@ -26,12 +26,11 @@ pub(super) fn check<'tcx>(
|
||||||
cx,
|
cx,
|
||||||
lint,
|
lint,
|
||||||
info.expr.span,
|
info.expr.span,
|
||||||
&format!("you should use the `{}` method", suggest),
|
&format!("you should use the `{suggest}` method"),
|
||||||
"like this",
|
"like this",
|
||||||
format!("{}{}.{}('{}')",
|
format!("{}{}.{suggest}('{}')",
|
||||||
if info.eq { "" } else { "!" },
|
if info.eq { "" } else { "!" },
|
||||||
snippet_with_applicability(cx, args[0].0.span, "..", &mut applicability),
|
snippet_with_applicability(cx, args[0].0.span, "..", &mut applicability),
|
||||||
suggest,
|
|
||||||
c.escape_default()),
|
c.escape_default()),
|
||||||
applicability,
|
applicability,
|
||||||
);
|
);
|
||||||
|
|
|
@ -49,8 +49,7 @@ pub(super) fn check(
|
||||||
expr.span,
|
expr.span,
|
||||||
&format!(
|
&format!(
|
||||||
"using `clone` on a double-reference; \
|
"using `clone` on a double-reference; \
|
||||||
this will copy the reference of type `{}` instead of cloning the inner type",
|
this will copy the reference of type `{ty}` instead of cloning the inner type"
|
||||||
ty
|
|
||||||
),
|
),
|
||||||
|diag| {
|
|diag| {
|
||||||
if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
|
if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
|
||||||
|
@ -62,11 +61,11 @@ pub(super) fn check(
|
||||||
}
|
}
|
||||||
let refs = "&".repeat(n + 1);
|
let refs = "&".repeat(n + 1);
|
||||||
let derefs = "*".repeat(n);
|
let derefs = "*".repeat(n);
|
||||||
let explicit = format!("<{}{}>::clone({})", refs, ty, snip);
|
let explicit = format!("<{refs}{ty}>::clone({snip})");
|
||||||
diag.span_suggestion(
|
diag.span_suggestion(
|
||||||
expr.span,
|
expr.span,
|
||||||
"try dereferencing it",
|
"try dereferencing it",
|
||||||
format!("{}({}{}).clone()", refs, derefs, snip.deref()),
|
format!("{refs}({derefs}{}).clone()", snip.deref()),
|
||||||
Applicability::MaybeIncorrect,
|
Applicability::MaybeIncorrect,
|
||||||
);
|
);
|
||||||
diag.span_suggestion(
|
diag.span_suggestion(
|
||||||
|
@ -121,16 +120,16 @@ pub(super) fn check(
|
||||||
let (help, sugg) = if deref_count == 0 {
|
let (help, sugg) = if deref_count == 0 {
|
||||||
("try removing the `clone` call", snip.into())
|
("try removing the `clone` call", snip.into())
|
||||||
} else if parent_is_suffix_expr {
|
} else if parent_is_suffix_expr {
|
||||||
("try dereferencing it", format!("({}{})", "*".repeat(deref_count), snip))
|
("try dereferencing it", format!("({}{snip})", "*".repeat(deref_count)))
|
||||||
} else {
|
} else {
|
||||||
("try dereferencing it", format!("{}{}", "*".repeat(deref_count), snip))
|
("try dereferencing it", format!("{}{snip}", "*".repeat(deref_count)))
|
||||||
};
|
};
|
||||||
|
|
||||||
span_lint_and_sugg(
|
span_lint_and_sugg(
|
||||||
cx,
|
cx,
|
||||||
CLONE_ON_COPY,
|
CLONE_ON_COPY,
|
||||||
expr.span,
|
expr.span,
|
||||||
&format!("using `clone` on type `{}` which implements the `Copy` trait", ty),
|
&format!("using `clone` on type `{ty}` which implements the `Copy` trait"),
|
||||||
help,
|
help,
|
||||||
sugg,
|
sugg,
|
||||||
app,
|
app,
|
||||||
|
|
|
@ -41,7 +41,7 @@ pub(super) fn check(
|
||||||
expr.span,
|
expr.span,
|
||||||
"using `.clone()` on a ref-counted pointer",
|
"using `.clone()` on a ref-counted pointer",
|
||||||
"try this",
|
"try this",
|
||||||
format!("{}::<{}>::clone(&{})", caller_type, subst.type_at(0), snippet),
|
format!("{caller_type}::<{}>::clone(&{snippet})", subst.type_at(0)),
|
||||||
Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
|
Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue