Reformat internal docs

This reformats all the internal docs, so that the md files use at most
80 characters per line. This is the usual formatting of md files. We
allow 120 chars per line in CI though.
This commit is contained in:
flip1995 2022-01-21 17:27:57 +01:00 committed by Philipp Krones
parent 206ec6e2f6
commit d6b013ff9e
No known key found for this signature in database
GPG Key ID: 1CA0DF2AF59D68A5
6 changed files with 326 additions and 273 deletions

View File

@ -45,9 +45,9 @@ take a look at our [lint naming guidelines][lint_naming]. To get started on this
lint you can run `cargo dev new_lint --name=foo_functions --pass=early
--category=pedantic` (category will default to nursery if not provided). This
command will create two files: `tests/ui/foo_functions.rs` and
`clippy_lints/src/foo_functions.rs`, as well as
[registering the lint](#lint-registration). For cargo lints, two project
hierarchies (fail/pass) will be created by default under `tests/ui-cargo`.
`clippy_lints/src/foo_functions.rs`, as well as [registering the
lint](#lint-registration). For cargo lints, two project hierarchies (fail/pass)
will be created by default under `tests/ui-cargo`.
Next, we'll open up these files and add our lint!
@ -58,8 +58,8 @@ Let's write some tests first that we can execute while we iterate on our lint.
Clippy uses UI tests for testing. UI tests check that the output of Clippy is
exactly as expected. Each test is just a plain Rust file that contains the code
we want to check. The output of Clippy is compared against a `.stderr` file.
Note that you don't have to create this file yourself, we'll get to
generating the `.stderr` files further down.
Note that you don't have to create this file yourself, we'll get to generating
the `.stderr` files further down.
We start by opening the test file created at `tests/ui/foo_functions.rs`.
@ -96,52 +96,54 @@ fn main() {
}
```
Now we can run the test with `TESTNAME=foo_functions cargo uitest`,
currently this test is meaningless though.
Now we can run the test with `TESTNAME=foo_functions cargo uitest`, currently
this test is meaningless though.
While we are working on implementing our lint, we can keep running the UI
test. That allows us to check if the output is turning into what we want.
While we are working on implementing our lint, we can keep running the UI test.
That allows us to check if the output is turning into what we want.
Once we are satisfied with the output, we need to run
`cargo dev bless` to update the `.stderr` file for our lint.
Please note that, we should run `TESTNAME=foo_functions cargo uitest`
every time before running `cargo dev bless`.
Running `TESTNAME=foo_functions cargo uitest` should pass then. When we commit
our lint, we need to commit the generated `.stderr` files, too. In general, you
should only commit files changed by `cargo dev bless` for the
Once we are satisfied with the output, we need to run `cargo dev bless` to
update the `.stderr` file for our lint. Please note that, we should run
`TESTNAME=foo_functions cargo uitest` every time before running `cargo dev
bless`. Running `TESTNAME=foo_functions cargo uitest` should pass then. When we
commit our lint, we need to commit the generated `.stderr` files, too. In
general, you should only commit files changed by `cargo dev bless` for the
specific lint you are creating/editing. Note that if the generated files are
empty, they should be removed.
Note that you can run multiple test files by specifying a comma separated list:
`TESTNAME=foo_functions,test2,test3`.
> _Note:_ you can run multiple test files by specifying a comma separated list:
> `TESTNAME=foo_functions,test2,test3`.
### Cargo lints
For cargo lints, the process of testing differs in that we are interested in
the `Cargo.toml` manifest file. We also need a minimal crate associated
with that manifest.
For cargo lints, the process of testing differs in that we are interested in the
`Cargo.toml` manifest file. We also need a minimal crate associated with that
manifest.
If our new lint is named e.g. `foo_categories`, after running `cargo dev new_lint`
we will find by default two new crates, each with its manifest file:
If our new lint is named e.g. `foo_categories`, after running `cargo dev
new_lint` we will find by default two new crates, each with its manifest file:
* `tests/ui-cargo/foo_categories/fail/Cargo.toml`: this file should cause the new lint to raise an error.
* `tests/ui-cargo/foo_categories/pass/Cargo.toml`: this file should not trigger the lint.
* `tests/ui-cargo/foo_categories/fail/Cargo.toml`: this file should cause the
new lint to raise an error.
* `tests/ui-cargo/foo_categories/pass/Cargo.toml`: this file should not trigger
the lint.
If you need more cases, you can copy one of those crates (under `foo_categories`) and rename it.
If you need more cases, you can copy one of those crates (under
`foo_categories`) and rename it.
The process of generating the `.stderr` file is the same, and prepending the `TESTNAME`
variable to `cargo uitest` works too.
The process of generating the `.stderr` file is the same, and prepending the
`TESTNAME` variable to `cargo uitest` works too.
## Rustfix tests
If the lint you are working on is making use of structured suggestions, the
test file should include a `// run-rustfix` comment at the top. This will
If the lint you are working on is making use of structured suggestions, the test
file should include a `// run-rustfix` comment at the top. This will
additionally run [rustfix] for that test. Rustfix will apply the suggestions
from the lint to the code of the test file and compare that to the contents of
a `.fixed` file.
from the lint to the code of the test file and compare that to the contents of a
`.fixed` file.
Use `cargo dev bless` to automatically generate the
`.fixed` file after running the tests.
Use `cargo dev bless` to automatically generate the `.fixed` file after running
the tests.
[rustfix]: https://github.com/rust-lang/rustfix
@ -149,7 +151,8 @@ Use `cargo dev bless` to automatically generate the
Some features require the 2018 edition to work (e.g. `async_await`), but
compile-test tests run on the 2015 edition by default. To change this behavior
add `// edition:2018` at the top of the test file (note that it's space-sensitive).
add `// edition:2018` at the top of the test file (note that it's
space-sensitive).
## Testing manually
@ -166,9 +169,9 @@ implementing our lint now.
## Lint declaration
Let's start by opening the new file created in the `clippy_lints` crate
at `clippy_lints/src/foo_functions.rs`. That's the crate where all the
lint code is. This file has already imported some initial things we will need:
Let's start by opening the new file created in the `clippy_lints` crate at
`clippy_lints/src/foo_functions.rs`. That's the crate where all the lint code
is. This file has already imported some initial things we will need:
```rust
use rustc_lint::{EarlyLintPass, EarlyContext};
@ -178,7 +181,8 @@ use rustc_ast::ast::*;
The next step is to update the lint declaration. Lints are declared using the
[`declare_clippy_lint!`][declare_clippy_lint] macro, and we just need to update
the auto-generated lint declaration to have a real description, something like this:
the auto-generated lint declaration to have a real description, something like
this:
```rust
declare_clippy_lint! {
@ -198,24 +202,25 @@ declare_clippy_lint! {
```
* The section of lines prefixed with `///` constitutes the lint documentation
section. This is the default documentation style and will be displayed
[like this][example_lint_page]. To render and open this documentation locally
in a browser, run `cargo dev serve`.
* The `#[clippy::version]` attribute will be rendered as part of the lint documentation.
The value should be set to the current Rust version that the lint is developed in,
it can be retrieved by running `rustc -vV` in the rust-clippy directory. The version
is listed under *release*. (Use the version without the `-nightly`) suffix.
* `FOO_FUNCTIONS` is the name of our lint. Be sure to follow the
[lint naming guidelines][lint_naming] here when naming your lint.
In short, the name should state the thing that is being checked for and
read well when used with `allow`/`warn`/`deny`.
* `pedantic` sets the lint level to `Allow`.
The exact mapping can be found [here][category_level_mapping]
section. This is the default documentation style and will be displayed [like
this][example_lint_page]. To render and open this documentation locally in a
browser, run `cargo dev serve`.
* The `#[clippy::version]` attribute will be rendered as part of the lint
documentation. The value should be set to the current Rust version that the
lint is developed in, it can be retrieved by running `rustc -vV` in the
rust-clippy directory. The version is listed under *release*. (Use the version
without the `-nightly`) suffix.
* `FOO_FUNCTIONS` is the name of our lint. Be sure to follow the [lint naming
guidelines][lint_naming] here when naming your lint. In short, the name should
state the thing that is being checked for and read well when used with
`allow`/`warn`/`deny`.
* `pedantic` sets the lint level to `Allow`. The exact mapping can be found
[here][category_level_mapping]
* The last part should be a text that explains what exactly is wrong with the
code
The rest of this file contains an empty implementation for our lint pass,
which in this case is `EarlyLintPass` and should look like this:
The rest of this file contains an empty implementation for our lint pass, which
in this case is `EarlyLintPass` and should look like this:
```rust
// clippy_lints/src/foo_functions.rs
@ -324,9 +329,9 @@ impl EarlyLintPass for FooFunctions {
Running our UI test should now produce output that contains the lint message.
According to [the rustc-dev-guide], the text should be matter of fact and avoid
capitalization and periods, unless multiple sentences are needed.
When code or an identifier must appear in a message or label, it should be
surrounded with single grave accents \`.
capitalization and periods, unless multiple sentences are needed. When code or
an identifier must appear in a message or label, it should be surrounded with
single grave accents \`.
[check_fn]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_lint/trait.EarlyLintPass.html#method.check_fn
[diagnostics]: https://github.com/rust-lang/rust-clippy/blob/master/clippy_utils/src/diagnostics.rs
@ -382,8 +387,8 @@ fn is_foo_fn(fn_kind: FnKind<'_>) -> bool {
```
Now we should also run the full test suite with `cargo test`. At this point
running `cargo test` should produce the expected output. Remember to run
`cargo dev bless` to update the `.stderr` file.
running `cargo test` should produce the expected output. Remember to run `cargo
dev bless` to update the `.stderr` file.
`cargo test` (as opposed to `cargo uitest`) will also ensure that our lint
implementation is not violating any Clippy lints itself.
@ -397,13 +402,16 @@ pass.
## Specifying the lint's minimum supported Rust version (MSRV)
Sometimes a lint makes suggestions that require a certain version of Rust. For example, the `manual_strip` lint suggests
using `str::strip_prefix` and `str::strip_suffix` which is only available after Rust 1.45. In such cases, you need to
ensure that the MSRV configured for the project is >= the MSRV of the required Rust feature. If multiple features are
required, just use the one with a lower MSRV.
Sometimes a lint makes suggestions that require a certain version of Rust. For
example, the `manual_strip` lint suggests using `str::strip_prefix` and
`str::strip_suffix` which is only available after Rust 1.45. In such cases, you
need to ensure that the MSRV configured for the project is >= the MSRV of the
required Rust feature. If multiple features are required, just use the one with
a lower MSRV.
First, add an MSRV alias for the required feature in [`clippy_utils::msrvs`](/clippy_utils/src/msrvs.rs). This can be
accessed later as `msrvs::STR_STRIP_PREFIX`, for example.
First, add an MSRV alias for the required feature in
[`clippy_utils::msrvs`](/clippy_utils/src/msrvs.rs). This can be accessed later
as `msrvs::STR_STRIP_PREFIX`, for example.
```rust
msrv_aliases! {
@ -412,8 +420,9 @@ msrv_aliases! {
}
```
In order to access the project-configured MSRV, you need to have an `msrv` field in the LintPass struct, and a
constructor to initialize the field. The `msrv` value is passed to the constructor in `clippy_lints/lib.rs`.
In order to access the project-configured MSRV, you need to have an `msrv` field
in the LintPass struct, and a constructor to initialize the field. The `msrv`
value is passed to the constructor in `clippy_lints/lib.rs`.
```rust
pub struct ManualStrip {
@ -472,11 +481,10 @@ If you have trouble implementing your lint, there is also the internal `author`
lint to generate Clippy code that detects the offending pattern. It does not
work for all of the Rust syntax, but can give a good starting point.
The quickest way to use it, is the
[Rust playground: play.rust-lang.org][author_example].
Put the code you want to lint into the editor and add the `#[clippy::author]`
attribute above the item. Then run Clippy via `Tools -> Clippy` and you should
see the generated code in the output below.
The quickest way to use it, is the [Rust playground:
play.rust-lang.org][author_example]. Put the code you want to lint into the
editor and add the `#[clippy::author]` attribute above the item. Then run Clippy
via `Tools -> Clippy` and you should see the generated code in the output below.
[Here][author_example] is an example on the playground.
@ -487,13 +495,15 @@ you are implementing your lint.
## Print HIR lint
To implement a lint, it's helpful to first understand the internal representation
that rustc uses. Clippy has the `#[clippy::dump]` attribute that prints the
[_High-Level Intermediate Representation (HIR)_] of the item, statement, or
expression that the attribute is attached to. To attach the attribute to expressions
you often need to enable `#![feature(stmt_expr_attributes)]`.
To implement a lint, it's helpful to first understand the internal
representation that rustc uses. Clippy has the `#[clippy::dump]` attribute that
prints the [_High-Level Intermediate Representation (HIR)_] of the item,
statement, or expression that the attribute is attached to. To attach the
attribute to expressions you often need to enable
`#![feature(stmt_expr_attributes)]`.
[Here][print_hir_example] you can find an example, just select _Tools_ and run _Clippy_.
[Here][print_hir_example] you can find an example, just select _Tools_ and run
_Clippy_.
[_High-Level Intermediate Representation (HIR)_]: https://rustc-dev-guide.rust-lang.org/hir.html
[print_hir_example]: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=daf14db3a7f39ca467cd1b86c34b9afb
@ -518,7 +528,7 @@ declare_clippy_lint! {
/// ```rust,ignore
/// // A short example of code that triggers the lint
/// ```
///
///
/// Use instead:
/// ```rust,ignore
/// // A short example of improved code that doesn't trigger the lint
@ -537,9 +547,9 @@ list][lint_list].
## Running rustfmt
[Rustfmt] is a tool for formatting Rust code according to style guidelines.
Your code has to be formatted by `rustfmt` before a PR can be merged.
Clippy uses nightly `rustfmt` in the CI.
[Rustfmt] is a tool for formatting Rust code according to style guidelines. Your
code has to be formatted by `rustfmt` before a PR can be merged. Clippy uses
nightly `rustfmt` in the CI.
It can be installed via `rustup`:
@ -575,94 +585,105 @@ Before submitting your PR make sure you followed all of the basic requirements:
## Adding configuration to a lint
Clippy supports the configuration of lints values using a `clippy.toml` file in the workspace
directory. Adding a configuration to a lint can be useful for thresholds or to constrain some
behavior that can be seen as a false positive for some users. Adding a configuration is done
in the following steps:
Clippy supports the configuration of lints values using a `clippy.toml` file in
the workspace directory. Adding a configuration to a lint can be useful for
thresholds or to constrain some behavior that can be seen as a false positive
for some users. Adding a configuration is done in the following steps:
1. Adding a new configuration entry to [clippy_lints::utils::conf](/clippy_lints/src/utils/conf.rs)
like this:
```rust
/// Lint: LINT_NAME.
///
/// <The configuration field doc comment>
(configuration_ident: Type = DefaultValue),
```
The doc comment is automatically added to the documentation of the listed lints. The default
value will be formatted using the `Debug` implementation of the type.
1. Adding a new configuration entry to
[clippy_lints::utils::conf](/clippy_lints/src/utils/conf.rs) like this:
```rust
/// Lint: LINT_NAME.
///
/// <The configuration field doc comment>
(configuration_ident: Type = DefaultValue),
```
The doc comment is automatically added to the documentation of the listed
lints. The default value will be formatted using the `Debug` implementation
of the type.
2. Adding the configuration value to the lint impl struct:
1. This first requires the definition of a lint impl struct. Lint impl structs are usually
generated with the `declare_lint_pass!` macro. This struct needs to be defined manually
to add some kind of metadata to it:
```rust
// Generated struct definition
declare_lint_pass!(StructName => [
LINT_NAME
]);
1. This first requires the definition of a lint impl struct. Lint impl
structs are usually generated with the `declare_lint_pass!` macro. This
struct needs to be defined manually to add some kind of metadata to it:
```rust
// Generated struct definition
declare_lint_pass!(StructName => [
LINT_NAME
]);
// New manual definition struct
#[derive(Copy, Clone)]
pub struct StructName {}
// New manual definition struct
#[derive(Copy, Clone)]
pub struct StructName {}
impl_lint_pass!(StructName => [
LINT_NAME
]);
```
impl_lint_pass!(StructName => [
LINT_NAME
]);
```
2. Next add the configuration value and a corresponding creation method like this:
```rust
#[derive(Copy, Clone)]
pub struct StructName {
configuration_ident: Type,
}
2. Next add the configuration value and a corresponding creation method like
this:
```rust
#[derive(Copy, Clone)]
pub struct StructName {
configuration_ident: Type,
}
// ...
// ...
impl StructName {
pub fn new(configuration_ident: Type) -> Self {
Self {
configuration_ident,
}
}
}
```
impl StructName {
pub fn new(configuration_ident: Type) -> Self {
Self {
configuration_ident,
}
}
}
```
3. Passing the configuration value to the lint impl struct:
First find the struct construction in the [clippy_lints lib file](/clippy_lints/src/lib.rs).
The configuration value is now cloned or copied into a local value that is then passed to the
impl struct like this:
```rust
// Default generated registration:
store.register_*_pass(|| box module::StructName);
First find the struct construction in the [clippy_lints lib
file](/clippy_lints/src/lib.rs). The configuration value is now cloned or
copied into a local value that is then passed to the impl struct like this:
// New registration with configuration value
let configuration_ident = conf.configuration_ident.clone();
store.register_*_pass(move || box module::StructName::new(configuration_ident));
```
```rust
// Default generated registration:
store.register_*_pass(|| box module::StructName);
Congratulations the work is almost done. The configuration value can now be accessed
in the linting code via `self.configuration_ident`.
// New registration with configuration value
let configuration_ident = conf.configuration_ident.clone();
store.register_*_pass(move || box module::StructName::new(configuration_ident));
```
Congratulations the work is almost done. The configuration value can now be
accessed in the linting code via `self.configuration_ident`.
4. Adding tests:
1. The default configured value can be tested like any normal lint in [`tests/ui`](/tests/ui).
2. The configuration itself will be tested separately in [`tests/ui-toml`](/tests/ui-toml).
Simply add a new subfolder with a fitting name. This folder contains a `clippy.toml` file
with the configuration value and a rust file that should be linted by Clippy. The test can
otherwise be written as usual.
1. The default configured value can be tested like any normal lint in
[`tests/ui`](/tests/ui).
2. The configuration itself will be tested separately in
[`tests/ui-toml`](/tests/ui-toml). Simply add a new subfolder with a
fitting name. This folder contains a `clippy.toml` file with the
configuration value and a rust file that should be linted by Clippy. The
test can otherwise be written as usual.
## Cheat Sheet
Here are some pointers to things you are likely going to need for every lint:
* [Clippy utils][utils] - Various helper functions. Maybe the function you need
is already in here ([`is_type_diagnostic_item`], [`implements_trait`], [`snippet`], etc)
is already in here ([`is_type_diagnostic_item`], [`implements_trait`],
[`snippet`], etc)
* [Clippy diagnostics][diagnostics]
* [Let chains][let-chains]
* [`from_expansion`][from_expansion] and [`in_external_macro`][in_external_macro]
* [`from_expansion`][from_expansion] and
[`in_external_macro`][in_external_macro]
* [`Span`][span]
* [`Applicability`][applicability]
* [Common tools for writing lints](common_tools_writing_lints.md) helps with common operations
* [The rustc-dev-guide][rustc-dev-guide] explains a lot of internal compiler concepts
* [Common tools for writing lints](common_tools_writing_lints.md) helps with
common operations
* [The rustc-dev-guide][rustc-dev-guide] explains a lot of internal compiler
concepts
* [The nightly rustc docs][nightly_docs] which has been linked to throughout
this guide

View File

@ -1,8 +1,8 @@
# Basics for hacking on Clippy
This document explains the basics for hacking on Clippy. Besides others, this
includes how to build and test Clippy. For a more in depth description on
the codebase take a look at [Adding Lints] or [Common Tools].
includes how to build and test Clippy. For a more in depth description on the
codebase take a look at [Adding Lints] or [Common Tools].
[Adding Lints]: https://github.com/rust-lang/rust-clippy/blob/master/doc/adding_lints.md
[Common Tools]: https://github.com/rust-lang/rust-clippy/blob/master/doc/common_tools_writing_lints.md
@ -62,8 +62,8 @@ TESTNAME="test_" cargo uitest
cargo test --test dogfood
```
If the output of a [UI test] differs from the expected output, you can update the
reference file with:
If the output of a [UI test] differs from the expected output, you can update
the reference file with:
```bash
cargo dev bless
@ -72,8 +72,8 @@ cargo dev bless
For example, this is necessary, if you fix a typo in an error message of a lint
or if you modify a test file to add a test case.
_Note:_ This command may update more files than you intended. In that case only
commit the files you wanted to update.
> _Note:_ This command may update more files than you intended. In that case
> only commit the files you wanted to update.
[UI test]: https://rustc-dev-guide.rust-lang.org/tests/adding.html#guide-to-the-ui-tests
@ -96,22 +96,26 @@ cargo dev setup git-hook
# (experimental) Setup Clippy to work with IntelliJ-Rust
cargo dev setup intellij
```
More about intellij command usage and reasons [here](../CONTRIBUTING.md#intellij-rust)
More about intellij command usage and reasons
[here](../CONTRIBUTING.md#intellij-rust)
## lintcheck
`cargo lintcheck` will build and run clippy on a fixed set of crates and generate a log of the results.
You can `git diff` the updated log against its previous version and
see what impact your lint made on a small set of crates.
If you add a new lint, please audit the resulting warnings and make sure
there are no false positives and that the suggestions are valid.
`cargo lintcheck` will build and run clippy on a fixed set of crates and
generate a log of the results. You can `git diff` the updated log against its
previous version and see what impact your lint made on a small set of crates.
If you add a new lint, please audit the resulting warnings and make sure there
are no false positives and that the suggestions are valid.
Refer to the tools [README] for more details.
[README]: https://github.com/rust-lang/rust-clippy/blob/master/lintcheck/README.md
## PR
We follow a rustc no merge-commit policy.
See <https://rustc-dev-guide.rust-lang.org/contributing.html#opening-a-pr>.
We follow a rustc no merge-commit policy. See
<https://rustc-dev-guide.rust-lang.org/contributing.html#opening-a-pr>.
## Common Abbreviations
@ -126,27 +130,34 @@ See <https://rustc-dev-guide.rust-lang.org/contributing.html#opening-a-pr>.
| HIR | High-Level Intermediate Representation |
| TCX | Type context |
This is a concise list of abbreviations that can come up during Clippy development. An extensive
general list can be found in the [rustc-dev-guide glossary][glossary]. Always feel free to ask if
an abbreviation or meaning is unclear to you.
This is a concise list of abbreviations that can come up during Clippy
development. An extensive general list can be found in the [rustc-dev-guide
glossary][glossary]. Always feel free to ask if an abbreviation or meaning is
unclear to you.
## Install from source
If you are hacking on Clippy and want to install it from source, do the following:
If you are hacking on Clippy and want to install it from source, do the
following:
First, take note of the toolchain [override](https://rust-lang.github.io/rustup/overrides.html) in `/rust-toolchain`.
We will use this override to install Clippy into the right toolchain.
First, take note of the toolchain
[override](https://rust-lang.github.io/rustup/overrides.html) in
`/rust-toolchain`. We will use this override to install Clippy into the right
toolchain.
> Tip: You can view the active toolchain for the current directory with `rustup show active-toolchain`.
> Tip: You can view the active toolchain for the current directory with `rustup
> show active-toolchain`.
From the Clippy project root, run the following command to build the Clippy binaries and copy them into the
toolchain directory. This will override the currently installed Clippy component.
From the Clippy project root, run the following command to build the Clippy
binaries and copy them into the toolchain directory. This will override the
currently installed Clippy component.
```terminal
cargo build --release --bin cargo-clippy --bin clippy-driver -Zunstable-options --out-dir "$(rustc --print=sysroot)/bin"
```
Now you may run `cargo clippy` in any project, using the toolchain where you just installed Clippy.
Now you may run `cargo clippy` in any project, using the toolchain where you
just installed Clippy.
```terminal
cd my-project
@ -159,16 +170,19 @@ cargo +nightly-2021-07-01 clippy
clippy-driver +nightly-2021-07-01 <filename>
```
If you need to restore the default Clippy installation, run the following (from the Clippy project root).
If you need to restore the default Clippy installation, run the following (from
the Clippy project root).
```terminal
rustup component remove clippy
rustup component add clippy
```
> **DO NOT** install using `cargo install --path . --force` since this will overwrite rustup
> [proxies](https://rust-lang.github.io/rustup/concepts/proxies.html). That is, `~/.cargo/bin/cargo-clippy` and
> `~/.cargo/bin/clippy-driver` should be hard or soft links to `~/.cargo/bin/rustup`. You can repair these by running
> `rustup update`.
> **DO NOT** install using `cargo install --path . --force` since this will
> overwrite rustup
> [proxies](https://rust-lang.github.io/rustup/concepts/proxies.html). That is,
> `~/.cargo/bin/cargo-clippy` and `~/.cargo/bin/clippy-driver` should be hard or
> soft links to `~/.cargo/bin/rustup`. You can repair these by running `rustup
> update`.
[glossary]: https://rustc-dev-guide.rust-lang.org/appendix/glossary.html

View File

@ -18,15 +18,17 @@ Useful Rustc dev guide links:
## Retrieving the type of an expression
Sometimes you may want to retrieve the type `Ty` of an expression `Expr`, for example to answer following questions:
Sometimes you may want to retrieve the type `Ty` of an expression `Expr`, for
example to answer following questions:
- which type does this expression correspond to (using its [`TyKind`][TyKind])?
- is it a sized type?
- is it a primitive type?
- does it implement a trait?
This operation is performed using the [`expr_ty()`][expr_ty] method from the [`TypeckResults`][TypeckResults] struct,
that gives you access to the underlying structure [`Ty`][Ty].
This operation is performed using the [`expr_ty()`][expr_ty] method from the
[`TypeckResults`][TypeckResults] struct, that gives you access to the underlying
structure [`Ty`][Ty].
Example of use:
```rust
@ -43,8 +45,8 @@ impl LateLintPass<'_> for MyStructLint {
}
```
Similarly in [`TypeckResults`][TypeckResults] methods, you have the [`pat_ty()`][pat_ty] method
to retrieve a type from a pattern.
Similarly in [`TypeckResults`][TypeckResults] methods, you have the
[`pat_ty()`][pat_ty] method to retrieve a type from a pattern.
Two noticeable items here:
- `cx` is the lint context [`LateContext`][LateContext]. The two most useful
@ -52,12 +54,13 @@ Two noticeable items here:
`LateContext::typeck_results`, allowing us to jump to type definitions and
other compilation stages such as HIR.
- `typeck_results`'s return value is [`TypeckResults`][TypeckResults] and is
created by type checking step, it includes useful information such as types
of expressions, ways to resolve methods and so on.
created by type checking step, it includes useful information such as types of
expressions, ways to resolve methods and so on.
## Checking if an expr is calling a specific method
Starting with an `expr`, you can check whether it is calling a specific method `some_method`:
Starting with an `expr`, you can check whether it is calling a specific method
`some_method`:
```rust
impl<'tcx> LateLintPass<'tcx> for MyStructLint {
@ -77,8 +80,9 @@ impl<'tcx> LateLintPass<'tcx> for MyStructLint {
## Checking for a specific type
There are three ways to check if an expression type is a specific type we want to check for.
All of these methods only check for the base type, generic arguments have to be checked separately.
There are three ways to check if an expression type is a specific type we want
to check for. All of these methods only check for the base type, generic
arguments have to be checked separately.
```rust
use clippy_utils::ty::{is_type_diagnostic_item, is_type_lang_item};
@ -115,7 +119,8 @@ Prefer using diagnostic items and lang items where possible.
## Checking if a type implements a specific trait
There are three ways to do this, depending on if the target trait has a diagnostic item, lang item or neither.
There are three ways to do this, depending on if the target trait has a
diagnostic item, lang item or neither.
```rust
use clippy_utils::{implements_trait, is_trait_method, match_trait_method, paths};
@ -151,8 +156,9 @@ impl LateLintPass<'_> for MyStructLint {
> Prefer using diagnostic and lang items, if the target trait has one.
We access lang items through the type context `tcx`. `tcx` is of type [`TyCtxt`][TyCtxt] and is defined in the `rustc_middle` crate.
A list of defined paths for Clippy can be found in [paths.rs][paths]
We access lang items through the type context `tcx`. `tcx` is of type
[`TyCtxt`][TyCtxt] and is defined in the `rustc_middle` crate. A list of defined
paths for Clippy can be found in [paths.rs][paths]
## Checking if a type defines a specific method
@ -182,14 +188,15 @@ impl<'tcx> LateLintPass<'tcx> for MyTypeImpl {
## Dealing with macros and expansions
Keep in mind that macros are already expanded and desugaring is already applied
to the code representation that you are working with in Clippy. This unfortunately causes a lot of
false positives because macro expansions are "invisible" unless you actively check for them.
Generally speaking, code with macro expansions should just be ignored by Clippy because that code can be
dynamic in ways that are difficult or impossible to see.
Use the following functions to deal with macros:
to the code representation that you are working with in Clippy. This
unfortunately causes a lot of false positives because macro expansions are
"invisible" unless you actively check for them. Generally speaking, code with
macro expansions should just be ignored by Clippy because that code can be
dynamic in ways that are difficult or impossible to see. Use the following
functions to deal with macros:
- `span.from_expansion()`: detects if a span is from macro expansion or desugaring.
Checking this is a common first step in a lint.
- `span.from_expansion()`: detects if a span is from macro expansion or
desugaring. Checking this is a common first step in a lint.
```rust
if expr.span.from_expansion() {
@ -198,45 +205,51 @@ Use the following functions to deal with macros:
}
```
- `span.ctxt()`: the span's context represents whether it is from expansion, and if so, which macro call expanded it.
It is sometimes useful to check if the context of two spans are equal.
- `span.ctxt()`: the span's context represents whether it is from expansion, and
if so, which macro call expanded it. It is sometimes useful to check if the
context of two spans are equal.
```rust
// expands to `1 + 0`, but don't lint
1 + mac!()
```
```rust
if left.span.ctxt() != right.span.ctxt() {
// the coder most likely cannot modify this expression
return;
}
```
Note: Code that is not from expansion is in the "root" context. So any spans where `from_expansion` returns `true` can
be assumed to have the same context. And so just using `span.from_expansion()` is often good enough.
```rust
// expands to `1 + 0`, but don't lint
1 + mac!()
```
```rust
if left.span.ctxt() != right.span.ctxt() {
// the coder most likely cannot modify this expression
return;
}
```
> Note: Code that is not from expansion is in the "root" context. So any spans
> where `from_expansion` returns `true` can be assumed to have the same
> context. And so just using `span.from_expansion()` is often good enough.
- `in_external_macro(span)`: detect if the given span is from a macro defined in a foreign crate.
If you want the lint to work with macro-generated code, this is the next line of defense to avoid macros
not defined in the current crate. It doesn't make sense to lint code that the coder can't change.
- `in_external_macro(span)`: detect if the given span is from a macro defined in
a foreign crate. If you want the lint to work with macro-generated code, this
is the next line of defense to avoid macros not defined in the current crate.
It doesn't make sense to lint code that the coder can't change.
You may want to use it for example to not start linting in macros from other crates
You may want to use it for example to not start linting in macros from other
crates
```rust
#[macro_use]
extern crate a_crate_with_macros;
```rust
#[macro_use]
extern crate a_crate_with_macros;
// `foo` is defined in `a_crate_with_macros`
foo!("bar");
// `foo` is defined in `a_crate_with_macros`
foo!("bar");
// if we lint the `match` of `foo` call and test its span
assert_eq!(in_external_macro(cx.sess(), match_span), true);
```
// if we lint the `match` of `foo` call and test its span
assert_eq!(in_external_macro(cx.sess(), match_span), true);
```
- `span.ctxt()`: the span's context represents whether it is from expansion, and if so, what expanded it
- `span.ctxt()`: the span's context represents whether it is from expansion, and
if so, what expanded it
One thing `SpanContext` is useful for is to check if two spans are in the same context. For example,
in `a == b`, `a` and `b` have the same context. In a `macro_rules!` with `a == $b`, `$b` is expanded to some
expression with a different context from `a`.
One thing `SpanContext` is useful for is to check if two spans are in the same
context. For example, in `a == b`, `a` and `b` have the same context. In a
`macro_rules!` with `a == $b`, `$b` is expanded to some expression with a
different context from `a`.
```rust
macro_rules! m {

View File

@ -1,38 +1,42 @@
# The Clippy Book
This document explains how to make additions and changes to the Clippy book, the guide to Clippy that you're reading
right now. The Clippy book is formatted with [Markdown](https://www.markdownguide.org) and generated
by [mdbook](https://github.com/rust-lang/mdBook).
This document explains how to make additions and changes to the Clippy book, the
guide to Clippy that you're reading right now. The Clippy book is formatted with
[Markdown](https://www.markdownguide.org) and generated by
[mdbook](https://github.com/rust-lang/mdBook).
- [Get mdbook](#get-mdbook)
- [Make changes](#make-changes)
## Get mdbook
While not strictly necessary since the book source is simply Markdown text files, having mdbook locally will allow you
to build, test and serve the book locally to view changes before you commit them to the repository. You likely already
have
`cargo` installed, so the easiest option is to simply:
While not strictly necessary since the book source is simply Markdown text
files, having mdbook locally will allow you to build, test and serve the book
locally to view changes before you commit them to the repository. You likely
already have `cargo` installed, so the easiest option is to simply:
```shell
cargo install mdbook
```
See the mdbook [installation](https://github.com/rust-lang/mdBook#installation) instructions for other options.
See the mdbook [installation](https://github.com/rust-lang/mdBook#installation)
instructions for other options.
## Make changes
The book's [src](https://github.com/joshrotenberg/rust-clippy/tree/clippy_guide/book/src) directory contains all of the
markdown files used to generate the book. If you want to see your changes in real time, you can use the mdbook `serve`
command to run a web server locally that will automatically update changes as they are made. From the top level of
your `rust-clippy`
directory:
The book's
[src](https://github.com/joshrotenberg/rust-clippy/tree/clippy_guide/book/src)
directory contains all of the markdown files used to generate the book. If you
want to see your changes in real time, you can use the mdbook `serve` command to
run a web server locally that will automatically update changes as they are
made. From the top level of your `rust-clippy` directory:
```shell
mdbook serve book --open
```
Then navigate to `http://localhost:3000` to see the generated book. While the server is running, changes you make will
automatically be updated.
Then navigate to `http://localhost:3000` to see the generated book. While the
server is running, changes you make will automatically be updated.
For more information, see the mdbook [guide](https://rust-lang.github.io/mdBook/).
For more information, see the mdbook
[guide](https://rust-lang.github.io/mdBook/).

View File

@ -1,6 +1,6 @@
# Changelog Update
If you want to help with updating the [changelog][changelog], you're in the right place.
If you want to help with updating the [changelog], you're in the right place.
## When to update
@ -11,8 +11,8 @@ Rust release. For that purpose, the changelog is ideally updated during the week
before an upcoming stable release. You can find the release dates on the [Rust
Forge][forge].
Most of the time we only need to update the changelog for minor Rust releases. It's
been very rare that Clippy changes were included in a patch release.
Most of the time we only need to update the changelog for minor Rust releases.
It's been very rare that Clippy changes were included in a patch release.
## Changelog update walkthrough
@ -24,10 +24,12 @@ be found in the `tools` directory of the Rust repository.
Depending on the current time and what exactly you want to update, the following
bullet points might be helpful:
* When writing the release notes for the **upcoming stable release** you need to check
out the Clippy commit of the current Rust `beta` branch. [Link][rust_beta_tools]
* When writing the release notes for the **upcoming beta release**, you need to check
out the Clippy commit of the current Rust `master`. [Link][rust_master_tools]
* When writing the release notes for the **upcoming stable release** you need to
check out the Clippy commit of the current Rust `beta` branch.
[Link][rust_beta_tools]
* When writing the release notes for the **upcoming beta release**, you need to
check out the Clippy commit of the current Rust `master`.
[Link][rust_master_tools]
* When writing the (forgotten) release notes for a **past stable release**, you
need to check out the Rust release tag of the stable release.
[Link][rust_stable_tools]
@ -35,7 +37,8 @@ bullet points might be helpful:
Usually you want to write the changelog of the **upcoming stable release**. Make
sure though, that `beta` was already branched in the Rust repository.
To find the commit hash, issue the following command when in a `rust-lang/rust` checkout:
To find the commit hash, issue the following command when in a `rust-lang/rust`
checkout:
```
git log --oneline -- src/tools/clippy/ | grep -o "Merge commit '[a-f0-9]*' into .*" | head -1 | sed -e "s/Merge commit '\([a-f0-9]*\)' into .*/\1/g"
```
@ -44,7 +47,9 @@ git log --oneline -- src/tools/clippy/ | grep -o "Merge commit '[a-f0-9]*' into
Once you've got the correct commit range, run
util/fetch_prs_between.sh commit1 commit2 > changes.txt
```
util/fetch_prs_between.sh commit1 commit2 > changes.txt
```
and open that file in your editor of choice.
@ -54,14 +59,14 @@ already correct in the current changelog.
### 3. Authoring the final changelog
The above script should have dumped all the relevant PRs to the file you
specified. It should have filtered out most of the irrelevant PRs
already, but it's a good idea to do a manual cleanup pass where you look for
more irrelevant PRs. If you're not sure about some PRs, just leave them in for
the review and ask for feedback.
specified. It should have filtered out most of the irrelevant PRs already, but
it's a good idea to do a manual cleanup pass where you look for more irrelevant
PRs. If you're not sure about some PRs, just leave them in for the review and
ask for feedback.
With the PRs filtered, you can start to take each PR and move the
`changelog: ` content to `CHANGELOG.md`. Adapt the wording as you see fit but
try to keep it somewhat coherent.
With the PRs filtered, you can start to take each PR and move the `changelog: `
content to `CHANGELOG.md`. Adapt the wording as you see fit but try to keep it
somewhat coherent.
The order should roughly be:

View File

@ -1,7 +1,7 @@
# Release a new Clippy Version
_NOTE: This document is probably only relevant to you, if you're a member of the
Clippy team._
> _NOTE:_ This document is probably only relevant to you, if you're a member of
> the Clippy team.
Clippy is released together with stable Rust releases. The dates for these
releases can be found at the [Rust Forge]. This document explains the necessary
@ -13,12 +13,11 @@ steps to create a Clippy release.
4. [Tag the stable commit](#tag-the-stable-commit)
5. [Update `CHANGELOG.md`](#update-changelogmd)
_NOTE: This document is for stable Rust releases, not for point releases. For
point releases, step 1. and 2. should be enough._
> _NOTE:_ This document is for stable Rust releases, not for point releases. For
> point releases, step 1. and 2. should be enough.
[Rust Forge]: https://forge.rust-lang.org/
## Remerge the `beta` branch
This step is only necessary, if since the last release something was backported
@ -45,9 +44,8 @@ $ git push origin backport_remerge # This can be pushed to your fork
```
After this, open a PR to the master branch. In this PR, the commit hash of the
`HEAD` of the `beta` branch must exists. In addition to that, no files should
be changed by this PR.
`HEAD` of the `beta` branch must exists. In addition to that, no files should be
changed by this PR.
## Update the `beta` branch
@ -72,7 +70,6 @@ $ git reset --hard $BETA_SHA
$ git push upstream beta
```
## Find the Clippy commit
The first step is to tag the Clippy commit, that is included in the stable Rust
@ -85,7 +82,6 @@ $ git checkout 1.XX.0 # XX should be exchanged with the corresponding version
$ SHA=$(git log --oneline -- src/tools/clippy/ | grep -o "Merge commit '[a-f0-9]*' into .*" | head -1 | sed -e "s/Merge commit '\([a-f0-9]*\)' into .*/\1/g")
```
## Tag the stable commit
After finding the Clippy commit, it can be tagged with the release number.
@ -112,10 +108,10 @@ tag. Updating the stable branch from here is as easy as:
$ git push upstream rust-1.XX.0:stable # `upstream` is the `rust-lang/rust-clippy` remote
```
_NOTE: Usually there are no stable backports for Clippy, so this update should
be possible without force pushing or anything like this. If there should have
happened a stable backport, make sure to re-merge those changes just as with the
`beta` branch._
> _NOTE:_ Usually there are no stable backports for Clippy, so this update
> should be possible without force pushing or anything like this. If there
> should have happened a stable backport, make sure to re-merge those changes
> just as with the `beta` branch.
## Update `CHANGELOG.md`
@ -142,4 +138,4 @@ the following parts:
Current stable, released 20YY-MM-DD -> Released 20YY-MM-DD
```
[how to update the changelog]: https://github.com/rust-lang/rust-clippy/blob/master/doc/changelog_update.md
[how to update the changelog]: changelog_update.md