Merge remote-tracking branch 'upstream/master' into rustup
This commit is contained in:
commit
731dfde267
12
.github/workflows/clippy_dev.yml
vendored
12
.github/workflows/clippy_dev.yml
vendored
@ -25,18 +25,6 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2.3.3
|
||||
|
||||
- name: remove toolchain file
|
||||
run: rm rust-toolchain
|
||||
|
||||
- name: rust-toolchain
|
||||
uses: actions-rs/toolchain@v1.0.6
|
||||
with:
|
||||
toolchain: nightly
|
||||
target: x86_64-unknown-linux-gnu
|
||||
profile: minimal
|
||||
components: rustfmt
|
||||
default: true
|
||||
|
||||
# Run
|
||||
- name: Build
|
||||
run: cargo build --features deny-warnings
|
||||
|
@ -2904,6 +2904,7 @@ Released 2018-09-13
|
||||
[`imprecise_flops`]: https://rust-lang.github.io/rust-clippy/master/index.html#imprecise_flops
|
||||
[`inconsistent_digit_grouping`]: https://rust-lang.github.io/rust-clippy/master/index.html#inconsistent_digit_grouping
|
||||
[`inconsistent_struct_constructor`]: https://rust-lang.github.io/rust-clippy/master/index.html#inconsistent_struct_constructor
|
||||
[`index_refutable_slice`]: https://rust-lang.github.io/rust-clippy/master/index.html#index_refutable_slice
|
||||
[`indexing_slicing`]: https://rust-lang.github.io/rust-clippy/master/index.html#indexing_slicing
|
||||
[`ineffective_bit_mask`]: https://rust-lang.github.io/rust-clippy/master/index.html#ineffective_bit_mask
|
||||
[`inefficient_to_string`]: https://rust-lang.github.io/rust-clippy/master/index.html#inefficient_to_string
|
||||
@ -3038,6 +3039,7 @@ Released 2018-09-13
|
||||
[`needless_question_mark`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_question_mark
|
||||
[`needless_range_loop`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_range_loop
|
||||
[`needless_return`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_return
|
||||
[`needless_splitn`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_splitn
|
||||
[`needless_update`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_update
|
||||
[`neg_cmp_op_on_partial_ord`]: https://rust-lang.github.io/rust-clippy/master/index.html#neg_cmp_op_on_partial_ord
|
||||
[`neg_multiply`]: https://rust-lang.github.io/rust-clippy/master/index.html#neg_multiply
|
||||
|
@ -47,6 +47,7 @@ itertools = "0.10"
|
||||
quote = "1.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
syn = { version = "1.0", features = ["full"] }
|
||||
parking_lot = "0.11.2"
|
||||
|
||||
[build-dependencies]
|
||||
rustc_tools_util = { version = "0.2", path = "rustc_tools_util" }
|
||||
|
@ -12,6 +12,7 @@ opener = "0.5"
|
||||
regex = "1.5"
|
||||
shell-escape = "0.1"
|
||||
walkdir = "2.3"
|
||||
cargo_metadata = "0.14"
|
||||
|
||||
[features]
|
||||
deny-warnings = []
|
||||
|
@ -1,6 +1,7 @@
|
||||
use crate::clippy_project_root;
|
||||
use itertools::Itertools;
|
||||
use shell_escape::escape;
|
||||
use std::ffi::OsStr;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::Path;
|
||||
use std::process::{self, Command};
|
||||
use std::{fs, io};
|
||||
@ -56,15 +57,22 @@ pub fn run(check: bool, verbose: bool) {
|
||||
success &= cargo_fmt(context, &project_root.join("rustc_tools_util"))?;
|
||||
success &= cargo_fmt(context, &project_root.join("lintcheck"))?;
|
||||
|
||||
for entry in WalkDir::new(project_root.join("tests")) {
|
||||
let entry = entry?;
|
||||
let chunks = WalkDir::new(project_root.join("tests"))
|
||||
.into_iter()
|
||||
.filter_map(|entry| {
|
||||
let entry = entry.expect("failed to find tests");
|
||||
let path = entry.path();
|
||||
|
||||
if path.extension() != Some("rs".as_ref()) || entry.file_name() == "ice-3891.rs" {
|
||||
continue;
|
||||
None
|
||||
} else {
|
||||
Some(entry.into_path().into_os_string())
|
||||
}
|
||||
})
|
||||
.chunks(250);
|
||||
|
||||
success &= rustfmt(context, path)?;
|
||||
for chunk in &chunks {
|
||||
success &= rustfmt(context, chunk)?;
|
||||
}
|
||||
|
||||
Ok(success)
|
||||
@ -149,7 +157,7 @@ fn exec(
|
||||
}
|
||||
|
||||
fn cargo_fmt(context: &FmtContext, path: &Path) -> Result<bool, CliError> {
|
||||
let mut args = vec!["+nightly", "fmt", "--all"];
|
||||
let mut args = vec!["fmt", "--all"];
|
||||
if context.check {
|
||||
args.push("--");
|
||||
args.push("--check");
|
||||
@ -162,7 +170,7 @@ fn cargo_fmt(context: &FmtContext, path: &Path) -> Result<bool, CliError> {
|
||||
fn rustfmt_test(context: &FmtContext) -> Result<(), CliError> {
|
||||
let program = "rustfmt";
|
||||
let dir = std::env::current_dir()?;
|
||||
let args = &["+nightly", "--version"];
|
||||
let args = &["--version"];
|
||||
|
||||
if context.verbose {
|
||||
println!("{}", format_command(&program, &dir, args));
|
||||
@ -185,14 +193,14 @@ fn rustfmt_test(context: &FmtContext) -> Result<(), CliError> {
|
||||
}
|
||||
}
|
||||
|
||||
fn rustfmt(context: &FmtContext, path: &Path) -> Result<bool, CliError> {
|
||||
let mut args = vec!["+nightly".as_ref(), path.as_os_str()];
|
||||
fn rustfmt(context: &FmtContext, paths: impl Iterator<Item = OsString>) -> Result<bool, CliError> {
|
||||
let mut args = Vec::new();
|
||||
if context.check {
|
||||
args.push("--check".as_ref());
|
||||
args.push(OsString::from("--check"));
|
||||
}
|
||||
args.extend(paths);
|
||||
|
||||
let success = exec(context, "rustfmt", std::env::current_dir()?, &args)?;
|
||||
if !success {
|
||||
eprintln!("rustfmt failed on {}", path.display());
|
||||
}
|
||||
|
||||
Ok(success)
|
||||
}
|
||||
|
@ -7,6 +7,7 @@ use std::path::PathBuf;
|
||||
|
||||
pub mod bless;
|
||||
pub mod fmt;
|
||||
pub mod lint;
|
||||
pub mod new_lint;
|
||||
pub mod serve;
|
||||
pub mod setup;
|
||||
|
20
clippy_dev/src/lint.rs
Normal file
20
clippy_dev/src/lint.rs
Normal file
@ -0,0 +1,20 @@
|
||||
use std::process::{self, Command};
|
||||
|
||||
pub fn run(filename: &str) {
|
||||
let code = Command::new("cargo")
|
||||
.args(["run", "--bin", "clippy-driver", "--"])
|
||||
.args(["-L", "./target/debug"])
|
||||
.args(["-Z", "no-codegen"])
|
||||
.args(["--edition", "2021"])
|
||||
.arg(filename)
|
||||
.env("__CLIPPY_INTERNAL_TESTS", "true")
|
||||
.status()
|
||||
.expect("failed to run cargo")
|
||||
.code();
|
||||
|
||||
if code.is_none() {
|
||||
eprintln!("Killed by signal");
|
||||
}
|
||||
|
||||
process::exit(code.unwrap_or(1));
|
||||
}
|
@ -3,7 +3,7 @@
|
||||
#![warn(rust_2018_idioms, unused_lifetimes)]
|
||||
|
||||
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
|
||||
use clippy_dev::{bless, fmt, new_lint, serve, setup, update_lints};
|
||||
use clippy_dev::{bless, fmt, lint, new_lint, serve, setup, update_lints};
|
||||
fn main() {
|
||||
let matches = get_clap_config();
|
||||
|
||||
@ -55,6 +55,10 @@ fn main() {
|
||||
let lint = matches.value_of("lint");
|
||||
serve::run(port, lint);
|
||||
},
|
||||
("lint", Some(matches)) => {
|
||||
let filename = matches.value_of("filename").unwrap();
|
||||
lint::run(filename);
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
@ -219,5 +223,14 @@ fn get_clap_config<'a>() -> ArgMatches<'a> {
|
||||
)
|
||||
.arg(Arg::with_name("lint").help("Which lint's page to load initially (optional)")),
|
||||
)
|
||||
.subcommand(
|
||||
SubCommand::with_name("lint")
|
||||
.about("Manually run clippy on a file")
|
||||
.arg(
|
||||
Arg::with_name("filename")
|
||||
.required(true)
|
||||
.help("The path to a file to lint"),
|
||||
),
|
||||
)
|
||||
.get_matches()
|
||||
}
|
||||
|
@ -132,6 +132,18 @@ fn to_camel_case(name: &str) -> String {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn get_stabilisation_version() -> String {
|
||||
let mut command = cargo_metadata::MetadataCommand::new();
|
||||
command.no_deps();
|
||||
if let Ok(metadata) = command.exec() {
|
||||
if let Some(pkg) = metadata.packages.iter().find(|pkg| pkg.name == "clippy") {
|
||||
return format!("{}.{}.0", pkg.version.minor, pkg.version.patch);
|
||||
}
|
||||
}
|
||||
|
||||
String::from("<TODO set version(see doc/adding_lints.md)>")
|
||||
}
|
||||
|
||||
fn get_test_file_contents(lint_name: &str, header_commands: Option<&str>) -> String {
|
||||
let mut contents = format!(
|
||||
indoc! {"
|
||||
@ -178,6 +190,7 @@ fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String {
|
||||
},
|
||||
};
|
||||
|
||||
let version = get_stabilisation_version();
|
||||
let lint_name = lint.name;
|
||||
let category = lint.category;
|
||||
let name_camel = to_camel_case(lint.name);
|
||||
@ -212,7 +225,7 @@ fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String {
|
||||
});
|
||||
|
||||
result.push_str(&format!(
|
||||
indoc! {"
|
||||
indoc! {r#"
|
||||
declare_clippy_lint! {{
|
||||
/// ### What it does
|
||||
///
|
||||
@ -226,11 +239,13 @@ fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String {
|
||||
/// ```rust
|
||||
/// // example code which does not raise clippy warning
|
||||
/// ```
|
||||
#[clippy::version = "{version}"]
|
||||
pub {name_upper},
|
||||
{category},
|
||||
\"default lint description\"
|
||||
"default lint description"
|
||||
}}
|
||||
"},
|
||||
"#},
|
||||
version = version,
|
||||
name_upper = name_upper,
|
||||
category = category,
|
||||
));
|
||||
|
@ -18,6 +18,7 @@ static DEC_CLIPPY_LINT_RE: SyncLazy<Regex> = SyncLazy::new(|| {
|
||||
r#"(?x)
|
||||
declare_clippy_lint!\s*[\{(]
|
||||
(?:\s+///.*)*
|
||||
(?:\s*\#\[clippy::version\s*=\s*"[^"]*"\])?
|
||||
\s+pub\s+(?P<name>[A-Z_][A-Z_0-9]*)\s*,\s*
|
||||
(?P<cat>[a-z_]+)\s*,\s*
|
||||
"(?P<desc>(?:[^"\\]+|\\(?s).(?-s))*)"\s*[})]
|
||||
@ -31,6 +32,7 @@ static DEC_DEPRECATED_LINT_RE: SyncLazy<Regex> = SyncLazy::new(|| {
|
||||
r#"(?x)
|
||||
declare_deprecated_lint!\s*[{(]\s*
|
||||
(?:\s+///.*)*
|
||||
(?:\s*\#\[clippy::version\s*=\s*"[^"]*"\])?
|
||||
\s+pub\s+(?P<name>[A-Z_][A-Z_0-9]*)\s*,\s*
|
||||
"(?P<desc>(?:[^"\\]+|\\(?s).(?-s))*)"\s*[})]
|
||||
"#,
|
||||
@ -495,6 +497,7 @@ fn test_parse_contents() {
|
||||
let result: Vec<Lint> = parse_contents(
|
||||
r#"
|
||||
declare_clippy_lint! {
|
||||
#[clippy::version = "Hello Clippy!"]
|
||||
pub PTR_ARG,
|
||||
style,
|
||||
"really long \
|
||||
@ -502,6 +505,7 @@ declare_clippy_lint! {
|
||||
}
|
||||
|
||||
declare_clippy_lint!{
|
||||
#[clippy::version = "Test version"]
|
||||
pub DOC_MARKDOWN,
|
||||
pedantic,
|
||||
"single line"
|
||||
@ -509,6 +513,7 @@ declare_clippy_lint!{
|
||||
|
||||
/// some doc comment
|
||||
declare_deprecated_lint! {
|
||||
#[clippy::version = "I'm a version"]
|
||||
pub SHOULD_ASSERT_EQ,
|
||||
"`assert!()` will be more flexible with RFC 2011"
|
||||
}
|
||||
|
@ -36,6 +36,7 @@ declare_clippy_lint! {
|
||||
/// if vec.len() <= 0 {}
|
||||
/// if 100 > i32::MAX {}
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub ABSURD_EXTREME_COMPARISONS,
|
||||
correctness,
|
||||
"a comparison with a maximum or minimum value that is always true or false"
|
||||
|
@ -33,6 +33,7 @@ declare_clippy_lint! {
|
||||
/// let x = std::f32::consts::PI;
|
||||
/// let y = std::f64::consts::FRAC_1_PI;
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub APPROX_CONSTANT,
|
||||
correctness,
|
||||
"the approximate of a known float constant (in `std::fXX::consts`)"
|
||||
|
@ -25,6 +25,7 @@ declare_clippy_lint! {
|
||||
/// # let a = 0;
|
||||
/// a + 1;
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub INTEGER_ARITHMETIC,
|
||||
restriction,
|
||||
"any integer arithmetic expression which could overflow or panic"
|
||||
@ -43,6 +44,7 @@ declare_clippy_lint! {
|
||||
/// # let a = 0.0;
|
||||
/// a + 1.0;
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub FLOAT_ARITHMETIC,
|
||||
restriction,
|
||||
"any floating-point arithmetic statement"
|
||||
|
@ -38,6 +38,7 @@ declare_clippy_lint! {
|
||||
/// f(a.try_into().expect("Unexpected u16 overflow in f"));
|
||||
/// ```
|
||||
///
|
||||
#[clippy::version = "1.41.0"]
|
||||
pub AS_CONVERSIONS,
|
||||
restriction,
|
||||
"using a potentially dangerous silent `as` conversion"
|
||||
|
@ -75,6 +75,7 @@ declare_clippy_lint! {
|
||||
/// asm!("lea ({}), {}", in(reg) ptr, lateout(reg) _, options(att_syntax));
|
||||
/// # }
|
||||
/// ```
|
||||
#[clippy::version = "1.49.0"]
|
||||
pub INLINE_ASM_X86_INTEL_SYNTAX,
|
||||
restriction,
|
||||
"prefer AT&T x86 assembly syntax"
|
||||
@ -111,6 +112,7 @@ declare_clippy_lint! {
|
||||
/// asm!("lea {}, [{}]", lateout(reg) _, in(reg) ptr);
|
||||
/// # }
|
||||
/// ```
|
||||
#[clippy::version = "1.49.0"]
|
||||
pub INLINE_ASM_X86_ATT_SYNTAX,
|
||||
restriction,
|
||||
"prefer Intel x86 assembly syntax"
|
||||
|
@ -26,6 +26,7 @@ declare_clippy_lint! {
|
||||
/// const B: bool = false;
|
||||
/// assert!(B)
|
||||
/// ```
|
||||
#[clippy::version = "1.34.0"]
|
||||
pub ASSERTIONS_ON_CONSTANTS,
|
||||
style,
|
||||
"`assert!(true)` / `assert!(false)` will be optimized out by the compiler, and should probably be replaced by a `panic!()` or `unreachable!()`"
|
||||
|
@ -34,6 +34,7 @@ declare_clippy_lint! {
|
||||
/// // Good
|
||||
/// a += b;
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub ASSIGN_OP_PATTERN,
|
||||
style,
|
||||
"assigning the result of an operation on a variable to that same variable"
|
||||
@ -60,6 +61,7 @@ declare_clippy_lint! {
|
||||
/// // ...
|
||||
/// a += a + b;
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub MISREFACTORED_ASSIGN_OP,
|
||||
suspicious,
|
||||
"having a variable on both sides of an assign op"
|
||||
|
@ -34,6 +34,7 @@ declare_clippy_lint! {
|
||||
/// };
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.48.0"]
|
||||
pub ASYNC_YIELDS_ASYNC,
|
||||
correctness,
|
||||
"async blocks that return a type that can be awaited"
|
||||
|
@ -1,8 +1,9 @@
|
||||
//! checks for attributes
|
||||
|
||||
use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then};
|
||||
use clippy_utils::match_panic_def_id;
|
||||
use clippy_utils::msrvs;
|
||||
use clippy_utils::source::{first_line_of_span, is_present_in_source, snippet_opt, without_block_comments};
|
||||
use clippy_utils::{extract_msrv_attr, match_panic_def_id, meets_msrv};
|
||||
use if_chain::if_chain;
|
||||
use rustc_ast::{AttrKind, AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem};
|
||||
use rustc_errors::Applicability;
|
||||
@ -12,7 +13,8 @@ use rustc_hir::{
|
||||
use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
|
||||
use rustc_middle::lint::in_external_macro;
|
||||
use rustc_middle::ty;
|
||||
use rustc_session::{declare_lint_pass, declare_tool_lint};
|
||||
use rustc_semver::RustcVersion;
|
||||
use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
|
||||
use rustc_span::source_map::Span;
|
||||
use rustc_span::sym;
|
||||
use rustc_span::symbol::{Symbol, SymbolStr};
|
||||
@ -64,6 +66,7 @@ declare_clippy_lint! {
|
||||
/// #[inline(always)]
|
||||
/// fn not_quite_hot_code(..) { ... }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub INLINE_ALWAYS,
|
||||
pedantic,
|
||||
"use of `#[inline(always)]`"
|
||||
@ -98,6 +101,7 @@ declare_clippy_lint! {
|
||||
/// #[macro_use]
|
||||
/// extern crate baz;
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub USELESS_ATTRIBUTE,
|
||||
correctness,
|
||||
"use of lint attributes on `extern crate` items"
|
||||
@ -117,6 +121,7 @@ declare_clippy_lint! {
|
||||
/// #[deprecated(since = "forever")]
|
||||
/// fn something_else() { /* ... */ }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub DEPRECATED_SEMVER,
|
||||
correctness,
|
||||
"use of `#[deprecated(since = \"x\")]` where x is not semver"
|
||||
@ -154,6 +159,7 @@ declare_clippy_lint! {
|
||||
/// #[allow(dead_code)]
|
||||
/// fn this_is_fine_too() { }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub EMPTY_LINE_AFTER_OUTER_ATTR,
|
||||
nursery,
|
||||
"empty line after outer attribute"
|
||||
@ -177,6 +183,7 @@ declare_clippy_lint! {
|
||||
/// ```rust
|
||||
/// #![deny(clippy::as_conversions)]
|
||||
/// ```
|
||||
#[clippy::version = "1.47.0"]
|
||||
pub BLANKET_CLIPPY_RESTRICTION_LINTS,
|
||||
suspicious,
|
||||
"enabling the complete restriction group"
|
||||
@ -208,6 +215,7 @@ declare_clippy_lint! {
|
||||
/// #[rustfmt::skip]
|
||||
/// fn main() { }
|
||||
/// ```
|
||||
#[clippy::version = "1.32.0"]
|
||||
pub DEPRECATED_CFG_ATTR,
|
||||
complexity,
|
||||
"usage of `cfg_attr(rustfmt)` instead of tool attributes"
|
||||
@ -240,6 +248,7 @@ declare_clippy_lint! {
|
||||
/// fn conditional() { }
|
||||
/// ```
|
||||
/// Check the [Rust Reference](https://doc.rust-lang.org/reference/conditional-compilation.html#target_os) for more details.
|
||||
#[clippy::version = "1.45.0"]
|
||||
pub MISMATCHED_TARGET_OS,
|
||||
correctness,
|
||||
"usage of `cfg(operating_system)` instead of `cfg(target_os = \"operating_system\")`"
|
||||
@ -497,7 +506,11 @@ fn is_word(nmi: &NestedMetaItem, expected: Symbol) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
declare_lint_pass!(EarlyAttributes => [
|
||||
pub struct EarlyAttributes {
|
||||
pub msrv: Option<RustcVersion>,
|
||||
}
|
||||
|
||||
impl_lint_pass!(EarlyAttributes => [
|
||||
DEPRECATED_CFG_ATTR,
|
||||
MISMATCHED_TARGET_OS,
|
||||
EMPTY_LINE_AFTER_OUTER_ATTR,
|
||||
@ -509,9 +522,11 @@ impl EarlyLintPass for EarlyAttributes {
|
||||
}
|
||||
|
||||
fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) {
|
||||
check_deprecated_cfg_attr(cx, attr);
|
||||
check_deprecated_cfg_attr(cx, attr, self.msrv);
|
||||
check_mismatched_target_os(cx, attr);
|
||||
}
|
||||
|
||||
extract_msrv_attr!(EarlyContext);
|
||||
}
|
||||
|
||||
fn check_empty_line_after_outer_attr(cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
|
||||
@ -548,8 +563,9 @@ fn check_empty_line_after_outer_attr(cx: &EarlyContext<'_>, item: &rustc_ast::It
|
||||
}
|
||||
}
|
||||
|
||||
fn check_deprecated_cfg_attr(cx: &EarlyContext<'_>, attr: &Attribute) {
|
||||
fn check_deprecated_cfg_attr(cx: &EarlyContext<'_>, attr: &Attribute, msrv: Option<RustcVersion>) {
|
||||
if_chain! {
|
||||
if meets_msrv(msrv.as_ref(), &msrvs::TOOL_ATTRIBUTES);
|
||||
// check cfg_attr
|
||||
if attr.has_name(sym::cfg_attr);
|
||||
if let Some(items) = attr.meta_item_list();
|
||||
|
@ -47,6 +47,7 @@ declare_clippy_lint! {
|
||||
/// bar.await;
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.45.0"]
|
||||
pub AWAIT_HOLDING_LOCK,
|
||||
pedantic,
|
||||
"Inside an async function, holding a MutexGuard while calling await"
|
||||
@ -88,6 +89,7 @@ declare_clippy_lint! {
|
||||
/// bar.await;
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.49.0"]
|
||||
pub AWAIT_HOLDING_REFCELL_REF,
|
||||
pedantic,
|
||||
"Inside an async function, holding a RefCell ref while calling await"
|
||||
|
@ -41,6 +41,7 @@ declare_clippy_lint! {
|
||||
/// # let x = 1;
|
||||
/// if (x & 1 == 2) { }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub BAD_BIT_MASK,
|
||||
correctness,
|
||||
"expressions of the form `_ & mask == select` that will only ever return `true` or `false`"
|
||||
@ -73,6 +74,7 @@ declare_clippy_lint! {
|
||||
/// # let x = 1;
|
||||
/// if (x | 1 > 3) { }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub INEFFECTIVE_BIT_MASK,
|
||||
correctness,
|
||||
"expressions where a bit mask will be rendered useless by a comparison, e.g., `(x | 1) > 2`"
|
||||
@ -95,6 +97,7 @@ declare_clippy_lint! {
|
||||
/// # let x = 1;
|
||||
/// if x & 0b1111 == 0 { }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub VERBOSE_BIT_MASK,
|
||||
pedantic,
|
||||
"expressions where a bit mask is less readable than the corresponding method call"
|
||||
|
@ -17,6 +17,7 @@ declare_clippy_lint! {
|
||||
/// ```rust
|
||||
/// let foo = 3.14;
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub BLACKLISTED_NAME,
|
||||
style,
|
||||
"usage of a blacklisted/placeholder name"
|
||||
|
@ -41,6 +41,7 @@ declare_clippy_lint! {
|
||||
/// let res = { let x = somefunc(); x };
|
||||
/// if res { /* ... */ }
|
||||
/// ```
|
||||
#[clippy::version = "1.45.0"]
|
||||
pub BLOCKS_IN_IF_CONDITIONS,
|
||||
style,
|
||||
"useless or complex blocks that can be eliminated in conditions"
|
||||
|
@ -23,6 +23,7 @@ declare_clippy_lint! {
|
||||
/// // Good
|
||||
/// assert!(!"a".is_empty());
|
||||
/// ```
|
||||
#[clippy::version = "1.53.0"]
|
||||
pub BOOL_ASSERT_COMPARISON,
|
||||
style,
|
||||
"Using a boolean as comparison value in an assert_* macro when there is no need"
|
||||
@ -72,7 +73,7 @@ impl<'tcx> LateLintPass<'tcx> for BoolAssertComparison {
|
||||
if let Some(span) = is_direct_expn_of(expr.span, mac) {
|
||||
if let Some(args) = higher::extract_assert_macro_args(expr) {
|
||||
if let [a, b, ..] = args[..] {
|
||||
let nb_bool_args = is_bool_lit(a) as usize + is_bool_lit(b) as usize;
|
||||
let nb_bool_args = usize::from(is_bool_lit(a)) + usize::from(is_bool_lit(b));
|
||||
|
||||
if nb_bool_args != 1 {
|
||||
// If there are two boolean arguments, we definitely don't understand
|
||||
|
@ -1,7 +1,7 @@
|
||||
use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
|
||||
use clippy_utils::source::snippet_opt;
|
||||
use clippy_utils::ty::{implements_trait, is_type_diagnostic_item};
|
||||
use clippy_utils::{eq_expr_value, get_trait_def_id, in_macro, paths};
|
||||
use clippy_utils::{eq_expr_value, get_trait_def_id, paths};
|
||||
use if_chain::if_chain;
|
||||
use rustc_ast::ast::LitKind;
|
||||
use rustc_errors::Applicability;
|
||||
@ -31,6 +31,7 @@ declare_clippy_lint! {
|
||||
/// if a && true // should be: if a
|
||||
/// if !(a == b) // should be: if a != b
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub NONMINIMAL_BOOL,
|
||||
complexity,
|
||||
"boolean expressions that can be written more concisely"
|
||||
@ -52,6 +53,7 @@ declare_clippy_lint! {
|
||||
/// if a && b || a { ... }
|
||||
/// ```
|
||||
/// The `b` is unnecessary, the expression is equivalent to `if a`.
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub LOGIC_BUG,
|
||||
correctness,
|
||||
"boolean expressions that contain terminals which can be eliminated"
|
||||
@ -453,9 +455,7 @@ impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
|
||||
type Map = Map<'tcx>;
|
||||
|
||||
fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
|
||||
if in_macro(e.span) {
|
||||
return;
|
||||
}
|
||||
if !e.span.from_expansion() {
|
||||
match &e.kind {
|
||||
ExprKind::Binary(binop, _, _) if binop.node == BinOpKind::Or || binop.node == BinOpKind::And => {
|
||||
self.bool_expr(e);
|
||||
@ -463,13 +463,13 @@ impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
|
||||
ExprKind::Unary(UnOp::Not, inner) => {
|
||||
if self.cx.typeck_results().node_types()[inner.hir_id].is_bool() {
|
||||
self.bool_expr(e);
|
||||
} else {
|
||||
walk_expr(self, e);
|
||||
}
|
||||
},
|
||||
_ => walk_expr(self, e),
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
walk_expr(self, e);
|
||||
}
|
||||
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
|
||||
NestedVisitorMap::None
|
||||
}
|
||||
|
@ -30,6 +30,7 @@ declare_clippy_lint! {
|
||||
/// # let vec = vec![1_u8];
|
||||
/// &vec.iter().filter(|x| **x == 0u8).count(); // use bytecount::count instead
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub NAIVE_BYTECOUNT,
|
||||
pedantic,
|
||||
"use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
|
||||
|
@ -42,6 +42,7 @@ declare_clippy_lint! {
|
||||
/// keywords = ["clippy", "lint", "plugin"]
|
||||
/// categories = ["development-tools", "development-tools::cargo-plugins"]
|
||||
/// ```
|
||||
#[clippy::version = "1.32.0"]
|
||||
pub CARGO_COMMON_METADATA,
|
||||
cargo,
|
||||
"common metadata is defined in `Cargo.toml`"
|
||||
|
@ -27,6 +27,7 @@ declare_clippy_lint! {
|
||||
/// filename.rsplit('.').next().map(|ext| ext.eq_ignore_ascii_case("rs")) == Some(true)
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.51.0"]
|
||||
pub CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
|
||||
pedantic,
|
||||
"Checks for calls to ends_with with case-sensitive file extensions"
|
||||
|
@ -1,16 +1,24 @@
|
||||
use clippy_utils::diagnostics::span_lint_and_sugg;
|
||||
use clippy_utils::in_constant;
|
||||
use clippy_utils::source::snippet_opt;
|
||||
use clippy_utils::ty::is_isize_or_usize;
|
||||
use clippy_utils::{in_constant, meets_msrv, msrvs};
|
||||
use rustc_errors::Applicability;
|
||||
use rustc_hir::{Expr, ExprKind};
|
||||
use rustc_lint::LateContext;
|
||||
use rustc_middle::ty::{self, FloatTy, Ty};
|
||||
use rustc_semver::RustcVersion;
|
||||
|
||||
use super::{utils, CAST_LOSSLESS};
|
||||
|
||||
pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
|
||||
if !should_lint(cx, expr, cast_from, cast_to) {
|
||||
pub(super) fn check(
|
||||
cx: &LateContext<'_>,
|
||||
expr: &Expr<'_>,
|
||||
cast_op: &Expr<'_>,
|
||||
cast_from: Ty<'_>,
|
||||
cast_to: Ty<'_>,
|
||||
msrv: &Option<RustcVersion>,
|
||||
) {
|
||||
if !should_lint(cx, expr, cast_from, cast_to, msrv) {
|
||||
return;
|
||||
}
|
||||
|
||||
@ -32,21 +40,36 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_op: &Expr<'_>, c
|
||||
},
|
||||
);
|
||||
|
||||
let message = if cast_from.is_bool() {
|
||||
format!(
|
||||
"casting `{0:}` to `{1:}` is more cleanly stated with `{1:}::from(_)`",
|
||||
cast_from, cast_to
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"casting `{}` to `{}` may become silently lossy if you later change the type",
|
||||
cast_from, cast_to
|
||||
)
|
||||
};
|
||||
|
||||
span_lint_and_sugg(
|
||||
cx,
|
||||
CAST_LOSSLESS,
|
||||
expr.span,
|
||||
&format!(
|
||||
"casting `{}` to `{}` may become silently lossy if you later change the type",
|
||||
cast_from, cast_to
|
||||
),
|
||||
&message,
|
||||
"try",
|
||||
format!("{}::from({})", cast_to, sugg),
|
||||
applicability,
|
||||
);
|
||||
}
|
||||
|
||||
fn should_lint(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) -> bool {
|
||||
fn should_lint(
|
||||
cx: &LateContext<'_>,
|
||||
expr: &Expr<'_>,
|
||||
cast_from: Ty<'_>,
|
||||
cast_to: Ty<'_>,
|
||||
msrv: &Option<RustcVersion>,
|
||||
) -> bool {
|
||||
// Do not suggest using From in consts/statics until it is valid to do so (see #2267).
|
||||
if in_constant(cx, expr.hir_id) {
|
||||
return false;
|
||||
@ -72,7 +95,7 @@ fn should_lint(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to
|
||||
};
|
||||
from_nbits < to_nbits
|
||||
},
|
||||
|
||||
(false, true) if matches!(cast_from.kind(), ty::Bool) && meets_msrv(msrv.as_ref(), &msrvs::FROM_BOOL) => true,
|
||||
(_, _) => {
|
||||
matches!(cast_from.kind(), ty::Float(FloatTy::F32)) && matches!(cast_to.kind(), ty::Float(FloatTy::F64))
|
||||
},
|
||||
|
@ -40,6 +40,7 @@ declare_clippy_lint! {
|
||||
/// let x = u64::MAX;
|
||||
/// x as f64;
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub CAST_PRECISION_LOSS,
|
||||
pedantic,
|
||||
"casts that cause loss of precision, e.g., `x as f32` where `x: u64`"
|
||||
@ -61,6 +62,7 @@ declare_clippy_lint! {
|
||||
/// let y: i8 = -1;
|
||||
/// y as u128; // will return 18446744073709551615
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub CAST_SIGN_LOSS,
|
||||
pedantic,
|
||||
"casts from signed types to unsigned types, e.g., `x as u32` where `x: i32`"
|
||||
@ -83,6 +85,7 @@ declare_clippy_lint! {
|
||||
/// x as u8
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub CAST_POSSIBLE_TRUNCATION,
|
||||
pedantic,
|
||||
"casts that may cause truncation of the value, e.g., `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
|
||||
@ -106,6 +109,7 @@ declare_clippy_lint! {
|
||||
/// ```rust
|
||||
/// u32::MAX as i32; // will yield a value of `-1`
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub CAST_POSSIBLE_WRAP,
|
||||
pedantic,
|
||||
"casts that may cause wrapping around the value, e.g., `x as i32` where `x: u32` and `x > i32::MAX`"
|
||||
@ -138,6 +142,7 @@ declare_clippy_lint! {
|
||||
/// u64::from(x)
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub CAST_LOSSLESS,
|
||||
pedantic,
|
||||
"casts using `as` that are known to be lossless, e.g., `x as u64` where `x: u8`"
|
||||
@ -163,6 +168,7 @@ declare_clippy_lint! {
|
||||
/// let _ = 2_i32;
|
||||
/// let _ = 0.5_f32;
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub UNNECESSARY_CAST,
|
||||
complexity,
|
||||
"cast to the same type, e.g., `x as i32` where `x: i32`"
|
||||
@ -190,6 +196,7 @@ declare_clippy_lint! {
|
||||
/// (&1u8 as *const u8).cast::<u16>();
|
||||
/// (&mut 1u8 as *mut u8).cast::<u16>();
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub CAST_PTR_ALIGNMENT,
|
||||
pedantic,
|
||||
"cast from a pointer to a more-strictly-aligned pointer"
|
||||
@ -217,6 +224,7 @@ declare_clippy_lint! {
|
||||
/// fn fun2() -> i32 { 1 }
|
||||
/// let a = fun2 as usize;
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub FN_TO_NUMERIC_CAST,
|
||||
style,
|
||||
"casting a function pointer to a numeric type other than usize"
|
||||
@ -247,6 +255,7 @@ declare_clippy_lint! {
|
||||
/// let fn_ptr = fn2 as usize;
|
||||
/// let fn_ptr_truncated = fn_ptr as i32;
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
|
||||
style,
|
||||
"casting a function pointer to a numeric type not wide enough to store the address"
|
||||
@ -283,6 +292,7 @@ declare_clippy_lint! {
|
||||
/// }
|
||||
/// let _ = fn3 as fn() -> u16;
|
||||
/// ```
|
||||
#[clippy::version = "1.58.0"]
|
||||
pub FN_TO_NUMERIC_CAST_ANY,
|
||||
restriction,
|
||||
"casting a function pointer to any integer type"
|
||||
@ -317,6 +327,7 @@ declare_clippy_lint! {
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.33.0"]
|
||||
pub CAST_REF_TO_MUT,
|
||||
correctness,
|
||||
"a cast of reference to a mutable pointer"
|
||||
@ -344,6 +355,7 @@ declare_clippy_lint! {
|
||||
/// ```rust,ignore
|
||||
/// b'x'
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub CHAR_LIT_AS_U8,
|
||||
complexity,
|
||||
"casting a character literal to `u8` truncates"
|
||||
@ -372,6 +384,7 @@ declare_clippy_lint! {
|
||||
/// let _ = ptr.cast::<i32>();
|
||||
/// let _ = mut_ptr.cast::<i32>();
|
||||
/// ```
|
||||
#[clippy::version = "1.51.0"]
|
||||
pub PTR_AS_PTR,
|
||||
pedantic,
|
||||
"casting using `as` from and to raw pointers that doesn't change its mutability, where `pointer::cast` could take the place of `as`"
|
||||
@ -426,13 +439,17 @@ impl<'tcx> LateLintPass<'tcx> for Casts {
|
||||
fn_to_numeric_cast_any::check(cx, expr, cast_expr, cast_from, cast_to);
|
||||
fn_to_numeric_cast::check(cx, expr, cast_expr, cast_from, cast_to);
|
||||
fn_to_numeric_cast_with_truncation::check(cx, expr, cast_expr, cast_from, cast_to);
|
||||
if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
|
||||
|
||||
if cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
|
||||
if cast_from.is_numeric() {
|
||||
cast_possible_truncation::check(cx, expr, cast_expr, cast_from, cast_to);
|
||||
cast_possible_wrap::check(cx, expr, cast_from, cast_to);
|
||||
cast_precision_loss::check(cx, expr, cast_from, cast_to);
|
||||
cast_lossless::check(cx, expr, cast_expr, cast_from, cast_to);
|
||||
cast_sign_loss::check(cx, expr, cast_expr, cast_from, cast_to);
|
||||
}
|
||||
|
||||
cast_lossless::check(cx, expr, cast_expr, cast_from, cast_to, &self.msrv);
|
||||
}
|
||||
}
|
||||
|
||||
cast_ref_to_mut::check(cx, expr);
|
||||
|
@ -36,6 +36,7 @@ declare_clippy_lint! {
|
||||
/// i32::try_from(foo).is_ok()
|
||||
/// # ;
|
||||
/// ```
|
||||
#[clippy::version = "1.37.0"]
|
||||
pub CHECKED_CONVERSIONS,
|
||||
pedantic,
|
||||
"`try_from` could replace manual bounds checking when casting"
|
||||
|
@ -27,6 +27,7 @@ declare_clippy_lint! {
|
||||
///
|
||||
/// ### Example
|
||||
/// No. You'll see it when you get the warning.
|
||||
#[clippy::version = "1.35.0"]
|
||||
pub COGNITIVE_COMPLEXITY,
|
||||
nursery,
|
||||
"functions that should be split up into multiple functions"
|
||||
|
@ -47,6 +47,7 @@ declare_clippy_lint! {
|
||||
/// …
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub COLLAPSIBLE_IF,
|
||||
style,
|
||||
"nested `if`s that can be collapsed (e.g., `if x { if y { ... } }`"
|
||||
@ -82,6 +83,7 @@ declare_clippy_lint! {
|
||||
/// …
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.51.0"]
|
||||
pub COLLAPSIBLE_ELSE_IF,
|
||||
style,
|
||||
"nested `else`-`if` expressions that can be collapsed (e.g., `else { if x { ... } }`)"
|
||||
|
@ -41,6 +41,7 @@ declare_clippy_lint! {
|
||||
/// };
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.50.0"]
|
||||
pub COLLAPSIBLE_MATCH,
|
||||
style,
|
||||
"Nested `match` or `if let` expressions where the patterns may be \"collapsed\" together."
|
||||
|
@ -49,6 +49,7 @@ declare_clippy_lint! {
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.40.0"]
|
||||
pub COMPARISON_CHAIN,
|
||||
style,
|
||||
"`if`s that can be rewritten with `match` and `cmp`"
|
||||
|
@ -1,8 +1,8 @@
|
||||
use clippy_utils::diagnostics::{span_lint_and_note, span_lint_and_then};
|
||||
use clippy_utils::source::{first_line_of_span, indent_of, reindent_multiline, snippet, snippet_opt};
|
||||
use clippy_utils::{
|
||||
both, count_eq, eq_expr_value, get_enclosing_block, get_parent_expr, if_sequence, in_macro, is_else_clause,
|
||||
is_lint_allowed, search_same, ContainsName, SpanlessEq, SpanlessHash,
|
||||
both, count_eq, eq_expr_value, get_enclosing_block, get_parent_expr, if_sequence, is_else_clause, is_lint_allowed,
|
||||
search_same, ContainsName, SpanlessEq, SpanlessHash,
|
||||
};
|
||||
use if_chain::if_chain;
|
||||
use rustc_data_structures::fx::FxHashSet;
|
||||
@ -41,6 +41,7 @@ declare_clippy_lint! {
|
||||
/// …
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub IFS_SAME_COND,
|
||||
correctness,
|
||||
"consecutive `if`s with the same condition"
|
||||
@ -88,6 +89,7 @@ declare_clippy_lint! {
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.41.0"]
|
||||
pub SAME_FUNCTIONS_IN_IF_CONDITION,
|
||||
pedantic,
|
||||
"consecutive `if`s with the same function call"
|
||||
@ -109,6 +111,7 @@ declare_clippy_lint! {
|
||||
/// 42
|
||||
/// };
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub IF_SAME_THEN_ELSE,
|
||||
correctness,
|
||||
"`if` with the same `then` and `else` blocks"
|
||||
@ -147,6 +150,7 @@ declare_clippy_lint! {
|
||||
/// 42
|
||||
/// };
|
||||
/// ```
|
||||
#[clippy::version = "1.53.0"]
|
||||
pub BRANCHES_SHARING_CODE,
|
||||
nursery,
|
||||
"`if` statement with shared code in all blocks"
|
||||
@ -623,7 +627,7 @@ fn lint_same_fns_in_if_cond(cx: &LateContext<'_>, conds: &[&Expr<'_>]) {
|
||||
|
||||
let eq: &dyn Fn(&&Expr<'_>, &&Expr<'_>) -> bool = &|&lhs, &rhs| -> bool {
|
||||
// Do not lint if any expr originates from a macro
|
||||
if in_macro(lhs.span) || in_macro(rhs.span) {
|
||||
if lhs.span.from_expansion() || rhs.span.from_expansion() {
|
||||
return false;
|
||||
}
|
||||
// Do not spawn warning if `IFS_SAME_COND` already produced it.
|
||||
|
@ -28,6 +28,7 @@ declare_clippy_lint! {
|
||||
/// let a: Vec<_> = my_iterator.take(1).collect();
|
||||
/// let b: Vec<_> = my_iterator.collect();
|
||||
/// ```
|
||||
#[clippy::version = "1.30.0"]
|
||||
pub COPY_ITERATOR,
|
||||
pedantic,
|
||||
"implementing `Iterator` on a `Copy` type"
|
||||
|
@ -23,6 +23,7 @@ declare_clippy_lint! {
|
||||
/// ```rust
|
||||
/// std::fs::create_dir_all("foo");
|
||||
/// ```
|
||||
#[clippy::version = "1.48.0"]
|
||||
pub CREATE_DIR,
|
||||
restriction,
|
||||
"calling `std::fs::create_dir` instead of `std::fs::create_dir_all`"
|
||||
|
@ -23,6 +23,7 @@ declare_clippy_lint! {
|
||||
/// // Good
|
||||
/// true
|
||||
/// ```
|
||||
#[clippy::version = "1.34.0"]
|
||||
pub DBG_MACRO,
|
||||
restriction,
|
||||
"`dbg!` macro is intended as a debugging tool"
|
||||
|
@ -1,7 +1,7 @@
|
||||
use clippy_utils::diagnostics::{span_lint_and_note, span_lint_and_sugg};
|
||||
use clippy_utils::source::snippet_with_macro_callsite;
|
||||
use clippy_utils::ty::{has_drop, is_copy};
|
||||
use clippy_utils::{any_parent_is_automatically_derived, contains_name, in_macro, match_def_path, paths};
|
||||
use clippy_utils::{any_parent_is_automatically_derived, contains_name, match_def_path, paths};
|
||||
use if_chain::if_chain;
|
||||
use rustc_data_structures::fx::FxHashSet;
|
||||
use rustc_errors::Applicability;
|
||||
@ -29,6 +29,7 @@ declare_clippy_lint! {
|
||||
/// // Good
|
||||
/// let s = String::default();
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub DEFAULT_TRAIT_ACCESS,
|
||||
pedantic,
|
||||
"checks for literal calls to `Default::default()`"
|
||||
@ -62,6 +63,7 @@ declare_clippy_lint! {
|
||||
/// .. Default::default()
|
||||
/// };
|
||||
/// ```
|
||||
#[clippy::version = "1.49.0"]
|
||||
pub FIELD_REASSIGN_WITH_DEFAULT,
|
||||
style,
|
||||
"binding initialized with Default should have its fields set in the initializer"
|
||||
@ -78,7 +80,7 @@ impl_lint_pass!(Default => [DEFAULT_TRAIT_ACCESS, FIELD_REASSIGN_WITH_DEFAULT]);
|
||||
impl LateLintPass<'_> for Default {
|
||||
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
|
||||
if_chain! {
|
||||
if !in_macro(expr.span);
|
||||
if !expr.span.from_expansion();
|
||||
// Avoid cases already linted by `field_reassign_with_default`
|
||||
if !self.reassigned_linted.contains(&expr.span);
|
||||
if let ExprKind::Call(path, ..) = expr.kind;
|
||||
@ -125,7 +127,7 @@ impl LateLintPass<'_> for Default {
|
||||
if let StmtKind::Local(local) = stmt.kind;
|
||||
if let Some(expr) = local.init;
|
||||
if !any_parent_is_automatically_derived(cx.tcx, expr.hir_id);
|
||||
if !in_macro(expr.span);
|
||||
if !expr.span.from_expansion();
|
||||
// only take bindings to identifiers
|
||||
if let PatKind::Binding(_, binding_id, ident, _) = local.pat.kind;
|
||||
// only when assigning `... = Default::default()`
|
||||
|
@ -46,6 +46,7 @@ declare_clippy_lint! {
|
||||
/// let i = 10i32;
|
||||
/// let f = 1.23f64;
|
||||
/// ```
|
||||
#[clippy::version = "1.52.0"]
|
||||
pub DEFAULT_NUMERIC_FALLBACK,
|
||||
restriction,
|
||||
"usage of unconstrained numeric literals which may cause default numeric fallback."
|
||||
|
@ -21,6 +21,7 @@ declare_deprecated_lint! {
|
||||
/// ### Deprecation reason
|
||||
/// This used to check for `assert!(a == b)` and recommend
|
||||
/// replacement with `assert_eq!(a, b)`, but this is no longer needed after RFC 2011.
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub SHOULD_ASSERT_EQ,
|
||||
"`assert!()` will be more flexible with RFC 2011"
|
||||
}
|
||||
@ -32,6 +33,7 @@ declare_deprecated_lint! {
|
||||
/// ### Deprecation reason
|
||||
/// This used to check for `Vec::extend`, which was slower than
|
||||
/// `Vec::extend_from_slice`. Thanks to specialization, this is no longer true.
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub EXTEND_FROM_SLICE,
|
||||
"`.extend_from_slice(_)` is a faster way to extend a Vec by a slice"
|
||||
}
|
||||
@ -45,6 +47,7 @@ declare_deprecated_lint! {
|
||||
/// an infinite iterator, which is better expressed by `iter::repeat`,
|
||||
/// but the method has been removed for `Iterator::step_by` which panics
|
||||
/// if given a zero
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub RANGE_STEP_BY_ZERO,
|
||||
"`iterator.step_by(0)` panics nowadays"
|
||||
}
|
||||
@ -56,6 +59,7 @@ declare_deprecated_lint! {
|
||||
/// ### Deprecation reason
|
||||
/// This used to check for `Vec::as_slice`, which was unstable with good
|
||||
/// stable alternatives. `Vec::as_slice` has now been stabilized.
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub UNSTABLE_AS_SLICE,
|
||||
"`Vec::as_slice` has been stabilized in 1.7"
|
||||
}
|
||||
@ -67,6 +71,7 @@ declare_deprecated_lint! {
|
||||
/// ### Deprecation reason
|
||||
/// This used to check for `Vec::as_mut_slice`, which was unstable with good
|
||||
/// stable alternatives. `Vec::as_mut_slice` has now been stabilized.
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub UNSTABLE_AS_MUT_SLICE,
|
||||
"`Vec::as_mut_slice` has been stabilized in 1.7"
|
||||
}
|
||||
@ -80,6 +85,7 @@ declare_deprecated_lint! {
|
||||
/// between non-pointer types of differing alignment is well-defined behavior (it's semantically
|
||||
/// equivalent to a memcpy). This lint has thus been refactored into two separate lints:
|
||||
/// cast_ptr_alignment and transmute_ptr_to_ptr.
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub MISALIGNED_TRANSMUTE,
|
||||
"this lint has been split into cast_ptr_alignment and transmute_ptr_to_ptr"
|
||||
}
|
||||
@ -92,6 +98,7 @@ declare_deprecated_lint! {
|
||||
/// This lint is too subjective, not having a good reason for being in clippy.
|
||||
/// Additionally, compound assignment operators may be overloaded separately from their non-assigning
|
||||
/// counterparts, so this lint may suggest a change in behavior or the code may not compile.
|
||||
#[clippy::version = "1.30.0"]
|
||||
pub ASSIGN_OPS,
|
||||
"using compound assignment operators (e.g., `+=`) is harmless"
|
||||
}
|
||||
@ -104,6 +111,7 @@ declare_deprecated_lint! {
|
||||
/// The original rule will only lint for `if let`. After
|
||||
/// making it support to lint `match`, naming as `if let` is not suitable for it.
|
||||
/// So, this lint is deprecated.
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub IF_LET_REDUNDANT_PATTERN_MATCHING,
|
||||
"this lint has been changed to redundant_pattern_matching"
|
||||
}
|
||||
@ -117,6 +125,7 @@ declare_deprecated_lint! {
|
||||
/// Vec::with_capacity(n); vec.set_len(n);` with `let vec = vec![0; n];`. The
|
||||
/// replacement has very different performance characteristics so the lint is
|
||||
/// deprecated.
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub UNSAFE_VECTOR_INITIALIZATION,
|
||||
"the replacement suggested by this lint had substantially different behavior"
|
||||
}
|
||||
@ -127,6 +136,7 @@ declare_deprecated_lint! {
|
||||
///
|
||||
/// ### Deprecation reason
|
||||
/// This lint has been superseded by #[must_use] in rustc.
|
||||
#[clippy::version = "1.39.0"]
|
||||
pub UNUSED_COLLECT,
|
||||
"`collect` has been marked as #[must_use] in rustc and that covers all cases of this lint"
|
||||
}
|
||||
@ -137,6 +147,7 @@ declare_deprecated_lint! {
|
||||
///
|
||||
/// ### Deprecation reason
|
||||
/// Associated-constants are now preferred.
|
||||
#[clippy::version = "1.44.0"]
|
||||
pub REPLACE_CONSTS,
|
||||
"associated-constants `MIN`/`MAX` of integers are preferred to `{min,max}_value()` and module constants"
|
||||
}
|
||||
@ -147,6 +158,7 @@ declare_deprecated_lint! {
|
||||
///
|
||||
/// ### Deprecation reason
|
||||
/// The regex! macro does not exist anymore.
|
||||
#[clippy::version = "1.47.0"]
|
||||
pub REGEX_MACRO,
|
||||
"the regex! macro has been removed from the regex crate in 2018"
|
||||
}
|
||||
@ -158,6 +170,7 @@ declare_deprecated_lint! {
|
||||
/// ### Deprecation reason
|
||||
/// This lint has been replaced by `manual_find_map`, a
|
||||
/// more specific lint.
|
||||
#[clippy::version = "1.51.0"]
|
||||
pub FIND_MAP,
|
||||
"this lint has been replaced by `manual_find_map`, a more specific lint"
|
||||
}
|
||||
@ -169,6 +182,7 @@ declare_deprecated_lint! {
|
||||
/// ### Deprecation reason
|
||||
/// This lint has been replaced by `manual_filter_map`, a
|
||||
/// more specific lint.
|
||||
#[clippy::version = "1.53.0"]
|
||||
pub FILTER_MAP,
|
||||
"this lint has been replaced by `manual_filter_map`, a more specific lint"
|
||||
}
|
||||
@ -181,6 +195,7 @@ declare_deprecated_lint! {
|
||||
/// The `avoid_breaking_exported_api` config option was added, which
|
||||
/// enables the `enum_variant_names` lint for public items.
|
||||
/// ```
|
||||
#[clippy::version = "1.54.0"]
|
||||
pub PUB_ENUM_VARIANT_NAMES,
|
||||
"set the `avoid-breaking-exported-api` config option to `false` to enable the `enum_variant_names` lint for public items"
|
||||
}
|
||||
@ -192,6 +207,7 @@ declare_deprecated_lint! {
|
||||
/// ### Deprecation reason
|
||||
/// The `avoid_breaking_exported_api` config option was added, which
|
||||
/// enables the `wrong_self_conversion` lint for public items.
|
||||
#[clippy::version = "1.54.0"]
|
||||
pub WRONG_PUB_SELF_CONVENTION,
|
||||
"set the `avoid-breaking-exported-api` config option to `false` to enable the `wrong_self_convention` lint for public items"
|
||||
}
|
||||
|
@ -1,7 +1,7 @@
|
||||
use clippy_utils::diagnostics::span_lint_and_sugg;
|
||||
use clippy_utils::source::snippet_with_context;
|
||||
use clippy_utils::ty::peel_mid_ty_refs;
|
||||
use clippy_utils::{get_parent_node, in_macro, is_lint_allowed};
|
||||
use clippy_utils::{get_parent_node, is_lint_allowed};
|
||||
use rustc_ast::util::parser::PREC_PREFIX;
|
||||
use rustc_errors::Applicability;
|
||||
use rustc_hir::{BorrowKind, Expr, ExprKind, HirId, MatchSource, Mutability, Node, UnOp};
|
||||
@ -34,6 +34,7 @@ declare_clippy_lint! {
|
||||
/// ```rust,ignore
|
||||
/// let _ = d.unwrap().deref();
|
||||
/// ```
|
||||
#[clippy::version = "1.44.0"]
|
||||
pub EXPLICIT_DEREF_METHODS,
|
||||
pedantic,
|
||||
"Explicit use of deref or deref_mut method while not in a method chain."
|
||||
@ -84,7 +85,7 @@ impl<'tcx> LateLintPass<'tcx> for Dereferencing {
|
||||
}
|
||||
|
||||
// Stop processing sub expressions when a macro call is seen
|
||||
if in_macro(expr.span) {
|
||||
if expr.span.from_expansion() {
|
||||
if let Some((state, data)) = self.state.take() {
|
||||
report(cx, expr, state, data);
|
||||
}
|
||||
|
@ -1,5 +1,5 @@
|
||||
use clippy_utils::diagnostics::span_lint_and_help;
|
||||
use clippy_utils::{in_macro, is_automatically_derived, is_default_equivalent, remove_blocks};
|
||||
use clippy_utils::{is_automatically_derived, is_default_equivalent, remove_blocks};
|
||||
use rustc_hir::{
|
||||
def::{DefKind, Res},
|
||||
Body, Expr, ExprKind, GenericArg, Impl, ImplItemKind, Item, ItemKind, Node, PathSegment, QPath, TyKind,
|
||||
@ -46,6 +46,7 @@ declare_clippy_lint! {
|
||||
/// has exactly equal bounds, and therefore this lint is disabled for types with
|
||||
/// generic parameters.
|
||||
///
|
||||
#[clippy::version = "1.57.0"]
|
||||
pub DERIVABLE_IMPLS,
|
||||
complexity,
|
||||
"manual implementation of the `Default` trait which is equal to a derive"
|
||||
@ -72,7 +73,7 @@ impl<'tcx> LateLintPass<'tcx> for DerivableImpls {
|
||||
}) = item.kind;
|
||||
if let attrs = cx.tcx.hir().attrs(item.hir_id());
|
||||
if !is_automatically_derived(attrs);
|
||||
if !in_macro(item.span);
|
||||
if !item.span.from_expansion();
|
||||
if let Some(def_id) = trait_ref.trait_def_id();
|
||||
if cx.tcx.is_diagnostic_item(sym::Default, def_id);
|
||||
if let impl_item_hir = child.id.hir_id();
|
||||
|
@ -38,6 +38,7 @@ declare_clippy_lint! {
|
||||
/// ...
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub DERIVE_HASH_XOR_EQ,
|
||||
correctness,
|
||||
"deriving `Hash` but implementing `PartialEq` explicitly"
|
||||
@ -88,6 +89,7 @@ declare_clippy_lint! {
|
||||
/// #[derive(Ord, PartialOrd, PartialEq, Eq)]
|
||||
/// struct Foo;
|
||||
/// ```
|
||||
#[clippy::version = "1.47.0"]
|
||||
pub DERIVE_ORD_XOR_PARTIAL_ORD,
|
||||
correctness,
|
||||
"deriving `Ord` but implementing `PartialOrd` explicitly"
|
||||
@ -114,6 +116,7 @@ declare_clippy_lint! {
|
||||
/// // ..
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub EXPL_IMPL_CLONE_ON_COPY,
|
||||
pedantic,
|
||||
"implementing `Clone` explicitly on `Copy` types"
|
||||
@ -147,6 +150,7 @@ declare_clippy_lint! {
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.45.0"]
|
||||
pub UNSAFE_DERIVE_DESERIALIZE,
|
||||
pedantic,
|
||||
"deriving `serde::Deserialize` on a type that has methods using `unsafe`"
|
||||
|
@ -47,6 +47,7 @@ declare_clippy_lint! {
|
||||
/// let mut xs = Vec::new(); // Vec::new is _not_ disallowed in the config.
|
||||
/// xs.push(123); // Vec::push is _not_ disallowed in the config.
|
||||
/// ```
|
||||
#[clippy::version = "1.49.0"]
|
||||
pub DISALLOWED_METHOD,
|
||||
nursery,
|
||||
"use of a disallowed method call"
|
||||
|
@ -38,6 +38,7 @@ declare_clippy_lint! {
|
||||
/// let zähler = 10; // OK, it's still latin.
|
||||
/// let カウンタ = 10; // Will spawn the lint.
|
||||
/// ```
|
||||
#[clippy::version = "1.55.0"]
|
||||
pub DISALLOWED_SCRIPT_IDENTS,
|
||||
restriction,
|
||||
"usage of non-allowed Unicode scripts"
|
||||
|
@ -42,6 +42,7 @@ declare_clippy_lint! {
|
||||
/// // A similar type that is allowed by the config
|
||||
/// use std::collections::HashMap;
|
||||
/// ```
|
||||
#[clippy::version = "1.55.0"]
|
||||
pub DISALLOWED_TYPE,
|
||||
nursery,
|
||||
"use of a disallowed type"
|
||||
|
@ -67,6 +67,7 @@ declare_clippy_lint! {
|
||||
/// /// [SmallVec]: SmallVec
|
||||
/// fn main() {}
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub DOC_MARKDOWN,
|
||||
pedantic,
|
||||
"presence of `_`, `::` or camel-case outside backticks in documentation"
|
||||
@ -101,6 +102,7 @@ declare_clippy_lint! {
|
||||
/// unimplemented!();
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.39.0"]
|
||||
pub MISSING_SAFETY_DOC,
|
||||
style,
|
||||
"`pub unsafe fn` without `# Safety` docs"
|
||||
@ -129,6 +131,7 @@ declare_clippy_lint! {
|
||||
/// unimplemented!();
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.41.0"]
|
||||
pub MISSING_ERRORS_DOC,
|
||||
pedantic,
|
||||
"`pub fn` returns `Result` without `# Errors` in doc comment"
|
||||
@ -159,6 +162,7 @@ declare_clippy_lint! {
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.52.0"]
|
||||
pub MISSING_PANICS_DOC,
|
||||
pedantic,
|
||||
"`pub fn` may panic without `# Panics` in doc comment"
|
||||
@ -187,6 +191,7 @@ declare_clippy_lint! {
|
||||
/// unimplemented!();
|
||||
/// }
|
||||
/// ``````
|
||||
#[clippy::version = "1.40.0"]
|
||||
pub NEEDLESS_DOCTEST_MAIN,
|
||||
style,
|
||||
"presence of `fn main() {` in code examples"
|
||||
@ -639,7 +644,9 @@ fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) {
|
||||
| ItemKind::ExternCrate(..)
|
||||
| ItemKind::ForeignMod(..) => return false,
|
||||
// We found a main function ...
|
||||
ItemKind::Fn(box Fn { sig, body: Some(block), .. }) if item.ident.name == sym::main => {
|
||||
ItemKind::Fn(box Fn {
|
||||
sig, body: Some(block), ..
|
||||
}) if item.ident.name == sym::main => {
|
||||
let is_async = matches!(sig.header.asyncness, Async::Yes { .. });
|
||||
let returns_nothing = match &sig.decl.output {
|
||||
FnRetTy::Default(..) => true,
|
||||
|
@ -31,6 +31,7 @@ declare_clippy_lint! {
|
||||
/// # let y = 2;
|
||||
/// if x <= y {}
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub DOUBLE_COMPARISONS,
|
||||
complexity,
|
||||
"unnecessary double comparisons that can be simplified"
|
||||
|
@ -32,6 +32,7 @@ declare_clippy_lint! {
|
||||
/// // Good
|
||||
/// foo(0);
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub DOUBLE_PARENS,
|
||||
complexity,
|
||||
"Warn on unnecessary double parentheses"
|
||||
|
@ -25,6 +25,7 @@ declare_clippy_lint! {
|
||||
/// // still locked
|
||||
/// operation_that_requires_mutex_to_be_unlocked();
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub DROP_REF,
|
||||
correctness,
|
||||
"calls to `std::mem::drop` with a reference instead of an owned value"
|
||||
@ -46,6 +47,7 @@ declare_clippy_lint! {
|
||||
/// let x = Box::new(1);
|
||||
/// std::mem::forget(&x) // Should have been forget(x), x will still be dropped
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub FORGET_REF,
|
||||
correctness,
|
||||
"calls to `std::mem::forget` with a reference instead of an owned value"
|
||||
@ -67,6 +69,7 @@ declare_clippy_lint! {
|
||||
/// std::mem::drop(x) // A copy of x is passed to the function, leaving the
|
||||
/// // original unaffected
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub DROP_COPY,
|
||||
correctness,
|
||||
"calls to `std::mem::drop` with a value that implements Copy"
|
||||
@ -94,6 +97,7 @@ declare_clippy_lint! {
|
||||
/// std::mem::forget(x) // A copy of x is passed to the function, leaving the
|
||||
/// // original unaffected
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub FORGET_COPY,
|
||||
correctness,
|
||||
"calls to `std::mem::forget` with a value that implements Copy"
|
||||
|
@ -33,6 +33,7 @@ declare_clippy_lint! {
|
||||
/// let _micros = dur.subsec_micros();
|
||||
/// let _millis = dur.subsec_millis();
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub DURATION_SUBSEC,
|
||||
complexity,
|
||||
"checks for calculation of subsecond microseconds or milliseconds"
|
||||
|
@ -40,6 +40,7 @@ declare_clippy_lint! {
|
||||
/// // We don't care about zero.
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub ELSE_IF_WITHOUT_ELSE,
|
||||
restriction,
|
||||
"`if` expression with an `else if`, but without a final `else` branch"
|
||||
|
@ -34,6 +34,7 @@ declare_clippy_lint! {
|
||||
///
|
||||
/// struct Test(!);
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub EMPTY_ENUM,
|
||||
pedantic,
|
||||
"enum with no variants"
|
||||
|
@ -54,6 +54,7 @@ declare_clippy_lint! {
|
||||
/// # let v = 1;
|
||||
/// map.entry(k).or_insert(v);
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub MAP_ENTRY,
|
||||
perf,
|
||||
"use of `contains_key` followed by `insert` on a `HashMap` or `BTreeMap`"
|
||||
|
@ -28,6 +28,7 @@ declare_clippy_lint! {
|
||||
/// Y = 0,
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub ENUM_CLIKE_UNPORTABLE_VARIANT,
|
||||
correctness,
|
||||
"C-like enums that are `repr(isize/usize)` and have values that don't fit into an `i32`"
|
||||
|
@ -34,6 +34,7 @@ declare_clippy_lint! {
|
||||
/// Battenberg,
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub ENUM_VARIANT_NAMES,
|
||||
style,
|
||||
"enums where all variants share a prefix/postfix"
|
||||
@ -59,6 +60,7 @@ declare_clippy_lint! {
|
||||
/// struct BlackForest;
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.33.0"]
|
||||
pub MODULE_NAME_REPETITIONS,
|
||||
pedantic,
|
||||
"type names prefixed/postfixed with their containing module's name"
|
||||
@ -89,6 +91,7 @@ declare_clippy_lint! {
|
||||
/// ...
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub MODULE_INCEPTION,
|
||||
style,
|
||||
"modules that have the same name as their parent module"
|
||||
|
@ -1,9 +1,7 @@
|
||||
use clippy_utils::diagnostics::{multispan_sugg, span_lint, span_lint_and_then};
|
||||
use clippy_utils::source::snippet;
|
||||
use clippy_utils::ty::{implements_trait, is_copy};
|
||||
use clippy_utils::{
|
||||
ast_utils::is_useless_with_eq_exprs, eq_expr_value, higher, in_macro, is_expn_of, is_in_test_function,
|
||||
};
|
||||
use clippy_utils::{ast_utils::is_useless_with_eq_exprs, eq_expr_value, higher, is_expn_of, is_in_test_function};
|
||||
use if_chain::if_chain;
|
||||
use rustc_errors::Applicability;
|
||||
use rustc_hir::{BinOpKind, BorrowKind, Expr, ExprKind, StmtKind};
|
||||
@ -36,6 +34,7 @@ declare_clippy_lint! {
|
||||
/// # let b = 4;
|
||||
/// assert_eq!(a, a);
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub EQ_OP,
|
||||
correctness,
|
||||
"equal operands on both sides of a comparison or bitwise combination (e.g., `x == x`)"
|
||||
@ -61,6 +60,7 @@ declare_clippy_lint! {
|
||||
/// // Good
|
||||
/// x == *y
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub OP_REF,
|
||||
style,
|
||||
"taking a reference to satisfy the type constraints on `==`"
|
||||
@ -102,7 +102,7 @@ impl<'tcx> LateLintPass<'tcx> for EqOp {
|
||||
}
|
||||
let macro_with_not_op = |expr_kind: &ExprKind<'_>| {
|
||||
if let ExprKind::Unary(_, expr) = *expr_kind {
|
||||
in_macro(expr.span)
|
||||
expr.span.from_expansion()
|
||||
} else {
|
||||
false
|
||||
}
|
||||
|
@ -32,6 +32,7 @@ declare_clippy_lint! {
|
||||
/// do_thing();
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.57.0"]
|
||||
pub EQUATABLE_IF_LET,
|
||||
nursery,
|
||||
"using pattern matching instead of equality"
|
||||
|
@ -21,6 +21,7 @@ declare_clippy_lint! {
|
||||
/// 0 * x;
|
||||
/// x & 0;
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub ERASING_OP,
|
||||
correctness,
|
||||
"using erasing operations, e.g., `x * 0` or `y & 0`"
|
||||
|
@ -41,6 +41,7 @@ declare_clippy_lint! {
|
||||
/// foo(x);
|
||||
/// println!("{}", x);
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub BOXED_LOCAL,
|
||||
perf,
|
||||
"using `Box<T>` where unnecessary"
|
||||
|
@ -1,8 +1,8 @@
|
||||
use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
|
||||
use clippy_utils::higher::VecArgs;
|
||||
use clippy_utils::source::snippet_opt;
|
||||
use clippy_utils::usage::UsedAfterExprVisitor;
|
||||
use clippy_utils::{get_enclosing_loop_or_closure, higher, path_to_local_id};
|
||||
use clippy_utils::usage::local_used_after_expr;
|
||||
use clippy_utils::{get_enclosing_loop_or_closure, higher, path_to_local, path_to_local_id};
|
||||
use if_chain::if_chain;
|
||||
use rustc_errors::Applicability;
|
||||
use rustc_hir::def_id::DefId;
|
||||
@ -39,6 +39,7 @@ declare_clippy_lint! {
|
||||
/// ```
|
||||
/// where `foo(_)` is a plain function that takes the exact argument type of
|
||||
/// `x`.
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub REDUNDANT_CLOSURE,
|
||||
style,
|
||||
"redundant closures, i.e., `|a| foo(a)` (which can be written as just `foo`)"
|
||||
@ -60,6 +61,7 @@ declare_clippy_lint! {
|
||||
/// ```rust,ignore
|
||||
/// Some('a').map(char::to_uppercase);
|
||||
/// ```
|
||||
#[clippy::version = "1.35.0"]
|
||||
pub REDUNDANT_CLOSURE_FOR_METHOD_CALLS,
|
||||
pedantic,
|
||||
"redundant closures for method calls"
|
||||
@ -118,7 +120,7 @@ impl<'tcx> LateLintPass<'tcx> for EtaReduction {
|
||||
if let ty::Closure(_, substs) = callee_ty.peel_refs().kind();
|
||||
if substs.as_closure().kind() == ClosureKind::FnMut;
|
||||
if get_enclosing_loop_or_closure(cx.tcx, expr).is_some()
|
||||
|| UsedAfterExprVisitor::is_found(cx, callee);
|
||||
|| path_to_local(callee).map_or(false, |l| local_used_after_expr(cx, l, callee));
|
||||
|
||||
then {
|
||||
// Mutable closure is used after current expr; we cannot consume it.
|
||||
|
@ -40,6 +40,7 @@ declare_clippy_lint! {
|
||||
/// };
|
||||
/// let a = tmp + x;
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub EVAL_ORDER_DEPENDENCE,
|
||||
suspicious,
|
||||
"whether a variable read occurs before a write depends on sub-expression evaluation order"
|
||||
@ -67,6 +68,7 @@ declare_clippy_lint! {
|
||||
/// let x = (a, b, c, panic!());
|
||||
/// // can simply be replaced by `panic!()`
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub DIVERGING_SUB_EXPRESSION,
|
||||
complexity,
|
||||
"whether an expression contains a diverging sub expression"
|
||||
|
@ -1,5 +1,4 @@
|
||||
use clippy_utils::diagnostics::span_lint_and_help;
|
||||
use clippy_utils::in_macro;
|
||||
use rustc_ast::ast::{AssocItemKind, Extern, Fn, FnSig, Impl, Item, ItemKind, Trait, Ty, TyKind};
|
||||
use rustc_lint::{EarlyContext, EarlyLintPass};
|
||||
use rustc_session::{declare_tool_lint, impl_lint_pass};
|
||||
@ -38,6 +37,7 @@ declare_clippy_lint! {
|
||||
/// Finished,
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.43.0"]
|
||||
pub STRUCT_EXCESSIVE_BOOLS,
|
||||
pedantic,
|
||||
"using too many bools in a struct"
|
||||
@ -76,6 +76,7 @@ declare_clippy_lint! {
|
||||
///
|
||||
/// fn f(shape: Shape, temperature: Temperature) { ... }
|
||||
/// ```
|
||||
#[clippy::version = "1.43.0"]
|
||||
pub FN_PARAMS_EXCESSIVE_BOOLS,
|
||||
pedantic,
|
||||
"using too many bools in function parameters"
|
||||
@ -135,7 +136,7 @@ fn is_bool_ty(ty: &Ty) -> bool {
|
||||
|
||||
impl EarlyLintPass for ExcessiveBools {
|
||||
fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
|
||||
if in_macro(item.span) {
|
||||
if item.span.from_expansion() {
|
||||
return;
|
||||
}
|
||||
match &item.kind {
|
||||
|
@ -31,6 +31,7 @@ declare_clippy_lint! {
|
||||
/// Baz
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.51.0"]
|
||||
pub EXHAUSTIVE_ENUMS,
|
||||
restriction,
|
||||
"detects exported enums that have not been marked #[non_exhaustive]"
|
||||
@ -60,6 +61,7 @@ declare_clippy_lint! {
|
||||
/// baz: String,
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.51.0"]
|
||||
pub EXHAUSTIVE_STRUCTS,
|
||||
restriction,
|
||||
"detects exported structs that have not been marked #[non_exhaustive]"
|
||||
|
@ -18,6 +18,7 @@ declare_clippy_lint! {
|
||||
/// ```ignore
|
||||
/// std::process::exit(0)
|
||||
/// ```
|
||||
#[clippy::version = "1.41.0"]
|
||||
pub EXIT,
|
||||
restriction,
|
||||
"`std::process::exit` is called, terminating the program"
|
||||
|
@ -23,6 +23,7 @@ declare_clippy_lint! {
|
||||
/// // this would be clearer as `eprintln!("foo: {:?}", bar);`
|
||||
/// writeln!(&mut std::io::stderr(), "foo: {:?}", bar).unwrap();
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub EXPLICIT_WRITE,
|
||||
complexity,
|
||||
"using the `write!()` family of functions instead of the `print!()` family of functions, when using the latter would work"
|
||||
|
@ -44,6 +44,7 @@ declare_clippy_lint! {
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub FALLIBLE_IMPL_FROM,
|
||||
nursery,
|
||||
"Warn on impls of `From<..>` that contain `panic!()` or `unwrap()`"
|
||||
|
@ -31,6 +31,7 @@ declare_clippy_lint! {
|
||||
/// ghi = []
|
||||
/// ```
|
||||
///
|
||||
#[clippy::version = "1.57.0"]
|
||||
pub REDUNDANT_FEATURE_NAMES,
|
||||
cargo,
|
||||
"usage of a redundant feature name"
|
||||
@ -60,6 +61,7 @@ declare_clippy_lint! {
|
||||
/// def = []
|
||||
///
|
||||
/// ```
|
||||
#[clippy::version = "1.57.0"]
|
||||
pub NEGATIVE_FEATURE_NAMES,
|
||||
cargo,
|
||||
"usage of a negative feature name"
|
||||
|
@ -37,6 +37,7 @@ declare_clippy_lint! {
|
||||
/// (a - b).abs() < f32::EPSILON
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.48.0"]
|
||||
pub FLOAT_EQUALITY_WITHOUT_ABS,
|
||||
suspicious,
|
||||
"float equality check without `.abs()`"
|
||||
|
@ -27,6 +27,7 @@ declare_clippy_lint! {
|
||||
/// let v: f64 = 0.123_456_789_9;
|
||||
/// println!("{}", v); // 0.123_456_789_9
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub EXCESSIVE_PRECISION,
|
||||
style,
|
||||
"excessive precision for float literal"
|
||||
@ -50,6 +51,7 @@ declare_clippy_lint! {
|
||||
/// let _: f32 = 16_777_216.0;
|
||||
/// let _: f64 = 16_777_217.0;
|
||||
/// ```
|
||||
#[clippy::version = "1.43.0"]
|
||||
pub LOSSY_FLOAT_LITERAL,
|
||||
restriction,
|
||||
"lossy whole number float literals"
|
||||
|
@ -43,6 +43,7 @@ declare_clippy_lint! {
|
||||
/// let _ = a.ln_1p();
|
||||
/// let _ = a.exp_m1();
|
||||
/// ```
|
||||
#[clippy::version = "1.43.0"]
|
||||
pub IMPRECISE_FLOPS,
|
||||
nursery,
|
||||
"usage of imprecise floating point operations"
|
||||
@ -99,6 +100,7 @@ declare_clippy_lint! {
|
||||
/// let _ = a.abs();
|
||||
/// let _ = -a.abs();
|
||||
/// ```
|
||||
#[clippy::version = "1.43.0"]
|
||||
pub SUBOPTIMAL_FLOPS,
|
||||
nursery,
|
||||
"usage of sub-optimal floating point operations"
|
||||
|
@ -33,6 +33,7 @@ declare_clippy_lint! {
|
||||
/// // Good
|
||||
/// foo.to_owned();
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub USELESS_FORMAT,
|
||||
complexity,
|
||||
"useless use of `format!`"
|
||||
|
@ -10,7 +10,7 @@ use rustc_lint::{LateContext, LateLintPass};
|
||||
use rustc_middle::ty::adjustment::{Adjust, Adjustment};
|
||||
use rustc_middle::ty::Ty;
|
||||
use rustc_session::{declare_lint_pass, declare_tool_lint};
|
||||
use rustc_span::{sym, BytePos, ExpnData, ExpnKind, Span, Symbol};
|
||||
use rustc_span::{sym, ExpnData, ExpnKind, Span, Symbol};
|
||||
|
||||
declare_clippy_lint! {
|
||||
/// ### What it does
|
||||
@ -31,6 +31,7 @@ declare_clippy_lint! {
|
||||
/// # use std::panic::Location;
|
||||
/// println!("error: something failed at {}", Location::caller());
|
||||
/// ```
|
||||
#[clippy::version = "1.58.0"]
|
||||
pub FORMAT_IN_FORMAT_ARGS,
|
||||
perf,
|
||||
"`format!` used in a macro that does formatting"
|
||||
@ -56,6 +57,7 @@ declare_clippy_lint! {
|
||||
/// # use std::panic::Location;
|
||||
/// println!("error: something failed at {}", Location::caller());
|
||||
/// ```
|
||||
#[clippy::version = "1.58.0"]
|
||||
pub TO_STRING_IN_FORMAT_ARGS,
|
||||
perf,
|
||||
"`to_string` applied to a type that implements `Display` in format args"
|
||||
@ -128,7 +130,7 @@ fn check_format_in_format_args(cx: &LateContext<'_>, call_site: Span, name: Symb
|
||||
span_lint_and_then(
|
||||
cx,
|
||||
FORMAT_IN_FORMAT_ARGS,
|
||||
trim_semicolon(cx, call_site),
|
||||
call_site,
|
||||
&format!("`format!` in `{}!` args", name),
|
||||
|diag| {
|
||||
diag.help(&format!(
|
||||
@ -192,13 +194,6 @@ fn is_aliased(args: &[FormatArgsArg<'_>], i: usize) -> bool {
|
||||
.any(|(j, arg)| i != j && std::ptr::eq(value, arg.value))
|
||||
}
|
||||
|
||||
fn trim_semicolon(cx: &LateContext<'_>, span: Span) -> Span {
|
||||
snippet_opt(cx, span).map_or(span, |snippet| {
|
||||
let snippet = snippet.trim_end_matches(';');
|
||||
span.with_hi(span.lo() + BytePos(u32::try_from(snippet.len()).unwrap()))
|
||||
})
|
||||
}
|
||||
|
||||
fn count_needed_derefs<'tcx, I>(mut ty: Ty<'tcx>, mut iter: I) -> (usize, Ty<'tcx>)
|
||||
where
|
||||
I: Iterator<Item = &'tcx Adjustment<'tcx>>,
|
||||
|
@ -21,6 +21,7 @@ declare_clippy_lint! {
|
||||
/// ```rust,ignore
|
||||
/// a =- 42; // confusing, should it be `a -= 42` or `a = -42`?
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub SUSPICIOUS_ASSIGNMENT_FORMATTING,
|
||||
suspicious,
|
||||
"suspicious formatting of `*=`, `-=` or `!=`"
|
||||
@ -43,6 +44,7 @@ declare_clippy_lint! {
|
||||
/// if foo &&! bar { // this should be `foo && !bar` but looks like a different operator
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.40.0"]
|
||||
pub SUSPICIOUS_UNARY_OP_FORMATTING,
|
||||
suspicious,
|
||||
"suspicious formatting of unary `-` or `!` on the RHS of a BinOp"
|
||||
@ -79,6 +81,7 @@ declare_clippy_lint! {
|
||||
/// if bar { // this is the `else` block of the previous `if`, but should it be?
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub SUSPICIOUS_ELSE_FORMATTING,
|
||||
suspicious,
|
||||
"suspicious formatting of `else`"
|
||||
@ -99,6 +102,7 @@ declare_clippy_lint! {
|
||||
/// -4, -5, -6
|
||||
/// ];
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub POSSIBLE_MISSING_COMMA,
|
||||
correctness,
|
||||
"possible missing comma in array"
|
||||
|
@ -34,6 +34,7 @@ declare_clippy_lint! {
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.51.0"]
|
||||
pub FROM_OVER_INTO,
|
||||
style,
|
||||
"Warns on implementations of `Into<..>` to use `From<..>`"
|
||||
|
@ -35,6 +35,7 @@ declare_clippy_lint! {
|
||||
/// let input: &str = get_input();
|
||||
/// let num: u16 = input.parse()?;
|
||||
/// ```
|
||||
#[clippy::version = "1.52.0"]
|
||||
pub FROM_STR_RADIX_10,
|
||||
style,
|
||||
"from_str_radix with radix 10"
|
||||
|
@ -26,6 +26,7 @@ declare_clippy_lint! {
|
||||
/// // ..
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub TOO_MANY_ARGUMENTS,
|
||||
complexity,
|
||||
"functions with too many arguments"
|
||||
@ -49,6 +50,7 @@ declare_clippy_lint! {
|
||||
/// println!("");
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.34.0"]
|
||||
pub TOO_MANY_LINES,
|
||||
pedantic,
|
||||
"functions with too many lines"
|
||||
@ -84,6 +86,7 @@ declare_clippy_lint! {
|
||||
/// println!("{}", unsafe { *x });
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub NOT_UNSAFE_PTR_ARG_DEREF,
|
||||
correctness,
|
||||
"public functions dereferencing raw pointer arguments but not marked `unsafe`"
|
||||
@ -103,6 +106,7 @@ declare_clippy_lint! {
|
||||
/// #[must_use]
|
||||
/// fn useless() { }
|
||||
/// ```
|
||||
#[clippy::version = "1.40.0"]
|
||||
pub MUST_USE_UNIT,
|
||||
style,
|
||||
"`#[must_use]` attribute on a unit-returning function / method"
|
||||
@ -126,6 +130,7 @@ declare_clippy_lint! {
|
||||
/// unimplemented!();
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.40.0"]
|
||||
pub DOUBLE_MUST_USE,
|
||||
style,
|
||||
"`#[must_use]` attribute on a `#[must_use]`-returning function / method"
|
||||
@ -155,6 +160,7 @@ declare_clippy_lint! {
|
||||
/// // this could be annotated with `#[must_use]`.
|
||||
/// fn id<T>(t: T) -> T { t }
|
||||
/// ```
|
||||
#[clippy::version = "1.40.0"]
|
||||
pub MUST_USE_CANDIDATE,
|
||||
pedantic,
|
||||
"function or method that could take a `#[must_use]` attribute"
|
||||
@ -204,6 +210,7 @@ declare_clippy_lint! {
|
||||
///
|
||||
/// Note that there are crates that simplify creating the error type, e.g.
|
||||
/// [`thiserror`](https://docs.rs/thiserror).
|
||||
#[clippy::version = "1.49.0"]
|
||||
pub RESULT_UNIT_ERR,
|
||||
style,
|
||||
"public function returning `Result` with an `Err` type of `()`"
|
||||
|
@ -56,8 +56,8 @@ pub(super) fn check_fn(
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
let multi_idx = line.find("/*").unwrap_or_else(|| line.len());
|
||||
let single_idx = line.find("//").unwrap_or_else(|| line.len());
|
||||
let multi_idx = line.find("/*").unwrap_or(line.len());
|
||||
let single_idx = line.find("//").unwrap_or(line.len());
|
||||
code_in_line |= multi_idx > 0 && single_idx > 0;
|
||||
// Implies multi_idx is below line.len()
|
||||
if multi_idx < single_idx {
|
||||
|
@ -41,6 +41,7 @@ declare_clippy_lint! {
|
||||
/// ```rust
|
||||
/// async fn is_send(bytes: std::sync::Arc<[u8]>) {}
|
||||
/// ```
|
||||
#[clippy::version = "1.44.0"]
|
||||
pub FUTURE_NOT_SEND,
|
||||
nursery,
|
||||
"public Futures must be Send"
|
||||
|
@ -39,6 +39,7 @@ declare_clippy_lint! {
|
||||
/// let x = vec![2, 3, 5];
|
||||
/// let last_element = x.last();
|
||||
/// ```
|
||||
#[clippy::version = "1.37.0"]
|
||||
pub GET_LAST_WITH_LEN,
|
||||
complexity,
|
||||
"Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
|
||||
|
@ -22,6 +22,7 @@ declare_clippy_lint! {
|
||||
/// # let x = 1;
|
||||
/// x / 1 + 0 * 1 - 0 | 0;
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub IDENTITY_OP,
|
||||
complexity,
|
||||
"using identity operations, e.g., `x + 0` or `y / 1`"
|
||||
|
@ -36,6 +36,7 @@ declare_clippy_lint! {
|
||||
/// use_locked(locked);
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.45.0"]
|
||||
pub IF_LET_MUTEX,
|
||||
correctness,
|
||||
"locking a `Mutex` in an `if let` block can cause deadlocks"
|
||||
|
@ -39,6 +39,7 @@ declare_clippy_lint! {
|
||||
/// a()
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub IF_NOT_ELSE,
|
||||
pedantic,
|
||||
"`if` branches that could be swapped so no negation operation is necessary on the condition"
|
||||
|
@ -36,6 +36,7 @@ declare_clippy_lint! {
|
||||
/// 42
|
||||
/// });
|
||||
/// ```
|
||||
#[clippy::version = "1.53.0"]
|
||||
pub IF_THEN_SOME_ELSE_NONE,
|
||||
restriction,
|
||||
"Finds if-else that could be written using `bool::then`"
|
||||
|
@ -54,6 +54,7 @@ declare_clippy_lint! {
|
||||
///
|
||||
/// pub fn foo<S: BuildHasher>(map: &mut HashMap<i32, i32, S>) { }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub IMPLICIT_HASHER,
|
||||
pedantic,
|
||||
"missing generalization over different hashers"
|
||||
|
@ -2,10 +2,10 @@ use clippy_utils::{
|
||||
diagnostics::span_lint_and_sugg,
|
||||
get_async_fn_body, is_async_fn,
|
||||
source::{snippet_with_applicability, snippet_with_context, walk_span_to_context},
|
||||
visitors::visit_break_exprs,
|
||||
visitors::expr_visitor_no_bodies,
|
||||
};
|
||||
use rustc_errors::Applicability;
|
||||
use rustc_hir::intravisit::FnKind;
|
||||
use rustc_hir::intravisit::{FnKind, Visitor};
|
||||
use rustc_hir::{Block, Body, Expr, ExprKind, FnDecl, FnRetTy, HirId};
|
||||
use rustc_lint::{LateContext, LateLintPass, LintContext};
|
||||
use rustc_middle::lint::in_external_macro;
|
||||
@ -35,6 +35,7 @@ declare_clippy_lint! {
|
||||
/// return x;
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.33.0"]
|
||||
pub IMPLICIT_RETURN,
|
||||
restriction,
|
||||
"use a return statement like `return expr` instead of an expression"
|
||||
@ -144,20 +145,24 @@ fn lint_implicit_returns(
|
||||
|
||||
ExprKind::Loop(block, ..) => {
|
||||
let mut add_return = false;
|
||||
visit_break_exprs(block, |break_expr, dest, sub_expr| {
|
||||
expr_visitor_no_bodies(|e| {
|
||||
if let ExprKind::Break(dest, sub_expr) = e.kind {
|
||||
if dest.target_id.ok() == Some(expr.hir_id) {
|
||||
if call_site_span.is_none() && break_expr.span.ctxt() == ctxt {
|
||||
// At this point sub_expr can be `None` in async functions which either diverge, or return the
|
||||
// unit type.
|
||||
if call_site_span.is_none() && e.span.ctxt() == ctxt {
|
||||
// At this point sub_expr can be `None` in async functions which either diverge, or return
|
||||
// the unit type.
|
||||
if let Some(sub_expr) = sub_expr {
|
||||
lint_break(cx, break_expr.span, sub_expr.span);
|
||||
lint_break(cx, e.span, sub_expr.span);
|
||||
}
|
||||
} else {
|
||||
// the break expression is from a macro call, add a return to the loop
|
||||
add_return = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
true
|
||||
})
|
||||
.visit_block(block);
|
||||
if add_return {
|
||||
#[allow(clippy::option_if_let_else)]
|
||||
if let Some(span) = call_site_span {
|
||||
|
@ -1,6 +1,6 @@
|
||||
use clippy_utils::diagnostics::span_lint_and_sugg;
|
||||
use clippy_utils::higher;
|
||||
use clippy_utils::{in_macro, SpanlessEq};
|
||||
use clippy_utils::SpanlessEq;
|
||||
use if_chain::if_chain;
|
||||
use rustc_ast::ast::LitKind;
|
||||
use rustc_errors::Applicability;
|
||||
@ -30,6 +30,7 @@ declare_clippy_lint! {
|
||||
/// // Good
|
||||
/// i = i.saturating_sub(1);
|
||||
/// ```
|
||||
#[clippy::version = "1.44.0"]
|
||||
pub IMPLICIT_SATURATING_SUB,
|
||||
pedantic,
|
||||
"Perform saturating subtraction instead of implicitly checking lower bound of data type"
|
||||
@ -39,7 +40,7 @@ declare_lint_pass!(ImplicitSaturatingSub => [IMPLICIT_SATURATING_SUB]);
|
||||
|
||||
impl<'tcx> LateLintPass<'tcx> for ImplicitSaturatingSub {
|
||||
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
|
||||
if in_macro(expr.span) {
|
||||
if expr.span.from_expansion() {
|
||||
return;
|
||||
}
|
||||
if_chain! {
|
||||
|
@ -1,5 +1,4 @@
|
||||
use clippy_utils::diagnostics::span_lint_and_sugg;
|
||||
use clippy_utils::in_macro;
|
||||
use clippy_utils::source::snippet;
|
||||
use if_chain::if_chain;
|
||||
use rustc_data_structures::fx::FxHashMap;
|
||||
@ -56,6 +55,7 @@ declare_clippy_lint! {
|
||||
/// # let y = 2;
|
||||
/// Foo { x, y };
|
||||
/// ```
|
||||
#[clippy::version = "1.52.0"]
|
||||
pub INCONSISTENT_STRUCT_CONSTRUCTOR,
|
||||
pedantic,
|
||||
"the order of the field init shorthand is inconsistent with the order in the struct definition"
|
||||
@ -66,7 +66,7 @@ declare_lint_pass!(InconsistentStructConstructor => [INCONSISTENT_STRUCT_CONSTRU
|
||||
impl LateLintPass<'_> for InconsistentStructConstructor {
|
||||
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
|
||||
if_chain! {
|
||||
if !in_macro(expr.span);
|
||||
if !expr.span.from_expansion();
|
||||
if let ExprKind::Struct(qpath, fields, base) = expr.kind;
|
||||
let ty = cx.typeck_results().expr_ty(expr);
|
||||
if let Some(adt_def) = ty.ty_adt_def();
|
||||
|
276
clippy_lints/src/index_refutable_slice.rs
Normal file
276
clippy_lints/src/index_refutable_slice.rs
Normal file
@ -0,0 +1,276 @@
|
||||
use clippy_utils::consts::{constant, Constant};
|
||||
use clippy_utils::diagnostics::span_lint_and_then;
|
||||
use clippy_utils::higher::IfLet;
|
||||
use clippy_utils::ty::is_copy;
|
||||
use clippy_utils::{is_expn_of, is_lint_allowed, meets_msrv, msrvs, path_to_local};
|
||||
use if_chain::if_chain;
|
||||
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
|
||||
use rustc_errors::Applicability;
|
||||
use rustc_hir as hir;
|
||||
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
|
||||
use rustc_lint::{LateContext, LateLintPass, LintContext};
|
||||
use rustc_middle::hir::map::Map;
|
||||
use rustc_middle::ty;
|
||||
use rustc_semver::RustcVersion;
|
||||
use rustc_session::{declare_tool_lint, impl_lint_pass};
|
||||
use rustc_span::{symbol::Ident, Span};
|
||||
use std::convert::TryInto;
|
||||
|
||||
declare_clippy_lint! {
|
||||
/// ### What it does
|
||||
/// The lint checks for slice bindings in patterns that are only used to
|
||||
/// access individual slice values.
|
||||
///
|
||||
/// ### Why is this bad?
|
||||
/// Accessing slice values using indices can lead to panics. Using refutable
|
||||
/// patterns can avoid these. Binding to individual values also improves the
|
||||
/// readability as they can be named.
|
||||
///
|
||||
/// ### Limitations
|
||||
/// This lint currently only checks for immutable access inside `if let`
|
||||
/// patterns.
|
||||
///
|
||||
/// ### Example
|
||||
/// ```rust
|
||||
/// let slice: Option<&[u32]> = Some(&[1, 2, 3]);
|
||||
///
|
||||
/// if let Some(slice) = slice {
|
||||
/// println!("{}", slice[0]);
|
||||
/// }
|
||||
/// ```
|
||||
/// Use instead:
|
||||
/// ```rust
|
||||
/// let slice: Option<&[u32]> = Some(&[1, 2, 3]);
|
||||
///
|
||||
/// if let Some(&[first, ..]) = slice {
|
||||
/// println!("{}", first);
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.58.0"]
|
||||
pub INDEX_REFUTABLE_SLICE,
|
||||
nursery,
|
||||
"avoid indexing on slices which could be destructed"
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct IndexRefutableSlice {
|
||||
max_suggested_slice: u64,
|
||||
msrv: Option<RustcVersion>,
|
||||
}
|
||||
|
||||
impl IndexRefutableSlice {
|
||||
pub fn new(max_suggested_slice_pattern_length: u64, msrv: Option<RustcVersion>) -> Self {
|
||||
Self {
|
||||
max_suggested_slice: max_suggested_slice_pattern_length,
|
||||
msrv,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl_lint_pass!(IndexRefutableSlice => [INDEX_REFUTABLE_SLICE]);
|
||||
|
||||
impl LateLintPass<'_> for IndexRefutableSlice {
|
||||
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
|
||||
if_chain! {
|
||||
if !expr.span.from_expansion() || is_expn_of(expr.span, "if_chain").is_some();
|
||||
if let Some(IfLet {let_pat, if_then, ..}) = IfLet::hir(cx, expr);
|
||||
if !is_lint_allowed(cx, INDEX_REFUTABLE_SLICE, expr.hir_id);
|
||||
if meets_msrv(self.msrv.as_ref(), &msrvs::SLICE_PATTERNS);
|
||||
|
||||
let found_slices = find_slice_values(cx, let_pat);
|
||||
if !found_slices.is_empty();
|
||||
let filtered_slices = filter_lintable_slices(cx, found_slices, self.max_suggested_slice, if_then);
|
||||
if !filtered_slices.is_empty();
|
||||
then {
|
||||
for slice in filtered_slices.values() {
|
||||
lint_slice(cx, slice);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extract_msrv_attr!(LateContext);
|
||||
}
|
||||
|
||||
fn find_slice_values(cx: &LateContext<'_>, pat: &hir::Pat<'_>) -> FxHashMap<hir::HirId, SliceLintInformation> {
|
||||
let mut removed_pat: FxHashSet<hir::HirId> = FxHashSet::default();
|
||||
let mut slices: FxHashMap<hir::HirId, SliceLintInformation> = FxHashMap::default();
|
||||
pat.walk_always(|pat| {
|
||||
if let hir::PatKind::Binding(binding, value_hir_id, ident, sub_pat) = pat.kind {
|
||||
// We'll just ignore mut and ref mut for simplicity sake right now
|
||||
if let hir::BindingAnnotation::Mutable | hir::BindingAnnotation::RefMut = binding {
|
||||
return;
|
||||
}
|
||||
|
||||
// This block catches bindings with sub patterns. It would be hard to build a correct suggestion
|
||||
// for them and it's likely that the user knows what they are doing in such a case.
|
||||
if removed_pat.contains(&value_hir_id) {
|
||||
return;
|
||||
}
|
||||
if sub_pat.is_some() {
|
||||
removed_pat.insert(value_hir_id);
|
||||
slices.remove(&value_hir_id);
|
||||
return;
|
||||
}
|
||||
|
||||
let bound_ty = cx.typeck_results().node_type(pat.hir_id);
|
||||
if let ty::Slice(inner_ty) | ty::Array(inner_ty, _) = bound_ty.peel_refs().kind() {
|
||||
// The values need to use the `ref` keyword if they can't be copied.
|
||||
// This will need to be adjusted if the lint want to support multable access in the future
|
||||
let src_is_ref = bound_ty.is_ref() && binding != hir::BindingAnnotation::Ref;
|
||||
let needs_ref = !(src_is_ref || is_copy(cx, inner_ty));
|
||||
|
||||
let slice_info = slices
|
||||
.entry(value_hir_id)
|
||||
.or_insert_with(|| SliceLintInformation::new(ident, needs_ref));
|
||||
slice_info.pattern_spans.push(pat.span);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
slices
|
||||
}
|
||||
|
||||
fn lint_slice(cx: &LateContext<'_>, slice: &SliceLintInformation) {
|
||||
let used_indices = slice
|
||||
.index_use
|
||||
.iter()
|
||||
.map(|(index, _)| *index)
|
||||
.collect::<FxHashSet<_>>();
|
||||
|
||||
let value_name = |index| format!("{}_{}", slice.ident.name, index);
|
||||
|
||||
if let Some(max_index) = used_indices.iter().max() {
|
||||
let opt_ref = if slice.needs_ref { "ref " } else { "" };
|
||||
let pat_sugg_idents = (0..=*max_index)
|
||||
.map(|index| {
|
||||
if used_indices.contains(&index) {
|
||||
format!("{}{}", opt_ref, value_name(index))
|
||||
} else {
|
||||
"_".to_string()
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let pat_sugg = format!("[{}, ..]", pat_sugg_idents.join(", "));
|
||||
|
||||
span_lint_and_then(
|
||||
cx,
|
||||
INDEX_REFUTABLE_SLICE,
|
||||
slice.ident.span,
|
||||
"this binding can be a slice pattern to avoid indexing",
|
||||
|diag| {
|
||||
diag.multipart_suggestion(
|
||||
"try using a slice pattern here",
|
||||
slice
|
||||
.pattern_spans
|
||||
.iter()
|
||||
.map(|span| (*span, pat_sugg.clone()))
|
||||
.collect(),
|
||||
Applicability::MaybeIncorrect,
|
||||
);
|
||||
|
||||
diag.multipart_suggestion(
|
||||
"and replace the index expressions here",
|
||||
slice
|
||||
.index_use
|
||||
.iter()
|
||||
.map(|(index, span)| (*span, value_name(*index)))
|
||||
.collect(),
|
||||
Applicability::MaybeIncorrect,
|
||||
);
|
||||
|
||||
// The lint message doesn't contain a warning about the removed index expression,
|
||||
// since `filter_lintable_slices` will only return slices where all access indices
|
||||
// are known at compile time. Therefore, they can be removed without side effects.
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SliceLintInformation {
|
||||
ident: Ident,
|
||||
needs_ref: bool,
|
||||
pattern_spans: Vec<Span>,
|
||||
index_use: Vec<(u64, Span)>,
|
||||
}
|
||||
|
||||
impl SliceLintInformation {
|
||||
fn new(ident: Ident, needs_ref: bool) -> Self {
|
||||
Self {
|
||||
ident,
|
||||
needs_ref,
|
||||
pattern_spans: Vec::new(),
|
||||
index_use: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn filter_lintable_slices<'a, 'tcx>(
|
||||
cx: &'a LateContext<'tcx>,
|
||||
slice_lint_info: FxHashMap<hir::HirId, SliceLintInformation>,
|
||||
max_suggested_slice: u64,
|
||||
scope: &'tcx hir::Expr<'tcx>,
|
||||
) -> FxHashMap<hir::HirId, SliceLintInformation> {
|
||||
let mut visitor = SliceIndexLintingVisitor {
|
||||
cx,
|
||||
slice_lint_info,
|
||||
max_suggested_slice,
|
||||
};
|
||||
|
||||
intravisit::walk_expr(&mut visitor, scope);
|
||||
|
||||
visitor.slice_lint_info
|
||||
}
|
||||
|
||||
struct SliceIndexLintingVisitor<'a, 'tcx> {
|
||||
cx: &'a LateContext<'tcx>,
|
||||
slice_lint_info: FxHashMap<hir::HirId, SliceLintInformation>,
|
||||
max_suggested_slice: u64,
|
||||
}
|
||||
|
||||
impl<'a, 'tcx> Visitor<'tcx> for SliceIndexLintingVisitor<'a, 'tcx> {
|
||||
type Map = Map<'tcx>;
|
||||
|
||||
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
|
||||
NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
|
||||
}
|
||||
|
||||
fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
|
||||
if let Some(local_id) = path_to_local(expr) {
|
||||
let Self {
|
||||
cx,
|
||||
ref mut slice_lint_info,
|
||||
max_suggested_slice,
|
||||
} = *self;
|
||||
|
||||
if_chain! {
|
||||
// Check if this is even a local we're interested in
|
||||
if let Some(use_info) = slice_lint_info.get_mut(&local_id);
|
||||
|
||||
let map = cx.tcx.hir();
|
||||
|
||||
// Checking for slice indexing
|
||||
let parent_id = map.get_parent_node(expr.hir_id);
|
||||
if let Some(hir::Node::Expr(parent_expr)) = map.find(parent_id);
|
||||
if let hir::ExprKind::Index(_, index_expr) = parent_expr.kind;
|
||||
if let Some((Constant::Int(index_value), _)) = constant(cx, cx.typeck_results(), index_expr);
|
||||
if let Ok(index_value) = index_value.try_into();
|
||||
if index_value < max_suggested_slice;
|
||||
|
||||
// Make sure that this slice index is read only
|
||||
let maybe_addrof_id = map.get_parent_node(parent_id);
|
||||
if let Some(hir::Node::Expr(maybe_addrof_expr)) = map.find(maybe_addrof_id);
|
||||
if let hir::ExprKind::AddrOf(_kind, hir::Mutability::Not, _inner_expr) = maybe_addrof_expr.kind;
|
||||
then {
|
||||
use_info.index_use.push((index_value, map.span(parent_expr.hir_id)));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// The slice was used for something other than indexing
|
||||
self.slice_lint_info.remove(&local_id);
|
||||
}
|
||||
intravisit::walk_expr(self, expr);
|
||||
}
|
||||
}
|
@ -33,6 +33,7 @@ declare_clippy_lint! {
|
||||
/// x[0];
|
||||
/// x[3];
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub OUT_OF_BOUNDS_INDEXING,
|
||||
correctness,
|
||||
"out of bounds constant indexing"
|
||||
@ -85,6 +86,7 @@ declare_clippy_lint! {
|
||||
/// y.get(10..);
|
||||
/// y.get(..100);
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub INDEXING_SLICING,
|
||||
restriction,
|
||||
"indexing/slicing usage"
|
||||
|
@ -20,6 +20,7 @@ declare_clippy_lint! {
|
||||
///
|
||||
/// iter::repeat(1_u8).collect::<Vec<_>>();
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub INFINITE_ITER,
|
||||
correctness,
|
||||
"infinite iteration"
|
||||
@ -42,6 +43,7 @@ declare_clippy_lint! {
|
||||
/// let infinite_iter = 0..;
|
||||
/// [0..].iter().zip(infinite_iter.take_while(|x| *x > 5));
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub MAYBE_INFINITE_ITER,
|
||||
pedantic,
|
||||
"possible infinite iteration"
|
||||
|
@ -1,7 +1,7 @@
|
||||
//! lint on inherent implementations
|
||||
|
||||
use clippy_utils::diagnostics::span_lint_and_note;
|
||||
use clippy_utils::{in_macro, is_lint_allowed};
|
||||
use clippy_utils::is_lint_allowed;
|
||||
use rustc_data_structures::fx::FxHashMap;
|
||||
use rustc_hir::{def_id::LocalDefId, Item, ItemKind, Node};
|
||||
use rustc_lint::{LateContext, LateLintPass};
|
||||
@ -36,6 +36,7 @@ declare_clippy_lint! {
|
||||
/// fn other() {}
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub MULTIPLE_INHERENT_IMPL,
|
||||
restriction,
|
||||
"Multiple inherent impl that could be grouped"
|
||||
@ -123,7 +124,9 @@ fn get_impl_span(cx: &LateContext<'_>, id: LocalDefId) -> Option<Span> {
|
||||
..
|
||||
}) = cx.tcx.hir().get(id)
|
||||
{
|
||||
(!in_macro(span) && impl_item.generics.params.is_empty() && !is_lint_allowed(cx, MULTIPLE_INHERENT_IMPL, id))
|
||||
(!span.from_expansion()
|
||||
&& impl_item.generics.params.is_empty()
|
||||
&& !is_lint_allowed(cx, MULTIPLE_INHERENT_IMPL, id))
|
||||
.then(|| span)
|
||||
} else {
|
||||
None
|
||||
|
@ -41,6 +41,7 @@ declare_clippy_lint! {
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.38.0"]
|
||||
pub INHERENT_TO_STRING,
|
||||
style,
|
||||
"type implements inherent method `to_string()`, but should instead implement the `Display` trait"
|
||||
@ -88,6 +89,7 @@ declare_clippy_lint! {
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "1.38.0"]
|
||||
pub INHERENT_TO_STRING_SHADOW_DISPLAY,
|
||||
correctness,
|
||||
"type implements inherent method `to_string()`, which gets shadowed by the implementation of the `Display` trait"
|
||||
|
@ -24,6 +24,7 @@ declare_clippy_lint! {
|
||||
/// fn name(&self) -> &'static str;
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub INLINE_FN_WITHOUT_BODY,
|
||||
correctness,
|
||||
"use of `#[inline]` on trait methods without bodies"
|
||||
|
@ -28,6 +28,7 @@ declare_clippy_lint! {
|
||||
/// # let y = 1;
|
||||
/// if x > y {}
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub INT_PLUS_ONE,
|
||||
complexity,
|
||||
"instead of using `x >= y + 1`, use `x > y`"
|
||||
|
@ -23,6 +23,7 @@ declare_clippy_lint! {
|
||||
/// let x = 3f32 / 2f32;
|
||||
/// println!("{}", x);
|
||||
/// ```
|
||||
#[clippy::version = "1.37.0"]
|
||||
pub INTEGER_DIVISION,
|
||||
restriction,
|
||||
"integer division may cause loss of precision"
|
||||
|
@ -30,6 +30,7 @@ declare_clippy_lint! {
|
||||
/// let x: u8 = 1;
|
||||
/// (x as u32) > 300;
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub INVALID_UPCAST_COMPARISONS,
|
||||
pedantic,
|
||||
"a comparison involving an upcast which is always true or false"
|
||||
|
@ -45,6 +45,7 @@ declare_clippy_lint! {
|
||||
/// foo(); // prints "foo"
|
||||
/// }
|
||||
/// ```
|
||||
#[clippy::version = "pre 1.29.0"]
|
||||
pub ITEMS_AFTER_STATEMENTS,
|
||||
pedantic,
|
||||
"blocks where an item comes after a statement"
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user