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