rust-clippy/clippy_lints/src/suspicious_trait_impl.rs

124 lines
4.3 KiB
Rust
Raw Normal View History

use clippy_utils::diagnostics::span_lint;
2021-07-16 19:41:19 +00:00
use clippy_utils::{binop_traits, trait_ref_of_method, BINOP_TRAITS, OP_ASSIGN_TRAITS};
2018-11-27 20:14:15 +00:00
use if_chain::if_chain;
2020-01-06 16:39:50 +00:00
use rustc_hir as hir;
2020-01-09 07:13:22 +00:00
use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
2020-01-12 06:08:41 +00:00
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::hir::map::Map;
2020-01-11 11:37:08 +00:00
use rustc_session::{declare_lint_pass, declare_tool_lint};
2018-03-28 13:24:26 +00:00
declare_clippy_lint! {
/// ### What it does
/// Lints for suspicious operations in impls of arithmetic operators, e.g.
/// subtracting elements in an Add impl.
///
/// ### Why is this bad?
/// This is probably a typo or copy-and-paste error and not intended.
///
/// ### Example
2019-03-05 22:23:50 +00:00
/// ```ignore
/// impl Add for Foo {
/// type Output = Foo;
///
/// fn add(self, other: Foo) -> Foo {
/// Foo(self.0 - other.0)
/// }
/// }
/// ```
Added `clippy::version` attribute to all normal lints So, some context for this, well, more a story. I'm not used to scripting, I've never really scripted anything, even if it's a valuable skill. I just never really needed it. Now, `@flip1995` correctly suggested using a script for this in `rust-clippy#7813`... And I decided to write a script using nushell because why not? This was a mistake... I spend way more time on this than I would like to admit. It has definitely been more than 4 hours. It shouldn't take that long, but me being new to scripting and nushell just wasn't a good mixture... Anyway, here is the script that creates another script which adds the versions. Fun... Just execute this on the `gh-pages` branch and the resulting `replacer.sh` in `clippy_lints` and it should all work. ```nu mv v0.0.212 rust-1.00.0; mv beta rust-1.57.0; mv master rust-1.58.0; let paths = (open ./rust-1.58.0/lints.json | select id id_span | flatten | select id path); let versions = ( ls | where name =~ "rust-" | select name | format {name}/lints.json | each { open $it | select id | insert version $it | str substring "5,11" version} | group-by id | rotate counter-clockwise id version | update version {get version | first 1} | flatten | select id version); $paths | each { |row| let version = ($versions | where id == ($row.id) | format {version}) let idu = ($row.id | str upcase) $"sed -i '0,/($idu),/{s/pub ($idu),/#[clippy::version = "($version)"]\n pub ($idu),/}' ($row.path)" } | str collect ";" | str find-replace --all '1.00.0' 'pre 1.29.0' | save "replacer.sh"; ``` And this still has some problems, but at this point I just want to be done -.-
2021-10-21 19:06:26 +00:00
#[clippy::version = "pre 1.29.0"]
pub SUSPICIOUS_ARITHMETIC_IMPL,
2021-06-14 19:09:17 +00:00
suspicious,
"suspicious use of operators in impl of arithmetic trait"
}
2018-03-28 13:24:26 +00:00
declare_clippy_lint! {
/// ### What it does
/// Lints for suspicious operations in impls of OpAssign, e.g.
/// subtracting elements in an AddAssign impl.
///
/// ### Why is this bad?
/// This is probably a typo or copy-and-paste error and not intended.
///
/// ### Example
2019-03-05 22:23:50 +00:00
/// ```ignore
/// impl AddAssign for Foo {
/// fn add_assign(&mut self, other: Foo) {
/// *self = *self - other;
/// }
/// }
/// ```
Added `clippy::version` attribute to all normal lints So, some context for this, well, more a story. I'm not used to scripting, I've never really scripted anything, even if it's a valuable skill. I just never really needed it. Now, `@flip1995` correctly suggested using a script for this in `rust-clippy#7813`... And I decided to write a script using nushell because why not? This was a mistake... I spend way more time on this than I would like to admit. It has definitely been more than 4 hours. It shouldn't take that long, but me being new to scripting and nushell just wasn't a good mixture... Anyway, here is the script that creates another script which adds the versions. Fun... Just execute this on the `gh-pages` branch and the resulting `replacer.sh` in `clippy_lints` and it should all work. ```nu mv v0.0.212 rust-1.00.0; mv beta rust-1.57.0; mv master rust-1.58.0; let paths = (open ./rust-1.58.0/lints.json | select id id_span | flatten | select id path); let versions = ( ls | where name =~ "rust-" | select name | format {name}/lints.json | each { open $it | select id | insert version $it | str substring "5,11" version} | group-by id | rotate counter-clockwise id version | update version {get version | first 1} | flatten | select id version); $paths | each { |row| let version = ($versions | where id == ($row.id) | format {version}) let idu = ($row.id | str upcase) $"sed -i '0,/($idu),/{s/pub ($idu),/#[clippy::version = "($version)"]\n pub ($idu),/}' ($row.path)" } | str collect ";" | str find-replace --all '1.00.0' 'pre 1.29.0' | save "replacer.sh"; ``` And this still has some problems, but at this point I just want to be done -.-
2021-10-21 19:06:26 +00:00
#[clippy::version = "pre 1.29.0"]
pub SUSPICIOUS_OP_ASSIGN_IMPL,
2021-06-14 19:09:17 +00:00
suspicious,
"suspicious use of operators in impl of OpAssign trait"
}
2019-04-08 20:43:55 +00:00
declare_lint_pass!(SuspiciousImpl => [SUSPICIOUS_ARITHMETIC_IMPL, SUSPICIOUS_OP_ASSIGN_IMPL]);
impl<'tcx> LateLintPass<'tcx> for SuspiciousImpl {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
2021-07-16 19:41:19 +00:00
if_chain! {
if let hir::ExprKind::Binary(binop, _, _) | hir::ExprKind::AssignOp(binop, ..) = expr.kind;
if let Some((binop_trait_lang, op_assign_trait_lang)) = binop_traits(binop.node);
if let Ok(binop_trait_id) = cx.tcx.lang_items().require(binop_trait_lang);
if let Ok(op_assign_trait_id) = cx.tcx.lang_items().require(op_assign_trait_lang);
// Check for more than one binary operation in the implemented function
// Linting when multiple operations are involved can result in false positives
2021-03-30 19:59:59 +00:00
let parent_fn = cx.tcx.hir().get_parent_item(expr.hir_id);
2021-07-16 19:41:19 +00:00
if let hir::Node::ImplItem(impl_item) = cx.tcx.hir().get(parent_fn);
if let hir::ImplItemKind::Fn(_, body_id) = impl_item.kind;
let body = cx.tcx.hir().body(body_id);
let parent_fn = cx.tcx.hir().get_parent_item(expr.hir_id);
if let Some(trait_ref) = trait_ref_of_method(cx, parent_fn);
let trait_id = trait_ref.path.res.def_id();
if ![binop_trait_id, op_assign_trait_id].contains(&trait_id);
if let Some(&(_, lint)) = [
(&BINOP_TRAITS, SUSPICIOUS_ARITHMETIC_IMPL),
(&OP_ASSIGN_TRAITS, SUSPICIOUS_OP_ASSIGN_IMPL),
]
.iter()
.find(|&(ts, _)| ts.iter().any(|&t| Ok(trait_id) == cx.tcx.lang_items().require(t)));
if count_binops(&body.value) == 1;
then {
span_lint(
cx,
2021-07-16 19:41:19 +00:00
lint,
binop.span,
2021-07-16 19:41:19 +00:00
&format!("suspicious use of `{}` in `{}` impl", binop.node.as_str(), cx.tcx.item_name(trait_id)),
);
}
}
}
}
2021-07-16 19:41:19 +00:00
fn count_binops(expr: &hir::Expr<'_>) -> u32 {
let mut visitor = BinaryExprVisitor::default();
visitor.visit_expr(expr);
visitor.nb_binops
}
2021-07-16 19:41:19 +00:00
#[derive(Default)]
struct BinaryExprVisitor {
nb_binops: u32,
}
impl<'tcx> Visitor<'tcx> for BinaryExprVisitor {
2020-01-09 07:13:22 +00:00
type Map = Map<'tcx>;
2019-12-27 07:12:26 +00:00
fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
2019-09-27 15:16:06 +00:00
match expr.kind {
2018-07-12 07:30:57 +00:00
hir::ExprKind::Binary(..)
| hir::ExprKind::Unary(hir::UnOp::Not | hir::UnOp::Neg, _)
| hir::ExprKind::AssignOp(..) => self.nb_binops += 1,
_ => {},
}
walk_expr(self, expr);
}
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
NestedVisitorMap::None
}
}