rust-clippy/clippy_lints/src/entry.rs

186 lines
6.6 KiB
Rust
Raw Normal View History

2019-05-14 08:06:21 +00:00
use crate::utils::SpanlessEq;
use crate::utils::{get_item_name, higher, match_type, paths, snippet, snippet_opt};
use crate::utils::{snippet_with_applicability, span_lint_and_then, walk_ptrs_ty};
2018-11-27 20:14:15 +00:00
use if_chain::if_chain;
2019-12-03 23:16:03 +00:00
use rustc::declare_lint_pass;
use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
use rustc::hir::*;
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
use rustc_errors::Applicability;
2019-12-03 23:16:03 +00:00
use rustc_session::declare_tool_lint;
use rustc_span::source_map::Span;
2015-12-21 23:35:56 +00:00
2018-03-28 13:24:26 +00:00
declare_clippy_lint! {
/// **What it does:** Checks for uses of `contains_key` + `insert` on `HashMap`
/// or `BTreeMap`.
///
/// **Why is this bad?** Using `entry` is more efficient.
///
/// **Known problems:** Some false negatives, eg.:
/// ```rust
/// # use std::collections::HashMap;
/// # let mut map = HashMap::new();
/// # let v = 1;
/// # let k = 1;
/// if !map.contains_key(&k) {
/// map.insert(k.clone(), v);
/// }
/// ```
///
/// **Example:**
/// ```rust
/// # use std::collections::HashMap;
/// # let mut map = HashMap::new();
/// # let k = 1;
/// # let v = 1;
/// if !map.contains_key(&k) {
/// map.insert(k, v);
/// }
/// ```
/// can both be rewritten as:
/// ```rust
/// # use std::collections::HashMap;
/// # let mut map = HashMap::new();
/// # let k = 1;
/// # let v = 1;
/// map.entry(k).or_insert(v);
/// ```
pub MAP_ENTRY,
2018-03-28 13:24:26 +00:00
perf,
"use of `contains_key` followed by `insert` on a `HashMap` or `BTreeMap`"
2015-12-21 23:35:56 +00:00
}
2019-04-08 20:43:55 +00:00
declare_lint_pass!(HashMapPass => [MAP_ENTRY]);
2015-12-21 23:35:56 +00:00
2019-04-08 20:43:55 +00:00
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for HashMapPass {
2019-12-27 07:12:26 +00:00
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
2019-05-11 02:34:47 +00:00
if let Some((ref check, ref then_block, ref else_block)) = higher::if_block(&expr) {
2019-09-27 15:16:06 +00:00
if let ExprKind::Unary(UnOp::UnNot, ref check) = check.kind {
if let Some((ty, map, key)) = check_cond(cx, check) {
// in case of `if !m.contains_key(&k) { m.insert(k, v); }`
// we can give a better error message
2017-04-12 09:06:32 +00:00
let sole_expr = {
2018-11-27 20:14:15 +00:00
else_block.is_none()
2019-09-27 15:16:06 +00:00
&& if let ExprKind::Block(ref then_block, _) = then_block.kind {
2018-11-27 20:14:15 +00:00
(then_block.expr.is_some() as usize) + then_block.stmts.len() == 1
} else {
true
}
// XXXManishearth we can also check for if/else blocks containing `None`.
};
let mut visitor = InsertVisitor {
cx,
span: expr.span,
ty,
map,
key,
sole_expr,
};
2016-01-03 15:31:28 +00:00
walk_expr(&mut visitor, &**then_block);
}
} else if let Some(ref else_block) = *else_block {
if let Some((ty, map, key)) = check_cond(cx, check) {
let mut visitor = InsertVisitor {
cx,
span: expr.span,
ty,
map,
key,
sole_expr: false,
};
walk_expr(&mut visitor, else_block);
2015-12-21 23:35:56 +00:00
}
}
}
}
}
fn check_cond<'a, 'tcx, 'b>(
cx: &'a LateContext<'a, 'tcx>,
2019-12-27 07:12:26 +00:00
check: &'b Expr<'b>,
) -> Option<(&'static str, &'b Expr<'b>, &'b Expr<'b>)> {
if_chain! {
2019-09-27 15:16:06 +00:00
if let ExprKind::MethodCall(ref path, _, ref params) = check.kind;
if params.len() >= 2;
2019-05-17 21:53:54 +00:00
if path.ident.name == sym!(contains_key);
2019-11-27 22:30:10 +00:00
if let ExprKind::AddrOf(BorrowKind::Ref, _, ref key) = params[1].kind;
then {
let map = &params[0];
let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(map));
2017-11-04 19:55:56 +00:00
2019-05-17 21:53:54 +00:00
return if match_type(cx, obj_ty, &paths::BTREEMAP) {
Some(("BTreeMap", map, key))
}
2019-05-17 21:53:54 +00:00
else if match_type(cx, obj_ty, &paths::HASHMAP) {
Some(("HashMap", map, key))
}
else {
None
};
}
}
None
}
struct InsertVisitor<'a, 'tcx, 'b> {
cx: &'a LateContext<'a, 'tcx>,
span: Span,
ty: &'static str,
2019-12-27 07:12:26 +00:00
map: &'b Expr<'b>,
key: &'b Expr<'b>,
sole_expr: bool,
}
impl<'a, 'tcx, 'b> Visitor<'tcx> for InsertVisitor<'a, 'tcx, 'b> {
2019-12-27 07:12:26 +00:00
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
if_chain! {
2019-09-27 15:16:06 +00:00
if let ExprKind::MethodCall(ref path, _, ref params) = expr.kind;
if params.len() == 3;
2019-05-17 21:53:54 +00:00
if path.ident.name == sym!(insert);
if get_item_name(self.cx, self.map) == get_item_name(self.cx, &params[0]);
if SpanlessEq::new(self.cx).eq_expr(self.key, &params[1]);
2019-09-03 00:41:37 +00:00
if snippet_opt(self.cx, self.map.span) == snippet_opt(self.cx, params[0].span);
then {
span_lint_and_then(self.cx, MAP_ENTRY, self.span,
&format!("usage of `contains_key` followed by `insert` on a `{}`", self.ty), |db| {
if self.sole_expr {
let mut app = Applicability::MachineApplicable;
let help = format!("{}.entry({}).or_insert({});",
snippet_with_applicability(self.cx, self.map.span, "map", &mut app),
snippet_with_applicability(self.cx, params[1].span, "..", &mut app),
snippet_with_applicability(self.cx, params[2].span, "..", &mut app));
2017-11-04 19:55:56 +00:00
db.span_suggestion(
2018-09-18 15:07:54 +00:00
self.span,
"consider using",
help,
Applicability::MachineApplicable, // snippet
2018-09-18 15:07:54 +00:00
);
}
else {
let help = format!("consider using `{}.entry({})`",
snippet(self.cx, self.map.span, "map"),
snippet(self.cx, params[1].span, ".."));
2017-11-04 19:55:56 +00:00
db.span_label(
2018-09-18 15:07:54 +00:00
self.span,
&help,
2018-09-18 15:07:54 +00:00
);
}
});
}
}
if !self.sole_expr {
walk_expr(self, expr);
2015-12-21 23:35:56 +00:00
}
}
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
NestedVisitorMap::None
}
2015-12-21 23:35:56 +00:00
}