Add an Option<Span> argument to span_lint_and_help.

This commit is contained in:
xiongmao86
2020-04-18 18:28:29 +08:00
parent d03d3bd95b
commit cf4e35339b
39 changed files with 138 additions and 37 deletions

View File

@@ -50,6 +50,7 @@ impl EarlyLintPass for AsConversions {
AS_CONVERSIONS, AS_CONVERSIONS,
expr.span, expr.span,
"using a potentially dangerous silent `as` conversion", "using a potentially dangerous silent `as` conversion",
None,
"consider using a safe wrapper for this conversion", "consider using a safe wrapper for this conversion",
); );
} }

View File

@@ -41,6 +41,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssertionsOnConstants {
} else { } else {
"`assert!(true)` will be optimized out by the compiler" "`assert!(true)` will be optimized out by the compiler"
}, },
None,
"remove it", "remove it",
); );
}; };
@@ -50,6 +51,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssertionsOnConstants {
ASSERTIONS_ON_CONSTANTS, ASSERTIONS_ON_CONSTANTS,
e.span, e.span,
"`assert!(false)` should probably be replaced", "`assert!(false)` should probably be replaced",
None,
"use `panic!()` or `unreachable!()`", "use `panic!()` or `unreachable!()`",
); );
}; };
@@ -59,6 +61,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssertionsOnConstants {
ASSERTIONS_ON_CONSTANTS, ASSERTIONS_ON_CONSTANTS,
e.span, e.span,
&format!("`assert!(false, {})` should probably be replaced", panic_message), &format!("`assert!(false, {})` should probably be replaced", panic_message),
None,
&format!("use `panic!({})` or `unreachable!({})`", panic_message, panic_message), &format!("use `panic!({})` or `unreachable!({})`", panic_message, panic_message),
) )
}; };

View File

@@ -85,6 +85,7 @@ fn check_atomic_load_store(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
INVALID_ATOMIC_ORDERING, INVALID_ATOMIC_ORDERING,
ordering_arg.span, ordering_arg.span,
"atomic loads cannot have `Release` and `AcqRel` ordering", "atomic loads cannot have `Release` and `AcqRel` ordering",
None,
"consider using ordering modes `Acquire`, `SeqCst` or `Relaxed`" "consider using ordering modes `Acquire`, `SeqCst` or `Relaxed`"
); );
} else if method == "store" && } else if method == "store" &&
@@ -94,6 +95,7 @@ fn check_atomic_load_store(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
INVALID_ATOMIC_ORDERING, INVALID_ATOMIC_ORDERING,
ordering_arg.span, ordering_arg.span,
"atomic stores cannot have `Acquire` and `AcqRel` ordering", "atomic stores cannot have `Acquire` and `AcqRel` ordering",
None,
"consider using ordering modes `Release`, `SeqCst` or `Relaxed`" "consider using ordering modes `Release`, `SeqCst` or `Relaxed`"
); );
} }
@@ -118,6 +120,7 @@ fn check_memory_fence(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
INVALID_ATOMIC_ORDERING, INVALID_ATOMIC_ORDERING,
args[0].span, args[0].span,
"memory fences cannot have `Relaxed` ordering", "memory fences cannot have `Relaxed` ordering",
None,
"consider using ordering modes `Acquire`, `Release`, `AcqRel` or `SeqCst`" "consider using ordering modes `Acquire`, `Release`, `AcqRel` or `SeqCst`"
); );
} }

View File

@@ -105,6 +105,7 @@ impl CognitiveComplexity {
rust_cc, rust_cc,
self.limit.limit() self.limit.limit()
), ),
None,
"you could split it up into multiple smaller functions", "you could split it up into multiple smaller functions",
); );
} }

View File

@@ -104,6 +104,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ComparisonChain {
COMPARISON_CHAIN, COMPARISON_CHAIN,
expr.span, expr.span,
"`if` chain can be rewritten with `match`", "`if` chain can be rewritten with `match`",
None,
"Consider rewriting the `if` chain to use `cmp` and `match`.", "Consider rewriting the `if` chain to use `cmp` and `match`.",
) )
} }

View File

@@ -48,6 +48,7 @@ impl EarlyLintPass for DbgMacro {
DBG_MACRO, DBG_MACRO,
mac.span(), mac.span(),
"`dbg!` macro is intended as a debugging tool", "`dbg!` macro is intended as a debugging tool",
None,
"ensure to avoid having uses of it in version control", "ensure to avoid having uses of it in version control",
); );
} }

View File

@@ -61,6 +61,7 @@ impl EarlyLintPass for ElseIfWithoutElse {
ELSE_IF_WITHOUT_ELSE, ELSE_IF_WITHOUT_ELSE,
els.span, els.span,
"`if` expression with an `else if`, but without a final `else`", "`if` expression with an `else if`, but without a final `else`",
None,
"add an `else` block here", "add an `else` block here",
); );
} }

View File

@@ -45,13 +45,14 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EmptyEnum {
let ty = cx.tcx.type_of(did); let ty = cx.tcx.type_of(did);
let adt = ty.ty_adt_def().expect("already checked whether this is an enum"); let adt = ty.ty_adt_def().expect("already checked whether this is an enum");
if adt.variants.is_empty() { if adt.variants.is_empty() {
span_lint_and_then( span_lint_and_help(
cx, cx,
EMPTY_ENUM, EMPTY_ENUM,
item.span, item.span,
"enum with no variants", "enum with no variants",
"consider using the uninhabited type `!` (never type) or a wrapper around it \ Some(item.span),
to introduce a type which can't be instantiated", "consider using the uninhabited type `!` (never type) or a wrapper \
around it to introduce a type which can't be instantiated",
); );
} }
} }

View File

@@ -206,6 +206,7 @@ fn check_variant(
lint, lint,
span, span,
&format!("All variants have the same {}fix: `{}`", what, value), &format!("All variants have the same {}fix: `{}`", what, value),
None,
&format!( &format!(
"remove the {}fixes and use full paths to \ "remove the {}fixes and use full paths to \
the variants instead of glob imports", the variants instead of glob imports",

View File

@@ -114,6 +114,7 @@ impl ExcessiveBools {
FN_PARAMS_EXCESSIVE_BOOLS, FN_PARAMS_EXCESSIVE_BOOLS,
span, span,
&format!("more than {} bools in function parameters", self.max_fn_params_bools), &format!("more than {} bools in function parameters", self.max_fn_params_bools),
None,
"consider refactoring bools into two-variant enums", "consider refactoring bools into two-variant enums",
); );
} }
@@ -153,6 +154,7 @@ impl EarlyLintPass for ExcessiveBools {
STRUCT_EXCESSIVE_BOOLS, STRUCT_EXCESSIVE_BOOLS,
item.span, item.span,
&format!("more than {} bools in a struct", self.max_struct_bools), &format!("more than {} bools in a struct", self.max_struct_bools),
None,
"consider using a state machine or refactoring bools into two-variant enums", "consider using a state machine or refactoring bools into two-variant enums",
); );
} }

View File

@@ -188,6 +188,7 @@ fn check_unop(cx: &EarlyContext<'_>, expr: &Expr) {
binop = binop_str, binop = binop_str,
unop = unop_str unop = unop_str
), ),
None,
&format!( &format!(
"put a space between `{binop}` and `{unop}` and remove the space after `{unop}`", "put a space between `{binop}` and `{unop}` and remove the space after `{unop}`",
binop = binop_str, binop = binop_str,

View File

@@ -431,6 +431,7 @@ fn check_needless_must_use(
DOUBLE_MUST_USE, DOUBLE_MUST_USE,
fn_header_span, fn_header_span,
"this function has an empty `#[must_use]` attribute, but returns a type already marked as `#[must_use]`", "this function has an empty `#[must_use]` attribute, but returns a type already marked as `#[must_use]`",
None,
"either add some descriptive text or remove the attribute", "either add some descriptive text or remove the attribute",
); );
} }

View File

@@ -61,6 +61,7 @@ impl EarlyLintPass for IfNotElse {
IF_NOT_ELSE, IF_NOT_ELSE,
item.span, item.span,
"Unnecessary boolean `not` operation", "Unnecessary boolean `not` operation",
None,
"remove the `!` and swap the blocks of the `if`/`else`", "remove the `!` and swap the blocks of the `if`/`else`",
); );
}, },
@@ -70,6 +71,7 @@ impl EarlyLintPass for IfNotElse {
IF_NOT_ELSE, IF_NOT_ELSE,
item.span, item.span,
"Unnecessary `!=` operation", "Unnecessary `!=` operation",
None,
"change to `==` and swap the blocks of the `if`/`else`", "change to `==` and swap the blocks of the `if`/`else`",
); );
}, },

View File

@@ -138,7 +138,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for IndexingSlicing {
(None, None) => return, // [..] is ok. (None, None) => return, // [..] is ok.
}; };
span_lint_and_help(cx, INDEXING_SLICING, expr.span, "slicing may panic.", help_msg); span_lint_and_help(cx, INDEXING_SLICING, expr.span, "slicing may panic.", None, help_msg);
} else { } else {
// Catchall non-range index, i.e., [n] or [n << m] // Catchall non-range index, i.e., [n] or [n << m]
if let ty::Array(..) = ty.kind { if let ty::Array(..) = ty.kind {
@@ -154,6 +154,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for IndexingSlicing {
INDEXING_SLICING, INDEXING_SLICING,
expr.span, expr.span,
"indexing may panic.", "indexing may panic.",
None,
"Consider using `.get(n)` or `.get_mut(n)` instead", "Consider using `.get(n)` or `.get_mut(n)` instead",
); );
} }

View File

@@ -137,6 +137,7 @@ fn show_lint(cx: &LateContext<'_, '_>, item: &ImplItem<'_>) {
"type `{}` implements inherent method `to_string(&self) -> String` which shadows the implementation of `Display`", "type `{}` implements inherent method `to_string(&self) -> String` which shadows the implementation of `Display`",
self_type.to_string() self_type.to_string()
), ),
None,
&format!("remove the inherent method from type `{}`", self_type.to_string()) &format!("remove the inherent method from type `{}`", self_type.to_string())
); );
} else { } else {
@@ -148,6 +149,7 @@ fn show_lint(cx: &LateContext<'_, '_>, item: &ImplItem<'_>) {
"implementation of inherent method `to_string(&self) -> String` for type `{}`", "implementation of inherent method `to_string(&self) -> String` for type `{}`",
self_type.to_string() self_type.to_string()
), ),
None,
&format!("implement trait `Display` for type `{}` instead", self_type.to_string()), &format!("implement trait `Display` for type `{}` instead", self_type.to_string()),
); );
} }

View File

@@ -35,6 +35,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for IntegerDivision {
INTEGER_DIVISION, INTEGER_DIVISION,
expr.span, expr.span,
"integer division", "integer division",
None,
"division of integers may cause loss of precision. consider using floats.", "division of integers may cause loss of precision. consider using floats.",
); );
} }

View File

@@ -57,6 +57,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LargeStackArrays {
"allocating a local array larger than {} bytes", "allocating a local array larger than {} bytes",
self.maximum_allowed_size self.maximum_allowed_size
), ),
None,
&format!( &format!(
"consider allocating on the heap with `vec!{}.into_boxed_slice()`", "consider allocating on the heap with `vec!{}.into_boxed_slice()`",
snippet(cx, expr.span, "[...]") snippet(cx, expr.span, "[...]")

View File

@@ -90,6 +90,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnderscore {
LET_UNDERSCORE_LOCK, LET_UNDERSCORE_LOCK,
local.span, local.span,
"non-binding let on a synchronization lock", "non-binding let on a synchronization lock",
None,
"consider using an underscore-prefixed named \ "consider using an underscore-prefixed named \
binding or dropping explicitly with `std::mem::drop`" binding or dropping explicitly with `std::mem::drop`"
) )
@@ -99,6 +100,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnderscore {
LET_UNDERSCORE_MUST_USE, LET_UNDERSCORE_MUST_USE,
local.span, local.span,
"non-binding let on an expression with `#[must_use]` type", "non-binding let on an expression with `#[must_use]` type",
None,
"consider explicitly using expression value" "consider explicitly using expression value"
) )
} else if is_must_use_func_call(cx, init) { } else if is_must_use_func_call(cx, init) {
@@ -107,6 +109,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnderscore {
LET_UNDERSCORE_MUST_USE, LET_UNDERSCORE_MUST_USE,
local.span, local.span,
"non-binding let on a result of a `#[must_use]` function", "non-binding let on a result of a `#[must_use]` function",
None,
"consider explicitly using function result" "consider explicitly using function result"
) )
} }

View File

@@ -1402,6 +1402,7 @@ fn check_arg_type(cx: &LateContext<'_, '_>, pat: &Pat<'_>, arg: &Expr<'_>) {
`if let` statement.", `if let` statement.",
snippet(cx, arg.span, "_") snippet(cx, arg.span, "_")
), ),
None,
&format!( &format!(
"consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`", "consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
snippet(cx, pat.span, "_"), snippet(cx, pat.span, "_"),
@@ -1418,6 +1419,7 @@ fn check_arg_type(cx: &LateContext<'_, '_>, pat: &Pat<'_>, arg: &Expr<'_>) {
`if let` statement.", `if let` statement.",
snippet(cx, arg.span, "_") snippet(cx, arg.span, "_")
), ),
None,
&format!( &format!(
"consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`", "consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
snippet(cx, pat.span, "_"), snippet(cx, pat.span, "_"),

View File

@@ -53,6 +53,7 @@ impl LateLintPass<'_, '_> for MainRecursion {
MAIN_RECURSION, MAIN_RECURSION,
func.span, func.span,
&format!("recursing into entrypoint `{}`", snippet(cx, func.span, "main")), &format!("recursing into entrypoint `{}`", snippet(cx, func.span, "main")),
None,
"consider using another function for this recursion" "consider using another function for this recursion"
) )
} }

View File

@@ -441,6 +441,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Matches {
REST_PAT_IN_FULLY_BOUND_STRUCTS, REST_PAT_IN_FULLY_BOUND_STRUCTS,
pat.span, pat.span,
"unnecessary use of `..` pattern in struct binding. All fields were already bound", "unnecessary use of `..` pattern in struct binding. All fields were already bound",
None,
"consider removing `..` from this binding", "consider removing `..` from this binding",
); );
} }
@@ -887,6 +888,7 @@ fn check_wild_in_or_pats(cx: &LateContext<'_, '_>, arms: &[Arm<'_>]) {
WILDCARD_IN_OR_PATTERNS, WILDCARD_IN_OR_PATTERNS,
arm.pat.span, arm.pat.span,
"wildcard pattern covers any other pattern as it will match anyway.", "wildcard pattern covers any other pattern as it will match anyway.",
None,
"Consider handling `_` separately.", "Consider handling `_` separately.",
); );
} }

View File

@@ -148,6 +148,7 @@ fn check_replace_with_uninit(cx: &LateContext<'_, '_>, src: &Expr<'_>, expr_span
MEM_REPLACE_WITH_UNINIT, MEM_REPLACE_WITH_UNINIT,
expr_span, expr_span,
"replacing with `mem::uninitialized()`", "replacing with `mem::uninitialized()`",
None,
"consider using the `take_mut` crate instead", "consider using the `take_mut` crate instead",
); );
} else if cx.tcx.is_diagnostic_item(sym::mem_zeroed, repl_def_id) && } else if cx.tcx.is_diagnostic_item(sym::mem_zeroed, repl_def_id) &&
@@ -157,6 +158,7 @@ fn check_replace_with_uninit(cx: &LateContext<'_, '_>, src: &Expr<'_>, expr_span
MEM_REPLACE_WITH_UNINIT, MEM_REPLACE_WITH_UNINIT,
expr_span, expr_span,
"replacing with `mem::zeroed()`", "replacing with `mem::zeroed()`",
None,
"consider using a default value or the `take_mut` crate instead", "consider using a default value or the `take_mut` crate instead",
); );
} }

View File

@@ -2255,6 +2255,7 @@ fn lint_iter_nth<'a, 'tcx>(
ITER_NTH, ITER_NTH,
expr.span, expr.span,
&format!("called `.iter{0}().nth()` on a {1}", mut_str, caller_type), &format!("called `.iter{0}().nth()` on a {1}", mut_str, caller_type),
None,
&format!("calling `.get{}()` is both faster and more readable", mut_str), &format!("calling `.get{}()` is both faster and more readable", mut_str),
); );
} }
@@ -2364,6 +2365,7 @@ fn lint_iter_skip_next(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) {
ITER_SKIP_NEXT, ITER_SKIP_NEXT,
expr.span, expr.span,
"called `skip(x).next()` on an iterator", "called `skip(x).next()` on an iterator",
None,
"this is more succinctly expressed by calling `nth(x)`", "this is more succinctly expressed by calling `nth(x)`",
); );
} }
@@ -2431,6 +2433,7 @@ fn lint_unwrap(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, unwrap_args: &[hi
lint, lint,
expr.span, expr.span,
&format!("used `unwrap()` on `{}` value", kind,), &format!("used `unwrap()` on `{}` value", kind,),
None,
&format!( &format!(
"if you don't want to handle the `{}` case gracefully, consider \ "if you don't want to handle the `{}` case gracefully, consider \
using `expect()` to provide a better panic message", using `expect()` to provide a better panic message",
@@ -2458,6 +2461,7 @@ fn lint_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, expect_args: &[hi
lint, lint,
expr.span, expr.span,
&format!("used `expect()` on `{}` value", kind,), &format!("used `expect()` on `{}` value", kind,),
None,
&format!("if this value is an `{}`, it will panic", none_value,), &format!("if this value is an `{}`, it will panic", none_value,),
); );
} }
@@ -2478,6 +2482,7 @@ fn lint_ok_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, ok_args: &[hir
OK_EXPECT, OK_EXPECT,
expr.span, expr.span,
"called `ok().expect()` on a `Result` value", "called `ok().expect()` on a `Result` value",
None,
"you can call `expect()` directly on the `Result`", "you can call `expect()` directly on the `Result`",
); );
} }
@@ -2774,6 +2779,7 @@ fn lint_skip_while_next<'a, 'tcx>(
SKIP_WHILE_NEXT, SKIP_WHILE_NEXT,
expr.span, expr.span,
"called `skip_while(p).next()` on an `Iterator`", "called `skip_while(p).next()` on an `Iterator`",
None,
"this is more succinctly expressed by calling `.find(!p)` instead", "this is more succinctly expressed by calling `.find(!p)` instead",
); );
} }
@@ -2790,7 +2796,7 @@ fn lint_filter_map<'a, 'tcx>(
if match_trait_method(cx, expr, &paths::ITERATOR) { if match_trait_method(cx, expr, &paths::ITERATOR) {
let msg = "called `filter(p).map(q)` on an `Iterator`"; let msg = "called `filter(p).map(q)` on an `Iterator`";
let hint = "this is more succinctly expressed by calling `.filter_map(..)` instead"; let hint = "this is more succinctly expressed by calling `.filter_map(..)` instead";
span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint); span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
} }
} }
@@ -2830,7 +2836,7 @@ fn lint_find_map<'a, 'tcx>(
if match_trait_method(cx, &map_args[0], &paths::ITERATOR) { if match_trait_method(cx, &map_args[0], &paths::ITERATOR) {
let msg = "called `find(p).map(q)` on an `Iterator`"; let msg = "called `find(p).map(q)` on an `Iterator`";
let hint = "this is more succinctly expressed by calling `.find_map(..)` instead"; let hint = "this is more succinctly expressed by calling `.find_map(..)` instead";
span_lint_and_help(cx, FIND_MAP, expr.span, msg, hint); span_lint_and_help(cx, FIND_MAP, expr.span, msg, None, hint);
} }
} }
@@ -2845,7 +2851,7 @@ fn lint_filter_map_map<'a, 'tcx>(
if match_trait_method(cx, expr, &paths::ITERATOR) { if match_trait_method(cx, expr, &paths::ITERATOR) {
let msg = "called `filter_map(p).map(q)` on an `Iterator`"; let msg = "called `filter_map(p).map(q)` on an `Iterator`";
let hint = "this is more succinctly expressed by only calling `.filter_map(..)` instead"; let hint = "this is more succinctly expressed by only calling `.filter_map(..)` instead";
span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint); span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
} }
} }
@@ -2861,7 +2867,7 @@ fn lint_filter_flat_map<'a, 'tcx>(
let msg = "called `filter(p).flat_map(q)` on an `Iterator`"; let msg = "called `filter(p).flat_map(q)` on an `Iterator`";
let hint = "this is more succinctly expressed by calling `.flat_map(..)` \ let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
and filtering by returning `iter::empty()`"; and filtering by returning `iter::empty()`";
span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint); span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
} }
} }
@@ -2877,7 +2883,7 @@ fn lint_filter_map_flat_map<'a, 'tcx>(
let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`"; let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`";
let hint = "this is more succinctly expressed by calling `.flat_map(..)` \ let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
and filtering by returning `iter::empty()`"; and filtering by returning `iter::empty()`";
span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint); span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
} }
} }
@@ -3260,6 +3266,7 @@ fn lint_suspicious_map(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) {
SUSPICIOUS_MAP, SUSPICIOUS_MAP,
expr.span, expr.span,
"this call to `map()` won't have an effect on the call to `count()`", "this call to `map()` won't have an effect on the call to `count()`",
None,
"make sure you did not confuse `map` with `filter` or `for_each`", "make sure you did not confuse `map` with `filter` or `for_each`",
); );
} }
@@ -3640,7 +3647,7 @@ fn lint_filetype_is_file(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &
} }
let lint_msg = format!("`{}FileType::is_file()` only {} regular files", lint_unary, verb); let lint_msg = format!("`{}FileType::is_file()` only {} regular files", lint_unary, verb);
let help_msg = format!("use `{}FileType::is_dir()` instead", help_unary); let help_msg = format!("use `{}FileType::is_dir()` instead", help_unary);
span_lint_and_help(cx, FILETYPE_IS_FILE, span, &lint_msg, &help_msg); span_lint_and_help(cx, FILETYPE_IS_FILE, span, &lint_msg, None, &help_msg);
} }
fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool { fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {

View File

@@ -313,6 +313,7 @@ impl EarlyLintPass for MiscEarlyLints {
UNNEEDED_FIELD_PATTERN, UNNEEDED_FIELD_PATTERN,
pat.span, pat.span,
"All the struct fields are matched to a wildcard pattern, consider using `..`.", "All the struct fields are matched to a wildcard pattern, consider using `..`.",
None,
&format!("Try with `{} {{ .. }}` instead", type_name), &format!("Try with `{} {{ .. }}` instead", type_name),
); );
return; return;
@@ -348,6 +349,7 @@ impl EarlyLintPass for MiscEarlyLints {
field.span, field.span,
"You matched a field with a wildcard pattern. Consider using `..` \ "You matched a field with a wildcard pattern. Consider using `..` \
instead", instead",
None,
&format!("Try with `{} {{ {}, .. }}`", type_name, normal[..].join(", ")), &format!("Try with `{} {{ {}, .. }}`", type_name, normal[..].join(", ")),
); );
} }

View File

@@ -304,6 +304,7 @@ fn emit_warning<'a>(cx: &EarlyContext<'_>, data: &'a LintData<'_>, header: &str,
NEEDLESS_CONTINUE, NEEDLESS_CONTINUE,
expr.span, expr.span,
message, message,
None,
&format!("{}\n{}", header, snip), &format!("{}\n{}", header, snip),
); );
} }

View File

@@ -46,6 +46,7 @@ impl EarlyLintPass for OptionEnvUnwrap {
OPTION_ENV_UNWRAP, OPTION_ENV_UNWRAP,
expr.span, expr.span,
"this will panic at run-time if the environment variable doesn't exist at compile-time", "this will panic at run-time if the environment variable doesn't exist at compile-time",
None,
"consider using the `env!` macro instead" "consider using the `env!` macro instead"
); );
} }

View File

@@ -208,7 +208,7 @@ fn check_regex<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>, utf8:
match parser.parse(r) { match parser.parse(r) {
Ok(r) => { Ok(r) => {
if let Some(repl) = is_trivial_regex(&r) { if let Some(repl) = is_trivial_regex(&r) {
span_lint_and_help(cx, TRIVIAL_REGEX, expr.span, "trivial regex", repl); span_lint_and_help(cx, TRIVIAL_REGEX, expr.span, "trivial regex", None, repl);
} }
}, },
Err(regex_syntax::Error::Parse(e)) => { Err(regex_syntax::Error::Parse(e)) => {
@@ -236,7 +236,7 @@ fn check_regex<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>, utf8:
match parser.parse(&r) { match parser.parse(&r) {
Ok(r) => { Ok(r) => {
if let Some(repl) = is_trivial_regex(&r) { if let Some(repl) = is_trivial_regex(&r) {
span_lint_and_help(cx, TRIVIAL_REGEX, expr.span, "trivial regex", repl); span_lint_and_help(cx, TRIVIAL_REGEX, expr.span, "trivial regex", None, repl);
} }
}, },
Err(regex_syntax::Error::Parse(e)) => { Err(regex_syntax::Error::Parse(e)) => {

View File

@@ -76,6 +76,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TraitBounds {
TYPE_REPETITION_IN_BOUNDS, TYPE_REPETITION_IN_BOUNDS,
p.span, p.span,
"this type has already been used as a bound predicate", "this type has already been used as a bound predicate",
None,
&hint_string, &hint_string,
); );
} }

View File

@@ -343,6 +343,7 @@ impl Types {
BOX_VEC, BOX_VEC,
hir_ty.span, hir_ty.span,
"you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`", "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
None,
"`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.", "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.",
); );
return; // don't recurse into the type return; // don't recurse into the type
@@ -437,6 +438,7 @@ impl Types {
LINKEDLIST, LINKEDLIST,
hir_ty.span, hir_ty.span,
"I see you're using a LinkedList! Perhaps you meant some other data structure?", "I see you're using a LinkedList! Perhaps you meant some other data structure?",
None,
"a `VecDeque` might work", "a `VecDeque` might work",
); );
return; // don't recurse into the type return; // don't recurse into the type
@@ -1900,7 +1902,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AbsurdExtremeComparisons {
conclusion conclusion
); );
span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help); span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, None, &help);
} }
} }
} }

View File

@@ -89,6 +89,7 @@ impl LateLintPass<'_, '_> for UnnamedAddress {
VTABLE_ADDRESS_COMPARISONS, VTABLE_ADDRESS_COMPARISONS,
expr.span, expr.span,
"comparing trait object pointers compares a non-unique vtable address", "comparing trait object pointers compares a non-unique vtable address",
None,
"consider extracting and comparing data pointers only", "consider extracting and comparing data pointers only",
); );
} }
@@ -109,6 +110,7 @@ impl LateLintPass<'_, '_> for UnnamedAddress {
VTABLE_ADDRESS_COMPARISONS, VTABLE_ADDRESS_COMPARISONS,
expr.span, expr.span,
"comparing trait object pointers compares a non-unique vtable address", "comparing trait object pointers compares a non-unique vtable address",
None,
"consider extracting and comparing data pointers only", "consider extracting and comparing data pointers only",
); );
} }

View File

@@ -69,6 +69,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedSelf {
UNUSED_SELF, UNUSED_SELF,
self_param.span, self_param.span,
"unused `self` argument", "unused `self` argument",
None,
"consider refactoring to a associated function", "consider refactoring to a associated function",
); );
return; return;

View File

@@ -62,12 +62,23 @@ pub fn span_lint<T: LintContext>(cx: &T, lint: &'static Lint, sp: impl Into<Mult
/// | /// |
/// = help: Consider using `f64::NAN` if you would like a constant representing NaN /// = help: Consider using `f64::NAN` if you would like a constant representing NaN
/// ``` /// ```
pub fn span_lint_and_help<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, span: Span, msg: &str, help: &str) { pub fn span_lint_and_help<'a, T: LintContext>(
cx.struct_span_lint(lint, span, |diag| { cx: &'a T,
let mut diag = diag.build(msg); lint: &'static Lint,
diag.help(help); span: Span,
docs_link(&mut diag, lint); msg: &str,
diag.emit(); help_span: Option<Span>,
help: &str,
) {
cx.struct_span_lint(lint, span, |ldb| {
let mut db = ldb.build(msg);
if let Some(help_span) = help_span {
db.span_help(help_span, help);
} else {
db.help(help);
}
docs_link(&mut db, lint);
db.emit();
}); });
} }

View File

@@ -196,8 +196,8 @@ declare_clippy_lint! {
/// sugg.to_string(), /// sugg.to_string(),
/// Applicability::MachineApplicable, /// Applicability::MachineApplicable,
/// ); /// );
/// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, help_msg); /// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, Some(expr.span), help_msg);
/// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, help_msg); /// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, None, help_msg);
/// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, expr.span, note_msg); /// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, expr.span, note_msg);
/// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, expr.span, note_msg); /// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, expr.span, note_msg);
/// ``` /// ```
@@ -403,6 +403,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CompilerLintFunctions {
COMPILER_LINT_FUNCTIONS, COMPILER_LINT_FUNCTIONS,
path.ident.span, path.ident.span,
"usage of a compiler lint function", "usage of a compiler lint function",
None,
&format!("please use the Clippy variant of this function: `{}`", sugg), &format!("please use the Clippy variant of this function: `{}`", sugg),
); );
} }
@@ -481,7 +482,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CollapsibleCalls {
}, },
"span_help" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => { "span_help" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#); let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow()); suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), true);
}, },
"span_note" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => { "span_note" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
let note_snippet = snippet(cx, span_call_args[2].span, r#""...""#); let note_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
@@ -489,7 +490,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CollapsibleCalls {
}, },
"help" => { "help" => {
let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#); let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow()); suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), false);
} }
"note" => { "note" => {
let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#); let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
@@ -573,7 +574,19 @@ fn suggest_suggestion(
); );
} }
fn suggest_help(cx: &LateContext<'_, '_>, expr: &Expr<'_>, and_then_snippets: &AndThenSnippets<'_>, help: &str) { fn suggest_help(
cx: &LateContext<'_, '_>,
expr: &Expr<'_>,
and_then_snippets: &AndThenSnippets<'_>,
help: &str,
with_span: bool,
) {
let option_span = if with_span {
format!("Some({})", and_then_snippets.span)
} else {
"None".to_string()
};
span_lint_and_sugg( span_lint_and_sugg(
cx, cx,
COLLAPSIBLE_SPAN_LINT_CALLS, COLLAPSIBLE_SPAN_LINT_CALLS,
@@ -581,8 +594,13 @@ fn suggest_help(cx: &LateContext<'_, '_>, expr: &Expr<'_>, and_then_snippets: &A
"this call is collapsible", "this call is collapsible",
"collapse into", "collapse into",
format!( format!(
"span_lint_and_help({}, {}, {}, {}, {})", "span_lint_and_help({}, {}, {}, {}, {}, {})",
and_then_snippets.cx, and_then_snippets.lint, and_then_snippets.span, and_then_snippets.msg, help and_then_snippets.cx,
and_then_snippets.lint,
and_then_snippets.span,
and_then_snippets.msg,
&option_span,
help
), ),
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );

View File

@@ -40,6 +40,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VerboseFileReads {
VERBOSE_FILE_READS, VERBOSE_FILE_READS,
expr.span, expr.span,
"use of `File::read_to_end`", "use of `File::read_to_end`",
None,
"consider using `fs::read` instead", "consider using `fs::read` instead",
); );
} else if is_file_read_to_string(cx, expr) { } else if is_file_read_to_string(cx, expr) {
@@ -48,6 +49,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VerboseFileReads {
VERBOSE_FILE_READS, VERBOSE_FILE_READS,
expr.span, expr.span,
"use of `File::read_to_string`", "use of `File::read_to_string`",
None,
"consider using `fs::read_to_string` instead", "consider using `fs::read_to_string` instead",
) )
} }

View File

@@ -49,6 +49,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ZeroDiv {
ZERO_DIVIDED_BY_ZERO, ZERO_DIVIDED_BY_ZERO,
expr.span, expr.span,
"constant division of `0.0` with `0.0` will always result in NaN", "constant division of `0.0` with `0.0` will always result in NaN",
None,
&format!( &format!(
"Consider using `{}::NAN` if you would like a constant representing NaN", "Consider using `{}::NAN` if you would like a constant representing NaN",
float_type, float_type,

View File

@@ -265,6 +265,7 @@ impl EarlyLintPass for FooFunctions {
FOO_FUNCTIONS, FOO_FUNCTIONS,
span, span,
"function named `foo`", "function named `foo`",
None,
"consider using a more meaningful name" "consider using a more meaningful name"
); );
} }
@@ -296,6 +297,7 @@ impl EarlyLintPass for FooFunctions {
FOO_FUNCTIONS, FOO_FUNCTIONS,
span, span,
"function named `foo`", "function named `foo`",
None,
"consider using a more meaningful name" "consider using a more meaningful name"
); );
} }

View File

@@ -22,7 +22,15 @@ where
} }
#[allow(unused_variables)] #[allow(unused_variables)]
fn span_lint_and_help<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, span: Span, msg: &str, help: &str) {} fn span_lint_and_help<'a, T: LintContext>(
cx: &'a T,
lint: &'static Lint,
span: Span,
msg: &str,
option_span: Option<Span>,
help: &str,
) {
}
#[allow(unused_variables)] #[allow(unused_variables)]
fn span_lint_and_note<'a, T: LintContext>( fn span_lint_and_note<'a, T: LintContext>(
@@ -65,8 +73,8 @@ impl EarlyLintPass for Pass {
let predicate = true; let predicate = true;
span_lint_and_sugg(cx, TEST_LINT, expr.span, lint_msg, help_msg, sugg.to_string(), Applicability::MachineApplicable); span_lint_and_sugg(cx, TEST_LINT, expr.span, lint_msg, help_msg, sugg.to_string(), Applicability::MachineApplicable);
span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, help_msg); span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, Some(expr.span), help_msg);
span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, help_msg); span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, None, help_msg);
span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, expr.span, note_msg); span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, expr.span, note_msg);
span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, expr.span, note_msg); span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, expr.span, note_msg);

View File

@@ -22,7 +22,15 @@ where
} }
#[allow(unused_variables)] #[allow(unused_variables)]
fn span_lint_and_help<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, span: Span, msg: &str, help: &str) {} fn span_lint_and_help<'a, T: LintContext>(
cx: &'a T,
lint: &'static Lint,
span: Span,
msg: &str,
option_span: Option<Span>,
help: &str,
) {
}
#[allow(unused_variables)] #[allow(unused_variables)]
fn span_lint_and_note<'a, T: LintContext>( fn span_lint_and_note<'a, T: LintContext>(

View File

@@ -1,5 +1,5 @@
error: this call is collapsible error: this call is collapsible
--> $DIR/collapsible_span_lint_calls.rs:67:9 --> $DIR/collapsible_span_lint_calls.rs:75:9
| |
LL | / span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |db| { LL | / span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |db| {
LL | | db.span_suggestion(expr.span, help_msg, sugg.to_string(), Applicability::MachineApplicable); LL | | db.span_suggestion(expr.span, help_msg, sugg.to_string(), Applicability::MachineApplicable);
@@ -14,23 +14,23 @@ LL | #![deny(clippy::internal)]
= note: `#[deny(clippy::collapsible_span_lint_calls)]` implied by `#[deny(clippy::internal)]` = note: `#[deny(clippy::collapsible_span_lint_calls)]` implied by `#[deny(clippy::internal)]`
error: this call is collapsible error: this call is collapsible
--> $DIR/collapsible_span_lint_calls.rs:70:9 --> $DIR/collapsible_span_lint_calls.rs:78:9
| |
LL | / span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |db| { LL | / span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |db| {
LL | | db.span_help(expr.span, help_msg); LL | | db.span_help(expr.span, help_msg);
LL | | }); LL | | });
| |__________^ help: collapse into: `span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, help_msg)` | |__________^ help: collapse into: `span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, Some(expr.span), help_msg)`
error: this call is collapsible error: this call is collapsible
--> $DIR/collapsible_span_lint_calls.rs:73:9 --> $DIR/collapsible_span_lint_calls.rs:81:9
| |
LL | / span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |db| { LL | / span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |db| {
LL | | db.help(help_msg); LL | | db.help(help_msg);
LL | | }); LL | | });
| |__________^ help: collapse into: `span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, help_msg)` | |__________^ help: collapse into: `span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, None, help_msg)`
error: this call is collspible error: this call is collspible
--> $DIR/collapsible_span_lint_calls.rs:76:9 --> $DIR/collapsible_span_lint_calls.rs:84:9
| |
LL | / span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |db| { LL | / span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |db| {
LL | | db.span_note(expr.span, note_msg); LL | | db.span_note(expr.span, note_msg);
@@ -38,7 +38,7 @@ LL | | });
| |__________^ help: collapse into: `span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, expr.span, note_msg)` | |__________^ help: collapse into: `span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, expr.span, note_msg)`
error: this call is collspible error: this call is collspible
--> $DIR/collapsible_span_lint_calls.rs:79:9 --> $DIR/collapsible_span_lint_calls.rs:87:9
| |
LL | / span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |db| { LL | / span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |db| {
LL | | db.note(note_msg); LL | | db.note(note_msg);