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