Skip to content

Commit

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

r? `@Manishearth`

Closes rust-lang/rust-clippy#12148
  • Loading branch information
matthiaskrgr authored Jan 26, 2024
2 parents f096e91 + 9ce0b83 commit 57f63a3
Show file tree
Hide file tree
Showing 158 changed files with 2,840 additions and 1,000 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5606,6 +5606,7 @@ Released 2018-09-13
[`suspicious_else_formatting`]: https://rust-lang.github.io/rust-clippy/master/index.html#suspicious_else_formatting
[`suspicious_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#suspicious_map
[`suspicious_op_assign_impl`]: https://rust-lang.github.io/rust-clippy/master/index.html#suspicious_op_assign_impl
[`suspicious_open_options`]: https://rust-lang.github.io/rust-clippy/master/index.html#suspicious_open_options
[`suspicious_operation_groupings`]: https://rust-lang.github.io/rust-clippy/master/index.html#suspicious_operation_groupings
[`suspicious_splitn`]: https://rust-lang.github.io/rust-clippy/master/index.html#suspicious_splitn
[`suspicious_to_owned`]: https://rust-lang.github.io/rust-clippy/master/index.html#suspicious_to_owned
Expand Down Expand Up @@ -5814,6 +5815,7 @@ Released 2018-09-13
[`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
[`allowed-duplicate-crates`]: https://doc.rust-lang.org/clippy/lint_configuration.html#allowed-duplicate-crates
[`enforce-iter-loop-reborrow`]: https://doc.rust-lang.org/clippy/lint_configuration.html#enforce-iter-loop-reborrow
[`check-private-items`]: https://doc.rust-lang.org/clippy/lint_configuration.html#check-private-items
[`pub-underscore-fields-behavior`]: https://doc.rust-lang.org/clippy/lint_configuration.html#pub-underscore-fields-behavior
Expand Down
21 changes: 17 additions & 4 deletions book/src/lint_configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ default configuration of Clippy. By default, any configuration will replace the
* `doc-valid-idents = ["ClipPy"]` would replace the default list with `["ClipPy"]`.
* `doc-valid-idents = ["ClipPy", ".."]` would append `ClipPy` to the default list.

**Default Value:** `["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "DirectX", "ECMAScript", "GPLv2", "GPLv3", "GitHub", "GitLab", "IPv4", "IPv6", "ClojureScript", "CoffeeScript", "JavaScript", "PureScript", "TypeScript", "WebAssembly", "NaN", "NaNs", "OAuth", "GraphQL", "OCaml", "OpenGL", "OpenMP", "OpenSSH", "OpenSSL", "OpenStreetMap", "OpenDNS", "WebGL", "WebGL2", "WebGPU", "TensorFlow", "TrueType", "iOS", "macOS", "FreeBSD", "TeX", "LaTeX", "BibTeX", "BibLaTeX", "MinGW", "CamelCase"]`
**Default Value:** `["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "DirectX", "ECMAScript", "GPLv2", "GPLv3", "GitHub", "GitLab", "IPv4", "IPv6", "ClojureScript", "CoffeeScript", "JavaScript", "PureScript", "TypeScript", "WebAssembly", "NaN", "NaNs", "OAuth", "GraphQL", "OCaml", "OpenDNS", "OpenGL", "OpenMP", "OpenSSH", "OpenSSL", "OpenStreetMap", "OpenTelemetry", "WebGL", "WebGL2", "WebGPU", "TensorFlow", "TrueType", "iOS", "macOS", "FreeBSD", "TeX", "LaTeX", "BibTeX", "BibLaTeX", "MinGW", "CamelCase"]`

---
**Affected lints:**
Expand Down Expand Up @@ -768,7 +768,19 @@ Additional dotfiles (files or directories starting with a dot) to allow
* [`path_ends_with_ext`](https://rust-lang.github.io/rust-clippy/master/index.html#path_ends_with_ext)


## `allowed-duplicate-crates`
A list of crate names to allow duplicates of

**Default Value:** `[]`

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


## `enforce-iter-loop-reborrow`
Whether to recommend using implicit into iter for reborrowed values.

#### Example
```no_run
let mut vec = vec![1, 2, 3];
Expand All @@ -793,7 +805,7 @@ for _ in &mut *rmvec {}


## `check-private-items`

Whether to also run the listed lints on private items.

**Default Value:** `false`

Expand All @@ -806,9 +818,10 @@ for _ in &mut *rmvec {}


## `pub-underscore-fields-behavior`
Lint "public" fields in a struct that are prefixed with an underscore based on their
exported visibility, or whether they are marked as "pub".


**Default Value:** `"PublicallyExported"`
**Default Value:** `"PubliclyExported"`

---
**Affected lints:**
Expand Down
80 changes: 63 additions & 17 deletions clippy_config/src/conf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ use crate::msrvs::Msrv;
use crate::types::{DisallowedPath, MacroMatcher, MatchLintBehaviour, PubUnderscoreFieldsBehaviour, Rename};
use crate::ClippyConfiguration;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::Applicability;
use rustc_session::Session;
use rustc_span::edit_distance::edit_distance;
use rustc_span::{BytePos, Pos, SourceFile, Span, SyntaxContext};
use serde::de::{IgnoredAny, IntoDeserializer, MapAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};
Expand All @@ -26,7 +28,7 @@ const DEFAULT_DOC_VALID_IDENTS: &[&str] = &[
"NaN", "NaNs",
"OAuth", "GraphQL",
"OCaml",
"OpenGL", "OpenMP", "OpenSSH", "OpenSSL", "OpenStreetMap", "OpenDNS",
"OpenDNS", "OpenGL", "OpenMP", "OpenSSH", "OpenSSL", "OpenStreetMap", "OpenTelemetry",
"WebGL", "WebGL2", "WebGPU",
"TensorFlow",
"TrueType",
Expand Down Expand Up @@ -59,18 +61,25 @@ impl TryConf {
#[derive(Debug)]
struct ConfError {
message: String,
suggestion: Option<Suggestion>,
span: Span,
}

impl ConfError {
fn from_toml(file: &SourceFile, error: &toml::de::Error) -> Self {
let span = error.span().unwrap_or(0..file.source_len.0 as usize);
Self::spanned(file, error.message(), span)
Self::spanned(file, error.message(), None, span)
}

fn spanned(file: &SourceFile, message: impl Into<String>, span: Range<usize>) -> Self {
fn spanned(
file: &SourceFile,
message: impl Into<String>,
suggestion: Option<Suggestion>,
span: Range<usize>,
) -> Self {
Self {
message: message.into(),
suggestion,
span: Span::new(
file.start_pos + BytePos::from_usize(span.start),
file.start_pos + BytePos::from_usize(span.end),
Expand Down Expand Up @@ -147,16 +156,18 @@ macro_rules! define_Conf {
match Field::deserialize(name.get_ref().as_str().into_deserializer()) {
Err(e) => {
let e: FieldError = e;
errors.push(ConfError::spanned(self.0, e.0, name.span()));
errors.push(ConfError::spanned(self.0, e.error, e.suggestion, name.span()));
}
$(Ok(Field::$name) => {
$(warnings.push(ConfError::spanned(self.0, format!("deprecated field `{}`. {}", name.get_ref(), $dep), name.span()));)?
$(warnings.push(ConfError::spanned(self.0, format!("deprecated field `{}`. {}", name.get_ref(), $dep), None, name.span()));)?
let raw_value = map.next_value::<toml::Spanned<toml::Value>>()?;
let value_span = raw_value.span();
match <$ty>::deserialize(raw_value.into_inner()) {
Err(e) => errors.push(ConfError::spanned(self.0, e.to_string().replace('\n', " ").trim(), value_span)),
Err(e) => errors.push(ConfError::spanned(self.0, e.to_string().replace('\n', " ").trim(), None, value_span)),
Ok(value) => match $name {
Some(_) => errors.push(ConfError::spanned(self.0, format!("duplicate field `{}`", name.get_ref()), name.span())),
Some(_) => {
errors.push(ConfError::spanned(self.0, format!("duplicate field `{}`", name.get_ref()), None, name.span()));
}
None => {
$name = Some(value);
// $new_conf is the same as one of the defined `$name`s, so
Expand All @@ -165,7 +176,7 @@ macro_rules! define_Conf {
Some(_) => errors.push(ConfError::spanned(self.0, concat!(
"duplicate field `", stringify!($new_conf),
"` (provided as `", stringify!($name), "`)"
), name.span())),
), None, name.span())),
None => $new_conf = $name.clone(),
})?
},
Expand Down Expand Up @@ -523,7 +534,11 @@ define_Conf! {
///
/// Additional dotfiles (files or directories starting with a dot) to allow
(allowed_dotfiles: FxHashSet<String> = FxHashSet::default()),
/// Lint: EXPLICIT_ITER_LOOP
/// Lint: MULTIPLE_CRATE_VERSIONS.
///
/// A list of crate names to allow duplicates of
(allowed_duplicate_crates: FxHashSet<String> = FxHashSet::default()),
/// Lint: EXPLICIT_ITER_LOOP.
///
/// Whether to recommend using implicit into iter for reborrowed values.
///
Expand All @@ -543,15 +558,15 @@ define_Conf! {
/// for _ in &mut *rmvec {}
/// ```
(enforce_iter_loop_reborrow: bool = false),
/// Lint: MISSING_SAFETY_DOC, UNNECESSARY_SAFETY_DOC, MISSING_PANICS_DOC, MISSING_ERRORS_DOC
/// Lint: MISSING_SAFETY_DOC, UNNECESSARY_SAFETY_DOC, MISSING_PANICS_DOC, MISSING_ERRORS_DOC.
///
/// Whether to also run the listed lints on private items.
(check_private_items: bool = false),
/// Lint: PUB_UNDERSCORE_FIELDS
/// Lint: PUB_UNDERSCORE_FIELDS.
///
/// Lint "public" fields in a struct that are prefixed with an underscore based on their
/// exported visibility, or whether they are marked as "pub".
(pub_underscore_fields_behavior: PubUnderscoreFieldsBehaviour = PubUnderscoreFieldsBehaviour::PublicallyExported),
(pub_underscore_fields_behavior: PubUnderscoreFieldsBehaviour = PubUnderscoreFieldsBehaviour::PubliclyExported),
}

/// Search for the configuration file.
Expand Down Expand Up @@ -669,10 +684,16 @@ impl Conf {

// all conf errors are non-fatal, we just use the default conf in case of error
for error in errors {
sess.dcx().span_err(
let mut diag = sess.dcx().struct_span_err(
error.span,
format!("error reading Clippy's configuration file: {}", error.message),
);

if let Some(sugg) = error.suggestion {
diag.span_suggestion(error.span, sugg.message, sugg.suggestion, Applicability::MaybeIncorrect);
}

diag.emit();
}

for warning in warnings {
Expand All @@ -689,19 +710,31 @@ impl Conf {
const SEPARATOR_WIDTH: usize = 4;

#[derive(Debug)]
struct FieldError(String);
struct FieldError {
error: String,
suggestion: Option<Suggestion>,
}

#[derive(Debug)]
struct Suggestion {
message: &'static str,
suggestion: &'static str,
}

impl std::error::Error for FieldError {}

impl Display for FieldError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.pad(&self.0)
f.pad(&self.error)
}
}

impl serde::de::Error for FieldError {
fn custom<T: Display>(msg: T) -> Self {
Self(msg.to_string())
Self {
error: msg.to_string(),
suggestion: None,
}
}

fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self {
Expand All @@ -723,7 +756,20 @@ impl serde::de::Error for FieldError {
write!(msg, "{:SEPARATOR_WIDTH$}{field:column_width$}", " ").unwrap();
}
}
Self(msg)

let suggestion = expected
.iter()
.filter_map(|expected| {
let dist = edit_distance(field, expected, 4)?;
Some((dist, expected))
})
.min_by_key(|&(dist, _)| dist)
.map(|(_, suggestion)| Suggestion {
message: "perhaps you meant",
suggestion,
});

Self { error: msg, suggestion }
}
}

Expand Down
1 change: 1 addition & 0 deletions clippy_config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ extern crate rustc_ast;
extern crate rustc_data_structures;
#[allow(unused_extern_crates)]
extern crate rustc_driver;
extern crate rustc_errors;
extern crate rustc_session;
extern crate rustc_span;

Expand Down
2 changes: 1 addition & 1 deletion clippy_config/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,6 @@ unimplemented_serialize! {

#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub enum PubUnderscoreFieldsBehaviour {
PublicallyExported,
PubliclyExported,
AllPubFields,
}
4 changes: 2 additions & 2 deletions clippy_dev/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ version = "0.0.1"
edition = "2021"

[dependencies]
aho-corasick = "0.7"
aho-corasick = "1.0"
clap = "4.1.4"
indoc = "1.0"
itertools = "0.11"
opener = "0.5"
opener = "0.6"
shell-escape = "0.1"
walkdir = "2.3"

Expand Down
3 changes: 1 addition & 2 deletions clippy_dev/src/update_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -504,9 +504,8 @@ fn replace_ident_like(contents: &str, replacements: &[(&str, &str)]) -> Option<S
}

let searcher = AhoCorasickBuilder::new()
.dfa(true)
.match_kind(aho_corasick::MatchKind::LeftmostLongest)
.build_with_size::<u16, _, _>(replacements.iter().map(|&(x, _)| x.as_bytes()))
.build(replacements.iter().map(|&(x, _)| x.as_bytes()))
.unwrap();

let mut result = String::with_capacity(contents.len() + 1024);
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ edition = "2021"

[dependencies]
arrayvec = { version = "0.7", default-features = false }
cargo_metadata = "0.15.3"
cargo_metadata = "0.18"
clippy_config = { path = "../clippy_config" }
clippy_utils = { path = "../clippy_utils" }
declare_clippy_lint = { path = "../declare_clippy_lint" }
Expand Down
8 changes: 4 additions & 4 deletions clippy_lints/src/arc_with_non_send_sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ declare_clippy_lint! {
/// This lint warns when you use `Arc` with a type that does not implement `Send` or `Sync`.
///
/// ### Why is this bad?
/// `Arc<T>` is an Atomic `RC<T>` and guarantees that updates to the reference counter are
/// Atomic. This is useful in multiprocessing scenarios. To send an `Arc<T>` across processes
/// and make use of the atomic ref counter, `T` must be [both `Send` and `Sync`](https://doc.rust-lang.org/std/sync/struct.Arc.html#impl-Send-for-Arc%3CT%3E),
/// either `T` should be made `Send + Sync` or an `Rc` should be used instead of an `Arc`
/// `Arc<T>` is a thread-safe `Rc<T>` and guarantees that updates to the reference counter
/// use atomic operations. To send an `Arc<T>` across thread boundaries and
/// share ownership between multiple threads, `T` must be [both `Send` and `Sync`](https://doc.rust-lang.org/std/sync/struct.Arc.html#thread-safety),
/// so either `T` should be made `Send + Sync` or an `Rc` should be used instead of an `Arc`
///
/// ### Example
/// ```no_run
Expand Down
5 changes: 5 additions & 0 deletions clippy_lints/src/blocks_in_conditions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ impl<'tcx> LateLintPass<'tcx> for BlocksInConditions {
);

if let ExprKind::Block(block, _) = &cond.kind {
if !block.span.eq_ctxt(expr.span) {
// If the block comes from a macro, or as an argument to a macro,
// do not lint.
return;
}
if block.rules == BlockCheckMode::DefaultBlock {
if block.stmts.is_empty() {
if let Some(ex) = &block.expr {
Expand Down
6 changes: 5 additions & 1 deletion clippy_lints/src/cargo/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ mod wildcard_dependencies;
use cargo_metadata::MetadataCommand;
use clippy_utils::diagnostics::span_lint;
use clippy_utils::is_lint_allowed;
use rustc_data_structures::fx::FxHashSet;
use rustc_hir::hir_id::CRATE_HIR_ID;
use rustc_lint::{LateContext, LateLintPass, Lint};
use rustc_session::impl_lint_pass;
Expand Down Expand Up @@ -128,6 +129,8 @@ declare_clippy_lint! {
/// ### Known problems
/// Because this can be caused purely by the dependencies
/// themselves, it's not always possible to fix this issue.
/// In those cases, you can allow that specific crate using
/// the `allowed_duplicate_crates` configuration option.
///
/// ### Example
/// ```toml
Expand Down Expand Up @@ -163,6 +166,7 @@ declare_clippy_lint! {
}

pub struct Cargo {
pub allowed_duplicate_crates: FxHashSet<String>,
pub ignore_publish: bool,
}

Expand Down Expand Up @@ -208,7 +212,7 @@ impl LateLintPass<'_> for Cargo {
{
match MetadataCommand::new().exec() {
Ok(metadata) => {
multiple_crate_versions::check(cx, &metadata);
multiple_crate_versions::check(cx, &metadata, &self.allowed_duplicate_crates);
},
Err(e) => {
for lint in WITH_DEPS_LINTS {
Expand Down
Loading

0 comments on commit 57f63a3

Please sign in to comment.