Skip to content

Commit

Permalink
submodules: update clippy from b7a431e to a416c5e
Browse files Browse the repository at this point in the history
Changes:

````
rustup rust-lang/rust#52994
Fix test
Line length fix
Remove references to sized for end users
Remove DUMMY_SP
Add suggestion for replacement
Update lint definitions
Lint for Vec<Box<T: Sized>> - Closes rust-lang#3530
Fix doc_markdown mixed case false positive
question_mark: Suggest Some(opt?) for if-else
redundant_field_names: Do not trigger on path with type params
question_mark: Lint only early returns
question_mark: Fix applicability
Remove obsolete comment
new_without_default, partialeq_ne_impl: Use span_lint_node
Update .stderr after rebase
cargo fmt and remove stabilized feature
Make suggestion Applicability::MachineApplicable
Address review feedback
Extract method
Check array lengths to prevent OOB access
Add suggestion for explicit_write lint
Fix write_with_newline escaping false positive
````
  • Loading branch information
matthiaskrgr committed Dec 15, 2018
1 parent 7a19419 commit 9d15aaf
Show file tree
Hide file tree
Showing 29 changed files with 396 additions and 85 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -899,6 +899,7 @@ All notable changes to this project will be documented in this file.
[`useless_let_if_seq`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_let_if_seq
[`useless_transmute`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_transmute
[`useless_vec`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_vec
[`vec_box`]: https://rust-lang.github.io/rust-clippy/master/index.html#vec_box
[`verbose_bit_mask`]: https://rust-lang.github.io/rust-clippy/master/index.html#verbose_bit_mask
[`while_immutable_condition`]: https://rust-lang.github.io/rust-clippy/master/index.html#while_immutable_condition
[`while_let_loop`]: https://rust-lang.github.io/rust-clippy/master/index.html#while_let_loop
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

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

[There are 290 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
[There are 291 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
2 changes: 1 addition & 1 deletion clippy_lints/src/collapsible_if.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ fn check_if(cx: &EarlyContext<'_>, expr: &ast::Expr) {
fn block_starts_with_comment(cx: &EarlyContext<'_>, expr: &ast::Block) -> bool {
// We trim all opening braces and whitespaces and then check if the next string is a comment.
let trimmed_block_text = snippet_block(cx, expr.span, "..")
.trim_left_matches(|c: char| c.is_whitespace() || c == '{')
.trim_start_matches(|c: char| c.is_whitespace() || c == '{')
.to_owned();
trimmed_block_text.starts_with("//") || trimmed_block_text.starts_with("/*")
}
Expand Down
11 changes: 10 additions & 1 deletion clippy_lints/src/doc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(
for line in doc.lines() {
let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
debug_assert_eq!(offset as u32 as usize, offset);
contains_initial_stars |= line.trim_left().starts_with('*');
contains_initial_stars |= line.trim_start().starts_with('*');
// +1 for the newline
sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
}
Expand Down Expand Up @@ -281,6 +281,10 @@ fn check_word(cx: &EarlyContext<'_>, word: &str, span: Span) {
s != "_" && !s.contains("\\_") && s.contains('_')
}

fn has_hyphen(s: &str) -> bool {
s != "-" && s.contains('-')
}

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() {
Expand All @@ -295,6 +299,11 @@ fn check_word(cx: &EarlyContext<'_>, word: &str, span: Span) {
}
}

// We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
if has_underscore(word) && has_hyphen(word) {
return;
}

if has_underscore(word) || word.contains("::") || is_camel_case(word) {
span_lint(
cx,
Expand Down
104 changes: 79 additions & 25 deletions clippy_lints/src/explicit_write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@
use crate::rustc::hir::*;
use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
use crate::rustc::{declare_tool_lint, lint_array};
use crate::utils::opt_def_id;
use crate::utils::{is_expn_of, match_def_path, resolve_node, span_lint};
use crate::rustc_errors::Applicability;
use crate::syntax::ast::LitKind;
use crate::utils::{is_expn_of, match_def_path, opt_def_id, resolve_node, span_lint, span_lint_and_sugg};
use if_chain::if_chain;

/// **What it does:** Checks for usage of `write!()` / `writeln()!` which can be
Expand Down Expand Up @@ -81,32 +82,85 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
} else {
""
};
if let Some(macro_name) = calling_macro {
span_lint(
cx,
EXPLICIT_WRITE,
expr.span,
&format!(
"use of `{}!({}(), ...).unwrap()`. Consider using `{}{}!` instead",
macro_name,
dest_name,
prefix,
macro_name.replace("write", "print")
)
);

// We need to remove the last trailing newline from the string because the
// underlying `fmt::write` function doesn't know whether `println!` or `print!` was
// used.
if let Some(mut write_output) = write_output_string(write_args) {
if write_output.ends_with('\n') {
write_output.pop();
}

if let Some(macro_name) = calling_macro {
span_lint_and_sugg(
cx,
EXPLICIT_WRITE,
expr.span,
&format!(
"use of `{}!({}(), ...).unwrap()`",
macro_name,
dest_name
),
"try this",
format!("{}{}!(\"{}\")", prefix, macro_name.replace("write", "print"), write_output.escape_default()),
Applicability::MachineApplicable
);
} else {
span_lint_and_sugg(
cx,
EXPLICIT_WRITE,
expr.span,
&format!("use of `{}().write_fmt(...).unwrap()`", dest_name),
"try this",
format!("{}print!(\"{}\")", prefix, write_output.escape_default()),
Applicability::MachineApplicable
);
}
} else {
span_lint(
cx,
EXPLICIT_WRITE,
expr.span,
&format!(
"use of `{}().write_fmt(...).unwrap()`. Consider using `{}print!` instead",
dest_name,
prefix,
)
);
// We don't have a proper suggestion
if let Some(macro_name) = calling_macro {
span_lint(
cx,
EXPLICIT_WRITE,
expr.span,
&format!(
"use of `{}!({}(), ...).unwrap()`. Consider using `{}{}!` instead",
macro_name,
dest_name,
prefix,
macro_name.replace("write", "print")
)
);
} else {
span_lint(
cx,
EXPLICIT_WRITE,
expr.span,
&format!("use of `{}().write_fmt(...).unwrap()`. Consider using `{}print!` instead", dest_name, prefix),
);
}
}

}
}
}
}

// Extract the output string from the given `write_args`.
fn write_output_string(write_args: &HirVec<Expr>) -> Option<String> {
if_chain! {
// Obtain the string that should be printed
if write_args.len() > 1;
if let ExprKind::Call(_, ref output_args) = write_args[1].node;
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;
if let ExprKind::Lit(ref lit) = string_exprs[0].node;
if let LitKind::Str(ref write_output, _) = lit.node;
then {
return Some(write_output.to_string())
}
}
None
}
3 changes: 3 additions & 0 deletions clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#![feature(slice_patterns)]
#![feature(stmt_expr_attributes)]
#![feature(range_contains)]
#![feature(str_escape)]
#![allow(clippy::missing_docs_in_private_items)]
#![recursion_limit = "256"]
#![warn(rust_2018_idioms, trivial_casts, trivial_numeric_casts)]
Expand Down Expand Up @@ -765,6 +766,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
types::UNIT_ARG,
types::UNIT_CMP,
types::UNNECESSARY_CAST,
types::VEC_BOX,
unicode::ZERO_WIDTH_SPACE,
unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME,
unused_io_amount::UNUSED_IO_AMOUNT,
Expand Down Expand Up @@ -930,6 +932,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
types::TYPE_COMPLEXITY,
types::UNIT_ARG,
types::UNNECESSARY_CAST,
types::VEC_BOX,
unused_label::UNUSED_LABEL,
zero_div_zero::ZERO_DIVIDED_BY_ZERO,
]);
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/methods/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2350,8 +2350,8 @@ const PATTERN_METHODS: [(&str, usize); 17] = [
("rmatches", 1),
("match_indices", 1),
("rmatch_indices", 1),
("trim_left_matches", 1),
("trim_right_matches", 1),
("trim_start_matches", 1),
("trim_end_matches", 1),
];

#[derive(Clone, Copy, PartialEq, Debug)]
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/misc_early.rs
Original file line number Diff line number Diff line change
Expand Up @@ -446,13 +446,13 @@ impl MiscEarly {
db.span_suggestion_with_applicability(
lit.span,
"if you mean to use a decimal constant, remove the `0` to remove confusion",
src.trim_left_matches(|c| c == '_' || c == '0').to_string(),
src.trim_start_matches(|c| c == '_' || c == '0').to_string(),
Applicability::MaybeIncorrect,
);
db.span_suggestion_with_applicability(
lit.span,
"if you mean to use an octal constant, use `0o`",
format!("0o{}", src.trim_left_matches(|c| c == '_' || c == '0')),
format!("0o{}", src.trim_start_matches(|c| c == '_' || c == '0')),
Applicability::MaybeIncorrect,
);
});
Expand Down
8 changes: 5 additions & 3 deletions clippy_lints/src/new_without_default.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use crate::rustc_errors::Applicability;
use crate::syntax::source_map::Span;
use crate::utils::paths;
use crate::utils::sugg::DiagnosticBuilderExt;
use crate::utils::{get_trait_def_id, implements_trait, return_ty, same_tys, span_lint_and_then};
use crate::utils::{get_trait_def_id, implements_trait, return_ty, same_tys, span_lint_node_and_then};
use if_chain::if_chain;

/// **What it does:** Checks for types with a `fn new() -> Self` method and no
Expand Down Expand Up @@ -165,9 +165,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NewWithoutDefault {
}

if let Some(sp) = can_derive_default(self_ty, cx, default_trait_id) {
span_lint_and_then(
span_lint_node_and_then(
cx,
NEW_WITHOUT_DEFAULT_DERIVE,
id,
impl_item.span,
&format!(
"you should consider deriving a `Default` implementation for `{}`",
Expand All @@ -183,9 +184,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NewWithoutDefault {
);
});
} else {
span_lint_and_then(
span_lint_node_and_then(
cx,
NEW_WITHOUT_DEFAULT,
id,
impl_item.span,
&format!(
"you should consider adding a `Default` implementation for `{}`",
Expand Down
13 changes: 8 additions & 5 deletions clippy_lints/src/partialeq_ne_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
use crate::rustc::hir::*;
use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
use crate::rustc::{declare_tool_lint, lint_array};
use crate::utils::{is_automatically_derived, span_lint};
use crate::utils::{is_automatically_derived, span_lint_node};
use if_chain::if_chain;

/// **What it does:** Checks for manual re-implementations of `PartialEq::ne`.
Expand Down Expand Up @@ -56,10 +56,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
then {
for impl_item in impl_items {
if impl_item.ident.name == "ne" {
span_lint(cx,
PARTIALEQ_NE_IMPL,
impl_item.span,
"re-implementing `PartialEq::ne` is unnecessary")
span_lint_node(
cx,
PARTIALEQ_NE_IMPL,
impl_item.id.node_id,
impl_item.span,
"re-implementing `PartialEq::ne` is unnecessary",
);
}
}
}
Expand Down
44 changes: 37 additions & 7 deletions clippy_lints/src/question_mark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use if_chain::if_chain;

use crate::rustc_errors::Applicability;
use crate::utils::paths::*;
use crate::utils::{match_def_path, match_type, span_lint_and_then};
use crate::utils::{match_def_path, match_type, span_lint_and_then, SpanlessEq};

/// **What it does:** Checks for expressions that could be replaced by the question mark operator
///
Expand Down Expand Up @@ -64,14 +64,40 @@ impl Pass {
/// If it matches, it will suggest to use the question mark operator instead
fn check_is_none_and_early_return_none(cx: &LateContext<'_, '_>, expr: &Expr) {
if_chain! {
if let ExprKind::If(ref if_expr, ref body, _) = expr.node;
if let ExprKind::MethodCall(ref segment, _, ref args) = if_expr.node;
if let ExprKind::If(if_expr, body, else_) = &expr.node;
if let ExprKind::MethodCall(segment, _, args) = &if_expr.node;
if segment.ident.name == "is_none";
if Self::expression_returns_none(cx, body);
if let Some(subject) = args.get(0);
if Self::is_option(cx, subject);

then {
if let Some(else_) = else_ {
if_chain! {
if let ExprKind::Block(block, None) = &else_.node;
if block.stmts.len() == 0;
if let Some(block_expr) = &block.expr;
if SpanlessEq::new(cx).ignore_fn().eq_expr(subject, block_expr);
then {
span_lint_and_then(
cx,
QUESTION_MARK,
expr.span,
"this block may be rewritten with the `?` operator",
|db| {
db.span_suggestion_with_applicability(
expr.span,
"replace_it_with",
format!("Some({}?)", Sugg::hir(cx, subject, "..")),
Applicability::MaybeIncorrect, // snippet
);
}
)
}
}
return;
}

span_lint_and_then(
cx,
QUESTION_MARK,
Expand All @@ -84,7 +110,7 @@ impl Pass {
expr.span,
"replace_it_with",
format!("{}?;", receiver_str),
Applicability::MachineApplicable, // snippet
Applicability::MaybeIncorrect, // snippet
);
}
)
Expand Down Expand Up @@ -133,9 +159,13 @@ impl Pass {
}
}

// Check if the block has an implicit return expression
if let Some(ref ret_expr) = block.expr {
return Some(ret_expr.clone());
// Check for `return` without a semicolon.
if_chain! {
if block.stmts.len() == 0;
if let Some(ExprKind::Ret(Some(ret_expr))) = block.expr.as_ref().map(|e| &e.node);
then {
return Some(ret_expr.clone());
}
}

None
Expand Down
5 changes: 4 additions & 1 deletion clippy_lints/src/redundant_field_names.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,10 @@ impl EarlyLintPass for RedundantFieldNames {
continue;
}
if let ExprKind::Path(None, path) = &field.expr.node {
if path.segments.len() == 1 && path.segments[0].ident == field.ident {
if path.segments.len() == 1
&& path.segments[0].ident == field.ident
&& path.segments[0].args.is_none()
{
span_lint_and_sugg(
cx,
REDUNDANT_FIELD_NAMES,
Expand Down
Loading

0 comments on commit 9d15aaf

Please sign in to comment.