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.
10 use crate::rustc::hir::def_id::DefId;
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
14 use crate::rustc::{declare_tool_lint, lint_array};
15 use crate::rustc_data_structures::fx::FxHashSet;
16 use crate::rustc_errors::Applicability;
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_with_applicability, 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.
43 /// if x.len().is_empty() {
46 /// if !y.len().is_empty() {
50 declare_clippy_lint! {
53 "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` \
54 could be used instead"
57 /// **What it does:** Checks for items that implement `.len()` but not
60 /// **Why is this bad?** It is good custom to have both methods, because for
61 /// some data structures, asking about the length will be a costly operation,
62 /// whereas `.is_empty()` can usually answer in constant time. Also it used to
63 /// lead to false positives on the [`len_zero`](#len_zero) lint – currently that
64 /// lint will ignore such entities.
66 /// **Known problems:** None.
71 /// pub fn len(&self) -> usize {
76 declare_clippy_lint! {
77 pub LEN_WITHOUT_IS_EMPTY,
79 "traits or impls with a public `len` method but no corresponding `is_empty` method"
82 #[derive(Copy, Clone)]
85 impl LintPass for LenZero {
86 fn get_lints(&self) -> LintArray {
87 lint_array!(LEN_ZERO, LEN_WITHOUT_IS_EMPTY)
91 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LenZero {
92 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
93 if in_macro(item.span) {
98 ItemKind::Trait(_, _, _, _, ref trait_items) => check_trait_items(cx, item, trait_items),
99 ItemKind::Impl(_, _, _, _, None, _, ref impl_items) => check_impl_items(cx, item, impl_items),
104 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
105 if in_macro(expr.span) {
109 if let ExprKind::Binary(Spanned { node: cmp, .. }, ref left, ref right) = expr.node {
112 check_cmp(cx, expr.span, left, right, "", 0); // len == 0
113 check_cmp(cx, expr.span, right, left, "", 0); // 0 == len
116 check_cmp(cx, expr.span, left, right, "!", 0); // len != 0
117 check_cmp(cx, expr.span, right, left, "!", 0); // 0 != len
120 check_cmp(cx, expr.span, left, right, "!", 0); // len > 0
121 check_cmp(cx, expr.span, right, left, "", 1); // 1 > len
124 check_cmp(cx, expr.span, left, right, "", 1); // len < 1
125 check_cmp(cx, expr.span, right, left, "!", 0); // 0 < len
127 BinOpKind::Ge => check_cmp(cx, expr.span, left, right, "!", 1), // len <= 1
128 BinOpKind::Le => check_cmp(cx, expr.span, right, left, "!", 1), // 1 >= len
135 fn check_trait_items(cx: &LateContext<'_, '_>, visited_trait: &Item, trait_items: &[TraitItemRef]) {
136 fn is_named_self(cx: &LateContext<'_, '_>, item: &TraitItemRef, name: &str) -> bool {
137 item.ident.name == name
138 && if let AssociatedItemKind::Method { has_self } = item.kind {
140 let did = cx.tcx.hir().local_def_id(item.id.node_id);
141 cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
148 // fill the set with current and super traits
149 fn fill_trait_set(traitt: DefId, set: &mut FxHashSet<DefId>, cx: &LateContext<'_, '_>) {
150 if set.insert(traitt) {
151 for supertrait in crate::rustc::traits::supertrait_def_ids(cx.tcx, traitt) {
152 fill_trait_set(supertrait, set, cx);
157 if cx.access_levels.is_exported(visited_trait.id) && trait_items.iter().any(|i| is_named_self(cx, i, "len")) {
158 let mut current_and_super_traits = FxHashSet::default();
159 let visited_trait_def_id = cx.tcx.hir().local_def_id(visited_trait.id);
160 fill_trait_set(visited_trait_def_id, &mut current_and_super_traits, cx);
162 let is_empty_method_found = current_and_super_traits
164 .flat_map(|&i| cx.tcx.associated_items(i))
166 i.kind == ty::AssociatedKind::Method
167 && i.method_has_self_argument
168 && i.ident.name == "is_empty"
169 && cx.tcx.fn_sig(i.def_id).inputs().skip_binder().len() == 1
172 if !is_empty_method_found {
175 LEN_WITHOUT_IS_EMPTY,
178 "trait `{}` has a `len` method but no (possibly inherited) `is_empty` method",
186 fn check_impl_items(cx: &LateContext<'_, '_>, item: &Item, impl_items: &[ImplItemRef]) {
187 fn is_named_self(cx: &LateContext<'_, '_>, item: &ImplItemRef, name: &str) -> bool {
188 item.ident.name == name
189 && if let AssociatedItemKind::Method { has_self } = item.kind {
191 let did = cx.tcx.hir().local_def_id(item.id.node_id);
192 cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
199 let is_empty = if let Some(is_empty) = impl_items.iter().find(|i| is_named_self(cx, i, "is_empty")) {
200 if cx.access_levels.is_exported(is_empty.id.node_id) {
209 if let Some(i) = impl_items.iter().find(|i| is_named_self(cx, i, "len")) {
210 if cx.access_levels.is_exported(i.id.node_id) {
211 let def_id = cx.tcx.hir().local_def_id(item.id);
212 let ty = cx.tcx.type_of(def_id);
216 LEN_WITHOUT_IS_EMPTY,
219 "item `{}` has a public `len` method but {} `is_empty` method",
227 fn check_cmp(cx: &LateContext<'_, '_>, span: Span, method: &Expr, lit: &Expr, op: &str, compare_to: u32) {
228 if let (&ExprKind::MethodCall(ref method_path, _, ref args), &ExprKind::Lit(ref lit)) = (&method.node, &lit.node) {
229 // check if we are in an is_empty() method
230 if let Some(name) = get_item_name(cx, method) {
231 if name == "is_empty" {
236 check_len(cx, span, method_path.ident.name, args, lit, op, compare_to)
241 cx: &LateContext<'_, '_>,
250 node: LitKind::Int(lit, _),
254 // check if length is compared to the specified number
255 if lit != u128::from(compare_to) {
259 if method_name == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
260 let mut applicability = Applicability::MachineApplicable;
265 &format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }),
266 "using `is_empty` is clearer and more explicit",
270 snippet_with_applicability(cx, args[0].span, "_", &mut applicability)
278 /// Check if this type has an `is_empty` method.
279 fn has_is_empty(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
280 /// Get an `AssociatedItem` and return true if it matches `is_empty(self)`.
281 fn is_is_empty(cx: &LateContext<'_, '_>, item: &ty::AssociatedItem) -> bool {
282 if let ty::AssociatedKind::Method = item.kind {
283 if item.ident.name == "is_empty" {
284 let sig = cx.tcx.fn_sig(item.def_id);
285 let ty = sig.skip_binder();
286 ty.inputs().len() == 1
295 /// Check the inherent impl's items for an `is_empty(self)` method.
296 fn has_is_empty_impl(cx: &LateContext<'_, '_>, id: DefId) -> bool {
300 .any(|imp| cx.tcx.associated_items(*imp).any(|item| is_is_empty(cx, &item)))
303 let ty = &walk_ptrs_ty(cx.tables.expr_ty(expr));
305 ty::Dynamic(ref tt, ..) => cx
307 .associated_items(tt.principal().def_id())
308 .any(|item| is_is_empty(cx, &item)),
309 ty::Projection(ref proj) => has_is_empty_impl(cx, proj.item_def_id),
310 ty::Adt(id, _) => has_is_empty_impl(cx, id.did),
311 ty::Array(..) | ty::Slice(..) | ty::Str => true,