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.
7 To get started, we will create a lint that detects functions called `foo`,
8 because that's clearly a non-descriptive name.
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)
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.
34 Let's write some tests first that we can execute while we iterate on our lint.
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.
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.
46 Inside the file we put some examples to get started:
49 #![warn(clippy::foo_functions)]
59 // Default trait methods
72 // We also don't want to lint method calls
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.
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.
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 Running `TESTNAME=ui/foo_functions cargo uitest` should pass then. When we
90 commit our lint, we need to commit the generated `.stderr` files, too.
94 If the lint you are working on is making use of structured suggestions, the
95 test file should include a `// run-rustfix` comment at the top. This will
96 additionally run [rustfix](https://github.com/rust-lang-nursery/rustfix) for
97 that test. Rustfix will apply the suggestions from the lint to the code of the
98 test file and compare that to the contents of a `.fixed` file.
100 Use `tests/ui/update-all-references.sh` to automatically generate the
101 `.fixed` file after running the tests.
103 With tests in place, let's have a look at implementing our lint now.
105 ### Edition 2018 tests
107 Some features require the 2018 edition to work (e.g. `async_await`), but
108 compile-test tests run on the 2015 edition by default. To change this behavior
109 add `// compile-flags: --edition 2018` at the top of the test file.
113 Manually testing against an example file can be useful if you have added some
114 `println!`s and the test suite output becomes unreadable. To try Clippy with
115 your local modifications, run `env CLIPPY_TESTS=true cargo run --bin
116 clippy-driver -- -L ./target/debug input.rs` from the working copy root.
120 We start by creating a new file in the `clippy_lints` crate. That's the crate
121 where all the lint code is. We are going to call the file
122 `clippy_lints/src/foo_functions.rs` and import some initial things we need:
125 use rustc::lint::{LintArray, LintPass, EarlyLintPass};
126 use rustc::{declare_lint_pass, declare_tool_lint};
129 The next step is to provide a lint declaration. Lints are declared using the
130 [`declare_clippy_lint!`][declare_clippy_lint] macro:
133 declare_clippy_lint! {
136 "function named `foo`, which is not a descriptive name"
140 * `FOO_FUNCTIONS` is the name of our lint. Be sure to follow the [lint naming
141 guidelines][lint_naming] here when naming your lint. In short, the name should
142 state the thing that is being checked for and read well when used with
143 `allow`/`warn`/`deny`.
144 * `pedantic` sets the lint level to `Allow`.
145 The exact mapping can be found [here][category_level_mapping]
146 * The last part should be a text that explains what exactly is wrong with the
149 With our lint declaration done, we will now make sure that it is assigned to a
153 // clippy_lints/src/foo_functions.rs
155 // .. imports and lint declaration ..
157 declare_lint_pass!(FooFunctions => [FOO_FUNCTIONS]);
159 impl EarlyLintPass for FooFunctions {}
162 Don't worry about the `name` method here. As long as it includes the name of the
163 lint pass it should be fine.
165 Next we need to run `util/dev update_lints` to register the lint in various
166 places, mainly in `clippy_lints/src/lib.rs`.
168 While `update_lints` automates some things, it doesn't automate everything. We
169 will have to register our lint pass manually in the `register_plugins` function
170 in `clippy_lints/src/lib.rs`:
173 reg.register_early_lint_pass(box foo_functions::FooFunctions);
176 This should fix the `unknown clippy lint: clippy::foo_functions` error that we
177 saw when we executed our tests the first time. The next decision we have to make
178 is which lint pass our lint is going to need.
182 Writing a lint that only checks for the name of a function means that we only
183 have to deal with the AST and don't have to deal with the type system at all.
184 This is good, because it makes writing this particular lint less complicated.
186 We have to make this decision with every new Clippy lint. It boils down to using
187 either [`EarlyLintPass`][early_lint_pass] or [`LateLintPass`][late_lint_pass].
189 In short, the `LateLintPass` has access to type information while the
190 `EarlyLintPass` doesn't. If you don't need access to type information, use the
191 `EarlyLintPass`. The `EarlyLintPass` is also faster. However linting speed
192 hasn't really been a concern with Clippy so far.
194 Since we don't need type information for checking the function name, we are
195 going to use the `EarlyLintPass`. It has to be imported as well, changing our
199 use rustc::lint::{LintArray, LintPass, EarlyLintPass, EarlyContext};
200 use rustc::{declare_tool_lint, lint_array};
205 With UI tests and the lint declaration in place, we can start working on the
206 implementation of the lint logic.
208 Let's start by implementing the `EarlyLintPass` for our `FooFunctions`:
211 impl EarlyLintPass for FooFunctions {
212 fn check_fn(&mut self, cx: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: &FnDecl, span: Span, _: NodeId) {
213 // TODO: Emit lint here
218 We implement the [`check_fn`][check_fn] method from the
219 [`EarlyLintPass`][early_lint_pass] trait. This gives us access to various
220 information about the function that is currently being checked. More on that in
221 the next section. Let's worry about the details later and emit our lint for
222 *every* function definition first.
224 Depending on how complex we want our lint message to be, we can choose from a
225 variety of lint emission functions. They can all be found in
226 [`clippy_lints/src/utils/diagnostics.rs`][diagnostics].
228 `span_help_and_lint` seems most appropriate in this case. It allows us to
229 provide an extra help message and we can't really suggest a better name
230 automatically. This is how it looks:
233 impl EarlyLintPass for FooFunctions {
234 fn check_fn(&mut self, cx: &EarlyContext<'_>, _: FnKind<'_>, _: &FnDecl, span: Span, _: NodeId) {
239 "function named `foo`",
240 "consider using a more meaningful name"
246 Running our UI test should now produce output that contains the lint message.
248 ### Adding the lint logic
250 Writing the logic for your lint will most likely be different from our example,
251 so this section is kept rather short.
253 Using the [`check_fn`][check_fn] method gives us access to [`FnKind`][fn_kind]
254 that has two relevant variants for us `FnKind::ItemFn` and `FnKind::Method`.
255 Both provide access to the name of the function/method via an [`Ident`][ident].
257 With that we can expand our `check_fn` method to:
260 impl EarlyLintPass for FooFunctions {
261 fn check_fn(&mut self, cx: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: &FnDecl, span: Span, _: NodeId) {
262 if is_foo_fn(fn_kind) {
267 "function named `foo`",
268 "consider using a more meaningful name"
275 We separate the lint conditional from the lint emissions because it makes the
276 code a bit easier to read. In some cases this separation would also allow to
277 write some unit tests (as opposed to only UI tests) for the separate function.
279 In our example, `is_foo_fn` looks like:
282 // use statements, impl EarlyLintPass, check_fn, ..
284 fn is_foo_fn(fn_kind: FnKind<'_>) -> bool {
286 FnKind::ItemFn(ident, ..) | FnKind::Method(ident, ..) => {
289 FnKind::Closure(..) => false
294 Now we should also run the full test suite with `cargo test`. At this point
295 running `cargo test` should produce the expected output. Remember to run
296 `tests/ui/update-all-references.sh` to update the `.stderr` file.
298 `cargo test` (as opposed to `cargo uitest`) will also ensure that our lint
299 implementation is not violating any Clippy lints itself.
301 That should be it for the lint implementation. Running `cargo test` should now
306 If you have trouble implementing your lint, there is also the internal `author`
307 lint to generate Clippy code that detects the offending pattern. It does not
308 work for all of the Rust syntax, but can give a good starting point.
310 The quickest way to use it, is the [Rust playground][play].rust-lang.org).
311 Put the code you want to lint into the editor and add the `#[clippy::author]`
312 attribute above the item. Then run Clippy via `Tools -> Clippy` and you should
313 see the generated code in the output below.
315 [Here][author_example] is an example on the playground.
317 If the command was executed successfully, you can copy the code over to where
318 you are implementing your lint.
322 The final thing before submitting our PR is to add some documentation to our
325 Please document your lint with a doc comment akin to the following:
328 declare_clippy_lint! {
329 /// **What it does:** Checks for ... (describe what the lint matches).
331 /// **Why is this bad?** Supply the reason for linting the code.
333 /// **Known problems:** None. (Or describe where it could go wrong.)
339 /// Insert a short example of code that triggers the lint
342 /// Insert a short example of improved code that doesn't trigger the lint
346 "function named `foo`, which is not a descriptive name"
350 Once your lint is merged, this documentation will show up in the [lint
355 [Rustfmt](https://github.com/rust-lang/rustfmt) is a tool for formatting Rust
356 code according to style guidelines. Your code has to be formatted by `rustfmt`
357 before a PR can be merged. Clippy uses nightly `rustfmt` in the CI.
359 It can be installed via `rustup`:
362 rustup component add rustfmt --toolchain=nightly
365 Use `./util/dev fmt` to format the whole codebase. Make sure that `rustfmt` is
366 installed for the nightly toolchain.
370 If you want to debug parts of your lint implementation, you can use the `dbg!`
371 macro anywhere in your code. Running the tests should then include the debug
372 output in the `stdout` part.
376 Before submitting your PR make sure you followed all of the basic requirements:
378 <!-- Sync this with `.github/PULL_REQUEST_TEMPLATE` -->
380 - [ ] Followed [lint naming conventions][lint_naming]
381 - [ ] Added passing UI tests (including committed `.stderr` file)
382 - [ ] `cargo test` passes locally
383 - [ ] Executed `./util/dev update_lints`
384 - [ ] Added lint documentation
385 - [ ] Run `./util/dev fmt`
389 Here are some pointers to things you are likely going to need for every lint:
391 * [Clippy utils][utils] - Various helper functions. Maybe the function you need
392 is already in here (`implements_trait`, `match_path`, `snippet`, etc)
393 * [Clippy diagnostics][diagnostics]
394 * [The `if_chain` macro][if_chain]
395 * [`in_macro_or_desugar`][in_macro_or_desugar] and [`in_external_macro`][in_external_macro]
397 * [`Applicability`][applicability]
398 * [The rustc guide][rustc_guide] explains a lot of internal compiler concepts
399 * [The nightly rustc docs][nightly_docs] which has been linked to throughout
402 For `EarlyLintPass` lints:
404 * [`EarlyLintPass`][early_lint_pass]
405 * [`syntax::ast`][ast]
407 For `LateLintPass` lints:
409 * [`LateLintPass`][late_lint_pass]
413 While most of Clippy's lint utils are documented, most of rustc's internals lack
414 documentation currently. This is unfortunate, but in most cases you can probably
415 get away with copying things from existing similar lints. If you are stuck,
416 don't hesitate to ask on Discord, IRC or in the issue/PR.
418 [lint_list]: https://rust-lang.github.io/rust-clippy/master/index.html
419 [lint_naming]: https://rust-lang.github.io/rfcs/0344-conventions-galore.html#lints
420 [category_level_mapping]: https://github.com/rust-lang/rust-clippy/blob/bd23cb89ec0ea63403a17d3fc5e50c88e38dd54f/clippy_lints/src/lib.rs#L43
421 [declare_clippy_lint]: https://github.com/rust-lang/rust-clippy/blob/a71acac1da7eaf667ab90a1d65d10e5cc4b80191/clippy_lints/src/lib.rs#L39
422 [compilation_stages]: https://rust-lang.github.io/rustc-guide/high-level-overview.html#the-main-stages-of-compilation
423 [check_fn]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/lint/trait.EarlyLintPass.html#method.check_fn
424 [early_lint_pass]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/lint/trait.EarlyLintPass.html
425 [late_lint_pass]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/lint/trait.LateLintPass.html
426 [fn_kind]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/visit/enum.FnKind.html
427 [diagnostics]: https://github.com/rust-lang/rust-clippy/blob/master/clippy_lints/src/utils/diagnostics.rs
428 [utils]: https://github.com/rust-lang/rust-clippy/blob/master/clippy_lints/src/utils/mod.rs
429 [ident]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/source_map/symbol/struct.Ident.html
430 [span]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax_pos/struct.Span.html
431 [applicability]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_errors/enum.Applicability.html
432 [if_chain]: https://docs.rs/if_chain/0.1.2/if_chain/
433 [ty]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/sty/index.html
434 [ast]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/ast/index.html
435 [in_macro_or_desugar]: https://github.com/rust-lang/rust-clippy/blob/d0717d1f9531a03d154aaeb0cad94c243915a146/clippy_lints/src/utils/mod.rs#L94
436 [in_external_macro]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/lint/fn.in_external_macro.html
437 [play]: https://play.rust-lang.org
438 [author_example]: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f093b986e80ad62f3b67a1f24f5e66e2
439 [rustc_guide]: https://rust-lang.github.io/rustc-guide/
440 [nightly_docs]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/