Skip to content

Clippy subtree update #116139

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 123 commits into from
Sep 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
123 commits
Select commit Hold shift + click to select a range
26c0f97
[`len_without_is_empty`]: follow type alias
y21 Sep 2, 2023
1c27ba9
Stabilize the Saturating type (saturating_int_impl, gh-87920)
kellerkindt Jul 26, 2023
e34e49f
`useless_conversion`: don't lint if ty param has multiple bounds
y21 Aug 6, 2023
cf10690
check that the receiver type satisfies bounds
y21 Aug 7, 2023
18f3689
use the correct node args for substitution
y21 Sep 5, 2023
0f74faf
Use `Freeze` for `SourceFile.lines`
Zoxc Aug 31, 2023
cc8c0e0
Ignore span's parents in `collect_ast_format_args`/`find_format_args`
Alexendoo Sep 8, 2023
e88a556
Reuse rustdoc's doc comment handling in Clippy
Alexendoo Sep 8, 2023
54f3ddb
Call `LateLintPass::check_attribute` from `with_lint_attrs`
Alexendoo Sep 10, 2023
ab08a3d
Update tools and fulldeps tests
matthewjasper Sep 8, 2023
f598bb7
Walk the left side of where bounds if the bounded type is not a gener…
mkrasnitski Sep 12, 2023
b643f20
Auto merge of #115689 - Alexendoo:clippy-doc-comments, r=notriddle,Ma…
bors Sep 12, 2023
f136e16
new unnecessary_map_on_constructor lint
jonboh Aug 26, 2023
cb05701
Auto merge of #11413 - jonboh:master, r=Alexendoo
bors Sep 12, 2023
b788add
Auto merge of #11473 - Alexendoo:format-args-span-parents, r=dswij
bors Sep 12, 2023
471469d
Merge commit '98363cbf6a7c3f8b571a7d92a3c645bb4376e4a6' into clippyup
flip1995 Sep 12, 2023
7f87020
add `byref` checking for the guard's local
kiscad Sep 13, 2023
5cd391c
make the set of methods between our two Const types more consistent
RalfJung Sep 12, 2023
e3267b1
Fix mutaby used async function argument in closure for `needless_pass…
GuillaumeGomez Sep 13, 2023
0c7dcba
Remove `derive_new` test dependency
Alexendoo Sep 13, 2023
0698591
Auto merge of #115790 - flip1995:clippyup, r=Manishearth
bors Sep 13, 2023
2009b58
Auto merge of #11452 - y21:issue11165, r=Centri3
bors Sep 13, 2023
0273ed3
Auto merge of #11497 - Alexendoo:remove-derive-new, r=dswij
bors Sep 14, 2023
2aaaeb4
use AllocId instead of Allocation in ConstValue::ByRef
RalfJung Sep 11, 2023
b2d5d68
cleanup op_to_const a bit; rename ConstValue::ByRef → Indirect
RalfJung Sep 12, 2023
8d3bbb0
handle the byref binding in the struct pattern
kiscad Sep 14, 2023
272df70
treat host effect params as erased generics in codegen
fee1-dead Sep 13, 2023
477a9b8
fix clippy (and MIR printing) handling of ConstValue::Indirect slices
RalfJung Sep 12, 2023
eb545d7
Auto merge of #115817 - fee1-dead-contrib:fix-codegen, r=oli-obk
bors Sep 14, 2023
c29de92
Return a value from find_format_args instead of using a callback
Alexendoo Sep 1, 2023
b27fc10
Auto merge of #11444 - Alexendoo:find-format-args-lifetime-crimes, r=…
bors Sep 14, 2023
da4244e
Ignore `#[doc(hidden)]` functions in clippy doc lints
Alexendoo Sep 14, 2023
9756a13
Auto merge of #115677 - matthewjasper:let-expr-recovery, r=b-naber
bors Sep 14, 2023
1d49cb6
move required_consts check to general post-mono-check function
RalfJung Sep 11, 2023
3226e4b
don't point at const usage site for resolution-time errors
RalfJung Sep 11, 2023
a2a31a0
Ignore closures for some type lints
Alexendoo Sep 14, 2023
3c0fc15
Truncate files when opening in metadata-collector
Alexendoo Sep 14, 2023
6734e96
Auto merge of #11505 - Alexendoo:metadata-collector-truncate, r=Manis…
bors Sep 14, 2023
1d76eed
trigger [`transmute_null_to_fn`] on chain of casts
J-ZhengLi Sep 15, 2023
c9b212d
fix filter_map_bool_then with a bool reference
kiscad Sep 15, 2023
c81888e
fix FP of let_unit_value on async fn args
kiscad Sep 15, 2023
2c629cc
Auto merge of #11504 - Alexendoo:type-lints-closures, r=xFrednet
bors Sep 15, 2023
2121629
Auto merge of #115851 - Alexendoo:clippy-doc-hidden-headers, r=flip1995
bors Sep 15, 2023
e609279
Auto merge of #11484 - mkrasnitski:fix-11302, r=Jarcho
bors Sep 15, 2023
eaf640d
Auto merge of #11506 - mojave2:issue-11503, r=giraffate
bors Sep 15, 2023
981e960
new lint: `path_ends_with_ext`
y21 Sep 11, 2023
daadab5
Auto merge of #11483 - y21:path_ends_with, r=Alexendoo
bors Sep 15, 2023
7426c83
add a test case
kiscad Sep 15, 2023
fed036a
Fix cycle detection in `needless_borrow`
Jarcho Sep 15, 2023
59636a2
Auto merge of #11301 - y21:issue11300, r=dswij
bors Sep 16, 2023
3f9db90
Auto merge of #11507 - J-ZhengLi:issue11485, r=dswij
bors Sep 16, 2023
f54275f
Auto merge of #11509 - mojave2:issue-11502, r=llogiq
bors Sep 16, 2023
860e800
[`filter_map_bool_then`]: peel as many refs as needed
y21 Sep 16, 2023
2ec6f3b
also count derefs through custom `Deref` impls
y21 Sep 16, 2023
67f0ba4
Update clippy_lints/src/matches/redundant_guards.rs
kiscad Sep 16, 2023
af2a847
fix cast_lossless with macro call
kiscad Sep 16, 2023
3cad623
更新 cast_lossless.rs
kiscad Sep 16, 2023
ef73648
Auto merge of #11468 - mojave2:issue-11465, r=blyxyas
bors Sep 16, 2023
5b790ff
fix FP with needless_raw_string_hashes
kiscad Sep 17, 2023
7b5e019
Auto merge of #11515 - y21:filter_map_bool_then_peel_refs, r=Jarcho
bors Sep 17, 2023
66aa7f7
Rollup merge of #115477 - kellerkindt:stabilized_int_impl, r=dtolnay
Dylan-DPC Sep 17, 2023
3665a41
fix ICE by `u64::try_from(<u128>)`
kiscad Sep 17, 2023
558ae4c
[`redundant_guards`]: lint if the pattern is on the LHS
y21 Sep 17, 2023
79247d9
Split part of `needless_borrow` into `needless_borrows_for_generic_a…
Jarcho Sep 15, 2023
251a475
Auto merge of #11511 - Jarcho:split_borrow, r=llogiq
bors Sep 17, 2023
32d3387
used_underscore_bindings: respect lint levels on the binding definition
Alexendoo Sep 17, 2023
1c9f3be
Add redundant_as_str lint
Dev380 Sep 17, 2023
01056c5
Fix missing semicolon in redundant_as_str docstring example
Dev380 Sep 17, 2023
c92de58
Auto merge of #11523 - Alexendoo:used-underscore-bindings-lint-levels…
bors Sep 18, 2023
b06b915
Move zero_ptr to the casts module
Alexendoo Sep 18, 2023
3251952
Update remark CI deps
Alexendoo Sep 18, 2023
ea16f81
Auto merge of #11531 - Alexendoo:remark-deps, r=flip1995
bors Sep 18, 2023
b8b420c
Improve code readability by moving the retrieval of closures inside a…
GuillaumeGomez Sep 18, 2023
4022591
Auto merge of #11517 - mojave2:issue-11426, r=Alexendoo
bors Sep 18, 2023
e9dc753
Auto merge of #115748 - RalfJung:post-mono, r=oli-obk
bors Sep 18, 2023
f2ab16e
Add not triggering examples to redundant_as_str test
Dev380 Sep 18, 2023
00ca47b
Add more examples and comments to redundant_as_str test
Dev380 Sep 18, 2023
367ba9c
Add not redundant examples for redundant_as_str
Dev380 Sep 18, 2023
5224853
Remove periods from end of sentences in redundant_as_str comments
Dev380 Sep 18, 2023
17d174d
Reformat redundant_as_str ui test
Dev380 Sep 18, 2023
d9d25e9
Fix redundant_as_str .fixed file not being consistent
Dev380 Sep 18, 2023
5cba09c
Auto merge of #11526 - Dev380:redundant-as-str, r=Manishearth
bors Sep 18, 2023
889e1b9
Auto merge of #11530 - Alexendoo:zero-ptr-file-location, r=blyxyas
bors Sep 18, 2023
b30cefc
move ConstValue into mir
RalfJung Sep 16, 2023
f464149
Auto merge of #11516 - mojave2:issue-11458, r=giraffate
bors Sep 20, 2023
1b3e5dd
Change default configuration of `undocumented_unsafe_blocks`
tgross35 Jul 17, 2023
ece3878
Auto merge of #11492 - GuillaumeGomez:async-fn-returned-closure, r=Ce…
bors Sep 20, 2023
ddbe110
Auto merge of #11170 - tgross35:undocumented-unsafe-blocks-defaults, …
bors Sep 20, 2023
01c25a8
Remove most usage of `hir_ty_to_ty`
Alexendoo Sep 20, 2023
c556695
Auto merge of #11522 - y21:redundant_guards_pat_lhs, r=giraffate
bors Sep 20, 2023
2ea6ac5
rename mir::Constant -> mir::ConstOperand, mir::ConstKind -> mir::Const
RalfJung Sep 20, 2023
238dc28
Prevent promotion of const fn calls in inline consts
oli-obk Sep 18, 2023
12815e9
Rollup merge of #115972 - RalfJung:const-consistency, r=oli-obk
GuillaumeGomez Sep 21, 2023
4d143d7
Auto merge of #11518 - mojave2:issue-11420, r=Alexendoo
bors Sep 21, 2023
33f084e
Auto merge of #11544 - Alexendoo:hir-ty-to-ty, r=Jarcho
bors Sep 21, 2023
823bcb4
Record asyncness span in HIR
compiler-errors Sep 14, 2023
1fac304
adjust how closure/generator types and rvalues are printed
RalfJung Sep 9, 2023
74573fb
fix clippy errors (ignore effects in certainty)
fee1-dead Sep 22, 2023
84917c8
Auto merge of #114776 - fee1-dead-contrib:enable-effects-in-libcore, …
bors Sep 22, 2023
5ee167e
Add a way to decouple the implementation and the declaration of a TyC…
oli-obk Sep 22, 2023
85801f5
fixed fp caused by moving &mut reference inside of a closure
Meczka Sep 22, 2023
f3a27d2
prevent ice when threshold is 0 and enum has no variants
jonboh Sep 22, 2023
835d7d9
Auto merge of #115696 - RalfJung:closure-ty-print, r=oli-obk
bors Sep 22, 2023
ab51f66
added tests
Meczka Sep 22, 2023
7e46fb9
Fix large_futures example
mickvangelderen Sep 22, 2023
50139e6
Auto merge of #11551 - Meczka:fix-fp-needless-pass-by-ref-mut, r=xFre…
bors Sep 22, 2023
d732cce
Auto merge of #11553 - mickvangelderen:fix-large-futures-example, r=x…
bors Sep 22, 2023
3da69c7
Auto merge of #116052 - oli-obk:ceci_nest_pas_une_query, r=WaffleLapkin
bors Sep 23, 2023
0a2d39d
Enable drop_tracking_mir by default.
cjgillot Jan 28, 2023
19e160f
Bless clippy.
cjgillot Jan 28, 2023
e2669b2
Remove GeneratorWitness and rename GeneratorWitnessMIR.
cjgillot Aug 3, 2023
6ce61d5
add missing configuration tests
y21 Sep 24, 2023
6e80db9
use a smaller number in test that fits in usize for 32 bit
y21 Sep 24, 2023
94fc431
Auto merge of #11560 - y21:ui-toml-tests, r=Alexendoo
bors Sep 24, 2023
b3e262a
add ui-toml test
jonboh Sep 24, 2023
0433e45
use first instead of get(0)
jonboh Sep 24, 2023
aa137a7
Auto merge of #11552 - jonboh:ice_threshold_0_enum_variants, r=y21
bors Sep 24, 2023
81fe8dc
Merge remote-tracking branch 'upstream/master' into rustup
flip1995 Sep 25, 2023
5eb7604
Bump nightly version -> 2023-09-25
flip1995 Sep 25, 2023
903add0
Fix dogfood fallout
flip1995 Sep 25, 2023
7671c28
Auto merge of #11563 - flip1995:rustup, r=flip1995
bors Sep 25, 2023
3112e37
Merge commit '7671c283a50b5d1168841f3014b14000f01dd204' into clippyup
flip1995 Sep 25, 2023
6d331b7
Update Cargo.lock
flip1995 Sep 25, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 0 additions & 12 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -515,7 +515,6 @@ version = "0.1.74"
dependencies = [
"clippy_lints",
"clippy_utils",
"derive-new",
"filetime",
"futures",
"if_chain",
Expand Down Expand Up @@ -944,17 +943,6 @@ dependencies = [
"syn 2.0.29",
]

[[package]]
name = "derive-new"
version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3418329ca0ad70234b9735dc4ceed10af4df60eff9c8e7b06cb5e520d92c3535"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]

[[package]]
name = "derive_builder"
version = "0.12.0"
Expand Down
8 changes: 4 additions & 4 deletions src/tools/clippy/.github/workflows/remark.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,27 +21,27 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '14.x'
node-version: '18.x'

- name: Install remark
run: npm install remark-cli remark-lint remark-lint-maximum-line-length remark-preset-lint-recommended remark-gfm

- name: Install mdbook
run: |
mkdir mdbook
curl -Lf https://github.com/rust-lang/mdBook/releases/download/v0.4.28/mdbook-v0.4.28-x86_64-unknown-linux-gnu.tar.gz | tar -xz --directory=./mdbook
curl -Lf https://github.com/rust-lang/mdBook/releases/download/v0.4.34/mdbook-v0.4.34-x86_64-unknown-linux-gnu.tar.gz | tar -xz --directory=./mdbook
echo `pwd`/mdbook >> $GITHUB_PATH

# Run
- name: Check *.md files
run: git ls-files -z '*.md' | xargs -0 -n 1 -I {} ./node_modules/.bin/remark {} -u lint -f > /dev/null
run: ./node_modules/.bin/remark -u lint -f .

- name: Linkcheck book
run: |
rustup toolchain install nightly --component rust-docs
curl https://raw.githubusercontent.com/rust-lang/rust/master/src/tools/linkchecker/linkcheck.sh -o linkcheck.sh
sh linkcheck.sh clippy --path ./book

- name: Build mdbook
run: mdbook build book

Expand Down
5 changes: 5 additions & 0 deletions src/tools/clippy/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5171,6 +5171,7 @@ Released 2018-09-13
[`needless_bool_assign`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_bool_assign
[`needless_borrow`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow
[`needless_borrowed_reference`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrowed_reference
[`needless_borrows_for_generic_args`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrows_for_generic_args
[`needless_collect`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_collect
[`needless_continue`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_continue
[`needless_doctest_main`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_doctest_main
Expand Down Expand Up @@ -5245,6 +5246,7 @@ Released 2018-09-13
[`partialeq_ne_impl`]: https://rust-lang.github.io/rust-clippy/master/index.html#partialeq_ne_impl
[`partialeq_to_none`]: https://rust-lang.github.io/rust-clippy/master/index.html#partialeq_to_none
[`path_buf_push_overwrite`]: https://rust-lang.github.io/rust-clippy/master/index.html#path_buf_push_overwrite
[`path_ends_with_ext`]: https://rust-lang.github.io/rust-clippy/master/index.html#path_ends_with_ext
[`pattern_type_mismatch`]: https://rust-lang.github.io/rust-clippy/master/index.html#pattern_type_mismatch
[`permissions_set_readonly_false`]: https://rust-lang.github.io/rust-clippy/master/index.html#permissions_set_readonly_false
[`positional_named_format_parameters`]: https://rust-lang.github.io/rust-clippy/master/index.html#positional_named_format_parameters
Expand Down Expand Up @@ -5279,6 +5281,7 @@ Released 2018-09-13
[`readonly_write_lock`]: https://rust-lang.github.io/rust-clippy/master/index.html#readonly_write_lock
[`recursive_format_impl`]: https://rust-lang.github.io/rust-clippy/master/index.html#recursive_format_impl
[`redundant_allocation`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_allocation
[`redundant_as_str`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_as_str
[`redundant_async_block`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_async_block
[`redundant_at_rest_pattern`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_at_rest_pattern
[`redundant_clone`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_clone
Expand Down Expand Up @@ -5437,6 +5440,7 @@ Released 2018-09-13
[`unnecessary_join`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_join
[`unnecessary_lazy_evaluations`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_lazy_evaluations
[`unnecessary_literal_unwrap`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_literal_unwrap
[`unnecessary_map_on_constructor`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_map_on_constructor
[`unnecessary_mut_passed`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_mut_passed
[`unnecessary_operation`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_operation
[`unnecessary_owned_empty_strings`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_owned_empty_strings
Expand Down Expand Up @@ -5574,5 +5578,6 @@ Released 2018-09-13
[`allow-one-hash-in-raw-strings`]: https://doc.rust-lang.org/clippy/lint_configuration.html#allow-one-hash-in-raw-strings
[`absolute-paths-max-segments`]: https://doc.rust-lang.org/clippy/lint_configuration.html#absolute-paths-max-segments
[`absolute-paths-allowed-crates`]: https://doc.rust-lang.org/clippy/lint_configuration.html#absolute-paths-allowed-crates
[`allowed-dotfiles`]: https://doc.rust-lang.org/clippy/lint_configuration.html#allowed-dotfiles
[`enforce-iter-loop-reborrow`]: https://doc.rust-lang.org/clippy/lint_configuration.html#enforce-iter-loop-reborrow
<!-- end autogenerated links to configuration documentation -->
1 change: 0 additions & 1 deletion src/tools/clippy/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ itertools = "0.10.1"

# UI test dependencies
clippy_utils = { path = "clippy_utils" }
derive-new = "0.5"
if_chain = "1.0"
quote = "1.0"
serde = { version = "1.0.125", features = ["derive"] }
Expand Down
14 changes: 12 additions & 2 deletions src/tools/clippy/book/src/lint_configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -703,7 +703,7 @@ Minimum chars an ident can have, anything below or equal to this will be linted.
## `accept-comment-above-statement`
Whether to accept a safety comment to be placed above the statement containing the `unsafe` block

**Default Value:** `false` (`bool`)
**Default Value:** `true` (`bool`)

---
**Affected lints:**
Expand All @@ -713,7 +713,7 @@ Whether to accept a safety comment to be placed above the statement containing t
## `accept-comment-above-attributes`
Whether to accept a safety comment to be placed above the attributes for the `unsafe` block

**Default Value:** `false` (`bool`)
**Default Value:** `true` (`bool`)

---
**Affected lints:**
Expand Down Expand Up @@ -751,6 +751,16 @@ Which crates to allow absolute paths from
* [`absolute_paths`](https://rust-lang.github.io/rust-clippy/master/index.html#absolute_paths)


## `allowed-dotfiles`
Additional dotfiles (files or directories starting with a dot) to allow

**Default Value:** `{}` (`rustc_data_structures::fx::FxHashSet<String>`)

---
**Affected lints:**
* [`path_ends_with_ext`](https://rust-lang.github.io/rust-clippy/master/index.html#path_ends_with_ext)


## `enforce-iter-loop-reborrow`
#### Example
```
Expand Down
2 changes: 1 addition & 1 deletion src/tools/clippy/clippy_lints/src/attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -616,7 +616,7 @@ fn check_should_panic_reason(cx: &LateContext<'_>, attr: &Attribute) {
attr.span,
"#[should_panic] attribute without a reason",
"consider specifying the expected panic",
r#"#[should_panic(expected = /* panic message */)]"#.into(),
"#[should_panic(expected = /* panic message */)]".into(),
Applicability::HasPlaceholders,
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/tools/clippy/clippy_lints/src/casts/cast_lossless.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub(super) fn check(
// The suggestion is to use a function call, so if the original expression
// has parens on the outside, they are no longer needed.
let mut applicability = Applicability::MachineApplicable;
let opt = snippet_opt(cx, cast_op.span);
let opt = snippet_opt(cx, cast_op.span.source_callsite());
let sugg = opt.as_ref().map_or_else(
|| {
applicability = Applicability::HasPlaceholders;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ fn apply_reductions(cx: &LateContext<'_>, nbits: u64, expr: &Expr<'_>, signed: b
.unwrap_or(u64::max_value())
.min(apply_reductions(cx, nbits, left, signed)),
BinOpKind::Shr => apply_reductions(cx, nbits, left, signed)
.saturating_sub(constant_int(cx, right).map_or(0, |s| u64::try_from(s).expect("shift too high"))),
.saturating_sub(constant_int(cx, right).map_or(0, |s| u64::try_from(s).unwrap_or_default())),
_ => nbits,
},
ExprKind::MethodCall(method, left, [right], _) => {
Expand Down
26 changes: 26 additions & 0 deletions src/tools/clippy/clippy_lints/src/casts/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ mod ptr_as_ptr;
mod ptr_cast_constness;
mod unnecessary_cast;
mod utils;
mod zero_ptr;

use clippy_utils::is_hir_ty_cfg_dependant;
use clippy_utils::msrvs::{self, Msrv};
Expand Down Expand Up @@ -665,6 +666,29 @@ declare_clippy_lint! {
"casting a known floating-point NaN into an integer"
}

declare_clippy_lint! {
/// ### What it does
/// Catch casts from `0` to some pointer type
///
/// ### Why is this bad?
/// This generally means `null` and is better expressed as
/// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
///
/// ### Example
/// ```rust
/// let a = 0 as *const u32;
/// ```
///
/// Use instead:
/// ```rust
/// let a = std::ptr::null::<u32>();
/// ```
#[clippy::version = "pre 1.29.0"]
pub ZERO_PTR,
style,
"using `0 as *{const, mut} T`"
}

pub struct Casts {
msrv: Msrv,
}
Expand Down Expand Up @@ -699,6 +723,7 @@ impl_lint_pass!(Casts => [
CAST_SLICE_FROM_RAW_PARTS,
AS_PTR_CAST_MUT,
CAST_NAN_TO_INT,
ZERO_PTR,
]);

impl<'tcx> LateLintPass<'tcx> for Casts {
Expand Down Expand Up @@ -729,6 +754,7 @@ impl<'tcx> LateLintPass<'tcx> for Casts {
fn_to_numeric_cast_any::check(cx, expr, cast_expr, cast_from, cast_to);
fn_to_numeric_cast::check(cx, expr, cast_expr, cast_from, cast_to);
fn_to_numeric_cast_with_truncation::check(cx, expr, cast_expr, cast_from, cast_to);
zero_ptr::check(cx, expr, cast_expr, cast_to_hir);

if cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
cast_possible_truncation::check(cx, expr, cast_expr, cast_from, cast_to, cast_to_hir.span);
Expand Down
39 changes: 39 additions & 0 deletions src/tools/clippy/clippy_lints/src/casts/zero_ptr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_opt;
use clippy_utils::{in_constant, is_integer_literal, std_or_core};
use rustc_errors::Applicability;
use rustc_hir::{Expr, Mutability, Ty, TyKind};
use rustc_lint::LateContext;

use super::ZERO_PTR;

pub fn check(cx: &LateContext<'_>, expr: &Expr<'_>, from: &Expr<'_>, to: &Ty<'_>) {
if let TyKind::Ptr(ref mut_ty) = to.kind
&& is_integer_literal(from, 0)
&& !in_constant(cx, from.hir_id)
&& let Some(std_or_core) = std_or_core(cx)
{
let (msg, sugg_fn) = match mut_ty.mutbl {
Mutability::Mut => ("`0 as *mut _` detected", "ptr::null_mut"),
Mutability::Not => ("`0 as *const _` detected", "ptr::null"),
};

let sugg = if let TyKind::Infer = mut_ty.ty.kind {
format!("{std_or_core}::{sugg_fn}()")
} else if let Some(mut_ty_snip) = snippet_opt(cx, mut_ty.ty.span) {
format!("{std_or_core}::{sugg_fn}::<{mut_ty_snip}>()")
} else {
return;
};

span_lint_and_sugg(
cx,
ZERO_PTR,
expr.span,
msg,
"try",
sugg,
Applicability::MachineApplicable,
);
}
}
6 changes: 5 additions & 1 deletion src/tools/clippy/clippy_lints/src/declared_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
crate::casts::PTR_AS_PTR_INFO,
crate::casts::PTR_CAST_CONSTNESS_INFO,
crate::casts::UNNECESSARY_CAST_INFO,
crate::casts::ZERO_PTR_INFO,
crate::checked_conversions::CHECKED_CONVERSIONS_INFO,
crate::cognitive_complexity::COGNITIVE_COMPLEXITY_INFO,
crate::collapsible_if::COLLAPSIBLE_ELSE_IF_INFO,
Expand Down Expand Up @@ -399,9 +400,11 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
crate::methods::OR_FUN_CALL_INFO,
crate::methods::OR_THEN_UNWRAP_INFO,
crate::methods::PATH_BUF_PUSH_OVERWRITE_INFO,
crate::methods::PATH_ENDS_WITH_EXT_INFO,
crate::methods::RANGE_ZIP_WITH_LEN_INFO,
crate::methods::READONLY_WRITE_LOCK_INFO,
crate::methods::READ_LINE_WITHOUT_TRIM_INFO,
crate::methods::REDUNDANT_AS_STR_INFO,
crate::methods::REPEAT_ONCE_INFO,
crate::methods::RESULT_MAP_OR_INTO_OPTION_INFO,
crate::methods::SEARCH_IS_SOME_INFO,
Expand Down Expand Up @@ -441,7 +444,6 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
crate::misc::SHORT_CIRCUIT_STATEMENT_INFO,
crate::misc::TOPLEVEL_REF_ARG_INFO,
crate::misc::USED_UNDERSCORE_BINDING_INFO,
crate::misc::ZERO_PTR_INFO,
crate::misc_early::BUILTIN_TYPE_SHADOW_INFO,
crate::misc_early::DOUBLE_NEG_INFO,
crate::misc_early::DUPLICATE_UNDERSCORE_ARGUMENT_INFO,
Expand Down Expand Up @@ -479,6 +481,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
crate::needless_bool::NEEDLESS_BOOL_INFO,
crate::needless_bool::NEEDLESS_BOOL_ASSIGN_INFO,
crate::needless_borrowed_ref::NEEDLESS_BORROWED_REFERENCE_INFO,
crate::needless_borrows_for_generic_args::NEEDLESS_BORROWS_FOR_GENERIC_ARGS_INFO,
crate::needless_continue::NEEDLESS_CONTINUE_INFO,
crate::needless_else::NEEDLESS_ELSE_INFO,
crate::needless_for_each::NEEDLESS_FOR_EACH_INFO,
Expand Down Expand Up @@ -671,6 +674,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
crate::unnamed_address::FN_ADDRESS_COMPARISONS_INFO,
crate::unnamed_address::VTABLE_ADDRESS_COMPARISONS_INFO,
crate::unnecessary_box_returns::UNNECESSARY_BOX_RETURNS_INFO,
crate::unnecessary_map_on_constructor::UNNECESSARY_MAP_ON_CONSTRUCTOR_INFO,
crate::unnecessary_owned_empty_strings::UNNECESSARY_OWNED_EMPTY_STRINGS_INFO,
crate::unnecessary_self_imports::UNNECESSARY_SELF_IMPORTS_INFO,
crate::unnecessary_struct_initialization::UNNECESSARY_STRUCT_INITIALIZATION_INFO,
Expand Down
22 changes: 12 additions & 10 deletions src/tools/clippy/clippy_lints/src/default_union_representation.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use clippy_utils::diagnostics::span_lint_and_help;
use rustc_hir::{self as hir, HirId, Item, ItemKind};
use rustc_hir_analysis::hir_ty_to_ty;
use rustc_hir::{HirId, Item, ItemKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::layout::LayoutOf;
use rustc_middle::ty::{self, FieldDef, GenericArg, List};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::sym;

Expand Down Expand Up @@ -52,7 +52,10 @@ declare_lint_pass!(DefaultUnionRepresentation => [DEFAULT_UNION_REPRESENTATION])

impl<'tcx> LateLintPass<'tcx> for DefaultUnionRepresentation {
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) {
if is_union_with_two_non_zst_fields(cx, item) && !has_c_repr_attr(cx, item.hir_id()) {
if !item.span.from_expansion()
&& is_union_with_two_non_zst_fields(cx, item)
&& !has_c_repr_attr(cx, item.hir_id())
{
span_lint_and_help(
cx,
DEFAULT_UNION_REPRESENTATION,
Expand All @@ -73,18 +76,17 @@ impl<'tcx> LateLintPass<'tcx> for DefaultUnionRepresentation {
/// if there is only one field left after ignoring ZST fields then the offset
/// of that field does not matter either.)
fn is_union_with_two_non_zst_fields(cx: &LateContext<'_>, item: &Item<'_>) -> bool {
if let ItemKind::Union(data, _) = &item.kind {
data.fields().iter().filter(|f| !is_zst(cx, f.ty)).count() >= 2
if let ItemKind::Union(..) = &item.kind
&& let ty::Adt(adt_def, args) = cx.tcx.type_of(item.owner_id).instantiate_identity().kind()
{
adt_def.all_fields().filter(|f| !is_zst(cx, f, args)).count() >= 2
} else {
false
}
}

fn is_zst(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>) -> bool {
if hir_ty.span.from_expansion() {
return false;
}
let ty = hir_ty_to_ty(cx.tcx, hir_ty);
fn is_zst<'tcx>(cx: &LateContext<'tcx>, field: &FieldDef, args: &'tcx List<GenericArg<'tcx>>) -> bool {
let ty = field.ty(cx.tcx, args);
if let Ok(layout) = cx.layout_of(ty) {
layout.is_zst()
} else {
Expand Down
Loading