]> git.lizzy.rs Git - rust.git/blob - doc/adding_lints.md
Implicit return
[rust.git] / doc / adding_lints.md
1 ## Adding a new lint
2
3 You are probably here because you want to add a new lint to Clippy. If this is
4 the first time you're contributing to Clippy, this document guides you through
5 creating an example lint from scratch.
6
7 To get started, we will create a lint that detects functions called `foo`,
8 because that's clearly a non-descriptive name.
9
10 * [Testing](#Testing)
11 * [Lint declaration](#Lint-declaration)
12 * [Lint passes](#Lint-passes)
13 * [Emitting a lint](#Emitting-a-lint)
14 * [Adding the lint logic](#Adding-the-lint-logic)
15 * [Documentation](#Documentation)
16 * [Debugging](#Debugging)
17 * [PR Checklist](#PR-Checklist)
18 * [Cheatsheet](#Cheatsheet)
19
20 ### Testing
21
22 Let's write some tests first that we can execute while we iterate on our lint.
23
24 Clippy uses UI tests for testing. UI tests check that the output of Clippy is
25 exactly as expected. Each test is just a plain Rust file that contains the code
26 we want to check. The output of Clippy is compared against a `.stderr` file.
27
28 Let's create the test file at `tests/ui/foo_functions.rs`. It doesn't really
29 matter what the file is called, but it's a good convention to name it after the
30 lint it is testing, so `foo_functions.rs` it is.
31
32 Inside we put some examples to get started:
33
34 ```rust
35 #![warn(clippy::foo_functions)]
36
37 // Impl methods
38 struct A;
39 impl A {
40     pub fn fo(&self) {}
41     pub fn foo(&self) {}
42     pub fn food(&self) {}
43 }
44
45 // Default trait methods
46 trait B {
47     pub fn fo(&self) {}
48     pub fn foo(&self) {}
49     pub fn food(&self) {}
50 }
51
52 // Plain functions
53 fn fo() {}
54 fn foo() {}
55 fn food() {}
56
57 fn main() {
58     // We also don't want to lint method calls
59     foo();
60     let a = A;
61     a.foo();
62 }
63
64 ```
65
66 Now we can run the test with `TESTNAME=ui/foo_functions cargo uitest`.
67 Currently this test will fail. If you go through the output you will see that we
68 have to add some missing imports to our lint file.
69
70 While you are working on implementing your lint, you can keep running the UI
71 test. That allows you to check if the output is turning into what you want.
72
73 Once you are satisfied with the output, you need to run
74 `tests/ui/update-all-references.sh` to update the `stderr` file for your lint.
75 Running `TESTNAME=ui/foo_functions cargo uitest` should pass then. When you
76 commit your lint, be sure to commit the `*.stderr` files, too.
77
78 Let's have a look at implementing our lint now.
79
80 ### Lint declaration
81
82 We start by creating a new file in the `clippy_lints` crate. That's the crate
83 where all the lint code is. We are going to call the file
84 `clippy_lints/src/foo_functions.rs` and import some initial things we need:
85
86 ```rust
87 use rustc::lint::{LintArray, LintPass};
88 use rustc::{declare_tool_lint, lint_array};
89 ```
90
91 The next step is to provide a lint declaration. Lints are declared using the [`declare_clippy_lint!`][declare_clippy_lint] macro:
92
93 ```rust
94 declare_clippy_lint! {
95     pub FOO_FUNCTIONS,
96     pedantic,
97     "function named `foo`, which is not a descriptive name"
98 }
99 ```
100
101 * `FOO_FUNCTIONS` is the name of our lint. Be sure to follow the [lint naming
102 guidelines][lint_naming] here when naming your lint. In short, the name should
103 state the thing that is being checked for and read well when used with
104 `allow`/`warn`/`deny`.
105 * `pedantic` sets the lint level to `Allow`.
106   The exact mapping can be found [here][category_level_mapping]
107 * The last part should be a text that explains what exactly is wrong with the
108   code
109
110 With our lint declaration done, we will now make sure that our lint declaration is assigned to a lint pass:
111
112 ```rust
113 // clippy_lints/src/foo_functions.rs
114
115 // .. imports and lint declaration ..
116
117 #[derive(Copy, Clone)]
118 pub struct FooFunctionsPass;
119
120 impl LintPass for FooFunctionsPass {
121     fn get_lints(&self) -> LintArray {
122         lint_array!(
123             FOO_FUNCTIONS,
124         )
125     }
126
127     fn name(&self) -> &'static str {
128         "FooFunctions"
129     }
130 }
131 ```
132
133 Don't worry about the `name` method here. As long as it includes the name of the lint pass it should be fine.
134
135 Next you should run `util/dev update_lints` to register the lint in various
136 places, mainly in `clippy_lints/src/lib.rs`.
137
138 While `update_lints` automates some things, it doesn't automate everything. We will have to register our lint pass manually in the `register_plugins` function in `clippy_lints/src/lib.rs`:
139
140 ```rust
141 reg.register_early_lint_pass(box foo_functions::FooFunctionsPass);
142 ```
143
144 Without that, running the UI tests would produce an error like `unknown clippy lint: clippy::foo_functions`.
145 The next decision we have to make is which lint pass our lint is going to need.
146
147 ### Lint passes
148
149 Writing a lint that just checks for the name of a function means that we just
150 have to deal with the AST and don't have to deal with the type system at all.
151 This is good, because it makes writing this particular lint less complicated.
152
153 We have to make this decision with every new Clippy lint. It boils down to using either `EarlyLintPass` or `LateLintPass`. This is a result of Rust's compilation process. You can read more about it [in the rustc guide][compilation_stages].
154
155 In short, the `LateLintPass` has access to type information while the `EarlyLintPass` doesn't. If you don't need access to type information, use the `EarlyLintPass`. The `EarlyLintPass` is also faster. However linting speed hasn't really been a concern with Clippy so far.
156
157 Since we don't need type information for checking the function name, we are going to use the `EarlyLintPass`. It has to be imported as well, changing our imports to:
158
159 ```rust
160 use rustc::lint::{LintArray, LintPass, EarlyLintPass, EarlyContext};
161 use rustc::{declare_tool_lint, lint_array};
162 ```
163
164 ### Emitting a lint
165
166 With UI tests in place, we can start working on the implementation of the lint logic. We can keep executing the tests until we make them pass.
167
168 Let's start by emitting a lint for every function definition.
169
170 ```rust
171 impl EarlyLintPass for Pass {
172     fn check_fn(&mut self, cx: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: &FnDecl, span: Span, _: NodeId) {
173         // TODO: Emit lint here
174     }
175 }
176 ```
177
178 We implement the [`check_fn`][check_fn] method from the [`EarlyLintPass`][early_lint_pass] trait. This gives us access to various information about the function that is currently being checked. More on that in the next section. Let's worry about the details later and emit our lint for *every* function definition first.
179
180 Depending on how complex we want our lint message to be, we can choose from a variety of lint emission functions.
181 They can all be found in  [`clippy_lints/src/utils/diagnostics.rs`][diagnostics].
182
183
184 ```rust
185 impl EarlyLintPass for Pass {
186     fn check_fn(&mut self, cx: &EarlyContext<'_>, _: FnKind<'_>, _: &FnDecl, span: Span, _: NodeId) {
187         span_help_and_lint(
188             cx,
189             FOO_FUNCTIONS,
190             span,
191             "function named `foo`",
192             "consider using a more meaningful name"
193         );
194     }
195 }
196 ```
197
198 ### Adding the lint logic
199
200 Writing the logic for your lint will most likely be different from this example,
201 so this section is kept rather short.
202
203 Using the [`check_fn`][check_fn] method gives us access to [`FnKind`][fn_kind]
204 that has two relevant variants for us `FnKind::ItemFn` and `FnKind::Method`.
205 Both provide access to the name of the function/method via an [`Ident`][ident].
206 and delegate our check to it's own function, passing through only the data we
207 need.
208
209 In our example, the implementation would look like:
210
211 ```rust
212 fn is_foo_fn(fn_kind: FnKind<'_>) -> bool {
213     match fn_kind {
214         FnKind::ItemFn(ident, ..) | FnKind::Method(ident, ..) => {
215             return ident.name == "foo"
216         },
217         FnKind::Closure(..) => false
218     }
219 }
220 ```
221
222
223 Now you'll want to also run the full test suite with `cargo test`. Apart from
224 running all other UI tests, this ensures that our lint implementation is not
225 violating any Clippy lints itself. If you are still following the example,
226 you'll see that the `FooFunctionsPass` violates a Clippy lint. So we are going
227 to rename that struct to just `Pass`:
228
229 ```rust
230 #[derive(Copy, Clone)]
231 pub struct Pass;
232
233 impl LintPass for Pass { /* .. */ }
234 ```
235
236
237 ### Documentation
238
239 The final thing before submitting our PR is to add some documentation to our
240 lint declaration.
241
242 Please document your lint with a doc comment akin to the following:
243
244 ```rust
245 /// **What it does:** Checks for ... (describe what the lint matches).
246 ///
247 /// **Why is this bad?** Supply the reason for linting the code.
248 ///
249 /// **Known problems:** None. (Or describe where it could go wrong.)
250 ///
251 /// **Example:**
252 ///
253 /// ```rust,ignore
254 /// // Bad
255 /// Insert a short example of code that triggers the lint
256 ///
257 /// // Good
258 /// Insert a short example of improved code that doesnt trigger the lint
259 /// ```
260 declare_clippy_lint! // ...
261 ```
262
263 Once your lint is merged, this documentation will show up in the [lint
264 list][lint_list].
265
266 ### Debugging
267
268 If you want to debug parts of your lint implementation, you can use the `dbg!`
269 macro anywhere in your code. Running the tests should then include the debug
270 output in the `stdout` part.
271
272 ### PR Checklist
273
274 TODO: Prose
275
276 - [ ] Followed [lint naming conventions][lint_naming]
277 - [ ] Added passing UI tests (including committed `.stderr` file)
278 - [ ] `cargo test` passes locally
279 - [ ] Added lint documentation
280
281 ### Cheatsheet
282
283 Here are some pointers to things you are likely going to need for every lint:
284
285 * [The `if_chain` macro][if_chain]
286 * [`in_macro`][in_macro] and [`in_external_macro`][in_external_macro]
287 * [`Span`][span]
288 * [Clippy diagnostics][diagnostics]
289 * [`Applicability`][applicability]
290
291 For `EarlyLintPass` lints:
292
293 * [`EarlyLintPass`][early_lint_pass]
294 * [`syntax::ast`][ast]
295
296 For `LateLintPass` lints:
297
298 * [`LateLintPass`][late_lint_pass]
299 * [`Ty::TyKind`][ty]
300
301
302 While most of Clippy's lint utils are documented, most of rustc's internals lack
303 documentation currently. This is unfortunate, but in most cases you can probably
304 get away with copying things from existing similar lints. If you are stuck,
305 don't hesitate to ask on Discord, IRC or in the issue/PR.
306
307 [lint_list]: https://rust-lang.github.io/rust-clippy/master/index.html
308 [lint_naming]: https://rust-lang.github.io/rfcs/0344-conventions-galore.html#lints
309 [category_level_mapping]: https://github.com/rust-lang/rust-clippy/blob/bd23cb89ec0ea63403a17d3fc5e50c88e38dd54f/clippy_lints/src/lib.rs#L43
310 [declare_clippy_lint]: https://github.com/rust-lang/rust-clippy/blob/a71acac1da7eaf667ab90a1d65d10e5cc4b80191/clippy_lints/src/lib.rs#L39
311 [compilation_stages]: https://rust-lang.github.io/rustc-guide/high-level-overview.html#the-main-stages-of-compilation
312 [check_fn]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/lint/trait.EarlyLintPass.html#method.check_fn
313 [early_lint_pass]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/lint/trait.EarlyLintPass.html
314 [late_lint_pass]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/lint/trait.LateLintPass.html
315 [fn_kind]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/visit/enum.FnKind.html
316 [diagnostics]: https://github.com/rust-lang/rust-clippy/blob/master/clippy_lints/src/utils/diagnostics.rs
317 [ident]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/source_map/symbol/struct.Ident.html
318 [span]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax_pos/struct.Span.html
319 [applicability]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_errors/enum.Applicability.html
320 [if_chain]: https://docs.rs/if_chain/0.1.2/if_chain/
321 [ty]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/sty/index.html
322 [ast]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/ast/index.html
323 [in_macro]: https://github.com/rust-lang/rust-clippy/blob/d0717d1f9531a03d154aaeb0cad94c243915a146/clippy_lints/src/utils/mod.rs#L94
324 [in_external_macro]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/lint/fn.in_external_macro.html