diff --git a/src/tools/clippy/CHANGELOG.md b/src/tools/clippy/CHANGELOG.md index c488c142e46fc..d847e4c749481 100644 --- a/src/tools/clippy/CHANGELOG.md +++ b/src/tools/clippy/CHANGELOG.md @@ -3583,7 +3583,7 @@ Released 2018-09-13 [`almost_complete_letter_range`]: https://rust-lang.github.io/rust-clippy/master/index.html#almost_complete_letter_range [`almost_swapped`]: https://rust-lang.github.io/rust-clippy/master/index.html#almost_swapped [`approx_constant`]: https://rust-lang.github.io/rust-clippy/master/index.html#approx_constant -[`arithmetic`]: https://rust-lang.github.io/rust-clippy/master/index.html#arithmetic +[`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_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 @@ -3603,6 +3603,7 @@ Released 2018-09-13 [`blocks_in_if_conditions`]: https://rust-lang.github.io/rust-clippy/master/index.html#blocks_in_if_conditions [`bool_assert_comparison`]: https://rust-lang.github.io/rust-clippy/master/index.html#bool_assert_comparison [`bool_comparison`]: https://rust-lang.github.io/rust-clippy/master/index.html#bool_comparison +[`bool_to_int_with_if`]: https://rust-lang.github.io/rust-clippy/master/index.html#bool_to_int_with_if [`borrow_as_ptr`]: https://rust-lang.github.io/rust-clippy/master/index.html#borrow_as_ptr [`borrow_deref_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#borrow_deref_ref [`borrow_interior_mutable_const`]: https://rust-lang.github.io/rust-clippy/master/index.html#borrow_interior_mutable_const diff --git a/src/tools/clippy/clippy_dev/src/update_lints.rs b/src/tools/clippy/clippy_dev/src/update_lints.rs index c503142e5e455..b95061bf81a25 100644 --- a/src/tools/clippy/clippy_dev/src/update_lints.rs +++ b/src/tools/clippy/clippy_dev/src/update_lints.rs @@ -3,7 +3,7 @@ use aho_corasick::AhoCorasickBuilder; use indoc::writedoc; use itertools::Itertools; use rustc_lexer::{tokenize, unescape, LiteralKind, TokenKind}; -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeSet, HashMap, HashSet}; use std::ffi::OsStr; use std::fmt::Write; use std::fs::{self, OpenOptions}; @@ -124,6 +124,8 @@ fn generate_lint_files( let content = gen_lint_group_list("all", all_group_lints); process_file("clippy_lints/src/lib.register_all.rs", update_mode, &content); + update_docs(update_mode, &usable_lints); + 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( @@ -140,6 +142,62 @@ fn generate_lint_files( process_file("tests/ui/rename.rs", update_mode, &content); } +fn update_docs(update_mode: UpdateMode, usable_lints: &[Lint]) { + replace_region_in_file(update_mode, Path::new("src/docs.rs"), "docs! {\n", "\n}\n", |res| { + for name in usable_lints.iter().map(|lint| lint.name.clone()).sorted() { + writeln!(res, r#" "{name}","#).unwrap(); + } + }); + + if update_mode == UpdateMode::Check { + let mut extra = BTreeSet::new(); + let mut lint_names = usable_lints + .iter() + .map(|lint| lint.name.clone()) + .collect::>(); + for file in std::fs::read_dir("src/docs").unwrap() { + let filename = file.unwrap().file_name().into_string().unwrap(); + if let Some(name) = filename.strip_suffix(".txt") { + if !lint_names.remove(name) { + extra.insert(name.to_string()); + } + } + } + + let failed = print_lint_names("extra lint docs:", &extra) | print_lint_names("missing lint docs:", &lint_names); + + if failed { + exit_with_failure(); + } + } else { + if std::fs::remove_dir_all("src/docs").is_err() { + eprintln!("could not remove src/docs directory"); + } + if std::fs::create_dir("src/docs").is_err() { + eprintln!("could not recreate src/docs directory"); + } + } + for lint in usable_lints { + process_file( + Path::new("src/docs").join(lint.name.clone() + ".txt"), + update_mode, + &lint.documentation, + ); + } +} + +fn print_lint_names(header: &str, lints: &BTreeSet) -> bool { + if lints.is_empty() { + return false; + } + println!("{}", header); + for lint in lints.iter().sorted() { + println!(" {}", lint); + } + println!(); + true +} + pub fn print_lints() { let (lint_list, _, _) = gather_all(); let usable_lints = Lint::usable_lints(&lint_list); @@ -589,17 +647,26 @@ struct Lint { desc: String, module: String, declaration_range: Range, + documentation: String, } impl Lint { #[must_use] - fn new(name: &str, group: &str, desc: &str, module: &str, declaration_range: Range) -> Self { + fn new( + name: &str, + group: &str, + desc: &str, + module: &str, + declaration_range: Range, + documentation: String, + ) -> Self { Self { name: name.to_lowercase(), group: group.into(), desc: remove_line_splices(desc), module: module.into(), declaration_range, + documentation, } } @@ -852,27 +919,35 @@ fn parse_contents(contents: &str, module: &str, lints: &mut Vec) { }| token_kind == &TokenKind::Ident && *content == "declare_clippy_lint", ) { let start = range.start; - - let mut iter = iter - .by_ref() - .filter(|t| !matches!(t.token_kind, TokenKind::Whitespace | TokenKind::LineComment { .. })); + let mut docs = String::with_capacity(128); + let mut iter = iter.by_ref().filter(|t| !matches!(t.token_kind, TokenKind::Whitespace)); // matches `!{` match_tokens!(iter, Bang OpenBrace); - match iter.next() { - // #[clippy::version = "version"] pub - Some(LintDeclSearchResult { - token_kind: TokenKind::Pound, - .. - }) => { - match_tokens!(iter, OpenBracket Ident Colon Colon Ident Eq Literal{..} CloseBracket Ident); - }, - // pub - Some(LintDeclSearchResult { - token_kind: TokenKind::Ident, - .. - }) => (), - _ => continue, + let mut in_code = false; + while let Some(t) = iter.next() { + match t.token_kind { + TokenKind::LineComment { .. } => { + if let Some(line) = t.content.strip_prefix("/// ").or_else(|| t.content.strip_prefix("///")) { + if line.starts_with("```") { + docs += "```\n"; + in_code = !in_code; + } else if !(in_code && line.starts_with("# ")) { + docs += line; + docs.push('\n'); + } + } + }, + TokenKind::Pound => { + match_tokens!(iter, OpenBracket Ident Colon Colon Ident Eq Literal{..} CloseBracket Ident); + break; + }, + TokenKind::Ident => { + break; + }, + _ => {}, + } } + docs.pop(); // remove final newline let (name, group, desc) = match_tokens!( iter, @@ -890,7 +965,7 @@ fn parse_contents(contents: &str, module: &str, lints: &mut Vec) { .. }) = iter.next() { - lints.push(Lint::new(name, group, desc, module, start..range.end)); + lints.push(Lint::new(name, group, desc, module, start..range.end, docs)); } } } @@ -977,7 +1052,11 @@ fn remove_line_splices(s: &str) -> String { .and_then(|s| s.strip_suffix('"')) .unwrap_or_else(|| panic!("expected quoted string, found `{}`", s)); let mut res = String::with_capacity(s.len()); - unescape::unescape_literal(s, unescape::Mode::Str, &mut |range, _| res.push_str(&s[range])); + unescape::unescape_literal(s, unescape::Mode::Str, &mut |range, ch| { + if ch.is_ok() { + res.push_str(&s[range]); + } + }); res } @@ -1116,6 +1195,7 @@ mod tests { "\"really long text\"", "module_name", Range::default(), + String::new(), ), Lint::new( "doc_markdown", @@ -1123,6 +1203,7 @@ mod tests { "\"single line\"", "module_name", Range::default(), + String::new(), ), ]; assert_eq!(expected, result); @@ -1162,6 +1243,7 @@ mod tests { "\"abc\"", "module_name", Range::default(), + String::new(), ), Lint::new( "should_assert_eq2", @@ -1169,6 +1251,7 @@ mod tests { "\"abc\"", "module_name", Range::default(), + String::new(), ), Lint::new( "should_assert_eq2", @@ -1176,6 +1259,7 @@ mod tests { "\"abc\"", "module_name", Range::default(), + String::new(), ), ]; let expected = vec![Lint::new( @@ -1184,6 +1268,7 @@ mod tests { "\"abc\"", "module_name", Range::default(), + String::new(), )]; assert_eq!(expected, Lint::usable_lints(&lints)); } @@ -1191,22 +1276,51 @@ mod tests { #[test] fn test_by_lint_group() { let lints = vec![ - Lint::new("should_assert_eq", "group1", "\"abc\"", "module_name", Range::default()), + Lint::new( + "should_assert_eq", + "group1", + "\"abc\"", + "module_name", + Range::default(), + String::new(), + ), Lint::new( "should_assert_eq2", "group2", "\"abc\"", "module_name", Range::default(), + String::new(), + ), + Lint::new( + "incorrect_match", + "group1", + "\"abc\"", + "module_name", + Range::default(), + String::new(), ), - Lint::new("incorrect_match", "group1", "\"abc\"", "module_name", Range::default()), ]; let mut expected: HashMap> = HashMap::new(); expected.insert( "group1".to_string(), vec![ - Lint::new("should_assert_eq", "group1", "\"abc\"", "module_name", Range::default()), - Lint::new("incorrect_match", "group1", "\"abc\"", "module_name", Range::default()), + Lint::new( + "should_assert_eq", + "group1", + "\"abc\"", + "module_name", + Range::default(), + String::new(), + ), + Lint::new( + "incorrect_match", + "group1", + "\"abc\"", + "module_name", + Range::default(), + String::new(), + ), ], ); expected.insert( @@ -1217,6 +1331,7 @@ mod tests { "\"abc\"", "module_name", Range::default(), + String::new(), )], ); assert_eq!(expected, Lint::by_lint_group(lints.into_iter())); @@ -1255,9 +1370,30 @@ mod tests { #[test] fn test_gen_lint_group_list() { let lints = vec![ - Lint::new("abc", "group1", "\"abc\"", "module_name", Range::default()), - Lint::new("should_assert_eq", "group1", "\"abc\"", "module_name", Range::default()), - Lint::new("internal", "internal_style", "\"abc\"", "module_name", Range::default()), + Lint::new( + "abc", + "group1", + "\"abc\"", + "module_name", + Range::default(), + String::new(), + ), + Lint::new( + "should_assert_eq", + "group1", + "\"abc\"", + "module_name", + Range::default(), + String::new(), + ), + Lint::new( + "internal", + "internal_style", + "\"abc\"", + "module_name", + Range::default(), + String::new(), + ), ]; let expected = GENERATED_FILE_COMMENT.to_string() + &[ diff --git a/src/tools/clippy/clippy_lints/src/async_yields_async.rs b/src/tools/clippy/clippy_lints/src/async_yields_async.rs index 27c2896e1e5ce..9464694a3b55a 100644 --- a/src/tools/clippy/clippy_lints/src/async_yields_async.rs +++ b/src/tools/clippy/clippy_lints/src/async_yields_async.rs @@ -54,7 +54,7 @@ impl<'tcx> LateLintPass<'tcx> for AsyncYieldsAsync { hir_id: body.value.hir_id, }; let typeck_results = cx.tcx.typeck_body(body_id); - let expr_ty = typeck_results.expr_ty(&body.value); + let expr_ty = typeck_results.expr_ty(body.value); if implements_trait(cx, expr_ty, future_trait_def_id, &[]) { let return_expr_span = match &body.value.kind { diff --git a/src/tools/clippy/clippy_lints/src/attrs.rs b/src/tools/clippy/clippy_lints/src/attrs.rs index 4bcbeacf9feb5..732dc2b433091 100644 --- a/src/tools/clippy/clippy_lints/src/attrs.rs +++ b/src/tools/clippy/clippy_lints/src/attrs.rs @@ -475,7 +475,7 @@ fn check_lint_reason(cx: &LateContext<'_>, name: Symbol, items: &[NestedMetaItem fn is_relevant_item(cx: &LateContext<'_>, item: &Item<'_>) -> bool { if let ItemKind::Fn(_, _, eid) = item.kind { - is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value) + is_relevant_expr(cx, cx.tcx.typeck_body(eid), cx.tcx.hir().body(eid).value) } else { true } @@ -483,7 +483,7 @@ fn is_relevant_item(cx: &LateContext<'_>, item: &Item<'_>) -> bool { fn is_relevant_impl(cx: &LateContext<'_>, item: &ImplItem<'_>) -> bool { match item.kind { - ImplItemKind::Fn(_, eid) => is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value), + ImplItemKind::Fn(_, eid) => is_relevant_expr(cx, cx.tcx.typeck_body(eid), cx.tcx.hir().body(eid).value), _ => false, } } @@ -492,7 +492,7 @@ fn is_relevant_trait(cx: &LateContext<'_>, item: &TraitItem<'_>) -> bool { match item.kind { TraitItemKind::Fn(_, TraitFn::Required(_)) => true, TraitItemKind::Fn(_, TraitFn::Provided(eid)) => { - is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value) + is_relevant_expr(cx, cx.tcx.typeck_body(eid), cx.tcx.hir().body(eid).value) }, _ => false, } diff --git a/src/tools/clippy/clippy_lints/src/bool_to_int_with_if.rs b/src/tools/clippy/clippy_lints/src/bool_to_int_with_if.rs new file mode 100644 index 0000000000000..a4b8cbb0d82aa --- /dev/null +++ b/src/tools/clippy/clippy_lints/src/bool_to_int_with_if.rs @@ -0,0 +1,125 @@ +use rustc_ast::{ExprPrecedence, LitKind}; +use rustc_hir::{Block, ExprKind}; +use rustc_lint::{LateContext, LateLintPass}; +use rustc_session::{declare_lint_pass, declare_tool_lint}; + +use clippy_utils::{diagnostics::span_lint_and_then, is_else_clause, source::snippet_block_with_applicability}; +use rustc_errors::Applicability; + +declare_clippy_lint! { + /// ### What it does + /// Instead of using an if statement to convert a bool to an int, + /// this lint suggests using a `from()` function or an `as` coercion. + /// + /// ### Why is this bad? + /// Coercion or `from()` is idiomatic way to convert bool to a number. + /// Both methods are guaranteed to return 1 for true, and 0 for false. + /// + /// See https://doc.rust-lang.org/std/primitive.bool.html#impl-From%3Cbool%3E + /// + /// ### Example + /// ```rust + /// # let condition = false; + /// if condition { + /// 1_i64 + /// } else { + /// 0 + /// }; + /// ``` + /// Use instead: + /// ```rust + /// # let condition = false; + /// i64::from(condition); + /// ``` + /// or + /// ```rust + /// # let condition = false; + /// condition as i64; + /// ``` + #[clippy::version = "1.65.0"] + pub BOOL_TO_INT_WITH_IF, + style, + "using if to convert bool to int" +} +declare_lint_pass!(BoolToIntWithIf => [BOOL_TO_INT_WITH_IF]); + +impl<'tcx> LateLintPass<'tcx> for BoolToIntWithIf { + fn check_expr(&mut self, ctx: &LateContext<'tcx>, expr: &'tcx rustc_hir::Expr<'tcx>) { + if !expr.span.from_expansion() { + check_if_else(ctx, expr); + } + } +} + +fn check_if_else<'tcx>(ctx: &LateContext<'tcx>, expr: &'tcx rustc_hir::Expr<'tcx>) { + if let ExprKind::If(check, then, Some(else_)) = expr.kind + && let Some(then_lit) = int_literal(then) + && let Some(else_lit) = int_literal(else_) + && check_int_literal_equals_val(then_lit, 1) + && check_int_literal_equals_val(else_lit, 0) + { + let mut applicability = Applicability::MachineApplicable; + let snippet = snippet_block_with_applicability(ctx, check.span, "..", None, &mut applicability); + let snippet_with_braces = { + let need_parens = should_have_parentheses(check); + let (left_paren, right_paren) = if need_parens {("(", ")")} else {("", "")}; + format!("{left_paren}{snippet}{right_paren}") + }; + + let ty = ctx.typeck_results().expr_ty(then_lit); // then and else must be of same type + + let suggestion = { + let wrap_in_curly = is_else_clause(ctx.tcx, expr); + let (left_curly, right_curly) = if wrap_in_curly {("{", "}")} else {("", "")}; + format!( + "{left_curly}{ty}::from({snippet}){right_curly}" + ) + }; // when used in else clause if statement should be wrapped in curly braces + + span_lint_and_then(ctx, + BOOL_TO_INT_WITH_IF, + expr.span, + "boolean to int conversion using if", + |diag| { + diag.span_suggestion( + expr.span, + "replace with from", + suggestion, + applicability, + ); + diag.note(format!("`{snippet_with_braces} as {ty}` or `{snippet_with_braces}.into()` can also be valid options")); + }); + }; +} + +// If block contains only a int literal expression, return literal expression +fn int_literal<'tcx>(expr: &'tcx rustc_hir::Expr<'tcx>) -> Option<&'tcx rustc_hir::Expr<'tcx>> { + if let ExprKind::Block(block, _) = expr.kind + && let Block { + stmts: [], // Shouldn't lint if statements with side effects + expr: Some(expr), + .. + } = block + && let ExprKind::Lit(lit) = &expr.kind + && let LitKind::Int(_, _) = lit.node + { + Some(expr) + } else { + None + } +} + +fn check_int_literal_equals_val<'tcx>(expr: &'tcx rustc_hir::Expr<'tcx>, expected_value: u128) -> bool { + if let ExprKind::Lit(lit) = &expr.kind + && let LitKind::Int(val, _) = lit.node + && val == expected_value + { + true + } else { + false + } +} + +fn should_have_parentheses<'tcx>(check: &'tcx rustc_hir::Expr<'tcx>) -> bool { + check.precedence().order() < ExprPrecedence::Cast.order() +} diff --git a/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs b/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs index 64c5de5104206..be02f328e989a 100644 --- a/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs +++ b/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs @@ -69,7 +69,10 @@ struct NumericFallbackVisitor<'a, 'tcx> { impl<'a, 'tcx> NumericFallbackVisitor<'a, 'tcx> { fn new(cx: &'a LateContext<'tcx>) -> Self { - Self { ty_bounds: vec![TyBound::Nothing], cx } + Self { + ty_bounds: vec![TyBound::Nothing], + cx, + } } /// Check whether a passed literal has potential to cause fallback or not. @@ -126,21 +129,19 @@ impl<'a, 'tcx> Visitor<'tcx> for NumericFallbackVisitor<'a, 'tcx> { } return; } - } + }, ExprKind::MethodCall(_, receiver, args, _) => { if let Some(def_id) = self.cx.typeck_results().type_dependent_def_id(expr.hir_id) { let fn_sig = self.cx.tcx.fn_sig(def_id).skip_binder(); - for (expr, bound) in - iter::zip(std::iter::once(*receiver).chain(args.iter()), fn_sig.inputs()) - { + for (expr, bound) in iter::zip(std::iter::once(*receiver).chain(args.iter()), fn_sig.inputs()) { self.ty_bounds.push(TyBound::Ty(*bound)); self.visit_expr(expr); self.ty_bounds.pop(); } return; } - } + }, ExprKind::Struct(_, fields, base) => { let ty = self.cx.typeck_results().expr_ty(expr); @@ -175,15 +176,15 @@ impl<'a, 'tcx> Visitor<'tcx> for NumericFallbackVisitor<'a, 'tcx> { return; } } - } + }, ExprKind::Lit(lit) => { let ty = self.cx.typeck_results().expr_ty(expr); self.check_lit(lit, ty, expr.hir_id); return; - } + }, - _ => {} + _ => {}, } walk_expr(self, expr); @@ -197,7 +198,7 @@ impl<'a, 'tcx> Visitor<'tcx> for NumericFallbackVisitor<'a, 'tcx> { } else { self.ty_bounds.push(TyBound::Nothing); } - } + }, _ => self.ty_bounds.push(TyBound::Nothing), } diff --git a/src/tools/clippy/clippy_lints/src/dereference.rs b/src/tools/clippy/clippy_lints/src/dereference.rs index d1ab7fb67962e..88e28018e5d00 100644 --- a/src/tools/clippy/clippy_lints/src/dereference.rs +++ b/src/tools/clippy/clippy_lints/src/dereference.rs @@ -830,25 +830,22 @@ fn walk_parents<'tcx>( ) { return Some(Position::MethodReceiverRefImpl) - } else { - return Some(Position::MethodReceiver) } + return Some(Position::MethodReceiver); } - args.iter() - .position(|arg| arg.hir_id == child_id) - .map(|i| { - let ty = cx.tcx.fn_sig(id).skip_binder().inputs()[i + 1]; - if let ty::Param(param_ty) = ty.kind() { - needless_borrow_impl_arg_position(cx, parent, i + 1, *param_ty, e, precedence, msrv) - } else { - ty_auto_deref_stability( - cx, - cx.tcx.erase_late_bound_regions(cx.tcx.fn_sig(id).input(i + 1)), - precedence, - ) - .position_for_arg() - } - }) + args.iter().position(|arg| arg.hir_id == child_id).map(|i| { + let ty = cx.tcx.fn_sig(id).skip_binder().inputs()[i + 1]; + if let ty::Param(param_ty) = ty.kind() { + needless_borrow_impl_arg_position(cx, parent, i + 1, *param_ty, e, precedence, msrv) + } else { + ty_auto_deref_stability( + cx, + cx.tcx.erase_late_bound_regions(cx.tcx.fn_sig(id).input(i + 1)), + precedence, + ) + .position_for_arg() + } + }) }, ExprKind::Field(child, name) if child.hir_id == e.hir_id => Some(Position::FieldAccess(name.name)), ExprKind::Unary(UnOp::Deref, child) if child.hir_id == e.hir_id => Some(Position::Deref), diff --git a/src/tools/clippy/clippy_lints/src/derivable_impls.rs b/src/tools/clippy/clippy_lints/src/derivable_impls.rs index 4d7f4076d7b51..ef9eeecc6a934 100644 --- a/src/tools/clippy/clippy_lints/src/derivable_impls.rs +++ b/src/tools/clippy/clippy_lints/src/derivable_impls.rs @@ -40,7 +40,7 @@ declare_clippy_lint! { /// /// ### Known problems /// Derive macros [sometimes use incorrect bounds](https://github.com/rust-lang/rust/issues/26925) - /// in generic types and the user defined `impl` maybe is more generalized or + /// in generic types and the user defined `impl` may be more generalized or /// specialized than what derive will produce. This lint can't detect the manual `impl` /// has exactly equal bounds, and therefore this lint is disabled for types with /// generic parameters. diff --git a/src/tools/clippy/clippy_lints/src/doc.rs b/src/tools/clippy/clippy_lints/src/doc.rs index 512872cedc1ea..eb158d850fa72 100644 --- a/src/tools/clippy/clippy_lints/src/doc.rs +++ b/src/tools/clippy/clippy_lints/src/doc.rs @@ -236,7 +236,7 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { typeck_results: cx.tcx.typeck(item.def_id), panic_span: None, }; - fpu.visit_expr(&body.value); + fpu.visit_expr(body.value); lint_for_missing_headers(cx, item.def_id, item.span, sig, headers, Some(body_id), fpu.panic_span); } }, @@ -286,7 +286,7 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { typeck_results: cx.tcx.typeck(item.def_id), panic_span: None, }; - fpu.visit_expr(&body.value); + fpu.visit_expr(body.value); lint_for_missing_headers(cx, item.def_id, item.span, sig, headers, Some(body_id), fpu.panic_span); } } @@ -348,7 +348,7 @@ fn lint_for_missing_headers<'tcx>( if let Some(future) = cx.tcx.lang_items().future_trait(); let typeck = cx.tcx.typeck_body(body_id); let body = cx.tcx.hir().body(body_id); - let ret_ty = typeck.expr_ty(&body.value); + let ret_ty = typeck.expr_ty(body.value); if implements_trait(cx, ret_ty, future, &[]); if let ty::Opaque(_, subs) = ret_ty.kind(); if let Some(gen) = subs.types().next(); @@ -828,7 +828,7 @@ impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> { // check for `unwrap` if let Some(arglists) = method_chain_args(expr, &["unwrap"]) { - let receiver_ty = self.typeck_results.expr_ty(&arglists[0].0).peel_refs(); + let receiver_ty = self.typeck_results.expr_ty(arglists[0].0).peel_refs(); if is_type_diagnostic_item(self.cx, receiver_ty, sym::Option) || is_type_diagnostic_item(self.cx, receiver_ty, sym::Result) { diff --git a/src/tools/clippy/clippy_lints/src/eta_reduction.rs b/src/tools/clippy/clippy_lints/src/eta_reduction.rs index 1342a4697b991..53bc617a4f5b7 100644 --- a/src/tools/clippy/clippy_lints/src/eta_reduction.rs +++ b/src/tools/clippy/clippy_lints/src/eta_reduction.rs @@ -83,7 +83,7 @@ impl<'tcx> LateLintPass<'tcx> for EtaReduction { }; if body.value.span.from_expansion() { if body.params.is_empty() { - if let Some(VecArgs::Vec(&[])) = higher::VecArgs::hir(cx, &body.value) { + if let Some(VecArgs::Vec(&[])) = higher::VecArgs::hir(cx, body.value) { // replace `|| vec![]` with `Vec::new` span_lint_and_sugg( cx, @@ -103,7 +103,7 @@ impl<'tcx> LateLintPass<'tcx> for EtaReduction { let closure_ty = cx.typeck_results().expr_ty(expr); if_chain!( - if !is_adjusted(cx, &body.value); + if !is_adjusted(cx, body.value); if let ExprKind::Call(callee, args) = body.value.kind; if let ExprKind::Path(_) = callee.kind; if check_inputs(cx, body.params, None, args); @@ -145,7 +145,7 @@ impl<'tcx> LateLintPass<'tcx> for EtaReduction { ); if_chain!( - if !is_adjusted(cx, &body.value); + if !is_adjusted(cx, body.value); if let ExprKind::MethodCall(path, receiver, args, _) = body.value.kind; if check_inputs(cx, body.params, Some(receiver), args); let method_def_id = cx.typeck_results().type_dependent_def_id(body.value.hir_id).unwrap(); @@ -206,8 +206,7 @@ fn check_inputs( _ => false, } }; - std::iter::zip(params, receiver.into_iter().chain(call_args.iter())) - .all(|(param, arg)| check_inputs(param, arg)) + std::iter::zip(params, receiver.into_iter().chain(call_args.iter())).all(|(param, arg)| check_inputs(param, arg)) } fn check_sig<'tcx>(cx: &LateContext<'tcx>, closure_ty: Ty<'tcx>, call_ty: Ty<'tcx>) -> bool { diff --git a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs index 790eea63f58c4..1f69f34a229df 100644 --- a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs +++ b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs @@ -84,7 +84,7 @@ fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_items: &[h // check for `unwrap` if let Some(arglists) = method_chain_args(expr, &["unwrap"]) { - let receiver_ty = self.typeck_results.expr_ty(&arglists[0].0).peel_refs(); + let receiver_ty = self.typeck_results.expr_ty(arglists[0].0).peel_refs(); if is_type_diagnostic_item(self.lcx, receiver_ty, sym::Option) || is_type_diagnostic_item(self.lcx, receiver_ty, sym::Result) { @@ -110,7 +110,7 @@ fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_items: &[h typeck_results: cx.tcx.typeck(impl_item.id.def_id), result: Vec::new(), }; - fpu.visit_expr(&body.value); + fpu.visit_expr(body.value); // if we've found one, lint if !fpu.result.is_empty() { diff --git a/src/tools/clippy/clippy_lints/src/floating_point_arithmetic.rs b/src/tools/clippy/clippy_lints/src/floating_point_arithmetic.rs index 728db41d60043..ba53a9678801c 100644 --- a/src/tools/clippy/clippy_lints/src/floating_point_arithmetic.rs +++ b/src/tools/clippy/clippy_lints/src/floating_point_arithmetic.rs @@ -238,23 +238,23 @@ fn get_integer_from_float_constant(value: &Constant) -> Option { fn check_powf(cx: &LateContext<'_>, expr: &Expr<'_>, receiver: &Expr<'_>, args: &[Expr<'_>]) { // Check receiver if let Some((value, _)) = constant(cx, cx.typeck_results(), receiver) { - let method = if F32(f32_consts::E) == value || F64(f64_consts::E) == value { - "exp" + if let Some(method) = if F32(f32_consts::E) == value || F64(f64_consts::E) == value { + Some("exp") } else if F32(2.0) == value || F64(2.0) == value { - "exp2" + Some("exp2") } else { - return; - }; - - span_lint_and_sugg( - cx, - SUBOPTIMAL_FLOPS, - expr.span, - "exponent for bases 2 and e can be computed more accurately", - "consider using", - format!("{}.{}()", prepare_receiver_sugg(cx, &args[0]), method), - Applicability::MachineApplicable, - ); + None + } { + span_lint_and_sugg( + cx, + SUBOPTIMAL_FLOPS, + expr.span, + "exponent for bases 2 and e can be computed more accurately", + "consider using", + format!("{}.{}()", prepare_receiver_sugg(cx, &args[0]), method), + Applicability::MachineApplicable, + ); + } } // Check argument diff --git a/src/tools/clippy/clippy_lints/src/functions/must_use.rs b/src/tools/clippy/clippy_lints/src/functions/must_use.rs index a17b23f5edc86..00a4937763eb5 100644 --- a/src/tools/clippy/clippy_lints/src/functions/must_use.rs +++ b/src/tools/clippy/clippy_lints/src/functions/must_use.rs @@ -272,6 +272,6 @@ fn mutates_static<'tcx>(cx: &LateContext<'tcx>, body: &'tcx hir::Body<'_>) -> bo cx, mutates_static: false, }; - intravisit::walk_expr(&mut v, &body.value); + intravisit::walk_expr(&mut v, body.value); v.mutates_static } diff --git a/src/tools/clippy/clippy_lints/src/functions/result.rs b/src/tools/clippy/clippy_lints/src/functions/result.rs index af520a493eda1..9591405cb06f7 100644 --- a/src/tools/clippy/clippy_lints/src/functions/result.rs +++ b/src/tools/clippy/clippy_lints/src/functions/result.rs @@ -4,7 +4,6 @@ use rustc_lint::{LateContext, LintContext}; use rustc_middle::lint::in_external_macro; use rustc_middle::ty::{self, Ty}; use rustc_span::{sym, Span}; -use rustc_typeck::hir_ty_to_ty; use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_then}; use clippy_utils::trait_ref_of_method; @@ -17,11 +16,12 @@ use super::{RESULT_LARGE_ERR, RESULT_UNIT_ERR}; fn result_err_ty<'tcx>( cx: &LateContext<'tcx>, decl: &hir::FnDecl<'tcx>, + id: hir::def_id::LocalDefId, item_span: Span, ) -> Option<(&'tcx hir::Ty<'tcx>, Ty<'tcx>)> { if !in_external_macro(cx.sess(), item_span) && let hir::FnRetTy::Return(hir_ty) = decl.output - && let ty = hir_ty_to_ty(cx.tcx, hir_ty) + && let ty = cx.tcx.erase_late_bound_regions(cx.tcx.fn_sig(id).output()) && is_type_diagnostic_item(cx, ty, sym::Result) && let ty::Adt(_, substs) = ty.kind() { @@ -34,7 +34,7 @@ fn result_err_ty<'tcx>( pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::Item<'tcx>, large_err_threshold: u64) { if let hir::ItemKind::Fn(ref sig, _generics, _) = item.kind - && let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.span) + && let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.def_id, item.span) { if cx.access_levels.is_exported(item.def_id) { let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); @@ -47,7 +47,7 @@ pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::Item<'tcx>, l pub(super) fn check_impl_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::ImplItem<'tcx>, large_err_threshold: u64) { // Don't lint if method is a trait's implementation, we can't do anything about those if let hir::ImplItemKind::Fn(ref sig, _) = item.kind - && let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.span) + && let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.def_id, item.span) && trait_ref_of_method(cx, item.def_id).is_none() { if cx.access_levels.is_exported(item.def_id) { @@ -61,7 +61,7 @@ pub(super) fn check_impl_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::ImplItem pub(super) fn check_trait_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::TraitItem<'tcx>, large_err_threshold: u64) { if let hir::TraitItemKind::Fn(ref sig, _) = item.kind { let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); - if let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.span) { + if let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.def_id, item.span) { if cx.access_levels.is_exported(item.def_id) { check_result_unit_err(cx, err_ty, fn_header_span); } diff --git a/src/tools/clippy/clippy_lints/src/implicit_return.rs b/src/tools/clippy/clippy_lints/src/implicit_return.rs index a6610ade37e56..feec8ec2e23f8 100644 --- a/src/tools/clippy/clippy_lints/src/implicit_return.rs +++ b/src/tools/clippy/clippy_lints/src/implicit_return.rs @@ -232,7 +232,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitReturn { return; } - let res_ty = cx.typeck_results().expr_ty(&body.value); + let res_ty = cx.typeck_results().expr_ty(body.value); if res_ty.is_unit() || res_ty.is_never() { return; } @@ -243,7 +243,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitReturn { None => return, } } else { - &body.value + body.value }; lint_implicit_returns(cx, expr, expr.span.ctxt(), None); } diff --git a/src/tools/clippy/clippy_lints/src/infinite_iter.rs b/src/tools/clippy/clippy_lints/src/infinite_iter.rs index d55a8e1ead17d..8c2c96fa105af 100644 --- a/src/tools/clippy/clippy_lints/src/infinite_iter.rs +++ b/src/tools/clippy/clippy_lints/src/infinite_iter.rs @@ -59,7 +59,7 @@ impl<'tcx> LateLintPass<'tcx> for InfiniteIter { MaybeInfinite => (MAYBE_INFINITE_ITER, "possible infinite iteration detected"), Finite => { return; - } + }, }; span_lint(cx, lint, expr.span, msg); } @@ -161,7 +161,7 @@ fn is_infinite(cx: &LateContext<'_>, expr: &Expr<'_>) -> Finiteness { if method.ident.name == sym!(flat_map) && args.len() == 1 { if let ExprKind::Closure(&Closure { body, .. }) = args[0].kind { let body = cx.tcx.hir().body(body); - return is_infinite(cx, &body.value); + return is_infinite(cx, body.value); } } Finite @@ -230,8 +230,10 @@ fn complete_infinite_iter(cx: &LateContext<'_>, expr: &Expr<'_>) -> Finiteness { } } if method.ident.name == sym!(last) && args.is_empty() { - let not_double_ended = - cx.tcx.get_diagnostic_item(sym::DoubleEndedIterator).map_or(false, |id| { + let not_double_ended = cx + .tcx + .get_diagnostic_item(sym::DoubleEndedIterator) + .map_or(false, |id| { !implements_trait(cx, cx.typeck_results().expr_ty(receiver), id, &[]) }); if not_double_ended { diff --git a/src/tools/clippy/clippy_lints/src/large_enum_variant.rs b/src/tools/clippy/clippy_lints/src/large_enum_variant.rs index c58df126d6244..eb13d0869c037 100644 --- a/src/tools/clippy/clippy_lints/src/large_enum_variant.rs +++ b/src/tools/clippy/clippy_lints/src/large_enum_variant.rs @@ -1,13 +1,12 @@ //! lint when there is a large size difference between variants on an enum use clippy_utils::source::snippet_with_applicability; -use clippy_utils::{diagnostics::span_lint_and_then, ty::is_copy}; +use clippy_utils::{diagnostics::span_lint_and_then, ty::approx_ty_size, ty::is_copy}; use rustc_errors::Applicability; use rustc_hir::{Item, ItemKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::lint::in_external_macro; -use rustc_middle::ty::layout::LayoutOf; -use rustc_middle::ty::{Adt, Ty}; +use rustc_middle::ty::{Adt, AdtDef, GenericArg, List, Ty}; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::source_map::Span; @@ -17,7 +16,7 @@ declare_clippy_lint! { /// `enum`s. /// /// ### Why is this bad? - /// Enum size is bounded by the largest variant. Having a + /// Enum size is bounded by the largest variant. Having one /// large variant can penalize the memory layout of that enum. /// /// ### Known problems @@ -33,8 +32,9 @@ declare_clippy_lint! { /// use case it may be possible to store the large data in an auxiliary /// structure (e.g. Arena or ECS). /// - /// The lint will ignore generic types if the layout depends on the - /// generics, even if the size difference will be large anyway. + /// The lint will ignore the impact of generic types to the type layout by + /// assuming every type parameter is zero-sized. Depending on your use case, + /// this may lead to a false positive. /// /// ### Example /// ```rust @@ -83,6 +83,38 @@ struct VariantInfo { fields_size: Vec, } +fn variants_size<'tcx>( + cx: &LateContext<'tcx>, + adt: AdtDef<'tcx>, + subst: &'tcx List>, +) -> Vec { + let mut variants_size = adt + .variants() + .iter() + .enumerate() + .map(|(i, variant)| { + let mut fields_size = variant + .fields + .iter() + .enumerate() + .map(|(i, f)| FieldInfo { + ind: i, + size: approx_ty_size(cx, f.ty(cx.tcx, subst)), + }) + .collect::>(); + fields_size.sort_by(|a, b| (a.size.cmp(&b.size))); + + VariantInfo { + ind: i, + size: fields_size.iter().map(|info| info.size).sum(), + fields_size, + } + }) + .collect::>(); + variants_size.sort_by(|a, b| (b.size.cmp(&a.size))); + variants_size +} + impl_lint_pass!(LargeEnumVariant => [LARGE_ENUM_VARIANT]); impl<'tcx> LateLintPass<'tcx> for LargeEnumVariant { @@ -92,36 +124,14 @@ impl<'tcx> LateLintPass<'tcx> for LargeEnumVariant { } if let ItemKind::Enum(ref def, _) = item.kind { let ty = cx.tcx.type_of(item.def_id); - let adt = ty.ty_adt_def().expect("already checked whether this is an enum"); + let (adt, subst) = match ty.kind() { + Adt(adt, subst) => (adt, subst), + _ => panic!("already checked whether this is an enum"), + }; if adt.variants().len() <= 1 { return; } - let mut variants_size: Vec = Vec::new(); - for (i, variant) in adt.variants().iter().enumerate() { - let mut fields_size = Vec::new(); - for (i, f) in variant.fields.iter().enumerate() { - let ty = cx.tcx.type_of(f.did); - // don't lint variants which have a field of generic type. - match cx.layout_of(ty) { - Ok(l) => { - let fsize = l.size.bytes(); - fields_size.push(FieldInfo { ind: i, size: fsize }); - }, - Err(_) => { - return; - }, - } - } - let size: u64 = fields_size.iter().map(|info| info.size).sum(); - - variants_size.push(VariantInfo { - ind: i, - size, - fields_size, - }); - } - - variants_size.sort_by(|a, b| (b.size.cmp(&a.size))); + let variants_size = variants_size(cx, *adt, subst); let mut difference = variants_size[0].size - variants_size[1].size; if difference > self.maximum_size_difference_allowed { @@ -129,20 +139,30 @@ impl<'tcx> LateLintPass<'tcx> for LargeEnumVariant { span_lint_and_then( cx, LARGE_ENUM_VARIANT, - def.variants[variants_size[0].ind].span, + item.span, "large size difference between variants", |diag| { + diag.span_label( + item.span, + format!("the entire enum is at least {} bytes", approx_ty_size(cx, ty)), + ); diag.span_label( def.variants[variants_size[0].ind].span, - &format!("this variant is {} bytes", variants_size[0].size), + format!("the largest variant contains at least {} bytes", variants_size[0].size), ); - diag.span_note( + diag.span_label( def.variants[variants_size[1].ind].span, - &format!("and the second-largest variant is {} bytes:", variants_size[1].size), + &if variants_size[1].fields_size.is_empty() { + "the second-largest variant carries no data at all".to_owned() + } else { + format!( + "the second-largest variant contains at least {} bytes", + variants_size[1].size + ) + }, ); let fields = def.variants[variants_size[0].ind].data.fields(); - variants_size[0].fields_size.sort_by(|a, b| (a.size.cmp(&b.size))); let mut applicability = Applicability::MaybeIncorrect; if is_copy(cx, ty) || maybe_copy(cx, ty) { diag.span_note( diff --git a/src/tools/clippy/clippy_lints/src/len_zero.rs b/src/tools/clippy/clippy_lints/src/len_zero.rs index 3cbdaff407b04..7ae8ef830faea 100644 --- a/src/tools/clippy/clippy_lints/src/len_zero.rs +++ b/src/tools/clippy/clippy_lints/src/len_zero.rs @@ -370,7 +370,8 @@ fn check_for_is_empty<'tcx>( } fn check_cmp(cx: &LateContext<'_>, span: Span, method: &Expr<'_>, lit: &Expr<'_>, op: &str, compare_to: u32) { - if let (&ExprKind::MethodCall(method_path, receiver, args, _), &ExprKind::Lit(ref lit)) = (&method.kind, &lit.kind) { + if let (&ExprKind::MethodCall(method_path, receiver, args, _), &ExprKind::Lit(ref lit)) = (&method.kind, &lit.kind) + { // check if we are in an is_empty() method if let Some(name) = get_item_name(cx, method) { if name.as_str() == "is_empty" { @@ -378,12 +379,23 @@ fn check_cmp(cx: &LateContext<'_>, span: Span, method: &Expr<'_>, lit: &Expr<'_> } } - check_len(cx, span, method_path.ident.name, receiver, args, &lit.node, op, compare_to); + check_len( + cx, + span, + method_path.ident.name, + receiver, + args, + &lit.node, + op, + compare_to, + ); } else { check_empty_expr(cx, span, method, lit, op); } } +// FIXME(flip1995): Figure out how to reduce the number of arguments +#[allow(clippy::too_many_arguments)] fn check_len( cx: &LateContext<'_>, span: Span, diff --git a/src/tools/clippy/clippy_lints/src/lib.register_all.rs b/src/tools/clippy/clippy_lints/src/lib.register_all.rs index 134cbbf7b5c66..1f85382347aa1 100644 --- a/src/tools/clippy/clippy_lints/src/lib.register_all.rs +++ b/src/tools/clippy/clippy_lints/src/lib.register_all.rs @@ -17,6 +17,7 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![ LintId::of(await_holding_invalid::AWAIT_HOLDING_REFCELL_REF), LintId::of(blocks_in_if_conditions::BLOCKS_IN_IF_CONDITIONS), LintId::of(bool_assert_comparison::BOOL_ASSERT_COMPARISON), + LintId::of(bool_to_int_with_if::BOOL_TO_INT_WITH_IF), LintId::of(booleans::NONMINIMAL_BOOL), LintId::of(booleans::OVERLY_COMPLEX_BOOL_EXPR), LintId::of(borrow_deref_ref::BORROW_DEREF_REF), diff --git a/src/tools/clippy/clippy_lints/src/lib.register_lints.rs b/src/tools/clippy/clippy_lints/src/lib.register_lints.rs index fd20e016578a1..962e67220069a 100644 --- a/src/tools/clippy/clippy_lints/src/lib.register_lints.rs +++ b/src/tools/clippy/clippy_lints/src/lib.register_lints.rs @@ -56,6 +56,7 @@ store.register_lints(&[ await_holding_invalid::AWAIT_HOLDING_REFCELL_REF, blocks_in_if_conditions::BLOCKS_IN_IF_CONDITIONS, bool_assert_comparison::BOOL_ASSERT_COMPARISON, + bool_to_int_with_if::BOOL_TO_INT_WITH_IF, booleans::NONMINIMAL_BOOL, booleans::OVERLY_COMPLEX_BOOL_EXPR, borrow_deref_ref::BORROW_DEREF_REF, @@ -436,7 +437,7 @@ store.register_lints(&[ octal_escapes::OCTAL_ESCAPES, only_used_in_recursion::ONLY_USED_IN_RECURSION, operators::ABSURD_EXTREME_COMPARISONS, - operators::ARITHMETIC, + operators::ARITHMETIC_SIDE_EFFECTS, operators::ASSIGN_OP_PATTERN, operators::BAD_BIT_MASK, operators::CMP_NAN, diff --git a/src/tools/clippy/clippy_lints/src/lib.register_restriction.rs b/src/tools/clippy/clippy_lints/src/lib.register_restriction.rs index dd1e1e1a8e33d..6eb9b3d3b9b7a 100644 --- a/src/tools/clippy/clippy_lints/src/lib.register_restriction.rs +++ b/src/tools/clippy/clippy_lints/src/lib.register_restriction.rs @@ -50,7 +50,7 @@ store.register_group(true, "clippy::restriction", Some("clippy_restriction"), ve LintId::of(mixed_read_write_in_expression::MIXED_READ_WRITE_IN_EXPRESSION), LintId::of(module_style::MOD_MODULE_FILES), LintId::of(module_style::SELF_NAMED_MODULE_FILES), - LintId::of(operators::ARITHMETIC), + LintId::of(operators::ARITHMETIC_SIDE_EFFECTS), LintId::of(operators::FLOAT_ARITHMETIC), LintId::of(operators::FLOAT_CMP_CONST), LintId::of(operators::INTEGER_ARITHMETIC), diff --git a/src/tools/clippy/clippy_lints/src/lib.register_style.rs b/src/tools/clippy/clippy_lints/src/lib.register_style.rs index b5cb078e7a3cc..05d2ec2e9e1e6 100644 --- a/src/tools/clippy/clippy_lints/src/lib.register_style.rs +++ b/src/tools/clippy/clippy_lints/src/lib.register_style.rs @@ -6,6 +6,7 @@ store.register_group(true, "clippy::style", Some("clippy_style"), vec![ LintId::of(assertions_on_constants::ASSERTIONS_ON_CONSTANTS), LintId::of(blocks_in_if_conditions::BLOCKS_IN_IF_CONDITIONS), LintId::of(bool_assert_comparison::BOOL_ASSERT_COMPARISON), + LintId::of(bool_to_int_with_if::BOOL_TO_INT_WITH_IF), LintId::of(casts::FN_TO_NUMERIC_CAST), LintId::of(casts::FN_TO_NUMERIC_CAST_WITH_TRUNCATION), LintId::of(collapsible_if::COLLAPSIBLE_ELSE_IF), diff --git a/src/tools/clippy/clippy_lints/src/lib.rs b/src/tools/clippy/clippy_lints/src/lib.rs index c70aa79ac8dcf..e984254bf2919 100644 --- a/src/tools/clippy/clippy_lints/src/lib.rs +++ b/src/tools/clippy/clippy_lints/src/lib.rs @@ -179,6 +179,7 @@ mod attrs; mod await_holding_invalid; mod blocks_in_if_conditions; mod bool_assert_comparison; +mod bool_to_int_with_if; mod booleans; mod borrow_deref_ref; mod cargo; @@ -523,7 +524,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: #[cfg(feature = "internal")] { if std::env::var("ENABLE_METADATA_COLLECTION").eq(&Ok("1".to_string())) { - store.register_late_pass(|_| Box::new(utils::internal_lints::metadata_collector::MetadataCollector::new())); + store.register_late_pass(|| Box::new(utils::internal_lints::metadata_collector::MetadataCollector::new())); return; } } @@ -544,8 +545,12 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: store.register_late_pass(|_| Box::new(utils::internal_lints::MsrvAttrImpl)); } - let arithmetic_allowed = conf.arithmetic_allowed.clone(); - store.register_late_pass(move |_| Box::new(operators::arithmetic::Arithmetic::new(arithmetic_allowed.clone()))); + let arithmetic_side_effects_allowed = conf.arithmetic_side_effects_allowed.clone(); + store.register_late_pass(move |_| { + Box::new(operators::arithmetic_side_effects::ArithmeticSideEffects::new( + arithmetic_side_effects_allowed.clone(), + )) + }); store.register_late_pass(|_| Box::new(utils::dump_hir::DumpHir)); store.register_late_pass(|_| Box::new(utils::author::Author)); let await_holding_invalid_types = conf.await_holding_invalid_types.clone(); @@ -901,6 +906,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: store.register_late_pass(|_| Box::new(manual_string_new::ManualStringNew)); store.register_late_pass(|_| Box::new(unused_peekable::UnusedPeekable)); store.register_early_pass(|| Box::new(multi_assignments::MultiAssignments)); + store.register_late_pass(|_| Box::new(bool_to_int_with_if::BoolToIntWithIf)); // add lints here, do not remove this comment, it's used in `new_lint` } diff --git a/src/tools/clippy/clippy_lints/src/lifetimes.rs b/src/tools/clippy/clippy_lints/src/lifetimes.rs index 5995675bd969c..f2b6e0b7ef9ba 100644 --- a/src/tools/clippy/clippy_lints/src/lifetimes.rs +++ b/src/tools/clippy/clippy_lints/src/lifetimes.rs @@ -276,7 +276,7 @@ fn could_use_elision<'tcx>( let mut checker = BodyLifetimeChecker { lifetimes_used_in_body: false, }; - checker.visit_expr(&body.value); + checker.visit_expr(body.value); if checker.lifetimes_used_in_body { return false; } diff --git a/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs b/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs index ffcf83e4605e2..8ab640051b635 100644 --- a/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs @@ -373,7 +373,7 @@ impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> { }, ExprKind::Closure(&Closure { body, .. }) => { let body = self.cx.tcx.hir().body(body); - self.visit_expr(&body.value); + self.visit_expr(body.value); }, _ => walk_expr(self, expr), } diff --git a/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs b/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs index 2c54033f85975..deb21894f36a9 100644 --- a/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs +++ b/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs @@ -356,7 +356,7 @@ fn needs_mutable_borrow(cx: &LateContext<'_>, iter_expr: &IterExpr, loop_expr: & after_loop: false, used_iter: false, }; - v.visit_expr(&cx.tcx.hir().body(cx.enclosing_body.unwrap()).value); + v.visit_expr(cx.tcx.hir().body(cx.enclosing_body.unwrap()).value); v.used_iter } } diff --git a/src/tools/clippy/clippy_lints/src/matches/match_wild_err_arm.rs b/src/tools/clippy/clippy_lints/src/matches/match_wild_err_arm.rs index bc16f17b6196e..a3aa2e4b389af 100644 --- a/src/tools/clippy/clippy_lints/src/matches/match_wild_err_arm.rs +++ b/src/tools/clippy/clippy_lints/src/matches/match_wild_err_arm.rs @@ -40,7 +40,7 @@ pub(crate) fn check<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm<' arm.pat.span, &format!("`Err({})` matches all errors", ident_bind_name), None, - "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable", + "match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable", ); } } diff --git a/src/tools/clippy/clippy_lints/src/matches/single_match.rs b/src/tools/clippy/clippy_lints/src/matches/single_match.rs index 1bf1c4d107895..56bcdc01fe4d6 100644 --- a/src/tools/clippy/clippy_lints/src/matches/single_match.rs +++ b/src/tools/clippy/clippy_lints/src/matches/single_match.rs @@ -203,12 +203,8 @@ fn form_exhaustive_matches<'a>(cx: &LateContext<'a>, ty: Ty<'a>, left: &Pat<'_>, let left_pos = left_pos.as_opt_usize(); let right_pos = right_pos.as_opt_usize(); let len = max( - left_in.len() + { - if left_pos.is_some() { 1 } else { 0 } - }, - right_in.len() + { - if right_pos.is_some() { 1 } else { 0 } - }, + left_in.len() + usize::from(left_pos.is_some()), + right_in.len() + usize::from(right_pos.is_some()), ); let mut left_pos = left_pos.unwrap_or(usize::MAX); let mut right_pos = right_pos.unwrap_or(usize::MAX); diff --git a/src/tools/clippy/clippy_lints/src/methods/bind_instead_of_map.rs b/src/tools/clippy/clippy_lints/src/methods/bind_instead_of_map.rs index 2f117e4dcc374..22f5635a5bccb 100644 --- a/src/tools/clippy/clippy_lints/src/methods/bind_instead_of_map.rs +++ b/src/tools/clippy/clippy_lints/src/methods/bind_instead_of_map.rs @@ -152,7 +152,7 @@ pub(crate) trait BindInsteadOfMap { match arg.kind { hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, .. }) => { let closure_body = cx.tcx.hir().body(body); - let closure_expr = peel_blocks(&closure_body.value); + let closure_expr = peel_blocks(closure_body.value); if Self::lint_closure_autofixable(cx, expr, recv, closure_expr, fn_decl_span) { true diff --git a/src/tools/clippy/clippy_lints/src/methods/chars_cmp.rs b/src/tools/clippy/clippy_lints/src/methods/chars_cmp.rs index 51aec21527a71..b2bc1ad5c9ed0 100644 --- a/src/tools/clippy/clippy_lints/src/methods/chars_cmp.rs +++ b/src/tools/clippy/clippy_lints/src/methods/chars_cmp.rs @@ -23,7 +23,7 @@ pub(super) fn check( if Some(id) == cx.tcx.lang_items().option_some_variant(); then { let mut applicability = Applicability::MachineApplicable; - let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0].0).peel_refs(); + let self_ty = cx.typeck_results().expr_ty_adjusted(args[0].0).peel_refs(); if *self_ty.kind() != ty::Str { return false; diff --git a/src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs b/src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs index f5bead387d7bd..7ab6b84c20749 100644 --- a/src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs +++ b/src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs @@ -21,7 +21,11 @@ pub(super) fn check( receiver: &Expr<'_>, args: &[Expr<'_>], ) { - let arg = if method_name == sym::clone && args.is_empty() { receiver } else { return }; + let arg = if method_name == sym::clone && args.is_empty() { + receiver + } else { + return; + }; if cx .typeck_results() .type_dependent_def_id(expr.hir_id) diff --git a/src/tools/clippy/clippy_lints/src/methods/filter_map.rs b/src/tools/clippy/clippy_lints/src/methods/filter_map.rs index 9dc839afc6256..9719b2f1c5125 100644 --- a/src/tools/clippy/clippy_lints/src/methods/filter_map.rs +++ b/src/tools/clippy/clippy_lints/src/methods/filter_map.rs @@ -25,7 +25,7 @@ fn is_method<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, method_name: Sy }, hir::ExprKind::Closure(&hir::Closure { body, .. }) => { let body = cx.tcx.hir().body(body); - let closure_expr = peel_blocks(&body.value); + let closure_expr = peel_blocks(body.value); let arg_id = body.params[0].pat.hir_id; match closure_expr.kind { hir::ExprKind::MethodCall(hir::PathSegment { ident, .. }, receiver, ..) => { diff --git a/src/tools/clippy/clippy_lints/src/methods/map_clone.rs b/src/tools/clippy/clippy_lints/src/methods/map_clone.rs index e8442091fd306..8261ef5e1ce34 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_clone.rs +++ b/src/tools/clippy/clippy_lints/src/methods/map_clone.rs @@ -30,7 +30,7 @@ pub(super) fn check<'tcx>( if let hir::ExprKind::Closure(&hir::Closure{ body, .. }) = arg.kind; then { let closure_body = cx.tcx.hir().body(body); - let closure_expr = peel_blocks(&closure_body.value); + let closure_expr = peel_blocks(closure_body.value); match closure_body.params[0].pat.kind { hir::PatKind::Ref(inner, hir::Mutability::Not) => if let hir::PatKind::Binding( hir::BindingAnnotation::NONE, .., name, None diff --git a/src/tools/clippy/clippy_lints/src/methods/mod.rs b/src/tools/clippy/clippy_lints/src/methods/mod.rs index 48a9d6e7c329e..41942b20ea163 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mod.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mod.rs @@ -825,8 +825,9 @@ declare_clippy_lint! { declare_clippy_lint! { /// ### What it does /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`, - /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or - /// `unwrap_or_default` instead. + /// `.or_insert(foo(..))` etc., and suggests to use `.or_else(|| foo(..))`, + /// `.unwrap_or_else(|| foo(..))`, `.unwrap_or_default()` or `.or_default()` + /// etc. instead. /// /// ### Why is this bad? /// The function will always be called and potentially diff --git a/src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs b/src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs index bd8458a222e29..b9593b3687d9c 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::ty::is_type_diagnostic_item; +use clippy_utils::{expr_custom_deref_adjustment, ty::is_type_diagnostic_item}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir::{Expr, Mutability}; @@ -11,6 +11,7 @@ use super::MUT_MUTEX_LOCK; pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'tcx>, recv: &'tcx Expr<'tcx>, name_span: Span) { if_chain! { + if matches!(expr_custom_deref_adjustment(cx, recv), None | Some(Mutability::Mut)); if let ty::Ref(_, _, Mutability::Mut) = cx.typeck_results().expr_ty(recv).kind(); if let Some(method_id) = cx.typeck_results().type_dependent_def_id(ex.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(method_id); diff --git a/src/tools/clippy/clippy_lints/src/methods/open_options.rs b/src/tools/clippy/clippy_lints/src/methods/open_options.rs index 903fa306f935a..597af853dc681 100644 --- a/src/tools/clippy/clippy_lints/src/methods/open_options.rs +++ b/src/tools/clippy/clippy_lints/src/methods/open_options.rs @@ -40,7 +40,7 @@ fn get_open_options(cx: &LateContext<'_>, argument: &Expr<'_>, options: &mut Vec let obj_ty = cx.typeck_results().expr_ty(receiver).peel_refs(); // Only proceed if this is a call on some object of type std::fs::OpenOptions - if match_type(cx, obj_ty, &paths::OPEN_OPTIONS) && arguments.len() >= 1 { + if match_type(cx, obj_ty, &paths::OPEN_OPTIONS) && !arguments.is_empty() { let argument_option = match arguments[0].kind { ExprKind::Lit(ref span) => { if let Spanned { diff --git a/src/tools/clippy/clippy_lints/src/methods/option_as_ref_deref.rs b/src/tools/clippy/clippy_lints/src/methods/option_as_ref_deref.rs index 81c67b4ca6a59..c409268de769d 100644 --- a/src/tools/clippy/clippy_lints/src/methods/option_as_ref_deref.rs +++ b/src/tools/clippy/clippy_lints/src/methods/option_as_ref_deref.rs @@ -53,7 +53,7 @@ pub(super) fn check<'tcx>( }), hir::ExprKind::Closure(&hir::Closure { body, .. }) => { let closure_body = cx.tcx.hir().body(body); - let closure_expr = peel_blocks(&closure_body.value); + let closure_expr = peel_blocks(closure_body.value); match &closure_expr.kind { hir::ExprKind::MethodCall(_, receiver, [], _) => { diff --git a/src/tools/clippy/clippy_lints/src/methods/option_map_or_none.rs b/src/tools/clippy/clippy_lints/src/methods/option_map_or_none.rs index 5a39b82b027d1..6657cdccd010c 100644 --- a/src/tools/clippy/clippy_lints/src/methods/option_map_or_none.rs +++ b/src/tools/clippy/clippy_lints/src/methods/option_map_or_none.rs @@ -74,7 +74,7 @@ pub(super) fn check<'tcx>( if let hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, .. }) = map_arg.kind; let arg_snippet = snippet(cx, fn_decl_span, ".."); let body = cx.tcx.hir().body(body); - if let Some((func, [arg_char])) = reduce_unit_expression(&body.value); + if let Some((func, [arg_char])) = reduce_unit_expression(body.value); if let Some(id) = path_def_id(cx, func).map(|ctor_id| cx.tcx.parent(ctor_id)); if Some(id) == cx.tcx.lang_items().option_some_variant(); then { diff --git a/src/tools/clippy/clippy_lints/src/methods/or_fun_call.rs b/src/tools/clippy/clippy_lints/src/methods/or_fun_call.rs index 76876d8662936..b43b9258c471d 100644 --- a/src/tools/clippy/clippy_lints/src/methods/or_fun_call.rs +++ b/src/tools/clippy/clippy_lints/src/methods/or_fun_call.rs @@ -23,7 +23,8 @@ pub(super) fn check<'tcx>( receiver: &'tcx hir::Expr<'_>, args: &'tcx [hir::Expr<'_>], ) { - /// Checks for `unwrap_or(T::new())` or `unwrap_or(T::default())`. + /// Checks for `unwrap_or(T::new())`, `unwrap_or(T::default())`, + /// `or_insert(T::new())` or `or_insert(T::default())`. #[allow(clippy::too_many_arguments)] fn check_unwrap_or_default( cx: &LateContext<'_>, @@ -43,7 +44,11 @@ pub(super) fn check<'tcx>( if_chain! { if !or_has_args; - if name == "unwrap_or"; + if let Some(sugg) = match name { + "unwrap_or" => Some("unwrap_or_default"), + "or_insert" => Some("or_default"), + _ => None, + }; if let hir::ExprKind::Path(ref qpath) = fun.kind; if let Some(default_trait_id) = cx.tcx.get_diagnostic_item(sym::Default); let path = last_path_segment(qpath).ident.name; @@ -59,7 +64,7 @@ pub(super) fn check<'tcx>( method_span.with_hi(span.hi()), &format!("use of `{}` followed by a call to `{}`", name, path), "try this", - "unwrap_or_default()".to_string(), + format!("{}()", sugg), Applicability::MachineApplicable, ); @@ -83,7 +88,7 @@ pub(super) fn check<'tcx>( fun_span: Option, ) { // (path, fn_has_argument, methods, suffix) - static KNOW_TYPES: [(&[&str], bool, &[&str], &str); 4] = [ + const KNOW_TYPES: [(&[&str], bool, &[&str], &str); 4] = [ (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"), (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"), (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"), diff --git a/src/tools/clippy/clippy_lints/src/methods/suspicious_map.rs b/src/tools/clippy/clippy_lints/src/methods/suspicious_map.rs index 9c3375bf35e7d..851cdf544550f 100644 --- a/src/tools/clippy/clippy_lints/src/methods/suspicious_map.rs +++ b/src/tools/clippy/clippy_lints/src/methods/suspicious_map.rs @@ -15,9 +15,9 @@ pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, count_recv: &hi if let Some(def_id) = cx.tcx.hir().opt_local_def_id(closure.hir_id); if let Some(body_id) = cx.tcx.hir().maybe_body_owned_by(def_id); let closure_body = cx.tcx.hir().body(body_id); - if !cx.typeck_results().expr_ty(&closure_body.value).is_unit(); + if !cx.typeck_results().expr_ty(closure_body.value).is_unit(); then { - if let Some(map_mutated_vars) = mutated_variables(&closure_body.value, cx) { + if let Some(map_mutated_vars) = mutated_variables(closure_body.value, cx) { // A variable is used mutably inside of the closure. Suppress the lint. if !map_mutated_vars.is_empty() { return; diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs index bafa6fc584d48..4e8c201f470ba 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs @@ -21,14 +21,13 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr< if let hir::ExprKind::Closure(&hir::Closure { body, .. }) = arg.kind { let body = cx.tcx.hir().body(body); let arg_id = body.params[0].pat.hir_id; - let mutates_arg = - mutated_variables(&body.value, cx).map_or(true, |used_mutably| used_mutably.contains(&arg_id)); - let (clone_or_copy_needed, _) = clone_or_copy_needed(cx, body.params[0].pat, &body.value); + let mutates_arg = mutated_variables(body.value, cx).map_or(true, |used_mutably| used_mutably.contains(&arg_id)); + let (clone_or_copy_needed, _) = clone_or_copy_needed(cx, body.params[0].pat, body.value); - let (mut found_mapping, mut found_filtering) = check_expression(cx, arg_id, &body.value); + let (mut found_mapping, mut found_filtering) = check_expression(cx, arg_id, body.value); let mut return_visitor = ReturnVisitor::new(cx, arg_id); - return_visitor.visit_expr(&body.value); + return_visitor.visit_expr(body.value); found_mapping |= return_visitor.found_mapping; found_filtering |= return_visitor.found_filtering; @@ -36,7 +35,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr< let sugg = if !found_filtering { if name == "filter_map" { "map" } else { "map(..).next()" } } else if !found_mapping && !mutates_arg && (!clone_or_copy_needed || is_copy(cx, in_ty)) { - match cx.typeck_results().expr_ty(&body.value).kind() { + match cx.typeck_results().expr_ty(body.value).kind() { ty::Adt(adt, subst) if cx.tcx.is_diagnostic_item(sym::Option, adt.did()) && in_ty == subst.type_at(0) => { diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_fold.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_fold.rs index c3531d4d0511e..c17ef6809f912 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_fold.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_fold.rs @@ -31,7 +31,7 @@ pub(super) fn check( // Extract the body of the closure passed to fold if let hir::ExprKind::Closure(&hir::Closure { body, .. }) = acc.kind; let closure_body = cx.tcx.hir().body(body); - let closure_expr = peel_blocks(&closure_body.value); + let closure_expr = peel_blocks(closure_body.value); // Check if the closure body is of the form `acc some_expr(x)` if let hir::ExprKind::Binary(ref bin_op, left_expr, right_expr) = closure_expr.kind; diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_sort_by.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_sort_by.rs index 6f25acca1de61..ed5a75b0f3ce5 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_sort_by.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_sort_by.rs @@ -131,7 +131,7 @@ fn detect_lint(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, arg: &Exp ] = &closure_body.params; if let ExprKind::MethodCall(method_path, left_expr, [right_expr], _) = closure_body.value.kind; if method_path.ident.name == sym::cmp; - if is_trait_method(cx, &closure_body.value, sym::Ord); + if is_trait_method(cx, closure_body.value, sym::Ord); then { let (closure_body, closure_arg, reverse) = if mirrored_exprs( left_expr, diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs index 85da97a39f9a1..763bfafecef14 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs @@ -1,21 +1,25 @@ use super::implicit_clone::is_clone_like; use super::unnecessary_iter_cloned::{self, is_into_iter}; +use crate::rustc_middle::ty::Subst; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::source::snippet_opt; -use clippy_utils::ty::{ - get_associated_type, get_iterator_item_ty, implements_trait, is_copy, is_type_diagnostic_item, peel_mid_ty_refs, -}; -use clippy_utils::{fn_def_id, get_parent_expr, is_diag_item_method, is_diag_trait_item}; +use clippy_utils::ty::{get_associated_type, get_iterator_item_ty, implements_trait, is_copy, peel_mid_ty_refs}; +use clippy_utils::visitors::find_all_ret_expressions; +use clippy_utils::{fn_def_id, get_parent_expr, is_diag_item_method, is_diag_trait_item, return_ty}; use clippy_utils::{meets_msrv, msrvs}; use rustc_errors::Applicability; -use rustc_hir::{def_id::DefId, BorrowKind, Expr, ExprKind}; +use rustc_hir::{def_id::DefId, BorrowKind, Expr, ExprKind, ItemKind, Node}; +use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::LateContext; use rustc_middle::mir::Mutability; use rustc_middle::ty::adjustment::{Adjust, Adjustment, OverloadedDeref}; use rustc_middle::ty::subst::{GenericArg, GenericArgKind, SubstsRef}; -use rustc_middle::ty::{self, PredicateKind, ProjectionPredicate, TraitPredicate, Ty}; +use rustc_middle::ty::EarlyBinder; +use rustc_middle::ty::{self, ParamTy, PredicateKind, ProjectionPredicate, TraitPredicate, Ty}; use rustc_semver::RustcVersion; use rustc_span::{sym, Symbol}; +use rustc_trait_selection::traits::{query::evaluate_obligation::InferCtxtExt as _, Obligation, ObligationCause}; +use rustc_typeck::check::{FnCtxt, Inherited}; use std::cmp::max; use super::UNNECESSARY_TO_OWNED; @@ -34,7 +38,7 @@ pub fn check<'tcx>( then { if is_cloned_or_copied(cx, method_name, method_def_id) { unnecessary_iter_cloned::check(cx, expr, method_name, receiver); - } else if is_to_owned_like(cx, method_name, method_def_id) { + } else if is_to_owned_like(cx, expr, method_name, method_def_id) { // At this point, we know the call is of a `to_owned`-like function. The functions // `check_addr_of_expr` and `check_call_arg` determine whether the call is unnecessary // based on its context, that is, whether it is a referent in an `AddrOf` expression, an @@ -246,17 +250,12 @@ fn check_other_call_arg<'tcx>( ) -> bool { if_chain! { if let Some((maybe_call, maybe_arg)) = skip_addr_of_ancestors(cx, expr); - if let Some((callee_def_id, call_substs, call_receiver, call_args)) = get_callee_substs_and_args(cx, maybe_call); + if let Some((callee_def_id, _, recv, call_args)) = get_callee_substs_and_args(cx, maybe_call); let fn_sig = cx.tcx.fn_sig(callee_def_id).skip_binder(); - let index = if let Some(call_receiver) = call_receiver { - std::iter::once(call_receiver).chain(call_args.iter()).position(|arg| arg.hir_id == maybe_arg.hir_id) - } else { - call_args.iter().position(|arg| arg.hir_id == maybe_arg.hir_id) - }; - if let Some(i) = index; + if let Some(i) = recv.into_iter().chain(call_args).position(|arg| arg.hir_id == maybe_arg.hir_id); if let Some(input) = fn_sig.inputs().get(i); let (input, n_refs) = peel_mid_ty_refs(*input); - if let (trait_predicates, projection_predicates) = get_input_traits_and_projections(cx, callee_def_id, input); + if let (trait_predicates, _) = get_input_traits_and_projections(cx, callee_def_id, input); if let Some(sized_def_id) = cx.tcx.lang_items().sized_trait(); if let [trait_predicate] = trait_predicates .iter() @@ -264,52 +263,13 @@ fn check_other_call_arg<'tcx>( .collect::>()[..]; if let Some(deref_trait_id) = cx.tcx.get_diagnostic_item(sym::Deref); if let Some(as_ref_trait_id) = cx.tcx.get_diagnostic_item(sym::AsRef); + if trait_predicate.def_id() == deref_trait_id || trait_predicate.def_id() == as_ref_trait_id; let receiver_ty = cx.typeck_results().expr_ty(receiver); - // If the callee has type parameters, they could appear in `projection_predicate.ty` or the - // types of `trait_predicate.trait_ref.substs`. - if if trait_predicate.def_id() == deref_trait_id { - if let [projection_predicate] = projection_predicates[..] { - let normalized_ty = - cx.tcx - .subst_and_normalize_erasing_regions(call_substs, cx.param_env, projection_predicate.term); - implements_trait(cx, receiver_ty, deref_trait_id, &[]) - && get_associated_type(cx, receiver_ty, deref_trait_id, "Target") - .map_or(false, |ty| ty::TermKind::Ty(ty) == normalized_ty.unpack()) - } else { - false - } - } else if trait_predicate.def_id() == as_ref_trait_id { - let composed_substs = compose_substs( - cx, - &trait_predicate.trait_ref.substs.iter().skip(1).collect::>()[..], - call_substs, - ); - // if `expr` is a `String` and generic target is [u8], skip - // (https://github.com/rust-lang/rust-clippy/issues/9317). - if let [subst] = composed_substs[..] - && let GenericArgKind::Type(arg_ty) = subst.unpack() - && arg_ty.is_slice() - && let inner_ty = arg_ty.builtin_index().unwrap() - && let ty::Uint(ty::UintTy::U8) = inner_ty.kind() - && let self_ty = cx.typeck_results().expr_ty(expr).peel_refs() - && is_type_diagnostic_item(cx, self_ty, sym::String) { - false - } else { - implements_trait(cx, receiver_ty, as_ref_trait_id, &composed_substs) - } - } else { - false - }; + if can_change_type(cx, maybe_arg, receiver_ty); // We can't add an `&` when the trait is `Deref` because `Target = &T` won't match // `Target = T`. if n_refs > 0 || is_copy(cx, receiver_ty) || trait_predicate.def_id() != deref_trait_id; let n_refs = max(n_refs, if is_copy(cx, receiver_ty) { 0 } else { 1 }); - // If the trait is `AsRef` and the input type variable `T` occurs in the output type, then - // `T` must not be instantiated with a reference - // (https://github.com/rust-lang/rust-clippy/issues/8507). - if (n_refs == 0 && !receiver_ty.is_ref()) - || trait_predicate.def_id() != as_ref_trait_id - || !fn_sig.output().contains(input); if let Some(receiver_snippet) = snippet_opt(cx, receiver.span); then { span_lint_and_sugg( @@ -359,11 +319,11 @@ fn get_callee_substs_and_args<'tcx>( } } if_chain! { - if let ExprKind::MethodCall(_, receiver, args, _) = expr.kind; + if let ExprKind::MethodCall(_, recv, args, _) = expr.kind; if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); then { let substs = cx.typeck_results().node_substs(expr.hir_id); - return Some((method_def_id, substs, Some(receiver), args)); + return Some((method_def_id, substs, Some(recv), args)); } } None @@ -395,22 +355,103 @@ fn get_input_traits_and_projections<'tcx>( (trait_predicates, projection_predicates) } -/// Composes two substitutions by applying the latter to the types of the former. -fn compose_substs<'tcx>( - cx: &LateContext<'tcx>, - left: &[GenericArg<'tcx>], - right: SubstsRef<'tcx>, -) -> Vec> { - left.iter() - .map(|arg| { - if let GenericArgKind::Type(arg_ty) = arg.unpack() { - let normalized_ty = cx.tcx.subst_and_normalize_erasing_regions(right, cx.param_env, arg_ty); - GenericArg::from(normalized_ty) - } else { - *arg +fn can_change_type<'a>(cx: &LateContext<'a>, mut expr: &'a Expr<'a>, mut ty: Ty<'a>) -> bool { + for (_, node) in cx.tcx.hir().parent_iter(expr.hir_id) { + match node { + Node::Stmt(_) => return true, + Node::Block(..) => continue, + Node::Item(item) => { + if let ItemKind::Fn(_, _, body_id) = &item.kind + && let output_ty = return_ty(cx, item.hir_id()) + && let local_def_id = cx.tcx.hir().local_def_id(item.hir_id()) + && Inherited::build(cx.tcx, local_def_id).enter(|inherited| { + let fn_ctxt = FnCtxt::new(&inherited, cx.param_env, item.hir_id()); + fn_ctxt.can_coerce(ty, output_ty) + }) { + if has_lifetime(output_ty) && has_lifetime(ty) { + return false; + } + let body = cx.tcx.hir().body(*body_id); + let body_expr = &body.value; + let mut count = 0; + return find_all_ret_expressions(cx, body_expr, |_| { count += 1; count <= 1 }); + } } - }) - .collect() + Node::Expr(parent_expr) => { + if let Some((callee_def_id, call_substs, recv, call_args)) = get_callee_substs_and_args(cx, parent_expr) + { + let fn_sig = cx.tcx.fn_sig(callee_def_id).skip_binder(); + if let Some(arg_index) = recv.into_iter().chain(call_args).position(|arg| arg.hir_id == expr.hir_id) + && let Some(param_ty) = fn_sig.inputs().get(arg_index) + && let ty::Param(ParamTy { index: param_index , ..}) = param_ty.kind() + { + if fn_sig + .inputs() + .iter() + .enumerate() + .filter(|(i, _)| *i != arg_index) + .any(|(_, ty)| ty.contains(*param_ty)) + { + return false; + } + + let mut trait_predicates = cx.tcx.param_env(callee_def_id) + .caller_bounds().iter().filter(|predicate| { + if let PredicateKind::Trait(trait_predicate) = predicate.kind().skip_binder() + && trait_predicate.trait_ref.self_ty() == *param_ty { + true + } else { + false + } + }); + + let new_subst = cx.tcx.mk_substs( + call_substs.iter() + .enumerate() + .map(|(i, t)| + if i == (*param_index as usize) { + GenericArg::from(ty) + } else { + t + })); + + if trait_predicates.any(|predicate| { + let predicate = EarlyBinder(predicate).subst(cx.tcx, new_subst); + let obligation = Obligation::new(ObligationCause::dummy(), cx.param_env, predicate); + !cx.tcx + .infer_ctxt() + .enter(|infcx| infcx.predicate_must_hold_modulo_regions(&obligation)) + }) { + return false; + } + + let output_ty = fn_sig.output(); + if output_ty.contains(*param_ty) { + if let Ok(new_ty) = cx.tcx.try_subst_and_normalize_erasing_regions( + new_subst, cx.param_env, output_ty) { + expr = parent_expr; + ty = new_ty; + continue; + } + return false; + } + + return true; + } + } else if let ExprKind::Block(..) = parent_expr.kind { + continue; + } + return false; + }, + _ => return false, + } + } + + false +} + +fn has_lifetime(ty: Ty<'_>) -> bool { + ty.walk().any(|t| matches!(t.unpack(), GenericArgKind::Lifetime(_))) } /// Returns true if the named method is `Iterator::cloned` or `Iterator::copied`. @@ -421,10 +462,10 @@ fn is_cloned_or_copied(cx: &LateContext<'_>, method_name: Symbol, method_def_id: /// Returns true if the named method can be used to convert the receiver to its "owned" /// representation. -fn is_to_owned_like(cx: &LateContext<'_>, method_name: Symbol, method_def_id: DefId) -> bool { +fn is_to_owned_like<'a>(cx: &LateContext<'a>, call_expr: &Expr<'a>, method_name: Symbol, method_def_id: DefId) -> bool { is_clone_like(cx, method_name.as_str(), method_def_id) || is_cow_into_owned(cx, method_name, method_def_id) - || is_to_string(cx, method_name, method_def_id) + || is_to_string_on_string_like(cx, call_expr, method_name, method_def_id) } /// Returns true if the named method is `Cow::into_owned`. @@ -432,7 +473,27 @@ fn is_cow_into_owned(cx: &LateContext<'_>, method_name: Symbol, method_def_id: D method_name.as_str() == "into_owned" && is_diag_item_method(cx, method_def_id, sym::Cow) } -/// Returns true if the named method is `ToString::to_string`. -fn is_to_string(cx: &LateContext<'_>, method_name: Symbol, method_def_id: DefId) -> bool { - method_name == sym::to_string && is_diag_trait_item(cx, method_def_id, sym::ToString) +/// Returns true if the named method is `ToString::to_string` and it's called on a type that +/// is string-like i.e. implements `AsRef` or `Deref`. +fn is_to_string_on_string_like<'a>( + cx: &LateContext<'_>, + call_expr: &'a Expr<'a>, + method_name: Symbol, + method_def_id: DefId, +) -> bool { + if method_name != sym::to_string || !is_diag_trait_item(cx, method_def_id, sym::ToString) { + return false; + } + + if let Some(substs) = cx.typeck_results().node_substs_opt(call_expr.hir_id) + && let [generic_arg] = substs.as_slice() + && let GenericArgKind::Type(ty) = generic_arg.unpack() + && let Some(deref_trait_id) = cx.tcx.get_diagnostic_item(sym::Deref) + && let Some(as_ref_trait_id) = cx.tcx.get_diagnostic_item(sym::AsRef) + && (implements_trait(cx, ty, deref_trait_id, &[cx.tcx.types.str_.into()]) || + implements_trait(cx, ty, as_ref_trait_id, &[cx.tcx.types.str_.into()])) { + true + } else { + false + } } diff --git a/src/tools/clippy/clippy_lints/src/methods/unwrap_or_else_default.rs b/src/tools/clippy/clippy_lints/src/methods/unwrap_or_else_default.rs index f3af281d6cacc..045f739e64ded 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unwrap_or_else_default.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unwrap_or_else_default.rs @@ -5,10 +5,11 @@ use clippy_utils::{ diagnostics::span_lint_and_sugg, is_default_equivalent_call, source::snippet_with_applicability, ty::is_type_diagnostic_item, }; +use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateContext; -use rustc_span::sym; +use rustc_span::{sym, symbol}; pub(super) fn check<'tcx>( cx: &LateContext<'tcx>, @@ -25,7 +26,7 @@ pub(super) fn check<'tcx>( if_chain! { if is_option || is_result; - if is_default_equivalent_call(cx, u_arg); + if closure_body_returns_empty_to_string(cx, u_arg) || is_default_equivalent_call(cx, u_arg); then { let mut applicability = Applicability::MachineApplicable; @@ -44,3 +45,22 @@ pub(super) fn check<'tcx>( } } } + +fn closure_body_returns_empty_to_string(cx: &LateContext<'_>, e: &hir::Expr<'_>) -> bool { + if let hir::ExprKind::Closure(&hir::Closure { body, .. }) = e.kind { + let body = cx.tcx.hir().body(body); + + if body.params.is_empty() + && let hir::Expr{ kind, .. } = &body.value + && let hir::ExprKind::MethodCall(hir::PathSegment {ident, ..}, self_arg, _, _) = kind + && ident == &symbol::Ident::from_str("to_string") + && let hir::Expr{ kind, .. } = self_arg + && let hir::ExprKind::Lit(lit) = kind + && let LitKind::Str(symbol::kw::Empty, _) = lit.node + { + return true; + } + } + + false +} diff --git a/src/tools/clippy/clippy_lints/src/minmax.rs b/src/tools/clippy/clippy_lints/src/minmax.rs index 44b21e7b080d2..4d8579135fc06 100644 --- a/src/tools/clippy/clippy_lints/src/minmax.rs +++ b/src/tools/clippy/clippy_lints/src/minmax.rs @@ -1,7 +1,6 @@ use clippy_utils::consts::{constant_simple, Constant}; use clippy_utils::diagnostics::span_lint; use clippy_utils::{match_trait_method, paths}; -use if_chain::if_chain; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; @@ -84,19 +83,16 @@ fn min_max<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<(MinMax, Cons } }, ExprKind::MethodCall(path, receiver, args @ [_], _) => { - if_chain! { - if cx.typeck_results().expr_ty(receiver).is_floating_point() || match_trait_method(cx, expr, &paths::ORD); - then { - if path.ident.name == sym!(max) { - fetch_const(cx, Some(receiver), args, MinMax::Max) - } else if path.ident.name == sym!(min) { - fetch_const(cx, Some(receiver), args, MinMax::Min) - } else { - None - } + if cx.typeck_results().expr_ty(receiver).is_floating_point() || match_trait_method(cx, expr, &paths::ORD) { + if path.ident.name == sym!(max) { + fetch_const(cx, Some(receiver), args, MinMax::Max) + } else if path.ident.name == sym!(min) { + fetch_const(cx, Some(receiver), args, MinMax::Min) } else { None } + } else { + None } }, _ => None, @@ -109,18 +105,18 @@ fn fetch_const<'a>( args: &'a [Expr<'a>], m: MinMax, ) -> Option<(MinMax, Constant, &'a Expr<'a>)> { - let mut args = receiver.into_iter().chain(args.into_iter()); - let arg0 = args.next()?; - let arg1 = args.next()?; + let mut args = receiver.into_iter().chain(args); + let first_arg = args.next()?; + let second_arg = args.next()?; if args.next().is_some() { return None; } - constant_simple(cx, cx.typeck_results(), arg0).map_or_else( - || constant_simple(cx, cx.typeck_results(), arg1).map(|c| (m, c, arg0)), + constant_simple(cx, cx.typeck_results(), first_arg).map_or_else( + || constant_simple(cx, cx.typeck_results(), second_arg).map(|c| (m, c, first_arg)), |c| { - if constant_simple(cx, cx.typeck_results(), arg1).is_none() { + if constant_simple(cx, cx.typeck_results(), second_arg).is_none() { // otherwise ignore - Some((m, c, arg1)) + Some((m, c, second_arg)) } else { None } diff --git a/src/tools/clippy/clippy_lints/src/needless_for_each.rs b/src/tools/clippy/clippy_lints/src/needless_for_each.rs index f8cc3fbb3cdfa..3233d87c07319 100644 --- a/src/tools/clippy/clippy_lints/src/needless_for_each.rs +++ b/src/tools/clippy/clippy_lints/src/needless_for_each.rs @@ -77,7 +77,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessForEach { if let ExprKind::Block(..) = body.value.kind; then { let mut ret_collector = RetCollector::default(); - ret_collector.visit_expr(&body.value); + ret_collector.visit_expr(body.value); // Skip the lint if `return` is used in `Loop` in order not to suggest using `'label`. if ret_collector.ret_in_loop { diff --git a/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs b/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs index 17d5fa2152bbf..6217110a1f3ae 100644 --- a/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs +++ b/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs @@ -12,6 +12,7 @@ use rustc_middle::ty::{self, ConstKind}; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::symbol::{kw, Ident}; use rustc_span::Span; +use std::iter; declare_clippy_lint! { /// ### What it does @@ -234,11 +235,7 @@ impl<'tcx> LateLintPass<'tcx> for OnlyUsedInRecursion { })) => ( def_id.to_def_id(), FnKind::TraitFn, - if sig.decl.implicit_self.has_implicit_self() { - 1 - } else { - 0 - }, + usize::from(sig.decl.implicit_self.has_implicit_self()), ), Some(Node::ImplItem(&ImplItem { kind: ImplItemKind::Fn(ref sig, _), @@ -253,11 +250,7 @@ impl<'tcx> LateLintPass<'tcx> for OnlyUsedInRecursion { ( trait_item_id, FnKind::ImplTraitFn(cx.tcx.erase_regions(trait_ref.substs) as *const _ as usize), - if sig.decl.implicit_self.has_implicit_self() { - 1 - } else { - 0 - }, + usize::from(sig.decl.implicit_self.has_implicit_self()), ) } else { (def_id.to_def_id(), FnKind::Fn, 0) @@ -310,7 +303,7 @@ impl<'tcx> LateLintPass<'tcx> for OnlyUsedInRecursion { && has_matching_substs(param.fn_kind, typeck.node_substs(parent.hir_id)) }) => { - if let Some(idx) = std::iter::once(receiver).chain(args.iter()).position(|arg| arg.hir_id == child_id) { + if let Some(idx) = iter::once(receiver).chain(args).position(|arg| arg.hir_id == child_id) { param.uses.push(Usage::new(span, idx)); } return; diff --git a/src/tools/clippy/clippy_lints/src/operators/arithmetic.rs b/src/tools/clippy/clippy_lints/src/operators/arithmetic.rs deleted file mode 100644 index 800cf249f5c78..0000000000000 --- a/src/tools/clippy/clippy_lints/src/operators/arithmetic.rs +++ /dev/null @@ -1,119 +0,0 @@ -#![allow( - // False positive - clippy::match_same_arms -)] - -use super::ARITHMETIC; -use clippy_utils::{consts::constant_simple, diagnostics::span_lint}; -use rustc_data_structures::fx::FxHashSet; -use rustc_hir as hir; -use rustc_lint::{LateContext, LateLintPass}; -use rustc_session::impl_lint_pass; -use rustc_span::source_map::Span; - -const HARD_CODED_ALLOWED: &[&str] = &["std::num::Saturating", "std::string::String", "std::num::Wrapping"]; - -#[derive(Debug)] -pub struct Arithmetic { - allowed: FxHashSet, - // Used to check whether expressions are constants, such as in enum discriminants and consts - const_span: Option, - expr_span: Option, -} - -impl_lint_pass!(Arithmetic => [ARITHMETIC]); - -impl Arithmetic { - #[must_use] - pub fn new(mut allowed: FxHashSet) -> Self { - allowed.extend(HARD_CODED_ALLOWED.iter().copied().map(String::from)); - Self { - allowed, - const_span: None, - expr_span: None, - } - } - - /// Checks if the given `expr` has any of the inner `allowed` elements. - fn is_allowed_ty(&self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool { - self.allowed.contains( - cx.typeck_results() - .expr_ty(expr) - .to_string() - .split('<') - .next() - .unwrap_or_default(), - ) - } - - fn issue_lint(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) { - span_lint(cx, ARITHMETIC, expr.span, "arithmetic detected"); - self.expr_span = Some(expr.span); - } -} - -impl<'tcx> LateLintPass<'tcx> for Arithmetic { - fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { - if self.expr_span.is_some() { - return; - } - if let Some(span) = self.const_span && span.contains(expr.span) { - return; - } - match &expr.kind { - hir::ExprKind::Binary(op, lhs, rhs) | hir::ExprKind::AssignOp(op, lhs, rhs) => { - let ( - hir::BinOpKind::Add - | hir::BinOpKind::Sub - | hir::BinOpKind::Mul - | hir::BinOpKind::Div - | hir::BinOpKind::Rem - | hir::BinOpKind::Shl - | hir::BinOpKind::Shr - ) = op.node else { - return; - }; - if self.is_allowed_ty(cx, lhs) || self.is_allowed_ty(cx, rhs) { - return; - } - self.issue_lint(cx, expr); - }, - hir::ExprKind::Unary(hir::UnOp::Neg, _) => { - // CTFE already takes care of things like `-1` that do not overflow. - if constant_simple(cx, cx.typeck_results(), expr).is_none() { - self.issue_lint(cx, expr); - } - }, - _ => {}, - } - } - - fn check_body(&mut self, cx: &LateContext<'_>, body: &hir::Body<'_>) { - let body_owner = cx.tcx.hir().body_owner_def_id(body.id()); - match cx.tcx.hir().body_owner_kind(body_owner) { - hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => { - let body_span = cx.tcx.def_span(body_owner); - if let Some(span) = self.const_span && span.contains(body_span) { - return; - } - self.const_span = Some(body_span); - }, - hir::BodyOwnerKind::Closure | hir::BodyOwnerKind::Fn => {}, - } - } - - fn check_body_post(&mut self, cx: &LateContext<'_>, body: &hir::Body<'_>) { - let body_owner = cx.tcx.hir().body_owner(body.id()); - let body_span = cx.tcx.hir().span(body_owner); - if let Some(span) = self.const_span && span.contains(body_span) { - return; - } - self.const_span = None; - } - - fn check_expr_post(&mut self, _: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { - if Some(expr.span) == self.expr_span { - self.expr_span = None; - } - } -} diff --git a/src/tools/clippy/clippy_lints/src/operators/arithmetic_side_effects.rs b/src/tools/clippy/clippy_lints/src/operators/arithmetic_side_effects.rs new file mode 100644 index 0000000000000..83b69fbb31164 --- /dev/null +++ b/src/tools/clippy/clippy_lints/src/operators/arithmetic_side_effects.rs @@ -0,0 +1,173 @@ +#![allow( + // False positive + clippy::match_same_arms +)] + +use super::ARITHMETIC_SIDE_EFFECTS; +use clippy_utils::{consts::constant_simple, diagnostics::span_lint}; +use rustc_ast as ast; +use rustc_data_structures::fx::FxHashSet; +use rustc_hir as hir; +use rustc_lint::{LateContext, LateLintPass}; +use rustc_middle::ty::Ty; +use rustc_session::impl_lint_pass; +use rustc_span::source_map::{Span, Spanned}; + +const HARD_CODED_ALLOWED: &[&str] = &[ + "f32", + "f64", + "std::num::Saturating", + "std::string::String", + "std::num::Wrapping", +]; + +#[derive(Debug)] +pub struct ArithmeticSideEffects { + allowed: FxHashSet, + // Used to check whether expressions are constants, such as in enum discriminants and consts + const_span: Option, + expr_span: Option, +} + +impl_lint_pass!(ArithmeticSideEffects => [ARITHMETIC_SIDE_EFFECTS]); + +impl ArithmeticSideEffects { + #[must_use] + pub fn new(mut allowed: FxHashSet) -> Self { + allowed.extend(HARD_CODED_ALLOWED.iter().copied().map(String::from)); + Self { + allowed, + const_span: None, + expr_span: None, + } + } + + /// Checks assign operators (+=, -=, *=, /=) of integers in a non-constant environment that + /// won't overflow. + fn has_valid_assign_op(op: &Spanned, rhs: &hir::Expr<'_>, rhs_refs: Ty<'_>) -> bool { + if !Self::is_literal_integer(rhs, rhs_refs) { + return false; + } + if let hir::BinOpKind::Div | hir::BinOpKind::Mul = op.node + && let hir::ExprKind::Lit(ref lit) = rhs.kind + && let ast::LitKind::Int(1, _) = lit.node + { + return true; + } + false + } + + /// Checks "raw" binary operators (+, -, *, /) of integers in a non-constant environment + /// already handled by the CTFE. + fn has_valid_bin_op(lhs: &hir::Expr<'_>, lhs_refs: Ty<'_>, rhs: &hir::Expr<'_>, rhs_refs: Ty<'_>) -> bool { + Self::is_literal_integer(lhs, lhs_refs) && Self::is_literal_integer(rhs, rhs_refs) + } + + /// Checks if the given `expr` has any of the inner `allowed` elements. + fn is_allowed_ty(&self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool { + self.allowed.contains( + cx.typeck_results() + .expr_ty(expr) + .to_string() + .split('<') + .next() + .unwrap_or_default(), + ) + } + + /// Explicit integers like `1` or `i32::MAX`. Does not take into consideration references. + fn is_literal_integer(expr: &hir::Expr<'_>, expr_refs: Ty<'_>) -> bool { + let is_integral = expr_refs.is_integral(); + let is_literal = matches!(expr.kind, hir::ExprKind::Lit(_)); + is_integral && is_literal + } + + fn issue_lint(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) { + span_lint(cx, ARITHMETIC_SIDE_EFFECTS, expr.span, "arithmetic detected"); + self.expr_span = Some(expr.span); + } + + /// Manages when the lint should be triggered. Operations in constant environments, hard coded + /// types, custom allowed types and non-constant operations that won't overflow are ignored. + fn manage_bin_ops( + &mut self, + cx: &LateContext<'_>, + expr: &hir::Expr<'_>, + op: &Spanned, + lhs: &hir::Expr<'_>, + rhs: &hir::Expr<'_>, + ) { + if constant_simple(cx, cx.typeck_results(), expr).is_some() { + return; + } + if !matches!( + op.node, + hir::BinOpKind::Add + | hir::BinOpKind::Sub + | hir::BinOpKind::Mul + | hir::BinOpKind::Div + | hir::BinOpKind::Rem + | hir::BinOpKind::Shl + | hir::BinOpKind::Shr + ) { + return; + }; + if self.is_allowed_ty(cx, lhs) || self.is_allowed_ty(cx, rhs) { + return; + } + let lhs_refs = cx.typeck_results().expr_ty(lhs).peel_refs(); + let rhs_refs = cx.typeck_results().expr_ty(rhs).peel_refs(); + let has_valid_assign_op = Self::has_valid_assign_op(op, rhs, rhs_refs); + if has_valid_assign_op || Self::has_valid_bin_op(lhs, lhs_refs, rhs, rhs_refs) { + return; + } + self.issue_lint(cx, expr); + } +} + +impl<'tcx> LateLintPass<'tcx> for ArithmeticSideEffects { + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { + if self.expr_span.is_some() || self.const_span.map_or(false, |sp| sp.contains(expr.span)) { + return; + } + match &expr.kind { + hir::ExprKind::Binary(op, lhs, rhs) | hir::ExprKind::AssignOp(op, lhs, rhs) => { + self.manage_bin_ops(cx, expr, op, lhs, rhs); + }, + hir::ExprKind::Unary(hir::UnOp::Neg, _) => { + if constant_simple(cx, cx.typeck_results(), expr).is_none() { + self.issue_lint(cx, expr); + } + }, + _ => {}, + } + } + + fn check_body(&mut self, cx: &LateContext<'_>, body: &hir::Body<'_>) { + let body_owner = cx.tcx.hir().body_owner(body.id()); + let body_owner_def_id = cx.tcx.hir().local_def_id(body_owner); + let body_owner_kind = cx.tcx.hir().body_owner_kind(body_owner_def_id); + if let hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) = body_owner_kind { + let body_span = cx.tcx.hir().span_with_body(body_owner); + if let Some(span) = self.const_span && span.contains(body_span) { + return; + } + self.const_span = Some(body_span); + } + } + + fn check_body_post(&mut self, cx: &LateContext<'_>, body: &hir::Body<'_>) { + let body_owner = cx.tcx.hir().body_owner(body.id()); + let body_span = cx.tcx.hir().span(body_owner); + if let Some(span) = self.const_span && span.contains(body_span) { + return; + } + self.const_span = None; + } + + fn check_expr_post(&mut self, _: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { + if Some(expr.span) == self.expr_span { + self.expr_span = None; + } + } +} diff --git a/src/tools/clippy/clippy_lints/src/operators/mod.rs b/src/tools/clippy/clippy_lints/src/operators/mod.rs index bb6d99406b493..c32b4df4f75c1 100644 --- a/src/tools/clippy/clippy_lints/src/operators/mod.rs +++ b/src/tools/clippy/clippy_lints/src/operators/mod.rs @@ -21,7 +21,7 @@ mod ptr_eq; mod self_assignment; mod verbose_bit_mask; -pub(crate) mod arithmetic; +pub(crate) mod arithmetic_side_effects; use rustc_hir::{Body, Expr, ExprKind, UnOp}; use rustc_lint::{LateContext, LateLintPass}; @@ -61,25 +61,29 @@ declare_clippy_lint! { declare_clippy_lint! { /// ### What it does - /// Checks for any kind of arithmetic operation of any type. + /// Checks any kind of arithmetic operation of any type. /// /// Operators like `+`, `-`, `*` or `<<` are usually capable of overflowing according to the [Rust /// Reference](https://doc.rust-lang.org/reference/expressions/operator-expr.html#overflow), - /// or can panic (`/`, `%`). Known safe built-in types like `Wrapping` or `Saturing` are filtered - /// away. + /// or can panic (`/`, `%`). + /// + /// Known safe built-in types like `Wrapping` or `Saturing`, floats, operations in constant + /// environments, allowed types and non-constant operations that won't overflow are ignored. /// /// ### Why is this bad? - /// Integer overflow will trigger a panic in debug builds or will wrap in - /// release mode. Division by zero will cause a panic in either mode. In some applications one - /// wants explicitly checked, wrapping or saturating arithmetic. + /// For integers, overflow will trigger a panic in debug builds or wrap the result in + /// release mode; division by zero will cause a panic in either mode. As a result, it is + /// desirable to explicitly call checked, wrapping or saturating arithmetic methods. /// /// #### Example /// ```rust - /// # let a = 0; - /// a + 1; + /// // `n` can be any number, including `i32::MAX`. + /// fn foo(n: i32) -> i32 { + /// n + 1 + /// } /// ``` /// - /// Third-party types also tend to overflow. + /// Third-party types can also overflow or present unwanted side-effects. /// /// #### Example /// ```ignore,rust @@ -88,11 +92,11 @@ declare_clippy_lint! { /// ``` /// /// ### Allowed types - /// Custom allowed types can be specified through the "arithmetic-allowed" filter. + /// Custom allowed types can be specified through the "arithmetic-side-effects-allowed" filter. #[clippy::version = "1.64.0"] - pub ARITHMETIC, + pub ARITHMETIC_SIDE_EFFECTS, restriction, - "any arithmetic expression that could overflow or panic" + "any arithmetic expression that can cause side effects like overflows or panics" } declare_clippy_lint! { @@ -785,7 +789,7 @@ pub struct Operators { } impl_lint_pass!(Operators => [ ABSURD_EXTREME_COMPARISONS, - ARITHMETIC, + ARITHMETIC_SIDE_EFFECTS, INTEGER_ARITHMETIC, FLOAT_ARITHMETIC, ASSIGN_OP_PATTERN, diff --git a/src/tools/clippy/clippy_lints/src/panic_in_result_fn.rs b/src/tools/clippy/clippy_lints/src/panic_in_result_fn.rs index 21acf003d92b2..4aa0d9227abad 100644 --- a/src/tools/clippy/clippy_lints/src/panic_in_result_fn.rs +++ b/src/tools/clippy/clippy_lints/src/panic_in_result_fn.rs @@ -69,7 +69,7 @@ fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, body: &'tcx hir } true }) - .visit_expr(&body.value); + .visit_expr(body.value); if !panics.is_empty() { span_lint_and_then( cx, diff --git a/src/tools/clippy/clippy_lints/src/ptr.rs b/src/tools/clippy/clippy_lints/src/ptr.rs index 0028e0bc6c517..41d1baba64f85 100644 --- a/src/tools/clippy/clippy_lints/src/ptr.rs +++ b/src/tools/clippy/clippy_lints/src/ptr.rs @@ -507,7 +507,7 @@ fn check_mut_from_ref<'tcx>(cx: &LateContext<'tcx>, sig: &FnSig<'_>, body: Optio if let Some(args) = args && !args.is_empty() && body.map_or(true, |body| { - sig.header.unsafety == Unsafety::Unsafe || contains_unsafe_block(cx, &body.value) + sig.header.unsafety == Unsafety::Unsafe || contains_unsafe_block(cx, body.value) }) { span_lint_and_then( @@ -664,7 +664,7 @@ fn check_ptr_arg_usage<'tcx>(cx: &LateContext<'tcx>, body: &'tcx Body<'_>, args: results, skip_count, }; - v.visit_expr(&body.value); + v.visit_expr(body.value); v.results } diff --git a/src/tools/clippy/clippy_lints/src/ranges.rs b/src/tools/clippy/clippy_lints/src/ranges.rs index 490f345d29707..918d624eec6fa 100644 --- a/src/tools/clippy/clippy_lints/src/ranges.rs +++ b/src/tools/clippy/clippy_lints/src/ranges.rs @@ -350,6 +350,7 @@ fn check_range_bounds<'a>(cx: &'a LateContext<'_>, ex: &'a Expr<'_>) -> Option, expr: &Expr<'_>) { if_chain! { + if expr.span.can_be_used_for_suggestions(); if let Some(higher::Range { start, end: Some(end), @@ -357,14 +358,7 @@ fn check_exclusive_range_plus_one(cx: &LateContext<'_>, expr: &Expr<'_>) { }) = higher::Range::hir(expr); if let Some(y) = y_plus_one(cx, end); then { - let span = if expr.span.from_expansion() { - expr.span - .ctxt() - .outer_expn_data() - .call_site - } else { - expr.span - }; + let span = expr.span; span_lint_and_then( cx, RANGE_PLUS_ONE, @@ -399,6 +393,7 @@ fn check_exclusive_range_plus_one(cx: &LateContext<'_>, expr: &Expr<'_>) { // inclusive range minus one: `x..=(y-1)` fn check_inclusive_range_minus_one(cx: &LateContext<'_>, expr: &Expr<'_>) { if_chain! { + if expr.span.can_be_used_for_suggestions(); if let Some(higher::Range { start, end: Some(end), limits: RangeLimits::Closed }) = higher::Range::hir(expr); if let Some(y) = y_minus_one(cx, end); then { diff --git a/src/tools/clippy/clippy_lints/src/returns.rs b/src/tools/clippy/clippy_lints/src/returns.rs index 1926661c59603..91553240e3c91 100644 --- a/src/tools/clippy/clippy_lints/src/returns.rs +++ b/src/tools/clippy/clippy_lints/src/returns.rs @@ -139,7 +139,7 @@ impl<'tcx> LateLintPass<'tcx> for Return { } else { RetReplacement::Empty }; - check_final_expr(cx, &body.value, Some(body.value.span), replacement); + check_final_expr(cx, body.value, Some(body.value.span), replacement); }, FnKind::ItemFn(..) | FnKind::Method(..) => { if let ExprKind::Block(block, _) = body.value.kind { diff --git a/src/tools/clippy/clippy_lints/src/suspicious_trait_impl.rs b/src/tools/clippy/clippy_lints/src/suspicious_trait_impl.rs index 4294464dbf61a..6add20c1fb712 100644 --- a/src/tools/clippy/clippy_lints/src/suspicious_trait_impl.rs +++ b/src/tools/clippy/clippy_lints/src/suspicious_trait_impl.rs @@ -78,7 +78,7 @@ impl<'tcx> LateLintPass<'tcx> for SuspiciousImpl { ] .iter() .find(|&(ts, _)| ts.iter().any(|&t| Ok(trait_id) == cx.tcx.lang_items().require(t))); - if count_binops(&body.value) == 1; + if count_binops(body.value) == 1; then { span_lint( cx, diff --git a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs index 851eef7b33241..c0a4f3fbacd64 100644 --- a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs +++ b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs @@ -149,7 +149,7 @@ impl<'tcx> LateLintPass<'tcx> for UnitReturnExpectingOrd { let args = std::iter::once(receiver).chain(args.iter()).collect::>(); for (i, trait_name) in arg_indices { if i < args.len() { - match check_arg(cx, &args[i]) { + match check_arg(cx, args[i]) { Some((span, None)) => { span_lint( cx, diff --git a/src/tools/clippy/clippy_lints/src/unit_types/unit_arg.rs b/src/tools/clippy/clippy_lints/src/unit_types/unit_arg.rs index 7ffb53dcf455f..a6f777abc6e94 100644 --- a/src/tools/clippy/clippy_lints/src/unit_types/unit_arg.rs +++ b/src/tools/clippy/clippy_lints/src/unit_types/unit_arg.rs @@ -50,7 +50,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { }) .collect::>(); if !args_to_recover.is_empty() && !is_from_proc_macro(cx, expr) { - lint_unit_args(cx, expr, &args_to_recover.as_slice()); + lint_unit_args(cx, expr, args_to_recover.as_slice()); } } diff --git a/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs b/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs index a5afbb8ff9da4..2c40827db0e75 100644 --- a/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs +++ b/src/tools/clippy/clippy_lints/src/unnecessary_wraps.rs @@ -115,7 +115,7 @@ impl<'tcx> LateLintPass<'tcx> for UnnecessaryWraps { // Check if all return expression respect the following condition and collect them. let mut suggs = Vec::new(); - let can_sugg = find_all_ret_expressions(cx, &body.value, |ret_expr| { + let can_sugg = find_all_ret_expressions(cx, body.value, |ret_expr| { if_chain! { if !ret_expr.span.from_expansion(); // Check if a function call. diff --git a/src/tools/clippy/clippy_lints/src/unwrap.rs b/src/tools/clippy/clippy_lints/src/unwrap.rs index 9092156be150a..7e451b7b7a419 100644 --- a/src/tools/clippy/clippy_lints/src/unwrap.rs +++ b/src/tools/clippy/clippy_lints/src/unwrap.rs @@ -160,7 +160,7 @@ fn collect_unwrap_info<'tcx>( let name = method_name.ident.as_str(); if is_relevant_option_call(cx, ty, name) || is_relevant_result_call(cx, ty, name); then { - assert!(args.len() == 0); + assert!(args.is_empty()); let unwrappable = match name { "is_some" | "is_ok" => true, "is_err" | "is_none" => false, diff --git a/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs b/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs index b3ca15f7648bc..46020adcaa2ca 100644 --- a/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs +++ b/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs @@ -83,7 +83,7 @@ impl<'a, 'tcx> Visitor<'tcx> for FindExpectUnwrap<'a, 'tcx> { fn visit_expr(&mut self, expr: &'tcx Expr<'_>) { // check for `expect` if let Some(arglists) = method_chain_args(expr, &["expect"]) { - let receiver_ty = self.typeck_results.expr_ty(&arglists[0].0).peel_refs(); + let receiver_ty = self.typeck_results.expr_ty(arglists[0].0).peel_refs(); if is_type_diagnostic_item(self.lcx, receiver_ty, sym::Option) || is_type_diagnostic_item(self.lcx, receiver_ty, sym::Result) { @@ -93,7 +93,7 @@ impl<'a, 'tcx> Visitor<'tcx> for FindExpectUnwrap<'a, 'tcx> { // check for `unwrap` if let Some(arglists) = method_chain_args(expr, &["unwrap"]) { - let receiver_ty = self.typeck_results.expr_ty(&arglists[0].0).peel_refs(); + let receiver_ty = self.typeck_results.expr_ty(arglists[0].0).peel_refs(); if is_type_diagnostic_item(self.lcx, receiver_ty, sym::Option) || is_type_diagnostic_item(self.lcx, receiver_ty, sym::Result) { @@ -114,7 +114,7 @@ fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_item: &'tc typeck_results: cx.tcx.typeck(impl_item.def_id), result: Vec::new(), }; - fpu.visit_expr(&body.value); + fpu.visit_expr(body.value); // if we've found one, lint if !fpu.result.is_empty() { diff --git a/src/tools/clippy/clippy_lints/src/utils/author.rs b/src/tools/clippy/clippy_lints/src/utils/author.rs index 1489c96d9e9b0..4003fff27c006 100644 --- a/src/tools/clippy/clippy_lints/src/utils/author.rs +++ b/src/tools/clippy/clippy_lints/src/utils/author.rs @@ -142,7 +142,7 @@ fn check_item(cx: &LateContext<'_>, hir_id: HirId) { let hir = cx.tcx.hir(); if let Some(body_id) = hir.maybe_body_owned_by(hir_id.expect_owner()) { check_node(cx, hir_id, |v| { - v.expr(&v.bind("expr", &hir.body(body_id).value)); + v.expr(&v.bind("expr", hir.body(body_id).value)); }); } } diff --git a/src/tools/clippy/clippy_lints/src/utils/conf.rs b/src/tools/clippy/clippy_lints/src/utils/conf.rs index 84e65d5fa0b71..a8500beb25747 100644 --- a/src/tools/clippy/clippy_lints/src/utils/conf.rs +++ b/src/tools/clippy/clippy_lints/src/utils/conf.rs @@ -208,7 +208,7 @@ define_Conf! { /// Lint: Arithmetic. /// /// Suppress checking of the passed type names. - (arithmetic_allowed: rustc_data_structures::fx::FxHashSet = <_>::default()), + (arithmetic_side_effects_allowed: rustc_data_structures::fx::FxHashSet = <_>::default()), /// Lint: ENUM_VARIANT_NAMES, LARGE_TYPES_PASSED_BY_VALUE, TRIVIALLY_COPY_PASS_BY_REF, UNNECESSARY_WRAPS, UNUSED_SELF, UPPER_CASE_ACRONYMS, WRONG_SELF_CONVENTION, BOX_COLLECTION, REDUNDANT_ALLOCATION, RC_BUFFER, VEC_BOX, OPTION_OPTION, LINKEDLIST, RC_MUTEX. /// /// Suppress lints whenever the suggested change would cause breakage for other crates. diff --git a/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs b/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs index ae1c11ef83c31..17d9a04185767 100644 --- a/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs +++ b/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs @@ -505,7 +505,7 @@ impl<'tcx> LateLintPass<'tcx> for LintWithoutLintPass { .hir_id(), ), ); - collector.visit_expr(&cx.tcx.hir().body(body_id).value); + collector.visit_expr(cx.tcx.hir().body(body_id).value); } } } @@ -653,7 +653,7 @@ impl<'tcx> LateLintPass<'tcx> for CompilerLintFunctions { } if_chain! { - if let ExprKind::MethodCall(path, [self_arg, ..], _) = &expr.kind; + if let ExprKind::MethodCall(path, self_arg, _, _) = &expr.kind; let fn_name = path.ident; if let Some(sugg) = self.map.get(fn_name.as_str()); let ty = cx.typeck_results().expr_ty(self_arg).peel_refs(); @@ -685,9 +685,8 @@ impl<'tcx> LateLintPass<'tcx> for OuterExpnDataPass { let method_names: Vec<&str> = method_names.iter().map(Symbol::as_str).collect(); if_chain! { if let ["expn_data", "outer_expn"] = method_names.as_slice(); - let args = arg_lists[1]; - if args.len() == 1; - let self_arg = &args.0; + let (self_arg, args)= arg_lists[1]; + if args.is_empty(); let self_ty = cx.typeck_results().expr_ty(self_arg).peel_refs(); if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT); then { @@ -734,30 +733,30 @@ impl<'tcx> LateLintPass<'tcx> for CollapsibleCalls { if and_then_args.len() == 5; if let ExprKind::Closure(&Closure { body, .. }) = &and_then_args[4].kind; let body = cx.tcx.hir().body(body); - let only_expr = peel_blocks_with_stmt(&body.value); - if let ExprKind::MethodCall(ps, span_call_args, _) = &only_expr.kind; - if let ExprKind::Path(..) = span_call_args[0].kind; + let only_expr = peel_blocks_with_stmt(body.value); + if let ExprKind::MethodCall(ps, recv, span_call_args, _) = &only_expr.kind; + if let ExprKind::Path(..) = recv.kind; then { let and_then_snippets = get_and_then_snippets(cx, and_then_args); let mut sle = SpanlessEq::new(cx).deny_side_effects(); match ps.ident.as_str() { - "span_suggestion" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => { + "span_suggestion" if sle.eq_expr(&and_then_args[2], &span_call_args[0]) => { suggest_suggestion(cx, expr, &and_then_snippets, &span_suggestion_snippets(cx, span_call_args)); }, - "span_help" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => { - let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#); + "span_help" if sle.eq_expr(&and_then_args[2], &span_call_args[0]) => { + let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#); suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), true); }, - "span_note" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => { - let note_snippet = snippet(cx, span_call_args[2].span, r#""...""#); + "span_note" if sle.eq_expr(&and_then_args[2], &span_call_args[0]) => { + let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#); suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), true); }, "help" => { - let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#); + let help_snippet = snippet(cx, span_call_args[0].span, r#""...""#); suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), false); } "note" => { - let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#); + let note_snippet = snippet(cx, span_call_args[0].span, r#""...""#); suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), false); } _ => (), @@ -798,9 +797,9 @@ fn span_suggestion_snippets<'a, 'hir>( cx: &LateContext<'_>, span_call_args: &'hir [Expr<'hir>], ) -> SpanSuggestionSnippets<'a> { - let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#); - let sugg_snippet = snippet(cx, span_call_args[3].span, ".."); - let applicability_snippet = snippet(cx, span_call_args[4].span, "Applicability::MachineApplicable"); + let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#); + let sugg_snippet = snippet(cx, span_call_args[2].span, ".."); + let applicability_snippet = snippet(cx, span_call_args[3].span, "Applicability::MachineApplicable"); SpanSuggestionSnippets { help: help_snippet, @@ -954,7 +953,7 @@ fn path_to_matched_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option LateLintPass<'tcx> for InvalidPaths { if el_ty.is_str(); let body = cx.tcx.hir().body(body_id); let typeck_results = cx.tcx.typeck_body(body_id); - if let Some(Constant::Vec(path)) = constant_simple(cx, typeck_results, &body.value); + if let Some(Constant::Vec(path)) = constant_simple(cx, typeck_results, body.value); let path: Vec<&str> = path.iter().map(|x| { if let Constant::Str(s) = x { s.as_str() @@ -1177,7 +1176,7 @@ impl InterningDefinedSymbol { }; if_chain! { // is a method call - if let ExprKind::MethodCall(_, [item], _) = call.kind; + if let ExprKind::MethodCall(_, item, [], _) = call.kind; if let Some(did) = cx.typeck_results().type_dependent_def_id(call.hir_id); let ty = cx.typeck_results().expr_ty(item); // ...on either an Ident or a Symbol diff --git a/src/tools/clippy/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/src/tools/clippy/clippy_lints/src/utils/internal_lints/metadata_collector.rs index b1148bccc2a28..342f627e38275 100644 --- a/src/tools/clippy/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/src/tools/clippy/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -1145,8 +1145,8 @@ impl<'a, 'hir> intravisit::Visitor<'hir> for IsMultiSpanScanner<'a, 'hir> { self.add_single_span_suggestion(); } }, - ExprKind::MethodCall(path, arg, _arg_span) => { - let (self_ty, _) = walk_ptrs_ty_depth(self.cx.typeck_results().expr_ty(&arg[0])); + ExprKind::MethodCall(path, recv, _, _arg_span) => { + let (self_ty, _) = walk_ptrs_ty_depth(self.cx.typeck_results().expr_ty(recv)); if match_type(self.cx, self_ty, &paths::DIAGNOSTIC_BUILDER) { let called_method = path.ident.name.as_str().to_string(); for (method_name, is_multi_part) in &SUGGESTION_DIAGNOSTIC_BUILDER_METHODS { diff --git a/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs b/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs index 8425837fd7336..bd5be0c9d7eda 100644 --- a/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs +++ b/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs @@ -86,7 +86,7 @@ impl VecPushSearcher { }, ExprKind::Unary(UnOp::Deref, _) | ExprKind::Index(..) if !needs_mut => { let mut last_place = parent; - while let Some(parent) = get_parent_expr(cx, parent) { + while let Some(parent) = get_parent_expr(cx, last_place) { if matches!(parent.kind, ExprKind::Unary(UnOp::Deref, _) | ExprKind::Field(..)) || matches!(parent.kind, ExprKind::Index(e, _) if e.hir_id == last_place.hir_id) { diff --git a/src/tools/clippy/clippy_lints/src/write.rs b/src/tools/clippy/clippy_lints/src/write.rs index 347165d9704a1..640a09a7a9123 100644 --- a/src/tools/clippy/clippy_lints/src/write.rs +++ b/src/tools/clippy/clippy_lints/src/write.rs @@ -805,7 +805,11 @@ fn check_newlines(fmtstr: &StrLit) -> bool { let contents = fmtstr.symbol.as_str(); let mut cb = |r: Range, c: Result| { - let c = c.unwrap(); + let c = match c { + Ok(c) => c, + Err(e) if !e.is_fatal() => return, + Err(e) => panic!("{:?}", e), + }; if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline { should_lint = true; diff --git a/src/tools/clippy/clippy_utils/src/check_proc_macro.rs b/src/tools/clippy/clippy_utils/src/check_proc_macro.rs index e8d2d579f097e..7a8d4e8068ed6 100644 --- a/src/tools/clippy/clippy_utils/src/check_proc_macro.rs +++ b/src/tools/clippy/clippy_utils/src/check_proc_macro.rs @@ -140,7 +140,7 @@ fn expr_search_pat(tcx: TyCtxt<'_>, e: &Expr<'_>) -> (Pat, Pat) { ExprKind::Match(e, _, MatchSource::AwaitDesugar) | ExprKind::Yield(e, YieldSource::Await { .. }) => { (expr_search_pat(tcx, e).0, Pat::Str("await")) }, - ExprKind::Closure(&Closure { body, .. }) => (Pat::Str(""), expr_search_pat(tcx, &tcx.hir().body(body).value).1), + ExprKind::Closure(&Closure { body, .. }) => (Pat::Str(""), expr_search_pat(tcx, tcx.hir().body(body).value).1), ExprKind::Block( Block { rules: BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided), @@ -254,7 +254,7 @@ fn fn_kind_pat(tcx: TyCtxt<'_>, kind: &FnKind<'_>, body: &Body<'_>, hir_id: HirI let (start_pat, end_pat) = match kind { FnKind::ItemFn(.., header) => (fn_header_search_pat(*header), Pat::Str("")), FnKind::Method(.., sig) => (fn_header_search_pat(sig.header), Pat::Str("")), - FnKind::Closure => return (Pat::Str(""), expr_search_pat(tcx, &body.value).1), + FnKind::Closure => return (Pat::Str(""), expr_search_pat(tcx, body.value).1), }; let start_pat = match tcx.hir().get(hir_id) { Node::Item(Item { vis_span, .. }) | Node::ImplItem(ImplItem { vis_span, .. }) => { diff --git a/src/tools/clippy/clippy_utils/src/eager_or_lazy.rs b/src/tools/clippy/clippy_utils/src/eager_or_lazy.rs index 124a00d817847..91c9c382c236b 100644 --- a/src/tools/clippy/clippy_utils/src/eager_or_lazy.rs +++ b/src/tools/clippy/clippy_utils/src/eager_or_lazy.rs @@ -45,7 +45,7 @@ impl ops::BitOrAssign for EagernessSuggestion { } /// Determine the eagerness of the given function call. -fn fn_eagerness<'tcx>(cx: &LateContext<'tcx>, fn_id: DefId, name: Symbol, have_one_arg: bool) -> EagernessSuggestion { +fn fn_eagerness(cx: &LateContext<'_>, fn_id: DefId, name: Symbol, have_one_arg: bool) -> EagernessSuggestion { use EagernessSuggestion::{Eager, Lazy, NoChange}; let name = name.as_str(); diff --git a/src/tools/clippy/clippy_utils/src/hir_utils.rs b/src/tools/clippy/clippy_utils/src/hir_utils.rs index f45cec9f0b430..7212d9cd74451 100644 --- a/src/tools/clippy/clippy_utils/src/hir_utils.rs +++ b/src/tools/clippy/clippy_utils/src/hir_utils.rs @@ -201,8 +201,8 @@ impl HirEqInterExpr<'_, '_, '_> { self.inner.cx.tcx.typeck_body(right), )); let res = self.eq_expr( - &self.inner.cx.tcx.hir().body(left).value, - &self.inner.cx.tcx.hir().body(right).value, + self.inner.cx.tcx.hir().body(left).value, + self.inner.cx.tcx.hir().body(right).value, ); self.inner.maybe_typeck_results = old_maybe_typeck_results; res @@ -649,7 +649,7 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { }) => { std::mem::discriminant(&capture_clause).hash(&mut self.s); // closures inherit TypeckResults - self.hash_expr(&self.cx.tcx.hir().body(body).value); + self.hash_expr(self.cx.tcx.hir().body(body).value); }, ExprKind::Field(e, ref f) => { self.hash_expr(e); @@ -1011,7 +1011,7 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { pub fn hash_body(&mut self, body_id: BodyId) { // swap out TypeckResults when hashing a body let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body_id)); - self.hash_expr(&self.cx.tcx.hir().body(body_id).value); + self.hash_expr(self.cx.tcx.hir().body(body_id).value); self.maybe_typeck_results = old_maybe_typeck_results; } @@ -1019,7 +1019,7 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { for arg in arg_list { match *arg { GenericArg::Lifetime(l) => self.hash_lifetime(l), - GenericArg::Type(ref ty) => self.hash_ty(ty), + GenericArg::Type(ty) => self.hash_ty(ty), GenericArg::Const(ref ca) => self.hash_body(ca.value.body), GenericArg::Infer(ref inf) => self.hash_ty(&inf.to_ty()), } diff --git a/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index 3cf043f22df5d..bdb858e1f9384 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/clippy_utils/src/lib.rs @@ -1031,12 +1031,12 @@ pub fn can_move_expr_to_closure<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<' v.allow_closure.then_some(v.captures) } +/// Arguments of a method: the receiver and all the additional arguments. +pub type MethodArguments<'tcx> = Vec<(&'tcx Expr<'tcx>, &'tcx [Expr<'tcx>])>; + /// Returns the method names and argument list of nested method call expressions that make up /// `expr`. method/span lists are sorted with the most recent call first. -pub fn method_calls<'tcx>( - expr: &'tcx Expr<'tcx>, - max_depth: usize, -) -> (Vec, Vec<(&'tcx Expr<'tcx>, &'tcx [Expr<'tcx>])>, Vec) { +pub fn method_calls<'tcx>(expr: &'tcx Expr<'tcx>, max_depth: usize) -> (Vec, MethodArguments<'tcx>, Vec) { let mut method_names = Vec::with_capacity(max_depth); let mut arg_lists = Vec::with_capacity(max_depth); let mut spans = Vec::with_capacity(max_depth); diff --git a/src/tools/clippy/clippy_utils/src/macros.rs b/src/tools/clippy/clippy_utils/src/macros.rs index 43e53f3feebd3..bd89ff977f877 100644 --- a/src/tools/clippy/clippy_utils/src/macros.rs +++ b/src/tools/clippy/clippy_utils/src/macros.rs @@ -389,8 +389,10 @@ impl FormatString { }; let mut unescaped = String::with_capacity(inner.len()); - unescape_literal(inner, mode, &mut |_, ch| { - unescaped.push(ch.unwrap()); + unescape_literal(inner, mode, &mut |_, ch| match ch { + Ok(ch) => unescaped.push(ch), + Err(e) if !e.is_fatal() => (), + Err(e) => panic!("{:?}", e), }); let mut parts = Vec::new(); diff --git a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs index b22a9c817460d..d5f64e5118f56 100644 --- a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs +++ b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs @@ -6,8 +6,8 @@ use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle::mir::{ - Body, CastKind, NullOp, Operand, Place, ProjectionElem, Rvalue, Statement, StatementKind, Terminator, - TerminatorKind, NonDivergingIntrinsic + Body, CastKind, NonDivergingIntrinsic, NullOp, Operand, Place, ProjectionElem, Rvalue, Statement, StatementKind, + Terminator, TerminatorKind, }; use rustc_middle::ty::subst::GenericArgKind; use rustc_middle::ty::{self, adjustment::PointerCast, Ty, TyCtxt}; @@ -212,9 +212,7 @@ fn check_statement<'tcx>( check_place(tcx, **place, span, body) }, - StatementKind::Intrinsic(box NonDivergingIntrinsic::Assume(op)) => { - check_operand(tcx, op, span, body) - }, + StatementKind::Intrinsic(box NonDivergingIntrinsic::Assume(op)) => check_operand(tcx, op, span, body), StatementKind::Intrinsic(box NonDivergingIntrinsic::CopyNonOverlapping( rustc_middle::mir::CopyNonOverlapping { dst, src, count }, diff --git a/src/tools/clippy/clippy_utils/src/visitors.rs b/src/tools/clippy/clippy_utils/src/visitors.rs index 6a62002a4d12e..232d571902b6c 100644 --- a/src/tools/clippy/clippy_utils/src/visitors.rs +++ b/src/tools/clippy/clippy_utils/src/visitors.rs @@ -274,7 +274,7 @@ pub fn is_res_used(cx: &LateContext<'_>, res: Res, body: BodyId) -> bool { } !found }) - .visit_expr(&cx.tcx.hir().body(body).value); + .visit_expr(cx.tcx.hir().body(body).value); found } @@ -568,6 +568,7 @@ pub fn for_each_local_use_after_expr<'tcx, B>( // Calls the given function for every unconsumed temporary created by the expression. Note the // function is only guaranteed to be called for types which need to be dropped, but it may be called // for other types. +#[allow(clippy::too_many_lines)] pub fn for_each_unconsumed_temporary<'tcx, B>( cx: &LateContext<'tcx>, e: &'tcx Expr<'tcx>, diff --git a/src/tools/clippy/lintcheck/lintcheck_crates.toml b/src/tools/clippy/lintcheck/lintcheck_crates.toml index 4fbae8614ca3d..ebbe9c9ae675f 100644 --- a/src/tools/clippy/lintcheck/lintcheck_crates.toml +++ b/src/tools/clippy/lintcheck/lintcheck_crates.toml @@ -1,6 +1,6 @@ [crates] # some of these are from cargotest -cargo = {name = "cargo", versions = ['0.49.0']} +cargo = {name = "cargo", versions = ['0.64.0']} iron = {name = "iron", versions = ['0.6.1']} ripgrep = {name = "ripgrep", versions = ['12.1.1']} xsv = {name = "xsv", versions = ['0.13.0']} diff --git a/src/tools/clippy/rust-toolchain b/src/tools/clippy/rust-toolchain index 85b60fefd60fc..b6976366dafc9 100644 --- a/src/tools/clippy/rust-toolchain +++ b/src/tools/clippy/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2022-08-27" +channel = "nightly-2022-09-08" components = ["cargo", "llvm-tools-preview", "rust-src", "rust-std", "rustc", "rustc-dev", "rustfmt"] diff --git a/src/tools/clippy/src/docs.rs b/src/tools/clippy/src/docs.rs new file mode 100644 index 0000000000000..f3a5048e7fa82 --- /dev/null +++ b/src/tools/clippy/src/docs.rs @@ -0,0 +1,596 @@ +// autogenerated. Please look at /clippy_dev/src/update_lints.rs + +macro_rules! include_lint { + ($file_name: expr) => { + include_str!($file_name) + }; +} + +macro_rules! docs { + ($($lint_name: expr,)*) => { + pub fn explain(lint: &str) { + println!("{}", match lint { + $( + $lint_name => include_lint!(concat!("docs/", concat!($lint_name, ".txt"))), + )* + _ => "unknown lint", + }) + } + } +} + +docs! { + "absurd_extreme_comparisons", + "alloc_instead_of_core", + "allow_attributes_without_reason", + "almost_complete_letter_range", + "almost_swapped", + "approx_constant", + "arithmetic_side_effects", + "as_conversions", + "as_underscore", + "assertions_on_constants", + "assertions_on_result_states", + "assign_op_pattern", + "async_yields_async", + "await_holding_invalid_type", + "await_holding_lock", + "await_holding_refcell_ref", + "bad_bit_mask", + "bind_instead_of_map", + "blanket_clippy_restriction_lints", + "blocks_in_if_conditions", + "bool_assert_comparison", + "bool_comparison", + "bool_to_int_with_if", + "borrow_as_ptr", + "borrow_deref_ref", + "borrow_interior_mutable_const", + "borrowed_box", + "box_collection", + "boxed_local", + "branches_sharing_code", + "builtin_type_shadow", + "bytes_count_to_len", + "bytes_nth", + "cargo_common_metadata", + "case_sensitive_file_extension_comparisons", + "cast_abs_to_unsigned", + "cast_enum_constructor", + "cast_enum_truncation", + "cast_lossless", + "cast_possible_truncation", + "cast_possible_wrap", + "cast_precision_loss", + "cast_ptr_alignment", + "cast_ref_to_mut", + "cast_sign_loss", + "cast_slice_different_sizes", + "cast_slice_from_raw_parts", + "char_lit_as_u8", + "chars_last_cmp", + "chars_next_cmp", + "checked_conversions", + "clone_double_ref", + "clone_on_copy", + "clone_on_ref_ptr", + "cloned_instead_of_copied", + "cmp_nan", + "cmp_null", + "cmp_owned", + "cognitive_complexity", + "collapsible_else_if", + "collapsible_if", + "collapsible_match", + "collapsible_str_replace", + "comparison_chain", + "comparison_to_empty", + "copy_iterator", + "crate_in_macro_def", + "create_dir", + "crosspointer_transmute", + "dbg_macro", + "debug_assert_with_mut_call", + "decimal_literal_representation", + "declare_interior_mutable_const", + "default_instead_of_iter_empty", + "default_numeric_fallback", + "default_trait_access", + "default_union_representation", + "deprecated_cfg_attr", + "deprecated_semver", + "deref_addrof", + "deref_by_slicing", + "derivable_impls", + "derive_hash_xor_eq", + "derive_ord_xor_partial_ord", + "derive_partial_eq_without_eq", + "disallowed_methods", + "disallowed_names", + "disallowed_script_idents", + "disallowed_types", + "diverging_sub_expression", + "doc_link_with_quotes", + "doc_markdown", + "double_comparisons", + "double_must_use", + "double_neg", + "double_parens", + "drop_copy", + "drop_non_drop", + "drop_ref", + "duplicate_mod", + "duplicate_underscore_argument", + "duration_subsec", + "else_if_without_else", + "empty_drop", + "empty_enum", + "empty_line_after_outer_attr", + "empty_loop", + "empty_structs_with_brackets", + "enum_clike_unportable_variant", + "enum_glob_use", + "enum_variant_names", + "eq_op", + "equatable_if_let", + "erasing_op", + "err_expect", + "excessive_precision", + "exhaustive_enums", + "exhaustive_structs", + "exit", + "expect_fun_call", + "expect_used", + "expl_impl_clone_on_copy", + "explicit_auto_deref", + "explicit_counter_loop", + "explicit_deref_methods", + "explicit_into_iter_loop", + "explicit_iter_loop", + "explicit_write", + "extend_with_drain", + "extra_unused_lifetimes", + "fallible_impl_from", + "field_reassign_with_default", + "filetype_is_file", + "filter_map_identity", + "filter_map_next", + "filter_next", + "flat_map_identity", + "flat_map_option", + "float_arithmetic", + "float_cmp", + "float_cmp_const", + "float_equality_without_abs", + "fn_address_comparisons", + "fn_params_excessive_bools", + "fn_to_numeric_cast", + "fn_to_numeric_cast_any", + "fn_to_numeric_cast_with_truncation", + "for_kv_map", + "for_loops_over_fallibles", + "forget_copy", + "forget_non_drop", + "forget_ref", + "format_in_format_args", + "format_push_string", + "from_iter_instead_of_collect", + "from_over_into", + "from_str_radix_10", + "future_not_send", + "get_first", + "get_last_with_len", + "get_unwrap", + "identity_op", + "if_let_mutex", + "if_not_else", + "if_same_then_else", + "if_then_some_else_none", + "ifs_same_cond", + "implicit_clone", + "implicit_hasher", + "implicit_return", + "implicit_saturating_sub", + "imprecise_flops", + "inconsistent_digit_grouping", + "inconsistent_struct_constructor", + "index_refutable_slice", + "indexing_slicing", + "ineffective_bit_mask", + "inefficient_to_string", + "infallible_destructuring_match", + "infinite_iter", + "inherent_to_string", + "inherent_to_string_shadow_display", + "init_numbered_fields", + "inline_always", + "inline_asm_x86_att_syntax", + "inline_asm_x86_intel_syntax", + "inline_fn_without_body", + "inspect_for_each", + "int_plus_one", + "integer_arithmetic", + "integer_division", + "into_iter_on_ref", + "invalid_null_ptr_usage", + "invalid_regex", + "invalid_upcast_comparisons", + "invalid_utf8_in_unchecked", + "invisible_characters", + "is_digit_ascii_radix", + "items_after_statements", + "iter_cloned_collect", + "iter_count", + "iter_next_loop", + "iter_next_slice", + "iter_not_returning_iterator", + "iter_nth", + "iter_nth_zero", + "iter_on_empty_collections", + "iter_on_single_items", + "iter_overeager_cloned", + "iter_skip_next", + "iter_with_drain", + "iterator_step_by_zero", + "just_underscores_and_digits", + "large_const_arrays", + "large_digit_groups", + "large_enum_variant", + "large_include_file", + "large_stack_arrays", + "large_types_passed_by_value", + "len_without_is_empty", + "len_zero", + "let_and_return", + "let_underscore_drop", + "let_underscore_lock", + "let_underscore_must_use", + "let_unit_value", + "linkedlist", + "lossy_float_literal", + "macro_use_imports", + "main_recursion", + "manual_assert", + "manual_async_fn", + "manual_bits", + "manual_filter_map", + "manual_find", + "manual_find_map", + "manual_flatten", + "manual_instant_elapsed", + "manual_map", + "manual_memcpy", + "manual_non_exhaustive", + "manual_ok_or", + "manual_range_contains", + "manual_rem_euclid", + "manual_retain", + "manual_saturating_arithmetic", + "manual_split_once", + "manual_str_repeat", + "manual_string_new", + "manual_strip", + "manual_swap", + "manual_unwrap_or", + "many_single_char_names", + "map_clone", + "map_collect_result_unit", + "map_entry", + "map_err_ignore", + "map_flatten", + "map_identity", + "map_unwrap_or", + "match_as_ref", + "match_bool", + "match_like_matches_macro", + "match_on_vec_items", + "match_overlapping_arm", + "match_ref_pats", + "match_result_ok", + "match_same_arms", + "match_single_binding", + "match_str_case_mismatch", + "match_wild_err_arm", + "match_wildcard_for_single_variants", + "maybe_infinite_iter", + "mem_forget", + "mem_replace_option_with_none", + "mem_replace_with_default", + "mem_replace_with_uninit", + "min_max", + "mismatched_target_os", + "mismatching_type_param_order", + "misrefactored_assign_op", + "missing_const_for_fn", + "missing_docs_in_private_items", + "missing_enforced_import_renames", + "missing_errors_doc", + "missing_inline_in_public_items", + "missing_panics_doc", + "missing_safety_doc", + "missing_spin_loop", + "mistyped_literal_suffixes", + "mixed_case_hex_literals", + "mixed_read_write_in_expression", + "mod_module_files", + "module_inception", + "module_name_repetitions", + "modulo_arithmetic", + "modulo_one", + "multi_assignments", + "multiple_crate_versions", + "multiple_inherent_impl", + "must_use_candidate", + "must_use_unit", + "mut_from_ref", + "mut_mut", + "mut_mutex_lock", + "mut_range_bound", + "mutable_key_type", + "mutex_atomic", + "mutex_integer", + "naive_bytecount", + "needless_arbitrary_self_type", + "needless_bitwise_bool", + "needless_bool", + "needless_borrow", + "needless_borrowed_reference", + "needless_collect", + "needless_continue", + "needless_doctest_main", + "needless_for_each", + "needless_late_init", + "needless_lifetimes", + "needless_match", + "needless_option_as_deref", + "needless_option_take", + "needless_parens_on_range_literals", + "needless_pass_by_value", + "needless_question_mark", + "needless_range_loop", + "needless_return", + "needless_splitn", + "needless_update", + "neg_cmp_op_on_partial_ord", + "neg_multiply", + "negative_feature_names", + "never_loop", + "new_ret_no_self", + "new_without_default", + "no_effect", + "no_effect_replace", + "no_effect_underscore_binding", + "non_ascii_literal", + "non_octal_unix_permissions", + "non_send_fields_in_send_ty", + "nonminimal_bool", + "nonsensical_open_options", + "nonstandard_macro_braces", + "not_unsafe_ptr_arg_deref", + "obfuscated_if_else", + "octal_escapes", + "ok_expect", + "only_used_in_recursion", + "op_ref", + "option_as_ref_deref", + "option_env_unwrap", + "option_filter_map", + "option_if_let_else", + "option_map_or_none", + "option_map_unit_fn", + "option_option", + "or_fun_call", + "or_then_unwrap", + "out_of_bounds_indexing", + "overflow_check_conditional", + "overly_complex_bool_expr", + "panic", + "panic_in_result_fn", + "panicking_unwrap", + "partialeq_ne_impl", + "partialeq_to_none", + "path_buf_push_overwrite", + "pattern_type_mismatch", + "positional_named_format_parameters", + "possible_missing_comma", + "precedence", + "print_in_format_impl", + "print_literal", + "print_stderr", + "print_stdout", + "print_with_newline", + "println_empty_string", + "ptr_arg", + "ptr_as_ptr", + "ptr_eq", + "ptr_offset_with_cast", + "pub_use", + "question_mark", + "range_minus_one", + "range_plus_one", + "range_zip_with_len", + "rc_buffer", + "rc_clone_in_vec_init", + "rc_mutex", + "read_zero_byte_vec", + "recursive_format_impl", + "redundant_allocation", + "redundant_clone", + "redundant_closure", + "redundant_closure_call", + "redundant_closure_for_method_calls", + "redundant_else", + "redundant_feature_names", + "redundant_field_names", + "redundant_pattern", + "redundant_pattern_matching", + "redundant_pub_crate", + "redundant_slicing", + "redundant_static_lifetimes", + "ref_binding_to_reference", + "ref_option_ref", + "repeat_once", + "rest_pat_in_fully_bound_structs", + "result_large_err", + "result_map_or_into_option", + "result_map_unit_fn", + "result_unit_err", + "return_self_not_must_use", + "reversed_empty_ranges", + "same_functions_in_if_condition", + "same_item_push", + "same_name_method", + "search_is_some", + "self_assignment", + "self_named_constructors", + "self_named_module_files", + "semicolon_if_nothing_returned", + "separated_literal_suffix", + "serde_api_misuse", + "shadow_reuse", + "shadow_same", + "shadow_unrelated", + "short_circuit_statement", + "should_implement_trait", + "significant_drop_in_scrutinee", + "similar_names", + "single_char_add_str", + "single_char_lifetime_names", + "single_char_pattern", + "single_component_path_imports", + "single_element_loop", + "single_match", + "single_match_else", + "size_of_in_element_count", + "skip_while_next", + "slow_vector_initialization", + "stable_sort_primitive", + "std_instead_of_alloc", + "std_instead_of_core", + "str_to_string", + "string_add", + "string_add_assign", + "string_extend_chars", + "string_from_utf8_as_bytes", + "string_lit_as_bytes", + "string_slice", + "string_to_string", + "strlen_on_c_strings", + "struct_excessive_bools", + "suboptimal_flops", + "suspicious_arithmetic_impl", + "suspicious_assignment_formatting", + "suspicious_else_formatting", + "suspicious_map", + "suspicious_op_assign_impl", + "suspicious_operation_groupings", + "suspicious_splitn", + "suspicious_to_owned", + "suspicious_unary_op_formatting", + "swap_ptr_to_ref", + "tabs_in_doc_comments", + "temporary_assignment", + "to_digit_is_some", + "to_string_in_format_args", + "todo", + "too_many_arguments", + "too_many_lines", + "toplevel_ref_arg", + "trailing_empty_array", + "trait_duplication_in_bounds", + "transmute_bytes_to_str", + "transmute_float_to_int", + "transmute_int_to_bool", + "transmute_int_to_char", + "transmute_int_to_float", + "transmute_num_to_bytes", + "transmute_ptr_to_ptr", + "transmute_ptr_to_ref", + "transmute_undefined_repr", + "transmutes_expressible_as_ptr_casts", + "transmuting_null", + "trim_split_whitespace", + "trivial_regex", + "trivially_copy_pass_by_ref", + "try_err", + "type_complexity", + "type_repetition_in_bounds", + "undocumented_unsafe_blocks", + "undropped_manually_drops", + "unicode_not_nfc", + "unimplemented", + "uninit_assumed_init", + "uninit_vec", + "unit_arg", + "unit_cmp", + "unit_hash", + "unit_return_expecting_ord", + "unnecessary_cast", + "unnecessary_filter_map", + "unnecessary_find_map", + "unnecessary_fold", + "unnecessary_join", + "unnecessary_lazy_evaluations", + "unnecessary_mut_passed", + "unnecessary_operation", + "unnecessary_owned_empty_strings", + "unnecessary_self_imports", + "unnecessary_sort_by", + "unnecessary_to_owned", + "unnecessary_unwrap", + "unnecessary_wraps", + "unneeded_field_pattern", + "unneeded_wildcard_pattern", + "unnested_or_patterns", + "unreachable", + "unreadable_literal", + "unsafe_derive_deserialize", + "unsafe_removed_from_name", + "unseparated_literal_suffix", + "unsound_collection_transmute", + "unused_async", + "unused_io_amount", + "unused_peekable", + "unused_rounding", + "unused_self", + "unused_unit", + "unusual_byte_groupings", + "unwrap_in_result", + "unwrap_or_else_default", + "unwrap_used", + "upper_case_acronyms", + "use_debug", + "use_self", + "used_underscore_binding", + "useless_asref", + "useless_attribute", + "useless_conversion", + "useless_format", + "useless_let_if_seq", + "useless_transmute", + "useless_vec", + "vec_box", + "vec_init_then_push", + "vec_resize_to_zero", + "verbose_bit_mask", + "verbose_file_reads", + "vtable_address_comparisons", + "while_immutable_condition", + "while_let_loop", + "while_let_on_iterator", + "wildcard_dependencies", + "wildcard_enum_match_arm", + "wildcard_imports", + "wildcard_in_or_patterns", + "write_literal", + "write_with_newline", + "writeln_empty_string", + "wrong_self_convention", + "wrong_transmute", + "zero_divided_by_zero", + "zero_prefixed_literal", + "zero_ptr", + "zero_sized_map_values", + "zst_offset", + +} diff --git a/src/tools/clippy/src/docs/absurd_extreme_comparisons.txt b/src/tools/clippy/src/docs/absurd_extreme_comparisons.txt new file mode 100644 index 0000000000000..590bee28aa237 --- /dev/null +++ b/src/tools/clippy/src/docs/absurd_extreme_comparisons.txt @@ -0,0 +1,25 @@ +### What it does +Checks for comparisons where one side of the relation is +either the minimum or maximum value for its type and warns if it involves a +case that is always true or always false. Only integer and boolean types are +checked. + +### Why is this bad? +An expression like `min <= x` may misleadingly imply +that it is possible for `x` to be less than the minimum. Expressions like +`max < x` are probably mistakes. + +### Known problems +For `usize` the size of the current compile target will +be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such +a comparison to detect target pointer width will trigger this lint. One can +use `mem::sizeof` and compare its value or conditional compilation +attributes +like `#[cfg(target_pointer_width = "64")] ..` instead. + +### Example +``` +let vec: Vec = Vec::new(); +if vec.len() <= 0 {} +if 100 > i32::MAX {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/alloc_instead_of_core.txt b/src/tools/clippy/src/docs/alloc_instead_of_core.txt new file mode 100644 index 0000000000000..488a36e9276c2 --- /dev/null +++ b/src/tools/clippy/src/docs/alloc_instead_of_core.txt @@ -0,0 +1,18 @@ +### What it does + +Finds items imported through `alloc` when available through `core`. + +### Why is this bad? + +Crates which have `no_std` compatibility and may optionally require alloc may wish to ensure types are +imported from core to ensure disabling `alloc` does not cause the crate to fail to compile. This lint +is also useful for crates migrating to become `no_std` compatible. + +### Example +``` +use alloc::slice::from_ref; +``` +Use instead: +``` +use core::slice::from_ref; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/allow_attributes_without_reason.txt b/src/tools/clippy/src/docs/allow_attributes_without_reason.txt new file mode 100644 index 0000000000000..fcc4f49b08b37 --- /dev/null +++ b/src/tools/clippy/src/docs/allow_attributes_without_reason.txt @@ -0,0 +1,22 @@ +### What it does +Checks for attributes that allow lints without a reason. + +(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 + +### Example +``` +#![feature(lint_reasons)] + +#![allow(clippy::some_lint)] +``` + +Use instead: +``` +#![feature(lint_reasons)] + +#![allow(clippy::some_lint, reason = "False positive rust-lang/rust-clippy#1002020")] +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/almost_complete_letter_range.txt b/src/tools/clippy/src/docs/almost_complete_letter_range.txt new file mode 100644 index 0000000000000..01cbaf9eae259 --- /dev/null +++ b/src/tools/clippy/src/docs/almost_complete_letter_range.txt @@ -0,0 +1,15 @@ +### What it does +Checks for ranges which almost include the entire range of letters from 'a' to 'z', but +don't because they're a half open range. + +### Why is this bad? +This (`'a'..'z'`) is almost certainly a typo meant to include all letters. + +### Example +``` +let _ = 'a'..'z'; +``` +Use instead: +``` +let _ = 'a'..='z'; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/almost_swapped.txt b/src/tools/clippy/src/docs/almost_swapped.txt new file mode 100644 index 0000000000000..cd10a8d5409b1 --- /dev/null +++ b/src/tools/clippy/src/docs/almost_swapped.txt @@ -0,0 +1,15 @@ +### What it does +Checks for `foo = bar; bar = foo` sequences. + +### Why is this bad? +This looks like a failed attempt to swap. + +### Example +``` +a = b; +b = a; +``` +If swapping is intended, use `swap()` instead: +``` +std::mem::swap(&mut a, &mut b); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/approx_constant.txt b/src/tools/clippy/src/docs/approx_constant.txt new file mode 100644 index 0000000000000..393fa4b5ef7ec --- /dev/null +++ b/src/tools/clippy/src/docs/approx_constant.txt @@ -0,0 +1,24 @@ +### What it does +Checks for floating point literals that approximate +constants which are defined in +[`std::f32::consts`](https://doc.rust-lang.org/stable/std/f32/consts/#constants) +or +[`std::f64::consts`](https://doc.rust-lang.org/stable/std/f64/consts/#constants), +respectively, suggesting to use the predefined constant. + +### Why is this bad? +Usually, the definition in the standard library is more +precise than what people come up with. If you find that your definition is +actually more precise, please [file a Rust +issue](https://github.com/rust-lang/rust/issues). + +### Example +``` +let x = 3.14; +let y = 1_f64 / x; +``` +Use instead: +``` +let x = std::f32::consts::PI; +let y = std::f64::consts::FRAC_1_PI; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/arithmetic_side_effects.txt b/src/tools/clippy/src/docs/arithmetic_side_effects.txt new file mode 100644 index 0000000000000..6c7d51a4989e0 --- /dev/null +++ b/src/tools/clippy/src/docs/arithmetic_side_effects.txt @@ -0,0 +1,33 @@ +### What it does +Checks any kind of arithmetic operation of any type. + +Operators like `+`, `-`, `*` or `<<` are usually capable of overflowing according to the [Rust +Reference](https://doc.rust-lang.org/reference/expressions/operator-expr.html#overflow), +or can panic (`/`, `%`). + +Known safe built-in types like `Wrapping` or `Saturing`, floats, operations in constant +environments, allowed types and non-constant operations that won't overflow are ignored. + +### Why is this bad? +For integers, overflow will trigger a panic in debug builds or wrap the result in +release mode; division by zero will cause a panic in either mode. As a result, it is +desirable to explicitly call checked, wrapping or saturating arithmetic methods. + +#### Example +``` +// `n` can be any number, including `i32::MAX`. +fn foo(n: i32) -> i32 { + n + 1 +} +``` + +Third-party types can also overflow or present unwanted side-effects. + +#### Example +``` +use rust_decimal::Decimal; +let _n = Decimal::MAX + Decimal::MAX; +``` + +### Allowed types +Custom allowed types can be specified through the "arithmetic-side-effects-allowed" filter. \ No newline at end of file diff --git a/src/tools/clippy/src/docs/as_conversions.txt b/src/tools/clippy/src/docs/as_conversions.txt new file mode 100644 index 0000000000000..4af479bd8111c --- /dev/null +++ b/src/tools/clippy/src/docs/as_conversions.txt @@ -0,0 +1,32 @@ +### What it does +Checks for usage of `as` conversions. + +Note that this lint is specialized in linting *every single* use of `as` +regardless of whether good alternatives exist or not. +If you want more precise lints for `as`, please consider using these separate lints: +`unnecessary_cast`, `cast_lossless/cast_possible_truncation/cast_possible_wrap/cast_precision_loss/cast_sign_loss`, +`fn_to_numeric_cast(_with_truncation)`, `char_lit_as_u8`, `ref_to_mut` and `ptr_as_ptr`. +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? +`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 +Allow by default. + +### Example +``` +let a: u32; +... +f(a as u16); +``` + +Use instead: +``` +f(a.try_into()?); + +// or + +f(a.try_into().expect("Unexpected u16 overflow in f")); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/as_underscore.txt b/src/tools/clippy/src/docs/as_underscore.txt new file mode 100644 index 0000000000000..2d9b0c358936b --- /dev/null +++ b/src/tools/clippy/src/docs/as_underscore.txt @@ -0,0 +1,21 @@ +### What it does +Check 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 +undetected due to the type being inferred. + +The lint is allowed by default as using `_` is less wordy than always specifying the type. + +### Example +``` +fn foo(n: usize) {} +let n: u16 = 256; +foo(n as _); +``` +Use instead: +``` +fn foo(n: usize) {} +let n: u16 = 256; +foo(n as usize); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/assertions_on_constants.txt b/src/tools/clippy/src/docs/assertions_on_constants.txt new file mode 100644 index 0000000000000..270c1e3b639d9 --- /dev/null +++ b/src/tools/clippy/src/docs/assertions_on_constants.txt @@ -0,0 +1,14 @@ +### What it does +Checks for `assert!(true)` and `assert!(false)` calls. + +### Why is this bad? +Will be optimized out by the compiler or should probably be replaced by a +`panic!()` or `unreachable!()` + +### Example +``` +assert!(false) +assert!(true) +const B: bool = false; +assert!(B) +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/assertions_on_result_states.txt b/src/tools/clippy/src/docs/assertions_on_result_states.txt new file mode 100644 index 0000000000000..0889084fd3ad6 --- /dev/null +++ b/src/tools/clippy/src/docs/assertions_on_result_states.txt @@ -0,0 +1,14 @@ +### 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. + +### Known problems +The suggested replacement decreases the readability of code and log output. + +### Example +``` +assert!(r.is_ok()); +assert!(r.is_err()); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/assign_op_pattern.txt b/src/tools/clippy/src/docs/assign_op_pattern.txt new file mode 100644 index 0000000000000..f355c0cc18d37 --- /dev/null +++ b/src/tools/clippy/src/docs/assign_op_pattern.txt @@ -0,0 +1,28 @@ +### What it does +Checks for `a = a op b` or `a = b commutative_op a` +patterns. + +### Why is this bad? +These can be written as the shorter `a op= b`. + +### Known problems +While forbidden by the spec, `OpAssign` traits may have +implementations that differ from the regular `Op` impl. + +### Example +``` +let mut a = 5; +let b = 0; +// ... + +a = a + b; +``` + +Use instead: +``` +let mut a = 5; +let b = 0; +// ... + +a += b; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/async_yields_async.txt b/src/tools/clippy/src/docs/async_yields_async.txt new file mode 100644 index 0000000000000..a40de6d2e4736 --- /dev/null +++ b/src/tools/clippy/src/docs/async_yields_async.txt @@ -0,0 +1,28 @@ +### What it does +Checks for async blocks that yield values of types +that can themselves be awaited. + +### Why is this bad? +An await is likely missing. + +### Example +``` +async fn foo() {} + +fn bar() { + let x = async { + foo() + }; +} +``` + +Use instead: +``` +async fn foo() {} + +fn bar() { + let x = async { + foo().await + }; +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/await_holding_invalid_type.txt b/src/tools/clippy/src/docs/await_holding_invalid_type.txt new file mode 100644 index 0000000000000..e9c768772ff6b --- /dev/null +++ b/src/tools/clippy/src/docs/await_holding_invalid_type.txt @@ -0,0 +1,29 @@ +### What it does +Allows users to configure types which should not be held across `await` +suspension points. + +### Why is this bad? +There are some types which are perfectly "safe" to be used concurrently +from a memory access perspective but will cause bugs at runtime if they +are held in such a way. + +### Example + +``` +await-holding-invalid-types = [ + # You can specify a type name + "CustomLockType", + # You can (optionally) specify a reason + { path = "OtherCustomLockType", reason = "Relies on a thread local" } +] +``` + +``` +struct CustomLockType; +struct OtherCustomLockType; +async fn foo() { + let _x = CustomLockType; + let _y = OtherCustomLockType; + baz().await; // Lint violation +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/await_holding_lock.txt b/src/tools/clippy/src/docs/await_holding_lock.txt new file mode 100644 index 0000000000000..0f450a11160cc --- /dev/null +++ b/src/tools/clippy/src/docs/await_holding_lock.txt @@ -0,0 +1,51 @@ +### What it does +Checks for calls to await while holding a non-async-aware MutexGuard. + +### Why is this bad? +The Mutex types found in std::sync and parking_lot +are not designed to operate in an async context across await points. + +There are two potential solutions. One is to use an async-aware Mutex +type. Many asynchronous foundation crates provide such a Mutex type. The +other solution is to ensure the mutex is unlocked before calling await, +either by introducing a scope or an explicit call to Drop::drop. + +### Known problems +Will report false positive for explicitly dropped guards +([#6446](https://github.com/rust-lang/rust-clippy/issues/6446)). A workaround for this is +to wrap the `.lock()` call in a block instead of explicitly dropping the guard. + +### Example +``` +async fn foo(x: &Mutex) { + let mut guard = x.lock().unwrap(); + *guard += 1; + baz().await; +} + +async fn bar(x: &Mutex) { + let mut guard = x.lock().unwrap(); + *guard += 1; + drop(guard); // explicit drop + baz().await; +} +``` + +Use instead: +``` +async fn foo(x: &Mutex) { + { + let mut guard = x.lock().unwrap(); + *guard += 1; + } + baz().await; +} + +async fn bar(x: &Mutex) { + { + let mut guard = x.lock().unwrap(); + *guard += 1; + } // guard dropped here at end of scope + baz().await; +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/await_holding_refcell_ref.txt b/src/tools/clippy/src/docs/await_holding_refcell_ref.txt new file mode 100644 index 0000000000000..226a261b9cc52 --- /dev/null +++ b/src/tools/clippy/src/docs/await_holding_refcell_ref.txt @@ -0,0 +1,47 @@ +### What it does +Checks for calls to await while holding a `RefCell` `Ref` or `RefMut`. + +### Why is this bad? +`RefCell` refs only check for exclusive mutable access +at runtime. Holding onto a `RefCell` ref across an `await` suspension point +risks panics from a mutable ref shared while other refs are outstanding. + +### Known problems +Will report false positive for explicitly dropped refs +([#6353](https://github.com/rust-lang/rust-clippy/issues/6353)). A workaround for this is +to wrap the `.borrow[_mut]()` call in a block instead of explicitly dropping the ref. + +### Example +``` +async fn foo(x: &RefCell) { + let mut y = x.borrow_mut(); + *y += 1; + baz().await; +} + +async fn bar(x: &RefCell) { + let mut y = x.borrow_mut(); + *y += 1; + drop(y); // explicit drop + baz().await; +} +``` + +Use instead: +``` +async fn foo(x: &RefCell) { + { + let mut y = x.borrow_mut(); + *y += 1; + } + baz().await; +} + +async fn bar(x: &RefCell) { + { + let mut y = x.borrow_mut(); + *y += 1; + } // y dropped here at end of scope + baz().await; +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/bad_bit_mask.txt b/src/tools/clippy/src/docs/bad_bit_mask.txt new file mode 100644 index 0000000000000..d40024ee56209 --- /dev/null +++ b/src/tools/clippy/src/docs/bad_bit_mask.txt @@ -0,0 +1,30 @@ +### What it does +Checks for incompatible bit masks in comparisons. + +The formula for detecting if an expression of the type `_ m + c` (where `` is one of {`&`, `|`} and `` is one of +{`!=`, `>=`, `>`, `!=`, `>=`, `>`}) can be determined from the following +table: + +|Comparison |Bit Op|Example |is always|Formula | +|------------|------|-------------|---------|----------------------| +|`==` or `!=`| `&` |`x & 2 == 3` |`false` |`c & m != c` | +|`<` or `>=`| `&` |`x & 2 < 3` |`true` |`m < c` | +|`>` or `<=`| `&` |`x & 1 > 1` |`false` |`m <= c` | +|`==` or `!=`| `\|` |`x \| 1 == 0`|`false` |`c \| m != c` | +|`<` or `>=`| `\|` |`x \| 1 < 1` |`false` |`m >= c` | +|`<=` or `>` | `\|` |`x \| 1 > 0` |`true` |`m > c` | + +### Why is this bad? +If the bits that the comparison cares about are always +set to zero or one by the bit mask, the comparison is constant `true` or +`false` (depending on mask, compared value, and operators). + +So the code is actively misleading, and the only reason someone would write +this intentionally is to win an underhanded Rust contest or create a +test-case for this lint. + +### Example +``` +if (x & 1 == 2) { } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/bind_instead_of_map.txt b/src/tools/clippy/src/docs/bind_instead_of_map.txt new file mode 100644 index 0000000000000..148575803d389 --- /dev/null +++ b/src/tools/clippy/src/docs/bind_instead_of_map.txt @@ -0,0 +1,22 @@ +### What it does +Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or +`_.or_else(|x| Err(y))`. + +### Why is this bad? +Readability, this can be written more concisely as +`_.map(|x| y)` or `_.map_err(|x| y)`. + +### Example +``` +let _ = opt().and_then(|s| Some(s.len())); +let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) }); +let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) }); +``` + +The correct use would be: + +``` +let _ = opt().map(|s| s.len()); +let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 }); +let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 }); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/blanket_clippy_restriction_lints.txt b/src/tools/clippy/src/docs/blanket_clippy_restriction_lints.txt new file mode 100644 index 0000000000000..28a4ebf7169bf --- /dev/null +++ b/src/tools/clippy/src/docs/blanket_clippy_restriction_lints.txt @@ -0,0 +1,16 @@ +### What it does +Checks for `warn`/`deny`/`forbid` attributes targeting the whole clippy::restriction category. + +### Why is this bad? +Restriction lints sometimes are in contrast with other lints or even go against idiomatic rust. +These lints should only be enabled on a lint-by-lint basis and with careful consideration. + +### Example +``` +#![deny(clippy::restriction)] +``` + +Use instead: +``` +#![deny(clippy::as_conversions)] +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/blocks_in_if_conditions.txt b/src/tools/clippy/src/docs/blocks_in_if_conditions.txt new file mode 100644 index 0000000000000..3afa14853fd21 --- /dev/null +++ b/src/tools/clippy/src/docs/blocks_in_if_conditions.txt @@ -0,0 +1,21 @@ +### What it does +Checks for `if` conditions that use blocks containing an +expression, statements or conditions that use closures with blocks. + +### Why is this bad? +Style, using blocks in the condition makes it hard to read. + +### Examples +``` +if { true } { /* ... */ } + +if { let x = somefunc(); x } { /* ... */ } +``` + +Use instead: +``` +if true { /* ... */ } + +let res = { let x = somefunc(); x }; +if res { /* ... */ } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/bool_assert_comparison.txt b/src/tools/clippy/src/docs/bool_assert_comparison.txt new file mode 100644 index 0000000000000..df7ca00cc2ba4 --- /dev/null +++ b/src/tools/clippy/src/docs/bool_assert_comparison.txt @@ -0,0 +1,16 @@ +### What it does +This lint warns about boolean comparisons in assert-like macros. + +### Why is this bad? +It is shorter to use the equivalent. + +### Example +``` +assert_eq!("a".is_empty(), false); +assert_ne!("a".is_empty(), true); +``` + +Use instead: +``` +assert!(!"a".is_empty()); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/bool_comparison.txt b/src/tools/clippy/src/docs/bool_comparison.txt new file mode 100644 index 0000000000000..0996f60cec44c --- /dev/null +++ b/src/tools/clippy/src/docs/bool_comparison.txt @@ -0,0 +1,18 @@ +### What it does +Checks for expressions of the form `x == true`, +`x != true` and order comparisons such as `x < true` (or vice versa) and +suggest using the variable directly. + +### Why is this bad? +Unnecessary code. + +### Example +``` +if x == true {} +if y == false {} +``` +use `x` directly: +``` +if x {} +if !y {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/bool_to_int_with_if.txt b/src/tools/clippy/src/docs/bool_to_int_with_if.txt new file mode 100644 index 0000000000000..63535b454c9f1 --- /dev/null +++ b/src/tools/clippy/src/docs/bool_to_int_with_if.txt @@ -0,0 +1,26 @@ +### What it does +Instead of using an if statement to convert a bool to an int, +this lint suggests using a `from()` function or an `as` coercion. + +### Why is this bad? +Coercion or `from()` is idiomatic way to convert bool to a number. +Both methods are guaranteed to return 1 for true, and 0 for false. + +See https://doc.rust-lang.org/std/primitive.bool.html#impl-From%3Cbool%3E + +### Example +``` +if condition { + 1_i64 +} else { + 0 +}; +``` +Use instead: +``` +i64::from(condition); +``` +or +``` +condition as i64; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/borrow_as_ptr.txt b/src/tools/clippy/src/docs/borrow_as_ptr.txt new file mode 100644 index 0000000000000..0be865abd5780 --- /dev/null +++ b/src/tools/clippy/src/docs/borrow_as_ptr.txt @@ -0,0 +1,26 @@ +### What it does +Checks for the usage of `&expr as *const T` or +`&mut expr as *mut T`, and suggest using `ptr::addr_of` or +`ptr::addr_of_mut` instead. + +### Why is this bad? +This would improve readability and avoid creating a reference +that points to an uninitialized value or unaligned place. +Read the `ptr::addr_of` docs for more information. + +### Example +``` +let val = 1; +let p = &val as *const i32; + +let mut val_mut = 1; +let p_mut = &mut val_mut as *mut i32; +``` +Use instead: +``` +let val = 1; +let p = std::ptr::addr_of!(val); + +let mut val_mut = 1; +let p_mut = std::ptr::addr_of_mut!(val_mut); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/borrow_deref_ref.txt b/src/tools/clippy/src/docs/borrow_deref_ref.txt new file mode 100644 index 0000000000000..352480d3f26a7 --- /dev/null +++ b/src/tools/clippy/src/docs/borrow_deref_ref.txt @@ -0,0 +1,27 @@ +### What it does +Checks for `&*(&T)`. + +### Why is this bad? +Dereferencing and then borrowing a reference value has no effect in most cases. + +### Known problems +False negative on such code: +``` +let x = &12; +let addr_x = &x as *const _ as usize; +let addr_y = &&*x as *const _ as usize; // assert ok now, and lint triggered. + // But if we fix it, assert will fail. +assert_ne!(addr_x, addr_y); +``` + +### Example +``` +let s = &String::new(); + +let a: &String = &* s; +``` + +Use instead: +``` +let a: &String = s; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/borrow_interior_mutable_const.txt b/src/tools/clippy/src/docs/borrow_interior_mutable_const.txt new file mode 100644 index 0000000000000..e55b6a77e6667 --- /dev/null +++ b/src/tools/clippy/src/docs/borrow_interior_mutable_const.txt @@ -0,0 +1,40 @@ +### What it does +Checks if `const` items which is interior mutable (e.g., +contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.) has been borrowed directly. + +### Why is this bad? +Consts are copied everywhere they are referenced, i.e., +every time you refer to the const a fresh instance of the `Cell` or `Mutex` +or `AtomicXxxx` will be created, which defeats the whole purpose of using +these types in the first place. + +The `const` value should be stored inside a `static` item. + +### Known problems +When an enum has variants with interior mutability, use of its non +interior mutable variants can generate false positives. See issue +[#3962](https://github.com/rust-lang/rust-clippy/issues/3962) + +Types that have underlying or potential interior mutability trigger the lint whether +the interior mutable field is used or not. See issues +[#5812](https://github.com/rust-lang/rust-clippy/issues/5812) and +[#3825](https://github.com/rust-lang/rust-clippy/issues/3825) + +### Example +``` +use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; +const CONST_ATOM: AtomicUsize = AtomicUsize::new(12); + +CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged +assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct +``` + +Use instead: +``` +use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; +const CONST_ATOM: AtomicUsize = AtomicUsize::new(12); + +static STATIC_ATOM: AtomicUsize = CONST_ATOM; +STATIC_ATOM.store(9, SeqCst); +assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/borrowed_box.txt b/src/tools/clippy/src/docs/borrowed_box.txt new file mode 100644 index 0000000000000..d7089be662a58 --- /dev/null +++ b/src/tools/clippy/src/docs/borrowed_box.txt @@ -0,0 +1,19 @@ +### What it does +Checks for use of `&Box` anywhere in the code. +Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information. + +### Why is this bad? +A `&Box` parameter requires the function caller to box `T` first before passing it to a function. +Using `&T` defines a concrete type for the parameter and generalizes the function, this would also +auto-deref to `&T` at the function call site if passed a `&Box`. + +### Example +``` +fn foo(bar: &Box) { ... } +``` + +Better: + +``` +fn foo(bar: &T) { ... } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/box_collection.txt b/src/tools/clippy/src/docs/box_collection.txt new file mode 100644 index 0000000000000..053f24c46281d --- /dev/null +++ b/src/tools/clippy/src/docs/box_collection.txt @@ -0,0 +1,23 @@ +### What it does +Checks for use of `Box` where T is a collection such as Vec anywhere in the code. +Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information. + +### Why is this bad? +Collections already keeps their contents in a separate area on +the heap. So if you `Box` them, you just add another level of indirection +without any benefit whatsoever. + +### Example +``` +struct X { + values: Box>, +} +``` + +Better: + +``` +struct X { + values: Vec, +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/boxed_local.txt b/src/tools/clippy/src/docs/boxed_local.txt new file mode 100644 index 0000000000000..8b1febf1455fd --- /dev/null +++ b/src/tools/clippy/src/docs/boxed_local.txt @@ -0,0 +1,18 @@ +### What it does +Checks for usage of `Box` where an unboxed `T` would +work fine. + +### Why is this bad? +This is an unnecessary allocation, and bad for +performance. It is only necessary to allocate if you wish to move the box +into something. + +### Example +``` +fn foo(x: Box) {} +``` + +Use instead: +``` +fn foo(x: u32) {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/branches_sharing_code.txt b/src/tools/clippy/src/docs/branches_sharing_code.txt new file mode 100644 index 0000000000000..79be6124798a2 --- /dev/null +++ b/src/tools/clippy/src/docs/branches_sharing_code.txt @@ -0,0 +1,32 @@ +### What it does +Checks if the `if` and `else` block contain shared code that can be +moved out of the blocks. + +### Why is this bad? +Duplicate code is less maintainable. + +### Known problems +* The lint doesn't check if the moved expressions modify values that are being used in + the if condition. The suggestion can in that case modify the behavior of the program. + See [rust-clippy#7452](https://github.com/rust-lang/rust-clippy/issues/7452) + +### Example +``` +let foo = if … { + println!("Hello World"); + 13 +} else { + println!("Hello World"); + 42 +}; +``` + +Use instead: +``` +println!("Hello World"); +let foo = if … { + 13 +} else { + 42 +}; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/builtin_type_shadow.txt b/src/tools/clippy/src/docs/builtin_type_shadow.txt new file mode 100644 index 0000000000000..15b1c9df7baab --- /dev/null +++ b/src/tools/clippy/src/docs/builtin_type_shadow.txt @@ -0,0 +1,15 @@ +### What it does +Warns if a generic shadows a built-in type. + +### Why is this bad? +This gives surprising type errors. + +### Example + +``` +impl Foo { + fn impl_func(&self) -> u32 { + 42 + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/bytes_count_to_len.txt b/src/tools/clippy/src/docs/bytes_count_to_len.txt new file mode 100644 index 0000000000000..ca7bf9a38da8e --- /dev/null +++ b/src/tools/clippy/src/docs/bytes_count_to_len.txt @@ -0,0 +1,18 @@ +### What it does +It checks for `str::bytes().count()` and suggests replacing it with +`str::len()`. + +### Why is this bad? +`str::bytes().count()` is longer and may not be as performant as using +`str::len()`. + +### Example +``` +"hello".bytes().count(); +String::from("hello").bytes().count(); +``` +Use instead: +``` +"hello".len(); +String::from("hello").len(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/bytes_nth.txt b/src/tools/clippy/src/docs/bytes_nth.txt new file mode 100644 index 0000000000000..260de343353d8 --- /dev/null +++ b/src/tools/clippy/src/docs/bytes_nth.txt @@ -0,0 +1,16 @@ +### What it does +Checks for the use of `.bytes().nth()`. + +### Why is this bad? +`.as_bytes().get()` is more efficient and more +readable. + +### Example +``` +"Hello".bytes().nth(3); +``` + +Use instead: +``` +"Hello".as_bytes().get(3); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/cargo_common_metadata.txt b/src/tools/clippy/src/docs/cargo_common_metadata.txt new file mode 100644 index 0000000000000..1998647a92740 --- /dev/null +++ b/src/tools/clippy/src/docs/cargo_common_metadata.txt @@ -0,0 +1,33 @@ +### What it does +Checks to see if all common metadata is defined in +`Cargo.toml`. See: https://rust-lang-nursery.github.io/api-guidelines/documentation.html#cargotoml-includes-all-common-metadata-c-metadata + +### Why is this bad? +It will be more difficult for users to discover the +purpose of the crate, and key information related to it. + +### Example +``` +[package] +name = "clippy" +version = "0.0.212" +repository = "https://github.com/rust-lang/rust-clippy" +readme = "README.md" +license = "MIT OR Apache-2.0" +keywords = ["clippy", "lint", "plugin"] +categories = ["development-tools", "development-tools::cargo-plugins"] +``` + +Should include a description field like: + +``` +[package] +name = "clippy" +version = "0.0.212" +description = "A bunch of helpful lints to avoid common pitfalls in Rust" +repository = "https://github.com/rust-lang/rust-clippy" +readme = "README.md" +license = "MIT OR Apache-2.0" +keywords = ["clippy", "lint", "plugin"] +categories = ["development-tools", "development-tools::cargo-plugins"] +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/case_sensitive_file_extension_comparisons.txt b/src/tools/clippy/src/docs/case_sensitive_file_extension_comparisons.txt new file mode 100644 index 0000000000000..8e6e18ed4e23a --- /dev/null +++ b/src/tools/clippy/src/docs/case_sensitive_file_extension_comparisons.txt @@ -0,0 +1,21 @@ +### What it does +Checks for calls to `ends_with` with possible file extensions +and suggests to use a case-insensitive approach instead. + +### Why is this bad? +`ends_with` is case-sensitive and may not detect files with a valid extension. + +### Example +``` +fn is_rust_file(filename: &str) -> bool { + filename.ends_with(".rs") +} +``` +Use instead: +``` +fn is_rust_file(filename: &str) -> bool { + let filename = std::path::Path::new(filename); + filename.extension() + .map_or(false, |ext| ext.eq_ignore_ascii_case("rs")) +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/cast_abs_to_unsigned.txt b/src/tools/clippy/src/docs/cast_abs_to_unsigned.txt new file mode 100644 index 0000000000000..c5d8ee034ce59 --- /dev/null +++ b/src/tools/clippy/src/docs/cast_abs_to_unsigned.txt @@ -0,0 +1,16 @@ +### What it does +Checks for uses of the `abs()` method that cast the result to unsigned. + +### Why is this bad? +The `unsigned_abs()` method avoids panic when called on the MIN value. + +### Example +``` +let x: i32 = -42; +let y: u32 = x.abs() as u32; +``` +Use instead: +``` +let x: i32 = -42; +let y: u32 = x.unsigned_abs(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/cast_enum_constructor.txt b/src/tools/clippy/src/docs/cast_enum_constructor.txt new file mode 100644 index 0000000000000..675c03a42bc23 --- /dev/null +++ b/src/tools/clippy/src/docs/cast_enum_constructor.txt @@ -0,0 +1,11 @@ +### What it does +Checks for casts from an enum tuple constructor to an integer. + +### Why is this bad? +The cast is easily confused with casting a c-like enum value to an integer. + +### Example +``` +enum E { X(i32) }; +let _ = E::X as usize; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/cast_enum_truncation.txt b/src/tools/clippy/src/docs/cast_enum_truncation.txt new file mode 100644 index 0000000000000..abe32a8296da2 --- /dev/null +++ b/src/tools/clippy/src/docs/cast_enum_truncation.txt @@ -0,0 +1,12 @@ +### What it does +Checks for casts from an enum type to an integral type which will definitely truncate the +value. + +### Why is this bad? +The resulting integral value will not match the value of the variant it came from. + +### Example +``` +enum E { X = 256 }; +let _ = E::X as u8; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/cast_lossless.txt b/src/tools/clippy/src/docs/cast_lossless.txt new file mode 100644 index 0000000000000..c3a61dd470fc9 --- /dev/null +++ b/src/tools/clippy/src/docs/cast_lossless.txt @@ -0,0 +1,26 @@ +### What it does +Checks for casts between numerical types that may +be replaced by safe conversion functions. + +### Why is this bad? +Rust's `as` keyword will perform many kinds of +conversions, including silently lossy conversions. Conversion functions such +as `i32::from` will only perform lossless conversions. Using the conversion +functions prevents conversions from turning into silent lossy conversions if +the types of the input expressions ever change, and make it easier for +people reading the code to know that the conversion is lossless. + +### Example +``` +fn as_u64(x: u8) -> u64 { + x as u64 +} +``` + +Using `::from` would look like this: + +``` +fn as_u64(x: u8) -> u64 { + u64::from(x) +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/cast_possible_truncation.txt b/src/tools/clippy/src/docs/cast_possible_truncation.txt new file mode 100644 index 0000000000000..0b164848cc7c2 --- /dev/null +++ b/src/tools/clippy/src/docs/cast_possible_truncation.txt @@ -0,0 +1,16 @@ +### What it does +Checks for casts between numerical types that may +truncate large values. This is expected behavior, so the cast is `Allow` by +default. + +### Why is this bad? +In some problem domains, it is good practice to avoid +truncation. This lint can be activated to help assess where additional +checks could be beneficial. + +### Example +``` +fn as_u8(x: u64) -> u8 { + x as u8 +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/cast_possible_wrap.txt b/src/tools/clippy/src/docs/cast_possible_wrap.txt new file mode 100644 index 0000000000000..f883fc9cfb994 --- /dev/null +++ b/src/tools/clippy/src/docs/cast_possible_wrap.txt @@ -0,0 +1,17 @@ +### What it does +Checks for casts from an unsigned type to a signed type of +the same size. Performing such a cast is a 'no-op' for the compiler, +i.e., nothing is changed at the bit level, and the binary representation of +the value is reinterpreted. This can cause wrapping if the value is too big +for the target signed type. However, the cast works as defined, so this lint +is `Allow` by default. + +### Why is this bad? +While such a cast is not bad in itself, the results can +be surprising when this is not the intended behavior, as demonstrated by the +example below. + +### Example +``` +u32::MAX as i32; // will yield a value of `-1` +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/cast_precision_loss.txt b/src/tools/clippy/src/docs/cast_precision_loss.txt new file mode 100644 index 0000000000000..f915d9f8a6d0d --- /dev/null +++ b/src/tools/clippy/src/docs/cast_precision_loss.txt @@ -0,0 +1,19 @@ +### What it does +Checks for casts from any numerical to a float type where +the receiving type cannot store all values from the original type without +rounding errors. This possible rounding is to be expected, so this lint is +`Allow` by default. + +Basically, this warns on casting any integer with 32 or more bits to `f32` +or any 64-bit integer to `f64`. + +### Why is this bad? +It's not bad at all. But in some applications it can be +helpful to know where precision loss can take place. This lint can help find +those places in the code. + +### Example +``` +let x = u64::MAX; +x as f64; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/cast_ptr_alignment.txt b/src/tools/clippy/src/docs/cast_ptr_alignment.txt new file mode 100644 index 0000000000000..6a6d4dcaa2ae5 --- /dev/null +++ b/src/tools/clippy/src/docs/cast_ptr_alignment.txt @@ -0,0 +1,21 @@ +### What it does +Checks for casts, using `as` or `pointer::cast`, +from a less-strictly-aligned pointer to a more-strictly-aligned pointer + +### Why is this bad? +Dereferencing the resulting pointer may be undefined +behavior. + +### Known problems +Using `std::ptr::read_unaligned` and `std::ptr::write_unaligned` or similar +on the resulting pointer is fine. Is over-zealous: Casts with manual alignment checks or casts like +u64-> u8 -> u16 can be fine. Miri is able to do a more in-depth analysis. + +### Example +``` +let _ = (&1u8 as *const u8) as *const u16; +let _ = (&mut 1u8 as *mut u8) as *mut u16; + +(&1u8 as *const u8).cast::(); +(&mut 1u8 as *mut u8).cast::(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/cast_ref_to_mut.txt b/src/tools/clippy/src/docs/cast_ref_to_mut.txt new file mode 100644 index 0000000000000..fb5b4dbb62d82 --- /dev/null +++ b/src/tools/clippy/src/docs/cast_ref_to_mut.txt @@ -0,0 +1,28 @@ +### What it does +Checks for casts of `&T` to `&mut T` anywhere in the code. + +### Why is this bad? +It’s basically guaranteed to be undefined behavior. +`UnsafeCell` is the only way to obtain aliasable data that is considered +mutable. + +### Example +``` +fn x(r: &i32) { + unsafe { + *(r as *const _ as *mut _) += 1; + } +} +``` + +Instead consider using interior mutability types. + +``` +use std::cell::UnsafeCell; + +fn x(r: &UnsafeCell) { + unsafe { + *r.get() += 1; + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/cast_sign_loss.txt b/src/tools/clippy/src/docs/cast_sign_loss.txt new file mode 100644 index 0000000000000..d64fe1b07f469 --- /dev/null +++ b/src/tools/clippy/src/docs/cast_sign_loss.txt @@ -0,0 +1,15 @@ +### What it does +Checks for casts from a signed to an unsigned numerical +type. In this case, negative values wrap around to large positive values, +which can be quite surprising in practice. However, as the cast works as +defined, this lint is `Allow` by default. + +### Why is this bad? +Possibly surprising results. You can activate this lint +as a one-time check to see where numerical wrapping can arise. + +### Example +``` +let y: i8 = -1; +y as u128; // will return 18446744073709551615 +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/cast_slice_different_sizes.txt b/src/tools/clippy/src/docs/cast_slice_different_sizes.txt new file mode 100644 index 0000000000000..c01ef0ba92c03 --- /dev/null +++ b/src/tools/clippy/src/docs/cast_slice_different_sizes.txt @@ -0,0 +1,38 @@ +### What it does +Checks for `as` casts between raw pointers to slices with differently sized elements. + +### Why is this bad? +The produced raw pointer to a slice does not update its length metadata. The produced +pointer will point to a different number of bytes than the original pointer because the +length metadata of a raw slice pointer is in elements rather than bytes. +Producing a slice reference from the raw pointer will either create a slice with +less data (which can be surprising) or create a slice with more data and cause Undefined Behavior. + +### Example +// Missing data +``` +let a = [1_i32, 2, 3, 4]; +let p = &a as *const [i32] as *const [u8]; +unsafe { + println!("{:?}", &*p); +} +``` +// Undefined Behavior (note: also potential alignment issues) +``` +let a = [1_u8, 2, 3, 4]; +let p = &a as *const [u8] as *const [u32]; +unsafe { + println!("{:?}", &*p); +} +``` +Instead use `ptr::slice_from_raw_parts` to construct a slice from a data pointer and the correct length +``` +let a = [1_i32, 2, 3, 4]; +let old_ptr = &a as *const [i32]; +// The data pointer is cast to a pointer to the target `u8` not `[u8]` +// The length comes from the known length of 4 i32s times the 4 bytes per i32 +let new_ptr = core::ptr::slice_from_raw_parts(old_ptr as *const u8, 16); +unsafe { + println!("{:?}", &*new_ptr); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/cast_slice_from_raw_parts.txt b/src/tools/clippy/src/docs/cast_slice_from_raw_parts.txt new file mode 100644 index 0000000000000..b58c739766aab --- /dev/null +++ b/src/tools/clippy/src/docs/cast_slice_from_raw_parts.txt @@ -0,0 +1,20 @@ +### What it does +Checks for a raw slice being cast to a slice pointer + +### Why is this bad? +This can result in multiple `&mut` references to the same location when only a pointer is +required. +`ptr::slice_from_raw_parts` is a safe alternative that doesn't require +the same [safety requirements] to be upheld. + +### Example +``` +let _: *const [u8] = std::slice::from_raw_parts(ptr, len) as *const _; +let _: *mut [u8] = std::slice::from_raw_parts_mut(ptr, len) as *mut _; +``` +Use instead: +``` +let _: *const [u8] = std::ptr::slice_from_raw_parts(ptr, len); +let _: *mut [u8] = std::ptr::slice_from_raw_parts_mut(ptr, len); +``` +[safety requirements]: https://doc.rust-lang.org/std/slice/fn.from_raw_parts.html#safety \ No newline at end of file diff --git a/src/tools/clippy/src/docs/char_lit_as_u8.txt b/src/tools/clippy/src/docs/char_lit_as_u8.txt new file mode 100644 index 0000000000000..00d60b9a451b9 --- /dev/null +++ b/src/tools/clippy/src/docs/char_lit_as_u8.txt @@ -0,0 +1,21 @@ +### What it does +Checks for expressions where a character literal is cast +to `u8` and suggests using a byte literal instead. + +### Why is this bad? +In general, casting values to smaller types is +error-prone and should be avoided where possible. In the particular case of +converting a character literal to u8, it is easy to avoid by just using a +byte literal instead. As an added bonus, `b'a'` is even slightly shorter +than `'a' as u8`. + +### Example +``` +'x' as u8 +``` + +A better version, using the byte literal: + +``` +b'x' +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/chars_last_cmp.txt b/src/tools/clippy/src/docs/chars_last_cmp.txt new file mode 100644 index 0000000000000..4c1d8838973a7 --- /dev/null +++ b/src/tools/clippy/src/docs/chars_last_cmp.txt @@ -0,0 +1,17 @@ +### What it does +Checks for usage of `_.chars().last()` or +`_.chars().next_back()` on a `str` to check if it ends with a given char. + +### Why is this bad? +Readability, this can be written more concisely as +`_.ends_with(_)`. + +### Example +``` +name.chars().last() == Some('_') || name.chars().next_back() == Some('-'); +``` + +Use instead: +``` +name.ends_with('_') || name.ends_with('-'); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/chars_next_cmp.txt b/src/tools/clippy/src/docs/chars_next_cmp.txt new file mode 100644 index 0000000000000..77cbce2de00f9 --- /dev/null +++ b/src/tools/clippy/src/docs/chars_next_cmp.txt @@ -0,0 +1,19 @@ +### What it does +Checks for usage of `.chars().next()` on a `str` to check +if it starts with a given char. + +### Why is this bad? +Readability, this can be written more concisely as +`_.starts_with(_)`. + +### Example +``` +let name = "foo"; +if name.chars().next() == Some('_') {}; +``` + +Use instead: +``` +let name = "foo"; +if name.starts_with('_') {}; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/checked_conversions.txt b/src/tools/clippy/src/docs/checked_conversions.txt new file mode 100644 index 0000000000000..536b01294ee17 --- /dev/null +++ b/src/tools/clippy/src/docs/checked_conversions.txt @@ -0,0 +1,15 @@ +### What it does +Checks for explicit bounds checking when casting. + +### Why is this bad? +Reduces the readability of statements & is error prone. + +### Example +``` +foo <= i32::MAX as u32; +``` + +Use instead: +``` +i32::try_from(foo).is_ok(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/clone_double_ref.txt b/src/tools/clippy/src/docs/clone_double_ref.txt new file mode 100644 index 0000000000000..2729635bd246f --- /dev/null +++ b/src/tools/clippy/src/docs/clone_double_ref.txt @@ -0,0 +1,16 @@ +### What it does +Checks for usage of `.clone()` on an `&&T`. + +### Why is this bad? +Cloning an `&&T` copies the inner `&T`, instead of +cloning the underlying `T`. + +### Example +``` +fn main() { + let x = vec![1]; + let y = &&x; + let z = y.clone(); + println!("{:p} {:p}", *y, z); // prints out the same pointer +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/clone_on_copy.txt b/src/tools/clippy/src/docs/clone_on_copy.txt new file mode 100644 index 0000000000000..99a0bdb4c4ac0 --- /dev/null +++ b/src/tools/clippy/src/docs/clone_on_copy.txt @@ -0,0 +1,11 @@ +### What it does +Checks for usage of `.clone()` on a `Copy` type. + +### Why is this bad? +The only reason `Copy` types implement `Clone` is for +generics, not for using the `clone` method on a concrete type. + +### Example +``` +42u64.clone(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/clone_on_ref_ptr.txt b/src/tools/clippy/src/docs/clone_on_ref_ptr.txt new file mode 100644 index 0000000000000..2d83f8fefc122 --- /dev/null +++ b/src/tools/clippy/src/docs/clone_on_ref_ptr.txt @@ -0,0 +1,21 @@ +### What it does +Checks for usage of `.clone()` on a ref-counted pointer, +(`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified +function syntax instead (e.g., `Rc::clone(foo)`). + +### Why is this bad? +Calling '.clone()' on an Rc, Arc, or Weak +can obscure the fact that only the pointer is being cloned, not the underlying +data. + +### Example +``` +let x = Rc::new(1); + +x.clone(); +``` + +Use instead: +``` +Rc::clone(&x); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/cloned_instead_of_copied.txt b/src/tools/clippy/src/docs/cloned_instead_of_copied.txt new file mode 100644 index 0000000000000..2f2014d5fd299 --- /dev/null +++ b/src/tools/clippy/src/docs/cloned_instead_of_copied.txt @@ -0,0 +1,16 @@ +### What it does +Checks for usages of `cloned()` on an `Iterator` or `Option` where +`copied()` could be used instead. + +### Why is this bad? +`copied()` is better because it guarantees that the type being cloned +implements `Copy`. + +### Example +``` +[1, 2, 3].iter().cloned(); +``` +Use instead: +``` +[1, 2, 3].iter().copied(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/cmp_nan.txt b/src/tools/clippy/src/docs/cmp_nan.txt new file mode 100644 index 0000000000000..e2ad04d932359 --- /dev/null +++ b/src/tools/clippy/src/docs/cmp_nan.txt @@ -0,0 +1,16 @@ +### What it does +Checks for comparisons to NaN. + +### Why is this bad? +NaN does not compare meaningfully to anything – not +even itself – so those comparisons are simply wrong. + +### Example +``` +if x == f32::NAN { } +``` + +Use instead: +``` +if x.is_nan() { } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/cmp_null.txt b/src/tools/clippy/src/docs/cmp_null.txt new file mode 100644 index 0000000000000..02fd15124f038 --- /dev/null +++ b/src/tools/clippy/src/docs/cmp_null.txt @@ -0,0 +1,23 @@ +### What it does +This lint checks for equality comparisons with `ptr::null` + +### Why is this bad? +It's easier and more readable to use the inherent +`.is_null()` +method instead + +### Example +``` +use std::ptr; + +if x == ptr::null { + // .. +} +``` + +Use instead: +``` +if x.is_null() { + // .. +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/cmp_owned.txt b/src/tools/clippy/src/docs/cmp_owned.txt new file mode 100644 index 0000000000000..f8d4956ff1d4b --- /dev/null +++ b/src/tools/clippy/src/docs/cmp_owned.txt @@ -0,0 +1,18 @@ +### What it does +Checks for conversions to owned values just for the sake +of a comparison. + +### Why is this bad? +The comparison can operate on a reference, so creating +an owned value effectively throws it away directly afterwards, which is +needlessly consuming code and heap space. + +### Example +``` +if x.to_owned() == y {} +``` + +Use instead: +``` +if x == y {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/cognitive_complexity.txt b/src/tools/clippy/src/docs/cognitive_complexity.txt new file mode 100644 index 0000000000000..fdd75f6479cd0 --- /dev/null +++ b/src/tools/clippy/src/docs/cognitive_complexity.txt @@ -0,0 +1,13 @@ +### What it does +Checks for methods with high cognitive complexity. + +### Why is this bad? +Methods of high cognitive complexity tend to be hard to +both read and maintain. Also LLVM will tend to optimize small methods better. + +### Known problems +Sometimes it's hard to find a way to reduce the +complexity. + +### Example +You'll see it when you get the warning. \ No newline at end of file diff --git a/src/tools/clippy/src/docs/collapsible_else_if.txt b/src/tools/clippy/src/docs/collapsible_else_if.txt new file mode 100644 index 0000000000000..4ddfca17731f7 --- /dev/null +++ b/src/tools/clippy/src/docs/collapsible_else_if.txt @@ -0,0 +1,29 @@ +### What it does +Checks for collapsible `else { if ... }` expressions +that can be collapsed to `else if ...`. + +### Why is this bad? +Each `if`-statement adds one level of nesting, which +makes code look more complex than it really is. + +### Example +``` + +if x { + … +} else { + if y { + … + } +} +``` + +Should be written: + +``` +if x { + … +} else if y { + … +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/collapsible_if.txt b/src/tools/clippy/src/docs/collapsible_if.txt new file mode 100644 index 0000000000000..e1264ee062e95 --- /dev/null +++ b/src/tools/clippy/src/docs/collapsible_if.txt @@ -0,0 +1,23 @@ +### What it does +Checks for nested `if` statements which can be collapsed +by `&&`-combining their conditions. + +### Why is this bad? +Each `if`-statement adds one level of nesting, which +makes code look more complex than it really is. + +### Example +``` +if x { + if y { + // … + } +} +``` + +Use instead: +``` +if x && y { + // … +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/collapsible_match.txt b/src/tools/clippy/src/docs/collapsible_match.txt new file mode 100644 index 0000000000000..0d59594a03a27 --- /dev/null +++ b/src/tools/clippy/src/docs/collapsible_match.txt @@ -0,0 +1,31 @@ +### What it does +Finds nested `match` or `if let` expressions where the patterns may be "collapsed" together +without adding any branches. + +Note that this lint is not intended to find _all_ cases where nested match patterns can be merged, but only +cases where merging would most likely make the code more readable. + +### Why is this bad? +It is unnecessarily verbose and complex. + +### Example +``` +fn func(opt: Option>) { + let n = match opt { + Some(n) => match n { + Ok(n) => n, + _ => return, + } + None => return, + }; +} +``` +Use instead: +``` +fn func(opt: Option>) { + let n = match opt { + Some(Ok(n)) => n, + _ => return, + }; +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/collapsible_str_replace.txt b/src/tools/clippy/src/docs/collapsible_str_replace.txt new file mode 100644 index 0000000000000..c24c25a3028a5 --- /dev/null +++ b/src/tools/clippy/src/docs/collapsible_str_replace.txt @@ -0,0 +1,19 @@ +### What it does +Checks for consecutive calls to `str::replace` (2 or more) +that can be collapsed into a single call. + +### Why is this bad? +Consecutive `str::replace` calls scan the string multiple times +with repetitive code. + +### Example +``` +let hello = "hesuo worpd" + .replace('s', "l") + .replace("u", "l") + .replace('p', "l"); +``` +Use instead: +``` +let hello = "hesuo worpd".replace(&['s', 'u', 'p'], "l"); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/comparison_chain.txt b/src/tools/clippy/src/docs/comparison_chain.txt new file mode 100644 index 0000000000000..43b09f31ff4aa --- /dev/null +++ b/src/tools/clippy/src/docs/comparison_chain.txt @@ -0,0 +1,36 @@ +### What it does +Checks comparison chains written with `if` that can be +rewritten with `match` and `cmp`. + +### Why is this bad? +`if` is not guaranteed to be exhaustive and conditionals can get +repetitive + +### Known problems +The match statement may be slower due to the compiler +not inlining the call to cmp. See issue [#5354](https://github.com/rust-lang/rust-clippy/issues/5354) + +### Example +``` +fn f(x: u8, y: u8) { + if x > y { + a() + } else if x < y { + b() + } else { + c() + } +} +``` + +Use instead: +``` +use std::cmp::Ordering; +fn f(x: u8, y: u8) { + match x.cmp(&y) { + Ordering::Greater => a(), + Ordering::Less => b(), + Ordering::Equal => c() + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/comparison_to_empty.txt b/src/tools/clippy/src/docs/comparison_to_empty.txt new file mode 100644 index 0000000000000..db6f74fe2706b --- /dev/null +++ b/src/tools/clippy/src/docs/comparison_to_empty.txt @@ -0,0 +1,31 @@ +### What it does +Checks for comparing to an empty slice such as `""` or `[]`, +and suggests using `.is_empty()` where applicable. + +### Why is this bad? +Some structures can answer `.is_empty()` much faster +than checking for equality. So it is good to get into the habit of using +`.is_empty()`, and having it is cheap. +Besides, it makes the intent clearer than a manual comparison in some contexts. + +### Example + +``` +if s == "" { + .. +} + +if arr == [] { + .. +} +``` +Use instead: +``` +if s.is_empty() { + .. +} + +if arr.is_empty() { + .. +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/copy_iterator.txt b/src/tools/clippy/src/docs/copy_iterator.txt new file mode 100644 index 0000000000000..5f9a2a015b86c --- /dev/null +++ b/src/tools/clippy/src/docs/copy_iterator.txt @@ -0,0 +1,20 @@ +### What it does +Checks for types that implement `Copy` as well as +`Iterator`. + +### Why is this bad? +Implicit copies can be confusing when working with +iterator combinators. + +### Example +``` +#[derive(Copy, Clone)] +struct Countdown(u8); + +impl Iterator for Countdown { + // ... +} + +let a: Vec<_> = my_iterator.take(1).collect(); +let b: Vec<_> = my_iterator.collect(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/crate_in_macro_def.txt b/src/tools/clippy/src/docs/crate_in_macro_def.txt new file mode 100644 index 0000000000000..047e986dee71f --- /dev/null +++ b/src/tools/clippy/src/docs/crate_in_macro_def.txt @@ -0,0 +1,35 @@ +### What it does +Checks for use of `crate` as opposed to `$crate` in a macro definition. + +### Why is this bad? +`crate` refers to the macro call's crate, whereas `$crate` refers to the macro definition's +crate. Rarely is the former intended. See: +https://doc.rust-lang.org/reference/macros-by-example.html#hygiene + +### Example +``` +#[macro_export] +macro_rules! print_message { + () => { + println!("{}", crate::MESSAGE); + }; +} +pub const MESSAGE: &str = "Hello!"; +``` +Use instead: +``` +#[macro_export] +macro_rules! print_message { + () => { + println!("{}", $crate::MESSAGE); + }; +} +pub const MESSAGE: &str = "Hello!"; +``` + +Note that if the use of `crate` is intentional, an `allow` attribute can be applied to the +macro definition, e.g.: +``` +#[allow(clippy::crate_in_macro_def)] +macro_rules! ok { ... crate::foo ... } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/create_dir.txt b/src/tools/clippy/src/docs/create_dir.txt new file mode 100644 index 0000000000000..e4e7937684e6e --- /dev/null +++ b/src/tools/clippy/src/docs/create_dir.txt @@ -0,0 +1,15 @@ +### 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`. + +### Example +``` +std::fs::create_dir("foo"); +``` + +Use instead: +``` +std::fs::create_dir_all("foo"); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/crosspointer_transmute.txt b/src/tools/clippy/src/docs/crosspointer_transmute.txt new file mode 100644 index 0000000000000..49dea154970e5 --- /dev/null +++ b/src/tools/clippy/src/docs/crosspointer_transmute.txt @@ -0,0 +1,12 @@ +### What it does +Checks for transmutes between a type `T` and `*T`. + +### Why is this bad? +It's easy to mistakenly transmute between a type and a +pointer to that type. + +### Example +``` +core::intrinsics::transmute(t) // where the result type is the same as + // `*t` or `&t`'s +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/dbg_macro.txt b/src/tools/clippy/src/docs/dbg_macro.txt new file mode 100644 index 0000000000000..3e1a9a043f9f4 --- /dev/null +++ b/src/tools/clippy/src/docs/dbg_macro.txt @@ -0,0 +1,16 @@ +### What it does +Checks for usage of dbg!() macro. + +### Why is this bad? +`dbg!` macro is intended as a debugging tool. It +should not be in version control. + +### Example +``` +dbg!(true) +``` + +Use instead: +``` +true +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/debug_assert_with_mut_call.txt b/src/tools/clippy/src/docs/debug_assert_with_mut_call.txt new file mode 100644 index 0000000000000..2c44abe1f05c8 --- /dev/null +++ b/src/tools/clippy/src/docs/debug_assert_with_mut_call.txt @@ -0,0 +1,18 @@ +### What it does +Checks for function/method calls with a mutable +parameter in `debug_assert!`, `debug_assert_eq!` and `debug_assert_ne!` macros. + +### Why is this bad? +In release builds `debug_assert!` macros are optimized out by the +compiler. +Therefore mutating something in a `debug_assert!` macro results in different behavior +between a release and debug build. + +### Example +``` +debug_assert_eq!(vec![3].pop(), Some(3)); + +// or + +debug_assert!(takes_a_mut_parameter(&mut x)); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/decimal_literal_representation.txt b/src/tools/clippy/src/docs/decimal_literal_representation.txt new file mode 100644 index 0000000000000..daca9bbb3a848 --- /dev/null +++ b/src/tools/clippy/src/docs/decimal_literal_representation.txt @@ -0,0 +1,13 @@ +### What it does +Warns if there is a better representation for a numeric literal. + +### Why is this bad? +Especially for big powers of 2 a hexadecimal representation is more +readable than a decimal representation. + +### Example +``` +`255` => `0xFF` +`65_535` => `0xFFFF` +`4_042_322_160` => `0xF0F0_F0F0` +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/declare_interior_mutable_const.txt b/src/tools/clippy/src/docs/declare_interior_mutable_const.txt new file mode 100644 index 0000000000000..2801b5ccff802 --- /dev/null +++ b/src/tools/clippy/src/docs/declare_interior_mutable_const.txt @@ -0,0 +1,46 @@ +### What it does +Checks for declaration of `const` items which is interior +mutable (e.g., contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.). + +### Why is this bad? +Consts are copied everywhere they are referenced, i.e., +every time you refer to the const a fresh instance of the `Cell` or `Mutex` +or `AtomicXxxx` will be created, which defeats the whole purpose of using +these types in the first place. + +The `const` should better be replaced by a `static` item if a global +variable is wanted, or replaced by a `const fn` if a constructor is wanted. + +### Known problems +A "non-constant" const item is a legacy way to supply an +initialized value to downstream `static` items (e.g., the +`std::sync::ONCE_INIT` constant). In this case the use of `const` is legit, +and this lint should be suppressed. + +Even though the lint avoids triggering on a constant whose type has enums that have variants +with interior mutability, and its value uses non interior mutable variants (see +[#3962](https://github.com/rust-lang/rust-clippy/issues/3962) and +[#3825](https://github.com/rust-lang/rust-clippy/issues/3825) for examples); +it complains about associated constants without default values only based on its types; +which might not be preferable. +There're other enums plus associated constants cases that the lint cannot handle. + +Types that have underlying or potential interior mutability trigger the lint whether +the interior mutable field is used or not. See issues +[#5812](https://github.com/rust-lang/rust-clippy/issues/5812) and + +### Example +``` +use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; + +const CONST_ATOM: AtomicUsize = AtomicUsize::new(12); +CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged +assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct +``` + +Use instead: +``` +static STATIC_ATOM: AtomicUsize = AtomicUsize::new(15); +STATIC_ATOM.store(9, SeqCst); +assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/default_instead_of_iter_empty.txt b/src/tools/clippy/src/docs/default_instead_of_iter_empty.txt new file mode 100644 index 0000000000000..b63ef3d18fc41 --- /dev/null +++ b/src/tools/clippy/src/docs/default_instead_of_iter_empty.txt @@ -0,0 +1,15 @@ +### What it does +It checks for `std::iter::Empty::default()` and suggests replacing it with +`std::iter::empty()`. +### Why is this bad? +`std::iter::empty()` is the more idiomatic way. +### Example +``` +let _ = std::iter::Empty::::default(); +let iter: std::iter::Empty = std::iter::Empty::default(); +``` +Use instead: +``` +let _ = std::iter::empty::(); +let iter: std::iter::Empty = std::iter::empty(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/default_numeric_fallback.txt b/src/tools/clippy/src/docs/default_numeric_fallback.txt new file mode 100644 index 0000000000000..15076a0a68bf6 --- /dev/null +++ b/src/tools/clippy/src/docs/default_numeric_fallback.txt @@ -0,0 +1,28 @@ +### What it does +Checks for usage of unconstrained numeric literals which may cause default numeric fallback in type +inference. + +Default numeric fallback means that if numeric types have not yet been bound to concrete +types at the end of type inference, then integer type is bound to `i32`, and similarly +floating type is bound to `f64`. + +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. + +### Known problems +This lint can only be allowed at the function level or above. + +### Example +``` +let i = 10; +let f = 1.23; +``` + +Use instead: +``` +let i = 10i32; +let f = 1.23f64; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/default_trait_access.txt b/src/tools/clippy/src/docs/default_trait_access.txt new file mode 100644 index 0000000000000..e69298969c8ed --- /dev/null +++ b/src/tools/clippy/src/docs/default_trait_access.txt @@ -0,0 +1,16 @@ +### What it does +Checks for literal calls to `Default::default()`. + +### Why is this bad? +It's easier for the reader if the name of the type is used, rather than the +generic `Default`. + +### Example +``` +let s: String = Default::default(); +``` + +Use instead: +``` +let s = String::default(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/default_union_representation.txt b/src/tools/clippy/src/docs/default_union_representation.txt new file mode 100644 index 0000000000000..f79ff9760e57e --- /dev/null +++ b/src/tools/clippy/src/docs/default_union_representation.txt @@ -0,0 +1,36 @@ +### What it does +Displays a warning when a union is declared with the default representation (without a `#[repr(C)]` attribute). + +### Why is this bad? +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 +specified layout. These cases may lead to undefined behavior in unsafe blocks. + +### Example +``` +union Foo { + a: i32, + b: u32, +} + +fn main() { + let _x: u32 = unsafe { + Foo { a: 0_i32 }.b // Undefined behavior: `b` is allowed to be padding + }; +} +``` +Use instead: +``` +#[repr(C)] +union Foo { + a: i32, + b: u32, +} + +fn main() { + let _x: u32 = unsafe { + Foo { a: 0_i32 }.b // Now defined behavior, this is just an i32 -> u32 transmute + }; +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/deprecated_cfg_attr.txt b/src/tools/clippy/src/docs/deprecated_cfg_attr.txt new file mode 100644 index 0000000000000..9f264887a057e --- /dev/null +++ b/src/tools/clippy/src/docs/deprecated_cfg_attr.txt @@ -0,0 +1,24 @@ +### What it does +Checks for `#[cfg_attr(rustfmt, rustfmt_skip)]` and suggests to replace it +with `#[rustfmt::skip]`. + +### Why is this bad? +Since tool_attributes ([rust-lang/rust#44690](https://github.com/rust-lang/rust/issues/44690)) +are stable now, they should be used instead of the old `cfg_attr(rustfmt)` attributes. + +### Known problems +This lint doesn't detect crate level inner attributes, because they get +processed before the PreExpansionPass lints get executed. See +[#3123](https://github.com/rust-lang/rust-clippy/pull/3123#issuecomment-422321765) + +### Example +``` +#[cfg_attr(rustfmt, rustfmt_skip)] +fn main() { } +``` + +Use instead: +``` +#[rustfmt::skip] +fn main() { } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/deprecated_semver.txt b/src/tools/clippy/src/docs/deprecated_semver.txt new file mode 100644 index 0000000000000..c9574a99b2bec --- /dev/null +++ b/src/tools/clippy/src/docs/deprecated_semver.txt @@ -0,0 +1,13 @@ +### What it does +Checks for `#[deprecated]` annotations with a `since` +field that is not a valid semantic version. + +### Why is this bad? +For checking the version of the deprecation, it must be +a valid semver. Failing that, the contained information is useless. + +### Example +``` +#[deprecated(since = "forever")] +fn something_else() { /* ... */ } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/deref_addrof.txt b/src/tools/clippy/src/docs/deref_addrof.txt new file mode 100644 index 0000000000000..fa711b924d480 --- /dev/null +++ b/src/tools/clippy/src/docs/deref_addrof.txt @@ -0,0 +1,22 @@ +### What it does +Checks for usage of `*&` and `*&mut` in expressions. + +### Why is this bad? +Immediately dereferencing a reference is no-op and +makes the code less clear. + +### Known problems +Multiple dereference/addrof pairs are not handled so +the suggested fix for `x = **&&y` is `x = *&y`, which is still incorrect. + +### Example +``` +let a = f(*&mut b); +let c = *&d; +``` + +Use instead: +``` +let a = f(b); +let c = d; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/deref_by_slicing.txt b/src/tools/clippy/src/docs/deref_by_slicing.txt new file mode 100644 index 0000000000000..4dad24ac00cad --- /dev/null +++ b/src/tools/clippy/src/docs/deref_by_slicing.txt @@ -0,0 +1,17 @@ +### What it does +Checks for slicing expressions which are equivalent to dereferencing the +value. + +### Why is this bad? +Some people may prefer to dereference rather than slice. + +### Example +``` +let vec = vec![1, 2, 3]; +let slice = &vec[..]; +``` +Use instead: +``` +let vec = vec![1, 2, 3]; +let slice = &*vec; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/derivable_impls.txt b/src/tools/clippy/src/docs/derivable_impls.txt new file mode 100644 index 0000000000000..5cee43956cc36 --- /dev/null +++ b/src/tools/clippy/src/docs/derivable_impls.txt @@ -0,0 +1,35 @@ +### What it does +Detects manual `std::default::Default` implementations that are identical to a derived implementation. + +### Why is this bad? +It is less concise. + +### Example +``` +struct Foo { + bar: bool +} + +impl Default for Foo { + fn default() -> Self { + Self { + bar: false + } + } +} +``` + +Use instead: +``` +#[derive(Default)] +struct Foo { + bar: bool +} +``` + +### Known problems +Derive macros [sometimes use incorrect bounds](https://github.com/rust-lang/rust/issues/26925) +in generic types and the user defined `impl` may be more generalized or +specialized than what derive will produce. This lint can't detect the manual `impl` +has exactly equal bounds, and therefore this lint is disabled for types with +generic parameters. \ No newline at end of file diff --git a/src/tools/clippy/src/docs/derive_hash_xor_eq.txt b/src/tools/clippy/src/docs/derive_hash_xor_eq.txt new file mode 100644 index 0000000000000..fbf623d5adbc1 --- /dev/null +++ b/src/tools/clippy/src/docs/derive_hash_xor_eq.txt @@ -0,0 +1,23 @@ +### What it does +Checks for deriving `Hash` but implementing `PartialEq` +explicitly or vice versa. + +### Why is this bad? +The implementation of these traits must agree (for +example for use with `HashMap`) so it’s probably a bad idea to use a +default-generated `Hash` implementation with an explicitly defined +`PartialEq`. In particular, the following must hold for any type: + +``` +k1 == k2 ⇒ hash(k1) == hash(k2) +``` + +### Example +``` +#[derive(Hash)] +struct Foo; + +impl PartialEq for Foo { + ... +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/derive_ord_xor_partial_ord.txt b/src/tools/clippy/src/docs/derive_ord_xor_partial_ord.txt new file mode 100644 index 0000000000000..f2107a5f69eea --- /dev/null +++ b/src/tools/clippy/src/docs/derive_ord_xor_partial_ord.txt @@ -0,0 +1,44 @@ +### What it does +Checks for deriving `Ord` but implementing `PartialOrd` +explicitly or vice versa. + +### Why is this bad? +The implementation of these traits must agree (for +example for use with `sort`) so it’s probably a bad idea to use a +default-generated `Ord` implementation with an explicitly defined +`PartialOrd`. In particular, the following must hold for any type +implementing `Ord`: + +``` +k1.cmp(&k2) == k1.partial_cmp(&k2).unwrap() +``` + +### Example +``` +#[derive(Ord, PartialEq, Eq)] +struct Foo; + +impl PartialOrd for Foo { + ... +} +``` +Use instead: +``` +#[derive(PartialEq, Eq)] +struct Foo; + +impl PartialOrd for Foo { + fn partial_cmp(&self, other: &Foo) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Foo { + ... +} +``` +or, if you don't need a custom ordering: +``` +#[derive(Ord, PartialOrd, PartialEq, Eq)] +struct Foo; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/derive_partial_eq_without_eq.txt b/src/tools/clippy/src/docs/derive_partial_eq_without_eq.txt new file mode 100644 index 0000000000000..932fabad666c3 --- /dev/null +++ b/src/tools/clippy/src/docs/derive_partial_eq_without_eq.txt @@ -0,0 +1,25 @@ +### What it does +Checks for types that derive `PartialEq` and could implement `Eq`. + +### Why is this bad? +If a type `T` derives `PartialEq` and all of its members implement `Eq`, +then `T` can always implement `Eq`. Implementing `Eq` allows `T` to be used +in APIs that require `Eq` types. It also allows structs containing `T` to derive +`Eq` themselves. + +### Example +``` +#[derive(PartialEq)] +struct Foo { + i_am_eq: i32, + i_am_eq_too: Vec, +} +``` +Use instead: +``` +#[derive(PartialEq, Eq)] +struct Foo { + i_am_eq: i32, + i_am_eq_too: Vec, +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/disallowed_methods.txt b/src/tools/clippy/src/docs/disallowed_methods.txt new file mode 100644 index 0000000000000..d8ad5b6a6674c --- /dev/null +++ b/src/tools/clippy/src/docs/disallowed_methods.txt @@ -0,0 +1,41 @@ +### What it does +Denies the configured methods and functions in clippy.toml + +Note: Even though this lint is warn-by-default, it will only trigger if +methods are defined in the clippy.toml file. + +### Why is this bad? +Some methods are undesirable in certain contexts, and it's beneficial to +lint for them as needed. + +### Example +An example clippy.toml configuration: +``` +disallowed-methods = [ + # Can use a string as the path of the disallowed method. + "std::boxed::Box::new", + # Can also use an inline table with a `path` key. + { path = "std::time::Instant::now" }, + # When using an inline table, can add a `reason` for why the method + # is disallowed. + { path = "std::vec::Vec::leak", reason = "no leaking memory" }, +] +``` + +``` +// Example code where clippy issues a warning +let xs = vec![1, 2, 3, 4]; +xs.leak(); // Vec::leak is disallowed in the config. +// The diagnostic contains the message "no leaking memory". + +let _now = Instant::now(); // Instant::now is disallowed in the config. + +let _box = Box::new(3); // Box::new is disallowed in the config. +``` + +Use instead: +``` +// Example code which does not raise clippy warning +let mut xs = Vec::new(); // Vec::new is _not_ disallowed in the config. +xs.push(123); // Vec::push is _not_ disallowed in the config. +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/disallowed_names.txt b/src/tools/clippy/src/docs/disallowed_names.txt new file mode 100644 index 0000000000000..f4aaee9c77b7b --- /dev/null +++ b/src/tools/clippy/src/docs/disallowed_names.txt @@ -0,0 +1,12 @@ +### What it does +Checks for usage of disallowed names for variables, such +as `foo`. + +### Why is this bad? +These names are usually placeholder names and should be +avoided. + +### Example +``` +let foo = 3.14; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/disallowed_script_idents.txt b/src/tools/clippy/src/docs/disallowed_script_idents.txt new file mode 100644 index 0000000000000..2151b7a20dedc --- /dev/null +++ b/src/tools/clippy/src/docs/disallowed_script_idents.txt @@ -0,0 +1,32 @@ +### What it does +Checks for usage of unicode scripts other than those explicitly allowed +by the lint config. + +This lint doesn't take into account non-text scripts such as `Unknown` and `Linear_A`. +It also ignores the `Common` script type. +While configuring, be sure to use official script name [aliases] from +[the list of supported scripts][supported_scripts]. + +See also: [`non_ascii_idents`]. + +[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? +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 +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 + +### Example +``` +// Assuming that `clippy.toml` contains the following line: +// allowed-locales = ["Latin", "Cyrillic"] +let counter = 10; // OK, latin is allowed. +let счётчик = 10; // OK, cyrillic is allowed. +let zähler = 10; // OK, it's still latin. +let カウンタ = 10; // Will spawn the lint. +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/disallowed_types.txt b/src/tools/clippy/src/docs/disallowed_types.txt new file mode 100644 index 0000000000000..2bcbcddee5666 --- /dev/null +++ b/src/tools/clippy/src/docs/disallowed_types.txt @@ -0,0 +1,33 @@ +### What it does +Denies the configured types in clippy.toml. + +Note: Even though this lint is warn-by-default, it will only trigger if +types are defined in the clippy.toml file. + +### Why is this bad? +Some types are undesirable in certain contexts. + +### Example: +An example clippy.toml configuration: +``` +disallowed-types = [ + # Can use a string as the path of the disallowed type. + "std::collections::BTreeMap", + # Can also use an inline table with a `path` key. + { path = "std::net::TcpListener" }, + # When using an inline table, can add a `reason` for why the type + # is disallowed. + { path = "std::net::Ipv4Addr", reason = "no IPv4 allowed" }, +] +``` + +``` +use std::collections::BTreeMap; +// or its use +let x = std::collections::BTreeMap::new(); +``` +Use instead: +``` +// A similar type that is allowed by the config +use std::collections::HashMap; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/diverging_sub_expression.txt b/src/tools/clippy/src/docs/diverging_sub_expression.txt new file mode 100644 index 0000000000000..1943622180251 --- /dev/null +++ b/src/tools/clippy/src/docs/diverging_sub_expression.txt @@ -0,0 +1,19 @@ +### What it does +Checks for diverging calls that are not match arms or +statements. + +### Why is this bad? +It is often confusing to read. In addition, the +sub-expression evaluation order for Rust is not well documented. + +### Known problems +Someone might want to use `some_bool || panic!()` as a +shorthand. + +### Example +``` +let a = b() || panic!() || c(); +// `c()` is dead, `panic!()` is only called if `b()` returns `false` +let x = (a, b, c, panic!()); +// can simply be replaced by `panic!()` +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/doc_link_with_quotes.txt b/src/tools/clippy/src/docs/doc_link_with_quotes.txt new file mode 100644 index 0000000000000..107c8ac116d93 --- /dev/null +++ b/src/tools/clippy/src/docs/doc_link_with_quotes.txt @@ -0,0 +1,16 @@ +### What it does +Detects the syntax `['foo']` in documentation comments (notice quotes instead of backticks) +outside of code blocks +### Why is this bad? +It is likely a typo when defining an intra-doc link + +### Example +``` +/// See also: ['foo'] +fn bar() {} +``` +Use instead: +``` +/// See also: [`foo`] +fn bar() {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/doc_markdown.txt b/src/tools/clippy/src/docs/doc_markdown.txt new file mode 100644 index 0000000000000..94f54c587e302 --- /dev/null +++ b/src/tools/clippy/src/docs/doc_markdown.txt @@ -0,0 +1,35 @@ +### What it does +Checks for the presence of `_`, `::` or camel-case words +outside ticks in documentation. + +### Why is this bad? +*Rustdoc* supports markdown formatting, `_`, `::` and +camel-case probably indicates some code which should be included between +ticks. `_` can also be used for emphasis in markdown, this lint tries to +consider that. + +### Known problems +Lots of bad docs won’t be fixed, what the lint checks +for is limited, and there are still false positives. HTML elements and their +content are not linted. + +In addition, when writing documentation comments, including `[]` brackets +inside a link text would trip the parser. Therefore, documenting link with +`[`SmallVec<[T; INLINE_CAPACITY]>`]` and then [`SmallVec<[T; INLINE_CAPACITY]>`]: SmallVec +would fail. + +### Examples +``` +/// Do something with the foo_bar parameter. See also +/// that::other::module::foo. +// ^ `foo_bar` and `that::other::module::foo` should be ticked. +fn doit(foo_bar: usize) {} +``` + +``` +// Link text with `[]` brackets should be written as following: +/// Consume the array and return the inner +/// [`SmallVec<[T; INLINE_CAPACITY]>`][SmallVec]. +/// [SmallVec]: SmallVec +fn main() {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/double_comparisons.txt b/src/tools/clippy/src/docs/double_comparisons.txt new file mode 100644 index 0000000000000..7dc6818779f4b --- /dev/null +++ b/src/tools/clippy/src/docs/double_comparisons.txt @@ -0,0 +1,17 @@ +### What it does +Checks for double comparisons that could be simplified to a single expression. + + +### Why is this bad? +Readability. + +### Example +``` +if x == y || x < y {} +``` + +Use instead: + +``` +if x <= y {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/double_must_use.txt b/src/tools/clippy/src/docs/double_must_use.txt new file mode 100644 index 0000000000000..0017d10d40d33 --- /dev/null +++ b/src/tools/clippy/src/docs/double_must_use.txt @@ -0,0 +1,17 @@ +### What it does +Checks for a `#[must_use]` attribute without +further information on functions and methods that return a type already +marked as `#[must_use]`. + +### Why is this bad? +The attribute isn't needed. Not using the result +will already be reported. Alternatively, one can add some text to the +attribute to improve the lint message. + +### Examples +``` +#[must_use] +fn double_must_use() -> Result<(), ()> { + unimplemented!(); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/double_neg.txt b/src/tools/clippy/src/docs/double_neg.txt new file mode 100644 index 0000000000000..a07f67496d7cc --- /dev/null +++ b/src/tools/clippy/src/docs/double_neg.txt @@ -0,0 +1,12 @@ +### What it does +Detects expressions of the form `--x`. + +### Why is this bad? +It can mislead C/C++ programmers to think `x` was +decremented. + +### Example +``` +let mut x = 3; +--x; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/double_parens.txt b/src/tools/clippy/src/docs/double_parens.txt new file mode 100644 index 0000000000000..260d7dd575e55 --- /dev/null +++ b/src/tools/clippy/src/docs/double_parens.txt @@ -0,0 +1,24 @@ +### What it does +Checks for unnecessary double parentheses. + +### Why is this bad? +This makes code harder to read and might indicate a +mistake. + +### Example +``` +fn simple_double_parens() -> i32 { + ((0)) +} + +foo((0)); +``` + +Use instead: +``` +fn simple_no_parens() -> i32 { + 0 +} + +foo(0); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/drop_copy.txt b/src/tools/clippy/src/docs/drop_copy.txt new file mode 100644 index 0000000000000..f917ca8ed21a6 --- /dev/null +++ b/src/tools/clippy/src/docs/drop_copy.txt @@ -0,0 +1,15 @@ +### What it does +Checks for calls to `std::mem::drop` with a value +that derives the Copy trait + +### Why is this bad? +Calling `std::mem::drop` [does nothing for types that +implement Copy](https://doc.rust-lang.org/std/mem/fn.drop.html), since the +value will be copied and moved into the function on invocation. + +### Example +``` +let x: i32 = 42; // i32 implements Copy +std::mem::drop(x) // A copy of x is passed to the function, leaving the + // original unaffected +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/drop_non_drop.txt b/src/tools/clippy/src/docs/drop_non_drop.txt new file mode 100644 index 0000000000000..ee1e3a6c216ef --- /dev/null +++ b/src/tools/clippy/src/docs/drop_non_drop.txt @@ -0,0 +1,13 @@ +### What it does +Checks for calls to `std::mem::drop` with a value that does not implement `Drop`. + +### Why is this bad? +Calling `std::mem::drop` is no different than dropping such a type. A different value may +have been intended. + +### Example +``` +struct Foo; +let x = Foo; +std::mem::drop(x); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/drop_ref.txt b/src/tools/clippy/src/docs/drop_ref.txt new file mode 100644 index 0000000000000..c4f7adf0cfa33 --- /dev/null +++ b/src/tools/clippy/src/docs/drop_ref.txt @@ -0,0 +1,17 @@ +### What it does +Checks for calls to `std::mem::drop` with a reference +instead of an owned value. + +### Why is this bad? +Calling `drop` on a reference will only drop the +reference itself, which is a no-op. It will not call the `drop` method (from +the `Drop` trait implementation) on the underlying referenced value, which +is likely what was intended. + +### Example +``` +let mut lock_guard = mutex.lock(); +std::mem::drop(&lock_guard) // Should have been drop(lock_guard), mutex +// still locked +operation_that_requires_mutex_to_be_unlocked(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/duplicate_mod.txt b/src/tools/clippy/src/docs/duplicate_mod.txt new file mode 100644 index 0000000000000..709a9aba03ad2 --- /dev/null +++ b/src/tools/clippy/src/docs/duplicate_mod.txt @@ -0,0 +1,31 @@ +### What it does +Checks for files that are included as modules multiple times. + +### Why is this bad? +Loading a file as a module more than once causes it to be compiled +multiple times, taking longer and putting duplicate content into the +module tree. + +### Example +``` +// lib.rs +mod a; +mod b; +``` +``` +// a.rs +#[path = "./b.rs"] +mod b; +``` + +Use instead: + +``` +// lib.rs +mod a; +mod b; +``` +``` +// a.rs +use crate::b; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/duplicate_underscore_argument.txt b/src/tools/clippy/src/docs/duplicate_underscore_argument.txt new file mode 100644 index 0000000000000..a8fcd6a9fbe68 --- /dev/null +++ b/src/tools/clippy/src/docs/duplicate_underscore_argument.txt @@ -0,0 +1,16 @@ +### What it does +Checks for function arguments having the similar names +differing by an underscore. + +### Why is this bad? +It affects code readability. + +### Example +``` +fn foo(a: i32, _a: i32) {} +``` + +Use instead: +``` +fn bar(a: i32, _b: i32) {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/duration_subsec.txt b/src/tools/clippy/src/docs/duration_subsec.txt new file mode 100644 index 0000000000000..e7e0ca88745ee --- /dev/null +++ b/src/tools/clippy/src/docs/duration_subsec.txt @@ -0,0 +1,19 @@ +### What it does +Checks for calculation of subsecond microseconds or milliseconds +from other `Duration` methods. + +### Why is this bad? +It's more concise to call `Duration::subsec_micros()` or +`Duration::subsec_millis()` than to calculate them. + +### Example +``` +let micros = duration.subsec_nanos() / 1_000; +let millis = duration.subsec_nanos() / 1_000_000; +``` + +Use instead: +``` +let micros = duration.subsec_micros(); +let millis = duration.subsec_millis(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/else_if_without_else.txt b/src/tools/clippy/src/docs/else_if_without_else.txt new file mode 100644 index 0000000000000..33f5d0f918592 --- /dev/null +++ b/src/tools/clippy/src/docs/else_if_without_else.txt @@ -0,0 +1,27 @@ +### What it does +Checks for usage of if expressions with an `else if` branch, +but without a final `else` branch. + +### Why is this bad? +Some coding guidelines require this (e.g., MISRA-C:2004 Rule 14.10). + +### Example +``` +if x.is_positive() { + a(); +} else if x.is_negative() { + b(); +} +``` + +Use instead: + +``` +if x.is_positive() { + a(); +} else if x.is_negative() { + b(); +} else { + // We don't care about zero. +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/empty_drop.txt b/src/tools/clippy/src/docs/empty_drop.txt new file mode 100644 index 0000000000000..d0c0c24a9c880 --- /dev/null +++ b/src/tools/clippy/src/docs/empty_drop.txt @@ -0,0 +1,20 @@ +### What it does +Checks for empty `Drop` implementations. + +### Why is this bad? +Empty `Drop` implementations have no effect when dropping an instance of the type. They are +most likely useless. However, an empty `Drop` implementation prevents a type from being +destructured, which might be the intention behind adding the implementation as a marker. + +### Example +``` +struct S; + +impl Drop for S { + fn drop(&mut self) {} +} +``` +Use instead: +``` +struct S; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/empty_enum.txt b/src/tools/clippy/src/docs/empty_enum.txt new file mode 100644 index 0000000000000..f7b41c41ee5a1 --- /dev/null +++ b/src/tools/clippy/src/docs/empty_enum.txt @@ -0,0 +1,27 @@ +### What it does +Checks for `enum`s with no variants. + +As of this writing, the `never_type` is still a +nightly-only experimental API. Therefore, this lint is only triggered +if the `never_type` is enabled. + +### Why is this bad? +If you want to introduce a type which +can't be instantiated, you should use `!` (the primitive type "never"), +or a wrapper around it, because `!` has more extensive +compiler support (type inference, etc...) and wrappers +around it are the conventional way to define an uninhabited type. +For further information visit [never type documentation](https://doc.rust-lang.org/std/primitive.never.html) + + +### Example +``` +enum Test {} +``` + +Use instead: +``` +#![feature(never_type)] + +struct Test(!); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/empty_line_after_outer_attr.txt b/src/tools/clippy/src/docs/empty_line_after_outer_attr.txt new file mode 100644 index 0000000000000..c85242bbee0ec --- /dev/null +++ b/src/tools/clippy/src/docs/empty_line_after_outer_attr.txt @@ -0,0 +1,35 @@ +### What it does +Checks for empty lines after outer attributes + +### Why is this bad? +Most likely the attribute was meant to be an inner attribute using a '!'. +If it was meant to be an outer attribute, then the following item +should not be separated by empty lines. + +### Known problems +Can cause false positives. + +From the clippy side it's difficult to detect empty lines between an attributes and the +following item because empty lines and comments are not part of the AST. The parsing +currently works for basic cases but is not perfect. + +### Example +``` +#[allow(dead_code)] + +fn not_quite_good_code() { } +``` + +Use instead: +``` +// Good (as inner attribute) +#![allow(dead_code)] + +fn this_is_fine() { } + +// or + +// Good (as outer attribute) +#[allow(dead_code)] +fn this_is_fine_too() { } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/empty_loop.txt b/src/tools/clippy/src/docs/empty_loop.txt new file mode 100644 index 0000000000000..fea49a74d04e0 --- /dev/null +++ b/src/tools/clippy/src/docs/empty_loop.txt @@ -0,0 +1,27 @@ +### What it does +Checks for empty `loop` expressions. + +### Why is this bad? +These busy loops burn CPU cycles without doing +anything. It is _almost always_ a better idea to `panic!` than to have +a busy loop. + +If panicking isn't possible, think of the environment and either: + - block on something + - sleep the thread for some microseconds + - yield or pause the thread + +For `std` targets, this can be done with +[`std::thread::sleep`](https://doc.rust-lang.org/std/thread/fn.sleep.html) +or [`std::thread::yield_now`](https://doc.rust-lang.org/std/thread/fn.yield_now.html). + +For `no_std` targets, doing this is more complicated, especially because +`#[panic_handler]`s can't panic. To stop/pause the thread, you will +probably need to invoke some target-specific intrinsic. Examples include: + - [`x86_64::instructions::hlt`](https://docs.rs/x86_64/0.12.2/x86_64/instructions/fn.hlt.html) + - [`cortex_m::asm::wfi`](https://docs.rs/cortex-m/0.6.3/cortex_m/asm/fn.wfi.html) + +### Example +``` +loop {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/empty_structs_with_brackets.txt b/src/tools/clippy/src/docs/empty_structs_with_brackets.txt new file mode 100644 index 0000000000000..ab5e35ae2ada8 --- /dev/null +++ b/src/tools/clippy/src/docs/empty_structs_with_brackets.txt @@ -0,0 +1,14 @@ +### What it does +Finds structs without fields (a so-called "empty struct") that are declared with brackets. + +### Why is this bad? +Empty brackets after a struct declaration can be omitted. + +### Example +``` +struct Cookie {} +``` +Use instead: +``` +struct Cookie; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/enum_clike_unportable_variant.txt b/src/tools/clippy/src/docs/enum_clike_unportable_variant.txt new file mode 100644 index 0000000000000..d30a973a5a135 --- /dev/null +++ b/src/tools/clippy/src/docs/enum_clike_unportable_variant.txt @@ -0,0 +1,16 @@ +### What it does +Checks for C-like enumerations that are +`repr(isize/usize)` and have values that don't fit into an `i32`. + +### Why is this bad? +This will truncate the variant value on 32 bit +architectures, but works fine on 64 bit. + +### Example +``` +#[repr(usize)] +enum NonPortable { + X = 0x1_0000_0000, + Y = 0, +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/enum_glob_use.txt b/src/tools/clippy/src/docs/enum_glob_use.txt new file mode 100644 index 0000000000000..3776822c35b0c --- /dev/null +++ b/src/tools/clippy/src/docs/enum_glob_use.txt @@ -0,0 +1,24 @@ +### What it does +Checks for `use Enum::*`. + +### Why is this bad? +It is usually better style to use the prefixed name of +an enumeration variant, rather than importing variants. + +### Known problems +Old-style enumerations that prefix the variants are +still around. + +### Example +``` +use std::cmp::Ordering::*; + +foo(Less); +``` + +Use instead: +``` +use std::cmp::Ordering; + +foo(Ordering::Less) +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/enum_variant_names.txt b/src/tools/clippy/src/docs/enum_variant_names.txt new file mode 100644 index 0000000000000..e726925edda82 --- /dev/null +++ b/src/tools/clippy/src/docs/enum_variant_names.txt @@ -0,0 +1,30 @@ +### What it does +Detects enumeration variants that are prefixed or suffixed +by the same characters. + +### Why is this bad? +Enumeration variant names should specify their variant, +not repeat the enumeration name. + +### Limitations +Characters with no casing will be considered when comparing prefixes/suffixes +This applies to numbers and non-ascii characters without casing +e.g. `Foo1` and `Foo2` is considered to have different prefixes +(the prefixes are `Foo1` and `Foo2` respectively), as also `Bar螃`, `Bar蟹` + +### Example +``` +enum Cake { + BlackForestCake, + HummingbirdCake, + BattenbergCake, +} +``` +Use instead: +``` +enum Cake { + BlackForest, + Hummingbird, + Battenberg, +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/eq_op.txt b/src/tools/clippy/src/docs/eq_op.txt new file mode 100644 index 0000000000000..2d75a0ec546e7 --- /dev/null +++ b/src/tools/clippy/src/docs/eq_op.txt @@ -0,0 +1,22 @@ +### What it does +Checks for equal operands to comparison, logical and +bitwise, difference and division binary operators (`==`, `>`, etc., `&&`, +`||`, `&`, `|`, `^`, `-` and `/`). + +### Why is this bad? +This is usually just a typo or a copy and paste error. + +### Known problems +False negatives: We had some false positives regarding +calls (notably [racer](https://github.com/phildawes/racer) had one instance +of `x.pop() && x.pop()`), so we removed matching any function or method +calls. We may introduce a list of known pure functions in the future. + +### Example +``` +if x + 1 == x + 1 {} + +// or + +assert_eq!(a, a); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/equatable_if_let.txt b/src/tools/clippy/src/docs/equatable_if_let.txt new file mode 100644 index 0000000000000..9997046954c20 --- /dev/null +++ b/src/tools/clippy/src/docs/equatable_if_let.txt @@ -0,0 +1,23 @@ +### What it does +Checks for pattern matchings that can be expressed using equality. + +### Why is this bad? + +* It reads better and has less cognitive load because equality won't cause binding. +* It is a [Yoda condition](https://en.wikipedia.org/wiki/Yoda_conditions). Yoda conditions are widely +criticized for increasing the cognitive load of reading the code. +* Equality is a simple bool expression and can be merged with `&&` and `||` and +reuse if blocks + +### Example +``` +if let Some(2) = x { + do_thing(); +} +``` +Use instead: +``` +if x == Some(2) { + do_thing(); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/erasing_op.txt b/src/tools/clippy/src/docs/erasing_op.txt new file mode 100644 index 0000000000000..3d285a6d86e48 --- /dev/null +++ b/src/tools/clippy/src/docs/erasing_op.txt @@ -0,0 +1,15 @@ +### What it does +Checks for erasing operations, e.g., `x * 0`. + +### Why is this bad? +The whole expression can be replaced by zero. +This is most likely not the intended outcome and should probably be +corrected + +### Example +``` +let x = 1; +0 / x; +0 * x; +x & 0; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/err_expect.txt b/src/tools/clippy/src/docs/err_expect.txt new file mode 100644 index 0000000000000..1dc83c5ce0ee0 --- /dev/null +++ b/src/tools/clippy/src/docs/err_expect.txt @@ -0,0 +1,16 @@ +### What it does +Checks for `.err().expect()` calls on the `Result` type. + +### Why is this bad? +`.expect_err()` can be called directly to avoid the extra type conversion from `err()`. + +### Example +``` +let x: Result = Ok(10); +x.err().expect("Testing err().expect()"); +``` +Use instead: +``` +let x: Result = Ok(10); +x.expect_err("Testing expect_err"); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/excessive_precision.txt b/src/tools/clippy/src/docs/excessive_precision.txt new file mode 100644 index 0000000000000..517879c47152b --- /dev/null +++ b/src/tools/clippy/src/docs/excessive_precision.txt @@ -0,0 +1,18 @@ +### What it does +Checks for float literals with a precision greater +than that supported by the underlying type. + +### Why is this bad? +Rust will truncate the literal silently. + +### Example +``` +let v: f32 = 0.123_456_789_9; +println!("{}", v); // 0.123_456_789 +``` + +Use instead: +``` +let v: f64 = 0.123_456_789_9; +println!("{}", v); // 0.123_456_789_9 +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/exhaustive_enums.txt b/src/tools/clippy/src/docs/exhaustive_enums.txt new file mode 100644 index 0000000000000..d1032a7a29aa0 --- /dev/null +++ b/src/tools/clippy/src/docs/exhaustive_enums.txt @@ -0,0 +1,23 @@ +### What it does +Warns on any exported `enum`s that are not tagged `#[non_exhaustive]` + +### Why is this bad? +Exhaustive enums are typically fine, but a project which does +not wish to make a stability commitment around exported enums may wish to +disable them by default. + +### Example +``` +enum Foo { + Bar, + Baz +} +``` +Use instead: +``` +#[non_exhaustive] +enum Foo { + Bar, + Baz +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/exhaustive_structs.txt b/src/tools/clippy/src/docs/exhaustive_structs.txt new file mode 100644 index 0000000000000..fd6e4f5caf1f2 --- /dev/null +++ b/src/tools/clippy/src/docs/exhaustive_structs.txt @@ -0,0 +1,23 @@ +### What it does +Warns on any exported `structs`s that are not tagged `#[non_exhaustive]` + +### Why is this bad? +Exhaustive structs are typically fine, but a project which does +not wish to make a stability commitment around exported structs may wish to +disable them by default. + +### Example +``` +struct Foo { + bar: u8, + baz: String, +} +``` +Use instead: +``` +#[non_exhaustive] +struct Foo { + bar: u8, + baz: String, +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/exit.txt b/src/tools/clippy/src/docs/exit.txt new file mode 100644 index 0000000000000..1e6154d43e053 --- /dev/null +++ b/src/tools/clippy/src/docs/exit.txt @@ -0,0 +1,12 @@ +### What it does +`exit()` terminates the program and doesn't provide a +stack trace. + +### Why is this bad? +Ideally a program is terminated by finishing +the main function. + +### Example +``` +std::process::exit(0) +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/expect_fun_call.txt b/src/tools/clippy/src/docs/expect_fun_call.txt new file mode 100644 index 0000000000000..d82d9aa9baff2 --- /dev/null +++ b/src/tools/clippy/src/docs/expect_fun_call.txt @@ -0,0 +1,24 @@ +### What it does +Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`, +etc., and suggests to use `unwrap_or_else` instead + +### Why is this bad? +The function will always be called. + +### Known problems +If the function has side-effects, not calling it will +change the semantics of the program, but you shouldn't rely on that anyway. + +### Example +``` +foo.expect(&format!("Err {}: {}", err_code, err_msg)); + +// or + +foo.expect(format!("Err {}: {}", err_code, err_msg).as_str()); +``` + +Use instead: +``` +foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg)); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/expect_used.txt b/src/tools/clippy/src/docs/expect_used.txt new file mode 100644 index 0000000000000..4a6981e334fd3 --- /dev/null +++ b/src/tools/clippy/src/docs/expect_used.txt @@ -0,0 +1,26 @@ +### What it does +Checks for `.expect()` or `.expect_err()` calls on `Result`s and `.expect()` call on `Option`s. + +### Why is this bad? +Usually it is better to handle the `None` or `Err` case. +Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why +this lint is `Allow` by default. + +`result.expect()` will let the thread panic on `Err` +values. Normally, you want to implement more sophisticated error handling, +and propagate errors upwards with `?` operator. + +### Examples +``` +option.expect("one"); +result.expect("one"); +``` + +Use instead: +``` +option?; + +// or + +result?; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/expl_impl_clone_on_copy.txt b/src/tools/clippy/src/docs/expl_impl_clone_on_copy.txt new file mode 100644 index 0000000000000..391d93b6713cc --- /dev/null +++ b/src/tools/clippy/src/docs/expl_impl_clone_on_copy.txt @@ -0,0 +1,20 @@ +### What it does +Checks for explicit `Clone` implementations for `Copy` +types. + +### Why is this bad? +To avoid surprising behavior, these traits should +agree and the behavior of `Copy` cannot be overridden. In almost all +situations a `Copy` type should have a `Clone` implementation that does +nothing more than copy the object, which is what `#[derive(Copy, Clone)]` +gets you. + +### Example +``` +#[derive(Copy)] +struct Foo; + +impl Clone for Foo { + // .. +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/explicit_auto_deref.txt b/src/tools/clippy/src/docs/explicit_auto_deref.txt new file mode 100644 index 0000000000000..65b2563177252 --- /dev/null +++ b/src/tools/clippy/src/docs/explicit_auto_deref.txt @@ -0,0 +1,16 @@ +### What it does +Checks for dereferencing expressions which would be covered by auto-deref. + +### Why is this bad? +This unnecessarily complicates the code. + +### Example +``` +let x = String::new(); +let y: &str = &*x; +``` +Use instead: +``` +let x = String::new(); +let y: &str = &x; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/explicit_counter_loop.txt b/src/tools/clippy/src/docs/explicit_counter_loop.txt new file mode 100644 index 0000000000000..2661a43e10341 --- /dev/null +++ b/src/tools/clippy/src/docs/explicit_counter_loop.txt @@ -0,0 +1,21 @@ +### What it does +Checks `for` loops over slices with an explicit counter +and suggests the use of `.enumerate()`. + +### Why is this bad? +Using `.enumerate()` makes the intent more clear, +declutters the code and may be faster in some instances. + +### Example +``` +let mut i = 0; +for item in &v { + bar(i, *item); + i += 1; +} +``` + +Use instead: +``` +for (i, item) in v.iter().enumerate() { bar(i, *item); } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/explicit_deref_methods.txt b/src/tools/clippy/src/docs/explicit_deref_methods.txt new file mode 100644 index 0000000000000..e14e981c7073b --- /dev/null +++ b/src/tools/clippy/src/docs/explicit_deref_methods.txt @@ -0,0 +1,24 @@ +### What it does +Checks for explicit `deref()` or `deref_mut()` method calls. + +### Why is this bad? +Dereferencing by `&*x` or `&mut *x` is clearer and more concise, +when not part of a method chain. + +### Example +``` +use std::ops::Deref; +let a: &mut String = &mut String::from("foo"); +let b: &str = a.deref(); +``` + +Use instead: +``` +let a: &mut String = &mut String::from("foo"); +let b = &*a; +``` + +This lint excludes: +``` +let _ = d.unwrap().deref(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/explicit_into_iter_loop.txt b/src/tools/clippy/src/docs/explicit_into_iter_loop.txt new file mode 100644 index 0000000000000..3931dfd69a318 --- /dev/null +++ b/src/tools/clippy/src/docs/explicit_into_iter_loop.txt @@ -0,0 +1,20 @@ +### What it does +Checks for loops on `y.into_iter()` where `y` will do, and +suggests the latter. + +### Why is this bad? +Readability. + +### Example +``` +// with `y` a `Vec` or slice: +for x in y.into_iter() { + // .. +} +``` +can be rewritten to +``` +for x in y { + // .. +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/explicit_iter_loop.txt b/src/tools/clippy/src/docs/explicit_iter_loop.txt new file mode 100644 index 0000000000000..cabe72e91d04f --- /dev/null +++ b/src/tools/clippy/src/docs/explicit_iter_loop.txt @@ -0,0 +1,25 @@ +### What it does +Checks for loops on `x.iter()` where `&x` will do, and +suggests the latter. + +### Why is this bad? +Readability. + +### Known problems +False negatives. We currently only warn on some known +types. + +### Example +``` +// with `y` a `Vec` or slice: +for x in y.iter() { + // .. +} +``` + +Use instead: +``` +for x in &y { + // .. +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/explicit_write.txt b/src/tools/clippy/src/docs/explicit_write.txt new file mode 100644 index 0000000000000..eafed5d39e5c6 --- /dev/null +++ b/src/tools/clippy/src/docs/explicit_write.txt @@ -0,0 +1,18 @@ +### What it does +Checks for usage of `write!()` / `writeln()!` which can be +replaced with `(e)print!()` / `(e)println!()` + +### Why is this bad? +Using `(e)println! is clearer and more concise + +### Example +``` +writeln!(&mut std::io::stderr(), "foo: {:?}", bar).unwrap(); +writeln!(&mut std::io::stdout(), "foo: {:?}", bar).unwrap(); +``` + +Use instead: +``` +eprintln!("foo: {:?}", bar); +println!("foo: {:?}", bar); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/extend_with_drain.txt b/src/tools/clippy/src/docs/extend_with_drain.txt new file mode 100644 index 0000000000000..2f31dcf5f7401 --- /dev/null +++ b/src/tools/clippy/src/docs/extend_with_drain.txt @@ -0,0 +1,21 @@ +### What it does +Checks for occurrences where one vector gets extended instead of append + +### Why is this bad? +Using `append` instead of `extend` is more concise and faster + +### Example +``` +let mut a = vec![1, 2, 3]; +let mut b = vec![4, 5, 6]; + +a.extend(b.drain(..)); +``` + +Use instead: +``` +let mut a = vec![1, 2, 3]; +let mut b = vec![4, 5, 6]; + +a.append(&mut b); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/extra_unused_lifetimes.txt b/src/tools/clippy/src/docs/extra_unused_lifetimes.txt new file mode 100644 index 0000000000000..bc1814aa4752d --- /dev/null +++ b/src/tools/clippy/src/docs/extra_unused_lifetimes.txt @@ -0,0 +1,23 @@ +### What it does +Checks for lifetimes in generics that are never used +anywhere else. + +### Why is this bad? +The additional lifetimes make the code look more +complicated, while there is nothing out of the ordinary going on. Removing +them leads to more readable code. + +### Example +``` +// unnecessary lifetimes +fn unused_lifetime<'a>(x: u8) { + // .. +} +``` + +Use instead: +``` +fn no_lifetime(x: u8) { + // ... +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/fallible_impl_from.txt b/src/tools/clippy/src/docs/fallible_impl_from.txt new file mode 100644 index 0000000000000..588a5bb103d46 --- /dev/null +++ b/src/tools/clippy/src/docs/fallible_impl_from.txt @@ -0,0 +1,32 @@ +### What it does +Checks for impls of `From<..>` that contain `panic!()` or `unwrap()` + +### Why is this bad? +`TryFrom` should be used if there's a possibility of failure. + +### Example +``` +struct Foo(i32); + +impl From for Foo { + fn from(s: String) -> Self { + Foo(s.parse().unwrap()) + } +} +``` + +Use instead: +``` +struct Foo(i32); + +impl TryFrom for Foo { + type Error = (); + fn try_from(s: String) -> Result { + if let Ok(parsed) = s.parse() { + Ok(Foo(parsed)) + } else { + Err(()) + } + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/field_reassign_with_default.txt b/src/tools/clippy/src/docs/field_reassign_with_default.txt new file mode 100644 index 0000000000000..e58b7239fde9e --- /dev/null +++ b/src/tools/clippy/src/docs/field_reassign_with_default.txt @@ -0,0 +1,23 @@ +### What it does +Checks for immediate reassignment of fields initialized +with Default::default(). + +### Why is this bad? +It's more idiomatic to use the [functional update syntax](https://doc.rust-lang.org/reference/expressions/struct-expr.html#functional-update-syntax). + +### Known problems +Assignments to patterns that are of tuple type are not linted. + +### Example +``` +let mut a: A = Default::default(); +a.i = 42; +``` + +Use instead: +``` +let a = A { + i: 42, + .. Default::default() +}; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/filetype_is_file.txt b/src/tools/clippy/src/docs/filetype_is_file.txt new file mode 100644 index 0000000000000..ad14bd62c4de4 --- /dev/null +++ b/src/tools/clippy/src/docs/filetype_is_file.txt @@ -0,0 +1,29 @@ +### What it does +Checks for `FileType::is_file()`. + +### Why is this bad? +When people testing a file type with `FileType::is_file` +they are testing whether a path is something they can get bytes from. But +`is_file` doesn't cover special file types in unix-like systems, and doesn't cover +symlink in windows. Using `!FileType::is_dir()` is a better way to that intention. + +### Example +``` +let metadata = std::fs::metadata("foo.txt")?; +let filetype = metadata.file_type(); + +if filetype.is_file() { + // read file +} +``` + +should be written as: + +``` +let metadata = std::fs::metadata("foo.txt")?; +let filetype = metadata.file_type(); + +if !filetype.is_dir() { + // read file +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/filter_map_identity.txt b/src/tools/clippy/src/docs/filter_map_identity.txt new file mode 100644 index 0000000000000..83b666f2e2782 --- /dev/null +++ b/src/tools/clippy/src/docs/filter_map_identity.txt @@ -0,0 +1,14 @@ +### What it does +Checks for usage of `filter_map(|x| x)`. + +### Why is this bad? +Readability, this can be written more concisely by using `flatten`. + +### Example +``` +iter.filter_map(|x| x); +``` +Use instead: +``` +iter.flatten(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/filter_map_next.txt b/src/tools/clippy/src/docs/filter_map_next.txt new file mode 100644 index 0000000000000..b38620b56a50f --- /dev/null +++ b/src/tools/clippy/src/docs/filter_map_next.txt @@ -0,0 +1,16 @@ +### What it does +Checks for usage of `_.filter_map(_).next()`. + +### Why is this bad? +Readability, this can be written more concisely as +`_.find_map(_)`. + +### Example +``` + (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next(); +``` +Can be written as + +``` + (0..3).find_map(|x| if x == 2 { Some(x) } else { None }); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/filter_next.txt b/src/tools/clippy/src/docs/filter_next.txt new file mode 100644 index 0000000000000..898a74166dc14 --- /dev/null +++ b/src/tools/clippy/src/docs/filter_next.txt @@ -0,0 +1,16 @@ +### What it does +Checks for usage of `_.filter(_).next()`. + +### Why is this bad? +Readability, this can be written more concisely as +`_.find(_)`. + +### Example +``` +vec.iter().filter(|x| **x == 0).next(); +``` + +Use instead: +``` +vec.iter().find(|x| **x == 0); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/flat_map_identity.txt b/src/tools/clippy/src/docs/flat_map_identity.txt new file mode 100644 index 0000000000000..a5ee79b4982fb --- /dev/null +++ b/src/tools/clippy/src/docs/flat_map_identity.txt @@ -0,0 +1,14 @@ +### What it does +Checks for usage of `flat_map(|x| x)`. + +### Why is this bad? +Readability, this can be written more concisely by using `flatten`. + +### Example +``` +iter.flat_map(|x| x); +``` +Can be written as +``` +iter.flatten(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/flat_map_option.txt b/src/tools/clippy/src/docs/flat_map_option.txt new file mode 100644 index 0000000000000..d50b9156d3654 --- /dev/null +++ b/src/tools/clippy/src/docs/flat_map_option.txt @@ -0,0 +1,16 @@ +### What it does +Checks for usages of `Iterator::flat_map()` where `filter_map()` could be +used instead. + +### Why is this bad? +When applicable, `filter_map()` is more clear since it shows that +`Option` is used to produce 0 or 1 items. + +### Example +``` +let nums: Vec = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect(); +``` +Use instead: +``` +let nums: Vec = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/float_arithmetic.txt b/src/tools/clippy/src/docs/float_arithmetic.txt new file mode 100644 index 0000000000000..1f9bce5abd59f --- /dev/null +++ b/src/tools/clippy/src/docs/float_arithmetic.txt @@ -0,0 +1,11 @@ +### What it does +Checks for float arithmetic. + +### Why is this bad? +For some embedded systems or kernel development, it +can be useful to rule out floating-point numbers. + +### Example +``` +a + 1.0; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/float_cmp.txt b/src/tools/clippy/src/docs/float_cmp.txt new file mode 100644 index 0000000000000..c19907c903e9d --- /dev/null +++ b/src/tools/clippy/src/docs/float_cmp.txt @@ -0,0 +1,28 @@ +### What it does +Checks for (in-)equality comparisons on floating-point +values (apart from zero), except in functions called `*eq*` (which probably +implement equality for a type involving floats). + +### Why is this bad? +Floating point calculations are usually imprecise, so +asking if two values are *exactly* equal is asking for trouble. For a good +guide on what to do, see [the floating point +guide](http://www.floating-point-gui.de/errors/comparison). + +### Example +``` +let x = 1.2331f64; +let y = 1.2332f64; + +if y == 1.23f64 { } +if y != x {} // where both are floats +``` + +Use instead: +``` +let error_margin = f64::EPSILON; // Use an epsilon for comparison +// Or, if Rust <= 1.42, use `std::f64::EPSILON` constant instead. +// let error_margin = std::f64::EPSILON; +if (y - 1.23f64).abs() < error_margin { } +if (y - x).abs() > error_margin { } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/float_cmp_const.txt b/src/tools/clippy/src/docs/float_cmp_const.txt new file mode 100644 index 0000000000000..9208feaacd810 --- /dev/null +++ b/src/tools/clippy/src/docs/float_cmp_const.txt @@ -0,0 +1,26 @@ +### What it does +Checks for (in-)equality comparisons on floating-point +value and constant, except in functions called `*eq*` (which probably +implement equality for a type involving floats). + +### Why is this bad? +Floating point calculations are usually imprecise, so +asking if two values are *exactly* equal is asking for trouble. For a good +guide on what to do, see [the floating point +guide](http://www.floating-point-gui.de/errors/comparison). + +### Example +``` +let x: f64 = 1.0; +const ONE: f64 = 1.00; + +if x == ONE { } // where both are floats +``` + +Use instead: +``` +let error_margin = f64::EPSILON; // Use an epsilon for comparison +// Or, if Rust <= 1.42, use `std::f64::EPSILON` constant instead. +// let error_margin = std::f64::EPSILON; +if (x - ONE).abs() < error_margin { } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/float_equality_without_abs.txt b/src/tools/clippy/src/docs/float_equality_without_abs.txt new file mode 100644 index 0000000000000..556b574e15d30 --- /dev/null +++ b/src/tools/clippy/src/docs/float_equality_without_abs.txt @@ -0,0 +1,26 @@ +### What it does +Checks for statements of the form `(a - b) < f32::EPSILON` or +`(a - b) < f64::EPSILON`. Notes the missing `.abs()`. + +### Why is this bad? +The code without `.abs()` is more likely to have a bug. + +### Known problems +If the user can ensure that b is larger than a, the `.abs()` is +technically unnecessary. However, it will make the code more robust and doesn't have any +large performance implications. If the abs call was deliberately left out for performance +reasons, it is probably better to state this explicitly in the code, which then can be done +with an allow. + +### Example +``` +pub fn is_roughly_equal(a: f32, b: f32) -> bool { + (a - b) < f32::EPSILON +} +``` +Use instead: +``` +pub fn is_roughly_equal(a: f32, b: f32) -> bool { + (a - b).abs() < f32::EPSILON +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/fn_address_comparisons.txt b/src/tools/clippy/src/docs/fn_address_comparisons.txt new file mode 100644 index 0000000000000..7d2b7b681deb1 --- /dev/null +++ b/src/tools/clippy/src/docs/fn_address_comparisons.txt @@ -0,0 +1,17 @@ +### What it does +Checks for comparisons with an address of a function item. + +### Why is this bad? +Function item address is not guaranteed to be unique and could vary +between different code generation units. Furthermore different function items could have +the same address after being merged together. + +### Example +``` +type F = fn(); +fn a() {} +let f: F = a; +if f == a { + // ... +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/fn_params_excessive_bools.txt b/src/tools/clippy/src/docs/fn_params_excessive_bools.txt new file mode 100644 index 0000000000000..2eae0563368c1 --- /dev/null +++ b/src/tools/clippy/src/docs/fn_params_excessive_bools.txt @@ -0,0 +1,31 @@ +### What it does +Checks for excessive use of +bools in function definitions. + +### Why is this bad? +Calls to such functions +are confusing and error prone, because it's +hard to remember argument order and you have +no type system support to back you up. Using +two-variant enums instead of bools often makes +API easier to use. + +### Example +``` +fn f(is_round: bool, is_hot: bool) { ... } +``` + +Use instead: +``` +enum Shape { + Round, + Spiky, +} + +enum Temperature { + Hot, + IceCold, +} + +fn f(shape: Shape, temperature: Temperature) { ... } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/fn_to_numeric_cast.txt b/src/tools/clippy/src/docs/fn_to_numeric_cast.txt new file mode 100644 index 0000000000000..1f587f6d71768 --- /dev/null +++ b/src/tools/clippy/src/docs/fn_to_numeric_cast.txt @@ -0,0 +1,21 @@ +### What it does +Checks for casts of function pointers to something other than usize + +### Why is this bad? +Casting a function pointer to anything other than usize/isize is not portable across +architectures, because you end up losing bits if the target type is too small or end up with a +bunch of extra bits that waste space and add more instructions to the final binary than +strictly necessary for the problem + +Casting to isize also doesn't make sense since there are no signed addresses. + +### Example +``` +fn fun() -> i32 { 1 } +let _ = fun as i64; +``` + +Use instead: +``` +let _ = fun as usize; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/fn_to_numeric_cast_any.txt b/src/tools/clippy/src/docs/fn_to_numeric_cast_any.txt new file mode 100644 index 0000000000000..ee3c33d237255 --- /dev/null +++ b/src/tools/clippy/src/docs/fn_to_numeric_cast_any.txt @@ -0,0 +1,35 @@ +### What it does +Checks for casts of a function pointer to any integer type. + +### Why is this bad? +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 +order to avoid mistakes. Alternatively, you can use this lint to audit all uses of function +pointer casts in your code. + +### Example +``` +// fn1 is cast as `usize` +fn fn1() -> u16 { + 1 +}; +let _ = fn1 as usize; +``` + +Use instead: +``` +// maybe you intended to call the function? +fn fn2() -> u16 { + 1 +}; +let _ = fn2() as usize; + +// or + +// maybe you intended to cast it to a function type? +fn fn3() -> u16 { + 1 +} +let _ = fn3 as fn() -> u16; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/fn_to_numeric_cast_with_truncation.txt b/src/tools/clippy/src/docs/fn_to_numeric_cast_with_truncation.txt new file mode 100644 index 0000000000000..69f12fa319f18 --- /dev/null +++ b/src/tools/clippy/src/docs/fn_to_numeric_cast_with_truncation.txt @@ -0,0 +1,26 @@ +### What it does +Checks for casts of a function pointer to a numeric type not wide enough to +store address. + +### Why is this bad? +Such a cast discards some bits of the function's address. If this is intended, it would be more +clearly expressed by casting to usize first, then casting the usize to the intended type (with +a comment) to perform the truncation. + +### Example +``` +fn fn1() -> i16 { + 1 +}; +let _ = fn1 as i32; +``` + +Use instead: +``` +// Cast to usize first, then comment with the reason for the truncation +fn fn1() -> i16 { + 1 +}; +let fn_ptr = fn1 as usize; +let fn_ptr_truncated = fn_ptr as i32; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/for_kv_map.txt b/src/tools/clippy/src/docs/for_kv_map.txt new file mode 100644 index 0000000000000..a9a2ffee9c743 --- /dev/null +++ b/src/tools/clippy/src/docs/for_kv_map.txt @@ -0,0 +1,22 @@ +### What it does +Checks for iterating a map (`HashMap` or `BTreeMap`) and +ignoring either the keys or values. + +### Why is this bad? +Readability. There are `keys` and `values` methods that +can be used to express that don't need the values or keys. + +### Example +``` +for (k, _) in &map { + .. +} +``` + +could be replaced by + +``` +for k in map.keys() { + .. +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/for_loops_over_fallibles.txt b/src/tools/clippy/src/docs/for_loops_over_fallibles.txt new file mode 100644 index 0000000000000..c5a7508e45d40 --- /dev/null +++ b/src/tools/clippy/src/docs/for_loops_over_fallibles.txt @@ -0,0 +1,32 @@ +### What it does +Checks for `for` loops over `Option` or `Result` values. + +### Why is this bad? +Readability. This is more clearly expressed as an `if +let`. + +### Example +``` +for x in opt { + // .. +} + +for x in &res { + // .. +} + +for x in res.iter() { + // .. +} +``` + +Use instead: +``` +if let Some(x) = opt { + // .. +} + +if let Ok(x) = res { + // .. +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/forget_copy.txt b/src/tools/clippy/src/docs/forget_copy.txt new file mode 100644 index 0000000000000..1d100912e9a48 --- /dev/null +++ b/src/tools/clippy/src/docs/forget_copy.txt @@ -0,0 +1,21 @@ +### What it does +Checks for calls to `std::mem::forget` with a value that +derives the Copy trait + +### Why is this bad? +Calling `std::mem::forget` [does nothing for types that +implement Copy](https://doc.rust-lang.org/std/mem/fn.drop.html) since the +value will be copied and moved into the function on invocation. + +An alternative, but also valid, explanation is that Copy types do not +implement +the Drop trait, which means they have no destructors. Without a destructor, +there +is nothing for `std::mem::forget` to ignore. + +### Example +``` +let x: i32 = 42; // i32 implements Copy +std::mem::forget(x) // A copy of x is passed to the function, leaving the + // original unaffected +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/forget_non_drop.txt b/src/tools/clippy/src/docs/forget_non_drop.txt new file mode 100644 index 0000000000000..3307d654c17f2 --- /dev/null +++ b/src/tools/clippy/src/docs/forget_non_drop.txt @@ -0,0 +1,13 @@ +### What it does +Checks for calls to `std::mem::forget` with a value that does not implement `Drop`. + +### Why is this bad? +Calling `std::mem::forget` is no different than dropping such a type. A different value may +have been intended. + +### Example +``` +struct Foo; +let x = Foo; +std::mem::forget(x); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/forget_ref.txt b/src/tools/clippy/src/docs/forget_ref.txt new file mode 100644 index 0000000000000..874fb8786068d --- /dev/null +++ b/src/tools/clippy/src/docs/forget_ref.txt @@ -0,0 +1,15 @@ +### What it does +Checks for calls to `std::mem::forget` with a reference +instead of an owned value. + +### Why is this bad? +Calling `forget` on a reference will only forget the +reference itself, which is a no-op. It will not forget the underlying +referenced +value, which is likely what was intended. + +### Example +``` +let x = Box::new(1); +std::mem::forget(&x) // Should have been forget(x), x will still be dropped +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/format_in_format_args.txt b/src/tools/clippy/src/docs/format_in_format_args.txt new file mode 100644 index 0000000000000..ac498472f017f --- /dev/null +++ b/src/tools/clippy/src/docs/format_in_format_args.txt @@ -0,0 +1,16 @@ +### What it does +Detects `format!` within the arguments of another macro that does +formatting such as `format!` itself, `write!` or `println!`. Suggests +inlining the `format!` call. + +### Why is this bad? +The recommended code is both shorter and avoids a temporary allocation. + +### Example +``` +println!("error: {}", format!("something failed at {}", Location::caller())); +``` +Use instead: +``` +println!("error: something failed at {}", Location::caller()); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/format_push_string.txt b/src/tools/clippy/src/docs/format_push_string.txt new file mode 100644 index 0000000000000..ca409ebc7ec26 --- /dev/null +++ b/src/tools/clippy/src/docs/format_push_string.txt @@ -0,0 +1,26 @@ +### What it does +Detects cases where the result of a `format!` call is +appended to an existing `String`. + +### Why is this bad? +Introduces an extra, avoidable heap allocation. + +### Known problems +`format!` returns a `String` but `write!` returns a `Result`. +Thus you are forced to ignore the `Err` variant to achieve the same API. + +While using `write!` in the suggested way should never fail, this isn't necessarily clear to the programmer. + +### Example +``` +let mut s = String::new(); +s += &format!("0x{:X}", 1024); +s.push_str(&format!("0x{:X}", 1024)); +``` +Use instead: +``` +use std::fmt::Write as _; // import without risk of name clashing + +let mut s = String::new(); +let _ = write!(s, "0x{:X}", 1024); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/from_iter_instead_of_collect.txt b/src/tools/clippy/src/docs/from_iter_instead_of_collect.txt new file mode 100644 index 0000000000000..f3fd275972645 --- /dev/null +++ b/src/tools/clippy/src/docs/from_iter_instead_of_collect.txt @@ -0,0 +1,24 @@ +### What it does +Checks for `from_iter()` function calls on types that implement the `FromIterator` +trait. + +### Why is this bad? +It is recommended style to use collect. See +[FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html) + +### Example +``` +let five_fives = std::iter::repeat(5).take(5); + +let v = Vec::from_iter(five_fives); + +assert_eq!(v, vec![5, 5, 5, 5, 5]); +``` +Use instead: +``` +let five_fives = std::iter::repeat(5).take(5); + +let v: Vec = five_fives.collect(); + +assert_eq!(v, vec![5, 5, 5, 5, 5]); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/from_over_into.txt b/src/tools/clippy/src/docs/from_over_into.txt new file mode 100644 index 0000000000000..0770bcc42c270 --- /dev/null +++ b/src/tools/clippy/src/docs/from_over_into.txt @@ -0,0 +1,26 @@ +### What it does +Searches for implementations of the `Into<..>` trait and suggests to implement `From<..>` instead. + +### Why is this bad? +According the std docs implementing `From<..>` is preferred since it gives you `Into<..>` for free where the reverse isn't true. + +### Example +``` +struct StringWrapper(String); + +impl Into for String { + fn into(self) -> StringWrapper { + StringWrapper(self) + } +} +``` +Use instead: +``` +struct StringWrapper(String); + +impl From for StringWrapper { + fn from(s: String) -> StringWrapper { + StringWrapper(s) + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/from_str_radix_10.txt b/src/tools/clippy/src/docs/from_str_radix_10.txt new file mode 100644 index 0000000000000..f6f319d3eaa18 --- /dev/null +++ b/src/tools/clippy/src/docs/from_str_radix_10.txt @@ -0,0 +1,25 @@ +### What it does + +Checks for function invocations of the form `primitive::from_str_radix(s, 10)` + +### Why is this bad? + +This specific common use case can be rewritten as `s.parse::()` +(and in most cases, the turbofish can be removed), which reduces code length +and complexity. + +### Known problems + +This lint may suggest using (&).parse() instead of .parse() directly +in some cases, which is correct but adds unnecessary complexity to the code. + +### Example +``` +let input: &str = get_input(); +let num = u16::from_str_radix(input, 10)?; +``` +Use instead: +``` +let input: &str = get_input(); +let num: u16 = input.parse()?; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/future_not_send.txt b/src/tools/clippy/src/docs/future_not_send.txt new file mode 100644 index 0000000000000..0aa048d273551 --- /dev/null +++ b/src/tools/clippy/src/docs/future_not_send.txt @@ -0,0 +1,29 @@ +### What it does +This lint requires Future implementations returned from +functions and methods to implement the `Send` marker trait. It is mostly +used by library authors (public and internal) that target an audience where +multithreaded executors are likely to be used for running these Futures. + +### Why is this bad? +A Future implementation captures some state that it +needs to eventually produce its final value. When targeting a multithreaded +executor (which is the norm on non-embedded devices) this means that this +state may need to be transported to other threads, in other words the +whole Future needs to implement the `Send` marker trait. If it does not, +then the resulting Future cannot be submitted to a thread pool in the +end user’s code. + +Especially for generic functions it can be confusing to leave the +discovery of this problem to the end user: the reported error location +will be far from its cause and can in many cases not even be fixed without +modifying the library where the offending Future implementation is +produced. + +### Example +``` +async fn not_send(bytes: std::rc::Rc<[u8]>) {} +``` +Use instead: +``` +async fn is_send(bytes: std::sync::Arc<[u8]>) {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/get_first.txt b/src/tools/clippy/src/docs/get_first.txt new file mode 100644 index 0000000000000..c905a737ddf3f --- /dev/null +++ b/src/tools/clippy/src/docs/get_first.txt @@ -0,0 +1,19 @@ +### What it does +Checks for using `x.get(0)` instead of +`x.first()`. + +### Why is this bad? +Using `x.first()` is easier to read and has the same +result. + +### Example +``` +let x = vec![2, 3, 5]; +let first_element = x.get(0); +``` + +Use instead: +``` +let x = vec![2, 3, 5]; +let first_element = x.first(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/get_last_with_len.txt b/src/tools/clippy/src/docs/get_last_with_len.txt new file mode 100644 index 0000000000000..31c7f269586ab --- /dev/null +++ b/src/tools/clippy/src/docs/get_last_with_len.txt @@ -0,0 +1,26 @@ +### What it does +Checks for using `x.get(x.len() - 1)` instead of +`x.last()`. + +### Why is this bad? +Using `x.last()` is easier to read and has the same +result. + +Note that using `x[x.len() - 1]` is semantically different from +`x.last()`. Indexing into the array will panic on out-of-bounds +accesses, while `x.get()` and `x.last()` will return `None`. + +There is another lint (get_unwrap) that covers the case of using +`x.get(index).unwrap()` instead of `x[index]`. + +### Example +``` +let x = vec![2, 3, 5]; +let last_element = x.get(x.len() - 1); +``` + +Use instead: +``` +let x = vec![2, 3, 5]; +let last_element = x.last(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/get_unwrap.txt b/src/tools/clippy/src/docs/get_unwrap.txt new file mode 100644 index 0000000000000..8defc22244169 --- /dev/null +++ b/src/tools/clippy/src/docs/get_unwrap.txt @@ -0,0 +1,30 @@ +### What it does +Checks for use of `.get().unwrap()` (or +`.get_mut().unwrap`) on a standard library type which implements `Index` + +### Why is this bad? +Using the Index trait (`[]`) is more clear and more +concise. + +### Known problems +Not a replacement for error handling: Using either +`.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic` +if the value being accessed is `None`. If the use of `.get().unwrap()` is a +temporary placeholder for dealing with the `Option` type, then this does +not mitigate the need for error handling. If there is a chance that `.get()` +will be `None` in your program, then it is advisable that the `None` case +is handled in a future refactor instead of using `.unwrap()` or the Index +trait. + +### Example +``` +let mut some_vec = vec![0, 1, 2, 3]; +let last = some_vec.get(3).unwrap(); +*some_vec.get_mut(0).unwrap() = 1; +``` +The correct use would be: +``` +let mut some_vec = vec![0, 1, 2, 3]; +let last = some_vec[3]; +some_vec[0] = 1; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/identity_op.txt b/src/tools/clippy/src/docs/identity_op.txt new file mode 100644 index 0000000000000..a8e40bb43e9d5 --- /dev/null +++ b/src/tools/clippy/src/docs/identity_op.txt @@ -0,0 +1,11 @@ +### What it does +Checks for identity operations, e.g., `x + 0`. + +### Why is this bad? +This code can be removed without changing the +meaning. So it just obscures what's going on. Delete it mercilessly. + +### Example +``` +x / 1 + 0 * 1 - 0 | 0; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/if_let_mutex.txt b/src/tools/clippy/src/docs/if_let_mutex.txt new file mode 100644 index 0000000000000..4d873ade9ace3 --- /dev/null +++ b/src/tools/clippy/src/docs/if_let_mutex.txt @@ -0,0 +1,25 @@ +### What it does +Checks for `Mutex::lock` calls in `if let` expression +with lock calls in any of the else blocks. + +### Why is this bad? +The Mutex lock remains held for the whole +`if let ... else` block and deadlocks. + +### Example +``` +if let Ok(thing) = mutex.lock() { + do_thing(); +} else { + mutex.lock(); +} +``` +Should be written +``` +let locked = mutex.lock(); +if let Ok(thing) = locked { + do_thing(thing); +} else { + use_locked(locked); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/if_not_else.txt b/src/tools/clippy/src/docs/if_not_else.txt new file mode 100644 index 0000000000000..0e5ac4ce6bb80 --- /dev/null +++ b/src/tools/clippy/src/docs/if_not_else.txt @@ -0,0 +1,25 @@ +### What it does +Checks for usage of `!` or `!=` in an if condition with an +else branch. + +### Why is this bad? +Negations reduce the readability of statements. + +### Example +``` +if !v.is_empty() { + a() +} else { + b() +} +``` + +Could be written: + +``` +if v.is_empty() { + b() +} else { + a() +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/if_same_then_else.txt b/src/tools/clippy/src/docs/if_same_then_else.txt new file mode 100644 index 0000000000000..75127016bb8c1 --- /dev/null +++ b/src/tools/clippy/src/docs/if_same_then_else.txt @@ -0,0 +1,15 @@ +### What it does +Checks for `if/else` with the same body as the *then* part +and the *else* part. + +### Why is this bad? +This is probably a copy & paste error. + +### Example +``` +let foo = if … { + 42 +} else { + 42 +}; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/if_then_some_else_none.txt b/src/tools/clippy/src/docs/if_then_some_else_none.txt new file mode 100644 index 0000000000000..13744f920e362 --- /dev/null +++ b/src/tools/clippy/src/docs/if_then_some_else_none.txt @@ -0,0 +1,26 @@ +### What it does +Checks for if-else that could be written using either `bool::then` or `bool::then_some`. + +### Why is this bad? +Looks a little redundant. Using `bool::then` is more concise and incurs no loss of clarity. +For simple calculations and known values, use `bool::then_some`, which is eagerly evaluated +in comparison to `bool::then`. + +### Example +``` +let a = if v.is_empty() { + println!("true!"); + Some(42) +} else { + None +}; +``` + +Could be written: + +``` +let a = v.is_empty().then(|| { + println!("true!"); + 42 +}); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/ifs_same_cond.txt b/src/tools/clippy/src/docs/ifs_same_cond.txt new file mode 100644 index 0000000000000..024ba5df93a63 --- /dev/null +++ b/src/tools/clippy/src/docs/ifs_same_cond.txt @@ -0,0 +1,25 @@ +### What it does +Checks for consecutive `if`s with the same condition. + +### Why is this bad? +This is probably a copy & paste error. + +### Example +``` +if a == b { + … +} else if a == b { + … +} +``` + +Note that this lint ignores all conditions with a function call as it could +have side effects: + +``` +if foo() { + … +} else if foo() { // not linted + … +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/implicit_clone.txt b/src/tools/clippy/src/docs/implicit_clone.txt new file mode 100644 index 0000000000000..f5aa112c52c36 --- /dev/null +++ b/src/tools/clippy/src/docs/implicit_clone.txt @@ -0,0 +1,19 @@ +### What it does +Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer. + +### Why is this bad? +These methods do the same thing as `_.clone()` but may be confusing as +to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned. + +### Example +``` +let a = vec![1, 2, 3]; +let b = a.to_vec(); +let c = a.to_owned(); +``` +Use instead: +``` +let a = vec![1, 2, 3]; +let b = a.clone(); +let c = a.clone(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/implicit_hasher.txt b/src/tools/clippy/src/docs/implicit_hasher.txt new file mode 100644 index 0000000000000..0c1f76620f51d --- /dev/null +++ b/src/tools/clippy/src/docs/implicit_hasher.txt @@ -0,0 +1,26 @@ +### What it does +Checks for public `impl` or `fn` missing generalization +over different hashers and implicitly defaulting to the default hashing +algorithm (`SipHash`). + +### Why is this bad? +`HashMap` or `HashSet` with custom hashers cannot be +used with them. + +### Known problems +Suggestions for replacing constructors can contain +false-positives. Also applying suggestions can require modification of other +pieces of code, possibly including external crates. + +### Example +``` +impl Serialize for HashMap { } + +pub fn foo(map: &mut HashMap) { } +``` +could be rewritten as +``` +impl Serialize for HashMap { } + +pub fn foo(map: &mut HashMap) { } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/implicit_return.txt b/src/tools/clippy/src/docs/implicit_return.txt new file mode 100644 index 0000000000000..ee65a636b38c5 --- /dev/null +++ b/src/tools/clippy/src/docs/implicit_return.txt @@ -0,0 +1,22 @@ +### What it does +Checks for missing return statements at the end of a block. + +### Why is this bad? +Actually omitting the return keyword is idiomatic Rust code. Programmers +coming from other languages might prefer the expressiveness of `return`. It's possible to miss +the last returning statement because the only difference is a missing `;`. Especially in bigger +code with multiple return paths having a `return` keyword makes it easier to find the +corresponding statements. + +### Example +``` +fn foo(x: usize) -> usize { + x +} +``` +add return +``` +fn foo(x: usize) -> usize { + return x; +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/implicit_saturating_sub.txt b/src/tools/clippy/src/docs/implicit_saturating_sub.txt new file mode 100644 index 0000000000000..03b47905a2118 --- /dev/null +++ b/src/tools/clippy/src/docs/implicit_saturating_sub.txt @@ -0,0 +1,21 @@ +### What it does +Checks for implicit saturating subtraction. + +### Why is this bad? +Simplicity and readability. Instead we can easily use an builtin function. + +### Example +``` +let mut i: u32 = end - start; + +if i != 0 { + i -= 1; +} +``` + +Use instead: +``` +let mut i: u32 = end - start; + +i = i.saturating_sub(1); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/imprecise_flops.txt b/src/tools/clippy/src/docs/imprecise_flops.txt new file mode 100644 index 0000000000000..e84d81cea98e0 --- /dev/null +++ b/src/tools/clippy/src/docs/imprecise_flops.txt @@ -0,0 +1,23 @@ +### What it does +Looks for floating-point expressions that +can be expressed using built-in methods to improve accuracy +at the cost of performance. + +### Why is this bad? +Negatively impacts accuracy. + +### Example +``` +let a = 3f32; +let _ = a.powf(1.0 / 3.0); +let _ = (1.0 + a).ln(); +let _ = a.exp() - 1.0; +``` + +Use instead: +``` +let a = 3f32; +let _ = a.cbrt(); +let _ = a.ln_1p(); +let _ = a.exp_m1(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/inconsistent_digit_grouping.txt b/src/tools/clippy/src/docs/inconsistent_digit_grouping.txt new file mode 100644 index 0000000000000..aa0b072de1c40 --- /dev/null +++ b/src/tools/clippy/src/docs/inconsistent_digit_grouping.txt @@ -0,0 +1,17 @@ +### What it does +Warns if an integral or floating-point constant is +grouped inconsistently with underscores. + +### Why is this bad? +Readers may incorrectly interpret inconsistently +grouped digits. + +### Example +``` +618_64_9189_73_511 +``` + +Use instead: +``` +61_864_918_973_511 +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/inconsistent_struct_constructor.txt b/src/tools/clippy/src/docs/inconsistent_struct_constructor.txt new file mode 100644 index 0000000000000..eb682109a54ee --- /dev/null +++ b/src/tools/clippy/src/docs/inconsistent_struct_constructor.txt @@ -0,0 +1,40 @@ +### What it does +Checks for struct constructors where all fields are shorthand and +the order of the field init shorthand in the constructor is inconsistent +with the order in the struct definition. + +### Why is this bad? +Since the order of fields in a constructor doesn't affect the +resulted instance as the below example indicates, + +``` +#[derive(Debug, PartialEq, Eq)] +struct Foo { + x: i32, + y: i32, +} +let x = 1; +let y = 2; + +// This assertion never fails: +assert_eq!(Foo { x, y }, Foo { y, x }); +``` + +inconsistent order can be confusing and decreases readability and consistency. + +### Example +``` +struct Foo { + x: i32, + y: i32, +} +let x = 1; +let y = 2; + +Foo { y, x }; +``` + +Use instead: +``` +Foo { x, y }; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/index_refutable_slice.txt b/src/tools/clippy/src/docs/index_refutable_slice.txt new file mode 100644 index 0000000000000..8a7d52761af81 --- /dev/null +++ b/src/tools/clippy/src/docs/index_refutable_slice.txt @@ -0,0 +1,29 @@ +### What it does +The lint checks for slice bindings in patterns that are only used to +access individual slice values. + +### Why is this bad? +Accessing slice values using indices can lead to panics. Using refutable +patterns can avoid these. Binding to individual values also improves the +readability as they can be named. + +### Limitations +This lint currently only checks for immutable access inside `if let` +patterns. + +### Example +``` +let slice: Option<&[u32]> = Some(&[1, 2, 3]); + +if let Some(slice) = slice { + println!("{}", slice[0]); +} +``` +Use instead: +``` +let slice: Option<&[u32]> = Some(&[1, 2, 3]); + +if let Some(&[first, ..]) = slice { + println!("{}", first); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/indexing_slicing.txt b/src/tools/clippy/src/docs/indexing_slicing.txt new file mode 100644 index 0000000000000..76ca6ed318b38 --- /dev/null +++ b/src/tools/clippy/src/docs/indexing_slicing.txt @@ -0,0 +1,33 @@ +### What it does +Checks for usage of indexing or slicing. Arrays are special cases, this lint +does report on arrays if we can tell that slicing operations are in bounds and does not +lint on constant `usize` indexing on arrays because that is handled by rustc's `const_err` lint. + +### Why is this bad? +Indexing and slicing can panic at runtime and there are +safe alternatives. + +### Example +``` +// Vector +let x = vec![0; 5]; + +x[2]; +&x[2..100]; + +// Array +let y = [0, 1, 2, 3]; + +&y[10..100]; +&y[10..]; +``` + +Use instead: +``` + +x.get(2); +x.get(2..100); + +y.get(10); +y.get(10..100); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/ineffective_bit_mask.txt b/src/tools/clippy/src/docs/ineffective_bit_mask.txt new file mode 100644 index 0000000000000..f6e7ef556215b --- /dev/null +++ b/src/tools/clippy/src/docs/ineffective_bit_mask.txt @@ -0,0 +1,25 @@ +### What it does +Checks for bit masks in comparisons which can be removed +without changing the outcome. The basic structure can be seen in the +following table: + +|Comparison| Bit Op |Example |equals | +|----------|----------|------------|-------| +|`>` / `<=`|`\|` / `^`|`x \| 2 > 3`|`x > 3`| +|`<` / `>=`|`\|` / `^`|`x ^ 1 < 4` |`x < 4`| + +### Why is this bad? +Not equally evil as [`bad_bit_mask`](#bad_bit_mask), +but still a bit misleading, because the bit mask is ineffective. + +### Known problems +False negatives: This lint will only match instances +where we have figured out the math (which is for a power-of-two compared +value). This means things like `x | 1 >= 7` (which would be better written +as `x >= 6`) will not be reported (but bit masks like this are fairly +uncommon). + +### Example +``` +if (x | 1 > 3) { } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/inefficient_to_string.txt b/src/tools/clippy/src/docs/inefficient_to_string.txt new file mode 100644 index 0000000000000..f7061d1ce7b08 --- /dev/null +++ b/src/tools/clippy/src/docs/inefficient_to_string.txt @@ -0,0 +1,17 @@ +### What it does +Checks for usage of `.to_string()` on an `&&T` where +`T` implements `ToString` directly (like `&&str` or `&&String`). + +### Why is this bad? +This bypasses the specialized implementation of +`ToString` and instead goes through the more expensive string formatting +facilities. + +### Example +``` +// Generic implementation for `T: Display` is used (slow) +["foo", "bar"].iter().map(|s| s.to_string()); + +// OK, the specialized impl is used +["foo", "bar"].iter().map(|&s| s.to_string()); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/infallible_destructuring_match.txt b/src/tools/clippy/src/docs/infallible_destructuring_match.txt new file mode 100644 index 0000000000000..4b5d3c4ba6c40 --- /dev/null +++ b/src/tools/clippy/src/docs/infallible_destructuring_match.txt @@ -0,0 +1,29 @@ +### What it does +Checks for matches being used to destructure a single-variant enum +or tuple struct where a `let` will suffice. + +### Why is this bad? +Just readability – `let` doesn't nest, whereas a `match` does. + +### Example +``` +enum Wrapper { + Data(i32), +} + +let wrapper = Wrapper::Data(42); + +let data = match wrapper { + Wrapper::Data(i) => i, +}; +``` + +The correct use would be: +``` +enum Wrapper { + Data(i32), +} + +let wrapper = Wrapper::Data(42); +let Wrapper::Data(data) = wrapper; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/infinite_iter.txt b/src/tools/clippy/src/docs/infinite_iter.txt new file mode 100644 index 0000000000000..8a22fabc5492c --- /dev/null +++ b/src/tools/clippy/src/docs/infinite_iter.txt @@ -0,0 +1,13 @@ +### What it does +Checks for iteration that is guaranteed to be infinite. + +### Why is this bad? +While there may be places where this is acceptable +(e.g., in event streams), in most cases this is simply an error. + +### Example +``` +use std::iter; + +iter::repeat(1_u8).collect::>(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/inherent_to_string.txt b/src/tools/clippy/src/docs/inherent_to_string.txt new file mode 100644 index 0000000000000..b18e600e9e67b --- /dev/null +++ b/src/tools/clippy/src/docs/inherent_to_string.txt @@ -0,0 +1,29 @@ +### What it does +Checks for the definition of inherent methods with a signature of `to_string(&self) -> String`. + +### Why is this bad? +This method is also implicitly defined if a type implements the `Display` trait. As the functionality of `Display` is much more versatile, it should be preferred. + +### Example +``` +pub struct A; + +impl A { + pub fn to_string(&self) -> String { + "I am A".to_string() + } +} +``` + +Use instead: +``` +use std::fmt; + +pub struct A; + +impl fmt::Display for A { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "I am A") + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/inherent_to_string_shadow_display.txt b/src/tools/clippy/src/docs/inherent_to_string_shadow_display.txt new file mode 100644 index 0000000000000..a4bd0b622c4f5 --- /dev/null +++ b/src/tools/clippy/src/docs/inherent_to_string_shadow_display.txt @@ -0,0 +1,37 @@ +### What it does +Checks for the definition of inherent methods with a signature of `to_string(&self) -> String` and if the type implementing this method also implements the `Display` trait. + +### Why is this bad? +This method is also implicitly defined if a type implements the `Display` trait. The less versatile inherent method will then shadow the implementation introduced by `Display`. + +### Example +``` +use std::fmt; + +pub struct A; + +impl A { + pub fn to_string(&self) -> String { + "I am A".to_string() + } +} + +impl fmt::Display for A { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "I am A, too") + } +} +``` + +Use instead: +``` +use std::fmt; + +pub struct A; + +impl fmt::Display for A { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "I am A") + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/init_numbered_fields.txt b/src/tools/clippy/src/docs/init_numbered_fields.txt new file mode 100644 index 0000000000000..ba40af6a5fa55 --- /dev/null +++ b/src/tools/clippy/src/docs/init_numbered_fields.txt @@ -0,0 +1,24 @@ +### What it does +Checks for tuple structs initialized with field syntax. +It will however not lint if a base initializer is present. +The lint will also ignore code in macros. + +### Why is this bad? +This may be confusing to the uninitiated and adds no +benefit as opposed to tuple initializers + +### Example +``` +struct TupleStruct(u8, u16); + +let _ = TupleStruct { + 0: 1, + 1: 23, +}; + +// should be written as +let base = TupleStruct(1, 23); + +// This is OK however +let _ = TupleStruct { 0: 42, ..base }; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/inline_always.txt b/src/tools/clippy/src/docs/inline_always.txt new file mode 100644 index 0000000000000..7721da4c4cc71 --- /dev/null +++ b/src/tools/clippy/src/docs/inline_always.txt @@ -0,0 +1,23 @@ +### What it does +Checks for items annotated with `#[inline(always)]`, +unless the annotated function is empty or simply panics. + +### Why is this bad? +While there are valid uses of this annotation (and once +you know when to use it, by all means `allow` this lint), it's a common +newbie-mistake to pepper one's code with it. + +As a rule of thumb, before slapping `#[inline(always)]` on a function, +measure if that additional function call really affects your runtime profile +sufficiently to make up for the increase in compile time. + +### Known problems +False positives, big time. This lint is meant to be +deactivated by everyone doing serious performance work. This means having +done the measurement. + +### Example +``` +#[inline(always)] +fn not_quite_hot_code(..) { ... } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/inline_asm_x86_att_syntax.txt b/src/tools/clippy/src/docs/inline_asm_x86_att_syntax.txt new file mode 100644 index 0000000000000..8eb49d122d899 --- /dev/null +++ b/src/tools/clippy/src/docs/inline_asm_x86_att_syntax.txt @@ -0,0 +1,16 @@ +### 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. + +### Example + +``` +asm!("lea ({}), {}", in(reg) ptr, lateout(reg) _, options(att_syntax)); +``` +Use instead: +``` +asm!("lea {}, [{}]", lateout(reg) _, in(reg) ptr); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/inline_asm_x86_intel_syntax.txt b/src/tools/clippy/src/docs/inline_asm_x86_intel_syntax.txt new file mode 100644 index 0000000000000..5aa22c8ed2357 --- /dev/null +++ b/src/tools/clippy/src/docs/inline_asm_x86_intel_syntax.txt @@ -0,0 +1,16 @@ +### 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. + +### Example + +``` +asm!("lea {}, [{}]", lateout(reg) _, in(reg) ptr); +``` +Use instead: +``` +asm!("lea ({}), {}", in(reg) ptr, lateout(reg) _, options(att_syntax)); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/inline_fn_without_body.txt b/src/tools/clippy/src/docs/inline_fn_without_body.txt new file mode 100644 index 0000000000000..127c161aaa250 --- /dev/null +++ b/src/tools/clippy/src/docs/inline_fn_without_body.txt @@ -0,0 +1,14 @@ +### What it does +Checks for `#[inline]` on trait methods without bodies + +### Why is this bad? +Only implementations of trait methods may be inlined. +The inline attribute is ignored for trait methods without bodies. + +### Example +``` +trait Animal { + #[inline] + fn name(&self) -> &'static str; +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/inspect_for_each.txt b/src/tools/clippy/src/docs/inspect_for_each.txt new file mode 100644 index 0000000000000..01a46d6c451f4 --- /dev/null +++ b/src/tools/clippy/src/docs/inspect_for_each.txt @@ -0,0 +1,23 @@ +### What it does +Checks for usage of `inspect().for_each()`. + +### Why is this bad? +It is the same as performing the computation +inside `inspect` at the beginning of the closure in `for_each`. + +### Example +``` +[1,2,3,4,5].iter() +.inspect(|&x| println!("inspect the number: {}", x)) +.for_each(|&x| { + assert!(x >= 0); +}); +``` +Can be written as +``` +[1,2,3,4,5].iter() +.for_each(|&x| { + println!("inspect the number: {}", x); + assert!(x >= 0); +}); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/int_plus_one.txt b/src/tools/clippy/src/docs/int_plus_one.txt new file mode 100644 index 0000000000000..1b68f3eeb64b4 --- /dev/null +++ b/src/tools/clippy/src/docs/int_plus_one.txt @@ -0,0 +1,15 @@ +### What it does +Checks for usage of `x >= y + 1` or `x - 1 >= y` (and `<=`) in a block + +### Why is this bad? +Readability -- better to use `> y` instead of `>= y + 1`. + +### Example +``` +if x >= y + 1 {} +``` + +Use instead: +``` +if x > y {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/integer_arithmetic.txt b/src/tools/clippy/src/docs/integer_arithmetic.txt new file mode 100644 index 0000000000000..ea57a2ef97bf5 --- /dev/null +++ b/src/tools/clippy/src/docs/integer_arithmetic.txt @@ -0,0 +1,18 @@ +### What it does +Checks for integer arithmetic operations which could overflow or panic. + +Specifically, checks for any operators (`+`, `-`, `*`, `<<`, etc) which are capable +of overflowing according to the [Rust +Reference](https://doc.rust-lang.org/reference/expressions/operator-expr.html#overflow), +or which can panic (`/`, `%`). No bounds analysis or sophisticated reasoning is +attempted. + +### Why is this bad? +Integer overflow will trigger a panic in debug builds or will wrap in +release mode. Division by zero will cause a panic in either mode. In some applications one +wants explicitly checked, wrapping or saturating arithmetic. + +### Example +``` +a + 1; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/integer_division.txt b/src/tools/clippy/src/docs/integer_division.txt new file mode 100644 index 0000000000000..f6d3349810ed8 --- /dev/null +++ b/src/tools/clippy/src/docs/integer_division.txt @@ -0,0 +1,19 @@ +### What it does +Checks for division of integers + +### Why is this bad? +When outside of some very specific algorithms, +integer division is very often a mistake because it discards the +remainder. + +### Example +``` +let x = 3 / 2; +println!("{}", x); +``` + +Use instead: +``` +let x = 3f32 / 2f32; +println!("{}", x); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/into_iter_on_ref.txt b/src/tools/clippy/src/docs/into_iter_on_ref.txt new file mode 100644 index 0000000000000..acb6bd474ebf3 --- /dev/null +++ b/src/tools/clippy/src/docs/into_iter_on_ref.txt @@ -0,0 +1,18 @@ +### What it does +Checks for `into_iter` calls on references which should be replaced by `iter` +or `iter_mut`. + +### Why is this bad? +Readability. Calling `into_iter` on a reference will not move out its +content into the resulting iterator, which is confusing. It is better just call `iter` or +`iter_mut` directly. + +### Example +``` +(&vec).into_iter(); +``` + +Use instead: +``` +(&vec).iter(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/invalid_null_ptr_usage.txt b/src/tools/clippy/src/docs/invalid_null_ptr_usage.txt new file mode 100644 index 0000000000000..6fb3fa3f83d66 --- /dev/null +++ b/src/tools/clippy/src/docs/invalid_null_ptr_usage.txt @@ -0,0 +1,16 @@ +### What it does +This lint checks for invalid usages of `ptr::null`. + +### Why is this bad? +This causes undefined behavior. + +### Example +``` +// Undefined behavior +unsafe { std::slice::from_raw_parts(ptr::null(), 0); } +``` + +Use instead: +``` +unsafe { std::slice::from_raw_parts(NonNull::dangling().as_ptr(), 0); } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/invalid_regex.txt b/src/tools/clippy/src/docs/invalid_regex.txt new file mode 100644 index 0000000000000..6c9969b6e1a33 --- /dev/null +++ b/src/tools/clippy/src/docs/invalid_regex.txt @@ -0,0 +1,12 @@ +### What it does +Checks [regex](https://crates.io/crates/regex) creation +(with `Regex::new`, `RegexBuilder::new`, or `RegexSet::new`) for correct +regex syntax. + +### Why is this bad? +This will lead to a runtime panic. + +### Example +``` +Regex::new("(") +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/invalid_upcast_comparisons.txt b/src/tools/clippy/src/docs/invalid_upcast_comparisons.txt new file mode 100644 index 0000000000000..77cb033080372 --- /dev/null +++ b/src/tools/clippy/src/docs/invalid_upcast_comparisons.txt @@ -0,0 +1,18 @@ +### What it does +Checks for comparisons where the relation is always either +true or false, but where one side has been upcast so that the comparison is +necessary. Only integer types are checked. + +### Why is this bad? +An expression like `let x : u8 = ...; (x as u32) > 300` +will mistakenly imply that it is possible for `x` to be outside the range of +`u8`. + +### Known problems +https://github.com/rust-lang/rust-clippy/issues/886 + +### Example +``` +let x: u8 = 1; +(x as u32) > 300; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/invalid_utf8_in_unchecked.txt b/src/tools/clippy/src/docs/invalid_utf8_in_unchecked.txt new file mode 100644 index 0000000000000..afb5acbe9c51c --- /dev/null +++ b/src/tools/clippy/src/docs/invalid_utf8_in_unchecked.txt @@ -0,0 +1,12 @@ +### What it does +Checks for `std::str::from_utf8_unchecked` with an invalid UTF-8 literal + +### Why is this bad? +Creating such a `str` would result in undefined behavior + +### Example +``` +unsafe { + std::str::from_utf8_unchecked(b"cl\x82ippy"); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/invisible_characters.txt b/src/tools/clippy/src/docs/invisible_characters.txt new file mode 100644 index 0000000000000..3dda380911f91 --- /dev/null +++ b/src/tools/clippy/src/docs/invisible_characters.txt @@ -0,0 +1,10 @@ +### What it does +Checks for invisible Unicode characters in the code. + +### Why is this bad? +Having an invisible character in the code makes for all +sorts of April fools, but otherwise is very much frowned upon. + +### Example +You don't see it, but there may be a zero-width space or soft hyphen +some­where in this text. \ No newline at end of file diff --git a/src/tools/clippy/src/docs/is_digit_ascii_radix.txt b/src/tools/clippy/src/docs/is_digit_ascii_radix.txt new file mode 100644 index 0000000000000..9f11cf43054fe --- /dev/null +++ b/src/tools/clippy/src/docs/is_digit_ascii_radix.txt @@ -0,0 +1,20 @@ +### What it does +Finds usages of [`char::is_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that +can be replaced with [`is_ascii_digit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or +[`is_ascii_hexdigit`](https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit). + +### Why is this bad? +`is_digit(..)` is slower and requires specifying the radix. + +### Example +``` +let c: char = '6'; +c.is_digit(10); +c.is_digit(16); +``` +Use instead: +``` +let c: char = '6'; +c.is_ascii_digit(); +c.is_ascii_hexdigit(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/items_after_statements.txt b/src/tools/clippy/src/docs/items_after_statements.txt new file mode 100644 index 0000000000000..6fdfff50d20e4 --- /dev/null +++ b/src/tools/clippy/src/docs/items_after_statements.txt @@ -0,0 +1,37 @@ +### What it does +Checks for items declared after some statement in a block. + +### Why is this bad? +Items live for the entire scope they are declared +in. But statements are processed in order. This might cause confusion as +it's hard to figure out which item is meant in a statement. + +### Example +``` +fn foo() { + println!("cake"); +} + +fn main() { + foo(); // prints "foo" + fn foo() { + println!("foo"); + } + foo(); // prints "foo" +} +``` + +Use instead: +``` +fn foo() { + println!("cake"); +} + +fn main() { + fn foo() { + println!("foo"); + } + foo(); // prints "foo" + foo(); // prints "foo" +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/iter_cloned_collect.txt b/src/tools/clippy/src/docs/iter_cloned_collect.txt new file mode 100644 index 0000000000000..90dc9ebb40f0b --- /dev/null +++ b/src/tools/clippy/src/docs/iter_cloned_collect.txt @@ -0,0 +1,17 @@ +### What it does +Checks for the use of `.cloned().collect()` on slice to +create a `Vec`. + +### Why is this bad? +`.to_vec()` is clearer + +### Example +``` +let s = [1, 2, 3, 4, 5]; +let s2: Vec = s[..].iter().cloned().collect(); +``` +The better use would be: +``` +let s = [1, 2, 3, 4, 5]; +let s2: Vec = s.to_vec(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/iter_count.txt b/src/tools/clippy/src/docs/iter_count.txt new file mode 100644 index 0000000000000..f3db4a26c2997 --- /dev/null +++ b/src/tools/clippy/src/docs/iter_count.txt @@ -0,0 +1,22 @@ +### What it does +Checks for the use of `.iter().count()`. + +### Why is this bad? +`.len()` is more efficient and more +readable. + +### Example +``` +let some_vec = vec![0, 1, 2, 3]; + +some_vec.iter().count(); +&some_vec[..].iter().count(); +``` + +Use instead: +``` +let some_vec = vec![0, 1, 2, 3]; + +some_vec.len(); +&some_vec[..].len(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/iter_next_loop.txt b/src/tools/clippy/src/docs/iter_next_loop.txt new file mode 100644 index 0000000000000..b33eb39d6e1d3 --- /dev/null +++ b/src/tools/clippy/src/docs/iter_next_loop.txt @@ -0,0 +1,17 @@ +### What it does +Checks for loops on `x.next()`. + +### Why is this bad? +`next()` returns either `Some(value)` if there was a +value, or `None` otherwise. The insidious thing is that `Option<_>` +implements `IntoIterator`, so that possibly one value will be iterated, +leading to some hard to find bugs. No one will want to write such code +[except to win an Underhanded Rust +Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr). + +### Example +``` +for x in y.next() { + .. +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/iter_next_slice.txt b/src/tools/clippy/src/docs/iter_next_slice.txt new file mode 100644 index 0000000000000..1cea25eaf3017 --- /dev/null +++ b/src/tools/clippy/src/docs/iter_next_slice.txt @@ -0,0 +1,16 @@ +### What it does +Checks for usage of `iter().next()` on a Slice or an Array + +### Why is this bad? +These can be shortened into `.get()` + +### Example +``` +a[2..].iter().next(); +b.iter().next(); +``` +should be written as: +``` +a.get(2); +b.get(0); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/iter_not_returning_iterator.txt b/src/tools/clippy/src/docs/iter_not_returning_iterator.txt new file mode 100644 index 0000000000000..0ca862910a6f0 --- /dev/null +++ b/src/tools/clippy/src/docs/iter_not_returning_iterator.txt @@ -0,0 +1,26 @@ +### What it does +Detects methods named `iter` or `iter_mut` that do not have a return type that implements `Iterator`. + +### Why is this bad? +Methods named `iter` or `iter_mut` conventionally return an `Iterator`. + +### Example +``` +// `String` does not implement `Iterator` +struct Data {} +impl Data { + fn iter(&self) -> String { + todo!() + } +} +``` +Use instead: +``` +use std::str::Chars; +struct Data {} +impl Data { + fn iter(&self) -> Chars<'static> { + todo!() + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/iter_nth.txt b/src/tools/clippy/src/docs/iter_nth.txt new file mode 100644 index 0000000000000..3d67d583ffde3 --- /dev/null +++ b/src/tools/clippy/src/docs/iter_nth.txt @@ -0,0 +1,20 @@ +### What it does +Checks for use of `.iter().nth()` (and the related +`.iter_mut().nth()`) on standard library types with *O*(1) element access. + +### Why is this bad? +`.get()` and `.get_mut()` are more efficient and more +readable. + +### Example +``` +let some_vec = vec![0, 1, 2, 3]; +let bad_vec = some_vec.iter().nth(3); +let bad_slice = &some_vec[..].iter().nth(3); +``` +The correct use would be: +``` +let some_vec = vec![0, 1, 2, 3]; +let bad_vec = some_vec.get(3); +let bad_slice = &some_vec[..].get(3); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/iter_nth_zero.txt b/src/tools/clippy/src/docs/iter_nth_zero.txt new file mode 100644 index 0000000000000..8efe47a16a100 --- /dev/null +++ b/src/tools/clippy/src/docs/iter_nth_zero.txt @@ -0,0 +1,17 @@ +### What it does +Checks for the use of `iter.nth(0)`. + +### Why is this bad? +`iter.next()` is equivalent to +`iter.nth(0)`, as they both consume the next element, + but is more readable. + +### Example +``` +let x = s.iter().nth(0); +``` + +Use instead: +``` +let x = s.iter().next(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/iter_on_empty_collections.txt b/src/tools/clippy/src/docs/iter_on_empty_collections.txt new file mode 100644 index 0000000000000..87c4ec12afae7 --- /dev/null +++ b/src/tools/clippy/src/docs/iter_on_empty_collections.txt @@ -0,0 +1,25 @@ +### What it does + +Checks for calls to `iter`, `iter_mut` or `into_iter` on empty collections + +### Why is this bad? + +It is simpler to use the empty function from the standard library: + +### Example + +``` +use std::{slice, option}; +let a: slice::Iter = [].iter(); +let f: option::IntoIter = None.into_iter(); +``` +Use instead: +``` +use std::iter; +let a: iter::Empty = iter::empty(); +let b: iter::Empty = iter::empty(); +``` + +### Known problems + +The type of the resulting iterator might become incompatible with its usage \ No newline at end of file diff --git a/src/tools/clippy/src/docs/iter_on_single_items.txt b/src/tools/clippy/src/docs/iter_on_single_items.txt new file mode 100644 index 0000000000000..d0388f25d045e --- /dev/null +++ b/src/tools/clippy/src/docs/iter_on_single_items.txt @@ -0,0 +1,24 @@ +### What it does + +Checks for calls to `iter`, `iter_mut` or `into_iter` on collections containing a single item + +### Why is this bad? + +It is simpler to use the once function from the standard library: + +### Example + +``` +let a = [123].iter(); +let b = Some(123).into_iter(); +``` +Use instead: +``` +use std::iter; +let a = iter::once(&123); +let b = iter::once(123); +``` + +### Known problems + +The type of the resulting iterator might become incompatible with its usage \ No newline at end of file diff --git a/src/tools/clippy/src/docs/iter_overeager_cloned.txt b/src/tools/clippy/src/docs/iter_overeager_cloned.txt new file mode 100644 index 0000000000000..2f902a0c2db4d --- /dev/null +++ b/src/tools/clippy/src/docs/iter_overeager_cloned.txt @@ -0,0 +1,22 @@ +### What it does +Checks for usage of `_.cloned().()` where call to `.cloned()` can be postponed. + +### Why is this bad? +It's often inefficient to clone all elements of an iterator, when eventually, only some +of them will be consumed. + +### Known Problems +This `lint` removes the side of effect of cloning items in the iterator. +A code that relies on that side-effect could fail. + +### Examples +``` +vec.iter().cloned().take(10); +vec.iter().cloned().last(); +``` + +Use instead: +``` +vec.iter().take(10).cloned(); +vec.iter().last().cloned(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/iter_skip_next.txt b/src/tools/clippy/src/docs/iter_skip_next.txt new file mode 100644 index 0000000000000..da226b041cf23 --- /dev/null +++ b/src/tools/clippy/src/docs/iter_skip_next.txt @@ -0,0 +1,18 @@ +### What it does +Checks for use of `.skip(x).next()` on iterators. + +### Why is this bad? +`.nth(x)` is cleaner + +### Example +``` +let some_vec = vec![0, 1, 2, 3]; +let bad_vec = some_vec.iter().skip(3).next(); +let bad_slice = &some_vec[..].iter().skip(3).next(); +``` +The correct use would be: +``` +let some_vec = vec![0, 1, 2, 3]; +let bad_vec = some_vec.iter().nth(3); +let bad_slice = &some_vec[..].iter().nth(3); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/iter_with_drain.txt b/src/tools/clippy/src/docs/iter_with_drain.txt new file mode 100644 index 0000000000000..2c52b99f7a5c5 --- /dev/null +++ b/src/tools/clippy/src/docs/iter_with_drain.txt @@ -0,0 +1,16 @@ +### What it does +Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration. + +### Why is this bad? +`.into_iter()` is simpler with better performance. + +### Example +``` +let mut foo = vec![0, 1, 2, 3]; +let bar: HashSet = foo.drain(..).collect(); +``` +Use instead: +``` +let foo = vec![0, 1, 2, 3]; +let bar: HashSet = foo.into_iter().collect(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/iterator_step_by_zero.txt b/src/tools/clippy/src/docs/iterator_step_by_zero.txt new file mode 100644 index 0000000000000..73ecc99acfcbc --- /dev/null +++ b/src/tools/clippy/src/docs/iterator_step_by_zero.txt @@ -0,0 +1,13 @@ +### What it does +Checks for calling `.step_by(0)` on iterators which panics. + +### Why is this bad? +This very much looks like an oversight. Use `panic!()` instead if you +actually intend to panic. + +### Example +``` +for x in (0..100).step_by(0) { + //.. +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/just_underscores_and_digits.txt b/src/tools/clippy/src/docs/just_underscores_and_digits.txt new file mode 100644 index 0000000000000..a8790bcf25be6 --- /dev/null +++ b/src/tools/clippy/src/docs/just_underscores_and_digits.txt @@ -0,0 +1,14 @@ +### What it does +Checks if you have variables whose name consists of just +underscores and digits. + +### Why is this bad? +It's hard to memorize what a variable means without a +descriptive name. + +### Example +``` +let _1 = 1; +let ___1 = 1; +let __1___2 = 11; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/large_const_arrays.txt b/src/tools/clippy/src/docs/large_const_arrays.txt new file mode 100644 index 0000000000000..71f67854f2a1a --- /dev/null +++ b/src/tools/clippy/src/docs/large_const_arrays.txt @@ -0,0 +1,17 @@ +### What it does +Checks for large `const` arrays that should +be defined as `static` instead. + +### Why is this bad? +Performance: const variables are inlined upon use. +Static items result in only one instance and has a fixed location in memory. + +### Example +``` +pub const a = [0u32; 1_000_000]; +``` + +Use instead: +``` +pub static a = [0u32; 1_000_000]; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/large_digit_groups.txt b/src/tools/clippy/src/docs/large_digit_groups.txt new file mode 100644 index 0000000000000..f60b19345af44 --- /dev/null +++ b/src/tools/clippy/src/docs/large_digit_groups.txt @@ -0,0 +1,12 @@ +### What it does +Warns if the digits of an integral or floating-point +constant are grouped into groups that +are too large. + +### Why is this bad? +Negatively impacts readability. + +### Example +``` +let x: u64 = 6186491_8973511; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/large_enum_variant.txt b/src/tools/clippy/src/docs/large_enum_variant.txt new file mode 100644 index 0000000000000..1f95430790d29 --- /dev/null +++ b/src/tools/clippy/src/docs/large_enum_variant.txt @@ -0,0 +1,41 @@ +### What it does +Checks for large size differences between variants on +`enum`s. + +### Why is this bad? +Enum size is bounded by the largest variant. Having one +large variant can penalize the memory layout of that enum. + +### Known problems +This lint obviously cannot take the distribution of +variants in your running program into account. It is possible that the +smaller variants make up less than 1% of all instances, in which case +the overhead is negligible and the boxing is counter-productive. Always +measure the change this lint suggests. + +For types that implement `Copy`, the suggestion to `Box` a variant's +data would require removing the trait impl. The types can of course +still be `Clone`, but that is worse ergonomically. Depending on the +use case it may be possible to store the large data in an auxiliary +structure (e.g. Arena or ECS). + +The lint will ignore the impact of generic types to the type layout by +assuming every type parameter is zero-sized. Depending on your use case, +this may lead to a false positive. + +### Example +``` +enum Test { + A(i32), + B([i32; 8000]), +} +``` + +Use instead: +``` +// Possibly better +enum Test2 { + A(i32), + B(Box<[i32; 8000]>), +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/large_include_file.txt b/src/tools/clippy/src/docs/large_include_file.txt new file mode 100644 index 0000000000000..b2a54bd2eb5ca --- /dev/null +++ b/src/tools/clippy/src/docs/large_include_file.txt @@ -0,0 +1,21 @@ +### What it does +Checks for the inclusion of large files via `include_bytes!()` +and `include_str!()` + +### Why is this bad? +Including large files can increase the size of the binary + +### Example +``` +let included_str = include_str!("very_large_file.txt"); +let included_bytes = include_bytes!("very_large_file.txt"); +``` + +Use instead: +``` +use std::fs; + +// You can load the file at runtime +let string = fs::read_to_string("very_large_file.txt")?; +let bytes = fs::read("very_large_file.txt")?; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/large_stack_arrays.txt b/src/tools/clippy/src/docs/large_stack_arrays.txt new file mode 100644 index 0000000000000..4a6f34785b0ef --- /dev/null +++ b/src/tools/clippy/src/docs/large_stack_arrays.txt @@ -0,0 +1,10 @@ +### What it does +Checks for local arrays that may be too large. + +### Why is this bad? +Large local arrays may cause stack overflow. + +### Example +``` +let a = [0u32; 1_000_000]; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/large_types_passed_by_value.txt b/src/tools/clippy/src/docs/large_types_passed_by_value.txt new file mode 100644 index 0000000000000..bca07f3ac61bb --- /dev/null +++ b/src/tools/clippy/src/docs/large_types_passed_by_value.txt @@ -0,0 +1,24 @@ +### What it does +Checks for functions taking arguments by value, where +the argument type is `Copy` and large enough to be worth considering +passing by reference. Does not trigger if the function is being exported, +because that might induce API breakage, if the parameter is declared as mutable, +or if the argument is a `self`. + +### Why is this bad? +Arguments passed by value might result in an unnecessary +shallow copy, taking up more space in the stack and requiring a call to +`memcpy`, which can be expensive. + +### Example +``` +#[derive(Clone, Copy)] +struct TooLarge([u8; 2048]); + +fn foo(v: TooLarge) {} +``` + +Use instead: +``` +fn foo(v: &TooLarge) {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/len_without_is_empty.txt b/src/tools/clippy/src/docs/len_without_is_empty.txt new file mode 100644 index 0000000000000..47a2e85752285 --- /dev/null +++ b/src/tools/clippy/src/docs/len_without_is_empty.txt @@ -0,0 +1,19 @@ +### What it does +Checks for items that implement `.len()` but not +`.is_empty()`. + +### Why is this bad? +It is good custom to have both methods, because for +some data structures, asking about the length will be a costly operation, +whereas `.is_empty()` can usually answer in constant time. Also it used to +lead to false positives on the [`len_zero`](#len_zero) lint – currently that +lint will ignore such entities. + +### Example +``` +impl X { + pub fn len(&self) -> usize { + .. + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/len_zero.txt b/src/tools/clippy/src/docs/len_zero.txt new file mode 100644 index 0000000000000..664124bd391df --- /dev/null +++ b/src/tools/clippy/src/docs/len_zero.txt @@ -0,0 +1,28 @@ +### What it does +Checks for getting the length of something via `.len()` +just to compare to zero, and suggests using `.is_empty()` where applicable. + +### Why is this bad? +Some structures can answer `.is_empty()` much faster +than calculating their length. So it is good to get into the habit of using +`.is_empty()`, and having it is cheap. +Besides, it makes the intent clearer than a manual comparison in some contexts. + +### Example +``` +if x.len() == 0 { + .. +} +if y.len() != 0 { + .. +} +``` +instead use +``` +if x.is_empty() { + .. +} +if !y.is_empty() { + .. +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/let_and_return.txt b/src/tools/clippy/src/docs/let_and_return.txt new file mode 100644 index 0000000000000..eba5a90ddd66c --- /dev/null +++ b/src/tools/clippy/src/docs/let_and_return.txt @@ -0,0 +1,21 @@ +### What it does +Checks for `let`-bindings, which are subsequently +returned. + +### Why is this bad? +It is just extraneous code. Remove it to make your code +more rusty. + +### Example +``` +fn foo() -> String { + let x = String::new(); + x +} +``` +instead, use +``` +fn foo() -> String { + String::new() +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/let_underscore_drop.txt b/src/tools/clippy/src/docs/let_underscore_drop.txt new file mode 100644 index 0000000000000..29ce9bf50ce6a --- /dev/null +++ b/src/tools/clippy/src/docs/let_underscore_drop.txt @@ -0,0 +1,29 @@ +### What it does +Checks for `let _ = ` +where expr has a type that implements `Drop` + +### Why is this bad? +This statement immediately drops the initializer +expression instead of extending its lifetime to the end of the scope, which +is often not intended. To extend the expression's lifetime to the end of the +scope, use an underscore-prefixed name instead (i.e. _var). If you want to +explicitly drop the expression, `std::mem::drop` conveys your intention +better and is less error-prone. + +### Example +``` +{ + let _ = DroppableItem; + // ^ dropped here + /* more code */ +} +``` + +Use instead: +``` +{ + let _droppable = DroppableItem; + /* more code */ + // dropped at end of scope +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/let_underscore_lock.txt b/src/tools/clippy/src/docs/let_underscore_lock.txt new file mode 100644 index 0000000000000..bd8217fb58b3c --- /dev/null +++ b/src/tools/clippy/src/docs/let_underscore_lock.txt @@ -0,0 +1,20 @@ +### What it does +Checks for `let _ = sync_lock`. +This supports `mutex` and `rwlock` in `std::sync` and `parking_lot`. + +### Why is this bad? +This statement immediately drops the lock instead of +extending its lifetime to the end of the scope, which is often not intended. +To extend lock lifetime to the end of the scope, use an underscore-prefixed +name instead (i.e. _lock). If you want to explicitly drop the lock, +`std::mem::drop` conveys your intention better and is less error-prone. + +### Example +``` +let _ = mutex.lock(); +``` + +Use instead: +``` +let _lock = mutex.lock(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/let_underscore_must_use.txt b/src/tools/clippy/src/docs/let_underscore_must_use.txt new file mode 100644 index 0000000000000..270b81d9a4c41 --- /dev/null +++ b/src/tools/clippy/src/docs/let_underscore_must_use.txt @@ -0,0 +1,17 @@ +### What it does +Checks for `let _ = ` where expr is `#[must_use]` + +### Why is this bad? +It's better to explicitly handle the value of a `#[must_use]` +expr + +### Example +``` +fn f() -> Result { + Ok(0) +} + +let _ = f(); +// is_ok() is marked #[must_use] +let _ = f().is_ok(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/let_unit_value.txt b/src/tools/clippy/src/docs/let_unit_value.txt new file mode 100644 index 0000000000000..bc16d5b3d81be --- /dev/null +++ b/src/tools/clippy/src/docs/let_unit_value.txt @@ -0,0 +1,13 @@ +### What it does +Checks for binding a unit value. + +### Why is this bad? +A unit value cannot usefully be used anywhere. So +binding one is kind of pointless. + +### Example +``` +let x = { + 1; +}; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/linkedlist.txt b/src/tools/clippy/src/docs/linkedlist.txt new file mode 100644 index 0000000000000..986ff1369e3c1 --- /dev/null +++ b/src/tools/clippy/src/docs/linkedlist.txt @@ -0,0 +1,32 @@ +### What it does +Checks for usage of any `LinkedList`, suggesting to use a +`Vec` or a `VecDeque` (formerly called `RingBuf`). + +### Why is this bad? +Gankro says: + +> The TL;DR of `LinkedList` is that it's built on a massive amount of +pointers and indirection. +> It wastes memory, it has terrible cache locality, and is all-around slow. +`RingBuf`, while +> "only" amortized for push/pop, should be faster in the general case for +almost every possible +> workload, and isn't even amortized at all if you can predict the capacity +you need. +> +> `LinkedList`s are only really good if you're doing a lot of merging or +splitting of lists. +> This is because they can just mangle some pointers instead of actually +copying the data. Even +> if you're doing a lot of insertion in the middle of the list, `RingBuf` +can still be better +> because of how expensive it is to seek to the middle of a `LinkedList`. + +### Known problems +False positives – the instances where using a +`LinkedList` makes sense are few and far between, but they can still happen. + +### Example +``` +let x: LinkedList = LinkedList::new(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/lossy_float_literal.txt b/src/tools/clippy/src/docs/lossy_float_literal.txt new file mode 100644 index 0000000000000..bbcb9115ea62a --- /dev/null +++ b/src/tools/clippy/src/docs/lossy_float_literal.txt @@ -0,0 +1,18 @@ +### What it does +Checks for whole number float literals that +cannot be represented as the underlying type without loss. + +### Why is this bad? +Rust will silently lose precision during +conversion to a float. + +### Example +``` +let _: f32 = 16_777_217.0; // 16_777_216.0 +``` + +Use instead: +``` +let _: f32 = 16_777_216.0; +let _: f64 = 16_777_217.0; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/macro_use_imports.txt b/src/tools/clippy/src/docs/macro_use_imports.txt new file mode 100644 index 0000000000000..6a8180a60bc6f --- /dev/null +++ b/src/tools/clippy/src/docs/macro_use_imports.txt @@ -0,0 +1,12 @@ +### What it does +Checks for `#[macro_use] use...`. + +### Why is this bad? +Since the Rust 2018 edition you can import +macro's directly, this is considered idiomatic. + +### Example +``` +#[macro_use] +use some_macro; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/main_recursion.txt b/src/tools/clippy/src/docs/main_recursion.txt new file mode 100644 index 0000000000000..e49becd15bbdb --- /dev/null +++ b/src/tools/clippy/src/docs/main_recursion.txt @@ -0,0 +1,13 @@ +### What it does +Checks for recursion using the entrypoint. + +### Why is this bad? +Apart from special setups (which we could detect following attributes like #![no_std]), +recursing into main() seems like an unintuitive anti-pattern we should be able to detect. + +### Example +``` +fn main() { + main(); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_assert.txt b/src/tools/clippy/src/docs/manual_assert.txt new file mode 100644 index 0000000000000..93653081a2ce0 --- /dev/null +++ b/src/tools/clippy/src/docs/manual_assert.txt @@ -0,0 +1,18 @@ +### What it does +Detects `if`-then-`panic!` that can be replaced with `assert!`. + +### Why is this bad? +`assert!` is simpler than `if`-then-`panic!`. + +### Example +``` +let sad_people: Vec<&str> = vec![]; +if !sad_people.is_empty() { + panic!("there are sad people: {:?}", sad_people); +} +``` +Use instead: +``` +let sad_people: Vec<&str> = vec![]; +assert!(sad_people.is_empty(), "there are sad people: {:?}", sad_people); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_async_fn.txt b/src/tools/clippy/src/docs/manual_async_fn.txt new file mode 100644 index 0000000000000..d01ac402e0d21 --- /dev/null +++ b/src/tools/clippy/src/docs/manual_async_fn.txt @@ -0,0 +1,16 @@ +### What it does +It checks for manual implementations of `async` functions. + +### Why is this bad? +It's more idiomatic to use the dedicated syntax. + +### Example +``` +use std::future::Future; + +fn foo() -> impl Future { async { 42 } } +``` +Use instead: +``` +async fn foo() -> i32 { 42 } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_bits.txt b/src/tools/clippy/src/docs/manual_bits.txt new file mode 100644 index 0000000000000..b96c2eb151d41 --- /dev/null +++ b/src/tools/clippy/src/docs/manual_bits.txt @@ -0,0 +1,15 @@ +### What it does +Checks for uses of `std::mem::size_of::() * 8` when +`T::BITS` is available. + +### Why is this bad? +Can be written as the shorter `T::BITS`. + +### Example +``` +std::mem::size_of::() * 8; +``` +Use instead: +``` +usize::BITS as usize; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_filter_map.txt b/src/tools/clippy/src/docs/manual_filter_map.txt new file mode 100644 index 0000000000000..3b6860798ff58 --- /dev/null +++ b/src/tools/clippy/src/docs/manual_filter_map.txt @@ -0,0 +1,19 @@ +### What it does +Checks for usage of `_.filter(_).map(_)` that can be written more simply +as `filter_map(_)`. + +### Why is this bad? +Redundant code in the `filter` and `map` operations is poor style and +less performant. + +### Example +``` +(0_i32..10) + .filter(|n| n.checked_add(1).is_some()) + .map(|n| n.checked_add(1).unwrap()); +``` + +Use instead: +``` +(0_i32..10).filter_map(|n| n.checked_add(1)); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_find.txt b/src/tools/clippy/src/docs/manual_find.txt new file mode 100644 index 0000000000000..e3e07a2771f95 --- /dev/null +++ b/src/tools/clippy/src/docs/manual_find.txt @@ -0,0 +1,24 @@ +### What it does +Check for manual implementations of Iterator::find + +### Why is this bad? +It doesn't affect performance, but using `find` is shorter and easier to read. + +### Example + +``` +fn example(arr: Vec) -> Option { + for el in arr { + if el == 1 { + return Some(el); + } + } + None +} +``` +Use instead: +``` +fn example(arr: Vec) -> Option { + arr.into_iter().find(|&el| el == 1) +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_find_map.txt b/src/tools/clippy/src/docs/manual_find_map.txt new file mode 100644 index 0000000000000..83b22060c0e19 --- /dev/null +++ b/src/tools/clippy/src/docs/manual_find_map.txt @@ -0,0 +1,19 @@ +### What it does +Checks for usage of `_.find(_).map(_)` that can be written more simply +as `find_map(_)`. + +### Why is this bad? +Redundant code in the `find` and `map` operations is poor style and +less performant. + +### Example +``` +(0_i32..10) + .find(|n| n.checked_add(1).is_some()) + .map(|n| n.checked_add(1).unwrap()); +``` + +Use instead: +``` +(0_i32..10).find_map(|n| n.checked_add(1)); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_flatten.txt b/src/tools/clippy/src/docs/manual_flatten.txt new file mode 100644 index 0000000000000..62d5f3ec93576 --- /dev/null +++ b/src/tools/clippy/src/docs/manual_flatten.txt @@ -0,0 +1,25 @@ +### What it does +Check for unnecessary `if let` usage in a for loop +where only the `Some` or `Ok` variant of the iterator element is used. + +### Why is this bad? +It is verbose and can be simplified +by first calling the `flatten` method on the `Iterator`. + +### Example + +``` +let x = vec![Some(1), Some(2), Some(3)]; +for n in x { + if let Some(n) = n { + println!("{}", n); + } +} +``` +Use instead: +``` +let x = vec![Some(1), Some(2), Some(3)]; +for n in x.into_iter().flatten() { + println!("{}", n); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_instant_elapsed.txt b/src/tools/clippy/src/docs/manual_instant_elapsed.txt new file mode 100644 index 0000000000000..dde3d493c70d3 --- /dev/null +++ b/src/tools/clippy/src/docs/manual_instant_elapsed.txt @@ -0,0 +1,21 @@ +### What it does +Lints subtraction between `Instant::now()` and another `Instant`. + +### Why is this bad? +It is easy to accidentally write `prev_instant - Instant::now()`, which will always be 0ns +as `Instant` subtraction saturates. + +`prev_instant.elapsed()` also more clearly signals intention. + +### Example +``` +use std::time::Instant; +let prev_instant = Instant::now(); +let duration = Instant::now() - prev_instant; +``` +Use instead: +``` +use std::time::Instant; +let prev_instant = Instant::now(); +let duration = prev_instant.elapsed(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_map.txt b/src/tools/clippy/src/docs/manual_map.txt new file mode 100644 index 0000000000000..7f68ccd1037e3 --- /dev/null +++ b/src/tools/clippy/src/docs/manual_map.txt @@ -0,0 +1,17 @@ +### What it does +Checks for usages of `match` which could be implemented using `map` + +### Why is this bad? +Using the `map` method is clearer and more concise. + +### Example +``` +match Some(0) { + Some(x) => Some(x + 1), + None => None, +}; +``` +Use instead: +``` +Some(0).map(|x| x + 1); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_memcpy.txt b/src/tools/clippy/src/docs/manual_memcpy.txt new file mode 100644 index 0000000000000..d7690bf258669 --- /dev/null +++ b/src/tools/clippy/src/docs/manual_memcpy.txt @@ -0,0 +1,18 @@ +### What it does +Checks for for-loops that manually copy items between +slices that could be optimized by having a memcpy. + +### Why is this bad? +It is not as fast as a memcpy. + +### Example +``` +for i in 0..src.len() { + dst[i + 64] = src[i]; +} +``` + +Use instead: +``` +dst[64..(src.len() + 64)].clone_from_slice(&src[..]); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_non_exhaustive.txt b/src/tools/clippy/src/docs/manual_non_exhaustive.txt new file mode 100644 index 0000000000000..fb021393bd7c9 --- /dev/null +++ b/src/tools/clippy/src/docs/manual_non_exhaustive.txt @@ -0,0 +1,41 @@ +### What it does +Checks for manual implementations of the non-exhaustive pattern. + +### Why is this bad? +Using the #[non_exhaustive] attribute expresses better the intent +and allows possible optimizations when applied to enums. + +### Example +``` +struct S { + pub a: i32, + pub b: i32, + _c: (), +} + +enum E { + A, + B, + #[doc(hidden)] + _C, +} + +struct T(pub i32, pub i32, ()); +``` +Use instead: +``` +#[non_exhaustive] +struct S { + pub a: i32, + pub b: i32, +} + +#[non_exhaustive] +enum E { + A, + B, +} + +#[non_exhaustive] +struct T(pub i32, pub i32); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_ok_or.txt b/src/tools/clippy/src/docs/manual_ok_or.txt new file mode 100644 index 0000000000000..5accdf25965ab --- /dev/null +++ b/src/tools/clippy/src/docs/manual_ok_or.txt @@ -0,0 +1,19 @@ +### What it does + +Finds patterns that reimplement `Option::ok_or`. + +### Why is this bad? + +Concise code helps focusing on behavior instead of boilerplate. + +### Examples +``` +let foo: Option = None; +foo.map_or(Err("error"), |v| Ok(v)); +``` + +Use instead: +``` +let foo: Option = None; +foo.ok_or("error"); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_range_contains.txt b/src/tools/clippy/src/docs/manual_range_contains.txt new file mode 100644 index 0000000000000..0ade26951d385 --- /dev/null +++ b/src/tools/clippy/src/docs/manual_range_contains.txt @@ -0,0 +1,19 @@ +### What it does +Checks for expressions like `x >= 3 && x < 8` that could +be more readably expressed as `(3..8).contains(x)`. + +### Why is this bad? +`contains` expresses the intent better and has less +failure modes (such as fencepost errors or using `||` instead of `&&`). + +### Example +``` +// given +let x = 6; + +assert!(x >= 3 && x < 8); +``` +Use instead: +``` +assert!((3..8).contains(&x)); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_rem_euclid.txt b/src/tools/clippy/src/docs/manual_rem_euclid.txt new file mode 100644 index 0000000000000..d3bb8c61304e1 --- /dev/null +++ b/src/tools/clippy/src/docs/manual_rem_euclid.txt @@ -0,0 +1,17 @@ +### What it does +Checks for an expression like `((x % 4) + 4) % 4` which is a common manual reimplementation +of `x.rem_euclid(4)`. + +### Why is this bad? +It's simpler and more readable. + +### Example +``` +let x: i32 = 24; +let rem = ((x % 4) + 4) % 4; +``` +Use instead: +``` +let x: i32 = 24; +let rem = x.rem_euclid(4); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_retain.txt b/src/tools/clippy/src/docs/manual_retain.txt new file mode 100644 index 0000000000000..cd4f65a93fc33 --- /dev/null +++ b/src/tools/clippy/src/docs/manual_retain.txt @@ -0,0 +1,15 @@ +### What it does +Checks for code to be replaced by `.retain()`. +### Why is this bad? +`.retain()` is simpler and avoids needless allocation. +### Example +``` +let mut vec = vec![0, 1, 2]; +vec = vec.iter().filter(|&x| x % 2 == 0).copied().collect(); +vec = vec.into_iter().filter(|x| x % 2 == 0).collect(); +``` +Use instead: +``` +let mut vec = vec![0, 1, 2]; +vec.retain(|x| x % 2 == 0); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_saturating_arithmetic.txt b/src/tools/clippy/src/docs/manual_saturating_arithmetic.txt new file mode 100644 index 0000000000000..d9f5d3d118712 --- /dev/null +++ b/src/tools/clippy/src/docs/manual_saturating_arithmetic.txt @@ -0,0 +1,18 @@ +### What it does +Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`. + +### Why is this bad? +These can be written simply with `saturating_add/sub` methods. + +### Example +``` +let add = x.checked_add(y).unwrap_or(u32::MAX); +let sub = x.checked_sub(y).unwrap_or(u32::MIN); +``` + +can be written using dedicated methods for saturating addition/subtraction as: + +``` +let add = x.saturating_add(y); +let sub = x.saturating_sub(y); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_split_once.txt b/src/tools/clippy/src/docs/manual_split_once.txt new file mode 100644 index 0000000000000..291ae447de08a --- /dev/null +++ b/src/tools/clippy/src/docs/manual_split_once.txt @@ -0,0 +1,29 @@ +### What it does +Checks for usages of `str::splitn(2, _)` + +### Why is this bad? +`split_once` is both clearer in intent and slightly more efficient. + +### Example +``` +let s = "key=value=add"; +let (key, value) = s.splitn(2, '=').next_tuple()?; +let value = s.splitn(2, '=').nth(1)?; + +let mut parts = s.splitn(2, '='); +let key = parts.next()?; +let value = parts.next()?; +``` + +Use instead: +``` +let s = "key=value=add"; +let (key, value) = s.split_once('=')?; +let value = s.split_once('=')?.1; + +let (key, value) = s.split_once('=')?; +``` + +### Limitations +The multiple statement variant currently only detects `iter.next()?`/`iter.next().unwrap()` +in two separate `let` statements that immediately follow the `splitn()` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_str_repeat.txt b/src/tools/clippy/src/docs/manual_str_repeat.txt new file mode 100644 index 0000000000000..1d4a7a48e2033 --- /dev/null +++ b/src/tools/clippy/src/docs/manual_str_repeat.txt @@ -0,0 +1,15 @@ +### What it does +Checks for manual implementations of `str::repeat` + +### Why is this bad? +These are both harder to read, as well as less performant. + +### Example +``` +let x: String = std::iter::repeat('x').take(10).collect(); +``` + +Use instead: +``` +let x: String = "x".repeat(10); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_string_new.txt b/src/tools/clippy/src/docs/manual_string_new.txt new file mode 100644 index 0000000000000..4cbc43f8f8439 --- /dev/null +++ b/src/tools/clippy/src/docs/manual_string_new.txt @@ -0,0 +1,20 @@ +### What it does + +Checks for usage of `""` to create a `String`, such as `"".to_string()`, `"".to_owned()`, +`String::from("")` and others. + +### Why is this bad? + +Different ways of creating an empty string makes your code less standardized, which can +be confusing. + +### Example +``` +let a = "".to_string(); +let b: String = "".into(); +``` +Use instead: +``` +let a = String::new(); +let b = String::new(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_strip.txt b/src/tools/clippy/src/docs/manual_strip.txt new file mode 100644 index 0000000000000..f32d8e7a09bb3 --- /dev/null +++ b/src/tools/clippy/src/docs/manual_strip.txt @@ -0,0 +1,24 @@ +### What it does +Suggests using `strip_{prefix,suffix}` over `str::{starts,ends}_with` and slicing using +the pattern's length. + +### Why is this bad? +Using `str:strip_{prefix,suffix}` is safer and may have better performance as there is no +slicing which may panic and the compiler does not need to insert this panic code. It is +also sometimes more readable as it removes the need for duplicating or storing the pattern +used by `str::{starts,ends}_with` and in the slicing. + +### Example +``` +let s = "hello, world!"; +if s.starts_with("hello, ") { + assert_eq!(s["hello, ".len()..].to_uppercase(), "WORLD!"); +} +``` +Use instead: +``` +let s = "hello, world!"; +if let Some(end) = s.strip_prefix("hello, ") { + assert_eq!(end.to_uppercase(), "WORLD!"); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_swap.txt b/src/tools/clippy/src/docs/manual_swap.txt new file mode 100644 index 0000000000000..bd9526288e35b --- /dev/null +++ b/src/tools/clippy/src/docs/manual_swap.txt @@ -0,0 +1,22 @@ +### What it does +Checks for manual swapping. + +### Why is this bad? +The `std::mem::swap` function exposes the intent better +without deinitializing or copying either variable. + +### Example +``` +let mut a = 42; +let mut b = 1337; + +let t = b; +b = a; +a = t; +``` +Use std::mem::swap(): +``` +let mut a = 1; +let mut b = 2; +std::mem::swap(&mut a, &mut b); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/manual_unwrap_or.txt b/src/tools/clippy/src/docs/manual_unwrap_or.txt new file mode 100644 index 0000000000000..1fd7d831bfca2 --- /dev/null +++ b/src/tools/clippy/src/docs/manual_unwrap_or.txt @@ -0,0 +1,20 @@ +### What it does +Finds patterns that reimplement `Option::unwrap_or` or `Result::unwrap_or`. + +### Why is this bad? +Concise code helps focusing on behavior instead of boilerplate. + +### Example +``` +let foo: Option = None; +match foo { + Some(v) => v, + None => 1, +}; +``` + +Use instead: +``` +let foo: Option = None; +foo.unwrap_or(1); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/many_single_char_names.txt b/src/tools/clippy/src/docs/many_single_char_names.txt new file mode 100644 index 0000000000000..55ee5da555744 --- /dev/null +++ b/src/tools/clippy/src/docs/many_single_char_names.txt @@ -0,0 +1,12 @@ +### What it does +Checks for too many variables whose name consists of a +single character. + +### Why is this bad? +It's hard to memorize what a variable means without a +descriptive name. + +### Example +``` +let (a, b, c, d, e, f, g) = (...); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/map_clone.txt b/src/tools/clippy/src/docs/map_clone.txt new file mode 100644 index 0000000000000..3ee27f072ef3d --- /dev/null +++ b/src/tools/clippy/src/docs/map_clone.txt @@ -0,0 +1,22 @@ +### What it does +Checks for usage of `map(|x| x.clone())` or +dereferencing closures for `Copy` types, on `Iterator` or `Option`, +and suggests `cloned()` or `copied()` instead + +### Why is this bad? +Readability, this can be written more concisely + +### Example +``` +let x = vec![42, 43]; +let y = x.iter(); +let z = y.map(|i| *i); +``` + +The correct use would be: + +``` +let x = vec![42, 43]; +let y = x.iter(); +let z = y.cloned(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/map_collect_result_unit.txt b/src/tools/clippy/src/docs/map_collect_result_unit.txt new file mode 100644 index 0000000000000..9b720612495ce --- /dev/null +++ b/src/tools/clippy/src/docs/map_collect_result_unit.txt @@ -0,0 +1,14 @@ +### What it does +Checks for usage of `_.map(_).collect::()`. + +### Why is this bad? +Using `try_for_each` instead is more readable and idiomatic. + +### Example +``` +(0..3).map(|t| Err(t)).collect::>(); +``` +Use instead: +``` +(0..3).try_for_each(|t| Err(t)); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/map_entry.txt b/src/tools/clippy/src/docs/map_entry.txt new file mode 100644 index 0000000000000..20dba1798d0d5 --- /dev/null +++ b/src/tools/clippy/src/docs/map_entry.txt @@ -0,0 +1,28 @@ +### What it does +Checks for uses of `contains_key` + `insert` on `HashMap` +or `BTreeMap`. + +### Why is this bad? +Using `entry` is more efficient. + +### Known problems +The suggestion may have type inference errors in some cases. e.g. +``` +let mut map = std::collections::HashMap::new(); +let _ = if !map.contains_key(&0) { + map.insert(0, 0) +} else { + None +}; +``` + +### Example +``` +if !map.contains_key(&k) { + map.insert(k, v); +} +``` +Use instead: +``` +map.entry(k).or_insert(v); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/map_err_ignore.txt b/src/tools/clippy/src/docs/map_err_ignore.txt new file mode 100644 index 0000000000000..2606c13a7afd9 --- /dev/null +++ b/src/tools/clippy/src/docs/map_err_ignore.txt @@ -0,0 +1,93 @@ +### What it does +Checks for instances of `map_err(|_| Some::Enum)` + +### Why is this bad? +This `map_err` throws away the original error rather than allowing the enum to contain and report the cause of the error + +### Example +Before: +``` +use std::fmt; + +#[derive(Debug)] +enum Error { + Indivisible, + Remainder(u8), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Indivisible => write!(f, "could not divide input by three"), + Error::Remainder(remainder) => write!( + f, + "input is not divisible by three, remainder = {}", + remainder + ), + } + } +} + +impl std::error::Error for Error {} + +fn divisible_by_3(input: &str) -> Result<(), Error> { + input + .parse::() + .map_err(|_| Error::Indivisible) + .map(|v| v % 3) + .and_then(|remainder| { + if remainder == 0 { + Ok(()) + } else { + Err(Error::Remainder(remainder as u8)) + } + }) +} + ``` + + After: + ```rust +use std::{fmt, num::ParseIntError}; + +#[derive(Debug)] +enum Error { + Indivisible(ParseIntError), + Remainder(u8), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Indivisible(_) => write!(f, "could not divide input by three"), + Error::Remainder(remainder) => write!( + f, + "input is not divisible by three, remainder = {}", + remainder + ), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Error::Indivisible(source) => Some(source), + _ => None, + } + } +} + +fn divisible_by_3(input: &str) -> Result<(), Error> { + input + .parse::() + .map_err(Error::Indivisible) + .map(|v| v % 3) + .and_then(|remainder| { + if remainder == 0 { + Ok(()) + } else { + Err(Error::Remainder(remainder as u8)) + } + }) +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/map_flatten.txt b/src/tools/clippy/src/docs/map_flatten.txt new file mode 100644 index 0000000000000..73c0e51407f28 --- /dev/null +++ b/src/tools/clippy/src/docs/map_flatten.txt @@ -0,0 +1,21 @@ +### What it does +Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option` + +### Why is this bad? +Readability, this can be written more concisely as +`_.flat_map(_)` for `Iterator` or `_.and_then(_)` for `Option` + +### Example +``` +let vec = vec![vec![1]]; +let opt = Some(5); + +vec.iter().map(|x| x.iter()).flatten(); +opt.map(|x| Some(x * 2)).flatten(); +``` + +Use instead: +``` +vec.iter().flat_map(|x| x.iter()); +opt.and_then(|x| Some(x * 2)); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/map_identity.txt b/src/tools/clippy/src/docs/map_identity.txt new file mode 100644 index 0000000000000..e2e7af0bed9b1 --- /dev/null +++ b/src/tools/clippy/src/docs/map_identity.txt @@ -0,0 +1,16 @@ +### What it does +Checks for instances of `map(f)` where `f` is the identity function. + +### Why is this bad? +It can be written more concisely without the call to `map`. + +### Example +``` +let x = [1, 2, 3]; +let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect(); +``` +Use instead: +``` +let x = [1, 2, 3]; +let y: Vec<_> = x.iter().map(|x| 2*x).collect(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/map_unwrap_or.txt b/src/tools/clippy/src/docs/map_unwrap_or.txt new file mode 100644 index 0000000000000..485b29f01b103 --- /dev/null +++ b/src/tools/clippy/src/docs/map_unwrap_or.txt @@ -0,0 +1,22 @@ +### What it does +Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or +`result.map(_).unwrap_or_else(_)`. + +### Why is this bad? +Readability, these can be written more concisely (resp.) as +`option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`. + +### Known problems +The order of the arguments is not in execution order + +### Examples +``` +option.map(|a| a + 1).unwrap_or(0); +result.map(|a| a + 1).unwrap_or_else(some_function); +``` + +Use instead: +``` +option.map_or(0, |a| a + 1); +result.map_or_else(some_function, |a| a + 1); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/match_as_ref.txt b/src/tools/clippy/src/docs/match_as_ref.txt new file mode 100644 index 0000000000000..5e5f3d645a4e4 --- /dev/null +++ b/src/tools/clippy/src/docs/match_as_ref.txt @@ -0,0 +1,23 @@ +### What it does +Checks for match which is used to add a reference to an +`Option` value. + +### Why is this bad? +Using `as_ref()` or `as_mut()` instead is shorter. + +### Example +``` +let x: Option<()> = None; + +let r: Option<&()> = match x { + None => None, + Some(ref v) => Some(v), +}; +``` + +Use instead: +``` +let x: Option<()> = None; + +let r: Option<&()> = x.as_ref(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/match_bool.txt b/src/tools/clippy/src/docs/match_bool.txt new file mode 100644 index 0000000000000..96f9e1f8b7d1b --- /dev/null +++ b/src/tools/clippy/src/docs/match_bool.txt @@ -0,0 +1,24 @@ +### What it does +Checks for matches where match expression is a `bool`. It +suggests to replace the expression with an `if...else` block. + +### Why is this bad? +It makes the code less readable. + +### Example +``` +let condition: bool = true; +match condition { + true => foo(), + false => bar(), +} +``` +Use if/else instead: +``` +let condition: bool = true; +if condition { + foo(); +} else { + bar(); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/match_like_matches_macro.txt b/src/tools/clippy/src/docs/match_like_matches_macro.txt new file mode 100644 index 0000000000000..643e2ddc97ba0 --- /dev/null +++ b/src/tools/clippy/src/docs/match_like_matches_macro.txt @@ -0,0 +1,32 @@ +### What it does +Checks for `match` or `if let` expressions producing a +`bool` that could be written using `matches!` + +### Why is this bad? +Readability and needless complexity. + +### Known problems +This lint falsely triggers, if there are arms with +`cfg` attributes that remove an arm evaluating to `false`. + +### Example +``` +let x = Some(5); + +let a = match x { + Some(0) => true, + _ => false, +}; + +let a = if let Some(0) = x { + true +} else { + false +}; +``` + +Use instead: +``` +let x = Some(5); +let a = matches!(x, Some(0)); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/match_on_vec_items.txt b/src/tools/clippy/src/docs/match_on_vec_items.txt new file mode 100644 index 0000000000000..981d18d0f9ed5 --- /dev/null +++ b/src/tools/clippy/src/docs/match_on_vec_items.txt @@ -0,0 +1,29 @@ +### What it does +Checks for `match vec[idx]` or `match vec[n..m]`. + +### Why is this bad? +This can panic at runtime. + +### Example +``` +let arr = vec![0, 1, 2, 3]; +let idx = 1; + +match arr[idx] { + 0 => println!("{}", 0), + 1 => println!("{}", 3), + _ => {}, +} +``` + +Use instead: +``` +let arr = vec![0, 1, 2, 3]; +let idx = 1; + +match arr.get(idx) { + Some(0) => println!("{}", 0), + Some(1) => println!("{}", 3), + _ => {}, +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/match_overlapping_arm.txt b/src/tools/clippy/src/docs/match_overlapping_arm.txt new file mode 100644 index 0000000000000..841c091bd5cad --- /dev/null +++ b/src/tools/clippy/src/docs/match_overlapping_arm.txt @@ -0,0 +1,16 @@ +### What it does +Checks for overlapping match arms. + +### Why is this bad? +It is likely to be an error and if not, makes the code +less obvious. + +### Example +``` +let x = 5; +match x { + 1..=10 => println!("1 ... 10"), + 5..=15 => println!("5 ... 15"), + _ => (), +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/match_ref_pats.txt b/src/tools/clippy/src/docs/match_ref_pats.txt new file mode 100644 index 0000000000000..b1d9029950972 --- /dev/null +++ b/src/tools/clippy/src/docs/match_ref_pats.txt @@ -0,0 +1,26 @@ +### What it does +Checks for matches where all arms match a reference, +suggesting to remove the reference and deref the matched expression +instead. It also checks for `if let &foo = bar` blocks. + +### Why is this bad? +It just makes the code less readable. That reference +destructuring adds nothing to the code. + +### Example +``` +match x { + &A(ref y) => foo(y), + &B => bar(), + _ => frob(&x), +} +``` + +Use instead: +``` +match *x { + A(ref y) => foo(y), + B => bar(), + _ => frob(x), +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/match_result_ok.txt b/src/tools/clippy/src/docs/match_result_ok.txt new file mode 100644 index 0000000000000..eea7c8e00f1bb --- /dev/null +++ b/src/tools/clippy/src/docs/match_result_ok.txt @@ -0,0 +1,27 @@ +### What it does +Checks for unnecessary `ok()` in `while let`. + +### Why is this bad? +Calling `ok()` in `while let` is unnecessary, instead match +on `Ok(pat)` + +### Example +``` +while let Some(value) = iter.next().ok() { + vec.push(value) +} + +if let Some(value) = iter.next().ok() { + vec.push(value) +} +``` +Use instead: +``` +while let Ok(value) = iter.next() { + vec.push(value) +} + +if let Ok(value) = iter.next() { + vec.push(value) +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/match_same_arms.txt b/src/tools/clippy/src/docs/match_same_arms.txt new file mode 100644 index 0000000000000..14edf12032e0d --- /dev/null +++ b/src/tools/clippy/src/docs/match_same_arms.txt @@ -0,0 +1,38 @@ +### What it does +Checks for `match` with identical arm bodies. + +### Why is this bad? +This is probably a copy & paste error. If arm bodies +are the same on purpose, you can factor them +[using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns). + +### Known problems +False positive possible with order dependent `match` +(see issue +[#860](https://github.com/rust-lang/rust-clippy/issues/860)). + +### Example +``` +match foo { + Bar => bar(), + Quz => quz(), + Baz => bar(), // <= oops +} +``` + +This should probably be +``` +match foo { + Bar => bar(), + Quz => quz(), + Baz => baz(), // <= fixed +} +``` + +or if the original code was not a typo: +``` +match foo { + Bar | Baz => bar(), // <= shows the intent better + Quz => quz(), +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/match_single_binding.txt b/src/tools/clippy/src/docs/match_single_binding.txt new file mode 100644 index 0000000000000..67ded0bbd5534 --- /dev/null +++ b/src/tools/clippy/src/docs/match_single_binding.txt @@ -0,0 +1,23 @@ +### What it does +Checks for useless match that binds to only one value. + +### Why is this bad? +Readability and needless complexity. + +### Known problems + Suggested replacements may be incorrect when `match` +is actually binding temporary value, bringing a 'dropped while borrowed' error. + +### Example +``` +match (a, b) { + (c, d) => { + // useless match + } +} +``` + +Use instead: +``` +let (c, d) = (a, b); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/match_str_case_mismatch.txt b/src/tools/clippy/src/docs/match_str_case_mismatch.txt new file mode 100644 index 0000000000000..19e74c2084eae --- /dev/null +++ b/src/tools/clippy/src/docs/match_str_case_mismatch.txt @@ -0,0 +1,22 @@ +### What it does +Checks for `match` expressions modifying the case of a string with non-compliant arms + +### Why is this bad? +The arm is unreachable, which is likely a mistake + +### Example +``` +match &*text.to_ascii_lowercase() { + "foo" => {}, + "Bar" => {}, + _ => {}, +} +``` +Use instead: +``` +match &*text.to_ascii_lowercase() { + "foo" => {}, + "bar" => {}, + _ => {}, +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/match_wild_err_arm.txt b/src/tools/clippy/src/docs/match_wild_err_arm.txt new file mode 100644 index 0000000000000..f89b3a23a1ca2 --- /dev/null +++ b/src/tools/clippy/src/docs/match_wild_err_arm.txt @@ -0,0 +1,16 @@ +### What it does +Checks for arm which matches all errors with `Err(_)` +and take drastic actions like `panic!`. + +### Why is this bad? +It is generally a bad practice, similar to +catching all exceptions in java with `catch(Exception)` + +### Example +``` +let x: Result = Ok(3); +match x { + Ok(_) => println!("ok"), + Err(_) => panic!("err"), +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/match_wildcard_for_single_variants.txt b/src/tools/clippy/src/docs/match_wildcard_for_single_variants.txt new file mode 100644 index 0000000000000..25559b9ecdcff --- /dev/null +++ b/src/tools/clippy/src/docs/match_wildcard_for_single_variants.txt @@ -0,0 +1,27 @@ +### What it does +Checks for wildcard enum matches for a single variant. + +### Why is this bad? +New enum variants added by library updates can be missed. + +### Known problems +Suggested replacements may not use correct path to enum +if it's not present in the current scope. + +### Example +``` +match x { + Foo::A => {}, + Foo::B => {}, + _ => {}, +} +``` + +Use instead: +``` +match x { + Foo::A => {}, + Foo::B => {}, + Foo::C => {}, +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/maybe_infinite_iter.txt b/src/tools/clippy/src/docs/maybe_infinite_iter.txt new file mode 100644 index 0000000000000..1204a49b46681 --- /dev/null +++ b/src/tools/clippy/src/docs/maybe_infinite_iter.txt @@ -0,0 +1,16 @@ +### What it does +Checks for iteration that may be infinite. + +### Why is this bad? +While there may be places where this is acceptable +(e.g., in event streams), in most cases this is simply an error. + +### Known problems +The code may have a condition to stop iteration, but +this lint is not clever enough to analyze it. + +### Example +``` +let infinite_iter = 0..; +[0..].iter().zip(infinite_iter.take_while(|x| *x > 5)); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/mem_forget.txt b/src/tools/clippy/src/docs/mem_forget.txt new file mode 100644 index 0000000000000..a6888c48fc33b --- /dev/null +++ b/src/tools/clippy/src/docs/mem_forget.txt @@ -0,0 +1,12 @@ +### What it does +Checks for usage of `std::mem::forget(t)` where `t` is +`Drop`. + +### Why is this bad? +`std::mem::forget(t)` prevents `t` from running its +destructor, possibly causing leaks. + +### Example +``` +mem::forget(Rc::new(55)) +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/mem_replace_option_with_none.txt b/src/tools/clippy/src/docs/mem_replace_option_with_none.txt new file mode 100644 index 0000000000000..7f243d1c16565 --- /dev/null +++ b/src/tools/clippy/src/docs/mem_replace_option_with_none.txt @@ -0,0 +1,21 @@ +### What it does +Checks for `mem::replace()` on an `Option` with +`None`. + +### Why is this bad? +`Option` already has the method `take()` for +taking its current value (Some(..) or None) and replacing it with +`None`. + +### Example +``` +use std::mem; + +let mut an_option = Some(0); +let replaced = mem::replace(&mut an_option, None); +``` +Is better expressed with: +``` +let mut an_option = Some(0); +let taken = an_option.take(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/mem_replace_with_default.txt b/src/tools/clippy/src/docs/mem_replace_with_default.txt new file mode 100644 index 0000000000000..24e0913a30c92 --- /dev/null +++ b/src/tools/clippy/src/docs/mem_replace_with_default.txt @@ -0,0 +1,18 @@ +### What it does +Checks for `std::mem::replace` on a value of type +`T` with `T::default()`. + +### Why is this bad? +`std::mem` module already has the method `take` to +take the current value and replace it with the default value of that type. + +### Example +``` +let mut text = String::from("foo"); +let replaced = std::mem::replace(&mut text, String::default()); +``` +Is better expressed with: +``` +let mut text = String::from("foo"); +let taken = std::mem::take(&mut text); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/mem_replace_with_uninit.txt b/src/tools/clippy/src/docs/mem_replace_with_uninit.txt new file mode 100644 index 0000000000000..0bb483668abc1 --- /dev/null +++ b/src/tools/clippy/src/docs/mem_replace_with_uninit.txt @@ -0,0 +1,24 @@ +### 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. + +### Example +``` +use std::mem; + +#[allow(deprecated, invalid_value)] +fn myfunc (v: &mut Vec) { + 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. \ No newline at end of file diff --git a/src/tools/clippy/src/docs/min_max.txt b/src/tools/clippy/src/docs/min_max.txt new file mode 100644 index 0000000000000..6acf0f932e986 --- /dev/null +++ b/src/tools/clippy/src/docs/min_max.txt @@ -0,0 +1,18 @@ +### What it does +Checks for expressions where `std::cmp::min` and `max` are +used to clamp values, but switched so that the result is constant. + +### Why is this bad? +This is in all probability not the intended outcome. At +the least it hurts readability of the code. + +### Example +``` +min(0, max(100, x)) + +// or + +x.max(100).min(0) +``` +It will always be equal to `0`. Probably the author meant to clamp the value +between 0 and 100, but has erroneously swapped `min` and `max`. \ No newline at end of file diff --git a/src/tools/clippy/src/docs/mismatched_target_os.txt b/src/tools/clippy/src/docs/mismatched_target_os.txt new file mode 100644 index 0000000000000..51e5ec6e7c5c4 --- /dev/null +++ b/src/tools/clippy/src/docs/mismatched_target_os.txt @@ -0,0 +1,24 @@ +### What it does +Checks for cfg attributes having operating systems used in target family position. + +### Why is this bad? +The configuration option will not be recognised and the related item will not be included +by the conditional compilation engine. + +### Example +``` +#[cfg(linux)] +fn conditional() { } +``` + +Use instead: +``` +#[cfg(target_os = "linux")] +fn conditional() { } + +// or + +#[cfg(unix)] +fn conditional() { } +``` +Check the [Rust Reference](https://doc.rust-lang.org/reference/conditional-compilation.html#target_os) for more details. \ No newline at end of file diff --git a/src/tools/clippy/src/docs/mismatching_type_param_order.txt b/src/tools/clippy/src/docs/mismatching_type_param_order.txt new file mode 100644 index 0000000000000..ffc7f32d0aad8 --- /dev/null +++ b/src/tools/clippy/src/docs/mismatching_type_param_order.txt @@ -0,0 +1,33 @@ +### What it does +Checks for type parameters which are positioned inconsistently between +a type definition and impl block. Specifically, a parameter in an impl +block which has the same name as a parameter in the type def, but is in +a different place. + +### Why is this bad? +Type parameters are determined by their position rather than name. +Naming type parameters inconsistently may cause you to refer to the +wrong type parameter. + +### Limitations +This lint only applies to impl blocks with simple generic params, e.g. +`A`. If there is anything more complicated, such as a tuple, it will be +ignored. + +### Example +``` +struct Foo { + x: A, + y: B, +} +// inside the impl, B refers to Foo::A +impl Foo {} +``` +Use instead: +``` +struct Foo { + x: A, + y: B, +} +impl Foo {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/misrefactored_assign_op.txt b/src/tools/clippy/src/docs/misrefactored_assign_op.txt new file mode 100644 index 0000000000000..3d691fe4178b5 --- /dev/null +++ b/src/tools/clippy/src/docs/misrefactored_assign_op.txt @@ -0,0 +1,20 @@ +### What it does +Checks for `a op= a op b` or `a op= b op a` patterns. + +### Why is this bad? +Most likely these are bugs where one meant to write `a +op= b`. + +### Known problems +Clippy cannot know for sure if `a op= a op b` should have +been `a = a op a op b` or `a = a op b`/`a op= b`. Therefore, it suggests both. +If `a op= a op b` is really the correct behavior it should be +written as `a = a op a op b` as it's less confusing. + +### Example +``` +let mut a = 5; +let b = 2; +// ... +a += a + b; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/missing_const_for_fn.txt b/src/tools/clippy/src/docs/missing_const_for_fn.txt new file mode 100644 index 0000000000000..067614d4c46bf --- /dev/null +++ b/src/tools/clippy/src/docs/missing_const_for_fn.txt @@ -0,0 +1,40 @@ +### What it does +Suggests the use of `const` in functions and methods where possible. + +### Why is this bad? +Not having the function const prevents callers of the function from being const as well. + +### Known problems +Const functions are currently still being worked on, with some features only being available +on nightly. This lint does not consider all edge cases currently and the suggestions may be +incorrect if you are using this lint on stable. + +Also, the lint only runs one pass over the code. Consider these two non-const functions: + +``` +fn a() -> i32 { + 0 +} +fn b() -> i32 { + a() +} +``` + +When running Clippy, the lint will only suggest to make `a` const, because `b` at this time +can't be const as it calls a non-const function. Making `a` const and running Clippy again, +will suggest to make `b` const, too. + +### Example +``` +fn new() -> Self { + Self { random_number: 42 } +} +``` + +Could be a const fn: + +``` +const fn new() -> Self { + Self { random_number: 42 } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/missing_docs_in_private_items.txt b/src/tools/clippy/src/docs/missing_docs_in_private_items.txt new file mode 100644 index 0000000000000..5d37505bb1716 --- /dev/null +++ b/src/tools/clippy/src/docs/missing_docs_in_private_items.txt @@ -0,0 +1,9 @@ +### What it does +Warns if there is missing doc for any documentable item +(public or private). + +### Why is this bad? +Doc is good. *rustc* has a `MISSING_DOCS` +allowed-by-default lint for +public members, but has no way to enforce documentation of private items. +This lint fixes that. \ No newline at end of file diff --git a/src/tools/clippy/src/docs/missing_enforced_import_renames.txt b/src/tools/clippy/src/docs/missing_enforced_import_renames.txt new file mode 100644 index 0000000000000..8f4649bd5923d --- /dev/null +++ b/src/tools/clippy/src/docs/missing_enforced_import_renames.txt @@ -0,0 +1,22 @@ +### What it does +Checks for imports that do not rename the item as specified +in the `enforce-import-renames` config option. + +### Why is this bad? +Consistency is important, if a project has defined import +renames they should be followed. More practically, some item names are too +vague outside of their defining scope this can enforce a more meaningful naming. + +### Example +An example clippy.toml configuration: +``` +enforced-import-renames = [ { path = "serde_json::Value", rename = "JsonValue" }] +``` + +``` +use serde_json::Value; +``` +Use instead: +``` +use serde_json::Value as JsonValue; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/missing_errors_doc.txt b/src/tools/clippy/src/docs/missing_errors_doc.txt new file mode 100644 index 0000000000000..028778d85aeba --- /dev/null +++ b/src/tools/clippy/src/docs/missing_errors_doc.txt @@ -0,0 +1,21 @@ +### What it does +Checks the doc comments of publicly visible functions that +return a `Result` type and warns if there is no `# Errors` section. + +### Why is this bad? +Documenting the type of errors that can be returned from a +function can help callers write code to handle the errors appropriately. + +### Examples +Since the following function returns a `Result` it has an `# Errors` section in +its doc comment: + +``` +/// # Errors +/// +/// Will return `Err` if `filename` does not exist or the user does not have +/// permission to read it. +pub fn read(filename: String) -> io::Result { + unimplemented!(); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/missing_inline_in_public_items.txt b/src/tools/clippy/src/docs/missing_inline_in_public_items.txt new file mode 100644 index 0000000000000..d90c50fe7f9e8 --- /dev/null +++ b/src/tools/clippy/src/docs/missing_inline_in_public_items.txt @@ -0,0 +1,45 @@ +### What it does +It lints if an exported function, method, trait method with default impl, +or trait method impl is not `#[inline]`. + +### Why is this bad? +In general, it is not. Functions can be inlined across +crates when that's profitable as long as any form of LTO is used. When LTO is disabled, +functions that are not `#[inline]` cannot be inlined across crates. Certain types of crates +might intend for most of the methods in their public API to be able to be inlined across +crates even when LTO is disabled. For these types of crates, enabling this lint might make +sense. It allows the crate to require all exported methods to be `#[inline]` by default, and +then opt out for specific methods where this might not make sense. + +### Example +``` +pub fn foo() {} // missing #[inline] +fn ok() {} // ok +#[inline] pub fn bar() {} // ok +#[inline(always)] pub fn baz() {} // ok + +pub trait Bar { + fn bar(); // ok + fn def_bar() {} // missing #[inline] +} + +struct Baz; +impl Baz { + fn private() {} // ok +} + +impl Bar for Baz { + fn bar() {} // ok - Baz is not exported +} + +pub struct PubBaz; +impl PubBaz { + fn private() {} // ok + pub fn not_private() {} // missing #[inline] +} + +impl Bar for PubBaz { + fn bar() {} // missing #[inline] + fn def_bar() {} // missing #[inline] +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/missing_panics_doc.txt b/src/tools/clippy/src/docs/missing_panics_doc.txt new file mode 100644 index 0000000000000..e5e39a824519b --- /dev/null +++ b/src/tools/clippy/src/docs/missing_panics_doc.txt @@ -0,0 +1,24 @@ +### What it does +Checks the doc comments of publicly visible functions that +may panic and warns if there is no `# Panics` section. + +### Why is this bad? +Documenting the scenarios in which panicking occurs +can help callers who do not want to panic to avoid those situations. + +### Examples +Since the following function may panic it has a `# Panics` section in +its doc comment: + +``` +/// # Panics +/// +/// Will panic if y is 0 +pub fn divide_by(x: i32, y: i32) -> i32 { + if y == 0 { + panic!("Cannot divide by 0") + } else { + x / y + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/missing_safety_doc.txt b/src/tools/clippy/src/docs/missing_safety_doc.txt new file mode 100644 index 0000000000000..6492eb84f63bf --- /dev/null +++ b/src/tools/clippy/src/docs/missing_safety_doc.txt @@ -0,0 +1,26 @@ +### What it does +Checks for the doc comments of publicly visible +unsafe functions and warns if there is no `# Safety` section. + +### Why is this bad? +Unsafe functions should document their safety +preconditions, so that users can be sure they are using them safely. + +### Examples +``` +/// This function should really be documented +pub unsafe fn start_apocalypse(u: &mut Universe) { + unimplemented!(); +} +``` + +At least write a line about safety: + +``` +/// # Safety +/// +/// This function should not be called before the horsemen are ready. +pub unsafe fn start_apocalypse(u: &mut Universe) { + unimplemented!(); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/missing_spin_loop.txt b/src/tools/clippy/src/docs/missing_spin_loop.txt new file mode 100644 index 0000000000000..3a06a91d71835 --- /dev/null +++ b/src/tools/clippy/src/docs/missing_spin_loop.txt @@ -0,0 +1,27 @@ +### What it does +Check for empty spin loops + +### Why is this bad? +The loop body should have something like `thread::park()` or at least +`std::hint::spin_loop()` to avoid needlessly burning cycles and conserve +energy. Perhaps even better use an actual lock, if possible. + +### Known problems +This lint doesn't currently trigger on `while let` or +`loop { match .. { .. } }` loops, which would be considered idiomatic in +combination with e.g. `AtomicBool::compare_exchange_weak`. + +### Example + +``` +use core::sync::atomic::{AtomicBool, Ordering}; +let b = AtomicBool::new(true); +// give a ref to `b` to another thread,wait for it to become false +while b.load(Ordering::Acquire) {}; +``` +Use instead: +``` +while b.load(Ordering::Acquire) { + std::hint::spin_loop() +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/mistyped_literal_suffixes.txt b/src/tools/clippy/src/docs/mistyped_literal_suffixes.txt new file mode 100644 index 0000000000000..1760fcbfeacc4 --- /dev/null +++ b/src/tools/clippy/src/docs/mistyped_literal_suffixes.txt @@ -0,0 +1,15 @@ +### What it does +Warns for mistyped suffix in literals + +### Why is this bad? +This is most probably a typo + +### Known problems +- Does not match on integers too large to fit in the corresponding unsigned type +- Does not match on `_127` since that is a valid grouping for decimal and octal numbers + +### Example +``` +`2_32` => `2_i32` +`250_8 => `250_u8` +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/mixed_case_hex_literals.txt b/src/tools/clippy/src/docs/mixed_case_hex_literals.txt new file mode 100644 index 0000000000000..d2d01e0c98eb4 --- /dev/null +++ b/src/tools/clippy/src/docs/mixed_case_hex_literals.txt @@ -0,0 +1,16 @@ +### What it does +Warns on hexadecimal literals with mixed-case letter +digits. + +### Why is this bad? +It looks confusing. + +### Example +``` +0x1a9BAcD +``` + +Use instead: +``` +0x1A9BACD +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/mixed_read_write_in_expression.txt b/src/tools/clippy/src/docs/mixed_read_write_in_expression.txt new file mode 100644 index 0000000000000..02d1c5d052524 --- /dev/null +++ b/src/tools/clippy/src/docs/mixed_read_write_in_expression.txt @@ -0,0 +1,32 @@ +### What it does +Checks for a read and a write to the same variable where +whether the read occurs before or after the write depends on the evaluation +order of sub-expressions. + +### Why is this bad? +It is often confusing to read. As described [here](https://doc.rust-lang.org/reference/expressions.html?highlight=subexpression#evaluation-order-of-operands), +the operands of these expressions are evaluated before applying the effects of the expression. + +### Known problems +Code which intentionally depends on the evaluation +order, or which is correct for any evaluation order. + +### Example +``` +let mut x = 0; + +let a = { + x = 1; + 1 +} + x; +// Unclear whether a is 1 or 2. +``` + +Use instead: +``` +let tmp = { + x = 1; + 1 +}; +let a = tmp + x; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/mod_module_files.txt b/src/tools/clippy/src/docs/mod_module_files.txt new file mode 100644 index 0000000000000..95bca583afd3c --- /dev/null +++ b/src/tools/clippy/src/docs/mod_module_files.txt @@ -0,0 +1,22 @@ +### What it does +Checks that module layout uses only self named module files, bans `mod.rs` files. + +### Why is this bad? +Having multiple module layout styles in a project can be confusing. + +### Example +``` +src/ + stuff/ + stuff_files.rs + mod.rs + lib.rs +``` +Use instead: +``` +src/ + stuff/ + stuff_files.rs + stuff.rs + lib.rs +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/module_inception.txt b/src/tools/clippy/src/docs/module_inception.txt new file mode 100644 index 0000000000000..d80a1b8d8fe57 --- /dev/null +++ b/src/tools/clippy/src/docs/module_inception.txt @@ -0,0 +1,24 @@ +### What it does +Checks for modules that have the same name as their +parent module + +### Why is this bad? +A typical beginner mistake is to have `mod foo;` and +again `mod foo { .. +}` in `foo.rs`. +The expectation is that items inside the inner `mod foo { .. }` are then +available +through `foo::x`, but they are only available through +`foo::foo::x`. +If this is done on purpose, it would be better to choose a more +representative module name. + +### Example +``` +// lib.rs +mod foo; +// foo.rs +mod foo { + ... +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/module_name_repetitions.txt b/src/tools/clippy/src/docs/module_name_repetitions.txt new file mode 100644 index 0000000000000..3bc05d02780ca --- /dev/null +++ b/src/tools/clippy/src/docs/module_name_repetitions.txt @@ -0,0 +1,20 @@ +### What it does +Detects type names that are prefixed or suffixed by the +containing module's name. + +### Why is this bad? +It requires the user to type the module name twice. + +### Example +``` +mod cake { + struct BlackForestCake; +} +``` + +Use instead: +``` +mod cake { + struct BlackForest; +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/modulo_arithmetic.txt b/src/tools/clippy/src/docs/modulo_arithmetic.txt new file mode 100644 index 0000000000000..ff7296f3c5b8d --- /dev/null +++ b/src/tools/clippy/src/docs/modulo_arithmetic.txt @@ -0,0 +1,15 @@ +### What it does +Checks for modulo arithmetic. + +### Why is this bad? +The results of modulo (%) operation might differ +depending on the language, when negative numbers are involved. +If you interop with different languages it might be beneficial +to double check all places that use modulo arithmetic. + +For example, in Rust `17 % -3 = 2`, but in Python `17 % -3 = -1`. + +### Example +``` +let x = -17 % 3; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/modulo_one.txt b/src/tools/clippy/src/docs/modulo_one.txt new file mode 100644 index 0000000000000..bc8f95b0be693 --- /dev/null +++ b/src/tools/clippy/src/docs/modulo_one.txt @@ -0,0 +1,16 @@ +### What it does +Checks for getting the remainder of a division by one or minus +one. + +### Why is this bad? +The result for a divisor of one can only ever be zero; for +minus one it can cause panic/overflow (if the left operand is the minimal value of +the respective integer type) or results in zero. No one will write such code +deliberately, unless trying to win an Underhanded Rust Contest. Even for that +contest, it's probably a bad idea. Use something more underhanded. + +### Example +``` +let a = x % 1; +let a = x % -1; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/multi_assignments.txt b/src/tools/clippy/src/docs/multi_assignments.txt new file mode 100644 index 0000000000000..ed1f1b420cbd3 --- /dev/null +++ b/src/tools/clippy/src/docs/multi_assignments.txt @@ -0,0 +1,17 @@ +### What it does +Checks for nested assignments. + +### Why is this bad? +While this is in most cases already a type mismatch, +the result of an assignment being `()` can throw off people coming from languages like python or C, +where such assignments return a copy of the assigned value. + +### Example +``` +a = b = 42; +``` +Use instead: +``` +b = 42; +a = b; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/multiple_crate_versions.txt b/src/tools/clippy/src/docs/multiple_crate_versions.txt new file mode 100644 index 0000000000000..cf2d2c6abee3e --- /dev/null +++ b/src/tools/clippy/src/docs/multiple_crate_versions.txt @@ -0,0 +1,19 @@ +### What it does +Checks to see if multiple versions of a crate are being +used. + +### Why is this bad? +This bloats the size of targets, and can lead to +confusing error messages when structs or traits are used interchangeably +between different versions of a crate. + +### Known problems +Because this can be caused purely by the dependencies +themselves, it's not always possible to fix this issue. + +### Example +``` +[dependencies] +ctrlc = "=3.1.0" +ansi_term = "=0.11.0" +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/multiple_inherent_impl.txt b/src/tools/clippy/src/docs/multiple_inherent_impl.txt new file mode 100644 index 0000000000000..9d42286560cef --- /dev/null +++ b/src/tools/clippy/src/docs/multiple_inherent_impl.txt @@ -0,0 +1,26 @@ +### What it does +Checks for multiple inherent implementations of a struct + +### Why is this bad? +Splitting the implementation of a type makes the code harder to navigate. + +### Example +``` +struct X; +impl X { + fn one() {} +} +impl X { + fn other() {} +} +``` + +Could be written: + +``` +struct X; +impl X { + fn one() {} + fn other() {} +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/must_use_candidate.txt b/src/tools/clippy/src/docs/must_use_candidate.txt new file mode 100644 index 0000000000000..70890346fe6b8 --- /dev/null +++ b/src/tools/clippy/src/docs/must_use_candidate.txt @@ -0,0 +1,23 @@ +### What it does +Checks for public functions that have no +`#[must_use]` attribute, but return something not already marked +must-use, have no mutable arg and mutate no statics. + +### Why is this bad? +Not bad at all, this lint just shows places where +you could add the attribute. + +### Known problems +The lint only checks the arguments for mutable +types without looking if they are actually changed. On the other hand, +it also ignores a broad range of potentially interesting side effects, +because we cannot decide whether the programmer intends the function to +be called for the side effect or the result. Expect many false +positives. At least we don't lint if the result type is unit or already +`#[must_use]`. + +### Examples +``` +// this could be annotated with `#[must_use]`. +fn id(t: T) -> T { t } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/must_use_unit.txt b/src/tools/clippy/src/docs/must_use_unit.txt new file mode 100644 index 0000000000000..cabbb23f8651e --- /dev/null +++ b/src/tools/clippy/src/docs/must_use_unit.txt @@ -0,0 +1,13 @@ +### What it does +Checks for a `#[must_use]` attribute on +unit-returning functions and methods. + +### Why is this bad? +Unit values are useless. The attribute is likely +a remnant of a refactoring that removed the return type. + +### Examples +``` +#[must_use] +fn useless() { } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/mut_from_ref.txt b/src/tools/clippy/src/docs/mut_from_ref.txt new file mode 100644 index 0000000000000..cc1da12549a5d --- /dev/null +++ b/src/tools/clippy/src/docs/mut_from_ref.txt @@ -0,0 +1,26 @@ +### What it does +This lint checks for functions that take immutable references and return +mutable ones. This will not trigger if no unsafe code exists as there +are multiple safe functions which will do this transformation + +To be on the conservative side, if there's at least one mutable +reference with the output lifetime, this lint will not trigger. + +### Why is this bad? +Creating a mutable reference which can be repeatably derived from an +immutable reference is unsound as it allows creating multiple live +mutable references to the same object. + +This [error](https://github.com/rust-lang/rust/issues/39465) actually +lead to an interim Rust release 1.15.1. + +### Known problems +This pattern is used by memory allocators to allow allocating multiple +objects while returning mutable references to each one. So long as +different mutable references are returned each time such a function may +be safe. + +### Example +``` +fn foo(&Foo) -> &mut Bar { .. } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/mut_mut.txt b/src/tools/clippy/src/docs/mut_mut.txt new file mode 100644 index 0000000000000..0bd34dd24b26a --- /dev/null +++ b/src/tools/clippy/src/docs/mut_mut.txt @@ -0,0 +1,12 @@ +### What it does +Checks for instances of `mut mut` references. + +### Why is this bad? +Multiple `mut`s don't add anything meaningful to the +source. This is either a copy'n'paste error, or it shows a fundamental +misunderstanding of references. + +### Example +``` +let x = &mut &mut y; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/mut_mutex_lock.txt b/src/tools/clippy/src/docs/mut_mutex_lock.txt new file mode 100644 index 0000000000000..5e9ad8a3f176a --- /dev/null +++ b/src/tools/clippy/src/docs/mut_mutex_lock.txt @@ -0,0 +1,29 @@ +### What it does +Checks for `&mut Mutex::lock` calls + +### Why is this bad? +`Mutex::lock` is less efficient than +calling `Mutex::get_mut`. In addition you also have a statically +guarantee that the mutex isn't locked, instead of just a runtime +guarantee. + +### Example +``` +use std::sync::{Arc, Mutex}; + +let mut value_rc = Arc::new(Mutex::new(42_u8)); +let value_mutex = Arc::get_mut(&mut value_rc).unwrap(); + +let mut value = value_mutex.lock().unwrap(); +*value += 1; +``` +Use instead: +``` +use std::sync::{Arc, Mutex}; + +let mut value_rc = Arc::new(Mutex::new(42_u8)); +let value_mutex = Arc::get_mut(&mut value_rc).unwrap(); + +let value = value_mutex.get_mut().unwrap(); +*value += 1; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/mut_range_bound.txt b/src/tools/clippy/src/docs/mut_range_bound.txt new file mode 100644 index 0000000000000..e9c38a543b146 --- /dev/null +++ b/src/tools/clippy/src/docs/mut_range_bound.txt @@ -0,0 +1,29 @@ +### What it does +Checks for loops which have a range bound that is a mutable variable + +### Why is this bad? +One might think that modifying the mutable variable changes the loop bounds + +### Known problems +False positive when mutation is followed by a `break`, but the `break` is not immediately +after the mutation: + +``` +let mut x = 5; +for _ in 0..x { + x += 1; // x is a range bound that is mutated + ..; // some other expression + break; // leaves the loop, so mutation is not an issue +} +``` + +False positive on nested loops ([#6072](https://github.com/rust-lang/rust-clippy/issues/6072)) + +### Example +``` +let mut foo = 42; +for i in 0..foo { + foo -= 1; + println!("{}", i); // prints numbers from 0 to 42, not 0 to 21 +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/mutable_key_type.txt b/src/tools/clippy/src/docs/mutable_key_type.txt new file mode 100644 index 0000000000000..15fe34f2bb5ec --- /dev/null +++ b/src/tools/clippy/src/docs/mutable_key_type.txt @@ -0,0 +1,61 @@ +### What it does +Checks for sets/maps with mutable key types. + +### Why is this bad? +All of `HashMap`, `HashSet`, `BTreeMap` and +`BtreeSet` rely on either the hash or the order of keys be unchanging, +so having types with interior mutability is a bad idea. + +### Known problems + +#### False Positives +It's correct to use a struct that contains interior mutability as a key, when its +implementation of `Hash` or `Ord` doesn't access any of the interior mutable types. +However, this lint is unable to recognize this, so it will often cause false positives in +theses cases. The `bytes` crate is a great example of this. + +#### False Negatives +For custom `struct`s/`enum`s, this lint is unable to check for interior mutability behind +indirection. For example, `struct BadKey<'a>(&'a Cell)` will be seen as immutable +and cause a false negative if its implementation of `Hash`/`Ord` accesses the `Cell`. + +This lint does check a few cases for indirection. Firstly, using some standard library +types (`Option`, `Result`, `Box`, `Rc`, `Arc`, `Vec`, `VecDeque`, `BTreeMap` and +`BTreeSet`) directly as keys (e.g. in `HashMap>, ()>`) **will** trigger the +lint, because the impls of `Hash`/`Ord` for these types directly call `Hash`/`Ord` on their +contained type. + +Secondly, the implementations of `Hash` and `Ord` for raw pointers (`*const T` or `*mut T`) +apply only to the **address** of the contained value. Therefore, interior mutability +behind raw pointers (e.g. in `HashSet<*mut Cell>`) can't impact the value of `Hash` +or `Ord`, and therefore will not trigger this link. For more info, see issue +[#6745](https://github.com/rust-lang/rust-clippy/issues/6745). + +### Example +``` +use std::cmp::{PartialEq, Eq}; +use std::collections::HashSet; +use std::hash::{Hash, Hasher}; +use std::sync::atomic::AtomicUsize; + +struct Bad(AtomicUsize); +impl PartialEq for Bad { + fn eq(&self, rhs: &Self) -> bool { + .. +; unimplemented!(); + } +} + +impl Eq for Bad {} + +impl Hash for Bad { + fn hash(&self, h: &mut H) { + .. +; unimplemented!(); + } +} + +fn main() { + let _: HashSet = HashSet::new(); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/mutex_atomic.txt b/src/tools/clippy/src/docs/mutex_atomic.txt new file mode 100644 index 0000000000000..062ac8b323b74 --- /dev/null +++ b/src/tools/clippy/src/docs/mutex_atomic.txt @@ -0,0 +1,22 @@ +### What it does +Checks for usages of `Mutex` where an atomic will do. + +### Why is this bad? +Using a mutex just to make access to a plain bool or +reference sequential is shooting flies with cannons. +`std::sync::atomic::AtomicBool` and `std::sync::atomic::AtomicPtr` are leaner and +faster. + +### Known problems +This lint cannot detect if the mutex is actually used +for waiting before a critical section. + +### Example +``` +let x = Mutex::new(&y); +``` + +Use instead: +``` +let x = AtomicBool::new(y); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/mutex_integer.txt b/src/tools/clippy/src/docs/mutex_integer.txt new file mode 100644 index 0000000000000..f9dbdfb904c9a --- /dev/null +++ b/src/tools/clippy/src/docs/mutex_integer.txt @@ -0,0 +1,22 @@ +### What it does +Checks for usages of `Mutex` where `X` is an integral +type. + +### Why is this bad? +Using a mutex just to make access to a plain integer +sequential is +shooting flies with cannons. `std::sync::atomic::AtomicUsize` is leaner and faster. + +### Known problems +This lint cannot detect if the mutex is actually used +for waiting before a critical section. + +### Example +``` +let x = Mutex::new(0usize); +``` + +Use instead: +``` +let x = AtomicUsize::new(0usize); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/naive_bytecount.txt b/src/tools/clippy/src/docs/naive_bytecount.txt new file mode 100644 index 0000000000000..24659dc79ae71 --- /dev/null +++ b/src/tools/clippy/src/docs/naive_bytecount.txt @@ -0,0 +1,22 @@ +### What it does +Checks for naive byte counts + +### Why is this bad? +The [`bytecount`](https://crates.io/crates/bytecount) +crate has methods to count your bytes faster, especially for large slices. + +### Known problems +If you have predominantly small slices, the +`bytecount::count(..)` method may actually be slower. However, if you can +ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be +faster in those cases. + +### Example +``` +let count = vec.iter().filter(|x| **x == 0u8).count(); +``` + +Use instead: +``` +let count = bytecount::count(&vec, 0u8); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_arbitrary_self_type.txt b/src/tools/clippy/src/docs/needless_arbitrary_self_type.txt new file mode 100644 index 0000000000000..8216a3a3fb6e5 --- /dev/null +++ b/src/tools/clippy/src/docs/needless_arbitrary_self_type.txt @@ -0,0 +1,44 @@ +### What it does +The lint checks for `self` in fn parameters that +specify the `Self`-type explicitly +### Why is this bad? +Increases the amount and decreases the readability of code + +### Example +``` +enum ValType { + I32, + I64, + F32, + F64, +} + +impl ValType { + pub fn bytes(self: Self) -> usize { + match self { + Self::I32 | Self::F32 => 4, + Self::I64 | Self::F64 => 8, + } + } +} +``` + +Could be rewritten as + +``` +enum ValType { + I32, + I64, + F32, + F64, +} + +impl ValType { + pub fn bytes(self) -> usize { + match self { + Self::I32 | Self::F32 => 4, + Self::I64 | Self::F64 => 8, + } + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_bitwise_bool.txt b/src/tools/clippy/src/docs/needless_bitwise_bool.txt new file mode 100644 index 0000000000000..fcd7b730aaae0 --- /dev/null +++ b/src/tools/clippy/src/docs/needless_bitwise_bool.txt @@ -0,0 +1,22 @@ +### What it does +Checks for uses of bitwise and/or operators between booleans, where performance may be improved by using +a lazy and. + +### Why is this bad? +The bitwise operators do not support short-circuiting, so it may hinder code performance. +Additionally, boolean logic "masked" as bitwise logic is not caught by lints like `unnecessary_fold` + +### Known problems +This lint evaluates only when the right side is determined to have no side effects. At this time, that +determination is quite conservative. + +### Example +``` +let (x,y) = (true, false); +if x & !y {} // where both x and y are booleans +``` +Use instead: +``` +let (x,y) = (true, false); +if x && !y {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_bool.txt b/src/tools/clippy/src/docs/needless_bool.txt new file mode 100644 index 0000000000000..b5c78871f14f6 --- /dev/null +++ b/src/tools/clippy/src/docs/needless_bool.txt @@ -0,0 +1,26 @@ +### What it does +Checks for expressions of the form `if c { true } else { +false }` (or vice versa) and suggests using the condition directly. + +### Why is this bad? +Redundant code. + +### Known problems +Maybe false positives: Sometimes, the two branches are +painstakingly documented (which we, of course, do not detect), so they *may* +have some value. Even then, the documentation can be rewritten to match the +shorter code. + +### Example +``` +if x { + false +} else { + true +} +``` + +Use instead: +``` +!x +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_borrow.txt b/src/tools/clippy/src/docs/needless_borrow.txt new file mode 100644 index 0000000000000..4debcf473723a --- /dev/null +++ b/src/tools/clippy/src/docs/needless_borrow.txt @@ -0,0 +1,21 @@ +### What it does +Checks for address of operations (`&`) that are going to +be dereferenced immediately by the compiler. + +### Why is this bad? +Suggests that the receiver of the expression borrows +the expression. + +### Example +``` +fn fun(_a: &i32) {} + +let x: &i32 = &&&&&&5; +fun(&x); +``` + +Use instead: +``` +let x: &i32 = &5; +fun(x); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_borrowed_reference.txt b/src/tools/clippy/src/docs/needless_borrowed_reference.txt new file mode 100644 index 0000000000000..55faa0cf57195 --- /dev/null +++ b/src/tools/clippy/src/docs/needless_borrowed_reference.txt @@ -0,0 +1,30 @@ +### What it does +Checks for bindings that destructure a reference and borrow the inner +value with `&ref`. + +### Why is this bad? +This pattern has no effect in almost all cases. + +### Known problems +In some cases, `&ref` is needed to avoid a lifetime mismatch error. +Example: +``` +fn foo(a: &Option, b: &Option) { + match (a, b) { + (None, &ref c) | (&ref c, None) => (), + (&Some(ref c), _) => (), + }; +} +``` + +### Example +``` +let mut v = Vec::::new(); +v.iter_mut().filter(|&ref a| a.is_empty()); +``` + +Use instead: +``` +let mut v = Vec::::new(); +v.iter_mut().filter(|a| a.is_empty()); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_collect.txt b/src/tools/clippy/src/docs/needless_collect.txt new file mode 100644 index 0000000000000..275c39afc9df1 --- /dev/null +++ b/src/tools/clippy/src/docs/needless_collect.txt @@ -0,0 +1,14 @@ +### What it does +Checks for functions collecting an iterator when collect +is not needed. + +### Why is this bad? +`collect` causes the allocation of a new data structure, +when this allocation may not be needed. + +### Example +``` +let len = iterator.clone().collect::>().len(); +// should be +let len = iterator.count(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_continue.txt b/src/tools/clippy/src/docs/needless_continue.txt new file mode 100644 index 0000000000000..2cee621c1af03 --- /dev/null +++ b/src/tools/clippy/src/docs/needless_continue.txt @@ -0,0 +1,61 @@ +### What it does +The lint checks for `if`-statements appearing in loops +that contain a `continue` statement in either their main blocks or their +`else`-blocks, when omitting the `else`-block possibly with some +rearrangement of code can make the code easier to understand. + +### Why is this bad? +Having explicit `else` blocks for `if` statements +containing `continue` in their THEN branch adds unnecessary branching and +nesting to the code. Having an else block containing just `continue` can +also be better written by grouping the statements following the whole `if` +statement within the THEN block and omitting the else block completely. + +### Example +``` +while condition() { + update_condition(); + if x { + // ... + } else { + continue; + } + println!("Hello, world"); +} +``` + +Could be rewritten as + +``` +while condition() { + update_condition(); + if x { + // ... + println!("Hello, world"); + } +} +``` + +As another example, the following code + +``` +loop { + if waiting() { + continue; + } else { + // Do something useful + } + # break; +} +``` +Could be rewritten as + +``` +loop { + if waiting() { + continue; + } + // Do something useful + # break; +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_doctest_main.txt b/src/tools/clippy/src/docs/needless_doctest_main.txt new file mode 100644 index 0000000000000..8f91a7baa7151 --- /dev/null +++ b/src/tools/clippy/src/docs/needless_doctest_main.txt @@ -0,0 +1,22 @@ +### What it does +Checks for `fn main() { .. }` in doctests + +### Why is this bad? +The test can be shorter (and likely more readable) +if the `fn main()` is left implicit. + +### Examples +``` +/// An example of a doctest with a `main()` function +/// +/// # Examples +/// +/// ``` +/// fn main() { +/// // this needs not be in an `fn` +/// } +/// ``` +fn needless_main() { + unimplemented!(); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_for_each.txt b/src/tools/clippy/src/docs/needless_for_each.txt new file mode 100644 index 0000000000000..9ae6dd360c8f7 --- /dev/null +++ b/src/tools/clippy/src/docs/needless_for_each.txt @@ -0,0 +1,24 @@ +### What it does +Checks for usage of `for_each` that would be more simply written as a +`for` loop. + +### Why is this bad? +`for_each` may be used after applying iterator transformers like +`filter` for better readability and performance. It may also be used to fit a simple +operation on one line. +But when none of these apply, a simple `for` loop is more idiomatic. + +### Example +``` +let v = vec![0, 1, 2]; +v.iter().for_each(|elem| { + println!("{}", elem); +}) +``` +Use instead: +``` +let v = vec![0, 1, 2]; +for elem in v.iter() { + println!("{}", elem); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_late_init.txt b/src/tools/clippy/src/docs/needless_late_init.txt new file mode 100644 index 0000000000000..9e7bbcea99825 --- /dev/null +++ b/src/tools/clippy/src/docs/needless_late_init.txt @@ -0,0 +1,42 @@ +### What it does +Checks for late initializations that can be replaced by a `let` statement +with an initializer. + +### Why is this bad? +Assigning in the `let` statement is less repetitive. + +### Example +``` +let a; +a = 1; + +let b; +match 3 { + 0 => b = "zero", + 1 => b = "one", + _ => b = "many", +} + +let c; +if true { + c = 1; +} else { + c = -1; +} +``` +Use instead: +``` +let a = 1; + +let b = match 3 { + 0 => "zero", + 1 => "one", + _ => "many", +}; + +let c = if true { + 1 +} else { + -1 +}; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_lifetimes.txt b/src/tools/clippy/src/docs/needless_lifetimes.txt new file mode 100644 index 0000000000000..b280caa66b583 --- /dev/null +++ b/src/tools/clippy/src/docs/needless_lifetimes.txt @@ -0,0 +1,29 @@ +### What it does +Checks for lifetime annotations which can be removed by +relying on lifetime elision. + +### Why is this bad? +The additional lifetimes make the code look more +complicated, while there is nothing out of the ordinary going on. Removing +them leads to more readable code. + +### Known problems +- We bail out if the function has a `where` clause where lifetimes +are mentioned due to potential false positives. +- Lifetime bounds such as `impl Foo + 'a` and `T: 'a` must be elided with the +placeholder notation `'_` because the fully elided notation leaves the type bound to `'static`. + +### Example +``` +// Unnecessary lifetime annotations +fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 { + x +} +``` + +Use instead: +``` +fn elided(x: &u8, y: u8) -> &u8 { + x +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_match.txt b/src/tools/clippy/src/docs/needless_match.txt new file mode 100644 index 0000000000000..92b40a5df6488 --- /dev/null +++ b/src/tools/clippy/src/docs/needless_match.txt @@ -0,0 +1,36 @@ +### What it does +Checks for unnecessary `match` or match-like `if let` returns for `Option` and `Result` +when function signatures are the same. + +### Why is this bad? +This `match` block does nothing and might not be what the coder intended. + +### Example +``` +fn foo() -> Result<(), i32> { + match result { + Ok(val) => Ok(val), + Err(err) => Err(err), + } +} + +fn bar() -> Option { + if let Some(val) = option { + Some(val) + } else { + None + } +} +``` + +Could be replaced as + +``` +fn foo() -> Result<(), i32> { + result +} + +fn bar() -> Option { + option +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_option_as_deref.txt b/src/tools/clippy/src/docs/needless_option_as_deref.txt new file mode 100644 index 0000000000000..226396c97ac49 --- /dev/null +++ b/src/tools/clippy/src/docs/needless_option_as_deref.txt @@ -0,0 +1,18 @@ +### What it does +Checks for no-op uses of `Option::{as_deref, as_deref_mut}`, +for example, `Option<&T>::as_deref()` returns the same type. + +### Why is this bad? +Redundant code and improving readability. + +### Example +``` +let a = Some(&1); +let b = a.as_deref(); // goes from Option<&i32> to Option<&i32> +``` + +Use instead: +``` +let a = Some(&1); +let b = a; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_option_take.txt b/src/tools/clippy/src/docs/needless_option_take.txt new file mode 100644 index 0000000000000..6bac65a13b5b8 --- /dev/null +++ b/src/tools/clippy/src/docs/needless_option_take.txt @@ -0,0 +1,17 @@ +### What it does +Checks for calling `take` function after `as_ref`. + +### Why is this bad? +Redundant code. `take` writes `None` to its argument. +In this case the modification is useless as it's a temporary that cannot be read from afterwards. + +### Example +``` +let x = Some(3); +x.as_ref().take(); +``` +Use instead: +``` +let x = Some(3); +x.as_ref(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_parens_on_range_literals.txt b/src/tools/clippy/src/docs/needless_parens_on_range_literals.txt new file mode 100644 index 0000000000000..85fab10cb5f65 --- /dev/null +++ b/src/tools/clippy/src/docs/needless_parens_on_range_literals.txt @@ -0,0 +1,23 @@ +### What it does +The lint checks for parenthesis on literals in range statements that are +superfluous. + +### Why is this bad? +Having superfluous parenthesis makes the code less readable +overhead when reading. + +### Example + +``` +for i in (0)..10 { + println!("{i}"); +} +``` + +Use instead: + +``` +for i in 0..10 { + println!("{i}"); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_pass_by_value.txt b/src/tools/clippy/src/docs/needless_pass_by_value.txt new file mode 100644 index 0000000000000..58c420b19f628 --- /dev/null +++ b/src/tools/clippy/src/docs/needless_pass_by_value.txt @@ -0,0 +1,27 @@ +### What it does +Checks for functions taking arguments by value, but not +consuming them in its +body. + +### Why is this bad? +Taking arguments by reference is more flexible and can +sometimes avoid +unnecessary allocations. + +### Known problems +* This lint suggests taking an argument by reference, +however sometimes it is better to let users decide the argument type +(by using `Borrow` trait, for example), depending on how the function is used. + +### Example +``` +fn foo(v: Vec) { + assert_eq!(v.len(), 42); +} +``` +should be +``` +fn foo(v: &[i32]) { + assert_eq!(v.len(), 42); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_question_mark.txt b/src/tools/clippy/src/docs/needless_question_mark.txt new file mode 100644 index 0000000000000..540739fd45fae --- /dev/null +++ b/src/tools/clippy/src/docs/needless_question_mark.txt @@ -0,0 +1,43 @@ +### What it does +Suggests alternatives for useless applications of `?` in terminating expressions + +### Why is this bad? +There's no reason to use `?` to short-circuit when execution of the body will end there anyway. + +### Example +``` +struct TO { + magic: Option, +} + +fn f(to: TO) -> Option { + Some(to.magic?) +} + +struct TR { + magic: Result, +} + +fn g(tr: Result) -> Result { + tr.and_then(|t| Ok(t.magic?)) +} + +``` +Use instead: +``` +struct TO { + magic: Option, +} + +fn f(to: TO) -> Option { + to.magic +} + +struct TR { + magic: Result, +} + +fn g(tr: Result) -> Result { + tr.and_then(|t| t.magic) +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_range_loop.txt b/src/tools/clippy/src/docs/needless_range_loop.txt new file mode 100644 index 0000000000000..583c09b284976 --- /dev/null +++ b/src/tools/clippy/src/docs/needless_range_loop.txt @@ -0,0 +1,23 @@ +### What it does +Checks for looping over the range of `0..len` of some +collection just to get the values by index. + +### Why is this bad? +Just iterating the collection itself makes the intent +more clear and is probably faster. + +### Example +``` +let vec = vec!['a', 'b', 'c']; +for i in 0..vec.len() { + println!("{}", vec[i]); +} +``` + +Use instead: +``` +let vec = vec!['a', 'b', 'c']; +for i in vec { + println!("{}", i); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_return.txt b/src/tools/clippy/src/docs/needless_return.txt new file mode 100644 index 0000000000000..48782cb0ca84d --- /dev/null +++ b/src/tools/clippy/src/docs/needless_return.txt @@ -0,0 +1,19 @@ +### What it does +Checks for return statements at the end of a block. + +### Why is this bad? +Removing the `return` and semicolon will make the code +more rusty. + +### Example +``` +fn foo(x: usize) -> usize { + return x; +} +``` +simplify to +``` +fn foo(x: usize) -> usize { + x +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_splitn.txt b/src/tools/clippy/src/docs/needless_splitn.txt new file mode 100644 index 0000000000000..b10a84fbc42d4 --- /dev/null +++ b/src/tools/clippy/src/docs/needless_splitn.txt @@ -0,0 +1,16 @@ +### What it does +Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same. +### Why is this bad? +The function `split` is simpler and there is no performance difference in these cases, considering +that both functions return a lazy iterator. +### Example +``` +let str = "key=value=add"; +let _ = str.splitn(3, '=').next().unwrap(); +``` + +Use instead: +``` +let str = "key=value=add"; +let _ = str.split('=').next().unwrap(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/needless_update.txt b/src/tools/clippy/src/docs/needless_update.txt new file mode 100644 index 0000000000000..82adabf6482c3 --- /dev/null +++ b/src/tools/clippy/src/docs/needless_update.txt @@ -0,0 +1,30 @@ +### What it does +Checks for needlessly including a base struct on update +when all fields are changed anyway. + +This lint is not applied to structs marked with +[non_exhaustive](https://doc.rust-lang.org/reference/attributes/type_system.html). + +### Why is this bad? +This will cost resources (because the base has to be +somewhere), and make the code less readable. + +### Example +``` +Point { + x: 1, + y: 1, + z: 1, + ..zero_point +}; +``` + +Use instead: +``` +// Missing field `z` +Point { + x: 1, + y: 1, + ..zero_point +}; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/neg_cmp_op_on_partial_ord.txt b/src/tools/clippy/src/docs/neg_cmp_op_on_partial_ord.txt new file mode 100644 index 0000000000000..fa55c6cfd74b3 --- /dev/null +++ b/src/tools/clippy/src/docs/neg_cmp_op_on_partial_ord.txt @@ -0,0 +1,26 @@ +### What it does +Checks for the usage of negated comparison operators on types which only implement +`PartialOrd` (e.g., `f64`). + +### Why is this bad? +These operators make it easy to forget that the underlying types actually allow not only three +potential Orderings (Less, Equal, Greater) but also a fourth one (Uncomparable). This is +especially easy to miss if the operator based comparison result is negated. + +### Example +``` +let a = 1.0; +let b = f64::NAN; + +let not_less_or_equal = !(a <= b); +``` + +Use instead: +``` +use std::cmp::Ordering; + +let _not_less_or_equal = match a.partial_cmp(&b) { + None | Some(Ordering::Greater) => true, + _ => false, +}; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/neg_multiply.txt b/src/tools/clippy/src/docs/neg_multiply.txt new file mode 100644 index 0000000000000..4e8b096eb9cc7 --- /dev/null +++ b/src/tools/clippy/src/docs/neg_multiply.txt @@ -0,0 +1,18 @@ +### What it does +Checks for multiplication by -1 as a form of negation. + +### Why is this bad? +It's more readable to just negate. + +### Known problems +This only catches integers (for now). + +### Example +``` +let a = x * -1; +``` + +Use instead: +``` +let a = -x; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/negative_feature_names.txt b/src/tools/clippy/src/docs/negative_feature_names.txt new file mode 100644 index 0000000000000..01ee9efb318be --- /dev/null +++ b/src/tools/clippy/src/docs/negative_feature_names.txt @@ -0,0 +1,22 @@ +### What it does +Checks for negative feature names with prefix `no-` or `not-` + +### Why is this bad? +Features are supposed to be additive, and negatively-named features violate it. + +### Example +``` +[features] +default = [] +no-abc = [] +not-def = [] + +``` +Use instead: +``` +[features] +default = ["abc", "def"] +abc = [] +def = [] + +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/never_loop.txt b/src/tools/clippy/src/docs/never_loop.txt new file mode 100644 index 0000000000000..737ccf415cb98 --- /dev/null +++ b/src/tools/clippy/src/docs/never_loop.txt @@ -0,0 +1,15 @@ +### What it does +Checks for loops that will always `break`, `return` or +`continue` an outer loop. + +### Why is this bad? +This loop never loops, all it does is obfuscating the +code. + +### Example +``` +loop { + ..; + break; +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/new_ret_no_self.txt b/src/tools/clippy/src/docs/new_ret_no_self.txt new file mode 100644 index 0000000000000..291bad24a643b --- /dev/null +++ b/src/tools/clippy/src/docs/new_ret_no_self.txt @@ -0,0 +1,47 @@ +### What it does +Checks for `new` not returning a type that contains `Self`. + +### Why is this bad? +As a convention, `new` methods are used to make a new +instance of a type. + +### Example +In an impl block: +``` +impl Foo { + fn new() -> NotAFoo { + } +} +``` + +``` +struct Bar(Foo); +impl Foo { + // Bad. The type name must contain `Self` + fn new() -> Bar { + } +} +``` + +``` +impl Foo { + // Good. Return type contains `Self` + fn new() -> Result { + } +} +``` + +Or in a trait definition: +``` +pub trait Trait { + // Bad. The type name must contain `Self` + fn new(); +} +``` + +``` +pub trait Trait { + // Good. Return type contains `Self` + fn new() -> Self; +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/new_without_default.txt b/src/tools/clippy/src/docs/new_without_default.txt new file mode 100644 index 0000000000000..662d39c8efdd2 --- /dev/null +++ b/src/tools/clippy/src/docs/new_without_default.txt @@ -0,0 +1,32 @@ +### What it does +Checks for public types with a `pub fn new() -> Self` method and no +implementation of +[`Default`](https://doc.rust-lang.org/std/default/trait.Default.html). + +### Why is this bad? +The user might expect to be able to use +[`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) as the +type can be constructed without arguments. + +### Example +``` +pub struct Foo(Bar); + +impl Foo { + pub fn new() -> Self { + Foo(Bar::new()) + } +} +``` + +To fix the lint, add a `Default` implementation that delegates to `new`: + +``` +pub struct Foo(Bar); + +impl Default for Foo { + fn default() -> Self { + Foo::new() + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/no_effect.txt b/src/tools/clippy/src/docs/no_effect.txt new file mode 100644 index 0000000000000..d4cc08fa8a7d8 --- /dev/null +++ b/src/tools/clippy/src/docs/no_effect.txt @@ -0,0 +1,12 @@ +### What it does +Checks for statements which have no effect. + +### Why is this bad? +Unlike dead code, these statements are actually +executed. However, as they have no effect, all they do is make the code less +readable. + +### Example +``` +0; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/no_effect_replace.txt b/src/tools/clippy/src/docs/no_effect_replace.txt new file mode 100644 index 0000000000000..646d45287ef50 --- /dev/null +++ b/src/tools/clippy/src/docs/no_effect_replace.txt @@ -0,0 +1,11 @@ +### What it does +Checks for `replace` statements which have no effect. + +### Why is this bad? +It's either a mistake or confusing. + +### Example +``` +"1234".replace("12", "12"); +"1234".replacen("12", "12", 1); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/no_effect_underscore_binding.txt b/src/tools/clippy/src/docs/no_effect_underscore_binding.txt new file mode 100644 index 0000000000000..972f60dd01e92 --- /dev/null +++ b/src/tools/clippy/src/docs/no_effect_underscore_binding.txt @@ -0,0 +1,16 @@ +### What it does +Checks for binding to underscore prefixed variable without side-effects. + +### Why is this bad? +Unlike dead code, these bindings are actually +executed. However, as they have no effect and shouldn't be used further on, all they +do is make the code less readable. + +### Known problems +Further usage of this variable is not checked, which can lead to false positives if it is +used later in the code. + +### Example +``` +let _i_serve_no_purpose = 1; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/non_ascii_literal.txt b/src/tools/clippy/src/docs/non_ascii_literal.txt new file mode 100644 index 0000000000000..164902b4726e1 --- /dev/null +++ b/src/tools/clippy/src/docs/non_ascii_literal.txt @@ -0,0 +1,19 @@ +### What it does +Checks for non-ASCII characters in string and char literals. + +### Why is this bad? +Yeah, we know, the 90's called and wanted their charset +back. Even so, there still are editors and other programs out there that +don't work well with Unicode. So if the code is meant to be used +internationally, on multiple operating systems, or has other portability +requirements, activating this lint could be useful. + +### Example +``` +let x = String::from("€"); +``` + +Use instead: +``` +let x = String::from("\u{20ac}"); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/non_octal_unix_permissions.txt b/src/tools/clippy/src/docs/non_octal_unix_permissions.txt new file mode 100644 index 0000000000000..4a468e94db164 --- /dev/null +++ b/src/tools/clippy/src/docs/non_octal_unix_permissions.txt @@ -0,0 +1,23 @@ +### What it does +Checks for non-octal values used to set Unix file permissions. + +### Why is this bad? +They will be converted into octal, creating potentially +unintended file permissions. + +### Example +``` +use std::fs::OpenOptions; +use std::os::unix::fs::OpenOptionsExt; + +let mut options = OpenOptions::new(); +options.mode(644); +``` +Use instead: +``` +use std::fs::OpenOptions; +use std::os::unix::fs::OpenOptionsExt; + +let mut options = OpenOptions::new(); +options.mode(0o644); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/non_send_fields_in_send_ty.txt b/src/tools/clippy/src/docs/non_send_fields_in_send_ty.txt new file mode 100644 index 0000000000000..11e6f6e162cf0 --- /dev/null +++ b/src/tools/clippy/src/docs/non_send_fields_in_send_ty.txt @@ -0,0 +1,36 @@ +### What it does +This lint warns about a `Send` implementation for a type that +contains fields that are not safe to be sent across threads. +It tries to detect fields that can cause a soundness issue +when sent to another thread (e.g., `Rc`) while allowing `!Send` fields +that are expected to exist in a `Send` type, such as raw pointers. + +### Why is this bad? +Sending the struct to another thread effectively sends all of its fields, +and the fields that do not implement `Send` can lead to soundness bugs +such as data races when accessed in a thread +that is different from the thread that created it. + +See: +* [*The Rustonomicon* about *Send and Sync*](https://doc.rust-lang.org/nomicon/send-and-sync.html) +* [The documentation of `Send`](https://doc.rust-lang.org/std/marker/trait.Send.html) + +### Known Problems +This lint relies on heuristics to distinguish types that are actually +unsafe to be sent across threads and `!Send` types that are expected to +exist in `Send` type. Its rule can filter out basic cases such as +`Vec<*const T>`, but it's not perfect. Feel free to create an issue if +you have a suggestion on how this heuristic can be improved. + +### Example +``` +struct ExampleStruct { + rc_is_not_send: Rc, + unbounded_generic_field: T, +} + +// This impl is unsound because it allows sending `!Send` types through `ExampleStruct` +unsafe impl Send for ExampleStruct {} +``` +Use thread-safe types like [`std::sync::Arc`](https://doc.rust-lang.org/std/sync/struct.Arc.html) +or specify correct bounds on generic type parameters (`T: Send`). \ No newline at end of file diff --git a/src/tools/clippy/src/docs/nonminimal_bool.txt b/src/tools/clippy/src/docs/nonminimal_bool.txt new file mode 100644 index 0000000000000..488980ddf0239 --- /dev/null +++ b/src/tools/clippy/src/docs/nonminimal_bool.txt @@ -0,0 +1,23 @@ +### What it does +Checks for boolean expressions that can be written more +concisely. + +### Why is this bad? +Readability of boolean expressions suffers from +unnecessary duplication. + +### Known problems +Ignores short circuiting behavior of `||` and +`&&`. Ignores `|`, `&` and `^`. + +### Example +``` +if a && true {} +if !(a == b) {} +``` + +Use instead: +``` +if a {} +if a != b {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/nonsensical_open_options.txt b/src/tools/clippy/src/docs/nonsensical_open_options.txt new file mode 100644 index 0000000000000..7a95443b51a50 --- /dev/null +++ b/src/tools/clippy/src/docs/nonsensical_open_options.txt @@ -0,0 +1,14 @@ +### What it does +Checks for duplicate open options as well as combinations +that make no sense. + +### Why is this bad? +In the best case, the code will be harder to read than +necessary. I don't know the worst case. + +### Example +``` +use std::fs::OpenOptions; + +OpenOptions::new().read(true).truncate(true); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/nonstandard_macro_braces.txt b/src/tools/clippy/src/docs/nonstandard_macro_braces.txt new file mode 100644 index 0000000000000..7e8d0d2d33bf1 --- /dev/null +++ b/src/tools/clippy/src/docs/nonstandard_macro_braces.txt @@ -0,0 +1,15 @@ +### What it does +Checks that common macros are used with consistent bracing. + +### Why is this bad? +This is mostly a consistency lint although using () or [] +doesn't give you a semicolon in item position, which can be unexpected. + +### Example +``` +vec!{1, 2, 3}; +``` +Use instead: +``` +vec![1, 2, 3]; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/not_unsafe_ptr_arg_deref.txt b/src/tools/clippy/src/docs/not_unsafe_ptr_arg_deref.txt new file mode 100644 index 0000000000000..31355fbb7b666 --- /dev/null +++ b/src/tools/clippy/src/docs/not_unsafe_ptr_arg_deref.txt @@ -0,0 +1,30 @@ +### What it does +Checks for public functions that dereference raw pointer +arguments but are not marked `unsafe`. + +### Why is this bad? +The function should probably be marked `unsafe`, since +for an arbitrary raw pointer, there is no way of telling for sure if it is +valid. + +### Known problems +* It does not check functions recursively so if the pointer is passed to a +private non-`unsafe` function which does the dereferencing, the lint won't +trigger. +* It only checks for arguments whose type are raw pointers, not raw pointers +got from an argument in some other way (`fn foo(bar: &[*const u8])` or +`some_argument.get_raw_ptr()`). + +### Example +``` +pub fn foo(x: *const u8) { + println!("{}", unsafe { *x }); +} +``` + +Use instead: +``` +pub unsafe fn foo(x: *const u8) { + println!("{}", unsafe { *x }); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/obfuscated_if_else.txt b/src/tools/clippy/src/docs/obfuscated_if_else.txt new file mode 100644 index 0000000000000..638f63b0db5e4 --- /dev/null +++ b/src/tools/clippy/src/docs/obfuscated_if_else.txt @@ -0,0 +1,21 @@ +### What it does +Checks for usages of `.then_some(..).unwrap_or(..)` + +### Why is this bad? +This can be written more clearly with `if .. else ..` + +### Limitations +This lint currently only looks for usages of +`.then_some(..).unwrap_or(..)`, but will be expanded +to account for similar patterns. + +### Example +``` +let x = true; +x.then_some("a").unwrap_or("b"); +``` +Use instead: +``` +let x = true; +if x { "a" } else { "b" }; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/octal_escapes.txt b/src/tools/clippy/src/docs/octal_escapes.txt new file mode 100644 index 0000000000000..eee820587158c --- /dev/null +++ b/src/tools/clippy/src/docs/octal_escapes.txt @@ -0,0 +1,33 @@ +### What it does +Checks for `\0` escapes in string and byte literals that look like octal +character escapes in C. + +### Why is this bad? + +C and other languages support octal character escapes in strings, where +a backslash is followed by up to three octal digits. For example, `\033` +stands for the ASCII character 27 (ESC). Rust does not support this +notation, but has the escape code `\0` which stands for a null +byte/character, and any following digits do not form part of the escape +sequence. Therefore, `\033` is not a compiler error but the result may +be surprising. + +### Known problems +The actual meaning can be the intended one. `\x00` can be used in these +cases to be unambiguous. + +The lint does not trigger for format strings in `print!()`, `write!()` +and friends since the string is already preprocessed when Clippy lints +can see it. + +### Example +``` +let one = "\033[1m Bold? \033[0m"; // \033 intended as escape +let two = "\033\0"; // \033 intended as null-3-3 +``` + +Use instead: +``` +let one = "\x1b[1mWill this be bold?\x1b[0m"; +let two = "\x0033\x00"; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/ok_expect.txt b/src/tools/clippy/src/docs/ok_expect.txt new file mode 100644 index 0000000000000..fd5205d49dc0e --- /dev/null +++ b/src/tools/clippy/src/docs/ok_expect.txt @@ -0,0 +1,19 @@ +### What it does +Checks for usage of `ok().expect(..)`. + +### Why is this bad? +Because you usually call `expect()` on the `Result` +directly to get a better error message. + +### Known problems +The error type needs to implement `Debug` + +### Example +``` +x.ok().expect("why did I do this again?"); +``` + +Use instead: +``` +x.expect("why did I do this again?"); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/only_used_in_recursion.txt b/src/tools/clippy/src/docs/only_used_in_recursion.txt new file mode 100644 index 0000000000000..f19f47ff9eb50 --- /dev/null +++ b/src/tools/clippy/src/docs/only_used_in_recursion.txt @@ -0,0 +1,58 @@ +### What it does +Checks for arguments that are only used in recursion with no side-effects. + +### Why is this bad? +It could contain a useless calculation and can make function simpler. + +The arguments can be involved in calculations and assignments but as long as +the calculations have no side-effects (function calls or mutating dereference) +and the assigned variables are also only in recursion, it is useless. + +### Known problems +Too many code paths in the linting code are currently untested and prone to produce false +positives or are prone to have performance implications. + +In some cases, this would not catch all useless arguments. + +``` +fn foo(a: usize, b: usize) -> usize { + let f = |x| x + 1; + + if a == 0 { + 1 + } else { + foo(a - 1, f(b)) + } +} +``` + +For example, the argument `b` is only used in recursion, but the lint would not catch it. + +List of some examples that can not be caught: +- binary operation of non-primitive types +- closure usage +- some `break` relative operations +- struct pattern binding + +Also, when you recurse the function name with path segments, it is not possible to detect. + +### Example +``` +fn f(a: usize, b: usize) -> usize { + if a == 0 { + 1 + } else { + f(a - 1, b + 1) + } +} +``` +Use instead: +``` +fn f(a: usize) -> usize { + if a == 0 { + 1 + } else { + f(a - 1) + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/op_ref.txt b/src/tools/clippy/src/docs/op_ref.txt new file mode 100644 index 0000000000000..7a7ed1bc9badc --- /dev/null +++ b/src/tools/clippy/src/docs/op_ref.txt @@ -0,0 +1,17 @@ +### What it does +Checks for arguments to `==` which have their address +taken to satisfy a bound +and suggests to dereference the other argument instead + +### Why is this bad? +It is more idiomatic to dereference the other argument. + +### Example +``` +&x == y +``` + +Use instead: +``` +x == *y +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/option_as_ref_deref.txt b/src/tools/clippy/src/docs/option_as_ref_deref.txt new file mode 100644 index 0000000000000..ad7411d3d4bd9 --- /dev/null +++ b/src/tools/clippy/src/docs/option_as_ref_deref.txt @@ -0,0 +1,15 @@ +### What it does +Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str). + +### Why is this bad? +Readability, this can be written more concisely as +`_.as_deref()`. + +### Example +``` +opt.as_ref().map(String::as_str) +``` +Can be written as +``` +opt.as_deref() +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/option_env_unwrap.txt b/src/tools/clippy/src/docs/option_env_unwrap.txt new file mode 100644 index 0000000000000..c952cba8e2615 --- /dev/null +++ b/src/tools/clippy/src/docs/option_env_unwrap.txt @@ -0,0 +1,19 @@ +### What it does +Checks for usage of `option_env!(...).unwrap()` and +suggests usage of the `env!` macro. + +### Why is this bad? +Unwrapping the result of `option_env!` will panic +at run-time if the environment variable doesn't exist, whereas `env!` +catches it at compile-time. + +### Example +``` +let _ = option_env!("HOME").unwrap(); +``` + +Is better expressed as: + +``` +let _ = env!("HOME"); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/option_filter_map.txt b/src/tools/clippy/src/docs/option_filter_map.txt new file mode 100644 index 0000000000000..25f7bde7b4d04 --- /dev/null +++ b/src/tools/clippy/src/docs/option_filter_map.txt @@ -0,0 +1,15 @@ +### What it does +Checks for indirect collection of populated `Option` + +### Why is this bad? +`Option` is like a collection of 0-1 things, so `flatten` +automatically does this without suspicious-looking `unwrap` calls. + +### Example +``` +let _ = std::iter::empty::>().filter(Option::is_some).map(Option::unwrap); +``` +Use instead: +``` +let _ = std::iter::empty::>().flatten(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/option_if_let_else.txt b/src/tools/clippy/src/docs/option_if_let_else.txt new file mode 100644 index 0000000000000..43652db513b4c --- /dev/null +++ b/src/tools/clippy/src/docs/option_if_let_else.txt @@ -0,0 +1,46 @@ +### What it does +Lints usage of `if let Some(v) = ... { y } else { x }` and +`match .. { Some(v) => y, None/_ => x }` which are more +idiomatically done with `Option::map_or` (if the else bit is a pure +expression) or `Option::map_or_else` (if the else bit is an impure +expression). + +### Why is this bad? +Using the dedicated functions of the `Option` type is clearer and +more concise than an `if let` expression. + +### Known problems +This lint uses a deliberately conservative metric for checking +if the inside of either body contains breaks or continues which will +cause it to not suggest a fix if either block contains a loop with +continues or breaks contained within the loop. + +### Example +``` +let _ = if let Some(foo) = optional { + foo +} else { + 5 +}; +let _ = match optional { + Some(val) => val + 1, + None => 5 +}; +let _ = if let Some(foo) = optional { + foo +} else { + let y = do_complicated_function(); + y*y +}; +``` + +should be + +``` +let _ = optional.map_or(5, |foo| foo); +let _ = optional.map_or(5, |val| val + 1); +let _ = optional.map_or_else(||{ + let y = do_complicated_function(); + y*y +}, |foo| foo); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/option_map_or_none.txt b/src/tools/clippy/src/docs/option_map_or_none.txt new file mode 100644 index 0000000000000..c86c65215f01c --- /dev/null +++ b/src/tools/clippy/src/docs/option_map_or_none.txt @@ -0,0 +1,19 @@ +### What it does +Checks for usage of `_.map_or(None, _)`. + +### Why is this bad? +Readability, this can be written more concisely as +`_.and_then(_)`. + +### Known problems +The order of the arguments is not in execution order. + +### Example +``` +opt.map_or(None, |a| Some(a + 1)); +``` + +Use instead: +``` +opt.and_then(|a| Some(a + 1)); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/option_map_unit_fn.txt b/src/tools/clippy/src/docs/option_map_unit_fn.txt new file mode 100644 index 0000000000000..fc4b528f0923e --- /dev/null +++ b/src/tools/clippy/src/docs/option_map_unit_fn.txt @@ -0,0 +1,27 @@ +### What it does +Checks for usage of `option.map(f)` where f is a function +or closure that returns the unit type `()`. + +### Why is this bad? +Readability, this can be written more clearly with +an if let statement + +### Example +``` +let x: Option = do_stuff(); +x.map(log_err_msg); +x.map(|msg| log_err_msg(format_msg(msg))); +``` + +The correct use would be: + +``` +let x: Option = do_stuff(); +if let Some(msg) = x { + log_err_msg(msg); +} + +if let Some(msg) = x { + log_err_msg(format_msg(msg)); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/option_option.txt b/src/tools/clippy/src/docs/option_option.txt new file mode 100644 index 0000000000000..b4324bd83990a --- /dev/null +++ b/src/tools/clippy/src/docs/option_option.txt @@ -0,0 +1,32 @@ +### What it does +Checks for use of `Option>` in function signatures and type +definitions + +### Why is this bad? +`Option<_>` represents an optional value. `Option>` +represents an optional optional value which is logically the same thing as an optional +value but has an unneeded extra level of wrapping. + +If you have a case where `Some(Some(_))`, `Some(None)` and `None` are distinct cases, +consider a custom `enum` instead, with clear names for each case. + +### Example +``` +fn get_data() -> Option> { + None +} +``` + +Better: + +``` +pub enum Contents { + Data(Vec), // Was Some(Some(Vec)) + NotYetFetched, // Was Some(None) + None, // Was None +} + +fn get_data() -> Contents { + Contents::None +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/or_fun_call.txt b/src/tools/clippy/src/docs/or_fun_call.txt new file mode 100644 index 0000000000000..6ce77cc268c51 --- /dev/null +++ b/src/tools/clippy/src/docs/or_fun_call.txt @@ -0,0 +1,27 @@ +### What it does +Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`, +`.or_insert(foo(..))` etc., and suggests to use `.or_else(|| foo(..))`, +`.unwrap_or_else(|| foo(..))`, `.unwrap_or_default()` or `.or_default()` +etc. instead. + +### Why is this bad? +The function will always be called and potentially +allocate an object acting as the default. + +### Known problems +If the function has side-effects, not calling it will +change the semantic of the program, but you shouldn't rely on that anyway. + +### Example +``` +foo.unwrap_or(String::new()); +``` + +Use instead: +``` +foo.unwrap_or_else(String::new); + +// or + +foo.unwrap_or_default(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/or_then_unwrap.txt b/src/tools/clippy/src/docs/or_then_unwrap.txt new file mode 100644 index 0000000000000..64ac53749e8ad --- /dev/null +++ b/src/tools/clippy/src/docs/or_then_unwrap.txt @@ -0,0 +1,22 @@ +### What it does +Checks for `.or(…).unwrap()` calls to Options and Results. + +### Why is this bad? +You should use `.unwrap_or(…)` instead for clarity. + +### Example +``` +// Result +let value = result.or::(Ok(fallback)).unwrap(); + +// Option +let value = option.or(Some(fallback)).unwrap(); +``` +Use instead: +``` +// Result +let value = result.unwrap_or(fallback); + +// Option +let value = option.unwrap_or(fallback); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/out_of_bounds_indexing.txt b/src/tools/clippy/src/docs/out_of_bounds_indexing.txt new file mode 100644 index 0000000000000..5802eea29966f --- /dev/null +++ b/src/tools/clippy/src/docs/out_of_bounds_indexing.txt @@ -0,0 +1,22 @@ +### What it does +Checks for out of bounds array indexing with a constant +index. + +### Why is this bad? +This will always panic at runtime. + +### Example +``` +let x = [1, 2, 3, 4]; + +x[9]; +&x[2..9]; +``` + +Use instead: +``` +// Index within bounds + +x[0]; +x[3]; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/overflow_check_conditional.txt b/src/tools/clippy/src/docs/overflow_check_conditional.txt new file mode 100644 index 0000000000000..a09cc18a0bcc5 --- /dev/null +++ b/src/tools/clippy/src/docs/overflow_check_conditional.txt @@ -0,0 +1,11 @@ +### What it does +Detects classic underflow/overflow checks. + +### Why is this bad? +Most classic C underflow/overflow checks will fail in +Rust. Users can use functions like `overflowing_*` and `wrapping_*` instead. + +### Example +``` +a + b < a; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/overly_complex_bool_expr.txt b/src/tools/clippy/src/docs/overly_complex_bool_expr.txt new file mode 100644 index 0000000000000..65ca18392e756 --- /dev/null +++ b/src/tools/clippy/src/docs/overly_complex_bool_expr.txt @@ -0,0 +1,20 @@ +### What it does +Checks for boolean expressions that contain terminals that +can be eliminated. + +### Why is this bad? +This is most likely a logic bug. + +### Known problems +Ignores short circuiting behavior. + +### Example +``` +// The `b` is unnecessary, the expression is equivalent to `if a`. +if a && b || a { ... } +``` + +Use instead: +``` +if a {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/panic.txt b/src/tools/clippy/src/docs/panic.txt new file mode 100644 index 0000000000000..f9bdc6e87ccf9 --- /dev/null +++ b/src/tools/clippy/src/docs/panic.txt @@ -0,0 +1,10 @@ +### What it does +Checks for usage of `panic!`. + +### Why is this bad? +`panic!` will stop the execution of the executable + +### Example +``` +panic!("even with a good reason"); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/panic_in_result_fn.txt b/src/tools/clippy/src/docs/panic_in_result_fn.txt new file mode 100644 index 0000000000000..51c2f8ae5a30e --- /dev/null +++ b/src/tools/clippy/src/docs/panic_in_result_fn.txt @@ -0,0 +1,22 @@ +### What it does +Checks for usage of `panic!`, `unimplemented!`, `todo!`, `unreachable!` or assertions in a function of type result. + +### Why is this bad? +For some codebases, it is desirable for functions of type result to return an error instead of crashing. Hence panicking macros should be avoided. + +### Known problems +Functions called from a function returning a `Result` may invoke a panicking macro. This is not checked. + +### Example +``` +fn result_with_panic() -> Result +{ + panic!("error"); +} +``` +Use instead: +``` +fn result_without_panic() -> Result { + Err(String::from("error")) +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/panicking_unwrap.txt b/src/tools/clippy/src/docs/panicking_unwrap.txt new file mode 100644 index 0000000000000..1fbc245c8ec38 --- /dev/null +++ b/src/tools/clippy/src/docs/panicking_unwrap.txt @@ -0,0 +1,18 @@ +### What it does +Checks for calls of `unwrap[_err]()` that will always fail. + +### Why is this bad? +If panicking is desired, an explicit `panic!()` should be used. + +### Known problems +This lint only checks `if` conditions not assignments. +So something like `let x: Option<()> = None; x.unwrap();` will not be recognized. + +### Example +``` +if option.is_none() { + do_something_with(option.unwrap()) +} +``` + +This code will always panic. The if condition should probably be inverted. \ No newline at end of file diff --git a/src/tools/clippy/src/docs/partialeq_ne_impl.txt b/src/tools/clippy/src/docs/partialeq_ne_impl.txt new file mode 100644 index 0000000000000..78f55188bab81 --- /dev/null +++ b/src/tools/clippy/src/docs/partialeq_ne_impl.txt @@ -0,0 +1,18 @@ +### What it does +Checks for manual re-implementations of `PartialEq::ne`. + +### Why is this bad? +`PartialEq::ne` is required to always return the +negated result of `PartialEq::eq`, which is exactly what the default +implementation does. Therefore, there should never be any need to +re-implement it. + +### Example +``` +struct Foo; + +impl PartialEq for Foo { + fn eq(&self, other: &Foo) -> bool { true } + fn ne(&self, other: &Foo) -> bool { !(self == other) } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/partialeq_to_none.txt b/src/tools/clippy/src/docs/partialeq_to_none.txt new file mode 100644 index 0000000000000..5cc07bf88435c --- /dev/null +++ b/src/tools/clippy/src/docs/partialeq_to_none.txt @@ -0,0 +1,24 @@ +### What it does + +Checks for binary comparisons to a literal `Option::None`. + +### Why is this bad? + +A programmer checking if some `foo` is `None` via a comparison `foo == None` +is usually inspired from other programming languages (e.g. `foo is None` +in Python). +Checking if a value of type `Option` is (not) equal to `None` in that +way relies on `T: PartialEq` to do the comparison, which is unneeded. + +### Example +``` +fn foo(f: Option) -> &'static str { + if f != None { "yay" } else { "nay" } +} +``` +Use instead: +``` +fn foo(f: Option) -> &'static str { + if f.is_some() { "yay" } else { "nay" } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/path_buf_push_overwrite.txt b/src/tools/clippy/src/docs/path_buf_push_overwrite.txt new file mode 100644 index 0000000000000..34f8901da2396 --- /dev/null +++ b/src/tools/clippy/src/docs/path_buf_push_overwrite.txt @@ -0,0 +1,25 @@ +### What it does +* Checks for [push](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.push) +calls on `PathBuf` that can cause overwrites. + +### Why is this bad? +Calling `push` with a root path at the start can overwrite the +previous defined path. + +### Example +``` +use std::path::PathBuf; + +let mut x = PathBuf::from("/foo"); +x.push("/bar"); +assert_eq!(x, PathBuf::from("/bar")); +``` +Could be written: + +``` +use std::path::PathBuf; + +let mut x = PathBuf::from("/foo"); +x.push("bar"); +assert_eq!(x, PathBuf::from("/foo/bar")); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/pattern_type_mismatch.txt b/src/tools/clippy/src/docs/pattern_type_mismatch.txt new file mode 100644 index 0000000000000..64da881d592a8 --- /dev/null +++ b/src/tools/clippy/src/docs/pattern_type_mismatch.txt @@ -0,0 +1,64 @@ +### What it does +Checks for patterns that aren't exact representations of the types +they are applied to. + +To satisfy this lint, you will have to adjust either the expression that is matched +against or the pattern itself, as well as the bindings that are introduced by the +adjusted patterns. For matching you will have to either dereference the expression +with the `*` operator, or amend the patterns to explicitly match against `&` +or `&mut ` depending on the reference mutability. For the bindings you need +to use the inverse. You can leave them as plain bindings if you wish for the value +to be copied, but you must use `ref mut ` or `ref ` to construct +a reference into the matched structure. + +If you are looking for a way to learn about ownership semantics in more detail, it +is recommended to look at IDE options available to you to highlight types, lifetimes +and reference semantics in your code. The available tooling would expose these things +in a general way even outside of the various pattern matching mechanics. Of course +this lint can still be used to highlight areas of interest and ensure a good understanding +of ownership semantics. + +### Why is this bad? +It isn't bad in general. But in some contexts it can be desirable +because it increases ownership hints in the code, and will guard against some changes +in ownership. + +### Example +This example shows the basic adjustments necessary to satisfy the lint. Note how +the matched expression is explicitly dereferenced with `*` and the `inner` variable +is bound to a shared borrow via `ref inner`. + +``` +// Bad +let value = &Some(Box::new(23)); +match value { + Some(inner) => println!("{}", inner), + None => println!("none"), +} + +// Good +let value = &Some(Box::new(23)); +match *value { + Some(ref inner) => println!("{}", inner), + None => println!("none"), +} +``` + +The following example demonstrates one of the advantages of the more verbose style. +Note how the second version uses `ref mut a` to explicitly declare `a` a shared mutable +borrow, while `b` is simply taken by value. This ensures that the loop body cannot +accidentally modify the wrong part of the structure. + +``` +// Bad +let mut values = vec![(2, 3), (3, 4)]; +for (a, b) in &mut values { + *a += *b; +} + +// Good +let mut values = vec![(2, 3), (3, 4)]; +for &mut (ref mut a, b) in &mut values { + *a += b; +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/positional_named_format_parameters.txt b/src/tools/clippy/src/docs/positional_named_format_parameters.txt new file mode 100644 index 0000000000000..e391d2406677d --- /dev/null +++ b/src/tools/clippy/src/docs/positional_named_format_parameters.txt @@ -0,0 +1,15 @@ +### What it does +This lint warns when a named parameter in a format string is used as a positional one. + +### Why is this bad? +It may be confused for an assignment and obfuscates which parameter is being used. + +### Example +``` +println!("{}", x = 10); +``` + +Use instead: +``` +println!("{x}", x = 10); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/possible_missing_comma.txt b/src/tools/clippy/src/docs/possible_missing_comma.txt new file mode 100644 index 0000000000000..5d92f4cae91e0 --- /dev/null +++ b/src/tools/clippy/src/docs/possible_missing_comma.txt @@ -0,0 +1,14 @@ +### What it does +Checks for possible missing comma in an array. It lints if +an array element is a binary operator expression and it lies on two lines. + +### Why is this bad? +This could lead to unexpected results. + +### Example +``` +let a = &[ + -1, -2, -3 // <= no comma here + -4, -5, -6 +]; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/precedence.txt b/src/tools/clippy/src/docs/precedence.txt new file mode 100644 index 0000000000000..fda0b831f335f --- /dev/null +++ b/src/tools/clippy/src/docs/precedence.txt @@ -0,0 +1,17 @@ +### What it does +Checks for operations where precedence may be unclear +and suggests to add parentheses. Currently it catches the following: +* mixed usage of arithmetic and bit shifting/combining operators without +parentheses +* a "negative" numeric literal (which is really a unary `-` followed by a +numeric literal) + followed by a method call + +### Why is this bad? +Not everyone knows the precedence of those operators by +heart, so expressions like these may trip others trying to reason about the +code. + +### Example +* `1 << 2 + 3` equals 32, while `(1 << 2) + 3` equals 7 +* `-1i32.abs()` equals -1, while `(-1i32).abs()` equals 1 \ No newline at end of file diff --git a/src/tools/clippy/src/docs/print_in_format_impl.txt b/src/tools/clippy/src/docs/print_in_format_impl.txt new file mode 100644 index 0000000000000..140d23d6faab4 --- /dev/null +++ b/src/tools/clippy/src/docs/print_in_format_impl.txt @@ -0,0 +1,34 @@ +### What it does +Checks for use of `println`, `print`, `eprintln` or `eprint` in an +implementation of a formatting trait. + +### Why is this bad? +Using a print macro is likely unintentional since formatting traits +should write to the `Formatter`, not stdout/stderr. + +### Example +``` +use std::fmt::{Display, Error, Formatter}; + +struct S; +impl Display for S { + fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { + println!("S"); + + Ok(()) + } +} +``` +Use instead: +``` +use std::fmt::{Display, Error, Formatter}; + +struct S; +impl Display for S { + fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { + writeln!(f, "S"); + + Ok(()) + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/print_literal.txt b/src/tools/clippy/src/docs/print_literal.txt new file mode 100644 index 0000000000000..160073414f9af --- /dev/null +++ b/src/tools/clippy/src/docs/print_literal.txt @@ -0,0 +1,20 @@ +### What it does +This lint warns about the use of literals as `print!`/`println!` args. + +### Why is this bad? +Using literals as `println!` args is inefficient +(c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary +(i.e., just put the literal in the format string) + +### Known problems +Will also warn with macro calls as arguments that expand to literals +-- e.g., `println!("{}", env!("FOO"))`. + +### Example +``` +println!("{}", "foo"); +``` +use the literal without formatting: +``` +println!("foo"); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/print_stderr.txt b/src/tools/clippy/src/docs/print_stderr.txt new file mode 100644 index 0000000000000..fc14511cd6a65 --- /dev/null +++ b/src/tools/clippy/src/docs/print_stderr.txt @@ -0,0 +1,21 @@ +### What it does +Checks for printing on *stderr*. The purpose of this lint +is to catch debugging remnants. + +### Why is this bad? +People often print on *stderr* while debugging an +application and might forget to remove those prints afterward. + +### Known problems +* Only catches `eprint!` and `eprintln!` calls. +* The lint level is unaffected by crate attributes. The level can still + be set for functions, modules and other items. To change the level for + the entire crate, please use command line flags. More information and a + configuration example can be found in [clippy#6610]. + +[clippy#6610]: https://github.com/rust-lang/rust-clippy/issues/6610#issuecomment-977120558 + +### Example +``` +eprintln!("Hello world!"); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/print_stdout.txt b/src/tools/clippy/src/docs/print_stdout.txt new file mode 100644 index 0000000000000..6c9a4b98e1e66 --- /dev/null +++ b/src/tools/clippy/src/docs/print_stdout.txt @@ -0,0 +1,21 @@ +### What it does +Checks for printing on *stdout*. The purpose of this lint +is to catch debugging remnants. + +### Why is this bad? +People often print on *stdout* while debugging an +application and might forget to remove those prints afterward. + +### Known problems +* Only catches `print!` and `println!` calls. +* The lint level is unaffected by crate attributes. The level can still + be set for functions, modules and other items. To change the level for + the entire crate, please use command line flags. More information and a + configuration example can be found in [clippy#6610]. + +[clippy#6610]: https://github.com/rust-lang/rust-clippy/issues/6610#issuecomment-977120558 + +### Example +``` +println!("Hello world!"); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/print_with_newline.txt b/src/tools/clippy/src/docs/print_with_newline.txt new file mode 100644 index 0000000000000..640323e822dbf --- /dev/null +++ b/src/tools/clippy/src/docs/print_with_newline.txt @@ -0,0 +1,16 @@ +### What it does +This lint warns when you use `print!()` with a format +string that ends in a newline. + +### Why is this bad? +You should use `println!()` instead, which appends the +newline. + +### Example +``` +print!("Hello {}!\n", name); +``` +use println!() instead +``` +println!("Hello {}!", name); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/println_empty_string.txt b/src/tools/clippy/src/docs/println_empty_string.txt new file mode 100644 index 0000000000000..b980413022cab --- /dev/null +++ b/src/tools/clippy/src/docs/println_empty_string.txt @@ -0,0 +1,16 @@ +### What it does +This lint warns when you use `println!("")` to +print a newline. + +### Why is this bad? +You should use `println!()`, which is simpler. + +### Example +``` +println!(""); +``` + +Use instead: +``` +println!(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/ptr_arg.txt b/src/tools/clippy/src/docs/ptr_arg.txt new file mode 100644 index 0000000000000..796b0a65b717f --- /dev/null +++ b/src/tools/clippy/src/docs/ptr_arg.txt @@ -0,0 +1,29 @@ +### What it does +This lint checks for function arguments of type `&String`, `&Vec`, +`&PathBuf`, and `Cow<_>`. It will also suggest you replace `.clone()` calls +with the appropriate `.to_owned()`/`to_string()` calls. + +### Why is this bad? +Requiring the argument to be of the specific size +makes the function less useful for no benefit; slices in the form of `&[T]` +or `&str` usually suffice and can be obtained from other types, too. + +### Known problems +There may be `fn(&Vec)`-typed references pointing to your function. +If you have them, you will get a compiler error after applying this lint's +suggestions. You then have the choice to undo your changes or change the +type of the reference. + +Note that if the function is part of your public interface, there may be +other crates referencing it, of which you may not be aware. Carefully +deprecate the function before applying the lint suggestions in this case. + +### Example +``` +fn foo(&Vec) { .. } +``` + +Use instead: +``` +fn foo(&[u32]) { .. } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/ptr_as_ptr.txt b/src/tools/clippy/src/docs/ptr_as_ptr.txt new file mode 100644 index 0000000000000..8fb35c4aae8f1 --- /dev/null +++ b/src/tools/clippy/src/docs/ptr_as_ptr.txt @@ -0,0 +1,22 @@ +### What it does +Checks for `as` casts between raw pointers without changing its mutability, +namely `*const T` to `*const U` and `*mut T` to `*mut U`. + +### Why is this bad? +Though `as` casts between raw pointers is not terrible, `pointer::cast` is safer because +it cannot accidentally change the pointer's mutability nor cast the pointer to other types like `usize`. + +### Example +``` +let ptr: *const u32 = &42_u32; +let mut_ptr: *mut u32 = &mut 42_u32; +let _ = ptr as *const i32; +let _ = mut_ptr as *mut i32; +``` +Use instead: +``` +let ptr: *const u32 = &42_u32; +let mut_ptr: *mut u32 = &mut 42_u32; +let _ = ptr.cast::(); +let _ = mut_ptr.cast::(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/ptr_eq.txt b/src/tools/clippy/src/docs/ptr_eq.txt new file mode 100644 index 0000000000000..06b36ca55e691 --- /dev/null +++ b/src/tools/clippy/src/docs/ptr_eq.txt @@ -0,0 +1,22 @@ +### What it does +Use `std::ptr::eq` when applicable + +### Why is this bad? +`ptr::eq` can be used to compare `&T` references +(which coerce to `*const T` implicitly) by their address rather than +comparing the values they point to. + +### Example +``` +let a = &[1, 2, 3]; +let b = &[1, 2, 3]; + +assert!(a as *const _ as usize == b as *const _ as usize); +``` +Use instead: +``` +let a = &[1, 2, 3]; +let b = &[1, 2, 3]; + +assert!(std::ptr::eq(a, b)); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/ptr_offset_with_cast.txt b/src/tools/clippy/src/docs/ptr_offset_with_cast.txt new file mode 100644 index 0000000000000..f204e769bf4b8 --- /dev/null +++ b/src/tools/clippy/src/docs/ptr_offset_with_cast.txt @@ -0,0 +1,30 @@ +### What it does +Checks for usage of the `offset` pointer method with a `usize` casted to an +`isize`. + +### Why is this bad? +If we’re always increasing the pointer address, we can avoid the numeric +cast by using the `add` method instead. + +### Example +``` +let vec = vec![b'a', b'b', b'c']; +let ptr = vec.as_ptr(); +let offset = 1_usize; + +unsafe { + ptr.offset(offset as isize); +} +``` + +Could be written: + +``` +let vec = vec![b'a', b'b', b'c']; +let ptr = vec.as_ptr(); +let offset = 1_usize; + +unsafe { + ptr.add(offset); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/pub_use.txt b/src/tools/clippy/src/docs/pub_use.txt new file mode 100644 index 0000000000000..407cafa01903f --- /dev/null +++ b/src/tools/clippy/src/docs/pub_use.txt @@ -0,0 +1,28 @@ +### What it does + +Restricts the usage of `pub use ...` + +### Why is this bad? + +`pub use` is usually fine, but a project may wish to limit `pub use` instances to prevent +unintentional exports or to encourage placing exported items directly in public modules + +### Example +``` +pub mod outer { + mod inner { + pub struct Test {} + } + pub use inner::Test; +} + +use outer::Test; +``` +Use instead: +``` +pub mod outer { + pub struct Test {} +} + +use outer::Test; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/question_mark.txt b/src/tools/clippy/src/docs/question_mark.txt new file mode 100644 index 0000000000000..4dc987be88132 --- /dev/null +++ b/src/tools/clippy/src/docs/question_mark.txt @@ -0,0 +1,18 @@ +### What it does +Checks for expressions that could be replaced by the question mark operator. + +### Why is this bad? +Question mark usage is more idiomatic. + +### Example +``` +if option.is_none() { + return None; +} +``` + +Could be written: + +``` +option?; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/range_minus_one.txt b/src/tools/clippy/src/docs/range_minus_one.txt new file mode 100644 index 0000000000000..fcb96dcc34edf --- /dev/null +++ b/src/tools/clippy/src/docs/range_minus_one.txt @@ -0,0 +1,27 @@ +### What it does +Checks for inclusive ranges where 1 is subtracted from +the upper bound, e.g., `x..=(y-1)`. + +### Why is this bad? +The code is more readable with an exclusive range +like `x..y`. + +### Known problems +This will cause a warning that cannot be fixed if +the consumer of the range only accepts a specific range type, instead of +the generic `RangeBounds` trait +([#3307](https://github.com/rust-lang/rust-clippy/issues/3307)). + +### Example +``` +for i in x..=(y-1) { + // .. +} +``` + +Use instead: +``` +for i in x..y { + // .. +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/range_plus_one.txt b/src/tools/clippy/src/docs/range_plus_one.txt new file mode 100644 index 0000000000000..193c85f9cbc72 --- /dev/null +++ b/src/tools/clippy/src/docs/range_plus_one.txt @@ -0,0 +1,36 @@ +### What it does +Checks for exclusive ranges where 1 is added to the +upper bound, e.g., `x..(y+1)`. + +### Why is this bad? +The code is more readable with an inclusive range +like `x..=y`. + +### Known problems +Will add unnecessary pair of parentheses when the +expression is not wrapped in a pair but starts with an opening parenthesis +and ends with a closing one. +I.e., `let _ = (f()+1)..(f()+1)` results in `let _ = ((f()+1)..=f())`. + +Also in many cases, inclusive ranges are still slower to run than +exclusive ranges, because they essentially add an extra branch that +LLVM may fail to hoist out of the loop. + +This will cause a warning that cannot be fixed if the consumer of the +range only accepts a specific range type, instead of the generic +`RangeBounds` trait +([#3307](https://github.com/rust-lang/rust-clippy/issues/3307)). + +### Example +``` +for i in x..(y+1) { + // .. +} +``` + +Use instead: +``` +for i in x..=y { + // .. +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/range_zip_with_len.txt b/src/tools/clippy/src/docs/range_zip_with_len.txt new file mode 100644 index 0000000000000..24c1efec789a9 --- /dev/null +++ b/src/tools/clippy/src/docs/range_zip_with_len.txt @@ -0,0 +1,16 @@ +### What it does +Checks for zipping a collection with the range of +`0.._.len()`. + +### Why is this bad? +The code is better expressed with `.enumerate()`. + +### Example +``` +let _ = x.iter().zip(0..x.len()); +``` + +Use instead: +``` +let _ = x.iter().enumerate(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/rc_buffer.txt b/src/tools/clippy/src/docs/rc_buffer.txt new file mode 100644 index 0000000000000..82ac58eeb3081 --- /dev/null +++ b/src/tools/clippy/src/docs/rc_buffer.txt @@ -0,0 +1,27 @@ +### What it does +Checks for `Rc` and `Arc` when `T` is a mutable buffer type such as `String` or `Vec`. + +### Why is this bad? +Expressions such as `Rc` usually have no advantage over `Rc`, since +it is larger and involves an extra level of indirection, and doesn't implement `Borrow`. + +While mutating a buffer type would still be possible with `Rc::get_mut()`, it only +works if there are no additional references yet, which usually defeats the purpose of +enclosing it in a shared ownership type. Instead, additionally wrapping the inner +type with an interior mutable container (such as `RefCell` or `Mutex`) would normally +be used. + +### Known problems +This pattern can be desirable to avoid the overhead of a `RefCell` or `Mutex` for +cases where mutation only happens before there are any additional references. + +### Example +``` +fn foo(interned: Rc) { ... } +``` + +Better: + +``` +fn foo(interned: Rc) { ... } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/rc_clone_in_vec_init.txt b/src/tools/clippy/src/docs/rc_clone_in_vec_init.txt new file mode 100644 index 0000000000000..6fc08aaf9ab57 --- /dev/null +++ b/src/tools/clippy/src/docs/rc_clone_in_vec_init.txt @@ -0,0 +1,29 @@ +### What it does +Checks for reference-counted pointers (`Arc`, `Rc`, `rc::Weak`, and `sync::Weak`) +in `vec![elem; len]` + +### Why is this bad? +This will create `elem` once and clone it `len` times - doing so with `Arc`/`Rc`/`Weak` +is a bit misleading, as it will create references to the same pointer, rather +than different instances. + +### Example +``` +let v = vec![std::sync::Arc::new("some data".to_string()); 100]; +// or +let v = vec![std::rc::Rc::new("some data".to_string()); 100]; +``` +Use instead: +``` +// Initialize each value separately: +let mut data = Vec::with_capacity(100); +for _ in 0..100 { + data.push(std::rc::Rc::new("some data".to_string())); +} + +// Or if you want clones of the same reference, +// Create the reference beforehand to clarify that +// it should be cloned for each value +let data = std::rc::Rc::new("some data".to_string()); +let v = vec![data; 100]; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/rc_mutex.txt b/src/tools/clippy/src/docs/rc_mutex.txt new file mode 100644 index 0000000000000..ed7a1e344d086 --- /dev/null +++ b/src/tools/clippy/src/docs/rc_mutex.txt @@ -0,0 +1,26 @@ +### What it does +Checks for `Rc>`. + +### Why is this bad? +`Rc` is used in single thread and `Mutex` is used in multi thread. +Consider using `Rc>` in single thread or `Arc>` in multi thread. + +### Known problems +Sometimes combining generic types can lead to the requirement that a +type use Rc in conjunction with Mutex. We must consider those cases false positives, but +alas they are quite hard to rule out. Luckily they are also rare. + +### Example +``` +use std::rc::Rc; +use std::sync::Mutex; +fn foo(interned: Rc>) { ... } +``` + +Better: + +``` +use std::rc::Rc; +use std::cell::RefCell +fn foo(interned: Rc>) { ... } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/read_zero_byte_vec.txt b/src/tools/clippy/src/docs/read_zero_byte_vec.txt new file mode 100644 index 0000000000000..cef5604e01c08 --- /dev/null +++ b/src/tools/clippy/src/docs/read_zero_byte_vec.txt @@ -0,0 +1,30 @@ +### What it does +This lint catches reads into a zero-length `Vec`. +Especially in the case of a call to `with_capacity`, this lint warns that read +gets the number of bytes from the `Vec`'s length, not its capacity. + +### Why is this bad? +Reading zero bytes is almost certainly not the intended behavior. + +### Known problems +In theory, a very unusual read implementation could assign some semantic meaning +to zero-byte reads. But it seems exceptionally unlikely that code intending to do +a zero-byte read would allocate a `Vec` for it. + +### Example +``` +use std::io; +fn foo(mut f: F) { + let mut data = Vec::with_capacity(100); + f.read(&mut data).unwrap(); +} +``` +Use instead: +``` +use std::io; +fn foo(mut f: F) { + let mut data = Vec::with_capacity(100); + data.resize(100, 0); + f.read(&mut data).unwrap(); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/recursive_format_impl.txt b/src/tools/clippy/src/docs/recursive_format_impl.txt new file mode 100644 index 0000000000000..32fffd84cf432 --- /dev/null +++ b/src/tools/clippy/src/docs/recursive_format_impl.txt @@ -0,0 +1,32 @@ +### What it does +Checks for format trait implementations (e.g. `Display`) with a recursive call to itself +which uses `self` as a parameter. +This is typically done indirectly with the `write!` macro or with `to_string()`. + +### Why is this bad? +This will lead to infinite recursion and a stack overflow. + +### Example + +``` +use std::fmt; + +struct Structure(i32); +impl fmt::Display for Structure { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.to_string()) + } +} + +``` +Use instead: +``` +use std::fmt; + +struct Structure(i32); +impl fmt::Display for Structure { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.0) + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/redundant_allocation.txt b/src/tools/clippy/src/docs/redundant_allocation.txt new file mode 100644 index 0000000000000..86bf51e8dfec7 --- /dev/null +++ b/src/tools/clippy/src/docs/redundant_allocation.txt @@ -0,0 +1,17 @@ +### What it does +Checks for use of redundant allocations anywhere in the code. + +### Why is this bad? +Expressions such as `Rc<&T>`, `Rc>`, `Rc>`, `Rc>`, `Arc<&T>`, `Arc>`, +`Arc>`, `Arc>`, `Box<&T>`, `Box>`, `Box>`, `Box>`, add an unnecessary level of indirection. + +### Example +``` +fn foo(bar: Rc<&usize>) {} +``` + +Better: + +``` +fn foo(bar: &usize) {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/redundant_clone.txt b/src/tools/clippy/src/docs/redundant_clone.txt new file mode 100644 index 0000000000000..b29aed0b5e779 --- /dev/null +++ b/src/tools/clippy/src/docs/redundant_clone.txt @@ -0,0 +1,23 @@ +### What it does +Checks for a redundant `clone()` (and its relatives) which clones an owned +value that is going to be dropped without further use. + +### Why is this bad? +It is not always possible for the compiler to eliminate useless +allocations and deallocations generated by redundant `clone()`s. + +### Known problems +False-negatives: analysis performed by this lint is conservative and limited. + +### Example +``` +{ + let x = Foo::new(); + call(x.clone()); + call(x.clone()); // this can just pass `x` +} + +["lorem", "ipsum"].join(" ").to_string(); + +Path::new("/a/b").join("c").to_path_buf(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/redundant_closure.txt b/src/tools/clippy/src/docs/redundant_closure.txt new file mode 100644 index 0000000000000..0faa9513f97f2 --- /dev/null +++ b/src/tools/clippy/src/docs/redundant_closure.txt @@ -0,0 +1,25 @@ +### What it does +Checks for closures which just call another function where +the function can be called directly. `unsafe` functions or calls where types +get adjusted are ignored. + +### Why is this bad? +Needlessly creating a closure adds code for no benefit +and gives the optimizer more work. + +### Known problems +If creating the closure inside the closure has a side- +effect then moving the closure creation out will change when that side- +effect runs. +See [#1439](https://github.com/rust-lang/rust-clippy/issues/1439) for more details. + +### Example +``` +xs.map(|x| foo(x)) +``` + +Use instead: +``` +// where `foo(_)` is a plain function that takes the exact argument type of `x`. +xs.map(foo) +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/redundant_closure_call.txt b/src/tools/clippy/src/docs/redundant_closure_call.txt new file mode 100644 index 0000000000000..913d1a705e294 --- /dev/null +++ b/src/tools/clippy/src/docs/redundant_closure_call.txt @@ -0,0 +1,17 @@ +### What it does +Detects closures called in the same expression where they +are defined. + +### Why is this bad? +It is unnecessarily adding to the expression's +complexity. + +### Example +``` +let a = (|| 42)(); +``` + +Use instead: +``` +let a = 42; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/redundant_closure_for_method_calls.txt b/src/tools/clippy/src/docs/redundant_closure_for_method_calls.txt new file mode 100644 index 0000000000000..865510e14755a --- /dev/null +++ b/src/tools/clippy/src/docs/redundant_closure_for_method_calls.txt @@ -0,0 +1,15 @@ +### What it does +Checks for closures which only invoke a method on the closure +argument and can be replaced by referencing the method directly. + +### Why is this bad? +It's unnecessary to create the closure. + +### Example +``` +Some('a').map(|s| s.to_uppercase()); +``` +may be rewritten as +``` +Some('a').map(char::to_uppercase); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/redundant_else.txt b/src/tools/clippy/src/docs/redundant_else.txt new file mode 100644 index 0000000000000..3f4e86917603c --- /dev/null +++ b/src/tools/clippy/src/docs/redundant_else.txt @@ -0,0 +1,30 @@ +### What it does +Checks for `else` blocks that can be removed without changing semantics. + +### Why is this bad? +The `else` block adds unnecessary indentation and verbosity. + +### Known problems +Some may prefer to keep the `else` block for clarity. + +### Example +``` +fn my_func(count: u32) { + if count == 0 { + print!("Nothing to do"); + return; + } else { + print!("Moving on..."); + } +} +``` +Use instead: +``` +fn my_func(count: u32) { + if count == 0 { + print!("Nothing to do"); + return; + } + print!("Moving on..."); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/redundant_feature_names.txt b/src/tools/clippy/src/docs/redundant_feature_names.txt new file mode 100644 index 0000000000000..5bd6925ed47d0 --- /dev/null +++ b/src/tools/clippy/src/docs/redundant_feature_names.txt @@ -0,0 +1,23 @@ +### What it does +Checks for feature names with prefix `use-`, `with-` or suffix `-support` + +### Why is this bad? +These prefixes and suffixes have no significant meaning. + +### Example +``` +[features] +default = ["use-abc", "with-def", "ghi-support"] +use-abc = [] // redundant +with-def = [] // redundant +ghi-support = [] // redundant +``` + +Use instead: +``` +[features] +default = ["abc", "def", "ghi"] +abc = [] +def = [] +ghi = [] +``` diff --git a/src/tools/clippy/src/docs/redundant_field_names.txt b/src/tools/clippy/src/docs/redundant_field_names.txt new file mode 100644 index 0000000000000..35f20a466b378 --- /dev/null +++ b/src/tools/clippy/src/docs/redundant_field_names.txt @@ -0,0 +1,22 @@ +### What it does +Checks for fields in struct literals where shorthands +could be used. + +### Why is this bad? +If the field and variable names are the same, +the field name is redundant. + +### Example +``` +let bar: u8 = 123; + +struct Foo { + bar: u8, +} + +let foo = Foo { bar: bar }; +``` +the last line can be simplified to +``` +let foo = Foo { bar }; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/redundant_pattern.txt b/src/tools/clippy/src/docs/redundant_pattern.txt new file mode 100644 index 0000000000000..45f6cfc86702c --- /dev/null +++ b/src/tools/clippy/src/docs/redundant_pattern.txt @@ -0,0 +1,22 @@ +### What it does +Checks for patterns in the form `name @ _`. + +### Why is this bad? +It's almost always more readable to just use direct +bindings. + +### Example +``` +match v { + Some(x) => (), + y @ _ => (), +} +``` + +Use instead: +``` +match v { + Some(x) => (), + y => (), +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/redundant_pattern_matching.txt b/src/tools/clippy/src/docs/redundant_pattern_matching.txt new file mode 100644 index 0000000000000..77b1021e0db3b --- /dev/null +++ b/src/tools/clippy/src/docs/redundant_pattern_matching.txt @@ -0,0 +1,45 @@ +### What it does +Lint for redundant pattern matching over `Result`, `Option`, +`std::task::Poll` or `std::net::IpAddr` + +### Why is this bad? +It's more concise and clear to just use the proper +utility function + +### Known problems +This will change the drop order for the matched type. Both `if let` and +`while let` will drop the value at the end of the block, both `if` and `while` will drop the +value before entering the block. For most types this change will not matter, but for a few +types this will not be an acceptable change (e.g. locks). See the +[reference](https://doc.rust-lang.org/reference/destructors.html#drop-scopes) for more about +drop order. + +### Example +``` +if let Ok(_) = Ok::(42) {} +if let Err(_) = Err::(42) {} +if let None = None::<()> {} +if let Some(_) = Some(42) {} +if let Poll::Pending = Poll::Pending::<()> {} +if let Poll::Ready(_) = Poll::Ready(42) {} +if let IpAddr::V4(_) = IpAddr::V4(Ipv4Addr::LOCALHOST) {} +if let IpAddr::V6(_) = IpAddr::V6(Ipv6Addr::LOCALHOST) {} +match Ok::(42) { + Ok(_) => true, + Err(_) => false, +}; +``` + +The more idiomatic use would be: + +``` +if Ok::(42).is_ok() {} +if Err::(42).is_err() {} +if None::<()>.is_none() {} +if Some(42).is_some() {} +if Poll::Pending::<()>.is_pending() {} +if Poll::Ready(42).is_ready() {} +if IpAddr::V4(Ipv4Addr::LOCALHOST).is_ipv4() {} +if IpAddr::V6(Ipv6Addr::LOCALHOST).is_ipv6() {} +Ok::(42).is_ok(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/redundant_pub_crate.txt b/src/tools/clippy/src/docs/redundant_pub_crate.txt new file mode 100644 index 0000000000000..a527bb5acda1e --- /dev/null +++ b/src/tools/clippy/src/docs/redundant_pub_crate.txt @@ -0,0 +1,21 @@ +### What it does +Checks for items declared `pub(crate)` that are not crate visible because they +are inside a private module. + +### Why is this bad? +Writing `pub(crate)` is misleading when it's redundant due to the parent +module's visibility. + +### Example +``` +mod internal { + pub(crate) fn internal_fn() { } +} +``` +This function is not visible outside the module and it can be declared with `pub` or +private visibility +``` +mod internal { + pub fn internal_fn() { } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/redundant_slicing.txt b/src/tools/clippy/src/docs/redundant_slicing.txt new file mode 100644 index 0000000000000..6798911ed76c0 --- /dev/null +++ b/src/tools/clippy/src/docs/redundant_slicing.txt @@ -0,0 +1,24 @@ +### What it does +Checks for redundant slicing expressions which use the full range, and +do not change the type. + +### Why is this bad? +It unnecessarily adds complexity to the expression. + +### Known problems +If the type being sliced has an implementation of `Index` +that actually changes anything then it can't be removed. However, this would be surprising +to people reading the code and should have a note with it. + +### Example +``` +fn get_slice(x: &[u32]) -> &[u32] { + &x[..] +} +``` +Use instead: +``` +fn get_slice(x: &[u32]) -> &[u32] { + x +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/redundant_static_lifetimes.txt b/src/tools/clippy/src/docs/redundant_static_lifetimes.txt new file mode 100644 index 0000000000000..edb8e7b5c62bf --- /dev/null +++ b/src/tools/clippy/src/docs/redundant_static_lifetimes.txt @@ -0,0 +1,19 @@ +### What it does +Checks for constants and statics with an explicit `'static` lifetime. + +### Why is this bad? +Adding `'static` to every reference can create very +complicated types. + +### Example +``` +const FOO: &'static [(&'static str, &'static str, fn(&Bar) -> bool)] = +&[...] +static FOO: &'static [(&'static str, &'static str, fn(&Bar) -> bool)] = +&[...] +``` +This code can be rewritten as +``` + const FOO: &[(&str, &str, fn(&Bar) -> bool)] = &[...] + static FOO: &[(&str, &str, fn(&Bar) -> bool)] = &[...] +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/ref_binding_to_reference.txt b/src/tools/clippy/src/docs/ref_binding_to_reference.txt new file mode 100644 index 0000000000000..dc391cd988e58 --- /dev/null +++ b/src/tools/clippy/src/docs/ref_binding_to_reference.txt @@ -0,0 +1,21 @@ +### What it does +Checks for `ref` bindings which create a reference to a reference. + +### Why is this bad? +The address-of operator at the use site is clearer about the need for a reference. + +### Example +``` +let x = Some(""); +if let Some(ref x) = x { + // use `x` here +} +``` + +Use instead: +``` +let x = Some(""); +if let Some(x) = x { + // use `&x` here +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/ref_option_ref.txt b/src/tools/clippy/src/docs/ref_option_ref.txt new file mode 100644 index 0000000000000..951c7bd7f7ec6 --- /dev/null +++ b/src/tools/clippy/src/docs/ref_option_ref.txt @@ -0,0 +1,19 @@ +### What it does +Checks for usage of `&Option<&T>`. + +### Why is this bad? +Since `&` is Copy, it's useless to have a +reference on `Option<&T>`. + +### Known problems +It may be irrelevant to use this lint on +public API code as it will make a breaking change to apply it. + +### Example +``` +let x: &Option<&u32> = &Some(&0u32); +``` +Use instead: +``` +let x: Option<&u32> = Some(&0u32); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/repeat_once.txt b/src/tools/clippy/src/docs/repeat_once.txt new file mode 100644 index 0000000000000..3ba189c1945d7 --- /dev/null +++ b/src/tools/clippy/src/docs/repeat_once.txt @@ -0,0 +1,25 @@ +### What it does +Checks for usage of `.repeat(1)` and suggest the following method for each types. +- `.to_string()` for `str` +- `.clone()` for `String` +- `.to_vec()` for `slice` + +The lint will evaluate constant expressions and values as arguments of `.repeat(..)` and emit a message if +they are equivalent to `1`. (Related discussion in [rust-clippy#7306](https://github.com/rust-lang/rust-clippy/issues/7306)) + +### Why is this bad? +For example, `String.repeat(1)` is equivalent to `.clone()`. If cloning +the string is the intention behind this, `clone()` should be used. + +### Example +``` +fn main() { + let x = String::from("hello world").repeat(1); +} +``` +Use instead: +``` +fn main() { + let x = String::from("hello world").clone(); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/rest_pat_in_fully_bound_structs.txt b/src/tools/clippy/src/docs/rest_pat_in_fully_bound_structs.txt new file mode 100644 index 0000000000000..40ebbe754a372 --- /dev/null +++ b/src/tools/clippy/src/docs/rest_pat_in_fully_bound_structs.txt @@ -0,0 +1,24 @@ +### What it does +Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched. + +### Why is this bad? +Correctness and readability. It's like having a wildcard pattern after +matching all enum variants explicitly. + +### Example +``` +let a = A { a: 5 }; + +match a { + A { a: 5, .. } => {}, + _ => {}, +} +``` + +Use instead: +``` +match a { + A { a: 5 } => {}, + _ => {}, +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/result_large_err.txt b/src/tools/clippy/src/docs/result_large_err.txt new file mode 100644 index 0000000000000..e5fab3c5cfcfa --- /dev/null +++ b/src/tools/clippy/src/docs/result_large_err.txt @@ -0,0 +1,36 @@ +### What it does +Checks for functions that return `Result` with an unusually large +`Err`-variant. + +### Why is this bad? +A `Result` is at least as large as the `Err`-variant. While we +expect that variant to be seldomly used, the compiler needs to reserve +and move that much memory every single time. + +### Known problems +The size determined by Clippy is platform-dependent. + +### Examples +``` +pub enum ParseError { + UnparsedBytes([u8; 512]), + UnexpectedEof, +} + +// The `Result` has at least 512 bytes, even in the `Ok`-case +pub fn parse() -> Result<(), ParseError> { + Ok(()) +} +``` +should be +``` +pub enum ParseError { + UnparsedBytes(Box<[u8; 512]>), + UnexpectedEof, +} + +// The `Result` is slightly larger than a pointer +pub fn parse() -> Result<(), ParseError> { + Ok(()) +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/result_map_or_into_option.txt b/src/tools/clippy/src/docs/result_map_or_into_option.txt new file mode 100644 index 0000000000000..899d98c307c8f --- /dev/null +++ b/src/tools/clippy/src/docs/result_map_or_into_option.txt @@ -0,0 +1,16 @@ +### What it does +Checks for usage of `_.map_or(None, Some)`. + +### Why is this bad? +Readability, this can be written more concisely as +`_.ok()`. + +### Example +``` +assert_eq!(Some(1), r.map_or(None, Some)); +``` + +Use instead: +``` +assert_eq!(Some(1), r.ok()); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/result_map_unit_fn.txt b/src/tools/clippy/src/docs/result_map_unit_fn.txt new file mode 100644 index 0000000000000..3455c5c1f9b8a --- /dev/null +++ b/src/tools/clippy/src/docs/result_map_unit_fn.txt @@ -0,0 +1,26 @@ +### What it does +Checks for usage of `result.map(f)` where f is a function +or closure that returns the unit type `()`. + +### Why is this bad? +Readability, this can be written more clearly with +an if let statement + +### Example +``` +let x: Result = do_stuff(); +x.map(log_err_msg); +x.map(|msg| log_err_msg(format_msg(msg))); +``` + +The correct use would be: + +``` +let x: Result = do_stuff(); +if let Ok(msg) = x { + log_err_msg(msg); +}; +if let Ok(msg) = x { + log_err_msg(format_msg(msg)); +}; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/result_unit_err.txt b/src/tools/clippy/src/docs/result_unit_err.txt new file mode 100644 index 0000000000000..7c8ec2ffcf948 --- /dev/null +++ b/src/tools/clippy/src/docs/result_unit_err.txt @@ -0,0 +1,40 @@ +### What it does +Checks for public functions that return a `Result` +with an `Err` type of `()`. It suggests using a custom type that +implements `std::error::Error`. + +### Why is this bad? +Unit does not implement `Error` and carries no +further information about what went wrong. + +### Known problems +Of course, this lint assumes that `Result` is used +for a fallible operation (which is after all the intended use). However +code may opt to (mis)use it as a basic two-variant-enum. In that case, +the suggestion is misguided, and the code should use a custom enum +instead. + +### Examples +``` +pub fn read_u8() -> Result { Err(()) } +``` +should become +``` +use std::fmt; + +#[derive(Debug)] +pub struct EndOfStream; + +impl fmt::Display for EndOfStream { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "End of Stream") + } +} + +impl std::error::Error for EndOfStream { } + +pub fn read_u8() -> Result { Err(EndOfStream) } +``` + +Note that there are crates that simplify creating the error type, e.g. +[`thiserror`](https://docs.rs/thiserror). \ No newline at end of file diff --git a/src/tools/clippy/src/docs/return_self_not_must_use.txt b/src/tools/clippy/src/docs/return_self_not_must_use.txt new file mode 100644 index 0000000000000..4a4fd2c6e517b --- /dev/null +++ b/src/tools/clippy/src/docs/return_self_not_must_use.txt @@ -0,0 +1,46 @@ +### What it does +This lint warns when a method returning `Self` doesn't have the `#[must_use]` attribute. + +### Why is this bad? +Methods returning `Self` often create new values, having the `#[must_use]` attribute +prevents users from "forgetting" to use the newly created value. + +The `#[must_use]` attribute can be added to the type itself to ensure that instances +are never forgotten. Functions returning a type marked with `#[must_use]` will not be +linted, as the usage is already enforced by the type attribute. + +### Limitations +This lint is only applied on methods taking a `self` argument. It would be mostly noise +if it was added on constructors for example. + +### Example +``` +pub struct Bar; +impl Bar { + // Missing attribute + pub fn bar(&self) -> Self { + Self + } +} +``` + +Use instead: +``` +// It's better to have the `#[must_use]` attribute on the method like this: +pub struct Bar; +impl Bar { + #[must_use] + pub fn bar(&self) -> Self { + Self + } +} + +// Or on the type definition like this: +#[must_use] +pub struct Bar; +impl Bar { + pub fn bar(&self) -> Self { + Self + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/reversed_empty_ranges.txt b/src/tools/clippy/src/docs/reversed_empty_ranges.txt new file mode 100644 index 0000000000000..39f4811938668 --- /dev/null +++ b/src/tools/clippy/src/docs/reversed_empty_ranges.txt @@ -0,0 +1,26 @@ +### What it does +Checks for range expressions `x..y` where both `x` and `y` +are constant and `x` is greater or equal to `y`. + +### Why is this bad? +Empty ranges yield no values so iterating them is a no-op. +Moreover, trying to use a reversed range to index a slice will panic at run-time. + +### Example +``` +fn main() { + (10..=0).for_each(|x| println!("{}", x)); + + let arr = [1, 2, 3, 4, 5]; + let sub = &arr[3..1]; +} +``` +Use instead: +``` +fn main() { + (0..=10).rev().for_each(|x| println!("{}", x)); + + let arr = [1, 2, 3, 4, 5]; + let sub = &arr[1..3]; +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/same_functions_in_if_condition.txt b/src/tools/clippy/src/docs/same_functions_in_if_condition.txt new file mode 100644 index 0000000000000..a0a90eec681e6 --- /dev/null +++ b/src/tools/clippy/src/docs/same_functions_in_if_condition.txt @@ -0,0 +1,41 @@ +### What it does +Checks for consecutive `if`s with the same function call. + +### Why is this bad? +This is probably a copy & paste error. +Despite the fact that function can have side effects and `if` works as +intended, such an approach is implicit and can be considered a "code smell". + +### Example +``` +if foo() == bar { + … +} else if foo() == bar { + … +} +``` + +This probably should be: +``` +if foo() == bar { + … +} else if foo() == baz { + … +} +``` + +or if the original code was not a typo and called function mutates a state, +consider move the mutation out of the `if` condition to avoid similarity to +a copy & paste error: + +``` +let first = foo(); +if first == bar { + … +} else { + let second = foo(); + if second == bar { + … + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/same_item_push.txt b/src/tools/clippy/src/docs/same_item_push.txt new file mode 100644 index 0000000000000..7e724073f8aa7 --- /dev/null +++ b/src/tools/clippy/src/docs/same_item_push.txt @@ -0,0 +1,29 @@ +### What it does +Checks whether a for loop is being used to push a constant +value into a Vec. + +### Why is this bad? +This kind of operation can be expressed more succinctly with +`vec![item; SIZE]` or `vec.resize(NEW_SIZE, item)` and using these alternatives may also +have better performance. + +### Example +``` +let item1 = 2; +let item2 = 3; +let mut vec: Vec = Vec::new(); +for _ in 0..20 { + vec.push(item1); +} +for _ in 0..30 { + vec.push(item2); +} +``` + +Use instead: +``` +let item1 = 2; +let item2 = 3; +let mut vec: Vec = vec![item1; 20]; +vec.resize(20 + 30, item2); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/same_name_method.txt b/src/tools/clippy/src/docs/same_name_method.txt new file mode 100644 index 0000000000000..792dd717fc645 --- /dev/null +++ b/src/tools/clippy/src/docs/same_name_method.txt @@ -0,0 +1,23 @@ +### What it does +It lints if a struct has two methods with the same name: +one from a trait, another not from trait. + +### Why is this bad? +Confusing. + +### Example +``` +trait T { + fn foo(&self) {} +} + +struct S; + +impl T for S { + fn foo(&self) {} +} + +impl S { + fn foo(&self) {} +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/search_is_some.txt b/src/tools/clippy/src/docs/search_is_some.txt new file mode 100644 index 0000000000000..67292d54585f2 --- /dev/null +++ b/src/tools/clippy/src/docs/search_is_some.txt @@ -0,0 +1,24 @@ +### What it does +Checks for an iterator or string search (such as `find()`, +`position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`. + +### Why is this bad? +Readability, this can be written more concisely as: +* `_.any(_)`, or `_.contains(_)` for `is_some()`, +* `!_.any(_)`, or `!_.contains(_)` for `is_none()`. + +### Example +``` +let vec = vec![1]; +vec.iter().find(|x| **x == 0).is_some(); + +"hello world".find("world").is_none(); +``` + +Use instead: +``` +let vec = vec![1]; +vec.iter().any(|x| *x == 0); + +!"hello world".contains("world"); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/self_assignment.txt b/src/tools/clippy/src/docs/self_assignment.txt new file mode 100644 index 0000000000000..ea60ea077ab5f --- /dev/null +++ b/src/tools/clippy/src/docs/self_assignment.txt @@ -0,0 +1,32 @@ +### What it does +Checks for explicit self-assignments. + +### Why is this bad? +Self-assignments are redundant and unlikely to be +intentional. + +### Known problems +If expression contains any deref coercions or +indexing operations they are assumed not to have any side effects. + +### Example +``` +struct Event { + x: i32, +} + +fn copy_position(a: &mut Event, b: &Event) { + a.x = a.x; +} +``` + +Should be: +``` +struct Event { + x: i32, +} + +fn copy_position(a: &mut Event, b: &Event) { + a.x = b.x; +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/self_named_constructors.txt b/src/tools/clippy/src/docs/self_named_constructors.txt new file mode 100644 index 0000000000000..a01669a84542d --- /dev/null +++ b/src/tools/clippy/src/docs/self_named_constructors.txt @@ -0,0 +1,26 @@ +### What it does +Warns when constructors have the same name as their types. + +### Why is this bad? +Repeating the name of the type is redundant. + +### Example +``` +struct Foo {} + +impl Foo { + pub fn foo() -> Foo { + Foo {} + } +} +``` +Use instead: +``` +struct Foo {} + +impl Foo { + pub fn new() -> Foo { + Foo {} + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/self_named_module_files.txt b/src/tools/clippy/src/docs/self_named_module_files.txt new file mode 100644 index 0000000000000..73e8051362883 --- /dev/null +++ b/src/tools/clippy/src/docs/self_named_module_files.txt @@ -0,0 +1,22 @@ +### What it does +Checks that module layout uses only `mod.rs` files. + +### Why is this bad? +Having multiple module layout styles in a project can be confusing. + +### Example +``` +src/ + stuff/ + stuff_files.rs + stuff.rs + lib.rs +``` +Use instead: +``` +src/ + stuff/ + stuff_files.rs + mod.rs + lib.rs +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/semicolon_if_nothing_returned.txt b/src/tools/clippy/src/docs/semicolon_if_nothing_returned.txt new file mode 100644 index 0000000000000..30c963ca211b3 --- /dev/null +++ b/src/tools/clippy/src/docs/semicolon_if_nothing_returned.txt @@ -0,0 +1,20 @@ +### What it does +Looks for blocks of expressions and fires if the last expression returns +`()` but is not followed by a semicolon. + +### Why is this bad? +The semicolon might be optional but when extending the block with new +code, it doesn't require a change in previous last line. + +### Example +``` +fn main() { + println!("Hello world") +} +``` +Use instead: +``` +fn main() { + println!("Hello world"); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/separated_literal_suffix.txt b/src/tools/clippy/src/docs/separated_literal_suffix.txt new file mode 100644 index 0000000000000..226a6b8a98766 --- /dev/null +++ b/src/tools/clippy/src/docs/separated_literal_suffix.txt @@ -0,0 +1,17 @@ +### What it does +Warns if literal suffixes are separated by an underscore. +To enforce separated literal suffix style, +see the `unseparated_literal_suffix` lint. + +### Why is this bad? +Suffix style should be consistent. + +### Example +``` +123832_i32 +``` + +Use instead: +``` +123832i32 +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/serde_api_misuse.txt b/src/tools/clippy/src/docs/serde_api_misuse.txt new file mode 100644 index 0000000000000..8a3c89ac11adc --- /dev/null +++ b/src/tools/clippy/src/docs/serde_api_misuse.txt @@ -0,0 +1,10 @@ +### What it does +Checks for mis-uses of the serde API. + +### Why is this bad? +Serde is very finnicky about how its API should be +used, but the type system can't be used to enforce it (yet?). + +### Example +Implementing `Visitor::visit_string` but not +`Visitor::visit_str`. \ No newline at end of file diff --git a/src/tools/clippy/src/docs/shadow_reuse.txt b/src/tools/clippy/src/docs/shadow_reuse.txt new file mode 100644 index 0000000000000..9eb8e7ad164bb --- /dev/null +++ b/src/tools/clippy/src/docs/shadow_reuse.txt @@ -0,0 +1,20 @@ +### What it does +Checks for bindings that shadow other bindings already in +scope, while reusing the original value. + +### Why is this bad? +Not too much, in fact it's a common pattern in Rust +code. Still, some argue that name shadowing like this hurts readability, +because a value may be bound to different things depending on position in +the code. + +### Example +``` +let x = 2; +let x = x + 1; +``` +use different variable name: +``` +let x = 2; +let y = x + 1; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/shadow_same.txt b/src/tools/clippy/src/docs/shadow_same.txt new file mode 100644 index 0000000000000..3cd96f560a5e2 --- /dev/null +++ b/src/tools/clippy/src/docs/shadow_same.txt @@ -0,0 +1,18 @@ +### What it does +Checks for bindings that shadow other bindings already in +scope, while just changing reference level or mutability. + +### Why is this bad? +Not much, in fact it's a very common pattern in Rust +code. Still, some may opt to avoid it in their code base, they can set this +lint to `Warn`. + +### Example +``` +let x = &x; +``` + +Use instead: +``` +let y = &x; // use different variable name +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/shadow_unrelated.txt b/src/tools/clippy/src/docs/shadow_unrelated.txt new file mode 100644 index 0000000000000..436251c520a98 --- /dev/null +++ b/src/tools/clippy/src/docs/shadow_unrelated.txt @@ -0,0 +1,22 @@ +### What it does +Checks for bindings that shadow other bindings already in +scope, either without an initialization or with one that does not even use +the original value. + +### Why is this bad? +Name shadowing can hurt readability, especially in +large code bases, because it is easy to lose track of the active binding at +any place in the code. This can be alleviated by either giving more specific +names to bindings or introducing more scopes to contain the bindings. + +### Example +``` +let x = y; +let x = z; // shadows the earlier binding +``` + +Use instead: +``` +let x = y; +let w = z; // use different variable name +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/short_circuit_statement.txt b/src/tools/clippy/src/docs/short_circuit_statement.txt new file mode 100644 index 0000000000000..31492bed03d4b --- /dev/null +++ b/src/tools/clippy/src/docs/short_circuit_statement.txt @@ -0,0 +1,14 @@ +### What it does +Checks for the use of short circuit boolean conditions as +a +statement. + +### Why is this bad? +Using a short circuit boolean condition as a statement +may hide the fact that the second part is executed or not depending on the +outcome of the first part. + +### Example +``` +f() && g(); // We should write `if f() { g(); }`. +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/should_implement_trait.txt b/src/tools/clippy/src/docs/should_implement_trait.txt new file mode 100644 index 0000000000000..02e74751ae034 --- /dev/null +++ b/src/tools/clippy/src/docs/should_implement_trait.txt @@ -0,0 +1,22 @@ +### What it does +Checks for methods that should live in a trait +implementation of a `std` trait (see [llogiq's blog +post](http://llogiq.github.io/2015/07/30/traits.html) for further +information) instead of an inherent implementation. + +### Why is this bad? +Implementing the traits improve ergonomics for users of +the code, often with very little cost. Also people seeing a `mul(...)` +method +may expect `*` to work equally, so you should have good reason to disappoint +them. + +### Example +``` +struct X; +impl X { + fn add(&self, other: &X) -> X { + // .. + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/significant_drop_in_scrutinee.txt b/src/tools/clippy/src/docs/significant_drop_in_scrutinee.txt new file mode 100644 index 0000000000000..f869def0ddb7c --- /dev/null +++ b/src/tools/clippy/src/docs/significant_drop_in_scrutinee.txt @@ -0,0 +1,43 @@ +### What it does +Check for temporaries returned from function calls in a match scrutinee that have the +`clippy::has_significant_drop` attribute. + +### Why is this bad? +The `clippy::has_significant_drop` attribute can be added to types whose Drop impls have +an important side-effect, such as unlocking a mutex, making it important for users to be +able to accurately understand their lifetimes. When a temporary is returned in a function +call in a match scrutinee, its lifetime lasts until the end of the match block, which may +be surprising. + +For `Mutex`es this can lead to a deadlock. This happens when the match scrutinee uses a +function call that returns a `MutexGuard` and then tries to lock again in one of the match +arms. In that case the `MutexGuard` in the scrutinee will not be dropped until the end of +the match block and thus will not unlock. + +### Example +``` +let mutex = Mutex::new(State {}); + +match mutex.lock().unwrap().foo() { + true => { + mutex.lock().unwrap().bar(); // Deadlock! + } + false => {} +}; + +println!("All done!"); +``` +Use instead: +``` +let mutex = Mutex::new(State {}); + +let is_foo = mutex.lock().unwrap().foo(); +match is_foo { + true => { + mutex.lock().unwrap().bar(); + } + false => {} +}; + +println!("All done!"); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/similar_names.txt b/src/tools/clippy/src/docs/similar_names.txt new file mode 100644 index 0000000000000..13aca9c0bb75b --- /dev/null +++ b/src/tools/clippy/src/docs/similar_names.txt @@ -0,0 +1,12 @@ +### What it does +Checks for names that are very similar and thus confusing. + +### Why is this bad? +It's hard to distinguish between names that differ only +by a single character. + +### Example +``` +let checked_exp = something; +let checked_expr = something_else; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/single_char_add_str.txt b/src/tools/clippy/src/docs/single_char_add_str.txt new file mode 100644 index 0000000000000..cf23dc0c89bbb --- /dev/null +++ b/src/tools/clippy/src/docs/single_char_add_str.txt @@ -0,0 +1,18 @@ +### What it does +Warns when using `push_str`/`insert_str` with a single-character string literal +where `push`/`insert` with a `char` would work fine. + +### Why is this bad? +It's less clear that we are pushing a single character. + +### Example +``` +string.insert_str(0, "R"); +string.push_str("R"); +``` + +Use instead: +``` +string.insert(0, 'R'); +string.push('R'); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/single_char_lifetime_names.txt b/src/tools/clippy/src/docs/single_char_lifetime_names.txt new file mode 100644 index 0000000000000..92dd24bf247ec --- /dev/null +++ b/src/tools/clippy/src/docs/single_char_lifetime_names.txt @@ -0,0 +1,28 @@ +### What it does +Checks for lifetimes with names which are one character +long. + +### Why is this bad? +A single character is likely not enough to express the +purpose of a lifetime. Using a longer name can make code +easier to understand, especially for those who are new to +Rust. + +### Known problems +Rust programmers and learning resources tend to use single +character lifetimes, so this lint is at odds with the +ecosystem at large. In addition, the lifetime's purpose may +be obvious or, rarely, expressible in one character. + +### Example +``` +struct DiagnosticCtx<'a> { + source: &'a str, +} +``` +Use instead: +``` +struct DiagnosticCtx<'src> { + source: &'src str, +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/single_char_pattern.txt b/src/tools/clippy/src/docs/single_char_pattern.txt new file mode 100644 index 0000000000000..9e5ad1e7d6395 --- /dev/null +++ b/src/tools/clippy/src/docs/single_char_pattern.txt @@ -0,0 +1,20 @@ +### What it does +Checks for string methods that receive a single-character +`str` as an argument, e.g., `_.split("x")`. + +### Why is this bad? +Performing these methods using a `char` is faster than +using a `str`. + +### Known problems +Does not catch multi-byte unicode characters. + +### Example +``` +_.split("x"); +``` + +Use instead: +``` +_.split('x'); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/single_component_path_imports.txt b/src/tools/clippy/src/docs/single_component_path_imports.txt new file mode 100644 index 0000000000000..3a026388183e1 --- /dev/null +++ b/src/tools/clippy/src/docs/single_component_path_imports.txt @@ -0,0 +1,21 @@ +### What it does +Checking for imports with single component use path. + +### Why is this bad? +Import with single component use path such as `use cratename;` +is not necessary, and thus should be removed. + +### Example +``` +use regex; + +fn main() { + regex::Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap(); +} +``` +Better as +``` +fn main() { + regex::Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap(); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/single_element_loop.txt b/src/tools/clippy/src/docs/single_element_loop.txt new file mode 100644 index 0000000000000..6f0c15a85f774 --- /dev/null +++ b/src/tools/clippy/src/docs/single_element_loop.txt @@ -0,0 +1,21 @@ +### What it does +Checks whether a for loop has a single element. + +### Why is this bad? +There is no reason to have a loop of a +single element. + +### Example +``` +let item1 = 2; +for item in &[item1] { + println!("{}", item); +} +``` + +Use instead: +``` +let item1 = 2; +let item = &item1; +println!("{}", item); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/single_match.txt b/src/tools/clippy/src/docs/single_match.txt new file mode 100644 index 0000000000000..31dde4da8489c --- /dev/null +++ b/src/tools/clippy/src/docs/single_match.txt @@ -0,0 +1,21 @@ +### What it does +Checks for matches with a single arm where an `if let` +will usually suffice. + +### Why is this bad? +Just readability – `if let` nests less than a `match`. + +### Example +``` +match x { + Some(ref foo) => bar(foo), + _ => (), +} +``` + +Use instead: +``` +if let Some(ref foo) = x { + bar(foo); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/single_match_else.txt b/src/tools/clippy/src/docs/single_match_else.txt new file mode 100644 index 0000000000000..29a447af09b86 --- /dev/null +++ b/src/tools/clippy/src/docs/single_match_else.txt @@ -0,0 +1,29 @@ +### What it does +Checks for matches with two arms where an `if let else` will +usually suffice. + +### Why is this bad? +Just readability – `if let` nests less than a `match`. + +### Known problems +Personal style preferences may differ. + +### Example +Using `match`: + +``` +match x { + Some(ref foo) => bar(foo), + _ => bar(&other_ref), +} +``` + +Using `if let` with `else`: + +``` +if let Some(ref foo) = x { + bar(foo); +} else { + bar(&other_ref); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/size_of_in_element_count.txt b/src/tools/clippy/src/docs/size_of_in_element_count.txt new file mode 100644 index 0000000000000..d893ec6a2a014 --- /dev/null +++ b/src/tools/clippy/src/docs/size_of_in_element_count.txt @@ -0,0 +1,16 @@ +### What it does +Detects expressions where +`size_of::` or `size_of_val::` is used as a +count of elements of type `T` + +### Why is this bad? +These functions expect a count +of `T` and not a number of bytes + +### Example +``` +const SIZE: usize = 128; +let x = [2u8; SIZE]; +let mut y = [2u8; SIZE]; +unsafe { copy_nonoverlapping(x.as_ptr(), y.as_mut_ptr(), size_of::() * SIZE) }; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/skip_while_next.txt b/src/tools/clippy/src/docs/skip_while_next.txt new file mode 100644 index 0000000000000..1ec8a3a28d5b0 --- /dev/null +++ b/src/tools/clippy/src/docs/skip_while_next.txt @@ -0,0 +1,16 @@ +### What it does +Checks for usage of `_.skip_while(condition).next()`. + +### Why is this bad? +Readability, this can be written more concisely as +`_.find(!condition)`. + +### Example +``` +vec.iter().skip_while(|x| **x == 0).next(); +``` + +Use instead: +``` +vec.iter().find(|x| **x != 0); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/slow_vector_initialization.txt b/src/tools/clippy/src/docs/slow_vector_initialization.txt new file mode 100644 index 0000000000000..53442e1796541 --- /dev/null +++ b/src/tools/clippy/src/docs/slow_vector_initialization.txt @@ -0,0 +1,24 @@ +### What it does +Checks slow zero-filled vector initialization + +### Why is this bad? +These structures are non-idiomatic and less efficient than simply using +`vec![0; len]`. + +### Example +``` +let mut vec1 = Vec::with_capacity(len); +vec1.resize(len, 0); + +let mut vec1 = Vec::with_capacity(len); +vec1.resize(vec1.capacity(), 0); + +let mut vec2 = Vec::with_capacity(len); +vec2.extend(repeat(0).take(len)); +``` + +Use instead: +``` +let mut vec1 = vec![0; len]; +let mut vec2 = vec![0; len]; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/stable_sort_primitive.txt b/src/tools/clippy/src/docs/stable_sort_primitive.txt new file mode 100644 index 0000000000000..6465dbee46b10 --- /dev/null +++ b/src/tools/clippy/src/docs/stable_sort_primitive.txt @@ -0,0 +1,31 @@ +### What it does +When sorting primitive values (integers, bools, chars, as well +as arrays, slices, and tuples of such items), it is typically better to +use an unstable sort than a stable sort. + +### Why is this bad? +Typically, using a stable sort consumes more memory and cpu cycles. +Because values which compare equal are identical, preserving their +relative order (the guarantee that a stable sort provides) means +nothing, while the extra costs still apply. + +### Known problems + +As pointed out in +[issue #8241](https://github.com/rust-lang/rust-clippy/issues/8241), +a stable sort can instead be significantly faster for certain scenarios +(eg. when a sorted vector is extended with new data and resorted). + +For more information and benchmarking results, please refer to the +issue linked above. + +### Example +``` +let mut vec = vec![2, 1, 3]; +vec.sort(); +``` +Use instead: +``` +let mut vec = vec![2, 1, 3]; +vec.sort_unstable(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/std_instead_of_alloc.txt b/src/tools/clippy/src/docs/std_instead_of_alloc.txt new file mode 100644 index 0000000000000..c2d32704e5055 --- /dev/null +++ b/src/tools/clippy/src/docs/std_instead_of_alloc.txt @@ -0,0 +1,18 @@ +### What it does + +Finds items imported through `std` when available through `alloc`. + +### Why is this bad? + +Crates which have `no_std` compatibility and require alloc may wish to ensure types are imported from +alloc to ensure disabling `std` does not cause the crate to fail to compile. This lint is also useful +for crates migrating to become `no_std` compatible. + +### Example +``` +use std::vec::Vec; +``` +Use instead: +``` +use alloc::vec::Vec; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/std_instead_of_core.txt b/src/tools/clippy/src/docs/std_instead_of_core.txt new file mode 100644 index 0000000000000..f1e1518c6a62a --- /dev/null +++ b/src/tools/clippy/src/docs/std_instead_of_core.txt @@ -0,0 +1,18 @@ +### What it does + +Finds items imported through `std` when available through `core`. + +### Why is this bad? + +Crates which have `no_std` compatibility may wish to ensure types are imported from core to ensure +disabling `std` does not cause the crate to fail to compile. This lint is also useful for crates +migrating to become `no_std` compatible. + +### Example +``` +use std::hash::Hasher; +``` +Use instead: +``` +use core::hash::Hasher; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/str_to_string.txt b/src/tools/clippy/src/docs/str_to_string.txt new file mode 100644 index 0000000000000..a24755223747b --- /dev/null +++ b/src/tools/clippy/src/docs/str_to_string.txt @@ -0,0 +1,18 @@ +### What it does +This lint checks for `.to_string()` method calls on values of type `&str`. + +### Why is this bad? +The `to_string` method is also used on other types to convert them to a string. +When called on a `&str` it turns the `&str` into the owned variant `String`, which can be better +expressed with `.to_owned()`. + +### Example +``` +// example code where clippy issues a warning +let _ = "str".to_string(); +``` +Use instead: +``` +// example code which does not raise clippy warning +let _ = "str".to_owned(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/string_add.txt b/src/tools/clippy/src/docs/string_add.txt new file mode 100644 index 0000000000000..23dafd0d0333d --- /dev/null +++ b/src/tools/clippy/src/docs/string_add.txt @@ -0,0 +1,27 @@ +### What it does +Checks for all instances of `x + _` where `x` is of type +`String`, but only if [`string_add_assign`](#string_add_assign) does *not* +match. + +### Why is this bad? +It's not bad in and of itself. However, this particular +`Add` implementation is asymmetric (the other operand need not be `String`, +but `x` does), while addition as mathematically defined is symmetric, also +the `String::push_str(_)` function is a perfectly good replacement. +Therefore, some dislike it and wish not to have it in their code. + +That said, other people think that string addition, having a long tradition +in other languages is actually fine, which is why we decided to make this +particular lint `allow` by default. + +### Example +``` +let x = "Hello".to_owned(); +x + ", World"; +``` + +Use instead: +``` +let mut x = "Hello".to_owned(); +x.push_str(", World"); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/string_add_assign.txt b/src/tools/clippy/src/docs/string_add_assign.txt new file mode 100644 index 0000000000000..7438be855db8c --- /dev/null +++ b/src/tools/clippy/src/docs/string_add_assign.txt @@ -0,0 +1,17 @@ +### What it does +Checks for string appends of the form `x = x + y` (without +`let`!). + +### Why is this bad? +It's not really bad, but some people think that the +`.push_str(_)` method is more readable. + +### Example +``` +let mut x = "Hello".to_owned(); +x = x + ", World"; + +// More readable +x += ", World"; +x.push_str(", World"); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/string_extend_chars.txt b/src/tools/clippy/src/docs/string_extend_chars.txt new file mode 100644 index 0000000000000..619ea3e118673 --- /dev/null +++ b/src/tools/clippy/src/docs/string_extend_chars.txt @@ -0,0 +1,23 @@ +### What it does +Checks for the use of `.extend(s.chars())` where s is a +`&str` or `String`. + +### Why is this bad? +`.push_str(s)` is clearer + +### Example +``` +let abc = "abc"; +let def = String::from("def"); +let mut s = String::new(); +s.extend(abc.chars()); +s.extend(def.chars()); +``` +The correct use would be: +``` +let abc = "abc"; +let def = String::from("def"); +let mut s = String::new(); +s.push_str(abc); +s.push_str(&def); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/string_from_utf8_as_bytes.txt b/src/tools/clippy/src/docs/string_from_utf8_as_bytes.txt new file mode 100644 index 0000000000000..9102d73471cb2 --- /dev/null +++ b/src/tools/clippy/src/docs/string_from_utf8_as_bytes.txt @@ -0,0 +1,15 @@ +### What it does +Check if the string is transformed to byte array and casted back to string. + +### Why is this bad? +It's unnecessary, the string can be used directly. + +### Example +``` +std::str::from_utf8(&"Hello World!".as_bytes()[6..11]).unwrap(); +``` + +Use instead: +``` +&"Hello World!"[6..11]; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/string_lit_as_bytes.txt b/src/tools/clippy/src/docs/string_lit_as_bytes.txt new file mode 100644 index 0000000000000..a125b97ed6567 --- /dev/null +++ b/src/tools/clippy/src/docs/string_lit_as_bytes.txt @@ -0,0 +1,39 @@ +### What it does +Checks for the `as_bytes` method called on string literals +that contain only ASCII characters. + +### Why is this bad? +Byte string literals (e.g., `b"foo"`) can be used +instead. They are shorter but less discoverable than `as_bytes()`. + +### Known problems +`"str".as_bytes()` and the suggested replacement of `b"str"` are not +equivalent because they have different types. The former is `&[u8]` +while the latter is `&[u8; 3]`. That means in general they will have a +different set of methods and different trait implementations. + +``` +fn f(v: Vec) {} + +f("...".as_bytes().to_owned()); // works +f(b"...".to_owned()); // does not work, because arg is [u8; 3] not Vec + +fn g(r: impl std::io::Read) {} + +g("...".as_bytes()); // works +g(b"..."); // does not work +``` + +The actual equivalent of `"str".as_bytes()` with the same type is not +`b"str"` but `&b"str"[..]`, which is a great deal of punctuation and not +more readable than a function call. + +### Example +``` +let bstr = "a byte string".as_bytes(); +``` + +Use instead: +``` +let bstr = b"a byte string"; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/string_slice.txt b/src/tools/clippy/src/docs/string_slice.txt new file mode 100644 index 0000000000000..3d9e49dd39eb7 --- /dev/null +++ b/src/tools/clippy/src/docs/string_slice.txt @@ -0,0 +1,17 @@ +### What it does +Checks for slice operations on strings + +### Why is this bad? +UTF-8 characters span multiple bytes, and it is easy to inadvertently confuse character +counts and string indices. This may lead to panics, and should warrant some test cases +containing wide UTF-8 characters. This lint is most useful in code that should avoid +panics at all costs. + +### Known problems +Probably lots of false positives. If an index comes from a known valid position (e.g. +obtained via `char_indices` over the same string), it is totally OK. + +# Example +``` +&"Ölkanne"[1..]; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/string_to_string.txt b/src/tools/clippy/src/docs/string_to_string.txt new file mode 100644 index 0000000000000..deb7eebe7842c --- /dev/null +++ b/src/tools/clippy/src/docs/string_to_string.txt @@ -0,0 +1,19 @@ +### What it does +This lint checks for `.to_string()` method calls on values of type `String`. + +### Why is this bad? +The `to_string` method is also used on other types to convert them to a string. +When called on a `String` it only clones the `String`, which can be better expressed with `.clone()`. + +### Example +``` +// example code where clippy issues a warning +let msg = String::from("Hello World"); +let _ = msg.to_string(); +``` +Use instead: +``` +// example code which does not raise clippy warning +let msg = String::from("Hello World"); +let _ = msg.clone(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/strlen_on_c_strings.txt b/src/tools/clippy/src/docs/strlen_on_c_strings.txt new file mode 100644 index 0000000000000..0454abf55a204 --- /dev/null +++ b/src/tools/clippy/src/docs/strlen_on_c_strings.txt @@ -0,0 +1,20 @@ +### What it does +Checks for usage of `libc::strlen` on a `CString` or `CStr` value, +and suggest calling `as_bytes().len()` or `to_bytes().len()` respectively instead. + +### Why is this bad? +This avoids calling an unsafe `libc` function. +Currently, it also avoids calculating the length. + +### Example +``` +use std::ffi::CString; +let cstring = CString::new("foo").expect("CString::new failed"); +let len = unsafe { libc::strlen(cstring.as_ptr()) }; +``` +Use instead: +``` +use std::ffi::CString; +let cstring = CString::new("foo").expect("CString::new failed"); +let len = cstring.as_bytes().len(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/struct_excessive_bools.txt b/src/tools/clippy/src/docs/struct_excessive_bools.txt new file mode 100644 index 0000000000000..9e197c786201d --- /dev/null +++ b/src/tools/clippy/src/docs/struct_excessive_bools.txt @@ -0,0 +1,29 @@ +### What it does +Checks for excessive +use of bools in structs. + +### Why is this bad? +Excessive bools in a struct +is often a sign that it's used as a state machine, +which is much better implemented as an enum. +If it's not the case, excessive bools usually benefit +from refactoring into two-variant enums for better +readability and API. + +### Example +``` +struct S { + is_pending: bool, + is_processing: bool, + is_finished: bool, +} +``` + +Use instead: +``` +enum S { + Pending, + Processing, + Finished, +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/suboptimal_flops.txt b/src/tools/clippy/src/docs/suboptimal_flops.txt new file mode 100644 index 0000000000000..f1c9c665b085d --- /dev/null +++ b/src/tools/clippy/src/docs/suboptimal_flops.txt @@ -0,0 +1,50 @@ +### What it does +Looks for floating-point expressions that +can be expressed using built-in methods to improve both +accuracy and performance. + +### Why is this bad? +Negatively impacts accuracy and performance. + +### Example +``` +use std::f32::consts::E; + +let a = 3f32; +let _ = (2f32).powf(a); +let _ = E.powf(a); +let _ = a.powf(1.0 / 2.0); +let _ = a.log(2.0); +let _ = a.log(10.0); +let _ = a.log(E); +let _ = a.powf(2.0); +let _ = a * 2.0 + 4.0; +let _ = if a < 0.0 { + -a +} else { + a +}; +let _ = if a < 0.0 { + a +} else { + -a +}; +``` + +is better expressed as + +``` +use std::f32::consts::E; + +let a = 3f32; +let _ = a.exp2(); +let _ = a.exp(); +let _ = a.sqrt(); +let _ = a.log2(); +let _ = a.log10(); +let _ = a.ln(); +let _ = a.powi(2); +let _ = a.mul_add(2.0, 4.0); +let _ = a.abs(); +let _ = -a.abs(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/suspicious_arithmetic_impl.txt b/src/tools/clippy/src/docs/suspicious_arithmetic_impl.txt new file mode 100644 index 0000000000000..d67ff279346dc --- /dev/null +++ b/src/tools/clippy/src/docs/suspicious_arithmetic_impl.txt @@ -0,0 +1,17 @@ +### What it does +Lints for suspicious operations in impls of arithmetic operators, e.g. +subtracting elements in an Add impl. + +### Why is this bad? +This is probably a typo or copy-and-paste error and not intended. + +### Example +``` +impl Add for Foo { + type Output = Foo; + + fn add(self, other: Foo) -> Foo { + Foo(self.0 - other.0) + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/suspicious_assignment_formatting.txt b/src/tools/clippy/src/docs/suspicious_assignment_formatting.txt new file mode 100644 index 0000000000000..b889827cdf27f --- /dev/null +++ b/src/tools/clippy/src/docs/suspicious_assignment_formatting.txt @@ -0,0 +1,12 @@ +### What it does +Checks for use of the non-existent `=*`, `=!` and `=-` +operators. + +### Why is this bad? +This is either a typo of `*=`, `!=` or `-=` or +confusing. + +### Example +``` +a =- 42; // confusing, should it be `a -= 42` or `a = -42`? +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/suspicious_else_formatting.txt b/src/tools/clippy/src/docs/suspicious_else_formatting.txt new file mode 100644 index 0000000000000..3cf2f74868ebf --- /dev/null +++ b/src/tools/clippy/src/docs/suspicious_else_formatting.txt @@ -0,0 +1,30 @@ +### What it does +Checks for formatting of `else`. It lints if the `else` +is followed immediately by a newline or the `else` seems to be missing. + +### Why is this bad? +This is probably some refactoring remnant, even if the +code is correct, it might look confusing. + +### Example +``` +if foo { +} { // looks like an `else` is missing here +} + +if foo { +} if bar { // looks like an `else` is missing here +} + +if foo { +} else + +{ // this is the `else` block of the previous `if`, but should it be? +} + +if foo { +} else + +if bar { // this is the `else` block of the previous `if`, but should it be? +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/suspicious_map.txt b/src/tools/clippy/src/docs/suspicious_map.txt new file mode 100644 index 0000000000000..d8fa52c43fb0a --- /dev/null +++ b/src/tools/clippy/src/docs/suspicious_map.txt @@ -0,0 +1,13 @@ +### What it does +Checks for calls to `map` followed by a `count`. + +### Why is this bad? +It looks suspicious. Maybe `map` was confused with `filter`. +If the `map` call is intentional, this should be rewritten +using `inspect`. Or, if you intend to drive the iterator to +completion, you can just use `for_each` instead. + +### Example +``` +let _ = (0..3).map(|x| x + 2).count(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/suspicious_op_assign_impl.txt b/src/tools/clippy/src/docs/suspicious_op_assign_impl.txt new file mode 100644 index 0000000000000..81abfbecae073 --- /dev/null +++ b/src/tools/clippy/src/docs/suspicious_op_assign_impl.txt @@ -0,0 +1,15 @@ +### What it does +Lints for suspicious operations in impls of OpAssign, e.g. +subtracting elements in an AddAssign impl. + +### Why is this bad? +This is probably a typo or copy-and-paste error and not intended. + +### Example +``` +impl AddAssign for Foo { + fn add_assign(&mut self, other: Foo) { + *self = *self - other; + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/suspicious_operation_groupings.txt b/src/tools/clippy/src/docs/suspicious_operation_groupings.txt new file mode 100644 index 0000000000000..81ede5d3da575 --- /dev/null +++ b/src/tools/clippy/src/docs/suspicious_operation_groupings.txt @@ -0,0 +1,41 @@ +### What it does +Checks for unlikely usages of binary operators that are almost +certainly typos and/or copy/paste errors, given the other usages +of binary operators nearby. + +### Why is this bad? +They are probably bugs and if they aren't then they look like bugs +and you should add a comment explaining why you are doing such an +odd set of operations. + +### Known problems +There may be some false positives if you are trying to do something +unusual that happens to look like a typo. + +### Example +``` +struct Vec3 { + x: f64, + y: f64, + z: f64, +} + +impl Eq for Vec3 {} + +impl PartialEq for Vec3 { + fn eq(&self, other: &Self) -> bool { + // This should trigger the lint because `self.x` is compared to `other.y` + self.x == other.y && self.y == other.y && self.z == other.z + } +} +``` +Use instead: +``` +// same as above except: +impl PartialEq for Vec3 { + fn eq(&self, other: &Self) -> bool { + // Note we now compare other.x to self.x + self.x == other.x && self.y == other.y && self.z == other.z + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/suspicious_splitn.txt b/src/tools/clippy/src/docs/suspicious_splitn.txt new file mode 100644 index 0000000000000..79a3dbfa6f4a7 --- /dev/null +++ b/src/tools/clippy/src/docs/suspicious_splitn.txt @@ -0,0 +1,22 @@ +### What it does +Checks for calls to [`splitn`] +(https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and +related functions with either zero or one splits. + +### Why is this bad? +These calls don't actually split the value and are +likely to be intended as a different number. + +### Example +``` +for x in s.splitn(1, ":") { + // .. +} +``` + +Use instead: +``` +for x in s.splitn(2, ":") { + // .. +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/suspicious_to_owned.txt b/src/tools/clippy/src/docs/suspicious_to_owned.txt new file mode 100644 index 0000000000000..8cbf61dc7175b --- /dev/null +++ b/src/tools/clippy/src/docs/suspicious_to_owned.txt @@ -0,0 +1,39 @@ +### What it does +Checks for the usage of `_.to_owned()`, on a `Cow<'_, _>`. + +### Why is this bad? +Calling `to_owned()` on a `Cow` creates a clone of the `Cow` +itself, without taking ownership of the `Cow` contents (i.e. +it's equivalent to calling `Cow::clone`). +The similarly named `into_owned` method, on the other hand, +clones the `Cow` contents, effectively turning any `Cow::Borrowed` +into a `Cow::Owned`. + +Given the potential ambiguity, consider replacing `to_owned` +with `clone` for better readability or, if getting a `Cow::Owned` +was the original intent, using `into_owned` instead. + +### Example +``` +let s = "Hello world!"; +let cow = Cow::Borrowed(s); + +let data = cow.to_owned(); +assert!(matches!(data, Cow::Borrowed(_))) +``` +Use instead: +``` +let s = "Hello world!"; +let cow = Cow::Borrowed(s); + +let data = cow.clone(); +assert!(matches!(data, Cow::Borrowed(_))) +``` +or +``` +let s = "Hello world!"; +let cow = Cow::Borrowed(s); + +let data = cow.into_owned(); +assert!(matches!(data, String)) +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/suspicious_unary_op_formatting.txt b/src/tools/clippy/src/docs/suspicious_unary_op_formatting.txt new file mode 100644 index 0000000000000..06fb09db76d0c --- /dev/null +++ b/src/tools/clippy/src/docs/suspicious_unary_op_formatting.txt @@ -0,0 +1,18 @@ +### What it does +Checks the formatting of a unary operator on the right hand side +of a binary operator. It lints if there is no space between the binary and unary operators, +but there is a space between the unary and its operand. + +### Why is this bad? +This is either a typo in the binary operator or confusing. + +### Example +``` +// &&! looks like a different operator +if foo &&! bar {} +``` + +Use instead: +``` +if foo && !bar {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/swap_ptr_to_ref.txt b/src/tools/clippy/src/docs/swap_ptr_to_ref.txt new file mode 100644 index 0000000000000..0215d1e8a4215 --- /dev/null +++ b/src/tools/clippy/src/docs/swap_ptr_to_ref.txt @@ -0,0 +1,23 @@ +### What it does +Checks for calls to `core::mem::swap` where either parameter is derived from a pointer + +### Why is this bad? +When at least one parameter to `swap` is derived from a pointer it may overlap with the +other. This would then lead to undefined behavior. + +### Example +``` +unsafe fn swap(x: &[*mut u32], y: &[*mut u32]) { + for (&x, &y) in x.iter().zip(y) { + core::mem::swap(&mut *x, &mut *y); + } +} +``` +Use instead: +``` +unsafe fn swap(x: &[*mut u32], y: &[*mut u32]) { + for (&x, &y) in x.iter().zip(y) { + core::ptr::swap(x, y); + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/tabs_in_doc_comments.txt b/src/tools/clippy/src/docs/tabs_in_doc_comments.txt new file mode 100644 index 0000000000000..f83dbe2b73cb7 --- /dev/null +++ b/src/tools/clippy/src/docs/tabs_in_doc_comments.txt @@ -0,0 +1,44 @@ +### What it does +Checks doc comments for usage of tab characters. + +### Why is this bad? +The rust style-guide promotes spaces instead of tabs for indentation. +To keep a consistent view on the source, also doc comments should not have tabs. +Also, explaining ascii-diagrams containing tabs can get displayed incorrectly when the +display settings of the author and reader differ. + +### Example +``` +/// +/// Struct to hold two strings: +/// - first one +/// - second one +pub struct DoubleString { + /// + /// - First String: + /// - needs to be inside here + first_string: String, + /// + /// - Second String: + /// - needs to be inside here + second_string: String, +} +``` + +Will be converted to: +``` +/// +/// Struct to hold two strings: +/// - first one +/// - second one +pub struct DoubleString { + /// + /// - First String: + /// - needs to be inside here + first_string: String, + /// + /// - Second String: + /// - needs to be inside here + second_string: String, +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/temporary_assignment.txt b/src/tools/clippy/src/docs/temporary_assignment.txt new file mode 100644 index 0000000000000..195b42cf0d492 --- /dev/null +++ b/src/tools/clippy/src/docs/temporary_assignment.txt @@ -0,0 +1,12 @@ +### What it does +Checks for construction of a structure or tuple just to +assign a value in it. + +### Why is this bad? +Readability. If the structure is only created to be +updated, why not write the structure you want in the first place? + +### Example +``` +(0, 0).0 = 1 +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/to_digit_is_some.txt b/src/tools/clippy/src/docs/to_digit_is_some.txt new file mode 100644 index 0000000000000..eee8375adf7ae --- /dev/null +++ b/src/tools/clippy/src/docs/to_digit_is_some.txt @@ -0,0 +1,15 @@ +### What it does +Checks for `.to_digit(..).is_some()` on `char`s. + +### Why is this bad? +This is a convoluted way of checking if a `char` is a digit. It's +more straight forward to use the dedicated `is_digit` method. + +### Example +``` +let is_digit = c.to_digit(radix).is_some(); +``` +can be written as: +``` +let is_digit = c.is_digit(radix); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/to_string_in_format_args.txt b/src/tools/clippy/src/docs/to_string_in_format_args.txt new file mode 100644 index 0000000000000..34b20583585ad --- /dev/null +++ b/src/tools/clippy/src/docs/to_string_in_format_args.txt @@ -0,0 +1,17 @@ +### What it does +Checks for [`ToString::to_string`](https://doc.rust-lang.org/std/string/trait.ToString.html#tymethod.to_string) +applied to a type that implements [`Display`](https://doc.rust-lang.org/std/fmt/trait.Display.html) +in a macro that does formatting. + +### Why is this bad? +Since the type implements `Display`, the use of `to_string` is +unnecessary. + +### Example +``` +println!("error: something failed at {}", Location::caller().to_string()); +``` +Use instead: +``` +println!("error: something failed at {}", Location::caller()); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/todo.txt b/src/tools/clippy/src/docs/todo.txt new file mode 100644 index 0000000000000..661eb1ac5cff4 --- /dev/null +++ b/src/tools/clippy/src/docs/todo.txt @@ -0,0 +1,10 @@ +### What it does +Checks for usage of `todo!`. + +### Why is this bad? +This macro should not be present in production code + +### Example +``` +todo!(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/too_many_arguments.txt b/src/tools/clippy/src/docs/too_many_arguments.txt new file mode 100644 index 0000000000000..4669f9f82e661 --- /dev/null +++ b/src/tools/clippy/src/docs/too_many_arguments.txt @@ -0,0 +1,14 @@ +### What it does +Checks for functions with too many parameters. + +### Why is this bad? +Functions with lots of parameters are considered bad +style and reduce readability (“what does the 5th parameter mean?”). Consider +grouping some parameters into a new type. + +### Example +``` +fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) { + // .. +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/too_many_lines.txt b/src/tools/clippy/src/docs/too_many_lines.txt new file mode 100644 index 0000000000000..425db348bbd75 --- /dev/null +++ b/src/tools/clippy/src/docs/too_many_lines.txt @@ -0,0 +1,17 @@ +### What it does +Checks for functions with a large amount of lines. + +### Why is this bad? +Functions with a lot of lines are harder to understand +due to having to look at a larger amount of code to understand what the +function is doing. Consider splitting the body of the function into +multiple functions. + +### Example +``` +fn im_too_long() { + println!(""); + // ... 100 more LoC + println!(""); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/toplevel_ref_arg.txt b/src/tools/clippy/src/docs/toplevel_ref_arg.txt new file mode 100644 index 0000000000000..96a9e2db8b7e7 --- /dev/null +++ b/src/tools/clippy/src/docs/toplevel_ref_arg.txt @@ -0,0 +1,28 @@ +### What it does +Checks for function arguments and let bindings denoted as +`ref`. + +### Why is this bad? +The `ref` declaration makes the function take an owned +value, but turns the argument into a reference (which means that the value +is destroyed when exiting the function). This adds not much value: either +take a reference type, or take an owned value and create references in the +body. + +For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The +type of `x` is more obvious with the former. + +### Known problems +If the argument is dereferenced within the function, +removing the `ref` will lead to errors. This can be fixed by removing the +dereferences, e.g., changing `*x` to `x` within the function. + +### Example +``` +fn foo(ref _x: u8) {} +``` + +Use instead: +``` +fn foo(_x: &u8) {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/trailing_empty_array.txt b/src/tools/clippy/src/docs/trailing_empty_array.txt new file mode 100644 index 0000000000000..db1908cc96d03 --- /dev/null +++ b/src/tools/clippy/src/docs/trailing_empty_array.txt @@ -0,0 +1,22 @@ +### What it does +Displays a warning when a struct with a trailing zero-sized array is declared without a `repr` attribute. + +### Why is this bad? +Zero-sized arrays aren't very useful in Rust itself, so such a struct is likely being created to pass to C code or in some other situation where control over memory layout matters (for example, in conjunction with manual allocation to make it easy to compute the offset of the array). Either way, `#[repr(C)]` (or another `repr` attribute) is needed. + +### Example +``` +struct RarelyUseful { + some_field: u32, + last: [u32; 0], +} +``` + +Use instead: +``` +#[repr(C)] +struct MoreOftenUseful { + some_field: usize, + last: [u32; 0], +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/trait_duplication_in_bounds.txt b/src/tools/clippy/src/docs/trait_duplication_in_bounds.txt new file mode 100644 index 0000000000000..509736bb36444 --- /dev/null +++ b/src/tools/clippy/src/docs/trait_duplication_in_bounds.txt @@ -0,0 +1,37 @@ +### What it does +Checks for cases where generics are being used and multiple +syntax specifications for trait bounds are used simultaneously. + +### Why is this bad? +Duplicate bounds makes the code +less readable than specifying them only once. + +### Example +``` +fn func(arg: T) where T: Clone + Default {} +``` + +Use instead: +``` +fn func(arg: T) {} + +// or + +fn func(arg: T) where T: Clone + Default {} +``` + +``` +fn foo(bar: T) {} +``` +Use instead: +``` +fn foo(bar: T) {} +``` + +``` +fn foo(bar: T) where T: Default + Default {} +``` +Use instead: +``` +fn foo(bar: T) where T: Default {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/transmute_bytes_to_str.txt b/src/tools/clippy/src/docs/transmute_bytes_to_str.txt new file mode 100644 index 0000000000000..75889b9c73ae3 --- /dev/null +++ b/src/tools/clippy/src/docs/transmute_bytes_to_str.txt @@ -0,0 +1,27 @@ +### What it does +Checks for transmutes from a `&[u8]` to a `&str`. + +### Why is this bad? +Not every byte slice is a valid UTF-8 string. + +### Known problems +- [`from_utf8`] which this lint suggests using is slower than `transmute` +as it needs to validate the input. +If you are certain that the input is always a valid UTF-8, +use [`from_utf8_unchecked`] which is as fast as `transmute` +but has a semantically meaningful name. +- You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`. + +[`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html +[`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html + +### Example +``` +let b: &[u8] = &[1_u8, 2_u8]; +unsafe { + let _: &str = std::mem::transmute(b); // where b: &[u8] +} + +// should be: +let _ = std::str::from_utf8(b).unwrap(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/transmute_float_to_int.txt b/src/tools/clippy/src/docs/transmute_float_to_int.txt new file mode 100644 index 0000000000000..1877e5a465a4e --- /dev/null +++ b/src/tools/clippy/src/docs/transmute_float_to_int.txt @@ -0,0 +1,16 @@ +### What it does +Checks for transmutes from a float to an integer. + +### Why is this bad? +Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive +and safe. + +### Example +``` +unsafe { + let _: u32 = std::mem::transmute(1f32); +} + +// should be: +let _: u32 = 1f32.to_bits(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/transmute_int_to_bool.txt b/src/tools/clippy/src/docs/transmute_int_to_bool.txt new file mode 100644 index 0000000000000..07c10f8d0bca7 --- /dev/null +++ b/src/tools/clippy/src/docs/transmute_int_to_bool.txt @@ -0,0 +1,16 @@ +### What it does +Checks for transmutes from an integer to a `bool`. + +### Why is this bad? +This might result in an invalid in-memory representation of a `bool`. + +### Example +``` +let x = 1_u8; +unsafe { + let _: bool = std::mem::transmute(x); // where x: u8 +} + +// should be: +let _: bool = x != 0; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/transmute_int_to_char.txt b/src/tools/clippy/src/docs/transmute_int_to_char.txt new file mode 100644 index 0000000000000..836d22d3f99c0 --- /dev/null +++ b/src/tools/clippy/src/docs/transmute_int_to_char.txt @@ -0,0 +1,27 @@ +### What it does +Checks for transmutes from an integer to a `char`. + +### Why is this bad? +Not every integer is a Unicode scalar value. + +### Known problems +- [`from_u32`] which this lint suggests using is slower than `transmute` +as it needs to validate the input. +If you are certain that the input is always a valid Unicode scalar value, +use [`from_u32_unchecked`] which is as fast as `transmute` +but has a semantically meaningful name. +- You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`. + +[`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html +[`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html + +### Example +``` +let x = 1_u32; +unsafe { + let _: char = std::mem::transmute(x); // where x: u32 +} + +// should be: +let _ = std::char::from_u32(x).unwrap(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/transmute_int_to_float.txt b/src/tools/clippy/src/docs/transmute_int_to_float.txt new file mode 100644 index 0000000000000..75cdc62e97275 --- /dev/null +++ b/src/tools/clippy/src/docs/transmute_int_to_float.txt @@ -0,0 +1,16 @@ +### What it does +Checks for transmutes from an integer to a float. + +### Why is this bad? +Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive +and safe. + +### Example +``` +unsafe { + let _: f32 = std::mem::transmute(1_u32); // where x: u32 +} + +// should be: +let _: f32 = f32::from_bits(1_u32); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/transmute_num_to_bytes.txt b/src/tools/clippy/src/docs/transmute_num_to_bytes.txt new file mode 100644 index 0000000000000..a2c39a1b947e3 --- /dev/null +++ b/src/tools/clippy/src/docs/transmute_num_to_bytes.txt @@ -0,0 +1,16 @@ +### What it does +Checks for transmutes from a number to an array of `u8` + +### Why this is bad? +Transmutes are dangerous and error-prone, whereas `to_ne_bytes` +is intuitive and safe. + +### Example +``` +unsafe { + let x: [u8; 8] = std::mem::transmute(1i64); +} + +// should be +let x: [u8; 8] = 0i64.to_ne_bytes(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/transmute_ptr_to_ptr.txt b/src/tools/clippy/src/docs/transmute_ptr_to_ptr.txt new file mode 100644 index 0000000000000..65777db986186 --- /dev/null +++ b/src/tools/clippy/src/docs/transmute_ptr_to_ptr.txt @@ -0,0 +1,21 @@ +### What it does +Checks for transmutes from a pointer to a pointer, or +from a reference to a reference. + +### Why is this bad? +Transmutes are dangerous, and these can instead be +written as casts. + +### Example +``` +let ptr = &1u32 as *const u32; +unsafe { + // pointer-to-pointer transmute + let _: *const f32 = std::mem::transmute(ptr); + // ref-ref transmute + let _: &f32 = std::mem::transmute(&1u32); +} +// These can be respectively written: +let _ = ptr as *const f32; +let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) }; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/transmute_ptr_to_ref.txt b/src/tools/clippy/src/docs/transmute_ptr_to_ref.txt new file mode 100644 index 0000000000000..aca550f5036ec --- /dev/null +++ b/src/tools/clippy/src/docs/transmute_ptr_to_ref.txt @@ -0,0 +1,21 @@ +### What it does +Checks for transmutes from a pointer to a reference. + +### Why is this bad? +This can always be rewritten with `&` and `*`. + +### Known problems +- `mem::transmute` in statics and constants is stable from Rust 1.46.0, +while dereferencing raw pointer is not stable yet. +If you need to do this in those places, +you would have to use `transmute` instead. + +### Example +``` +unsafe { + let _: &T = std::mem::transmute(p); // where p: *const T +} + +// can be written: +let _: &T = &*p; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/transmute_undefined_repr.txt b/src/tools/clippy/src/docs/transmute_undefined_repr.txt new file mode 100644 index 0000000000000..5ee6aaf4ca92c --- /dev/null +++ b/src/tools/clippy/src/docs/transmute_undefined_repr.txt @@ -0,0 +1,22 @@ +### What it does +Checks for transmutes between types which do not have a representation defined relative to +each other. + +### Why is this bad? +The results of such a transmute are not defined. + +### Known problems +This lint has had multiple problems in the past and was moved to `nursery`. See issue +[#8496](https://github.com/rust-lang/rust-clippy/issues/8496) for more details. + +### Example +``` +struct Foo(u32, T); +let _ = unsafe { core::mem::transmute::, Foo>(Foo(0u32, 0u32)) }; +``` +Use instead: +``` +#[repr(C)] +struct Foo(u32, T); +let _ = unsafe { core::mem::transmute::, Foo>(Foo(0u32, 0u32)) }; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/transmutes_expressible_as_ptr_casts.txt b/src/tools/clippy/src/docs/transmutes_expressible_as_ptr_casts.txt new file mode 100644 index 0000000000000..b68a8cda9c74b --- /dev/null +++ b/src/tools/clippy/src/docs/transmutes_expressible_as_ptr_casts.txt @@ -0,0 +1,16 @@ +### What it does +Checks for transmutes that could be a pointer cast. + +### Why is this bad? +Readability. The code tricks people into thinking that +something complex is going on. + +### Example + +``` +unsafe { std::mem::transmute::<*const [i32], *const [u16]>(p) }; +``` +Use instead: +``` +p as *const [u16]; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/transmuting_null.txt b/src/tools/clippy/src/docs/transmuting_null.txt new file mode 100644 index 0000000000000..f8bacfc0b90b4 --- /dev/null +++ b/src/tools/clippy/src/docs/transmuting_null.txt @@ -0,0 +1,15 @@ +### What it does +Checks for transmute calls which would receive a null pointer. + +### Why is this bad? +Transmuting a null pointer is undefined behavior. + +### Known problems +Not all cases can be detected at the moment of this writing. +For example, variables which hold a null pointer and are then fed to a `transmute` +call, aren't detectable yet. + +### Example +``` +let null_ref: &u64 = unsafe { std::mem::transmute(0 as *const u64) }; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/trim_split_whitespace.txt b/src/tools/clippy/src/docs/trim_split_whitespace.txt new file mode 100644 index 0000000000000..f7e3e7858f949 --- /dev/null +++ b/src/tools/clippy/src/docs/trim_split_whitespace.txt @@ -0,0 +1,14 @@ +### What it does +Warns about calling `str::trim` (or variants) before `str::split_whitespace`. + +### Why is this bad? +`split_whitespace` already ignores leading and trailing whitespace. + +### Example +``` +" A B C ".trim().split_whitespace(); +``` +Use instead: +``` +" A B C ".split_whitespace(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/trivial_regex.txt b/src/tools/clippy/src/docs/trivial_regex.txt new file mode 100644 index 0000000000000..f71d667fd7711 --- /dev/null +++ b/src/tools/clippy/src/docs/trivial_regex.txt @@ -0,0 +1,18 @@ +### What it does +Checks for trivial [regex](https://crates.io/crates/regex) +creation (with `Regex::new`, `RegexBuilder::new`, or `RegexSet::new`). + +### Why is this bad? +Matching the regex can likely be replaced by `==` or +`str::starts_with`, `str::ends_with` or `std::contains` or other `str` +methods. + +### Known problems +If the same regex is going to be applied to multiple +inputs, the precomputations done by `Regex` construction can give +significantly better performance than any of the `str`-based methods. + +### Example +``` +Regex::new("^foobar") +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/trivially_copy_pass_by_ref.txt b/src/tools/clippy/src/docs/trivially_copy_pass_by_ref.txt new file mode 100644 index 0000000000000..f54cce5e2bd76 --- /dev/null +++ b/src/tools/clippy/src/docs/trivially_copy_pass_by_ref.txt @@ -0,0 +1,43 @@ +### What it does +Checks for functions taking arguments by reference, where +the argument type is `Copy` and small enough to be more efficient to always +pass by value. + +### Why is this bad? +In many calling conventions instances of structs will +be passed through registers if they fit into two or less general purpose +registers. + +### Known problems +This lint is target register size dependent, it is +limited to 32-bit to try and reduce portability problems between 32 and +64-bit, but if you are compiling for 8 or 16-bit targets then the limit +will be different. + +The configuration option `trivial_copy_size_limit` can be set to override +this limit for a project. + +This lint attempts to allow passing arguments by reference if a reference +to that argument is returned. This is implemented by comparing the lifetime +of the argument and return value for equality. However, this can cause +false positives in cases involving multiple lifetimes that are bounded by +each other. + +Also, it does not take account of other similar cases where getting memory addresses +matters; namely, returning the pointer to the argument in question, +and passing the argument, as both references and pointers, +to a function that needs the memory address. For further details, refer to +[this issue](https://github.com/rust-lang/rust-clippy/issues/5953) +that explains a real case in which this false positive +led to an **undefined behavior** introduced with unsafe code. + +### Example + +``` +fn foo(v: &u32) {} +``` + +Use instead: +``` +fn foo(v: u32) {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/try_err.txt b/src/tools/clippy/src/docs/try_err.txt new file mode 100644 index 0000000000000..e3d4ef3a09df1 --- /dev/null +++ b/src/tools/clippy/src/docs/try_err.txt @@ -0,0 +1,28 @@ +### What it does +Checks for usages of `Err(x)?`. + +### Why is this bad? +The `?` operator is designed to allow calls that +can fail to be easily chained. For example, `foo()?.bar()` or +`foo(bar()?)`. Because `Err(x)?` can't be used that way (it will +always return), it is more clear to write `return Err(x)`. + +### Example +``` +fn foo(fail: bool) -> Result { + if fail { + Err("failed")?; + } + Ok(0) +} +``` +Could be written: + +``` +fn foo(fail: bool) -> Result { + if fail { + return Err("failed".into()); + } + Ok(0) +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/type_complexity.txt b/src/tools/clippy/src/docs/type_complexity.txt new file mode 100644 index 0000000000000..69cd875005043 --- /dev/null +++ b/src/tools/clippy/src/docs/type_complexity.txt @@ -0,0 +1,14 @@ +### What it does +Checks for types used in structs, parameters and `let` +declarations above a certain complexity threshold. + +### Why is this bad? +Too complex types make the code less readable. Consider +using a `type` definition to simplify them. + +### Example +``` +struct Foo { + inner: Rc>>>, +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/type_repetition_in_bounds.txt b/src/tools/clippy/src/docs/type_repetition_in_bounds.txt new file mode 100644 index 0000000000000..18ed372fd13e3 --- /dev/null +++ b/src/tools/clippy/src/docs/type_repetition_in_bounds.txt @@ -0,0 +1,16 @@ +### What it does +This lint warns about unnecessary type repetitions in trait bounds + +### Why is this bad? +Repeating the type for every bound makes the code +less readable than combining the bounds + +### Example +``` +pub fn foo(t: T) where T: Copy, T: Clone {} +``` + +Use instead: +``` +pub fn foo(t: T) where T: Copy + Clone {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/undocumented_unsafe_blocks.txt b/src/tools/clippy/src/docs/undocumented_unsafe_blocks.txt new file mode 100644 index 0000000000000..f3af4753c5f75 --- /dev/null +++ b/src/tools/clippy/src/docs/undocumented_unsafe_blocks.txt @@ -0,0 +1,43 @@ +### What it does +Checks for `unsafe` blocks and impls without a `// SAFETY: ` comment +explaining why the unsafe operations performed inside +the block are safe. + +Note the comment must appear on the line(s) preceding the unsafe block +with nothing appearing in between. The following is ok: +``` +foo( + // SAFETY: + // This is a valid safety comment + unsafe { *x } +) +``` +But neither of these are: +``` +// SAFETY: +// This is not a valid safety comment +foo( + /* SAFETY: Neither is this */ unsafe { *x }, +); +``` + +### Why is this bad? +Undocumented unsafe blocks and impls can make it difficult to +read and maintain code, as well as uncover unsoundness +and bugs. + +### Example +``` +use std::ptr::NonNull; +let a = &mut 42; + +let ptr = unsafe { NonNull::new_unchecked(a) }; +``` +Use instead: +``` +use std::ptr::NonNull; +let a = &mut 42; + +// SAFETY: references are guaranteed to be non-null. +let ptr = unsafe { NonNull::new_unchecked(a) }; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/undropped_manually_drops.txt b/src/tools/clippy/src/docs/undropped_manually_drops.txt new file mode 100644 index 0000000000000..85e3ec56653c9 --- /dev/null +++ b/src/tools/clippy/src/docs/undropped_manually_drops.txt @@ -0,0 +1,22 @@ +### What it does +Prevents the safe `std::mem::drop` function from being called on `std::mem::ManuallyDrop`. + +### Why is this bad? +The safe `drop` function does not drop the inner value of a `ManuallyDrop`. + +### Known problems +Does not catch cases if the user binds `std::mem::drop` +to a different name and calls it that way. + +### Example +``` +struct S; +drop(std::mem::ManuallyDrop::new(S)); +``` +Use instead: +``` +struct S; +unsafe { + std::mem::ManuallyDrop::drop(&mut std::mem::ManuallyDrop::new(S)); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unicode_not_nfc.txt b/src/tools/clippy/src/docs/unicode_not_nfc.txt new file mode 100644 index 0000000000000..c660c51dadb26 --- /dev/null +++ b/src/tools/clippy/src/docs/unicode_not_nfc.txt @@ -0,0 +1,12 @@ +### What it does +Checks for string literals that contain Unicode in a form +that is not equal to its +[NFC-recomposition](http://www.unicode.org/reports/tr15/#Norm_Forms). + +### Why is this bad? +If such a string is compared to another, the results +may be surprising. + +### Example +You may not see it, but "à"" and "à"" aren't the same string. The +former when escaped is actually `"a\u{300}"` while the latter is `"\u{e0}"`. \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unimplemented.txt b/src/tools/clippy/src/docs/unimplemented.txt new file mode 100644 index 0000000000000..7095594fb2e73 --- /dev/null +++ b/src/tools/clippy/src/docs/unimplemented.txt @@ -0,0 +1,10 @@ +### What it does +Checks for usage of `unimplemented!`. + +### Why is this bad? +This macro should not be present in production code + +### Example +``` +unimplemented!(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/uninit_assumed_init.txt b/src/tools/clippy/src/docs/uninit_assumed_init.txt new file mode 100644 index 0000000000000..cca24093d40df --- /dev/null +++ b/src/tools/clippy/src/docs/uninit_assumed_init.txt @@ -0,0 +1,28 @@ +### What it does +Checks for `MaybeUninit::uninit().assume_init()`. + +### Why is this bad? +For most types, this is undefined behavior. + +### Known problems +For now, we accept empty tuples and tuples / arrays +of `MaybeUninit`. There may be other types that allow uninitialized +data, but those are not yet rigorously defined. + +### Example +``` +// Beware the UB +use std::mem::MaybeUninit; + +let _: usize = unsafe { MaybeUninit::uninit().assume_init() }; +``` + +Note that the following is OK: + +``` +use std::mem::MaybeUninit; + +let _: [MaybeUninit; 5] = unsafe { + MaybeUninit::uninit().assume_init() +}; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/uninit_vec.txt b/src/tools/clippy/src/docs/uninit_vec.txt new file mode 100644 index 0000000000000..cd50afe78f6f2 --- /dev/null +++ b/src/tools/clippy/src/docs/uninit_vec.txt @@ -0,0 +1,41 @@ +### What it does +Checks for `set_len()` call that creates `Vec` with uninitialized elements. +This is commonly caused by calling `set_len()` right after allocating or +reserving a buffer with `new()`, `default()`, `with_capacity()`, or `reserve()`. + +### Why is this bad? +It creates a `Vec` with uninitialized data, which leads to +undefined behavior with most safe operations. Notably, uninitialized +`Vec` must not be used with generic `Read`. + +Moreover, calling `set_len()` on a `Vec` created with `new()` or `default()` +creates out-of-bound values that lead to heap memory corruption when used. + +### Known Problems +This lint only checks directly adjacent statements. + +### Example +``` +let mut vec: Vec = Vec::with_capacity(1000); +unsafe { vec.set_len(1000); } +reader.read(&mut vec); // undefined behavior! +``` + +### How to fix? +1. Use an initialized buffer: + ```rust,ignore + let mut vec: Vec = vec![0; 1000]; + reader.read(&mut vec); + ``` +2. Wrap the content in `MaybeUninit`: + ```rust,ignore + let mut vec: Vec> = Vec::with_capacity(1000); + vec.set_len(1000); // `MaybeUninit` can be uninitialized + ``` +3. If you are on 1.60.0 or later, `Vec::spare_capacity_mut()` is available: + ```rust,ignore + let mut vec: Vec = Vec::with_capacity(1000); + let remaining = vec.spare_capacity_mut(); // `&mut [MaybeUninit]` + // perform initialization with `remaining` + vec.set_len(...); // Safe to call `set_len()` on initialized part + ``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unit_arg.txt b/src/tools/clippy/src/docs/unit_arg.txt new file mode 100644 index 0000000000000..eb83403bb275c --- /dev/null +++ b/src/tools/clippy/src/docs/unit_arg.txt @@ -0,0 +1,14 @@ +### What it does +Checks for passing a unit value as an argument to a function without using a +unit literal (`()`). + +### Why is this bad? +This is likely the result of an accidental semicolon. + +### Example +``` +foo({ + let a = bar(); + baz(a); +}) +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unit_cmp.txt b/src/tools/clippy/src/docs/unit_cmp.txt new file mode 100644 index 0000000000000..6f3d62010dc51 --- /dev/null +++ b/src/tools/clippy/src/docs/unit_cmp.txt @@ -0,0 +1,33 @@ +### What it does +Checks for comparisons to unit. This includes all binary +comparisons (like `==` and `<`) and asserts. + +### Why is this bad? +Unit is always equal to itself, and thus is just a +clumsily written constant. Mostly this happens when someone accidentally +adds semicolons at the end of the operands. + +### Example +``` +if { + foo(); +} == { + bar(); +} { + baz(); +} +``` +is equal to +``` +{ + foo(); + bar(); + baz(); +} +``` + +For asserts: +``` +assert_eq!({ foo(); }, { bar(); }); +``` +will always succeed \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unit_hash.txt b/src/tools/clippy/src/docs/unit_hash.txt new file mode 100644 index 0000000000000..a22d2994602ac --- /dev/null +++ b/src/tools/clippy/src/docs/unit_hash.txt @@ -0,0 +1,20 @@ +### What it does +Detects `().hash(_)`. + +### Why is this bad? +Hashing a unit value doesn't do anything as the implementation of `Hash` for `()` is a no-op. + +### Example +``` +match my_enum { + Empty => ().hash(&mut state), + WithValue(x) => x.hash(&mut state), +} +``` +Use instead: +``` +match my_enum { + Empty => 0_u8.hash(&mut state), + WithValue(x) => x.hash(&mut state), +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unit_return_expecting_ord.txt b/src/tools/clippy/src/docs/unit_return_expecting_ord.txt new file mode 100644 index 0000000000000..781feac5afcfc --- /dev/null +++ b/src/tools/clippy/src/docs/unit_return_expecting_ord.txt @@ -0,0 +1,20 @@ +### What it does +Checks for functions that expect closures of type +Fn(...) -> Ord where the implemented closure returns the unit type. +The lint also suggests to remove the semi-colon at the end of the statement if present. + +### Why is this bad? +Likely, returning the unit type is unintentional, and +could simply be caused by an extra semi-colon. Since () implements Ord +it doesn't cause a compilation error. +This is the same reasoning behind the unit_cmp lint. + +### Known problems +If returning unit is intentional, then there is no +way of specifying this without triggering needless_return lint + +### Example +``` +let mut twins = vec!((1, 1), (2, 2)); +twins.sort_by_key(|x| { x.1; }); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unnecessary_cast.txt b/src/tools/clippy/src/docs/unnecessary_cast.txt new file mode 100644 index 0000000000000..603f2606099c8 --- /dev/null +++ b/src/tools/clippy/src/docs/unnecessary_cast.txt @@ -0,0 +1,19 @@ +### What it does +Checks for casts to the same type, casts of int literals to integer types +and casts of float literals to float types. + +### Why is this bad? +It's just unnecessary. + +### Example +``` +let _ = 2i32 as i32; +let _ = 0.5 as f32; +``` + +Better: + +``` +let _ = 2_i32; +let _ = 0.5_f32; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unnecessary_filter_map.txt b/src/tools/clippy/src/docs/unnecessary_filter_map.txt new file mode 100644 index 0000000000000..b19341ecf660e --- /dev/null +++ b/src/tools/clippy/src/docs/unnecessary_filter_map.txt @@ -0,0 +1,23 @@ +### What it does +Checks for `filter_map` calls that could be replaced by `filter` or `map`. +More specifically it checks if the closure provided is only performing one of the +filter or map operations and suggests the appropriate option. + +### Why is this bad? +Complexity. The intent is also clearer if only a single +operation is being performed. + +### Example +``` +let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None }); + +// As there is no transformation of the argument this could be written as: +let _ = (0..3).filter(|&x| x > 2); +``` + +``` +let _ = (0..4).filter_map(|x| Some(x + 1)); + +// As there is no conditional check on the argument this could be written as: +let _ = (0..4).map(|x| x + 1); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unnecessary_find_map.txt b/src/tools/clippy/src/docs/unnecessary_find_map.txt new file mode 100644 index 0000000000000..f9444dc48ad6a --- /dev/null +++ b/src/tools/clippy/src/docs/unnecessary_find_map.txt @@ -0,0 +1,23 @@ +### What it does +Checks for `find_map` calls that could be replaced by `find` or `map`. More +specifically it checks if the closure provided is only performing one of the +find or map operations and suggests the appropriate option. + +### Why is this bad? +Complexity. The intent is also clearer if only a single +operation is being performed. + +### Example +``` +let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None }); + +// As there is no transformation of the argument this could be written as: +let _ = (0..3).find(|&x| x > 2); +``` + +``` +let _ = (0..4).find_map(|x| Some(x + 1)); + +// As there is no conditional check on the argument this could be written as: +let _ = (0..4).map(|x| x + 1).next(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unnecessary_fold.txt b/src/tools/clippy/src/docs/unnecessary_fold.txt new file mode 100644 index 0000000000000..e1b0e65f51971 --- /dev/null +++ b/src/tools/clippy/src/docs/unnecessary_fold.txt @@ -0,0 +1,17 @@ +### What it does +Checks for using `fold` when a more succinct alternative exists. +Specifically, this checks for `fold`s which could be replaced by `any`, `all`, +`sum` or `product`. + +### Why is this bad? +Readability. + +### Example +``` +(0..3).fold(false, |acc, x| acc || x > 2); +``` + +Use instead: +``` +(0..3).any(|x| x > 2); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unnecessary_join.txt b/src/tools/clippy/src/docs/unnecessary_join.txt new file mode 100644 index 0000000000000..ee4e78601f847 --- /dev/null +++ b/src/tools/clippy/src/docs/unnecessary_join.txt @@ -0,0 +1,25 @@ +### What it does +Checks for use of `.collect::>().join("")` on iterators. + +### Why is this bad? +`.collect::()` is more concise and might be more performant + +### Example +``` +let vector = vec!["hello", "world"]; +let output = vector.iter().map(|item| item.to_uppercase()).collect::>().join(""); +println!("{}", output); +``` +The correct use would be: +``` +let vector = vec!["hello", "world"]; +let output = vector.iter().map(|item| item.to_uppercase()).collect::(); +println!("{}", output); +``` +### Known problems +While `.collect::()` is sometimes more performant, there are cases where +using `.collect::()` over `.collect::>().join("")` +will prevent loop unrolling and will result in a negative performance impact. + +Additionally, differences have been observed between aarch64 and x86_64 assembly output, +with aarch64 tending to producing faster assembly in more cases when using `.collect::()` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unnecessary_lazy_evaluations.txt b/src/tools/clippy/src/docs/unnecessary_lazy_evaluations.txt new file mode 100644 index 0000000000000..208188ce971a5 --- /dev/null +++ b/src/tools/clippy/src/docs/unnecessary_lazy_evaluations.txt @@ -0,0 +1,32 @@ +### What it does +As the counterpart to `or_fun_call`, this lint looks for unnecessary +lazily evaluated closures on `Option` and `Result`. + +This lint suggests changing the following functions, when eager evaluation results in +simpler code: + - `unwrap_or_else` to `unwrap_or` + - `and_then` to `and` + - `or_else` to `or` + - `get_or_insert_with` to `get_or_insert` + - `ok_or_else` to `ok_or` + +### Why is this bad? +Using eager evaluation is shorter and simpler in some cases. + +### Known problems +It is possible, but not recommended for `Deref` and `Index` to have +side effects. Eagerly evaluating them can change the semantics of the program. + +### Example +``` +// example code where clippy issues a warning +let opt: Option = None; + +opt.unwrap_or_else(|| 42); +``` +Use instead: +``` +let opt: Option = None; + +opt.unwrap_or(42); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unnecessary_mut_passed.txt b/src/tools/clippy/src/docs/unnecessary_mut_passed.txt new file mode 100644 index 0000000000000..2f8bdd113dfdb --- /dev/null +++ b/src/tools/clippy/src/docs/unnecessary_mut_passed.txt @@ -0,0 +1,17 @@ +### What it does +Detects passing a mutable reference to a function that only +requires an immutable reference. + +### Why is this bad? +The mutable reference rules out all other references to +the value. Also the code misleads about the intent of the call site. + +### Example +``` +vec.push(&mut value); +``` + +Use instead: +``` +vec.push(&value); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unnecessary_operation.txt b/src/tools/clippy/src/docs/unnecessary_operation.txt new file mode 100644 index 0000000000000..7f455e264cb30 --- /dev/null +++ b/src/tools/clippy/src/docs/unnecessary_operation.txt @@ -0,0 +1,12 @@ +### What it does +Checks for expression statements that can be reduced to a +sub-expression. + +### Why is this bad? +Expressions by themselves often have no side-effects. +Having such expressions reduces readability. + +### Example +``` +compute_array()[0]; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unnecessary_owned_empty_strings.txt b/src/tools/clippy/src/docs/unnecessary_owned_empty_strings.txt new file mode 100644 index 0000000000000..8cd9fba603e06 --- /dev/null +++ b/src/tools/clippy/src/docs/unnecessary_owned_empty_strings.txt @@ -0,0 +1,16 @@ +### What it does + +Detects cases of owned empty strings being passed as an argument to a function expecting `&str` + +### Why is this bad? + +This results in longer and less readable code + +### Example +``` +vec!["1", "2", "3"].join(&String::new()); +``` +Use instead: +``` +vec!["1", "2", "3"].join(""); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unnecessary_self_imports.txt b/src/tools/clippy/src/docs/unnecessary_self_imports.txt new file mode 100644 index 0000000000000..b909cd5a76dae --- /dev/null +++ b/src/tools/clippy/src/docs/unnecessary_self_imports.txt @@ -0,0 +1,19 @@ +### What it does +Checks for imports ending in `::{self}`. + +### Why is this bad? +In most cases, this can be written much more cleanly by omitting `::{self}`. + +### Known problems +Removing `::{self}` will cause any non-module items at the same path to also be imported. +This might cause a naming conflict (https://github.com/rust-lang/rustfmt/issues/3568). This lint makes no attempt +to detect this scenario and that is why it is a restriction lint. + +### Example +``` +use std::io::{self}; +``` +Use instead: +``` +use std::io; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unnecessary_sort_by.txt b/src/tools/clippy/src/docs/unnecessary_sort_by.txt new file mode 100644 index 0000000000000..6913b62c48eb4 --- /dev/null +++ b/src/tools/clippy/src/docs/unnecessary_sort_by.txt @@ -0,0 +1,21 @@ +### What it does +Detects uses of `Vec::sort_by` passing in a closure +which compares the two arguments, either directly or indirectly. + +### Why is this bad? +It is more clear to use `Vec::sort_by_key` (or `Vec::sort` if +possible) than to use `Vec::sort_by` and a more complicated +closure. + +### Known problems +If the suggested `Vec::sort_by_key` uses Reverse and it isn't already +imported by a use statement, then it will need to be added manually. + +### Example +``` +vec.sort_by(|a, b| a.foo().cmp(&b.foo())); +``` +Use instead: +``` +vec.sort_by_key(|a| a.foo()); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unnecessary_to_owned.txt b/src/tools/clippy/src/docs/unnecessary_to_owned.txt new file mode 100644 index 0000000000000..5d4213bdaf899 --- /dev/null +++ b/src/tools/clippy/src/docs/unnecessary_to_owned.txt @@ -0,0 +1,24 @@ +### What it does +Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned) +and other `to_owned`-like functions. + +### Why is this bad? +The unnecessary calls result in useless allocations. + +### Known problems +`unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an +owned copy of a resource and the resource is later used mutably. See +[#8148](https://github.com/rust-lang/rust-clippy/issues/8148). + +### Example +``` +let path = std::path::Path::new("x"); +foo(&path.to_string_lossy().to_string()); +fn foo(s: &str) {} +``` +Use instead: +``` +let path = std::path::Path::new("x"); +foo(&path.to_string_lossy()); +fn foo(s: &str) {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unnecessary_unwrap.txt b/src/tools/clippy/src/docs/unnecessary_unwrap.txt new file mode 100644 index 0000000000000..50ae845bb44f7 --- /dev/null +++ b/src/tools/clippy/src/docs/unnecessary_unwrap.txt @@ -0,0 +1,20 @@ +### What it does +Checks for calls of `unwrap[_err]()` that cannot fail. + +### Why is this bad? +Using `if let` or `match` is more idiomatic. + +### Example +``` +if option.is_some() { + do_something_with(option.unwrap()) +} +``` + +Could be written: + +``` +if let Some(value) = option { + do_something_with(value) +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unnecessary_wraps.txt b/src/tools/clippy/src/docs/unnecessary_wraps.txt new file mode 100644 index 0000000000000..c0a23d492889a --- /dev/null +++ b/src/tools/clippy/src/docs/unnecessary_wraps.txt @@ -0,0 +1,36 @@ +### What it does +Checks for private functions that only return `Ok` or `Some`. + +### Why is this bad? +It is not meaningful to wrap values when no `None` or `Err` is returned. + +### Known problems +There can be false positives if the function signature is designed to +fit some external requirement. + +### Example +``` +fn get_cool_number(a: bool, b: bool) -> Option { + if a && b { + return Some(50); + } + if a { + Some(0) + } else { + Some(10) + } +} +``` +Use instead: +``` +fn get_cool_number(a: bool, b: bool) -> i32 { + if a && b { + return 50; + } + if a { + 0 + } else { + 10 + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unneeded_field_pattern.txt b/src/tools/clippy/src/docs/unneeded_field_pattern.txt new file mode 100644 index 0000000000000..3cd00a0f3e384 --- /dev/null +++ b/src/tools/clippy/src/docs/unneeded_field_pattern.txt @@ -0,0 +1,26 @@ +### What it does +Checks for structure field patterns bound to wildcards. + +### Why is this bad? +Using `..` instead is shorter and leaves the focus on +the fields that are actually bound. + +### Example +``` +let f = Foo { a: 0, b: 0, c: 0 }; + +match f { + Foo { a: _, b: 0, .. } => {}, + Foo { a: _, b: _, c: _ } => {}, +} +``` + +Use instead: +``` +let f = Foo { a: 0, b: 0, c: 0 }; + +match f { + Foo { b: 0, .. } => {}, + Foo { .. } => {}, +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unneeded_wildcard_pattern.txt b/src/tools/clippy/src/docs/unneeded_wildcard_pattern.txt new file mode 100644 index 0000000000000..817061efd1622 --- /dev/null +++ b/src/tools/clippy/src/docs/unneeded_wildcard_pattern.txt @@ -0,0 +1,28 @@ +### What it does +Checks for tuple patterns with a wildcard +pattern (`_`) is next to a rest pattern (`..`). + +_NOTE_: While `_, ..` means there is at least one element left, `..` +means there are 0 or more elements left. This can make a difference +when refactoring, but shouldn't result in errors in the refactored code, +since the wildcard pattern isn't used anyway. + +### Why is this bad? +The wildcard pattern is unneeded as the rest pattern +can match that element as well. + +### Example +``` +match t { + TupleStruct(0, .., _) => (), + _ => (), +} +``` + +Use instead: +``` +match t { + TupleStruct(0, ..) => (), + _ => (), +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unnested_or_patterns.txt b/src/tools/clippy/src/docs/unnested_or_patterns.txt new file mode 100644 index 0000000000000..49c45d4ee5e9c --- /dev/null +++ b/src/tools/clippy/src/docs/unnested_or_patterns.txt @@ -0,0 +1,22 @@ +### What it does +Checks for unnested or-patterns, e.g., `Some(0) | Some(2)` and +suggests replacing the pattern with a nested one, `Some(0 | 2)`. + +Another way to think of this is that it rewrites patterns in +*disjunctive normal form (DNF)* into *conjunctive normal form (CNF)*. + +### Why is this bad? +In the example above, `Some` is repeated, which unnecessarily complicates the pattern. + +### Example +``` +fn main() { + if let Some(0) | Some(2) = Some(0) {} +} +``` +Use instead: +``` +fn main() { + if let Some(0 | 2) = Some(0) {} +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unreachable.txt b/src/tools/clippy/src/docs/unreachable.txt new file mode 100644 index 0000000000000..10469ca77454f --- /dev/null +++ b/src/tools/clippy/src/docs/unreachable.txt @@ -0,0 +1,10 @@ +### What it does +Checks for usage of `unreachable!`. + +### Why is this bad? +This macro can cause code to panic + +### Example +``` +unreachable!(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unreadable_literal.txt b/src/tools/clippy/src/docs/unreadable_literal.txt new file mode 100644 index 0000000000000..e168f90a84c19 --- /dev/null +++ b/src/tools/clippy/src/docs/unreadable_literal.txt @@ -0,0 +1,16 @@ +### What it does +Warns if a long integral or floating-point constant does +not contain underscores. + +### Why is this bad? +Reading long numbers is difficult without separators. + +### Example +``` +61864918973511 +``` + +Use instead: +``` +61_864_918_973_511 +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unsafe_derive_deserialize.txt b/src/tools/clippy/src/docs/unsafe_derive_deserialize.txt new file mode 100644 index 0000000000000..f56c48044f4fa --- /dev/null +++ b/src/tools/clippy/src/docs/unsafe_derive_deserialize.txt @@ -0,0 +1,27 @@ +### What it does +Checks for deriving `serde::Deserialize` on a type that +has methods using `unsafe`. + +### Why is this bad? +Deriving `serde::Deserialize` will create a constructor +that may violate invariants hold by another constructor. + +### Example +``` +use serde::Deserialize; + +#[derive(Deserialize)] +pub struct Foo { + // .. +} + +impl Foo { + pub fn new() -> Self { + // setup here .. + } + + pub unsafe fn parts() -> (&str, &str) { + // assumes invariants hold + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unsafe_removed_from_name.txt b/src/tools/clippy/src/docs/unsafe_removed_from_name.txt new file mode 100644 index 0000000000000..6f55c1815dd65 --- /dev/null +++ b/src/tools/clippy/src/docs/unsafe_removed_from_name.txt @@ -0,0 +1,15 @@ +### What it does +Checks for imports that remove "unsafe" from an item's +name. + +### Why is this bad? +Renaming makes it less clear which traits and +structures are unsafe. + +### Example +``` +use std::cell::{UnsafeCell as TotallySafeCell}; + +extern crate crossbeam; +use crossbeam::{spawn_unsafe as spawn}; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unseparated_literal_suffix.txt b/src/tools/clippy/src/docs/unseparated_literal_suffix.txt new file mode 100644 index 0000000000000..d80248e34d0c7 --- /dev/null +++ b/src/tools/clippy/src/docs/unseparated_literal_suffix.txt @@ -0,0 +1,18 @@ +### What it does +Warns if literal suffixes are not separated by an +underscore. +To enforce unseparated literal suffix style, +see the `separated_literal_suffix` lint. + +### Why is this bad? +Suffix style should be consistent. + +### Example +``` +123832i32 +``` + +Use instead: +``` +123832_i32 +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unsound_collection_transmute.txt b/src/tools/clippy/src/docs/unsound_collection_transmute.txt new file mode 100644 index 0000000000000..29db9258e83fb --- /dev/null +++ b/src/tools/clippy/src/docs/unsound_collection_transmute.txt @@ -0,0 +1,25 @@ +### What it does +Checks for transmutes between collections whose +types have different ABI, size or alignment. + +### Why is this bad? +This is undefined behavior. + +### Known problems +Currently, we cannot know whether a type is a +collection, so we just lint the ones that come with `std`. + +### Example +``` +// different size, therefore likely out-of-bounds memory access +// You absolutely do not want this in your code! +unsafe { + std::mem::transmute::<_, Vec>(vec![2_u16]) +}; +``` + +You must always iterate, map and collect the values: + +``` +vec![2_u16].into_iter().map(u32::from).collect::>(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unused_async.txt b/src/tools/clippy/src/docs/unused_async.txt new file mode 100644 index 0000000000000..26def11aa17a5 --- /dev/null +++ b/src/tools/clippy/src/docs/unused_async.txt @@ -0,0 +1,23 @@ +### What it does +Checks for functions that are declared `async` but have no `.await`s inside of them. + +### Why is this bad? +Async functions with no async code create overhead, both mentally and computationally. +Callers of async methods either need to be calling from an async function themselves or run it on an executor, both of which +causes runtime overhead and hassle for the caller. + +### Example +``` +async fn get_random_number() -> i64 { + 4 // Chosen by fair dice roll. Guaranteed to be random. +} +let number_future = get_random_number(); +``` + +Use instead: +``` +fn get_random_number_improved() -> i64 { + 4 // Chosen by fair dice roll. Guaranteed to be random. +} +let number_future = async { get_random_number_improved() }; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unused_io_amount.txt b/src/tools/clippy/src/docs/unused_io_amount.txt new file mode 100644 index 0000000000000..fbc4c299c7bb7 --- /dev/null +++ b/src/tools/clippy/src/docs/unused_io_amount.txt @@ -0,0 +1,31 @@ +### What it does +Checks for unused written/read amount. + +### Why is this bad? +`io::Write::write(_vectored)` and +`io::Read::read(_vectored)` are not guaranteed to +process the entire buffer. They return how many bytes were processed, which +might be smaller +than a given buffer's length. If you don't need to deal with +partial-write/read, use +`write_all`/`read_exact` instead. + +When working with asynchronous code (either with the `futures` +crate or with `tokio`), a similar issue exists for +`AsyncWriteExt::write()` and `AsyncReadExt::read()` : these +functions are also not guaranteed to process the entire +buffer. Your code should either handle partial-writes/reads, or +call the `write_all`/`read_exact` methods on those traits instead. + +### Known problems +Detects only common patterns. + +### Examples +``` +use std::io; +fn foo(w: &mut W) -> io::Result<()> { + // must be `w.write_all(b"foo")?;` + w.write(b"foo")?; + Ok(()) +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unused_peekable.txt b/src/tools/clippy/src/docs/unused_peekable.txt new file mode 100644 index 0000000000000..268de1ce3bec3 --- /dev/null +++ b/src/tools/clippy/src/docs/unused_peekable.txt @@ -0,0 +1,26 @@ +### What it does +Checks for the creation of a `peekable` iterator that is never `.peek()`ed + +### Why is this bad? +Creating a peekable iterator without using any of its methods is likely a mistake, +or just a leftover after a refactor. + +### Example +``` +let collection = vec![1, 2, 3]; +let iter = collection.iter().peekable(); + +for item in iter { + // ... +} +``` + +Use instead: +``` +let collection = vec![1, 2, 3]; +let iter = collection.iter(); + +for item in iter { + // ... +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unused_rounding.txt b/src/tools/clippy/src/docs/unused_rounding.txt new file mode 100644 index 0000000000000..70947aceee77b --- /dev/null +++ b/src/tools/clippy/src/docs/unused_rounding.txt @@ -0,0 +1,17 @@ +### What it does + +Detects cases where a whole-number literal float is being rounded, using +the `floor`, `ceil`, or `round` methods. + +### Why is this bad? + +This is unnecessary and confusing to the reader. Doing this is probably a mistake. + +### Example +``` +let x = 1f32.ceil(); +``` +Use instead: +``` +let x = 1f32; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unused_self.txt b/src/tools/clippy/src/docs/unused_self.txt new file mode 100644 index 0000000000000..a8d0fc7598954 --- /dev/null +++ b/src/tools/clippy/src/docs/unused_self.txt @@ -0,0 +1,23 @@ +### What it does +Checks methods that contain a `self` argument but don't use it + +### Why is this bad? +It may be clearer to define the method as an associated function instead +of an instance method if it doesn't require `self`. + +### Example +``` +struct A; +impl A { + fn method(&self) {} +} +``` + +Could be written: + +``` +struct A; +impl A { + fn method() {} +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unused_unit.txt b/src/tools/clippy/src/docs/unused_unit.txt new file mode 100644 index 0000000000000..48d16ca655232 --- /dev/null +++ b/src/tools/clippy/src/docs/unused_unit.txt @@ -0,0 +1,18 @@ +### What it does +Checks for unit (`()`) expressions that can be removed. + +### Why is this bad? +Such expressions add no value, but can make the code +less readable. Depending on formatting they can make a `break` or `return` +statement look like a function call. + +### Example +``` +fn return_unit() -> () { + () +} +``` +is equivalent to +``` +fn return_unit() {} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unusual_byte_groupings.txt b/src/tools/clippy/src/docs/unusual_byte_groupings.txt new file mode 100644 index 0000000000000..9a1f132a6112f --- /dev/null +++ b/src/tools/clippy/src/docs/unusual_byte_groupings.txt @@ -0,0 +1,12 @@ +### What it does +Warns if hexadecimal or binary literals are not grouped +by nibble or byte. + +### Why is this bad? +Negatively impacts readability. + +### Example +``` +let x: u32 = 0xFFF_FFF; +let y: u8 = 0b01_011_101; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unwrap_in_result.txt b/src/tools/clippy/src/docs/unwrap_in_result.txt new file mode 100644 index 0000000000000..7497dd863d354 --- /dev/null +++ b/src/tools/clippy/src/docs/unwrap_in_result.txt @@ -0,0 +1,39 @@ +### What it does +Checks for functions of type `Result` that contain `expect()` or `unwrap()` + +### Why is this bad? +These functions promote recoverable errors to non-recoverable errors which may be undesirable in code bases which wish to avoid panics. + +### Known problems +This can cause false positives in functions that handle both recoverable and non recoverable errors. + +### Example +Before: +``` +fn divisible_by_3(i_str: String) -> Result<(), String> { + let i = i_str + .parse::() + .expect("cannot divide the input by three"); + + if i % 3 != 0 { + Err("Number is not divisible by 3")? + } + + Ok(()) +} +``` + +After: +``` +fn divisible_by_3(i_str: String) -> Result<(), String> { + let i = i_str + .parse::() + .map_err(|e| format!("cannot divide the input by three: {}", e))?; + + if i % 3 != 0 { + Err("Number is not divisible by 3")? + } + + Ok(()) +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unwrap_or_else_default.txt b/src/tools/clippy/src/docs/unwrap_or_else_default.txt new file mode 100644 index 0000000000000..34b4cf088581f --- /dev/null +++ b/src/tools/clippy/src/docs/unwrap_or_else_default.txt @@ -0,0 +1,18 @@ +### What it does +Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and +`Result` values. + +### Why is this bad? +Readability, these can be written as `_.unwrap_or_default`, which is +simpler and more concise. + +### Examples +``` +x.unwrap_or_else(Default::default); +x.unwrap_or_else(u32::default); +``` + +Use instead: +``` +x.unwrap_or_default(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/unwrap_used.txt b/src/tools/clippy/src/docs/unwrap_used.txt new file mode 100644 index 0000000000000..9b4713df515d6 --- /dev/null +++ b/src/tools/clippy/src/docs/unwrap_used.txt @@ -0,0 +1,37 @@ +### What it does +Checks for `.unwrap()` or `.unwrap_err()` calls on `Result`s and `.unwrap()` call on `Option`s. + +### Why is this bad? +It is better to handle the `None` or `Err` case, +or at least call `.expect(_)` with a more helpful message. Still, for a lot of +quick-and-dirty code, `unwrap` is a good choice, which is why this lint is +`Allow` by default. + +`result.unwrap()` will let the thread panic on `Err` values. +Normally, you want to implement more sophisticated error handling, +and propagate errors upwards with `?` operator. + +Even if you want to panic on errors, not all `Error`s implement good +messages on display. Therefore, it may be beneficial to look at the places +where they may get displayed. Activate this lint to do just that. + +### Examples +``` +option.unwrap(); +result.unwrap(); +``` + +Use instead: +``` +option.expect("more helpful message"); +result.expect("more helpful message"); +``` + +If [expect_used](#expect_used) is enabled, instead: +``` +option?; + +// or + +result?; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/upper_case_acronyms.txt b/src/tools/clippy/src/docs/upper_case_acronyms.txt new file mode 100644 index 0000000000000..a1e39c7e10c6e --- /dev/null +++ b/src/tools/clippy/src/docs/upper_case_acronyms.txt @@ -0,0 +1,25 @@ +### What it does +Checks for fully capitalized names and optionally names containing a capitalized acronym. + +### Why is this bad? +In CamelCase, acronyms count as one word. +See [naming conventions](https://rust-lang.github.io/api-guidelines/naming.html#casing-conforms-to-rfc-430-c-case) +for more. + +By default, the lint only triggers on fully-capitalized names. +You can use the `upper-case-acronyms-aggressive: true` config option to enable linting +on all camel case names + +### Known problems +When two acronyms are contiguous, the lint can't tell where +the first acronym ends and the second starts, so it suggests to lowercase all of +the letters in the second acronym. + +### Example +``` +struct HTTPResponse; +``` +Use instead: +``` +struct HttpResponse; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/use_debug.txt b/src/tools/clippy/src/docs/use_debug.txt new file mode 100644 index 0000000000000..94d4a6fd29ae5 --- /dev/null +++ b/src/tools/clippy/src/docs/use_debug.txt @@ -0,0 +1,12 @@ +### What it does +Checks for use of `Debug` formatting. The purpose of this +lint is to catch debugging remnants. + +### Why is this bad? +The purpose of the `Debug` trait is to facilitate +debugging Rust code. It should not be used in user-facing output. + +### Example +``` +println!("{:?}", foo); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/use_self.txt b/src/tools/clippy/src/docs/use_self.txt new file mode 100644 index 0000000000000..bd37ed1e00256 --- /dev/null +++ b/src/tools/clippy/src/docs/use_self.txt @@ -0,0 +1,31 @@ +### What it does +Checks for unnecessary repetition of structure name when a +replacement with `Self` is applicable. + +### Why is this bad? +Unnecessary repetition. Mixed use of `Self` and struct +name +feels inconsistent. + +### Known problems +- Unaddressed false negative in fn bodies of trait implementations +- False positive with associated types in traits (#4140) + +### Example +``` +struct Foo; +impl Foo { + fn new() -> Foo { + Foo {} + } +} +``` +could be +``` +struct Foo; +impl Foo { + fn new() -> Self { + Self {} + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/used_underscore_binding.txt b/src/tools/clippy/src/docs/used_underscore_binding.txt new file mode 100644 index 0000000000000..ed67c41eb0dbf --- /dev/null +++ b/src/tools/clippy/src/docs/used_underscore_binding.txt @@ -0,0 +1,19 @@ +### What it does +Checks for the use of bindings with a single leading +underscore. + +### Why is this bad? +A single leading underscore is usually used to indicate +that a binding will not be used. Using such a binding breaks this +expectation. + +### Known problems +The lint does not work properly with desugaring and +macro, it has been allowed in the mean time. + +### Example +``` +let _x = 0; +let y = _x + 1; // Here we are using `_x`, even though it has a leading + // underscore. We should rename `_x` to `x` +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/useless_asref.txt b/src/tools/clippy/src/docs/useless_asref.txt new file mode 100644 index 0000000000000..f777cd3775edf --- /dev/null +++ b/src/tools/clippy/src/docs/useless_asref.txt @@ -0,0 +1,17 @@ +### What it does +Checks for usage of `.as_ref()` or `.as_mut()` where the +types before and after the call are the same. + +### Why is this bad? +The call is unnecessary. + +### Example +``` +let x: &[i32] = &[1, 2, 3, 4, 5]; +do_stuff(x.as_ref()); +``` +The correct use would be: +``` +let x: &[i32] = &[1, 2, 3, 4, 5]; +do_stuff(x); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/useless_attribute.txt b/src/tools/clippy/src/docs/useless_attribute.txt new file mode 100644 index 0000000000000..e02d4c9078984 --- /dev/null +++ b/src/tools/clippy/src/docs/useless_attribute.txt @@ -0,0 +1,36 @@ +### What it does +Checks for `extern crate` and `use` items annotated with +lint attributes. + +This lint permits lint attributes for lints emitted on the items themself. +For `use` items these lints are: +* deprecated +* unreachable_pub +* unused_imports +* clippy::enum_glob_use +* clippy::macro_use_imports +* clippy::wildcard_imports + +For `extern crate` items these lints are: +* `unused_imports` on items with `#[macro_use]` + +### Why is this bad? +Lint attributes have no effect on crate imports. Most +likely a `!` was forgotten. + +### Example +``` +#[deny(dead_code)] +extern crate foo; +#[forbid(dead_code)] +use foo::bar; +``` + +Use instead: +``` +#[allow(unused_imports)] +use foo::baz; +#[allow(unused_imports)] +#[macro_use] +extern crate baz; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/useless_conversion.txt b/src/tools/clippy/src/docs/useless_conversion.txt new file mode 100644 index 0000000000000..06000a7ad98d5 --- /dev/null +++ b/src/tools/clippy/src/docs/useless_conversion.txt @@ -0,0 +1,17 @@ +### What it does +Checks for `Into`, `TryInto`, `From`, `TryFrom`, or `IntoIter` calls +which uselessly convert to the same type. + +### Why is this bad? +Redundant code. + +### Example +``` +// format!() returns a `String` +let s: String = format!("hello").into(); +``` + +Use instead: +``` +let s: String = format!("hello"); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/useless_format.txt b/src/tools/clippy/src/docs/useless_format.txt new file mode 100644 index 0000000000000..eb4819da1e95a --- /dev/null +++ b/src/tools/clippy/src/docs/useless_format.txt @@ -0,0 +1,22 @@ +### What it does +Checks for the use of `format!("string literal with no +argument")` and `format!("{}", foo)` where `foo` is a string. + +### Why is this bad? +There is no point of doing that. `format!("foo")` can +be replaced by `"foo".to_owned()` if you really need a `String`. The even +worse `&format!("foo")` is often encountered in the wild. `format!("{}", +foo)` can be replaced by `foo.clone()` if `foo: String` or `foo.to_owned()` +if `foo: &str`. + +### Examples +``` +let foo = "foo"; +format!("{}", foo); +``` + +Use instead: +``` +let foo = "foo"; +foo.to_owned(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/useless_let_if_seq.txt b/src/tools/clippy/src/docs/useless_let_if_seq.txt new file mode 100644 index 0000000000000..c6dcd57eb2e2d --- /dev/null +++ b/src/tools/clippy/src/docs/useless_let_if_seq.txt @@ -0,0 +1,39 @@ +### What it does +Checks for variable declarations immediately followed by a +conditional affectation. + +### Why is this bad? +This is not idiomatic Rust. + +### Example +``` +let foo; + +if bar() { + foo = 42; +} else { + foo = 0; +} + +let mut baz = None; + +if bar() { + baz = Some(42); +} +``` + +should be written + +``` +let foo = if bar() { + 42 +} else { + 0 +}; + +let baz = if bar() { + Some(42) +} else { + None +}; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/useless_transmute.txt b/src/tools/clippy/src/docs/useless_transmute.txt new file mode 100644 index 0000000000000..1d3a175881455 --- /dev/null +++ b/src/tools/clippy/src/docs/useless_transmute.txt @@ -0,0 +1,12 @@ +### What it does +Checks for transmutes to the original type of the object +and transmutes that could be a cast. + +### Why is this bad? +Readability. The code tricks people into thinking that +something complex is going on. + +### Example +``` +core::intrinsics::transmute(t); // where the result type is the same as `t`'s +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/useless_vec.txt b/src/tools/clippy/src/docs/useless_vec.txt new file mode 100644 index 0000000000000..ee5afc99e4bf2 --- /dev/null +++ b/src/tools/clippy/src/docs/useless_vec.txt @@ -0,0 +1,18 @@ +### What it does +Checks for usage of `&vec![..]` when using `&[..]` would +be possible. + +### Why is this bad? +This is less efficient. + +### Example +``` +fn foo(_x: &[u8]) {} + +foo(&vec![1, 2]); +``` + +Use instead: +``` +foo(&[1, 2]); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/vec_box.txt b/src/tools/clippy/src/docs/vec_box.txt new file mode 100644 index 0000000000000..701b1c9ce9b94 --- /dev/null +++ b/src/tools/clippy/src/docs/vec_box.txt @@ -0,0 +1,26 @@ +### What it does +Checks for use of `Vec>` where T: Sized anywhere in the code. +Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information. + +### Why is this bad? +`Vec` already keeps its contents in a separate area on +the heap. So if you `Box` its contents, you just add another level of indirection. + +### Known problems +Vec> makes sense if T is a large type (see [#3530](https://github.com/rust-lang/rust-clippy/issues/3530), +1st comment). + +### Example +``` +struct X { + values: Vec>, +} +``` + +Better: + +``` +struct X { + values: Vec, +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/vec_init_then_push.txt b/src/tools/clippy/src/docs/vec_init_then_push.txt new file mode 100644 index 0000000000000..445f2874796bb --- /dev/null +++ b/src/tools/clippy/src/docs/vec_init_then_push.txt @@ -0,0 +1,23 @@ +### What it does +Checks for calls to `push` immediately after creating a new `Vec`. + +If the `Vec` is created using `with_capacity` this will only lint if the capacity is a +constant and the number of pushes is greater than or equal to the initial capacity. + +If the `Vec` is extended after the initial sequence of pushes and it was default initialized +then this will only lint after there were at least four pushes. This number may change in +the future. + +### Why is this bad? +The `vec![]` macro is both more performant and easier to read than +multiple `push` calls. + +### Example +``` +let mut v = Vec::new(); +v.push(0); +``` +Use instead: +``` +let v = vec![0]; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/vec_resize_to_zero.txt b/src/tools/clippy/src/docs/vec_resize_to_zero.txt new file mode 100644 index 0000000000000..0b92686772bb0 --- /dev/null +++ b/src/tools/clippy/src/docs/vec_resize_to_zero.txt @@ -0,0 +1,15 @@ +### What it does +Finds occurrences of `Vec::resize(0, an_int)` + +### Why is this bad? +This is probably an argument inversion mistake. + +### Example +``` +vec!(1, 2, 3, 4, 5).resize(0, 5) +``` + +Use instead: +``` +vec!(1, 2, 3, 4, 5).clear() +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/verbose_bit_mask.txt b/src/tools/clippy/src/docs/verbose_bit_mask.txt new file mode 100644 index 0000000000000..87a84702925ed --- /dev/null +++ b/src/tools/clippy/src/docs/verbose_bit_mask.txt @@ -0,0 +1,15 @@ +### What it does +Checks for bit masks that can be replaced by a call +to `trailing_zeros` + +### Why is this bad? +`x.trailing_zeros() > 4` is much clearer than `x & 15 +== 0` + +### Known problems +llvm generates better code for `x & 15 == 0` on x86 + +### Example +``` +if x & 0b1111 == 0 { } +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/verbose_file_reads.txt b/src/tools/clippy/src/docs/verbose_file_reads.txt new file mode 100644 index 0000000000000..9703df423a575 --- /dev/null +++ b/src/tools/clippy/src/docs/verbose_file_reads.txt @@ -0,0 +1,17 @@ +### What it does +Checks for use of File::read_to_end and File::read_to_string. + +### Why is this bad? +`fs::{read, read_to_string}` provide the same functionality when `buf` is empty with fewer imports and no intermediate values. +See also: [fs::read docs](https://doc.rust-lang.org/std/fs/fn.read.html), [fs::read_to_string docs](https://doc.rust-lang.org/std/fs/fn.read_to_string.html) + +### Example +``` +let mut f = File::open("foo.txt").unwrap(); +let mut bytes = Vec::new(); +f.read_to_end(&mut bytes).unwrap(); +``` +Can be written more concisely as +``` +let mut bytes = fs::read("foo.txt").unwrap(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/vtable_address_comparisons.txt b/src/tools/clippy/src/docs/vtable_address_comparisons.txt new file mode 100644 index 0000000000000..4a34e4ba78ef4 --- /dev/null +++ b/src/tools/clippy/src/docs/vtable_address_comparisons.txt @@ -0,0 +1,17 @@ +### What it does +Checks for comparisons with an address of a trait vtable. + +### Why is this bad? +Comparing trait objects pointers compares an vtable addresses which +are not guaranteed to be unique and could vary between different code generation units. +Furthermore vtables for different types could have the same address after being merged +together. + +### Example +``` +let a: Rc = ... +let b: Rc = ... +if Rc::ptr_eq(&a, &b) { + ... +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/while_immutable_condition.txt b/src/tools/clippy/src/docs/while_immutable_condition.txt new file mode 100644 index 0000000000000..71800701f4897 --- /dev/null +++ b/src/tools/clippy/src/docs/while_immutable_condition.txt @@ -0,0 +1,20 @@ +### What it does +Checks whether variables used within while loop condition +can be (and are) mutated in the body. + +### Why is this bad? +If the condition is unchanged, entering the body of the loop +will lead to an infinite loop. + +### Known problems +If the `while`-loop is in a closure, the check for mutation of the +condition variables in the body can cause false negatives. For example when only `Upvar` `a` is +in the condition and only `Upvar` `b` gets mutated in the body, the lint will not trigger. + +### Example +``` +let i = 0; +while i > 10 { + println!("let me loop forever!"); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/while_let_loop.txt b/src/tools/clippy/src/docs/while_let_loop.txt new file mode 100644 index 0000000000000..ab7bf60975ec5 --- /dev/null +++ b/src/tools/clippy/src/docs/while_let_loop.txt @@ -0,0 +1,25 @@ +### What it does +Detects `loop + match` combinations that are easier +written as a `while let` loop. + +### Why is this bad? +The `while let` loop is usually shorter and more +readable. + +### Known problems +Sometimes the wrong binding is displayed ([#383](https://github.com/rust-lang/rust-clippy/issues/383)). + +### Example +``` +loop { + let x = match y { + Some(x) => x, + None => break, + }; + // .. do something with x +} +// is easier written as +while let Some(x) = y { + // .. do something with x +}; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/while_let_on_iterator.txt b/src/tools/clippy/src/docs/while_let_on_iterator.txt new file mode 100644 index 0000000000000..af053c541199d --- /dev/null +++ b/src/tools/clippy/src/docs/while_let_on_iterator.txt @@ -0,0 +1,20 @@ +### What it does +Checks for `while let` expressions on iterators. + +### Why is this bad? +Readability. A simple `for` loop is shorter and conveys +the intent better. + +### Example +``` +while let Some(val) = iter.next() { + .. +} +``` + +Use instead: +``` +for val in &mut iter { + .. +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/wildcard_dependencies.txt b/src/tools/clippy/src/docs/wildcard_dependencies.txt new file mode 100644 index 0000000000000..2affaf9740d9f --- /dev/null +++ b/src/tools/clippy/src/docs/wildcard_dependencies.txt @@ -0,0 +1,13 @@ +### What it does +Checks for wildcard dependencies in the `Cargo.toml`. + +### Why is this bad? +[As the edition guide says](https://rust-lang-nursery.github.io/edition-guide/rust-2018/cargo-and-crates-io/crates-io-disallows-wildcard-dependencies.html), +it is highly unlikely that you work with any possible version of your dependency, +and wildcard dependencies would cause unnecessary breakage in the ecosystem. + +### Example +``` +[dependencies] +regex = "*" +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/wildcard_enum_match_arm.txt b/src/tools/clippy/src/docs/wildcard_enum_match_arm.txt new file mode 100644 index 0000000000000..09807c01c652b --- /dev/null +++ b/src/tools/clippy/src/docs/wildcard_enum_match_arm.txt @@ -0,0 +1,25 @@ +### What it does +Checks for wildcard enum matches using `_`. + +### Why is this bad? +New enum variants added by library updates can be missed. + +### Known problems +Suggested replacements may be incorrect if guards exhaustively cover some +variants, and also may not use correct path to enum if it's not present in the current scope. + +### Example +``` +match x { + Foo::A(_) => {}, + _ => {}, +} +``` + +Use instead: +``` +match x { + Foo::A(_) => {}, + Foo::B(_) => {}, +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/wildcard_imports.txt b/src/tools/clippy/src/docs/wildcard_imports.txt new file mode 100644 index 0000000000000..bd56aa5b08282 --- /dev/null +++ b/src/tools/clippy/src/docs/wildcard_imports.txt @@ -0,0 +1,45 @@ +### What it does +Checks for wildcard imports `use _::*`. + +### Why is this bad? +wildcard imports can pollute the namespace. This is especially bad if +you try to import something through a wildcard, that already has been imported by name from +a different source: + +``` +use crate1::foo; // Imports a function named foo +use crate2::*; // Has a function named foo + +foo(); // Calls crate1::foo +``` + +This can lead to confusing error messages at best and to unexpected behavior at worst. + +### Exceptions +Wildcard imports are allowed from modules named `prelude`. Many crates (including the standard library) +provide modules named "prelude" specifically designed for wildcard import. + +`use super::*` is allowed in test modules. This is defined as any module with "test" in the name. + +These exceptions can be disabled using the `warn-on-all-wildcard-imports` configuration flag. + +### Known problems +If macros are imported through the wildcard, this macro is not included +by the suggestion and has to be added by hand. + +Applying the suggestion when explicit imports of the things imported with a glob import +exist, may result in `unused_imports` warnings. + +### Example +``` +use crate1::*; + +foo(); +``` + +Use instead: +``` +use crate1::foo; + +foo(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/wildcard_in_or_patterns.txt b/src/tools/clippy/src/docs/wildcard_in_or_patterns.txt new file mode 100644 index 0000000000000..70468ca41e0b8 --- /dev/null +++ b/src/tools/clippy/src/docs/wildcard_in_or_patterns.txt @@ -0,0 +1,22 @@ +### What it does +Checks for wildcard pattern used with others patterns in same match arm. + +### Why is this bad? +Wildcard pattern already covers any other pattern as it will match anyway. +It makes the code less readable, especially to spot wildcard pattern use in match arm. + +### Example +``` +match s { + "a" => {}, + "bar" | _ => {}, +} +``` + +Use instead: +``` +match s { + "a" => {}, + _ => {}, +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/write_literal.txt b/src/tools/clippy/src/docs/write_literal.txt new file mode 100644 index 0000000000000..9c41a48f9f731 --- /dev/null +++ b/src/tools/clippy/src/docs/write_literal.txt @@ -0,0 +1,21 @@ +### What it does +This lint warns about the use of literals as `write!`/`writeln!` args. + +### Why is this bad? +Using literals as `writeln!` args is inefficient +(c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary +(i.e., just put the literal in the format string) + +### Known problems +Will also warn with macro calls as arguments that expand to literals +-- e.g., `writeln!(buf, "{}", env!("FOO"))`. + +### Example +``` +writeln!(buf, "{}", "foo"); +``` + +Use instead: +``` +writeln!(buf, "foo"); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/write_with_newline.txt b/src/tools/clippy/src/docs/write_with_newline.txt new file mode 100644 index 0000000000000..22845fd6515bd --- /dev/null +++ b/src/tools/clippy/src/docs/write_with_newline.txt @@ -0,0 +1,18 @@ +### What it does +This lint warns when you use `write!()` with a format +string that +ends in a newline. + +### Why is this bad? +You should use `writeln!()` instead, which appends the +newline. + +### Example +``` +write!(buf, "Hello {}!\n", name); +``` + +Use instead: +``` +writeln!(buf, "Hello {}!", name); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/writeln_empty_string.txt b/src/tools/clippy/src/docs/writeln_empty_string.txt new file mode 100644 index 0000000000000..3b3aeb79a48bc --- /dev/null +++ b/src/tools/clippy/src/docs/writeln_empty_string.txt @@ -0,0 +1,16 @@ +### What it does +This lint warns when you use `writeln!(buf, "")` to +print a newline. + +### Why is this bad? +You should use `writeln!(buf)`, which is simpler. + +### Example +``` +writeln!(buf, ""); +``` + +Use instead: +``` +writeln!(buf); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/wrong_self_convention.txt b/src/tools/clippy/src/docs/wrong_self_convention.txt new file mode 100644 index 0000000000000..d6b69ab87f862 --- /dev/null +++ b/src/tools/clippy/src/docs/wrong_self_convention.txt @@ -0,0 +1,39 @@ +### What it does +Checks for methods with certain name prefixes and which +doesn't match how self is taken. The actual rules are: + +|Prefix |Postfix |`self` taken | `self` type | +|-------|------------|-------------------------------|--------------| +|`as_` | none |`&self` or `&mut self` | any | +|`from_`| none | none | any | +|`into_`| none |`self` | any | +|`is_` | none |`&mut self` or `&self` or none | any | +|`to_` | `_mut` |`&mut self` | any | +|`to_` | not `_mut` |`self` | `Copy` | +|`to_` | not `_mut` |`&self` | not `Copy` | + +Note: Clippy doesn't trigger methods with `to_` prefix in: +- Traits definition. +Clippy can not tell if a type that implements a trait is `Copy` or not. +- Traits implementation, when `&self` is taken. +The method signature is controlled by the trait and often `&self` is required for all types that implement the trait +(see e.g. the `std::string::ToString` trait). + +Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required. + +Please find more info here: +https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv + +### Why is this bad? +Consistency breeds readability. If you follow the +conventions, your users won't be surprised that they, e.g., need to supply a +mutable reference to a `as_..` function. + +### Example +``` +impl X { + fn as_str(self) -> &'static str { + // .. + } +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/wrong_transmute.txt b/src/tools/clippy/src/docs/wrong_transmute.txt new file mode 100644 index 0000000000000..9fc71e0e382e3 --- /dev/null +++ b/src/tools/clippy/src/docs/wrong_transmute.txt @@ -0,0 +1,15 @@ +### What it does +Checks for transmutes that can't ever be correct on any +architecture. + +### Why is this bad? +It's basically guaranteed to be undefined behavior. + +### Known problems +When accessing C, users might want to store pointer +sized objects in `extradata` arguments to save an allocation. + +### Example +``` +let ptr: *const T = core::intrinsics::transmute('x') +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/zero_divided_by_zero.txt b/src/tools/clippy/src/docs/zero_divided_by_zero.txt new file mode 100644 index 0000000000000..394de20c0c0c6 --- /dev/null +++ b/src/tools/clippy/src/docs/zero_divided_by_zero.txt @@ -0,0 +1,15 @@ +### What it does +Checks for `0.0 / 0.0`. + +### Why is this bad? +It's less readable than `f32::NAN` or `f64::NAN`. + +### Example +``` +let nan = 0.0f32 / 0.0; +``` + +Use instead: +``` +let nan = f32::NAN; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/zero_prefixed_literal.txt b/src/tools/clippy/src/docs/zero_prefixed_literal.txt new file mode 100644 index 0000000000000..5c5588725363e --- /dev/null +++ b/src/tools/clippy/src/docs/zero_prefixed_literal.txt @@ -0,0 +1,32 @@ +### What it does +Warns if an integral constant literal starts with `0`. + +### Why is this bad? +In some languages (including the infamous C language +and most of its +family), this marks an octal constant. In Rust however, this is a decimal +constant. This could +be confusing for both the writer and a reader of the constant. + +### Example + +In Rust: +``` +fn main() { + let a = 0123; + println!("{}", a); +} +``` + +prints `123`, while in C: + +``` +#include + +int main() { + int a = 0123; + printf("%d\n", a); +} +``` + +prints `83` (as `83 == 0o123` while `123 == 0o173`). \ No newline at end of file diff --git a/src/tools/clippy/src/docs/zero_ptr.txt b/src/tools/clippy/src/docs/zero_ptr.txt new file mode 100644 index 0000000000000..e768a02366009 --- /dev/null +++ b/src/tools/clippy/src/docs/zero_ptr.txt @@ -0,0 +1,16 @@ +### What it does +Catch casts from `0` to some pointer type + +### Why is this bad? +This generally means `null` and is better expressed as +{`std`, `core`}`::ptr::`{`null`, `null_mut`}. + +### Example +``` +let a = 0 as *const u32; +``` + +Use instead: +``` +let a = std::ptr::null::(); +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/zero_sized_map_values.txt b/src/tools/clippy/src/docs/zero_sized_map_values.txt new file mode 100644 index 0000000000000..0502bdbf3950e --- /dev/null +++ b/src/tools/clippy/src/docs/zero_sized_map_values.txt @@ -0,0 +1,24 @@ +### What it does +Checks for maps with zero-sized value types anywhere in the code. + +### Why is this bad? +Since there is only a single value for a zero-sized type, a map +containing zero sized values is effectively a set. Using a set in that case improves +readability and communicates intent more clearly. + +### Known problems +* A zero-sized type cannot be recovered later if it contains private fields. +* This lints the signature of public items + +### Example +``` +fn unique_words(text: &str) -> HashMap<&str, ()> { + todo!(); +} +``` +Use instead: +``` +fn unique_words(text: &str) -> HashSet<&str> { + todo!(); +} +``` \ No newline at end of file diff --git a/src/tools/clippy/src/docs/zst_offset.txt b/src/tools/clippy/src/docs/zst_offset.txt new file mode 100644 index 0000000000000..5810455ee9550 --- /dev/null +++ b/src/tools/clippy/src/docs/zst_offset.txt @@ -0,0 +1,11 @@ +### What it does +Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to +zero-sized types + +### Why is this bad? +This is a no-op, and likely unintended + +### Example +``` +unsafe { (&() as *const ()).offset(1) }; +``` \ No newline at end of file diff --git a/src/tools/clippy/src/main.rs b/src/tools/clippy/src/main.rs index 9ee4a40cbf242..4a32e0e54a81b 100644 --- a/src/tools/clippy/src/main.rs +++ b/src/tools/clippy/src/main.rs @@ -7,6 +7,8 @@ use std::env; use std::path::PathBuf; use std::process::{self, Command}; +mod docs; + const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code. Usage: @@ -17,6 +19,7 @@ Common options: --fix Automatically apply lint suggestions. This flag implies `--no-deps` -h, --help Print this message -V, --version Print version info and exit + --explain LINT Print the documentation for a given lint Other options are the same as `cargo check`. @@ -54,6 +57,16 @@ pub fn main() { return; } + if let Some(pos) = env::args().position(|a| a == "--explain") { + if let Some(mut lint) = env::args().nth(pos + 1) { + lint.make_ascii_lowercase(); + docs::explain(&lint.strip_prefix("clippy::").unwrap_or(&lint).replace('-', "_")); + } else { + show_help(); + } + return; + } + if let Err(code) = process(env::args().skip(2)) { process::exit(code); } diff --git a/src/tools/clippy/tests/ui-toml/arithmetic_allowed/clippy.toml b/src/tools/clippy/tests/ui-toml/arithmetic_allowed/clippy.toml deleted file mode 100644 index cc40570b12a08..0000000000000 --- a/src/tools/clippy/tests/ui-toml/arithmetic_allowed/clippy.toml +++ /dev/null @@ -1 +0,0 @@ -arithmetic-allowed = ["Point"] diff --git a/src/tools/clippy/tests/ui-toml/arithmetic_allowed/arithmetic_allowed.rs b/src/tools/clippy/tests/ui-toml/arithmetic_side_effects_allowed/arithmetic_side_effects_allowed.rs similarity index 89% rename from src/tools/clippy/tests/ui-toml/arithmetic_allowed/arithmetic_allowed.rs rename to src/tools/clippy/tests/ui-toml/arithmetic_side_effects_allowed/arithmetic_side_effects_allowed.rs index 195fabdbf710b..1aed09b7c7bd4 100644 --- a/src/tools/clippy/tests/ui-toml/arithmetic_allowed/arithmetic_allowed.rs +++ b/src/tools/clippy/tests/ui-toml/arithmetic_side_effects_allowed/arithmetic_side_effects_allowed.rs @@ -1,4 +1,4 @@ -#![warn(clippy::arithmetic)] +#![warn(clippy::arithmetic_side_effects)] use core::ops::Add; diff --git a/src/tools/clippy/tests/ui-toml/arithmetic_side_effects_allowed/clippy.toml b/src/tools/clippy/tests/ui-toml/arithmetic_side_effects_allowed/clippy.toml new file mode 100644 index 0000000000000..e736256f29a47 --- /dev/null +++ b/src/tools/clippy/tests/ui-toml/arithmetic_side_effects_allowed/clippy.toml @@ -0,0 +1 @@ +arithmetic-side-effects-allowed = ["Point"] diff --git a/src/tools/clippy/tests/ui-toml/toml_unknown_key/conf_unknown_key.stderr b/src/tools/clippy/tests/ui-toml/toml_unknown_key/conf_unknown_key.stderr index a52a0b5289fe4..f27f78d15d3a0 100644 --- a/src/tools/clippy/tests/ui-toml/toml_unknown_key/conf_unknown_key.stderr +++ b/src/tools/clippy/tests/ui-toml/toml_unknown_key/conf_unknown_key.stderr @@ -3,7 +3,7 @@ error: error reading Clippy's configuration file `$DIR/clippy.toml`: unknown fie allow-expect-in-tests allow-unwrap-in-tests allowed-scripts - arithmetic-allowed + arithmetic-side-effects-allowed array-size-threshold avoid-breaking-exported-api await-holding-invalid-types diff --git a/src/tools/clippy/tests/ui/arithmetic.fixed b/src/tools/clippy/tests/ui/arithmetic.fixed deleted file mode 100644 index a2a1c4394c21f..0000000000000 --- a/src/tools/clippy/tests/ui/arithmetic.fixed +++ /dev/null @@ -1,27 +0,0 @@ -// run-rustfix - -#![allow(clippy::unnecessary_owned_empty_strings)] -#![feature(saturating_int_impl)] -#![warn(clippy::arithmetic)] - -use core::num::{Saturating, Wrapping}; - -pub fn hard_coded_allowed() { - let _ = Saturating(0u32) + Saturating(0u32); - let _ = String::new() + ""; - let _ = Wrapping(0u32) + Wrapping(0u32); - - let saturating: Saturating = Saturating(0u32); - let string: String = String::new(); - let wrapping: Wrapping = Wrapping(0u32); - - let inferred_saturating = saturating + saturating; - let inferred_string = string + ""; - let inferred_wrapping = wrapping + wrapping; - - let _ = inferred_saturating + inferred_saturating; - let _ = inferred_string + ""; - let _ = inferred_wrapping + inferred_wrapping; -} - -fn main() {} diff --git a/src/tools/clippy/tests/ui/arithmetic.rs b/src/tools/clippy/tests/ui/arithmetic.rs deleted file mode 100644 index a2a1c4394c21f..0000000000000 --- a/src/tools/clippy/tests/ui/arithmetic.rs +++ /dev/null @@ -1,27 +0,0 @@ -// run-rustfix - -#![allow(clippy::unnecessary_owned_empty_strings)] -#![feature(saturating_int_impl)] -#![warn(clippy::arithmetic)] - -use core::num::{Saturating, Wrapping}; - -pub fn hard_coded_allowed() { - let _ = Saturating(0u32) + Saturating(0u32); - let _ = String::new() + ""; - let _ = Wrapping(0u32) + Wrapping(0u32); - - let saturating: Saturating = Saturating(0u32); - let string: String = String::new(); - let wrapping: Wrapping = Wrapping(0u32); - - let inferred_saturating = saturating + saturating; - let inferred_string = string + ""; - let inferred_wrapping = wrapping + wrapping; - - let _ = inferred_saturating + inferred_saturating; - let _ = inferred_string + ""; - let _ = inferred_wrapping + inferred_wrapping; -} - -fn main() {} diff --git a/src/tools/clippy/tests/ui/arithmetic_side_effects.rs b/src/tools/clippy/tests/ui/arithmetic_side_effects.rs new file mode 100644 index 0000000000000..f5390c7464250 --- /dev/null +++ b/src/tools/clippy/tests/ui/arithmetic_side_effects.rs @@ -0,0 +1,57 @@ +#![allow(clippy::assign_op_pattern, clippy::unnecessary_owned_empty_strings)] +#![feature(inline_const, saturating_int_impl)] +#![warn(clippy::arithmetic_side_effects)] + +use core::num::{Saturating, Wrapping}; + +pub fn hard_coded_allowed() { + let _ = 1f32 + 1f32; + let _ = 1f64 + 1f64; + + let _ = Saturating(0u32) + Saturating(0u32); + let _ = String::new() + ""; + let _ = Wrapping(0u32) + Wrapping(0u32); + + let saturating: Saturating = Saturating(0u32); + let string: String = String::new(); + let wrapping: Wrapping = Wrapping(0u32); + + let inferred_saturating = saturating + saturating; + let inferred_string = string + ""; + let inferred_wrapping = wrapping + wrapping; + + let _ = inferred_saturating + inferred_saturating; + let _ = inferred_string + ""; + let _ = inferred_wrapping + inferred_wrapping; +} + +#[rustfmt::skip] +pub fn non_overflowing_ops() { + const _: i32 = { let mut n = 1; n += 1; n }; + let _ = const { let mut n = 1; n += 1; n }; + + const _: i32 = { let mut n = 1; n = n + 1; n }; + let _ = const { let mut n = 1; n = n + 1; n }; + + const _: i32 = { let mut n = 1; n = 1 + n; n }; + let _ = const { let mut n = 1; n = 1 + n; n }; + + const _: i32 = 1 + 1; + let _ = 1 + 1; + let _ = const { 1 + 1 }; + + let mut _a = 1; + _a *= 1; + _a /= 1; +} + +#[rustfmt::skip] +pub fn overflowing_ops() { + let mut _a = 1; _a += 1; + + let mut _b = 1; _b = _b + 1; + + let mut _c = 1; _c = 1 + _c; +} + +fn main() {} diff --git a/src/tools/clippy/tests/ui/arithmetic_side_effects.stderr b/src/tools/clippy/tests/ui/arithmetic_side_effects.stderr new file mode 100644 index 0000000000000..6c4c8bdec0f05 --- /dev/null +++ b/src/tools/clippy/tests/ui/arithmetic_side_effects.stderr @@ -0,0 +1,22 @@ +error: arithmetic detected + --> $DIR/arithmetic_side_effects.rs:50:21 + | +LL | let mut _a = 1; _a += 1; + | ^^^^^^^ + | + = note: `-D clippy::arithmetic-side-effects` implied by `-D warnings` + +error: arithmetic detected + --> $DIR/arithmetic_side_effects.rs:52:26 + | +LL | let mut _b = 1; _b = _b + 1; + | ^^^^^^ + +error: arithmetic detected + --> $DIR/arithmetic_side_effects.rs:54:26 + | +LL | let mut _c = 1; _c = 1 + _c; + | ^^^^^^ + +error: aborting due to 3 previous errors + diff --git a/src/tools/clippy/tests/ui/author/struct.rs b/src/tools/clippy/tests/ui/author/struct.rs index 5fdf3433a3702..a99bdfc131379 100644 --- a/src/tools/clippy/tests/ui/author/struct.rs +++ b/src/tools/clippy/tests/ui/author/struct.rs @@ -1,4 +1,9 @@ -#[allow(clippy::unnecessary_operation, clippy::single_match)] +#![allow( + clippy::unnecessary_operation, + clippy::single_match, + clippy::no_effect, + clippy::bool_to_int_with_if +)] fn main() { struct Test { field: u32, diff --git a/src/tools/clippy/tests/ui/bool_to_int_with_if.fixed b/src/tools/clippy/tests/ui/bool_to_int_with_if.fixed new file mode 100644 index 0000000000000..9c1098dc4c17a --- /dev/null +++ b/src/tools/clippy/tests/ui/bool_to_int_with_if.fixed @@ -0,0 +1,85 @@ +// run-rustfix + +#![warn(clippy::bool_to_int_with_if)] +#![allow(unused, dead_code, clippy::unnecessary_operation, clippy::no_effect)] + +fn main() { + let a = true; + let b = false; + + let x = 1; + let y = 2; + + // Should lint + // precedence + i32::from(a); + i32::from(!a); + i32::from(a || b); + i32::from(cond(a, b)); + i32::from(x + y < 4); + + // if else if + if a { + 123 + } else {i32::from(b)}; + + // Shouldn't lint + + if a { + 1 + } else if b { + 0 + } else { + 3 + }; + + if a { + 3 + } else if b { + 1 + } else { + -2 + }; + + if a { + 3 + } else { + 0 + }; + if a { + side_effect(); + 1 + } else { + 0 + }; + if a { + 1 + } else { + side_effect(); + 0 + }; + + // multiple else ifs + if a { + 123 + } else if b { + 1 + } else if a | b { + 0 + } else { + 123 + }; + + some_fn(a); +} + +// Lint returns and type inference +fn some_fn(a: bool) -> u8 { + u8::from(a) +} + +fn side_effect() {} + +fn cond(a: bool, b: bool) -> bool { + a || b +} diff --git a/src/tools/clippy/tests/ui/bool_to_int_with_if.rs b/src/tools/clippy/tests/ui/bool_to_int_with_if.rs new file mode 100644 index 0000000000000..0c967dac6e2dd --- /dev/null +++ b/src/tools/clippy/tests/ui/bool_to_int_with_if.rs @@ -0,0 +1,109 @@ +// run-rustfix + +#![warn(clippy::bool_to_int_with_if)] +#![allow(unused, dead_code, clippy::unnecessary_operation, clippy::no_effect)] + +fn main() { + let a = true; + let b = false; + + let x = 1; + let y = 2; + + // Should lint + // precedence + if a { + 1 + } else { + 0 + }; + if !a { + 1 + } else { + 0 + }; + if a || b { + 1 + } else { + 0 + }; + if cond(a, b) { + 1 + } else { + 0 + }; + if x + y < 4 { + 1 + } else { + 0 + }; + + // if else if + if a { + 123 + } else if b { + 1 + } else { + 0 + }; + + // Shouldn't lint + + if a { + 1 + } else if b { + 0 + } else { + 3 + }; + + if a { + 3 + } else if b { + 1 + } else { + -2 + }; + + if a { + 3 + } else { + 0 + }; + if a { + side_effect(); + 1 + } else { + 0 + }; + if a { + 1 + } else { + side_effect(); + 0 + }; + + // multiple else ifs + if a { + 123 + } else if b { + 1 + } else if a | b { + 0 + } else { + 123 + }; + + some_fn(a); +} + +// Lint returns and type inference +fn some_fn(a: bool) -> u8 { + if a { 1 } else { 0 } +} + +fn side_effect() {} + +fn cond(a: bool, b: bool) -> bool { + a || b +} diff --git a/src/tools/clippy/tests/ui/bool_to_int_with_if.stderr b/src/tools/clippy/tests/ui/bool_to_int_with_if.stderr new file mode 100644 index 0000000000000..8647a9cffbede --- /dev/null +++ b/src/tools/clippy/tests/ui/bool_to_int_with_if.stderr @@ -0,0 +1,84 @@ +error: boolean to int conversion using if + --> $DIR/bool_to_int_with_if.rs:15:5 + | +LL | / if a { +LL | | 1 +LL | | } else { +LL | | 0 +LL | | }; + | |_____^ help: replace with from: `i32::from(a)` + | + = note: `-D clippy::bool-to-int-with-if` implied by `-D warnings` + = note: `a as i32` or `a.into()` can also be valid options + +error: boolean to int conversion using if + --> $DIR/bool_to_int_with_if.rs:20:5 + | +LL | / if !a { +LL | | 1 +LL | | } else { +LL | | 0 +LL | | }; + | |_____^ help: replace with from: `i32::from(!a)` + | + = note: `!a as i32` or `!a.into()` can also be valid options + +error: boolean to int conversion using if + --> $DIR/bool_to_int_with_if.rs:25:5 + | +LL | / if a || b { +LL | | 1 +LL | | } else { +LL | | 0 +LL | | }; + | |_____^ help: replace with from: `i32::from(a || b)` + | + = note: `(a || b) as i32` or `(a || b).into()` can also be valid options + +error: boolean to int conversion using if + --> $DIR/bool_to_int_with_if.rs:30:5 + | +LL | / if cond(a, b) { +LL | | 1 +LL | | } else { +LL | | 0 +LL | | }; + | |_____^ help: replace with from: `i32::from(cond(a, b))` + | + = note: `cond(a, b) as i32` or `cond(a, b).into()` can also be valid options + +error: boolean to int conversion using if + --> $DIR/bool_to_int_with_if.rs:35:5 + | +LL | / if x + y < 4 { +LL | | 1 +LL | | } else { +LL | | 0 +LL | | }; + | |_____^ help: replace with from: `i32::from(x + y < 4)` + | + = note: `(x + y < 4) as i32` or `(x + y < 4).into()` can also be valid options + +error: boolean to int conversion using if + --> $DIR/bool_to_int_with_if.rs:44:12 + | +LL | } else if b { + | ____________^ +LL | | 1 +LL | | } else { +LL | | 0 +LL | | }; + | |_____^ help: replace with from: `{i32::from(b)}` + | + = note: `b as i32` or `b.into()` can also be valid options + +error: boolean to int conversion using if + --> $DIR/bool_to_int_with_if.rs:102:5 + | +LL | if a { 1 } else { 0 } + | ^^^^^^^^^^^^^^^^^^^^^ help: replace with from: `u8::from(a)` + | + = note: `a as u8` or `a.into()` can also be valid options + +error: aborting due to 7 previous errors + diff --git a/src/tools/clippy/tests/ui/crashes/ice-9405.rs b/src/tools/clippy/tests/ui/crashes/ice-9405.rs new file mode 100644 index 0000000000000..e2d274aeb0442 --- /dev/null +++ b/src/tools/clippy/tests/ui/crashes/ice-9405.rs @@ -0,0 +1,11 @@ +#![warn(clippy::useless_format)] +#![allow(clippy::print_literal)] + +fn main() { + println!( + "\ + + {}", + "multiple skipped lines" + ); +} diff --git a/src/tools/clippy/tests/ui/crashes/ice-9405.stderr b/src/tools/clippy/tests/ui/crashes/ice-9405.stderr new file mode 100644 index 0000000000000..9a6e410f21ea8 --- /dev/null +++ b/src/tools/clippy/tests/ui/crashes/ice-9405.stderr @@ -0,0 +1,11 @@ +warning: multiple lines skipped by escaped newline + --> $DIR/ice-9405.rs:6:10 + | +LL | "/ + | __________^ +LL | | +LL | | {}", + | |____________^ skipping everything up to and including this point + +warning: 1 warning emitted + diff --git a/src/tools/clippy/tests/ui/crashes/ice-9414.rs b/src/tools/clippy/tests/ui/crashes/ice-9414.rs new file mode 100644 index 0000000000000..02cf5d5c240fa --- /dev/null +++ b/src/tools/clippy/tests/ui/crashes/ice-9414.rs @@ -0,0 +1,8 @@ +#![warn(clippy::result_large_err)] + +trait T {} +fn f(_: &u32) -> Result<(), *const (dyn '_ + T)> { + Ok(()) +} + +fn main() {} diff --git a/src/tools/clippy/tests/ui/floating_point_powf.fixed b/src/tools/clippy/tests/ui/floating_point_powf.fixed index 7efe10a10f9e9..e7ef45634dff4 100644 --- a/src/tools/clippy/tests/ui/floating_point_powf.fixed +++ b/src/tools/clippy/tests/ui/floating_point_powf.fixed @@ -18,6 +18,11 @@ fn main() { let _ = x.powi(-16_777_215); let _ = (x as f32).powi(-16_777_215); let _ = (x as f32).powi(3); + let _ = (1.5_f32 + 1.0).cbrt(); + let _ = 1.5_f64.cbrt(); + let _ = 1.5_f64.sqrt(); + let _ = 1.5_f64.powi(3); + // Cases where the lint shouldn't be applied let _ = x.powf(2.1); let _ = x.powf(-2.1); diff --git a/src/tools/clippy/tests/ui/floating_point_powf.rs b/src/tools/clippy/tests/ui/floating_point_powf.rs index 445080417f2ed..d749aa2d48a41 100644 --- a/src/tools/clippy/tests/ui/floating_point_powf.rs +++ b/src/tools/clippy/tests/ui/floating_point_powf.rs @@ -18,6 +18,11 @@ fn main() { let _ = x.powf(-16_777_215.0); let _ = (x as f32).powf(-16_777_215.0); let _ = (x as f32).powf(3.0); + let _ = (1.5_f32 + 1.0).powf(1.0 / 3.0); + let _ = 1.5_f64.powf(1.0 / 3.0); + let _ = 1.5_f64.powf(1.0 / 2.0); + let _ = 1.5_f64.powf(3.0); + // Cases where the lint shouldn't be applied let _ = x.powf(2.1); let _ = x.powf(-2.1); diff --git a/src/tools/clippy/tests/ui/floating_point_powf.stderr b/src/tools/clippy/tests/ui/floating_point_powf.stderr index 6ee696e6ada5f..e9693de8fc909 100644 --- a/src/tools/clippy/tests/ui/floating_point_powf.stderr +++ b/src/tools/clippy/tests/ui/floating_point_powf.stderr @@ -92,77 +92,101 @@ error: exponentiation with integer powers can be computed more efficiently LL | let _ = (x as f32).powf(3.0); | ^^^^^^^^^^^^^^^^^^^^ help: consider using: `(x as f32).powi(3)` +error: cube-root of a number can be computed more accurately + --> $DIR/floating_point_powf.rs:21:13 + | +LL | let _ = (1.5_f32 + 1.0).powf(1.0 / 3.0); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `(1.5_f32 + 1.0).cbrt()` + +error: cube-root of a number can be computed more accurately + --> $DIR/floating_point_powf.rs:22:13 + | +LL | let _ = 1.5_f64.powf(1.0 / 3.0); + | ^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `1.5_f64.cbrt()` + +error: square-root of a number can be computed more efficiently and accurately + --> $DIR/floating_point_powf.rs:23:13 + | +LL | let _ = 1.5_f64.powf(1.0 / 2.0); + | ^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `1.5_f64.sqrt()` + +error: exponentiation with integer powers can be computed more efficiently + --> $DIR/floating_point_powf.rs:24:13 + | +LL | let _ = 1.5_f64.powf(3.0); + | ^^^^^^^^^^^^^^^^^ help: consider using: `1.5_f64.powi(3)` + error: exponent for bases 2 and e can be computed more accurately - --> $DIR/floating_point_powf.rs:28:13 + --> $DIR/floating_point_powf.rs:33:13 | LL | let _ = 2f64.powf(x); | ^^^^^^^^^^^^ help: consider using: `x.exp2()` error: exponent for bases 2 and e can be computed more accurately - --> $DIR/floating_point_powf.rs:29:13 + --> $DIR/floating_point_powf.rs:34:13 | LL | let _ = 2f64.powf(3.1); | ^^^^^^^^^^^^^^ help: consider using: `3.1f64.exp2()` error: exponent for bases 2 and e can be computed more accurately - --> $DIR/floating_point_powf.rs:30:13 + --> $DIR/floating_point_powf.rs:35:13 | LL | let _ = 2f64.powf(-3.1); | ^^^^^^^^^^^^^^^ help: consider using: `(-3.1f64).exp2()` error: exponent for bases 2 and e can be computed more accurately - --> $DIR/floating_point_powf.rs:31:13 + --> $DIR/floating_point_powf.rs:36:13 | LL | let _ = std::f64::consts::E.powf(x); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `x.exp()` error: exponent for bases 2 and e can be computed more accurately - --> $DIR/floating_point_powf.rs:32:13 + --> $DIR/floating_point_powf.rs:37:13 | LL | let _ = std::f64::consts::E.powf(3.1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `3.1f64.exp()` error: exponent for bases 2 and e can be computed more accurately - --> $DIR/floating_point_powf.rs:33:13 + --> $DIR/floating_point_powf.rs:38:13 | LL | let _ = std::f64::consts::E.powf(-3.1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `(-3.1f64).exp()` error: square-root of a number can be computed more efficiently and accurately - --> $DIR/floating_point_powf.rs:34:13 + --> $DIR/floating_point_powf.rs:39:13 | LL | let _ = x.powf(1.0 / 2.0); | ^^^^^^^^^^^^^^^^^ help: consider using: `x.sqrt()` error: cube-root of a number can be computed more accurately - --> $DIR/floating_point_powf.rs:35:13 + --> $DIR/floating_point_powf.rs:40:13 | LL | let _ = x.powf(1.0 / 3.0); | ^^^^^^^^^^^^^^^^^ help: consider using: `x.cbrt()` error: exponentiation with integer powers can be computed more efficiently - --> $DIR/floating_point_powf.rs:36:13 + --> $DIR/floating_point_powf.rs:41:13 | LL | let _ = x.powf(3.0); | ^^^^^^^^^^^ help: consider using: `x.powi(3)` error: exponentiation with integer powers can be computed more efficiently - --> $DIR/floating_point_powf.rs:37:13 + --> $DIR/floating_point_powf.rs:42:13 | LL | let _ = x.powf(-2.0); | ^^^^^^^^^^^^ help: consider using: `x.powi(-2)` error: exponentiation with integer powers can be computed more efficiently - --> $DIR/floating_point_powf.rs:38:13 + --> $DIR/floating_point_powf.rs:43:13 | LL | let _ = x.powf(-2_147_483_648.0); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `x.powi(-2_147_483_648)` error: exponentiation with integer powers can be computed more efficiently - --> $DIR/floating_point_powf.rs:39:13 + --> $DIR/floating_point_powf.rs:44:13 | LL | let _ = x.powf(2_147_483_647.0); | ^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `x.powi(2_147_483_647)` -error: aborting due to 27 previous errors +error: aborting due to 31 previous errors diff --git a/src/tools/clippy/tests/ui/large_enum_variant.rs b/src/tools/clippy/tests/ui/large_enum_variant.rs index 23152a13322e8..717009e4c4cca 100644 --- a/src/tools/clippy/tests/ui/large_enum_variant.rs +++ b/src/tools/clippy/tests/ui/large_enum_variant.rs @@ -130,6 +130,30 @@ impl Clone for SomeGenericPossiblyCopyEnum { impl Copy for SomeGenericPossiblyCopyEnum {} +enum LargeEnumWithGenerics { + Small, + Large((T, [u8; 512])), +} + +struct Foo { + foo: T, +} + +enum WithGenerics { + Large([Foo; 64]), + Small(u8), +} + +enum PossiblyLargeEnumWithConst { + SmallBuffer([u8; 4]), + MightyBuffer([u16; U]), +} + +enum LargeEnumOfConst { + Ok, + Error(PossiblyLargeEnumWithConst<256>), +} + fn main() { large_enum_variant!(); } diff --git a/src/tools/clippy/tests/ui/large_enum_variant.stderr b/src/tools/clippy/tests/ui/large_enum_variant.stderr index 0248327262da0..c6ed97487c0e3 100644 --- a/src/tools/clippy/tests/ui/large_enum_variant.stderr +++ b/src/tools/clippy/tests/ui/large_enum_variant.stderr @@ -1,143 +1,177 @@ error: large size difference between variants - --> $DIR/large_enum_variant.rs:12:5 + --> $DIR/large_enum_variant.rs:10:1 | -LL | B([i32; 8000]), - | ^^^^^^^^^^^^^^ this variant is 32000 bytes +LL | / enum LargeEnum { +LL | | A(i32), + | | ------ the second-largest variant contains at least 4 bytes +LL | | B([i32; 8000]), + | | -------------- the largest variant contains at least 32000 bytes +LL | | } + | |_^ the entire enum is at least 32004 bytes | = note: `-D clippy::large-enum-variant` implied by `-D warnings` -note: and the second-largest variant is 4 bytes: - --> $DIR/large_enum_variant.rs:11:5 - | -LL | A(i32), - | ^^^^^^ help: consider boxing the large fields to reduce the total size of the enum | LL | B(Box<[i32; 8000]>), | ~~~~~~~~~~~~~~~~ error: large size difference between variants - --> $DIR/large_enum_variant.rs:36:5 - | -LL | ContainingLargeEnum(LargeEnum), - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this variant is 32004 bytes + --> $DIR/large_enum_variant.rs:34:1 | -note: and the second-largest variant is 8 bytes: - --> $DIR/large_enum_variant.rs:35:5 +LL | / enum LargeEnum2 { +LL | | VariantOk(i32, u32), + | | ------------------- the second-largest variant contains at least 8 bytes +LL | | ContainingLargeEnum(LargeEnum), + | | ------------------------------ the largest variant contains at least 32004 bytes +LL | | } + | |_^ the entire enum is at least 32004 bytes | -LL | VariantOk(i32, u32), - | ^^^^^^^^^^^^^^^^^^^ help: consider boxing the large fields to reduce the total size of the enum | LL | ContainingLargeEnum(Box), | ~~~~~~~~~~~~~~ error: large size difference between variants - --> $DIR/large_enum_variant.rs:40:5 - | -LL | ContainingMoreThanOneField(i32, [i32; 8000], [i32; 9500]), - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this variant is 70004 bytes + --> $DIR/large_enum_variant.rs:39:1 | -note: and the second-largest variant is 8 bytes: - --> $DIR/large_enum_variant.rs:42:5 +LL | / enum LargeEnum3 { +LL | | ContainingMoreThanOneField(i32, [i32; 8000], [i32; 9500]), + | | --------------------------------------------------------- the largest variant contains at least 70004 bytes +LL | | VoidVariant, +LL | | StructLikeLittle { x: i32, y: i32 }, + | | ----------------------------------- the second-largest variant contains at least 8 bytes +LL | | } + | |_^ the entire enum is at least 70008 bytes | -LL | StructLikeLittle { x: i32, y: i32 }, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider boxing the large fields to reduce the total size of the enum | LL | ContainingMoreThanOneField(i32, Box<[i32; 8000]>, Box<[i32; 9500]>), | ~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~ error: large size difference between variants - --> $DIR/large_enum_variant.rs:47:5 + --> $DIR/large_enum_variant.rs:45:1 | -LL | StructLikeLarge { x: [i32; 8000], y: i32 }, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this variant is 32004 bytes +LL | / enum LargeEnum4 { +LL | | VariantOk(i32, u32), + | | ------------------- the second-largest variant contains at least 8 bytes +LL | | StructLikeLarge { x: [i32; 8000], y: i32 }, + | | ------------------------------------------ the largest variant contains at least 32004 bytes +LL | | } + | |_^ the entire enum is at least 32008 bytes | -note: and the second-largest variant is 8 bytes: - --> $DIR/large_enum_variant.rs:46:5 - | -LL | VariantOk(i32, u32), - | ^^^^^^^^^^^^^^^^^^^ help: consider boxing the large fields to reduce the total size of the enum | LL | StructLikeLarge { x: Box<[i32; 8000]>, y: i32 }, | ~~~~~~~~~~~~~~~~ error: large size difference between variants - --> $DIR/large_enum_variant.rs:52:5 - | -LL | StructLikeLarge2 { x: [i32; 8000] }, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this variant is 32000 bytes + --> $DIR/large_enum_variant.rs:50:1 | -note: and the second-largest variant is 8 bytes: - --> $DIR/large_enum_variant.rs:51:5 +LL | / enum LargeEnum5 { +LL | | VariantOk(i32, u32), + | | ------------------- the second-largest variant contains at least 8 bytes +LL | | StructLikeLarge2 { x: [i32; 8000] }, + | | ----------------------------------- the largest variant contains at least 32000 bytes +LL | | } + | |_^ the entire enum is at least 32004 bytes | -LL | VariantOk(i32, u32), - | ^^^^^^^^^^^^^^^^^^^ help: consider boxing the large fields to reduce the total size of the enum | LL | StructLikeLarge2 { x: Box<[i32; 8000]> }, | ~~~~~~~~~~~~~~~~ error: large size difference between variants - --> $DIR/large_enum_variant.rs:68:5 - | -LL | B([u8; 1255]), - | ^^^^^^^^^^^^^ this variant is 1255 bytes + --> $DIR/large_enum_variant.rs:66:1 | -note: and the second-largest variant is 200 bytes: - --> $DIR/large_enum_variant.rs:69:5 +LL | / enum LargeEnum7 { +LL | | A, +LL | | B([u8; 1255]), + | | ------------- the largest variant contains at least 1255 bytes +LL | | C([u8; 200]), + | | ------------ the second-largest variant contains at least 200 bytes +LL | | } + | |_^ the entire enum is at least 1256 bytes | -LL | C([u8; 200]), - | ^^^^^^^^^^^^ help: consider boxing the large fields to reduce the total size of the enum | LL | B(Box<[u8; 1255]>), | ~~~~~~~~~~~~~~~ error: large size difference between variants - --> $DIR/large_enum_variant.rs:74:5 + --> $DIR/large_enum_variant.rs:72:1 | -LL | ContainingMoreThanOneField([i32; 8000], [i32; 2], [i32; 9500], [i32; 30]), - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this variant is 70128 bytes +LL | / enum LargeEnum8 { +LL | | VariantOk(i32, u32), + | | ------------------- the second-largest variant contains at least 8 bytes +LL | | ContainingMoreThanOneField([i32; 8000], [i32; 2], [i32; 9500], [i32; 30]), + | | ------------------------------------------------------------------------- the largest variant contains at least 70128 bytes +LL | | } + | |_^ the entire enum is at least 70132 bytes | -note: and the second-largest variant is 8 bytes: - --> $DIR/large_enum_variant.rs:73:5 - | -LL | VariantOk(i32, u32), - | ^^^^^^^^^^^^^^^^^^^ help: consider boxing the large fields to reduce the total size of the enum | LL | ContainingMoreThanOneField(Box<[i32; 8000]>, [i32; 2], Box<[i32; 9500]>, [i32; 30]), | ~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~ error: large size difference between variants - --> $DIR/large_enum_variant.rs:79:5 + --> $DIR/large_enum_variant.rs:77:1 + | +LL | / enum LargeEnum9 { +LL | | A(Struct<()>), + | | ------------- the second-largest variant contains at least 4 bytes +LL | | B(Struct2), + | | ---------- the largest variant contains at least 32000 bytes +LL | | } + | |_^ the entire enum is at least 32004 bytes + | +help: consider boxing the large fields to reduce the total size of the enum | -LL | B(Struct2), - | ^^^^^^^^^^ this variant is 32000 bytes +LL | B(Box), + | ~~~~~~~~~~~~ + +error: large size difference between variants + --> $DIR/large_enum_variant.rs:82:1 | -note: and the second-largest variant is 4 bytes: - --> $DIR/large_enum_variant.rs:78:5 +LL | / enum LargeEnumOk2 { +LL | | A(T), + | | ---- the second-largest variant contains at least 0 bytes +LL | | B(Struct2), + | | ---------- the largest variant contains at least 32000 bytes +LL | | } + | |_^ the entire enum is at least 32000 bytes | -LL | A(Struct<()>), - | ^^^^^^^^^^^^^ help: consider boxing the large fields to reduce the total size of the enum | LL | B(Box), | ~~~~~~~~~~~~ error: large size difference between variants - --> $DIR/large_enum_variant.rs:104:5 + --> $DIR/large_enum_variant.rs:87:1 | -LL | B([u128; 4000]), - | ^^^^^^^^^^^^^^^ this variant is 64000 bytes +LL | / enum LargeEnumOk3 { +LL | | A(Struct), + | | ------------ the second-largest variant contains at least 4 bytes +LL | | B(Struct2), + | | ---------- the largest variant contains at least 32000 bytes +LL | | } + | |_^ the entire enum is at least 32000 bytes + | +help: consider boxing the large fields to reduce the total size of the enum | -note: and the second-largest variant is 1 bytes: - --> $DIR/large_enum_variant.rs:103:5 +LL | B(Box), + | ~~~~~~~~~~~~ + +error: large size difference between variants + --> $DIR/large_enum_variant.rs:102:1 + | +LL | / enum CopyableLargeEnum { +LL | | A(bool), + | | ------- the second-largest variant contains at least 1 bytes +LL | | B([u128; 4000]), + | | --------------- the largest variant contains at least 64000 bytes +LL | | } + | |_^ the entire enum is at least 64008 bytes | -LL | A(bool), - | ^^^^^^^ note: boxing a variant would require the type no longer be `Copy` --> $DIR/large_enum_variant.rs:102:6 | @@ -150,16 +184,16 @@ LL | B([u128; 4000]), | ^^^^^^^^^^^^^^^ error: large size difference between variants - --> $DIR/large_enum_variant.rs:109:5 + --> $DIR/large_enum_variant.rs:107:1 | -LL | B([u128; 4000]), - | ^^^^^^^^^^^^^^^ this variant is 64000 bytes - | -note: and the second-largest variant is 1 bytes: - --> $DIR/large_enum_variant.rs:108:5 +LL | / enum ManuallyCopyLargeEnum { +LL | | A(bool), + | | ------- the second-largest variant contains at least 1 bytes +LL | | B([u128; 4000]), + | | --------------- the largest variant contains at least 64000 bytes +LL | | } + | |_^ the entire enum is at least 64008 bytes | -LL | A(bool), - | ^^^^^^^ note: boxing a variant would require the type no longer be `Copy` --> $DIR/large_enum_variant.rs:107:6 | @@ -172,16 +206,16 @@ LL | B([u128; 4000]), | ^^^^^^^^^^^^^^^ error: large size difference between variants - --> $DIR/large_enum_variant.rs:122:5 + --> $DIR/large_enum_variant.rs:120:1 | -LL | B([u64; 4000]), - | ^^^^^^^^^^^^^^ this variant is 32000 bytes - | -note: and the second-largest variant is 1 bytes: - --> $DIR/large_enum_variant.rs:121:5 +LL | / enum SomeGenericPossiblyCopyEnum { +LL | | A(bool, std::marker::PhantomData), + | | ------------------------------------ the second-largest variant contains at least 1 bytes +LL | | B([u64; 4000]), + | | -------------- the largest variant contains at least 32000 bytes +LL | | } + | |_^ the entire enum is at least 32008 bytes | -LL | A(bool, std::marker::PhantomData), - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: boxing a variant would require the type no longer be `Copy` --> $DIR/large_enum_variant.rs:120:6 | @@ -193,5 +227,53 @@ help: consider boxing the large fields to reduce the total size of the enum LL | B([u64; 4000]), | ^^^^^^^^^^^^^^ -error: aborting due to 11 previous errors +error: large size difference between variants + --> $DIR/large_enum_variant.rs:133:1 + | +LL | / enum LargeEnumWithGenerics { +LL | | Small, + | | ----- the second-largest variant carries no data at all +LL | | Large((T, [u8; 512])), + | | --------------------- the largest variant contains at least 512 bytes +LL | | } + | |_^ the entire enum is at least 512 bytes + | +help: consider boxing the large fields to reduce the total size of the enum + | +LL | Large(Box<(T, [u8; 512])>), + | ~~~~~~~~~~~~~~~~~~~ + +error: large size difference between variants + --> $DIR/large_enum_variant.rs:142:1 + | +LL | / enum WithGenerics { +LL | | Large([Foo; 64]), + | | --------------------- the largest variant contains at least 512 bytes +LL | | Small(u8), + | | --------- the second-largest variant contains at least 1 bytes +LL | | } + | |_^ the entire enum is at least 520 bytes + | +help: consider boxing the large fields to reduce the total size of the enum + | +LL | Large(Box<[Foo; 64]>), + | ~~~~~~~~~~~~~~~~~~~ + +error: large size difference between variants + --> $DIR/large_enum_variant.rs:152:1 + | +LL | / enum LargeEnumOfConst { +LL | | Ok, + | | -- the second-largest variant carries no data at all +LL | | Error(PossiblyLargeEnumWithConst<256>), + | | -------------------------------------- the largest variant contains at least 514 bytes +LL | | } + | |_^ the entire enum is at least 514 bytes + | +help: consider boxing the large fields to reduce the total size of the enum + | +LL | Error(Box>), + | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +error: aborting due to 16 previous errors diff --git a/src/tools/clippy/tests/ui/match_wild_err_arm.edition2018.stderr b/src/tools/clippy/tests/ui/match_wild_err_arm.edition2018.stderr index 2a4012039ba97..2d66daea8046e 100644 --- a/src/tools/clippy/tests/ui/match_wild_err_arm.edition2018.stderr +++ b/src/tools/clippy/tests/ui/match_wild_err_arm.edition2018.stderr @@ -5,7 +5,7 @@ LL | Err(_) => panic!("err"), | ^^^^^^ | = note: `-D clippy::match-wild-err-arm` implied by `-D warnings` - = note: match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable + = note: match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable error: `Err(_)` matches all errors --> $DIR/match_wild_err_arm.rs:20:9 @@ -13,7 +13,7 @@ error: `Err(_)` matches all errors LL | Err(_) => panic!(), | ^^^^^^ | - = note: match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable + = note: match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable error: `Err(_)` matches all errors --> $DIR/match_wild_err_arm.rs:26:9 @@ -21,7 +21,7 @@ error: `Err(_)` matches all errors LL | Err(_) => { | ^^^^^^ | - = note: match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable + = note: match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable error: `Err(_e)` matches all errors --> $DIR/match_wild_err_arm.rs:34:9 @@ -29,7 +29,7 @@ error: `Err(_e)` matches all errors LL | Err(_e) => panic!(), | ^^^^^^^ | - = note: match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable + = note: match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable error: aborting due to 4 previous errors diff --git a/src/tools/clippy/tests/ui/match_wild_err_arm.edition2021.stderr b/src/tools/clippy/tests/ui/match_wild_err_arm.edition2021.stderr index 2a4012039ba97..2d66daea8046e 100644 --- a/src/tools/clippy/tests/ui/match_wild_err_arm.edition2021.stderr +++ b/src/tools/clippy/tests/ui/match_wild_err_arm.edition2021.stderr @@ -5,7 +5,7 @@ LL | Err(_) => panic!("err"), | ^^^^^^ | = note: `-D clippy::match-wild-err-arm` implied by `-D warnings` - = note: match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable + = note: match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable error: `Err(_)` matches all errors --> $DIR/match_wild_err_arm.rs:20:9 @@ -13,7 +13,7 @@ error: `Err(_)` matches all errors LL | Err(_) => panic!(), | ^^^^^^ | - = note: match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable + = note: match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable error: `Err(_)` matches all errors --> $DIR/match_wild_err_arm.rs:26:9 @@ -21,7 +21,7 @@ error: `Err(_)` matches all errors LL | Err(_) => { | ^^^^^^ | - = note: match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable + = note: match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable error: `Err(_e)` matches all errors --> $DIR/match_wild_err_arm.rs:34:9 @@ -29,7 +29,7 @@ error: `Err(_e)` matches all errors LL | Err(_e) => panic!(), | ^^^^^^^ | - = note: match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable + = note: match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable error: aborting due to 4 previous errors diff --git a/src/tools/clippy/tests/ui/mut_mutex_lock.fixed b/src/tools/clippy/tests/ui/mut_mutex_lock.fixed index 36bc52e3374e1..ecad10a829038 100644 --- a/src/tools/clippy/tests/ui/mut_mutex_lock.fixed +++ b/src/tools/clippy/tests/ui/mut_mutex_lock.fixed @@ -18,4 +18,11 @@ fn no_owned_mutex_lock() { *value += 1; } +fn issue9415() { + let mut arc_mutex = Arc::new(Mutex::new(42_u8)); + let arc_mutex: &mut Arc> = &mut arc_mutex; + let mut guard = arc_mutex.lock().unwrap(); + *guard += 1; +} + fn main() {} diff --git a/src/tools/clippy/tests/ui/mut_mutex_lock.rs b/src/tools/clippy/tests/ui/mut_mutex_lock.rs index ea60df5ae1bbc..f2b1d6fbfbc3e 100644 --- a/src/tools/clippy/tests/ui/mut_mutex_lock.rs +++ b/src/tools/clippy/tests/ui/mut_mutex_lock.rs @@ -18,4 +18,11 @@ fn no_owned_mutex_lock() { *value += 1; } +fn issue9415() { + let mut arc_mutex = Arc::new(Mutex::new(42_u8)); + let arc_mutex: &mut Arc> = &mut arc_mutex; + let mut guard = arc_mutex.lock().unwrap(); + *guard += 1; +} + fn main() {} diff --git a/src/tools/clippy/tests/ui/or_fun_call.fixed b/src/tools/clippy/tests/ui/or_fun_call.fixed index 18ea4e550292a..5991188ab6372 100644 --- a/src/tools/clippy/tests/ui/or_fun_call.fixed +++ b/src/tools/clippy/tests/ui/or_fun_call.fixed @@ -79,16 +79,16 @@ fn or_fun_call() { without_default.unwrap_or_else(Foo::new); let mut map = HashMap::::new(); - map.entry(42).or_insert(String::new()); + map.entry(42).or_default(); let mut map_vec = HashMap::>::new(); - map_vec.entry(42).or_insert(vec![]); + map_vec.entry(42).or_default(); let mut btree = BTreeMap::::new(); - btree.entry(42).or_insert(String::new()); + btree.entry(42).or_default(); let mut btree_vec = BTreeMap::>::new(); - btree_vec.entry(42).or_insert(vec![]); + btree_vec.entry(42).or_default(); let stringy = Some(String::new()); let _ = stringy.unwrap_or_default(); diff --git a/src/tools/clippy/tests/ui/or_fun_call.stderr b/src/tools/clippy/tests/ui/or_fun_call.stderr index 887f23ac9761d..e3dab4cb14778 100644 --- a/src/tools/clippy/tests/ui/or_fun_call.stderr +++ b/src/tools/clippy/tests/ui/or_fun_call.stderr @@ -66,6 +66,30 @@ error: use of `unwrap_or` followed by a function call LL | without_default.unwrap_or(Foo::new()); | ^^^^^^^^^^^^^^^^^^^^^ help: try this: `unwrap_or_else(Foo::new)` +error: use of `or_insert` followed by a call to `new` + --> $DIR/or_fun_call.rs:82:19 + | +LL | map.entry(42).or_insert(String::new()); + | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `or_default()` + +error: use of `or_insert` followed by a call to `new` + --> $DIR/or_fun_call.rs:85:23 + | +LL | map_vec.entry(42).or_insert(vec![]); + | ^^^^^^^^^^^^^^^^^ help: try this: `or_default()` + +error: use of `or_insert` followed by a call to `new` + --> $DIR/or_fun_call.rs:88:21 + | +LL | btree.entry(42).or_insert(String::new()); + | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `or_default()` + +error: use of `or_insert` followed by a call to `new` + --> $DIR/or_fun_call.rs:91:25 + | +LL | btree_vec.entry(42).or_insert(vec![]); + | ^^^^^^^^^^^^^^^^^ help: try this: `or_default()` + error: use of `unwrap_or` followed by a call to `new` --> $DIR/or_fun_call.rs:94:21 | @@ -132,5 +156,5 @@ error: use of `unwrap_or` followed by a call to `new` LL | .unwrap_or(String::new()); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `unwrap_or_default()` -error: aborting due to 22 previous errors +error: aborting due to 26 previous errors diff --git a/src/tools/clippy/tests/ui/range_plus_minus_one.fixed b/src/tools/clippy/tests/ui/range_plus_minus_one.fixed index 40d7791df281a..a16a3e54d45ea 100644 --- a/src/tools/clippy/tests/ui/range_plus_minus_one.fixed +++ b/src/tools/clippy/tests/ui/range_plus_minus_one.fixed @@ -6,6 +6,22 @@ fn f() -> usize { 42 } +macro_rules! macro_plus_one { + ($m: literal) => { + for i in 0..$m + 1 { + println!("{}", i); + } + }; +} + +macro_rules! macro_minus_one { + ($m: literal) => { + for i in 0..=$m - 1 { + println!("{}", i); + } + }; +} + #[warn(clippy::range_plus_one)] #[warn(clippy::range_minus_one)] fn main() { @@ -39,4 +55,7 @@ fn main() { let mut vec: Vec<()> = std::vec::Vec::new(); vec.drain(..); + + macro_plus_one!(5); + macro_minus_one!(5); } diff --git a/src/tools/clippy/tests/ui/range_plus_minus_one.rs b/src/tools/clippy/tests/ui/range_plus_minus_one.rs index a8ddd9b5f751b..bd6cb4d21be51 100644 --- a/src/tools/clippy/tests/ui/range_plus_minus_one.rs +++ b/src/tools/clippy/tests/ui/range_plus_minus_one.rs @@ -6,6 +6,22 @@ fn f() -> usize { 42 } +macro_rules! macro_plus_one { + ($m: literal) => { + for i in 0..$m + 1 { + println!("{}", i); + } + }; +} + +macro_rules! macro_minus_one { + ($m: literal) => { + for i in 0..=$m - 1 { + println!("{}", i); + } + }; +} + #[warn(clippy::range_plus_one)] #[warn(clippy::range_minus_one)] fn main() { @@ -39,4 +55,7 @@ fn main() { let mut vec: Vec<()> = std::vec::Vec::new(); vec.drain(..); + + macro_plus_one!(5); + macro_minus_one!(5); } diff --git a/src/tools/clippy/tests/ui/range_plus_minus_one.stderr b/src/tools/clippy/tests/ui/range_plus_minus_one.stderr index fb4f1658597a5..0223696243b20 100644 --- a/src/tools/clippy/tests/ui/range_plus_minus_one.stderr +++ b/src/tools/clippy/tests/ui/range_plus_minus_one.stderr @@ -1,5 +1,5 @@ error: an inclusive range would be more readable - --> $DIR/range_plus_minus_one.rs:15:14 + --> $DIR/range_plus_minus_one.rs:31:14 | LL | for _ in 0..3 + 1 {} | ^^^^^^^^ help: use: `0..=3` @@ -7,25 +7,25 @@ LL | for _ in 0..3 + 1 {} = note: `-D clippy::range-plus-one` implied by `-D warnings` error: an inclusive range would be more readable - --> $DIR/range_plus_minus_one.rs:18:14 + --> $DIR/range_plus_minus_one.rs:34:14 | LL | for _ in 0..1 + 5 {} | ^^^^^^^^ help: use: `0..=5` error: an inclusive range would be more readable - --> $DIR/range_plus_minus_one.rs:21:14 + --> $DIR/range_plus_minus_one.rs:37:14 | LL | for _ in 1..1 + 1 {} | ^^^^^^^^ help: use: `1..=1` error: an inclusive range would be more readable - --> $DIR/range_plus_minus_one.rs:27:14 + --> $DIR/range_plus_minus_one.rs:43:14 | LL | for _ in 0..(1 + f()) {} | ^^^^^^^^^^^^ help: use: `0..=f()` error: an exclusive range would be more readable - --> $DIR/range_plus_minus_one.rs:31:13 + --> $DIR/range_plus_minus_one.rs:47:13 | LL | let _ = ..=11 - 1; | ^^^^^^^^^ help: use: `..11` @@ -33,25 +33,25 @@ LL | let _ = ..=11 - 1; = note: `-D clippy::range-minus-one` implied by `-D warnings` error: an exclusive range would be more readable - --> $DIR/range_plus_minus_one.rs:32:13 + --> $DIR/range_plus_minus_one.rs:48:13 | LL | let _ = ..=(11 - 1); | ^^^^^^^^^^^ help: use: `..11` error: an inclusive range would be more readable - --> $DIR/range_plus_minus_one.rs:33:13 + --> $DIR/range_plus_minus_one.rs:49:13 | LL | let _ = (1..11 + 1); | ^^^^^^^^^^^ help: use: `(1..=11)` error: an inclusive range would be more readable - --> $DIR/range_plus_minus_one.rs:34:13 + --> $DIR/range_plus_minus_one.rs:50:13 | LL | let _ = (f() + 1)..(f() + 1); | ^^^^^^^^^^^^^^^^^^^^ help: use: `((f() + 1)..=f())` error: an inclusive range would be more readable - --> $DIR/range_plus_minus_one.rs:38:14 + --> $DIR/range_plus_minus_one.rs:54:14 | LL | for _ in 1..ONE + ONE {} | ^^^^^^^^^^^^ help: use: `1..=ONE` diff --git a/src/tools/clippy/tests/ui/result_large_err.rs b/src/tools/clippy/tests/ui/result_large_err.rs index 78d8f76fe669f..f7df3b8565501 100644 --- a/src/tools/clippy/tests/ui/result_large_err.rs +++ b/src/tools/clippy/tests/ui/result_large_err.rs @@ -1,4 +1,5 @@ #![warn(clippy::result_large_err)] +#![allow(clippy::large_enum_variant)] pub fn small_err() -> Result<(), u128> { Ok(()) diff --git a/src/tools/clippy/tests/ui/result_large_err.stderr b/src/tools/clippy/tests/ui/result_large_err.stderr index 0f1f39d72cba1..ef19f2854ab12 100644 --- a/src/tools/clippy/tests/ui/result_large_err.stderr +++ b/src/tools/clippy/tests/ui/result_large_err.stderr @@ -1,5 +1,5 @@ error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:7:23 + --> $DIR/result_large_err.rs:8:23 | LL | pub fn large_err() -> Result<(), [u8; 512]> { | ^^^^^^^^^^^^^^^^^^^^^ the `Err`-variant is at least 512 bytes @@ -8,7 +8,7 @@ LL | pub fn large_err() -> Result<(), [u8; 512]> { = help: try reducing the size of `[u8; 512]`, for example by boxing large elements or replacing it with `Box<[u8; 512]>` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:18:21 + --> $DIR/result_large_err.rs:19:21 | LL | pub fn ret() -> Result<(), Self> { | ^^^^^^^^^^^^^^^^ the `Err`-variant is at least 240 bytes @@ -16,7 +16,7 @@ LL | pub fn ret() -> Result<(), Self> { = help: try reducing the size of `FullyDefinedLargeError`, for example by boxing large elements or replacing it with `Box` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:23:26 + --> $DIR/result_large_err.rs:24:26 | LL | pub fn struct_error() -> Result<(), FullyDefinedLargeError> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the `Err`-variant is at least 240 bytes @@ -24,7 +24,7 @@ LL | pub fn struct_error() -> Result<(), FullyDefinedLargeError> { = help: try reducing the size of `FullyDefinedLargeError`, for example by boxing large elements or replacing it with `Box` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:28:45 + --> $DIR/result_large_err.rs:29:45 | LL | pub fn large_err_via_type_alias(x: T) -> Fdlr { | ^^^^^^^ the `Err`-variant is at least 240 bytes @@ -32,7 +32,7 @@ LL | pub fn large_err_via_type_alias(x: T) -> Fdlr { = help: try reducing the size of `FullyDefinedLargeError`, for example by boxing large elements or replacing it with `Box` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:36:34 + --> $DIR/result_large_err.rs:37:34 | LL | pub fn param_large_error() -> Result<(), (u128, R, FullyDefinedLargeError)> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the `Err`-variant is at least 256 bytes @@ -40,7 +40,7 @@ LL | pub fn param_large_error() -> Result<(), (u128, R, FullyDefinedLargeErro = help: try reducing the size of `(u128, R, FullyDefinedLargeError)`, for example by boxing large elements or replacing it with `Box<(u128, R, FullyDefinedLargeError)>` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:47:34 + --> $DIR/result_large_err.rs:48:34 | LL | pub fn large_enum_error() -> Result<(), Self> { | ^^^^^^^^^^^^^^^^ the `Err`-variant is at least 513 bytes @@ -48,7 +48,7 @@ LL | pub fn large_enum_error() -> Result<(), Self> { = help: try reducing the size of `LargeErrorVariants<()>`, for example by boxing large elements or replacing it with `Box>` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:53:25 + --> $DIR/result_large_err.rs:54:25 | LL | fn large_error() -> Result<(), [u8; 512]> { | ^^^^^^^^^^^^^^^^^^^^^ the `Err`-variant is at least 512 bytes @@ -56,7 +56,7 @@ LL | fn large_error() -> Result<(), [u8; 512]> { = help: try reducing the size of `[u8; 512]`, for example by boxing large elements or replacing it with `Box<[u8; 512]>` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:72:29 + --> $DIR/result_large_err.rs:73:29 | LL | pub fn large_union_err() -> Result<(), FullyDefinedUnionError> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the `Err`-variant is at least 512 bytes @@ -64,7 +64,7 @@ LL | pub fn large_union_err() -> Result<(), FullyDefinedUnionError> { = help: try reducing the size of `FullyDefinedUnionError`, for example by boxing large elements or replacing it with `Box` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:81:40 + --> $DIR/result_large_err.rs:82:40 | LL | pub fn param_large_union() -> Result<(), UnionError> { | ^^^^^^^^^^^^^^^^^^^^^^^^^ the `Err`-variant is at least 512 bytes @@ -72,7 +72,7 @@ LL | pub fn param_large_union() -> Result<(), UnionError> { = help: try reducing the size of `UnionError`, for example by boxing large elements or replacing it with `Box>` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:90:34 + --> $DIR/result_large_err.rs:91:34 | LL | pub fn array_error_subst() -> Result<(), ArrayError> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the `Err`-variant is at least 128 bytes @@ -80,7 +80,7 @@ LL | pub fn array_error_subst() -> Result<(), ArrayError> { = help: try reducing the size of `ArrayError`, for example by boxing large elements or replacing it with `Box>` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:94:31 + --> $DIR/result_large_err.rs:95:31 | LL | pub fn array_error() -> Result<(), ArrayError<(i32, T), U>> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the `Err`-variant is at least 128 bytes diff --git a/src/tools/clippy/tests/ui/unnecessary_to_owned.fixed b/src/tools/clippy/tests/ui/unnecessary_to_owned.fixed index 9cd5bc73b1ec5..a920c63b199c1 100644 --- a/src/tools/clippy/tests/ui/unnecessary_to_owned.fixed +++ b/src/tools/clippy/tests/ui/unnecessary_to_owned.fixed @@ -357,3 +357,63 @@ mod issue_9317 { consume(b.to_string()); } } + +mod issue_9351 { + #![allow(dead_code)] + + use std::ops::Deref; + use std::path::{Path, PathBuf}; + + fn require_deref_path>(x: T) -> T { + x + } + + fn generic_arg_used_elsewhere>(_x: T, _y: T) {} + + fn id>(x: T) -> T { + x + } + + fn predicates_are_satisfied(_x: impl std::fmt::Write) {} + + // Should lint + fn single_return() -> impl AsRef { + id("abc") + } + + // Should not lint + fn multiple_returns(b: bool) -> impl AsRef { + if b { + return String::new(); + } + + id("abc".to_string()) + } + + struct S1(String); + + // Should not lint + fn fields1() -> S1 { + S1(id("abc".to_string())) + } + + struct S2 { + s: String, + } + + // Should not lint + fn fields2() { + let mut s = S2 { s: "abc".into() }; + s.s = id("abc".to_string()); + } + + pub fn main() { + let path = std::path::Path::new("x"); + let path_buf = path.to_owned(); + + // Should not lint. + let _x: PathBuf = require_deref_path(path.to_owned()); + generic_arg_used_elsewhere(path.to_owned(), path_buf); + predicates_are_satisfied(id("abc".to_string())); + } +} diff --git a/src/tools/clippy/tests/ui/unnecessary_to_owned.rs b/src/tools/clippy/tests/ui/unnecessary_to_owned.rs index 7f62ba3ab5d55..2128bdacddadf 100644 --- a/src/tools/clippy/tests/ui/unnecessary_to_owned.rs +++ b/src/tools/clippy/tests/ui/unnecessary_to_owned.rs @@ -357,3 +357,63 @@ mod issue_9317 { consume(b.to_string()); } } + +mod issue_9351 { + #![allow(dead_code)] + + use std::ops::Deref; + use std::path::{Path, PathBuf}; + + fn require_deref_path>(x: T) -> T { + x + } + + fn generic_arg_used_elsewhere>(_x: T, _y: T) {} + + fn id>(x: T) -> T { + x + } + + fn predicates_are_satisfied(_x: impl std::fmt::Write) {} + + // Should lint + fn single_return() -> impl AsRef { + id("abc".to_string()) + } + + // Should not lint + fn multiple_returns(b: bool) -> impl AsRef { + if b { + return String::new(); + } + + id("abc".to_string()) + } + + struct S1(String); + + // Should not lint + fn fields1() -> S1 { + S1(id("abc".to_string())) + } + + struct S2 { + s: String, + } + + // Should not lint + fn fields2() { + let mut s = S2 { s: "abc".into() }; + s.s = id("abc".to_string()); + } + + pub fn main() { + let path = std::path::Path::new("x"); + let path_buf = path.to_owned(); + + // Should not lint. + let _x: PathBuf = require_deref_path(path.to_owned()); + generic_arg_used_elsewhere(path.to_owned(), path_buf); + predicates_are_satisfied(id("abc".to_string())); + } +} diff --git a/src/tools/clippy/tests/ui/unnecessary_to_owned.stderr b/src/tools/clippy/tests/ui/unnecessary_to_owned.stderr index 243b4599dba42..7deb90b06f3b7 100644 --- a/src/tools/clippy/tests/ui/unnecessary_to_owned.stderr +++ b/src/tools/clippy/tests/ui/unnecessary_to_owned.stderr @@ -509,5 +509,11 @@ error: unnecessary use of `to_string` LL | Box::new(build(y.to_string())) | ^^^^^^^^^^^^^ help: use: `y` -error: aborting due to 78 previous errors +error: unnecessary use of `to_string` + --> $DIR/unnecessary_to_owned.rs:381:12 + | +LL | id("abc".to_string()) + | ^^^^^^^^^^^^^^^^^ help: use: `"abc"` + +error: aborting due to 79 previous errors diff --git a/src/tools/clippy/tests/ui/unwrap_or_else_default.fixed b/src/tools/clippy/tests/ui/unwrap_or_else_default.fixed index c2b9bd2c881fe..84f779569ff9d 100644 --- a/src/tools/clippy/tests/ui/unwrap_or_else_default.fixed +++ b/src/tools/clippy/tests/ui/unwrap_or_else_default.fixed @@ -69,6 +69,9 @@ fn unwrap_or_else_default() { let with_default_type: Option> = None; with_default_type.unwrap_or_default(); + + let empty_string = None::; + empty_string.unwrap_or_default(); } fn main() {} diff --git a/src/tools/clippy/tests/ui/unwrap_or_else_default.rs b/src/tools/clippy/tests/ui/unwrap_or_else_default.rs index d55664990aeb9..1735bd5808e5a 100644 --- a/src/tools/clippy/tests/ui/unwrap_or_else_default.rs +++ b/src/tools/clippy/tests/ui/unwrap_or_else_default.rs @@ -69,6 +69,9 @@ fn unwrap_or_else_default() { let with_default_type: Option> = None; with_default_type.unwrap_or_else(Vec::new); + + let empty_string = None::; + empty_string.unwrap_or_else(|| "".to_string()); } fn main() {} diff --git a/src/tools/clippy/tests/ui/unwrap_or_else_default.stderr b/src/tools/clippy/tests/ui/unwrap_or_else_default.stderr index 53e31d85edfca..d2b9212223f77 100644 --- a/src/tools/clippy/tests/ui/unwrap_or_else_default.stderr +++ b/src/tools/clippy/tests/ui/unwrap_or_else_default.stderr @@ -30,5 +30,11 @@ error: use of `.unwrap_or_else(..)` to construct default value LL | with_default_type.unwrap_or_else(Vec::new); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `with_default_type.unwrap_or_default()` -error: aborting due to 5 previous errors +error: use of `.unwrap_or_else(..)` to construct default value + --> $DIR/unwrap_or_else_default.rs:74:5 + | +LL | empty_string.unwrap_or_else(|| "".to_string()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `empty_string.unwrap_or_default()` + +error: aborting due to 6 previous errors diff --git a/src/tools/clippy/tests/ui/vec_init_then_push.rs b/src/tools/clippy/tests/ui/vec_init_then_push.rs index 531745424a7d0..8dd098a5b5405 100644 --- a/src/tools/clippy/tests/ui/vec_init_then_push.rs +++ b/src/tools/clippy/tests/ui/vec_init_then_push.rs @@ -104,3 +104,9 @@ fn _cond_push_with_large_start(x: bool) -> Vec { v2 } + +fn f() { + let mut v = Vec::new(); + v.push((0i32, 0i32)); + let y = v[0].0.abs(); +} diff --git a/src/tools/clippy/tests/ui/vec_init_then_push.stderr b/src/tools/clippy/tests/ui/vec_init_then_push.stderr index 50b029fc33727..a9da1c520197d 100644 --- a/src/tools/clippy/tests/ui/vec_init_then_push.stderr +++ b/src/tools/clippy/tests/ui/vec_init_then_push.stderr @@ -62,5 +62,12 @@ LL | | v2.push(1); LL | | v2.push(0); | |_______________^ help: consider using the `vec![]` macro: `let mut v2 = vec![..];` -error: aborting due to 7 previous errors +error: calls to `push` immediately after creation + --> $DIR/vec_init_then_push.rs:109:5 + | +LL | / let mut v = Vec::new(); +LL | | v.push((0i32, 0i32)); + | |_________________________^ help: consider using the `vec![]` macro: `let v = vec![..];` + +error: aborting due to 8 previous errors