]> git.lizzy.rs Git - rust.git/blob - doc/adding_lints.md
Add implementation for the EarlyLintPass trait into the Adding Lints documentation.
[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 * [Setup](#Setup)
11 * [Testing](#Testing)
12 * [Rustfix tests](#Rustfix-tests)
13 * [Lint declaration](#Lint-declaration)
14 * [Lint passes](#Lint-passes)
15 * [Emitting a lint](#Emitting-a-lint)
16 * [Adding the lint logic](#Adding-the-lint-logic)
17 * [Author lint](#Author-lint)
18 * [Documentation](#Documentation)
19 * [Running rustfmt](#Running-rustfmt)
20 * [Debugging](#Debugging)
21 * [PR Checklist](#PR-Checklist)
22 * [Cheatsheet](#Cheatsheet)
23
24 ### Setup
25
26 When working on Clippy, you will need the current git master version of rustc,
27 which can change rapidly. Make sure you're working near rust-clippy's master,
28 and use the `setup-toolchain.sh` script to configure the appropriate toolchain
29 for the Clippy directory.
30
31 ### Testing
32
33 Let's write some tests first that we can execute while we iterate on our lint.
34
35 Clippy uses UI tests for testing. UI tests check that the output of Clippy is
36 exactly as expected. Each test is just a plain Rust file that contains the code
37 we want to check. The output of Clippy is compared against a `.stderr` file.
38 Note that you don't have to create this file yourself, we'll get to
39 generating the `.stderr` files further down.
40
41 We start by creating the test file at `tests/ui/foo_functions.rs`. It doesn't
42 really matter what the file is called, but it's a good convention to name it
43 after the lint it is testing, so `foo_functions.rs` it is.
44
45 Inside the file we put some examples to get started:
46
47 ```rust
48 #![warn(clippy::foo_functions)]
49
50 // Impl methods
51 struct A;
52 impl A {
53     pub fn fo(&self) {}
54     pub fn foo(&self) {}
55     pub fn food(&self) {}
56 }
57
58 // Default trait methods
59 trait B {
60     pub fn fo(&self) {}
61     pub fn foo(&self) {}
62     pub fn food(&self) {}
63 }
64
65 // Plain functions
66 fn fo() {}
67 fn foo() {}
68 fn food() {}
69
70 fn main() {
71     // We also don't want to lint method calls
72     foo();
73     let a = A;
74     a.foo();
75 }
76
77 ```
78
79 Now we can run the test with `TESTNAME=ui/foo_functions cargo uitest`.
80 Currently this test will fail. If you go through the output you will see that we
81 are told that `clippy::foo_functions` is an unknown lint, which is expected.
82
83 While we are working on implementing our lint, we can keep running the UI
84 test. That allows us to check if the output is turning into what we want.
85
86 Once we are satisfied with the output, we need to run
87 `tests/ui/update-all-references.sh` to update the `.stderr` file for our lint.
88 Running `TESTNAME=ui/foo_functions cargo uitest` should pass then. When we
89 commit our lint, we need to commit the generated `.stderr` files, too.
90
91 ### Rustfix tests
92
93 If the lint you are working on is making use of structured suggestions, the
94 test file should include a `// run-rustfix` comment at the top. This will
95 additionally run [rustfix](https://github.com/rust-lang-nursery/rustfix) for
96 that test. Rustfix will apply the suggestions from the lint to the code of the
97 test file and compare that to the contents of a `.fixed` file.
98
99 Use `tests/ui/update-all-references.sh` to automatically generate the
100 `.fixed` file after running the tests.
101
102 With tests in place, let's have a look at implementing our lint now.
103
104 ### Testing manually
105
106 Manually testing against an example file can be useful if you have added some
107 `println!`s and the test suite output becomes unreadable. To try Clippy with
108 your local modifications, run `env CLIPPY_TESTS=true cargo run --bin
109 clippy-driver -- -L ./target/debug input.rs` from the working copy root.
110
111 ### Lint declaration
112
113 We start by creating a new file in the `clippy_lints` crate. That's the crate
114 where all the lint code is. We are going to call the file
115 `clippy_lints/src/foo_functions.rs` and import some initial things we need:
116
117 ```rust
118 use rustc::lint::{LintArray, LintPass, EarlyLintPass};
119 use rustc::{declare_tool_lint, lint_array};
120 ```
121
122 The next step is to provide a lint declaration. Lints are declared using the
123 [`declare_clippy_lint!`][declare_clippy_lint] macro:
124
125 ```rust
126 declare_clippy_lint! {
127     pub FOO_FUNCTIONS,
128     pedantic,
129     "function named `foo`, which is not a descriptive name"
130 }
131 ```
132
133 * `FOO_FUNCTIONS` is the name of our lint. Be sure to follow the [lint naming
134 guidelines][lint_naming] here when naming your lint. In short, the name should
135 state the thing that is being checked for and read well when used with
136 `allow`/`warn`/`deny`.
137 * `pedantic` sets the lint level to `Allow`.
138   The exact mapping can be found [here][category_level_mapping]
139 * The last part should be a text that explains what exactly is wrong with the
140   code
141
142 With our lint declaration done, we will now make sure that it is assigned to a
143 lint pass:
144
145 ```rust
146 // clippy_lints/src/foo_functions.rs
147
148 // .. imports and lint declaration ..
149
150 #[derive(Copy, Clone)]
151 pub struct FooFunctionsPass;
152
153 impl LintPass for FooFunctionsPass {
154     fn get_lints(&self) -> LintArray {
155         lint_array!(
156             FOO_FUNCTIONS,
157         )
158     }
159
160     fn name(&self) -> &'static str {
161         "FooFunctions"
162     }
163 }
164
165 impl EarlyLintPass for FooFunctionsPass {}
166 ```
167
168 Don't worry about the `name` method here. As long as it includes the name of the
169 lint pass it should be fine.
170
171 Next we need to run `util/dev update_lints` to register the lint in various
172 places, mainly in `clippy_lints/src/lib.rs`.
173
174 While `update_lints` automates some things, it doesn't automate everything. We
175 will have to register our lint pass manually in the `register_plugins` function
176 in `clippy_lints/src/lib.rs`:
177
178 ```rust
179 reg.register_early_lint_pass(box foo_functions::FooFunctionsPass);
180 ```
181
182 This should fix the `unknown clippy lint: clippy::foo_functions` error that we
183 saw when we executed our tests the first time. The next decision we have to make
184 is which lint pass our lint is going to need.
185
186 ### Lint passes
187
188 Writing a lint that only checks for the name of a function means that we only
189 have to deal with the AST and don't have to deal with the type system at all.
190 This is good, because it makes writing this particular lint less complicated.
191
192 We have to make this decision with every new Clippy lint. It boils down to using
193 either [`EarlyLintPass`][early_lint_pass] or [`LateLintPass`][late_lint_pass].
194
195 In short, the `LateLintPass` has access to type information while the
196 `EarlyLintPass` doesn't. If you don't need access to type information, use the
197 `EarlyLintPass`. The `EarlyLintPass` is also faster. However linting speed
198 hasn't really been a concern with Clippy so far.
199
200 Since we don't need type information for checking the function name, we are
201 going to use the `EarlyLintPass`. It has to be imported as well, changing our
202 imports to:
203
204 ```rust
205 use rustc::lint::{LintArray, LintPass, EarlyLintPass, EarlyContext};
206 use rustc::{declare_tool_lint, lint_array};
207 ```
208
209 ### Emitting a lint
210
211 With UI tests and the lint declaration in place, we can start working on the
212 implementation of the lint logic.
213
214 Let's start by implementing the `EarlyLintPass` for our `FooFunctionsPass`:
215
216 ```rust
217 impl EarlyLintPass for FooFunctionsPass {
218     fn check_fn(&mut self, cx: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: &FnDecl, span: Span, _: NodeId) {
219         // TODO: Emit lint here
220     }
221 }
222 ```
223
224 We implement the [`check_fn`][check_fn] method from the
225 [`EarlyLintPass`][early_lint_pass] trait. This gives us access to various
226 information about the function that is currently being checked. More on that in
227 the next section. Let's worry about the details later and emit our lint for
228 *every* function definition first.
229
230 Depending on how complex we want our lint message to be, we can choose from a
231 variety of lint emission functions. They can all be found in
232 [`clippy_lints/src/utils/diagnostics.rs`][diagnostics].
233
234 `span_help_and_lint` seems most appropriate in this case. It allows us to
235 provide an extra help message and we can't really suggest a better name
236 automatically. This is how it looks:
237
238 ```rust
239 impl EarlyLintPass for Pass {
240     fn check_fn(&mut self, cx: &EarlyContext<'_>, _: FnKind<'_>, _: &FnDecl, span: Span, _: NodeId) {
241         span_help_and_lint(
242             cx,
243             FOO_FUNCTIONS,
244             span,
245             "function named `foo`",
246             "consider using a more meaningful name"
247         );
248     }
249 }
250 ```
251
252 Running our UI test should now produce output that contains the lint message.
253
254 ### Adding the lint logic
255
256 Writing the logic for your lint will most likely be different from our example,
257 so this section is kept rather short.
258
259 Using the [`check_fn`][check_fn] method gives us access to [`FnKind`][fn_kind]
260 that has two relevant variants for us `FnKind::ItemFn` and `FnKind::Method`.
261 Both provide access to the name of the function/method via an [`Ident`][ident].
262
263 With that we can expand our `check_fn` method to:
264
265 ```rust
266 impl EarlyLintPass for Pass {
267     fn check_fn(&mut self, cx: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: &FnDecl, span: Span, _: NodeId) {
268         if is_foo_fn(fn_kind) {
269             span_help_and_lint(
270                 cx,
271                 FOO_FUNCTIONS,
272                 span,
273                 "function named `foo`",
274                 "consider using a more meaningful name"
275             );
276         }
277     }
278 }
279 ```
280
281 We separate the lint conditional from the lint emissions because it makes the
282 code a bit easier to read. In some cases this separation would also allow to
283 write some unit tests (as opposed to only UI tests) for the separate function.
284
285 In our example, `is_foo_fn` looks like:
286
287 ```rust
288 // use statements, impl EarlyLintPass, check_fn, ..
289
290 fn is_foo_fn(fn_kind: FnKind<'_>) -> bool {
291     match fn_kind {
292         FnKind::ItemFn(ident, ..) | FnKind::Method(ident, ..) => {
293             ident.name == "foo"
294         },
295         FnKind::Closure(..) => false
296     }
297 }
298 ```
299
300 Now we should also run the full test suite with `cargo test`. At this point
301 running `cargo test` should produce the expected output. Remember to run
302 `tests/ui/update-all-references.sh` to update the `.stderr` file.
303
304 `cargo test` (as opposed to `cargo uitest`) will also ensure that our lint
305 implementation is not violating any Clippy lints itself.
306
307 If you are still following the example, you will see that `FooFunctionsPass`
308 violates a Clippy lint. So we are going to rename that struct to just `Pass`:
309
310 ```rust
311 #[derive(Copy, Clone)]
312 pub struct Pass;
313
314 impl LintPass for Pass { /* .. */ }
315 ```
316
317 That should be it for the lint implementation. Running `cargo test` should now
318 pass.
319
320 ### Author lint
321
322 If you have trouble implementing your lint, there is also the internal `author`
323 lint to generate Clippy code that detects the offending pattern. It does not
324 work for all of the Rust syntax, but can give a good starting point.
325
326 The quickest way to use it, is the [Rust playground][play].rust-lang.org).
327 Put the code you want to lint into the editor and add the `#[clippy::author]`
328 attribute above the item. Then run Clippy via `Tools -> Clippy` and you should
329 see the generated code in the output below.
330
331 [Here][author_example] is an example on the playground.
332
333 If the command was executed successfully, you can copy the code over to where
334 you are implementing your lint.
335
336 ### Documentation
337
338 The final thing before submitting our PR is to add some documentation to our
339 lint declaration.
340
341 Please document your lint with a doc comment akin to the following:
342
343 ```rust
344 declare_clippy_lint! {
345     /// **What it does:** Checks for ... (describe what the lint matches).
346     ///
347     /// **Why is this bad?** Supply the reason for linting the code.
348     ///
349     /// **Known problems:** None. (Or describe where it could go wrong.)
350     ///
351     /// **Example:**
352     ///
353     /// ```rust,ignore
354     /// // Bad
355     /// Insert a short example of code that triggers the lint
356     ///
357     /// // Good
358     /// Insert a short example of improved code that doesn't trigger the lint
359     /// ```
360     pub FOO_FUNCTIONS,
361     pedantic,
362     "function named `foo`, which is not a descriptive name"
363 }
364 ```
365
366 Once your lint is merged, this documentation will show up in the [lint
367 list][lint_list].
368
369 ### Running rustfmt
370
371 [Rustfmt](https://github.com/rust-lang/rustfmt) is a tool for formatting Rust code according
372 to style guidelines. Your code has to be formatted by `rustfmt` before a PR can be merged.
373
374 It can be installed via `rustup`:
375
376 ```bash
377 rustup component add rustfmt
378 ```
379
380 Use `cargo fmt --all` to format the whole codebase.
381
382 ### Debugging
383
384 If you want to debug parts of your lint implementation, you can use the `dbg!`
385 macro anywhere in your code. Running the tests should then include the debug
386 output in the `stdout` part.
387
388 ### PR Checklist
389
390 Before submitting your PR make sure you followed all of the basic requirements:
391
392 - [ ] Followed [lint naming conventions][lint_naming]
393 - [ ] Added passing UI tests (including committed `.stderr` file)
394 - [ ] `cargo test` passes locally
395 - [ ] Executed `util/dev update_lints`
396 - [ ] Added lint documentation
397
398 ### Cheatsheet
399
400 Here are some pointers to things you are likely going to need for every lint:
401
402 * [Clippy utils][utils] - Various helper functions. Maybe the function you need
403   is already in here (`implements_trait`, `match_path`, `snippet`, etc)
404 * [Clippy diagnostics][diagnostics]
405 * [The `if_chain` macro][if_chain]
406 * [`in_macro`][in_macro] and [`in_external_macro`][in_external_macro]
407 * [`Span`][span]
408 * [`Applicability`][applicability]
409 * [The rustc guide][rustc_guide] explains a lot of internal compiler concepts
410 * [The nightly rustc docs][nightly_docs] which has been linked to throughout
411   this guide
412
413 For `EarlyLintPass` lints:
414
415 * [`EarlyLintPass`][early_lint_pass]
416 * [`syntax::ast`][ast]
417
418 For `LateLintPass` lints:
419
420 * [`LateLintPass`][late_lint_pass]
421 * [`Ty::TyKind`][ty]
422
423
424 While most of Clippy's lint utils are documented, most of rustc's internals lack
425 documentation currently. This is unfortunate, but in most cases you can probably
426 get away with copying things from existing similar lints. If you are stuck,
427 don't hesitate to ask on Discord, IRC or in the issue/PR.
428
429 [lint_list]: https://rust-lang.github.io/rust-clippy/master/index.html
430 [lint_naming]: https://rust-lang.github.io/rfcs/0344-conventions-galore.html#lints
431 [category_level_mapping]: https://github.com/rust-lang/rust-clippy/blob/bd23cb89ec0ea63403a17d3fc5e50c88e38dd54f/clippy_lints/src/lib.rs#L43
432 [declare_clippy_lint]: https://github.com/rust-lang/rust-clippy/blob/a71acac1da7eaf667ab90a1d65d10e5cc4b80191/clippy_lints/src/lib.rs#L39
433 [compilation_stages]: https://rust-lang.github.io/rustc-guide/high-level-overview.html#the-main-stages-of-compilation
434 [check_fn]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/lint/trait.EarlyLintPass.html#method.check_fn
435 [early_lint_pass]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/lint/trait.EarlyLintPass.html
436 [late_lint_pass]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/lint/trait.LateLintPass.html
437 [fn_kind]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/visit/enum.FnKind.html
438 [diagnostics]: https://github.com/rust-lang/rust-clippy/blob/master/clippy_lints/src/utils/diagnostics.rs
439 [utils]: https://github.com/rust-lang/rust-clippy/blob/master/clippy_lints/src/utils/mod.rs
440 [ident]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/source_map/symbol/struct.Ident.html
441 [span]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax_pos/struct.Span.html
442 [applicability]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_errors/enum.Applicability.html
443 [if_chain]: https://docs.rs/if_chain/0.1.2/if_chain/
444 [ty]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/sty/index.html
445 [ast]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/ast/index.html
446 [in_macro]: https://github.com/rust-lang/rust-clippy/blob/d0717d1f9531a03d154aaeb0cad94c243915a146/clippy_lints/src/utils/mod.rs#L94
447 [in_external_macro]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/lint/fn.in_external_macro.html
448 [play]: https://play.rust-lang.org
449 [author_example]: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f093b986e80ad62f3b67a1f24f5e66e2
450 [rustc_guide]: https://rust-lang.github.io/rustc-guide/
451 [nightly_docs]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/