Skip to content

Commit 0cc1594

Browse files
committed
Fix trait method checking in book
1 parent 09c3237 commit 0cc1594

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

book/src/development/method_checking.md

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,13 @@ use clippy_utils::sym;
2121
impl<'tcx> LateLintPass<'tcx> for OurFancyMethodLint {
2222
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
2323
// Check our expr is calling a method with pattern matching
24-
if let hir::ExprKind::MethodCall(path, _, [self_arg, ..], _) = &expr.kind
24+
if let hir::ExprKind::MethodCall(path, _, _, _) = &expr.kind
2525
// Check if the name of this method is `our_fancy_method`
2626
&& path.ident.name == sym::our_fancy_method
27-
// We can check the type of the self argument whenever necessary.
28-
// (It's necessary if we want to check that method is specifically belonging to a specific trait,
29-
// for example, a `map` method could belong to user-defined trait instead of to `Iterator`)
27+
// Check if the method belongs to the `sym::OurFancyTrait` trait.
28+
// (for example, a `map` method could belong to user-defined trait instead of to `Iterator`)
3029
// See the next section for more information.
31-
&& cx.ty_based_def(self_arg).opt_parent(cx).is_diag_item(cx, sym::OurFancyTrait)
30+
&& cx.ty_based_def(expr).opt_parent(cx).is_diag_item(cx, sym::OurFancyTrait)
3231
{
3332
println!("`expr` is a method call for `our_fancy_method`");
3433
}
@@ -45,6 +44,12 @@ New symbols such as `our_fancy_method` need to be added to the `clippy_utils::sy
4544
This module extends the list of symbols already provided by the compiler crates
4645
in `rustc_span::sym`.
4746

47+
If a trait defines only one method (such as the `std::ops::Deref` trait, which only has the `deref()` method),
48+
one might be tempted to omit the method name check. This would work, but is not always advisable because:
49+
- If a new method (possibly with a default implementation) were to be added to the trait, there would be a risk of
50+
matching the wrong method.
51+
- Comparing symbols is very cheap and might prevent a more expensive lookup.
52+
4853
## Checking if a `impl` block implements a method
4954

5055
While sometimes we want to check whether a method is being called or not, other

0 commit comments

Comments
 (0)