Skip to content

Commit

Permalink
Auto merge of #125764 - flip1995:clippy-subtree-update, r=Manishearth
Browse files Browse the repository at this point in the history
Clippy subtree update

r? `@Manishearth`
  • Loading branch information
bors committed May 30, 2024
2 parents c9e6650 + 497d721 commit 00c355b
Show file tree
Hide file tree
Showing 128 changed files with 1,422 additions and 676 deletions.
2 changes: 1 addition & 1 deletion book/src/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ Very rarely, you may wish to prevent Clippy from evaluating certain sections of
`clippy` cfg is not set. You may need to provide a stub so that the code compiles:

```rust
#[cfg(not(clippy)]
#[cfg(not(clippy))]
include!(concat!(env!("OUT_DIR"), "/my_big_function-generated.rs"));

#[cfg(clippy)]
Expand Down
5 changes: 5 additions & 0 deletions book/src/development/adding_lints.md
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,11 @@ declare_clippy_lint! {
}
```

If the lint is in the `restriction` group because it lints things that are not
necessarily “bad” but are more of a style choice, then replace the
“Why is this bad?” section heading with “Why restrict this?”, to avoid writing
“Why is this bad? It isn't, but ...”.

Once your lint is merged, this documentation will show up in the [lint
list][lint_list].

Expand Down
7 changes: 6 additions & 1 deletion clippy_dev/src/new_lint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,12 +331,17 @@ fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String {
}

fn get_lint_declaration(name_upper: &str, category: &str) -> String {
let justification_heading = if category == "restriction" {
"Why restrict this?"
} else {
"Why is this bad?"
};
formatdoc!(
r#"
declare_clippy_lint! {{
/// ### What it does
///
/// ### Why is this bad?
/// ### {justification_heading}
///
/// ### Example
/// ```no_run
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/absolute_paths.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ declare_clippy_lint! {
/// ### What it does
/// Checks for usage of items through absolute paths, like `std::env::current_dir`.
///
/// ### Why is this bad?
/// ### Why restrict this?
/// Many codebases have their own style when it comes to importing, but one that is seldom used
/// is using absolute paths *everywhere*. This is generally considered unidiomatic, and you
/// should add a `use` statement.
Expand Down
7 changes: 4 additions & 3 deletions clippy_lints/src/allow_attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,11 @@ declare_clippy_lint! {
/// This lint only warns outer attributes (`#[allow]`), as inner attributes
/// (`#![allow]`) are usually used to enable or disable lints on a global scale.
///
/// ### Why is this bad?
/// `#[expect]` attributes suppress the lint emission, but emit a warning, if
/// ### Why restrict this?
/// `#[allow]` attributes can linger after their reason for existence is gone.
/// `#[expect]` attributes suppress the lint emission, but emit a warning if
/// the expectation is unfulfilled. This can be useful to be notified when the
/// lint is no longer triggered.
/// lint is no longer triggered, which may indicate the attribute can be removed.
///
/// ### Example
/// ```rust,ignore
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/as_conversions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ declare_clippy_lint! {
/// There is a good explanation the reason why this lint should work in this way and how it is useful
/// [in this issue](https://github.com/rust-lang/rust-clippy/issues/5122).
///
/// ### Why is this bad?
/// ### Why restrict this?
/// `as` conversions will perform many kinds of
/// conversions, including silently lossy conversions and dangerous coercions.
/// There are cases when it makes sense to use `as`, so the lint is
Expand Down
10 changes: 4 additions & 6 deletions clippy_lints/src/asm_syntax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,8 @@ declare_clippy_lint! {
/// ### What it does
/// Checks for usage of Intel x86 assembly syntax.
///
/// ### Why is this bad?
/// The lint has been enabled to indicate a preference
/// for AT&T x86 assembly syntax.
/// ### Why restrict this?
/// To enforce consistent use of AT&T x86 assembly syntax.
///
/// ### Example
///
Expand Down Expand Up @@ -114,9 +113,8 @@ declare_clippy_lint! {
/// ### What it does
/// Checks for usage of AT&T x86 assembly syntax.
///
/// ### Why is this bad?
/// The lint has been enabled to indicate a preference
/// for Intel x86 assembly syntax.
/// ### Why restrict this?
/// To enforce consistent use of Intel x86 assembly syntax.
///
/// ### Example
///
Expand Down
20 changes: 15 additions & 5 deletions clippy_lints/src/assertions_on_result_states.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,33 @@ declare_clippy_lint! {
/// ### What it does
/// Checks for `assert!(r.is_ok())` or `assert!(r.is_err())` calls.
///
/// ### Why is this bad?
/// An assertion failure cannot output an useful message of the error.
/// ### Why restrict this?
/// This form of assertion does not show any of the information present in the `Result`
/// other than which variant it isn’t.
///
/// ### Known problems
/// The suggested replacement decreases the readability of code and log output.
///
/// ### Example
/// ```rust,ignore
/// ```rust,no_run
/// # let r = Ok::<_, ()>(());
/// assert!(r.is_ok());
/// # let r = Err::<_, ()>(());
/// # let r = Err::<(), _>(());
/// assert!(r.is_err());
/// ```
///
/// Use instead:
///
/// ```rust,no_run
/// # let r = Ok::<_, ()>(());
/// r.unwrap();
/// # let r = Err::<(), _>(());
/// r.unwrap_err();
/// ```
#[clippy::version = "1.64.0"]
pub ASSERTIONS_ON_RESULT_STATES,
restriction,
"`assert!(r.is_ok())`/`assert!(r.is_err())` gives worse error message than directly calling `r.unwrap()`/`r.unwrap_err()`"
"`assert!(r.is_ok())` or `assert!(r.is_err())` gives worse panic messages than directly calling `r.unwrap()` or `r.unwrap_err()`"
}

declare_lint_pass!(AssertionsOnResultStates => [ASSERTIONS_ON_RESULT_STATES]);
Expand Down
6 changes: 3 additions & 3 deletions clippy_lints/src/attrs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -309,9 +309,9 @@ declare_clippy_lint! {
///
/// (This requires the `lint_reasons` feature)
///
/// ### Why is this bad?
/// Allowing a lint should always have a reason. This reason should be documented to
/// ensure that others understand the reasoning
/// ### Why restrict this?
/// Justifying each `allow` helps readers understand the reasoning,
/// and may allow removing `allow` attributes if their purpose is obsolete.
///
/// ### Example
/// ```no_run
Expand Down
6 changes: 3 additions & 3 deletions clippy_lints/src/casts/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ declare_clippy_lint! {
/// ### What it does
/// Checks for casts of a function pointer to any integer type.
///
/// ### Why is this bad?
/// ### Why restrict this?
/// Casting a function pointer to an integer can have surprising results and can occur
/// accidentally if parentheses are omitted from a function call. If you aren't doing anything
/// low-level with function pointers then you can opt-out of casting functions to integers in
Expand Down Expand Up @@ -535,8 +535,8 @@ declare_clippy_lint! {
/// ### What it does
/// Checks for the usage of `as _` conversion using inferred type.
///
/// ### Why is this bad?
/// The conversion might include lossy conversion and dangerous cast that might go
/// ### Why restrict this?
/// The conversion might include lossy conversion or a dangerous cast that might go
/// undetected due to the type being inferred.
///
/// The lint is allowed by default as using `_` is less wordy than always specifying the type.
Expand Down
6 changes: 4 additions & 2 deletions clippy_lints/src/create_dir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ declare_clippy_lint! {
/// ### What it does
/// Checks usage of `std::fs::create_dir` and suggest using `std::fs::create_dir_all` instead.
///
/// ### Why is this bad?
/// Sometimes `std::fs::create_dir` is mistakenly chosen over `std::fs::create_dir_all`.
/// ### Why restrict this?
/// Sometimes `std::fs::create_dir` is mistakenly chosen over `std::fs::create_dir_all`,
/// resulting in failure when more than one directory needs to be created or when the directory already exists.
/// Crates which never need to specifically create a single directory may wish to prevent this mistake.
///
/// ### Example
/// ```rust,ignore
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/dbg_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ declare_clippy_lint! {
/// ### What it does
/// Checks for usage of the [`dbg!`](https://doc.rust-lang.org/std/macro.dbg.html) macro.
///
/// ### Why is this bad?
/// ### Why restrict this?
/// The `dbg!` macro is intended as a debugging tool. It should not be present in released
/// software or committed to a version control system.
///
Expand Down
5 changes: 2 additions & 3 deletions clippy_lints/src/default_numeric_fallback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,8 @@ declare_clippy_lint! {
///
/// See [RFC0212](https://github.com/rust-lang/rfcs/blob/master/text/0212-restore-int-fallback.md) for more information about the fallback.
///
/// ### Why is this bad?
/// For those who are very careful about types, default numeric fallback
/// can be a pitfall that cause unexpected runtime behavior.
/// ### Why restrict this?
/// To ensure that every numeric type is chosen explicitly rather than implicitly.
///
/// ### Known problems
/// This lint can only be allowed at the function level or above.
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/default_union_representation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ declare_clippy_lint! {
/// ### What it does
/// Displays a warning when a union is declared with the default representation (without a `#[repr(C)]` attribute).
///
/// ### Why is this bad?
/// ### Why restrict this?
/// Unions in Rust have unspecified layout by default, despite many people thinking that they
/// lay out each field at the start of the union (like C does). That is, there are no guarantees
/// about the offset of the fields for unions with multiple non-ZST fields without an explicitly
Expand Down
14 changes: 5 additions & 9 deletions clippy_lints/src/dereference.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_hir_and_then};
use clippy_utils::source::{snippet_with_applicability, snippet_with_context};
use clippy_utils::sugg::has_enclosing_paren;
use clippy_utils::ty::{implements_trait, is_manually_drop, peel_mid_ty_refs};
use clippy_utils::{expr_use_ctxt, get_parent_expr, is_lint_allowed, path_to_local, DefinedTy, ExprUseNode};
use clippy_utils::{
expr_use_ctxt, get_parent_expr, is_block_like, is_lint_allowed, path_to_local, DefinedTy, ExprUseNode,
};
use core::mem;
use rustc_ast::util::parser::{PREC_POSTFIX, PREC_PREFIX};
use rustc_data_structures::fx::FxIndexMap;
Expand Down Expand Up @@ -1038,14 +1040,8 @@ fn report<'tcx>(
);
},
State::ExplicitDeref { mutability } => {
if matches!(
expr.kind,
ExprKind::Block(..)
| ExprKind::ConstBlock(_)
| ExprKind::If(..)
| ExprKind::Loop(..)
| ExprKind::Match(..)
) && let ty::Ref(_, ty, _) = data.adjusted_ty.kind()
if is_block_like(expr)
&& let ty::Ref(_, ty, _) = data.adjusted_ty.kind()
&& ty.is_sized(cx.tcx, cx.param_env)
{
// Rustc bug: auto deref doesn't work on block expression when targeting sized types.
Expand Down
31 changes: 21 additions & 10 deletions clippy_lints/src/derive.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_note, span_lint_and_sugg, span_lint_and_then};
use clippy_utils::diagnostics::{span_lint_and_note, span_lint_and_then, span_lint_hir_and_then};
use clippy_utils::ty::{implements_trait, implements_trait_with_env, is_copy};
use clippy_utils::{has_non_exhaustive_attr, is_lint_allowed, match_def_path, paths};
use rustc_errors::Applicability;
use rustc_hir::def_id::DefId;
use rustc_hir::intravisit::{walk_expr, walk_fn, walk_item, FnKind, Visitor};
use rustc_hir::{
self as hir, BlockCheckMode, BodyId, Expr, ExprKind, FnDecl, Safety, Impl, Item, ItemKind, UnsafeSource,
self as hir, BlockCheckMode, BodyId, Expr, ExprKind, FnDecl, Impl, Item, ItemKind, Safety, UnsafeSource,
};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::hir::nested_filter;
use rustc_middle::traits::Reveal;
use rustc_middle::ty::{
self, ClauseKind, GenericArgKind, GenericParamDefKind, ParamEnv, Upcast, TraitPredicate, Ty, TyCtxt,
self, ClauseKind, GenericArgKind, GenericParamDefKind, ParamEnv, TraitPredicate, Ty, TyCtxt, Upcast,
};
use rustc_session::declare_lint_pass;
use rustc_span::def_id::LocalDefId;
Expand Down Expand Up @@ -390,13 +390,17 @@ fn check_unsafe_derive_deserialize<'tcx>(
.map(|imp_did| cx.tcx.hir().expect_item(imp_did.expect_local()))
.any(|imp| has_unsafe(cx, imp))
{
span_lint_and_help(
span_lint_hir_and_then(
cx,
UNSAFE_DERIVE_DESERIALIZE,
adt_hir_id,
item.span,
"you are deriving `serde::Deserialize` on a type that has methods using `unsafe`",
None,
"consider implementing `serde::Deserialize` manually. See https://serde.rs/impl-deserialize.html",
|diag| {
diag.help(
"consider implementing `serde::Deserialize` manually. See https://serde.rs/impl-deserialize.html",
);
},
);
}
}
Expand Down Expand Up @@ -452,20 +456,27 @@ fn check_partial_eq_without_eq<'tcx>(cx: &LateContext<'tcx>, span: Span, trait_r
&& !has_non_exhaustive_attr(cx.tcx, *adt)
&& !ty_implements_eq_trait(cx.tcx, ty, eq_trait_def_id)
&& let param_env = param_env_for_derived_eq(cx.tcx, adt.did(), eq_trait_def_id)
&& let Some(local_def_id) = adt.did().as_local()
// If all of our fields implement `Eq`, we can implement `Eq` too
&& adt
.all_fields()
.map(|f| f.ty(cx.tcx, args))
.all(|ty| implements_trait_with_env(cx.tcx, param_env, ty, eq_trait_def_id, None, &[]))
{
span_lint_and_sugg(
span_lint_hir_and_then(
cx,
DERIVE_PARTIAL_EQ_WITHOUT_EQ,
cx.tcx.local_def_id_to_hir_id(local_def_id),
span.ctxt().outer_expn_data().call_site,
"you are deriving `PartialEq` and can implement `Eq`",
"consider deriving `Eq` as well",
"PartialEq, Eq".to_string(),
Applicability::MachineApplicable,
|diag| {
diag.span_suggestion(
span.ctxt().outer_expn_data().call_site,
"consider deriving `Eq` as well",
"PartialEq, Eq",
Applicability::MachineApplicable,
);
},
);
}
}
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/disallowed_script_idents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ declare_clippy_lint! {
/// [aliases]: http://www.unicode.org/reports/tr24/tr24-31.html#Script_Value_Aliases
/// [supported_scripts]: https://www.unicode.org/iso15924/iso15924-codes.html
///
/// ### Why is this bad?
/// ### Why restrict this?
/// It may be not desired to have many different scripts for
/// identifiers in the codebase.
///
/// Note that if you only want to allow plain English, you might want to use
/// Note that if you only want to allow typical English, you might want to use
/// built-in [`non_ascii_idents`] lint instead.
///
/// [`non_ascii_idents`]: https://doc.rust-lang.org/rustc/lints/listing/allowed-by-default.html#non-ascii-idents
Expand Down
28 changes: 25 additions & 3 deletions clippy_lints/src/doc/markdown.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use clippy_utils::diagnostics::{span_lint, span_lint_and_then};
use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
use clippy_utils::source::snippet_with_applicability;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::{Applicability, SuggestionStyle};
Expand Down Expand Up @@ -30,6 +30,7 @@ pub fn check(
word = tmp_word;
}

let original_len = word.len();
word = word.trim_start_matches(trim_pattern);

// Remove leading or trailing single `:` which may be part of a sentence.
Expand All @@ -44,6 +45,25 @@ pub fn check(
continue;
}

// Ensure that all reachable matching closing parens are included as well.
let size_diff = original_len - word.len();
let mut open_parens = 0;
let mut close_parens = 0;
for c in word.chars() {
if c == '(' {
open_parens += 1;
} else if c == ')' {
close_parens += 1;
}
}
while close_parens < open_parens
&& let Some(tmp_word) = orig_word.get(size_diff..=(word.len() + size_diff))
&& tmp_word.ends_with(')')
{
word = tmp_word;
close_parens += 1;
}

// Adjust for the current word
let offset = word.as_ptr() as usize - text.as_ptr() as usize;
let span = Span::new(
Expand Down Expand Up @@ -92,13 +112,15 @@ fn check_word(cx: &LateContext<'_>, word: &str, span: Span, code_level: isize, b
if let Ok(url) = Url::parse(word) {
// try to get around the fact that `foo::bar` parses as a valid URL
if !url.cannot_be_a_base() {
span_lint(
span_lint_and_sugg(
cx,
DOC_MARKDOWN,
span,
"you should put bare URLs between `<`/`>` or make a proper Markdown link",
"try",
format!("<{word}>"),
Applicability::MachineApplicable,
);

return;
}
}
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/doc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ declare_clippy_lint! {
/// Checks for the doc comments of publicly visible
/// safe functions and traits and warns if there is a `# Safety` section.
///
/// ### Why is this bad?
/// ### Why restrict this?
/// Safe functions and traits are safe to implement and therefore do not
/// need to describe safety preconditions that users are required to uphold.
///
Expand Down
Loading

0 comments on commit 00c355b

Please sign in to comment.