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.
11 * [Lint declaration](#Lint-declaration)
12 * [Lint passes](#Lint-passes)
13 * [Emitting a lint](#Emitting-a-lint)
14 * [Adding the lint logic](#Adding-the-lint-logic)
15 * [Documentation](#Documentation)
16 * [Debugging](#Debugging)
17 * [PR Checklist](#PR-Checklist)
18 * [Cheatsheet](#Cheatsheet)
22 Let's write some tests first that we can execute while we iterate on our lint.
24 Clippy uses UI tests for testing. UI tests check that the output of Clippy is
25 exactly as expected. Each test is just a plain Rust file that contains the code
26 we want to check. The output of Clippy is compared against a `.stderr` file.
28 Let's create the test file at `tests/ui/foo_functions.rs`. It doesn't really
29 matter what the file is called, but it's a good convention to name it after the
30 lint it is testing, so `foo_functions.rs` it is.
32 Inside we put some examples to get started:
35 #![warn(clippy::foo_functions)]
45 // Default trait methods
58 // We also don't want to lint method calls
66 Now we can run the test with `TESTNAME=ui/foo_functions cargo uitest`.
67 Currently this test will fail. If you go through the output you will see that we
68 have to add some missing imports to our lint file.
70 While you are working on implementing your lint, you can keep running the UI
71 test. That allows you to check if the output is turning into what you want.
73 Once you are satisfied with the output, you need to run
74 `tests/ui/update-all-references.sh` to update the `stderr` file for your lint.
75 Running `TESTNAME=ui/foo_functions cargo uitest` should pass then. When you
76 commit your lint, be sure to commit the `*.stderr` files, too.
78 Let's have a look at implementing our lint now.
82 We start by creating a new file in the `clippy_lints` crate. That's the crate
83 where all the lint code is. We are going to call the file
84 `clippy_lints/src/foo_functions.rs` and import some initial things we need:
87 use rustc::lint::{LintArray, LintPass};
88 use rustc::{declare_tool_lint, lint_array};
91 The next step is to provide a lint declaration. Lints are declared using the
92 [`declare_clippy_lint!`][declare_clippy_lint] macro:
95 declare_clippy_lint! {
98 "function named `foo`, which is not a descriptive name"
102 * `FOO_FUNCTIONS` is the name of our lint. Be sure to follow the [lint naming
103 guidelines][lint_naming] here when naming your lint. In short, the name should
104 state the thing that is being checked for and read well when used with
105 `allow`/`warn`/`deny`.
106 * `pedantic` sets the lint level to `Allow`.
107 The exact mapping can be found [here][category_level_mapping]
108 * The last part should be a text that explains what exactly is wrong with the
111 With our lint declaration done, we will now make sure that our lint declaration
112 is assigned to a lint pass:
115 // clippy_lints/src/foo_functions.rs
117 // .. imports and lint declaration ..
119 #[derive(Copy, Clone)]
120 pub struct FooFunctionsPass;
122 impl LintPass for FooFunctionsPass {
123 fn get_lints(&self) -> LintArray {
129 fn name(&self) -> &'static str {
135 Don't worry about the `name` method here. As long as it includes the name of the
136 lint pass it should be fine.
138 Next you should run `util/dev update_lints` to register the lint in various
139 places, mainly in `clippy_lints/src/lib.rs`.
141 While `update_lints` automates some things, it doesn't automate everything. We
142 will have to register our lint pass manually in the `register_plugins` function
143 in `clippy_lints/src/lib.rs`:
146 reg.register_early_lint_pass(box foo_functions::FooFunctionsPass);
149 Without that, running the UI tests would produce an error like `unknown clippy
150 lint: clippy::foo_functions`. The next decision we have to make is which lint
151 pass our lint is going to need.
155 Writing a lint that just checks for the name of a function means that we just
156 have to deal with the AST and don't have to deal with the type system at all.
157 This is good, because it makes writing this particular lint less complicated.
159 We have to make this decision with every new Clippy lint. It boils down to using
160 either [`EarlyLintPass`][early_lint_pass] or [`LateLintPass`][late_lint_pass].
161 This is a result of Rust's compilation process. You can read more about it [in
162 the rustc guide][compilation_stages].
164 In short, the `LateLintPass` has access to type information while the
165 `EarlyLintPass` doesn't. If you don't need access to type information, use the
166 `EarlyLintPass`. The `EarlyLintPass` is also faster. However linting speed
167 hasn't really been a concern with Clippy so far.
169 Since we don't need type information for checking the function name, we are
170 going to use the `EarlyLintPass`. It has to be imported as well, changing our
174 use rustc::lint::{LintArray, LintPass, EarlyLintPass, EarlyContext};
175 use rustc::{declare_tool_lint, lint_array};
180 With UI tests in place, we can start working on the implementation of the lint logic. We can keep executing the tests until we make them pass.
182 Let's start by implementing the `EarlyLintPass` for our `FooFunctionsPass`:
185 impl EarlyLintPass for FooFunctionsPass {
186 fn check_fn(&mut self, cx: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: &FnDecl, span: Span, _: NodeId) {
187 // TODO: Emit lint here
192 We implement the [`check_fn`][check_fn] method from the
193 [`EarlyLintPass`][early_lint_pass] trait. This gives us access to various
194 information about the function that is currently being checked. More on that in
195 the next section. Let's worry about the details later and emit our lint for
196 *every* function definition first.
198 Depending on how complex we want our lint message to be, we can choose from a
199 variety of lint emission functions. They can all be found in
200 [`clippy_lints/src/utils/diagnostics.rs`][diagnostics].
204 impl EarlyLintPass for Pass {
205 fn check_fn(&mut self, cx: &EarlyContext<'_>, _: FnKind<'_>, _: &FnDecl, span: Span, _: NodeId) {
210 "function named `foo`",
211 "consider using a more meaningful name"
217 ### Adding the lint logic
219 Writing the logic for your lint will most likely be different from this example,
220 so this section is kept rather short.
222 Using the [`check_fn`][check_fn] method gives us access to [`FnKind`][fn_kind]
223 that has two relevant variants for us `FnKind::ItemFn` and `FnKind::Method`.
224 Both provide access to the name of the function/method via an [`Ident`][ident].
226 With that we can expand our `check_fn` method to:
229 impl EarlyLintPass for Pass {
230 fn check_fn(&mut self, cx: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: &FnDecl, span: Span, _: NodeId) {
231 if !is_foo_fn(fn_kind) { return; }
236 "function named `foo`",
237 "consider using a more meaningful name"
243 We separate the lint conditional from the lint emissions because it makes the
244 code a bit easier to read. In some cases this separation would also allow to
245 write some unit tests (as opposed to UI tests) for the separate function.
247 In our example, `is_foo_fn` looks like:
250 // use statements, impl EarlyLintPass, check_fn, ..
252 fn is_foo_fn(fn_kind: FnKind<'_>) -> bool {
254 FnKind::ItemFn(ident, ..) | FnKind::Method(ident, ..) => {
257 FnKind::Closure(..) => false
262 Now you'll want to also run the full test suite with `cargo test`. Apart from
263 running all other UI tests, this ensures that our lint implementation is not
264 violating any Clippy lints itself.
266 If you are still following the example, you'll see that the `FooFunctionsPass`
267 violates a Clippy lint. So we are going to rename that struct to just `Pass`:
270 #[derive(Copy, Clone)]
273 impl LintPass for Pass { /* .. */ }
276 That should be it for the lint implementation. Running `cargo test` should now
277 pass and we can finish up our work by adding some documentation.
281 The final thing before submitting our PR is to add some documentation to our
284 Please document your lint with a doc comment akin to the following:
287 /// **What it does:** Checks for ... (describe what the lint matches).
289 /// **Why is this bad?** Supply the reason for linting the code.
291 /// **Known problems:** None. (Or describe where it could go wrong.)
297 /// Insert a short example of code that triggers the lint
300 /// Insert a short example of improved code that doesn't trigger the lint
302 declare_clippy_lint! { /* ... */ }
305 Once your lint is merged, this documentation will show up in the [lint
310 If you want to debug parts of your lint implementation, you can use the `dbg!`
311 macro anywhere in your code. Running the tests should then include the debug
312 output in the `stdout` part.
318 - [ ] Followed [lint naming conventions][lint_naming]
319 - [ ] Added passing UI tests (including committed `.stderr` file)
320 - [ ] `cargo test` passes locally
321 - [ ] Added lint documentation
325 Here are some pointers to things you are likely going to need for every lint:
327 * [The `if_chain` macro][if_chain]
328 * [`in_macro`][in_macro] and [`in_external_macro`][in_external_macro]
330 * [Clippy diagnostics][diagnostics]
331 * [`Applicability`][applicability]
333 For `EarlyLintPass` lints:
335 * [`EarlyLintPass`][early_lint_pass]
336 * [`syntax::ast`][ast]
338 For `LateLintPass` lints:
340 * [`LateLintPass`][late_lint_pass]
344 While most of Clippy's lint utils are documented, most of rustc's internals lack
345 documentation currently. This is unfortunate, but in most cases you can probably
346 get away with copying things from existing similar lints. If you are stuck,
347 don't hesitate to ask on Discord, IRC or in the issue/PR.
349 [lint_list]: https://rust-lang.github.io/rust-clippy/master/index.html
350 [lint_naming]: https://rust-lang.github.io/rfcs/0344-conventions-galore.html#lints
351 [category_level_mapping]: https://github.com/rust-lang/rust-clippy/blob/bd23cb89ec0ea63403a17d3fc5e50c88e38dd54f/clippy_lints/src/lib.rs#L43
352 [declare_clippy_lint]: https://github.com/rust-lang/rust-clippy/blob/a71acac1da7eaf667ab90a1d65d10e5cc4b80191/clippy_lints/src/lib.rs#L39
353 [compilation_stages]: https://rust-lang.github.io/rustc-guide/high-level-overview.html#the-main-stages-of-compilation
354 [check_fn]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/lint/trait.EarlyLintPass.html#method.check_fn
355 [early_lint_pass]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/lint/trait.EarlyLintPass.html
356 [late_lint_pass]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/lint/trait.LateLintPass.html
357 [fn_kind]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/visit/enum.FnKind.html
358 [diagnostics]: https://github.com/rust-lang/rust-clippy/blob/master/clippy_lints/src/utils/diagnostics.rs
359 [ident]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/source_map/symbol/struct.Ident.html
360 [span]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax_pos/struct.Span.html
361 [applicability]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_errors/enum.Applicability.html
362 [if_chain]: https://docs.rs/if_chain/0.1.2/if_chain/
363 [ty]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/sty/index.html
364 [ast]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/ast/index.html
365 [in_macro]: https://github.com/rust-lang/rust-clippy/blob/d0717d1f9531a03d154aaeb0cad94c243915a146/clippy_lints/src/utils/mod.rs#L94
366 [in_external_macro]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/lint/fn.in_external_macro.html