diff --git a/clippy_dev/src/update_lints.rs b/clippy_dev/src/update_lints.rs index 28bec872c..b95061bf8 100644 --- a/clippy_dev/src/update_lints.rs +++ b/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)); } } } @@ -1120,6 +1195,7 @@ mod tests { "\"really long text\"", "module_name", Range::default(), + String::new(), ), Lint::new( "doc_markdown", @@ -1127,6 +1203,7 @@ mod tests { "\"single line\"", "module_name", Range::default(), + String::new(), ), ]; assert_eq!(expected, result); @@ -1166,6 +1243,7 @@ mod tests { "\"abc\"", "module_name", Range::default(), + String::new(), ), Lint::new( "should_assert_eq2", @@ -1173,6 +1251,7 @@ mod tests { "\"abc\"", "module_name", Range::default(), + String::new(), ), Lint::new( "should_assert_eq2", @@ -1180,6 +1259,7 @@ mod tests { "\"abc\"", "module_name", Range::default(), + String::new(), ), ]; let expected = vec![Lint::new( @@ -1188,6 +1268,7 @@ mod tests { "\"abc\"", "module_name", Range::default(), + String::new(), )]; assert_eq!(expected, Lint::usable_lints(&lints)); } @@ -1195,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( @@ -1221,6 +1331,7 @@ mod tests { "\"abc\"", "module_name", Range::default(), + String::new(), )], ); assert_eq!(expected, Lint::by_lint_group(lints.into_iter())); @@ -1259,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/docs.rs b/src/docs.rs new file mode 100644 index 000000000..69243bf4d --- /dev/null +++ b/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", + "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/docs/absurd_extreme_comparisons.txt b/src/docs/absurd_extreme_comparisons.txt new file mode 100644 index 000000000..590bee28a --- /dev/null +++ b/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/docs/alloc_instead_of_core.txt b/src/docs/alloc_instead_of_core.txt new file mode 100644 index 000000000..488a36e92 --- /dev/null +++ b/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/docs/allow_attributes_without_reason.txt b/src/docs/allow_attributes_without_reason.txt new file mode 100644 index 000000000..fcc4f49b0 --- /dev/null +++ b/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/docs/almost_complete_letter_range.txt b/src/docs/almost_complete_letter_range.txt new file mode 100644 index 000000000..01cbaf9ea --- /dev/null +++ b/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/docs/almost_swapped.txt b/src/docs/almost_swapped.txt new file mode 100644 index 000000000..cd10a8d54 --- /dev/null +++ b/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/docs/approx_constant.txt b/src/docs/approx_constant.txt new file mode 100644 index 000000000..393fa4b5e --- /dev/null +++ b/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/docs/arithmetic.txt b/src/docs/arithmetic.txt new file mode 100644 index 000000000..0b3f07d95 --- /dev/null +++ b/src/docs/arithmetic.txt @@ -0,0 +1,28 @@ +### What it does +Checks for 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. + +### 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; +``` + +Third-party types also tend to overflow. + +#### Example +``` +use rust_decimal::Decimal; +let _n = Decimal::MAX + Decimal::MAX; +``` + +### Allowed types +Custom allowed types can be specified through the "arithmetic-allowed" filter. \ No newline at end of file diff --git a/src/docs/as_conversions.txt b/src/docs/as_conversions.txt new file mode 100644 index 000000000..4af479bd8 --- /dev/null +++ b/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/docs/as_underscore.txt b/src/docs/as_underscore.txt new file mode 100644 index 000000000..2d9b0c358 --- /dev/null +++ b/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/docs/assertions_on_constants.txt b/src/docs/assertions_on_constants.txt new file mode 100644 index 000000000..270c1e3b6 --- /dev/null +++ b/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/docs/assertions_on_result_states.txt b/src/docs/assertions_on_result_states.txt new file mode 100644 index 000000000..0889084fd --- /dev/null +++ b/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/docs/assign_op_pattern.txt b/src/docs/assign_op_pattern.txt new file mode 100644 index 000000000..f355c0cc1 --- /dev/null +++ b/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/docs/async_yields_async.txt b/src/docs/async_yields_async.txt new file mode 100644 index 000000000..a40de6d2e --- /dev/null +++ b/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/docs/await_holding_invalid_type.txt b/src/docs/await_holding_invalid_type.txt new file mode 100644 index 000000000..e9c768772 --- /dev/null +++ b/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/docs/await_holding_lock.txt b/src/docs/await_holding_lock.txt new file mode 100644 index 000000000..0f450a111 --- /dev/null +++ b/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/docs/await_holding_refcell_ref.txt b/src/docs/await_holding_refcell_ref.txt new file mode 100644 index 000000000..226a261b9 --- /dev/null +++ b/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/docs/bad_bit_mask.txt b/src/docs/bad_bit_mask.txt new file mode 100644 index 000000000..d40024ee5 --- /dev/null +++ b/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/docs/bind_instead_of_map.txt b/src/docs/bind_instead_of_map.txt new file mode 100644 index 000000000..148575803 --- /dev/null +++ b/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/docs/blanket_clippy_restriction_lints.txt b/src/docs/blanket_clippy_restriction_lints.txt new file mode 100644 index 000000000..28a4ebf71 --- /dev/null +++ b/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/docs/blocks_in_if_conditions.txt b/src/docs/blocks_in_if_conditions.txt new file mode 100644 index 000000000..3afa14853 --- /dev/null +++ b/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/docs/bool_assert_comparison.txt b/src/docs/bool_assert_comparison.txt new file mode 100644 index 000000000..df7ca00cc --- /dev/null +++ b/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/docs/bool_comparison.txt b/src/docs/bool_comparison.txt new file mode 100644 index 000000000..0996f60ce --- /dev/null +++ b/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/docs/bool_to_int_with_if.txt b/src/docs/bool_to_int_with_if.txt new file mode 100644 index 000000000..63535b454 --- /dev/null +++ b/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/docs/borrow_as_ptr.txt b/src/docs/borrow_as_ptr.txt new file mode 100644 index 000000000..0be865abd --- /dev/null +++ b/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/docs/borrow_deref_ref.txt b/src/docs/borrow_deref_ref.txt new file mode 100644 index 000000000..352480d3f --- /dev/null +++ b/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/docs/borrow_interior_mutable_const.txt b/src/docs/borrow_interior_mutable_const.txt new file mode 100644 index 000000000..e55b6a77e --- /dev/null +++ b/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/docs/borrowed_box.txt b/src/docs/borrowed_box.txt new file mode 100644 index 000000000..d7089be66 --- /dev/null +++ b/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/docs/box_collection.txt b/src/docs/box_collection.txt new file mode 100644 index 000000000..053f24c46 --- /dev/null +++ b/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/docs/boxed_local.txt b/src/docs/boxed_local.txt new file mode 100644 index 000000000..8b1febf14 --- /dev/null +++ b/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/docs/branches_sharing_code.txt b/src/docs/branches_sharing_code.txt new file mode 100644 index 000000000..79be61247 --- /dev/null +++ b/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/docs/builtin_type_shadow.txt b/src/docs/builtin_type_shadow.txt new file mode 100644 index 000000000..15b1c9df7 --- /dev/null +++ b/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/docs/bytes_count_to_len.txt b/src/docs/bytes_count_to_len.txt new file mode 100644 index 000000000..ca7bf9a38 --- /dev/null +++ b/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/docs/bytes_nth.txt b/src/docs/bytes_nth.txt new file mode 100644 index 000000000..260de3433 --- /dev/null +++ b/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/docs/cargo_common_metadata.txt b/src/docs/cargo_common_metadata.txt new file mode 100644 index 000000000..1998647a9 --- /dev/null +++ b/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/docs/case_sensitive_file_extension_comparisons.txt b/src/docs/case_sensitive_file_extension_comparisons.txt new file mode 100644 index 000000000..8e6e18ed4 --- /dev/null +++ b/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/docs/cast_abs_to_unsigned.txt b/src/docs/cast_abs_to_unsigned.txt new file mode 100644 index 000000000..c5d8ee034 --- /dev/null +++ b/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/docs/cast_enum_constructor.txt b/src/docs/cast_enum_constructor.txt new file mode 100644 index 000000000..675c03a42 --- /dev/null +++ b/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/docs/cast_enum_truncation.txt b/src/docs/cast_enum_truncation.txt new file mode 100644 index 000000000..abe32a829 --- /dev/null +++ b/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/docs/cast_lossless.txt b/src/docs/cast_lossless.txt new file mode 100644 index 000000000..c3a61dd47 --- /dev/null +++ b/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/docs/cast_possible_truncation.txt b/src/docs/cast_possible_truncation.txt new file mode 100644 index 000000000..0b164848c --- /dev/null +++ b/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/docs/cast_possible_wrap.txt b/src/docs/cast_possible_wrap.txt new file mode 100644 index 000000000..f883fc9cf --- /dev/null +++ b/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/docs/cast_precision_loss.txt b/src/docs/cast_precision_loss.txt new file mode 100644 index 000000000..f915d9f8a --- /dev/null +++ b/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/docs/cast_ptr_alignment.txt b/src/docs/cast_ptr_alignment.txt new file mode 100644 index 000000000..6a6d4dcaa --- /dev/null +++ b/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/docs/cast_ref_to_mut.txt b/src/docs/cast_ref_to_mut.txt new file mode 100644 index 000000000..fb5b4dbb6 --- /dev/null +++ b/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/docs/cast_sign_loss.txt b/src/docs/cast_sign_loss.txt new file mode 100644 index 000000000..d64fe1b07 --- /dev/null +++ b/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/docs/cast_slice_different_sizes.txt b/src/docs/cast_slice_different_sizes.txt new file mode 100644 index 000000000..c01ef0ba9 --- /dev/null +++ b/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/docs/cast_slice_from_raw_parts.txt b/src/docs/cast_slice_from_raw_parts.txt new file mode 100644 index 000000000..b58c73976 --- /dev/null +++ b/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/docs/char_lit_as_u8.txt b/src/docs/char_lit_as_u8.txt new file mode 100644 index 000000000..00d60b9a4 --- /dev/null +++ b/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/docs/chars_last_cmp.txt b/src/docs/chars_last_cmp.txt new file mode 100644 index 000000000..4c1d88389 --- /dev/null +++ b/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/docs/chars_next_cmp.txt b/src/docs/chars_next_cmp.txt new file mode 100644 index 000000000..77cbce2de --- /dev/null +++ b/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/docs/checked_conversions.txt b/src/docs/checked_conversions.txt new file mode 100644 index 000000000..536b01294 --- /dev/null +++ b/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/docs/clone_double_ref.txt b/src/docs/clone_double_ref.txt new file mode 100644 index 000000000..2729635bd --- /dev/null +++ b/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/docs/clone_on_copy.txt b/src/docs/clone_on_copy.txt new file mode 100644 index 000000000..99a0bdb4c --- /dev/null +++ b/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/docs/clone_on_ref_ptr.txt b/src/docs/clone_on_ref_ptr.txt new file mode 100644 index 000000000..2d83f8fef --- /dev/null +++ b/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/docs/cloned_instead_of_copied.txt b/src/docs/cloned_instead_of_copied.txt new file mode 100644 index 000000000..2f2014d5f --- /dev/null +++ b/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/docs/cmp_nan.txt b/src/docs/cmp_nan.txt new file mode 100644 index 000000000..e2ad04d93 --- /dev/null +++ b/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/docs/cmp_null.txt b/src/docs/cmp_null.txt new file mode 100644 index 000000000..02fd15124 --- /dev/null +++ b/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/docs/cmp_owned.txt b/src/docs/cmp_owned.txt new file mode 100644 index 000000000..f8d4956ff --- /dev/null +++ b/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/docs/cognitive_complexity.txt b/src/docs/cognitive_complexity.txt new file mode 100644 index 000000000..fdd75f647 --- /dev/null +++ b/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/docs/collapsible_else_if.txt b/src/docs/collapsible_else_if.txt new file mode 100644 index 000000000..4ddfca177 --- /dev/null +++ b/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/docs/collapsible_if.txt b/src/docs/collapsible_if.txt new file mode 100644 index 000000000..e1264ee06 --- /dev/null +++ b/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/docs/collapsible_match.txt b/src/docs/collapsible_match.txt new file mode 100644 index 000000000..0d59594a0 --- /dev/null +++ b/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/docs/collapsible_str_replace.txt b/src/docs/collapsible_str_replace.txt new file mode 100644 index 000000000..c24c25a30 --- /dev/null +++ b/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/docs/comparison_chain.txt b/src/docs/comparison_chain.txt new file mode 100644 index 000000000..43b09f31f --- /dev/null +++ b/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/docs/comparison_to_empty.txt b/src/docs/comparison_to_empty.txt new file mode 100644 index 000000000..db6f74fe2 --- /dev/null +++ b/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/docs/copy_iterator.txt b/src/docs/copy_iterator.txt new file mode 100644 index 000000000..5f9a2a015 --- /dev/null +++ b/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/docs/crate_in_macro_def.txt b/src/docs/crate_in_macro_def.txt new file mode 100644 index 000000000..047e986de --- /dev/null +++ b/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/docs/create_dir.txt b/src/docs/create_dir.txt new file mode 100644 index 000000000..e4e793768 --- /dev/null +++ b/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/docs/crosspointer_transmute.txt b/src/docs/crosspointer_transmute.txt new file mode 100644 index 000000000..49dea1549 --- /dev/null +++ b/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/docs/dbg_macro.txt b/src/docs/dbg_macro.txt new file mode 100644 index 000000000..3e1a9a043 --- /dev/null +++ b/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/docs/debug_assert_with_mut_call.txt b/src/docs/debug_assert_with_mut_call.txt new file mode 100644 index 000000000..2c44abe1f --- /dev/null +++ b/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/docs/decimal_literal_representation.txt b/src/docs/decimal_literal_representation.txt new file mode 100644 index 000000000..daca9bbb3 --- /dev/null +++ b/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/docs/declare_interior_mutable_const.txt b/src/docs/declare_interior_mutable_const.txt new file mode 100644 index 000000000..2801b5ccf --- /dev/null +++ b/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/docs/default_instead_of_iter_empty.txt b/src/docs/default_instead_of_iter_empty.txt new file mode 100644 index 000000000..b63ef3d18 --- /dev/null +++ b/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/docs/default_numeric_fallback.txt b/src/docs/default_numeric_fallback.txt new file mode 100644 index 000000000..15076a0a6 --- /dev/null +++ b/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/docs/default_trait_access.txt b/src/docs/default_trait_access.txt new file mode 100644 index 000000000..e69298969 --- /dev/null +++ b/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/docs/default_union_representation.txt b/src/docs/default_union_representation.txt new file mode 100644 index 000000000..f79ff9760 --- /dev/null +++ b/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/docs/deprecated_cfg_attr.txt b/src/docs/deprecated_cfg_attr.txt new file mode 100644 index 000000000..9f264887a --- /dev/null +++ b/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/docs/deprecated_semver.txt b/src/docs/deprecated_semver.txt new file mode 100644 index 000000000..c9574a99b --- /dev/null +++ b/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/docs/deref_addrof.txt b/src/docs/deref_addrof.txt new file mode 100644 index 000000000..fa711b924 --- /dev/null +++ b/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/docs/deref_by_slicing.txt b/src/docs/deref_by_slicing.txt new file mode 100644 index 000000000..4dad24ac0 --- /dev/null +++ b/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/docs/derivable_impls.txt b/src/docs/derivable_impls.txt new file mode 100644 index 000000000..8e4a80a67 --- /dev/null +++ b/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` maybe is 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/docs/derive_hash_xor_eq.txt b/src/docs/derive_hash_xor_eq.txt new file mode 100644 index 000000000..fbf623d5a --- /dev/null +++ b/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/docs/derive_ord_xor_partial_ord.txt b/src/docs/derive_ord_xor_partial_ord.txt new file mode 100644 index 000000000..f2107a5f6 --- /dev/null +++ b/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/docs/derive_partial_eq_without_eq.txt b/src/docs/derive_partial_eq_without_eq.txt new file mode 100644 index 000000000..932fabad6 --- /dev/null +++ b/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/docs/disallowed_methods.txt b/src/docs/disallowed_methods.txt new file mode 100644 index 000000000..d8ad5b6a6 --- /dev/null +++ b/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/docs/disallowed_names.txt b/src/docs/disallowed_names.txt new file mode 100644 index 000000000..f4aaee9c7 --- /dev/null +++ b/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/docs/disallowed_script_idents.txt b/src/docs/disallowed_script_idents.txt new file mode 100644 index 000000000..2151b7a20 --- /dev/null +++ b/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/docs/disallowed_types.txt b/src/docs/disallowed_types.txt new file mode 100644 index 000000000..2bcbcddee --- /dev/null +++ b/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/docs/diverging_sub_expression.txt b/src/docs/diverging_sub_expression.txt new file mode 100644 index 000000000..194362218 --- /dev/null +++ b/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/docs/doc_link_with_quotes.txt b/src/docs/doc_link_with_quotes.txt new file mode 100644 index 000000000..107c8ac11 --- /dev/null +++ b/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/docs/doc_markdown.txt b/src/docs/doc_markdown.txt new file mode 100644 index 000000000..94f54c587 --- /dev/null +++ b/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/docs/double_comparisons.txt b/src/docs/double_comparisons.txt new file mode 100644 index 000000000..7dc681877 --- /dev/null +++ b/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/docs/double_must_use.txt b/src/docs/double_must_use.txt new file mode 100644 index 000000000..0017d10d4 --- /dev/null +++ b/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/docs/double_neg.txt b/src/docs/double_neg.txt new file mode 100644 index 000000000..a07f67496 --- /dev/null +++ b/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/docs/double_parens.txt b/src/docs/double_parens.txt new file mode 100644 index 000000000..260d7dd57 --- /dev/null +++ b/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/docs/drop_copy.txt b/src/docs/drop_copy.txt new file mode 100644 index 000000000..f917ca8ed --- /dev/null +++ b/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/docs/drop_non_drop.txt b/src/docs/drop_non_drop.txt new file mode 100644 index 000000000..ee1e3a6c2 --- /dev/null +++ b/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/docs/drop_ref.txt b/src/docs/drop_ref.txt new file mode 100644 index 000000000..c4f7adf0c --- /dev/null +++ b/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/docs/duplicate_mod.txt b/src/docs/duplicate_mod.txt new file mode 100644 index 000000000..709a9aba0 --- /dev/null +++ b/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/docs/duplicate_underscore_argument.txt b/src/docs/duplicate_underscore_argument.txt new file mode 100644 index 000000000..a8fcd6a9f --- /dev/null +++ b/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/docs/duration_subsec.txt b/src/docs/duration_subsec.txt new file mode 100644 index 000000000..e7e0ca887 --- /dev/null +++ b/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/docs/else_if_without_else.txt b/src/docs/else_if_without_else.txt new file mode 100644 index 000000000..33f5d0f91 --- /dev/null +++ b/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/docs/empty_drop.txt b/src/docs/empty_drop.txt new file mode 100644 index 000000000..d0c0c24a9 --- /dev/null +++ b/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/docs/empty_enum.txt b/src/docs/empty_enum.txt new file mode 100644 index 000000000..f7b41c41e --- /dev/null +++ b/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/docs/empty_line_after_outer_attr.txt b/src/docs/empty_line_after_outer_attr.txt new file mode 100644 index 000000000..c85242bbe --- /dev/null +++ b/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/docs/empty_loop.txt b/src/docs/empty_loop.txt new file mode 100644 index 000000000..fea49a74d --- /dev/null +++ b/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/docs/empty_structs_with_brackets.txt b/src/docs/empty_structs_with_brackets.txt new file mode 100644 index 000000000..ab5e35ae2 --- /dev/null +++ b/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/docs/enum_clike_unportable_variant.txt b/src/docs/enum_clike_unportable_variant.txt new file mode 100644 index 000000000..d30a973a5 --- /dev/null +++ b/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/docs/enum_glob_use.txt b/src/docs/enum_glob_use.txt new file mode 100644 index 000000000..3776822c3 --- /dev/null +++ b/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/docs/enum_variant_names.txt b/src/docs/enum_variant_names.txt new file mode 100644 index 000000000..e726925ed --- /dev/null +++ b/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/docs/eq_op.txt b/src/docs/eq_op.txt new file mode 100644 index 000000000..2d75a0ec5 --- /dev/null +++ b/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/docs/equatable_if_let.txt b/src/docs/equatable_if_let.txt new file mode 100644 index 000000000..999704695 --- /dev/null +++ b/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/docs/erasing_op.txt b/src/docs/erasing_op.txt new file mode 100644 index 000000000..3d285a6d8 --- /dev/null +++ b/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/docs/err_expect.txt b/src/docs/err_expect.txt new file mode 100644 index 000000000..1dc83c5ce --- /dev/null +++ b/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/docs/excessive_precision.txt b/src/docs/excessive_precision.txt new file mode 100644 index 000000000..517879c47 --- /dev/null +++ b/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/docs/exhaustive_enums.txt b/src/docs/exhaustive_enums.txt new file mode 100644 index 000000000..d1032a7a2 --- /dev/null +++ b/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/docs/exhaustive_structs.txt b/src/docs/exhaustive_structs.txt new file mode 100644 index 000000000..fd6e4f5ca --- /dev/null +++ b/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/docs/exit.txt b/src/docs/exit.txt new file mode 100644 index 000000000..1e6154d43 --- /dev/null +++ b/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/docs/expect_fun_call.txt b/src/docs/expect_fun_call.txt new file mode 100644 index 000000000..d82d9aa9b --- /dev/null +++ b/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/docs/expect_used.txt b/src/docs/expect_used.txt new file mode 100644 index 000000000..4a6981e33 --- /dev/null +++ b/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/docs/expl_impl_clone_on_copy.txt b/src/docs/expl_impl_clone_on_copy.txt new file mode 100644 index 000000000..391d93b67 --- /dev/null +++ b/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/docs/explicit_auto_deref.txt b/src/docs/explicit_auto_deref.txt new file mode 100644 index 000000000..65b256317 --- /dev/null +++ b/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/docs/explicit_counter_loop.txt b/src/docs/explicit_counter_loop.txt new file mode 100644 index 000000000..2661a43e1 --- /dev/null +++ b/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/docs/explicit_deref_methods.txt b/src/docs/explicit_deref_methods.txt new file mode 100644 index 000000000..e14e981c7 --- /dev/null +++ b/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/docs/explicit_into_iter_loop.txt b/src/docs/explicit_into_iter_loop.txt new file mode 100644 index 000000000..3931dfd69 --- /dev/null +++ b/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/docs/explicit_iter_loop.txt b/src/docs/explicit_iter_loop.txt new file mode 100644 index 000000000..cabe72e91 --- /dev/null +++ b/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/docs/explicit_write.txt b/src/docs/explicit_write.txt new file mode 100644 index 000000000..eafed5d39 --- /dev/null +++ b/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/docs/extend_with_drain.txt b/src/docs/extend_with_drain.txt new file mode 100644 index 000000000..2f31dcf5f --- /dev/null +++ b/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/docs/extra_unused_lifetimes.txt b/src/docs/extra_unused_lifetimes.txt new file mode 100644 index 000000000..bc1814aa4 --- /dev/null +++ b/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/docs/fallible_impl_from.txt b/src/docs/fallible_impl_from.txt new file mode 100644 index 000000000..588a5bb10 --- /dev/null +++ b/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/docs/field_reassign_with_default.txt b/src/docs/field_reassign_with_default.txt new file mode 100644 index 000000000..e58b7239f --- /dev/null +++ b/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/docs/filetype_is_file.txt b/src/docs/filetype_is_file.txt new file mode 100644 index 000000000..ad14bd62c --- /dev/null +++ b/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/docs/filter_map_identity.txt b/src/docs/filter_map_identity.txt new file mode 100644 index 000000000..83b666f2e --- /dev/null +++ b/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/docs/filter_map_next.txt b/src/docs/filter_map_next.txt new file mode 100644 index 000000000..b38620b56 --- /dev/null +++ b/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/docs/filter_next.txt b/src/docs/filter_next.txt new file mode 100644 index 000000000..898a74166 --- /dev/null +++ b/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/docs/flat_map_identity.txt b/src/docs/flat_map_identity.txt new file mode 100644 index 000000000..a5ee79b49 --- /dev/null +++ b/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/docs/flat_map_option.txt b/src/docs/flat_map_option.txt new file mode 100644 index 000000000..d50b9156d --- /dev/null +++ b/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/docs/float_arithmetic.txt b/src/docs/float_arithmetic.txt new file mode 100644 index 000000000..1f9bce5ab --- /dev/null +++ b/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/docs/float_cmp.txt b/src/docs/float_cmp.txt new file mode 100644 index 000000000..c19907c90 --- /dev/null +++ b/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/docs/float_cmp_const.txt b/src/docs/float_cmp_const.txt new file mode 100644 index 000000000..9208feaac --- /dev/null +++ b/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/docs/float_equality_without_abs.txt b/src/docs/float_equality_without_abs.txt new file mode 100644 index 000000000..556b574e1 --- /dev/null +++ b/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/docs/fn_address_comparisons.txt b/src/docs/fn_address_comparisons.txt new file mode 100644 index 000000000..7d2b7b681 --- /dev/null +++ b/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/docs/fn_params_excessive_bools.txt b/src/docs/fn_params_excessive_bools.txt new file mode 100644 index 000000000..2eae05633 --- /dev/null +++ b/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/docs/fn_to_numeric_cast.txt b/src/docs/fn_to_numeric_cast.txt new file mode 100644 index 000000000..1f587f6d7 --- /dev/null +++ b/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/docs/fn_to_numeric_cast_any.txt b/src/docs/fn_to_numeric_cast_any.txt new file mode 100644 index 000000000..ee3c33d23 --- /dev/null +++ b/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/docs/fn_to_numeric_cast_with_truncation.txt b/src/docs/fn_to_numeric_cast_with_truncation.txt new file mode 100644 index 000000000..69f12fa31 --- /dev/null +++ b/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/docs/for_kv_map.txt b/src/docs/for_kv_map.txt new file mode 100644 index 000000000..a9a2ffee9 --- /dev/null +++ b/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/docs/for_loops_over_fallibles.txt b/src/docs/for_loops_over_fallibles.txt new file mode 100644 index 000000000..c5a7508e4 --- /dev/null +++ b/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/docs/forget_copy.txt b/src/docs/forget_copy.txt new file mode 100644 index 000000000..1d100912e --- /dev/null +++ b/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/docs/forget_non_drop.txt b/src/docs/forget_non_drop.txt new file mode 100644 index 000000000..3307d654c --- /dev/null +++ b/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/docs/forget_ref.txt b/src/docs/forget_ref.txt new file mode 100644 index 000000000..874fb8786 --- /dev/null +++ b/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/docs/format_in_format_args.txt b/src/docs/format_in_format_args.txt new file mode 100644 index 000000000..ac498472f --- /dev/null +++ b/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/docs/format_push_string.txt b/src/docs/format_push_string.txt new file mode 100644 index 000000000..ca409ebc7 --- /dev/null +++ b/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/docs/from_iter_instead_of_collect.txt b/src/docs/from_iter_instead_of_collect.txt new file mode 100644 index 000000000..f3fd27597 --- /dev/null +++ b/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/docs/from_over_into.txt b/src/docs/from_over_into.txt new file mode 100644 index 000000000..0770bcc42 --- /dev/null +++ b/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/docs/from_str_radix_10.txt b/src/docs/from_str_radix_10.txt new file mode 100644 index 000000000..f6f319d3e --- /dev/null +++ b/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/docs/future_not_send.txt b/src/docs/future_not_send.txt new file mode 100644 index 000000000..0aa048d27 --- /dev/null +++ b/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/docs/get_first.txt b/src/docs/get_first.txt new file mode 100644 index 000000000..c905a737d --- /dev/null +++ b/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/docs/get_last_with_len.txt b/src/docs/get_last_with_len.txt new file mode 100644 index 000000000..31c7f2695 --- /dev/null +++ b/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/docs/get_unwrap.txt b/src/docs/get_unwrap.txt new file mode 100644 index 000000000..8defc2224 --- /dev/null +++ b/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/docs/identity_op.txt b/src/docs/identity_op.txt new file mode 100644 index 000000000..a8e40bb43 --- /dev/null +++ b/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/docs/if_let_mutex.txt b/src/docs/if_let_mutex.txt new file mode 100644 index 000000000..4d873ade9 --- /dev/null +++ b/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/docs/if_not_else.txt b/src/docs/if_not_else.txt new file mode 100644 index 000000000..0e5ac4ce6 --- /dev/null +++ b/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/docs/if_same_then_else.txt b/src/docs/if_same_then_else.txt new file mode 100644 index 000000000..75127016b --- /dev/null +++ b/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/docs/if_then_some_else_none.txt b/src/docs/if_then_some_else_none.txt new file mode 100644 index 000000000..13744f920 --- /dev/null +++ b/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/docs/ifs_same_cond.txt b/src/docs/ifs_same_cond.txt new file mode 100644 index 000000000..024ba5df9 --- /dev/null +++ b/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/docs/implicit_clone.txt b/src/docs/implicit_clone.txt new file mode 100644 index 000000000..f5aa112c5 --- /dev/null +++ b/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/docs/implicit_hasher.txt b/src/docs/implicit_hasher.txt new file mode 100644 index 000000000..0c1f76620 --- /dev/null +++ b/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/docs/implicit_return.txt b/src/docs/implicit_return.txt new file mode 100644 index 000000000..ee65a636b --- /dev/null +++ b/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/docs/implicit_saturating_sub.txt b/src/docs/implicit_saturating_sub.txt new file mode 100644 index 000000000..03b47905a --- /dev/null +++ b/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/docs/imprecise_flops.txt b/src/docs/imprecise_flops.txt new file mode 100644 index 000000000..e84d81cea --- /dev/null +++ b/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/docs/inconsistent_digit_grouping.txt b/src/docs/inconsistent_digit_grouping.txt new file mode 100644 index 000000000..aa0b072de --- /dev/null +++ b/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/docs/inconsistent_struct_constructor.txt b/src/docs/inconsistent_struct_constructor.txt new file mode 100644 index 000000000..eb682109a --- /dev/null +++ b/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/docs/index_refutable_slice.txt b/src/docs/index_refutable_slice.txt new file mode 100644 index 000000000..8a7d52761 --- /dev/null +++ b/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/docs/indexing_slicing.txt b/src/docs/indexing_slicing.txt new file mode 100644 index 000000000..76ca6ed31 --- /dev/null +++ b/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/docs/ineffective_bit_mask.txt b/src/docs/ineffective_bit_mask.txt new file mode 100644 index 000000000..f6e7ef556 --- /dev/null +++ b/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/docs/inefficient_to_string.txt b/src/docs/inefficient_to_string.txt new file mode 100644 index 000000000..f7061d1ce --- /dev/null +++ b/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/docs/infallible_destructuring_match.txt b/src/docs/infallible_destructuring_match.txt new file mode 100644 index 000000000..4b5d3c4ba --- /dev/null +++ b/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/docs/infinite_iter.txt b/src/docs/infinite_iter.txt new file mode 100644 index 000000000..8a22fabc5 --- /dev/null +++ b/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/docs/inherent_to_string.txt b/src/docs/inherent_to_string.txt new file mode 100644 index 000000000..b18e600e9 --- /dev/null +++ b/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/docs/inherent_to_string_shadow_display.txt b/src/docs/inherent_to_string_shadow_display.txt new file mode 100644 index 000000000..a4bd0b622 --- /dev/null +++ b/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/docs/init_numbered_fields.txt b/src/docs/init_numbered_fields.txt new file mode 100644 index 000000000..ba40af6a5 --- /dev/null +++ b/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/docs/inline_always.txt b/src/docs/inline_always.txt new file mode 100644 index 000000000..7721da4c4 --- /dev/null +++ b/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/docs/inline_asm_x86_att_syntax.txt b/src/docs/inline_asm_x86_att_syntax.txt new file mode 100644 index 000000000..8eb49d122 --- /dev/null +++ b/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/docs/inline_asm_x86_intel_syntax.txt b/src/docs/inline_asm_x86_intel_syntax.txt new file mode 100644 index 000000000..5aa22c8ed --- /dev/null +++ b/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/docs/inline_fn_without_body.txt b/src/docs/inline_fn_without_body.txt new file mode 100644 index 000000000..127c161aa --- /dev/null +++ b/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/docs/inspect_for_each.txt b/src/docs/inspect_for_each.txt new file mode 100644 index 000000000..01a46d6c4 --- /dev/null +++ b/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/docs/int_plus_one.txt b/src/docs/int_plus_one.txt new file mode 100644 index 000000000..1b68f3eeb --- /dev/null +++ b/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/docs/integer_arithmetic.txt b/src/docs/integer_arithmetic.txt new file mode 100644 index 000000000..ea57a2ef9 --- /dev/null +++ b/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/docs/integer_division.txt b/src/docs/integer_division.txt new file mode 100644 index 000000000..f6d334981 --- /dev/null +++ b/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/docs/into_iter_on_ref.txt b/src/docs/into_iter_on_ref.txt new file mode 100644 index 000000000..acb6bd474 --- /dev/null +++ b/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/docs/invalid_null_ptr_usage.txt b/src/docs/invalid_null_ptr_usage.txt new file mode 100644 index 000000000..6fb3fa3f8 --- /dev/null +++ b/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/docs/invalid_regex.txt b/src/docs/invalid_regex.txt new file mode 100644 index 000000000..6c9969b6e --- /dev/null +++ b/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/docs/invalid_upcast_comparisons.txt b/src/docs/invalid_upcast_comparisons.txt new file mode 100644 index 000000000..77cb03308 --- /dev/null +++ b/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/docs/invalid_utf8_in_unchecked.txt b/src/docs/invalid_utf8_in_unchecked.txt new file mode 100644 index 000000000..afb5acbe9 --- /dev/null +++ b/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/docs/invisible_characters.txt b/src/docs/invisible_characters.txt new file mode 100644 index 000000000..3dda38091 --- /dev/null +++ b/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/docs/is_digit_ascii_radix.txt b/src/docs/is_digit_ascii_radix.txt new file mode 100644 index 000000000..9f11cf430 --- /dev/null +++ b/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/docs/items_after_statements.txt b/src/docs/items_after_statements.txt new file mode 100644 index 000000000..6fdfff50d --- /dev/null +++ b/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/docs/iter_cloned_collect.txt b/src/docs/iter_cloned_collect.txt new file mode 100644 index 000000000..90dc9ebb4 --- /dev/null +++ b/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/docs/iter_count.txt b/src/docs/iter_count.txt new file mode 100644 index 000000000..f3db4a26c --- /dev/null +++ b/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/docs/iter_next_loop.txt b/src/docs/iter_next_loop.txt new file mode 100644 index 000000000..b33eb39d6 --- /dev/null +++ b/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/docs/iter_next_slice.txt b/src/docs/iter_next_slice.txt new file mode 100644 index 000000000..1cea25eaf --- /dev/null +++ b/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/docs/iter_not_returning_iterator.txt b/src/docs/iter_not_returning_iterator.txt new file mode 100644 index 000000000..0ca862910 --- /dev/null +++ b/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/docs/iter_nth.txt b/src/docs/iter_nth.txt new file mode 100644 index 000000000..3d67d583f --- /dev/null +++ b/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/docs/iter_nth_zero.txt b/src/docs/iter_nth_zero.txt new file mode 100644 index 000000000..8efe47a16 --- /dev/null +++ b/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/docs/iter_on_empty_collections.txt b/src/docs/iter_on_empty_collections.txt new file mode 100644 index 000000000..87c4ec12a --- /dev/null +++ b/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/docs/iter_on_single_items.txt b/src/docs/iter_on_single_items.txt new file mode 100644 index 000000000..d0388f25d --- /dev/null +++ b/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/docs/iter_overeager_cloned.txt b/src/docs/iter_overeager_cloned.txt new file mode 100644 index 000000000..2f902a0c2 --- /dev/null +++ b/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/docs/iter_skip_next.txt b/src/docs/iter_skip_next.txt new file mode 100644 index 000000000..da226b041 --- /dev/null +++ b/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/docs/iter_with_drain.txt b/src/docs/iter_with_drain.txt new file mode 100644 index 000000000..2c52b99f7 --- /dev/null +++ b/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/docs/iterator_step_by_zero.txt b/src/docs/iterator_step_by_zero.txt new file mode 100644 index 000000000..73ecc99ac --- /dev/null +++ b/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/docs/just_underscores_and_digits.txt b/src/docs/just_underscores_and_digits.txt new file mode 100644 index 000000000..a8790bcf2 --- /dev/null +++ b/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/docs/large_const_arrays.txt b/src/docs/large_const_arrays.txt new file mode 100644 index 000000000..71f67854f --- /dev/null +++ b/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/docs/large_digit_groups.txt b/src/docs/large_digit_groups.txt new file mode 100644 index 000000000..f60b19345 --- /dev/null +++ b/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/docs/large_enum_variant.txt b/src/docs/large_enum_variant.txt new file mode 100644 index 000000000..787e8e027 --- /dev/null +++ b/src/docs/large_enum_variant.txt @@ -0,0 +1,40 @@ +### 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 a +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 generic types if the layout depends on the +generics, even if the size difference will be large anyway. + +### 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/docs/large_include_file.txt b/src/docs/large_include_file.txt new file mode 100644 index 000000000..b2a54bd2e --- /dev/null +++ b/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/docs/large_stack_arrays.txt b/src/docs/large_stack_arrays.txt new file mode 100644 index 000000000..4a6f34785 --- /dev/null +++ b/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/docs/large_types_passed_by_value.txt b/src/docs/large_types_passed_by_value.txt new file mode 100644 index 000000000..bca07f3ac --- /dev/null +++ b/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/docs/len_without_is_empty.txt b/src/docs/len_without_is_empty.txt new file mode 100644 index 000000000..47a2e8575 --- /dev/null +++ b/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/docs/len_zero.txt b/src/docs/len_zero.txt new file mode 100644 index 000000000..664124bd3 --- /dev/null +++ b/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/docs/let_and_return.txt b/src/docs/let_and_return.txt new file mode 100644 index 000000000..eba5a90dd --- /dev/null +++ b/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/docs/let_underscore_drop.txt b/src/docs/let_underscore_drop.txt new file mode 100644 index 000000000..29ce9bf50 --- /dev/null +++ b/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/docs/let_underscore_lock.txt b/src/docs/let_underscore_lock.txt new file mode 100644 index 000000000..bd8217fb5 --- /dev/null +++ b/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/docs/let_underscore_must_use.txt b/src/docs/let_underscore_must_use.txt new file mode 100644 index 000000000..270b81d9a --- /dev/null +++ b/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/docs/let_unit_value.txt b/src/docs/let_unit_value.txt new file mode 100644 index 000000000..bc16d5b3d --- /dev/null +++ b/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/docs/linkedlist.txt b/src/docs/linkedlist.txt new file mode 100644 index 000000000..986ff1369 --- /dev/null +++ b/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/docs/lossy_float_literal.txt b/src/docs/lossy_float_literal.txt new file mode 100644 index 000000000..bbcb9115e --- /dev/null +++ b/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/docs/macro_use_imports.txt b/src/docs/macro_use_imports.txt new file mode 100644 index 000000000..6a8180a60 --- /dev/null +++ b/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/docs/main_recursion.txt b/src/docs/main_recursion.txt new file mode 100644 index 000000000..e49becd15 --- /dev/null +++ b/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/docs/manual_assert.txt b/src/docs/manual_assert.txt new file mode 100644 index 000000000..93653081a --- /dev/null +++ b/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/docs/manual_async_fn.txt b/src/docs/manual_async_fn.txt new file mode 100644 index 000000000..d01ac402e --- /dev/null +++ b/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/docs/manual_bits.txt b/src/docs/manual_bits.txt new file mode 100644 index 000000000..b96c2eb15 --- /dev/null +++ b/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/docs/manual_filter_map.txt b/src/docs/manual_filter_map.txt new file mode 100644 index 000000000..3b6860798 --- /dev/null +++ b/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/docs/manual_find.txt b/src/docs/manual_find.txt new file mode 100644 index 000000000..e3e07a277 --- /dev/null +++ b/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/docs/manual_find_map.txt b/src/docs/manual_find_map.txt new file mode 100644 index 000000000..83b22060c --- /dev/null +++ b/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/docs/manual_flatten.txt b/src/docs/manual_flatten.txt new file mode 100644 index 000000000..62d5f3ec9 --- /dev/null +++ b/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/docs/manual_instant_elapsed.txt b/src/docs/manual_instant_elapsed.txt new file mode 100644 index 000000000..dde3d493c --- /dev/null +++ b/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/docs/manual_map.txt b/src/docs/manual_map.txt new file mode 100644 index 000000000..7f68ccd10 --- /dev/null +++ b/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/docs/manual_memcpy.txt b/src/docs/manual_memcpy.txt new file mode 100644 index 000000000..d7690bf25 --- /dev/null +++ b/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/docs/manual_non_exhaustive.txt b/src/docs/manual_non_exhaustive.txt new file mode 100644 index 000000000..fb021393b --- /dev/null +++ b/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/docs/manual_ok_or.txt b/src/docs/manual_ok_or.txt new file mode 100644 index 000000000..5accdf259 --- /dev/null +++ b/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/docs/manual_range_contains.txt b/src/docs/manual_range_contains.txt new file mode 100644 index 000000000..0ade26951 --- /dev/null +++ b/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/docs/manual_rem_euclid.txt b/src/docs/manual_rem_euclid.txt new file mode 100644 index 000000000..d3bb8c613 --- /dev/null +++ b/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/docs/manual_retain.txt b/src/docs/manual_retain.txt new file mode 100644 index 000000000..cd4f65a93 --- /dev/null +++ b/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/docs/manual_saturating_arithmetic.txt b/src/docs/manual_saturating_arithmetic.txt new file mode 100644 index 000000000..d9f5d3d11 --- /dev/null +++ b/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/docs/manual_split_once.txt b/src/docs/manual_split_once.txt new file mode 100644 index 000000000..291ae447d --- /dev/null +++ b/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/docs/manual_str_repeat.txt b/src/docs/manual_str_repeat.txt new file mode 100644 index 000000000..1d4a7a48e --- /dev/null +++ b/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/docs/manual_string_new.txt b/src/docs/manual_string_new.txt new file mode 100644 index 000000000..4cbc43f8f --- /dev/null +++ b/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/docs/manual_strip.txt b/src/docs/manual_strip.txt new file mode 100644 index 000000000..f32d8e7a0 --- /dev/null +++ b/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/docs/manual_swap.txt b/src/docs/manual_swap.txt new file mode 100644 index 000000000..bd9526288 --- /dev/null +++ b/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/docs/manual_unwrap_or.txt b/src/docs/manual_unwrap_or.txt new file mode 100644 index 000000000..1fd7d831b --- /dev/null +++ b/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/docs/many_single_char_names.txt b/src/docs/many_single_char_names.txt new file mode 100644 index 000000000..55ee5da55 --- /dev/null +++ b/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/docs/map_clone.txt b/src/docs/map_clone.txt new file mode 100644 index 000000000..3ee27f072 --- /dev/null +++ b/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/docs/map_collect_result_unit.txt b/src/docs/map_collect_result_unit.txt new file mode 100644 index 000000000..9b7206124 --- /dev/null +++ b/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/docs/map_entry.txt b/src/docs/map_entry.txt new file mode 100644 index 000000000..20dba1798 --- /dev/null +++ b/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/docs/map_err_ignore.txt b/src/docs/map_err_ignore.txt new file mode 100644 index 000000000..2606c13a7 --- /dev/null +++ b/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/docs/map_flatten.txt b/src/docs/map_flatten.txt new file mode 100644 index 000000000..73c0e5140 --- /dev/null +++ b/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/docs/map_identity.txt b/src/docs/map_identity.txt new file mode 100644 index 000000000..e2e7af0be --- /dev/null +++ b/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/docs/map_unwrap_or.txt b/src/docs/map_unwrap_or.txt new file mode 100644 index 000000000..485b29f01 --- /dev/null +++ b/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/docs/match_as_ref.txt b/src/docs/match_as_ref.txt new file mode 100644 index 000000000..5e5f3d645 --- /dev/null +++ b/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/docs/match_bool.txt b/src/docs/match_bool.txt new file mode 100644 index 000000000..96f9e1f8b --- /dev/null +++ b/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/docs/match_like_matches_macro.txt b/src/docs/match_like_matches_macro.txt new file mode 100644 index 000000000..643e2ddc9 --- /dev/null +++ b/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/docs/match_on_vec_items.txt b/src/docs/match_on_vec_items.txt new file mode 100644 index 000000000..981d18d0f --- /dev/null +++ b/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/docs/match_overlapping_arm.txt b/src/docs/match_overlapping_arm.txt new file mode 100644 index 000000000..841c091bd --- /dev/null +++ b/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/docs/match_ref_pats.txt b/src/docs/match_ref_pats.txt new file mode 100644 index 000000000..b1d902995 --- /dev/null +++ b/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/docs/match_result_ok.txt b/src/docs/match_result_ok.txt new file mode 100644 index 000000000..eea7c8e00 --- /dev/null +++ b/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/docs/match_same_arms.txt b/src/docs/match_same_arms.txt new file mode 100644 index 000000000..14edf1203 --- /dev/null +++ b/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/docs/match_single_binding.txt b/src/docs/match_single_binding.txt new file mode 100644 index 000000000..67ded0bbd --- /dev/null +++ b/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/docs/match_str_case_mismatch.txt b/src/docs/match_str_case_mismatch.txt new file mode 100644 index 000000000..19e74c208 --- /dev/null +++ b/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/docs/match_wild_err_arm.txt b/src/docs/match_wild_err_arm.txt new file mode 100644 index 000000000..f89b3a23a --- /dev/null +++ b/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/docs/match_wildcard_for_single_variants.txt b/src/docs/match_wildcard_for_single_variants.txt new file mode 100644 index 000000000..25559b9ec --- /dev/null +++ b/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/docs/maybe_infinite_iter.txt b/src/docs/maybe_infinite_iter.txt new file mode 100644 index 000000000..1204a49b4 --- /dev/null +++ b/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/docs/mem_forget.txt b/src/docs/mem_forget.txt new file mode 100644 index 000000000..a6888c48f --- /dev/null +++ b/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/docs/mem_replace_option_with_none.txt b/src/docs/mem_replace_option_with_none.txt new file mode 100644 index 000000000..7f243d1c1 --- /dev/null +++ b/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/docs/mem_replace_with_default.txt b/src/docs/mem_replace_with_default.txt new file mode 100644 index 000000000..24e0913a3 --- /dev/null +++ b/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/docs/mem_replace_with_uninit.txt b/src/docs/mem_replace_with_uninit.txt new file mode 100644 index 000000000..0bb483668 --- /dev/null +++ b/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/docs/min_max.txt b/src/docs/min_max.txt new file mode 100644 index 000000000..6acf0f932 --- /dev/null +++ b/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/docs/mismatched_target_os.txt b/src/docs/mismatched_target_os.txt new file mode 100644 index 000000000..51e5ec6e7 --- /dev/null +++ b/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/docs/mismatching_type_param_order.txt b/src/docs/mismatching_type_param_order.txt new file mode 100644 index 000000000..ffc7f32d0 --- /dev/null +++ b/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/docs/misrefactored_assign_op.txt b/src/docs/misrefactored_assign_op.txt new file mode 100644 index 000000000..3d691fe41 --- /dev/null +++ b/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/docs/missing_const_for_fn.txt b/src/docs/missing_const_for_fn.txt new file mode 100644 index 000000000..067614d4c --- /dev/null +++ b/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/docs/missing_docs_in_private_items.txt b/src/docs/missing_docs_in_private_items.txt new file mode 100644 index 000000000..5d37505bb --- /dev/null +++ b/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/docs/missing_enforced_import_renames.txt b/src/docs/missing_enforced_import_renames.txt new file mode 100644 index 000000000..8f4649bd5 --- /dev/null +++ b/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/docs/missing_errors_doc.txt b/src/docs/missing_errors_doc.txt new file mode 100644 index 000000000..028778d85 --- /dev/null +++ b/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/docs/missing_inline_in_public_items.txt b/src/docs/missing_inline_in_public_items.txt new file mode 100644 index 000000000..d90c50fe7 --- /dev/null +++ b/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/docs/missing_panics_doc.txt b/src/docs/missing_panics_doc.txt new file mode 100644 index 000000000..e5e39a824 --- /dev/null +++ b/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/docs/missing_safety_doc.txt b/src/docs/missing_safety_doc.txt new file mode 100644 index 000000000..6492eb84f --- /dev/null +++ b/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/docs/missing_spin_loop.txt b/src/docs/missing_spin_loop.txt new file mode 100644 index 000000000..3a06a91d7 --- /dev/null +++ b/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/docs/mistyped_literal_suffixes.txt b/src/docs/mistyped_literal_suffixes.txt new file mode 100644 index 000000000..1760fcbfe --- /dev/null +++ b/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/docs/mixed_case_hex_literals.txt b/src/docs/mixed_case_hex_literals.txt new file mode 100644 index 000000000..d2d01e0c9 --- /dev/null +++ b/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/docs/mixed_read_write_in_expression.txt b/src/docs/mixed_read_write_in_expression.txt new file mode 100644 index 000000000..02d1c5d05 --- /dev/null +++ b/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/docs/mod_module_files.txt b/src/docs/mod_module_files.txt new file mode 100644 index 000000000..95bca583a --- /dev/null +++ b/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/docs/module_inception.txt b/src/docs/module_inception.txt new file mode 100644 index 000000000..d80a1b8d8 --- /dev/null +++ b/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/docs/module_name_repetitions.txt b/src/docs/module_name_repetitions.txt new file mode 100644 index 000000000..3bc05d027 --- /dev/null +++ b/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/docs/modulo_arithmetic.txt b/src/docs/modulo_arithmetic.txt new file mode 100644 index 000000000..ff7296f3c --- /dev/null +++ b/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/docs/modulo_one.txt b/src/docs/modulo_one.txt new file mode 100644 index 000000000..bc8f95b0b --- /dev/null +++ b/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/docs/multi_assignments.txt b/src/docs/multi_assignments.txt new file mode 100644 index 000000000..ed1f1b420 --- /dev/null +++ b/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/docs/multiple_crate_versions.txt b/src/docs/multiple_crate_versions.txt new file mode 100644 index 000000000..cf2d2c6ab --- /dev/null +++ b/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/docs/multiple_inherent_impl.txt b/src/docs/multiple_inherent_impl.txt new file mode 100644 index 000000000..9d4228656 --- /dev/null +++ b/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/docs/must_use_candidate.txt b/src/docs/must_use_candidate.txt new file mode 100644 index 000000000..70890346f --- /dev/null +++ b/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/docs/must_use_unit.txt b/src/docs/must_use_unit.txt new file mode 100644 index 000000000..cabbb23f8 --- /dev/null +++ b/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/docs/mut_from_ref.txt b/src/docs/mut_from_ref.txt new file mode 100644 index 000000000..cc1da1254 --- /dev/null +++ b/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/docs/mut_mut.txt b/src/docs/mut_mut.txt new file mode 100644 index 000000000..0bd34dd24 --- /dev/null +++ b/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/docs/mut_mutex_lock.txt b/src/docs/mut_mutex_lock.txt new file mode 100644 index 000000000..5e9ad8a3f --- /dev/null +++ b/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/docs/mut_range_bound.txt b/src/docs/mut_range_bound.txt new file mode 100644 index 000000000..e9c38a543 --- /dev/null +++ b/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/docs/mutable_key_type.txt b/src/docs/mutable_key_type.txt new file mode 100644 index 000000000..15fe34f2b --- /dev/null +++ b/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/docs/mutex_atomic.txt b/src/docs/mutex_atomic.txt new file mode 100644 index 000000000..062ac8b32 --- /dev/null +++ b/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/docs/mutex_integer.txt b/src/docs/mutex_integer.txt new file mode 100644 index 000000000..f9dbdfb90 --- /dev/null +++ b/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/docs/naive_bytecount.txt b/src/docs/naive_bytecount.txt new file mode 100644 index 000000000..24659dc79 --- /dev/null +++ b/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/docs/needless_arbitrary_self_type.txt b/src/docs/needless_arbitrary_self_type.txt new file mode 100644 index 000000000..8216a3a3f --- /dev/null +++ b/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/docs/needless_bitwise_bool.txt b/src/docs/needless_bitwise_bool.txt new file mode 100644 index 000000000..fcd7b730a --- /dev/null +++ b/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/docs/needless_bool.txt b/src/docs/needless_bool.txt new file mode 100644 index 000000000..b5c78871f --- /dev/null +++ b/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/docs/needless_borrow.txt b/src/docs/needless_borrow.txt new file mode 100644 index 000000000..4debcf473 --- /dev/null +++ b/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/docs/needless_borrowed_reference.txt b/src/docs/needless_borrowed_reference.txt new file mode 100644 index 000000000..55faa0cf5 --- /dev/null +++ b/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/docs/needless_collect.txt b/src/docs/needless_collect.txt new file mode 100644 index 000000000..275c39afc --- /dev/null +++ b/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/docs/needless_continue.txt b/src/docs/needless_continue.txt new file mode 100644 index 000000000..2cee621c1 --- /dev/null +++ b/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/docs/needless_doctest_main.txt b/src/docs/needless_doctest_main.txt new file mode 100644 index 000000000..8f91a7baa --- /dev/null +++ b/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/docs/needless_for_each.txt b/src/docs/needless_for_each.txt new file mode 100644 index 000000000..9ae6dd360 --- /dev/null +++ b/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/docs/needless_late_init.txt b/src/docs/needless_late_init.txt new file mode 100644 index 000000000..9e7bbcea9 --- /dev/null +++ b/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/docs/needless_lifetimes.txt b/src/docs/needless_lifetimes.txt new file mode 100644 index 000000000..b280caa66 --- /dev/null +++ b/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/docs/needless_match.txt b/src/docs/needless_match.txt new file mode 100644 index 000000000..92b40a5df --- /dev/null +++ b/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/docs/needless_option_as_deref.txt b/src/docs/needless_option_as_deref.txt new file mode 100644 index 000000000..226396c97 --- /dev/null +++ b/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/docs/needless_option_take.txt b/src/docs/needless_option_take.txt new file mode 100644 index 000000000..6bac65a13 --- /dev/null +++ b/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/docs/needless_parens_on_range_literals.txt b/src/docs/needless_parens_on_range_literals.txt new file mode 100644 index 000000000..85fab10cb --- /dev/null +++ b/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/docs/needless_pass_by_value.txt b/src/docs/needless_pass_by_value.txt new file mode 100644 index 000000000..58c420b19 --- /dev/null +++ b/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/docs/needless_question_mark.txt b/src/docs/needless_question_mark.txt new file mode 100644 index 000000000..540739fd4 --- /dev/null +++ b/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/docs/needless_range_loop.txt b/src/docs/needless_range_loop.txt new file mode 100644 index 000000000..583c09b28 --- /dev/null +++ b/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/docs/needless_return.txt b/src/docs/needless_return.txt new file mode 100644 index 000000000..48782cb0c --- /dev/null +++ b/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/docs/needless_splitn.txt b/src/docs/needless_splitn.txt new file mode 100644 index 000000000..b10a84fbc --- /dev/null +++ b/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/docs/needless_update.txt b/src/docs/needless_update.txt new file mode 100644 index 000000000..82adabf64 --- /dev/null +++ b/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/docs/neg_cmp_op_on_partial_ord.txt b/src/docs/neg_cmp_op_on_partial_ord.txt new file mode 100644 index 000000000..fa55c6cfd --- /dev/null +++ b/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/docs/neg_multiply.txt b/src/docs/neg_multiply.txt new file mode 100644 index 000000000..4e8b096eb --- /dev/null +++ b/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/docs/negative_feature_names.txt b/src/docs/negative_feature_names.txt new file mode 100644 index 000000000..01ee9efb3 --- /dev/null +++ b/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/docs/never_loop.txt b/src/docs/never_loop.txt new file mode 100644 index 000000000..737ccf415 --- /dev/null +++ b/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/docs/new_ret_no_self.txt b/src/docs/new_ret_no_self.txt new file mode 100644 index 000000000..291bad24a --- /dev/null +++ b/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/docs/new_without_default.txt b/src/docs/new_without_default.txt new file mode 100644 index 000000000..662d39c8e --- /dev/null +++ b/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/docs/no_effect.txt b/src/docs/no_effect.txt new file mode 100644 index 000000000..d4cc08fa8 --- /dev/null +++ b/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/docs/no_effect_replace.txt b/src/docs/no_effect_replace.txt new file mode 100644 index 000000000..646d45287 --- /dev/null +++ b/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/docs/no_effect_underscore_binding.txt b/src/docs/no_effect_underscore_binding.txt new file mode 100644 index 000000000..972f60dd0 --- /dev/null +++ b/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/docs/non_ascii_literal.txt b/src/docs/non_ascii_literal.txt new file mode 100644 index 000000000..164902b47 --- /dev/null +++ b/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/docs/non_octal_unix_permissions.txt b/src/docs/non_octal_unix_permissions.txt new file mode 100644 index 000000000..4a468e94d --- /dev/null +++ b/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/docs/non_send_fields_in_send_ty.txt b/src/docs/non_send_fields_in_send_ty.txt new file mode 100644 index 000000000..11e6f6e16 --- /dev/null +++ b/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/docs/nonminimal_bool.txt b/src/docs/nonminimal_bool.txt new file mode 100644 index 000000000..488980ddf --- /dev/null +++ b/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/docs/nonsensical_open_options.txt b/src/docs/nonsensical_open_options.txt new file mode 100644 index 000000000..7a95443b5 --- /dev/null +++ b/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/docs/nonstandard_macro_braces.txt b/src/docs/nonstandard_macro_braces.txt new file mode 100644 index 000000000..7e8d0d2d3 --- /dev/null +++ b/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/docs/not_unsafe_ptr_arg_deref.txt b/src/docs/not_unsafe_ptr_arg_deref.txt new file mode 100644 index 000000000..31355fbb7 --- /dev/null +++ b/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/docs/obfuscated_if_else.txt b/src/docs/obfuscated_if_else.txt new file mode 100644 index 000000000..638f63b0d --- /dev/null +++ b/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/docs/octal_escapes.txt b/src/docs/octal_escapes.txt new file mode 100644 index 000000000..eee820587 --- /dev/null +++ b/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/docs/ok_expect.txt b/src/docs/ok_expect.txt new file mode 100644 index 000000000..fd5205d49 --- /dev/null +++ b/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/docs/only_used_in_recursion.txt b/src/docs/only_used_in_recursion.txt new file mode 100644 index 000000000..f19f47ff9 --- /dev/null +++ b/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/docs/op_ref.txt b/src/docs/op_ref.txt new file mode 100644 index 000000000..7a7ed1bc9 --- /dev/null +++ b/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/docs/option_as_ref_deref.txt b/src/docs/option_as_ref_deref.txt new file mode 100644 index 000000000..ad7411d3d --- /dev/null +++ b/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/docs/option_env_unwrap.txt b/src/docs/option_env_unwrap.txt new file mode 100644 index 000000000..c952cba8e --- /dev/null +++ b/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/docs/option_filter_map.txt b/src/docs/option_filter_map.txt new file mode 100644 index 000000000..25f7bde7b --- /dev/null +++ b/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/docs/option_if_let_else.txt b/src/docs/option_if_let_else.txt new file mode 100644 index 000000000..43652db51 --- /dev/null +++ b/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/docs/option_map_or_none.txt b/src/docs/option_map_or_none.txt new file mode 100644 index 000000000..c86c65215 --- /dev/null +++ b/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/docs/option_map_unit_fn.txt b/src/docs/option_map_unit_fn.txt new file mode 100644 index 000000000..fc4b528f0 --- /dev/null +++ b/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/docs/option_option.txt b/src/docs/option_option.txt new file mode 100644 index 000000000..b4324bd83 --- /dev/null +++ b/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/docs/or_fun_call.txt b/src/docs/or_fun_call.txt new file mode 100644 index 000000000..5605e96c9 --- /dev/null +++ b/src/docs/or_fun_call.txt @@ -0,0 +1,26 @@ +### 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. + +### 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/docs/or_then_unwrap.txt b/src/docs/or_then_unwrap.txt new file mode 100644 index 000000000..64ac53749 --- /dev/null +++ b/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/docs/out_of_bounds_indexing.txt b/src/docs/out_of_bounds_indexing.txt new file mode 100644 index 000000000..5802eea29 --- /dev/null +++ b/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/docs/overflow_check_conditional.txt b/src/docs/overflow_check_conditional.txt new file mode 100644 index 000000000..a09cc18a0 --- /dev/null +++ b/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/docs/overly_complex_bool_expr.txt b/src/docs/overly_complex_bool_expr.txt new file mode 100644 index 000000000..65ca18392 --- /dev/null +++ b/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/docs/panic.txt b/src/docs/panic.txt new file mode 100644 index 000000000..f9bdc6e87 --- /dev/null +++ b/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/docs/panic_in_result_fn.txt b/src/docs/panic_in_result_fn.txt new file mode 100644 index 000000000..51c2f8ae5 --- /dev/null +++ b/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/docs/panicking_unwrap.txt b/src/docs/panicking_unwrap.txt new file mode 100644 index 000000000..1fbc245c8 --- /dev/null +++ b/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/docs/partialeq_ne_impl.txt b/src/docs/partialeq_ne_impl.txt new file mode 100644 index 000000000..78f55188b --- /dev/null +++ b/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/docs/partialeq_to_none.txt b/src/docs/partialeq_to_none.txt new file mode 100644 index 000000000..5cc07bf88 --- /dev/null +++ b/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/docs/path_buf_push_overwrite.txt b/src/docs/path_buf_push_overwrite.txt new file mode 100644 index 000000000..34f8901da --- /dev/null +++ b/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/docs/pattern_type_mismatch.txt b/src/docs/pattern_type_mismatch.txt new file mode 100644 index 000000000..64da881d5 --- /dev/null +++ b/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/docs/positional_named_format_parameters.txt b/src/docs/positional_named_format_parameters.txt new file mode 100644 index 000000000..e391d2406 --- /dev/null +++ b/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/docs/possible_missing_comma.txt b/src/docs/possible_missing_comma.txt new file mode 100644 index 000000000..5d92f4cae --- /dev/null +++ b/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/docs/precedence.txt b/src/docs/precedence.txt new file mode 100644 index 000000000..fda0b831f --- /dev/null +++ b/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/docs/print_in_format_impl.txt b/src/docs/print_in_format_impl.txt new file mode 100644 index 000000000..140d23d6f --- /dev/null +++ b/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/docs/print_literal.txt b/src/docs/print_literal.txt new file mode 100644 index 000000000..160073414 --- /dev/null +++ b/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/docs/print_stderr.txt b/src/docs/print_stderr.txt new file mode 100644 index 000000000..fc14511cd --- /dev/null +++ b/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/docs/print_stdout.txt b/src/docs/print_stdout.txt new file mode 100644 index 000000000..6c9a4b98e --- /dev/null +++ b/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/docs/print_with_newline.txt b/src/docs/print_with_newline.txt new file mode 100644 index 000000000..640323e82 --- /dev/null +++ b/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/docs/println_empty_string.txt b/src/docs/println_empty_string.txt new file mode 100644 index 000000000..b98041302 --- /dev/null +++ b/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/docs/ptr_arg.txt b/src/docs/ptr_arg.txt new file mode 100644 index 000000000..796b0a65b --- /dev/null +++ b/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/docs/ptr_as_ptr.txt b/src/docs/ptr_as_ptr.txt new file mode 100644 index 000000000..8fb35c4aa --- /dev/null +++ b/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/docs/ptr_eq.txt b/src/docs/ptr_eq.txt new file mode 100644 index 000000000..06b36ca55 --- /dev/null +++ b/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/docs/ptr_offset_with_cast.txt b/src/docs/ptr_offset_with_cast.txt new file mode 100644 index 000000000..f204e769b --- /dev/null +++ b/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/docs/pub_use.txt b/src/docs/pub_use.txt new file mode 100644 index 000000000..407cafa01 --- /dev/null +++ b/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/docs/question_mark.txt b/src/docs/question_mark.txt new file mode 100644 index 000000000..4dc987be8 --- /dev/null +++ b/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/docs/range_minus_one.txt b/src/docs/range_minus_one.txt new file mode 100644 index 000000000..fcb96dcc3 --- /dev/null +++ b/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/docs/range_plus_one.txt b/src/docs/range_plus_one.txt new file mode 100644 index 000000000..193c85f9c --- /dev/null +++ b/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/docs/range_zip_with_len.txt b/src/docs/range_zip_with_len.txt new file mode 100644 index 000000000..24c1efec7 --- /dev/null +++ b/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/docs/rc_buffer.txt b/src/docs/rc_buffer.txt new file mode 100644 index 000000000..82ac58eeb --- /dev/null +++ b/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/docs/rc_clone_in_vec_init.txt b/src/docs/rc_clone_in_vec_init.txt new file mode 100644 index 000000000..6fc08aaf9 --- /dev/null +++ b/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/docs/rc_mutex.txt b/src/docs/rc_mutex.txt new file mode 100644 index 000000000..ed7a1e344 --- /dev/null +++ b/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/docs/read_zero_byte_vec.txt b/src/docs/read_zero_byte_vec.txt new file mode 100644 index 000000000..cef5604e0 --- /dev/null +++ b/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/docs/recursive_format_impl.txt b/src/docs/recursive_format_impl.txt new file mode 100644 index 000000000..32fffd84c --- /dev/null +++ b/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/docs/redundant_allocation.txt b/src/docs/redundant_allocation.txt new file mode 100644 index 000000000..86bf51e8d --- /dev/null +++ b/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/docs/redundant_clone.txt b/src/docs/redundant_clone.txt new file mode 100644 index 000000000..b29aed0b5 --- /dev/null +++ b/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/docs/redundant_closure.txt b/src/docs/redundant_closure.txt new file mode 100644 index 000000000..0faa9513f --- /dev/null +++ b/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/docs/redundant_closure_call.txt b/src/docs/redundant_closure_call.txt new file mode 100644 index 000000000..913d1a705 --- /dev/null +++ b/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/docs/redundant_closure_for_method_calls.txt b/src/docs/redundant_closure_for_method_calls.txt new file mode 100644 index 000000000..865510e14 --- /dev/null +++ b/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/docs/redundant_else.txt b/src/docs/redundant_else.txt new file mode 100644 index 000000000..3f4e86917 --- /dev/null +++ b/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/docs/redundant_feature_names.txt b/src/docs/redundant_feature_names.txt new file mode 100644 index 000000000..5bd6925ed --- /dev/null +++ b/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/docs/redundant_field_names.txt b/src/docs/redundant_field_names.txt new file mode 100644 index 000000000..35f20a466 --- /dev/null +++ b/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/docs/redundant_pattern.txt b/src/docs/redundant_pattern.txt new file mode 100644 index 000000000..45f6cfc86 --- /dev/null +++ b/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/docs/redundant_pattern_matching.txt b/src/docs/redundant_pattern_matching.txt new file mode 100644 index 000000000..77b1021e0 --- /dev/null +++ b/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/docs/redundant_pub_crate.txt b/src/docs/redundant_pub_crate.txt new file mode 100644 index 000000000..a527bb5ac --- /dev/null +++ b/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/docs/redundant_slicing.txt b/src/docs/redundant_slicing.txt new file mode 100644 index 000000000..6798911ed --- /dev/null +++ b/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/docs/redundant_static_lifetimes.txt b/src/docs/redundant_static_lifetimes.txt new file mode 100644 index 000000000..edb8e7b5c --- /dev/null +++ b/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/docs/ref_binding_to_reference.txt b/src/docs/ref_binding_to_reference.txt new file mode 100644 index 000000000..dc391cd98 --- /dev/null +++ b/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/docs/ref_option_ref.txt b/src/docs/ref_option_ref.txt new file mode 100644 index 000000000..951c7bd7f --- /dev/null +++ b/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/docs/repeat_once.txt b/src/docs/repeat_once.txt new file mode 100644 index 000000000..3ba189c19 --- /dev/null +++ b/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/docs/rest_pat_in_fully_bound_structs.txt b/src/docs/rest_pat_in_fully_bound_structs.txt new file mode 100644 index 000000000..40ebbe754 --- /dev/null +++ b/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/docs/result_large_err.txt b/src/docs/result_large_err.txt new file mode 100644 index 000000000..e5fab3c5c --- /dev/null +++ b/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/docs/result_map_or_into_option.txt b/src/docs/result_map_or_into_option.txt new file mode 100644 index 000000000..899d98c30 --- /dev/null +++ b/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/docs/result_map_unit_fn.txt b/src/docs/result_map_unit_fn.txt new file mode 100644 index 000000000..3455c5c1f --- /dev/null +++ b/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/docs/result_unit_err.txt b/src/docs/result_unit_err.txt new file mode 100644 index 000000000..7c8ec2ffc --- /dev/null +++ b/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/docs/return_self_not_must_use.txt b/src/docs/return_self_not_must_use.txt new file mode 100644 index 000000000..4a4fd2c6e --- /dev/null +++ b/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/docs/reversed_empty_ranges.txt b/src/docs/reversed_empty_ranges.txt new file mode 100644 index 000000000..39f481193 --- /dev/null +++ b/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/docs/same_functions_in_if_condition.txt b/src/docs/same_functions_in_if_condition.txt new file mode 100644 index 000000000..a0a90eec6 --- /dev/null +++ b/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/docs/same_item_push.txt b/src/docs/same_item_push.txt new file mode 100644 index 000000000..7e724073f --- /dev/null +++ b/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/docs/same_name_method.txt b/src/docs/same_name_method.txt new file mode 100644 index 000000000..792dd717f --- /dev/null +++ b/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/docs/search_is_some.txt b/src/docs/search_is_some.txt new file mode 100644 index 000000000..67292d545 --- /dev/null +++ b/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/docs/self_assignment.txt b/src/docs/self_assignment.txt new file mode 100644 index 000000000..ea60ea077 --- /dev/null +++ b/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/docs/self_named_constructors.txt b/src/docs/self_named_constructors.txt new file mode 100644 index 000000000..a01669a84 --- /dev/null +++ b/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/docs/self_named_module_files.txt b/src/docs/self_named_module_files.txt new file mode 100644 index 000000000..73e805136 --- /dev/null +++ b/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/docs/semicolon_if_nothing_returned.txt b/src/docs/semicolon_if_nothing_returned.txt new file mode 100644 index 000000000..30c963ca2 --- /dev/null +++ b/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/docs/separated_literal_suffix.txt b/src/docs/separated_literal_suffix.txt new file mode 100644 index 000000000..226a6b8a9 --- /dev/null +++ b/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/docs/serde_api_misuse.txt b/src/docs/serde_api_misuse.txt new file mode 100644 index 000000000..8a3c89ac1 --- /dev/null +++ b/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/docs/shadow_reuse.txt b/src/docs/shadow_reuse.txt new file mode 100644 index 000000000..9eb8e7ad1 --- /dev/null +++ b/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/docs/shadow_same.txt b/src/docs/shadow_same.txt new file mode 100644 index 000000000..3cd96f560 --- /dev/null +++ b/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/docs/shadow_unrelated.txt b/src/docs/shadow_unrelated.txt new file mode 100644 index 000000000..436251c52 --- /dev/null +++ b/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/docs/short_circuit_statement.txt b/src/docs/short_circuit_statement.txt new file mode 100644 index 000000000..31492bed0 --- /dev/null +++ b/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/docs/should_implement_trait.txt b/src/docs/should_implement_trait.txt new file mode 100644 index 000000000..02e74751a --- /dev/null +++ b/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/docs/significant_drop_in_scrutinee.txt b/src/docs/significant_drop_in_scrutinee.txt new file mode 100644 index 000000000..f869def0d --- /dev/null +++ b/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/docs/similar_names.txt b/src/docs/similar_names.txt new file mode 100644 index 000000000..13aca9c0b --- /dev/null +++ b/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/docs/single_char_add_str.txt b/src/docs/single_char_add_str.txt new file mode 100644 index 000000000..cf23dc0c8 --- /dev/null +++ b/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/docs/single_char_lifetime_names.txt b/src/docs/single_char_lifetime_names.txt new file mode 100644 index 000000000..92dd24bf2 --- /dev/null +++ b/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/docs/single_char_pattern.txt b/src/docs/single_char_pattern.txt new file mode 100644 index 000000000..9e5ad1e7d --- /dev/null +++ b/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/docs/single_component_path_imports.txt b/src/docs/single_component_path_imports.txt new file mode 100644 index 000000000..3a0263881 --- /dev/null +++ b/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/docs/single_element_loop.txt b/src/docs/single_element_loop.txt new file mode 100644 index 000000000..6f0c15a85 --- /dev/null +++ b/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/docs/single_match.txt b/src/docs/single_match.txt new file mode 100644 index 000000000..31dde4da8 --- /dev/null +++ b/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/docs/single_match_else.txt b/src/docs/single_match_else.txt new file mode 100644 index 000000000..29a447af0 --- /dev/null +++ b/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/docs/size_of_in_element_count.txt b/src/docs/size_of_in_element_count.txt new file mode 100644 index 000000000..d893ec6a2 --- /dev/null +++ b/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/docs/skip_while_next.txt b/src/docs/skip_while_next.txt new file mode 100644 index 000000000..1ec8a3a28 --- /dev/null +++ b/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/docs/slow_vector_initialization.txt b/src/docs/slow_vector_initialization.txt new file mode 100644 index 000000000..53442e179 --- /dev/null +++ b/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/docs/stable_sort_primitive.txt b/src/docs/stable_sort_primitive.txt new file mode 100644 index 000000000..6465dbee4 --- /dev/null +++ b/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/docs/std_instead_of_alloc.txt b/src/docs/std_instead_of_alloc.txt new file mode 100644 index 000000000..c2d32704e --- /dev/null +++ b/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/docs/std_instead_of_core.txt b/src/docs/std_instead_of_core.txt new file mode 100644 index 000000000..f1e1518c6 --- /dev/null +++ b/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/docs/str_to_string.txt b/src/docs/str_to_string.txt new file mode 100644 index 000000000..a24755223 --- /dev/null +++ b/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/docs/string_add.txt b/src/docs/string_add.txt new file mode 100644 index 000000000..23dafd0d0 --- /dev/null +++ b/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/docs/string_add_assign.txt b/src/docs/string_add_assign.txt new file mode 100644 index 000000000..7438be855 --- /dev/null +++ b/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/docs/string_extend_chars.txt b/src/docs/string_extend_chars.txt new file mode 100644 index 000000000..619ea3e11 --- /dev/null +++ b/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/docs/string_from_utf8_as_bytes.txt b/src/docs/string_from_utf8_as_bytes.txt new file mode 100644 index 000000000..9102d7347 --- /dev/null +++ b/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/docs/string_lit_as_bytes.txt b/src/docs/string_lit_as_bytes.txt new file mode 100644 index 000000000..a125b97ed --- /dev/null +++ b/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/docs/string_slice.txt b/src/docs/string_slice.txt new file mode 100644 index 000000000..3d9e49dd3 --- /dev/null +++ b/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/docs/string_to_string.txt b/src/docs/string_to_string.txt new file mode 100644 index 000000000..deb7eebe7 --- /dev/null +++ b/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/docs/strlen_on_c_strings.txt b/src/docs/strlen_on_c_strings.txt new file mode 100644 index 000000000..0454abf55 --- /dev/null +++ b/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/docs/struct_excessive_bools.txt b/src/docs/struct_excessive_bools.txt new file mode 100644 index 000000000..9e197c786 --- /dev/null +++ b/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/docs/suboptimal_flops.txt b/src/docs/suboptimal_flops.txt new file mode 100644 index 000000000..f1c9c665b --- /dev/null +++ b/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/docs/suspicious_arithmetic_impl.txt b/src/docs/suspicious_arithmetic_impl.txt new file mode 100644 index 000000000..d67ff2793 --- /dev/null +++ b/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/docs/suspicious_assignment_formatting.txt b/src/docs/suspicious_assignment_formatting.txt new file mode 100644 index 000000000..b889827cd --- /dev/null +++ b/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/docs/suspicious_else_formatting.txt b/src/docs/suspicious_else_formatting.txt new file mode 100644 index 000000000..3cf2f7486 --- /dev/null +++ b/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/docs/suspicious_map.txt b/src/docs/suspicious_map.txt new file mode 100644 index 000000000..d8fa52c43 --- /dev/null +++ b/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/docs/suspicious_op_assign_impl.txt b/src/docs/suspicious_op_assign_impl.txt new file mode 100644 index 000000000..81abfbeca --- /dev/null +++ b/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/docs/suspicious_operation_groupings.txt b/src/docs/suspicious_operation_groupings.txt new file mode 100644 index 000000000..81ede5d3d --- /dev/null +++ b/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/docs/suspicious_splitn.txt b/src/docs/suspicious_splitn.txt new file mode 100644 index 000000000..79a3dbfa6 --- /dev/null +++ b/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/docs/suspicious_to_owned.txt b/src/docs/suspicious_to_owned.txt new file mode 100644 index 000000000..8cbf61dc7 --- /dev/null +++ b/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/docs/suspicious_unary_op_formatting.txt b/src/docs/suspicious_unary_op_formatting.txt new file mode 100644 index 000000000..06fb09db7 --- /dev/null +++ b/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/docs/swap_ptr_to_ref.txt b/src/docs/swap_ptr_to_ref.txt new file mode 100644 index 000000000..0215d1e8a --- /dev/null +++ b/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/docs/tabs_in_doc_comments.txt b/src/docs/tabs_in_doc_comments.txt new file mode 100644 index 000000000..f83dbe2b7 --- /dev/null +++ b/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/docs/temporary_assignment.txt b/src/docs/temporary_assignment.txt new file mode 100644 index 000000000..195b42cf0 --- /dev/null +++ b/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/docs/to_digit_is_some.txt b/src/docs/to_digit_is_some.txt new file mode 100644 index 000000000..eee8375ad --- /dev/null +++ b/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/docs/to_string_in_format_args.txt b/src/docs/to_string_in_format_args.txt new file mode 100644 index 000000000..34b205835 --- /dev/null +++ b/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/docs/todo.txt b/src/docs/todo.txt new file mode 100644 index 000000000..661eb1ac5 --- /dev/null +++ b/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/docs/too_many_arguments.txt b/src/docs/too_many_arguments.txt new file mode 100644 index 000000000..4669f9f82 --- /dev/null +++ b/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/docs/too_many_lines.txt b/src/docs/too_many_lines.txt new file mode 100644 index 000000000..425db348b --- /dev/null +++ b/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/docs/toplevel_ref_arg.txt b/src/docs/toplevel_ref_arg.txt new file mode 100644 index 000000000..96a9e2db8 --- /dev/null +++ b/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/docs/trailing_empty_array.txt b/src/docs/trailing_empty_array.txt new file mode 100644 index 000000000..db1908cc9 --- /dev/null +++ b/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/docs/trait_duplication_in_bounds.txt b/src/docs/trait_duplication_in_bounds.txt new file mode 100644 index 000000000..509736bb3 --- /dev/null +++ b/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/docs/transmute_bytes_to_str.txt b/src/docs/transmute_bytes_to_str.txt new file mode 100644 index 000000000..75889b9c7 --- /dev/null +++ b/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/docs/transmute_float_to_int.txt b/src/docs/transmute_float_to_int.txt new file mode 100644 index 000000000..1877e5a46 --- /dev/null +++ b/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/docs/transmute_int_to_bool.txt b/src/docs/transmute_int_to_bool.txt new file mode 100644 index 000000000..07c10f8d0 --- /dev/null +++ b/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/docs/transmute_int_to_char.txt b/src/docs/transmute_int_to_char.txt new file mode 100644 index 000000000..836d22d3f --- /dev/null +++ b/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/docs/transmute_int_to_float.txt b/src/docs/transmute_int_to_float.txt new file mode 100644 index 000000000..75cdc62e9 --- /dev/null +++ b/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/docs/transmute_num_to_bytes.txt b/src/docs/transmute_num_to_bytes.txt new file mode 100644 index 000000000..a2c39a1b9 --- /dev/null +++ b/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/docs/transmute_ptr_to_ptr.txt b/src/docs/transmute_ptr_to_ptr.txt new file mode 100644 index 000000000..65777db98 --- /dev/null +++ b/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/docs/transmute_ptr_to_ref.txt b/src/docs/transmute_ptr_to_ref.txt new file mode 100644 index 000000000..aca550f50 --- /dev/null +++ b/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/docs/transmute_undefined_repr.txt b/src/docs/transmute_undefined_repr.txt new file mode 100644 index 000000000..5ee6aaf4c --- /dev/null +++ b/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/docs/transmutes_expressible_as_ptr_casts.txt b/src/docs/transmutes_expressible_as_ptr_casts.txt new file mode 100644 index 000000000..b68a8cda9 --- /dev/null +++ b/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/docs/transmuting_null.txt b/src/docs/transmuting_null.txt new file mode 100644 index 000000000..f8bacfc0b --- /dev/null +++ b/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/docs/trim_split_whitespace.txt b/src/docs/trim_split_whitespace.txt new file mode 100644 index 000000000..f7e3e7858 --- /dev/null +++ b/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/docs/trivial_regex.txt b/src/docs/trivial_regex.txt new file mode 100644 index 000000000..f71d667fd --- /dev/null +++ b/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/docs/trivially_copy_pass_by_ref.txt b/src/docs/trivially_copy_pass_by_ref.txt new file mode 100644 index 000000000..f54cce5e2 --- /dev/null +++ b/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/docs/try_err.txt b/src/docs/try_err.txt new file mode 100644 index 000000000..e3d4ef3a0 --- /dev/null +++ b/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/docs/type_complexity.txt b/src/docs/type_complexity.txt new file mode 100644 index 000000000..69cd87500 --- /dev/null +++ b/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/docs/type_repetition_in_bounds.txt b/src/docs/type_repetition_in_bounds.txt new file mode 100644 index 000000000..18ed372fd --- /dev/null +++ b/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/docs/undocumented_unsafe_blocks.txt b/src/docs/undocumented_unsafe_blocks.txt new file mode 100644 index 000000000..f3af4753c --- /dev/null +++ b/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/docs/undropped_manually_drops.txt b/src/docs/undropped_manually_drops.txt new file mode 100644 index 000000000..85e3ec566 --- /dev/null +++ b/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/docs/unicode_not_nfc.txt b/src/docs/unicode_not_nfc.txt new file mode 100644 index 000000000..c660c51da --- /dev/null +++ b/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/docs/unimplemented.txt b/src/docs/unimplemented.txt new file mode 100644 index 000000000..7095594fb --- /dev/null +++ b/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/docs/uninit_assumed_init.txt b/src/docs/uninit_assumed_init.txt new file mode 100644 index 000000000..cca24093d --- /dev/null +++ b/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/docs/uninit_vec.txt b/src/docs/uninit_vec.txt new file mode 100644 index 000000000..cd50afe78 --- /dev/null +++ b/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/docs/unit_arg.txt b/src/docs/unit_arg.txt new file mode 100644 index 000000000..eb83403bb --- /dev/null +++ b/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/docs/unit_cmp.txt b/src/docs/unit_cmp.txt new file mode 100644 index 000000000..6f3d62010 --- /dev/null +++ b/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/docs/unit_hash.txt b/src/docs/unit_hash.txt new file mode 100644 index 000000000..a22d29946 --- /dev/null +++ b/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/docs/unit_return_expecting_ord.txt b/src/docs/unit_return_expecting_ord.txt new file mode 100644 index 000000000..781feac5a --- /dev/null +++ b/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/docs/unnecessary_cast.txt b/src/docs/unnecessary_cast.txt new file mode 100644 index 000000000..603f26060 --- /dev/null +++ b/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/docs/unnecessary_filter_map.txt b/src/docs/unnecessary_filter_map.txt new file mode 100644 index 000000000..b19341ecf --- /dev/null +++ b/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/docs/unnecessary_find_map.txt b/src/docs/unnecessary_find_map.txt new file mode 100644 index 000000000..f9444dc48 --- /dev/null +++ b/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/docs/unnecessary_fold.txt b/src/docs/unnecessary_fold.txt new file mode 100644 index 000000000..e1b0e65f5 --- /dev/null +++ b/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/docs/unnecessary_join.txt b/src/docs/unnecessary_join.txt new file mode 100644 index 000000000..ee4e78601 --- /dev/null +++ b/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/docs/unnecessary_lazy_evaluations.txt b/src/docs/unnecessary_lazy_evaluations.txt new file mode 100644 index 000000000..208188ce9 --- /dev/null +++ b/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/docs/unnecessary_mut_passed.txt b/src/docs/unnecessary_mut_passed.txt new file mode 100644 index 000000000..2f8bdd113 --- /dev/null +++ b/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/docs/unnecessary_operation.txt b/src/docs/unnecessary_operation.txt new file mode 100644 index 000000000..7f455e264 --- /dev/null +++ b/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/docs/unnecessary_owned_empty_strings.txt b/src/docs/unnecessary_owned_empty_strings.txt new file mode 100644 index 000000000..8cd9fba60 --- /dev/null +++ b/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/docs/unnecessary_self_imports.txt b/src/docs/unnecessary_self_imports.txt new file mode 100644 index 000000000..b909cd5a7 --- /dev/null +++ b/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/docs/unnecessary_sort_by.txt b/src/docs/unnecessary_sort_by.txt new file mode 100644 index 000000000..6913b62c4 --- /dev/null +++ b/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/docs/unnecessary_to_owned.txt b/src/docs/unnecessary_to_owned.txt new file mode 100644 index 000000000..5d4213bda --- /dev/null +++ b/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/docs/unnecessary_unwrap.txt b/src/docs/unnecessary_unwrap.txt new file mode 100644 index 000000000..50ae845bb --- /dev/null +++ b/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/docs/unnecessary_wraps.txt b/src/docs/unnecessary_wraps.txt new file mode 100644 index 000000000..c0a23d492 --- /dev/null +++ b/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/docs/unneeded_field_pattern.txt b/src/docs/unneeded_field_pattern.txt new file mode 100644 index 000000000..3cd00a0f3 --- /dev/null +++ b/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/docs/unneeded_wildcard_pattern.txt b/src/docs/unneeded_wildcard_pattern.txt new file mode 100644 index 000000000..817061efd --- /dev/null +++ b/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/docs/unnested_or_patterns.txt b/src/docs/unnested_or_patterns.txt new file mode 100644 index 000000000..49c45d4ee --- /dev/null +++ b/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/docs/unreachable.txt b/src/docs/unreachable.txt new file mode 100644 index 000000000..10469ca77 --- /dev/null +++ b/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/docs/unreadable_literal.txt b/src/docs/unreadable_literal.txt new file mode 100644 index 000000000..e168f90a8 --- /dev/null +++ b/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/docs/unsafe_derive_deserialize.txt b/src/docs/unsafe_derive_deserialize.txt new file mode 100644 index 000000000..f56c48044 --- /dev/null +++ b/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/docs/unsafe_removed_from_name.txt b/src/docs/unsafe_removed_from_name.txt new file mode 100644 index 000000000..6f55c1815 --- /dev/null +++ b/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/docs/unseparated_literal_suffix.txt b/src/docs/unseparated_literal_suffix.txt new file mode 100644 index 000000000..d80248e34 --- /dev/null +++ b/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/docs/unsound_collection_transmute.txt b/src/docs/unsound_collection_transmute.txt new file mode 100644 index 000000000..29db9258e --- /dev/null +++ b/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/docs/unused_async.txt b/src/docs/unused_async.txt new file mode 100644 index 000000000..26def11aa --- /dev/null +++ b/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/docs/unused_io_amount.txt b/src/docs/unused_io_amount.txt new file mode 100644 index 000000000..fbc4c299c --- /dev/null +++ b/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/docs/unused_peekable.txt b/src/docs/unused_peekable.txt new file mode 100644 index 000000000..268de1ce3 --- /dev/null +++ b/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/docs/unused_rounding.txt b/src/docs/unused_rounding.txt new file mode 100644 index 000000000..70947acee --- /dev/null +++ b/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/docs/unused_self.txt b/src/docs/unused_self.txt new file mode 100644 index 000000000..a8d0fc759 --- /dev/null +++ b/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/docs/unused_unit.txt b/src/docs/unused_unit.txt new file mode 100644 index 000000000..48d16ca65 --- /dev/null +++ b/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/docs/unusual_byte_groupings.txt b/src/docs/unusual_byte_groupings.txt new file mode 100644 index 000000000..9a1f132a6 --- /dev/null +++ b/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/docs/unwrap_in_result.txt b/src/docs/unwrap_in_result.txt new file mode 100644 index 000000000..7497dd863 --- /dev/null +++ b/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/docs/unwrap_or_else_default.txt b/src/docs/unwrap_or_else_default.txt new file mode 100644 index 000000000..34b4cf088 --- /dev/null +++ b/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/docs/unwrap_used.txt b/src/docs/unwrap_used.txt new file mode 100644 index 000000000..9b4713df5 --- /dev/null +++ b/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/docs/upper_case_acronyms.txt b/src/docs/upper_case_acronyms.txt new file mode 100644 index 000000000..a1e39c7e1 --- /dev/null +++ b/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/docs/use_debug.txt b/src/docs/use_debug.txt new file mode 100644 index 000000000..94d4a6fd2 --- /dev/null +++ b/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/docs/use_self.txt b/src/docs/use_self.txt new file mode 100644 index 000000000..bd37ed1e0 --- /dev/null +++ b/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/docs/used_underscore_binding.txt b/src/docs/used_underscore_binding.txt new file mode 100644 index 000000000..ed67c41eb --- /dev/null +++ b/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/docs/useless_asref.txt b/src/docs/useless_asref.txt new file mode 100644 index 000000000..f777cd377 --- /dev/null +++ b/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/docs/useless_attribute.txt b/src/docs/useless_attribute.txt new file mode 100644 index 000000000..e02d4c907 --- /dev/null +++ b/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/docs/useless_conversion.txt b/src/docs/useless_conversion.txt new file mode 100644 index 000000000..06000a7ad --- /dev/null +++ b/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/docs/useless_format.txt b/src/docs/useless_format.txt new file mode 100644 index 000000000..eb4819da1 --- /dev/null +++ b/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/docs/useless_let_if_seq.txt b/src/docs/useless_let_if_seq.txt new file mode 100644 index 000000000..c6dcd57eb --- /dev/null +++ b/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/docs/useless_transmute.txt b/src/docs/useless_transmute.txt new file mode 100644 index 000000000..1d3a17588 --- /dev/null +++ b/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/docs/useless_vec.txt b/src/docs/useless_vec.txt new file mode 100644 index 000000000..ee5afc99e --- /dev/null +++ b/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/docs/vec_box.txt b/src/docs/vec_box.txt new file mode 100644 index 000000000..701b1c9ce --- /dev/null +++ b/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/docs/vec_init_then_push.txt b/src/docs/vec_init_then_push.txt new file mode 100644 index 000000000..445f28747 --- /dev/null +++ b/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/docs/vec_resize_to_zero.txt b/src/docs/vec_resize_to_zero.txt new file mode 100644 index 000000000..0b9268677 --- /dev/null +++ b/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/docs/verbose_bit_mask.txt b/src/docs/verbose_bit_mask.txt new file mode 100644 index 000000000..87a847029 --- /dev/null +++ b/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/docs/verbose_file_reads.txt b/src/docs/verbose_file_reads.txt new file mode 100644 index 000000000..9703df423 --- /dev/null +++ b/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/docs/vtable_address_comparisons.txt b/src/docs/vtable_address_comparisons.txt new file mode 100644 index 000000000..4a34e4ba7 --- /dev/null +++ b/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/docs/while_immutable_condition.txt b/src/docs/while_immutable_condition.txt new file mode 100644 index 000000000..71800701f --- /dev/null +++ b/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/docs/while_let_loop.txt b/src/docs/while_let_loop.txt new file mode 100644 index 000000000..ab7bf6097 --- /dev/null +++ b/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/docs/while_let_on_iterator.txt b/src/docs/while_let_on_iterator.txt new file mode 100644 index 000000000..af053c541 --- /dev/null +++ b/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/docs/wildcard_dependencies.txt b/src/docs/wildcard_dependencies.txt new file mode 100644 index 000000000..2affaf974 --- /dev/null +++ b/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/docs/wildcard_enum_match_arm.txt b/src/docs/wildcard_enum_match_arm.txt new file mode 100644 index 000000000..09807c01c --- /dev/null +++ b/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/docs/wildcard_imports.txt b/src/docs/wildcard_imports.txt new file mode 100644 index 000000000..bd56aa5b0 --- /dev/null +++ b/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/docs/wildcard_in_or_patterns.txt b/src/docs/wildcard_in_or_patterns.txt new file mode 100644 index 000000000..70468ca41 --- /dev/null +++ b/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/docs/write_literal.txt b/src/docs/write_literal.txt new file mode 100644 index 000000000..9c41a48f9 --- /dev/null +++ b/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/docs/write_with_newline.txt b/src/docs/write_with_newline.txt new file mode 100644 index 000000000..22845fd65 --- /dev/null +++ b/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/docs/writeln_empty_string.txt b/src/docs/writeln_empty_string.txt new file mode 100644 index 000000000..3b3aeb79a --- /dev/null +++ b/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/docs/wrong_self_convention.txt b/src/docs/wrong_self_convention.txt new file mode 100644 index 000000000..d6b69ab87 --- /dev/null +++ b/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/docs/wrong_transmute.txt b/src/docs/wrong_transmute.txt new file mode 100644 index 000000000..9fc71e0e3 --- /dev/null +++ b/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/docs/zero_divided_by_zero.txt b/src/docs/zero_divided_by_zero.txt new file mode 100644 index 000000000..394de20c0 --- /dev/null +++ b/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/docs/zero_prefixed_literal.txt b/src/docs/zero_prefixed_literal.txt new file mode 100644 index 000000000..5c5588725 --- /dev/null +++ b/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/docs/zero_ptr.txt b/src/docs/zero_ptr.txt new file mode 100644 index 000000000..e768a0236 --- /dev/null +++ b/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/docs/zero_sized_map_values.txt b/src/docs/zero_sized_map_values.txt new file mode 100644 index 000000000..0502bdbf3 --- /dev/null +++ b/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/docs/zst_offset.txt b/src/docs/zst_offset.txt new file mode 100644 index 000000000..5810455ee --- /dev/null +++ b/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/main.rs b/src/main.rs index 9ee4a40cb..4a32e0e54 100644 --- a/src/main.rs +++ b/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); }