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