@@ -75,20 +75,21 @@ impl LateLintPass<'_> for MyStructLint {
75
75
76
76
# Checking if a type implements a specific trait
77
77
78
- There are two ways to do this, depending if the target trait is part of lang items .
78
+ There are three ways to do this, depending on if the target trait has a diagnostic item, lang item or neither .
79
79
80
80
``` rust
81
- use clippy_utils :: {implements_trait, match_trait_method, paths};
81
+ use clippy_utils :: {implements_trait, is_trait_method, match_trait_method};
82
+ use rustc_span :: symbol :: sym;
82
83
83
84
impl LateLintPass <'_ > for MyStructLint {
84
85
fn check_expr (& mut self , cx : & LateContext <'_ >, expr : & Expr <'_ >) {
85
- // 1. Using expression and Clippy's convenient method
86
- // we use `match_trait_method ` function from Clippy's toolbox
87
- if match_trait_method (cx , expr , & paths :: INTO ) {
88
- // `expr` implements `Into ` trait
86
+ // 1. Using diagnostic items with the expression
87
+ // we use `is_trait_method ` function from Clippy's utils
88
+ if is_trait_method (cx , expr , sym :: Iterator ) {
89
+ // method call in `expr` belongs to `Iterator ` trait
89
90
}
90
91
91
- // 2. Using type context `TyCtxt`
92
+ // 2. Using lang items with the expression type
92
93
let ty = cx . typeck_results (). expr_ty (expr );
93
94
if cx . tcx. lang_items ()
94
95
// we are looking for the `DefId` of `Drop` trait in lang items
@@ -97,15 +98,20 @@ impl LateLintPass<'_> for MyStructLint {
97
98
. map_or (false , | id | implements_trait (cx , ty , id , & [])) {
98
99
// `expr` implements `Drop` trait
99
100
}
101
+
102
+ // 3. Using the type path with the expression
103
+ // we use `match_trait_method` function from Clippy's utils
104
+ if match_trait_method (cx , expr , & paths :: INTO ) {
105
+ // `expr` implements `Into` trait
106
+ }
100
107
}
101
108
}
102
109
```
103
110
104
- > Prefer using lang items, if the target trait is available there.
105
-
106
- A list of defined paths for Clippy can be found in [ paths.rs] [ paths ]
111
+ > Prefer using diagnostic and lang items, if the target trait has one.
107
112
108
113
We access lang items through the type context ` tcx ` . ` tcx ` is of type [ ` TyCtxt ` ] [ TyCtxt ] and is defined in the ` rustc_middle ` crate.
114
+ A list of defined paths for Clippy can be found in [ paths.rs] [ paths ]
109
115
110
116
# Checking if a type defines a specific method
111
117
0 commit comments