Skip to content

Commit

Permalink
Auto merge of #103337 - flip1995:clippyup, r=Manishearth
Browse files Browse the repository at this point in the history
Update Clippy

r? `@Manishearth`
  • Loading branch information
bors committed Oct 24, 2022
2 parents c07a6a9 + da9755b commit 758f196
Show file tree
Hide file tree
Showing 284 changed files with 8,511 additions and 4,206 deletions.
1 change: 1 addition & 0 deletions src/tools/clippy/.github/workflows/clippy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ env:
CARGO_TARGET_DIR: '${{ github.workspace }}/target'
NO_FMT_TEST: 1
CARGO_INCREMENTAL: 0
CARGO_UNSTABLE_SPARSE_REGISTRY: true

jobs:
base:
Expand Down
1 change: 1 addition & 0 deletions src/tools/clippy/.github/workflows/clippy_bors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ env:
CARGO_TARGET_DIR: '${{ github.workspace }}/target'
NO_FMT_TEST: 1
CARGO_INCREMENTAL: 0
CARGO_UNSTABLE_SPARSE_REGISTRY: true

defaults:
run:
Expand Down
2 changes: 2 additions & 0 deletions src/tools/clippy/.github/workflows/clippy_dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ on:

env:
RUST_BACKTRACE: 1
CARGO_INCREMENTAL: 0
CARGO_UNSTABLE_SPARSE_REGISTRY: true

jobs:
clippy_dev:
Expand Down
6 changes: 6 additions & 0 deletions src/tools/clippy/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3735,6 +3735,7 @@ Released 2018-09-13
[`approx_constant`]: https://rust-lang.github.io/rust-clippy/master/index.html#approx_constant
[`arithmetic_side_effects`]: https://rust-lang.github.io/rust-clippy/master/index.html#arithmetic_side_effects
[`as_conversions`]: https://rust-lang.github.io/rust-clippy/master/index.html#as_conversions
[`as_ptr_cast_mut`]: https://rust-lang.github.io/rust-clippy/master/index.html#as_ptr_cast_mut
[`as_underscore`]: https://rust-lang.github.io/rust-clippy/master/index.html#as_underscore
[`assertions_on_constants`]: https://rust-lang.github.io/rust-clippy/master/index.html#assertions_on_constants
[`assertions_on_result_states`]: https://rust-lang.github.io/rust-clippy/master/index.html#assertions_on_result_states
Expand Down Expand Up @@ -3772,6 +3773,7 @@ Released 2018-09-13
[`cast_enum_constructor`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_enum_constructor
[`cast_enum_truncation`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_enum_truncation
[`cast_lossless`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_lossless
[`cast_nan_to_int`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_nan_to_int
[`cast_possible_truncation`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_possible_truncation
[`cast_possible_wrap`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_possible_wrap
[`cast_precision_loss`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_precision_loss
Expand Down Expand Up @@ -3988,6 +3990,7 @@ Released 2018-09-13
[`manual_async_fn`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_async_fn
[`manual_bits`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_bits
[`manual_clamp`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_clamp
[`manual_filter`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_filter
[`manual_filter_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_filter_map
[`manual_find`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_find
[`manual_find_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_find_map
Expand Down Expand Up @@ -4046,6 +4049,7 @@ Released 2018-09-13
[`missing_panics_doc`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_panics_doc
[`missing_safety_doc`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_safety_doc
[`missing_spin_loop`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_spin_loop
[`missing_trait_methods`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_trait_methods
[`mistyped_literal_suffixes`]: https://rust-lang.github.io/rust-clippy/master/index.html#mistyped_literal_suffixes
[`mixed_case_hex_literals`]: https://rust-lang.github.io/rust-clippy/master/index.html#mixed_case_hex_literals
[`mixed_read_write_in_expression`]: https://rust-lang.github.io/rust-clippy/master/index.html#mixed_read_write_in_expression
Expand Down Expand Up @@ -4131,6 +4135,7 @@ Released 2018-09-13
[`panic_in_result_fn`]: https://rust-lang.github.io/rust-clippy/master/index.html#panic_in_result_fn
[`panic_params`]: https://rust-lang.github.io/rust-clippy/master/index.html#panic_params
[`panicking_unwrap`]: https://rust-lang.github.io/rust-clippy/master/index.html#panicking_unwrap
[`partial_pub_fields`]: https://rust-lang.github.io/rust-clippy/master/index.html#partial_pub_fields
[`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
Expand Down Expand Up @@ -4312,6 +4317,7 @@ Released 2018-09-13
[`unstable_as_slice`]: https://rust-lang.github.io/rust-clippy/master/index.html#unstable_as_slice
[`unused_async`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_async
[`unused_collect`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_collect
[`unused_format_specs`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_format_specs
[`unused_io_amount`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_io_amount
[`unused_label`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_label
[`unused_peekable`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_peekable
Expand Down
2 changes: 1 addition & 1 deletion src/tools/clippy/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ All contributors are expected to follow the [Rust Code of Conduct].

## The Clippy book

If you're new to Clippy and don't know where to start the [Clippy book] includes
If you're new to Clippy and don't know where to start, the [Clippy book] includes
a [developer guide] and is a good place to start your journey.

[Clippy book]: https://doc.rust-lang.org/nightly/clippy/index.html
Expand Down
23 changes: 21 additions & 2 deletions src/tools/clippy/book/src/development/adding_lints.md
Original file line number Diff line number Diff line change
Expand Up @@ -478,8 +478,27 @@ impl<'tcx> LateLintPass<'tcx> for ManualStrip {
```

Once the `msrv` is added to the lint, a relevant test case should be added to
`tests/ui/min_rust_version_attr.rs` which verifies that the lint isn't emitted
if the project's MSRV is lower.
the lint's test file, `tests/ui/manual_strip.rs` in this example. It should
have a case for the version below the MSRV and one with the same contents but
for the MSRV version itself.

```rust
#![feature(custom_inner_attributes)]

...

fn msrv_1_44() {
#![clippy::msrv = "1.44"]

/* something that would trigger the lint */
}

fn msrv_1_45() {
#![clippy::msrv = "1.45"]

/* something that would trigger the lint */
}
```

As a last step, the lint should be added to the lint documentation. This is done
in `clippy_lints/src/utils/conf.rs`:
Expand Down
7 changes: 4 additions & 3 deletions src/tools/clippy/book/src/development/basics.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ the reference file with:
cargo dev bless
```

For example, this is necessary, if you fix a typo in an error message of a lint
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
Expand Down Expand Up @@ -101,8 +101,9 @@ cargo dev setup intellij
cargo dev dogfood
```

More about intellij command usage and reasons
[here](https://github.com/rust-lang/rust-clippy/blob/master/CONTRIBUTING.md#intellij-rust)
More about [intellij] command usage and reasons.

[intellij]: https://github.com/rust-lang/rust-clippy/blob/master/CONTRIBUTING.md#intellij-rust

## lintcheck

Expand Down
2 changes: 1 addition & 1 deletion src/tools/clippy/clippy_dev/src/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ fn mtime(path: impl AsRef<Path>) -> SystemTime {
.into_iter()
.flatten()
.flatten()
.map(|entry| mtime(&entry.path()))
.map(|entry| mtime(entry.path()))
.max()
.unwrap_or(SystemTime::UNIX_EPOCH)
} else {
Expand Down
17 changes: 5 additions & 12 deletions src/tools/clippy/clippy_dev/src/setup/intellij.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,8 @@ impl ClippyProjectInfo {
}

pub fn setup_rustc_src(rustc_path: &str) {
let rustc_source_dir = match check_and_get_rustc_dir(rustc_path) {
Ok(path) => path,
Err(_) => return,
let Ok(rustc_source_dir) = check_and_get_rustc_dir(rustc_path) else {
return
};

for project in CLIPPY_PROJECTS {
Expand Down Expand Up @@ -172,24 +171,18 @@ pub fn remove_rustc_src() {
}

fn remove_rustc_src_from_project(project: &ClippyProjectInfo) -> bool {
let mut cargo_content = if let Ok(content) = read_project_file(project.cargo_file) {
content
} else {
let Ok(mut cargo_content) = read_project_file(project.cargo_file) else {
return false;
};
let section_start = if let Some(section_start) = cargo_content.find(RUSTC_PATH_SECTION) {
section_start
} else {
let Some(section_start) = cargo_content.find(RUSTC_PATH_SECTION) else {
println!(
"info: dependencies could not be found in `{}` for {}, skipping file",
project.cargo_file, project.name
);
return true;
};

let end_point = if let Some(end_point) = cargo_content.find(DEPENDENCIES_SECTION) {
end_point
} else {
let Some(end_point) = cargo_content.find(DEPENDENCIES_SECTION) else {
eprintln!(
"error: the end of the rustc dependencies section could not be found in `{}`",
project.cargo_file
Expand Down
10 changes: 4 additions & 6 deletions src/tools/clippy/clippy_dev/src/update_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ fn generate_lint_files(
for (lint_group, lints) in Lint::by_lint_group(usable_lints.into_iter().chain(internal_lints)) {
let content = gen_lint_group_list(&lint_group, lints.iter());
process_file(
&format!("clippy_lints/src/lib.register_{lint_group}.rs"),
format!("clippy_lints/src/lib.register_{lint_group}.rs"),
update_mode,
&content,
);
Expand Down Expand Up @@ -869,13 +869,11 @@ fn clippy_lints_src_files() -> impl Iterator<Item = (PathBuf, DirEntry)> {
macro_rules! match_tokens {
($iter:ident, $($token:ident $({$($fields:tt)*})? $(($capture:ident))?)*) => {
{
$($(let $capture =)? if let Some(LintDeclSearchResult {
$(#[allow(clippy::redundant_pattern)] let Some(LintDeclSearchResult {
token_kind: TokenKind::$token $({$($fields)*})?,
content: _x,
content: $($capture @)? _,
..
}) = $iter.next() {
_x
} else {
}) = $iter.next() else {
continue;
};)*
#[allow(clippy::unused_unit)]
Expand Down
6 changes: 4 additions & 2 deletions src/tools/clippy/clippy_lints/src/booleans.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_hir_and_then};
use clippy_utils::eq_expr_value;
use clippy_utils::source::snippet_opt;
use clippy_utils::ty::{implements_trait, is_type_diagnostic_item};
use clippy_utils::{eq_expr_value, get_trait_def_id, paths};
use if_chain::if_chain;
use rustc_ast::ast::LitKind;
use rustc_errors::Applicability;
Expand Down Expand Up @@ -483,7 +483,9 @@ impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {

fn implements_ord<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> bool {
let ty = cx.typeck_results().expr_ty(expr);
get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[]))
cx.tcx
.get_diagnostic_item(sym::Ord)
.map_or(false, |id| implements_trait(cx, ty, id, &[]))
}

struct NotSimplificationVisitor<'a, 'tcx> {
Expand Down
96 changes: 82 additions & 14 deletions src/tools/clippy/clippy_lints/src/box_default.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
use clippy_utils::{diagnostics::span_lint_and_help, is_default_equivalent, path_def_id};
use rustc_hir::{Expr, ExprKind, QPath};
use clippy_utils::{
diagnostics::span_lint_and_sugg, get_parent_node, is_default_equivalent, macros::macro_backtrace, match_path,
path_def_id, paths, ty::expr_sig,
};
use rustc_errors::Applicability;
use rustc_hir::{
intravisit::{walk_ty, Visitor},
Block, Expr, ExprKind, Local, Node, QPath, TyKind,
};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::lint::in_external_macro;
use rustc_session::{declare_lint_pass, declare_tool_lint};
Expand All @@ -15,12 +22,6 @@ declare_clippy_lint! {
/// Second, `Box::default()` can be faster
/// [in certain cases](https://nnethercote.github.io/perf-book/standard-library-types.html#box).
///
/// ### Known problems
/// The lint may miss some cases (e.g. Box::new(String::from(""))).
/// On the other hand, it will trigger on cases where the `default`
/// code comes from a macro that does something different based on
/// e.g. target operating system.
///
/// ### Example
/// ```rust
/// let x: Box<String> = Box::new(Default::default());
Expand All @@ -41,21 +42,88 @@ impl LateLintPass<'_> for BoxDefault {
fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
if let ExprKind::Call(box_new, [arg]) = expr.kind
&& let ExprKind::Path(QPath::TypeRelative(ty, seg)) = box_new.kind
&& let ExprKind::Call(..) = arg.kind
&& let ExprKind::Call(arg_path, ..) = arg.kind
&& !in_external_macro(cx.sess(), expr.span)
&& expr.span.eq_ctxt(arg.span)
&& (expr.span.eq_ctxt(arg.span) || is_vec_expn(cx, arg))
&& seg.ident.name == sym::new
&& path_def_id(cx, ty) == cx.tcx.lang_items().owned_box()
&& path_def_id(cx, ty).map_or(false, |id| Some(id) == cx.tcx.lang_items().owned_box())
&& is_default_equivalent(cx, arg)
{
span_lint_and_help(
let arg_ty = cx.typeck_results().expr_ty(arg);
span_lint_and_sugg(
cx,
BOX_DEFAULT,
expr.span,
"`Box::new(_)` of default value",
None,
"use `Box::default()` instead",
"try",
if is_plain_default(arg_path) || given_type(cx, expr) {
"Box::default()".into()
} else {
format!("Box::<{arg_ty}>::default()")
},
Applicability::MachineApplicable
);
}
}
}

fn is_plain_default(arg_path: &Expr<'_>) -> bool {
// we need to match the actual path so we don't match e.g. "u8::default"
if let ExprKind::Path(QPath::Resolved(None, path)) = &arg_path.kind {
// avoid generic parameters
match_path(path, &paths::DEFAULT_TRAIT_METHOD) && path.segments.iter().all(|seg| seg.args.is_none())
} else {
false
}
}

fn is_vec_expn(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
macro_backtrace(expr.span)
.next()
.map_or(false, |call| cx.tcx.is_diagnostic_item(sym::vec_macro, call.def_id))
}

#[derive(Default)]
struct InferVisitor(bool);

impl<'tcx> Visitor<'tcx> for InferVisitor {
fn visit_ty(&mut self, t: &rustc_hir::Ty<'_>) {
self.0 |= matches!(t.kind, TyKind::Infer | TyKind::OpaqueDef(..) | TyKind::TraitObject(..));
if !self.0 {
walk_ty(self, t);
}
}
}

fn given_type(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
match get_parent_node(cx.tcx, expr.hir_id) {
Some(Node::Local(Local { ty: Some(ty), .. })) => {
let mut v = InferVisitor::default();
v.visit_ty(ty);
!v.0
},
Some(
Node::Expr(Expr {
kind: ExprKind::Call(path, args),
..
}) | Node::Block(Block {
expr:
Some(Expr {
kind: ExprKind::Call(path, args),
..
}),
..
}),
) => {
if let Some(index) = args.iter().position(|arg| arg.hir_id == expr.hir_id) &&
let Some(sig) = expr_sig(cx, path) &&
let Some(input) = sig.input(index)
{
input.no_bound_vars().is_some()
} else {
false
}
},
_ => false,
}
}
38 changes: 38 additions & 0 deletions src/tools/clippy/clippy_lints/src/casts/as_ptr_cast_mut.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_opt;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::LateContext;
use rustc_middle::{
mir::Mutability,
ty::{self, Ty, TypeAndMut},
};

use super::AS_PTR_CAST_MUT;

pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, cast_to: Ty<'_>) {
if let ty::RawPtr(ptrty @ TypeAndMut { mutbl: Mutability::Mut, .. }) = cast_to.kind()
&& let ty::RawPtr(TypeAndMut { mutbl: Mutability::Not, .. }) =
cx.typeck_results().node_type(cast_expr.hir_id).kind()
&& let ExprKind::MethodCall(method_name, receiver, [], _) = cast_expr.peel_blocks().kind
&& method_name.ident.name == rustc_span::sym::as_ptr
&& let Some(as_ptr_did) = cx.typeck_results().type_dependent_def_id(cast_expr.peel_blocks().hir_id)
&& let as_ptr_sig = cx.tcx.fn_sig(as_ptr_did)
&& let Some(first_param_ty) = as_ptr_sig.skip_binder().inputs().iter().next()
&& let ty::Ref(_, _, Mutability::Not) = first_param_ty.kind()
&& let Some(recv) = snippet_opt(cx, receiver.span)
{
// `as_mut_ptr` might not exist
let applicability = Applicability::MaybeIncorrect;

span_lint_and_sugg(
cx,
AS_PTR_CAST_MUT,
expr.span,
&format!("casting the result of `as_ptr` to *{ptrty}"),
"replace with",
format!("{recv}.as_mut_ptr()"),
applicability
);
}
}
Loading

0 comments on commit 758f196

Please sign in to comment.