use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then};
use clippy_utils::source::snippet_with_applicability;
-use clippy_utils::{get_item_name, get_parent_as_impl, is_allowed};
+use clippy_utils::{get_item_name, get_parent_as_impl, is_lint_allowed};
use if_chain::if_chain;
use rustc_ast::ast::LitKind;
use rustc_errors::Applicability;
};
declare_clippy_lint! {
- /// **What it does:** Checks for getting the length of something via `.len()`
+ /// ### What it does
+ /// Checks for getting the length of something via `.len()`
/// just to compare to zero, and suggests using `.is_empty()` where applicable.
///
- /// **Why is this bad?** Some structures can answer `.is_empty()` much faster
+ /// ### Why is this bad?
+ /// Some structures can answer `.is_empty()` much faster
/// than calculating their length. So it is good to get into the habit of using
/// `.is_empty()`, and having it is cheap.
/// Besides, it makes the intent clearer than a manual comparison in some contexts.
///
- /// **Known problems:** None.
- ///
- /// **Example:**
+ /// ### Example
/// ```ignore
/// if x.len() == 0 {
/// ..
/// ..
/// }
/// ```
+ #[clippy::version = "pre 1.29.0"]
pub LEN_ZERO,
style,
"checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` could be used instead"
}
declare_clippy_lint! {
- /// **What it does:** Checks for items that implement `.len()` but not
+ /// ### What it does
+ /// Checks for items that implement `.len()` but not
/// `.is_empty()`.
///
- /// **Why is this bad?** It is good custom to have both methods, because for
+ /// ### Why is this bad?
+ /// It is good custom to have both methods, because for
/// some data structures, asking about the length will be a costly operation,
/// whereas `.is_empty()` can usually answer in constant time. Also it used to
/// lead to false positives on the [`len_zero`](#len_zero) lint – currently that
/// lint will ignore such entities.
///
- /// **Known problems:** None.
- ///
- /// **Example:**
+ /// ### Example
/// ```ignore
/// impl X {
/// pub fn len(&self) -> usize {
/// }
/// }
/// ```
+ #[clippy::version = "pre 1.29.0"]
pub LEN_WITHOUT_IS_EMPTY,
style,
"traits or impls with a public `len` method but no corresponding `is_empty` method"
}
declare_clippy_lint! {
- /// **What it does:** Checks for comparing to an empty slice such as `""` or `[]`,
+ /// ### What it does
+ /// Checks for comparing to an empty slice such as `""` or `[]`,
/// and suggests using `.is_empty()` where applicable.
///
- /// **Why is this bad?** Some structures can answer `.is_empty()` much faster
+ /// ### Why is this bad?
+ /// Some structures can answer `.is_empty()` much faster
/// than checking for equality. So it is good to get into the habit of using
/// `.is_empty()`, and having it is cheap.
/// Besides, it makes the intent clearer than a manual comparison in some contexts.
///
- /// **Known problems:** None.
- ///
- /// **Example:**
+ /// ### Example
///
/// ```ignore
/// if s == "" {
/// ..
/// }
/// ```
+ #[clippy::version = "1.49.0"]
pub COMPARISON_TO_EMPTY,
style,
"checking `x == \"\"` or `x == []` (or similar) when `.is_empty()` could be used instead"
fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
if_chain! {
- if item.ident.as_str() == "len";
+ if item.ident.name == sym::len;
if let ImplItemKind::Fn(sig, _) = &item.kind;
if sig.decl.implicit_self.has_implicit_self();
- if cx.access_levels.is_exported(item.hir_id());
+ if cx.access_levels.is_exported(item.def_id);
if matches!(sig.decl.output, FnRetTy::Return(_));
if let Some(imp) = get_parent_as_impl(cx.tcx, item.hir_id());
if imp.of_trait.is_none();
if let Some(ty_id) = cx.qpath_res(ty_path, imp.self_ty.hir_id).opt_def_id();
if let Some(local_id) = ty_id.as_local();
let ty_hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_id);
- if !is_allowed(cx, LEN_WITHOUT_IS_EMPTY, ty_hir_id);
+ if !is_lint_allowed(cx, LEN_WITHOUT_IS_EMPTY, ty_hir_id);
if let Some(output) = parse_len_output(cx, cx.tcx.fn_sig(item.def_id).skip_binder());
then {
let (name, kind) = match cx.tcx.hir().find(ty_hir_id) {
}
fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, trait_items: &[TraitItemRef]) {
- fn is_named_self(cx: &LateContext<'_>, item: &TraitItemRef, name: &str) -> bool {
- item.ident.name.as_str() == name
+ fn is_named_self(cx: &LateContext<'_>, item: &TraitItemRef, name: Symbol) -> bool {
+ item.ident.name == name
&& if let AssocItemKind::Fn { has_self } = item.kind {
has_self && { cx.tcx.fn_sig(item.id.def_id).inputs().skip_binder().len() == 1 }
} else {
}
}
- if cx.access_levels.is_exported(visited_trait.hir_id()) && trait_items.iter().any(|i| is_named_self(cx, i, "len")) {
+ if cx.access_levels.is_exported(visited_trait.def_id) && trait_items.iter().any(|i| is_named_self(cx, i, sym::len))
+ {
let mut current_and_super_traits = DefIdSet::default();
fill_trait_set(visited_trait.def_id.to_def_id(), &mut current_and_super_traits, cx);
+ let is_empty = sym!(is_empty);
let is_empty_method_found = current_and_super_traits
.iter()
- .flat_map(|&i| cx.tcx.associated_items(i).in_definition_order())
+ .flat_map(|&i| cx.tcx.associated_items(i).filter_by_name_unhygienic(is_empty))
.any(|i| {
i.kind == ty::AssocKind::Fn
&& i.fn_has_self_parameter
- && i.ident.name == sym!(is_empty)
&& cx.tcx.fn_sig(i.def_id).inputs().skip_binder().len() == 1
});
Option(DefId),
Result(DefId, Ty<'tcx>),
}
-fn parse_len_output(cx: &LateContext<'_>, sig: FnSig<'tcx>) -> Option<LenOutput<'tcx>> {
+fn parse_len_output<'tcx>(cx: &LateContext<'_>, sig: FnSig<'tcx>) -> Option<LenOutput<'tcx>> {
match *sig.output().kind() {
ty::Int(_) | ty::Uint(_) => Some(LenOutput::Integral),
- ty::Adt(adt, subs) if cx.tcx.is_diagnostic_item(sym::option_type, adt.did) => {
+ ty::Adt(adt, subs) if cx.tcx.is_diagnostic_item(sym::Option, adt.did) => {
subs.type_at(0).is_integral().then(|| LenOutput::Option(adt.did))
},
- ty::Adt(adt, subs) if cx.tcx.is_diagnostic_item(sym::result_type, adt.did) => subs
+ ty::Adt(adt, subs) if cx.tcx.is_diagnostic_item(sym::Result, adt.did) => subs
.type_at(0)
.is_integral()
.then(|| LenOutput::Result(adt.did, subs.type_at(1))),
None,
None,
),
- Some(is_empty)
- if !cx
- .access_levels
- .is_exported(cx.tcx.hir().local_def_id_to_hir_id(is_empty.def_id.expect_local())) =>
- {
- (
- format!(
- "{} `{}` has a public `len` method, but a private `is_empty` method",
- item_kind,
- item_name.as_str(),
- ),
- Some(cx.tcx.def_span(is_empty.def_id)),
- None,
- )
- },
+ Some(is_empty) if !cx.access_levels.is_exported(is_empty.def_id.expect_local()) => (
+ format!(
+ "{} `{}` has a public `len` method, but a private `is_empty` method",
+ item_kind,
+ item_name.as_str(),
+ ),
+ Some(cx.tcx.def_span(is_empty.def_id)),
+ None,
+ ),
Some(is_empty)
if !(is_empty.fn_has_self_parameter
&& check_is_empty_sig(cx.tcx.fn_sig(is_empty.def_id).skip_binder(), self_kind, output)) =>
}
fn check_cmp(cx: &LateContext<'_>, span: Span, method: &Expr<'_>, lit: &Expr<'_>, op: &str, compare_to: u32) {
- if let (&ExprKind::MethodCall(method_path, _, args, _), &ExprKind::Lit(ref lit)) = (&method.kind, &lit.kind) {
+ if let (&ExprKind::MethodCall(method_path, args, _), &ExprKind::Lit(ref lit)) = (&method.kind, &lit.kind) {
// check if we are in an is_empty() method
if let Some(name) = get_item_name(cx, method) {
if name.as_str() == "is_empty" {
return;
}
- if method_name.as_str() == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
+ if method_name == sym::len && args.len() == 1 && has_is_empty(cx, &args[0]) {
let mut applicability = Applicability::MachineApplicable;
span_lint_and_sugg(
cx,
if let ExprKind::Lit(ref lit) = expr.kind {
if let LitKind::Str(lit, _) = lit.node {
let lit = lit.as_str();
- return lit == "";
+ return lit.is_empty();
}
}
false
fn has_is_empty(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
/// Gets an `AssocItem` and return true if it matches `is_empty(self)`.
fn is_is_empty(cx: &LateContext<'_>, item: &ty::AssocItem) -> bool {
- if let ty::AssocKind::Fn = item.kind {
- if item.ident.name.as_str() == "is_empty" {
- let sig = cx.tcx.fn_sig(item.def_id);
- let ty = sig.skip_binder();
- ty.inputs().len() == 1
- } else {
- false
- }
+ if item.kind == ty::AssocKind::Fn {
+ let sig = cx.tcx.fn_sig(item.def_id);
+ let ty = sig.skip_binder();
+ ty.inputs().len() == 1
} else {
false
}
/// Checks the inherent impl's items for an `is_empty(self)` method.
fn has_is_empty_impl(cx: &LateContext<'_>, id: DefId) -> bool {
+ let is_empty = sym!(is_empty);
cx.tcx.inherent_impls(id).iter().any(|imp| {
cx.tcx
.associated_items(*imp)
- .in_definition_order()
+ .filter_by_name_unhygienic(is_empty)
.any(|item| is_is_empty(cx, item))
})
}
let ty = &cx.typeck_results().expr_ty(expr).peel_refs();
match ty.kind() {
ty::Dynamic(tt, ..) => tt.principal().map_or(false, |principal| {
+ let is_empty = sym!(is_empty);
cx.tcx
.associated_items(principal.def_id())
- .in_definition_order()
+ .filter_by_name_unhygienic(is_empty)
.any(|item| is_is_empty(cx, item))
}),
ty::Projection(ref proj) => has_is_empty_impl(cx, proj.item_def_id),