1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 use crate::rustc::hir::def_id::DefId;
12 use crate::rustc::hir::*;
13 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
14 use crate::rustc::{declare_tool_lint, lint_array};
16 use crate::rustc_data_structures::fx::FxHashSet;
17 use crate::syntax::ast::{Lit, LitKind, Name};
18 use crate::syntax::source_map::{Span, Spanned};
19 use crate::utils::{get_item_name, in_macro, snippet, span_lint, span_lint_and_sugg, walk_ptrs_ty};
21 /// **What it does:** Checks for getting the length of something via `.len()`
22 /// just to compare to zero, and suggests using `.is_empty()` where applicable.
24 /// **Why is this bad?** Some structures can answer `.is_empty()` much faster
25 /// than calculating their length. Notably, for slices, getting the length
26 /// requires a subtraction whereas `.is_empty()` is just a comparison. So it is
27 /// good to get into the habit of using `.is_empty()`, and having it is cheap.
28 /// Besides, it makes the intent clearer than a manual comparison.
30 /// **Known problems:** None.
34 /// if x.len() == 0 { .. }
35 /// if y.len() != 0 { .. }
39 /// if x.len().is_empty() { .. }
40 /// if !y.len().is_empty() { .. }
42 declare_clippy_lint! {
45 "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` \
46 could be used instead"
49 /// **What it does:** Checks for items that implement `.len()` but not
52 /// **Why is this bad?** It is good custom to have both methods, because for
53 /// some data structures, asking about the length will be a costly operation,
54 /// whereas `.is_empty()` can usually answer in constant time. Also it used to
55 /// lead to false positives on the [`len_zero`](#len_zero) lint – currently that
56 /// lint will ignore such entities.
58 /// **Known problems:** None.
63 /// pub fn len(&self) -> usize { .. }
66 declare_clippy_lint! {
67 pub LEN_WITHOUT_IS_EMPTY,
69 "traits or impls with a public `len` method but no corresponding `is_empty` method"
72 #[derive(Copy, Clone)]
75 impl LintPass for LenZero {
76 fn get_lints(&self) -> LintArray {
77 lint_array!(LEN_ZERO, LEN_WITHOUT_IS_EMPTY)
81 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LenZero {
82 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
83 if in_macro(item.span) {
88 ItemKind::Trait(_, _, _, _, ref trait_items) => check_trait_items(cx, item, trait_items),
89 ItemKind::Impl(_, _, _, _, None, _, ref impl_items) => check_impl_items(cx, item, impl_items),
94 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
95 if in_macro(expr.span) {
99 if let ExprKind::Binary(Spanned { node: cmp, .. }, ref left, ref right) = expr.node {
102 check_cmp(cx, expr.span, left, right, "", 0); // len == 0
103 check_cmp(cx, expr.span, right, left, "", 0); // 0 == len
106 check_cmp(cx, expr.span, left, right, "!", 0); // len != 0
107 check_cmp(cx, expr.span, right, left, "!", 0); // 0 != len
110 check_cmp(cx, expr.span, left, right, "!", 0); // len > 0
111 check_cmp(cx, expr.span, right, left, "", 1); // 1 > len
114 check_cmp(cx, expr.span, left, right, "", 1); // len < 1
115 check_cmp(cx, expr.span, right, left, "!", 0); // 0 < len
117 BinOpKind::Ge => check_cmp(cx, expr.span, left, right, "!", 1), // len <= 1
118 BinOpKind::Le => check_cmp(cx, expr.span, right, left, "!", 1), // 1 >= len
125 fn check_trait_items(cx: &LateContext<'_, '_>, visited_trait: &Item, trait_items: &[TraitItemRef]) {
126 fn is_named_self(cx: &LateContext<'_, '_>, item: &TraitItemRef, name: &str) -> bool {
127 item.ident.name == name && if let AssociatedItemKind::Method { has_self } = item.kind {
129 let did = cx.tcx.hir.local_def_id(item.id.node_id);
130 cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
137 // fill the set with current and super traits
138 fn fill_trait_set(traitt: DefId, set: &mut FxHashSet<DefId>, cx: &LateContext<'_, '_>) {
139 if set.insert(traitt) {
140 for supertrait in crate::rustc::traits::supertrait_def_ids(cx.tcx, traitt) {
141 fill_trait_set(supertrait, set, cx);
146 if cx.access_levels.is_exported(visited_trait.id) && trait_items.iter().any(|i| is_named_self(cx, i, "len")) {
147 let mut current_and_super_traits = FxHashSet::default();
148 let visited_trait_def_id = cx.tcx.hir.local_def_id(visited_trait.id);
149 fill_trait_set(visited_trait_def_id, &mut current_and_super_traits, cx);
151 let is_empty_method_found = current_and_super_traits
153 .flat_map(|&i| cx.tcx.associated_items(i))
155 i.kind == ty::AssociatedKind::Method && i.method_has_self_argument && i.ident.name == "is_empty"
156 && cx.tcx.fn_sig(i.def_id).inputs().skip_binder().len() == 1
159 if !is_empty_method_found {
162 LEN_WITHOUT_IS_EMPTY,
165 "trait `{}` has a `len` method but no (possibly inherited) `is_empty` method",
173 fn check_impl_items(cx: &LateContext<'_, '_>, item: &Item, impl_items: &[ImplItemRef]) {
174 fn is_named_self(cx: &LateContext<'_, '_>, item: &ImplItemRef, name: &str) -> bool {
175 item.ident.name == name && if let AssociatedItemKind::Method { has_self } = item.kind {
177 let did = cx.tcx.hir.local_def_id(item.id.node_id);
178 cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
185 let is_empty = if let Some(is_empty) = impl_items.iter().find(|i| is_named_self(cx, i, "is_empty")) {
186 if cx.access_levels.is_exported(is_empty.id.node_id) {
195 if let Some(i) = impl_items.iter().find(|i| is_named_self(cx, i, "len")) {
196 if cx.access_levels.is_exported(i.id.node_id) {
197 let def_id = cx.tcx.hir.local_def_id(item.id);
198 let ty = cx.tcx.type_of(def_id);
202 LEN_WITHOUT_IS_EMPTY,
205 "item `{}` has a public `len` method but {} `is_empty` method",
213 fn check_cmp(cx: &LateContext<'_, '_>, span: Span, method: &Expr, lit: &Expr, op: &str, compare_to: u32) {
214 if let (&ExprKind::MethodCall(ref method_path, _, ref args), &ExprKind::Lit(ref lit)) = (&method.node, &lit.node) {
215 // check if we are in an is_empty() method
216 if let Some(name) = get_item_name(cx, method) {
217 if name == "is_empty" {
222 check_len(cx, span, method_path.ident.name, args, lit, op, compare_to)
226 fn check_len(cx: &LateContext<'_, '_>, span: Span, method_name: Name, args: &[Expr], lit: &Lit, op: &str, compare_to: u32) {
228 node: LitKind::Int(lit, _),
232 // check if length is compared to the specified number
233 if lit != u128::from(compare_to) {
237 if method_name == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
242 &format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }),
243 "using `is_empty` is more concise",
244 format!("{}{}.is_empty()", op, snippet(cx, args[0].span, "_")),
250 /// Check if this type has an `is_empty` method.
251 fn has_is_empty(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
252 /// Get an `AssociatedItem` and return true if it matches `is_empty(self)`.
253 fn is_is_empty(cx: &LateContext<'_, '_>, item: &ty::AssociatedItem) -> bool {
254 if let ty::AssociatedKind::Method = item.kind {
255 if item.ident.name == "is_empty" {
256 let sig = cx.tcx.fn_sig(item.def_id);
257 let ty = sig.skip_binder();
258 ty.inputs().len() == 1
267 /// Check the inherent impl's items for an `is_empty(self)` method.
268 fn has_is_empty_impl(cx: &LateContext<'_, '_>, id: DefId) -> bool {
269 cx.tcx.inherent_impls(id).iter().any(|imp| {
271 .associated_items(*imp)
272 .any(|item| is_is_empty(cx, &item))
276 let ty = &walk_ptrs_ty(cx.tables.expr_ty(expr));
278 ty::Dynamic(ref tt, ..) => cx.tcx
279 .associated_items(tt.principal().expect("trait impl not found").def_id())
280 .any(|item| is_is_empty(cx, &item)),
281 ty::Projection(ref proj) => has_is_empty_impl(cx, proj.item_def_id),
282 ty::Adt(id, _) => has_is_empty_impl(cx, id.did),
283 ty::Array(..) | ty::Slice(..) | ty::Str => true,