Skip to content

Commit

Permalink
Auto merge of rust-lang#13543 - GnomedDev:symbol-comparisons, r=y21
Browse files Browse the repository at this point in the history
Add internal lint to check for slow symbol comparisons

See the conversation on [Zulip](https://rust-lang.zulipchat.com/#narrow/stream/257328-clippy/topic/Checking.20a.20Symbol.20is.20equal.20to.20a.20string.20literal).

changelog: none
  • Loading branch information
bors committed Oct 18, 2024
2 parents 6a79588 + 979e297 commit f2f0175
Show file tree
Hide file tree
Showing 36 changed files with 200 additions and 63 deletions.
4 changes: 2 additions & 2 deletions book/src/development/common_tools_writing_lints.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ impl<'tcx> LateLintPass<'tcx> for MyStructLint {
// Check our expr is calling a method
if let hir::ExprKind::MethodCall(path, _, _self_arg, ..) = &expr.kind
// Check the name of this method is `some_method`
&& path.ident.name == sym!(some_method)
&& path.ident.name.as_str() == "some_method"
// Optionally, check the type of the self argument.
// - See "Checking for a specific type"
{
Expand Down Expand Up @@ -167,7 +167,7 @@ impl<'tcx> LateLintPass<'tcx> for MyTypeImpl {
// Check if item is a method/function
if let ImplItemKind::Fn(ref signature, _) = impl_item.kind
// Check the method is named `some_method`
&& impl_item.ident.name == sym!(some_method)
&& impl_item.ident.name.as_str() == "some_method"
// We can also check it has a parameter `self`
&& signature.decl.implicit_self.has_implicit_self()
// We can go further and even check if its return type is `String`
Expand Down
15 changes: 4 additions & 11 deletions book/src/development/method_checking.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
In some scenarios we might want to check for methods when developing
a lint. There are two kinds of questions that we might be curious about:

- Invocation: Does an expression call a specific method?
- Definition: Does an `impl` define a method?
- Invocation: Does an expression call a specific method?
- Definition: Does an `impl` define a method?

## Checking if an `expr` is calling a specific method

Expand All @@ -23,7 +23,7 @@ impl<'tcx> LateLintPass<'tcx> for OurFancyMethodLint {
// Check our expr is calling a method with pattern matching
if let hir::ExprKind::MethodCall(path, _, [self_arg, ..]) = &expr.kind
// Check if the name of this method is `our_fancy_method`
&& path.ident.name == sym!(our_fancy_method)
&& path.ident.name.as_str() == "our_fancy_method"
// We can check the type of the self argument whenever necessary.
// (It's necessary if we want to check that method is specifically belonging to a specific trait,
// for example, a `map` method could belong to user-defined trait instead of to `Iterator`)
Expand All @@ -41,10 +41,6 @@ information on the pattern matching. As mentioned in [Define
Lints](defining_lints.md#lint-types), the `methods` lint type is full of pattern
matching with `MethodCall` in case the reader wishes to explore more.

Additionally, we use the [`clippy_utils::sym!`][sym] macro to conveniently
convert an input `our_fancy_method` into a `Symbol` and compare that symbol to
the [`Ident`]'s name in the [`PathSegment`] in the [`MethodCall`].

## Checking if a `impl` block implements a method

While sometimes we want to check whether a method is being called or not, other
Expand All @@ -71,7 +67,7 @@ impl<'tcx> LateLintPass<'tcx> for MyTypeImpl {
// Check if item is a method/function
if let ImplItemKind::Fn(ref signature, _) = impl_item.kind
// Check the method is named `our_fancy_method`
&& impl_item.ident.name == sym!(our_fancy_method)
&& impl_item.ident.name.as_str() == "our_fancy_method"
// We can also check it has a parameter `self`
&& signature.decl.implicit_self.has_implicit_self()
// We can go even further and even check if its return type is `String`
Expand All @@ -85,9 +81,6 @@ impl<'tcx> LateLintPass<'tcx> for MyTypeImpl {

[`check_impl_item`]: https://doc.rust-lang.org/stable/nightly-rustc/rustc_lint/trait.LateLintPass.html#method.check_impl_item
[`ExprKind`]: https://doc.rust-lang.org/beta/nightly-rustc/rustc_hir/hir/enum.ExprKind.html
[`Ident`]: https://doc.rust-lang.org/beta/nightly-rustc/rustc_span/symbol/struct.Ident.html
[`ImplItem`]: https://doc.rust-lang.org/stable/nightly-rustc/rustc_hir/hir/struct.ImplItem.html
[`LateLintPass`]: https://doc.rust-lang.org/stable/nightly-rustc/rustc_lint/trait.LateLintPass.html
[`MethodCall`]: https://doc.rust-lang.org/beta/nightly-rustc/rustc_hir/hir/enum.ExprKind.html#variant.MethodCall
[`PathSegment`]: https://doc.rust-lang.org/beta/nightly-rustc/rustc_hir/hir/struct.PathSegment.html
[sym]: https://doc.rust-lang.org/stable/nightly-rustc/clippy_utils/macro.sym.html
2 changes: 1 addition & 1 deletion clippy_lints/src/casts/cast_ptr_alignment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>) {
);
lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
} else if let ExprKind::MethodCall(method_path, self_arg, [], _) = &expr.kind {
if method_path.ident.name == sym!(cast)
if method_path.ident.name.as_str() == "cast"
&& let Some(generic_args) = method_path.args
&& let [GenericArg::Type(cast_to)] = generic_args.args
// There probably is no obvious reason to do this, just to be consistent with `as` cases.
Expand Down
2 changes: 2 additions & 0 deletions clippy_lints/src/declared_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ pub static LINTS: &[&crate::LintInfo] = &[
#[cfg(feature = "internal")]
crate::utils::internal_lints::produce_ice::PRODUCE_ICE_INFO,
#[cfg(feature = "internal")]
crate::utils::internal_lints::slow_symbol_comparisons::SLOW_SYMBOL_COMPARISONS_INFO,
#[cfg(feature = "internal")]
crate::utils::internal_lints::unnecessary_def_path::UNNECESSARY_DEF_PATH_INFO,
#[cfg(feature = "internal")]
crate::utils::internal_lints::unsorted_clippy_utils_paths::UNSORTED_CLIPPY_UTILS_PATHS_INFO,
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/explicit_write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ impl<'tcx> LateLintPass<'tcx> for ExplicitWrite {
// match call to write_fmt
&& let ExprKind::MethodCall(write_fun, write_recv, [write_arg], _) = *look_in_block(cx, &write_call.kind)
&& let ExprKind::Call(write_recv_path, []) = write_recv.kind
&& write_fun.ident.name == sym!(write_fmt)
&& write_fun.ident.name.as_str() == "write_fmt"
&& let Some(def_id) = path_def_id(cx, write_recv_path)
{
// match calls to std::io::stdout() / std::io::stderr ()
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/from_raw_with_void_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ impl LateLintPass<'_> for FromRawWithVoidPtr {
fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
if let ExprKind::Call(box_from_raw, [arg]) = expr.kind
&& let ExprKind::Path(QPath::TypeRelative(ty, seg)) = box_from_raw.kind
&& seg.ident.name == sym!(from_raw)
&& seg.ident.name.as_str() == "from_raw"
&& let Some(type_str) = path_def_id(cx, ty).and_then(|id| def_id_matches_type(cx, id))
&& let arg_kind = cx.typeck_results().expr_ty(arg).kind()
&& let ty::RawPtr(ty, _) = arg_kind
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/implicit_hasher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ impl<'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'_, '_, 'tcx> {
if self.cx.tcx.is_diagnostic_item(sym::HashMap, ty_did) {
if method.ident.name == sym::new {
self.suggestions.insert(e.span, "HashMap::default()".to_string());
} else if method.ident.name == sym!(with_capacity) {
} else if method.ident.name.as_str() == "with_capacity" {
self.suggestions.insert(
e.span,
format!(
Expand All @@ -352,7 +352,7 @@ impl<'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'_, '_, 'tcx> {
} else if self.cx.tcx.is_diagnostic_item(sym::HashSet, ty_did) {
if method.ident.name == sym::new {
self.suggestions.insert(e.span, "HashSet::default()".to_string());
} else if method.ident.name == sym!(with_capacity) {
} else if method.ident.name.as_str() == "with_capacity" {
self.suggestions.insert(
e.span,
format!(
Expand Down
6 changes: 3 additions & 3 deletions clippy_lints/src/infinite_iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ fn is_infinite(cx: &LateContext<'_>, expr: &Expr<'_>) -> Finiteness {
.and(cap);
}
}
if method.ident.name == sym!(flat_map) && args.len() == 1 {
if method.ident.name.as_str() == "flat_map" && args.len() == 1 {
if let ExprKind::Closure(&Closure { body, .. }) = args[0].kind {
let body = cx.tcx.hir().body(body);
return is_infinite(cx, body.value);
Expand Down Expand Up @@ -224,7 +224,7 @@ fn complete_infinite_iter(cx: &LateContext<'_>, expr: &Expr<'_>) -> Finiteness {
return MaybeInfinite.and(is_infinite(cx, receiver));
}
}
if method.ident.name == sym!(last) && args.is_empty() {
if method.ident.name.as_str() == "last" && args.is_empty() {
let not_double_ended = cx
.tcx
.get_diagnostic_item(sym::DoubleEndedIterator)
Expand All @@ -234,7 +234,7 @@ fn complete_infinite_iter(cx: &LateContext<'_>, expr: &Expr<'_>) -> Finiteness {
if not_double_ended {
return is_infinite(cx, receiver);
}
} else if method.ident.name == sym!(collect) {
} else if method.ident.name.as_str() == "collect" {
let ty = cx.typeck_results().expr_ty(expr);
if matches!(
get_type_diagnostic_name(cx, ty),
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/iter_without_into_iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ impl LateLintPass<'_> for IterWithoutIntoIter {
ty.peel_refs().is_slice() || get_adt_inherent_method(cx, ty, expected_method_name).is_some()
})
&& let Some(iter_assoc_span) = imp.items.iter().find_map(|item| {
if item.ident.name == sym!(IntoIter) {
if item.ident.name.as_str() == "IntoIter" {
Some(cx.tcx.hir().impl_item(item.id).expect_type().span)
} else {
None
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,7 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
store.register_late_pass(|_| {
Box::new(utils::internal_lints::almost_standard_lint_formulation::AlmostStandardFormulation::new())
});
store.register_late_pass(|_| Box::new(utils::internal_lints::slow_symbol_comparisons::SlowSymbolComparisons));
}

store.register_late_pass(move |_| Box::new(operators::arithmetic_side_effects::ArithmeticSideEffects::new(conf)));
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/manual_hash_one.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ impl LateLintPass<'_> for ManualHashOne {
&& let Some(init) = local.init
&& !init.span.from_expansion()
&& let ExprKind::MethodCall(seg, build_hasher, [], _) = init.kind
&& seg.ident.name == sym!(build_hasher)
&& seg.ident.name.as_str() == "build_hasher"

&& let Node::Stmt(local_stmt) = cx.tcx.parent_hir_node(local.hir_id)
&& let Node::Block(block) = cx.tcx.parent_hir_node(local_stmt.hir_id)
Expand Down Expand Up @@ -96,7 +96,7 @@ impl LateLintPass<'_> for ManualHashOne {
&& let Node::Expr(finish_expr) = cx.tcx.parent_hir_node(path_expr.hir_id)
&& !finish_expr.span.from_expansion()
&& let ExprKind::MethodCall(seg, _, [], _) = finish_expr.kind
&& seg.ident.name == sym!(finish)
&& seg.ident.name.as_str() == "finish"

&& self.msrv.meets(msrvs::BUILD_HASHER_HASH_ONE)
{
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/manual_is_ascii_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualIsAsciiCheck {
check_is_ascii(cx, macro_call.span, recv, &range, None);
}
} else if let ExprKind::MethodCall(path, receiver, [arg], ..) = expr.kind
&& path.ident.name == sym!(contains)
&& path.ident.name.as_str() == "contains"
&& let Some(higher::Range {
start: Some(start),
end: Some(end),
Expand Down
12 changes: 6 additions & 6 deletions clippy_lints/src/matches/redundant_guards.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use rustc_hir::def::{DefKind, Res};
use rustc_hir::{Arm, BinOpKind, Expr, ExprKind, MatchSource, Node, PatKind, UnOp};
use rustc_lint::LateContext;
use rustc_span::symbol::Ident;
use rustc_span::{Span, Symbol, sym};
use rustc_span::{Span, sym};
use std::borrow::Cow;
use std::ops::ControlFlow;

Expand Down Expand Up @@ -95,15 +95,15 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'tcx>], msrv:
} else if let ExprKind::MethodCall(path, recv, args, ..) = guard.kind
&& let Some(binding) = get_pat_binding(cx, recv, outer_arm)
{
check_method_calls(cx, outer_arm, path.ident.name, recv, args, guard, &binding);
check_method_calls(cx, outer_arm, path.ident.name.as_str(), recv, args, guard, &binding);
}
}
}

fn check_method_calls<'tcx>(
cx: &LateContext<'tcx>,
arm: &Arm<'tcx>,
method: Symbol,
method: &str,
recv: &Expr<'_>,
args: &[Expr<'_>],
if_expr: &Expr<'_>,
Expand All @@ -112,7 +112,7 @@ fn check_method_calls<'tcx>(
let ty = cx.typeck_results().expr_ty(recv).peel_refs();
let slice_like = ty.is_slice() || ty.is_array();

let sugg = if method == sym!(is_empty) {
let sugg = if method == "is_empty" {
// `s if s.is_empty()` becomes ""
// `arr if arr.is_empty()` becomes []

Expand All @@ -137,9 +137,9 @@ fn check_method_calls<'tcx>(

if needles.is_empty() {
sugg.insert_str(1, "..");
} else if method == sym!(starts_with) {
} else if method == "starts_with" {
sugg.insert_str(sugg.len() - 1, ", ..");
} else if method == sym!(ends_with) {
} else if method == "ends_with" {
sugg.insert_str(1, ".., ");
} else {
return;
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/methods/filter_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,12 +234,12 @@ impl<'tcx> OffendingFilterExpr<'tcx> {
// the latter only calls `effect` once
let side_effect_expr_span = receiver.can_have_side_effects().then_some(receiver.span);

if cx.tcx.is_diagnostic_item(sym::Option, recv_ty.did()) && path.ident.name == sym!(is_some) {
if cx.tcx.is_diagnostic_item(sym::Option, recv_ty.did()) && path.ident.name.as_str() == "is_some" {
Some(Self::IsSome {
receiver,
side_effect_expr_span,
})
} else if cx.tcx.is_diagnostic_item(sym::Result, recv_ty.did()) && path.ident.name == sym!(is_ok) {
} else if cx.tcx.is_diagnostic_item(sym::Result, recv_ty.did()) && path.ident.name.as_str() == "is_ok" {
Some(Self::IsOk {
receiver,
side_effect_expr_span,
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/methods/needless_collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ impl<'tcx> Visitor<'tcx> for IterFunctionVisitor<'_, 'tcx> {
// Check function calls on our collection
if let ExprKind::MethodCall(method_name, recv, args, _) = &expr.kind {
if args.is_empty()
&& method_name.ident.name == sym!(collect)
&& method_name.ident.name.as_str() == "collect"
&& is_trait_method(self.cx, expr, sym::Iterator)
{
self.current_mutably_captured_ids = get_captured_ids(self.cx, self.cx.typeck_results().expr_ty(recv));
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/methods/read_line_without_trim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ pub fn check(cx: &LateContext<'_>, call: &Expr<'_>, recv: &Expr<'_>, arg: &Expr<
if let Some(parent) = get_parent_expr(cx, expr) {
let data = if let ExprKind::MethodCall(segment, recv, args, span) = parent.kind {
if args.is_empty()
&& segment.ident.name == sym!(parse)
&& segment.ident.name.as_str() == "parse"
&& let parse_result_ty = cx.typeck_results().expr_ty(parent)
&& is_type_diagnostic_item(cx, parse_result_ty, sym::Result)
&& let ty::Adt(_, substs) = parse_result_ty.kind()
Expand All @@ -58,7 +58,7 @@ pub fn check(cx: &LateContext<'_>, call: &Expr<'_>, recv: &Expr<'_>, arg: &Expr<
"calling `.parse()` on a string without trimming the trailing newline character",
"checking",
))
} else if segment.ident.name == sym!(ends_with)
} else if segment.ident.name.as_str() == "ends_with"
&& recv.span == expr.span
&& let [arg] = args
&& expr_is_string_literal_without_trailing_newline(arg)
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/methods/unnecessary_filter_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ fn check_expression<'tcx>(cx: &LateContext<'tcx>, arg_id: hir::HirId, expr: &'tc
(true, true)
},
hir::ExprKind::MethodCall(segment, recv, [arg], _) => {
if segment.ident.name == sym!(then_some)
if segment.ident.name.as_str() == "then_some"
&& cx.typeck_results().expr_ty(recv).is_bool()
&& path_to_local_id(arg, arg_id)
{
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/minmax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,9 @@ fn min_max<'a, 'tcx>(cx: &LateContext<'tcx>, expr: &'a Expr<'a>) -> Option<(MinM
},
ExprKind::MethodCall(path, receiver, args @ [_], _) => {
if cx.typeck_results().expr_ty(receiver).is_floating_point() || is_trait_method(cx, expr, sym::Ord) {
if path.ident.name == sym!(max) {
if path.ident.name.as_str() == "max" {
fetch_const(cx, Some(receiver), args, MinMax::Max)
} else if path.ident.name == sym!(min) {
} else if path.ident.name.as_str() == "min" {
fetch_const(cx, Some(receiver), args, MinMax::Min)
} else {
None
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/missing_fields_in_debug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ fn should_lint<'tcx>(

if path.ident.name == sym::debug_struct && is_type_diagnostic_item(cx, recv_ty, sym::Formatter) {
has_debug_struct = true;
} else if path.ident.name == sym!(finish_non_exhaustive)
} else if path.ident.name.as_str() == "finish_non_exhaustive"
&& is_type_diagnostic_item(cx, recv_ty, sym::DebugStruct)
{
has_finish_non_exhaustive = true;
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/non_octal_unix_permissions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,12 @@ impl<'tcx> LateLintPass<'tcx> for NonOctalUnixPermissions {
match &expr.kind {
ExprKind::MethodCall(path, func, [param], _) => {
if let Some(adt) = cx.typeck_results().expr_ty(func).peel_refs().ty_adt_def()
&& ((path.ident.name == sym!(mode)
&& ((path.ident.name.as_str() == "mode"
&& matches!(
cx.tcx.get_diagnostic_name(adt.did()),
Some(sym::FsOpenOptions | sym::DirBuilder)
))
|| (path.ident.name == sym!(set_mode)
|| (path.ident.name.as_str() == "set_mode"
&& cx.tcx.is_diagnostic_item(sym::FsPermissions, adt.did())))
&& let ExprKind::Lit(_) = param.kind
&& param.span.eq_ctxt(expr.span)
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/operators/float_cmp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ fn is_signum(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
}

if let ExprKind::MethodCall(method_name, self_arg, [], _) = expr.kind
&& sym!(signum) == method_name.ident.name
&& method_name.ident.name.as_str() == "signum"
// Check that the receiver of the signum() is a float (expressions[0] is the receiver of
// the method call)
{
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/ptr_offset_with_cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ fn expr_as_ptr_offset_call<'tcx>(
if path_segment.ident.name == sym::offset {
return Some((arg_0, arg_1, Method::Offset));
}
if path_segment.ident.name == sym!(wrapping_offset) {
if path_segment.ident.name.as_str() == "wrapping_offset" {
return Some((arg_0, arg_1, Method::WrappingOffset));
}
}
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/question_mark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,8 @@ fn is_early_return(smbl: Symbol, cx: &LateContext<'_>, if_block: &IfBlockType<'_
is_type_diagnostic_item(cx, caller_ty, smbl)
&& expr_return_none_or_err(smbl, cx, if_then, caller, None)
&& match smbl {
sym::Option => call_sym == sym!(is_none),
sym::Result => call_sym == sym!(is_err),
sym::Option => call_sym.as_str() == "is_none",
sym::Result => call_sym.as_str() == "is_err",
_ => false,
}
},
Expand Down
Loading

0 comments on commit f2f0175

Please sign in to comment.