Skip to content
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

Rollup of 3 pull requests #4552

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -1050,6 +1050,7 @@ Released 2018-09-13
[`mem_discriminant_non_enum`]: https://rust-lang.github.io/rust-clippy/master/index.html#mem_discriminant_non_enum
[`mem_forget`]: https://rust-lang.github.io/rust-clippy/master/index.html#mem_forget
[`mem_replace_option_with_none`]: https://rust-lang.github.io/rust-clippy/master/index.html#mem_replace_option_with_none
[`mem_replace_with_uninit`]: https://rust-lang.github.io/rust-clippy/master/index.html#mem_replace_with_uninit
[`min_max`]: https://rust-lang.github.io/rust-clippy/master/index.html#min_max
[`misaligned_transmute`]: https://rust-lang.github.io/rust-clippy/master/index.html#misaligned_transmute
[`misrefactored_assign_op`]: https://rust-lang.github.io/rust-clippy/master/index.html#misrefactored_assign_op
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

A collection of lints to catch common mistakes and improve your [Rust](https://github.com/rust-lang/rust) code.

[There are 313 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
[There are 314 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)

We have a bunch of lint categories to allow you to choose how much Clippy is supposed to ~~annoy~~ help you:

Expand Down
3 changes: 2 additions & 1 deletion clippy_lints/src/explicit_write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,8 @@ fn write_output_string(write_args: &HirVec<Expr>) -> Option<String> {
if output_args.len() > 0;
if let ExprKind::AddrOf(_, ref output_string_expr) = output_args[0].node;
if let ExprKind::Array(ref string_exprs) = output_string_expr.node;
if string_exprs.len() > 0;
// we only want to provide an automatic suggestion for simple (non-format) strings
if string_exprs.len() == 1;
if let ExprKind::Lit(ref lit) = string_exprs[0].node;
if let LitKind::Str(ref write_output, _) = lit.node;
then {
Expand Down
5 changes: 3 additions & 2 deletions clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -667,6 +667,7 @@ pub fn register_plugins(reg: &mut rustc_driver::plugin::Registry<'_>, conf: &Con
shadow::SHADOW_UNRELATED,
strings::STRING_ADD_ASSIGN,
trait_bounds::TYPE_REPETITION_IN_BOUNDS,
types::CAST_LOSSLESS,
types::CAST_POSSIBLE_TRUNCATION,
types::CAST_POSSIBLE_WRAP,
types::CAST_PRECISION_LOSS,
Expand Down Expand Up @@ -781,6 +782,7 @@ pub fn register_plugins(reg: &mut rustc_driver::plugin::Registry<'_>, conf: &Con
matches::SINGLE_MATCH,
mem_discriminant::MEM_DISCRIMINANT_NON_ENUM,
mem_replace::MEM_REPLACE_OPTION_WITH_NONE,
mem_replace::MEM_REPLACE_WITH_UNINIT,
methods::CHARS_LAST_CMP,
methods::CHARS_NEXT_CMP,
methods::CLONE_DOUBLE_REF,
Expand Down Expand Up @@ -890,7 +892,6 @@ pub fn register_plugins(reg: &mut rustc_driver::plugin::Registry<'_>, conf: &Con
types::ABSURD_EXTREME_COMPARISONS,
types::BORROWED_BOX,
types::BOX_VEC,
types::CAST_LOSSLESS,
types::CAST_PTR_ALIGNMENT,
types::CAST_REF_TO_MUT,
types::CHAR_LIT_AS_U8,
Expand Down Expand Up @@ -1072,7 +1073,6 @@ pub fn register_plugins(reg: &mut rustc_driver::plugin::Registry<'_>, conf: &Con
transmute::TRANSMUTE_PTR_TO_REF,
transmute::USELESS_TRANSMUTE,
types::BORROWED_BOX,
types::CAST_LOSSLESS,
types::CHAR_LIT_AS_U8,
types::OPTION_OPTION,
types::TYPE_COMPLEXITY,
Expand Down Expand Up @@ -1116,6 +1116,7 @@ pub fn register_plugins(reg: &mut rustc_driver::plugin::Registry<'_>, conf: &Con
loops::REVERSE_RANGE_LOOP,
loops::WHILE_IMMUTABLE_CONDITION,
mem_discriminant::MEM_DISCRIMINANT_NON_ENUM,
mem_replace::MEM_REPLACE_WITH_UNINIT,
methods::CLONE_DOUBLE_REF,
methods::INTO_ITER_ON_ARRAY,
methods::TEMPORARY_CSTRING_AS_PTR,
Expand Down
126 changes: 95 additions & 31 deletions clippy_lints/src/mem_replace.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use crate::utils::{match_def_path, match_qpath, paths, snippet_with_applicability, span_lint_and_sugg};
use crate::utils::{
match_def_path, match_qpath, paths, snippet_with_applicability, span_help_and_lint, span_lint_and_sugg,
};
use if_chain::if_chain;
use rustc::hir::{Expr, ExprKind, MutMutable, QPath};
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
Expand Down Expand Up @@ -32,7 +34,40 @@ declare_clippy_lint! {
"replacing an `Option` with `None` instead of `take()`"
}

declare_lint_pass!(MemReplace => [MEM_REPLACE_OPTION_WITH_NONE]);
declare_clippy_lint! {
/// **What it does:** Checks for `mem::replace(&mut _, mem::uninitialized())`
/// and `mem::replace(&mut _, mem::zeroed())`.
///
/// **Why is this bad?** This will lead to undefined behavior even if the
/// value is overwritten later, because the uninitialized value may be
/// observed in the case of a panic.
///
/// **Known problems:** None.
///
/// **Example:**
///
/// ```
/// use std::mem;
///# fn may_panic(v: Vec<i32>) -> Vec<i32> { v }
///
/// #[allow(deprecated, invalid_value)]
/// fn myfunc (v: &mut Vec<i32>) {
/// let taken_v = unsafe { mem::replace(v, mem::uninitialized()) };
/// let new_v = may_panic(taken_v); // undefined behavior on panic
/// mem::forget(mem::replace(v, new_v));
/// }
/// ```
///
/// The [take_mut](https://docs.rs/take_mut) crate offers a sound solution,
/// at the cost of either lazily creating a replacement value or aborting
/// on panic, to ensure that the uninitialized value cannot be observed.
pub MEM_REPLACE_WITH_UNINIT,
correctness,
"`mem::replace(&mut _, mem::uninitialized())` or `mem::replace(&mut _, mem::zeroed())`"
}

declare_lint_pass!(MemReplace =>
[MEM_REPLACE_OPTION_WITH_NONE, MEM_REPLACE_WITH_UNINIT]);

impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemReplace {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
Expand All @@ -45,37 +80,66 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemReplace {
if match_def_path(cx, def_id, &paths::MEM_REPLACE);

// Check that second argument is `Option::None`
if let ExprKind::Path(ref replacement_qpath) = func_args[1].node;
if match_qpath(replacement_qpath, &paths::OPTION_NONE);

then {
// Since this is a late pass (already type-checked),
// and we already know that the second argument is an
// `Option`, we do not need to check the first
// argument's type. All that's left is to get
// replacee's path.
let replaced_path = match func_args[0].node {
ExprKind::AddrOf(MutMutable, ref replaced) => {
if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.node {
replaced_path
} else {
return
}
},
ExprKind::Path(QPath::Resolved(None, ref replaced_path)) => replaced_path,
_ => return,
};
if let ExprKind::Path(ref replacement_qpath) = func_args[1].node {
if match_qpath(replacement_qpath, &paths::OPTION_NONE) {

let mut applicability = Applicability::MachineApplicable;
span_lint_and_sugg(
cx,
MEM_REPLACE_OPTION_WITH_NONE,
expr.span,
"replacing an `Option` with `None`",
"consider `Option::take()` instead",
format!("{}.take()", snippet_with_applicability(cx, replaced_path.span, "", &mut applicability)),
applicability,
);
// Since this is a late pass (already type-checked),
// and we already know that the second argument is an
// `Option`, we do not need to check the first
// argument's type. All that's left is to get
// replacee's path.
let replaced_path = match func_args[0].node {
ExprKind::AddrOf(MutMutable, ref replaced) => {
if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.node {
replaced_path
} else {
return
}
},
ExprKind::Path(QPath::Resolved(None, ref replaced_path)) => replaced_path,
_ => return,
};

let mut applicability = Applicability::MachineApplicable;
span_lint_and_sugg(
cx,
MEM_REPLACE_OPTION_WITH_NONE,
expr.span,
"replacing an `Option` with `None`",
"consider `Option::take()` instead",
format!("{}.take()", snippet_with_applicability(cx, replaced_path.span, "", &mut applicability)),
applicability,
);
}
}
if let ExprKind::Call(ref repl_func, ref repl_args) = func_args[1].node {
if_chain! {
if repl_args.is_empty();
if let ExprKind::Path(ref repl_func_qpath) = repl_func.node;
if let Some(repl_def_id) = cx.tables.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id();
then {
if match_def_path(cx, repl_def_id, &paths::MEM_UNINITIALIZED) {
span_help_and_lint(
cx,
MEM_REPLACE_WITH_UNINIT,
expr.span,
"replacing with `mem::uninitialized()`",
"consider using the `take_mut` crate instead",
);
} else if match_def_path(cx, repl_def_id, &paths::MEM_ZEROED) &&
!cx.tables.expr_ty(&func_args[1]).is_primitive() {
span_help_and_lint(
cx,
MEM_REPLACE_WITH_UNINIT,
expr.span,
"replacing with `mem::zeroed()`",
"consider using a default value or the `take_mut` crate instead",
);
}
}
}
}
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -765,7 +765,7 @@ declare_clippy_lint! {
/// }
/// ```
pub CAST_LOSSLESS,
complexity,
pedantic,
"casts using `as` that are known to be lossless, e.g., `x as u64` where `x: u8`"
}

Expand Down
2 changes: 2 additions & 0 deletions clippy_lints/src/utils/paths.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ pub const MEM_FORGET: [&str; 3] = ["core", "mem", "forget"];
pub const MEM_MAYBEUNINIT: [&str; 4] = ["core", "mem", "maybe_uninit", "MaybeUninit"];
pub const MEM_MAYBEUNINIT_UNINIT: [&str; 5] = ["core", "mem", "maybe_uninit", "MaybeUninit", "uninit"];
pub const MEM_REPLACE: [&str; 3] = ["core", "mem", "replace"];
pub const MEM_UNINITIALIZED: [&str; 3] = ["core", "mem", "uninitialized"];
pub const MEM_ZEROED: [&str; 3] = ["core", "mem", "zeroed"];
pub const MUTEX: [&str; 4] = ["std", "sync", "mutex", "Mutex"];
pub const OPEN_OPTIONS: [&str; 3] = ["std", "fs", "OpenOptions"];
pub const OPS_MODULE: [&str; 2] = ["core", "ops"];
Expand Down
11 changes: 9 additions & 2 deletions src/lintlist/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pub use lint::Lint;
pub use lint::LINT_LEVELS;

// begin lint list, do not remove this comment, it’s used in `update_lints`
pub const ALL_LINTS: [Lint; 313] = [
pub const ALL_LINTS: [Lint; 314] = [
Lint {
name: "absurd_extreme_comparisons",
group: "correctness",
Expand Down Expand Up @@ -121,7 +121,7 @@ pub const ALL_LINTS: [Lint; 313] = [
},
Lint {
name: "cast_lossless",
group: "complexity",
group: "pedantic",
desc: "casts using `as` that are known to be lossless, e.g., `x as u64` where `x: u8`",
deprecation: None,
module: "types",
Expand Down Expand Up @@ -1043,6 +1043,13 @@ pub const ALL_LINTS: [Lint; 313] = [
deprecation: None,
module: "mem_replace",
},
Lint {
name: "mem_replace_with_uninit",
group: "correctness",
desc: "`mem::replace(&mut _, mem::uninitialized())` or `mem::zeroed()`",
deprecation: None,
module: "mem_replace",
},
Lint {
name: "min_max",
group: "correctness",
Expand Down
8 changes: 8 additions & 0 deletions tests/ui/explicit_write_non_rustfix.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#![allow(unused_imports, clippy::blacklisted_name)]
#![warn(clippy::explicit_write)]

fn main() {
use std::io::Write;
let bar = "bar";
writeln!(std::io::stderr(), "foo {}", bar).unwrap();
}
10 changes: 10 additions & 0 deletions tests/ui/explicit_write_non_rustfix.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
error: use of `writeln!(stderr(), ...).unwrap()`. Consider using `eprintln!` instead
--> $DIR/explicit_write_non_rustfix.rs:7:5
|
LL | writeln!(std::io::stderr(), "foo {}", bar).unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: `-D clippy::explicit-write` implied by `-D warnings`

error: aborting due to previous error

35 changes: 35 additions & 0 deletions tests/ui/repl_uninit.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#![allow(deprecated, invalid_value)]
#![warn(clippy::all)]

use std::mem;

fn might_panic<X>(x: X) -> X {
// in practice this would be a possibly-panicky operation
x
}

fn main() {
let mut v = vec![0i32; 4];
// the following is UB if `might_panic` panics
unsafe {
let taken_v = mem::replace(&mut v, mem::uninitialized());
let new_v = might_panic(taken_v);
std::mem::forget(mem::replace(&mut v, new_v));
}

unsafe {
let taken_v = mem::replace(&mut v, mem::zeroed());
let new_v = might_panic(taken_v);
std::mem::forget(mem::replace(&mut v, new_v));
}

// this is silly but OK, because usize is a primitive type
let mut u: usize = 42;
let uref = &mut u;
let taken_u = unsafe { mem::replace(uref, mem::zeroed()) };
*uref = taken_u + 1;

// this is still not OK, because uninit
let taken_u = unsafe { mem::replace(uref, mem::uninitialized()) };
*uref = taken_u + 1;
}
27 changes: 27 additions & 0 deletions tests/ui/repl_uninit.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
error: replacing with `mem::uninitialized()`
--> $DIR/repl_uninit.rs:15:23
|
LL | let taken_v = mem::replace(&mut v, mem::uninitialized());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: `-D clippy::mem-replace-with-uninit` implied by `-D warnings`
= help: consider using the `take_mut` crate instead

error: replacing with `mem::zeroed()`
--> $DIR/repl_uninit.rs:21:23
|
LL | let taken_v = mem::replace(&mut v, mem::zeroed());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: consider using a default value or the `take_mut` crate instead

error: replacing with `mem::uninitialized()`
--> $DIR/repl_uninit.rs:33:28
|
LL | let taken_u = unsafe { mem::replace(uref, mem::uninitialized()) };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: consider using the `take_mut` crate instead

error: aborting due to 3 previous errors

1 change: 1 addition & 0 deletions tests/ui/types.fixed
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// run-rustfix

#![allow(dead_code, unused_variables)]
#![warn(clippy::all, clippy::pedantic)]

// should not warn on lossy casting in constant types
// because not supported yet
Expand Down
1 change: 1 addition & 0 deletions tests/ui/types.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// run-rustfix

#![allow(dead_code, unused_variables)]
#![warn(clippy::all, clippy::pedantic)]

// should not warn on lossy casting in constant types
// because not supported yet
Expand Down
2 changes: 1 addition & 1 deletion tests/ui/types.stderr
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
error: casting i32 to i64 may become silently lossy if you later change the type
--> $DIR/types.rs:13:22
--> $DIR/types.rs:14:22
|
LL | let c_i64: i64 = c as i64;
| ^^^^^^^^ help: try: `i64::from(c)`
Expand Down