From abd3e7eabb8712244ca4dfbed5455df591aed0fc Mon Sep 17 00:00:00 2001 From: Jason Newcomb Date: Tue, 6 Sep 2022 14:23:03 -0400 Subject: [PATCH 01/34] Allow lint passes to be bound by `TyCtxt` --- clippy_dev/src/new_lint.rs | 6 +- clippy_lints/src/lib.rs | 414 ++++++++++++++++++------------------- 2 files changed, 211 insertions(+), 209 deletions(-) diff --git a/clippy_dev/src/new_lint.rs b/clippy_dev/src/new_lint.rs index be05e67d7..331b76484 100644 --- a/clippy_dev/src/new_lint.rs +++ b/clippy_dev/src/new_lint.rs @@ -120,15 +120,17 @@ fn add_lint(lint: &LintData<'_>, enable_msrv: bool) -> io::Result<()> { let new_lint = if enable_msrv { format!( - "store.register_{lint_pass}_pass(move || Box::new({module_name}::{camel_name}::new(msrv)));\n ", + "store.register_{lint_pass}_pass(move |{ctor_arg}| Box::new({module_name}::{camel_name}::new(msrv)));\n ", lint_pass = lint.pass, + ctor_arg = if lint.pass == "late" { "_" } else { "" }, module_name = lint.name, camel_name = to_camel_case(lint.name), ) } else { format!( - "store.register_{lint_pass}_pass(|| Box::new({module_name}::{camel_name}));\n ", + "store.register_{lint_pass}_pass(|{ctor_arg}| Box::new({module_name}::{camel_name}));\n ", lint_pass = lint.pass, + ctor_arg = if lint.pass == "late" { "_" } else { "" }, module_name = lint.name, camel_name = to_camel_case(lint.name), ) diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index dfdaf90f0..c70aa79ac 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -523,7 +523,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: #[cfg(feature = "internal")] { if std::env::var("ENABLE_METADATA_COLLECTION").eq(&Ok("1".to_string())) { - store.register_late_pass(|| Box::new(utils::internal_lints::metadata_collector::MetadataCollector::new())); + store.register_late_pass(|_| Box::new(utils::internal_lints::metadata_collector::MetadataCollector::new())); return; } } @@ -533,69 +533,69 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: { store.register_early_pass(|| Box::new(utils::internal_lints::ClippyLintsInternal)); store.register_early_pass(|| Box::new(utils::internal_lints::ProduceIce)); - store.register_late_pass(|| Box::new(utils::internal_lints::CollapsibleCalls)); - store.register_late_pass(|| Box::new(utils::internal_lints::CompilerLintFunctions::new())); - store.register_late_pass(|| Box::new(utils::internal_lints::IfChainStyle)); - store.register_late_pass(|| Box::new(utils::internal_lints::InvalidPaths)); - store.register_late_pass(|| Box::new(utils::internal_lints::InterningDefinedSymbol::default())); - store.register_late_pass(|| Box::new(utils::internal_lints::LintWithoutLintPass::default())); - store.register_late_pass(|| Box::new(utils::internal_lints::MatchTypeOnDiagItem)); - store.register_late_pass(|| Box::new(utils::internal_lints::OuterExpnDataPass)); - store.register_late_pass(|| Box::new(utils::internal_lints::MsrvAttrImpl)); + store.register_late_pass(|_| Box::new(utils::internal_lints::CollapsibleCalls)); + store.register_late_pass(|_| Box::new(utils::internal_lints::CompilerLintFunctions::new())); + store.register_late_pass(|_| Box::new(utils::internal_lints::IfChainStyle)); + store.register_late_pass(|_| Box::new(utils::internal_lints::InvalidPaths)); + store.register_late_pass(|_| Box::new(utils::internal_lints::InterningDefinedSymbol::default())); + store.register_late_pass(|_| Box::new(utils::internal_lints::LintWithoutLintPass::default())); + store.register_late_pass(|_| Box::new(utils::internal_lints::MatchTypeOnDiagItem)); + store.register_late_pass(|_| Box::new(utils::internal_lints::OuterExpnDataPass)); + store.register_late_pass(|_| Box::new(utils::internal_lints::MsrvAttrImpl)); } let arithmetic_allowed = conf.arithmetic_allowed.clone(); - store.register_late_pass(move || Box::new(operators::arithmetic::Arithmetic::new(arithmetic_allowed.clone()))); - store.register_late_pass(|| Box::new(utils::dump_hir::DumpHir)); - store.register_late_pass(|| Box::new(utils::author::Author)); + store.register_late_pass(move |_| Box::new(operators::arithmetic::Arithmetic::new(arithmetic_allowed.clone()))); + store.register_late_pass(|_| Box::new(utils::dump_hir::DumpHir)); + store.register_late_pass(|_| Box::new(utils::author::Author)); let await_holding_invalid_types = conf.await_holding_invalid_types.clone(); - store.register_late_pass(move || { + store.register_late_pass(move |_| { Box::new(await_holding_invalid::AwaitHolding::new( await_holding_invalid_types.clone(), )) }); - store.register_late_pass(|| Box::new(serde_api::SerdeApi)); + store.register_late_pass(|_| Box::new(serde_api::SerdeApi)); let vec_box_size_threshold = conf.vec_box_size_threshold; let type_complexity_threshold = conf.type_complexity_threshold; let avoid_breaking_exported_api = conf.avoid_breaking_exported_api; - store.register_late_pass(move || { + store.register_late_pass(move |_| { Box::new(types::Types::new( vec_box_size_threshold, type_complexity_threshold, avoid_breaking_exported_api, )) }); - store.register_late_pass(|| Box::new(booleans::NonminimalBool)); - store.register_late_pass(|| Box::new(enum_clike::UnportableVariant)); - store.register_late_pass(|| Box::new(float_literal::FloatLiteral)); - store.register_late_pass(|| Box::new(ptr::Ptr)); - store.register_late_pass(|| Box::new(needless_bool::NeedlessBool)); - store.register_late_pass(|| Box::new(needless_bool::BoolComparison)); - store.register_late_pass(|| Box::new(needless_for_each::NeedlessForEach)); - store.register_late_pass(|| Box::new(misc::MiscLints)); - store.register_late_pass(|| Box::new(eta_reduction::EtaReduction)); - store.register_late_pass(|| Box::new(mut_mut::MutMut)); - store.register_late_pass(|| Box::new(mut_reference::UnnecessaryMutPassed)); - store.register_late_pass(|| Box::new(len_zero::LenZero)); - store.register_late_pass(|| Box::new(attrs::Attributes)); - store.register_late_pass(|| Box::new(blocks_in_if_conditions::BlocksInIfConditions)); - store.register_late_pass(|| Box::new(unicode::Unicode)); - store.register_late_pass(|| Box::new(uninit_vec::UninitVec)); - store.register_late_pass(|| Box::new(unit_return_expecting_ord::UnitReturnExpectingOrd)); - store.register_late_pass(|| Box::new(strings::StringAdd)); - store.register_late_pass(|| Box::new(implicit_return::ImplicitReturn)); - store.register_late_pass(|| Box::new(implicit_saturating_sub::ImplicitSaturatingSub)); - store.register_late_pass(|| Box::new(default_numeric_fallback::DefaultNumericFallback)); - store.register_late_pass(|| Box::new(inconsistent_struct_constructor::InconsistentStructConstructor)); - store.register_late_pass(|| Box::new(non_octal_unix_permissions::NonOctalUnixPermissions)); + store.register_late_pass(|_| Box::new(booleans::NonminimalBool)); + store.register_late_pass(|_| Box::new(enum_clike::UnportableVariant)); + store.register_late_pass(|_| Box::new(float_literal::FloatLiteral)); + store.register_late_pass(|_| Box::new(ptr::Ptr)); + store.register_late_pass(|_| Box::new(needless_bool::NeedlessBool)); + store.register_late_pass(|_| Box::new(needless_bool::BoolComparison)); + store.register_late_pass(|_| Box::new(needless_for_each::NeedlessForEach)); + store.register_late_pass(|_| Box::new(misc::MiscLints)); + store.register_late_pass(|_| Box::new(eta_reduction::EtaReduction)); + store.register_late_pass(|_| Box::new(mut_mut::MutMut)); + store.register_late_pass(|_| Box::new(mut_reference::UnnecessaryMutPassed)); + store.register_late_pass(|_| Box::new(len_zero::LenZero)); + store.register_late_pass(|_| Box::new(attrs::Attributes)); + store.register_late_pass(|_| Box::new(blocks_in_if_conditions::BlocksInIfConditions)); + store.register_late_pass(|_| Box::new(unicode::Unicode)); + store.register_late_pass(|_| Box::new(uninit_vec::UninitVec)); + store.register_late_pass(|_| Box::new(unit_return_expecting_ord::UnitReturnExpectingOrd)); + store.register_late_pass(|_| Box::new(strings::StringAdd)); + store.register_late_pass(|_| Box::new(implicit_return::ImplicitReturn)); + store.register_late_pass(|_| Box::new(implicit_saturating_sub::ImplicitSaturatingSub)); + store.register_late_pass(|_| Box::new(default_numeric_fallback::DefaultNumericFallback)); + store.register_late_pass(|_| Box::new(inconsistent_struct_constructor::InconsistentStructConstructor)); + store.register_late_pass(|_| Box::new(non_octal_unix_permissions::NonOctalUnixPermissions)); store.register_early_pass(|| Box::new(unnecessary_self_imports::UnnecessarySelfImports)); let msrv = read_msrv(conf, sess); let avoid_breaking_exported_api = conf.avoid_breaking_exported_api; let allow_expect_in_tests = conf.allow_expect_in_tests; let allow_unwrap_in_tests = conf.allow_unwrap_in_tests; - store.register_late_pass(move || Box::new(approx_const::ApproxConstant::new(msrv))); - store.register_late_pass(move || { + store.register_late_pass(move |_| Box::new(approx_const::ApproxConstant::new(msrv))); + store.register_late_pass(move |_| { Box::new(methods::Methods::new( avoid_breaking_exported_api, msrv, @@ -603,74 +603,74 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: allow_unwrap_in_tests, )) }); - store.register_late_pass(move || Box::new(matches::Matches::new(msrv))); + store.register_late_pass(move |_| Box::new(matches::Matches::new(msrv))); store.register_early_pass(move || Box::new(manual_non_exhaustive::ManualNonExhaustiveStruct::new(msrv))); - store.register_late_pass(move || Box::new(manual_non_exhaustive::ManualNonExhaustiveEnum::new(msrv))); - store.register_late_pass(move || Box::new(manual_strip::ManualStrip::new(msrv))); + store.register_late_pass(move |_| Box::new(manual_non_exhaustive::ManualNonExhaustiveEnum::new(msrv))); + store.register_late_pass(move |_| Box::new(manual_strip::ManualStrip::new(msrv))); store.register_early_pass(move || Box::new(redundant_static_lifetimes::RedundantStaticLifetimes::new(msrv))); store.register_early_pass(move || Box::new(redundant_field_names::RedundantFieldNames::new(msrv))); - store.register_late_pass(move || Box::new(checked_conversions::CheckedConversions::new(msrv))); - store.register_late_pass(move || Box::new(mem_replace::MemReplace::new(msrv))); - store.register_late_pass(move || Box::new(ranges::Ranges::new(msrv))); - store.register_late_pass(move || Box::new(from_over_into::FromOverInto::new(msrv))); - store.register_late_pass(move || Box::new(use_self::UseSelf::new(msrv))); - store.register_late_pass(move || Box::new(missing_const_for_fn::MissingConstForFn::new(msrv))); - store.register_late_pass(move || Box::new(needless_question_mark::NeedlessQuestionMark)); - store.register_late_pass(move || Box::new(casts::Casts::new(msrv))); + store.register_late_pass(move |_| Box::new(checked_conversions::CheckedConversions::new(msrv))); + store.register_late_pass(move |_| Box::new(mem_replace::MemReplace::new(msrv))); + store.register_late_pass(move |_| Box::new(ranges::Ranges::new(msrv))); + store.register_late_pass(move |_| Box::new(from_over_into::FromOverInto::new(msrv))); + store.register_late_pass(move |_| Box::new(use_self::UseSelf::new(msrv))); + store.register_late_pass(move |_| Box::new(missing_const_for_fn::MissingConstForFn::new(msrv))); + store.register_late_pass(move |_| Box::new(needless_question_mark::NeedlessQuestionMark)); + store.register_late_pass(move |_| Box::new(casts::Casts::new(msrv))); store.register_early_pass(move || Box::new(unnested_or_patterns::UnnestedOrPatterns::new(msrv))); - store.register_late_pass(|| Box::new(size_of_in_element_count::SizeOfInElementCount)); - store.register_late_pass(|| Box::new(same_name_method::SameNameMethod)); + store.register_late_pass(|_| Box::new(size_of_in_element_count::SizeOfInElementCount)); + store.register_late_pass(|_| Box::new(same_name_method::SameNameMethod)); let max_suggested_slice_pattern_length = conf.max_suggested_slice_pattern_length; - store.register_late_pass(move || { + store.register_late_pass(move |_| { Box::new(index_refutable_slice::IndexRefutableSlice::new( max_suggested_slice_pattern_length, msrv, )) }); - store.register_late_pass(|| Box::new(shadow::Shadow::default())); - store.register_late_pass(|| Box::new(unit_types::UnitTypes)); - store.register_late_pass(|| Box::new(loops::Loops)); - store.register_late_pass(|| Box::new(main_recursion::MainRecursion::default())); - store.register_late_pass(|| Box::new(lifetimes::Lifetimes)); - store.register_late_pass(|| Box::new(entry::HashMapPass)); - store.register_late_pass(|| Box::new(minmax::MinMaxPass)); - store.register_late_pass(|| Box::new(zero_div_zero::ZeroDiv)); - store.register_late_pass(|| Box::new(mutex_atomic::Mutex)); - store.register_late_pass(|| Box::new(needless_update::NeedlessUpdate)); - store.register_late_pass(|| Box::new(needless_borrowed_ref::NeedlessBorrowedRef)); - store.register_late_pass(|| Box::new(borrow_deref_ref::BorrowDerefRef)); - store.register_late_pass(|| Box::new(no_effect::NoEffect)); - store.register_late_pass(|| Box::new(temporary_assignment::TemporaryAssignment)); - store.register_late_pass(move || Box::new(transmute::Transmute::new(msrv))); + store.register_late_pass(|_| Box::new(shadow::Shadow::default())); + store.register_late_pass(|_| Box::new(unit_types::UnitTypes)); + store.register_late_pass(|_| Box::new(loops::Loops)); + store.register_late_pass(|_| Box::new(main_recursion::MainRecursion::default())); + store.register_late_pass(|_| Box::new(lifetimes::Lifetimes)); + store.register_late_pass(|_| Box::new(entry::HashMapPass)); + store.register_late_pass(|_| Box::new(minmax::MinMaxPass)); + store.register_late_pass(|_| Box::new(zero_div_zero::ZeroDiv)); + store.register_late_pass(|_| Box::new(mutex_atomic::Mutex)); + store.register_late_pass(|_| Box::new(needless_update::NeedlessUpdate)); + store.register_late_pass(|_| Box::new(needless_borrowed_ref::NeedlessBorrowedRef)); + store.register_late_pass(|_| Box::new(borrow_deref_ref::BorrowDerefRef)); + store.register_late_pass(|_| Box::new(no_effect::NoEffect)); + store.register_late_pass(|_| Box::new(temporary_assignment::TemporaryAssignment)); + store.register_late_pass(move |_| Box::new(transmute::Transmute::new(msrv))); let cognitive_complexity_threshold = conf.cognitive_complexity_threshold; - store.register_late_pass(move || { + store.register_late_pass(move |_| { Box::new(cognitive_complexity::CognitiveComplexity::new( cognitive_complexity_threshold, )) }); let too_large_for_stack = conf.too_large_for_stack; - store.register_late_pass(move || Box::new(escape::BoxedLocal { too_large_for_stack })); - store.register_late_pass(move || Box::new(vec::UselessVec { too_large_for_stack })); - store.register_late_pass(|| Box::new(panic_unimplemented::PanicUnimplemented)); - store.register_late_pass(|| Box::new(strings::StringLitAsBytes)); - store.register_late_pass(|| Box::new(derive::Derive)); - store.register_late_pass(|| Box::new(derivable_impls::DerivableImpls)); - store.register_late_pass(|| Box::new(drop_forget_ref::DropForgetRef)); - store.register_late_pass(|| Box::new(empty_enum::EmptyEnum)); - store.register_late_pass(|| Box::new(invalid_upcast_comparisons::InvalidUpcastComparisons)); - store.register_late_pass(|| Box::new(regex::Regex)); - store.register_late_pass(|| Box::new(copies::CopyAndPaste)); - store.register_late_pass(|| Box::new(copy_iterator::CopyIterator)); - store.register_late_pass(|| Box::new(format::UselessFormat)); - store.register_late_pass(|| Box::new(swap::Swap)); - store.register_late_pass(|| Box::new(overflow_check_conditional::OverflowCheckConditional)); - store.register_late_pass(|| Box::new(new_without_default::NewWithoutDefault::default())); + store.register_late_pass(move |_| Box::new(escape::BoxedLocal { too_large_for_stack })); + store.register_late_pass(move |_| Box::new(vec::UselessVec { too_large_for_stack })); + store.register_late_pass(|_| Box::new(panic_unimplemented::PanicUnimplemented)); + store.register_late_pass(|_| Box::new(strings::StringLitAsBytes)); + store.register_late_pass(|_| Box::new(derive::Derive)); + store.register_late_pass(|_| Box::new(derivable_impls::DerivableImpls)); + store.register_late_pass(|_| Box::new(drop_forget_ref::DropForgetRef)); + store.register_late_pass(|_| Box::new(empty_enum::EmptyEnum)); + store.register_late_pass(|_| Box::new(invalid_upcast_comparisons::InvalidUpcastComparisons)); + store.register_late_pass(|_| Box::new(regex::Regex)); + store.register_late_pass(|_| Box::new(copies::CopyAndPaste)); + store.register_late_pass(|_| Box::new(copy_iterator::CopyIterator)); + store.register_late_pass(|_| Box::new(format::UselessFormat)); + store.register_late_pass(|_| Box::new(swap::Swap)); + store.register_late_pass(|_| Box::new(overflow_check_conditional::OverflowCheckConditional)); + store.register_late_pass(|_| Box::new(new_without_default::NewWithoutDefault::default())); let disallowed_names = conf.disallowed_names.iter().cloned().collect::>(); - store.register_late_pass(move || Box::new(disallowed_names::DisallowedNames::new(disallowed_names.clone()))); + store.register_late_pass(move |_| Box::new(disallowed_names::DisallowedNames::new(disallowed_names.clone()))); let too_many_arguments_threshold = conf.too_many_arguments_threshold; let too_many_lines_threshold = conf.too_many_lines_threshold; let large_error_threshold = conf.large_error_threshold; - store.register_late_pass(move || { + store.register_late_pass(move |_| { Box::new(functions::Functions::new( too_many_arguments_threshold, too_many_lines_threshold, @@ -678,73 +678,73 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: )) }); let doc_valid_idents = conf.doc_valid_idents.iter().cloned().collect::>(); - store.register_late_pass(move || Box::new(doc::DocMarkdown::new(doc_valid_idents.clone()))); - store.register_late_pass(|| Box::new(neg_multiply::NegMultiply)); - store.register_late_pass(|| Box::new(mem_forget::MemForget)); - store.register_late_pass(|| Box::new(let_if_seq::LetIfSeq)); - store.register_late_pass(|| Box::new(mixed_read_write_in_expression::EvalOrderDependence)); - store.register_late_pass(|| Box::new(missing_doc::MissingDoc::new())); - store.register_late_pass(|| Box::new(missing_inline::MissingInline)); - store.register_late_pass(move || Box::new(exhaustive_items::ExhaustiveItems)); - store.register_late_pass(|| Box::new(match_result_ok::MatchResultOk)); - store.register_late_pass(|| Box::new(partialeq_ne_impl::PartialEqNeImpl)); - store.register_late_pass(|| Box::new(unused_io_amount::UnusedIoAmount)); + store.register_late_pass(move |_| Box::new(doc::DocMarkdown::new(doc_valid_idents.clone()))); + store.register_late_pass(|_| Box::new(neg_multiply::NegMultiply)); + store.register_late_pass(|_| Box::new(mem_forget::MemForget)); + store.register_late_pass(|_| Box::new(let_if_seq::LetIfSeq)); + store.register_late_pass(|_| Box::new(mixed_read_write_in_expression::EvalOrderDependence)); + store.register_late_pass(|_| Box::new(missing_doc::MissingDoc::new())); + store.register_late_pass(|_| Box::new(missing_inline::MissingInline)); + store.register_late_pass(move |_| Box::new(exhaustive_items::ExhaustiveItems)); + store.register_late_pass(|_| Box::new(match_result_ok::MatchResultOk)); + store.register_late_pass(|_| Box::new(partialeq_ne_impl::PartialEqNeImpl)); + store.register_late_pass(|_| Box::new(unused_io_amount::UnusedIoAmount)); let enum_variant_size_threshold = conf.enum_variant_size_threshold; - store.register_late_pass(move || Box::new(large_enum_variant::LargeEnumVariant::new(enum_variant_size_threshold))); - store.register_late_pass(|| Box::new(explicit_write::ExplicitWrite)); - store.register_late_pass(|| Box::new(needless_pass_by_value::NeedlessPassByValue)); + store.register_late_pass(move |_| Box::new(large_enum_variant::LargeEnumVariant::new(enum_variant_size_threshold))); + store.register_late_pass(|_| Box::new(explicit_write::ExplicitWrite)); + store.register_late_pass(|_| Box::new(needless_pass_by_value::NeedlessPassByValue)); let pass_by_ref_or_value = pass_by_ref_or_value::PassByRefOrValue::new( conf.trivial_copy_size_limit, conf.pass_by_value_size_limit, conf.avoid_breaking_exported_api, &sess.target, ); - store.register_late_pass(move || Box::new(pass_by_ref_or_value)); - store.register_late_pass(|| Box::new(ref_option_ref::RefOptionRef)); - store.register_late_pass(|| Box::new(infinite_iter::InfiniteIter)); - store.register_late_pass(|| Box::new(inline_fn_without_body::InlineFnWithoutBody)); - store.register_late_pass(|| Box::new(useless_conversion::UselessConversion::default())); - store.register_late_pass(|| Box::new(implicit_hasher::ImplicitHasher)); - store.register_late_pass(|| Box::new(fallible_impl_from::FallibleImplFrom)); - store.register_late_pass(|| Box::new(question_mark::QuestionMark)); + store.register_late_pass(move |_| Box::new(pass_by_ref_or_value)); + store.register_late_pass(|_| Box::new(ref_option_ref::RefOptionRef)); + store.register_late_pass(|_| Box::new(infinite_iter::InfiniteIter)); + store.register_late_pass(|_| Box::new(inline_fn_without_body::InlineFnWithoutBody)); + store.register_late_pass(|_| Box::new(useless_conversion::UselessConversion::default())); + store.register_late_pass(|_| Box::new(implicit_hasher::ImplicitHasher)); + store.register_late_pass(|_| Box::new(fallible_impl_from::FallibleImplFrom)); + store.register_late_pass(|_| Box::new(question_mark::QuestionMark)); store.register_early_pass(|| Box::new(suspicious_operation_groupings::SuspiciousOperationGroupings)); - store.register_late_pass(|| Box::new(suspicious_trait_impl::SuspiciousImpl)); - store.register_late_pass(|| Box::new(map_unit_fn::MapUnit)); - store.register_late_pass(|| Box::new(inherent_impl::MultipleInherentImpl)); - store.register_late_pass(|| Box::new(neg_cmp_op_on_partial_ord::NoNegCompOpForPartialOrd)); - store.register_late_pass(|| Box::new(unwrap::Unwrap)); - store.register_late_pass(|| Box::new(indexing_slicing::IndexingSlicing)); - store.register_late_pass(|| Box::new(non_copy_const::NonCopyConst)); - store.register_late_pass(|| Box::new(ptr_offset_with_cast::PtrOffsetWithCast)); - store.register_late_pass(|| Box::new(redundant_clone::RedundantClone)); - store.register_late_pass(|| Box::new(slow_vector_initialization::SlowVectorInit)); - store.register_late_pass(move || Box::new(unnecessary_wraps::UnnecessaryWraps::new(avoid_breaking_exported_api))); - store.register_late_pass(|| Box::new(assertions_on_constants::AssertionsOnConstants)); - store.register_late_pass(|| Box::new(assertions_on_result_states::AssertionsOnResultStates)); - store.register_late_pass(|| Box::new(inherent_to_string::InherentToString)); + store.register_late_pass(|_| Box::new(suspicious_trait_impl::SuspiciousImpl)); + store.register_late_pass(|_| Box::new(map_unit_fn::MapUnit)); + store.register_late_pass(|_| Box::new(inherent_impl::MultipleInherentImpl)); + store.register_late_pass(|_| Box::new(neg_cmp_op_on_partial_ord::NoNegCompOpForPartialOrd)); + store.register_late_pass(|_| Box::new(unwrap::Unwrap)); + store.register_late_pass(|_| Box::new(indexing_slicing::IndexingSlicing)); + store.register_late_pass(|_| Box::new(non_copy_const::NonCopyConst)); + store.register_late_pass(|_| Box::new(ptr_offset_with_cast::PtrOffsetWithCast)); + store.register_late_pass(|_| Box::new(redundant_clone::RedundantClone)); + store.register_late_pass(|_| Box::new(slow_vector_initialization::SlowVectorInit)); + store.register_late_pass(move |_| Box::new(unnecessary_wraps::UnnecessaryWraps::new(avoid_breaking_exported_api))); + store.register_late_pass(|_| Box::new(assertions_on_constants::AssertionsOnConstants)); + store.register_late_pass(|_| Box::new(assertions_on_result_states::AssertionsOnResultStates)); + store.register_late_pass(|_| Box::new(inherent_to_string::InherentToString)); let max_trait_bounds = conf.max_trait_bounds; - store.register_late_pass(move || Box::new(trait_bounds::TraitBounds::new(max_trait_bounds))); - store.register_late_pass(|| Box::new(comparison_chain::ComparisonChain)); - store.register_late_pass(|| Box::new(mut_key::MutableKeyType)); + store.register_late_pass(move |_| Box::new(trait_bounds::TraitBounds::new(max_trait_bounds))); + store.register_late_pass(|_| Box::new(comparison_chain::ComparisonChain)); + store.register_late_pass(|_| Box::new(mut_key::MutableKeyType)); store.register_early_pass(|| Box::new(reference::DerefAddrOf)); store.register_early_pass(|| Box::new(double_parens::DoubleParens)); - store.register_late_pass(|| Box::new(format_impl::FormatImpl::new())); + store.register_late_pass(|_| Box::new(format_impl::FormatImpl::new())); store.register_early_pass(|| Box::new(unsafe_removed_from_name::UnsafeNameRemoval)); store.register_early_pass(|| Box::new(else_if_without_else::ElseIfWithoutElse)); store.register_early_pass(|| Box::new(int_plus_one::IntPlusOne)); store.register_early_pass(|| Box::new(formatting::Formatting)); store.register_early_pass(|| Box::new(misc_early::MiscEarlyLints)); store.register_early_pass(|| Box::new(redundant_closure_call::RedundantClosureCall)); - store.register_late_pass(|| Box::new(redundant_closure_call::RedundantClosureCall)); + store.register_late_pass(|_| Box::new(redundant_closure_call::RedundantClosureCall)); store.register_early_pass(|| Box::new(unused_unit::UnusedUnit)); - store.register_late_pass(|| Box::new(returns::Return)); + store.register_late_pass(|_| Box::new(returns::Return)); store.register_early_pass(|| Box::new(collapsible_if::CollapsibleIf)); store.register_early_pass(|| Box::new(items_after_statements::ItemsAfterStatements)); store.register_early_pass(|| Box::new(precedence::Precedence)); - store.register_late_pass(|| Box::new(needless_parens_on_range_literals::NeedlessParensOnRangeLiterals)); + store.register_late_pass(|_| Box::new(needless_parens_on_range_literals::NeedlessParensOnRangeLiterals)); store.register_early_pass(|| Box::new(needless_continue::NeedlessContinue)); store.register_early_pass(|| Box::new(redundant_else::RedundantElse)); - store.register_late_pass(|| Box::new(create_dir::CreateDir)); + store.register_late_pass(|_| Box::new(create_dir::CreateDir)); store.register_early_pass(|| Box::new(needless_arbitrary_self_type::NeedlessArbitrarySelfType)); let literal_representation_lint_fraction_readability = conf.unreadable_literal_lint_fractions; store.register_early_pass(move || { @@ -759,7 +759,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: )) }); let enum_variant_name_threshold = conf.enum_variant_name_threshold; - store.register_late_pass(move || { + store.register_late_pass(move |_| { Box::new(enum_variants::EnumVariantNames::new( enum_variant_name_threshold, avoid_breaking_exported_api, @@ -767,23 +767,23 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: }); store.register_early_pass(|| Box::new(tabs_in_doc_comments::TabsInDocComments)); let upper_case_acronyms_aggressive = conf.upper_case_acronyms_aggressive; - store.register_late_pass(move || { + store.register_late_pass(move |_| { Box::new(upper_case_acronyms::UpperCaseAcronyms::new( avoid_breaking_exported_api, upper_case_acronyms_aggressive, )) }); - store.register_late_pass(|| Box::new(default::Default::default())); - store.register_late_pass(move || Box::new(unused_self::UnusedSelf::new(avoid_breaking_exported_api))); - store.register_late_pass(|| Box::new(mutable_debug_assertion::DebugAssertWithMutCall)); - store.register_late_pass(|| Box::new(exit::Exit)); - store.register_late_pass(|| Box::new(to_digit_is_some::ToDigitIsSome)); + store.register_late_pass(|_| Box::new(default::Default::default())); + store.register_late_pass(move |_| Box::new(unused_self::UnusedSelf::new(avoid_breaking_exported_api))); + store.register_late_pass(|_| Box::new(mutable_debug_assertion::DebugAssertWithMutCall)); + store.register_late_pass(|_| Box::new(exit::Exit)); + store.register_late_pass(|_| Box::new(to_digit_is_some::ToDigitIsSome)); let array_size_threshold = conf.array_size_threshold; - store.register_late_pass(move || Box::new(large_stack_arrays::LargeStackArrays::new(array_size_threshold))); - store.register_late_pass(move || Box::new(large_const_arrays::LargeConstArrays::new(array_size_threshold))); - store.register_late_pass(|| Box::new(floating_point_arithmetic::FloatingPointArithmetic)); + store.register_late_pass(move |_| Box::new(large_stack_arrays::LargeStackArrays::new(array_size_threshold))); + store.register_late_pass(move |_| Box::new(large_const_arrays::LargeConstArrays::new(array_size_threshold))); + store.register_late_pass(|_| Box::new(floating_point_arithmetic::FloatingPointArithmetic)); store.register_early_pass(|| Box::new(as_conversions::AsConversions)); - store.register_late_pass(|| Box::new(let_underscore::LetUnderscore)); + store.register_late_pass(|_| Box::new(let_underscore::LetUnderscore)); store.register_early_pass(|| Box::new(single_component_path_imports::SingleComponentPathImports)); let max_fn_params_bools = conf.max_fn_params_bools; let max_struct_bools = conf.max_struct_bools; @@ -795,17 +795,17 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: }); store.register_early_pass(|| Box::new(option_env_unwrap::OptionEnvUnwrap)); let warn_on_all_wildcard_imports = conf.warn_on_all_wildcard_imports; - store.register_late_pass(move || Box::new(wildcard_imports::WildcardImports::new(warn_on_all_wildcard_imports))); - store.register_late_pass(|| Box::new(redundant_pub_crate::RedundantPubCrate::default())); - store.register_late_pass(|| Box::new(unnamed_address::UnnamedAddress)); - store.register_late_pass(move || Box::new(dereference::Dereferencing::new(msrv))); - store.register_late_pass(|| Box::new(option_if_let_else::OptionIfLetElse)); - store.register_late_pass(|| Box::new(future_not_send::FutureNotSend)); - store.register_late_pass(|| Box::new(if_let_mutex::IfLetMutex)); - store.register_late_pass(|| Box::new(if_not_else::IfNotElse)); - store.register_late_pass(|| Box::new(equatable_if_let::PatternEquality)); - store.register_late_pass(|| Box::new(manual_async_fn::ManualAsyncFn)); - store.register_late_pass(|| Box::new(panic_in_result_fn::PanicInResultFn)); + store.register_late_pass(move |_| Box::new(wildcard_imports::WildcardImports::new(warn_on_all_wildcard_imports))); + store.register_late_pass(|_| Box::new(redundant_pub_crate::RedundantPubCrate::default())); + store.register_late_pass(|_| Box::new(unnamed_address::UnnamedAddress)); + store.register_late_pass(move |_| Box::new(dereference::Dereferencing::new(msrv))); + store.register_late_pass(|_| Box::new(option_if_let_else::OptionIfLetElse)); + store.register_late_pass(|_| Box::new(future_not_send::FutureNotSend)); + store.register_late_pass(|_| Box::new(if_let_mutex::IfLetMutex)); + store.register_late_pass(|_| Box::new(if_not_else::IfNotElse)); + store.register_late_pass(|_| Box::new(equatable_if_let::PatternEquality)); + store.register_late_pass(|_| Box::new(manual_async_fn::ManualAsyncFn)); + store.register_late_pass(|_| Box::new(panic_in_result_fn::PanicInResultFn)); let single_char_binding_names_threshold = conf.single_char_binding_names_threshold; store.register_early_pass(move || { Box::new(non_expressive_names::NonExpressiveNames { @@ -814,92 +814,92 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: }); let macro_matcher = conf.standard_macro_braces.iter().cloned().collect::>(); store.register_early_pass(move || Box::new(nonstandard_macro_braces::MacroBraces::new(¯o_matcher))); - store.register_late_pass(|| Box::new(macro_use::MacroUseImports::default())); - store.register_late_pass(|| Box::new(pattern_type_mismatch::PatternTypeMismatch)); - store.register_late_pass(|| Box::new(unwrap_in_result::UnwrapInResult)); - store.register_late_pass(|| Box::new(semicolon_if_nothing_returned::SemicolonIfNothingReturned)); - store.register_late_pass(|| Box::new(async_yields_async::AsyncYieldsAsync)); + store.register_late_pass(|_| Box::new(macro_use::MacroUseImports::default())); + store.register_late_pass(|_| Box::new(pattern_type_mismatch::PatternTypeMismatch)); + store.register_late_pass(|_| Box::new(unwrap_in_result::UnwrapInResult)); + store.register_late_pass(|_| Box::new(semicolon_if_nothing_returned::SemicolonIfNothingReturned)); + store.register_late_pass(|_| Box::new(async_yields_async::AsyncYieldsAsync)); let disallowed_methods = conf.disallowed_methods.clone(); - store.register_late_pass(move || Box::new(disallowed_methods::DisallowedMethods::new(disallowed_methods.clone()))); + store.register_late_pass(move |_| Box::new(disallowed_methods::DisallowedMethods::new(disallowed_methods.clone()))); store.register_early_pass(|| Box::new(asm_syntax::InlineAsmX86AttSyntax)); store.register_early_pass(|| Box::new(asm_syntax::InlineAsmX86IntelSyntax)); - store.register_late_pass(|| Box::new(empty_drop::EmptyDrop)); - store.register_late_pass(|| Box::new(strings::StrToString)); - store.register_late_pass(|| Box::new(strings::StringToString)); - store.register_late_pass(|| Box::new(zero_sized_map_values::ZeroSizedMapValues)); - store.register_late_pass(|| Box::new(vec_init_then_push::VecInitThenPush::default())); - store.register_late_pass(|| Box::new(redundant_slicing::RedundantSlicing)); - store.register_late_pass(|| Box::new(from_str_radix_10::FromStrRadix10)); - store.register_late_pass(move || Box::new(if_then_some_else_none::IfThenSomeElseNone::new(msrv))); - store.register_late_pass(|| Box::new(bool_assert_comparison::BoolAssertComparison)); + store.register_late_pass(|_| Box::new(empty_drop::EmptyDrop)); + store.register_late_pass(|_| Box::new(strings::StrToString)); + store.register_late_pass(|_| Box::new(strings::StringToString)); + store.register_late_pass(|_| Box::new(zero_sized_map_values::ZeroSizedMapValues)); + store.register_late_pass(|_| Box::new(vec_init_then_push::VecInitThenPush::default())); + store.register_late_pass(|_| Box::new(redundant_slicing::RedundantSlicing)); + store.register_late_pass(|_| Box::new(from_str_radix_10::FromStrRadix10)); + store.register_late_pass(move |_| Box::new(if_then_some_else_none::IfThenSomeElseNone::new(msrv))); + store.register_late_pass(|_| Box::new(bool_assert_comparison::BoolAssertComparison)); store.register_early_pass(move || Box::new(module_style::ModStyle)); - store.register_late_pass(|| Box::new(unused_async::UnusedAsync)); + store.register_late_pass(|_| Box::new(unused_async::UnusedAsync)); let disallowed_types = conf.disallowed_types.clone(); - store.register_late_pass(move || Box::new(disallowed_types::DisallowedTypes::new(disallowed_types.clone()))); + store.register_late_pass(move |_| Box::new(disallowed_types::DisallowedTypes::new(disallowed_types.clone()))); let import_renames = conf.enforced_import_renames.clone(); - store.register_late_pass(move || { + store.register_late_pass(move |_| { Box::new(missing_enforced_import_rename::ImportRename::new( import_renames.clone(), )) }); let scripts = conf.allowed_scripts.clone(); store.register_early_pass(move || Box::new(disallowed_script_idents::DisallowedScriptIdents::new(&scripts))); - store.register_late_pass(|| Box::new(strlen_on_c_strings::StrlenOnCStrings)); - store.register_late_pass(move || Box::new(self_named_constructors::SelfNamedConstructors)); - store.register_late_pass(move || Box::new(iter_not_returning_iterator::IterNotReturningIterator)); - store.register_late_pass(move || Box::new(manual_assert::ManualAssert)); + store.register_late_pass(|_| Box::new(strlen_on_c_strings::StrlenOnCStrings)); + store.register_late_pass(move |_| Box::new(self_named_constructors::SelfNamedConstructors)); + store.register_late_pass(move |_| Box::new(iter_not_returning_iterator::IterNotReturningIterator)); + store.register_late_pass(move |_| Box::new(manual_assert::ManualAssert)); let enable_raw_pointer_heuristic_for_send = conf.enable_raw_pointer_heuristic_for_send; - store.register_late_pass(move || { + store.register_late_pass(move |_| { Box::new(non_send_fields_in_send_ty::NonSendFieldInSendTy::new( enable_raw_pointer_heuristic_for_send, )) }); - store.register_late_pass(move || Box::new(undocumented_unsafe_blocks::UndocumentedUnsafeBlocks)); - store.register_late_pass(move || Box::new(format_args::FormatArgs)); - store.register_late_pass(|| Box::new(trailing_empty_array::TrailingEmptyArray)); + store.register_late_pass(move |_| Box::new(undocumented_unsafe_blocks::UndocumentedUnsafeBlocks)); + store.register_late_pass(move |_| Box::new(format_args::FormatArgs)); + store.register_late_pass(|_| Box::new(trailing_empty_array::TrailingEmptyArray)); store.register_early_pass(|| Box::new(octal_escapes::OctalEscapes)); - store.register_late_pass(|| Box::new(needless_late_init::NeedlessLateInit)); - store.register_late_pass(|| Box::new(return_self_not_must_use::ReturnSelfNotMustUse)); - store.register_late_pass(|| Box::new(init_numbered_fields::NumberedFields)); + store.register_late_pass(|_| Box::new(needless_late_init::NeedlessLateInit)); + store.register_late_pass(|_| Box::new(return_self_not_must_use::ReturnSelfNotMustUse)); + store.register_late_pass(|_| Box::new(init_numbered_fields::NumberedFields)); store.register_early_pass(|| Box::new(single_char_lifetime_names::SingleCharLifetimeNames)); - store.register_late_pass(move || Box::new(manual_bits::ManualBits::new(msrv))); - store.register_late_pass(|| Box::new(default_union_representation::DefaultUnionRepresentation)); + store.register_late_pass(move |_| Box::new(manual_bits::ManualBits::new(msrv))); + store.register_late_pass(|_| Box::new(default_union_representation::DefaultUnionRepresentation)); store.register_early_pass(|| Box::new(doc_link_with_quotes::DocLinkWithQuotes)); - store.register_late_pass(|| Box::new(only_used_in_recursion::OnlyUsedInRecursion::default())); + store.register_late_pass(|_| Box::new(only_used_in_recursion::OnlyUsedInRecursion::default())); let allow_dbg_in_tests = conf.allow_dbg_in_tests; - store.register_late_pass(move || Box::new(dbg_macro::DbgMacro::new(allow_dbg_in_tests))); + store.register_late_pass(move |_| Box::new(dbg_macro::DbgMacro::new(allow_dbg_in_tests))); let cargo_ignore_publish = conf.cargo_ignore_publish; - store.register_late_pass(move || { + store.register_late_pass(move |_| { Box::new(cargo::Cargo { ignore_publish: cargo_ignore_publish, }) }); store.register_early_pass(|| Box::new(crate_in_macro_def::CrateInMacroDef)); store.register_early_pass(|| Box::new(empty_structs_with_brackets::EmptyStructsWithBrackets)); - store.register_late_pass(|| Box::new(unnecessary_owned_empty_strings::UnnecessaryOwnedEmptyStrings)); + store.register_late_pass(|_| Box::new(unnecessary_owned_empty_strings::UnnecessaryOwnedEmptyStrings)); store.register_early_pass(|| Box::new(pub_use::PubUse)); - store.register_late_pass(|| Box::new(format_push_string::FormatPushString)); + store.register_late_pass(|_| Box::new(format_push_string::FormatPushString)); let max_include_file_size = conf.max_include_file_size; - store.register_late_pass(move || Box::new(large_include_file::LargeIncludeFile::new(max_include_file_size))); - store.register_late_pass(|| Box::new(strings::TrimSplitWhitespace)); - store.register_late_pass(|| Box::new(rc_clone_in_vec_init::RcCloneInVecInit)); + store.register_late_pass(move |_| Box::new(large_include_file::LargeIncludeFile::new(max_include_file_size))); + store.register_late_pass(|_| Box::new(strings::TrimSplitWhitespace)); + store.register_late_pass(|_| Box::new(rc_clone_in_vec_init::RcCloneInVecInit)); store.register_early_pass(|| Box::new(duplicate_mod::DuplicateMod::default())); store.register_early_pass(|| Box::new(unused_rounding::UnusedRounding)); store.register_early_pass(move || Box::new(almost_complete_letter_range::AlmostCompleteLetterRange::new(msrv))); - store.register_late_pass(|| Box::new(swap_ptr_to_ref::SwapPtrToRef)); - store.register_late_pass(|| Box::new(mismatching_type_param_order::TypeParamMismatch)); - store.register_late_pass(|| Box::new(read_zero_byte_vec::ReadZeroByteVec)); - store.register_late_pass(|| Box::new(default_instead_of_iter_empty::DefaultIterEmpty)); - store.register_late_pass(move || Box::new(manual_rem_euclid::ManualRemEuclid::new(msrv))); - store.register_late_pass(move || Box::new(manual_retain::ManualRetain::new(msrv))); + store.register_late_pass(|_| Box::new(swap_ptr_to_ref::SwapPtrToRef)); + store.register_late_pass(|_| Box::new(mismatching_type_param_order::TypeParamMismatch)); + store.register_late_pass(|_| Box::new(read_zero_byte_vec::ReadZeroByteVec)); + store.register_late_pass(|_| Box::new(default_instead_of_iter_empty::DefaultIterEmpty)); + store.register_late_pass(move |_| Box::new(manual_rem_euclid::ManualRemEuclid::new(msrv))); + store.register_late_pass(move |_| Box::new(manual_retain::ManualRetain::new(msrv))); let verbose_bit_mask_threshold = conf.verbose_bit_mask_threshold; - store.register_late_pass(move || Box::new(operators::Operators::new(verbose_bit_mask_threshold))); - store.register_late_pass(|| Box::new(invalid_utf8_in_unchecked::InvalidUtf8InUnchecked)); - store.register_late_pass(|| Box::new(std_instead_of_core::StdReexports::default())); - store.register_late_pass(|| Box::new(manual_instant_elapsed::ManualInstantElapsed)); - store.register_late_pass(|| Box::new(partialeq_to_none::PartialeqToNone)); - store.register_late_pass(|| Box::new(manual_string_new::ManualStringNew)); - store.register_late_pass(|| Box::new(unused_peekable::UnusedPeekable)); + store.register_late_pass(move |_| Box::new(operators::Operators::new(verbose_bit_mask_threshold))); + store.register_late_pass(|_| Box::new(invalid_utf8_in_unchecked::InvalidUtf8InUnchecked)); + store.register_late_pass(|_| Box::new(std_instead_of_core::StdReexports::default())); + store.register_late_pass(|_| Box::new(manual_instant_elapsed::ManualInstantElapsed)); + store.register_late_pass(|_| Box::new(partialeq_to_none::PartialeqToNone)); + store.register_late_pass(|_| Box::new(manual_string_new::ManualStringNew)); + store.register_late_pass(|_| Box::new(unused_peekable::UnusedPeekable)); store.register_early_pass(|| Box::new(multi_assignments::MultiAssignments)); // add lints here, do not remove this comment, it's used in `new_lint` } From 91360966297a4cf2008a56f727b03012d3d9e4b3 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sun, 28 Aug 2022 00:10:06 +0300 Subject: [PATCH 02/34] rustc: Parameterize `ty::Visibility` over used ID It allows using `LocalDefId` instead of `DefId` when possible, and also encode cheaper `Visibility` into metadata. --- clippy_lints/src/default.rs | 2 +- clippy_lints/src/derive.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/clippy_lints/src/default.rs b/clippy_lints/src/default.rs index 74f7df611..4e68d6810 100644 --- a/clippy_lints/src/default.rs +++ b/clippy_lints/src/default.rs @@ -142,7 +142,7 @@ impl<'tcx> LateLintPass<'tcx> for Default { if adt.is_struct(); let variant = adt.non_enum_variant(); if adt.did().is_local() || !variant.is_field_list_non_exhaustive(); - let module_did = cx.tcx.parent_module(stmt.hir_id).to_def_id(); + let module_did = cx.tcx.parent_module(stmt.hir_id); if variant .fields .iter() diff --git a/clippy_lints/src/derive.rs b/clippy_lints/src/derive.rs index 9ca443b7d..23c86482b 100644 --- a/clippy_lints/src/derive.rs +++ b/clippy_lints/src/derive.rs @@ -15,7 +15,7 @@ use rustc_middle::hir::nested_filter; use rustc_middle::traits::Reveal; use rustc_middle::ty::{ self, Binder, BoundConstness, GenericParamDefKind, ImplPolarity, ParamEnv, PredicateKind, TraitPredicate, TraitRef, - Ty, TyCtxt, Visibility, + Ty, TyCtxt, }; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::source_map::Span; @@ -464,7 +464,7 @@ impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> { fn check_partial_eq_without_eq<'tcx>(cx: &LateContext<'tcx>, span: Span, trait_ref: &hir::TraitRef<'_>, ty: Ty<'tcx>) { if_chain! { if let ty::Adt(adt, substs) = ty.kind(); - if cx.tcx.visibility(adt.did()) == Visibility::Public; + if cx.tcx.visibility(adt.did()).is_public(); if let Some(eq_trait_def_id) = cx.tcx.get_diagnostic_item(sym::Eq); if let Some(def_id) = trait_ref.trait_def_id(); if cx.tcx.is_diagnostic_item(sym::PartialEq, def_id); From 977b6e29a345ee43acabd2e1a7eb8e454626e2f3 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 1 Sep 2022 12:06:48 +1000 Subject: [PATCH 03/34] Arena-allocate `hir::Lifetime`. This shrinks `hir::Ty` from 72 to 48 bytes. `visit_lifetime` is added to the HIR stats collector because these types are now stored in memory on their own, instead of being within other types. --- clippy_utils/src/hir_utils.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clippy_utils/src/hir_utils.rs b/clippy_utils/src/hir_utils.rs index 57448f716..ff23ed5ff 100644 --- a/clippy_utils/src/hir_utils.rs +++ b/clippy_utils/src/hir_utils.rs @@ -929,7 +929,7 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { } } - pub fn hash_lifetime(&mut self, lifetime: Lifetime) { + pub fn hash_lifetime(&mut self, lifetime: &Lifetime) { std::mem::discriminant(&lifetime.name).hash(&mut self.s); if let LifetimeName::Param(param_id, ref name) = lifetime.name { std::mem::discriminant(name).hash(&mut self.s); From c86a9c077c3b3a8c04166934ec1465920419a2cd Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 1 Sep 2022 13:29:57 +1000 Subject: [PATCH 04/34] Introduce `DotDotPos`. This shrinks `hir::Pat` from 88 to 72 bytes. --- clippy_lints/src/equatable_if_let.rs | 4 +++- clippy_lints/src/matches/match_same_arms.rs | 4 ++-- clippy_lints/src/matches/single_match.rs | 2 ++ clippy_lints/src/question_mark.rs | 3 ++- clippy_lints/src/unit_types/let_unit_value.rs | 6 ++++-- clippy_utils/src/lib.rs | 3 ++- 6 files changed, 15 insertions(+), 7 deletions(-) diff --git a/clippy_lints/src/equatable_if_let.rs b/clippy_lints/src/equatable_if_let.rs index fdfb821ac..bce49165e 100644 --- a/clippy_lints/src/equatable_if_let.rs +++ b/clippy_lints/src/equatable_if_let.rs @@ -51,7 +51,9 @@ fn unary_pattern(pat: &Pat<'_>) -> bool { false }, PatKind::Struct(_, a, etc) => !etc && a.iter().all(|x| unary_pattern(x.pat)), - PatKind::Tuple(a, etc) | PatKind::TupleStruct(_, a, etc) => !etc.is_some() && array_rec(a), + PatKind::Tuple(a, etc) | PatKind::TupleStruct(_, a, etc) => { + !etc.as_opt_usize().is_some() && array_rec(a) + } PatKind::Ref(x, _) | PatKind::Box(x) => unary_pattern(x), PatKind::Path(_) | PatKind::Lit(_) => true, } diff --git a/clippy_lints/src/matches/match_same_arms.rs b/clippy_lints/src/matches/match_same_arms.rs index e32ef9933..93874b103 100644 --- a/clippy_lints/src/matches/match_same_arms.rs +++ b/clippy_lints/src/matches/match_same_arms.rs @@ -248,7 +248,7 @@ impl<'a> NormalizedPat<'a> { } else { (None, adt.non_enum_variant()) }; - let (front, back) = match wild_idx { + let (front, back) = match wild_idx.as_opt_usize() { Some(i) => pats.split_at(i), None => (pats, [].as_slice()), }; @@ -268,7 +268,7 @@ impl<'a> NormalizedPat<'a> { ty::Tuple(subs) => subs.len(), _ => return Self::Wild, }; - let (front, back) = match wild_idx { + let (front, back) = match wild_idx.as_opt_usize() { Some(i) => pats.split_at(i), None => (pats, [].as_slice()), }; diff --git a/clippy_lints/src/matches/single_match.rs b/clippy_lints/src/matches/single_match.rs index 95478af45..1bf1c4d10 100644 --- a/clippy_lints/src/matches/single_match.rs +++ b/clippy_lints/src/matches/single_match.rs @@ -200,6 +200,8 @@ fn form_exhaustive_matches<'a>(cx: &LateContext<'a>, ty: Ty<'a>, left: &Pat<'_>, // We don't actually know the position and the presence of the `..` (dotdot) operator // in the arms, so we need to evaluate the correct offsets here in order to iterate in // both arms at the same time. + let left_pos = left_pos.as_opt_usize(); + let right_pos = right_pos.as_opt_usize(); let len = max( left_in.len() + { if left_pos.is_some() { 1 } else { 0 } diff --git a/clippy_lints/src/question_mark.rs b/clippy_lints/src/question_mark.rs index f4f1fd336..569870ab2 100644 --- a/clippy_lints/src/question_mark.rs +++ b/clippy_lints/src/question_mark.rs @@ -122,7 +122,8 @@ fn check_if_let_some_or_err_and_early_return<'tcx>(cx: &LateContext<'tcx>, expr: if_chain! { if let Some(higher::IfLet { let_pat, let_expr, if_then, if_else }) = higher::IfLet::hir(cx, expr); if !is_else_clause(cx.tcx, expr); - if let PatKind::TupleStruct(ref path1, [field], None) = let_pat.kind; + if let PatKind::TupleStruct(ref path1, [field], ddpos) = let_pat.kind; + if ddpos.as_opt_usize().is_none(); if let PatKind::Binding(BindingAnnotation(by_ref, _), bind_id, ident, None) = field.kind; let caller_ty = cx.typeck_results().expr_ty(let_expr); let if_block = IfBlockType::IfLet(path1, caller_ty, ident.name, let_expr, if_then, if_else); diff --git a/clippy_lints/src/unit_types/let_unit_value.rs b/clippy_lints/src/unit_types/let_unit_value.rs index 35824b031..ce9ebad8c 100644 --- a/clippy_lints/src/unit_types/let_unit_value.rs +++ b/clippy_lints/src/unit_types/let_unit_value.rs @@ -19,10 +19,12 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, local: &'tcx Local<'_>) { && cx.typeck_results().pat_ty(local.pat).is_unit() { if (local.ty.map_or(false, |ty| !matches!(ty.kind, TyKind::Infer)) - || matches!(local.pat.kind, PatKind::Tuple([], None))) + || matches!(local.pat.kind, PatKind::Tuple([], ddpos) if ddpos.as_opt_usize().is_none())) && expr_needs_inferred_result(cx, init) { - if !matches!(local.pat.kind, PatKind::Wild | PatKind::Tuple([], None)) { + if !matches!(local.pat.kind, PatKind::Wild) + && !matches!(local.pat.kind, PatKind::Tuple([], ddpos) if ddpos.as_opt_usize().is_none()) + { span_lint_and_then( cx, LET_UNIT_VALUE, diff --git a/clippy_utils/src/lib.rs b/clippy_utils/src/lib.rs index b27439cbe..3cf043f22 100644 --- a/clippy_utils/src/lib.rs +++ b/clippy_utils/src/lib.rs @@ -1552,7 +1552,8 @@ pub fn iter_input_pats<'tcx>(decl: &FnDecl<'_>, body: &'tcx Body<'_>) -> impl It pub fn is_try<'tcx>(cx: &LateContext<'_>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> { fn is_ok(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool { if_chain! { - if let PatKind::TupleStruct(ref path, pat, None) = arm.pat.kind; + if let PatKind::TupleStruct(ref path, pat, ddpos) = arm.pat.kind; + if ddpos.as_opt_usize().is_none(); if is_lang_ctor(cx, path, ResultOk); if let PatKind::Binding(_, hir_id, _, None) = pat[0].kind; if path_to_local_id(arm.body, hir_id); From b640eaa71da9c48712565b9de2a98d1e9551fc54 Mon Sep 17 00:00:00 2001 From: Jack Huey <31162821+jackh726@users.noreply.github.com> Date: Sun, 26 Jun 2022 15:40:45 -0400 Subject: [PATCH 05/34] Remove ReEmpty --- clippy_lints/src/needless_pass_by_value.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clippy_lints/src/needless_pass_by_value.rs b/clippy_lints/src/needless_pass_by_value.rs index 6d17c7a73..060037ed4 100644 --- a/clippy_lints/src/needless_pass_by_value.rs +++ b/clippy_lints/src/needless_pass_by_value.rs @@ -173,7 +173,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { ( preds.iter().any(|t| cx.tcx.is_diagnostic_item(sym::Borrow, t.def_id())), !preds.is_empty() && { - let ty_empty_region = cx.tcx.mk_imm_ref(cx.tcx.lifetimes.re_root_empty, ty); + let ty_empty_region = cx.tcx.mk_imm_ref(cx.tcx.lifetimes.re_erased, ty); preds.iter().all(|t| { let ty_params = t.trait_ref.substs.iter().skip(1).collect::>(); implements_trait(cx, ty_empty_region, t.def_id(), &ty_params) From ac1c68a5e6a25bcf32f352328b69bcf32f5b9973 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 31 Aug 2022 05:29:36 +0000 Subject: [PATCH 06/34] Make clippy happy --- clippy_lints/src/dereference.rs | 2 +- clippy_lints/src/missing_doc.rs | 3 ++- clippy_lints/src/missing_inline.rs | 1 + clippy_utils/src/hir_utils.rs | 3 +++ 4 files changed, 7 insertions(+), 2 deletions(-) diff --git a/clippy_lints/src/dereference.rs b/clippy_lints/src/dereference.rs index d1ab7fb67..09a073f42 100644 --- a/clippy_lints/src/dereference.rs +++ b/clippy_lints/src/dereference.rs @@ -959,7 +959,7 @@ fn binding_ty_auto_deref_stability<'tcx>( )) .is_sized(cx.tcx.at(DUMMY_SP), cx.param_env.without_caller_bounds()), ), - TyKind::OpaqueDef(..) | TyKind::Infer | TyKind::Typeof(..) | TyKind::TraitObject(..) | TyKind::Err => { + TyKind::OpaqueDef(..) | TyKind::ImplTraitInTrait(..) | TyKind::Infer | TyKind::Typeof(..) | TyKind::TraitObject(..) | TyKind::Err => { Position::ReborrowStable(precedence) }, }; diff --git a/clippy_lints/src/missing_doc.rs b/clippy_lints/src/missing_doc.rs index 3701fdb4a..9f518c7aa 100644 --- a/clippy_lints/src/missing_doc.rs +++ b/clippy_lints/src/missing_doc.rs @@ -147,7 +147,8 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { | hir::ItemKind::TraitAlias(..) | hir::ItemKind::TyAlias(..) | hir::ItemKind::Union(..) - | hir::ItemKind::OpaqueTy(..) => {}, + | hir::ItemKind::OpaqueTy(..) + | hir::ItemKind::ImplTraitPlaceholder(..) => {}, hir::ItemKind::ExternCrate(..) | hir::ItemKind::ForeignMod { .. } | hir::ItemKind::GlobalAsm(..) diff --git a/clippy_lints/src/missing_inline.rs b/clippy_lints/src/missing_inline.rs index 07bc2ca5d..9fd1a475d 100644 --- a/clippy_lints/src/missing_inline.rs +++ b/clippy_lints/src/missing_inline.rs @@ -128,6 +128,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingInline { | hir::ItemKind::TyAlias(..) | hir::ItemKind::Union(..) | hir::ItemKind::OpaqueTy(..) + | hir::ItemKind::ImplTraitPlaceholder(..) | hir::ItemKind::ExternCrate(..) | hir::ItemKind::ForeignMod { .. } | hir::ItemKind::Impl { .. } diff --git a/clippy_utils/src/hir_utils.rs b/clippy_utils/src/hir_utils.rs index ff23ed5ff..9f8500d41 100644 --- a/clippy_utils/src/hir_utils.rs +++ b/clippy_utils/src/hir_utils.rs @@ -990,6 +990,9 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { TyKind::OpaqueDef(_, arg_list) => { self.hash_generic_args(arg_list); }, + TyKind::ImplTraitInTrait(_) => { + // Do nothing + } TyKind::TraitObject(_, lifetime, _) => { self.hash_lifetime(*lifetime); }, From 854f751b263dfac06dc3f635f8a9f92b8bc51da6 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 6 Sep 2022 17:27:47 +0000 Subject: [PATCH 07/34] Appease clippy again --- clippy_lints/src/dereference.rs | 2 +- clippy_lints/src/lifetimes.rs | 2 +- clippy_lints/src/manual_async_fn.rs | 2 +- clippy_lints/src/missing_doc.rs | 3 +-- clippy_lints/src/missing_inline.rs | 1 - clippy_utils/src/hir_utils.rs | 6 ++---- 6 files changed, 6 insertions(+), 10 deletions(-) diff --git a/clippy_lints/src/dereference.rs b/clippy_lints/src/dereference.rs index 09a073f42..d1ab7fb67 100644 --- a/clippy_lints/src/dereference.rs +++ b/clippy_lints/src/dereference.rs @@ -959,7 +959,7 @@ fn binding_ty_auto_deref_stability<'tcx>( )) .is_sized(cx.tcx.at(DUMMY_SP), cx.param_env.without_caller_bounds()), ), - TyKind::OpaqueDef(..) | TyKind::ImplTraitInTrait(..) | TyKind::Infer | TyKind::Typeof(..) | TyKind::TraitObject(..) | TyKind::Err => { + TyKind::OpaqueDef(..) | TyKind::Infer | TyKind::Typeof(..) | TyKind::TraitObject(..) | TyKind::Err => { Position::ReborrowStable(precedence) }, }; diff --git a/clippy_lints/src/lifetimes.rs b/clippy_lints/src/lifetimes.rs index 573a7c016..5995675bd 100644 --- a/clippy_lints/src/lifetimes.rs +++ b/clippy_lints/src/lifetimes.rs @@ -441,7 +441,7 @@ impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> { fn visit_ty(&mut self, ty: &'tcx Ty<'_>) { match ty.kind { - TyKind::OpaqueDef(item, bounds) => { + TyKind::OpaqueDef(item, bounds, _) => { let map = self.cx.tcx.hir(); let item = map.item(item); let len = self.lts.len(); diff --git a/clippy_lints/src/manual_async_fn.rs b/clippy_lints/src/manual_async_fn.rs index 2502c8f88..754b0e78a 100644 --- a/clippy_lints/src/manual_async_fn.rs +++ b/clippy_lints/src/manual_async_fn.rs @@ -103,7 +103,7 @@ fn future_trait_ref<'tcx>( ty: &'tcx Ty<'tcx>, ) -> Option<(&'tcx TraitRef<'tcx>, Vec)> { if_chain! { - if let TyKind::OpaqueDef(item_id, bounds) = ty.kind; + if let TyKind::OpaqueDef(item_id, bounds, false) = ty.kind; let item = cx.tcx.hir().item(item_id); if let ItemKind::OpaqueTy(opaque) = &item.kind; if let Some(trait_ref) = opaque.bounds.iter().find_map(|bound| { diff --git a/clippy_lints/src/missing_doc.rs b/clippy_lints/src/missing_doc.rs index 9f518c7aa..3701fdb4a 100644 --- a/clippy_lints/src/missing_doc.rs +++ b/clippy_lints/src/missing_doc.rs @@ -147,8 +147,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { | hir::ItemKind::TraitAlias(..) | hir::ItemKind::TyAlias(..) | hir::ItemKind::Union(..) - | hir::ItemKind::OpaqueTy(..) - | hir::ItemKind::ImplTraitPlaceholder(..) => {}, + | hir::ItemKind::OpaqueTy(..) => {}, hir::ItemKind::ExternCrate(..) | hir::ItemKind::ForeignMod { .. } | hir::ItemKind::GlobalAsm(..) diff --git a/clippy_lints/src/missing_inline.rs b/clippy_lints/src/missing_inline.rs index 9fd1a475d..07bc2ca5d 100644 --- a/clippy_lints/src/missing_inline.rs +++ b/clippy_lints/src/missing_inline.rs @@ -128,7 +128,6 @@ impl<'tcx> LateLintPass<'tcx> for MissingInline { | hir::ItemKind::TyAlias(..) | hir::ItemKind::Union(..) | hir::ItemKind::OpaqueTy(..) - | hir::ItemKind::ImplTraitPlaceholder(..) | hir::ItemKind::ExternCrate(..) | hir::ItemKind::ForeignMod { .. } | hir::ItemKind::Impl { .. } diff --git a/clippy_utils/src/hir_utils.rs b/clippy_utils/src/hir_utils.rs index 9f8500d41..f45cec9f0 100644 --- a/clippy_utils/src/hir_utils.rs +++ b/clippy_utils/src/hir_utils.rs @@ -987,12 +987,10 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { } }, TyKind::Path(ref qpath) => self.hash_qpath(qpath), - TyKind::OpaqueDef(_, arg_list) => { + TyKind::OpaqueDef(_, arg_list, in_trait) => { self.hash_generic_args(arg_list); + in_trait.hash(&mut self.s); }, - TyKind::ImplTraitInTrait(_) => { - // Do nothing - } TyKind::TraitObject(_, lifetime, _) => { self.hash_lifetime(*lifetime); }, From 98bf99e2f8cf8b357d63a67ce67d5fc5ceef8b3c Mon Sep 17 00:00:00 2001 From: Philipp Krones Date: Fri, 9 Sep 2022 13:36:26 +0200 Subject: [PATCH 08/34] Merge commit 'b52fb5234cd7c11ecfae51897a6f7fa52e8777fc' into clippyup --- CHANGELOG.md | 3 +- clippy_dev/src/update_lints.rs | 194 +++++- clippy_lints/src/async_yields_async.rs | 2 +- clippy_lints/src/attrs.rs | 6 +- clippy_lints/src/bool_to_int_with_if.rs | 125 ++++ clippy_lints/src/default_numeric_fallback.rs | 21 +- clippy_lints/src/dereference.rs | 31 +- clippy_lints/src/derivable_impls.rs | 2 +- clippy_lints/src/doc.rs | 8 +- clippy_lints/src/eta_reduction.rs | 9 +- clippy_lints/src/fallible_impl_from.rs | 4 +- clippy_lints/src/floating_point_arithmetic.rs | 30 +- clippy_lints/src/functions/must_use.rs | 2 +- clippy_lints/src/functions/result.rs | 10 +- clippy_lints/src/implicit_return.rs | 4 +- clippy_lints/src/infinite_iter.rs | 10 +- clippy_lints/src/large_enum_variant.rs | 98 +-- clippy_lints/src/len_zero.rs | 16 +- clippy_lints/src/lib.register_all.rs | 1 + clippy_lints/src/lib.register_lints.rs | 3 +- clippy_lints/src/lib.register_restriction.rs | 2 +- clippy_lints/src/lib.register_style.rs | 1 + clippy_lints/src/lib.rs | 12 +- clippy_lints/src/lifetimes.rs | 2 +- clippy_lints/src/loops/needless_range_loop.rs | 2 +- .../src/loops/while_let_on_iterator.rs | 2 +- .../src/matches/match_wild_err_arm.rs | 2 +- clippy_lints/src/matches/single_match.rs | 8 +- .../src/methods/bind_instead_of_map.rs | 2 +- clippy_lints/src/methods/chars_cmp.rs | 2 +- clippy_lints/src/methods/clone_on_copy.rs | 6 +- clippy_lints/src/methods/filter_map.rs | 2 +- clippy_lints/src/methods/map_clone.rs | 2 +- clippy_lints/src/methods/mod.rs | 5 +- clippy_lints/src/methods/mut_mutex_lock.rs | 3 +- clippy_lints/src/methods/open_options.rs | 2 +- .../src/methods/option_as_ref_deref.rs | 2 +- .../src/methods/option_map_or_none.rs | 2 +- clippy_lints/src/methods/or_fun_call.rs | 13 +- clippy_lints/src/methods/suspicious_map.rs | 4 +- .../src/methods/unnecessary_filter_map.rs | 11 +- clippy_lints/src/methods/unnecessary_fold.rs | 2 +- .../src/methods/unnecessary_sort_by.rs | 2 +- .../src/methods/unnecessary_to_owned.rs | 217 ++++--- .../src/methods/unwrap_or_else_default.rs | 24 +- clippy_lints/src/minmax.rs | 32 +- clippy_lints/src/needless_for_each.rs | 2 +- clippy_lints/src/only_used_in_recursion.rs | 15 +- clippy_lints/src/operators/arithmetic.rs | 119 ---- .../src/operators/arithmetic_side_effects.rs | 173 +++++ clippy_lints/src/operators/mod.rs | 32 +- clippy_lints/src/panic_in_result_fn.rs | 2 +- clippy_lints/src/ptr.rs | 4 +- clippy_lints/src/ranges.rs | 11 +- clippy_lints/src/returns.rs | 2 +- clippy_lints/src/suspicious_trait_impl.rs | 2 +- clippy_lints/src/unit_return_expecting_ord.rs | 2 +- clippy_lints/src/unit_types/unit_arg.rs | 2 +- clippy_lints/src/unnecessary_wraps.rs | 2 +- clippy_lints/src/unwrap.rs | 2 +- clippy_lints/src/unwrap_in_result.rs | 6 +- clippy_lints/src/utils/author.rs | 2 +- clippy_lints/src/utils/conf.rs | 2 +- clippy_lints/src/utils/internal_lints.rs | 41 +- .../internal_lints/metadata_collector.rs | 4 +- clippy_lints/src/vec_init_then_push.rs | 2 +- clippy_lints/src/write.rs | 6 +- clippy_utils/src/check_proc_macro.rs | 4 +- clippy_utils/src/eager_or_lazy.rs | 2 +- clippy_utils/src/hir_utils.rs | 10 +- clippy_utils/src/lib.rs | 8 +- clippy_utils/src/macros.rs | 6 +- clippy_utils/src/qualify_min_const_fn.rs | 8 +- clippy_utils/src/visitors.rs | 3 +- lintcheck/lintcheck_crates.toml | 2 +- rust-toolchain | 2 +- src/docs.rs | 596 ++++++++++++++++++ src/docs/absurd_extreme_comparisons.txt | 25 + src/docs/alloc_instead_of_core.txt | 18 + src/docs/allow_attributes_without_reason.txt | 22 + src/docs/almost_complete_letter_range.txt | 15 + src/docs/almost_swapped.txt | 15 + src/docs/approx_constant.txt | 24 + src/docs/arithmetic_side_effects.txt | 33 + src/docs/as_conversions.txt | 32 + src/docs/as_underscore.txt | 21 + src/docs/assertions_on_constants.txt | 14 + src/docs/assertions_on_result_states.txt | 14 + src/docs/assign_op_pattern.txt | 28 + src/docs/async_yields_async.txt | 28 + src/docs/await_holding_invalid_type.txt | 29 + src/docs/await_holding_lock.txt | 51 ++ src/docs/await_holding_refcell_ref.txt | 47 ++ src/docs/bad_bit_mask.txt | 30 + src/docs/bind_instead_of_map.txt | 22 + src/docs/blanket_clippy_restriction_lints.txt | 16 + src/docs/blocks_in_if_conditions.txt | 21 + src/docs/bool_assert_comparison.txt | 16 + src/docs/bool_comparison.txt | 18 + src/docs/bool_to_int_with_if.txt | 26 + src/docs/borrow_as_ptr.txt | 26 + src/docs/borrow_deref_ref.txt | 27 + src/docs/borrow_interior_mutable_const.txt | 40 ++ src/docs/borrowed_box.txt | 19 + src/docs/box_collection.txt | 23 + src/docs/boxed_local.txt | 18 + src/docs/branches_sharing_code.txt | 32 + src/docs/builtin_type_shadow.txt | 15 + src/docs/bytes_count_to_len.txt | 18 + src/docs/bytes_nth.txt | 16 + src/docs/cargo_common_metadata.txt | 33 + ...e_sensitive_file_extension_comparisons.txt | 21 + src/docs/cast_abs_to_unsigned.txt | 16 + src/docs/cast_enum_constructor.txt | 11 + src/docs/cast_enum_truncation.txt | 12 + src/docs/cast_lossless.txt | 26 + src/docs/cast_possible_truncation.txt | 16 + src/docs/cast_possible_wrap.txt | 17 + src/docs/cast_precision_loss.txt | 19 + src/docs/cast_ptr_alignment.txt | 21 + src/docs/cast_ref_to_mut.txt | 28 + src/docs/cast_sign_loss.txt | 15 + src/docs/cast_slice_different_sizes.txt | 38 ++ src/docs/cast_slice_from_raw_parts.txt | 20 + src/docs/char_lit_as_u8.txt | 21 + src/docs/chars_last_cmp.txt | 17 + src/docs/chars_next_cmp.txt | 19 + src/docs/checked_conversions.txt | 15 + src/docs/clone_double_ref.txt | 16 + src/docs/clone_on_copy.txt | 11 + src/docs/clone_on_ref_ptr.txt | 21 + src/docs/cloned_instead_of_copied.txt | 16 + src/docs/cmp_nan.txt | 16 + src/docs/cmp_null.txt | 23 + src/docs/cmp_owned.txt | 18 + src/docs/cognitive_complexity.txt | 13 + src/docs/collapsible_else_if.txt | 29 + src/docs/collapsible_if.txt | 23 + src/docs/collapsible_match.txt | 31 + src/docs/collapsible_str_replace.txt | 19 + src/docs/comparison_chain.txt | 36 ++ src/docs/comparison_to_empty.txt | 31 + src/docs/copy_iterator.txt | 20 + src/docs/crate_in_macro_def.txt | 35 + src/docs/create_dir.txt | 15 + src/docs/crosspointer_transmute.txt | 12 + src/docs/dbg_macro.txt | 16 + src/docs/debug_assert_with_mut_call.txt | 18 + src/docs/decimal_literal_representation.txt | 13 + src/docs/declare_interior_mutable_const.txt | 46 ++ src/docs/default_instead_of_iter_empty.txt | 15 + src/docs/default_numeric_fallback.txt | 28 + src/docs/default_trait_access.txt | 16 + src/docs/default_union_representation.txt | 36 ++ src/docs/deprecated_cfg_attr.txt | 24 + src/docs/deprecated_semver.txt | 13 + src/docs/deref_addrof.txt | 22 + src/docs/deref_by_slicing.txt | 17 + src/docs/derivable_impls.txt | 35 + src/docs/derive_hash_xor_eq.txt | 23 + src/docs/derive_ord_xor_partial_ord.txt | 44 ++ src/docs/derive_partial_eq_without_eq.txt | 25 + src/docs/disallowed_methods.txt | 41 ++ src/docs/disallowed_names.txt | 12 + src/docs/disallowed_script_idents.txt | 32 + src/docs/disallowed_types.txt | 33 + src/docs/diverging_sub_expression.txt | 19 + src/docs/doc_link_with_quotes.txt | 16 + src/docs/doc_markdown.txt | 35 + src/docs/double_comparisons.txt | 17 + src/docs/double_must_use.txt | 17 + src/docs/double_neg.txt | 12 + src/docs/double_parens.txt | 24 + src/docs/drop_copy.txt | 15 + src/docs/drop_non_drop.txt | 13 + src/docs/drop_ref.txt | 17 + src/docs/duplicate_mod.txt | 31 + src/docs/duplicate_underscore_argument.txt | 16 + src/docs/duration_subsec.txt | 19 + src/docs/else_if_without_else.txt | 27 + src/docs/empty_drop.txt | 20 + src/docs/empty_enum.txt | 27 + src/docs/empty_line_after_outer_attr.txt | 35 + src/docs/empty_loop.txt | 27 + src/docs/empty_structs_with_brackets.txt | 14 + src/docs/enum_clike_unportable_variant.txt | 16 + src/docs/enum_glob_use.txt | 24 + src/docs/enum_variant_names.txt | 30 + src/docs/eq_op.txt | 22 + src/docs/equatable_if_let.txt | 23 + src/docs/erasing_op.txt | 15 + src/docs/err_expect.txt | 16 + src/docs/excessive_precision.txt | 18 + src/docs/exhaustive_enums.txt | 23 + src/docs/exhaustive_structs.txt | 23 + src/docs/exit.txt | 12 + src/docs/expect_fun_call.txt | 24 + src/docs/expect_used.txt | 26 + src/docs/expl_impl_clone_on_copy.txt | 20 + src/docs/explicit_auto_deref.txt | 16 + src/docs/explicit_counter_loop.txt | 21 + src/docs/explicit_deref_methods.txt | 24 + src/docs/explicit_into_iter_loop.txt | 20 + src/docs/explicit_iter_loop.txt | 25 + src/docs/explicit_write.txt | 18 + src/docs/extend_with_drain.txt | 21 + src/docs/extra_unused_lifetimes.txt | 23 + src/docs/fallible_impl_from.txt | 32 + src/docs/field_reassign_with_default.txt | 23 + src/docs/filetype_is_file.txt | 29 + src/docs/filter_map_identity.txt | 14 + src/docs/filter_map_next.txt | 16 + src/docs/filter_next.txt | 16 + src/docs/flat_map_identity.txt | 14 + src/docs/flat_map_option.txt | 16 + src/docs/float_arithmetic.txt | 11 + src/docs/float_cmp.txt | 28 + src/docs/float_cmp_const.txt | 26 + src/docs/float_equality_without_abs.txt | 26 + src/docs/fn_address_comparisons.txt | 17 + src/docs/fn_params_excessive_bools.txt | 31 + src/docs/fn_to_numeric_cast.txt | 21 + src/docs/fn_to_numeric_cast_any.txt | 35 + .../fn_to_numeric_cast_with_truncation.txt | 26 + src/docs/for_kv_map.txt | 22 + src/docs/for_loops_over_fallibles.txt | 32 + src/docs/forget_copy.txt | 21 + src/docs/forget_non_drop.txt | 13 + src/docs/forget_ref.txt | 15 + src/docs/format_in_format_args.txt | 16 + src/docs/format_push_string.txt | 26 + src/docs/from_iter_instead_of_collect.txt | 24 + src/docs/from_over_into.txt | 26 + src/docs/from_str_radix_10.txt | 25 + src/docs/future_not_send.txt | 29 + src/docs/get_first.txt | 19 + src/docs/get_last_with_len.txt | 26 + src/docs/get_unwrap.txt | 30 + src/docs/identity_op.txt | 11 + src/docs/if_let_mutex.txt | 25 + src/docs/if_not_else.txt | 25 + src/docs/if_same_then_else.txt | 15 + src/docs/if_then_some_else_none.txt | 26 + src/docs/ifs_same_cond.txt | 25 + src/docs/implicit_clone.txt | 19 + src/docs/implicit_hasher.txt | 26 + src/docs/implicit_return.txt | 22 + src/docs/implicit_saturating_sub.txt | 21 + src/docs/imprecise_flops.txt | 23 + src/docs/inconsistent_digit_grouping.txt | 17 + src/docs/inconsistent_struct_constructor.txt | 40 ++ src/docs/index_refutable_slice.txt | 29 + src/docs/indexing_slicing.txt | 33 + src/docs/ineffective_bit_mask.txt | 25 + src/docs/inefficient_to_string.txt | 17 + src/docs/infallible_destructuring_match.txt | 29 + src/docs/infinite_iter.txt | 13 + src/docs/inherent_to_string.txt | 29 + .../inherent_to_string_shadow_display.txt | 37 ++ src/docs/init_numbered_fields.txt | 24 + src/docs/inline_always.txt | 23 + src/docs/inline_asm_x86_att_syntax.txt | 16 + src/docs/inline_asm_x86_intel_syntax.txt | 16 + src/docs/inline_fn_without_body.txt | 14 + src/docs/inspect_for_each.txt | 23 + src/docs/int_plus_one.txt | 15 + src/docs/integer_arithmetic.txt | 18 + src/docs/integer_division.txt | 19 + src/docs/into_iter_on_ref.txt | 18 + src/docs/invalid_null_ptr_usage.txt | 16 + src/docs/invalid_regex.txt | 12 + src/docs/invalid_upcast_comparisons.txt | 18 + src/docs/invalid_utf8_in_unchecked.txt | 12 + src/docs/invisible_characters.txt | 10 + src/docs/is_digit_ascii_radix.txt | 20 + src/docs/items_after_statements.txt | 37 ++ src/docs/iter_cloned_collect.txt | 17 + src/docs/iter_count.txt | 22 + src/docs/iter_next_loop.txt | 17 + src/docs/iter_next_slice.txt | 16 + src/docs/iter_not_returning_iterator.txt | 26 + src/docs/iter_nth.txt | 20 + src/docs/iter_nth_zero.txt | 17 + src/docs/iter_on_empty_collections.txt | 25 + src/docs/iter_on_single_items.txt | 24 + src/docs/iter_overeager_cloned.txt | 22 + src/docs/iter_skip_next.txt | 18 + src/docs/iter_with_drain.txt | 16 + src/docs/iterator_step_by_zero.txt | 13 + src/docs/just_underscores_and_digits.txt | 14 + src/docs/large_const_arrays.txt | 17 + src/docs/large_digit_groups.txt | 12 + src/docs/large_enum_variant.txt | 41 ++ src/docs/large_include_file.txt | 21 + src/docs/large_stack_arrays.txt | 10 + src/docs/large_types_passed_by_value.txt | 24 + src/docs/len_without_is_empty.txt | 19 + src/docs/len_zero.txt | 28 + src/docs/let_and_return.txt | 21 + src/docs/let_underscore_drop.txt | 29 + src/docs/let_underscore_lock.txt | 20 + src/docs/let_underscore_must_use.txt | 17 + src/docs/let_unit_value.txt | 13 + src/docs/linkedlist.txt | 32 + src/docs/lossy_float_literal.txt | 18 + src/docs/macro_use_imports.txt | 12 + src/docs/main_recursion.txt | 13 + src/docs/manual_assert.txt | 18 + src/docs/manual_async_fn.txt | 16 + src/docs/manual_bits.txt | 15 + src/docs/manual_filter_map.txt | 19 + src/docs/manual_find.txt | 24 + src/docs/manual_find_map.txt | 19 + src/docs/manual_flatten.txt | 25 + src/docs/manual_instant_elapsed.txt | 21 + src/docs/manual_map.txt | 17 + src/docs/manual_memcpy.txt | 18 + src/docs/manual_non_exhaustive.txt | 41 ++ src/docs/manual_ok_or.txt | 19 + src/docs/manual_range_contains.txt | 19 + src/docs/manual_rem_euclid.txt | 17 + src/docs/manual_retain.txt | 15 + src/docs/manual_saturating_arithmetic.txt | 18 + src/docs/manual_split_once.txt | 29 + src/docs/manual_str_repeat.txt | 15 + src/docs/manual_string_new.txt | 20 + src/docs/manual_strip.txt | 24 + src/docs/manual_swap.txt | 22 + src/docs/manual_unwrap_or.txt | 20 + src/docs/many_single_char_names.txt | 12 + src/docs/map_clone.txt | 22 + src/docs/map_collect_result_unit.txt | 14 + src/docs/map_entry.txt | 28 + src/docs/map_err_ignore.txt | 93 +++ src/docs/map_flatten.txt | 21 + src/docs/map_identity.txt | 16 + src/docs/map_unwrap_or.txt | 22 + src/docs/match_as_ref.txt | 23 + src/docs/match_bool.txt | 24 + src/docs/match_like_matches_macro.txt | 32 + src/docs/match_on_vec_items.txt | 29 + src/docs/match_overlapping_arm.txt | 16 + src/docs/match_ref_pats.txt | 26 + src/docs/match_result_ok.txt | 27 + src/docs/match_same_arms.txt | 38 ++ src/docs/match_single_binding.txt | 23 + src/docs/match_str_case_mismatch.txt | 22 + src/docs/match_wild_err_arm.txt | 16 + .../match_wildcard_for_single_variants.txt | 27 + src/docs/maybe_infinite_iter.txt | 16 + src/docs/mem_forget.txt | 12 + src/docs/mem_replace_option_with_none.txt | 21 + src/docs/mem_replace_with_default.txt | 18 + src/docs/mem_replace_with_uninit.txt | 24 + src/docs/min_max.txt | 18 + src/docs/mismatched_target_os.txt | 24 + src/docs/mismatching_type_param_order.txt | 33 + src/docs/misrefactored_assign_op.txt | 20 + src/docs/missing_const_for_fn.txt | 40 ++ src/docs/missing_docs_in_private_items.txt | 9 + src/docs/missing_enforced_import_renames.txt | 22 + src/docs/missing_errors_doc.txt | 21 + src/docs/missing_inline_in_public_items.txt | 45 ++ src/docs/missing_panics_doc.txt | 24 + src/docs/missing_safety_doc.txt | 26 + src/docs/missing_spin_loop.txt | 27 + src/docs/mistyped_literal_suffixes.txt | 15 + src/docs/mixed_case_hex_literals.txt | 16 + src/docs/mixed_read_write_in_expression.txt | 32 + src/docs/mod_module_files.txt | 22 + src/docs/module_inception.txt | 24 + src/docs/module_name_repetitions.txt | 20 + src/docs/modulo_arithmetic.txt | 15 + src/docs/modulo_one.txt | 16 + src/docs/multi_assignments.txt | 17 + src/docs/multiple_crate_versions.txt | 19 + src/docs/multiple_inherent_impl.txt | 26 + src/docs/must_use_candidate.txt | 23 + src/docs/must_use_unit.txt | 13 + src/docs/mut_from_ref.txt | 26 + src/docs/mut_mut.txt | 12 + src/docs/mut_mutex_lock.txt | 29 + src/docs/mut_range_bound.txt | 29 + src/docs/mutable_key_type.txt | 61 ++ src/docs/mutex_atomic.txt | 22 + src/docs/mutex_integer.txt | 22 + src/docs/naive_bytecount.txt | 22 + src/docs/needless_arbitrary_self_type.txt | 44 ++ src/docs/needless_bitwise_bool.txt | 22 + src/docs/needless_bool.txt | 26 + src/docs/needless_borrow.txt | 21 + src/docs/needless_borrowed_reference.txt | 30 + src/docs/needless_collect.txt | 14 + src/docs/needless_continue.txt | 61 ++ src/docs/needless_doctest_main.txt | 22 + src/docs/needless_for_each.txt | 24 + src/docs/needless_late_init.txt | 42 ++ src/docs/needless_lifetimes.txt | 29 + src/docs/needless_match.txt | 36 ++ src/docs/needless_option_as_deref.txt | 18 + src/docs/needless_option_take.txt | 17 + .../needless_parens_on_range_literals.txt | 23 + src/docs/needless_pass_by_value.txt | 27 + src/docs/needless_question_mark.txt | 43 ++ src/docs/needless_range_loop.txt | 23 + src/docs/needless_return.txt | 19 + src/docs/needless_splitn.txt | 16 + src/docs/needless_update.txt | 30 + src/docs/neg_cmp_op_on_partial_ord.txt | 26 + src/docs/neg_multiply.txt | 18 + src/docs/negative_feature_names.txt | 22 + src/docs/never_loop.txt | 15 + src/docs/new_ret_no_self.txt | 47 ++ src/docs/new_without_default.txt | 32 + src/docs/no_effect.txt | 12 + src/docs/no_effect_replace.txt | 11 + src/docs/no_effect_underscore_binding.txt | 16 + src/docs/non_ascii_literal.txt | 19 + src/docs/non_octal_unix_permissions.txt | 23 + src/docs/non_send_fields_in_send_ty.txt | 36 ++ src/docs/nonminimal_bool.txt | 23 + src/docs/nonsensical_open_options.txt | 14 + src/docs/nonstandard_macro_braces.txt | 15 + src/docs/not_unsafe_ptr_arg_deref.txt | 30 + src/docs/obfuscated_if_else.txt | 21 + src/docs/octal_escapes.txt | 33 + src/docs/ok_expect.txt | 19 + src/docs/only_used_in_recursion.txt | 58 ++ src/docs/op_ref.txt | 17 + src/docs/option_as_ref_deref.txt | 15 + src/docs/option_env_unwrap.txt | 19 + src/docs/option_filter_map.txt | 15 + src/docs/option_if_let_else.txt | 46 ++ src/docs/option_map_or_none.txt | 19 + src/docs/option_map_unit_fn.txt | 27 + src/docs/option_option.txt | 32 + src/docs/or_fun_call.txt | 27 + src/docs/or_then_unwrap.txt | 22 + src/docs/out_of_bounds_indexing.txt | 22 + src/docs/overflow_check_conditional.txt | 11 + src/docs/overly_complex_bool_expr.txt | 20 + src/docs/panic.txt | 10 + src/docs/panic_in_result_fn.txt | 22 + src/docs/panicking_unwrap.txt | 18 + src/docs/partialeq_ne_impl.txt | 18 + src/docs/partialeq_to_none.txt | 24 + src/docs/path_buf_push_overwrite.txt | 25 + src/docs/pattern_type_mismatch.txt | 64 ++ .../positional_named_format_parameters.txt | 15 + src/docs/possible_missing_comma.txt | 14 + src/docs/precedence.txt | 17 + src/docs/print_in_format_impl.txt | 34 + src/docs/print_literal.txt | 20 + src/docs/print_stderr.txt | 21 + src/docs/print_stdout.txt | 21 + src/docs/print_with_newline.txt | 16 + src/docs/println_empty_string.txt | 16 + src/docs/ptr_arg.txt | 29 + src/docs/ptr_as_ptr.txt | 22 + src/docs/ptr_eq.txt | 22 + src/docs/ptr_offset_with_cast.txt | 30 + src/docs/pub_use.txt | 28 + src/docs/question_mark.txt | 18 + src/docs/range_minus_one.txt | 27 + src/docs/range_plus_one.txt | 36 ++ src/docs/range_zip_with_len.txt | 16 + src/docs/rc_buffer.txt | 27 + src/docs/rc_clone_in_vec_init.txt | 29 + src/docs/rc_mutex.txt | 26 + src/docs/read_zero_byte_vec.txt | 30 + src/docs/recursive_format_impl.txt | 32 + src/docs/redundant_allocation.txt | 17 + src/docs/redundant_clone.txt | 23 + src/docs/redundant_closure.txt | 25 + src/docs/redundant_closure_call.txt | 17 + .../redundant_closure_for_method_calls.txt | 15 + src/docs/redundant_else.txt | 30 + src/docs/redundant_feature_names.txt | 23 + src/docs/redundant_field_names.txt | 22 + src/docs/redundant_pattern.txt | 22 + src/docs/redundant_pattern_matching.txt | 45 ++ src/docs/redundant_pub_crate.txt | 21 + src/docs/redundant_slicing.txt | 24 + src/docs/redundant_static_lifetimes.txt | 19 + src/docs/ref_binding_to_reference.txt | 21 + src/docs/ref_option_ref.txt | 19 + src/docs/repeat_once.txt | 25 + src/docs/rest_pat_in_fully_bound_structs.txt | 24 + src/docs/result_large_err.txt | 36 ++ src/docs/result_map_or_into_option.txt | 16 + src/docs/result_map_unit_fn.txt | 26 + src/docs/result_unit_err.txt | 40 ++ src/docs/return_self_not_must_use.txt | 46 ++ src/docs/reversed_empty_ranges.txt | 26 + src/docs/same_functions_in_if_condition.txt | 41 ++ src/docs/same_item_push.txt | 29 + src/docs/same_name_method.txt | 23 + src/docs/search_is_some.txt | 24 + src/docs/self_assignment.txt | 32 + src/docs/self_named_constructors.txt | 26 + src/docs/self_named_module_files.txt | 22 + src/docs/semicolon_if_nothing_returned.txt | 20 + src/docs/separated_literal_suffix.txt | 17 + src/docs/serde_api_misuse.txt | 10 + src/docs/shadow_reuse.txt | 20 + src/docs/shadow_same.txt | 18 + src/docs/shadow_unrelated.txt | 22 + src/docs/short_circuit_statement.txt | 14 + src/docs/should_implement_trait.txt | 22 + src/docs/significant_drop_in_scrutinee.txt | 43 ++ src/docs/similar_names.txt | 12 + src/docs/single_char_add_str.txt | 18 + src/docs/single_char_lifetime_names.txt | 28 + src/docs/single_char_pattern.txt | 20 + src/docs/single_component_path_imports.txt | 21 + src/docs/single_element_loop.txt | 21 + src/docs/single_match.txt | 21 + src/docs/single_match_else.txt | 29 + src/docs/size_of_in_element_count.txt | 16 + src/docs/skip_while_next.txt | 16 + src/docs/slow_vector_initialization.txt | 24 + src/docs/stable_sort_primitive.txt | 31 + src/docs/std_instead_of_alloc.txt | 18 + src/docs/std_instead_of_core.txt | 18 + src/docs/str_to_string.txt | 18 + src/docs/string_add.txt | 27 + src/docs/string_add_assign.txt | 17 + src/docs/string_extend_chars.txt | 23 + src/docs/string_from_utf8_as_bytes.txt | 15 + src/docs/string_lit_as_bytes.txt | 39 ++ src/docs/string_slice.txt | 17 + src/docs/string_to_string.txt | 19 + src/docs/strlen_on_c_strings.txt | 20 + src/docs/struct_excessive_bools.txt | 29 + src/docs/suboptimal_flops.txt | 50 ++ src/docs/suspicious_arithmetic_impl.txt | 17 + src/docs/suspicious_assignment_formatting.txt | 12 + src/docs/suspicious_else_formatting.txt | 30 + src/docs/suspicious_map.txt | 13 + src/docs/suspicious_op_assign_impl.txt | 15 + src/docs/suspicious_operation_groupings.txt | 41 ++ src/docs/suspicious_splitn.txt | 22 + src/docs/suspicious_to_owned.txt | 39 ++ src/docs/suspicious_unary_op_formatting.txt | 18 + src/docs/swap_ptr_to_ref.txt | 23 + src/docs/tabs_in_doc_comments.txt | 44 ++ src/docs/temporary_assignment.txt | 12 + src/docs/to_digit_is_some.txt | 15 + src/docs/to_string_in_format_args.txt | 17 + src/docs/todo.txt | 10 + src/docs/too_many_arguments.txt | 14 + src/docs/too_many_lines.txt | 17 + src/docs/toplevel_ref_arg.txt | 28 + src/docs/trailing_empty_array.txt | 22 + src/docs/trait_duplication_in_bounds.txt | 37 ++ src/docs/transmute_bytes_to_str.txt | 27 + src/docs/transmute_float_to_int.txt | 16 + src/docs/transmute_int_to_bool.txt | 16 + src/docs/transmute_int_to_char.txt | 27 + src/docs/transmute_int_to_float.txt | 16 + src/docs/transmute_num_to_bytes.txt | 16 + src/docs/transmute_ptr_to_ptr.txt | 21 + src/docs/transmute_ptr_to_ref.txt | 21 + src/docs/transmute_undefined_repr.txt | 22 + .../transmutes_expressible_as_ptr_casts.txt | 16 + src/docs/transmuting_null.txt | 15 + src/docs/trim_split_whitespace.txt | 14 + src/docs/trivial_regex.txt | 18 + src/docs/trivially_copy_pass_by_ref.txt | 43 ++ src/docs/try_err.txt | 28 + src/docs/type_complexity.txt | 14 + src/docs/type_repetition_in_bounds.txt | 16 + src/docs/undocumented_unsafe_blocks.txt | 43 ++ src/docs/undropped_manually_drops.txt | 22 + src/docs/unicode_not_nfc.txt | 12 + src/docs/unimplemented.txt | 10 + src/docs/uninit_assumed_init.txt | 28 + src/docs/uninit_vec.txt | 41 ++ src/docs/unit_arg.txt | 14 + src/docs/unit_cmp.txt | 33 + src/docs/unit_hash.txt | 20 + src/docs/unit_return_expecting_ord.txt | 20 + src/docs/unnecessary_cast.txt | 19 + src/docs/unnecessary_filter_map.txt | 23 + src/docs/unnecessary_find_map.txt | 23 + src/docs/unnecessary_fold.txt | 17 + src/docs/unnecessary_join.txt | 25 + src/docs/unnecessary_lazy_evaluations.txt | 32 + src/docs/unnecessary_mut_passed.txt | 17 + src/docs/unnecessary_operation.txt | 12 + src/docs/unnecessary_owned_empty_strings.txt | 16 + src/docs/unnecessary_self_imports.txt | 19 + src/docs/unnecessary_sort_by.txt | 21 + src/docs/unnecessary_to_owned.txt | 24 + src/docs/unnecessary_unwrap.txt | 20 + src/docs/unnecessary_wraps.txt | 36 ++ src/docs/unneeded_field_pattern.txt | 26 + src/docs/unneeded_wildcard_pattern.txt | 28 + src/docs/unnested_or_patterns.txt | 22 + src/docs/unreachable.txt | 10 + src/docs/unreadable_literal.txt | 16 + src/docs/unsafe_derive_deserialize.txt | 27 + src/docs/unsafe_removed_from_name.txt | 15 + src/docs/unseparated_literal_suffix.txt | 18 + src/docs/unsound_collection_transmute.txt | 25 + src/docs/unused_async.txt | 23 + src/docs/unused_io_amount.txt | 31 + src/docs/unused_peekable.txt | 26 + src/docs/unused_rounding.txt | 17 + src/docs/unused_self.txt | 23 + src/docs/unused_unit.txt | 18 + src/docs/unusual_byte_groupings.txt | 12 + src/docs/unwrap_in_result.txt | 39 ++ src/docs/unwrap_or_else_default.txt | 18 + src/docs/unwrap_used.txt | 37 ++ src/docs/upper_case_acronyms.txt | 25 + src/docs/use_debug.txt | 12 + src/docs/use_self.txt | 31 + src/docs/used_underscore_binding.txt | 19 + src/docs/useless_asref.txt | 17 + src/docs/useless_attribute.txt | 36 ++ src/docs/useless_conversion.txt | 17 + src/docs/useless_format.txt | 22 + src/docs/useless_let_if_seq.txt | 39 ++ src/docs/useless_transmute.txt | 12 + src/docs/useless_vec.txt | 18 + src/docs/vec_box.txt | 26 + src/docs/vec_init_then_push.txt | 23 + src/docs/vec_resize_to_zero.txt | 15 + src/docs/verbose_bit_mask.txt | 15 + src/docs/verbose_file_reads.txt | 17 + src/docs/vtable_address_comparisons.txt | 17 + src/docs/while_immutable_condition.txt | 20 + src/docs/while_let_loop.txt | 25 + src/docs/while_let_on_iterator.txt | 20 + src/docs/wildcard_dependencies.txt | 13 + src/docs/wildcard_enum_match_arm.txt | 25 + src/docs/wildcard_imports.txt | 45 ++ src/docs/wildcard_in_or_patterns.txt | 22 + src/docs/write_literal.txt | 21 + src/docs/write_with_newline.txt | 18 + src/docs/writeln_empty_string.txt | 16 + src/docs/wrong_self_convention.txt | 39 ++ src/docs/wrong_transmute.txt | 15 + src/docs/zero_divided_by_zero.txt | 15 + src/docs/zero_prefixed_literal.txt | 32 + src/docs/zero_ptr.txt | 16 + src/docs/zero_sized_map_values.txt | 24 + src/docs/zst_offset.txt | 11 + src/main.rs | 13 + tests/ui-toml/arithmetic_allowed/clippy.toml | 1 - .../arithmetic_side_effects_allowed.rs} | 2 +- .../clippy.toml | 1 + .../toml_unknown_key/conf_unknown_key.stderr | 2 +- tests/ui/arithmetic.fixed | 27 - tests/ui/arithmetic.rs | 27 - tests/ui/arithmetic_side_effects.rs | 57 ++ tests/ui/arithmetic_side_effects.stderr | 22 + tests/ui/author/struct.rs | 7 +- tests/ui/bool_to_int_with_if.fixed | 85 +++ tests/ui/bool_to_int_with_if.rs | 109 ++++ tests/ui/bool_to_int_with_if.stderr | 84 +++ tests/ui/crashes/ice-9405.rs | 11 + tests/ui/crashes/ice-9405.stderr | 11 + tests/ui/crashes/ice-9414.rs | 8 + tests/ui/floating_point_powf.fixed | 5 + tests/ui/floating_point_powf.rs | 5 + tests/ui/floating_point_powf.stderr | 50 +- tests/ui/large_enum_variant.rs | 24 + tests/ui/large_enum_variant.stderr | 258 +++++--- .../ui/match_wild_err_arm.edition2018.stderr | 8 +- .../ui/match_wild_err_arm.edition2021.stderr | 8 +- tests/ui/mut_mutex_lock.fixed | 7 + tests/ui/mut_mutex_lock.rs | 7 + tests/ui/or_fun_call.fixed | 8 +- tests/ui/or_fun_call.stderr | 26 +- tests/ui/range_plus_minus_one.fixed | 19 + tests/ui/range_plus_minus_one.rs | 19 + tests/ui/range_plus_minus_one.stderr | 18 +- tests/ui/result_large_err.rs | 1 + tests/ui/result_large_err.stderr | 22 +- tests/ui/unnecessary_to_owned.fixed | 60 ++ tests/ui/unnecessary_to_owned.rs | 60 ++ tests/ui/unnecessary_to_owned.stderr | 8 +- tests/ui/unwrap_or_else_default.fixed | 3 + tests/ui/unwrap_or_else_default.rs | 3 + tests/ui/unwrap_or_else_default.stderr | 8 +- tests/ui/vec_init_then_push.rs | 6 + tests/ui/vec_init_then_push.stderr | 9 +- 689 files changed, 15493 insertions(+), 688 deletions(-) create mode 100644 clippy_lints/src/bool_to_int_with_if.rs delete mode 100644 clippy_lints/src/operators/arithmetic.rs create mode 100644 clippy_lints/src/operators/arithmetic_side_effects.rs create mode 100644 src/docs.rs create mode 100644 src/docs/absurd_extreme_comparisons.txt create mode 100644 src/docs/alloc_instead_of_core.txt create mode 100644 src/docs/allow_attributes_without_reason.txt create mode 100644 src/docs/almost_complete_letter_range.txt create mode 100644 src/docs/almost_swapped.txt create mode 100644 src/docs/approx_constant.txt create mode 100644 src/docs/arithmetic_side_effects.txt create mode 100644 src/docs/as_conversions.txt create mode 100644 src/docs/as_underscore.txt create mode 100644 src/docs/assertions_on_constants.txt create mode 100644 src/docs/assertions_on_result_states.txt create mode 100644 src/docs/assign_op_pattern.txt create mode 100644 src/docs/async_yields_async.txt create mode 100644 src/docs/await_holding_invalid_type.txt create mode 100644 src/docs/await_holding_lock.txt create mode 100644 src/docs/await_holding_refcell_ref.txt create mode 100644 src/docs/bad_bit_mask.txt create mode 100644 src/docs/bind_instead_of_map.txt create mode 100644 src/docs/blanket_clippy_restriction_lints.txt create mode 100644 src/docs/blocks_in_if_conditions.txt create mode 100644 src/docs/bool_assert_comparison.txt create mode 100644 src/docs/bool_comparison.txt create mode 100644 src/docs/bool_to_int_with_if.txt create mode 100644 src/docs/borrow_as_ptr.txt create mode 100644 src/docs/borrow_deref_ref.txt create mode 100644 src/docs/borrow_interior_mutable_const.txt create mode 100644 src/docs/borrowed_box.txt create mode 100644 src/docs/box_collection.txt create mode 100644 src/docs/boxed_local.txt create mode 100644 src/docs/branches_sharing_code.txt create mode 100644 src/docs/builtin_type_shadow.txt create mode 100644 src/docs/bytes_count_to_len.txt create mode 100644 src/docs/bytes_nth.txt create mode 100644 src/docs/cargo_common_metadata.txt create mode 100644 src/docs/case_sensitive_file_extension_comparisons.txt create mode 100644 src/docs/cast_abs_to_unsigned.txt create mode 100644 src/docs/cast_enum_constructor.txt create mode 100644 src/docs/cast_enum_truncation.txt create mode 100644 src/docs/cast_lossless.txt create mode 100644 src/docs/cast_possible_truncation.txt create mode 100644 src/docs/cast_possible_wrap.txt create mode 100644 src/docs/cast_precision_loss.txt create mode 100644 src/docs/cast_ptr_alignment.txt create mode 100644 src/docs/cast_ref_to_mut.txt create mode 100644 src/docs/cast_sign_loss.txt create mode 100644 src/docs/cast_slice_different_sizes.txt create mode 100644 src/docs/cast_slice_from_raw_parts.txt create mode 100644 src/docs/char_lit_as_u8.txt create mode 100644 src/docs/chars_last_cmp.txt create mode 100644 src/docs/chars_next_cmp.txt create mode 100644 src/docs/checked_conversions.txt create mode 100644 src/docs/clone_double_ref.txt create mode 100644 src/docs/clone_on_copy.txt create mode 100644 src/docs/clone_on_ref_ptr.txt create mode 100644 src/docs/cloned_instead_of_copied.txt create mode 100644 src/docs/cmp_nan.txt create mode 100644 src/docs/cmp_null.txt create mode 100644 src/docs/cmp_owned.txt create mode 100644 src/docs/cognitive_complexity.txt create mode 100644 src/docs/collapsible_else_if.txt create mode 100644 src/docs/collapsible_if.txt create mode 100644 src/docs/collapsible_match.txt create mode 100644 src/docs/collapsible_str_replace.txt create mode 100644 src/docs/comparison_chain.txt create mode 100644 src/docs/comparison_to_empty.txt create mode 100644 src/docs/copy_iterator.txt create mode 100644 src/docs/crate_in_macro_def.txt create mode 100644 src/docs/create_dir.txt create mode 100644 src/docs/crosspointer_transmute.txt create mode 100644 src/docs/dbg_macro.txt create mode 100644 src/docs/debug_assert_with_mut_call.txt create mode 100644 src/docs/decimal_literal_representation.txt create mode 100644 src/docs/declare_interior_mutable_const.txt create mode 100644 src/docs/default_instead_of_iter_empty.txt create mode 100644 src/docs/default_numeric_fallback.txt create mode 100644 src/docs/default_trait_access.txt create mode 100644 src/docs/default_union_representation.txt create mode 100644 src/docs/deprecated_cfg_attr.txt create mode 100644 src/docs/deprecated_semver.txt create mode 100644 src/docs/deref_addrof.txt create mode 100644 src/docs/deref_by_slicing.txt create mode 100644 src/docs/derivable_impls.txt create mode 100644 src/docs/derive_hash_xor_eq.txt create mode 100644 src/docs/derive_ord_xor_partial_ord.txt create mode 100644 src/docs/derive_partial_eq_without_eq.txt create mode 100644 src/docs/disallowed_methods.txt create mode 100644 src/docs/disallowed_names.txt create mode 100644 src/docs/disallowed_script_idents.txt create mode 100644 src/docs/disallowed_types.txt create mode 100644 src/docs/diverging_sub_expression.txt create mode 100644 src/docs/doc_link_with_quotes.txt create mode 100644 src/docs/doc_markdown.txt create mode 100644 src/docs/double_comparisons.txt create mode 100644 src/docs/double_must_use.txt create mode 100644 src/docs/double_neg.txt create mode 100644 src/docs/double_parens.txt create mode 100644 src/docs/drop_copy.txt create mode 100644 src/docs/drop_non_drop.txt create mode 100644 src/docs/drop_ref.txt create mode 100644 src/docs/duplicate_mod.txt create mode 100644 src/docs/duplicate_underscore_argument.txt create mode 100644 src/docs/duration_subsec.txt create mode 100644 src/docs/else_if_without_else.txt create mode 100644 src/docs/empty_drop.txt create mode 100644 src/docs/empty_enum.txt create mode 100644 src/docs/empty_line_after_outer_attr.txt create mode 100644 src/docs/empty_loop.txt create mode 100644 src/docs/empty_structs_with_brackets.txt create mode 100644 src/docs/enum_clike_unportable_variant.txt create mode 100644 src/docs/enum_glob_use.txt create mode 100644 src/docs/enum_variant_names.txt create mode 100644 src/docs/eq_op.txt create mode 100644 src/docs/equatable_if_let.txt create mode 100644 src/docs/erasing_op.txt create mode 100644 src/docs/err_expect.txt create mode 100644 src/docs/excessive_precision.txt create mode 100644 src/docs/exhaustive_enums.txt create mode 100644 src/docs/exhaustive_structs.txt create mode 100644 src/docs/exit.txt create mode 100644 src/docs/expect_fun_call.txt create mode 100644 src/docs/expect_used.txt create mode 100644 src/docs/expl_impl_clone_on_copy.txt create mode 100644 src/docs/explicit_auto_deref.txt create mode 100644 src/docs/explicit_counter_loop.txt create mode 100644 src/docs/explicit_deref_methods.txt create mode 100644 src/docs/explicit_into_iter_loop.txt create mode 100644 src/docs/explicit_iter_loop.txt create mode 100644 src/docs/explicit_write.txt create mode 100644 src/docs/extend_with_drain.txt create mode 100644 src/docs/extra_unused_lifetimes.txt create mode 100644 src/docs/fallible_impl_from.txt create mode 100644 src/docs/field_reassign_with_default.txt create mode 100644 src/docs/filetype_is_file.txt create mode 100644 src/docs/filter_map_identity.txt create mode 100644 src/docs/filter_map_next.txt create mode 100644 src/docs/filter_next.txt create mode 100644 src/docs/flat_map_identity.txt create mode 100644 src/docs/flat_map_option.txt create mode 100644 src/docs/float_arithmetic.txt create mode 100644 src/docs/float_cmp.txt create mode 100644 src/docs/float_cmp_const.txt create mode 100644 src/docs/float_equality_without_abs.txt create mode 100644 src/docs/fn_address_comparisons.txt create mode 100644 src/docs/fn_params_excessive_bools.txt create mode 100644 src/docs/fn_to_numeric_cast.txt create mode 100644 src/docs/fn_to_numeric_cast_any.txt create mode 100644 src/docs/fn_to_numeric_cast_with_truncation.txt create mode 100644 src/docs/for_kv_map.txt create mode 100644 src/docs/for_loops_over_fallibles.txt create mode 100644 src/docs/forget_copy.txt create mode 100644 src/docs/forget_non_drop.txt create mode 100644 src/docs/forget_ref.txt create mode 100644 src/docs/format_in_format_args.txt create mode 100644 src/docs/format_push_string.txt create mode 100644 src/docs/from_iter_instead_of_collect.txt create mode 100644 src/docs/from_over_into.txt create mode 100644 src/docs/from_str_radix_10.txt create mode 100644 src/docs/future_not_send.txt create mode 100644 src/docs/get_first.txt create mode 100644 src/docs/get_last_with_len.txt create mode 100644 src/docs/get_unwrap.txt create mode 100644 src/docs/identity_op.txt create mode 100644 src/docs/if_let_mutex.txt create mode 100644 src/docs/if_not_else.txt create mode 100644 src/docs/if_same_then_else.txt create mode 100644 src/docs/if_then_some_else_none.txt create mode 100644 src/docs/ifs_same_cond.txt create mode 100644 src/docs/implicit_clone.txt create mode 100644 src/docs/implicit_hasher.txt create mode 100644 src/docs/implicit_return.txt create mode 100644 src/docs/implicit_saturating_sub.txt create mode 100644 src/docs/imprecise_flops.txt create mode 100644 src/docs/inconsistent_digit_grouping.txt create mode 100644 src/docs/inconsistent_struct_constructor.txt create mode 100644 src/docs/index_refutable_slice.txt create mode 100644 src/docs/indexing_slicing.txt create mode 100644 src/docs/ineffective_bit_mask.txt create mode 100644 src/docs/inefficient_to_string.txt create mode 100644 src/docs/infallible_destructuring_match.txt create mode 100644 src/docs/infinite_iter.txt create mode 100644 src/docs/inherent_to_string.txt create mode 100644 src/docs/inherent_to_string_shadow_display.txt create mode 100644 src/docs/init_numbered_fields.txt create mode 100644 src/docs/inline_always.txt create mode 100644 src/docs/inline_asm_x86_att_syntax.txt create mode 100644 src/docs/inline_asm_x86_intel_syntax.txt create mode 100644 src/docs/inline_fn_without_body.txt create mode 100644 src/docs/inspect_for_each.txt create mode 100644 src/docs/int_plus_one.txt create mode 100644 src/docs/integer_arithmetic.txt create mode 100644 src/docs/integer_division.txt create mode 100644 src/docs/into_iter_on_ref.txt create mode 100644 src/docs/invalid_null_ptr_usage.txt create mode 100644 src/docs/invalid_regex.txt create mode 100644 src/docs/invalid_upcast_comparisons.txt create mode 100644 src/docs/invalid_utf8_in_unchecked.txt create mode 100644 src/docs/invisible_characters.txt create mode 100644 src/docs/is_digit_ascii_radix.txt create mode 100644 src/docs/items_after_statements.txt create mode 100644 src/docs/iter_cloned_collect.txt create mode 100644 src/docs/iter_count.txt create mode 100644 src/docs/iter_next_loop.txt create mode 100644 src/docs/iter_next_slice.txt create mode 100644 src/docs/iter_not_returning_iterator.txt create mode 100644 src/docs/iter_nth.txt create mode 100644 src/docs/iter_nth_zero.txt create mode 100644 src/docs/iter_on_empty_collections.txt create mode 100644 src/docs/iter_on_single_items.txt create mode 100644 src/docs/iter_overeager_cloned.txt create mode 100644 src/docs/iter_skip_next.txt create mode 100644 src/docs/iter_with_drain.txt create mode 100644 src/docs/iterator_step_by_zero.txt create mode 100644 src/docs/just_underscores_and_digits.txt create mode 100644 src/docs/large_const_arrays.txt create mode 100644 src/docs/large_digit_groups.txt create mode 100644 src/docs/large_enum_variant.txt create mode 100644 src/docs/large_include_file.txt create mode 100644 src/docs/large_stack_arrays.txt create mode 100644 src/docs/large_types_passed_by_value.txt create mode 100644 src/docs/len_without_is_empty.txt create mode 100644 src/docs/len_zero.txt create mode 100644 src/docs/let_and_return.txt create mode 100644 src/docs/let_underscore_drop.txt create mode 100644 src/docs/let_underscore_lock.txt create mode 100644 src/docs/let_underscore_must_use.txt create mode 100644 src/docs/let_unit_value.txt create mode 100644 src/docs/linkedlist.txt create mode 100644 src/docs/lossy_float_literal.txt create mode 100644 src/docs/macro_use_imports.txt create mode 100644 src/docs/main_recursion.txt create mode 100644 src/docs/manual_assert.txt create mode 100644 src/docs/manual_async_fn.txt create mode 100644 src/docs/manual_bits.txt create mode 100644 src/docs/manual_filter_map.txt create mode 100644 src/docs/manual_find.txt create mode 100644 src/docs/manual_find_map.txt create mode 100644 src/docs/manual_flatten.txt create mode 100644 src/docs/manual_instant_elapsed.txt create mode 100644 src/docs/manual_map.txt create mode 100644 src/docs/manual_memcpy.txt create mode 100644 src/docs/manual_non_exhaustive.txt create mode 100644 src/docs/manual_ok_or.txt create mode 100644 src/docs/manual_range_contains.txt create mode 100644 src/docs/manual_rem_euclid.txt create mode 100644 src/docs/manual_retain.txt create mode 100644 src/docs/manual_saturating_arithmetic.txt create mode 100644 src/docs/manual_split_once.txt create mode 100644 src/docs/manual_str_repeat.txt create mode 100644 src/docs/manual_string_new.txt create mode 100644 src/docs/manual_strip.txt create mode 100644 src/docs/manual_swap.txt create mode 100644 src/docs/manual_unwrap_or.txt create mode 100644 src/docs/many_single_char_names.txt create mode 100644 src/docs/map_clone.txt create mode 100644 src/docs/map_collect_result_unit.txt create mode 100644 src/docs/map_entry.txt create mode 100644 src/docs/map_err_ignore.txt create mode 100644 src/docs/map_flatten.txt create mode 100644 src/docs/map_identity.txt create mode 100644 src/docs/map_unwrap_or.txt create mode 100644 src/docs/match_as_ref.txt create mode 100644 src/docs/match_bool.txt create mode 100644 src/docs/match_like_matches_macro.txt create mode 100644 src/docs/match_on_vec_items.txt create mode 100644 src/docs/match_overlapping_arm.txt create mode 100644 src/docs/match_ref_pats.txt create mode 100644 src/docs/match_result_ok.txt create mode 100644 src/docs/match_same_arms.txt create mode 100644 src/docs/match_single_binding.txt create mode 100644 src/docs/match_str_case_mismatch.txt create mode 100644 src/docs/match_wild_err_arm.txt create mode 100644 src/docs/match_wildcard_for_single_variants.txt create mode 100644 src/docs/maybe_infinite_iter.txt create mode 100644 src/docs/mem_forget.txt create mode 100644 src/docs/mem_replace_option_with_none.txt create mode 100644 src/docs/mem_replace_with_default.txt create mode 100644 src/docs/mem_replace_with_uninit.txt create mode 100644 src/docs/min_max.txt create mode 100644 src/docs/mismatched_target_os.txt create mode 100644 src/docs/mismatching_type_param_order.txt create mode 100644 src/docs/misrefactored_assign_op.txt create mode 100644 src/docs/missing_const_for_fn.txt create mode 100644 src/docs/missing_docs_in_private_items.txt create mode 100644 src/docs/missing_enforced_import_renames.txt create mode 100644 src/docs/missing_errors_doc.txt create mode 100644 src/docs/missing_inline_in_public_items.txt create mode 100644 src/docs/missing_panics_doc.txt create mode 100644 src/docs/missing_safety_doc.txt create mode 100644 src/docs/missing_spin_loop.txt create mode 100644 src/docs/mistyped_literal_suffixes.txt create mode 100644 src/docs/mixed_case_hex_literals.txt create mode 100644 src/docs/mixed_read_write_in_expression.txt create mode 100644 src/docs/mod_module_files.txt create mode 100644 src/docs/module_inception.txt create mode 100644 src/docs/module_name_repetitions.txt create mode 100644 src/docs/modulo_arithmetic.txt create mode 100644 src/docs/modulo_one.txt create mode 100644 src/docs/multi_assignments.txt create mode 100644 src/docs/multiple_crate_versions.txt create mode 100644 src/docs/multiple_inherent_impl.txt create mode 100644 src/docs/must_use_candidate.txt create mode 100644 src/docs/must_use_unit.txt create mode 100644 src/docs/mut_from_ref.txt create mode 100644 src/docs/mut_mut.txt create mode 100644 src/docs/mut_mutex_lock.txt create mode 100644 src/docs/mut_range_bound.txt create mode 100644 src/docs/mutable_key_type.txt create mode 100644 src/docs/mutex_atomic.txt create mode 100644 src/docs/mutex_integer.txt create mode 100644 src/docs/naive_bytecount.txt create mode 100644 src/docs/needless_arbitrary_self_type.txt create mode 100644 src/docs/needless_bitwise_bool.txt create mode 100644 src/docs/needless_bool.txt create mode 100644 src/docs/needless_borrow.txt create mode 100644 src/docs/needless_borrowed_reference.txt create mode 100644 src/docs/needless_collect.txt create mode 100644 src/docs/needless_continue.txt create mode 100644 src/docs/needless_doctest_main.txt create mode 100644 src/docs/needless_for_each.txt create mode 100644 src/docs/needless_late_init.txt create mode 100644 src/docs/needless_lifetimes.txt create mode 100644 src/docs/needless_match.txt create mode 100644 src/docs/needless_option_as_deref.txt create mode 100644 src/docs/needless_option_take.txt create mode 100644 src/docs/needless_parens_on_range_literals.txt create mode 100644 src/docs/needless_pass_by_value.txt create mode 100644 src/docs/needless_question_mark.txt create mode 100644 src/docs/needless_range_loop.txt create mode 100644 src/docs/needless_return.txt create mode 100644 src/docs/needless_splitn.txt create mode 100644 src/docs/needless_update.txt create mode 100644 src/docs/neg_cmp_op_on_partial_ord.txt create mode 100644 src/docs/neg_multiply.txt create mode 100644 src/docs/negative_feature_names.txt create mode 100644 src/docs/never_loop.txt create mode 100644 src/docs/new_ret_no_self.txt create mode 100644 src/docs/new_without_default.txt create mode 100644 src/docs/no_effect.txt create mode 100644 src/docs/no_effect_replace.txt create mode 100644 src/docs/no_effect_underscore_binding.txt create mode 100644 src/docs/non_ascii_literal.txt create mode 100644 src/docs/non_octal_unix_permissions.txt create mode 100644 src/docs/non_send_fields_in_send_ty.txt create mode 100644 src/docs/nonminimal_bool.txt create mode 100644 src/docs/nonsensical_open_options.txt create mode 100644 src/docs/nonstandard_macro_braces.txt create mode 100644 src/docs/not_unsafe_ptr_arg_deref.txt create mode 100644 src/docs/obfuscated_if_else.txt create mode 100644 src/docs/octal_escapes.txt create mode 100644 src/docs/ok_expect.txt create mode 100644 src/docs/only_used_in_recursion.txt create mode 100644 src/docs/op_ref.txt create mode 100644 src/docs/option_as_ref_deref.txt create mode 100644 src/docs/option_env_unwrap.txt create mode 100644 src/docs/option_filter_map.txt create mode 100644 src/docs/option_if_let_else.txt create mode 100644 src/docs/option_map_or_none.txt create mode 100644 src/docs/option_map_unit_fn.txt create mode 100644 src/docs/option_option.txt create mode 100644 src/docs/or_fun_call.txt create mode 100644 src/docs/or_then_unwrap.txt create mode 100644 src/docs/out_of_bounds_indexing.txt create mode 100644 src/docs/overflow_check_conditional.txt create mode 100644 src/docs/overly_complex_bool_expr.txt create mode 100644 src/docs/panic.txt create mode 100644 src/docs/panic_in_result_fn.txt create mode 100644 src/docs/panicking_unwrap.txt create mode 100644 src/docs/partialeq_ne_impl.txt create mode 100644 src/docs/partialeq_to_none.txt create mode 100644 src/docs/path_buf_push_overwrite.txt create mode 100644 src/docs/pattern_type_mismatch.txt create mode 100644 src/docs/positional_named_format_parameters.txt create mode 100644 src/docs/possible_missing_comma.txt create mode 100644 src/docs/precedence.txt create mode 100644 src/docs/print_in_format_impl.txt create mode 100644 src/docs/print_literal.txt create mode 100644 src/docs/print_stderr.txt create mode 100644 src/docs/print_stdout.txt create mode 100644 src/docs/print_with_newline.txt create mode 100644 src/docs/println_empty_string.txt create mode 100644 src/docs/ptr_arg.txt create mode 100644 src/docs/ptr_as_ptr.txt create mode 100644 src/docs/ptr_eq.txt create mode 100644 src/docs/ptr_offset_with_cast.txt create mode 100644 src/docs/pub_use.txt create mode 100644 src/docs/question_mark.txt create mode 100644 src/docs/range_minus_one.txt create mode 100644 src/docs/range_plus_one.txt create mode 100644 src/docs/range_zip_with_len.txt create mode 100644 src/docs/rc_buffer.txt create mode 100644 src/docs/rc_clone_in_vec_init.txt create mode 100644 src/docs/rc_mutex.txt create mode 100644 src/docs/read_zero_byte_vec.txt create mode 100644 src/docs/recursive_format_impl.txt create mode 100644 src/docs/redundant_allocation.txt create mode 100644 src/docs/redundant_clone.txt create mode 100644 src/docs/redundant_closure.txt create mode 100644 src/docs/redundant_closure_call.txt create mode 100644 src/docs/redundant_closure_for_method_calls.txt create mode 100644 src/docs/redundant_else.txt create mode 100644 src/docs/redundant_feature_names.txt create mode 100644 src/docs/redundant_field_names.txt create mode 100644 src/docs/redundant_pattern.txt create mode 100644 src/docs/redundant_pattern_matching.txt create mode 100644 src/docs/redundant_pub_crate.txt create mode 100644 src/docs/redundant_slicing.txt create mode 100644 src/docs/redundant_static_lifetimes.txt create mode 100644 src/docs/ref_binding_to_reference.txt create mode 100644 src/docs/ref_option_ref.txt create mode 100644 src/docs/repeat_once.txt create mode 100644 src/docs/rest_pat_in_fully_bound_structs.txt create mode 100644 src/docs/result_large_err.txt create mode 100644 src/docs/result_map_or_into_option.txt create mode 100644 src/docs/result_map_unit_fn.txt create mode 100644 src/docs/result_unit_err.txt create mode 100644 src/docs/return_self_not_must_use.txt create mode 100644 src/docs/reversed_empty_ranges.txt create mode 100644 src/docs/same_functions_in_if_condition.txt create mode 100644 src/docs/same_item_push.txt create mode 100644 src/docs/same_name_method.txt create mode 100644 src/docs/search_is_some.txt create mode 100644 src/docs/self_assignment.txt create mode 100644 src/docs/self_named_constructors.txt create mode 100644 src/docs/self_named_module_files.txt create mode 100644 src/docs/semicolon_if_nothing_returned.txt create mode 100644 src/docs/separated_literal_suffix.txt create mode 100644 src/docs/serde_api_misuse.txt create mode 100644 src/docs/shadow_reuse.txt create mode 100644 src/docs/shadow_same.txt create mode 100644 src/docs/shadow_unrelated.txt create mode 100644 src/docs/short_circuit_statement.txt create mode 100644 src/docs/should_implement_trait.txt create mode 100644 src/docs/significant_drop_in_scrutinee.txt create mode 100644 src/docs/similar_names.txt create mode 100644 src/docs/single_char_add_str.txt create mode 100644 src/docs/single_char_lifetime_names.txt create mode 100644 src/docs/single_char_pattern.txt create mode 100644 src/docs/single_component_path_imports.txt create mode 100644 src/docs/single_element_loop.txt create mode 100644 src/docs/single_match.txt create mode 100644 src/docs/single_match_else.txt create mode 100644 src/docs/size_of_in_element_count.txt create mode 100644 src/docs/skip_while_next.txt create mode 100644 src/docs/slow_vector_initialization.txt create mode 100644 src/docs/stable_sort_primitive.txt create mode 100644 src/docs/std_instead_of_alloc.txt create mode 100644 src/docs/std_instead_of_core.txt create mode 100644 src/docs/str_to_string.txt create mode 100644 src/docs/string_add.txt create mode 100644 src/docs/string_add_assign.txt create mode 100644 src/docs/string_extend_chars.txt create mode 100644 src/docs/string_from_utf8_as_bytes.txt create mode 100644 src/docs/string_lit_as_bytes.txt create mode 100644 src/docs/string_slice.txt create mode 100644 src/docs/string_to_string.txt create mode 100644 src/docs/strlen_on_c_strings.txt create mode 100644 src/docs/struct_excessive_bools.txt create mode 100644 src/docs/suboptimal_flops.txt create mode 100644 src/docs/suspicious_arithmetic_impl.txt create mode 100644 src/docs/suspicious_assignment_formatting.txt create mode 100644 src/docs/suspicious_else_formatting.txt create mode 100644 src/docs/suspicious_map.txt create mode 100644 src/docs/suspicious_op_assign_impl.txt create mode 100644 src/docs/suspicious_operation_groupings.txt create mode 100644 src/docs/suspicious_splitn.txt create mode 100644 src/docs/suspicious_to_owned.txt create mode 100644 src/docs/suspicious_unary_op_formatting.txt create mode 100644 src/docs/swap_ptr_to_ref.txt create mode 100644 src/docs/tabs_in_doc_comments.txt create mode 100644 src/docs/temporary_assignment.txt create mode 100644 src/docs/to_digit_is_some.txt create mode 100644 src/docs/to_string_in_format_args.txt create mode 100644 src/docs/todo.txt create mode 100644 src/docs/too_many_arguments.txt create mode 100644 src/docs/too_many_lines.txt create mode 100644 src/docs/toplevel_ref_arg.txt create mode 100644 src/docs/trailing_empty_array.txt create mode 100644 src/docs/trait_duplication_in_bounds.txt create mode 100644 src/docs/transmute_bytes_to_str.txt create mode 100644 src/docs/transmute_float_to_int.txt create mode 100644 src/docs/transmute_int_to_bool.txt create mode 100644 src/docs/transmute_int_to_char.txt create mode 100644 src/docs/transmute_int_to_float.txt create mode 100644 src/docs/transmute_num_to_bytes.txt create mode 100644 src/docs/transmute_ptr_to_ptr.txt create mode 100644 src/docs/transmute_ptr_to_ref.txt create mode 100644 src/docs/transmute_undefined_repr.txt create mode 100644 src/docs/transmutes_expressible_as_ptr_casts.txt create mode 100644 src/docs/transmuting_null.txt create mode 100644 src/docs/trim_split_whitespace.txt create mode 100644 src/docs/trivial_regex.txt create mode 100644 src/docs/trivially_copy_pass_by_ref.txt create mode 100644 src/docs/try_err.txt create mode 100644 src/docs/type_complexity.txt create mode 100644 src/docs/type_repetition_in_bounds.txt create mode 100644 src/docs/undocumented_unsafe_blocks.txt create mode 100644 src/docs/undropped_manually_drops.txt create mode 100644 src/docs/unicode_not_nfc.txt create mode 100644 src/docs/unimplemented.txt create mode 100644 src/docs/uninit_assumed_init.txt create mode 100644 src/docs/uninit_vec.txt create mode 100644 src/docs/unit_arg.txt create mode 100644 src/docs/unit_cmp.txt create mode 100644 src/docs/unit_hash.txt create mode 100644 src/docs/unit_return_expecting_ord.txt create mode 100644 src/docs/unnecessary_cast.txt create mode 100644 src/docs/unnecessary_filter_map.txt create mode 100644 src/docs/unnecessary_find_map.txt create mode 100644 src/docs/unnecessary_fold.txt create mode 100644 src/docs/unnecessary_join.txt create mode 100644 src/docs/unnecessary_lazy_evaluations.txt create mode 100644 src/docs/unnecessary_mut_passed.txt create mode 100644 src/docs/unnecessary_operation.txt create mode 100644 src/docs/unnecessary_owned_empty_strings.txt create mode 100644 src/docs/unnecessary_self_imports.txt create mode 100644 src/docs/unnecessary_sort_by.txt create mode 100644 src/docs/unnecessary_to_owned.txt create mode 100644 src/docs/unnecessary_unwrap.txt create mode 100644 src/docs/unnecessary_wraps.txt create mode 100644 src/docs/unneeded_field_pattern.txt create mode 100644 src/docs/unneeded_wildcard_pattern.txt create mode 100644 src/docs/unnested_or_patterns.txt create mode 100644 src/docs/unreachable.txt create mode 100644 src/docs/unreadable_literal.txt create mode 100644 src/docs/unsafe_derive_deserialize.txt create mode 100644 src/docs/unsafe_removed_from_name.txt create mode 100644 src/docs/unseparated_literal_suffix.txt create mode 100644 src/docs/unsound_collection_transmute.txt create mode 100644 src/docs/unused_async.txt create mode 100644 src/docs/unused_io_amount.txt create mode 100644 src/docs/unused_peekable.txt create mode 100644 src/docs/unused_rounding.txt create mode 100644 src/docs/unused_self.txt create mode 100644 src/docs/unused_unit.txt create mode 100644 src/docs/unusual_byte_groupings.txt create mode 100644 src/docs/unwrap_in_result.txt create mode 100644 src/docs/unwrap_or_else_default.txt create mode 100644 src/docs/unwrap_used.txt create mode 100644 src/docs/upper_case_acronyms.txt create mode 100644 src/docs/use_debug.txt create mode 100644 src/docs/use_self.txt create mode 100644 src/docs/used_underscore_binding.txt create mode 100644 src/docs/useless_asref.txt create mode 100644 src/docs/useless_attribute.txt create mode 100644 src/docs/useless_conversion.txt create mode 100644 src/docs/useless_format.txt create mode 100644 src/docs/useless_let_if_seq.txt create mode 100644 src/docs/useless_transmute.txt create mode 100644 src/docs/useless_vec.txt create mode 100644 src/docs/vec_box.txt create mode 100644 src/docs/vec_init_then_push.txt create mode 100644 src/docs/vec_resize_to_zero.txt create mode 100644 src/docs/verbose_bit_mask.txt create mode 100644 src/docs/verbose_file_reads.txt create mode 100644 src/docs/vtable_address_comparisons.txt create mode 100644 src/docs/while_immutable_condition.txt create mode 100644 src/docs/while_let_loop.txt create mode 100644 src/docs/while_let_on_iterator.txt create mode 100644 src/docs/wildcard_dependencies.txt create mode 100644 src/docs/wildcard_enum_match_arm.txt create mode 100644 src/docs/wildcard_imports.txt create mode 100644 src/docs/wildcard_in_or_patterns.txt create mode 100644 src/docs/write_literal.txt create mode 100644 src/docs/write_with_newline.txt create mode 100644 src/docs/writeln_empty_string.txt create mode 100644 src/docs/wrong_self_convention.txt create mode 100644 src/docs/wrong_transmute.txt create mode 100644 src/docs/zero_divided_by_zero.txt create mode 100644 src/docs/zero_prefixed_literal.txt create mode 100644 src/docs/zero_ptr.txt create mode 100644 src/docs/zero_sized_map_values.txt create mode 100644 src/docs/zst_offset.txt delete mode 100644 tests/ui-toml/arithmetic_allowed/clippy.toml rename tests/ui-toml/{arithmetic_allowed/arithmetic_allowed.rs => arithmetic_side_effects_allowed/arithmetic_side_effects_allowed.rs} (89%) create mode 100644 tests/ui-toml/arithmetic_side_effects_allowed/clippy.toml delete mode 100644 tests/ui/arithmetic.fixed delete mode 100644 tests/ui/arithmetic.rs create mode 100644 tests/ui/arithmetic_side_effects.rs create mode 100644 tests/ui/arithmetic_side_effects.stderr create mode 100644 tests/ui/bool_to_int_with_if.fixed create mode 100644 tests/ui/bool_to_int_with_if.rs create mode 100644 tests/ui/bool_to_int_with_if.stderr create mode 100644 tests/ui/crashes/ice-9405.rs create mode 100644 tests/ui/crashes/ice-9405.stderr create mode 100644 tests/ui/crashes/ice-9414.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index c488c142e..d847e4c74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3583,7 +3583,7 @@ Released 2018-09-13 [`almost_complete_letter_range`]: https://rust-lang.github.io/rust-clippy/master/index.html#almost_complete_letter_range [`almost_swapped`]: https://rust-lang.github.io/rust-clippy/master/index.html#almost_swapped [`approx_constant`]: https://rust-lang.github.io/rust-clippy/master/index.html#approx_constant -[`arithmetic`]: https://rust-lang.github.io/rust-clippy/master/index.html#arithmetic +[`arithmetic_side_effects`]: https://rust-lang.github.io/rust-clippy/master/index.html#arithmetic_side_effects [`as_conversions`]: https://rust-lang.github.io/rust-clippy/master/index.html#as_conversions [`as_underscore`]: https://rust-lang.github.io/rust-clippy/master/index.html#as_underscore [`assertions_on_constants`]: https://rust-lang.github.io/rust-clippy/master/index.html#assertions_on_constants @@ -3603,6 +3603,7 @@ Released 2018-09-13 [`blocks_in_if_conditions`]: https://rust-lang.github.io/rust-clippy/master/index.html#blocks_in_if_conditions [`bool_assert_comparison`]: https://rust-lang.github.io/rust-clippy/master/index.html#bool_assert_comparison [`bool_comparison`]: https://rust-lang.github.io/rust-clippy/master/index.html#bool_comparison +[`bool_to_int_with_if`]: https://rust-lang.github.io/rust-clippy/master/index.html#bool_to_int_with_if [`borrow_as_ptr`]: https://rust-lang.github.io/rust-clippy/master/index.html#borrow_as_ptr [`borrow_deref_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#borrow_deref_ref [`borrow_interior_mutable_const`]: https://rust-lang.github.io/rust-clippy/master/index.html#borrow_interior_mutable_const diff --git a/clippy_dev/src/update_lints.rs b/clippy_dev/src/update_lints.rs index c503142e5..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)); } } } @@ -977,7 +1052,11 @@ fn remove_line_splices(s: &str) -> String { .and_then(|s| s.strip_suffix('"')) .unwrap_or_else(|| panic!("expected quoted string, found `{}`", s)); let mut res = String::with_capacity(s.len()); - unescape::unescape_literal(s, unescape::Mode::Str, &mut |range, _| res.push_str(&s[range])); + unescape::unescape_literal(s, unescape::Mode::Str, &mut |range, ch| { + if ch.is_ok() { + res.push_str(&s[range]); + } + }); res } @@ -1116,6 +1195,7 @@ mod tests { "\"really long text\"", "module_name", Range::default(), + String::new(), ), Lint::new( "doc_markdown", @@ -1123,6 +1203,7 @@ mod tests { "\"single line\"", "module_name", Range::default(), + String::new(), ), ]; assert_eq!(expected, result); @@ -1162,6 +1243,7 @@ mod tests { "\"abc\"", "module_name", Range::default(), + String::new(), ), Lint::new( "should_assert_eq2", @@ -1169,6 +1251,7 @@ mod tests { "\"abc\"", "module_name", Range::default(), + String::new(), ), Lint::new( "should_assert_eq2", @@ -1176,6 +1259,7 @@ mod tests { "\"abc\"", "module_name", Range::default(), + String::new(), ), ]; let expected = vec![Lint::new( @@ -1184,6 +1268,7 @@ mod tests { "\"abc\"", "module_name", Range::default(), + String::new(), )]; assert_eq!(expected, Lint::usable_lints(&lints)); } @@ -1191,22 +1276,51 @@ mod tests { #[test] fn test_by_lint_group() { let lints = vec![ - Lint::new("should_assert_eq", "group1", "\"abc\"", "module_name", Range::default()), + Lint::new( + "should_assert_eq", + "group1", + "\"abc\"", + "module_name", + Range::default(), + String::new(), + ), Lint::new( "should_assert_eq2", "group2", "\"abc\"", "module_name", Range::default(), + String::new(), + ), + Lint::new( + "incorrect_match", + "group1", + "\"abc\"", + "module_name", + Range::default(), + String::new(), ), - Lint::new("incorrect_match", "group1", "\"abc\"", "module_name", Range::default()), ]; let mut expected: HashMap> = HashMap::new(); expected.insert( "group1".to_string(), vec![ - Lint::new("should_assert_eq", "group1", "\"abc\"", "module_name", Range::default()), - Lint::new("incorrect_match", "group1", "\"abc\"", "module_name", Range::default()), + Lint::new( + "should_assert_eq", + "group1", + "\"abc\"", + "module_name", + Range::default(), + String::new(), + ), + Lint::new( + "incorrect_match", + "group1", + "\"abc\"", + "module_name", + Range::default(), + String::new(), + ), ], ); expected.insert( @@ -1217,6 +1331,7 @@ mod tests { "\"abc\"", "module_name", Range::default(), + String::new(), )], ); assert_eq!(expected, Lint::by_lint_group(lints.into_iter())); @@ -1255,9 +1370,30 @@ mod tests { #[test] fn test_gen_lint_group_list() { let lints = vec![ - Lint::new("abc", "group1", "\"abc\"", "module_name", Range::default()), - Lint::new("should_assert_eq", "group1", "\"abc\"", "module_name", Range::default()), - Lint::new("internal", "internal_style", "\"abc\"", "module_name", Range::default()), + Lint::new( + "abc", + "group1", + "\"abc\"", + "module_name", + Range::default(), + String::new(), + ), + Lint::new( + "should_assert_eq", + "group1", + "\"abc\"", + "module_name", + Range::default(), + String::new(), + ), + Lint::new( + "internal", + "internal_style", + "\"abc\"", + "module_name", + Range::default(), + String::new(), + ), ]; let expected = GENERATED_FILE_COMMENT.to_string() + &[ diff --git a/clippy_lints/src/async_yields_async.rs b/clippy_lints/src/async_yields_async.rs index 27c2896e1..9464694a3 100644 --- a/clippy_lints/src/async_yields_async.rs +++ b/clippy_lints/src/async_yields_async.rs @@ -54,7 +54,7 @@ impl<'tcx> LateLintPass<'tcx> for AsyncYieldsAsync { hir_id: body.value.hir_id, }; let typeck_results = cx.tcx.typeck_body(body_id); - let expr_ty = typeck_results.expr_ty(&body.value); + let expr_ty = typeck_results.expr_ty(body.value); if implements_trait(cx, expr_ty, future_trait_def_id, &[]) { let return_expr_span = match &body.value.kind { diff --git a/clippy_lints/src/attrs.rs b/clippy_lints/src/attrs.rs index 4bcbeacf9..732dc2b43 100644 --- a/clippy_lints/src/attrs.rs +++ b/clippy_lints/src/attrs.rs @@ -475,7 +475,7 @@ fn check_lint_reason(cx: &LateContext<'_>, name: Symbol, items: &[NestedMetaItem fn is_relevant_item(cx: &LateContext<'_>, item: &Item<'_>) -> bool { if let ItemKind::Fn(_, _, eid) = item.kind { - is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value) + is_relevant_expr(cx, cx.tcx.typeck_body(eid), cx.tcx.hir().body(eid).value) } else { true } @@ -483,7 +483,7 @@ fn is_relevant_item(cx: &LateContext<'_>, item: &Item<'_>) -> bool { fn is_relevant_impl(cx: &LateContext<'_>, item: &ImplItem<'_>) -> bool { match item.kind { - ImplItemKind::Fn(_, eid) => is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value), + ImplItemKind::Fn(_, eid) => is_relevant_expr(cx, cx.tcx.typeck_body(eid), cx.tcx.hir().body(eid).value), _ => false, } } @@ -492,7 +492,7 @@ fn is_relevant_trait(cx: &LateContext<'_>, item: &TraitItem<'_>) -> bool { match item.kind { TraitItemKind::Fn(_, TraitFn::Required(_)) => true, TraitItemKind::Fn(_, TraitFn::Provided(eid)) => { - is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value) + is_relevant_expr(cx, cx.tcx.typeck_body(eid), cx.tcx.hir().body(eid).value) }, _ => false, } diff --git a/clippy_lints/src/bool_to_int_with_if.rs b/clippy_lints/src/bool_to_int_with_if.rs new file mode 100644 index 000000000..a4b8cbb0d --- /dev/null +++ b/clippy_lints/src/bool_to_int_with_if.rs @@ -0,0 +1,125 @@ +use rustc_ast::{ExprPrecedence, LitKind}; +use rustc_hir::{Block, ExprKind}; +use rustc_lint::{LateContext, LateLintPass}; +use rustc_session::{declare_lint_pass, declare_tool_lint}; + +use clippy_utils::{diagnostics::span_lint_and_then, is_else_clause, source::snippet_block_with_applicability}; +use rustc_errors::Applicability; + +declare_clippy_lint! { + /// ### What it does + /// Instead of using an if statement to convert a bool to an int, + /// this lint suggests using a `from()` function or an `as` coercion. + /// + /// ### Why is this bad? + /// Coercion or `from()` is idiomatic way to convert bool to a number. + /// Both methods are guaranteed to return 1 for true, and 0 for false. + /// + /// See https://doc.rust-lang.org/std/primitive.bool.html#impl-From%3Cbool%3E + /// + /// ### Example + /// ```rust + /// # let condition = false; + /// if condition { + /// 1_i64 + /// } else { + /// 0 + /// }; + /// ``` + /// Use instead: + /// ```rust + /// # let condition = false; + /// i64::from(condition); + /// ``` + /// or + /// ```rust + /// # let condition = false; + /// condition as i64; + /// ``` + #[clippy::version = "1.65.0"] + pub BOOL_TO_INT_WITH_IF, + style, + "using if to convert bool to int" +} +declare_lint_pass!(BoolToIntWithIf => [BOOL_TO_INT_WITH_IF]); + +impl<'tcx> LateLintPass<'tcx> for BoolToIntWithIf { + fn check_expr(&mut self, ctx: &LateContext<'tcx>, expr: &'tcx rustc_hir::Expr<'tcx>) { + if !expr.span.from_expansion() { + check_if_else(ctx, expr); + } + } +} + +fn check_if_else<'tcx>(ctx: &LateContext<'tcx>, expr: &'tcx rustc_hir::Expr<'tcx>) { + if let ExprKind::If(check, then, Some(else_)) = expr.kind + && let Some(then_lit) = int_literal(then) + && let Some(else_lit) = int_literal(else_) + && check_int_literal_equals_val(then_lit, 1) + && check_int_literal_equals_val(else_lit, 0) + { + let mut applicability = Applicability::MachineApplicable; + let snippet = snippet_block_with_applicability(ctx, check.span, "..", None, &mut applicability); + let snippet_with_braces = { + let need_parens = should_have_parentheses(check); + let (left_paren, right_paren) = if need_parens {("(", ")")} else {("", "")}; + format!("{left_paren}{snippet}{right_paren}") + }; + + let ty = ctx.typeck_results().expr_ty(then_lit); // then and else must be of same type + + let suggestion = { + let wrap_in_curly = is_else_clause(ctx.tcx, expr); + let (left_curly, right_curly) = if wrap_in_curly {("{", "}")} else {("", "")}; + format!( + "{left_curly}{ty}::from({snippet}){right_curly}" + ) + }; // when used in else clause if statement should be wrapped in curly braces + + span_lint_and_then(ctx, + BOOL_TO_INT_WITH_IF, + expr.span, + "boolean to int conversion using if", + |diag| { + diag.span_suggestion( + expr.span, + "replace with from", + suggestion, + applicability, + ); + diag.note(format!("`{snippet_with_braces} as {ty}` or `{snippet_with_braces}.into()` can also be valid options")); + }); + }; +} + +// If block contains only a int literal expression, return literal expression +fn int_literal<'tcx>(expr: &'tcx rustc_hir::Expr<'tcx>) -> Option<&'tcx rustc_hir::Expr<'tcx>> { + if let ExprKind::Block(block, _) = expr.kind + && let Block { + stmts: [], // Shouldn't lint if statements with side effects + expr: Some(expr), + .. + } = block + && let ExprKind::Lit(lit) = &expr.kind + && let LitKind::Int(_, _) = lit.node + { + Some(expr) + } else { + None + } +} + +fn check_int_literal_equals_val<'tcx>(expr: &'tcx rustc_hir::Expr<'tcx>, expected_value: u128) -> bool { + if let ExprKind::Lit(lit) = &expr.kind + && let LitKind::Int(val, _) = lit.node + && val == expected_value + { + true + } else { + false + } +} + +fn should_have_parentheses<'tcx>(check: &'tcx rustc_hir::Expr<'tcx>) -> bool { + check.precedence().order() < ExprPrecedence::Cast.order() +} diff --git a/clippy_lints/src/default_numeric_fallback.rs b/clippy_lints/src/default_numeric_fallback.rs index 64c5de510..be02f328e 100644 --- a/clippy_lints/src/default_numeric_fallback.rs +++ b/clippy_lints/src/default_numeric_fallback.rs @@ -69,7 +69,10 @@ struct NumericFallbackVisitor<'a, 'tcx> { impl<'a, 'tcx> NumericFallbackVisitor<'a, 'tcx> { fn new(cx: &'a LateContext<'tcx>) -> Self { - Self { ty_bounds: vec![TyBound::Nothing], cx } + Self { + ty_bounds: vec![TyBound::Nothing], + cx, + } } /// Check whether a passed literal has potential to cause fallback or not. @@ -126,21 +129,19 @@ impl<'a, 'tcx> Visitor<'tcx> for NumericFallbackVisitor<'a, 'tcx> { } return; } - } + }, ExprKind::MethodCall(_, receiver, args, _) => { if let Some(def_id) = self.cx.typeck_results().type_dependent_def_id(expr.hir_id) { let fn_sig = self.cx.tcx.fn_sig(def_id).skip_binder(); - for (expr, bound) in - iter::zip(std::iter::once(*receiver).chain(args.iter()), fn_sig.inputs()) - { + for (expr, bound) in iter::zip(std::iter::once(*receiver).chain(args.iter()), fn_sig.inputs()) { self.ty_bounds.push(TyBound::Ty(*bound)); self.visit_expr(expr); self.ty_bounds.pop(); } return; } - } + }, ExprKind::Struct(_, fields, base) => { let ty = self.cx.typeck_results().expr_ty(expr); @@ -175,15 +176,15 @@ impl<'a, 'tcx> Visitor<'tcx> for NumericFallbackVisitor<'a, 'tcx> { return; } } - } + }, ExprKind::Lit(lit) => { let ty = self.cx.typeck_results().expr_ty(expr); self.check_lit(lit, ty, expr.hir_id); return; - } + }, - _ => {} + _ => {}, } walk_expr(self, expr); @@ -197,7 +198,7 @@ impl<'a, 'tcx> Visitor<'tcx> for NumericFallbackVisitor<'a, 'tcx> { } else { self.ty_bounds.push(TyBound::Nothing); } - } + }, _ => self.ty_bounds.push(TyBound::Nothing), } diff --git a/clippy_lints/src/dereference.rs b/clippy_lints/src/dereference.rs index d1ab7fb67..88e28018e 100644 --- a/clippy_lints/src/dereference.rs +++ b/clippy_lints/src/dereference.rs @@ -830,25 +830,22 @@ fn walk_parents<'tcx>( ) { return Some(Position::MethodReceiverRefImpl) - } else { - return Some(Position::MethodReceiver) } + return Some(Position::MethodReceiver); } - args.iter() - .position(|arg| arg.hir_id == child_id) - .map(|i| { - let ty = cx.tcx.fn_sig(id).skip_binder().inputs()[i + 1]; - if let ty::Param(param_ty) = ty.kind() { - needless_borrow_impl_arg_position(cx, parent, i + 1, *param_ty, e, precedence, msrv) - } else { - ty_auto_deref_stability( - cx, - cx.tcx.erase_late_bound_regions(cx.tcx.fn_sig(id).input(i + 1)), - precedence, - ) - .position_for_arg() - } - }) + args.iter().position(|arg| arg.hir_id == child_id).map(|i| { + let ty = cx.tcx.fn_sig(id).skip_binder().inputs()[i + 1]; + if let ty::Param(param_ty) = ty.kind() { + needless_borrow_impl_arg_position(cx, parent, i + 1, *param_ty, e, precedence, msrv) + } else { + ty_auto_deref_stability( + cx, + cx.tcx.erase_late_bound_regions(cx.tcx.fn_sig(id).input(i + 1)), + precedence, + ) + .position_for_arg() + } + }) }, ExprKind::Field(child, name) if child.hir_id == e.hir_id => Some(Position::FieldAccess(name.name)), ExprKind::Unary(UnOp::Deref, child) if child.hir_id == e.hir_id => Some(Position::Deref), diff --git a/clippy_lints/src/derivable_impls.rs b/clippy_lints/src/derivable_impls.rs index 4d7f4076d..ef9eeecc6 100644 --- a/clippy_lints/src/derivable_impls.rs +++ b/clippy_lints/src/derivable_impls.rs @@ -40,7 +40,7 @@ declare_clippy_lint! { /// /// ### Known problems /// Derive macros [sometimes use incorrect bounds](https://github.com/rust-lang/rust/issues/26925) - /// in generic types and the user defined `impl` maybe is more generalized or + /// in generic types and the user defined `impl` may be more generalized or /// specialized than what derive will produce. This lint can't detect the manual `impl` /// has exactly equal bounds, and therefore this lint is disabled for types with /// generic parameters. diff --git a/clippy_lints/src/doc.rs b/clippy_lints/src/doc.rs index 512872ced..eb158d850 100644 --- a/clippy_lints/src/doc.rs +++ b/clippy_lints/src/doc.rs @@ -236,7 +236,7 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { typeck_results: cx.tcx.typeck(item.def_id), panic_span: None, }; - fpu.visit_expr(&body.value); + fpu.visit_expr(body.value); lint_for_missing_headers(cx, item.def_id, item.span, sig, headers, Some(body_id), fpu.panic_span); } }, @@ -286,7 +286,7 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { typeck_results: cx.tcx.typeck(item.def_id), panic_span: None, }; - fpu.visit_expr(&body.value); + fpu.visit_expr(body.value); lint_for_missing_headers(cx, item.def_id, item.span, sig, headers, Some(body_id), fpu.panic_span); } } @@ -348,7 +348,7 @@ fn lint_for_missing_headers<'tcx>( if let Some(future) = cx.tcx.lang_items().future_trait(); let typeck = cx.tcx.typeck_body(body_id); let body = cx.tcx.hir().body(body_id); - let ret_ty = typeck.expr_ty(&body.value); + let ret_ty = typeck.expr_ty(body.value); if implements_trait(cx, ret_ty, future, &[]); if let ty::Opaque(_, subs) = ret_ty.kind(); if let Some(gen) = subs.types().next(); @@ -828,7 +828,7 @@ impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> { // check for `unwrap` if let Some(arglists) = method_chain_args(expr, &["unwrap"]) { - let receiver_ty = self.typeck_results.expr_ty(&arglists[0].0).peel_refs(); + let receiver_ty = self.typeck_results.expr_ty(arglists[0].0).peel_refs(); if is_type_diagnostic_item(self.cx, receiver_ty, sym::Option) || is_type_diagnostic_item(self.cx, receiver_ty, sym::Result) { diff --git a/clippy_lints/src/eta_reduction.rs b/clippy_lints/src/eta_reduction.rs index 1342a4697..53bc617a4 100644 --- a/clippy_lints/src/eta_reduction.rs +++ b/clippy_lints/src/eta_reduction.rs @@ -83,7 +83,7 @@ impl<'tcx> LateLintPass<'tcx> for EtaReduction { }; if body.value.span.from_expansion() { if body.params.is_empty() { - if let Some(VecArgs::Vec(&[])) = higher::VecArgs::hir(cx, &body.value) { + if let Some(VecArgs::Vec(&[])) = higher::VecArgs::hir(cx, body.value) { // replace `|| vec![]` with `Vec::new` span_lint_and_sugg( cx, @@ -103,7 +103,7 @@ impl<'tcx> LateLintPass<'tcx> for EtaReduction { let closure_ty = cx.typeck_results().expr_ty(expr); if_chain!( - if !is_adjusted(cx, &body.value); + if !is_adjusted(cx, body.value); if let ExprKind::Call(callee, args) = body.value.kind; if let ExprKind::Path(_) = callee.kind; if check_inputs(cx, body.params, None, args); @@ -145,7 +145,7 @@ impl<'tcx> LateLintPass<'tcx> for EtaReduction { ); if_chain!( - if !is_adjusted(cx, &body.value); + if !is_adjusted(cx, body.value); if let ExprKind::MethodCall(path, receiver, args, _) = body.value.kind; if check_inputs(cx, body.params, Some(receiver), args); let method_def_id = cx.typeck_results().type_dependent_def_id(body.value.hir_id).unwrap(); @@ -206,8 +206,7 @@ fn check_inputs( _ => false, } }; - std::iter::zip(params, receiver.into_iter().chain(call_args.iter())) - .all(|(param, arg)| check_inputs(param, arg)) + std::iter::zip(params, receiver.into_iter().chain(call_args.iter())).all(|(param, arg)| check_inputs(param, arg)) } fn check_sig<'tcx>(cx: &LateContext<'tcx>, closure_ty: Ty<'tcx>, call_ty: Ty<'tcx>) -> bool { diff --git a/clippy_lints/src/fallible_impl_from.rs b/clippy_lints/src/fallible_impl_from.rs index 790eea63f..1f69f34a2 100644 --- a/clippy_lints/src/fallible_impl_from.rs +++ b/clippy_lints/src/fallible_impl_from.rs @@ -84,7 +84,7 @@ fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_items: &[h // check for `unwrap` if let Some(arglists) = method_chain_args(expr, &["unwrap"]) { - let receiver_ty = self.typeck_results.expr_ty(&arglists[0].0).peel_refs(); + let receiver_ty = self.typeck_results.expr_ty(arglists[0].0).peel_refs(); if is_type_diagnostic_item(self.lcx, receiver_ty, sym::Option) || is_type_diagnostic_item(self.lcx, receiver_ty, sym::Result) { @@ -110,7 +110,7 @@ fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_items: &[h typeck_results: cx.tcx.typeck(impl_item.id.def_id), result: Vec::new(), }; - fpu.visit_expr(&body.value); + fpu.visit_expr(body.value); // if we've found one, lint if !fpu.result.is_empty() { diff --git a/clippy_lints/src/floating_point_arithmetic.rs b/clippy_lints/src/floating_point_arithmetic.rs index 728db41d6..ba53a9678 100644 --- a/clippy_lints/src/floating_point_arithmetic.rs +++ b/clippy_lints/src/floating_point_arithmetic.rs @@ -238,23 +238,23 @@ fn get_integer_from_float_constant(value: &Constant) -> Option { fn check_powf(cx: &LateContext<'_>, expr: &Expr<'_>, receiver: &Expr<'_>, args: &[Expr<'_>]) { // Check receiver if let Some((value, _)) = constant(cx, cx.typeck_results(), receiver) { - let method = if F32(f32_consts::E) == value || F64(f64_consts::E) == value { - "exp" + if let Some(method) = if F32(f32_consts::E) == value || F64(f64_consts::E) == value { + Some("exp") } else if F32(2.0) == value || F64(2.0) == value { - "exp2" + Some("exp2") } else { - return; - }; - - span_lint_and_sugg( - cx, - SUBOPTIMAL_FLOPS, - expr.span, - "exponent for bases 2 and e can be computed more accurately", - "consider using", - format!("{}.{}()", prepare_receiver_sugg(cx, &args[0]), method), - Applicability::MachineApplicable, - ); + None + } { + span_lint_and_sugg( + cx, + SUBOPTIMAL_FLOPS, + expr.span, + "exponent for bases 2 and e can be computed more accurately", + "consider using", + format!("{}.{}()", prepare_receiver_sugg(cx, &args[0]), method), + Applicability::MachineApplicable, + ); + } } // Check argument diff --git a/clippy_lints/src/functions/must_use.rs b/clippy_lints/src/functions/must_use.rs index a17b23f5e..00a493776 100644 --- a/clippy_lints/src/functions/must_use.rs +++ b/clippy_lints/src/functions/must_use.rs @@ -272,6 +272,6 @@ fn mutates_static<'tcx>(cx: &LateContext<'tcx>, body: &'tcx hir::Body<'_>) -> bo cx, mutates_static: false, }; - intravisit::walk_expr(&mut v, &body.value); + intravisit::walk_expr(&mut v, body.value); v.mutates_static } diff --git a/clippy_lints/src/functions/result.rs b/clippy_lints/src/functions/result.rs index af520a493..9591405cb 100644 --- a/clippy_lints/src/functions/result.rs +++ b/clippy_lints/src/functions/result.rs @@ -4,7 +4,6 @@ use rustc_lint::{LateContext, LintContext}; use rustc_middle::lint::in_external_macro; use rustc_middle::ty::{self, Ty}; use rustc_span::{sym, Span}; -use rustc_typeck::hir_ty_to_ty; use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_then}; use clippy_utils::trait_ref_of_method; @@ -17,11 +16,12 @@ use super::{RESULT_LARGE_ERR, RESULT_UNIT_ERR}; fn result_err_ty<'tcx>( cx: &LateContext<'tcx>, decl: &hir::FnDecl<'tcx>, + id: hir::def_id::LocalDefId, item_span: Span, ) -> Option<(&'tcx hir::Ty<'tcx>, Ty<'tcx>)> { if !in_external_macro(cx.sess(), item_span) && let hir::FnRetTy::Return(hir_ty) = decl.output - && let ty = hir_ty_to_ty(cx.tcx, hir_ty) + && let ty = cx.tcx.erase_late_bound_regions(cx.tcx.fn_sig(id).output()) && is_type_diagnostic_item(cx, ty, sym::Result) && let ty::Adt(_, substs) = ty.kind() { @@ -34,7 +34,7 @@ fn result_err_ty<'tcx>( pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::Item<'tcx>, large_err_threshold: u64) { if let hir::ItemKind::Fn(ref sig, _generics, _) = item.kind - && let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.span) + && let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.def_id, item.span) { if cx.access_levels.is_exported(item.def_id) { let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); @@ -47,7 +47,7 @@ pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::Item<'tcx>, l pub(super) fn check_impl_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::ImplItem<'tcx>, large_err_threshold: u64) { // Don't lint if method is a trait's implementation, we can't do anything about those if let hir::ImplItemKind::Fn(ref sig, _) = item.kind - && let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.span) + && let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.def_id, item.span) && trait_ref_of_method(cx, item.def_id).is_none() { if cx.access_levels.is_exported(item.def_id) { @@ -61,7 +61,7 @@ pub(super) fn check_impl_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::ImplItem pub(super) fn check_trait_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::TraitItem<'tcx>, large_err_threshold: u64) { if let hir::TraitItemKind::Fn(ref sig, _) = item.kind { let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); - if let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.span) { + if let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.def_id, item.span) { if cx.access_levels.is_exported(item.def_id) { check_result_unit_err(cx, err_ty, fn_header_span); } diff --git a/clippy_lints/src/implicit_return.rs b/clippy_lints/src/implicit_return.rs index a6610ade3..feec8ec2e 100644 --- a/clippy_lints/src/implicit_return.rs +++ b/clippy_lints/src/implicit_return.rs @@ -232,7 +232,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitReturn { return; } - let res_ty = cx.typeck_results().expr_ty(&body.value); + let res_ty = cx.typeck_results().expr_ty(body.value); if res_ty.is_unit() || res_ty.is_never() { return; } @@ -243,7 +243,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitReturn { None => return, } } else { - &body.value + body.value }; lint_implicit_returns(cx, expr, expr.span.ctxt(), None); } diff --git a/clippy_lints/src/infinite_iter.rs b/clippy_lints/src/infinite_iter.rs index d55a8e1ea..8c2c96fa1 100644 --- a/clippy_lints/src/infinite_iter.rs +++ b/clippy_lints/src/infinite_iter.rs @@ -59,7 +59,7 @@ impl<'tcx> LateLintPass<'tcx> for InfiniteIter { MaybeInfinite => (MAYBE_INFINITE_ITER, "possible infinite iteration detected"), Finite => { return; - } + }, }; span_lint(cx, lint, expr.span, msg); } @@ -161,7 +161,7 @@ fn is_infinite(cx: &LateContext<'_>, expr: &Expr<'_>) -> Finiteness { if method.ident.name == sym!(flat_map) && args.len() == 1 { if let ExprKind::Closure(&Closure { body, .. }) = args[0].kind { let body = cx.tcx.hir().body(body); - return is_infinite(cx, &body.value); + return is_infinite(cx, body.value); } } Finite @@ -230,8 +230,10 @@ fn complete_infinite_iter(cx: &LateContext<'_>, expr: &Expr<'_>) -> Finiteness { } } if method.ident.name == sym!(last) && args.is_empty() { - let not_double_ended = - cx.tcx.get_diagnostic_item(sym::DoubleEndedIterator).map_or(false, |id| { + let not_double_ended = cx + .tcx + .get_diagnostic_item(sym::DoubleEndedIterator) + .map_or(false, |id| { !implements_trait(cx, cx.typeck_results().expr_ty(receiver), id, &[]) }); if not_double_ended { diff --git a/clippy_lints/src/large_enum_variant.rs b/clippy_lints/src/large_enum_variant.rs index c58df126d..eb13d0869 100644 --- a/clippy_lints/src/large_enum_variant.rs +++ b/clippy_lints/src/large_enum_variant.rs @@ -1,13 +1,12 @@ //! lint when there is a large size difference between variants on an enum use clippy_utils::source::snippet_with_applicability; -use clippy_utils::{diagnostics::span_lint_and_then, ty::is_copy}; +use clippy_utils::{diagnostics::span_lint_and_then, ty::approx_ty_size, ty::is_copy}; use rustc_errors::Applicability; use rustc_hir::{Item, ItemKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::lint::in_external_macro; -use rustc_middle::ty::layout::LayoutOf; -use rustc_middle::ty::{Adt, Ty}; +use rustc_middle::ty::{Adt, AdtDef, GenericArg, List, Ty}; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::source_map::Span; @@ -17,7 +16,7 @@ declare_clippy_lint! { /// `enum`s. /// /// ### Why is this bad? - /// Enum size is bounded by the largest variant. Having a + /// Enum size is bounded by the largest variant. Having one /// large variant can penalize the memory layout of that enum. /// /// ### Known problems @@ -33,8 +32,9 @@ declare_clippy_lint! { /// use case it may be possible to store the large data in an auxiliary /// structure (e.g. Arena or ECS). /// - /// The lint will ignore generic types if the layout depends on the - /// generics, even if the size difference will be large anyway. + /// The lint will ignore the impact of generic types to the type layout by + /// assuming every type parameter is zero-sized. Depending on your use case, + /// this may lead to a false positive. /// /// ### Example /// ```rust @@ -83,6 +83,38 @@ struct VariantInfo { fields_size: Vec, } +fn variants_size<'tcx>( + cx: &LateContext<'tcx>, + adt: AdtDef<'tcx>, + subst: &'tcx List>, +) -> Vec { + let mut variants_size = adt + .variants() + .iter() + .enumerate() + .map(|(i, variant)| { + let mut fields_size = variant + .fields + .iter() + .enumerate() + .map(|(i, f)| FieldInfo { + ind: i, + size: approx_ty_size(cx, f.ty(cx.tcx, subst)), + }) + .collect::>(); + fields_size.sort_by(|a, b| (a.size.cmp(&b.size))); + + VariantInfo { + ind: i, + size: fields_size.iter().map(|info| info.size).sum(), + fields_size, + } + }) + .collect::>(); + variants_size.sort_by(|a, b| (b.size.cmp(&a.size))); + variants_size +} + impl_lint_pass!(LargeEnumVariant => [LARGE_ENUM_VARIANT]); impl<'tcx> LateLintPass<'tcx> for LargeEnumVariant { @@ -92,36 +124,14 @@ impl<'tcx> LateLintPass<'tcx> for LargeEnumVariant { } if let ItemKind::Enum(ref def, _) = item.kind { let ty = cx.tcx.type_of(item.def_id); - let adt = ty.ty_adt_def().expect("already checked whether this is an enum"); + let (adt, subst) = match ty.kind() { + Adt(adt, subst) => (adt, subst), + _ => panic!("already checked whether this is an enum"), + }; if adt.variants().len() <= 1 { return; } - let mut variants_size: Vec = Vec::new(); - for (i, variant) in adt.variants().iter().enumerate() { - let mut fields_size = Vec::new(); - for (i, f) in variant.fields.iter().enumerate() { - let ty = cx.tcx.type_of(f.did); - // don't lint variants which have a field of generic type. - match cx.layout_of(ty) { - Ok(l) => { - let fsize = l.size.bytes(); - fields_size.push(FieldInfo { ind: i, size: fsize }); - }, - Err(_) => { - return; - }, - } - } - let size: u64 = fields_size.iter().map(|info| info.size).sum(); - - variants_size.push(VariantInfo { - ind: i, - size, - fields_size, - }); - } - - variants_size.sort_by(|a, b| (b.size.cmp(&a.size))); + let variants_size = variants_size(cx, *adt, subst); let mut difference = variants_size[0].size - variants_size[1].size; if difference > self.maximum_size_difference_allowed { @@ -129,20 +139,30 @@ impl<'tcx> LateLintPass<'tcx> for LargeEnumVariant { span_lint_and_then( cx, LARGE_ENUM_VARIANT, - def.variants[variants_size[0].ind].span, + item.span, "large size difference between variants", |diag| { diag.span_label( - def.variants[variants_size[0].ind].span, - &format!("this variant is {} bytes", variants_size[0].size), + item.span, + format!("the entire enum is at least {} bytes", approx_ty_size(cx, ty)), ); - diag.span_note( + diag.span_label( + def.variants[variants_size[0].ind].span, + format!("the largest variant contains at least {} bytes", variants_size[0].size), + ); + diag.span_label( def.variants[variants_size[1].ind].span, - &format!("and the second-largest variant is {} bytes:", variants_size[1].size), + &if variants_size[1].fields_size.is_empty() { + "the second-largest variant carries no data at all".to_owned() + } else { + format!( + "the second-largest variant contains at least {} bytes", + variants_size[1].size + ) + }, ); let fields = def.variants[variants_size[0].ind].data.fields(); - variants_size[0].fields_size.sort_by(|a, b| (a.size.cmp(&b.size))); let mut applicability = Applicability::MaybeIncorrect; if is_copy(cx, ty) || maybe_copy(cx, ty) { diag.span_note( diff --git a/clippy_lints/src/len_zero.rs b/clippy_lints/src/len_zero.rs index 3cbdaff40..7ae8ef830 100644 --- a/clippy_lints/src/len_zero.rs +++ b/clippy_lints/src/len_zero.rs @@ -370,7 +370,8 @@ fn check_for_is_empty<'tcx>( } fn check_cmp(cx: &LateContext<'_>, span: Span, method: &Expr<'_>, lit: &Expr<'_>, op: &str, compare_to: u32) { - if let (&ExprKind::MethodCall(method_path, receiver, args, _), &ExprKind::Lit(ref lit)) = (&method.kind, &lit.kind) { + if let (&ExprKind::MethodCall(method_path, receiver, args, _), &ExprKind::Lit(ref lit)) = (&method.kind, &lit.kind) + { // check if we are in an is_empty() method if let Some(name) = get_item_name(cx, method) { if name.as_str() == "is_empty" { @@ -378,12 +379,23 @@ fn check_cmp(cx: &LateContext<'_>, span: Span, method: &Expr<'_>, lit: &Expr<'_> } } - check_len(cx, span, method_path.ident.name, receiver, args, &lit.node, op, compare_to); + check_len( + cx, + span, + method_path.ident.name, + receiver, + args, + &lit.node, + op, + compare_to, + ); } else { check_empty_expr(cx, span, method, lit, op); } } +// FIXME(flip1995): Figure out how to reduce the number of arguments +#[allow(clippy::too_many_arguments)] fn check_len( cx: &LateContext<'_>, span: Span, diff --git a/clippy_lints/src/lib.register_all.rs b/clippy_lints/src/lib.register_all.rs index 134cbbf7b..1f8538234 100644 --- a/clippy_lints/src/lib.register_all.rs +++ b/clippy_lints/src/lib.register_all.rs @@ -17,6 +17,7 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![ LintId::of(await_holding_invalid::AWAIT_HOLDING_REFCELL_REF), LintId::of(blocks_in_if_conditions::BLOCKS_IN_IF_CONDITIONS), LintId::of(bool_assert_comparison::BOOL_ASSERT_COMPARISON), + LintId::of(bool_to_int_with_if::BOOL_TO_INT_WITH_IF), LintId::of(booleans::NONMINIMAL_BOOL), LintId::of(booleans::OVERLY_COMPLEX_BOOL_EXPR), LintId::of(borrow_deref_ref::BORROW_DEREF_REF), diff --git a/clippy_lints/src/lib.register_lints.rs b/clippy_lints/src/lib.register_lints.rs index fd20e0165..962e67220 100644 --- a/clippy_lints/src/lib.register_lints.rs +++ b/clippy_lints/src/lib.register_lints.rs @@ -56,6 +56,7 @@ store.register_lints(&[ await_holding_invalid::AWAIT_HOLDING_REFCELL_REF, blocks_in_if_conditions::BLOCKS_IN_IF_CONDITIONS, bool_assert_comparison::BOOL_ASSERT_COMPARISON, + bool_to_int_with_if::BOOL_TO_INT_WITH_IF, booleans::NONMINIMAL_BOOL, booleans::OVERLY_COMPLEX_BOOL_EXPR, borrow_deref_ref::BORROW_DEREF_REF, @@ -436,7 +437,7 @@ store.register_lints(&[ octal_escapes::OCTAL_ESCAPES, only_used_in_recursion::ONLY_USED_IN_RECURSION, operators::ABSURD_EXTREME_COMPARISONS, - operators::ARITHMETIC, + operators::ARITHMETIC_SIDE_EFFECTS, operators::ASSIGN_OP_PATTERN, operators::BAD_BIT_MASK, operators::CMP_NAN, diff --git a/clippy_lints/src/lib.register_restriction.rs b/clippy_lints/src/lib.register_restriction.rs index dd1e1e1a8..6eb9b3d3b 100644 --- a/clippy_lints/src/lib.register_restriction.rs +++ b/clippy_lints/src/lib.register_restriction.rs @@ -50,7 +50,7 @@ store.register_group(true, "clippy::restriction", Some("clippy_restriction"), ve LintId::of(mixed_read_write_in_expression::MIXED_READ_WRITE_IN_EXPRESSION), LintId::of(module_style::MOD_MODULE_FILES), LintId::of(module_style::SELF_NAMED_MODULE_FILES), - LintId::of(operators::ARITHMETIC), + LintId::of(operators::ARITHMETIC_SIDE_EFFECTS), LintId::of(operators::FLOAT_ARITHMETIC), LintId::of(operators::FLOAT_CMP_CONST), LintId::of(operators::INTEGER_ARITHMETIC), diff --git a/clippy_lints/src/lib.register_style.rs b/clippy_lints/src/lib.register_style.rs index b5cb078e7..05d2ec2e9 100644 --- a/clippy_lints/src/lib.register_style.rs +++ b/clippy_lints/src/lib.register_style.rs @@ -6,6 +6,7 @@ store.register_group(true, "clippy::style", Some("clippy_style"), vec![ LintId::of(assertions_on_constants::ASSERTIONS_ON_CONSTANTS), LintId::of(blocks_in_if_conditions::BLOCKS_IN_IF_CONDITIONS), LintId::of(bool_assert_comparison::BOOL_ASSERT_COMPARISON), + LintId::of(bool_to_int_with_if::BOOL_TO_INT_WITH_IF), LintId::of(casts::FN_TO_NUMERIC_CAST), LintId::of(casts::FN_TO_NUMERIC_CAST_WITH_TRUNCATION), LintId::of(collapsible_if::COLLAPSIBLE_ELSE_IF), diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index c70aa79ac..e984254bf 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -179,6 +179,7 @@ mod attrs; mod await_holding_invalid; mod blocks_in_if_conditions; mod bool_assert_comparison; +mod bool_to_int_with_if; mod booleans; mod borrow_deref_ref; mod cargo; @@ -523,7 +524,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: #[cfg(feature = "internal")] { if std::env::var("ENABLE_METADATA_COLLECTION").eq(&Ok("1".to_string())) { - store.register_late_pass(|_| Box::new(utils::internal_lints::metadata_collector::MetadataCollector::new())); + store.register_late_pass(|| Box::new(utils::internal_lints::metadata_collector::MetadataCollector::new())); return; } } @@ -544,8 +545,12 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: store.register_late_pass(|_| Box::new(utils::internal_lints::MsrvAttrImpl)); } - let arithmetic_allowed = conf.arithmetic_allowed.clone(); - store.register_late_pass(move |_| Box::new(operators::arithmetic::Arithmetic::new(arithmetic_allowed.clone()))); + let arithmetic_side_effects_allowed = conf.arithmetic_side_effects_allowed.clone(); + store.register_late_pass(move |_| { + Box::new(operators::arithmetic_side_effects::ArithmeticSideEffects::new( + arithmetic_side_effects_allowed.clone(), + )) + }); store.register_late_pass(|_| Box::new(utils::dump_hir::DumpHir)); store.register_late_pass(|_| Box::new(utils::author::Author)); let await_holding_invalid_types = conf.await_holding_invalid_types.clone(); @@ -901,6 +906,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: store.register_late_pass(|_| Box::new(manual_string_new::ManualStringNew)); store.register_late_pass(|_| Box::new(unused_peekable::UnusedPeekable)); store.register_early_pass(|| Box::new(multi_assignments::MultiAssignments)); + store.register_late_pass(|_| Box::new(bool_to_int_with_if::BoolToIntWithIf)); // add lints here, do not remove this comment, it's used in `new_lint` } diff --git a/clippy_lints/src/lifetimes.rs b/clippy_lints/src/lifetimes.rs index 5995675bd..f2b6e0b7e 100644 --- a/clippy_lints/src/lifetimes.rs +++ b/clippy_lints/src/lifetimes.rs @@ -276,7 +276,7 @@ fn could_use_elision<'tcx>( let mut checker = BodyLifetimeChecker { lifetimes_used_in_body: false, }; - checker.visit_expr(&body.value); + checker.visit_expr(body.value); if checker.lifetimes_used_in_body { return false; } diff --git a/clippy_lints/src/loops/needless_range_loop.rs b/clippy_lints/src/loops/needless_range_loop.rs index ffcf83e46..8ab640051 100644 --- a/clippy_lints/src/loops/needless_range_loop.rs +++ b/clippy_lints/src/loops/needless_range_loop.rs @@ -373,7 +373,7 @@ impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> { }, ExprKind::Closure(&Closure { body, .. }) => { let body = self.cx.tcx.hir().body(body); - self.visit_expr(&body.value); + self.visit_expr(body.value); }, _ => walk_expr(self, expr), } diff --git a/clippy_lints/src/loops/while_let_on_iterator.rs b/clippy_lints/src/loops/while_let_on_iterator.rs index 2c54033f8..deb21894f 100644 --- a/clippy_lints/src/loops/while_let_on_iterator.rs +++ b/clippy_lints/src/loops/while_let_on_iterator.rs @@ -356,7 +356,7 @@ fn needs_mutable_borrow(cx: &LateContext<'_>, iter_expr: &IterExpr, loop_expr: & after_loop: false, used_iter: false, }; - v.visit_expr(&cx.tcx.hir().body(cx.enclosing_body.unwrap()).value); + v.visit_expr(cx.tcx.hir().body(cx.enclosing_body.unwrap()).value); v.used_iter } } diff --git a/clippy_lints/src/matches/match_wild_err_arm.rs b/clippy_lints/src/matches/match_wild_err_arm.rs index bc16f17b6..a3aa2e4b3 100644 --- a/clippy_lints/src/matches/match_wild_err_arm.rs +++ b/clippy_lints/src/matches/match_wild_err_arm.rs @@ -40,7 +40,7 @@ pub(crate) fn check<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm<' arm.pat.span, &format!("`Err({})` matches all errors", ident_bind_name), None, - "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable", + "match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable", ); } } diff --git a/clippy_lints/src/matches/single_match.rs b/clippy_lints/src/matches/single_match.rs index 1bf1c4d10..56bcdc01f 100644 --- a/clippy_lints/src/matches/single_match.rs +++ b/clippy_lints/src/matches/single_match.rs @@ -203,12 +203,8 @@ fn form_exhaustive_matches<'a>(cx: &LateContext<'a>, ty: Ty<'a>, left: &Pat<'_>, let left_pos = left_pos.as_opt_usize(); let right_pos = right_pos.as_opt_usize(); let len = max( - left_in.len() + { - if left_pos.is_some() { 1 } else { 0 } - }, - right_in.len() + { - if right_pos.is_some() { 1 } else { 0 } - }, + left_in.len() + usize::from(left_pos.is_some()), + right_in.len() + usize::from(right_pos.is_some()), ); let mut left_pos = left_pos.unwrap_or(usize::MAX); let mut right_pos = right_pos.unwrap_or(usize::MAX); diff --git a/clippy_lints/src/methods/bind_instead_of_map.rs b/clippy_lints/src/methods/bind_instead_of_map.rs index 2f117e4dc..22f5635a5 100644 --- a/clippy_lints/src/methods/bind_instead_of_map.rs +++ b/clippy_lints/src/methods/bind_instead_of_map.rs @@ -152,7 +152,7 @@ pub(crate) trait BindInsteadOfMap { match arg.kind { hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, .. }) => { let closure_body = cx.tcx.hir().body(body); - let closure_expr = peel_blocks(&closure_body.value); + let closure_expr = peel_blocks(closure_body.value); if Self::lint_closure_autofixable(cx, expr, recv, closure_expr, fn_decl_span) { true diff --git a/clippy_lints/src/methods/chars_cmp.rs b/clippy_lints/src/methods/chars_cmp.rs index 51aec2152..b2bc1ad5c 100644 --- a/clippy_lints/src/methods/chars_cmp.rs +++ b/clippy_lints/src/methods/chars_cmp.rs @@ -23,7 +23,7 @@ pub(super) fn check( if Some(id) == cx.tcx.lang_items().option_some_variant(); then { let mut applicability = Applicability::MachineApplicable; - let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0].0).peel_refs(); + let self_ty = cx.typeck_results().expr_ty_adjusted(args[0].0).peel_refs(); if *self_ty.kind() != ty::Str { return false; diff --git a/clippy_lints/src/methods/clone_on_copy.rs b/clippy_lints/src/methods/clone_on_copy.rs index f5bead387..7ab6b84c2 100644 --- a/clippy_lints/src/methods/clone_on_copy.rs +++ b/clippy_lints/src/methods/clone_on_copy.rs @@ -21,7 +21,11 @@ pub(super) fn check( receiver: &Expr<'_>, args: &[Expr<'_>], ) { - let arg = if method_name == sym::clone && args.is_empty() { receiver } else { return }; + let arg = if method_name == sym::clone && args.is_empty() { + receiver + } else { + return; + }; if cx .typeck_results() .type_dependent_def_id(expr.hir_id) diff --git a/clippy_lints/src/methods/filter_map.rs b/clippy_lints/src/methods/filter_map.rs index 9dc839afc..9719b2f1c 100644 --- a/clippy_lints/src/methods/filter_map.rs +++ b/clippy_lints/src/methods/filter_map.rs @@ -25,7 +25,7 @@ fn is_method<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, method_name: Sy }, hir::ExprKind::Closure(&hir::Closure { body, .. }) => { let body = cx.tcx.hir().body(body); - let closure_expr = peel_blocks(&body.value); + let closure_expr = peel_blocks(body.value); let arg_id = body.params[0].pat.hir_id; match closure_expr.kind { hir::ExprKind::MethodCall(hir::PathSegment { ident, .. }, receiver, ..) => { diff --git a/clippy_lints/src/methods/map_clone.rs b/clippy_lints/src/methods/map_clone.rs index e8442091f..8261ef5e1 100644 --- a/clippy_lints/src/methods/map_clone.rs +++ b/clippy_lints/src/methods/map_clone.rs @@ -30,7 +30,7 @@ pub(super) fn check<'tcx>( if let hir::ExprKind::Closure(&hir::Closure{ body, .. }) = arg.kind; then { let closure_body = cx.tcx.hir().body(body); - let closure_expr = peel_blocks(&closure_body.value); + let closure_expr = peel_blocks(closure_body.value); match closure_body.params[0].pat.kind { hir::PatKind::Ref(inner, hir::Mutability::Not) => if let hir::PatKind::Binding( hir::BindingAnnotation::NONE, .., name, None diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index 48a9d6e7c..41942b20e 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -825,8 +825,9 @@ declare_clippy_lint! { declare_clippy_lint! { /// ### What it does /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`, - /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or - /// `unwrap_or_default` instead. + /// `.or_insert(foo(..))` etc., and suggests to use `.or_else(|| foo(..))`, + /// `.unwrap_or_else(|| foo(..))`, `.unwrap_or_default()` or `.or_default()` + /// etc. instead. /// /// ### Why is this bad? /// The function will always be called and potentially diff --git a/clippy_lints/src/methods/mut_mutex_lock.rs b/clippy_lints/src/methods/mut_mutex_lock.rs index bd8458a22..b9593b368 100644 --- a/clippy_lints/src/methods/mut_mutex_lock.rs +++ b/clippy_lints/src/methods/mut_mutex_lock.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::ty::is_type_diagnostic_item; +use clippy_utils::{expr_custom_deref_adjustment, ty::is_type_diagnostic_item}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir::{Expr, Mutability}; @@ -11,6 +11,7 @@ use super::MUT_MUTEX_LOCK; pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'tcx>, recv: &'tcx Expr<'tcx>, name_span: Span) { if_chain! { + if matches!(expr_custom_deref_adjustment(cx, recv), None | Some(Mutability::Mut)); if let ty::Ref(_, _, Mutability::Mut) = cx.typeck_results().expr_ty(recv).kind(); if let Some(method_id) = cx.typeck_results().type_dependent_def_id(ex.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(method_id); diff --git a/clippy_lints/src/methods/open_options.rs b/clippy_lints/src/methods/open_options.rs index 903fa306f..597af853d 100644 --- a/clippy_lints/src/methods/open_options.rs +++ b/clippy_lints/src/methods/open_options.rs @@ -40,7 +40,7 @@ fn get_open_options(cx: &LateContext<'_>, argument: &Expr<'_>, options: &mut Vec let obj_ty = cx.typeck_results().expr_ty(receiver).peel_refs(); // Only proceed if this is a call on some object of type std::fs::OpenOptions - if match_type(cx, obj_ty, &paths::OPEN_OPTIONS) && arguments.len() >= 1 { + if match_type(cx, obj_ty, &paths::OPEN_OPTIONS) && !arguments.is_empty() { let argument_option = match arguments[0].kind { ExprKind::Lit(ref span) => { if let Spanned { diff --git a/clippy_lints/src/methods/option_as_ref_deref.rs b/clippy_lints/src/methods/option_as_ref_deref.rs index 81c67b4ca..c409268de 100644 --- a/clippy_lints/src/methods/option_as_ref_deref.rs +++ b/clippy_lints/src/methods/option_as_ref_deref.rs @@ -53,7 +53,7 @@ pub(super) fn check<'tcx>( }), hir::ExprKind::Closure(&hir::Closure { body, .. }) => { let closure_body = cx.tcx.hir().body(body); - let closure_expr = peel_blocks(&closure_body.value); + let closure_expr = peel_blocks(closure_body.value); match &closure_expr.kind { hir::ExprKind::MethodCall(_, receiver, [], _) => { diff --git a/clippy_lints/src/methods/option_map_or_none.rs b/clippy_lints/src/methods/option_map_or_none.rs index 5a39b82b0..6657cdccd 100644 --- a/clippy_lints/src/methods/option_map_or_none.rs +++ b/clippy_lints/src/methods/option_map_or_none.rs @@ -74,7 +74,7 @@ pub(super) fn check<'tcx>( if let hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, .. }) = map_arg.kind; let arg_snippet = snippet(cx, fn_decl_span, ".."); let body = cx.tcx.hir().body(body); - if let Some((func, [arg_char])) = reduce_unit_expression(&body.value); + if let Some((func, [arg_char])) = reduce_unit_expression(body.value); if let Some(id) = path_def_id(cx, func).map(|ctor_id| cx.tcx.parent(ctor_id)); if Some(id) == cx.tcx.lang_items().option_some_variant(); then { diff --git a/clippy_lints/src/methods/or_fun_call.rs b/clippy_lints/src/methods/or_fun_call.rs index 76876d866..b43b9258c 100644 --- a/clippy_lints/src/methods/or_fun_call.rs +++ b/clippy_lints/src/methods/or_fun_call.rs @@ -23,7 +23,8 @@ pub(super) fn check<'tcx>( receiver: &'tcx hir::Expr<'_>, args: &'tcx [hir::Expr<'_>], ) { - /// Checks for `unwrap_or(T::new())` or `unwrap_or(T::default())`. + /// Checks for `unwrap_or(T::new())`, `unwrap_or(T::default())`, + /// `or_insert(T::new())` or `or_insert(T::default())`. #[allow(clippy::too_many_arguments)] fn check_unwrap_or_default( cx: &LateContext<'_>, @@ -43,7 +44,11 @@ pub(super) fn check<'tcx>( if_chain! { if !or_has_args; - if name == "unwrap_or"; + if let Some(sugg) = match name { + "unwrap_or" => Some("unwrap_or_default"), + "or_insert" => Some("or_default"), + _ => None, + }; if let hir::ExprKind::Path(ref qpath) = fun.kind; if let Some(default_trait_id) = cx.tcx.get_diagnostic_item(sym::Default); let path = last_path_segment(qpath).ident.name; @@ -59,7 +64,7 @@ pub(super) fn check<'tcx>( method_span.with_hi(span.hi()), &format!("use of `{}` followed by a call to `{}`", name, path), "try this", - "unwrap_or_default()".to_string(), + format!("{}()", sugg), Applicability::MachineApplicable, ); @@ -83,7 +88,7 @@ pub(super) fn check<'tcx>( fun_span: Option, ) { // (path, fn_has_argument, methods, suffix) - static KNOW_TYPES: [(&[&str], bool, &[&str], &str); 4] = [ + const KNOW_TYPES: [(&[&str], bool, &[&str], &str); 4] = [ (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"), (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"), (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"), diff --git a/clippy_lints/src/methods/suspicious_map.rs b/clippy_lints/src/methods/suspicious_map.rs index 9c3375bf3..851cdf544 100644 --- a/clippy_lints/src/methods/suspicious_map.rs +++ b/clippy_lints/src/methods/suspicious_map.rs @@ -15,9 +15,9 @@ pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, count_recv: &hi if let Some(def_id) = cx.tcx.hir().opt_local_def_id(closure.hir_id); if let Some(body_id) = cx.tcx.hir().maybe_body_owned_by(def_id); let closure_body = cx.tcx.hir().body(body_id); - if !cx.typeck_results().expr_ty(&closure_body.value).is_unit(); + if !cx.typeck_results().expr_ty(closure_body.value).is_unit(); then { - if let Some(map_mutated_vars) = mutated_variables(&closure_body.value, cx) { + if let Some(map_mutated_vars) = mutated_variables(closure_body.value, cx) { // A variable is used mutably inside of the closure. Suppress the lint. if !map_mutated_vars.is_empty() { return; diff --git a/clippy_lints/src/methods/unnecessary_filter_map.rs b/clippy_lints/src/methods/unnecessary_filter_map.rs index bafa6fc58..4e8c201f4 100644 --- a/clippy_lints/src/methods/unnecessary_filter_map.rs +++ b/clippy_lints/src/methods/unnecessary_filter_map.rs @@ -21,14 +21,13 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr< if let hir::ExprKind::Closure(&hir::Closure { body, .. }) = arg.kind { let body = cx.tcx.hir().body(body); let arg_id = body.params[0].pat.hir_id; - let mutates_arg = - mutated_variables(&body.value, cx).map_or(true, |used_mutably| used_mutably.contains(&arg_id)); - let (clone_or_copy_needed, _) = clone_or_copy_needed(cx, body.params[0].pat, &body.value); + let mutates_arg = mutated_variables(body.value, cx).map_or(true, |used_mutably| used_mutably.contains(&arg_id)); + let (clone_or_copy_needed, _) = clone_or_copy_needed(cx, body.params[0].pat, body.value); - let (mut found_mapping, mut found_filtering) = check_expression(cx, arg_id, &body.value); + let (mut found_mapping, mut found_filtering) = check_expression(cx, arg_id, body.value); let mut return_visitor = ReturnVisitor::new(cx, arg_id); - return_visitor.visit_expr(&body.value); + return_visitor.visit_expr(body.value); found_mapping |= return_visitor.found_mapping; found_filtering |= return_visitor.found_filtering; @@ -36,7 +35,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr< let sugg = if !found_filtering { if name == "filter_map" { "map" } else { "map(..).next()" } } else if !found_mapping && !mutates_arg && (!clone_or_copy_needed || is_copy(cx, in_ty)) { - match cx.typeck_results().expr_ty(&body.value).kind() { + match cx.typeck_results().expr_ty(body.value).kind() { ty::Adt(adt, subst) if cx.tcx.is_diagnostic_item(sym::Option, adt.did()) && in_ty == subst.type_at(0) => { diff --git a/clippy_lints/src/methods/unnecessary_fold.rs b/clippy_lints/src/methods/unnecessary_fold.rs index c3531d4d0..c17ef6809 100644 --- a/clippy_lints/src/methods/unnecessary_fold.rs +++ b/clippy_lints/src/methods/unnecessary_fold.rs @@ -31,7 +31,7 @@ pub(super) fn check( // Extract the body of the closure passed to fold if let hir::ExprKind::Closure(&hir::Closure { body, .. }) = acc.kind; let closure_body = cx.tcx.hir().body(body); - let closure_expr = peel_blocks(&closure_body.value); + let closure_expr = peel_blocks(closure_body.value); // Check if the closure body is of the form `acc some_expr(x)` if let hir::ExprKind::Binary(ref bin_op, left_expr, right_expr) = closure_expr.kind; diff --git a/clippy_lints/src/methods/unnecessary_sort_by.rs b/clippy_lints/src/methods/unnecessary_sort_by.rs index 6f25acca1..ed5a75b0f 100644 --- a/clippy_lints/src/methods/unnecessary_sort_by.rs +++ b/clippy_lints/src/methods/unnecessary_sort_by.rs @@ -131,7 +131,7 @@ fn detect_lint(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, arg: &Exp ] = &closure_body.params; if let ExprKind::MethodCall(method_path, left_expr, [right_expr], _) = closure_body.value.kind; if method_path.ident.name == sym::cmp; - if is_trait_method(cx, &closure_body.value, sym::Ord); + if is_trait_method(cx, closure_body.value, sym::Ord); then { let (closure_body, closure_arg, reverse) = if mirrored_exprs( left_expr, diff --git a/clippy_lints/src/methods/unnecessary_to_owned.rs b/clippy_lints/src/methods/unnecessary_to_owned.rs index 85da97a39..763bfafec 100644 --- a/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/clippy_lints/src/methods/unnecessary_to_owned.rs @@ -1,21 +1,25 @@ use super::implicit_clone::is_clone_like; use super::unnecessary_iter_cloned::{self, is_into_iter}; +use crate::rustc_middle::ty::Subst; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::source::snippet_opt; -use clippy_utils::ty::{ - get_associated_type, get_iterator_item_ty, implements_trait, is_copy, is_type_diagnostic_item, peel_mid_ty_refs, -}; -use clippy_utils::{fn_def_id, get_parent_expr, is_diag_item_method, is_diag_trait_item}; +use clippy_utils::ty::{get_associated_type, get_iterator_item_ty, implements_trait, is_copy, peel_mid_ty_refs}; +use clippy_utils::visitors::find_all_ret_expressions; +use clippy_utils::{fn_def_id, get_parent_expr, is_diag_item_method, is_diag_trait_item, return_ty}; use clippy_utils::{meets_msrv, msrvs}; use rustc_errors::Applicability; -use rustc_hir::{def_id::DefId, BorrowKind, Expr, ExprKind}; +use rustc_hir::{def_id::DefId, BorrowKind, Expr, ExprKind, ItemKind, Node}; +use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::LateContext; use rustc_middle::mir::Mutability; use rustc_middle::ty::adjustment::{Adjust, Adjustment, OverloadedDeref}; use rustc_middle::ty::subst::{GenericArg, GenericArgKind, SubstsRef}; -use rustc_middle::ty::{self, PredicateKind, ProjectionPredicate, TraitPredicate, Ty}; +use rustc_middle::ty::EarlyBinder; +use rustc_middle::ty::{self, ParamTy, PredicateKind, ProjectionPredicate, TraitPredicate, Ty}; use rustc_semver::RustcVersion; use rustc_span::{sym, Symbol}; +use rustc_trait_selection::traits::{query::evaluate_obligation::InferCtxtExt as _, Obligation, ObligationCause}; +use rustc_typeck::check::{FnCtxt, Inherited}; use std::cmp::max; use super::UNNECESSARY_TO_OWNED; @@ -34,7 +38,7 @@ pub fn check<'tcx>( then { if is_cloned_or_copied(cx, method_name, method_def_id) { unnecessary_iter_cloned::check(cx, expr, method_name, receiver); - } else if is_to_owned_like(cx, method_name, method_def_id) { + } else if is_to_owned_like(cx, expr, method_name, method_def_id) { // At this point, we know the call is of a `to_owned`-like function. The functions // `check_addr_of_expr` and `check_call_arg` determine whether the call is unnecessary // based on its context, that is, whether it is a referent in an `AddrOf` expression, an @@ -246,17 +250,12 @@ fn check_other_call_arg<'tcx>( ) -> bool { if_chain! { if let Some((maybe_call, maybe_arg)) = skip_addr_of_ancestors(cx, expr); - if let Some((callee_def_id, call_substs, call_receiver, call_args)) = get_callee_substs_and_args(cx, maybe_call); + if let Some((callee_def_id, _, recv, call_args)) = get_callee_substs_and_args(cx, maybe_call); let fn_sig = cx.tcx.fn_sig(callee_def_id).skip_binder(); - let index = if let Some(call_receiver) = call_receiver { - std::iter::once(call_receiver).chain(call_args.iter()).position(|arg| arg.hir_id == maybe_arg.hir_id) - } else { - call_args.iter().position(|arg| arg.hir_id == maybe_arg.hir_id) - }; - if let Some(i) = index; + if let Some(i) = recv.into_iter().chain(call_args).position(|arg| arg.hir_id == maybe_arg.hir_id); if let Some(input) = fn_sig.inputs().get(i); let (input, n_refs) = peel_mid_ty_refs(*input); - if let (trait_predicates, projection_predicates) = get_input_traits_and_projections(cx, callee_def_id, input); + if let (trait_predicates, _) = get_input_traits_and_projections(cx, callee_def_id, input); if let Some(sized_def_id) = cx.tcx.lang_items().sized_trait(); if let [trait_predicate] = trait_predicates .iter() @@ -264,52 +263,13 @@ fn check_other_call_arg<'tcx>( .collect::>()[..]; if let Some(deref_trait_id) = cx.tcx.get_diagnostic_item(sym::Deref); if let Some(as_ref_trait_id) = cx.tcx.get_diagnostic_item(sym::AsRef); + if trait_predicate.def_id() == deref_trait_id || trait_predicate.def_id() == as_ref_trait_id; let receiver_ty = cx.typeck_results().expr_ty(receiver); - // If the callee has type parameters, they could appear in `projection_predicate.ty` or the - // types of `trait_predicate.trait_ref.substs`. - if if trait_predicate.def_id() == deref_trait_id { - if let [projection_predicate] = projection_predicates[..] { - let normalized_ty = - cx.tcx - .subst_and_normalize_erasing_regions(call_substs, cx.param_env, projection_predicate.term); - implements_trait(cx, receiver_ty, deref_trait_id, &[]) - && get_associated_type(cx, receiver_ty, deref_trait_id, "Target") - .map_or(false, |ty| ty::TermKind::Ty(ty) == normalized_ty.unpack()) - } else { - false - } - } else if trait_predicate.def_id() == as_ref_trait_id { - let composed_substs = compose_substs( - cx, - &trait_predicate.trait_ref.substs.iter().skip(1).collect::>()[..], - call_substs, - ); - // if `expr` is a `String` and generic target is [u8], skip - // (https://github.com/rust-lang/rust-clippy/issues/9317). - if let [subst] = composed_substs[..] - && let GenericArgKind::Type(arg_ty) = subst.unpack() - && arg_ty.is_slice() - && let inner_ty = arg_ty.builtin_index().unwrap() - && let ty::Uint(ty::UintTy::U8) = inner_ty.kind() - && let self_ty = cx.typeck_results().expr_ty(expr).peel_refs() - && is_type_diagnostic_item(cx, self_ty, sym::String) { - false - } else { - implements_trait(cx, receiver_ty, as_ref_trait_id, &composed_substs) - } - } else { - false - }; + if can_change_type(cx, maybe_arg, receiver_ty); // We can't add an `&` when the trait is `Deref` because `Target = &T` won't match // `Target = T`. if n_refs > 0 || is_copy(cx, receiver_ty) || trait_predicate.def_id() != deref_trait_id; let n_refs = max(n_refs, if is_copy(cx, receiver_ty) { 0 } else { 1 }); - // If the trait is `AsRef` and the input type variable `T` occurs in the output type, then - // `T` must not be instantiated with a reference - // (https://github.com/rust-lang/rust-clippy/issues/8507). - if (n_refs == 0 && !receiver_ty.is_ref()) - || trait_predicate.def_id() != as_ref_trait_id - || !fn_sig.output().contains(input); if let Some(receiver_snippet) = snippet_opt(cx, receiver.span); then { span_lint_and_sugg( @@ -359,11 +319,11 @@ fn get_callee_substs_and_args<'tcx>( } } if_chain! { - if let ExprKind::MethodCall(_, receiver, args, _) = expr.kind; + if let ExprKind::MethodCall(_, recv, args, _) = expr.kind; if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); then { let substs = cx.typeck_results().node_substs(expr.hir_id); - return Some((method_def_id, substs, Some(receiver), args)); + return Some((method_def_id, substs, Some(recv), args)); } } None @@ -395,22 +355,103 @@ fn get_input_traits_and_projections<'tcx>( (trait_predicates, projection_predicates) } -/// Composes two substitutions by applying the latter to the types of the former. -fn compose_substs<'tcx>( - cx: &LateContext<'tcx>, - left: &[GenericArg<'tcx>], - right: SubstsRef<'tcx>, -) -> Vec> { - left.iter() - .map(|arg| { - if let GenericArgKind::Type(arg_ty) = arg.unpack() { - let normalized_ty = cx.tcx.subst_and_normalize_erasing_regions(right, cx.param_env, arg_ty); - GenericArg::from(normalized_ty) - } else { - *arg +fn can_change_type<'a>(cx: &LateContext<'a>, mut expr: &'a Expr<'a>, mut ty: Ty<'a>) -> bool { + for (_, node) in cx.tcx.hir().parent_iter(expr.hir_id) { + match node { + Node::Stmt(_) => return true, + Node::Block(..) => continue, + Node::Item(item) => { + if let ItemKind::Fn(_, _, body_id) = &item.kind + && let output_ty = return_ty(cx, item.hir_id()) + && let local_def_id = cx.tcx.hir().local_def_id(item.hir_id()) + && Inherited::build(cx.tcx, local_def_id).enter(|inherited| { + let fn_ctxt = FnCtxt::new(&inherited, cx.param_env, item.hir_id()); + fn_ctxt.can_coerce(ty, output_ty) + }) { + if has_lifetime(output_ty) && has_lifetime(ty) { + return false; + } + let body = cx.tcx.hir().body(*body_id); + let body_expr = &body.value; + let mut count = 0; + return find_all_ret_expressions(cx, body_expr, |_| { count += 1; count <= 1 }); + } } - }) - .collect() + Node::Expr(parent_expr) => { + if let Some((callee_def_id, call_substs, recv, call_args)) = get_callee_substs_and_args(cx, parent_expr) + { + let fn_sig = cx.tcx.fn_sig(callee_def_id).skip_binder(); + if let Some(arg_index) = recv.into_iter().chain(call_args).position(|arg| arg.hir_id == expr.hir_id) + && let Some(param_ty) = fn_sig.inputs().get(arg_index) + && let ty::Param(ParamTy { index: param_index , ..}) = param_ty.kind() + { + if fn_sig + .inputs() + .iter() + .enumerate() + .filter(|(i, _)| *i != arg_index) + .any(|(_, ty)| ty.contains(*param_ty)) + { + return false; + } + + let mut trait_predicates = cx.tcx.param_env(callee_def_id) + .caller_bounds().iter().filter(|predicate| { + if let PredicateKind::Trait(trait_predicate) = predicate.kind().skip_binder() + && trait_predicate.trait_ref.self_ty() == *param_ty { + true + } else { + false + } + }); + + let new_subst = cx.tcx.mk_substs( + call_substs.iter() + .enumerate() + .map(|(i, t)| + if i == (*param_index as usize) { + GenericArg::from(ty) + } else { + t + })); + + if trait_predicates.any(|predicate| { + let predicate = EarlyBinder(predicate).subst(cx.tcx, new_subst); + let obligation = Obligation::new(ObligationCause::dummy(), cx.param_env, predicate); + !cx.tcx + .infer_ctxt() + .enter(|infcx| infcx.predicate_must_hold_modulo_regions(&obligation)) + }) { + return false; + } + + let output_ty = fn_sig.output(); + if output_ty.contains(*param_ty) { + if let Ok(new_ty) = cx.tcx.try_subst_and_normalize_erasing_regions( + new_subst, cx.param_env, output_ty) { + expr = parent_expr; + ty = new_ty; + continue; + } + return false; + } + + return true; + } + } else if let ExprKind::Block(..) = parent_expr.kind { + continue; + } + return false; + }, + _ => return false, + } + } + + false +} + +fn has_lifetime(ty: Ty<'_>) -> bool { + ty.walk().any(|t| matches!(t.unpack(), GenericArgKind::Lifetime(_))) } /// Returns true if the named method is `Iterator::cloned` or `Iterator::copied`. @@ -421,10 +462,10 @@ fn is_cloned_or_copied(cx: &LateContext<'_>, method_name: Symbol, method_def_id: /// Returns true if the named method can be used to convert the receiver to its "owned" /// representation. -fn is_to_owned_like(cx: &LateContext<'_>, method_name: Symbol, method_def_id: DefId) -> bool { +fn is_to_owned_like<'a>(cx: &LateContext<'a>, call_expr: &Expr<'a>, method_name: Symbol, method_def_id: DefId) -> bool { is_clone_like(cx, method_name.as_str(), method_def_id) || is_cow_into_owned(cx, method_name, method_def_id) - || is_to_string(cx, method_name, method_def_id) + || is_to_string_on_string_like(cx, call_expr, method_name, method_def_id) } /// Returns true if the named method is `Cow::into_owned`. @@ -432,7 +473,27 @@ fn is_cow_into_owned(cx: &LateContext<'_>, method_name: Symbol, method_def_id: D method_name.as_str() == "into_owned" && is_diag_item_method(cx, method_def_id, sym::Cow) } -/// Returns true if the named method is `ToString::to_string`. -fn is_to_string(cx: &LateContext<'_>, method_name: Symbol, method_def_id: DefId) -> bool { - method_name == sym::to_string && is_diag_trait_item(cx, method_def_id, sym::ToString) +/// Returns true if the named method is `ToString::to_string` and it's called on a type that +/// is string-like i.e. implements `AsRef` or `Deref`. +fn is_to_string_on_string_like<'a>( + cx: &LateContext<'_>, + call_expr: &'a Expr<'a>, + method_name: Symbol, + method_def_id: DefId, +) -> bool { + if method_name != sym::to_string || !is_diag_trait_item(cx, method_def_id, sym::ToString) { + return false; + } + + if let Some(substs) = cx.typeck_results().node_substs_opt(call_expr.hir_id) + && let [generic_arg] = substs.as_slice() + && let GenericArgKind::Type(ty) = generic_arg.unpack() + && let Some(deref_trait_id) = cx.tcx.get_diagnostic_item(sym::Deref) + && let Some(as_ref_trait_id) = cx.tcx.get_diagnostic_item(sym::AsRef) + && (implements_trait(cx, ty, deref_trait_id, &[cx.tcx.types.str_.into()]) || + implements_trait(cx, ty, as_ref_trait_id, &[cx.tcx.types.str_.into()])) { + true + } else { + false + } } diff --git a/clippy_lints/src/methods/unwrap_or_else_default.rs b/clippy_lints/src/methods/unwrap_or_else_default.rs index f3af281d6..045f739e6 100644 --- a/clippy_lints/src/methods/unwrap_or_else_default.rs +++ b/clippy_lints/src/methods/unwrap_or_else_default.rs @@ -5,10 +5,11 @@ use clippy_utils::{ diagnostics::span_lint_and_sugg, is_default_equivalent_call, source::snippet_with_applicability, ty::is_type_diagnostic_item, }; +use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateContext; -use rustc_span::sym; +use rustc_span::{sym, symbol}; pub(super) fn check<'tcx>( cx: &LateContext<'tcx>, @@ -25,7 +26,7 @@ pub(super) fn check<'tcx>( if_chain! { if is_option || is_result; - if is_default_equivalent_call(cx, u_arg); + if closure_body_returns_empty_to_string(cx, u_arg) || is_default_equivalent_call(cx, u_arg); then { let mut applicability = Applicability::MachineApplicable; @@ -44,3 +45,22 @@ pub(super) fn check<'tcx>( } } } + +fn closure_body_returns_empty_to_string(cx: &LateContext<'_>, e: &hir::Expr<'_>) -> bool { + if let hir::ExprKind::Closure(&hir::Closure { body, .. }) = e.kind { + let body = cx.tcx.hir().body(body); + + if body.params.is_empty() + && let hir::Expr{ kind, .. } = &body.value + && let hir::ExprKind::MethodCall(hir::PathSegment {ident, ..}, self_arg, _, _) = kind + && ident == &symbol::Ident::from_str("to_string") + && let hir::Expr{ kind, .. } = self_arg + && let hir::ExprKind::Lit(lit) = kind + && let LitKind::Str(symbol::kw::Empty, _) = lit.node + { + return true; + } + } + + false +} diff --git a/clippy_lints/src/minmax.rs b/clippy_lints/src/minmax.rs index 44b21e7b0..4d8579135 100644 --- a/clippy_lints/src/minmax.rs +++ b/clippy_lints/src/minmax.rs @@ -1,7 +1,6 @@ use clippy_utils::consts::{constant_simple, Constant}; use clippy_utils::diagnostics::span_lint; use clippy_utils::{match_trait_method, paths}; -use if_chain::if_chain; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; @@ -84,19 +83,16 @@ fn min_max<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<(MinMax, Cons } }, ExprKind::MethodCall(path, receiver, args @ [_], _) => { - if_chain! { - if cx.typeck_results().expr_ty(receiver).is_floating_point() || match_trait_method(cx, expr, &paths::ORD); - then { - if path.ident.name == sym!(max) { - fetch_const(cx, Some(receiver), args, MinMax::Max) - } else if path.ident.name == sym!(min) { - fetch_const(cx, Some(receiver), args, MinMax::Min) - } else { - None - } + if cx.typeck_results().expr_ty(receiver).is_floating_point() || match_trait_method(cx, expr, &paths::ORD) { + if path.ident.name == sym!(max) { + fetch_const(cx, Some(receiver), args, MinMax::Max) + } else if path.ident.name == sym!(min) { + fetch_const(cx, Some(receiver), args, MinMax::Min) } else { None } + } else { + None } }, _ => None, @@ -109,18 +105,18 @@ fn fetch_const<'a>( args: &'a [Expr<'a>], m: MinMax, ) -> Option<(MinMax, Constant, &'a Expr<'a>)> { - let mut args = receiver.into_iter().chain(args.into_iter()); - let arg0 = args.next()?; - let arg1 = args.next()?; + let mut args = receiver.into_iter().chain(args); + let first_arg = args.next()?; + let second_arg = args.next()?; if args.next().is_some() { return None; } - constant_simple(cx, cx.typeck_results(), arg0).map_or_else( - || constant_simple(cx, cx.typeck_results(), arg1).map(|c| (m, c, arg0)), + constant_simple(cx, cx.typeck_results(), first_arg).map_or_else( + || constant_simple(cx, cx.typeck_results(), second_arg).map(|c| (m, c, first_arg)), |c| { - if constant_simple(cx, cx.typeck_results(), arg1).is_none() { + if constant_simple(cx, cx.typeck_results(), second_arg).is_none() { // otherwise ignore - Some((m, c, arg1)) + Some((m, c, second_arg)) } else { None } diff --git a/clippy_lints/src/needless_for_each.rs b/clippy_lints/src/needless_for_each.rs index f8cc3fbb3..3233d87c0 100644 --- a/clippy_lints/src/needless_for_each.rs +++ b/clippy_lints/src/needless_for_each.rs @@ -77,7 +77,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessForEach { if let ExprKind::Block(..) = body.value.kind; then { let mut ret_collector = RetCollector::default(); - ret_collector.visit_expr(&body.value); + ret_collector.visit_expr(body.value); // Skip the lint if `return` is used in `Loop` in order not to suggest using `'label`. if ret_collector.ret_in_loop { diff --git a/clippy_lints/src/only_used_in_recursion.rs b/clippy_lints/src/only_used_in_recursion.rs index 17d5fa215..6217110a1 100644 --- a/clippy_lints/src/only_used_in_recursion.rs +++ b/clippy_lints/src/only_used_in_recursion.rs @@ -12,6 +12,7 @@ use rustc_middle::ty::{self, ConstKind}; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::symbol::{kw, Ident}; use rustc_span::Span; +use std::iter; declare_clippy_lint! { /// ### What it does @@ -234,11 +235,7 @@ impl<'tcx> LateLintPass<'tcx> for OnlyUsedInRecursion { })) => ( def_id.to_def_id(), FnKind::TraitFn, - if sig.decl.implicit_self.has_implicit_self() { - 1 - } else { - 0 - }, + usize::from(sig.decl.implicit_self.has_implicit_self()), ), Some(Node::ImplItem(&ImplItem { kind: ImplItemKind::Fn(ref sig, _), @@ -253,11 +250,7 @@ impl<'tcx> LateLintPass<'tcx> for OnlyUsedInRecursion { ( trait_item_id, FnKind::ImplTraitFn(cx.tcx.erase_regions(trait_ref.substs) as *const _ as usize), - if sig.decl.implicit_self.has_implicit_self() { - 1 - } else { - 0 - }, + usize::from(sig.decl.implicit_self.has_implicit_self()), ) } else { (def_id.to_def_id(), FnKind::Fn, 0) @@ -310,7 +303,7 @@ impl<'tcx> LateLintPass<'tcx> for OnlyUsedInRecursion { && has_matching_substs(param.fn_kind, typeck.node_substs(parent.hir_id)) }) => { - if let Some(idx) = std::iter::once(receiver).chain(args.iter()).position(|arg| arg.hir_id == child_id) { + if let Some(idx) = iter::once(receiver).chain(args).position(|arg| arg.hir_id == child_id) { param.uses.push(Usage::new(span, idx)); } return; diff --git a/clippy_lints/src/operators/arithmetic.rs b/clippy_lints/src/operators/arithmetic.rs deleted file mode 100644 index 800cf249f..000000000 --- a/clippy_lints/src/operators/arithmetic.rs +++ /dev/null @@ -1,119 +0,0 @@ -#![allow( - // False positive - clippy::match_same_arms -)] - -use super::ARITHMETIC; -use clippy_utils::{consts::constant_simple, diagnostics::span_lint}; -use rustc_data_structures::fx::FxHashSet; -use rustc_hir as hir; -use rustc_lint::{LateContext, LateLintPass}; -use rustc_session::impl_lint_pass; -use rustc_span::source_map::Span; - -const HARD_CODED_ALLOWED: &[&str] = &["std::num::Saturating", "std::string::String", "std::num::Wrapping"]; - -#[derive(Debug)] -pub struct Arithmetic { - allowed: FxHashSet, - // Used to check whether expressions are constants, such as in enum discriminants and consts - const_span: Option, - expr_span: Option, -} - -impl_lint_pass!(Arithmetic => [ARITHMETIC]); - -impl Arithmetic { - #[must_use] - pub fn new(mut allowed: FxHashSet) -> Self { - allowed.extend(HARD_CODED_ALLOWED.iter().copied().map(String::from)); - Self { - allowed, - const_span: None, - expr_span: None, - } - } - - /// Checks if the given `expr` has any of the inner `allowed` elements. - fn is_allowed_ty(&self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool { - self.allowed.contains( - cx.typeck_results() - .expr_ty(expr) - .to_string() - .split('<') - .next() - .unwrap_or_default(), - ) - } - - fn issue_lint(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) { - span_lint(cx, ARITHMETIC, expr.span, "arithmetic detected"); - self.expr_span = Some(expr.span); - } -} - -impl<'tcx> LateLintPass<'tcx> for Arithmetic { - fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { - if self.expr_span.is_some() { - return; - } - if let Some(span) = self.const_span && span.contains(expr.span) { - return; - } - match &expr.kind { - hir::ExprKind::Binary(op, lhs, rhs) | hir::ExprKind::AssignOp(op, lhs, rhs) => { - let ( - hir::BinOpKind::Add - | hir::BinOpKind::Sub - | hir::BinOpKind::Mul - | hir::BinOpKind::Div - | hir::BinOpKind::Rem - | hir::BinOpKind::Shl - | hir::BinOpKind::Shr - ) = op.node else { - return; - }; - if self.is_allowed_ty(cx, lhs) || self.is_allowed_ty(cx, rhs) { - return; - } - self.issue_lint(cx, expr); - }, - hir::ExprKind::Unary(hir::UnOp::Neg, _) => { - // CTFE already takes care of things like `-1` that do not overflow. - if constant_simple(cx, cx.typeck_results(), expr).is_none() { - self.issue_lint(cx, expr); - } - }, - _ => {}, - } - } - - fn check_body(&mut self, cx: &LateContext<'_>, body: &hir::Body<'_>) { - let body_owner = cx.tcx.hir().body_owner_def_id(body.id()); - match cx.tcx.hir().body_owner_kind(body_owner) { - hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => { - let body_span = cx.tcx.def_span(body_owner); - if let Some(span) = self.const_span && span.contains(body_span) { - return; - } - self.const_span = Some(body_span); - }, - hir::BodyOwnerKind::Closure | hir::BodyOwnerKind::Fn => {}, - } - } - - fn check_body_post(&mut self, cx: &LateContext<'_>, body: &hir::Body<'_>) { - let body_owner = cx.tcx.hir().body_owner(body.id()); - let body_span = cx.tcx.hir().span(body_owner); - if let Some(span) = self.const_span && span.contains(body_span) { - return; - } - self.const_span = None; - } - - fn check_expr_post(&mut self, _: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { - if Some(expr.span) == self.expr_span { - self.expr_span = None; - } - } -} diff --git a/clippy_lints/src/operators/arithmetic_side_effects.rs b/clippy_lints/src/operators/arithmetic_side_effects.rs new file mode 100644 index 000000000..83b69fbb3 --- /dev/null +++ b/clippy_lints/src/operators/arithmetic_side_effects.rs @@ -0,0 +1,173 @@ +#![allow( + // False positive + clippy::match_same_arms +)] + +use super::ARITHMETIC_SIDE_EFFECTS; +use clippy_utils::{consts::constant_simple, diagnostics::span_lint}; +use rustc_ast as ast; +use rustc_data_structures::fx::FxHashSet; +use rustc_hir as hir; +use rustc_lint::{LateContext, LateLintPass}; +use rustc_middle::ty::Ty; +use rustc_session::impl_lint_pass; +use rustc_span::source_map::{Span, Spanned}; + +const HARD_CODED_ALLOWED: &[&str] = &[ + "f32", + "f64", + "std::num::Saturating", + "std::string::String", + "std::num::Wrapping", +]; + +#[derive(Debug)] +pub struct ArithmeticSideEffects { + allowed: FxHashSet, + // Used to check whether expressions are constants, such as in enum discriminants and consts + const_span: Option, + expr_span: Option, +} + +impl_lint_pass!(ArithmeticSideEffects => [ARITHMETIC_SIDE_EFFECTS]); + +impl ArithmeticSideEffects { + #[must_use] + pub fn new(mut allowed: FxHashSet) -> Self { + allowed.extend(HARD_CODED_ALLOWED.iter().copied().map(String::from)); + Self { + allowed, + const_span: None, + expr_span: None, + } + } + + /// Checks assign operators (+=, -=, *=, /=) of integers in a non-constant environment that + /// won't overflow. + fn has_valid_assign_op(op: &Spanned, rhs: &hir::Expr<'_>, rhs_refs: Ty<'_>) -> bool { + if !Self::is_literal_integer(rhs, rhs_refs) { + return false; + } + if let hir::BinOpKind::Div | hir::BinOpKind::Mul = op.node + && let hir::ExprKind::Lit(ref lit) = rhs.kind + && let ast::LitKind::Int(1, _) = lit.node + { + return true; + } + false + } + + /// Checks "raw" binary operators (+, -, *, /) of integers in a non-constant environment + /// already handled by the CTFE. + fn has_valid_bin_op(lhs: &hir::Expr<'_>, lhs_refs: Ty<'_>, rhs: &hir::Expr<'_>, rhs_refs: Ty<'_>) -> bool { + Self::is_literal_integer(lhs, lhs_refs) && Self::is_literal_integer(rhs, rhs_refs) + } + + /// Checks if the given `expr` has any of the inner `allowed` elements. + fn is_allowed_ty(&self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool { + self.allowed.contains( + cx.typeck_results() + .expr_ty(expr) + .to_string() + .split('<') + .next() + .unwrap_or_default(), + ) + } + + /// Explicit integers like `1` or `i32::MAX`. Does not take into consideration references. + fn is_literal_integer(expr: &hir::Expr<'_>, expr_refs: Ty<'_>) -> bool { + let is_integral = expr_refs.is_integral(); + let is_literal = matches!(expr.kind, hir::ExprKind::Lit(_)); + is_integral && is_literal + } + + fn issue_lint(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) { + span_lint(cx, ARITHMETIC_SIDE_EFFECTS, expr.span, "arithmetic detected"); + self.expr_span = Some(expr.span); + } + + /// Manages when the lint should be triggered. Operations in constant environments, hard coded + /// types, custom allowed types and non-constant operations that won't overflow are ignored. + fn manage_bin_ops( + &mut self, + cx: &LateContext<'_>, + expr: &hir::Expr<'_>, + op: &Spanned, + lhs: &hir::Expr<'_>, + rhs: &hir::Expr<'_>, + ) { + if constant_simple(cx, cx.typeck_results(), expr).is_some() { + return; + } + if !matches!( + op.node, + hir::BinOpKind::Add + | hir::BinOpKind::Sub + | hir::BinOpKind::Mul + | hir::BinOpKind::Div + | hir::BinOpKind::Rem + | hir::BinOpKind::Shl + | hir::BinOpKind::Shr + ) { + return; + }; + if self.is_allowed_ty(cx, lhs) || self.is_allowed_ty(cx, rhs) { + return; + } + let lhs_refs = cx.typeck_results().expr_ty(lhs).peel_refs(); + let rhs_refs = cx.typeck_results().expr_ty(rhs).peel_refs(); + let has_valid_assign_op = Self::has_valid_assign_op(op, rhs, rhs_refs); + if has_valid_assign_op || Self::has_valid_bin_op(lhs, lhs_refs, rhs, rhs_refs) { + return; + } + self.issue_lint(cx, expr); + } +} + +impl<'tcx> LateLintPass<'tcx> for ArithmeticSideEffects { + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { + if self.expr_span.is_some() || self.const_span.map_or(false, |sp| sp.contains(expr.span)) { + return; + } + match &expr.kind { + hir::ExprKind::Binary(op, lhs, rhs) | hir::ExprKind::AssignOp(op, lhs, rhs) => { + self.manage_bin_ops(cx, expr, op, lhs, rhs); + }, + hir::ExprKind::Unary(hir::UnOp::Neg, _) => { + if constant_simple(cx, cx.typeck_results(), expr).is_none() { + self.issue_lint(cx, expr); + } + }, + _ => {}, + } + } + + fn check_body(&mut self, cx: &LateContext<'_>, body: &hir::Body<'_>) { + let body_owner = cx.tcx.hir().body_owner(body.id()); + let body_owner_def_id = cx.tcx.hir().local_def_id(body_owner); + let body_owner_kind = cx.tcx.hir().body_owner_kind(body_owner_def_id); + if let hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) = body_owner_kind { + let body_span = cx.tcx.hir().span_with_body(body_owner); + if let Some(span) = self.const_span && span.contains(body_span) { + return; + } + self.const_span = Some(body_span); + } + } + + fn check_body_post(&mut self, cx: &LateContext<'_>, body: &hir::Body<'_>) { + let body_owner = cx.tcx.hir().body_owner(body.id()); + let body_span = cx.tcx.hir().span(body_owner); + if let Some(span) = self.const_span && span.contains(body_span) { + return; + } + self.const_span = None; + } + + fn check_expr_post(&mut self, _: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { + if Some(expr.span) == self.expr_span { + self.expr_span = None; + } + } +} diff --git a/clippy_lints/src/operators/mod.rs b/clippy_lints/src/operators/mod.rs index bb6d99406..c32b4df4f 100644 --- a/clippy_lints/src/operators/mod.rs +++ b/clippy_lints/src/operators/mod.rs @@ -21,7 +21,7 @@ mod ptr_eq; mod self_assignment; mod verbose_bit_mask; -pub(crate) mod arithmetic; +pub(crate) mod arithmetic_side_effects; use rustc_hir::{Body, Expr, ExprKind, UnOp}; use rustc_lint::{LateContext, LateLintPass}; @@ -61,25 +61,29 @@ declare_clippy_lint! { declare_clippy_lint! { /// ### What it does - /// Checks for any kind of arithmetic operation of any type. + /// Checks any kind of arithmetic operation of any type. /// /// Operators like `+`, `-`, `*` or `<<` are usually capable of overflowing according to the [Rust /// Reference](https://doc.rust-lang.org/reference/expressions/operator-expr.html#overflow), - /// or can panic (`/`, `%`). Known safe built-in types like `Wrapping` or `Saturing` are filtered - /// away. + /// or can panic (`/`, `%`). + /// + /// Known safe built-in types like `Wrapping` or `Saturing`, floats, operations in constant + /// environments, allowed types and non-constant operations that won't overflow are ignored. /// /// ### Why is this bad? - /// Integer overflow will trigger a panic in debug builds or will wrap in - /// release mode. Division by zero will cause a panic in either mode. In some applications one - /// wants explicitly checked, wrapping or saturating arithmetic. + /// For integers, overflow will trigger a panic in debug builds or wrap the result in + /// release mode; division by zero will cause a panic in either mode. As a result, it is + /// desirable to explicitly call checked, wrapping or saturating arithmetic methods. /// /// #### Example /// ```rust - /// # let a = 0; - /// a + 1; + /// // `n` can be any number, including `i32::MAX`. + /// fn foo(n: i32) -> i32 { + /// n + 1 + /// } /// ``` /// - /// Third-party types also tend to overflow. + /// Third-party types can also overflow or present unwanted side-effects. /// /// #### Example /// ```ignore,rust @@ -88,11 +92,11 @@ declare_clippy_lint! { /// ``` /// /// ### Allowed types - /// Custom allowed types can be specified through the "arithmetic-allowed" filter. + /// Custom allowed types can be specified through the "arithmetic-side-effects-allowed" filter. #[clippy::version = "1.64.0"] - pub ARITHMETIC, + pub ARITHMETIC_SIDE_EFFECTS, restriction, - "any arithmetic expression that could overflow or panic" + "any arithmetic expression that can cause side effects like overflows or panics" } declare_clippy_lint! { @@ -785,7 +789,7 @@ pub struct Operators { } impl_lint_pass!(Operators => [ ABSURD_EXTREME_COMPARISONS, - ARITHMETIC, + ARITHMETIC_SIDE_EFFECTS, INTEGER_ARITHMETIC, FLOAT_ARITHMETIC, ASSIGN_OP_PATTERN, diff --git a/clippy_lints/src/panic_in_result_fn.rs b/clippy_lints/src/panic_in_result_fn.rs index 21acf003d..4aa0d9227 100644 --- a/clippy_lints/src/panic_in_result_fn.rs +++ b/clippy_lints/src/panic_in_result_fn.rs @@ -69,7 +69,7 @@ fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, body: &'tcx hir } true }) - .visit_expr(&body.value); + .visit_expr(body.value); if !panics.is_empty() { span_lint_and_then( cx, diff --git a/clippy_lints/src/ptr.rs b/clippy_lints/src/ptr.rs index 0028e0bc6..41d1baba6 100644 --- a/clippy_lints/src/ptr.rs +++ b/clippy_lints/src/ptr.rs @@ -507,7 +507,7 @@ fn check_mut_from_ref<'tcx>(cx: &LateContext<'tcx>, sig: &FnSig<'_>, body: Optio if let Some(args) = args && !args.is_empty() && body.map_or(true, |body| { - sig.header.unsafety == Unsafety::Unsafe || contains_unsafe_block(cx, &body.value) + sig.header.unsafety == Unsafety::Unsafe || contains_unsafe_block(cx, body.value) }) { span_lint_and_then( @@ -664,7 +664,7 @@ fn check_ptr_arg_usage<'tcx>(cx: &LateContext<'tcx>, body: &'tcx Body<'_>, args: results, skip_count, }; - v.visit_expr(&body.value); + v.visit_expr(body.value); v.results } diff --git a/clippy_lints/src/ranges.rs b/clippy_lints/src/ranges.rs index 490f345d2..918d624ee 100644 --- a/clippy_lints/src/ranges.rs +++ b/clippy_lints/src/ranges.rs @@ -350,6 +350,7 @@ fn check_range_bounds<'a>(cx: &'a LateContext<'_>, ex: &'a Expr<'_>) -> Option, expr: &Expr<'_>) { if_chain! { + if expr.span.can_be_used_for_suggestions(); if let Some(higher::Range { start, end: Some(end), @@ -357,14 +358,7 @@ fn check_exclusive_range_plus_one(cx: &LateContext<'_>, expr: &Expr<'_>) { }) = higher::Range::hir(expr); if let Some(y) = y_plus_one(cx, end); then { - let span = if expr.span.from_expansion() { - expr.span - .ctxt() - .outer_expn_data() - .call_site - } else { - expr.span - }; + let span = expr.span; span_lint_and_then( cx, RANGE_PLUS_ONE, @@ -399,6 +393,7 @@ fn check_exclusive_range_plus_one(cx: &LateContext<'_>, expr: &Expr<'_>) { // inclusive range minus one: `x..=(y-1)` fn check_inclusive_range_minus_one(cx: &LateContext<'_>, expr: &Expr<'_>) { if_chain! { + if expr.span.can_be_used_for_suggestions(); if let Some(higher::Range { start, end: Some(end), limits: RangeLimits::Closed }) = higher::Range::hir(expr); if let Some(y) = y_minus_one(cx, end); then { diff --git a/clippy_lints/src/returns.rs b/clippy_lints/src/returns.rs index 1926661c5..91553240e 100644 --- a/clippy_lints/src/returns.rs +++ b/clippy_lints/src/returns.rs @@ -139,7 +139,7 @@ impl<'tcx> LateLintPass<'tcx> for Return { } else { RetReplacement::Empty }; - check_final_expr(cx, &body.value, Some(body.value.span), replacement); + check_final_expr(cx, body.value, Some(body.value.span), replacement); }, FnKind::ItemFn(..) | FnKind::Method(..) => { if let ExprKind::Block(block, _) = body.value.kind { diff --git a/clippy_lints/src/suspicious_trait_impl.rs b/clippy_lints/src/suspicious_trait_impl.rs index 4294464db..6add20c1f 100644 --- a/clippy_lints/src/suspicious_trait_impl.rs +++ b/clippy_lints/src/suspicious_trait_impl.rs @@ -78,7 +78,7 @@ impl<'tcx> LateLintPass<'tcx> for SuspiciousImpl { ] .iter() .find(|&(ts, _)| ts.iter().any(|&t| Ok(trait_id) == cx.tcx.lang_items().require(t))); - if count_binops(&body.value) == 1; + if count_binops(body.value) == 1; then { span_lint( cx, diff --git a/clippy_lints/src/unit_return_expecting_ord.rs b/clippy_lints/src/unit_return_expecting_ord.rs index 851eef7b3..c0a4f3fba 100644 --- a/clippy_lints/src/unit_return_expecting_ord.rs +++ b/clippy_lints/src/unit_return_expecting_ord.rs @@ -149,7 +149,7 @@ impl<'tcx> LateLintPass<'tcx> for UnitReturnExpectingOrd { let args = std::iter::once(receiver).chain(args.iter()).collect::>(); for (i, trait_name) in arg_indices { if i < args.len() { - match check_arg(cx, &args[i]) { + match check_arg(cx, args[i]) { Some((span, None)) => { span_lint( cx, diff --git a/clippy_lints/src/unit_types/unit_arg.rs b/clippy_lints/src/unit_types/unit_arg.rs index 7ffb53dcf..a6f777abc 100644 --- a/clippy_lints/src/unit_types/unit_arg.rs +++ b/clippy_lints/src/unit_types/unit_arg.rs @@ -50,7 +50,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { }) .collect::>(); if !args_to_recover.is_empty() && !is_from_proc_macro(cx, expr) { - lint_unit_args(cx, expr, &args_to_recover.as_slice()); + lint_unit_args(cx, expr, args_to_recover.as_slice()); } } diff --git a/clippy_lints/src/unnecessary_wraps.rs b/clippy_lints/src/unnecessary_wraps.rs index a5afbb8ff..2c40827db 100644 --- a/clippy_lints/src/unnecessary_wraps.rs +++ b/clippy_lints/src/unnecessary_wraps.rs @@ -115,7 +115,7 @@ impl<'tcx> LateLintPass<'tcx> for UnnecessaryWraps { // Check if all return expression respect the following condition and collect them. let mut suggs = Vec::new(); - let can_sugg = find_all_ret_expressions(cx, &body.value, |ret_expr| { + let can_sugg = find_all_ret_expressions(cx, body.value, |ret_expr| { if_chain! { if !ret_expr.span.from_expansion(); // Check if a function call. diff --git a/clippy_lints/src/unwrap.rs b/clippy_lints/src/unwrap.rs index 9092156be..7e451b7b7 100644 --- a/clippy_lints/src/unwrap.rs +++ b/clippy_lints/src/unwrap.rs @@ -160,7 +160,7 @@ fn collect_unwrap_info<'tcx>( let name = method_name.ident.as_str(); if is_relevant_option_call(cx, ty, name) || is_relevant_result_call(cx, ty, name); then { - assert!(args.len() == 0); + assert!(args.is_empty()); let unwrappable = match name { "is_some" | "is_ok" => true, "is_err" | "is_none" => false, diff --git a/clippy_lints/src/unwrap_in_result.rs b/clippy_lints/src/unwrap_in_result.rs index b3ca15f76..46020adca 100644 --- a/clippy_lints/src/unwrap_in_result.rs +++ b/clippy_lints/src/unwrap_in_result.rs @@ -83,7 +83,7 @@ impl<'a, 'tcx> Visitor<'tcx> for FindExpectUnwrap<'a, 'tcx> { fn visit_expr(&mut self, expr: &'tcx Expr<'_>) { // check for `expect` if let Some(arglists) = method_chain_args(expr, &["expect"]) { - let receiver_ty = self.typeck_results.expr_ty(&arglists[0].0).peel_refs(); + let receiver_ty = self.typeck_results.expr_ty(arglists[0].0).peel_refs(); if is_type_diagnostic_item(self.lcx, receiver_ty, sym::Option) || is_type_diagnostic_item(self.lcx, receiver_ty, sym::Result) { @@ -93,7 +93,7 @@ impl<'a, 'tcx> Visitor<'tcx> for FindExpectUnwrap<'a, 'tcx> { // check for `unwrap` if let Some(arglists) = method_chain_args(expr, &["unwrap"]) { - let receiver_ty = self.typeck_results.expr_ty(&arglists[0].0).peel_refs(); + let receiver_ty = self.typeck_results.expr_ty(arglists[0].0).peel_refs(); if is_type_diagnostic_item(self.lcx, receiver_ty, sym::Option) || is_type_diagnostic_item(self.lcx, receiver_ty, sym::Result) { @@ -114,7 +114,7 @@ fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_item: &'tc typeck_results: cx.tcx.typeck(impl_item.def_id), result: Vec::new(), }; - fpu.visit_expr(&body.value); + fpu.visit_expr(body.value); // if we've found one, lint if !fpu.result.is_empty() { diff --git a/clippy_lints/src/utils/author.rs b/clippy_lints/src/utils/author.rs index 1489c96d9..4003fff27 100644 --- a/clippy_lints/src/utils/author.rs +++ b/clippy_lints/src/utils/author.rs @@ -142,7 +142,7 @@ fn check_item(cx: &LateContext<'_>, hir_id: HirId) { let hir = cx.tcx.hir(); if let Some(body_id) = hir.maybe_body_owned_by(hir_id.expect_owner()) { check_node(cx, hir_id, |v| { - v.expr(&v.bind("expr", &hir.body(body_id).value)); + v.expr(&v.bind("expr", hir.body(body_id).value)); }); } } diff --git a/clippy_lints/src/utils/conf.rs b/clippy_lints/src/utils/conf.rs index 84e65d5fa..a8500beb2 100644 --- a/clippy_lints/src/utils/conf.rs +++ b/clippy_lints/src/utils/conf.rs @@ -208,7 +208,7 @@ define_Conf! { /// Lint: Arithmetic. /// /// Suppress checking of the passed type names. - (arithmetic_allowed: rustc_data_structures::fx::FxHashSet = <_>::default()), + (arithmetic_side_effects_allowed: rustc_data_structures::fx::FxHashSet = <_>::default()), /// Lint: ENUM_VARIANT_NAMES, LARGE_TYPES_PASSED_BY_VALUE, TRIVIALLY_COPY_PASS_BY_REF, UNNECESSARY_WRAPS, UNUSED_SELF, UPPER_CASE_ACRONYMS, WRONG_SELF_CONVENTION, BOX_COLLECTION, REDUNDANT_ALLOCATION, RC_BUFFER, VEC_BOX, OPTION_OPTION, LINKEDLIST, RC_MUTEX. /// /// Suppress lints whenever the suggested change would cause breakage for other crates. diff --git a/clippy_lints/src/utils/internal_lints.rs b/clippy_lints/src/utils/internal_lints.rs index ae1c11ef8..17d9a0418 100644 --- a/clippy_lints/src/utils/internal_lints.rs +++ b/clippy_lints/src/utils/internal_lints.rs @@ -505,7 +505,7 @@ impl<'tcx> LateLintPass<'tcx> for LintWithoutLintPass { .hir_id(), ), ); - collector.visit_expr(&cx.tcx.hir().body(body_id).value); + collector.visit_expr(cx.tcx.hir().body(body_id).value); } } } @@ -653,7 +653,7 @@ impl<'tcx> LateLintPass<'tcx> for CompilerLintFunctions { } if_chain! { - if let ExprKind::MethodCall(path, [self_arg, ..], _) = &expr.kind; + if let ExprKind::MethodCall(path, self_arg, _, _) = &expr.kind; let fn_name = path.ident; if let Some(sugg) = self.map.get(fn_name.as_str()); let ty = cx.typeck_results().expr_ty(self_arg).peel_refs(); @@ -685,9 +685,8 @@ impl<'tcx> LateLintPass<'tcx> for OuterExpnDataPass { let method_names: Vec<&str> = method_names.iter().map(Symbol::as_str).collect(); if_chain! { if let ["expn_data", "outer_expn"] = method_names.as_slice(); - let args = arg_lists[1]; - if args.len() == 1; - let self_arg = &args.0; + let (self_arg, args)= arg_lists[1]; + if args.is_empty(); let self_ty = cx.typeck_results().expr_ty(self_arg).peel_refs(); if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT); then { @@ -734,30 +733,30 @@ impl<'tcx> LateLintPass<'tcx> for CollapsibleCalls { if and_then_args.len() == 5; if let ExprKind::Closure(&Closure { body, .. }) = &and_then_args[4].kind; let body = cx.tcx.hir().body(body); - let only_expr = peel_blocks_with_stmt(&body.value); - if let ExprKind::MethodCall(ps, span_call_args, _) = &only_expr.kind; - if let ExprKind::Path(..) = span_call_args[0].kind; + let only_expr = peel_blocks_with_stmt(body.value); + if let ExprKind::MethodCall(ps, recv, span_call_args, _) = &only_expr.kind; + if let ExprKind::Path(..) = recv.kind; then { let and_then_snippets = get_and_then_snippets(cx, and_then_args); let mut sle = SpanlessEq::new(cx).deny_side_effects(); match ps.ident.as_str() { - "span_suggestion" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => { + "span_suggestion" if sle.eq_expr(&and_then_args[2], &span_call_args[0]) => { suggest_suggestion(cx, expr, &and_then_snippets, &span_suggestion_snippets(cx, span_call_args)); }, - "span_help" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => { - let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#); + "span_help" if sle.eq_expr(&and_then_args[2], &span_call_args[0]) => { + let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#); suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), true); }, - "span_note" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => { - let note_snippet = snippet(cx, span_call_args[2].span, r#""...""#); + "span_note" if sle.eq_expr(&and_then_args[2], &span_call_args[0]) => { + let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#); suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), true); }, "help" => { - let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#); + let help_snippet = snippet(cx, span_call_args[0].span, r#""...""#); suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), false); } "note" => { - let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#); + let note_snippet = snippet(cx, span_call_args[0].span, r#""...""#); suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), false); } _ => (), @@ -798,9 +797,9 @@ fn span_suggestion_snippets<'a, 'hir>( cx: &LateContext<'_>, span_call_args: &'hir [Expr<'hir>], ) -> SpanSuggestionSnippets<'a> { - let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#); - let sugg_snippet = snippet(cx, span_call_args[3].span, ".."); - let applicability_snippet = snippet(cx, span_call_args[4].span, "Applicability::MachineApplicable"); + let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#); + let sugg_snippet = snippet(cx, span_call_args[2].span, ".."); + let applicability_snippet = snippet(cx, span_call_args[3].span, "Applicability::MachineApplicable"); SpanSuggestionSnippets { help: help_snippet, @@ -954,7 +953,7 @@ fn path_to_matched_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option LateLintPass<'tcx> for InvalidPaths { if el_ty.is_str(); let body = cx.tcx.hir().body(body_id); let typeck_results = cx.tcx.typeck_body(body_id); - if let Some(Constant::Vec(path)) = constant_simple(cx, typeck_results, &body.value); + if let Some(Constant::Vec(path)) = constant_simple(cx, typeck_results, body.value); let path: Vec<&str> = path.iter().map(|x| { if let Constant::Str(s) = x { s.as_str() @@ -1177,7 +1176,7 @@ impl InterningDefinedSymbol { }; if_chain! { // is a method call - if let ExprKind::MethodCall(_, [item], _) = call.kind; + if let ExprKind::MethodCall(_, item, [], _) = call.kind; if let Some(did) = cx.typeck_results().type_dependent_def_id(call.hir_id); let ty = cx.typeck_results().expr_ty(item); // ...on either an Ident or a Symbol diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs index b1148bccc..342f627e3 100644 --- a/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -1145,8 +1145,8 @@ impl<'a, 'hir> intravisit::Visitor<'hir> for IsMultiSpanScanner<'a, 'hir> { self.add_single_span_suggestion(); } }, - ExprKind::MethodCall(path, arg, _arg_span) => { - let (self_ty, _) = walk_ptrs_ty_depth(self.cx.typeck_results().expr_ty(&arg[0])); + ExprKind::MethodCall(path, recv, _, _arg_span) => { + let (self_ty, _) = walk_ptrs_ty_depth(self.cx.typeck_results().expr_ty(recv)); if match_type(self.cx, self_ty, &paths::DIAGNOSTIC_BUILDER) { let called_method = path.ident.name.as_str().to_string(); for (method_name, is_multi_part) in &SUGGESTION_DIAGNOSTIC_BUILDER_METHODS { diff --git a/clippy_lints/src/vec_init_then_push.rs b/clippy_lints/src/vec_init_then_push.rs index 8425837fd..bd5be0c9d 100644 --- a/clippy_lints/src/vec_init_then_push.rs +++ b/clippy_lints/src/vec_init_then_push.rs @@ -86,7 +86,7 @@ impl VecPushSearcher { }, ExprKind::Unary(UnOp::Deref, _) | ExprKind::Index(..) if !needs_mut => { let mut last_place = parent; - while let Some(parent) = get_parent_expr(cx, parent) { + while let Some(parent) = get_parent_expr(cx, last_place) { if matches!(parent.kind, ExprKind::Unary(UnOp::Deref, _) | ExprKind::Field(..)) || matches!(parent.kind, ExprKind::Index(e, _) if e.hir_id == last_place.hir_id) { diff --git a/clippy_lints/src/write.rs b/clippy_lints/src/write.rs index 347165d97..640a09a7a 100644 --- a/clippy_lints/src/write.rs +++ b/clippy_lints/src/write.rs @@ -805,7 +805,11 @@ fn check_newlines(fmtstr: &StrLit) -> bool { let contents = fmtstr.symbol.as_str(); let mut cb = |r: Range, c: Result| { - let c = c.unwrap(); + let c = match c { + Ok(c) => c, + Err(e) if !e.is_fatal() => return, + Err(e) => panic!("{:?}", e), + }; if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline { should_lint = true; diff --git a/clippy_utils/src/check_proc_macro.rs b/clippy_utils/src/check_proc_macro.rs index e8d2d579f..7a8d4e806 100644 --- a/clippy_utils/src/check_proc_macro.rs +++ b/clippy_utils/src/check_proc_macro.rs @@ -140,7 +140,7 @@ fn expr_search_pat(tcx: TyCtxt<'_>, e: &Expr<'_>) -> (Pat, Pat) { ExprKind::Match(e, _, MatchSource::AwaitDesugar) | ExprKind::Yield(e, YieldSource::Await { .. }) => { (expr_search_pat(tcx, e).0, Pat::Str("await")) }, - ExprKind::Closure(&Closure { body, .. }) => (Pat::Str(""), expr_search_pat(tcx, &tcx.hir().body(body).value).1), + ExprKind::Closure(&Closure { body, .. }) => (Pat::Str(""), expr_search_pat(tcx, tcx.hir().body(body).value).1), ExprKind::Block( Block { rules: BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided), @@ -254,7 +254,7 @@ fn fn_kind_pat(tcx: TyCtxt<'_>, kind: &FnKind<'_>, body: &Body<'_>, hir_id: HirI let (start_pat, end_pat) = match kind { FnKind::ItemFn(.., header) => (fn_header_search_pat(*header), Pat::Str("")), FnKind::Method(.., sig) => (fn_header_search_pat(sig.header), Pat::Str("")), - FnKind::Closure => return (Pat::Str(""), expr_search_pat(tcx, &body.value).1), + FnKind::Closure => return (Pat::Str(""), expr_search_pat(tcx, body.value).1), }; let start_pat = match tcx.hir().get(hir_id) { Node::Item(Item { vis_span, .. }) | Node::ImplItem(ImplItem { vis_span, .. }) => { diff --git a/clippy_utils/src/eager_or_lazy.rs b/clippy_utils/src/eager_or_lazy.rs index 124a00d81..91c9c382c 100644 --- a/clippy_utils/src/eager_or_lazy.rs +++ b/clippy_utils/src/eager_or_lazy.rs @@ -45,7 +45,7 @@ impl ops::BitOrAssign for EagernessSuggestion { } /// Determine the eagerness of the given function call. -fn fn_eagerness<'tcx>(cx: &LateContext<'tcx>, fn_id: DefId, name: Symbol, have_one_arg: bool) -> EagernessSuggestion { +fn fn_eagerness(cx: &LateContext<'_>, fn_id: DefId, name: Symbol, have_one_arg: bool) -> EagernessSuggestion { use EagernessSuggestion::{Eager, Lazy, NoChange}; let name = name.as_str(); diff --git a/clippy_utils/src/hir_utils.rs b/clippy_utils/src/hir_utils.rs index f45cec9f0..7212d9cd7 100644 --- a/clippy_utils/src/hir_utils.rs +++ b/clippy_utils/src/hir_utils.rs @@ -201,8 +201,8 @@ impl HirEqInterExpr<'_, '_, '_> { self.inner.cx.tcx.typeck_body(right), )); let res = self.eq_expr( - &self.inner.cx.tcx.hir().body(left).value, - &self.inner.cx.tcx.hir().body(right).value, + self.inner.cx.tcx.hir().body(left).value, + self.inner.cx.tcx.hir().body(right).value, ); self.inner.maybe_typeck_results = old_maybe_typeck_results; res @@ -649,7 +649,7 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { }) => { std::mem::discriminant(&capture_clause).hash(&mut self.s); // closures inherit TypeckResults - self.hash_expr(&self.cx.tcx.hir().body(body).value); + self.hash_expr(self.cx.tcx.hir().body(body).value); }, ExprKind::Field(e, ref f) => { self.hash_expr(e); @@ -1011,7 +1011,7 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { pub fn hash_body(&mut self, body_id: BodyId) { // swap out TypeckResults when hashing a body let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body_id)); - self.hash_expr(&self.cx.tcx.hir().body(body_id).value); + self.hash_expr(self.cx.tcx.hir().body(body_id).value); self.maybe_typeck_results = old_maybe_typeck_results; } @@ -1019,7 +1019,7 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { for arg in arg_list { match *arg { GenericArg::Lifetime(l) => self.hash_lifetime(l), - GenericArg::Type(ref ty) => self.hash_ty(ty), + GenericArg::Type(ty) => self.hash_ty(ty), GenericArg::Const(ref ca) => self.hash_body(ca.value.body), GenericArg::Infer(ref inf) => self.hash_ty(&inf.to_ty()), } diff --git a/clippy_utils/src/lib.rs b/clippy_utils/src/lib.rs index 3cf043f22..bdb858e1f 100644 --- a/clippy_utils/src/lib.rs +++ b/clippy_utils/src/lib.rs @@ -1031,12 +1031,12 @@ pub fn can_move_expr_to_closure<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<' v.allow_closure.then_some(v.captures) } +/// Arguments of a method: the receiver and all the additional arguments. +pub type MethodArguments<'tcx> = Vec<(&'tcx Expr<'tcx>, &'tcx [Expr<'tcx>])>; + /// Returns the method names and argument list of nested method call expressions that make up /// `expr`. method/span lists are sorted with the most recent call first. -pub fn method_calls<'tcx>( - expr: &'tcx Expr<'tcx>, - max_depth: usize, -) -> (Vec, Vec<(&'tcx Expr<'tcx>, &'tcx [Expr<'tcx>])>, Vec) { +pub fn method_calls<'tcx>(expr: &'tcx Expr<'tcx>, max_depth: usize) -> (Vec, MethodArguments<'tcx>, Vec) { let mut method_names = Vec::with_capacity(max_depth); let mut arg_lists = Vec::with_capacity(max_depth); let mut spans = Vec::with_capacity(max_depth); diff --git a/clippy_utils/src/macros.rs b/clippy_utils/src/macros.rs index 43e53f3fe..bd89ff977 100644 --- a/clippy_utils/src/macros.rs +++ b/clippy_utils/src/macros.rs @@ -389,8 +389,10 @@ impl FormatString { }; let mut unescaped = String::with_capacity(inner.len()); - unescape_literal(inner, mode, &mut |_, ch| { - unescaped.push(ch.unwrap()); + unescape_literal(inner, mode, &mut |_, ch| match ch { + Ok(ch) => unescaped.push(ch), + Err(e) if !e.is_fatal() => (), + Err(e) => panic!("{:?}", e), }); let mut parts = Vec::new(); diff --git a/clippy_utils/src/qualify_min_const_fn.rs b/clippy_utils/src/qualify_min_const_fn.rs index b22a9c817..d5f64e511 100644 --- a/clippy_utils/src/qualify_min_const_fn.rs +++ b/clippy_utils/src/qualify_min_const_fn.rs @@ -6,8 +6,8 @@ use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle::mir::{ - Body, CastKind, NullOp, Operand, Place, ProjectionElem, Rvalue, Statement, StatementKind, Terminator, - TerminatorKind, NonDivergingIntrinsic + Body, CastKind, NonDivergingIntrinsic, NullOp, Operand, Place, ProjectionElem, Rvalue, Statement, StatementKind, + Terminator, TerminatorKind, }; use rustc_middle::ty::subst::GenericArgKind; use rustc_middle::ty::{self, adjustment::PointerCast, Ty, TyCtxt}; @@ -212,9 +212,7 @@ fn check_statement<'tcx>( check_place(tcx, **place, span, body) }, - StatementKind::Intrinsic(box NonDivergingIntrinsic::Assume(op)) => { - check_operand(tcx, op, span, body) - }, + StatementKind::Intrinsic(box NonDivergingIntrinsic::Assume(op)) => check_operand(tcx, op, span, body), StatementKind::Intrinsic(box NonDivergingIntrinsic::CopyNonOverlapping( rustc_middle::mir::CopyNonOverlapping { dst, src, count }, diff --git a/clippy_utils/src/visitors.rs b/clippy_utils/src/visitors.rs index 6a62002a4..232d57190 100644 --- a/clippy_utils/src/visitors.rs +++ b/clippy_utils/src/visitors.rs @@ -274,7 +274,7 @@ pub fn is_res_used(cx: &LateContext<'_>, res: Res, body: BodyId) -> bool { } !found }) - .visit_expr(&cx.tcx.hir().body(body).value); + .visit_expr(cx.tcx.hir().body(body).value); found } @@ -568,6 +568,7 @@ pub fn for_each_local_use_after_expr<'tcx, B>( // Calls the given function for every unconsumed temporary created by the expression. Note the // function is only guaranteed to be called for types which need to be dropped, but it may be called // for other types. +#[allow(clippy::too_many_lines)] pub fn for_each_unconsumed_temporary<'tcx, B>( cx: &LateContext<'tcx>, e: &'tcx Expr<'tcx>, diff --git a/lintcheck/lintcheck_crates.toml b/lintcheck/lintcheck_crates.toml index 4fbae8614..ebbe9c9ae 100644 --- a/lintcheck/lintcheck_crates.toml +++ b/lintcheck/lintcheck_crates.toml @@ -1,6 +1,6 @@ [crates] # some of these are from cargotest -cargo = {name = "cargo", versions = ['0.49.0']} +cargo = {name = "cargo", versions = ['0.64.0']} iron = {name = "iron", versions = ['0.6.1']} ripgrep = {name = "ripgrep", versions = ['12.1.1']} xsv = {name = "xsv", versions = ['0.13.0']} diff --git a/rust-toolchain b/rust-toolchain index 85b60fefd..b6976366d 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2022-08-27" +channel = "nightly-2022-09-08" components = ["cargo", "llvm-tools-preview", "rust-src", "rust-std", "rustc", "rustc-dev", "rustfmt"] diff --git a/src/docs.rs b/src/docs.rs new file mode 100644 index 000000000..f3a5048e7 --- /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_side_effects", + "as_conversions", + "as_underscore", + "assertions_on_constants", + "assertions_on_result_states", + "assign_op_pattern", + "async_yields_async", + "await_holding_invalid_type", + "await_holding_lock", + "await_holding_refcell_ref", + "bad_bit_mask", + "bind_instead_of_map", + "blanket_clippy_restriction_lints", + "blocks_in_if_conditions", + "bool_assert_comparison", + "bool_comparison", + "bool_to_int_with_if", + "borrow_as_ptr", + "borrow_deref_ref", + "borrow_interior_mutable_const", + "borrowed_box", + "box_collection", + "boxed_local", + "branches_sharing_code", + "builtin_type_shadow", + "bytes_count_to_len", + "bytes_nth", + "cargo_common_metadata", + "case_sensitive_file_extension_comparisons", + "cast_abs_to_unsigned", + "cast_enum_constructor", + "cast_enum_truncation", + "cast_lossless", + "cast_possible_truncation", + "cast_possible_wrap", + "cast_precision_loss", + "cast_ptr_alignment", + "cast_ref_to_mut", + "cast_sign_loss", + "cast_slice_different_sizes", + "cast_slice_from_raw_parts", + "char_lit_as_u8", + "chars_last_cmp", + "chars_next_cmp", + "checked_conversions", + "clone_double_ref", + "clone_on_copy", + "clone_on_ref_ptr", + "cloned_instead_of_copied", + "cmp_nan", + "cmp_null", + "cmp_owned", + "cognitive_complexity", + "collapsible_else_if", + "collapsible_if", + "collapsible_match", + "collapsible_str_replace", + "comparison_chain", + "comparison_to_empty", + "copy_iterator", + "crate_in_macro_def", + "create_dir", + "crosspointer_transmute", + "dbg_macro", + "debug_assert_with_mut_call", + "decimal_literal_representation", + "declare_interior_mutable_const", + "default_instead_of_iter_empty", + "default_numeric_fallback", + "default_trait_access", + "default_union_representation", + "deprecated_cfg_attr", + "deprecated_semver", + "deref_addrof", + "deref_by_slicing", + "derivable_impls", + "derive_hash_xor_eq", + "derive_ord_xor_partial_ord", + "derive_partial_eq_without_eq", + "disallowed_methods", + "disallowed_names", + "disallowed_script_idents", + "disallowed_types", + "diverging_sub_expression", + "doc_link_with_quotes", + "doc_markdown", + "double_comparisons", + "double_must_use", + "double_neg", + "double_parens", + "drop_copy", + "drop_non_drop", + "drop_ref", + "duplicate_mod", + "duplicate_underscore_argument", + "duration_subsec", + "else_if_without_else", + "empty_drop", + "empty_enum", + "empty_line_after_outer_attr", + "empty_loop", + "empty_structs_with_brackets", + "enum_clike_unportable_variant", + "enum_glob_use", + "enum_variant_names", + "eq_op", + "equatable_if_let", + "erasing_op", + "err_expect", + "excessive_precision", + "exhaustive_enums", + "exhaustive_structs", + "exit", + "expect_fun_call", + "expect_used", + "expl_impl_clone_on_copy", + "explicit_auto_deref", + "explicit_counter_loop", + "explicit_deref_methods", + "explicit_into_iter_loop", + "explicit_iter_loop", + "explicit_write", + "extend_with_drain", + "extra_unused_lifetimes", + "fallible_impl_from", + "field_reassign_with_default", + "filetype_is_file", + "filter_map_identity", + "filter_map_next", + "filter_next", + "flat_map_identity", + "flat_map_option", + "float_arithmetic", + "float_cmp", + "float_cmp_const", + "float_equality_without_abs", + "fn_address_comparisons", + "fn_params_excessive_bools", + "fn_to_numeric_cast", + "fn_to_numeric_cast_any", + "fn_to_numeric_cast_with_truncation", + "for_kv_map", + "for_loops_over_fallibles", + "forget_copy", + "forget_non_drop", + "forget_ref", + "format_in_format_args", + "format_push_string", + "from_iter_instead_of_collect", + "from_over_into", + "from_str_radix_10", + "future_not_send", + "get_first", + "get_last_with_len", + "get_unwrap", + "identity_op", + "if_let_mutex", + "if_not_else", + "if_same_then_else", + "if_then_some_else_none", + "ifs_same_cond", + "implicit_clone", + "implicit_hasher", + "implicit_return", + "implicit_saturating_sub", + "imprecise_flops", + "inconsistent_digit_grouping", + "inconsistent_struct_constructor", + "index_refutable_slice", + "indexing_slicing", + "ineffective_bit_mask", + "inefficient_to_string", + "infallible_destructuring_match", + "infinite_iter", + "inherent_to_string", + "inherent_to_string_shadow_display", + "init_numbered_fields", + "inline_always", + "inline_asm_x86_att_syntax", + "inline_asm_x86_intel_syntax", + "inline_fn_without_body", + "inspect_for_each", + "int_plus_one", + "integer_arithmetic", + "integer_division", + "into_iter_on_ref", + "invalid_null_ptr_usage", + "invalid_regex", + "invalid_upcast_comparisons", + "invalid_utf8_in_unchecked", + "invisible_characters", + "is_digit_ascii_radix", + "items_after_statements", + "iter_cloned_collect", + "iter_count", + "iter_next_loop", + "iter_next_slice", + "iter_not_returning_iterator", + "iter_nth", + "iter_nth_zero", + "iter_on_empty_collections", + "iter_on_single_items", + "iter_overeager_cloned", + "iter_skip_next", + "iter_with_drain", + "iterator_step_by_zero", + "just_underscores_and_digits", + "large_const_arrays", + "large_digit_groups", + "large_enum_variant", + "large_include_file", + "large_stack_arrays", + "large_types_passed_by_value", + "len_without_is_empty", + "len_zero", + "let_and_return", + "let_underscore_drop", + "let_underscore_lock", + "let_underscore_must_use", + "let_unit_value", + "linkedlist", + "lossy_float_literal", + "macro_use_imports", + "main_recursion", + "manual_assert", + "manual_async_fn", + "manual_bits", + "manual_filter_map", + "manual_find", + "manual_find_map", + "manual_flatten", + "manual_instant_elapsed", + "manual_map", + "manual_memcpy", + "manual_non_exhaustive", + "manual_ok_or", + "manual_range_contains", + "manual_rem_euclid", + "manual_retain", + "manual_saturating_arithmetic", + "manual_split_once", + "manual_str_repeat", + "manual_string_new", + "manual_strip", + "manual_swap", + "manual_unwrap_or", + "many_single_char_names", + "map_clone", + "map_collect_result_unit", + "map_entry", + "map_err_ignore", + "map_flatten", + "map_identity", + "map_unwrap_or", + "match_as_ref", + "match_bool", + "match_like_matches_macro", + "match_on_vec_items", + "match_overlapping_arm", + "match_ref_pats", + "match_result_ok", + "match_same_arms", + "match_single_binding", + "match_str_case_mismatch", + "match_wild_err_arm", + "match_wildcard_for_single_variants", + "maybe_infinite_iter", + "mem_forget", + "mem_replace_option_with_none", + "mem_replace_with_default", + "mem_replace_with_uninit", + "min_max", + "mismatched_target_os", + "mismatching_type_param_order", + "misrefactored_assign_op", + "missing_const_for_fn", + "missing_docs_in_private_items", + "missing_enforced_import_renames", + "missing_errors_doc", + "missing_inline_in_public_items", + "missing_panics_doc", + "missing_safety_doc", + "missing_spin_loop", + "mistyped_literal_suffixes", + "mixed_case_hex_literals", + "mixed_read_write_in_expression", + "mod_module_files", + "module_inception", + "module_name_repetitions", + "modulo_arithmetic", + "modulo_one", + "multi_assignments", + "multiple_crate_versions", + "multiple_inherent_impl", + "must_use_candidate", + "must_use_unit", + "mut_from_ref", + "mut_mut", + "mut_mutex_lock", + "mut_range_bound", + "mutable_key_type", + "mutex_atomic", + "mutex_integer", + "naive_bytecount", + "needless_arbitrary_self_type", + "needless_bitwise_bool", + "needless_bool", + "needless_borrow", + "needless_borrowed_reference", + "needless_collect", + "needless_continue", + "needless_doctest_main", + "needless_for_each", + "needless_late_init", + "needless_lifetimes", + "needless_match", + "needless_option_as_deref", + "needless_option_take", + "needless_parens_on_range_literals", + "needless_pass_by_value", + "needless_question_mark", + "needless_range_loop", + "needless_return", + "needless_splitn", + "needless_update", + "neg_cmp_op_on_partial_ord", + "neg_multiply", + "negative_feature_names", + "never_loop", + "new_ret_no_self", + "new_without_default", + "no_effect", + "no_effect_replace", + "no_effect_underscore_binding", + "non_ascii_literal", + "non_octal_unix_permissions", + "non_send_fields_in_send_ty", + "nonminimal_bool", + "nonsensical_open_options", + "nonstandard_macro_braces", + "not_unsafe_ptr_arg_deref", + "obfuscated_if_else", + "octal_escapes", + "ok_expect", + "only_used_in_recursion", + "op_ref", + "option_as_ref_deref", + "option_env_unwrap", + "option_filter_map", + "option_if_let_else", + "option_map_or_none", + "option_map_unit_fn", + "option_option", + "or_fun_call", + "or_then_unwrap", + "out_of_bounds_indexing", + "overflow_check_conditional", + "overly_complex_bool_expr", + "panic", + "panic_in_result_fn", + "panicking_unwrap", + "partialeq_ne_impl", + "partialeq_to_none", + "path_buf_push_overwrite", + "pattern_type_mismatch", + "positional_named_format_parameters", + "possible_missing_comma", + "precedence", + "print_in_format_impl", + "print_literal", + "print_stderr", + "print_stdout", + "print_with_newline", + "println_empty_string", + "ptr_arg", + "ptr_as_ptr", + "ptr_eq", + "ptr_offset_with_cast", + "pub_use", + "question_mark", + "range_minus_one", + "range_plus_one", + "range_zip_with_len", + "rc_buffer", + "rc_clone_in_vec_init", + "rc_mutex", + "read_zero_byte_vec", + "recursive_format_impl", + "redundant_allocation", + "redundant_clone", + "redundant_closure", + "redundant_closure_call", + "redundant_closure_for_method_calls", + "redundant_else", + "redundant_feature_names", + "redundant_field_names", + "redundant_pattern", + "redundant_pattern_matching", + "redundant_pub_crate", + "redundant_slicing", + "redundant_static_lifetimes", + "ref_binding_to_reference", + "ref_option_ref", + "repeat_once", + "rest_pat_in_fully_bound_structs", + "result_large_err", + "result_map_or_into_option", + "result_map_unit_fn", + "result_unit_err", + "return_self_not_must_use", + "reversed_empty_ranges", + "same_functions_in_if_condition", + "same_item_push", + "same_name_method", + "search_is_some", + "self_assignment", + "self_named_constructors", + "self_named_module_files", + "semicolon_if_nothing_returned", + "separated_literal_suffix", + "serde_api_misuse", + "shadow_reuse", + "shadow_same", + "shadow_unrelated", + "short_circuit_statement", + "should_implement_trait", + "significant_drop_in_scrutinee", + "similar_names", + "single_char_add_str", + "single_char_lifetime_names", + "single_char_pattern", + "single_component_path_imports", + "single_element_loop", + "single_match", + "single_match_else", + "size_of_in_element_count", + "skip_while_next", + "slow_vector_initialization", + "stable_sort_primitive", + "std_instead_of_alloc", + "std_instead_of_core", + "str_to_string", + "string_add", + "string_add_assign", + "string_extend_chars", + "string_from_utf8_as_bytes", + "string_lit_as_bytes", + "string_slice", + "string_to_string", + "strlen_on_c_strings", + "struct_excessive_bools", + "suboptimal_flops", + "suspicious_arithmetic_impl", + "suspicious_assignment_formatting", + "suspicious_else_formatting", + "suspicious_map", + "suspicious_op_assign_impl", + "suspicious_operation_groupings", + "suspicious_splitn", + "suspicious_to_owned", + "suspicious_unary_op_formatting", + "swap_ptr_to_ref", + "tabs_in_doc_comments", + "temporary_assignment", + "to_digit_is_some", + "to_string_in_format_args", + "todo", + "too_many_arguments", + "too_many_lines", + "toplevel_ref_arg", + "trailing_empty_array", + "trait_duplication_in_bounds", + "transmute_bytes_to_str", + "transmute_float_to_int", + "transmute_int_to_bool", + "transmute_int_to_char", + "transmute_int_to_float", + "transmute_num_to_bytes", + "transmute_ptr_to_ptr", + "transmute_ptr_to_ref", + "transmute_undefined_repr", + "transmutes_expressible_as_ptr_casts", + "transmuting_null", + "trim_split_whitespace", + "trivial_regex", + "trivially_copy_pass_by_ref", + "try_err", + "type_complexity", + "type_repetition_in_bounds", + "undocumented_unsafe_blocks", + "undropped_manually_drops", + "unicode_not_nfc", + "unimplemented", + "uninit_assumed_init", + "uninit_vec", + "unit_arg", + "unit_cmp", + "unit_hash", + "unit_return_expecting_ord", + "unnecessary_cast", + "unnecessary_filter_map", + "unnecessary_find_map", + "unnecessary_fold", + "unnecessary_join", + "unnecessary_lazy_evaluations", + "unnecessary_mut_passed", + "unnecessary_operation", + "unnecessary_owned_empty_strings", + "unnecessary_self_imports", + "unnecessary_sort_by", + "unnecessary_to_owned", + "unnecessary_unwrap", + "unnecessary_wraps", + "unneeded_field_pattern", + "unneeded_wildcard_pattern", + "unnested_or_patterns", + "unreachable", + "unreadable_literal", + "unsafe_derive_deserialize", + "unsafe_removed_from_name", + "unseparated_literal_suffix", + "unsound_collection_transmute", + "unused_async", + "unused_io_amount", + "unused_peekable", + "unused_rounding", + "unused_self", + "unused_unit", + "unusual_byte_groupings", + "unwrap_in_result", + "unwrap_or_else_default", + "unwrap_used", + "upper_case_acronyms", + "use_debug", + "use_self", + "used_underscore_binding", + "useless_asref", + "useless_attribute", + "useless_conversion", + "useless_format", + "useless_let_if_seq", + "useless_transmute", + "useless_vec", + "vec_box", + "vec_init_then_push", + "vec_resize_to_zero", + "verbose_bit_mask", + "verbose_file_reads", + "vtable_address_comparisons", + "while_immutable_condition", + "while_let_loop", + "while_let_on_iterator", + "wildcard_dependencies", + "wildcard_enum_match_arm", + "wildcard_imports", + "wildcard_in_or_patterns", + "write_literal", + "write_with_newline", + "writeln_empty_string", + "wrong_self_convention", + "wrong_transmute", + "zero_divided_by_zero", + "zero_prefixed_literal", + "zero_ptr", + "zero_sized_map_values", + "zst_offset", + +} diff --git a/src/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_side_effects.txt b/src/docs/arithmetic_side_effects.txt new file mode 100644 index 000000000..6c7d51a49 --- /dev/null +++ b/src/docs/arithmetic_side_effects.txt @@ -0,0 +1,33 @@ +### What it does +Checks any kind of arithmetic operation of any type. + +Operators like `+`, `-`, `*` or `<<` are usually capable of overflowing according to the [Rust +Reference](https://doc.rust-lang.org/reference/expressions/operator-expr.html#overflow), +or can panic (`/`, `%`). + +Known safe built-in types like `Wrapping` or `Saturing`, floats, operations in constant +environments, allowed types and non-constant operations that won't overflow are ignored. + +### Why is this bad? +For integers, overflow will trigger a panic in debug builds or wrap the result in +release mode; division by zero will cause a panic in either mode. As a result, it is +desirable to explicitly call checked, wrapping or saturating arithmetic methods. + +#### Example +``` +// `n` can be any number, including `i32::MAX`. +fn foo(n: i32) -> i32 { + n + 1 +} +``` + +Third-party types can also overflow or present unwanted side-effects. + +#### Example +``` +use rust_decimal::Decimal; +let _n = Decimal::MAX + Decimal::MAX; +``` + +### Allowed types +Custom allowed types can be specified through the "arithmetic-side-effects-allowed" filter. \ No newline at end of file diff --git a/src/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..5cee43956 --- /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` may be more generalized or +specialized than what derive will produce. This lint can't detect the manual `impl` +has exactly equal bounds, and therefore this lint is disabled for types with +generic parameters. \ No newline at end of file diff --git a/src/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..1f9543079 --- /dev/null +++ b/src/docs/large_enum_variant.txt @@ -0,0 +1,41 @@ +### What it does +Checks for large size differences between variants on +`enum`s. + +### Why is this bad? +Enum size is bounded by the largest variant. Having one +large variant can penalize the memory layout of that enum. + +### Known problems +This lint obviously cannot take the distribution of +variants in your running program into account. It is possible that the +smaller variants make up less than 1% of all instances, in which case +the overhead is negligible and the boxing is counter-productive. Always +measure the change this lint suggests. + +For types that implement `Copy`, the suggestion to `Box` a variant's +data would require removing the trait impl. The types can of course +still be `Clone`, but that is worse ergonomically. Depending on the +use case it may be possible to store the large data in an auxiliary +structure (e.g. Arena or ECS). + +The lint will ignore the impact of generic types to the type layout by +assuming every type parameter is zero-sized. Depending on your use case, +this may lead to a false positive. + +### Example +``` +enum Test { + A(i32), + B([i32; 8000]), +} +``` + +Use instead: +``` +// Possibly better +enum Test2 { + A(i32), + B(Box<[i32; 8000]>), +} +``` \ No newline at end of file diff --git a/src/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..6ce77cc26 --- /dev/null +++ b/src/docs/or_fun_call.txt @@ -0,0 +1,27 @@ +### What it does +Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`, +`.or_insert(foo(..))` etc., and suggests to use `.or_else(|| foo(..))`, +`.unwrap_or_else(|| foo(..))`, `.unwrap_or_default()` or `.or_default()` +etc. instead. + +### Why is this bad? +The function will always be called and potentially +allocate an object acting as the default. + +### Known problems +If the function has side-effects, not calling it will +change the semantic of the program, but you shouldn't rely on that anyway. + +### Example +``` +foo.unwrap_or(String::new()); +``` + +Use instead: +``` +foo.unwrap_or_else(String::new); + +// or + +foo.unwrap_or_default(); +``` \ No newline at end of file diff --git a/src/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); } diff --git a/tests/ui-toml/arithmetic_allowed/clippy.toml b/tests/ui-toml/arithmetic_allowed/clippy.toml deleted file mode 100644 index cc40570b1..000000000 --- a/tests/ui-toml/arithmetic_allowed/clippy.toml +++ /dev/null @@ -1 +0,0 @@ -arithmetic-allowed = ["Point"] diff --git a/tests/ui-toml/arithmetic_allowed/arithmetic_allowed.rs b/tests/ui-toml/arithmetic_side_effects_allowed/arithmetic_side_effects_allowed.rs similarity index 89% rename from tests/ui-toml/arithmetic_allowed/arithmetic_allowed.rs rename to tests/ui-toml/arithmetic_side_effects_allowed/arithmetic_side_effects_allowed.rs index 195fabdbf..1aed09b7c 100644 --- a/tests/ui-toml/arithmetic_allowed/arithmetic_allowed.rs +++ b/tests/ui-toml/arithmetic_side_effects_allowed/arithmetic_side_effects_allowed.rs @@ -1,4 +1,4 @@ -#![warn(clippy::arithmetic)] +#![warn(clippy::arithmetic_side_effects)] use core::ops::Add; diff --git a/tests/ui-toml/arithmetic_side_effects_allowed/clippy.toml b/tests/ui-toml/arithmetic_side_effects_allowed/clippy.toml new file mode 100644 index 000000000..e736256f2 --- /dev/null +++ b/tests/ui-toml/arithmetic_side_effects_allowed/clippy.toml @@ -0,0 +1 @@ +arithmetic-side-effects-allowed = ["Point"] diff --git a/tests/ui-toml/toml_unknown_key/conf_unknown_key.stderr b/tests/ui-toml/toml_unknown_key/conf_unknown_key.stderr index a52a0b528..f27f78d15 100644 --- a/tests/ui-toml/toml_unknown_key/conf_unknown_key.stderr +++ b/tests/ui-toml/toml_unknown_key/conf_unknown_key.stderr @@ -3,7 +3,7 @@ error: error reading Clippy's configuration file `$DIR/clippy.toml`: unknown fie allow-expect-in-tests allow-unwrap-in-tests allowed-scripts - arithmetic-allowed + arithmetic-side-effects-allowed array-size-threshold avoid-breaking-exported-api await-holding-invalid-types diff --git a/tests/ui/arithmetic.fixed b/tests/ui/arithmetic.fixed deleted file mode 100644 index a2a1c4394..000000000 --- a/tests/ui/arithmetic.fixed +++ /dev/null @@ -1,27 +0,0 @@ -// run-rustfix - -#![allow(clippy::unnecessary_owned_empty_strings)] -#![feature(saturating_int_impl)] -#![warn(clippy::arithmetic)] - -use core::num::{Saturating, Wrapping}; - -pub fn hard_coded_allowed() { - let _ = Saturating(0u32) + Saturating(0u32); - let _ = String::new() + ""; - let _ = Wrapping(0u32) + Wrapping(0u32); - - let saturating: Saturating = Saturating(0u32); - let string: String = String::new(); - let wrapping: Wrapping = Wrapping(0u32); - - let inferred_saturating = saturating + saturating; - let inferred_string = string + ""; - let inferred_wrapping = wrapping + wrapping; - - let _ = inferred_saturating + inferred_saturating; - let _ = inferred_string + ""; - let _ = inferred_wrapping + inferred_wrapping; -} - -fn main() {} diff --git a/tests/ui/arithmetic.rs b/tests/ui/arithmetic.rs deleted file mode 100644 index a2a1c4394..000000000 --- a/tests/ui/arithmetic.rs +++ /dev/null @@ -1,27 +0,0 @@ -// run-rustfix - -#![allow(clippy::unnecessary_owned_empty_strings)] -#![feature(saturating_int_impl)] -#![warn(clippy::arithmetic)] - -use core::num::{Saturating, Wrapping}; - -pub fn hard_coded_allowed() { - let _ = Saturating(0u32) + Saturating(0u32); - let _ = String::new() + ""; - let _ = Wrapping(0u32) + Wrapping(0u32); - - let saturating: Saturating = Saturating(0u32); - let string: String = String::new(); - let wrapping: Wrapping = Wrapping(0u32); - - let inferred_saturating = saturating + saturating; - let inferred_string = string + ""; - let inferred_wrapping = wrapping + wrapping; - - let _ = inferred_saturating + inferred_saturating; - let _ = inferred_string + ""; - let _ = inferred_wrapping + inferred_wrapping; -} - -fn main() {} diff --git a/tests/ui/arithmetic_side_effects.rs b/tests/ui/arithmetic_side_effects.rs new file mode 100644 index 000000000..f5390c746 --- /dev/null +++ b/tests/ui/arithmetic_side_effects.rs @@ -0,0 +1,57 @@ +#![allow(clippy::assign_op_pattern, clippy::unnecessary_owned_empty_strings)] +#![feature(inline_const, saturating_int_impl)] +#![warn(clippy::arithmetic_side_effects)] + +use core::num::{Saturating, Wrapping}; + +pub fn hard_coded_allowed() { + let _ = 1f32 + 1f32; + let _ = 1f64 + 1f64; + + let _ = Saturating(0u32) + Saturating(0u32); + let _ = String::new() + ""; + let _ = Wrapping(0u32) + Wrapping(0u32); + + let saturating: Saturating = Saturating(0u32); + let string: String = String::new(); + let wrapping: Wrapping = Wrapping(0u32); + + let inferred_saturating = saturating + saturating; + let inferred_string = string + ""; + let inferred_wrapping = wrapping + wrapping; + + let _ = inferred_saturating + inferred_saturating; + let _ = inferred_string + ""; + let _ = inferred_wrapping + inferred_wrapping; +} + +#[rustfmt::skip] +pub fn non_overflowing_ops() { + const _: i32 = { let mut n = 1; n += 1; n }; + let _ = const { let mut n = 1; n += 1; n }; + + const _: i32 = { let mut n = 1; n = n + 1; n }; + let _ = const { let mut n = 1; n = n + 1; n }; + + const _: i32 = { let mut n = 1; n = 1 + n; n }; + let _ = const { let mut n = 1; n = 1 + n; n }; + + const _: i32 = 1 + 1; + let _ = 1 + 1; + let _ = const { 1 + 1 }; + + let mut _a = 1; + _a *= 1; + _a /= 1; +} + +#[rustfmt::skip] +pub fn overflowing_ops() { + let mut _a = 1; _a += 1; + + let mut _b = 1; _b = _b + 1; + + let mut _c = 1; _c = 1 + _c; +} + +fn main() {} diff --git a/tests/ui/arithmetic_side_effects.stderr b/tests/ui/arithmetic_side_effects.stderr new file mode 100644 index 000000000..6c4c8bdec --- /dev/null +++ b/tests/ui/arithmetic_side_effects.stderr @@ -0,0 +1,22 @@ +error: arithmetic detected + --> $DIR/arithmetic_side_effects.rs:50:21 + | +LL | let mut _a = 1; _a += 1; + | ^^^^^^^ + | + = note: `-D clippy::arithmetic-side-effects` implied by `-D warnings` + +error: arithmetic detected + --> $DIR/arithmetic_side_effects.rs:52:26 + | +LL | let mut _b = 1; _b = _b + 1; + | ^^^^^^ + +error: arithmetic detected + --> $DIR/arithmetic_side_effects.rs:54:26 + | +LL | let mut _c = 1; _c = 1 + _c; + | ^^^^^^ + +error: aborting due to 3 previous errors + diff --git a/tests/ui/author/struct.rs b/tests/ui/author/struct.rs index 5fdf3433a..a99bdfc13 100644 --- a/tests/ui/author/struct.rs +++ b/tests/ui/author/struct.rs @@ -1,4 +1,9 @@ -#[allow(clippy::unnecessary_operation, clippy::single_match)] +#![allow( + clippy::unnecessary_operation, + clippy::single_match, + clippy::no_effect, + clippy::bool_to_int_with_if +)] fn main() { struct Test { field: u32, diff --git a/tests/ui/bool_to_int_with_if.fixed b/tests/ui/bool_to_int_with_if.fixed new file mode 100644 index 000000000..9c1098dc4 --- /dev/null +++ b/tests/ui/bool_to_int_with_if.fixed @@ -0,0 +1,85 @@ +// run-rustfix + +#![warn(clippy::bool_to_int_with_if)] +#![allow(unused, dead_code, clippy::unnecessary_operation, clippy::no_effect)] + +fn main() { + let a = true; + let b = false; + + let x = 1; + let y = 2; + + // Should lint + // precedence + i32::from(a); + i32::from(!a); + i32::from(a || b); + i32::from(cond(a, b)); + i32::from(x + y < 4); + + // if else if + if a { + 123 + } else {i32::from(b)}; + + // Shouldn't lint + + if a { + 1 + } else if b { + 0 + } else { + 3 + }; + + if a { + 3 + } else if b { + 1 + } else { + -2 + }; + + if a { + 3 + } else { + 0 + }; + if a { + side_effect(); + 1 + } else { + 0 + }; + if a { + 1 + } else { + side_effect(); + 0 + }; + + // multiple else ifs + if a { + 123 + } else if b { + 1 + } else if a | b { + 0 + } else { + 123 + }; + + some_fn(a); +} + +// Lint returns and type inference +fn some_fn(a: bool) -> u8 { + u8::from(a) +} + +fn side_effect() {} + +fn cond(a: bool, b: bool) -> bool { + a || b +} diff --git a/tests/ui/bool_to_int_with_if.rs b/tests/ui/bool_to_int_with_if.rs new file mode 100644 index 000000000..0c967dac6 --- /dev/null +++ b/tests/ui/bool_to_int_with_if.rs @@ -0,0 +1,109 @@ +// run-rustfix + +#![warn(clippy::bool_to_int_with_if)] +#![allow(unused, dead_code, clippy::unnecessary_operation, clippy::no_effect)] + +fn main() { + let a = true; + let b = false; + + let x = 1; + let y = 2; + + // Should lint + // precedence + if a { + 1 + } else { + 0 + }; + if !a { + 1 + } else { + 0 + }; + if a || b { + 1 + } else { + 0 + }; + if cond(a, b) { + 1 + } else { + 0 + }; + if x + y < 4 { + 1 + } else { + 0 + }; + + // if else if + if a { + 123 + } else if b { + 1 + } else { + 0 + }; + + // Shouldn't lint + + if a { + 1 + } else if b { + 0 + } else { + 3 + }; + + if a { + 3 + } else if b { + 1 + } else { + -2 + }; + + if a { + 3 + } else { + 0 + }; + if a { + side_effect(); + 1 + } else { + 0 + }; + if a { + 1 + } else { + side_effect(); + 0 + }; + + // multiple else ifs + if a { + 123 + } else if b { + 1 + } else if a | b { + 0 + } else { + 123 + }; + + some_fn(a); +} + +// Lint returns and type inference +fn some_fn(a: bool) -> u8 { + if a { 1 } else { 0 } +} + +fn side_effect() {} + +fn cond(a: bool, b: bool) -> bool { + a || b +} diff --git a/tests/ui/bool_to_int_with_if.stderr b/tests/ui/bool_to_int_with_if.stderr new file mode 100644 index 000000000..8647a9cff --- /dev/null +++ b/tests/ui/bool_to_int_with_if.stderr @@ -0,0 +1,84 @@ +error: boolean to int conversion using if + --> $DIR/bool_to_int_with_if.rs:15:5 + | +LL | / if a { +LL | | 1 +LL | | } else { +LL | | 0 +LL | | }; + | |_____^ help: replace with from: `i32::from(a)` + | + = note: `-D clippy::bool-to-int-with-if` implied by `-D warnings` + = note: `a as i32` or `a.into()` can also be valid options + +error: boolean to int conversion using if + --> $DIR/bool_to_int_with_if.rs:20:5 + | +LL | / if !a { +LL | | 1 +LL | | } else { +LL | | 0 +LL | | }; + | |_____^ help: replace with from: `i32::from(!a)` + | + = note: `!a as i32` or `!a.into()` can also be valid options + +error: boolean to int conversion using if + --> $DIR/bool_to_int_with_if.rs:25:5 + | +LL | / if a || b { +LL | | 1 +LL | | } else { +LL | | 0 +LL | | }; + | |_____^ help: replace with from: `i32::from(a || b)` + | + = note: `(a || b) as i32` or `(a || b).into()` can also be valid options + +error: boolean to int conversion using if + --> $DIR/bool_to_int_with_if.rs:30:5 + | +LL | / if cond(a, b) { +LL | | 1 +LL | | } else { +LL | | 0 +LL | | }; + | |_____^ help: replace with from: `i32::from(cond(a, b))` + | + = note: `cond(a, b) as i32` or `cond(a, b).into()` can also be valid options + +error: boolean to int conversion using if + --> $DIR/bool_to_int_with_if.rs:35:5 + | +LL | / if x + y < 4 { +LL | | 1 +LL | | } else { +LL | | 0 +LL | | }; + | |_____^ help: replace with from: `i32::from(x + y < 4)` + | + = note: `(x + y < 4) as i32` or `(x + y < 4).into()` can also be valid options + +error: boolean to int conversion using if + --> $DIR/bool_to_int_with_if.rs:44:12 + | +LL | } else if b { + | ____________^ +LL | | 1 +LL | | } else { +LL | | 0 +LL | | }; + | |_____^ help: replace with from: `{i32::from(b)}` + | + = note: `b as i32` or `b.into()` can also be valid options + +error: boolean to int conversion using if + --> $DIR/bool_to_int_with_if.rs:102:5 + | +LL | if a { 1 } else { 0 } + | ^^^^^^^^^^^^^^^^^^^^^ help: replace with from: `u8::from(a)` + | + = note: `a as u8` or `a.into()` can also be valid options + +error: aborting due to 7 previous errors + diff --git a/tests/ui/crashes/ice-9405.rs b/tests/ui/crashes/ice-9405.rs new file mode 100644 index 000000000..e2d274aeb --- /dev/null +++ b/tests/ui/crashes/ice-9405.rs @@ -0,0 +1,11 @@ +#![warn(clippy::useless_format)] +#![allow(clippy::print_literal)] + +fn main() { + println!( + "\ + + {}", + "multiple skipped lines" + ); +} diff --git a/tests/ui/crashes/ice-9405.stderr b/tests/ui/crashes/ice-9405.stderr new file mode 100644 index 000000000..9a6e410f2 --- /dev/null +++ b/tests/ui/crashes/ice-9405.stderr @@ -0,0 +1,11 @@ +warning: multiple lines skipped by escaped newline + --> $DIR/ice-9405.rs:6:10 + | +LL | "/ + | __________^ +LL | | +LL | | {}", + | |____________^ skipping everything up to and including this point + +warning: 1 warning emitted + diff --git a/tests/ui/crashes/ice-9414.rs b/tests/ui/crashes/ice-9414.rs new file mode 100644 index 000000000..02cf5d5c2 --- /dev/null +++ b/tests/ui/crashes/ice-9414.rs @@ -0,0 +1,8 @@ +#![warn(clippy::result_large_err)] + +trait T {} +fn f(_: &u32) -> Result<(), *const (dyn '_ + T)> { + Ok(()) +} + +fn main() {} diff --git a/tests/ui/floating_point_powf.fixed b/tests/ui/floating_point_powf.fixed index 7efe10a10..e7ef45634 100644 --- a/tests/ui/floating_point_powf.fixed +++ b/tests/ui/floating_point_powf.fixed @@ -18,6 +18,11 @@ fn main() { let _ = x.powi(-16_777_215); let _ = (x as f32).powi(-16_777_215); let _ = (x as f32).powi(3); + let _ = (1.5_f32 + 1.0).cbrt(); + let _ = 1.5_f64.cbrt(); + let _ = 1.5_f64.sqrt(); + let _ = 1.5_f64.powi(3); + // Cases where the lint shouldn't be applied let _ = x.powf(2.1); let _ = x.powf(-2.1); diff --git a/tests/ui/floating_point_powf.rs b/tests/ui/floating_point_powf.rs index 445080417..d749aa2d4 100644 --- a/tests/ui/floating_point_powf.rs +++ b/tests/ui/floating_point_powf.rs @@ -18,6 +18,11 @@ fn main() { let _ = x.powf(-16_777_215.0); let _ = (x as f32).powf(-16_777_215.0); let _ = (x as f32).powf(3.0); + let _ = (1.5_f32 + 1.0).powf(1.0 / 3.0); + let _ = 1.5_f64.powf(1.0 / 3.0); + let _ = 1.5_f64.powf(1.0 / 2.0); + let _ = 1.5_f64.powf(3.0); + // Cases where the lint shouldn't be applied let _ = x.powf(2.1); let _ = x.powf(-2.1); diff --git a/tests/ui/floating_point_powf.stderr b/tests/ui/floating_point_powf.stderr index 6ee696e6a..e9693de8f 100644 --- a/tests/ui/floating_point_powf.stderr +++ b/tests/ui/floating_point_powf.stderr @@ -92,77 +92,101 @@ error: exponentiation with integer powers can be computed more efficiently LL | let _ = (x as f32).powf(3.0); | ^^^^^^^^^^^^^^^^^^^^ help: consider using: `(x as f32).powi(3)` +error: cube-root of a number can be computed more accurately + --> $DIR/floating_point_powf.rs:21:13 + | +LL | let _ = (1.5_f32 + 1.0).powf(1.0 / 3.0); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `(1.5_f32 + 1.0).cbrt()` + +error: cube-root of a number can be computed more accurately + --> $DIR/floating_point_powf.rs:22:13 + | +LL | let _ = 1.5_f64.powf(1.0 / 3.0); + | ^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `1.5_f64.cbrt()` + +error: square-root of a number can be computed more efficiently and accurately + --> $DIR/floating_point_powf.rs:23:13 + | +LL | let _ = 1.5_f64.powf(1.0 / 2.0); + | ^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `1.5_f64.sqrt()` + +error: exponentiation with integer powers can be computed more efficiently + --> $DIR/floating_point_powf.rs:24:13 + | +LL | let _ = 1.5_f64.powf(3.0); + | ^^^^^^^^^^^^^^^^^ help: consider using: `1.5_f64.powi(3)` + error: exponent for bases 2 and e can be computed more accurately - --> $DIR/floating_point_powf.rs:28:13 + --> $DIR/floating_point_powf.rs:33:13 | LL | let _ = 2f64.powf(x); | ^^^^^^^^^^^^ help: consider using: `x.exp2()` error: exponent for bases 2 and e can be computed more accurately - --> $DIR/floating_point_powf.rs:29:13 + --> $DIR/floating_point_powf.rs:34:13 | LL | let _ = 2f64.powf(3.1); | ^^^^^^^^^^^^^^ help: consider using: `3.1f64.exp2()` error: exponent for bases 2 and e can be computed more accurately - --> $DIR/floating_point_powf.rs:30:13 + --> $DIR/floating_point_powf.rs:35:13 | LL | let _ = 2f64.powf(-3.1); | ^^^^^^^^^^^^^^^ help: consider using: `(-3.1f64).exp2()` error: exponent for bases 2 and e can be computed more accurately - --> $DIR/floating_point_powf.rs:31:13 + --> $DIR/floating_point_powf.rs:36:13 | LL | let _ = std::f64::consts::E.powf(x); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `x.exp()` error: exponent for bases 2 and e can be computed more accurately - --> $DIR/floating_point_powf.rs:32:13 + --> $DIR/floating_point_powf.rs:37:13 | LL | let _ = std::f64::consts::E.powf(3.1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `3.1f64.exp()` error: exponent for bases 2 and e can be computed more accurately - --> $DIR/floating_point_powf.rs:33:13 + --> $DIR/floating_point_powf.rs:38:13 | LL | let _ = std::f64::consts::E.powf(-3.1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `(-3.1f64).exp()` error: square-root of a number can be computed more efficiently and accurately - --> $DIR/floating_point_powf.rs:34:13 + --> $DIR/floating_point_powf.rs:39:13 | LL | let _ = x.powf(1.0 / 2.0); | ^^^^^^^^^^^^^^^^^ help: consider using: `x.sqrt()` error: cube-root of a number can be computed more accurately - --> $DIR/floating_point_powf.rs:35:13 + --> $DIR/floating_point_powf.rs:40:13 | LL | let _ = x.powf(1.0 / 3.0); | ^^^^^^^^^^^^^^^^^ help: consider using: `x.cbrt()` error: exponentiation with integer powers can be computed more efficiently - --> $DIR/floating_point_powf.rs:36:13 + --> $DIR/floating_point_powf.rs:41:13 | LL | let _ = x.powf(3.0); | ^^^^^^^^^^^ help: consider using: `x.powi(3)` error: exponentiation with integer powers can be computed more efficiently - --> $DIR/floating_point_powf.rs:37:13 + --> $DIR/floating_point_powf.rs:42:13 | LL | let _ = x.powf(-2.0); | ^^^^^^^^^^^^ help: consider using: `x.powi(-2)` error: exponentiation with integer powers can be computed more efficiently - --> $DIR/floating_point_powf.rs:38:13 + --> $DIR/floating_point_powf.rs:43:13 | LL | let _ = x.powf(-2_147_483_648.0); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `x.powi(-2_147_483_648)` error: exponentiation with integer powers can be computed more efficiently - --> $DIR/floating_point_powf.rs:39:13 + --> $DIR/floating_point_powf.rs:44:13 | LL | let _ = x.powf(2_147_483_647.0); | ^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `x.powi(2_147_483_647)` -error: aborting due to 27 previous errors +error: aborting due to 31 previous errors diff --git a/tests/ui/large_enum_variant.rs b/tests/ui/large_enum_variant.rs index 23152a133..717009e4c 100644 --- a/tests/ui/large_enum_variant.rs +++ b/tests/ui/large_enum_variant.rs @@ -130,6 +130,30 @@ impl Clone for SomeGenericPossiblyCopyEnum { impl Copy for SomeGenericPossiblyCopyEnum {} +enum LargeEnumWithGenerics { + Small, + Large((T, [u8; 512])), +} + +struct Foo { + foo: T, +} + +enum WithGenerics { + Large([Foo; 64]), + Small(u8), +} + +enum PossiblyLargeEnumWithConst { + SmallBuffer([u8; 4]), + MightyBuffer([u16; U]), +} + +enum LargeEnumOfConst { + Ok, + Error(PossiblyLargeEnumWithConst<256>), +} + fn main() { large_enum_variant!(); } diff --git a/tests/ui/large_enum_variant.stderr b/tests/ui/large_enum_variant.stderr index 024832726..c6ed97487 100644 --- a/tests/ui/large_enum_variant.stderr +++ b/tests/ui/large_enum_variant.stderr @@ -1,143 +1,177 @@ error: large size difference between variants - --> $DIR/large_enum_variant.rs:12:5 + --> $DIR/large_enum_variant.rs:10:1 | -LL | B([i32; 8000]), - | ^^^^^^^^^^^^^^ this variant is 32000 bytes +LL | / enum LargeEnum { +LL | | A(i32), + | | ------ the second-largest variant contains at least 4 bytes +LL | | B([i32; 8000]), + | | -------------- the largest variant contains at least 32000 bytes +LL | | } + | |_^ the entire enum is at least 32004 bytes | = note: `-D clippy::large-enum-variant` implied by `-D warnings` -note: and the second-largest variant is 4 bytes: - --> $DIR/large_enum_variant.rs:11:5 - | -LL | A(i32), - | ^^^^^^ help: consider boxing the large fields to reduce the total size of the enum | LL | B(Box<[i32; 8000]>), | ~~~~~~~~~~~~~~~~ error: large size difference between variants - --> $DIR/large_enum_variant.rs:36:5 + --> $DIR/large_enum_variant.rs:34:1 | -LL | ContainingLargeEnum(LargeEnum), - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this variant is 32004 bytes +LL | / enum LargeEnum2 { +LL | | VariantOk(i32, u32), + | | ------------------- the second-largest variant contains at least 8 bytes +LL | | ContainingLargeEnum(LargeEnum), + | | ------------------------------ the largest variant contains at least 32004 bytes +LL | | } + | |_^ the entire enum is at least 32004 bytes | -note: and the second-largest variant is 8 bytes: - --> $DIR/large_enum_variant.rs:35:5 - | -LL | VariantOk(i32, u32), - | ^^^^^^^^^^^^^^^^^^^ help: consider boxing the large fields to reduce the total size of the enum | LL | ContainingLargeEnum(Box), | ~~~~~~~~~~~~~~ error: large size difference between variants - --> $DIR/large_enum_variant.rs:40:5 + --> $DIR/large_enum_variant.rs:39:1 | -LL | ContainingMoreThanOneField(i32, [i32; 8000], [i32; 9500]), - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this variant is 70004 bytes +LL | / enum LargeEnum3 { +LL | | ContainingMoreThanOneField(i32, [i32; 8000], [i32; 9500]), + | | --------------------------------------------------------- the largest variant contains at least 70004 bytes +LL | | VoidVariant, +LL | | StructLikeLittle { x: i32, y: i32 }, + | | ----------------------------------- the second-largest variant contains at least 8 bytes +LL | | } + | |_^ the entire enum is at least 70008 bytes | -note: and the second-largest variant is 8 bytes: - --> $DIR/large_enum_variant.rs:42:5 - | -LL | StructLikeLittle { x: i32, y: i32 }, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider boxing the large fields to reduce the total size of the enum | LL | ContainingMoreThanOneField(i32, Box<[i32; 8000]>, Box<[i32; 9500]>), | ~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~ error: large size difference between variants - --> $DIR/large_enum_variant.rs:47:5 + --> $DIR/large_enum_variant.rs:45:1 | -LL | StructLikeLarge { x: [i32; 8000], y: i32 }, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this variant is 32004 bytes +LL | / enum LargeEnum4 { +LL | | VariantOk(i32, u32), + | | ------------------- the second-largest variant contains at least 8 bytes +LL | | StructLikeLarge { x: [i32; 8000], y: i32 }, + | | ------------------------------------------ the largest variant contains at least 32004 bytes +LL | | } + | |_^ the entire enum is at least 32008 bytes | -note: and the second-largest variant is 8 bytes: - --> $DIR/large_enum_variant.rs:46:5 - | -LL | VariantOk(i32, u32), - | ^^^^^^^^^^^^^^^^^^^ help: consider boxing the large fields to reduce the total size of the enum | LL | StructLikeLarge { x: Box<[i32; 8000]>, y: i32 }, | ~~~~~~~~~~~~~~~~ error: large size difference between variants - --> $DIR/large_enum_variant.rs:52:5 + --> $DIR/large_enum_variant.rs:50:1 | -LL | StructLikeLarge2 { x: [i32; 8000] }, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this variant is 32000 bytes +LL | / enum LargeEnum5 { +LL | | VariantOk(i32, u32), + | | ------------------- the second-largest variant contains at least 8 bytes +LL | | StructLikeLarge2 { x: [i32; 8000] }, + | | ----------------------------------- the largest variant contains at least 32000 bytes +LL | | } + | |_^ the entire enum is at least 32004 bytes | -note: and the second-largest variant is 8 bytes: - --> $DIR/large_enum_variant.rs:51:5 - | -LL | VariantOk(i32, u32), - | ^^^^^^^^^^^^^^^^^^^ help: consider boxing the large fields to reduce the total size of the enum | LL | StructLikeLarge2 { x: Box<[i32; 8000]> }, | ~~~~~~~~~~~~~~~~ error: large size difference between variants - --> $DIR/large_enum_variant.rs:68:5 + --> $DIR/large_enum_variant.rs:66:1 | -LL | B([u8; 1255]), - | ^^^^^^^^^^^^^ this variant is 1255 bytes +LL | / enum LargeEnum7 { +LL | | A, +LL | | B([u8; 1255]), + | | ------------- the largest variant contains at least 1255 bytes +LL | | C([u8; 200]), + | | ------------ the second-largest variant contains at least 200 bytes +LL | | } + | |_^ the entire enum is at least 1256 bytes | -note: and the second-largest variant is 200 bytes: - --> $DIR/large_enum_variant.rs:69:5 - | -LL | C([u8; 200]), - | ^^^^^^^^^^^^ help: consider boxing the large fields to reduce the total size of the enum | LL | B(Box<[u8; 1255]>), | ~~~~~~~~~~~~~~~ error: large size difference between variants - --> $DIR/large_enum_variant.rs:74:5 + --> $DIR/large_enum_variant.rs:72:1 | -LL | ContainingMoreThanOneField([i32; 8000], [i32; 2], [i32; 9500], [i32; 30]), - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this variant is 70128 bytes +LL | / enum LargeEnum8 { +LL | | VariantOk(i32, u32), + | | ------------------- the second-largest variant contains at least 8 bytes +LL | | ContainingMoreThanOneField([i32; 8000], [i32; 2], [i32; 9500], [i32; 30]), + | | ------------------------------------------------------------------------- the largest variant contains at least 70128 bytes +LL | | } + | |_^ the entire enum is at least 70132 bytes | -note: and the second-largest variant is 8 bytes: - --> $DIR/large_enum_variant.rs:73:5 - | -LL | VariantOk(i32, u32), - | ^^^^^^^^^^^^^^^^^^^ help: consider boxing the large fields to reduce the total size of the enum | LL | ContainingMoreThanOneField(Box<[i32; 8000]>, [i32; 2], Box<[i32; 9500]>, [i32; 30]), | ~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~ error: large size difference between variants - --> $DIR/large_enum_variant.rs:79:5 + --> $DIR/large_enum_variant.rs:77:1 | -LL | B(Struct2), - | ^^^^^^^^^^ this variant is 32000 bytes +LL | / enum LargeEnum9 { +LL | | A(Struct<()>), + | | ------------- the second-largest variant contains at least 4 bytes +LL | | B(Struct2), + | | ---------- the largest variant contains at least 32000 bytes +LL | | } + | |_^ the entire enum is at least 32004 bytes | -note: and the second-largest variant is 4 bytes: - --> $DIR/large_enum_variant.rs:78:5 - | -LL | A(Struct<()>), - | ^^^^^^^^^^^^^ help: consider boxing the large fields to reduce the total size of the enum | LL | B(Box), | ~~~~~~~~~~~~ error: large size difference between variants - --> $DIR/large_enum_variant.rs:104:5 + --> $DIR/large_enum_variant.rs:82:1 | -LL | B([u128; 4000]), - | ^^^^^^^^^^^^^^^ this variant is 64000 bytes +LL | / enum LargeEnumOk2 { +LL | | A(T), + | | ---- the second-largest variant contains at least 0 bytes +LL | | B(Struct2), + | | ---------- the largest variant contains at least 32000 bytes +LL | | } + | |_^ the entire enum is at least 32000 bytes | -note: and the second-largest variant is 1 bytes: - --> $DIR/large_enum_variant.rs:103:5 +help: consider boxing the large fields to reduce the total size of the enum + | +LL | B(Box), + | ~~~~~~~~~~~~ + +error: large size difference between variants + --> $DIR/large_enum_variant.rs:87:1 + | +LL | / enum LargeEnumOk3 { +LL | | A(Struct), + | | ------------ the second-largest variant contains at least 4 bytes +LL | | B(Struct2), + | | ---------- the largest variant contains at least 32000 bytes +LL | | } + | |_^ the entire enum is at least 32000 bytes + | +help: consider boxing the large fields to reduce the total size of the enum + | +LL | B(Box), + | ~~~~~~~~~~~~ + +error: large size difference between variants + --> $DIR/large_enum_variant.rs:102:1 + | +LL | / enum CopyableLargeEnum { +LL | | A(bool), + | | ------- the second-largest variant contains at least 1 bytes +LL | | B([u128; 4000]), + | | --------------- the largest variant contains at least 64000 bytes +LL | | } + | |_^ the entire enum is at least 64008 bytes | -LL | A(bool), - | ^^^^^^^ note: boxing a variant would require the type no longer be `Copy` --> $DIR/large_enum_variant.rs:102:6 | @@ -150,16 +184,16 @@ LL | B([u128; 4000]), | ^^^^^^^^^^^^^^^ error: large size difference between variants - --> $DIR/large_enum_variant.rs:109:5 + --> $DIR/large_enum_variant.rs:107:1 | -LL | B([u128; 4000]), - | ^^^^^^^^^^^^^^^ this variant is 64000 bytes +LL | / enum ManuallyCopyLargeEnum { +LL | | A(bool), + | | ------- the second-largest variant contains at least 1 bytes +LL | | B([u128; 4000]), + | | --------------- the largest variant contains at least 64000 bytes +LL | | } + | |_^ the entire enum is at least 64008 bytes | -note: and the second-largest variant is 1 bytes: - --> $DIR/large_enum_variant.rs:108:5 - | -LL | A(bool), - | ^^^^^^^ note: boxing a variant would require the type no longer be `Copy` --> $DIR/large_enum_variant.rs:107:6 | @@ -172,16 +206,16 @@ LL | B([u128; 4000]), | ^^^^^^^^^^^^^^^ error: large size difference between variants - --> $DIR/large_enum_variant.rs:122:5 + --> $DIR/large_enum_variant.rs:120:1 | -LL | B([u64; 4000]), - | ^^^^^^^^^^^^^^ this variant is 32000 bytes +LL | / enum SomeGenericPossiblyCopyEnum { +LL | | A(bool, std::marker::PhantomData), + | | ------------------------------------ the second-largest variant contains at least 1 bytes +LL | | B([u64; 4000]), + | | -------------- the largest variant contains at least 32000 bytes +LL | | } + | |_^ the entire enum is at least 32008 bytes | -note: and the second-largest variant is 1 bytes: - --> $DIR/large_enum_variant.rs:121:5 - | -LL | A(bool, std::marker::PhantomData), - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: boxing a variant would require the type no longer be `Copy` --> $DIR/large_enum_variant.rs:120:6 | @@ -193,5 +227,53 @@ help: consider boxing the large fields to reduce the total size of the enum LL | B([u64; 4000]), | ^^^^^^^^^^^^^^ -error: aborting due to 11 previous errors +error: large size difference between variants + --> $DIR/large_enum_variant.rs:133:1 + | +LL | / enum LargeEnumWithGenerics { +LL | | Small, + | | ----- the second-largest variant carries no data at all +LL | | Large((T, [u8; 512])), + | | --------------------- the largest variant contains at least 512 bytes +LL | | } + | |_^ the entire enum is at least 512 bytes + | +help: consider boxing the large fields to reduce the total size of the enum + | +LL | Large(Box<(T, [u8; 512])>), + | ~~~~~~~~~~~~~~~~~~~ + +error: large size difference between variants + --> $DIR/large_enum_variant.rs:142:1 + | +LL | / enum WithGenerics { +LL | | Large([Foo; 64]), + | | --------------------- the largest variant contains at least 512 bytes +LL | | Small(u8), + | | --------- the second-largest variant contains at least 1 bytes +LL | | } + | |_^ the entire enum is at least 520 bytes + | +help: consider boxing the large fields to reduce the total size of the enum + | +LL | Large(Box<[Foo; 64]>), + | ~~~~~~~~~~~~~~~~~~~ + +error: large size difference between variants + --> $DIR/large_enum_variant.rs:152:1 + | +LL | / enum LargeEnumOfConst { +LL | | Ok, + | | -- the second-largest variant carries no data at all +LL | | Error(PossiblyLargeEnumWithConst<256>), + | | -------------------------------------- the largest variant contains at least 514 bytes +LL | | } + | |_^ the entire enum is at least 514 bytes + | +help: consider boxing the large fields to reduce the total size of the enum + | +LL | Error(Box>), + | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +error: aborting due to 16 previous errors diff --git a/tests/ui/match_wild_err_arm.edition2018.stderr b/tests/ui/match_wild_err_arm.edition2018.stderr index 2a4012039..2d66daea8 100644 --- a/tests/ui/match_wild_err_arm.edition2018.stderr +++ b/tests/ui/match_wild_err_arm.edition2018.stderr @@ -5,7 +5,7 @@ LL | Err(_) => panic!("err"), | ^^^^^^ | = note: `-D clippy::match-wild-err-arm` implied by `-D warnings` - = note: match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable + = note: match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable error: `Err(_)` matches all errors --> $DIR/match_wild_err_arm.rs:20:9 @@ -13,7 +13,7 @@ error: `Err(_)` matches all errors LL | Err(_) => panic!(), | ^^^^^^ | - = note: match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable + = note: match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable error: `Err(_)` matches all errors --> $DIR/match_wild_err_arm.rs:26:9 @@ -21,7 +21,7 @@ error: `Err(_)` matches all errors LL | Err(_) => { | ^^^^^^ | - = note: match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable + = note: match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable error: `Err(_e)` matches all errors --> $DIR/match_wild_err_arm.rs:34:9 @@ -29,7 +29,7 @@ error: `Err(_e)` matches all errors LL | Err(_e) => panic!(), | ^^^^^^^ | - = note: match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable + = note: match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable error: aborting due to 4 previous errors diff --git a/tests/ui/match_wild_err_arm.edition2021.stderr b/tests/ui/match_wild_err_arm.edition2021.stderr index 2a4012039..2d66daea8 100644 --- a/tests/ui/match_wild_err_arm.edition2021.stderr +++ b/tests/ui/match_wild_err_arm.edition2021.stderr @@ -5,7 +5,7 @@ LL | Err(_) => panic!("err"), | ^^^^^^ | = note: `-D clippy::match-wild-err-arm` implied by `-D warnings` - = note: match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable + = note: match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable error: `Err(_)` matches all errors --> $DIR/match_wild_err_arm.rs:20:9 @@ -13,7 +13,7 @@ error: `Err(_)` matches all errors LL | Err(_) => panic!(), | ^^^^^^ | - = note: match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable + = note: match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable error: `Err(_)` matches all errors --> $DIR/match_wild_err_arm.rs:26:9 @@ -21,7 +21,7 @@ error: `Err(_)` matches all errors LL | Err(_) => { | ^^^^^^ | - = note: match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable + = note: match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable error: `Err(_e)` matches all errors --> $DIR/match_wild_err_arm.rs:34:9 @@ -29,7 +29,7 @@ error: `Err(_e)` matches all errors LL | Err(_e) => panic!(), | ^^^^^^^ | - = note: match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable + = note: match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable error: aborting due to 4 previous errors diff --git a/tests/ui/mut_mutex_lock.fixed b/tests/ui/mut_mutex_lock.fixed index 36bc52e33..ecad10a82 100644 --- a/tests/ui/mut_mutex_lock.fixed +++ b/tests/ui/mut_mutex_lock.fixed @@ -18,4 +18,11 @@ fn no_owned_mutex_lock() { *value += 1; } +fn issue9415() { + let mut arc_mutex = Arc::new(Mutex::new(42_u8)); + let arc_mutex: &mut Arc> = &mut arc_mutex; + let mut guard = arc_mutex.lock().unwrap(); + *guard += 1; +} + fn main() {} diff --git a/tests/ui/mut_mutex_lock.rs b/tests/ui/mut_mutex_lock.rs index ea60df5ae..f2b1d6fbf 100644 --- a/tests/ui/mut_mutex_lock.rs +++ b/tests/ui/mut_mutex_lock.rs @@ -18,4 +18,11 @@ fn no_owned_mutex_lock() { *value += 1; } +fn issue9415() { + let mut arc_mutex = Arc::new(Mutex::new(42_u8)); + let arc_mutex: &mut Arc> = &mut arc_mutex; + let mut guard = arc_mutex.lock().unwrap(); + *guard += 1; +} + fn main() {} diff --git a/tests/ui/or_fun_call.fixed b/tests/ui/or_fun_call.fixed index 18ea4e550..5991188ab 100644 --- a/tests/ui/or_fun_call.fixed +++ b/tests/ui/or_fun_call.fixed @@ -79,16 +79,16 @@ fn or_fun_call() { without_default.unwrap_or_else(Foo::new); let mut map = HashMap::::new(); - map.entry(42).or_insert(String::new()); + map.entry(42).or_default(); let mut map_vec = HashMap::>::new(); - map_vec.entry(42).or_insert(vec![]); + map_vec.entry(42).or_default(); let mut btree = BTreeMap::::new(); - btree.entry(42).or_insert(String::new()); + btree.entry(42).or_default(); let mut btree_vec = BTreeMap::>::new(); - btree_vec.entry(42).or_insert(vec![]); + btree_vec.entry(42).or_default(); let stringy = Some(String::new()); let _ = stringy.unwrap_or_default(); diff --git a/tests/ui/or_fun_call.stderr b/tests/ui/or_fun_call.stderr index 887f23ac9..e3dab4cb1 100644 --- a/tests/ui/or_fun_call.stderr +++ b/tests/ui/or_fun_call.stderr @@ -66,6 +66,30 @@ error: use of `unwrap_or` followed by a function call LL | without_default.unwrap_or(Foo::new()); | ^^^^^^^^^^^^^^^^^^^^^ help: try this: `unwrap_or_else(Foo::new)` +error: use of `or_insert` followed by a call to `new` + --> $DIR/or_fun_call.rs:82:19 + | +LL | map.entry(42).or_insert(String::new()); + | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `or_default()` + +error: use of `or_insert` followed by a call to `new` + --> $DIR/or_fun_call.rs:85:23 + | +LL | map_vec.entry(42).or_insert(vec![]); + | ^^^^^^^^^^^^^^^^^ help: try this: `or_default()` + +error: use of `or_insert` followed by a call to `new` + --> $DIR/or_fun_call.rs:88:21 + | +LL | btree.entry(42).or_insert(String::new()); + | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `or_default()` + +error: use of `or_insert` followed by a call to `new` + --> $DIR/or_fun_call.rs:91:25 + | +LL | btree_vec.entry(42).or_insert(vec![]); + | ^^^^^^^^^^^^^^^^^ help: try this: `or_default()` + error: use of `unwrap_or` followed by a call to `new` --> $DIR/or_fun_call.rs:94:21 | @@ -132,5 +156,5 @@ error: use of `unwrap_or` followed by a call to `new` LL | .unwrap_or(String::new()); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `unwrap_or_default()` -error: aborting due to 22 previous errors +error: aborting due to 26 previous errors diff --git a/tests/ui/range_plus_minus_one.fixed b/tests/ui/range_plus_minus_one.fixed index 40d7791df..a16a3e54d 100644 --- a/tests/ui/range_plus_minus_one.fixed +++ b/tests/ui/range_plus_minus_one.fixed @@ -6,6 +6,22 @@ fn f() -> usize { 42 } +macro_rules! macro_plus_one { + ($m: literal) => { + for i in 0..$m + 1 { + println!("{}", i); + } + }; +} + +macro_rules! macro_minus_one { + ($m: literal) => { + for i in 0..=$m - 1 { + println!("{}", i); + } + }; +} + #[warn(clippy::range_plus_one)] #[warn(clippy::range_minus_one)] fn main() { @@ -39,4 +55,7 @@ fn main() { let mut vec: Vec<()> = std::vec::Vec::new(); vec.drain(..); + + macro_plus_one!(5); + macro_minus_one!(5); } diff --git a/tests/ui/range_plus_minus_one.rs b/tests/ui/range_plus_minus_one.rs index a8ddd9b5f..bd6cb4d21 100644 --- a/tests/ui/range_plus_minus_one.rs +++ b/tests/ui/range_plus_minus_one.rs @@ -6,6 +6,22 @@ fn f() -> usize { 42 } +macro_rules! macro_plus_one { + ($m: literal) => { + for i in 0..$m + 1 { + println!("{}", i); + } + }; +} + +macro_rules! macro_minus_one { + ($m: literal) => { + for i in 0..=$m - 1 { + println!("{}", i); + } + }; +} + #[warn(clippy::range_plus_one)] #[warn(clippy::range_minus_one)] fn main() { @@ -39,4 +55,7 @@ fn main() { let mut vec: Vec<()> = std::vec::Vec::new(); vec.drain(..); + + macro_plus_one!(5); + macro_minus_one!(5); } diff --git a/tests/ui/range_plus_minus_one.stderr b/tests/ui/range_plus_minus_one.stderr index fb4f16585..022369624 100644 --- a/tests/ui/range_plus_minus_one.stderr +++ b/tests/ui/range_plus_minus_one.stderr @@ -1,5 +1,5 @@ error: an inclusive range would be more readable - --> $DIR/range_plus_minus_one.rs:15:14 + --> $DIR/range_plus_minus_one.rs:31:14 | LL | for _ in 0..3 + 1 {} | ^^^^^^^^ help: use: `0..=3` @@ -7,25 +7,25 @@ LL | for _ in 0..3 + 1 {} = note: `-D clippy::range-plus-one` implied by `-D warnings` error: an inclusive range would be more readable - --> $DIR/range_plus_minus_one.rs:18:14 + --> $DIR/range_plus_minus_one.rs:34:14 | LL | for _ in 0..1 + 5 {} | ^^^^^^^^ help: use: `0..=5` error: an inclusive range would be more readable - --> $DIR/range_plus_minus_one.rs:21:14 + --> $DIR/range_plus_minus_one.rs:37:14 | LL | for _ in 1..1 + 1 {} | ^^^^^^^^ help: use: `1..=1` error: an inclusive range would be more readable - --> $DIR/range_plus_minus_one.rs:27:14 + --> $DIR/range_plus_minus_one.rs:43:14 | LL | for _ in 0..(1 + f()) {} | ^^^^^^^^^^^^ help: use: `0..=f()` error: an exclusive range would be more readable - --> $DIR/range_plus_minus_one.rs:31:13 + --> $DIR/range_plus_minus_one.rs:47:13 | LL | let _ = ..=11 - 1; | ^^^^^^^^^ help: use: `..11` @@ -33,25 +33,25 @@ LL | let _ = ..=11 - 1; = note: `-D clippy::range-minus-one` implied by `-D warnings` error: an exclusive range would be more readable - --> $DIR/range_plus_minus_one.rs:32:13 + --> $DIR/range_plus_minus_one.rs:48:13 | LL | let _ = ..=(11 - 1); | ^^^^^^^^^^^ help: use: `..11` error: an inclusive range would be more readable - --> $DIR/range_plus_minus_one.rs:33:13 + --> $DIR/range_plus_minus_one.rs:49:13 | LL | let _ = (1..11 + 1); | ^^^^^^^^^^^ help: use: `(1..=11)` error: an inclusive range would be more readable - --> $DIR/range_plus_minus_one.rs:34:13 + --> $DIR/range_plus_minus_one.rs:50:13 | LL | let _ = (f() + 1)..(f() + 1); | ^^^^^^^^^^^^^^^^^^^^ help: use: `((f() + 1)..=f())` error: an inclusive range would be more readable - --> $DIR/range_plus_minus_one.rs:38:14 + --> $DIR/range_plus_minus_one.rs:54:14 | LL | for _ in 1..ONE + ONE {} | ^^^^^^^^^^^^ help: use: `1..=ONE` diff --git a/tests/ui/result_large_err.rs b/tests/ui/result_large_err.rs index 78d8f76fe..f7df3b856 100644 --- a/tests/ui/result_large_err.rs +++ b/tests/ui/result_large_err.rs @@ -1,4 +1,5 @@ #![warn(clippy::result_large_err)] +#![allow(clippy::large_enum_variant)] pub fn small_err() -> Result<(), u128> { Ok(()) diff --git a/tests/ui/result_large_err.stderr b/tests/ui/result_large_err.stderr index 0f1f39d72..ef19f2854 100644 --- a/tests/ui/result_large_err.stderr +++ b/tests/ui/result_large_err.stderr @@ -1,5 +1,5 @@ error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:7:23 + --> $DIR/result_large_err.rs:8:23 | LL | pub fn large_err() -> Result<(), [u8; 512]> { | ^^^^^^^^^^^^^^^^^^^^^ the `Err`-variant is at least 512 bytes @@ -8,7 +8,7 @@ LL | pub fn large_err() -> Result<(), [u8; 512]> { = help: try reducing the size of `[u8; 512]`, for example by boxing large elements or replacing it with `Box<[u8; 512]>` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:18:21 + --> $DIR/result_large_err.rs:19:21 | LL | pub fn ret() -> Result<(), Self> { | ^^^^^^^^^^^^^^^^ the `Err`-variant is at least 240 bytes @@ -16,7 +16,7 @@ LL | pub fn ret() -> Result<(), Self> { = help: try reducing the size of `FullyDefinedLargeError`, for example by boxing large elements or replacing it with `Box` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:23:26 + --> $DIR/result_large_err.rs:24:26 | LL | pub fn struct_error() -> Result<(), FullyDefinedLargeError> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the `Err`-variant is at least 240 bytes @@ -24,7 +24,7 @@ LL | pub fn struct_error() -> Result<(), FullyDefinedLargeError> { = help: try reducing the size of `FullyDefinedLargeError`, for example by boxing large elements or replacing it with `Box` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:28:45 + --> $DIR/result_large_err.rs:29:45 | LL | pub fn large_err_via_type_alias(x: T) -> Fdlr { | ^^^^^^^ the `Err`-variant is at least 240 bytes @@ -32,7 +32,7 @@ LL | pub fn large_err_via_type_alias(x: T) -> Fdlr { = help: try reducing the size of `FullyDefinedLargeError`, for example by boxing large elements or replacing it with `Box` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:36:34 + --> $DIR/result_large_err.rs:37:34 | LL | pub fn param_large_error() -> Result<(), (u128, R, FullyDefinedLargeError)> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the `Err`-variant is at least 256 bytes @@ -40,7 +40,7 @@ LL | pub fn param_large_error() -> Result<(), (u128, R, FullyDefinedLargeErro = help: try reducing the size of `(u128, R, FullyDefinedLargeError)`, for example by boxing large elements or replacing it with `Box<(u128, R, FullyDefinedLargeError)>` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:47:34 + --> $DIR/result_large_err.rs:48:34 | LL | pub fn large_enum_error() -> Result<(), Self> { | ^^^^^^^^^^^^^^^^ the `Err`-variant is at least 513 bytes @@ -48,7 +48,7 @@ LL | pub fn large_enum_error() -> Result<(), Self> { = help: try reducing the size of `LargeErrorVariants<()>`, for example by boxing large elements or replacing it with `Box>` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:53:25 + --> $DIR/result_large_err.rs:54:25 | LL | fn large_error() -> Result<(), [u8; 512]> { | ^^^^^^^^^^^^^^^^^^^^^ the `Err`-variant is at least 512 bytes @@ -56,7 +56,7 @@ LL | fn large_error() -> Result<(), [u8; 512]> { = help: try reducing the size of `[u8; 512]`, for example by boxing large elements or replacing it with `Box<[u8; 512]>` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:72:29 + --> $DIR/result_large_err.rs:73:29 | LL | pub fn large_union_err() -> Result<(), FullyDefinedUnionError> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the `Err`-variant is at least 512 bytes @@ -64,7 +64,7 @@ LL | pub fn large_union_err() -> Result<(), FullyDefinedUnionError> { = help: try reducing the size of `FullyDefinedUnionError`, for example by boxing large elements or replacing it with `Box` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:81:40 + --> $DIR/result_large_err.rs:82:40 | LL | pub fn param_large_union() -> Result<(), UnionError> { | ^^^^^^^^^^^^^^^^^^^^^^^^^ the `Err`-variant is at least 512 bytes @@ -72,7 +72,7 @@ LL | pub fn param_large_union() -> Result<(), UnionError> { = help: try reducing the size of `UnionError`, for example by boxing large elements or replacing it with `Box>` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:90:34 + --> $DIR/result_large_err.rs:91:34 | LL | pub fn array_error_subst() -> Result<(), ArrayError> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the `Err`-variant is at least 128 bytes @@ -80,7 +80,7 @@ LL | pub fn array_error_subst() -> Result<(), ArrayError> { = help: try reducing the size of `ArrayError`, for example by boxing large elements or replacing it with `Box>` error: the `Err`-variant returned from this function is very large - --> $DIR/result_large_err.rs:94:31 + --> $DIR/result_large_err.rs:95:31 | LL | pub fn array_error() -> Result<(), ArrayError<(i32, T), U>> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the `Err`-variant is at least 128 bytes diff --git a/tests/ui/unnecessary_to_owned.fixed b/tests/ui/unnecessary_to_owned.fixed index 9cd5bc73b..a920c63b1 100644 --- a/tests/ui/unnecessary_to_owned.fixed +++ b/tests/ui/unnecessary_to_owned.fixed @@ -357,3 +357,63 @@ mod issue_9317 { consume(b.to_string()); } } + +mod issue_9351 { + #![allow(dead_code)] + + use std::ops::Deref; + use std::path::{Path, PathBuf}; + + fn require_deref_path>(x: T) -> T { + x + } + + fn generic_arg_used_elsewhere>(_x: T, _y: T) {} + + fn id>(x: T) -> T { + x + } + + fn predicates_are_satisfied(_x: impl std::fmt::Write) {} + + // Should lint + fn single_return() -> impl AsRef { + id("abc") + } + + // Should not lint + fn multiple_returns(b: bool) -> impl AsRef { + if b { + return String::new(); + } + + id("abc".to_string()) + } + + struct S1(String); + + // Should not lint + fn fields1() -> S1 { + S1(id("abc".to_string())) + } + + struct S2 { + s: String, + } + + // Should not lint + fn fields2() { + let mut s = S2 { s: "abc".into() }; + s.s = id("abc".to_string()); + } + + pub fn main() { + let path = std::path::Path::new("x"); + let path_buf = path.to_owned(); + + // Should not lint. + let _x: PathBuf = require_deref_path(path.to_owned()); + generic_arg_used_elsewhere(path.to_owned(), path_buf); + predicates_are_satisfied(id("abc".to_string())); + } +} diff --git a/tests/ui/unnecessary_to_owned.rs b/tests/ui/unnecessary_to_owned.rs index 7f62ba3ab..2128bdacd 100644 --- a/tests/ui/unnecessary_to_owned.rs +++ b/tests/ui/unnecessary_to_owned.rs @@ -357,3 +357,63 @@ mod issue_9317 { consume(b.to_string()); } } + +mod issue_9351 { + #![allow(dead_code)] + + use std::ops::Deref; + use std::path::{Path, PathBuf}; + + fn require_deref_path>(x: T) -> T { + x + } + + fn generic_arg_used_elsewhere>(_x: T, _y: T) {} + + fn id>(x: T) -> T { + x + } + + fn predicates_are_satisfied(_x: impl std::fmt::Write) {} + + // Should lint + fn single_return() -> impl AsRef { + id("abc".to_string()) + } + + // Should not lint + fn multiple_returns(b: bool) -> impl AsRef { + if b { + return String::new(); + } + + id("abc".to_string()) + } + + struct S1(String); + + // Should not lint + fn fields1() -> S1 { + S1(id("abc".to_string())) + } + + struct S2 { + s: String, + } + + // Should not lint + fn fields2() { + let mut s = S2 { s: "abc".into() }; + s.s = id("abc".to_string()); + } + + pub fn main() { + let path = std::path::Path::new("x"); + let path_buf = path.to_owned(); + + // Should not lint. + let _x: PathBuf = require_deref_path(path.to_owned()); + generic_arg_used_elsewhere(path.to_owned(), path_buf); + predicates_are_satisfied(id("abc".to_string())); + } +} diff --git a/tests/ui/unnecessary_to_owned.stderr b/tests/ui/unnecessary_to_owned.stderr index 243b4599d..7deb90b06 100644 --- a/tests/ui/unnecessary_to_owned.stderr +++ b/tests/ui/unnecessary_to_owned.stderr @@ -509,5 +509,11 @@ error: unnecessary use of `to_string` LL | Box::new(build(y.to_string())) | ^^^^^^^^^^^^^ help: use: `y` -error: aborting due to 78 previous errors +error: unnecessary use of `to_string` + --> $DIR/unnecessary_to_owned.rs:381:12 + | +LL | id("abc".to_string()) + | ^^^^^^^^^^^^^^^^^ help: use: `"abc"` + +error: aborting due to 79 previous errors diff --git a/tests/ui/unwrap_or_else_default.fixed b/tests/ui/unwrap_or_else_default.fixed index c2b9bd2c8..84f779569 100644 --- a/tests/ui/unwrap_or_else_default.fixed +++ b/tests/ui/unwrap_or_else_default.fixed @@ -69,6 +69,9 @@ fn unwrap_or_else_default() { let with_default_type: Option> = None; with_default_type.unwrap_or_default(); + + let empty_string = None::; + empty_string.unwrap_or_default(); } fn main() {} diff --git a/tests/ui/unwrap_or_else_default.rs b/tests/ui/unwrap_or_else_default.rs index d55664990..1735bd580 100644 --- a/tests/ui/unwrap_or_else_default.rs +++ b/tests/ui/unwrap_or_else_default.rs @@ -69,6 +69,9 @@ fn unwrap_or_else_default() { let with_default_type: Option> = None; with_default_type.unwrap_or_else(Vec::new); + + let empty_string = None::; + empty_string.unwrap_or_else(|| "".to_string()); } fn main() {} diff --git a/tests/ui/unwrap_or_else_default.stderr b/tests/ui/unwrap_or_else_default.stderr index 53e31d85e..d2b921222 100644 --- a/tests/ui/unwrap_or_else_default.stderr +++ b/tests/ui/unwrap_or_else_default.stderr @@ -30,5 +30,11 @@ error: use of `.unwrap_or_else(..)` to construct default value LL | with_default_type.unwrap_or_else(Vec::new); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `with_default_type.unwrap_or_default()` -error: aborting due to 5 previous errors +error: use of `.unwrap_or_else(..)` to construct default value + --> $DIR/unwrap_or_else_default.rs:74:5 + | +LL | empty_string.unwrap_or_else(|| "".to_string()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `empty_string.unwrap_or_default()` + +error: aborting due to 6 previous errors diff --git a/tests/ui/vec_init_then_push.rs b/tests/ui/vec_init_then_push.rs index 531745424..8dd098a5b 100644 --- a/tests/ui/vec_init_then_push.rs +++ b/tests/ui/vec_init_then_push.rs @@ -104,3 +104,9 @@ fn _cond_push_with_large_start(x: bool) -> Vec { v2 } + +fn f() { + let mut v = Vec::new(); + v.push((0i32, 0i32)); + let y = v[0].0.abs(); +} diff --git a/tests/ui/vec_init_then_push.stderr b/tests/ui/vec_init_then_push.stderr index 50b029fc3..a9da1c520 100644 --- a/tests/ui/vec_init_then_push.stderr +++ b/tests/ui/vec_init_then_push.stderr @@ -62,5 +62,12 @@ LL | | v2.push(1); LL | | v2.push(0); | |_______________^ help: consider using the `vec![]` macro: `let mut v2 = vec![..];` -error: aborting due to 7 previous errors +error: calls to `push` immediately after creation + --> $DIR/vec_init_then_push.rs:109:5 + | +LL | / let mut v = Vec::new(); +LL | | v.push((0i32, 0i32)); + | |_________________________^ help: consider using the `vec![]` macro: `let v = vec![..];` + +error: aborting due to 8 previous errors From 41b30843910b160c0daa69d737cac46ed2c13f09 Mon Sep 17 00:00:00 2001 From: Niklas Jonsson Date: Sat, 16 Jul 2022 15:16:57 +0200 Subject: [PATCH 09/34] rustc_error, rustc_private, rustc_ast: Switch to stable hash containers --- clippy_lints/src/matches/match_same_arms.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/clippy_lints/src/matches/match_same_arms.rs b/clippy_lints/src/matches/match_same_arms.rs index 93874b103..d37f44d4a 100644 --- a/clippy_lints/src/matches/match_same_arms.rs +++ b/clippy_lints/src/matches/match_same_arms.rs @@ -8,11 +8,10 @@ use rustc_arena::DroplessArena; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir::def_id::DefId; -use rustc_hir::{Arm, Expr, ExprKind, HirId, HirIdMap, HirIdSet, Pat, PatKind, RangeEnd}; +use rustc_hir::{Arm, Expr, ExprKind, HirId, HirIdMap, HirIdMapEntry, HirIdSet, Pat, PatKind, RangeEnd}; use rustc_lint::LateContext; use rustc_middle::ty; use rustc_span::Symbol; -use std::collections::hash_map::Entry; use super::MATCH_SAME_ARMS; @@ -71,9 +70,9 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>]) { if let Some(a_id) = path_to_local(a); if let Some(b_id) = path_to_local(b); let entry = match local_map.entry(a_id) { - Entry::Vacant(entry) => entry, + HirIdMapEntry::Vacant(entry) => entry, // check if using the same bindings as before - Entry::Occupied(entry) => return *entry.get() == b_id, + HirIdMapEntry::Occupied(entry) => return *entry.get() == b_id, }; // the names technically don't have to match; this makes the lint more conservative if cx.tcx.hir().name(a_id) == cx.tcx.hir().name(b_id); From f6005c6b89e1d4752add58a49a3e84884a513022 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Mon, 12 Sep 2022 13:13:22 +1000 Subject: [PATCH 10/34] Remove unused span argument from `walk_fn`. --- clippy_lints/src/derive.rs | 4 ++-- clippy_lints/src/unused_async.rs | 2 +- clippy_lints/src/unwrap.rs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/clippy_lints/src/derive.rs b/clippy_lints/src/derive.rs index 23c86482b..751ca24d5 100644 --- a/clippy_lints/src/derive.rs +++ b/clippy_lints/src/derive.rs @@ -425,7 +425,7 @@ struct UnsafeVisitor<'a, 'tcx> { impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> { type NestedFilter = nested_filter::All; - fn visit_fn(&mut self, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body_id: BodyId, span: Span, id: HirId) { + fn visit_fn(&mut self, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body_id: BodyId, _: Span, id: HirId) { if self.has_unsafe { return; } @@ -438,7 +438,7 @@ impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> { } } - walk_fn(self, kind, decl, body_id, span, id); + walk_fn(self, kind, decl, body_id, id); } fn visit_expr(&mut self, expr: &'tcx Expr<'_>) { diff --git a/clippy_lints/src/unused_async.rs b/clippy_lints/src/unused_async.rs index a832dfccc..bf487c7ca 100644 --- a/clippy_lints/src/unused_async.rs +++ b/clippy_lints/src/unused_async.rs @@ -70,7 +70,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedAsync { ) { if !span.from_expansion() && fn_kind.asyncness() == IsAsync::Async { let mut visitor = AsyncFnVisitor { cx, found_await: false }; - walk_fn(&mut visitor, fn_kind, fn_decl, body.id(), span, hir_id); + walk_fn(&mut visitor, fn_kind, fn_decl, body.id(), hir_id); if !visitor.found_await { span_lint_and_help( cx, diff --git a/clippy_lints/src/unwrap.rs b/clippy_lints/src/unwrap.rs index 7e451b7b7..3ef265580 100644 --- a/clippy_lints/src/unwrap.rs +++ b/clippy_lints/src/unwrap.rs @@ -326,6 +326,6 @@ impl<'tcx> LateLintPass<'tcx> for Unwrap { unwrappables: Vec::new(), }; - walk_fn(&mut v, kind, decl, body.id(), span, fn_id); + walk_fn(&mut v, kind, decl, body.id(), fn_id); } } From 308153563bf008ab3cadec9148c4930521189844 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Mon, 12 Sep 2022 13:30:15 +1000 Subject: [PATCH 11/34] Remove unused span argument from `visit_name`. --- clippy_utils/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clippy_utils/src/lib.rs b/clippy_utils/src/lib.rs index bdb858e1f..23b51ec2d 100644 --- a/clippy_utils/src/lib.rs +++ b/clippy_utils/src/lib.rs @@ -1121,7 +1121,7 @@ pub struct ContainsName { } impl<'tcx> Visitor<'tcx> for ContainsName { - fn visit_name(&mut self, _: Span, name: Symbol) { + fn visit_name(&mut self, name: Symbol) { if self.name == name { self.result = true; } From 0d1469ad348f5ac1b6ed6d6847e8b613b49e00fa Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Mon, 12 Sep 2022 13:37:18 +1000 Subject: [PATCH 12/34] Remove unused argument from `visit_poly_trait_ref`. --- clippy_lints/src/disallowed_types.rs | 4 ++-- clippy_lints/src/lifetimes.rs | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/clippy_lints/src/disallowed_types.rs b/clippy_lints/src/disallowed_types.rs index 14f89edce..28dbfbab2 100644 --- a/clippy_lints/src/disallowed_types.rs +++ b/clippy_lints/src/disallowed_types.rs @@ -2,7 +2,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use rustc_data_structures::fx::FxHashMap; use rustc_hir::{ - def::Res, def_id::DefId, Item, ItemKind, PolyTraitRef, PrimTy, TraitBoundModifier, Ty, TyKind, UseKind, + def::Res, def_id::DefId, Item, ItemKind, PolyTraitRef, PrimTy, Ty, TyKind, UseKind, }; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_tool_lint, impl_lint_pass}; @@ -120,7 +120,7 @@ impl<'tcx> LateLintPass<'tcx> for DisallowedTypes { } } - fn check_poly_trait_ref(&mut self, cx: &LateContext<'tcx>, poly: &'tcx PolyTraitRef<'tcx>, _: TraitBoundModifier) { + fn check_poly_trait_ref(&mut self, cx: &LateContext<'tcx>, poly: &'tcx PolyTraitRef<'tcx>) { self.check_res_emit(cx, &poly.trait_ref.path.res, poly.trait_ref.path.span); } } diff --git a/clippy_lints/src/lifetimes.rs b/clippy_lints/src/lifetimes.rs index f2b6e0b7e..643a7cfd5 100644 --- a/clippy_lints/src/lifetimes.rs +++ b/clippy_lints/src/lifetimes.rs @@ -10,7 +10,7 @@ use rustc_hir::FnRetTy::Return; use rustc_hir::{ BareFnTy, BodyId, FnDecl, GenericArg, GenericBound, GenericParam, GenericParamKind, Generics, Impl, ImplItem, ImplItemKind, Item, ItemKind, LangItem, Lifetime, LifetimeName, ParamName, PolyTraitRef, PredicateOrigin, - TraitBoundModifier, TraitFn, TraitItem, TraitItemKind, Ty, TyKind, WherePredicate, + TraitFn, TraitItem, TraitItemKind, Ty, TyKind, WherePredicate, }; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::nested_filter as middle_nested_filter; @@ -422,7 +422,7 @@ impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> { self.record(&Some(*lifetime)); } - fn visit_poly_trait_ref(&mut self, poly_tref: &'tcx PolyTraitRef<'tcx>, tbm: TraitBoundModifier) { + fn visit_poly_trait_ref(&mut self, poly_tref: &'tcx PolyTraitRef<'tcx>) { let trait_ref = &poly_tref.trait_ref; if CLOSURE_TRAIT_BOUNDS.iter().any(|&item| { self.cx @@ -435,7 +435,7 @@ impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> { sub_visitor.visit_trait_ref(trait_ref); self.nested_elision_site_lts.append(&mut sub_visitor.all_lts()); } else { - walk_poly_trait_ref(self, poly_tref, tbm); + walk_poly_trait_ref(self, poly_tref); } } @@ -466,7 +466,7 @@ impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> { self.unelided_trait_object_lifetime = true; } for bound in bounds { - self.visit_poly_trait_ref(bound, TraitBoundModifier::None); + self.visit_poly_trait_ref(bound); } }, _ => walk_ty(self, ty), From c0e249ce675924f760e94b0426fbb450f1d1c2cb Mon Sep 17 00:00:00 2001 From: Markus Reiter Date: Fri, 2 Sep 2022 01:11:20 +0200 Subject: [PATCH 13/34] Fix clippy. --- .../src/matches/redundant_pattern_match.rs | 81 +++++++++++++++---- 1 file changed, 65 insertions(+), 16 deletions(-) diff --git a/clippy_lints/src/matches/redundant_pattern_match.rs b/clippy_lints/src/matches/redundant_pattern_match.rs index f7443471e..39c8e9a93 100644 --- a/clippy_lints/src/matches/redundant_pattern_match.rs +++ b/clippy_lints/src/matches/redundant_pattern_match.rs @@ -2,7 +2,7 @@ use super::REDUNDANT_PATTERN_MATCHING; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::snippet; use clippy_utils::sugg::Sugg; -use clippy_utils::ty::needs_ordered_drop; +use clippy_utils::ty::{is_type_diagnostic_item, needs_ordered_drop}; use clippy_utils::visitors::any_temporaries_need_ordered_drop; use clippy_utils::{higher, is_lang_ctor, is_trait_method, match_def_path, paths}; use if_chain::if_chain; @@ -12,7 +12,7 @@ use rustc_hir::LangItem::{OptionNone, PollPending}; use rustc_hir::{Arm, Expr, ExprKind, Node, Pat, PatKind, QPath, UnOp}; use rustc_lint::LateContext; use rustc_middle::ty::{self, subst::GenericArgKind, DefIdTree, Ty}; -use rustc_span::sym; +use rustc_span::{sym, Symbol, def_id::DefId}; pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if let Some(higher::WhileLet { let_pat, let_expr, .. }) = higher::WhileLet::hir(expr) { @@ -75,9 +75,9 @@ fn find_sugg_for_if_let<'tcx>( ("is_some()", op_ty) } else if Some(id) == lang_items.poll_ready_variant() { ("is_ready()", op_ty) - } else if match_def_path(cx, id, &paths::IPADDR_V4) { + } else if is_pat_variant(cx, check_pat, qpath, &paths::IPADDR_V4, Item::Diag(sym!(IpAddr), sym!(V4))) { ("is_ipv4()", op_ty) - } else if match_def_path(cx, id, &paths::IPADDR_V6) { + } else if is_pat_variant(cx, check_pat, qpath, &paths::IPADDR_V6, Item::Diag(sym!(IpAddr), sym!(V6))) { ("is_ipv6()", op_ty) } else { return; @@ -174,6 +174,7 @@ fn find_sugg_for_if_let<'tcx>( pub(super) fn check_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op: &Expr<'_>, arms: &[Arm<'_>]) { if arms.len() == 2 { + let lang_items = cx.tcx.lang_items(); let node_pair = (&arms[0].pat.kind, &arms[1].pat.kind); let found_good_method = match node_pair { @@ -188,7 +189,9 @@ pub(super) fn check_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op path_left, path_right, &paths::RESULT_OK, + Item::Lang(lang_items.result_ok_variant()), &paths::RESULT_ERR, + Item::Lang(lang_items.result_err_variant()), "is_ok()", "is_err()", ) @@ -199,7 +202,9 @@ pub(super) fn check_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op path_left, path_right, &paths::IPADDR_V4, + Item::Diag(sym!(IpAddr), sym!(V4)), &paths::IPADDR_V6, + Item::Diag(sym!(IpAddr), sym!(V6)), "is_ipv4()", "is_ipv6()", ) @@ -213,13 +218,16 @@ pub(super) fn check_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op if patterns.len() == 1 => { if let PatKind::Wild = patterns[0].kind { + find_good_method_for_match( cx, arms, path_left, path_right, &paths::OPTION_SOME, + Item::Lang(lang_items.option_some_variant()), &paths::OPTION_NONE, + Item::Lang(lang_items.option_none_variant()), "is_some()", "is_none()", ) @@ -230,7 +238,9 @@ pub(super) fn check_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op path_left, path_right, &paths::POLL_READY, + Item::Lang(lang_items.poll_ready_variant()), &paths::POLL_PENDING, + Item::Lang(lang_items.poll_pending_variant()), "is_ready()", "is_pending()", ) @@ -266,28 +276,67 @@ pub(super) fn check_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op } } +#[derive(Clone, Copy)] +enum Item { + Lang(Option), + Diag(Symbol, Symbol), +} + +fn is_pat_variant(cx: &LateContext<'_>, pat: &Pat<'_>, path: &QPath<'_>, expected_path: &[&str], expected_item: Item) -> bool { + let Some(id) = cx.typeck_results().qpath_res(path, pat.hir_id).opt_def_id() else { return false }; + + // TODO: Path matching can be removed when `IpAddr` is a diagnostic item. + if match_def_path(cx, id, expected_path) { + return true + } + + match expected_item { + Item::Lang(expected_id) => { + Some(cx.tcx.parent(id)) == expected_id + }, + Item::Diag(expected_ty, expected_variant) => { + let ty = cx.typeck_results().pat_ty(pat); + + if is_type_diagnostic_item(cx, ty, expected_ty) { + let variant = ty.ty_adt_def() + .expect("struct pattern type is not an ADT") + .variant_of_res(cx.qpath_res(path, pat.hir_id)); + + return variant.name == expected_variant + } + + false + } + } +} + #[expect(clippy::too_many_arguments)] fn find_good_method_for_match<'a>( cx: &LateContext<'_>, arms: &[Arm<'_>], path_left: &QPath<'_>, path_right: &QPath<'_>, - expected_left: &[&str], - expected_right: &[&str], + expected_path_left: &[&str], + expected_item_left: Item, + expected_path_right: &[&str], + expected_item_right: Item, should_be_left: &'a str, should_be_right: &'a str, ) -> Option<&'a str> { - let left_id = cx - .typeck_results() - .qpath_res(path_left, arms[0].pat.hir_id) - .opt_def_id()?; - let right_id = cx - .typeck_results() - .qpath_res(path_right, arms[1].pat.hir_id) - .opt_def_id()?; - let body_node_pair = if match_def_path(cx, left_id, expected_left) && match_def_path(cx, right_id, expected_right) { + let pat_left = arms[0].pat; + let pat_right = arms[1].pat; + + let body_node_pair = if ( + is_pat_variant(cx, pat_left, path_left, expected_path_left, expected_item_left) + ) && ( + is_pat_variant(cx, pat_right, path_right, expected_path_right, expected_item_right) + ) { (&arms[0].body.kind, &arms[1].body.kind) - } else if match_def_path(cx, right_id, expected_left) && match_def_path(cx, right_id, expected_right) { + } else if ( + is_pat_variant(cx, pat_left, path_left, expected_path_right, expected_item_right) + ) && ( + is_pat_variant(cx, pat_right, path_right, expected_path_left, expected_item_left) + ) { (&arms[1].body.kind, &arms[0].body.kind) } else { return None; From 64a42db51a8d866031fe69cd68a9ca108a8435fa Mon Sep 17 00:00:00 2001 From: Markus Reiter Date: Mon, 12 Sep 2022 19:03:24 +0200 Subject: [PATCH 14/34] Simplify `clippy` fix. --- .../src/matches/redundant_pattern_match.rs | 59 +++++++------------ clippy_utils/src/paths.rs | 2 - 2 files changed, 22 insertions(+), 39 deletions(-) diff --git a/clippy_lints/src/matches/redundant_pattern_match.rs b/clippy_lints/src/matches/redundant_pattern_match.rs index 39c8e9a93..c89784065 100644 --- a/clippy_lints/src/matches/redundant_pattern_match.rs +++ b/clippy_lints/src/matches/redundant_pattern_match.rs @@ -4,15 +4,15 @@ use clippy_utils::source::snippet; use clippy_utils::sugg::Sugg; use clippy_utils::ty::{is_type_diagnostic_item, needs_ordered_drop}; use clippy_utils::visitors::any_temporaries_need_ordered_drop; -use clippy_utils::{higher, is_lang_ctor, is_trait_method, match_def_path, paths}; +use clippy_utils::{higher, is_lang_ctor, is_trait_method}; use if_chain::if_chain; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; -use rustc_hir::LangItem::{OptionNone, PollPending}; +use rustc_hir::LangItem::{self, OptionSome, OptionNone, PollPending, PollReady, ResultOk, ResultErr}; use rustc_hir::{Arm, Expr, ExprKind, Node, Pat, PatKind, QPath, UnOp}; use rustc_lint::LateContext; use rustc_middle::ty::{self, subst::GenericArgKind, DefIdTree, Ty}; -use rustc_span::{sym, Symbol, def_id::DefId}; +use rustc_span::{sym, Symbol}; pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if let Some(higher::WhileLet { let_pat, let_expr, .. }) = higher::WhileLet::hir(expr) { @@ -75,9 +75,9 @@ fn find_sugg_for_if_let<'tcx>( ("is_some()", op_ty) } else if Some(id) == lang_items.poll_ready_variant() { ("is_ready()", op_ty) - } else if is_pat_variant(cx, check_pat, qpath, &paths::IPADDR_V4, Item::Diag(sym!(IpAddr), sym!(V4))) { + } else if is_pat_variant(cx, check_pat, qpath, Item::Diag(sym::IpAddr, sym!(V4))) { ("is_ipv4()", op_ty) - } else if is_pat_variant(cx, check_pat, qpath, &paths::IPADDR_V6, Item::Diag(sym!(IpAddr), sym!(V6))) { + } else if is_pat_variant(cx, check_pat, qpath, Item::Diag(sym::IpAddr, sym!(V6))) { ("is_ipv6()", op_ty) } else { return; @@ -174,7 +174,6 @@ fn find_sugg_for_if_let<'tcx>( pub(super) fn check_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op: &Expr<'_>, arms: &[Arm<'_>]) { if arms.len() == 2 { - let lang_items = cx.tcx.lang_items(); let node_pair = (&arms[0].pat.kind, &arms[1].pat.kind); let found_good_method = match node_pair { @@ -188,10 +187,8 @@ pub(super) fn check_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op arms, path_left, path_right, - &paths::RESULT_OK, - Item::Lang(lang_items.result_ok_variant()), - &paths::RESULT_ERR, - Item::Lang(lang_items.result_err_variant()), + Item::Lang(ResultOk), + Item::Lang(ResultErr), "is_ok()", "is_err()", ) @@ -201,10 +198,8 @@ pub(super) fn check_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op arms, path_left, path_right, - &paths::IPADDR_V4, - Item::Diag(sym!(IpAddr), sym!(V4)), - &paths::IPADDR_V6, - Item::Diag(sym!(IpAddr), sym!(V6)), + Item::Diag(sym::IpAddr, sym!(V4)), + Item::Diag(sym::IpAddr, sym!(V6)), "is_ipv4()", "is_ipv6()", ) @@ -224,10 +219,8 @@ pub(super) fn check_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op arms, path_left, path_right, - &paths::OPTION_SOME, - Item::Lang(lang_items.option_some_variant()), - &paths::OPTION_NONE, - Item::Lang(lang_items.option_none_variant()), + Item::Lang(OptionSome), + Item::Lang(OptionNone), "is_some()", "is_none()", ) @@ -237,10 +230,8 @@ pub(super) fn check_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op arms, path_left, path_right, - &paths::POLL_READY, - Item::Lang(lang_items.poll_ready_variant()), - &paths::POLL_PENDING, - Item::Lang(lang_items.poll_pending_variant()), + Item::Lang(PollReady), + Item::Lang(PollPending), "is_ready()", "is_pending()", ) @@ -278,21 +269,17 @@ pub(super) fn check_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op #[derive(Clone, Copy)] enum Item { - Lang(Option), + Lang(LangItem), Diag(Symbol, Symbol), } -fn is_pat_variant(cx: &LateContext<'_>, pat: &Pat<'_>, path: &QPath<'_>, expected_path: &[&str], expected_item: Item) -> bool { +fn is_pat_variant(cx: &LateContext<'_>, pat: &Pat<'_>, path: &QPath<'_>, expected_item: Item) -> bool { let Some(id) = cx.typeck_results().qpath_res(path, pat.hir_id).opt_def_id() else { return false }; - // TODO: Path matching can be removed when `IpAddr` is a diagnostic item. - if match_def_path(cx, id, expected_path) { - return true - } - match expected_item { - Item::Lang(expected_id) => { - Some(cx.tcx.parent(id)) == expected_id + Item::Lang(expected_lang_item) => { + let expected_id = cx.tcx.lang_items().require(expected_lang_item).unwrap(); + cx.tcx.parent(id) == expected_id }, Item::Diag(expected_ty, expected_variant) => { let ty = cx.typeck_results().pat_ty(pat); @@ -316,9 +303,7 @@ fn find_good_method_for_match<'a>( arms: &[Arm<'_>], path_left: &QPath<'_>, path_right: &QPath<'_>, - expected_path_left: &[&str], expected_item_left: Item, - expected_path_right: &[&str], expected_item_right: Item, should_be_left: &'a str, should_be_right: &'a str, @@ -327,15 +312,15 @@ fn find_good_method_for_match<'a>( let pat_right = arms[1].pat; let body_node_pair = if ( - is_pat_variant(cx, pat_left, path_left, expected_path_left, expected_item_left) + is_pat_variant(cx, pat_left, path_left, expected_item_left) ) && ( - is_pat_variant(cx, pat_right, path_right, expected_path_right, expected_item_right) + is_pat_variant(cx, pat_right, path_right, expected_item_right) ) { (&arms[0].body.kind, &arms[1].body.kind) } else if ( - is_pat_variant(cx, pat_left, path_left, expected_path_right, expected_item_right) + is_pat_variant(cx, pat_left, path_left, expected_item_right) ) && ( - is_pat_variant(cx, pat_right, path_right, expected_path_left, expected_item_left) + is_pat_variant(cx, pat_right, path_right, expected_item_left) ) { (&arms[1].body.kind, &arms[0].body.kind) } else { diff --git a/clippy_utils/src/paths.rs b/clippy_utils/src/paths.rs index fb0d34e02..07170e2df 100644 --- a/clippy_utils/src/paths.rs +++ b/clippy_utils/src/paths.rs @@ -66,8 +66,6 @@ pub const INDEX_MUT: [&str; 3] = ["core", "ops", "IndexMut"]; pub const INSERT_STR: [&str; 4] = ["alloc", "string", "String", "insert_str"]; pub const IO_READ: [&str; 3] = ["std", "io", "Read"]; pub const IO_WRITE: [&str; 3] = ["std", "io", "Write"]; -pub const IPADDR_V4: [&str; 5] = ["std", "net", "ip", "IpAddr", "V4"]; -pub const IPADDR_V6: [&str; 5] = ["std", "net", "ip", "IpAddr", "V6"]; pub const ITER_COUNT: [&str; 6] = ["core", "iter", "traits", "iterator", "Iterator", "count"]; pub const ITER_EMPTY: [&str; 5] = ["core", "iter", "sources", "empty", "Empty"]; pub const ITER_REPEAT: [&str; 5] = ["core", "iter", "sources", "repeat", "repeat"]; From b95b285ef4831ea1342e4aead7aa245156b24cb7 Mon Sep 17 00:00:00 2001 From: Eric Holk Date: Tue, 30 Aug 2022 12:39:28 -0700 Subject: [PATCH 15/34] Make x.py check work --- clippy_lints/src/transmute/utils.rs | 29 ++-- clippy_utils/src/qualify_min_const_fn.rs | 141 +++++++++++-------- clippy_utils/src/ty.rs | 165 ++++++++++++++--------- 3 files changed, 204 insertions(+), 131 deletions(-) diff --git a/clippy_lints/src/transmute/utils.rs b/clippy_lints/src/transmute/utils.rs index 74927570b..78cc589cc 100644 --- a/clippy_lints/src/transmute/utils.rs +++ b/clippy_lints/src/transmute/utils.rs @@ -2,11 +2,18 @@ use rustc_hir::Expr; use rustc_lint::LateContext; use rustc_middle::ty::{cast::CastKind, Ty}; use rustc_span::DUMMY_SP; -use rustc_typeck::check::{cast::CastCheck, FnCtxt, Inherited}; +use rustc_typeck::check::{ + cast::{self, CastCheckResult}, + FnCtxt, Inherited, +}; // check if the component types of the transmuted collection and the result have different ABI, // size or alignment -pub(super) fn is_layout_incompatible<'tcx>(cx: &LateContext<'tcx>, from: Ty<'tcx>, to: Ty<'tcx>) -> bool { +pub(super) fn is_layout_incompatible<'tcx>( + cx: &LateContext<'tcx>, + from: Ty<'tcx>, + to: Ty<'tcx>, +) -> bool { if let Ok(from) = cx.tcx.try_normalize_erasing_regions(cx.param_env, from) && let Ok(to) = cx.tcx.try_normalize_erasing_regions(cx.param_env, to) && let Ok(from_layout) = cx.tcx.layout_of(cx.param_env.and(from)) @@ -29,7 +36,9 @@ pub(super) fn can_be_expressed_as_pointer_cast<'tcx>( from_ty: Ty<'tcx>, to_ty: Ty<'tcx>, ) -> bool { - use CastKind::{AddrPtrCast, ArrayPtrCast, FnPtrAddrCast, FnPtrPtrCast, PtrAddrCast, PtrPtrCast}; + use CastKind::{ + AddrPtrCast, ArrayPtrCast, FnPtrAddrCast, FnPtrPtrCast, PtrAddrCast, PtrPtrCast, + }; matches!( check_cast(cx, e, from_ty, to_ty), Some(PtrPtrCast | PtrAddrCast | AddrPtrCast | ArrayPtrCast | FnPtrPtrCast | FnPtrAddrCast) @@ -40,7 +49,12 @@ pub(super) fn can_be_expressed_as_pointer_cast<'tcx>( /// the cast. In certain cases, including some invalid casts from array references /// to pointers, this may cause additional errors to be emitted and/or ICE error /// messages. This function will panic if that occurs. -fn check_cast<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> Option { +fn check_cast<'tcx>( + cx: &LateContext<'tcx>, + e: &'tcx Expr<'_>, + from_ty: Ty<'tcx>, + to_ty: Ty<'tcx>, +) -> Option { let hir_id = e.hir_id; let local_def_id = hir_id.owner; @@ -48,12 +62,9 @@ fn check_cast<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx> let fn_ctxt = FnCtxt::new(&inherited, cx.param_env, hir_id); // If we already have errors, we can't be sure we can pointer cast. - assert!( - !fn_ctxt.errors_reported_since_creation(), - "Newly created FnCtxt contained errors" - ); + assert!(!fn_ctxt.errors_reported_since_creation(), "Newly created FnCtxt contained errors"); - if let Ok(check) = CastCheck::new( + if let CastCheckResult::Deferred(check) = cast::check_cast( &fn_ctxt, e, from_ty, to_ty, // We won't show any error to the user, so we don't care what the span is here. DUMMY_SP, DUMMY_SP, diff --git a/clippy_utils/src/qualify_min_const_fn.rs b/clippy_utils/src/qualify_min_const_fn.rs index d5f64e511..781744870 100644 --- a/clippy_utils/src/qualify_min_const_fn.rs +++ b/clippy_utils/src/qualify_min_const_fn.rs @@ -18,7 +18,11 @@ use std::borrow::Cow; type McfResult = Result<(), (Span, Cow<'static, str>)>; -pub fn is_min_const_fn<'a, 'tcx>(tcx: TyCtxt<'tcx>, body: &'a Body<'tcx>, msrv: Option) -> McfResult { +pub fn is_min_const_fn<'a, 'tcx>( + tcx: TyCtxt<'tcx>, + body: &'a Body<'tcx>, + msrv: Option, +) -> McfResult { let def_id = body.source.def_id(); let mut current = def_id; loop { @@ -33,10 +37,18 @@ pub fn is_min_const_fn<'a, 'tcx>(tcx: TyCtxt<'tcx>, body: &'a Body<'tcx>, msrv: | ty::PredicateKind::ConstEquate(..) | ty::PredicateKind::Trait(..) | ty::PredicateKind::TypeWellFormedFromEnv(..) => continue, - ty::PredicateKind::ObjectSafe(_) => panic!("object safe predicate on function: {:#?}", predicate), - ty::PredicateKind::ClosureKind(..) => panic!("closure kind predicate on function: {:#?}", predicate), - ty::PredicateKind::Subtype(_) => panic!("subtype predicate on function: {:#?}", predicate), - ty::PredicateKind::Coerce(_) => panic!("coerce predicate on function: {:#?}", predicate), + ty::PredicateKind::ObjectSafe(_) => { + panic!("object safe predicate on function: {:#?}", predicate) + } + ty::PredicateKind::ClosureKind(..) => { + panic!("closure kind predicate on function: {:#?}", predicate) + } + ty::PredicateKind::Subtype(_) => { + panic!("subtype predicate on function: {:#?}", predicate) + } + ty::PredicateKind::Coerce(_) => { + panic!("coerce predicate on function: {:#?}", predicate) + } } } match predicates.parent { @@ -77,22 +89,23 @@ fn check_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span) -> McfResult { match ty.kind() { ty::Ref(_, _, hir::Mutability::Mut) => { return Err((span, "mutable references in const fn are unstable".into())); - }, + } ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())), ty::FnPtr(..) => { return Err((span, "function pointers in const fn are unstable".into())); - }, - ty::Dynamic(preds, _) => { + } + ty::Dynamic(preds, _, _) => { for pred in preds.iter() { match pred.skip_binder() { - ty::ExistentialPredicate::AutoTrait(_) | ty::ExistentialPredicate::Projection(_) => { + ty::ExistentialPredicate::AutoTrait(_) + | ty::ExistentialPredicate::Projection(_) => { return Err(( span, "trait bounds other than `Sized` \ on const fn parameters are unstable" .into(), )); - }, + } ty::ExistentialPredicate::Trait(trait_ref) => { if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() { return Err(( @@ -102,11 +115,11 @@ fn check_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span) -> McfResult { .into(), )); } - }, + } } } - }, - _ => {}, + } + _ => {} } } Ok(()) @@ -120,10 +133,13 @@ fn check_rvalue<'tcx>( span: Span, ) -> McfResult { match rvalue { - Rvalue::ThreadLocalRef(_) => Err((span, "cannot access thread local storage in const fn".into())), - Rvalue::Len(place) | Rvalue::Discriminant(place) | Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => { - check_place(tcx, *place, span, body) - }, + Rvalue::ThreadLocalRef(_) => { + Err((span, "cannot access thread local storage in const fn".into())) + } + Rvalue::Len(place) + | Rvalue::Discriminant(place) + | Rvalue::Ref(_, _, place) + | Rvalue::AddressOf(_, place) => check_place(tcx, *place, span, body), Rvalue::CopyForDeref(place) => check_place(tcx, *place, span, body), Rvalue::Repeat(operand, _) | Rvalue::Use(operand) @@ -136,7 +152,9 @@ fn check_rvalue<'tcx>( ) => check_operand(tcx, operand, span, body), Rvalue::Cast( CastKind::Pointer( - PointerCast::UnsafeFnPointer | PointerCast::ClosureFnPointer(_) | PointerCast::ReifyFnPointer, + PointerCast::UnsafeFnPointer + | PointerCast::ClosureFnPointer(_) + | PointerCast::ReifyFnPointer, ), _, _, @@ -146,7 +164,10 @@ fn check_rvalue<'tcx>( deref_ty.ty } else { // We cannot allow this for now. - return Err((span, "unsizing casts are only allowed for references right now".into())); + return Err(( + span, + "unsizing casts are only allowed for references right now".into(), + )); }; let unsized_ty = tcx.struct_tail_erasing_lifetimes(pointee_ty, tcx.param_env(def_id)); if let ty::Slice(_) | ty::Str = unsized_ty.kind() { @@ -157,10 +178,14 @@ fn check_rvalue<'tcx>( // We just can't allow trait objects until we have figured out trait method calls. Err((span, "unsizing casts are not allowed in const fn".into())) } - }, + } Rvalue::Cast(CastKind::PointerExposeAddress, _, _) => { Err((span, "casting pointers to ints is unstable in const fn".into())) - }, + } + Rvalue::Cast(CastKind::DynStar, _, _) => { + // FIXME(dyn-star) + unimplemented!() + } // binops are fine on integers Rvalue::BinaryOp(_, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(_, box (lhs, rhs)) => { check_operand(tcx, lhs, span, body)?; @@ -169,13 +194,12 @@ fn check_rvalue<'tcx>( if ty.is_integral() || ty.is_bool() || ty.is_char() { Ok(()) } else { - Err(( - span, - "only int, `bool` and `char` operations are stable in const fn".into(), - )) + Err((span, "only int, `bool` and `char` operations are stable in const fn".into())) } - }, - Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf, _) | Rvalue::ShallowInitBox(_, _) => Ok(()), + } + Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf, _) | Rvalue::ShallowInitBox(_, _) => { + Ok(()) + } Rvalue::UnaryOp(_, operand) => { let ty = operand.ty(body, tcx); if ty.is_integral() || ty.is_bool() { @@ -183,13 +207,13 @@ fn check_rvalue<'tcx>( } else { Err((span, "only int and `bool` operations are stable in const fn".into())) } - }, + } Rvalue::Aggregate(_, operands) => { for operand in operands { check_operand(tcx, operand, span, body)?; } Ok(()) - }, + } } } @@ -204,7 +228,7 @@ fn check_statement<'tcx>( StatementKind::Assign(box (place, rval)) => { check_place(tcx, *place, span, body)?; check_rvalue(tcx, body, def_id, rval, span) - }, + } StatementKind::FakeRead(box (_, place)) => check_place(tcx, *place, span, body), // just an assignment @@ -214,14 +238,15 @@ fn check_statement<'tcx>( StatementKind::Intrinsic(box NonDivergingIntrinsic::Assume(op)) => check_operand(tcx, op, span, body), - StatementKind::Intrinsic(box NonDivergingIntrinsic::CopyNonOverlapping( - rustc_middle::mir::CopyNonOverlapping { dst, src, count }, - )) => { + StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping { + dst, + src, + count, + }) => { check_operand(tcx, dst, span, body)?; check_operand(tcx, src, span, body)?; check_operand(tcx, count, span, body) - }, - + } // These are all NOPs StatementKind::StorageLive(_) | StatementKind::StorageDead(_) @@ -232,7 +257,12 @@ fn check_statement<'tcx>( } } -fn check_operand<'tcx>(tcx: TyCtxt<'tcx>, operand: &Operand<'tcx>, span: Span, body: &Body<'tcx>) -> McfResult { +fn check_operand<'tcx>( + tcx: TyCtxt<'tcx>, + operand: &Operand<'tcx>, + span: Span, + body: &Body<'tcx>, +) -> McfResult { match operand { Operand::Move(place) | Operand::Copy(place) => check_place(tcx, *place, span, body), Operand::Constant(c) => match c.check_static_ptr(tcx) { @@ -242,7 +272,12 @@ fn check_operand<'tcx>(tcx: TyCtxt<'tcx>, operand: &Operand<'tcx>, span: Span, b } } -fn check_place<'tcx>(tcx: TyCtxt<'tcx>, place: Place<'tcx>, span: Span, body: &Body<'tcx>) -> McfResult { +fn check_place<'tcx>( + tcx: TyCtxt<'tcx>, + place: Place<'tcx>, + span: Span, + body: &Body<'tcx>, +) -> McfResult { let mut cursor = place.projection.as_ref(); while let [ref proj_base @ .., elem] = *cursor { cursor = proj_base; @@ -255,12 +290,12 @@ fn check_place<'tcx>(tcx: TyCtxt<'tcx>, place: Place<'tcx>, span: Span, body: &B return Err((span, "accessing union fields is unstable".into())); } } - }, + } ProjectionElem::ConstantIndex { .. } | ProjectionElem::Downcast(..) | ProjectionElem::Subslice { .. } | ProjectionElem::Deref - | ProjectionElem::Index(_) => {}, + | ProjectionElem::Index(_) => {} } } @@ -286,18 +321,16 @@ fn check_terminator<'a, 'tcx>( TerminatorKind::DropAndReplace { place, value, .. } => { check_place(tcx, *place, span, body)?; check_operand(tcx, value, span, body) - }, + } - TerminatorKind::SwitchInt { - discr, - switch_ty: _, - targets: _, - } => check_operand(tcx, discr, span, body), + TerminatorKind::SwitchInt { discr, switch_ty: _, targets: _ } => { + check_operand(tcx, discr, span, body) + } TerminatorKind::Abort => Err((span, "abort is not stable in const fn".into())), TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => { Err((span, "const fn generators are unstable".into())) - }, + } TerminatorKind::Call { func, @@ -342,17 +375,15 @@ fn check_terminator<'a, 'tcx>( } else { Err((span, "can only call other const fns within const fn".into())) } - }, + } - TerminatorKind::Assert { - cond, - expected: _, - msg: _, - target: _, - cleanup: _, - } => check_operand(tcx, cond, span, body), + TerminatorKind::Assert { cond, expected: _, msg: _, target: _, cleanup: _ } => { + check_operand(tcx, cond, span, body) + } - TerminatorKind::InlineAsm { .. } => Err((span, "cannot use inline assembly in const fn".into())), + TerminatorKind::InlineAsm { .. } => { + Err((span, "cannot use inline assembly in const fn".into())) + } } } diff --git a/clippy_utils/src/ty.rs b/clippy_utils/src/ty.rs index 5a7f95684..99803ae93 100644 --- a/clippy_utils/src/ty.rs +++ b/clippy_utils/src/ty.rs @@ -14,8 +14,9 @@ use rustc_lint::LateContext; use rustc_middle::mir::interpret::{ConstValue, Scalar}; use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst}; use rustc_middle::ty::{ - self, AdtDef, Binder, BoundRegion, DefIdTree, FnSig, IntTy, ParamEnv, Predicate, PredicateKind, ProjectionTy, - Region, RegionKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor, UintTy, VariantDef, VariantDiscr, + self, AdtDef, Binder, BoundRegion, DefIdTree, FnSig, IntTy, ParamEnv, Predicate, PredicateKind, + ProjectionTy, Region, RegionKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor, + UintTy, VariantDef, VariantDiscr, }; use rustc_span::symbol::Ident; use rustc_span::{sym, Span, Symbol, DUMMY_SP}; @@ -166,9 +167,7 @@ pub fn implements_trait_with_env<'tcx>( } let ty_params = tcx.mk_substs(ty_params.iter()); tcx.infer_ctxt().enter(|infcx| { - infcx - .type_implements_trait(trait_id, ty, ty_params, param_env) - .must_apply_modulo_regions() + infcx.type_implements_trait(trait_id, ty, ty_params, param_env).must_apply_modulo_regions() }) } @@ -185,11 +184,14 @@ pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { match ty.kind() { ty::Adt(adt, _) => cx.tcx.has_attr(adt.did(), sym::must_use), ty::Foreign(did) => cx.tcx.has_attr(*did, sym::must_use), - ty::Slice(ty) | ty::Array(ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) | ty::Ref(_, ty, _) => { + ty::Slice(ty) + | ty::Array(ty, _) + | ty::RawPtr(ty::TypeAndMut { ty, .. }) + | ty::Ref(_, ty, _) => { // for the Array case we don't need to care for the len == 0 case // because we don't want to lint functions returning empty arrays is_must_use_ty(cx, *ty) - }, + } ty::Tuple(substs) => substs.iter().any(|ty| is_must_use_ty(cx, ty)), ty::Opaque(def_id, _) => { for (predicate, _) in cx.tcx.explicit_item_bounds(*def_id) { @@ -200,8 +202,8 @@ pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { } } false - }, - ty::Dynamic(binder, _) => { + } + ty::Dynamic(binder, _, _) => { for predicate in binder.iter() { if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() { if cx.tcx.has_attr(trait_ref.def_id, sym::must_use) { @@ -210,7 +212,7 @@ pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { } } false - }, + } _ => false, } } @@ -220,7 +222,11 @@ pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { // not succeed /// Checks if `Ty` is normalizable. This function is useful /// to avoid crashes on `layout_of`. -pub fn is_normalizable<'tcx>(cx: &LateContext<'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool { +pub fn is_normalizable<'tcx>( + cx: &LateContext<'tcx>, + param_env: ty::ParamEnv<'tcx>, + ty: Ty<'tcx>, +) -> bool { is_normalizable_helper(cx, param_env, ty, &mut FxHashMap::default()) } @@ -240,15 +246,14 @@ fn is_normalizable_helper<'tcx>( if infcx.at(&cause, param_env).normalize(ty).is_ok() { match ty.kind() { ty::Adt(def, substs) => def.variants().iter().all(|variant| { - variant - .fields - .iter() - .all(|field| is_normalizable_helper(cx, param_env, field.ty(cx.tcx, substs), cache)) + variant.fields.iter().all(|field| { + is_normalizable_helper(cx, param_env, field.ty(cx.tcx, substs), cache) + }) }), _ => ty.walk().all(|generic_arg| match generic_arg.unpack() { GenericArgKind::Type(inner_ty) if inner_ty != ty => { is_normalizable_helper(cx, param_env, inner_ty, cache) - }, + } _ => true, // if inner_ty == ty, we've already checked it }), } @@ -273,7 +278,9 @@ pub fn is_recursively_primitive_type(ty: Ty<'_>) -> bool { match *ty.kind() { ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => true, ty::Ref(_, inner, _) if *inner.kind() == ty::Str => true, - ty::Array(inner_type, _) | ty::Slice(inner_type) => is_recursively_primitive_type(inner_type), + ty::Array(inner_type, _) | ty::Slice(inner_type) => { + is_recursively_primitive_type(inner_type) + } ty::Tuple(inner_types) => inner_types.iter().all(is_recursively_primitive_type), _ => false, } @@ -313,11 +320,9 @@ pub fn is_type_diagnostic_item(cx: &LateContext<'_>, ty: Ty<'_>, diag_item: Symb /// Returns `false` if the `LangItem` is not defined. pub fn is_type_lang_item(cx: &LateContext<'_>, ty: Ty<'_>, lang_item: hir::LangItem) -> bool { match ty.kind() { - ty::Adt(adt, _) => cx - .tcx - .lang_items() - .require(lang_item) - .map_or(false, |li| li == adt.did()), + ty::Adt(adt, _) => { + cx.tcx.lang_items().require(lang_item).map_or(false, |li| li == adt.did()) + } _ => false, } } @@ -342,7 +347,11 @@ pub fn match_type(cx: &LateContext<'_>, ty: Ty<'_>, path: &[&str]) -> bool { /// deallocate memory. For these types, and composites containing them, changing the drop order /// won't result in any observable side effects. pub fn needs_ordered_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { - fn needs_ordered_drop_inner<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, seen: &mut FxHashSet>) -> bool { + fn needs_ordered_drop_inner<'tcx>( + cx: &LateContext<'tcx>, + ty: Ty<'tcx>, + seen: &mut FxHashSet>, + ) -> bool { if !seen.insert(ty) { return false; } @@ -393,11 +402,7 @@ pub fn needs_ordered_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { /// removed. pub fn peel_mid_ty_refs(ty: Ty<'_>) -> (Ty<'_>, usize) { fn peel(ty: Ty<'_>, count: usize) -> (Ty<'_>, usize) { - if let ty::Ref(_, ty, _) = ty.kind() { - peel(*ty, count + 1) - } else { - (ty, count) - } + if let ty::Ref(_, ty, _) = ty.kind() { peel(*ty, count + 1) } else { (ty, count) } } peel(ty, 0) } @@ -452,17 +457,18 @@ pub fn same_type_and_consts<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool { return false; } - substs_a - .iter() - .zip(substs_b.iter()) - .all(|(arg_a, arg_b)| match (arg_a.unpack(), arg_b.unpack()) { - (GenericArgKind::Const(inner_a), GenericArgKind::Const(inner_b)) => inner_a == inner_b, + substs_a.iter().zip(substs_b.iter()).all(|(arg_a, arg_b)| { + match (arg_a.unpack(), arg_b.unpack()) { + (GenericArgKind::Const(inner_a), GenericArgKind::Const(inner_b)) => { + inner_a == inner_b + } (GenericArgKind::Type(type_a), GenericArgKind::Type(type_b)) => { same_type_and_consts(type_a, type_b) - }, + } _ => true, - }) - }, + } + }) + } _ => a == b, } } @@ -478,7 +484,10 @@ pub fn is_uninit_value_valid_for_ty(cx: &LateContext<'_>, ty: Ty<'_>) -> bool { } /// Gets an iterator over all predicates which apply to the given item. -pub fn all_predicates_of(tcx: TyCtxt<'_>, id: DefId) -> impl Iterator, Span)> { +pub fn all_predicates_of( + tcx: TyCtxt<'_>, + id: DefId, +) -> impl Iterator, Span)> { let mut next_id = Some(id); iter::from_fn(move || { next_id.take().map(|id| { @@ -508,7 +517,7 @@ impl<'tcx> ExprFnSig<'tcx> { } else { Some(sig.input(i)) } - }, + } Self::Closure(_, sig) => Some(sig.input(0).map_bound(|ty| ty.tuple_fields()[i])), Self::Trait(inputs, _, _) => Some(inputs.map_bound(|ty| ty.tuple_fields()[i])), } @@ -517,7 +526,10 @@ impl<'tcx> ExprFnSig<'tcx> { /// Gets the argument type at the given offset. For closures this will also get the type as /// written. This will return `None` when the index is out of bounds only for variadic /// functions, otherwise this will panic. - pub fn input_with_hir(self, i: usize) -> Option<(Option<&'tcx hir::Ty<'tcx>>, Binder<'tcx, Ty<'tcx>>)> { + pub fn input_with_hir( + self, + i: usize, + ) -> Option<(Option<&'tcx hir::Ty<'tcx>>, Binder<'tcx, Ty<'tcx>>)> { match self { Self::Sig(sig, _) => { if sig.c_variadic() { @@ -528,7 +540,7 @@ impl<'tcx> ExprFnSig<'tcx> { } else { Some((None, sig.input(i))) } - }, + } Self::Closure(decl, sig) => Some(( decl.and_then(|decl| decl.inputs.get(i)), sig.input(0).map_bound(|ty| ty.tuple_fields()[i]), @@ -547,17 +559,15 @@ impl<'tcx> ExprFnSig<'tcx> { } pub fn predicates_id(&self) -> Option { - if let ExprFnSig::Sig(_, id) | ExprFnSig::Trait(_, _, id) = *self { - id - } else { - None - } + if let ExprFnSig::Sig(_, id) | ExprFnSig::Trait(_, _, id) = *self { id } else { None } } } /// If the expression is function like, get the signature for it. pub fn expr_sig<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> Option> { - if let Res::Def(DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::AssocFn, id) = path_res(cx, expr) { + if let Res::Def(DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::AssocFn, id) = + path_res(cx, expr) + { Some(ExprFnSig::Sig(cx.tcx.fn_sig(id), Some(id))) } else { ty_sig(cx, cx.typeck_results().expr_ty_adjusted(expr).peel_refs()) @@ -571,15 +581,17 @@ pub fn ty_sig<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option { - let decl = id - .as_local() - .and_then(|id| cx.tcx.hir().fn_decl_by_hir_id(cx.tcx.hir().local_def_id_to_hir_id(id))); + let decl = id.as_local().and_then(|id| { + cx.tcx.hir().fn_decl_by_hir_id(cx.tcx.hir().local_def_id_to_hir_id(id)) + }); Some(ExprFnSig::Closure(decl, subs.as_closure().sig())) - }, - ty::FnDef(id, subs) => Some(ExprFnSig::Sig(cx.tcx.bound_fn_sig(id).subst(cx.tcx, subs), Some(id))), + } + ty::FnDef(id, subs) => { + Some(ExprFnSig::Sig(cx.tcx.bound_fn_sig(id).subst(cx.tcx, subs), Some(id))) + } ty::Opaque(id, _) => sig_from_bounds(cx, ty, cx.tcx.item_bounds(id), cx.tcx.opt_parent(id)), ty::FnPtr(sig) => Some(ExprFnSig::Sig(sig, None)), - ty::Dynamic(bounds, _) => { + ty::Dynamic(bounds, _, _) => { let lang_items = cx.tcx.lang_items(); match bounds.principal() { Some(bound) @@ -589,16 +601,19 @@ pub fn ty_sig<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option None, } - }, + } ty::Projection(proj) => match cx.tcx.try_normalize_erasing_regions(cx.param_env, ty) { Ok(normalized_ty) if normalized_ty != ty => ty_sig(cx, normalized_ty), - _ => sig_for_projection(cx, proj).or_else(|| sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None)), + _ => sig_for_projection(cx, proj) + .or_else(|| sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None)), }, ty::Param(_) => sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None), _ => None, @@ -629,7 +644,7 @@ fn sig_from_bounds<'tcx>( return None; } inputs = Some(i); - }, + } PredicateKind::Projection(p) if Some(p.projection_ty.item_def_id) == lang_items.fn_once_output() && p.projection_ty.self_ty() == ty => @@ -639,7 +654,7 @@ fn sig_from_bounds<'tcx>( return None; } output = Some(pred.kind().rebind(p.term.ty().unwrap())); - }, + } _ => (), } } @@ -647,7 +662,10 @@ fn sig_from_bounds<'tcx>( inputs.map(|ty| ExprFnSig::Trait(ty, output, predicates_id)) } -fn sig_for_projection<'tcx>(cx: &LateContext<'tcx>, ty: ProjectionTy<'tcx>) -> Option> { +fn sig_for_projection<'tcx>( + cx: &LateContext<'tcx>, + ty: ProjectionTy<'tcx>, +) -> Option> { let mut inputs = None; let mut output = None; let lang_items = cx.tcx.lang_items(); @@ -673,8 +691,10 @@ fn sig_for_projection<'tcx>(cx: &LateContext<'tcx>, ty: ProjectionTy<'tcx>) -> O return None; } inputs = Some(i); - }, - PredicateKind::Projection(p) if Some(p.projection_ty.item_def_id) == lang_items.fn_once_output() => { + } + PredicateKind::Projection(p) + if Some(p.projection_ty.item_def_id) == lang_items.fn_once_output() => + { if output.is_some() { // Multiple different fn trait impls. Is this even allowed? return None; @@ -683,7 +703,7 @@ fn sig_for_projection<'tcx>(cx: &LateContext<'tcx>, ty: ProjectionTy<'tcx>) -> O pred.map_bound(|pred| pred.kind().rebind(p.term.ty().unwrap())) .subst(cx.tcx, ty.substs), ); - }, + } _ => (), } } @@ -777,7 +797,10 @@ pub fn for_each_top_level_late_bound_region( ControlFlow::Continue(()) } } - fn visit_binder>(&mut self, t: &Binder<'tcx, T>) -> ControlFlow { + fn visit_binder>( + &mut self, + t: &Binder<'tcx, T>, + ) -> ControlFlow { self.index += 1; let res = t.super_visit_with(self); self.index -= 1; @@ -791,19 +814,27 @@ pub fn for_each_top_level_late_bound_region( pub fn variant_of_res<'tcx>(cx: &LateContext<'tcx>, res: Res) -> Option<&'tcx VariantDef> { match res { Res::Def(DefKind::Struct, id) => Some(cx.tcx.adt_def(id).non_enum_variant()), - Res::Def(DefKind::Variant, id) => Some(cx.tcx.adt_def(cx.tcx.parent(id)).variant_with_id(id)), - Res::Def(DefKind::Ctor(CtorOf::Struct, _), id) => Some(cx.tcx.adt_def(cx.tcx.parent(id)).non_enum_variant()), + Res::Def(DefKind::Variant, id) => { + Some(cx.tcx.adt_def(cx.tcx.parent(id)).variant_with_id(id)) + } + Res::Def(DefKind::Ctor(CtorOf::Struct, _), id) => { + Some(cx.tcx.adt_def(cx.tcx.parent(id)).non_enum_variant()) + } Res::Def(DefKind::Ctor(CtorOf::Variant, _), id) => { let var_id = cx.tcx.parent(id); Some(cx.tcx.adt_def(cx.tcx.parent(var_id)).variant_with_id(var_id)) - }, + } Res::SelfCtor(id) => Some(cx.tcx.type_of(id).ty_adt_def().unwrap().non_enum_variant()), _ => None, } } /// Checks if the type is a type parameter implementing `FnOnce`, but not `FnMut`. -pub fn ty_is_fn_once_param<'tcx>(tcx: TyCtxt<'_>, ty: Ty<'tcx>, predicates: &'tcx [Predicate<'_>]) -> bool { +pub fn ty_is_fn_once_param<'tcx>( + tcx: TyCtxt<'_>, + ty: Ty<'tcx>, + predicates: &'tcx [Predicate<'_>], +) -> bool { let ty::Param(ty) = *ty.kind() else { return false; }; From 27e91b65d565a21b11a0f31fdd2c61a582ea966e Mon Sep 17 00:00:00 2001 From: Eric Holk Date: Tue, 30 Aug 2022 12:44:00 -0700 Subject: [PATCH 16/34] Address code review comments --- clippy_lints/src/transmute/utils.rs | 27 ++-- clippy_utils/src/qualify_min_const_fn.rs | 136 ++++++++----------- clippy_utils/src/ty.rs | 161 +++++++++-------------- 3 files changed, 127 insertions(+), 197 deletions(-) diff --git a/clippy_lints/src/transmute/utils.rs b/clippy_lints/src/transmute/utils.rs index 78cc589cc..8bdadf244 100644 --- a/clippy_lints/src/transmute/utils.rs +++ b/clippy_lints/src/transmute/utils.rs @@ -2,18 +2,11 @@ use rustc_hir::Expr; use rustc_lint::LateContext; use rustc_middle::ty::{cast::CastKind, Ty}; use rustc_span::DUMMY_SP; -use rustc_typeck::check::{ - cast::{self, CastCheckResult}, - FnCtxt, Inherited, -}; +use rustc_typeck::check::{cast::{self, CastCheckResult}, FnCtxt, Inherited}; // check if the component types of the transmuted collection and the result have different ABI, // size or alignment -pub(super) fn is_layout_incompatible<'tcx>( - cx: &LateContext<'tcx>, - from: Ty<'tcx>, - to: Ty<'tcx>, -) -> bool { +pub(super) fn is_layout_incompatible<'tcx>(cx: &LateContext<'tcx>, from: Ty<'tcx>, to: Ty<'tcx>) -> bool { if let Ok(from) = cx.tcx.try_normalize_erasing_regions(cx.param_env, from) && let Ok(to) = cx.tcx.try_normalize_erasing_regions(cx.param_env, to) && let Ok(from_layout) = cx.tcx.layout_of(cx.param_env.and(from)) @@ -36,9 +29,7 @@ pub(super) fn can_be_expressed_as_pointer_cast<'tcx>( from_ty: Ty<'tcx>, to_ty: Ty<'tcx>, ) -> bool { - use CastKind::{ - AddrPtrCast, ArrayPtrCast, FnPtrAddrCast, FnPtrPtrCast, PtrAddrCast, PtrPtrCast, - }; + use CastKind::{AddrPtrCast, ArrayPtrCast, FnPtrAddrCast, FnPtrPtrCast, PtrAddrCast, PtrPtrCast}; matches!( check_cast(cx, e, from_ty, to_ty), Some(PtrPtrCast | PtrAddrCast | AddrPtrCast | ArrayPtrCast | FnPtrPtrCast | FnPtrAddrCast) @@ -49,12 +40,7 @@ pub(super) fn can_be_expressed_as_pointer_cast<'tcx>( /// the cast. In certain cases, including some invalid casts from array references /// to pointers, this may cause additional errors to be emitted and/or ICE error /// messages. This function will panic if that occurs. -fn check_cast<'tcx>( - cx: &LateContext<'tcx>, - e: &'tcx Expr<'_>, - from_ty: Ty<'tcx>, - to_ty: Ty<'tcx>, -) -> Option { +fn check_cast<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> Option { let hir_id = e.hir_id; let local_def_id = hir_id.owner; @@ -62,7 +48,10 @@ fn check_cast<'tcx>( let fn_ctxt = FnCtxt::new(&inherited, cx.param_env, hir_id); // If we already have errors, we can't be sure we can pointer cast. - assert!(!fn_ctxt.errors_reported_since_creation(), "Newly created FnCtxt contained errors"); + assert!( + !fn_ctxt.errors_reported_since_creation(), + "Newly created FnCtxt contained errors" + ); if let CastCheckResult::Deferred(check) = cast::check_cast( &fn_ctxt, e, from_ty, to_ty, diff --git a/clippy_utils/src/qualify_min_const_fn.rs b/clippy_utils/src/qualify_min_const_fn.rs index 781744870..8835b9329 100644 --- a/clippy_utils/src/qualify_min_const_fn.rs +++ b/clippy_utils/src/qualify_min_const_fn.rs @@ -18,11 +18,7 @@ use std::borrow::Cow; type McfResult = Result<(), (Span, Cow<'static, str>)>; -pub fn is_min_const_fn<'a, 'tcx>( - tcx: TyCtxt<'tcx>, - body: &'a Body<'tcx>, - msrv: Option, -) -> McfResult { +pub fn is_min_const_fn<'a, 'tcx>(tcx: TyCtxt<'tcx>, body: &'a Body<'tcx>, msrv: Option) -> McfResult { let def_id = body.source.def_id(); let mut current = def_id; loop { @@ -37,18 +33,10 @@ pub fn is_min_const_fn<'a, 'tcx>( | ty::PredicateKind::ConstEquate(..) | ty::PredicateKind::Trait(..) | ty::PredicateKind::TypeWellFormedFromEnv(..) => continue, - ty::PredicateKind::ObjectSafe(_) => { - panic!("object safe predicate on function: {:#?}", predicate) - } - ty::PredicateKind::ClosureKind(..) => { - panic!("closure kind predicate on function: {:#?}", predicate) - } - ty::PredicateKind::Subtype(_) => { - panic!("subtype predicate on function: {:#?}", predicate) - } - ty::PredicateKind::Coerce(_) => { - panic!("coerce predicate on function: {:#?}", predicate) - } + ty::PredicateKind::ObjectSafe(_) => panic!("object safe predicate on function: {:#?}", predicate), + ty::PredicateKind::ClosureKind(..) => panic!("closure kind predicate on function: {:#?}", predicate), + ty::PredicateKind::Subtype(_) => panic!("subtype predicate on function: {:#?}", predicate), + ty::PredicateKind::Coerce(_) => panic!("coerce predicate on function: {:#?}", predicate), } } match predicates.parent { @@ -89,23 +77,22 @@ fn check_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span) -> McfResult { match ty.kind() { ty::Ref(_, _, hir::Mutability::Mut) => { return Err((span, "mutable references in const fn are unstable".into())); - } + }, ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())), ty::FnPtr(..) => { return Err((span, "function pointers in const fn are unstable".into())); - } + }, ty::Dynamic(preds, _, _) => { for pred in preds.iter() { match pred.skip_binder() { - ty::ExistentialPredicate::AutoTrait(_) - | ty::ExistentialPredicate::Projection(_) => { + ty::ExistentialPredicate::AutoTrait(_) | ty::ExistentialPredicate::Projection(_) => { return Err(( span, "trait bounds other than `Sized` \ on const fn parameters are unstable" .into(), )); - } + }, ty::ExistentialPredicate::Trait(trait_ref) => { if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() { return Err(( @@ -115,11 +102,11 @@ fn check_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span) -> McfResult { .into(), )); } - } + }, } } - } - _ => {} + }, + _ => {}, } } Ok(()) @@ -133,13 +120,10 @@ fn check_rvalue<'tcx>( span: Span, ) -> McfResult { match rvalue { - Rvalue::ThreadLocalRef(_) => { - Err((span, "cannot access thread local storage in const fn".into())) - } - Rvalue::Len(place) - | Rvalue::Discriminant(place) - | Rvalue::Ref(_, _, place) - | Rvalue::AddressOf(_, place) => check_place(tcx, *place, span, body), + Rvalue::ThreadLocalRef(_) => Err((span, "cannot access thread local storage in const fn".into())), + Rvalue::Len(place) | Rvalue::Discriminant(place) | Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => { + check_place(tcx, *place, span, body) + }, Rvalue::CopyForDeref(place) => check_place(tcx, *place, span, body), Rvalue::Repeat(operand, _) | Rvalue::Use(operand) @@ -152,9 +136,7 @@ fn check_rvalue<'tcx>( ) => check_operand(tcx, operand, span, body), Rvalue::Cast( CastKind::Pointer( - PointerCast::UnsafeFnPointer - | PointerCast::ClosureFnPointer(_) - | PointerCast::ReifyFnPointer, + PointerCast::UnsafeFnPointer | PointerCast::ClosureFnPointer(_) | PointerCast::ReifyFnPointer, ), _, _, @@ -164,10 +146,7 @@ fn check_rvalue<'tcx>( deref_ty.ty } else { // We cannot allow this for now. - return Err(( - span, - "unsizing casts are only allowed for references right now".into(), - )); + return Err((span, "unsizing casts are only allowed for references right now".into())); }; let unsized_ty = tcx.struct_tail_erasing_lifetimes(pointee_ty, tcx.param_env(def_id)); if let ty::Slice(_) | ty::Str = unsized_ty.kind() { @@ -178,14 +157,14 @@ fn check_rvalue<'tcx>( // We just can't allow trait objects until we have figured out trait method calls. Err((span, "unsizing casts are not allowed in const fn".into())) } - } + }, Rvalue::Cast(CastKind::PointerExposeAddress, _, _) => { Err((span, "casting pointers to ints is unstable in const fn".into())) - } + }, Rvalue::Cast(CastKind::DynStar, _, _) => { // FIXME(dyn-star) unimplemented!() - } + }, // binops are fine on integers Rvalue::BinaryOp(_, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(_, box (lhs, rhs)) => { check_operand(tcx, lhs, span, body)?; @@ -194,12 +173,13 @@ fn check_rvalue<'tcx>( if ty.is_integral() || ty.is_bool() || ty.is_char() { Ok(()) } else { - Err((span, "only int, `bool` and `char` operations are stable in const fn".into())) + Err(( + span, + "only int, `bool` and `char` operations are stable in const fn".into(), + )) } - } - Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf, _) | Rvalue::ShallowInitBox(_, _) => { - Ok(()) - } + }, + Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf, _) | Rvalue::ShallowInitBox(_, _) => Ok(()), Rvalue::UnaryOp(_, operand) => { let ty = operand.ty(body, tcx); if ty.is_integral() || ty.is_bool() { @@ -207,13 +187,13 @@ fn check_rvalue<'tcx>( } else { Err((span, "only int and `bool` operations are stable in const fn".into())) } - } + }, Rvalue::Aggregate(_, operands) => { for operand in operands { check_operand(tcx, operand, span, body)?; } Ok(()) - } + }, } } @@ -228,7 +208,7 @@ fn check_statement<'tcx>( StatementKind::Assign(box (place, rval)) => { check_place(tcx, *place, span, body)?; check_rvalue(tcx, body, def_id, rval, span) - } + }, StatementKind::FakeRead(box (_, place)) => check_place(tcx, *place, span, body), // just an assignment @@ -238,15 +218,13 @@ fn check_statement<'tcx>( StatementKind::Intrinsic(box NonDivergingIntrinsic::Assume(op)) => check_operand(tcx, op, span, body), - StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping { - dst, - src, - count, - }) => { + StatementKind::Intrinsic(box NonDivergingIntrinsic::CopyNonOverlapping( + rustc_middle::mir::CopyNonOverlapping { dst, src, count }, + )) => { check_operand(tcx, dst, span, body)?; check_operand(tcx, src, span, body)?; check_operand(tcx, count, span, body) - } + }, // These are all NOPs StatementKind::StorageLive(_) | StatementKind::StorageDead(_) @@ -257,12 +235,7 @@ fn check_statement<'tcx>( } } -fn check_operand<'tcx>( - tcx: TyCtxt<'tcx>, - operand: &Operand<'tcx>, - span: Span, - body: &Body<'tcx>, -) -> McfResult { +fn check_operand<'tcx>(tcx: TyCtxt<'tcx>, operand: &Operand<'tcx>, span: Span, body: &Body<'tcx>) -> McfResult { match operand { Operand::Move(place) | Operand::Copy(place) => check_place(tcx, *place, span, body), Operand::Constant(c) => match c.check_static_ptr(tcx) { @@ -272,12 +245,7 @@ fn check_operand<'tcx>( } } -fn check_place<'tcx>( - tcx: TyCtxt<'tcx>, - place: Place<'tcx>, - span: Span, - body: &Body<'tcx>, -) -> McfResult { +fn check_place<'tcx>(tcx: TyCtxt<'tcx>, place: Place<'tcx>, span: Span, body: &Body<'tcx>) -> McfResult { let mut cursor = place.projection.as_ref(); while let [ref proj_base @ .., elem] = *cursor { cursor = proj_base; @@ -290,12 +258,12 @@ fn check_place<'tcx>( return Err((span, "accessing union fields is unstable".into())); } } - } + }, ProjectionElem::ConstantIndex { .. } | ProjectionElem::Downcast(..) | ProjectionElem::Subslice { .. } | ProjectionElem::Deref - | ProjectionElem::Index(_) => {} + | ProjectionElem::Index(_) => {}, } } @@ -321,16 +289,18 @@ fn check_terminator<'a, 'tcx>( TerminatorKind::DropAndReplace { place, value, .. } => { check_place(tcx, *place, span, body)?; check_operand(tcx, value, span, body) - } + }, - TerminatorKind::SwitchInt { discr, switch_ty: _, targets: _ } => { - check_operand(tcx, discr, span, body) - } + TerminatorKind::SwitchInt { + discr, + switch_ty: _, + targets: _, + } => check_operand(tcx, discr, span, body), TerminatorKind::Abort => Err((span, "abort is not stable in const fn".into())), TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => { Err((span, "const fn generators are unstable".into())) - } + }, TerminatorKind::Call { func, @@ -375,15 +345,17 @@ fn check_terminator<'a, 'tcx>( } else { Err((span, "can only call other const fns within const fn".into())) } - } + }, - TerminatorKind::Assert { cond, expected: _, msg: _, target: _, cleanup: _ } => { - check_operand(tcx, cond, span, body) - } + TerminatorKind::Assert { + cond, + expected: _, + msg: _, + target: _, + cleanup: _, + } => check_operand(tcx, cond, span, body), - TerminatorKind::InlineAsm { .. } => { - Err((span, "cannot use inline assembly in const fn".into())) - } + TerminatorKind::InlineAsm { .. } => Err((span, "cannot use inline assembly in const fn".into())), } } diff --git a/clippy_utils/src/ty.rs b/clippy_utils/src/ty.rs index 99803ae93..a8ad6cf4f 100644 --- a/clippy_utils/src/ty.rs +++ b/clippy_utils/src/ty.rs @@ -14,9 +14,8 @@ use rustc_lint::LateContext; use rustc_middle::mir::interpret::{ConstValue, Scalar}; use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst}; use rustc_middle::ty::{ - self, AdtDef, Binder, BoundRegion, DefIdTree, FnSig, IntTy, ParamEnv, Predicate, PredicateKind, - ProjectionTy, Region, RegionKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor, - UintTy, VariantDef, VariantDiscr, + self, AdtDef, Binder, BoundRegion, DefIdTree, FnSig, IntTy, ParamEnv, Predicate, PredicateKind, ProjectionTy, + Region, RegionKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor, UintTy, VariantDef, VariantDiscr, }; use rustc_span::symbol::Ident; use rustc_span::{sym, Span, Symbol, DUMMY_SP}; @@ -167,7 +166,9 @@ pub fn implements_trait_with_env<'tcx>( } let ty_params = tcx.mk_substs(ty_params.iter()); tcx.infer_ctxt().enter(|infcx| { - infcx.type_implements_trait(trait_id, ty, ty_params, param_env).must_apply_modulo_regions() + infcx + .type_implements_trait(trait_id, ty, ty_params, param_env) + .must_apply_modulo_regions() }) } @@ -184,14 +185,11 @@ pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { match ty.kind() { ty::Adt(adt, _) => cx.tcx.has_attr(adt.did(), sym::must_use), ty::Foreign(did) => cx.tcx.has_attr(*did, sym::must_use), - ty::Slice(ty) - | ty::Array(ty, _) - | ty::RawPtr(ty::TypeAndMut { ty, .. }) - | ty::Ref(_, ty, _) => { + ty::Slice(ty) | ty::Array(ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) | ty::Ref(_, ty, _) => { // for the Array case we don't need to care for the len == 0 case // because we don't want to lint functions returning empty arrays is_must_use_ty(cx, *ty) - } + }, ty::Tuple(substs) => substs.iter().any(|ty| is_must_use_ty(cx, ty)), ty::Opaque(def_id, _) => { for (predicate, _) in cx.tcx.explicit_item_bounds(*def_id) { @@ -202,7 +200,7 @@ pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { } } false - } + }, ty::Dynamic(binder, _, _) => { for predicate in binder.iter() { if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() { @@ -212,7 +210,7 @@ pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { } } false - } + }, _ => false, } } @@ -222,11 +220,7 @@ pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { // not succeed /// Checks if `Ty` is normalizable. This function is useful /// to avoid crashes on `layout_of`. -pub fn is_normalizable<'tcx>( - cx: &LateContext<'tcx>, - param_env: ty::ParamEnv<'tcx>, - ty: Ty<'tcx>, -) -> bool { +pub fn is_normalizable<'tcx>(cx: &LateContext<'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool { is_normalizable_helper(cx, param_env, ty, &mut FxHashMap::default()) } @@ -246,14 +240,15 @@ fn is_normalizable_helper<'tcx>( if infcx.at(&cause, param_env).normalize(ty).is_ok() { match ty.kind() { ty::Adt(def, substs) => def.variants().iter().all(|variant| { - variant.fields.iter().all(|field| { - is_normalizable_helper(cx, param_env, field.ty(cx.tcx, substs), cache) - }) + variant + .fields + .iter() + .all(|field| is_normalizable_helper(cx, param_env, field.ty(cx.tcx, substs), cache)) }), _ => ty.walk().all(|generic_arg| match generic_arg.unpack() { GenericArgKind::Type(inner_ty) if inner_ty != ty => { is_normalizable_helper(cx, param_env, inner_ty, cache) - } + }, _ => true, // if inner_ty == ty, we've already checked it }), } @@ -278,9 +273,7 @@ pub fn is_recursively_primitive_type(ty: Ty<'_>) -> bool { match *ty.kind() { ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => true, ty::Ref(_, inner, _) if *inner.kind() == ty::Str => true, - ty::Array(inner_type, _) | ty::Slice(inner_type) => { - is_recursively_primitive_type(inner_type) - } + ty::Array(inner_type, _) | ty::Slice(inner_type) => is_recursively_primitive_type(inner_type), ty::Tuple(inner_types) => inner_types.iter().all(is_recursively_primitive_type), _ => false, } @@ -320,9 +313,11 @@ pub fn is_type_diagnostic_item(cx: &LateContext<'_>, ty: Ty<'_>, diag_item: Symb /// Returns `false` if the `LangItem` is not defined. pub fn is_type_lang_item(cx: &LateContext<'_>, ty: Ty<'_>, lang_item: hir::LangItem) -> bool { match ty.kind() { - ty::Adt(adt, _) => { - cx.tcx.lang_items().require(lang_item).map_or(false, |li| li == adt.did()) - } + ty::Adt(adt, _) => cx + .tcx + .lang_items() + .require(lang_item) + .map_or(false, |li| li == adt.did()), _ => false, } } @@ -347,11 +342,7 @@ pub fn match_type(cx: &LateContext<'_>, ty: Ty<'_>, path: &[&str]) -> bool { /// deallocate memory. For these types, and composites containing them, changing the drop order /// won't result in any observable side effects. pub fn needs_ordered_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { - fn needs_ordered_drop_inner<'tcx>( - cx: &LateContext<'tcx>, - ty: Ty<'tcx>, - seen: &mut FxHashSet>, - ) -> bool { + fn needs_ordered_drop_inner<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, seen: &mut FxHashSet>) -> bool { if !seen.insert(ty) { return false; } @@ -402,7 +393,11 @@ pub fn needs_ordered_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { /// removed. pub fn peel_mid_ty_refs(ty: Ty<'_>) -> (Ty<'_>, usize) { fn peel(ty: Ty<'_>, count: usize) -> (Ty<'_>, usize) { - if let ty::Ref(_, ty, _) = ty.kind() { peel(*ty, count + 1) } else { (ty, count) } + if let ty::Ref(_, ty, _) = ty.kind() { + peel(*ty, count + 1) + } else { + (ty, count) + } } peel(ty, 0) } @@ -457,18 +452,17 @@ pub fn same_type_and_consts<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool { return false; } - substs_a.iter().zip(substs_b.iter()).all(|(arg_a, arg_b)| { - match (arg_a.unpack(), arg_b.unpack()) { - (GenericArgKind::Const(inner_a), GenericArgKind::Const(inner_b)) => { - inner_a == inner_b - } + substs_a + .iter() + .zip(substs_b.iter()) + .all(|(arg_a, arg_b)| match (arg_a.unpack(), arg_b.unpack()) { + (GenericArgKind::Const(inner_a), GenericArgKind::Const(inner_b)) => inner_a == inner_b, (GenericArgKind::Type(type_a), GenericArgKind::Type(type_b)) => { same_type_and_consts(type_a, type_b) - } + }, _ => true, - } - }) - } + }) + }, _ => a == b, } } @@ -484,10 +478,7 @@ pub fn is_uninit_value_valid_for_ty(cx: &LateContext<'_>, ty: Ty<'_>) -> bool { } /// Gets an iterator over all predicates which apply to the given item. -pub fn all_predicates_of( - tcx: TyCtxt<'_>, - id: DefId, -) -> impl Iterator, Span)> { +pub fn all_predicates_of(tcx: TyCtxt<'_>, id: DefId) -> impl Iterator, Span)> { let mut next_id = Some(id); iter::from_fn(move || { next_id.take().map(|id| { @@ -517,7 +508,7 @@ impl<'tcx> ExprFnSig<'tcx> { } else { Some(sig.input(i)) } - } + }, Self::Closure(_, sig) => Some(sig.input(0).map_bound(|ty| ty.tuple_fields()[i])), Self::Trait(inputs, _, _) => Some(inputs.map_bound(|ty| ty.tuple_fields()[i])), } @@ -526,10 +517,7 @@ impl<'tcx> ExprFnSig<'tcx> { /// Gets the argument type at the given offset. For closures this will also get the type as /// written. This will return `None` when the index is out of bounds only for variadic /// functions, otherwise this will panic. - pub fn input_with_hir( - self, - i: usize, - ) -> Option<(Option<&'tcx hir::Ty<'tcx>>, Binder<'tcx, Ty<'tcx>>)> { + pub fn input_with_hir(self, i: usize) -> Option<(Option<&'tcx hir::Ty<'tcx>>, Binder<'tcx, Ty<'tcx>>)> { match self { Self::Sig(sig, _) => { if sig.c_variadic() { @@ -540,7 +528,7 @@ impl<'tcx> ExprFnSig<'tcx> { } else { Some((None, sig.input(i))) } - } + }, Self::Closure(decl, sig) => Some(( decl.and_then(|decl| decl.inputs.get(i)), sig.input(0).map_bound(|ty| ty.tuple_fields()[i]), @@ -559,15 +547,17 @@ impl<'tcx> ExprFnSig<'tcx> { } pub fn predicates_id(&self) -> Option { - if let ExprFnSig::Sig(_, id) | ExprFnSig::Trait(_, _, id) = *self { id } else { None } + if let ExprFnSig::Sig(_, id) | ExprFnSig::Trait(_, _, id) = *self { + id + } else { + None + } } } /// If the expression is function like, get the signature for it. pub fn expr_sig<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> Option> { - if let Res::Def(DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::AssocFn, id) = - path_res(cx, expr) - { + if let Res::Def(DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::AssocFn, id) = path_res(cx, expr) { Some(ExprFnSig::Sig(cx.tcx.fn_sig(id), Some(id))) } else { ty_sig(cx, cx.typeck_results().expr_ty_adjusted(expr).peel_refs()) @@ -581,14 +571,12 @@ pub fn ty_sig<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option { - let decl = id.as_local().and_then(|id| { - cx.tcx.hir().fn_decl_by_hir_id(cx.tcx.hir().local_def_id_to_hir_id(id)) - }); + let decl = id + .as_local() + .and_then(|id| cx.tcx.hir().fn_decl_by_hir_id(cx.tcx.hir().local_def_id_to_hir_id(id))); Some(ExprFnSig::Closure(decl, subs.as_closure().sig())) - } - ty::FnDef(id, subs) => { - Some(ExprFnSig::Sig(cx.tcx.bound_fn_sig(id).subst(cx.tcx, subs), Some(id))) - } + }, + ty::FnDef(id, subs) => Some(ExprFnSig::Sig(cx.tcx.bound_fn_sig(id).subst(cx.tcx, subs), Some(id))), ty::Opaque(id, _) => sig_from_bounds(cx, ty, cx.tcx.item_bounds(id), cx.tcx.opt_parent(id)), ty::FnPtr(sig) => Some(ExprFnSig::Sig(sig, None)), ty::Dynamic(bounds, _, _) => { @@ -601,19 +589,16 @@ pub fn ty_sig<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option None, } - } + }, ty::Projection(proj) => match cx.tcx.try_normalize_erasing_regions(cx.param_env, ty) { Ok(normalized_ty) if normalized_ty != ty => ty_sig(cx, normalized_ty), - _ => sig_for_projection(cx, proj) - .or_else(|| sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None)), + _ => sig_for_projection(cx, proj).or_else(|| sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None)), }, ty::Param(_) => sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None), _ => None, @@ -644,7 +629,7 @@ fn sig_from_bounds<'tcx>( return None; } inputs = Some(i); - } + }, PredicateKind::Projection(p) if Some(p.projection_ty.item_def_id) == lang_items.fn_once_output() && p.projection_ty.self_ty() == ty => @@ -654,7 +639,7 @@ fn sig_from_bounds<'tcx>( return None; } output = Some(pred.kind().rebind(p.term.ty().unwrap())); - } + }, _ => (), } } @@ -662,10 +647,7 @@ fn sig_from_bounds<'tcx>( inputs.map(|ty| ExprFnSig::Trait(ty, output, predicates_id)) } -fn sig_for_projection<'tcx>( - cx: &LateContext<'tcx>, - ty: ProjectionTy<'tcx>, -) -> Option> { +fn sig_for_projection<'tcx>(cx: &LateContext<'tcx>, ty: ProjectionTy<'tcx>) -> Option> { let mut inputs = None; let mut output = None; let lang_items = cx.tcx.lang_items(); @@ -691,10 +673,8 @@ fn sig_for_projection<'tcx>( return None; } inputs = Some(i); - } - PredicateKind::Projection(p) - if Some(p.projection_ty.item_def_id) == lang_items.fn_once_output() => - { + }, + PredicateKind::Projection(p) if Some(p.projection_ty.item_def_id) == lang_items.fn_once_output() => { if output.is_some() { // Multiple different fn trait impls. Is this even allowed? return None; @@ -703,7 +683,7 @@ fn sig_for_projection<'tcx>( pred.map_bound(|pred| pred.kind().rebind(p.term.ty().unwrap())) .subst(cx.tcx, ty.substs), ); - } + }, _ => (), } } @@ -797,10 +777,7 @@ pub fn for_each_top_level_late_bound_region( ControlFlow::Continue(()) } } - fn visit_binder>( - &mut self, - t: &Binder<'tcx, T>, - ) -> ControlFlow { + fn visit_binder>(&mut self, t: &Binder<'tcx, T>) -> ControlFlow { self.index += 1; let res = t.super_visit_with(self); self.index -= 1; @@ -814,27 +791,19 @@ pub fn for_each_top_level_late_bound_region( pub fn variant_of_res<'tcx>(cx: &LateContext<'tcx>, res: Res) -> Option<&'tcx VariantDef> { match res { Res::Def(DefKind::Struct, id) => Some(cx.tcx.adt_def(id).non_enum_variant()), - Res::Def(DefKind::Variant, id) => { - Some(cx.tcx.adt_def(cx.tcx.parent(id)).variant_with_id(id)) - } - Res::Def(DefKind::Ctor(CtorOf::Struct, _), id) => { - Some(cx.tcx.adt_def(cx.tcx.parent(id)).non_enum_variant()) - } + Res::Def(DefKind::Variant, id) => Some(cx.tcx.adt_def(cx.tcx.parent(id)).variant_with_id(id)), + Res::Def(DefKind::Ctor(CtorOf::Struct, _), id) => Some(cx.tcx.adt_def(cx.tcx.parent(id)).non_enum_variant()), Res::Def(DefKind::Ctor(CtorOf::Variant, _), id) => { let var_id = cx.tcx.parent(id); Some(cx.tcx.adt_def(cx.tcx.parent(var_id)).variant_with_id(var_id)) - } + }, Res::SelfCtor(id) => Some(cx.tcx.type_of(id).ty_adt_def().unwrap().non_enum_variant()), _ => None, } } /// Checks if the type is a type parameter implementing `FnOnce`, but not `FnMut`. -pub fn ty_is_fn_once_param<'tcx>( - tcx: TyCtxt<'_>, - ty: Ty<'tcx>, - predicates: &'tcx [Predicate<'_>], -) -> bool { +pub fn ty_is_fn_once_param<'tcx>(tcx: TyCtxt<'_>, ty: Ty<'tcx>, predicates: &'tcx [Predicate<'_>]) -> bool { let ty::Param(ty) = *ty.kind() else { return false; }; From 525e0c86bc8e11f9b8585f987a973302bb86ff33 Mon Sep 17 00:00:00 2001 From: Philipp Krones Date: Wed, 14 Sep 2022 20:13:30 +0200 Subject: [PATCH 17/34] Temporarily move clippy::unused_peekable to nursery --- clippy_lints/src/lib.register_all.rs | 1 - clippy_lints/src/lib.register_nursery.rs | 1 + clippy_lints/src/lib.register_suspicious.rs | 1 - clippy_lints/src/unused_peekable.rs | 2 +- 4 files changed, 2 insertions(+), 3 deletions(-) diff --git a/clippy_lints/src/lib.register_all.rs b/clippy_lints/src/lib.register_all.rs index 1f8538234..59d1760fe 100644 --- a/clippy_lints/src/lib.register_all.rs +++ b/clippy_lints/src/lib.register_all.rs @@ -344,7 +344,6 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![ LintId::of(unnecessary_owned_empty_strings::UNNECESSARY_OWNED_EMPTY_STRINGS), LintId::of(unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME), LintId::of(unused_io_amount::UNUSED_IO_AMOUNT), - LintId::of(unused_peekable::UNUSED_PEEKABLE), LintId::of(unused_unit::UNUSED_UNIT), LintId::of(unwrap::PANICKING_UNWRAP), LintId::of(unwrap::UNNECESSARY_UNWRAP), diff --git a/clippy_lints/src/lib.register_nursery.rs b/clippy_lints/src/lib.register_nursery.rs index e319e7ee7..f1783dd9d 100644 --- a/clippy_lints/src/lib.register_nursery.rs +++ b/clippy_lints/src/lib.register_nursery.rs @@ -31,6 +31,7 @@ store.register_group(true, "clippy::nursery", Some("clippy_nursery"), vec![ LintId::of(suspicious_operation_groupings::SUSPICIOUS_OPERATION_GROUPINGS), LintId::of(trailing_empty_array::TRAILING_EMPTY_ARRAY), LintId::of(transmute::TRANSMUTE_UNDEFINED_REPR), + LintId::of(unused_peekable::UNUSED_PEEKABLE), LintId::of(unused_rounding::UNUSED_ROUNDING), LintId::of(use_self::USE_SELF), ]) diff --git a/clippy_lints/src/lib.register_suspicious.rs b/clippy_lints/src/lib.register_suspicious.rs index 8f131bbf9..bede91f18 100644 --- a/clippy_lints/src/lib.register_suspicious.rs +++ b/clippy_lints/src/lib.register_suspicious.rs @@ -35,6 +35,5 @@ store.register_group(true, "clippy::suspicious", Some("clippy_suspicious"), vec! LintId::of(suspicious_trait_impl::SUSPICIOUS_ARITHMETIC_IMPL), LintId::of(suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL), LintId::of(swap_ptr_to_ref::SWAP_PTR_TO_REF), - LintId::of(unused_peekable::UNUSED_PEEKABLE), LintId::of(write::POSITIONAL_NAMED_FORMAT_PARAMETERS), ]) diff --git a/clippy_lints/src/unused_peekable.rs b/clippy_lints/src/unused_peekable.rs index cfc181e43..cc8656435 100644 --- a/clippy_lints/src/unused_peekable.rs +++ b/clippy_lints/src/unused_peekable.rs @@ -38,7 +38,7 @@ declare_clippy_lint! { /// ``` #[clippy::version = "1.64.0"] pub UNUSED_PEEKABLE, - suspicious, + nursery, "creating a peekable iterator without using any of its methods" } From 2be8b7332819d9819502f54e45a2c70f1f9903cf Mon Sep 17 00:00:00 2001 From: est31 Date: Fri, 4 Feb 2022 10:13:48 +0100 Subject: [PATCH 18/34] Fix clippy --- clippy_dev/src/lib.rs | 2 +- clippy_lints/src/lib.rs | 2 +- clippy_utils/src/lib.rs | 2 +- tests/ui/needless_return.fixed | 1 - tests/ui/needless_return.rs | 1 - tests/ui/needless_return.stderr | 74 +++++++++---------- tests/ui/semicolon_if_nothing_returned.rs | 1 - tests/ui/semicolon_if_nothing_returned.stderr | 10 +-- 8 files changed, 45 insertions(+), 48 deletions(-) diff --git a/clippy_dev/src/lib.rs b/clippy_dev/src/lib.rs index 82574a8e6..54c7456a2 100644 --- a/clippy_dev/src/lib.rs +++ b/clippy_dev/src/lib.rs @@ -1,5 +1,5 @@ #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(once_cell)] #![feature(rustc_private)] #![cfg_attr(feature = "deny-warnings", deny(warnings))] diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index e984254bf..ceaaf5c6d 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -5,7 +5,7 @@ #![feature(drain_filter)] #![feature(iter_intersperse)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(lint_reasons)] #![feature(never_type)] #![feature(once_cell)] diff --git a/clippy_utils/src/lib.rs b/clippy_utils/src/lib.rs index 23b51ec2d..62da850a1 100644 --- a/clippy_utils/src/lib.rs +++ b/clippy_utils/src/lib.rs @@ -1,9 +1,9 @@ #![feature(array_chunks)] #![feature(box_patterns)] #![feature(control_flow_enum)] -#![feature(let_else)] #![feature(let_chains)] #![feature(lint_reasons)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(once_cell)] #![feature(rustc_private)] #![recursion_limit = "512"] diff --git a/tests/ui/needless_return.fixed b/tests/ui/needless_return.fixed index 87c8fc03b..695883e8d 100644 --- a/tests/ui/needless_return.fixed +++ b/tests/ui/needless_return.fixed @@ -1,7 +1,6 @@ // run-rustfix #![feature(lint_reasons)] -#![feature(let_else)] #![allow(unused)] #![allow( clippy::if_same_then_else, diff --git a/tests/ui/needless_return.rs b/tests/ui/needless_return.rs index 5a86e6562..63d9fe9ec 100644 --- a/tests/ui/needless_return.rs +++ b/tests/ui/needless_return.rs @@ -1,7 +1,6 @@ // run-rustfix #![feature(lint_reasons)] -#![feature(let_else)] #![allow(unused)] #![allow( clippy::if_same_then_else, diff --git a/tests/ui/needless_return.stderr b/tests/ui/needless_return.stderr index 83ff07638..cadee6e00 100644 --- a/tests/ui/needless_return.stderr +++ b/tests/ui/needless_return.stderr @@ -1,5 +1,5 @@ error: unneeded `return` statement - --> $DIR/needless_return.rs:27:5 + --> $DIR/needless_return.rs:26:5 | LL | return true; | ^^^^^^^^^^^^ help: remove `return`: `true` @@ -7,217 +7,217 @@ LL | return true; = note: `-D clippy::needless-return` implied by `-D warnings` error: unneeded `return` statement - --> $DIR/needless_return.rs:31:5 + --> $DIR/needless_return.rs:30:5 | LL | return true; | ^^^^^^^^^^^^ help: remove `return`: `true` error: unneeded `return` statement - --> $DIR/needless_return.rs:36:9 + --> $DIR/needless_return.rs:35:9 | LL | return true; | ^^^^^^^^^^^^ help: remove `return`: `true` error: unneeded `return` statement - --> $DIR/needless_return.rs:38:9 + --> $DIR/needless_return.rs:37:9 | LL | return false; | ^^^^^^^^^^^^^ help: remove `return`: `false` error: unneeded `return` statement - --> $DIR/needless_return.rs:44:17 + --> $DIR/needless_return.rs:43:17 | LL | true => return false, | ^^^^^^^^^^^^ help: remove `return`: `false` error: unneeded `return` statement - --> $DIR/needless_return.rs:46:13 + --> $DIR/needless_return.rs:45:13 | LL | return true; | ^^^^^^^^^^^^ help: remove `return`: `true` error: unneeded `return` statement - --> $DIR/needless_return.rs:53:9 + --> $DIR/needless_return.rs:52:9 | LL | return true; | ^^^^^^^^^^^^ help: remove `return`: `true` error: unneeded `return` statement - --> $DIR/needless_return.rs:55:16 + --> $DIR/needless_return.rs:54:16 | LL | let _ = || return true; | ^^^^^^^^^^^ help: remove `return`: `true` error: unneeded `return` statement - --> $DIR/needless_return.rs:59:5 + --> $DIR/needless_return.rs:58:5 | LL | return the_answer!(); | ^^^^^^^^^^^^^^^^^^^^^ help: remove `return`: `the_answer!()` error: unneeded `return` statement - --> $DIR/needless_return.rs:63:5 + --> $DIR/needless_return.rs:62:5 | LL | return; | ^^^^^^^ help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:68:9 + --> $DIR/needless_return.rs:67:9 | LL | return; | ^^^^^^^ help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:70:9 + --> $DIR/needless_return.rs:69:9 | LL | return; | ^^^^^^^ help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:77:14 + --> $DIR/needless_return.rs:76:14 | LL | _ => return, | ^^^^^^ help: replace `return` with a unit value: `()` error: unneeded `return` statement - --> $DIR/needless_return.rs:86:13 + --> $DIR/needless_return.rs:85:13 | LL | return; | ^^^^^^^ help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:88:14 + --> $DIR/needless_return.rs:87:14 | LL | _ => return, | ^^^^^^ help: replace `return` with a unit value: `()` error: unneeded `return` statement - --> $DIR/needless_return.rs:101:9 + --> $DIR/needless_return.rs:100:9 | LL | return String::from("test"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove `return`: `String::from("test")` error: unneeded `return` statement - --> $DIR/needless_return.rs:103:9 + --> $DIR/needless_return.rs:102:9 | LL | return String::new(); | ^^^^^^^^^^^^^^^^^^^^^ help: remove `return`: `String::new()` error: unneeded `return` statement - --> $DIR/needless_return.rs:125:32 + --> $DIR/needless_return.rs:124:32 | LL | bar.unwrap_or_else(|_| return) | ^^^^^^ help: replace `return` with an empty block: `{}` error: unneeded `return` statement - --> $DIR/needless_return.rs:130:13 + --> $DIR/needless_return.rs:129:13 | LL | return; | ^^^^^^^ help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:132:20 + --> $DIR/needless_return.rs:131:20 | LL | let _ = || return; | ^^^^^^ help: replace `return` with an empty block: `{}` error: unneeded `return` statement - --> $DIR/needless_return.rs:138:32 + --> $DIR/needless_return.rs:137:32 | LL | res.unwrap_or_else(|_| return Foo) | ^^^^^^^^^^ help: remove `return`: `Foo` error: unneeded `return` statement - --> $DIR/needless_return.rs:147:5 + --> $DIR/needless_return.rs:146:5 | LL | return true; | ^^^^^^^^^^^^ help: remove `return`: `true` error: unneeded `return` statement - --> $DIR/needless_return.rs:151:5 + --> $DIR/needless_return.rs:150:5 | LL | return true; | ^^^^^^^^^^^^ help: remove `return`: `true` error: unneeded `return` statement - --> $DIR/needless_return.rs:156:9 + --> $DIR/needless_return.rs:155:9 | LL | return true; | ^^^^^^^^^^^^ help: remove `return`: `true` error: unneeded `return` statement - --> $DIR/needless_return.rs:158:9 + --> $DIR/needless_return.rs:157:9 | LL | return false; | ^^^^^^^^^^^^^ help: remove `return`: `false` error: unneeded `return` statement - --> $DIR/needless_return.rs:164:17 + --> $DIR/needless_return.rs:163:17 | LL | true => return false, | ^^^^^^^^^^^^ help: remove `return`: `false` error: unneeded `return` statement - --> $DIR/needless_return.rs:166:13 + --> $DIR/needless_return.rs:165:13 | LL | return true; | ^^^^^^^^^^^^ help: remove `return`: `true` error: unneeded `return` statement - --> $DIR/needless_return.rs:173:9 + --> $DIR/needless_return.rs:172:9 | LL | return true; | ^^^^^^^^^^^^ help: remove `return`: `true` error: unneeded `return` statement - --> $DIR/needless_return.rs:175:16 + --> $DIR/needless_return.rs:174:16 | LL | let _ = || return true; | ^^^^^^^^^^^ help: remove `return`: `true` error: unneeded `return` statement - --> $DIR/needless_return.rs:179:5 + --> $DIR/needless_return.rs:178:5 | LL | return the_answer!(); | ^^^^^^^^^^^^^^^^^^^^^ help: remove `return`: `the_answer!()` error: unneeded `return` statement - --> $DIR/needless_return.rs:183:5 + --> $DIR/needless_return.rs:182:5 | LL | return; | ^^^^^^^ help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:188:9 + --> $DIR/needless_return.rs:187:9 | LL | return; | ^^^^^^^ help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:190:9 + --> $DIR/needless_return.rs:189:9 | LL | return; | ^^^^^^^ help: remove `return` error: unneeded `return` statement - --> $DIR/needless_return.rs:197:14 + --> $DIR/needless_return.rs:196:14 | LL | _ => return, | ^^^^^^ help: replace `return` with a unit value: `()` error: unneeded `return` statement - --> $DIR/needless_return.rs:210:9 + --> $DIR/needless_return.rs:209:9 | LL | return String::from("test"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove `return`: `String::from("test")` error: unneeded `return` statement - --> $DIR/needless_return.rs:212:9 + --> $DIR/needless_return.rs:211:9 | LL | return String::new(); | ^^^^^^^^^^^^^^^^^^^^^ help: remove `return`: `String::new()` error: unneeded `return` statement - --> $DIR/needless_return.rs:228:5 + --> $DIR/needless_return.rs:227:5 | LL | return format!("Hello {}", "world!"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove `return`: `format!("Hello {}", "world!")` diff --git a/tests/ui/semicolon_if_nothing_returned.rs b/tests/ui/semicolon_if_nothing_returned.rs index c3235f067..c4dfbd921 100644 --- a/tests/ui/semicolon_if_nothing_returned.rs +++ b/tests/ui/semicolon_if_nothing_returned.rs @@ -1,6 +1,5 @@ #![warn(clippy::semicolon_if_nothing_returned)] #![allow(clippy::redundant_closure)] -#![feature(let_else)] fn get_unit() {} diff --git a/tests/ui/semicolon_if_nothing_returned.stderr b/tests/ui/semicolon_if_nothing_returned.stderr index 78813e7cc..8d9a67585 100644 --- a/tests/ui/semicolon_if_nothing_returned.stderr +++ b/tests/ui/semicolon_if_nothing_returned.stderr @@ -1,5 +1,5 @@ error: consider adding a `;` to the last statement for consistent formatting - --> $DIR/semicolon_if_nothing_returned.rs:9:5 + --> $DIR/semicolon_if_nothing_returned.rs:8:5 | LL | println!("Hello") | ^^^^^^^^^^^^^^^^^ help: add a `;` here: `println!("Hello");` @@ -7,25 +7,25 @@ LL | println!("Hello") = note: `-D clippy::semicolon-if-nothing-returned` implied by `-D warnings` error: consider adding a `;` to the last statement for consistent formatting - --> $DIR/semicolon_if_nothing_returned.rs:13:5 + --> $DIR/semicolon_if_nothing_returned.rs:12:5 | LL | get_unit() | ^^^^^^^^^^ help: add a `;` here: `get_unit();` error: consider adding a `;` to the last statement for consistent formatting - --> $DIR/semicolon_if_nothing_returned.rs:18:5 + --> $DIR/semicolon_if_nothing_returned.rs:17:5 | LL | y = x + 1 | ^^^^^^^^^ help: add a `;` here: `y = x + 1;` error: consider adding a `;` to the last statement for consistent formatting - --> $DIR/semicolon_if_nothing_returned.rs:24:9 + --> $DIR/semicolon_if_nothing_returned.rs:23:9 | LL | hello() | ^^^^^^^ help: add a `;` here: `hello();` error: consider adding a `;` to the last statement for consistent formatting - --> $DIR/semicolon_if_nothing_returned.rs:35:9 + --> $DIR/semicolon_if_nothing_returned.rs:34:9 | LL | ptr::drop_in_place(s.as_mut_ptr()) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: add a `;` here: `ptr::drop_in_place(s.as_mut_ptr());` From c2e9c991d59d3aae0809165dbd9237515ae57ce3 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Wed, 27 Jul 2022 11:58:34 +0000 Subject: [PATCH 19/34] Revert "Revert "Rollup merge of #98582 - oli-obk:unconstrained_opaque_type, r=estebank"" This reverts commit 4a742a691e7dd2522bad68b86fe2fd5a199d5561. --- clippy_utils/src/qualify_min_const_fn.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/clippy_utils/src/qualify_min_const_fn.rs b/clippy_utils/src/qualify_min_const_fn.rs index 8835b9329..405f02286 100644 --- a/clippy_utils/src/qualify_min_const_fn.rs +++ b/clippy_utils/src/qualify_min_const_fn.rs @@ -260,6 +260,7 @@ fn check_place<'tcx>(tcx: TyCtxt<'tcx>, place: Place<'tcx>, span: Span, body: &B } }, ProjectionElem::ConstantIndex { .. } + | ProjectionElem::OpaqueCast(..) | ProjectionElem::Downcast(..) | ProjectionElem::Subslice { .. } | ProjectionElem::Deref From 70f4c712c55929a2584b0a45bbca8ebf03079b9c Mon Sep 17 00:00:00 2001 From: lcnr Date: Fri, 16 Sep 2022 15:31:10 +0200 Subject: [PATCH 20/34] remove the `Subst` trait, always use `EarlyBinder` --- clippy_lints/src/dereference.rs | 2 +- clippy_lints/src/eta_reduction.rs | 1 - clippy_lints/src/future_not_send.rs | 1 - clippy_lints/src/methods/unnecessary_to_owned.rs | 1 - clippy_lints/src/mut_reference.rs | 1 - clippy_lints/src/transmute/transmute_undefined_repr.rs | 2 +- clippy_utils/src/consts.rs | 2 +- clippy_utils/src/ty.rs | 2 +- 8 files changed, 4 insertions(+), 8 deletions(-) diff --git a/clippy_lints/src/dereference.rs b/clippy_lints/src/dereference.rs index 88e28018e..45b5d79d4 100644 --- a/clippy_lints/src/dereference.rs +++ b/clippy_lints/src/dereference.rs @@ -20,7 +20,7 @@ use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability}; use rustc_middle::ty::{ - self, subst::Subst, Binder, BoundVariableKind, EarlyBinder, FnSig, GenericArgKind, List, ParamTy, PredicateKind, + self, Binder, BoundVariableKind, EarlyBinder, FnSig, GenericArgKind, List, ParamTy, PredicateKind, ProjectionPredicate, Ty, TyCtxt, TypeVisitable, TypeckResults, }; use rustc_semver::RustcVersion; diff --git a/clippy_lints/src/eta_reduction.rs b/clippy_lints/src/eta_reduction.rs index 53bc617a4..598f8c318 100644 --- a/clippy_lints/src/eta_reduction.rs +++ b/clippy_lints/src/eta_reduction.rs @@ -11,7 +11,6 @@ use rustc_hir::{Closure, Expr, ExprKind, Param, PatKind, Unsafety}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow}; use rustc_middle::ty::binding::BindingMode; -use rustc_middle::ty::subst::Subst; use rustc_middle::ty::{self, ClosureKind, Ty, TypeVisitable}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::symbol::sym; diff --git a/clippy_lints/src/future_not_send.rs b/clippy_lints/src/future_not_send.rs index ef7d75aa8..eb2eefe0d 100644 --- a/clippy_lints/src/future_not_send.rs +++ b/clippy_lints/src/future_not_send.rs @@ -4,7 +4,6 @@ use rustc_hir::intravisit::FnKind; use rustc_hir::{Body, FnDecl, HirId}; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty::subst::Subst; use rustc_middle::ty::{EarlyBinder, Opaque, PredicateKind::Trait}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::{sym, Span}; diff --git a/clippy_lints/src/methods/unnecessary_to_owned.rs b/clippy_lints/src/methods/unnecessary_to_owned.rs index 763bfafec..8d3cede70 100644 --- a/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/clippy_lints/src/methods/unnecessary_to_owned.rs @@ -1,6 +1,5 @@ use super::implicit_clone::is_clone_like; use super::unnecessary_iter_cloned::{self, is_into_iter}; -use crate::rustc_middle::ty::Subst; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::source::snippet_opt; use clippy_utils::ty::{get_associated_type, get_iterator_item_ty, implements_trait, is_copy, peel_mid_ty_refs}; diff --git a/clippy_lints/src/mut_reference.rs b/clippy_lints/src/mut_reference.rs index 82dc03ef5..084c0d471 100644 --- a/clippy_lints/src/mut_reference.rs +++ b/clippy_lints/src/mut_reference.rs @@ -1,7 +1,6 @@ use clippy_utils::diagnostics::span_lint; use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability}; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty::subst::Subst; use rustc_middle::ty::{self, Ty}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use std::iter; diff --git a/clippy_lints/src/transmute/transmute_undefined_repr.rs b/clippy_lints/src/transmute/transmute_undefined_repr.rs index b6d7d9f5b..ae55a6bf5 100644 --- a/clippy_lints/src/transmute/transmute_undefined_repr.rs +++ b/clippy_lints/src/transmute/transmute_undefined_repr.rs @@ -3,7 +3,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::ty::is_c_void; use rustc_hir::Expr; use rustc_lint::LateContext; -use rustc_middle::ty::subst::{Subst, SubstsRef}; +use rustc_middle::ty::SubstsRef; use rustc_middle::ty::{self, IntTy, Ty, TypeAndMut, UintTy}; use rustc_span::DUMMY_SP; diff --git a/clippy_utils/src/consts.rs b/clippy_utils/src/consts.rs index e053708ed..96c55111f 100644 --- a/clippy_utils/src/consts.rs +++ b/clippy_utils/src/consts.rs @@ -9,7 +9,7 @@ use rustc_hir::{BinOp, BinOpKind, Block, Expr, ExprKind, HirId, Item, ItemKind, use rustc_lint::LateContext; use rustc_middle::mir; use rustc_middle::mir::interpret::Scalar; -use rustc_middle::ty::subst::{Subst, SubstsRef}; +use rustc_middle::ty::SubstsRef; use rustc_middle::ty::{self, EarlyBinder, FloatTy, ScalarInt, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_span::symbol::Symbol; diff --git a/clippy_utils/src/ty.rs b/clippy_utils/src/ty.rs index a8ad6cf4f..926ecf965 100644 --- a/clippy_utils/src/ty.rs +++ b/clippy_utils/src/ty.rs @@ -12,7 +12,7 @@ use rustc_hir::{Expr, FnDecl, LangItem, TyKind, Unsafety}; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::LateContext; use rustc_middle::mir::interpret::{ConstValue, Scalar}; -use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst}; +use rustc_middle::ty::{GenericArg, GenericArgKind}; use rustc_middle::ty::{ self, AdtDef, Binder, BoundRegion, DefIdTree, FnSig, IntTy, ParamEnv, Predicate, PredicateKind, ProjectionTy, Region, RegionKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor, UintTy, VariantDef, VariantDiscr, From 4d015293d1cb7ebdd0972e620c3e0f1763ad2ec8 Mon Sep 17 00:00:00 2001 From: David Koloski Date: Wed, 21 Sep 2022 13:02:37 -0400 Subject: [PATCH 21/34] Merge commit '7248d06384c6a90de58c04c1f46be88821278d8b' into sync-from-clippy --- CHANGELOG.md | 1 + CONTRIBUTING.md | 25 +- book/src/development/adding_lints.md | 1 + .../development/common_tools_writing_lints.md | 15 +- clippy_dev/src/new_lint.rs | 1 + .../src/almost_complete_letter_range.rs | 2 + .../src/assertions_on_result_states.rs | 22 +- clippy_lints/src/bool_to_int_with_if.rs | 47 +- clippy_lints/src/booleans.rs | 2 +- clippy_lints/src/dereference.rs | 7 +- clippy_lints/src/derivable_impls.rs | 24 +- clippy_lints/src/format.rs | 2 +- clippy_lints/src/format_args.rs | 2 +- clippy_lints/src/large_stack_arrays.rs | 50 +- clippy_lints/src/lib.register_all.rs | 2 +- clippy_lints/src/lib.register_complexity.rs | 1 + clippy_lints/src/lib.register_lints.rs | 2 +- clippy_lints/src/lib.register_suspicious.rs | 1 - clippy_lints/src/lib.rs | 5 +- clippy_lints/src/methods/err_expect.rs | 11 +- clippy_lints/src/methods/iter_kv_map.rs | 87 ++ clippy_lints/src/methods/mod.rs | 36 + clippy_lints/src/methods/ok_expect.rs | 11 +- .../src/methods/unnecessary_to_owned.rs | 8 +- clippy_lints/src/module_style.rs | 6 +- clippy_lints/src/nonstandard_macro_braces.rs | 4 + .../src/operators/arithmetic_side_effects.rs | 51 +- clippy_lints/src/renamed_lints.rs | 1 + clippy_lints/src/unused_peekable.rs | 36 +- clippy_lints/src/use_self.rs | 8 +- clippy_lints/src/utils/conf.rs | 2 +- clippy_lints/src/write.rs | 813 ++++++------------ clippy_utils/src/consts.rs | 8 +- clippy_utils/src/macros.rs | 100 +-- clippy_utils/src/sugg.rs | 48 +- clippy_utils/src/ty.rs | 7 + src/docs.rs | 2 +- src/docs/iter_kv_map.txt | 22 + .../positional_named_format_parameters.txt | 15 - src/docs/print_literal.txt | 4 - src/docs/print_stderr.txt | 8 +- src/docs/print_stdout.txt | 8 +- src/docs/write_literal.txt | 4 - .../module_style/fail_mod_remap/Cargo.toml | 9 + .../module_style/fail_mod_remap/src/bad.rs | 1 + .../fail_mod_remap/src/bad/inner.rs | 1 + .../module_style/fail_mod_remap/src/main.rs | 7 + .../fail_mod_remap/src/main.stderr | 11 + .../conf_nonstandard_macro_braces.rs | 1 + .../conf_nonstandard_macro_braces.stderr | 30 +- tests/ui/almost_complete_letter_range.fixed | 13 + tests/ui/almost_complete_letter_range.rs | 13 + tests/ui/almost_complete_letter_range.stderr | 39 +- tests/ui/arithmetic_side_effects.rs | 104 ++- tests/ui/arithmetic_side_effects.stderr | 92 +- tests/ui/assertions_on_result_states.fixed | 6 + tests/ui/assertions_on_result_states.rs | 6 + tests/ui/assertions_on_result_states.stderr | 8 +- tests/ui/auxiliary/macro_rules.rs | 7 + tests/ui/bool_to_int_with_if.fixed | 8 +- tests/ui/bool_to_int_with_if.rs | 14 + tests/ui/bool_to_int_with_if.stderr | 41 +- tests/ui/collapsible_if.fixed | 3 + tests/ui/collapsible_if.rs | 5 + tests/ui/collapsible_if.stderr | 10 +- tests/ui/crashes/ice-9463.rs | 5 + tests/ui/crashes/ice-9463.stderr | 29 + tests/ui/derivable_impls.fixed | 213 +++++ tests/ui/derivable_impls.rs | 4 + tests/ui/derivable_impls.stderr | 56 +- tests/ui/eprint_with_newline.rs | 10 +- tests/ui/eprint_with_newline.stderr | 18 +- tests/ui/explicit_write.fixed | 2 + tests/ui/explicit_write.rs | 2 + tests/ui/explicit_write.stderr | 8 +- tests/ui/format.fixed | 4 - tests/ui/format.rs | 4 - tests/ui/format.stderr | 44 +- tests/ui/iter_kv_map.fixed | 64 ++ tests/ui/iter_kv_map.rs | 64 ++ tests/ui/iter_kv_map.stderr | 136 +++ tests/ui/large_enum_variant.rs | 4 +- tests/ui/large_enum_variant.stderr | 16 +- tests/ui/large_stack_arrays.rs | 6 + tests/ui/large_stack_arrays.stderr | 8 +- tests/ui/len_without_is_empty.rs | 2 +- tests/ui/nonminimal_bool.rs | 6 + tests/ui/nonminimal_bool.stderr | 8 +- .../positional_named_format_parameters.fixed | 56 -- .../ui/positional_named_format_parameters.rs | 56 -- .../positional_named_format_parameters.stderr | 418 --------- tests/ui/print_literal.rs | 2 + tests/ui/print_literal.stderr | 86 +- tests/ui/print_with_newline.rs | 10 +- tests/ui/print_with_newline.stderr | 18 +- tests/ui/println_empty_string.stderr | 24 +- tests/ui/rename.fixed | 2 + tests/ui/rename.rs | 2 + tests/ui/rename.stderr | 82 +- tests/ui/unnecessary_to_owned.fixed | 9 + tests/ui/unnecessary_to_owned.rs | 9 + tests/ui/unused_peekable.rs | 33 +- tests/ui/use_self.fixed | 9 + tests/ui/use_self.rs | 9 + tests/ui/write_literal.rs | 2 + tests/ui/write_literal.stderr | 86 +- tests/ui/write_literal_2.rs | 9 +- tests/ui/write_literal_2.stderr | 80 +- tests/ui/write_with_newline.rs | 8 + tests/ui/write_with_newline.stderr | 38 +- tests/ui/writeln_empty_string.stderr | 12 +- 111 files changed, 2040 insertions(+), 1674 deletions(-) create mode 100644 clippy_lints/src/methods/iter_kv_map.rs create mode 100644 src/docs/iter_kv_map.txt delete mode 100644 src/docs/positional_named_format_parameters.txt create mode 100644 tests/ui-cargo/module_style/fail_mod_remap/Cargo.toml create mode 100644 tests/ui-cargo/module_style/fail_mod_remap/src/bad.rs create mode 100644 tests/ui-cargo/module_style/fail_mod_remap/src/bad/inner.rs create mode 100644 tests/ui-cargo/module_style/fail_mod_remap/src/main.rs create mode 100644 tests/ui-cargo/module_style/fail_mod_remap/src/main.stderr create mode 100644 tests/ui/crashes/ice-9463.rs create mode 100644 tests/ui/crashes/ice-9463.stderr create mode 100644 tests/ui/derivable_impls.fixed create mode 100644 tests/ui/iter_kv_map.fixed create mode 100644 tests/ui/iter_kv_map.rs create mode 100644 tests/ui/iter_kv_map.stderr delete mode 100644 tests/ui/positional_named_format_parameters.fixed delete mode 100644 tests/ui/positional_named_format_parameters.rs delete mode 100644 tests/ui/positional_named_format_parameters.stderr diff --git a/CHANGELOG.md b/CHANGELOG.md index d847e4c74..044cbff4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3800,6 +3800,7 @@ Released 2018-09-13 [`items_after_statements`]: https://rust-lang.github.io/rust-clippy/master/index.html#items_after_statements [`iter_cloned_collect`]: https://rust-lang.github.io/rust-clippy/master/index.html#iter_cloned_collect [`iter_count`]: https://rust-lang.github.io/rust-clippy/master/index.html#iter_count +[`iter_kv_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#iter_kv_map [`iter_next_loop`]: https://rust-lang.github.io/rust-clippy/master/index.html#iter_next_loop [`iter_next_slice`]: https://rust-lang.github.io/rust-clippy/master/index.html#iter_next_slice [`iter_not_returning_iterator`]: https://rust-lang.github.io/rust-clippy/master/index.html#iter_not_returning_iterator diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 28b4cfd5f..6c977b2ca 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -110,23 +110,28 @@ Just make sure to remove the dependencies again before finally making a pull req [IntelliJ_rust_homepage]: https://intellij-rust.github.io/ ### Rust Analyzer -As of [#6869][6869], [`rust-analyzer`][ra_homepage] can understand that Clippy uses compiler-internals -using `extern crate` when `package.metadata.rust-analyzer.rustc_private` is set to `true` in Clippy's `Cargo.toml.` -You will require a `nightly` toolchain with the `rustc-dev` component installed. -Make sure that in the `rust-analyzer` configuration, you set +For [`rust-analyzer`][ra_homepage] to work correctly make sure that in the `rust-analyzer` configuration you set + ```json { "rust-analyzer.rustc.source": "discover" } ``` -and -```json -{ "rust-analyzer.updates.channel": "nightly" } -``` + You should be able to see information on things like `Expr` or `EarlyContext` now if you hover them, also a lot more type hints. -This will work with `rust-analyzer 2021-03-15` shipped in nightly `1.52.0-nightly (107896c32 2021-03-15)` or later. + +To have `rust-analyzer` also work in the `clippy_dev` and `lintcheck` crates, add the following configuration + +```json +{ + "rust-analyzer.linkedProjects": [ + "./Cargo.toml", + "clippy_dev/Cargo.toml", + "lintcheck/Cargo.toml", + ] +} +``` [ra_homepage]: https://rust-analyzer.github.io/ -[6869]: https://github.com/rust-lang/rust-clippy/pull/6869 ## How Clippy works diff --git a/book/src/development/adding_lints.md b/book/src/development/adding_lints.md index da781eb97..b1e843bc7 100644 --- a/book/src/development/adding_lints.md +++ b/book/src/development/adding_lints.md @@ -90,6 +90,7 @@ We start by opening the test file created at `tests/ui/foo_functions.rs`. Update the file with some examples to get started: ```rust +#![allow(unused)] #![warn(clippy::foo_functions)] // Impl methods diff --git a/book/src/development/common_tools_writing_lints.md b/book/src/development/common_tools_writing_lints.md index 2bc275cef..f5aa06e4b 100644 --- a/book/src/development/common_tools_writing_lints.md +++ b/book/src/development/common_tools_writing_lints.md @@ -123,7 +123,8 @@ There are three ways to do this, depending on if the target trait has a diagnostic item, lang item or neither. ```rust -use clippy_utils::{implements_trait, is_trait_method, match_trait_method, paths}; +use clippy_utils::ty::implements_trait; +use clippy_utils::is_trait_method; use rustc_span::symbol::sym; impl LateLintPass<'_> for MyStructLint { @@ -143,13 +144,6 @@ impl LateLintPass<'_> for MyStructLint { .map_or(false, |id| implements_trait(cx, ty, id, &[])) { // `expr` implements `Drop` trait } - - // 3. Using the type path with the expression - // we use `match_trait_method` function from Clippy's utils - // (This method should be avoided if possible) - if match_trait_method(cx, expr, &paths::INTO) { - // `expr` implements `Into` trait - } } } ``` @@ -233,8 +227,9 @@ functions to deal with macros: crates ```rust - #[macro_use] - extern crate a_crate_with_macros; + use rustc_middle::lint::in_external_macro; + + use a_crate_with_macros::foo; // `foo` is defined in `a_crate_with_macros` foo!("bar"); diff --git a/clippy_dev/src/new_lint.rs b/clippy_dev/src/new_lint.rs index 331b76484..02cb13a1d 100644 --- a/clippy_dev/src/new_lint.rs +++ b/clippy_dev/src/new_lint.rs @@ -188,6 +188,7 @@ pub(crate) fn get_stabilization_version() -> String { fn get_test_file_contents(lint_name: &str, header_commands: Option<&str>) -> String { let mut contents = format!( indoc! {" + #![allow(unused)] #![warn(clippy::{})] fn main() {{ diff --git a/clippy_lints/src/almost_complete_letter_range.rs b/clippy_lints/src/almost_complete_letter_range.rs index 59a7c5354..073e4af13 100644 --- a/clippy_lints/src/almost_complete_letter_range.rs +++ b/clippy_lints/src/almost_complete_letter_range.rs @@ -4,6 +4,7 @@ use clippy_utils::{meets_msrv, msrvs}; use rustc_ast::ast::{Expr, ExprKind, LitKind, Pat, PatKind, RangeEnd, RangeLimits}; use rustc_errors::Applicability; use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; +use rustc_middle::lint::in_external_macro; use rustc_semver::RustcVersion; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::Span; @@ -79,6 +80,7 @@ fn check_range(cx: &EarlyContext<'_>, span: Span, start: &Expr, end: &Expr, sugg (LitKind::Byte(b'a') | LitKind::Char('a'), LitKind::Byte(b'z') | LitKind::Char('z')) | (LitKind::Byte(b'A') | LitKind::Char('A'), LitKind::Byte(b'Z') | LitKind::Char('Z')) ) + && !in_external_macro(cx.sess(), span) { span_lint_and_then( cx, diff --git a/clippy_lints/src/assertions_on_result_states.rs b/clippy_lints/src/assertions_on_result_states.rs index 7cd198ace..656dc5fee 100644 --- a/clippy_lints/src/assertions_on_result_states.rs +++ b/clippy_lints/src/assertions_on_result_states.rs @@ -1,9 +1,9 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::macros::{find_assert_args, root_macro_call_first_node, PanicExpn}; -use clippy_utils::path_res; use clippy_utils::source::snippet_with_context; -use clippy_utils::ty::{implements_trait, is_copy, is_type_diagnostic_item}; +use clippy_utils::ty::{has_debug_impl, is_copy, is_type_diagnostic_item}; use clippy_utils::usage::local_used_after_expr; +use clippy_utils::{is_expr_final_block_expr, path_res}; use rustc_errors::Applicability; use rustc_hir::def::Res; use rustc_hir::{Expr, ExprKind}; @@ -58,6 +58,7 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnResultStates { return; } } + let semicolon = if is_expr_final_block_expr(cx.tcx, e) {";"} else {""}; let mut app = Applicability::MachineApplicable; match method_segment.ident.as_str() { "is_ok" if type_suitable_to_unwrap(cx, substs.type_at(1)) => { @@ -68,8 +69,9 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnResultStates { "called `assert!` with `Result::is_ok`", "replace with", format!( - "{}.unwrap()", - snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0 + "{}.unwrap(){}", + snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0, + semicolon ), app, ); @@ -82,8 +84,9 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnResultStates { "called `assert!` with `Result::is_err`", "replace with", format!( - "{}.unwrap_err()", - snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0 + "{}.unwrap_err(){}", + snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0, + semicolon ), app, ); @@ -94,13 +97,6 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnResultStates { } } -/// This checks whether a given type is known to implement Debug. -fn has_debug_impl<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { - cx.tcx - .get_diagnostic_item(sym::Debug) - .map_or(false, |debug| implements_trait(cx, ty, debug, &[])) -} - fn type_suitable_to_unwrap<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { has_debug_impl(cx, ty) && !ty.is_unit() && !ty.is_never() } diff --git a/clippy_lints/src/bool_to_int_with_if.rs b/clippy_lints/src/bool_to_int_with_if.rs index a4b8cbb0d..51e98cda8 100644 --- a/clippy_lints/src/bool_to_int_with_if.rs +++ b/clippy_lints/src/bool_to_int_with_if.rs @@ -1,9 +1,9 @@ -use rustc_ast::{ExprPrecedence, LitKind}; +use rustc_ast::LitKind; use rustc_hir::{Block, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use clippy_utils::{diagnostics::span_lint_and_then, is_else_clause, source::snippet_block_with_applicability}; +use clippy_utils::{diagnostics::span_lint_and_then, is_else_clause, sugg::Sugg}; use rustc_errors::Applicability; declare_clippy_lint! { @@ -55,27 +55,42 @@ fn check_if_else<'tcx>(ctx: &LateContext<'tcx>, expr: &'tcx rustc_hir::Expr<'tcx if let ExprKind::If(check, then, Some(else_)) = expr.kind && let Some(then_lit) = int_literal(then) && let Some(else_lit) = int_literal(else_) - && check_int_literal_equals_val(then_lit, 1) - && check_int_literal_equals_val(else_lit, 0) { + let inverted = if + check_int_literal_equals_val(then_lit, 1) + && check_int_literal_equals_val(else_lit, 0) { + false + } else if + check_int_literal_equals_val(then_lit, 0) + && check_int_literal_equals_val(else_lit, 1) { + true + } else { + // Expression isn't boolean, exit + return; + }; let mut applicability = Applicability::MachineApplicable; - let snippet = snippet_block_with_applicability(ctx, check.span, "..", None, &mut applicability); - let snippet_with_braces = { - let need_parens = should_have_parentheses(check); - let (left_paren, right_paren) = if need_parens {("(", ")")} else {("", "")}; - format!("{left_paren}{snippet}{right_paren}") + let snippet = { + let mut sugg = Sugg::hir_with_applicability(ctx, check, "..", &mut applicability); + if inverted { + sugg = !sugg; + } + sugg }; let ty = ctx.typeck_results().expr_ty(then_lit); // then and else must be of same type let suggestion = { let wrap_in_curly = is_else_clause(ctx.tcx, expr); - let (left_curly, right_curly) = if wrap_in_curly {("{", "}")} else {("", "")}; - format!( - "{left_curly}{ty}::from({snippet}){right_curly}" - ) + let mut s = Sugg::NonParen(format!("{ty}::from({snippet})").into()); + if wrap_in_curly { + s = s.blockify(); + } + s }; // when used in else clause if statement should be wrapped in curly braces + let into_snippet = snippet.clone().maybe_par(); + let as_snippet = snippet.as_ty(ty); + span_lint_and_then(ctx, BOOL_TO_INT_WITH_IF, expr.span, @@ -87,7 +102,7 @@ fn check_if_else<'tcx>(ctx: &LateContext<'tcx>, expr: &'tcx rustc_hir::Expr<'tcx suggestion, applicability, ); - diag.note(format!("`{snippet_with_braces} as {ty}` or `{snippet_with_braces}.into()` can also be valid options")); + diag.note(format!("`{as_snippet}` or `{into_snippet}.into()` can also be valid options")); }); }; } @@ -119,7 +134,3 @@ fn check_int_literal_equals_val<'tcx>(expr: &'tcx rustc_hir::Expr<'tcx>, expecte false } } - -fn should_have_parentheses<'tcx>(check: &'tcx rustc_hir::Expr<'tcx>) -> bool { - check.precedence().order() < ExprPrecedence::Cast.order() -} diff --git a/clippy_lints/src/booleans.rs b/clippy_lints/src/booleans.rs index 656d639f0..03d262d5a 100644 --- a/clippy_lints/src/booleans.rs +++ b/clippy_lints/src/booleans.rs @@ -237,7 +237,7 @@ impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> { } }, &Term(n) => { - let snip = snippet_opt(self.cx, self.terminals[n as usize].span)?; + let snip = snippet_opt(self.cx, self.terminals[n as usize].span.source_callsite())?; self.output.push_str(&snip); }, } diff --git a/clippy_lints/src/dereference.rs b/clippy_lints/src/dereference.rs index 45b5d79d4..501f9ef78 100644 --- a/clippy_lints/src/dereference.rs +++ b/clippy_lints/src/dereference.rs @@ -297,13 +297,10 @@ impl<'tcx> LateLintPass<'tcx> for Dereferencing { if !is_lint_allowed(cx, EXPLICIT_DEREF_METHODS, expr.hir_id) && position.lint_explicit_deref() => { + let ty_changed_count = usize::from(!deref_method_same_type(expr_ty, typeck.expr_ty(sub_expr))); self.state = Some(( State::DerefMethod { - ty_changed_count: if deref_method_same_type(expr_ty, typeck.expr_ty(sub_expr)) { - 0 - } else { - 1 - }, + ty_changed_count, is_final_ufcs: matches!(expr.kind, ExprKind::Call(..)), target_mut, }, diff --git a/clippy_lints/src/derivable_impls.rs b/clippy_lints/src/derivable_impls.rs index ef9eeecc6..06ae5abea 100644 --- a/clippy_lints/src/derivable_impls.rs +++ b/clippy_lints/src/derivable_impls.rs @@ -1,5 +1,6 @@ -use clippy_utils::diagnostics::span_lint_and_help; +use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::{is_default_equivalent, peel_blocks}; +use rustc_errors::Applicability; use rustc_hir::{ def::{DefKind, Res}, Body, Expr, ExprKind, GenericArg, Impl, ImplItemKind, Item, ItemKind, Node, PathSegment, QPath, TyKind, @@ -100,15 +101,28 @@ impl<'tcx> LateLintPass<'tcx> for DerivableImpls { ExprKind::Struct(_, fields, _) => fields.iter().all(|ef| is_default_equivalent(cx, ef.expr)), _ => false, }; + if should_emit { - let path_string = cx.tcx.def_path_str(adt_def.did()); - span_lint_and_help( + let struct_span = cx.tcx.def_span(adt_def.did()); + span_lint_and_then( cx, DERIVABLE_IMPLS, item.span, "this `impl` can be derived", - None, - &format!("try annotating `{}` with `#[derive(Default)]`", path_string), + |diag| { + diag.span_suggestion_hidden( + item.span, + "remove the manual implementation...", + String::new(), + Applicability::MachineApplicable + ); + diag.span_suggestion( + struct_span.shrink_to_lo(), + "...and instead derive it", + "#[derive(Default)]\n".to_string(), + Applicability::MachineApplicable + ); + } ); } } diff --git a/clippy_lints/src/format.rs b/clippy_lints/src/format.rs index 0c5851cdb..f10d82569 100644 --- a/clippy_lints/src/format.rs +++ b/clippy_lints/src/format.rs @@ -71,12 +71,12 @@ impl<'tcx> LateLintPass<'tcx> for UselessFormat { let value = arg.param.value; if_chain! { if format_args.format_string.parts == [kw::Empty]; + if arg.format.is_default(); if match cx.typeck_results().expr_ty(value).peel_refs().kind() { ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(sym::String, adt.did()), ty::Str => true, _ => false, }; - if !arg.format.has_string_formatting(); then { let is_new_string = match value.kind { ExprKind::Binary(..) => true, diff --git a/clippy_lints/src/format_args.rs b/clippy_lints/src/format_args.rs index 2a55c48cf..9e1eaf248 100644 --- a/clippy_lints/src/format_args.rs +++ b/clippy_lints/src/format_args.rs @@ -77,7 +77,7 @@ impl<'tcx> LateLintPass<'tcx> for FormatArgs { if let ExpnKind::Macro(_, name) = outermost_expn_data.kind; then { for arg in &format_args.args { - if arg.format.has_string_formatting() { + if !arg.format.is_default() { continue; } if is_aliased(&format_args, arg.param.value.hir_id) { diff --git a/clippy_lints/src/large_stack_arrays.rs b/clippy_lints/src/large_stack_arrays.rs index 0acbd81ae..5857d81ab 100644 --- a/clippy_lints/src/large_stack_arrays.rs +++ b/clippy_lints/src/large_stack_arrays.rs @@ -1,7 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::source::snippet; -use if_chain::if_chain; -use rustc_hir::{Expr, ExprKind}; +use rustc_hir::{Expr, ExprKind, Item, ItemKind, Node}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::{self, ConstKind}; @@ -39,29 +38,28 @@ impl_lint_pass!(LargeStackArrays => [LARGE_STACK_ARRAYS]); impl<'tcx> LateLintPass<'tcx> for LargeStackArrays { fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { - if_chain! { - if let ExprKind::Repeat(_, _) = expr.kind; - if let ty::Array(element_type, cst) = cx.typeck_results().expr_ty(expr).kind(); - if let ConstKind::Value(ty::ValTree::Leaf(element_count)) = cst.kind(); - if let Ok(element_count) = element_count.try_to_machine_usize(cx.tcx); - if let Ok(element_size) = cx.layout_of(*element_type).map(|l| l.size.bytes()); - if self.maximum_allowed_size < element_count * element_size; - then { - span_lint_and_help( - cx, - LARGE_STACK_ARRAYS, - expr.span, - &format!( - "allocating a local array larger than {} bytes", - self.maximum_allowed_size - ), - None, - &format!( - "consider allocating on the heap with `vec!{}.into_boxed_slice()`", - snippet(cx, expr.span, "[...]") - ), - ); - } - } + if let ExprKind::Repeat(_, _) = expr.kind + && let ty::Array(element_type, cst) = cx.typeck_results().expr_ty(expr).kind() + && let ConstKind::Value(ty::ValTree::Leaf(element_count)) = cst.kind() + && let Ok(element_count) = element_count.try_to_machine_usize(cx.tcx) + && let Ok(element_size) = cx.layout_of(*element_type).map(|l| l.size.bytes()) + && !cx.tcx.hir().parent_iter(expr.hir_id) + .any(|(_, node)| matches!(node, Node::Item(Item { kind: ItemKind::Static(..), .. }))) + && self.maximum_allowed_size < element_count * element_size { + span_lint_and_help( + cx, + LARGE_STACK_ARRAYS, + expr.span, + &format!( + "allocating a local array larger than {} bytes", + self.maximum_allowed_size + ), + None, + &format!( + "consider allocating on the heap with `vec!{}.into_boxed_slice()`", + snippet(cx, expr.span, "[...]") + ), + ); + } } } diff --git a/clippy_lints/src/lib.register_all.rs b/clippy_lints/src/lib.register_all.rs index 59d1760fe..8718d5fa1 100644 --- a/clippy_lints/src/lib.register_all.rs +++ b/clippy_lints/src/lib.register_all.rs @@ -171,6 +171,7 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![ LintId::of(methods::ITERATOR_STEP_BY_ZERO), LintId::of(methods::ITER_CLONED_COLLECT), LintId::of(methods::ITER_COUNT), + LintId::of(methods::ITER_KV_MAP), LintId::of(methods::ITER_NEXT_SLICE), LintId::of(methods::ITER_NTH), LintId::of(methods::ITER_NTH_ZERO), @@ -351,7 +352,6 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![ LintId::of(useless_conversion::USELESS_CONVERSION), LintId::of(vec::USELESS_VEC), LintId::of(vec_init_then_push::VEC_INIT_THEN_PUSH), - LintId::of(write::POSITIONAL_NAMED_FORMAT_PARAMETERS), LintId::of(write::PRINTLN_EMPTY_STRING), LintId::of(write::PRINT_LITERAL), LintId::of(write::PRINT_WITH_NEWLINE), diff --git a/clippy_lints/src/lib.register_complexity.rs b/clippy_lints/src/lib.register_complexity.rs index aa247352f..185189a6a 100644 --- a/clippy_lints/src/lib.register_complexity.rs +++ b/clippy_lints/src/lib.register_complexity.rs @@ -40,6 +40,7 @@ store.register_group(true, "clippy::complexity", Some("clippy_complexity"), vec! LintId::of(methods::GET_LAST_WITH_LEN), LintId::of(methods::INSPECT_FOR_EACH), LintId::of(methods::ITER_COUNT), + LintId::of(methods::ITER_KV_MAP), LintId::of(methods::MANUAL_FILTER_MAP), LintId::of(methods::MANUAL_FIND_MAP), LintId::of(methods::MANUAL_SPLIT_ONCE), diff --git a/clippy_lints/src/lib.register_lints.rs b/clippy_lints/src/lib.register_lints.rs index 962e67220..02fcc8de5 100644 --- a/clippy_lints/src/lib.register_lints.rs +++ b/clippy_lints/src/lib.register_lints.rs @@ -313,6 +313,7 @@ store.register_lints(&[ methods::ITERATOR_STEP_BY_ZERO, methods::ITER_CLONED_COLLECT, methods::ITER_COUNT, + methods::ITER_KV_MAP, methods::ITER_NEXT_SLICE, methods::ITER_NTH, methods::ITER_NTH_ZERO, @@ -595,7 +596,6 @@ store.register_lints(&[ vec_init_then_push::VEC_INIT_THEN_PUSH, wildcard_imports::ENUM_GLOB_USE, wildcard_imports::WILDCARD_IMPORTS, - write::POSITIONAL_NAMED_FORMAT_PARAMETERS, write::PRINTLN_EMPTY_STRING, write::PRINT_LITERAL, write::PRINT_STDERR, diff --git a/clippy_lints/src/lib.register_suspicious.rs b/clippy_lints/src/lib.register_suspicious.rs index bede91f18..6125d0f7a 100644 --- a/clippy_lints/src/lib.register_suspicious.rs +++ b/clippy_lints/src/lib.register_suspicious.rs @@ -35,5 +35,4 @@ store.register_group(true, "clippy::suspicious", Some("clippy_suspicious"), vec! LintId::of(suspicious_trait_impl::SUSPICIOUS_ARITHMETIC_IMPL), LintId::of(suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL), LintId::of(swap_ptr_to_ref::SWAP_PTR_TO_REF), - LintId::of(write::POSITIONAL_NAMED_FORMAT_PARAMETERS), ]) diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index ceaaf5c6d..298566cb5 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -40,7 +40,6 @@ extern crate rustc_lint; extern crate rustc_middle; extern crate rustc_mir_dataflow; extern crate rustc_parse; -extern crate rustc_parse_format; extern crate rustc_session; extern crate rustc_span; extern crate rustc_target; @@ -425,7 +424,6 @@ pub fn register_pre_expansion_lints(store: &mut rustc_lint::LintStore, sess: &Se }) }); - store.register_pre_expansion_pass(|| Box::new(write::Write::default())); store.register_pre_expansion_pass(move || Box::new(attrs::EarlyAttributes { msrv })); } @@ -524,7 +522,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: #[cfg(feature = "internal")] { if std::env::var("ENABLE_METADATA_COLLECTION").eq(&Ok("1".to_string())) { - store.register_late_pass(|| Box::new(utils::internal_lints::metadata_collector::MetadataCollector::new())); + store.register_late_pass(|_| Box::new(utils::internal_lints::metadata_collector::MetadataCollector::new())); return; } } @@ -879,6 +877,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: ignore_publish: cargo_ignore_publish, }) }); + store.register_late_pass(|_| Box::new(write::Write::default())); store.register_early_pass(|| Box::new(crate_in_macro_def::CrateInMacroDef)); store.register_early_pass(|| Box::new(empty_structs_with_brackets::EmptyStructsWithBrackets)); store.register_late_pass(|_| Box::new(unnecessary_owned_empty_strings::UnnecessaryOwnedEmptyStrings)); diff --git a/clippy_lints/src/methods/err_expect.rs b/clippy_lints/src/methods/err_expect.rs index 570a1b873..720d9a68c 100644 --- a/clippy_lints/src/methods/err_expect.rs +++ b/clippy_lints/src/methods/err_expect.rs @@ -1,6 +1,6 @@ use super::ERR_EXPECT; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::ty::implements_trait; +use clippy_utils::ty::has_debug_impl; use clippy_utils::{meets_msrv, msrvs, ty::is_type_diagnostic_item}; use rustc_errors::Applicability; use rustc_lint::LateContext; @@ -28,7 +28,7 @@ pub(super) fn check( // Tests if the T type in a `Result` is not None if let Some(data_type) = get_data_type(cx, result_type); // Tests if the T type in a `Result` implements debug - if has_debug_impl(data_type, cx); + if has_debug_impl(cx, data_type); then { span_lint_and_sugg( @@ -51,10 +51,3 @@ fn get_data_type<'a>(cx: &LateContext<'_>, ty: Ty<'a>) -> Option> { _ => None, } } - -/// Given a type, very if the Debug trait has been impl'd -fn has_debug_impl<'tcx>(ty: Ty<'tcx>, cx: &LateContext<'tcx>) -> bool { - cx.tcx - .get_diagnostic_item(sym::Debug) - .map_or(false, |debug| implements_trait(cx, ty, debug, &[])) -} diff --git a/clippy_lints/src/methods/iter_kv_map.rs b/clippy_lints/src/methods/iter_kv_map.rs new file mode 100644 index 000000000..a7eecabd6 --- /dev/null +++ b/clippy_lints/src/methods/iter_kv_map.rs @@ -0,0 +1,87 @@ +#![allow(unused_imports)] + +use super::ITER_KV_MAP; +use clippy_utils::diagnostics::{multispan_sugg, span_lint_and_sugg, span_lint_and_then}; +use clippy_utils::source::{snippet, snippet_with_applicability}; +use clippy_utils::sugg; +use clippy_utils::ty::is_type_diagnostic_item; +use clippy_utils::visitors::is_local_used; +use rustc_hir::{BindingAnnotation, Body, BorrowKind, Expr, ExprKind, Mutability, Pat, PatKind}; +use rustc_lint::{LateContext, LintContext}; +use rustc_middle::ty; +use rustc_span::sym; +use rustc_span::Span; + +/// lint use of: +/// - `hashmap.iter().map(|(_, v)| v)` +/// - `hashmap.into_iter().map(|(_, v)| v)` +/// on `HashMaps` and `BTreeMaps` in std + +pub(super) fn check<'tcx>( + cx: &LateContext<'tcx>, + map_type: &'tcx str, // iter / into_iter + expr: &'tcx Expr<'tcx>, // .iter().map(|(_, v_| v)) + recv: &'tcx Expr<'tcx>, // hashmap + m_arg: &'tcx Expr<'tcx>, // |(_, v)| v +) { + if_chain! { + if !expr.span.from_expansion(); + if let ExprKind::Closure(c) = m_arg.kind; + if let Body {params: [p], value: body_expr, generator_kind: _ } = cx.tcx.hir().body(c.body); + if let PatKind::Tuple([key_pat, val_pat], _) = p.pat.kind; + + let (replacement_kind, binded_ident) = match (&key_pat.kind, &val_pat.kind) { + (key, PatKind::Binding(_, _, value, _)) if pat_is_wild(cx, key, m_arg) => ("value", value), + (PatKind::Binding(_, _, key, _), value) if pat_is_wild(cx, value, m_arg) => ("key", key), + _ => return, + }; + + let ty = cx.typeck_results().expr_ty(recv); + if is_type_diagnostic_item(cx, ty, sym::HashMap) || is_type_diagnostic_item(cx, ty, sym::BTreeMap); + + then { + let mut applicability = rustc_errors::Applicability::MachineApplicable; + let recv_snippet = snippet_with_applicability(cx, recv.span, "map", &mut applicability); + let into_prefix = if map_type == "into_iter" {"into_"} else {""}; + + if_chain! { + if let ExprKind::Path(rustc_hir::QPath::Resolved(_, path)) = body_expr.kind; + if let [local_ident] = path.segments; + if local_ident.ident.as_str() == binded_ident.as_str(); + + then { + span_lint_and_sugg( + cx, + ITER_KV_MAP, + expr.span, + &format!("iterating on a map's {}s", replacement_kind), + "try", + format!("{}.{}{}s()", recv_snippet, into_prefix, replacement_kind), + applicability, + ); + } else { + span_lint_and_sugg( + cx, + ITER_KV_MAP, + expr.span, + &format!("iterating on a map's {}s", replacement_kind), + "try", + format!("{}.{}{}s().map(|{}| {})", recv_snippet, into_prefix, replacement_kind, binded_ident, + snippet_with_applicability(cx, body_expr.span, "/* body */", &mut applicability)), + applicability, + ); + } + } + } + } +} + +/// Returns `true` if the pattern is a `PatWild`, or is an ident prefixed with `_` +/// that is not locally used. +fn pat_is_wild<'tcx>(cx: &LateContext<'tcx>, pat: &'tcx PatKind<'_>, body: &'tcx Expr<'_>) -> bool { + match *pat { + PatKind::Wild => true, + PatKind::Binding(_, id, ident, None) if ident.as_str().starts_with('_') => !is_local_used(cx, body, id), + _ => false, + } +} diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index 41942b20e..cdde4c54d 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -35,6 +35,7 @@ mod into_iter_on_ref; mod is_digit_ascii_radix; mod iter_cloned_collect; mod iter_count; +mod iter_kv_map; mod iter_next_slice; mod iter_nth; mod iter_nth_zero; @@ -3036,6 +3037,37 @@ declare_clippy_lint! { "use of `File::read_to_end` or `File::read_to_string`" } +declare_clippy_lint! { + /// ### 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 we only need the keys or the values. + /// + /// ### Example + /// + /// ``` + /// # use std::collections::HashMap; + /// let map: HashMap = HashMap::new(); + /// let values = map.iter().map(|(_, value)| value).collect::>(); + /// ``` + /// + /// Use instead: + /// ``` + /// # use std::collections::HashMap; + /// let map: HashMap = HashMap::new(); + /// let values = map.values().collect::>(); + /// ``` + #[clippy::version = "1.65.0"] + pub ITER_KV_MAP, + complexity, + "iterating on map using `iter` when `keys` or `values` would do" +} + pub struct Methods { avoid_breaking_exported_api: bool, msrv: Option, @@ -3159,6 +3191,7 @@ impl_lint_pass!(Methods => [ UNNECESSARY_SORT_BY, VEC_RESIZE_TO_ZERO, VERBOSE_FILE_READS, + ITER_KV_MAP, ]); /// Extracts a method call name, args, and `Span` of the method name. @@ -3498,6 +3531,9 @@ impl Methods { (name @ ("map" | "map_err"), [m_arg]) => { if name == "map" { map_clone::check(cx, expr, recv, m_arg, self.msrv); + if let Some((map_name @ ("iter" | "into_iter"), recv2, _, _)) = method_call(recv) { + iter_kv_map::check(cx, map_name, expr, recv2, m_arg); + } } else { map_err_ignore::check(cx, expr, m_arg); } diff --git a/clippy_lints/src/methods/ok_expect.rs b/clippy_lints/src/methods/ok_expect.rs index d64a9f320..646fc4a7b 100644 --- a/clippy_lints/src/methods/ok_expect.rs +++ b/clippy_lints/src/methods/ok_expect.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_help; -use clippy_utils::ty::{implements_trait, is_type_diagnostic_item}; +use clippy_utils::ty::{has_debug_impl, is_type_diagnostic_item}; use if_chain::if_chain; use rustc_hir as hir; use rustc_lint::LateContext; @@ -15,7 +15,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, recv: &hir::Expr if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv), sym::Result); let result_type = cx.typeck_results().expr_ty(recv); if let Some(error_type) = get_error_type(cx, result_type); - if has_debug_impl(error_type, cx); + if has_debug_impl(cx, error_type); then { span_lint_and_help( @@ -37,10 +37,3 @@ fn get_error_type<'a>(cx: &LateContext<'_>, ty: Ty<'a>) -> Option> { _ => None, } } - -/// This checks whether a given type is known to implement Debug. -fn has_debug_impl<'tcx>(ty: Ty<'tcx>, cx: &LateContext<'tcx>) -> bool { - cx.tcx - .get_diagnostic_item(sym::Debug) - .map_or(false, |debug| implements_trait(cx, ty, debug, &[])) -} diff --git a/clippy_lints/src/methods/unnecessary_to_owned.rs b/clippy_lints/src/methods/unnecessary_to_owned.rs index 8d3cede70..79d784c34 100644 --- a/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/clippy_lints/src/methods/unnecessary_to_owned.rs @@ -7,7 +7,7 @@ use clippy_utils::visitors::find_all_ret_expressions; use clippy_utils::{fn_def_id, get_parent_expr, is_diag_item_method, is_diag_trait_item, return_ty}; use clippy_utils::{meets_msrv, msrvs}; use rustc_errors::Applicability; -use rustc_hir::{def_id::DefId, BorrowKind, Expr, ExprKind, ItemKind, Node}; +use rustc_hir::{def_id::DefId, BorrowKind, Expr, ExprKind, ItemKind, LangItem, Node}; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::LateContext; use rustc_middle::mir::Mutability; @@ -268,7 +268,7 @@ fn check_other_call_arg<'tcx>( // We can't add an `&` when the trait is `Deref` because `Target = &T` won't match // `Target = T`. if n_refs > 0 || is_copy(cx, receiver_ty) || trait_predicate.def_id() != deref_trait_id; - let n_refs = max(n_refs, if is_copy(cx, receiver_ty) { 0 } else { 1 }); + let n_refs = max(n_refs, usize::from(!is_copy(cx, receiver_ty))); if let Some(receiver_snippet) = snippet_opt(cx, receiver.span); then { span_lint_and_sugg( @@ -379,6 +379,10 @@ fn can_change_type<'a>(cx: &LateContext<'a>, mut expr: &'a Expr<'a>, mut ty: Ty< Node::Expr(parent_expr) => { if let Some((callee_def_id, call_substs, recv, call_args)) = get_callee_substs_and_args(cx, parent_expr) { + if cx.tcx.lang_items().require(LangItem::IntoFutureIntoFuture) == Ok(callee_def_id) { + return false; + } + let fn_sig = cx.tcx.fn_sig(callee_def_id).skip_binder(); if let Some(arg_index) = recv.into_iter().chain(call_args).position(|arg| arg.hir_id == expr.hir_id) && let Some(param_ty) = fn_sig.inputs().get(arg_index) diff --git a/clippy_lints/src/module_style.rs b/clippy_lints/src/module_style.rs index 0a3936572..22071ab30 100644 --- a/clippy_lints/src/module_style.rs +++ b/clippy_lints/src/module_style.rs @@ -2,7 +2,7 @@ use rustc_ast::ast; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_lint::{EarlyContext, EarlyLintPass, Level, LintContext}; use rustc_session::{declare_tool_lint, impl_lint_pass}; -use rustc_span::{FileName, RealFileName, SourceFile, Span, SyntaxContext}; +use rustc_span::{FileName, SourceFile, Span, SyntaxContext}; use std::ffi::OsStr; use std::path::{Component, Path}; @@ -79,7 +79,7 @@ impl EarlyLintPass for ModStyle { let files = cx.sess().source_map().files(); - let RealFileName::LocalPath(trim_to_src) = &cx.sess().opts.working_dir else { return }; + let Some(trim_to_src) = cx.sess().opts.working_dir.local_path() else { return }; // `folder_segments` is all unique folder path segments `path/to/foo.rs` gives // `[path, to]` but not foo @@ -90,7 +90,7 @@ impl EarlyLintPass for ModStyle { // `{ foo => path/to/foo.rs, .. } let mut file_map = FxHashMap::default(); for file in files.iter() { - if let FileName::Real(RealFileName::LocalPath(lp)) = &file.name { + if let FileName::Real(name) = &file.name && let Some(lp) = name.local_path() { let path = if lp.is_relative() { lp } else if let Ok(relative) = lp.strip_prefix(trim_to_src) { diff --git a/clippy_lints/src/nonstandard_macro_braces.rs b/clippy_lints/src/nonstandard_macro_braces.rs index 4722c0310..f86dfb6b8 100644 --- a/clippy_lints/src/nonstandard_macro_braces.rs +++ b/clippy_lints/src/nonstandard_macro_braces.rs @@ -184,6 +184,10 @@ fn macro_braces(conf: FxHashSet) -> FxHashMap>(); diff --git a/clippy_lints/src/operators/arithmetic_side_effects.rs b/clippy_lints/src/operators/arithmetic_side_effects.rs index 83b69fbb3..d24c57c0a 100644 --- a/clippy_lints/src/operators/arithmetic_side_effects.rs +++ b/clippy_lints/src/operators/arithmetic_side_effects.rs @@ -42,27 +42,30 @@ impl ArithmeticSideEffects { } } - /// Checks assign operators (+=, -=, *=, /=) of integers in a non-constant environment that - /// won't overflow. - fn has_valid_assign_op(op: &Spanned, rhs: &hir::Expr<'_>, rhs_refs: Ty<'_>) -> bool { - if !Self::is_literal_integer(rhs, rhs_refs) { - return false; + /// Assuming that `expr` is a literal integer, checks operators (+=, -=, *, /) in a + /// non-constant environment that won't overflow. + fn has_valid_op(op: &Spanned, expr: &hir::Expr<'_>) -> bool { + if let hir::BinOpKind::Add | hir::BinOpKind::Sub = op.node + && let hir::ExprKind::Lit(ref lit) = expr.kind + && let ast::LitKind::Int(0, _) = lit.node + { + return true; } - if let hir::BinOpKind::Div | hir::BinOpKind::Mul = op.node - && let hir::ExprKind::Lit(ref lit) = rhs.kind - && let ast::LitKind::Int(1, _) = lit.node + if let hir::BinOpKind::Div | hir::BinOpKind::Rem = op.node + && let hir::ExprKind::Lit(ref lit) = expr.kind + && !matches!(lit.node, ast::LitKind::Int(0, _)) + { + return true; + } + if let hir::BinOpKind::Mul = op.node + && let hir::ExprKind::Lit(ref lit) = expr.kind + && let ast::LitKind::Int(0 | 1, _) = lit.node { return true; } false } - /// Checks "raw" binary operators (+, -, *, /) of integers in a non-constant environment - /// already handled by the CTFE. - fn has_valid_bin_op(lhs: &hir::Expr<'_>, lhs_refs: Ty<'_>, rhs: &hir::Expr<'_>, rhs_refs: Ty<'_>) -> bool { - Self::is_literal_integer(lhs, lhs_refs) && Self::is_literal_integer(rhs, rhs_refs) - } - /// Checks if the given `expr` has any of the inner `allowed` elements. fn is_allowed_ty(&self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool { self.allowed.contains( @@ -83,7 +86,8 @@ impl ArithmeticSideEffects { } fn issue_lint(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) { - span_lint(cx, ARITHMETIC_SIDE_EFFECTS, expr.span, "arithmetic detected"); + let msg = "arithmetic operation that can potentially result in unexpected side-effects"; + span_lint(cx, ARITHMETIC_SIDE_EFFECTS, expr.span, msg); self.expr_span = Some(expr.span); } @@ -115,13 +119,18 @@ impl ArithmeticSideEffects { if self.is_allowed_ty(cx, lhs) || self.is_allowed_ty(cx, rhs) { return; } - let lhs_refs = cx.typeck_results().expr_ty(lhs).peel_refs(); - let rhs_refs = cx.typeck_results().expr_ty(rhs).peel_refs(); - let has_valid_assign_op = Self::has_valid_assign_op(op, rhs, rhs_refs); - if has_valid_assign_op || Self::has_valid_bin_op(lhs, lhs_refs, rhs, rhs_refs) { - return; + let has_valid_op = match ( + Self::is_literal_integer(lhs, cx.typeck_results().expr_ty(lhs).peel_refs()), + Self::is_literal_integer(rhs, cx.typeck_results().expr_ty(rhs).peel_refs()), + ) { + (true, true) => true, + (true, false) => Self::has_valid_op(op, lhs), + (false, true) => Self::has_valid_op(op, rhs), + (false, false) => false, + }; + if !has_valid_op { + self.issue_lint(cx, expr); } - self.issue_lint(cx, expr); } } diff --git a/clippy_lints/src/renamed_lints.rs b/clippy_lints/src/renamed_lints.rs index 6bea6dc07..d320eea1c 100644 --- a/clippy_lints/src/renamed_lints.rs +++ b/clippy_lints/src/renamed_lints.rs @@ -36,6 +36,7 @@ pub static RENAMED_LINTS: &[(&str, &str)] = &[ ("clippy::invalid_ref", "invalid_value"), ("clippy::mem_discriminant_non_enum", "enum_intrinsics_non_enums"), ("clippy::panic_params", "non_fmt_panics"), + ("clippy::positional_named_format_parameters", "named_arguments_used_positionally"), ("clippy::temporary_cstring_as_ptr", "temporary_cstring_as_ptr"), ("clippy::unknown_clippy_lints", "unknown_lints"), ("clippy::unused_label", "unused_labels"), diff --git a/clippy_lints/src/unused_peekable.rs b/clippy_lints/src/unused_peekable.rs index cc8656435..f1cebf0f9 100644 --- a/clippy_lints/src/unused_peekable.rs +++ b/clippy_lints/src/unused_peekable.rs @@ -6,6 +6,7 @@ use rustc_hir::intravisit::{walk_expr, Visitor}; use rustc_hir::lang_items::LangItem; use rustc_hir::{Block, Expr, ExprKind, HirId, Local, Node, PatKind, PathSegment, StmtKind}; use rustc_lint::{LateContext, LateLintPass}; +use rustc_middle::hir::nested_filter::OnlyBodies; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::sym; @@ -109,8 +110,14 @@ impl<'a, 'tcx> PeekableVisitor<'a, 'tcx> { } } -impl<'tcx> Visitor<'_> for PeekableVisitor<'_, 'tcx> { - fn visit_expr(&mut self, ex: &'_ Expr<'_>) { +impl<'tcx> Visitor<'tcx> for PeekableVisitor<'_, 'tcx> { + type NestedFilter = OnlyBodies; + + fn nested_visit_map(&mut self) -> Self::Map { + self.cx.tcx.hir() + } + + fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) { if self.found_peek_call { return; } @@ -136,12 +143,11 @@ impl<'tcx> Visitor<'_> for PeekableVisitor<'_, 'tcx> { return; } - if args.iter().any(|arg| { - matches!(arg.kind, ExprKind::Path(_)) && arg_is_mut_peekable(self.cx, arg) - }) { + if args.iter().any(|arg| arg_is_mut_peekable(self.cx, arg)) { self.found_peek_call = true; - return; } + + return; }, // Catch anything taking a Peekable mutably ExprKind::MethodCall( @@ -190,21 +196,21 @@ impl<'tcx> Visitor<'_> for PeekableVisitor<'_, 'tcx> { Node::Local(Local { init: Some(init), .. }) => { if arg_is_mut_peekable(self.cx, init) { self.found_peek_call = true; - return; } - break; + return; }, - Node::Stmt(stmt) => match stmt.kind { - StmtKind::Expr(_) | StmtKind::Semi(_) => {}, - _ => { - self.found_peek_call = true; - return; - }, + Node::Stmt(stmt) => { + match stmt.kind { + StmtKind::Local(_) | StmtKind::Item(_) => self.found_peek_call = true, + StmtKind::Expr(_) | StmtKind::Semi(_) => {}, + } + + return; }, Node::Block(_) | Node::ExprField(_) => {}, _ => { - break; + return; }, } } diff --git a/clippy_lints/src/use_self.rs b/clippy_lints/src/use_self.rs index 486ea5e5c..44ab9bca7 100644 --- a/clippy_lints/src/use_self.rs +++ b/clippy_lints/src/use_self.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::ty::same_type_and_consts; -use clippy_utils::{meets_msrv, msrvs}; +use clippy_utils::{is_from_proc_macro, meets_msrv, msrvs}; use if_chain::if_chain; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; @@ -87,7 +87,7 @@ impl_lint_pass!(UseSelf => [USE_SELF]); const SEGMENTS_MSG: &str = "segments should be composed of at least 1 element"; impl<'tcx> LateLintPass<'tcx> for UseSelf { - fn check_item(&mut self, _cx: &LateContext<'_>, item: &Item<'_>) { + fn check_item(&mut self, cx: &LateContext<'tcx>, item: &Item<'tcx>) { if matches!(item.kind, ItemKind::OpaqueTy(_)) { // skip over `ItemKind::OpaqueTy` in order to lint `foo() -> impl <..>` return; @@ -103,6 +103,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { if parameters.as_ref().map_or(true, |params| { !params.parenthesized && !params.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_))) }); + if !is_from_proc_macro(cx, item); // expensive, should be last check then { StackItem::Check { impl_id: item.def_id, @@ -213,9 +214,6 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { hir_ty_to_ty(cx.tcx, hir_ty) }; if same_type_and_consts(ty, cx.tcx.type_of(impl_id)); - let hir = cx.tcx.hir(); - // prevents false positive on `#[derive(serde::Deserialize)]` - if !hir.span(hir.get_parent_node(hir_ty.hir_id)).in_derive_expansion(); then { span_lint(cx, hir_ty.span); } diff --git a/clippy_lints/src/utils/conf.rs b/clippy_lints/src/utils/conf.rs index a8500beb2..2be3fa99c 100644 --- a/clippy_lints/src/utils/conf.rs +++ b/clippy_lints/src/utils/conf.rs @@ -476,7 +476,7 @@ pub fn format_error(error: Box) -> String { let mut msg = String::from(prefix); for row in 0..rows { - write!(msg, "\n").unwrap(); + writeln!(msg).unwrap(); for (column, column_width) in column_widths.iter().copied().enumerate() { let index = column * rows + row; let field = fields.get(index).copied().unwrap_or_default(); diff --git a/clippy_lints/src/write.rs b/clippy_lints/src/write.rs index 640a09a7a..06e7d7017 100644 --- a/clippy_lints/src/write.rs +++ b/clippy_lints/src/write.rs @@ -1,20 +1,12 @@ -use std::borrow::Cow; -use std::iter; -use std::ops::{Deref, Range}; - -use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then}; -use clippy_utils::source::{snippet, snippet_opt, snippet_with_applicability}; -use rustc_ast::ast::{Expr, ExprKind, Impl, Item, ItemKind, MacCall, Path, StrLit, StrStyle}; -use rustc_ast::ptr::P; -use rustc_ast::token::{self, LitKind}; -use rustc_ast::tokenstream::TokenStream; -use rustc_errors::{Applicability, DiagnosticBuilder}; -use rustc_lexer::unescape::{self, EscapeError}; -use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; -use rustc_parse::parser; +use clippy_utils::diagnostics::{span_lint, span_lint_and_then}; +use clippy_utils::macros::{root_macro_call_first_node, FormatArgsExpn, MacroCall}; +use clippy_utils::source::snippet_opt; +use rustc_ast::LitKind; +use rustc_errors::Applicability; +use rustc_hir::{Expr, ExprKind, HirIdMap, Impl, Item, ItemKind}; +use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_session::{declare_tool_lint, impl_lint_pass}; -use rustc_span::symbol::{kw, Symbol}; -use rustc_span::{sym, BytePos, InnerSpan, Span, DUMMY_SP}; +use rustc_span::{sym, BytePos, Span}; declare_clippy_lint! { /// ### What it does @@ -74,13 +66,7 @@ declare_clippy_lint! { /// 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 + /// Only catches `print!` and `println!` calls. /// /// ### Example /// ```rust @@ -102,13 +88,7 @@ declare_clippy_lint! { /// 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 + /// Only catches `eprint!` and `eprintln!` calls. /// /// ### Example /// ```rust @@ -149,10 +129,6 @@ declare_clippy_lint! { /// (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 /// ```rust /// println!("{}", "foo"); @@ -234,10 +210,6 @@ declare_clippy_lint! { /// (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 /// ```rust /// # use std::fmt::Write; @@ -257,28 +229,6 @@ declare_clippy_lint! { "writing a literal with a format string" } -declare_clippy_lint! { - /// ### 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 - /// ```rust - /// println!("{}", x = 10); - /// ``` - /// - /// Use instead: - /// ```rust - /// println!("{x}", x = 10); - /// ``` - #[clippy::version = "1.63.0"] - pub POSITIONAL_NAMED_FORMAT_PARAMETERS, - suspicious, - "named parameter in a format string is used positionally" -} - #[derive(Default)] pub struct Write { in_debug_impl: bool, @@ -294,537 +244,308 @@ impl_lint_pass!(Write => [ WRITE_WITH_NEWLINE, WRITELN_EMPTY_STRING, WRITE_LITERAL, - POSITIONAL_NAMED_FORMAT_PARAMETERS, ]); -impl EarlyLintPass for Write { - fn check_item(&mut self, _: &EarlyContext<'_>, item: &Item) { - if let ItemKind::Impl(box Impl { - of_trait: Some(trait_ref), - .. - }) = &item.kind - { - let trait_name = trait_ref - .path - .segments - .iter() - .last() - .expect("path has at least one segment") - .ident - .name; - if trait_name == sym::Debug { - self.in_debug_impl = true; - } +impl<'tcx> LateLintPass<'tcx> for Write { + fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { + if is_debug_impl(cx, item) { + self.in_debug_impl = true; } } - fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &Item) { - self.in_debug_impl = false; + fn check_item_post(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { + if is_debug_impl(cx, item) { + self.in_debug_impl = false; + } } - fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &MacCall) { - fn is_build_script(cx: &EarlyContext<'_>) -> bool { - // Cargo sets the crate name for build scripts to `build_script_build` - cx.sess() - .opts - .crate_name - .as_ref() - .map_or(false, |crate_name| crate_name == "build_script_build") - } + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { + let Some(macro_call) = root_macro_call_first_node(cx, expr) else { return }; + let Some(diag_name) = cx.tcx.get_diagnostic_name(macro_call.def_id) else { return }; + let Some(name) = diag_name.as_str().strip_suffix("_macro") else { return }; - if mac.path == sym!(print) { - if !is_build_script(cx) { - span_lint(cx, PRINT_STDOUT, mac.span(), "use of `print!`"); - } - self.lint_print_with_newline(cx, mac); - } else if mac.path == sym!(println) { - if !is_build_script(cx) { - span_lint(cx, PRINT_STDOUT, mac.span(), "use of `println!`"); - } - self.lint_println_empty_string(cx, mac); - } else if mac.path == sym!(eprint) { - span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprint!`"); - self.lint_print_with_newline(cx, mac); - } else if mac.path == sym!(eprintln) { - span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprintln!`"); - self.lint_println_empty_string(cx, mac); - } else if mac.path == sym!(write) { - if let (Some(fmt_str), dest) = self.check_tts(cx, mac.args.inner_tokens(), true) { - if check_newlines(&fmt_str) { - let (nl_span, only_nl) = newline_span(&fmt_str); - let nl_span = match (dest, only_nl) { - // Special case of `write!(buf, "\n")`: Mark everything from the end of - // `buf` for removal so no trailing comma [`writeln!(buf, )`] remains. - (Some(dest_expr), true) => nl_span.with_lo(dest_expr.span.hi()), - _ => nl_span, - }; - span_lint_and_then( - cx, - WRITE_WITH_NEWLINE, - mac.span(), - "using `write!()` with a format string that ends in a single newline", - |err| { - err.multipart_suggestion( - "use `writeln!()` instead", - vec![(mac.path.span, String::from("writeln")), (nl_span, String::new())], - Applicability::MachineApplicable, - ); - }, - ); + let is_build_script = cx + .sess() + .opts + .crate_name + .as_ref() + .map_or(false, |crate_name| crate_name == "build_script_build"); + + match diag_name { + sym::print_macro | sym::println_macro => { + if !is_build_script { + span_lint(cx, PRINT_STDOUT, macro_call.span, &format!("use of `{name}!`")); } - } - } else if mac.path == sym!(writeln) { - if let (Some(fmt_str), expr) = self.check_tts(cx, mac.args.inner_tokens(), true) { - if fmt_str.symbol == kw::Empty { - let mut applicability = Applicability::MachineApplicable; - let suggestion = if let Some(e) = expr { - snippet_with_applicability(cx, e.span, "v", &mut applicability) - } else { - applicability = Applicability::HasPlaceholders; - Cow::Borrowed("v") - }; + }, + sym::eprint_macro | sym::eprintln_macro => { + span_lint(cx, PRINT_STDERR, macro_call.span, &format!("use of `{name}!`")); + }, + sym::write_macro | sym::writeln_macro => {}, + _ => return, + } - span_lint_and_sugg( - cx, - WRITELN_EMPTY_STRING, - mac.span(), - format!("using `writeln!({}, \"\")`", suggestion).as_str(), - "replace it with", - format!("writeln!({})", suggestion), - applicability, - ); + let Some(format_args) = FormatArgsExpn::find_nested(cx, expr, macro_call.expn) else { return }; + + // ignore `writeln!(w)` and `write!(v, some_macro!())` + if format_args.format_string.span.from_expansion() { + return; + } + + match diag_name { + sym::print_macro | sym::eprint_macro | sym::write_macro => { + check_newline(cx, &format_args, ¯o_call, name); + }, + sym::println_macro | sym::eprintln_macro | sym::writeln_macro => { + check_empty_string(cx, &format_args, ¯o_call, name); + }, + _ => {}, + } + + check_literal(cx, &format_args, name); + + if !self.in_debug_impl { + for arg in &format_args.args { + if arg.format.r#trait == sym::Debug { + span_lint(cx, USE_DEBUG, arg.span, "use of `Debug`-based formatting"); } } } } } - -/// Given a format string that ends in a newline and its span, calculates the span of the -/// newline, or the format string itself if the format string consists solely of a newline. -/// Return this and a boolean indicating whether it only consisted of a newline. -fn newline_span(fmtstr: &StrLit) -> (Span, bool) { - let sp = fmtstr.span; - let contents = fmtstr.symbol.as_str(); - - if contents == r"\n" { - return (sp, true); - } - - let newline_sp_hi = sp.hi() - - match fmtstr.style { - StrStyle::Cooked => BytePos(1), - StrStyle::Raw(hashes) => BytePos((1 + hashes).into()), - }; - - let newline_sp_len = if contents.ends_with('\n') { - BytePos(1) - } else if contents.ends_with(r"\n") { - BytePos(2) +fn is_debug_impl(cx: &LateContext<'_>, item: &Item<'_>) -> bool { + if let ItemKind::Impl(Impl { of_trait: Some(trait_ref), .. }) = &item.kind + && let Some(trait_id) = trait_ref.trait_def_id() + { + cx.tcx.is_diagnostic_item(sym::Debug, trait_id) } else { - panic!("expected format string to contain a newline"); + false + } +} + +fn check_newline(cx: &LateContext<'_>, format_args: &FormatArgsExpn<'_>, macro_call: &MacroCall, name: &str) { + let format_string_parts = &format_args.format_string.parts; + let mut format_string_span = format_args.format_string.span; + + let Some(last) = format_string_parts.last() else { return }; + + let count_vertical_whitespace = || { + format_string_parts + .iter() + .flat_map(|part| part.as_str().chars()) + .filter(|ch| matches!(ch, '\r' | '\n')) + .count() }; - (sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi), false) -} + if last.as_str().ends_with('\n') + // ignore format strings with other internal vertical whitespace + && count_vertical_whitespace() == 1 -/// Stores a list of replacement spans for each argument, but only if all the replacements used an -/// empty format string. -#[derive(Default)] -struct SimpleFormatArgs { - unnamed: Vec>, - complex_unnamed: Vec>, - named: Vec<(Symbol, Vec)>, -} -impl SimpleFormatArgs { - fn get_unnamed(&self) -> impl Iterator { - self.unnamed.iter().map(|x| match x.as_slice() { - // Ignore the dummy span added from out of order format arguments. - [DUMMY_SP] => &[], - x => x, - }) - } + // ignore trailing arguments: `print!("Issue\n{}", 1265);` + && format_string_parts.len() > format_args.args.len() + { + let lint = if name == "write" { + format_string_span = expand_past_previous_comma(cx, format_string_span); - fn get_complex_unnamed(&self) -> impl Iterator { - self.complex_unnamed.iter().map(Vec::as_slice) - } - - fn get_named(&self, n: &Path) -> &[Span] { - self.named.iter().find(|x| *n == x.0).map_or(&[], |x| x.1.as_slice()) - } - - fn push(&mut self, arg: rustc_parse_format::Argument<'_>, span: Span) { - use rustc_parse_format::{ - AlignUnknown, ArgumentImplicitlyIs, ArgumentIs, ArgumentNamed, CountImplied, FormatSpec, + WRITE_WITH_NEWLINE + } else { + PRINT_WITH_NEWLINE }; - const SIMPLE: FormatSpec<'_> = FormatSpec { - fill: None, - align: AlignUnknown, - flags: 0, - precision: CountImplied, - precision_span: None, - width: CountImplied, - width_span: None, - ty: "", - ty_span: None, - }; + span_lint_and_then( + cx, + lint, + macro_call.span, + &format!("using `{name}!()` with a format string that ends in a single newline"), + |diag| { + let name_span = cx.sess().source_map().span_until_char(macro_call.span, '!'); + let Some(format_snippet) = snippet_opt(cx, format_string_span) else { return }; - match arg.position { - ArgumentIs(n) | ArgumentImplicitlyIs(n) => { - if self.unnamed.len() <= n { - // Use a dummy span to mark all unseen arguments. - self.unnamed.resize_with(n, || vec![DUMMY_SP]); - if arg.format == SIMPLE { - self.unnamed.push(vec![span]); - } else { - self.unnamed.push(Vec::new()); - } - } else { - let args = &mut self.unnamed[n]; - match (args.as_mut_slice(), arg.format == SIMPLE) { - // A non-empty format string has been seen already. - ([], _) => (), - // Replace the dummy span, if it exists. - ([dummy @ DUMMY_SP], true) => *dummy = span, - ([_, ..], true) => args.push(span), - ([_, ..], false) => *args = Vec::new(), - } + if format_string_parts.len() == 1 && last.as_str() == "\n" { + // print!("\n"), write!(f, "\n") + + diag.multipart_suggestion( + &format!("use `{name}ln!` instead"), + vec![(name_span, format!("{name}ln")), (format_string_span, String::new())], + Applicability::MachineApplicable, + ); + } else if format_snippet.ends_with("\\n\"") { + // print!("...\n"), write!(f, "...\n") + + let hi = format_string_span.hi(); + let newline_span = format_string_span.with_lo(hi - BytePos(3)).with_hi(hi - BytePos(1)); + + diag.multipart_suggestion( + &format!("use `{name}ln!` instead"), + vec![(name_span, format!("{name}ln")), (newline_span, String::new())], + Applicability::MachineApplicable, + ); } }, - ArgumentNamed(n) => { - let n = Symbol::intern(n); - if let Some(x) = self.named.iter_mut().find(|x| x.0 == n) { - match x.1.as_slice() { - // A non-empty format string has been seen already. - [] => (), - [_, ..] if arg.format == SIMPLE => x.1.push(span), - [_, ..] => x.1 = Vec::new(), - } - } else if arg.format == SIMPLE { - self.named.push((n, vec![span])); - } else { - self.named.push((n, Vec::new())); - } - }, - }; - } - - fn push_to_complex(&mut self, span: Span, position: usize) { - if self.complex_unnamed.len() <= position { - self.complex_unnamed.resize_with(position, Vec::new); - self.complex_unnamed.push(vec![span]); - } else { - let args: &mut Vec = &mut self.complex_unnamed[position]; - args.push(span); - } - } - - fn push_complex( - &mut self, - cx: &EarlyContext<'_>, - arg: rustc_parse_format::Argument<'_>, - str_lit_span: Span, - fmt_span: Span, - ) { - use rustc_parse_format::{ArgumentImplicitlyIs, ArgumentIs, CountIsParam, CountIsStar}; - - let snippet = snippet_opt(cx, fmt_span); - - let end = snippet - .as_ref() - .and_then(|s| s.find(':')) - .or_else(|| fmt_span.hi().0.checked_sub(fmt_span.lo().0 + 1).map(|u| u as usize)); - - if let (ArgumentIs(n) | ArgumentImplicitlyIs(n), Some(end)) = (arg.position, end) { - let span = fmt_span.from_inner(InnerSpan::new(1, end)); - self.push_to_complex(span, n); - }; - - if let (CountIsParam(n) | CountIsStar(n), Some(span)) = (arg.format.precision, arg.format.precision_span) { - // We need to do this hack as precision spans should be converted from .* to .foo$ - let hack = if snippet.as_ref().and_then(|s| s.find('*')).is_some() { - 0 - } else { - 1 - }; - - let span = str_lit_span.from_inner(InnerSpan { - start: span.start + 1, - end: span.end - hack, - }); - self.push_to_complex(span, n); - }; - - if let (CountIsParam(n), Some(span)) = (arg.format.width, arg.format.width_span) { - let span = str_lit_span.from_inner(InnerSpan { - start: span.start, - end: span.end - 1, - }); - self.push_to_complex(span, n); - }; + ); } } -impl Write { - /// Parses a format string into a collection of spans for each argument. This only keeps track - /// of empty format arguments. Will also lint usages of debug format strings outside of debug - /// impls. - fn parse_fmt_string(&self, cx: &EarlyContext<'_>, str_lit: &StrLit) -> Option { - use rustc_parse_format::{ParseMode, Parser, Piece}; +fn check_empty_string(cx: &LateContext<'_>, format_args: &FormatArgsExpn<'_>, macro_call: &MacroCall, name: &str) { + if let [part] = &format_args.format_string.parts[..] + && let mut span = format_args.format_string.span + && part.as_str() == "\n" + { + let lint = if name == "writeln" { + span = expand_past_previous_comma(cx, span); - let str_sym = str_lit.symbol_unescaped.as_str(); - let style = match str_lit.style { - StrStyle::Cooked => None, - StrStyle::Raw(n) => Some(n as usize), - }; - - let mut parser = Parser::new(str_sym, style, snippet_opt(cx, str_lit.span), false, ParseMode::Format); - let mut args = SimpleFormatArgs::default(); - - while let Some(arg) = parser.next() { - let arg = match arg { - Piece::String(_) => continue, - Piece::NextArgument(arg) => arg, - }; - let span = parser - .arg_places - .last() - .map_or(DUMMY_SP, |&x| str_lit.span.from_inner(InnerSpan::new(x.start, x.end))); - - if !self.in_debug_impl && arg.format.ty == "?" { - // FIXME: modify rustc's fmt string parser to give us the current span - span_lint(cx, USE_DEBUG, span, "use of `Debug`-based formatting"); - } - args.push(arg, span); - args.push_complex(cx, arg, str_lit.span, span); - } - - parser.errors.is_empty().then_some(args) - } - - /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two - /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes - /// the contents of the string, whether it's a raw string, and the span of the literal in the - /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the - /// `format_str` should be written to. - /// - /// Example: - /// - /// Calling this function on - /// ```rust - /// # use std::fmt::Write; - /// # let mut buf = String::new(); - /// # let something = "something"; - /// writeln!(buf, "string to write: {}", something); - /// ``` - /// will return - /// ```rust,ignore - /// (Some("string to write: {}"), Some(buf)) - /// ``` - fn check_tts<'a>(&self, cx: &EarlyContext<'a>, tts: TokenStream, is_write: bool) -> (Option, Option) { - let mut parser = parser::Parser::new(&cx.sess().parse_sess, tts, false, None); - let expr = if is_write { - match parser - .parse_expr() - .map(rustc_ast::ptr::P::into_inner) - .map_err(DiagnosticBuilder::cancel) - { - // write!(e, ...) - Ok(p) if parser.eat(&token::Comma) => Some(p), - // write!(e) or error - e => return (None, e.ok()), - } + WRITELN_EMPTY_STRING } else { - None + PRINTLN_EMPTY_STRING }; - let fmtstr = match parser.parse_str_lit() { - Ok(fmtstr) => fmtstr, - Err(_) => return (None, expr), - }; - - let args = match self.parse_fmt_string(cx, &fmtstr) { - Some(args) => args, - None => return (Some(fmtstr), expr), - }; - - let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL }; - let mut unnamed_args = args.get_unnamed(); - let mut complex_unnamed_args = args.get_complex_unnamed(); - loop { - if !parser.eat(&token::Comma) { - return (Some(fmtstr), expr); - } - - let comma_span = parser.prev_token.span; - let token_expr = if let Ok(expr) = parser.parse_expr().map_err(DiagnosticBuilder::cancel) { - expr - } else { - return (Some(fmtstr), None); - }; - let complex_unnamed_arg = complex_unnamed_args.next(); - - let (fmt_spans, lit) = match &token_expr.kind { - ExprKind::Lit(lit) => (unnamed_args.next().unwrap_or(&[]), lit), - ExprKind::Assign(lhs, rhs, _) => { - if let Some(span) = complex_unnamed_arg { - for x in span { - Self::report_positional_named_param(cx, *x, lhs, rhs); - } - } - match (&lhs.kind, &rhs.kind) { - (ExprKind::Path(_, p), ExprKind::Lit(lit)) => (args.get_named(p), lit), - _ => continue, - } - }, - _ => { - unnamed_args.next(); - continue; - }, - }; - - let replacement: String = match lit.token_lit.kind { - LitKind::StrRaw(_) | LitKind::ByteStrRaw(_) if matches!(fmtstr.style, StrStyle::Raw(_)) => { - lit.token_lit.symbol.as_str().replace('{', "{{").replace('}', "}}") - }, - LitKind::Str | LitKind::ByteStr if matches!(fmtstr.style, StrStyle::Cooked) => { - lit.token_lit.symbol.as_str().replace('{', "{{").replace('}', "}}") - }, - LitKind::StrRaw(_) - | LitKind::Str - | LitKind::ByteStrRaw(_) - | LitKind::ByteStr - | LitKind::Integer - | LitKind::Float - | LitKind::Err => continue, - LitKind::Byte | LitKind::Char => match lit.token_lit.symbol.as_str() { - "\"" if matches!(fmtstr.style, StrStyle::Cooked) => "\\\"", - "\"" if matches!(fmtstr.style, StrStyle::Raw(0)) => continue, - "\\\\" if matches!(fmtstr.style, StrStyle::Raw(_)) => "\\", - "\\'" => "'", - "{" => "{{", - "}" => "}}", - x if matches!(fmtstr.style, StrStyle::Raw(_)) && x.starts_with('\\') => continue, - x => x, - } - .into(), - LitKind::Bool => lit.token_lit.symbol.as_str().deref().into(), - }; - - if !fmt_spans.is_empty() { - span_lint_and_then( - cx, - lint, - token_expr.span, - "literal with an empty format string", - |diag| { - diag.multipart_suggestion( - "try this", - iter::once((comma_span.to(token_expr.span), String::new())) - .chain(fmt_spans.iter().copied().zip(iter::repeat(replacement))) - .collect(), - Applicability::MachineApplicable, - ); - }, - ); - } - } - } - - fn report_positional_named_param(cx: &EarlyContext<'_>, span: Span, lhs: &P, _rhs: &P) { - if let ExprKind::Path(_, _p) = &lhs.kind { - let mut applicability = Applicability::MachineApplicable; - let name = snippet_with_applicability(cx, lhs.span, "name", &mut applicability); - // We need to do this hack as precision spans should be converted from .* to .foo$ - let hack = snippet(cx, span, "").contains('*'); - - span_lint_and_sugg( - cx, - POSITIONAL_NAMED_FORMAT_PARAMETERS, - span, - &format!("named parameter {} is used as a positional parameter", name), - "replace it with", - if hack { - format!("{}$", name) - } else { - format!("{}", name) - }, - applicability, - ); - }; - } - - fn lint_println_empty_string(&self, cx: &EarlyContext<'_>, mac: &MacCall) { - if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) { - if fmt_str.symbol == kw::Empty { - let name = mac.path.segments[0].ident.name; - span_lint_and_sugg( - cx, - PRINTLN_EMPTY_STRING, - mac.span(), - &format!("using `{}!(\"\")`", name), - "replace it with", - format!("{}!()", name), + span_lint_and_then( + cx, + lint, + macro_call.span, + &format!("empty string literal in `{name}!`"), + |diag| { + diag.span_suggestion( + span, + "remove the empty string", + String::new(), Applicability::MachineApplicable, ); - } - } + }, + ); + } +} + +fn check_literal(cx: &LateContext<'_>, format_args: &FormatArgsExpn<'_>, name: &str) { + let mut counts = HirIdMap::::default(); + for param in format_args.params() { + *counts.entry(param.value.hir_id).or_default() += 1; } - fn lint_print_with_newline(&self, cx: &EarlyContext<'_>, mac: &MacCall) { - if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) { - if check_newlines(&fmt_str) { - let name = mac.path.segments[0].ident.name; - let suggested = format!("{}ln", name); - span_lint_and_then( - cx, - PRINT_WITH_NEWLINE, - mac.span(), - &format!("using `{}!()` with a format string that ends in a single newline", name), - |err| { - err.multipart_suggestion( - &format!("use `{}!` instead", suggested), - vec![(mac.path.span, suggested), (newline_span(&fmt_str).0, String::new())], + for arg in &format_args.args { + let value = arg.param.value; + + if counts[&value.hir_id] == 1 + && arg.format.is_default() + && let ExprKind::Lit(lit) = &value.kind + && !value.span.from_expansion() + && let Some(value_string) = snippet_opt(cx, value.span) + { + let (replacement, replace_raw) = match lit.node { + LitKind::Str(..) => extract_str_literal(&value_string), + LitKind::Char(ch) => ( + match ch { + '"' => "\\\"", + '\'' => "'", + _ => &value_string[1..value_string.len() - 1], + } + .to_string(), + false, + ), + LitKind::Bool(b) => (b.to_string(), false), + _ => continue, + }; + + let lint = if name.starts_with("write") { + WRITE_LITERAL + } else { + PRINT_LITERAL + }; + + let format_string_is_raw = format_args.format_string.style.is_some(); + let replacement = match (format_string_is_raw, replace_raw) { + (false, false) => Some(replacement), + (false, true) => Some(replacement.replace('"', "\\\"").replace('\\', "\\\\")), + (true, false) => match conservative_unescape(&replacement) { + Ok(unescaped) => Some(unescaped), + Err(UnescapeErr::Lint) => None, + Err(UnescapeErr::Ignore) => continue, + }, + (true, true) => { + if replacement.contains(['#', '"']) { + None + } else { + Some(replacement) + } + }, + }; + + span_lint_and_then( + cx, + lint, + value.span, + "literal with an empty format string", + |diag| { + if let Some(replacement) = replacement { + // `format!("{}", "a")`, `format!("{named}", named = "b") + // ~~~~~ ~~~~~~~~~~~~~ + let value_span = expand_past_previous_comma(cx, value.span); + + let replacement = replacement.replace('{', "{{").replace('}', "}}"); + diag.multipart_suggestion( + "try this", + vec![(arg.span, replacement), (value_span, String::new())], Applicability::MachineApplicable, ); - }, - ); - } + } + }, + ); } } } -/// Checks if the format string contains a single newline that terminates it. +/// Removes the raw marker, `#`s and quotes from a str, and returns if the literal is raw /// -/// Literal and escaped newlines are both checked (only literal for raw strings). -fn check_newlines(fmtstr: &StrLit) -> bool { - let mut has_internal_newline = false; - let mut last_was_cr = false; - let mut should_lint = false; - - let contents = fmtstr.symbol.as_str(); - - let mut cb = |r: Range, c: Result| { - let c = match c { - Ok(c) => c, - Err(e) if !e.is_fatal() => return, - Err(e) => panic!("{:?}", e), - }; - - if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline { - should_lint = true; - } else { - last_was_cr = c == '\r'; - if c == '\n' { - has_internal_newline = true; - } - } +/// `r#"a"#` -> (`a`, true) +/// +/// `"b"` -> (`b`, false) +fn extract_str_literal(literal: &str) -> (String, bool) { + let (literal, raw) = match literal.strip_prefix('r') { + Some(stripped) => (stripped.trim_matches('#'), true), + None => (literal, false), }; - match fmtstr.style { - StrStyle::Cooked => unescape::unescape_literal(contents, unescape::Mode::Str, &mut cb), - StrStyle::Raw(_) => unescape::unescape_literal(contents, unescape::Mode::RawStr, &mut cb), + (literal[1..literal.len() - 1].to_string(), raw) +} + +enum UnescapeErr { + /// Should still be linted, can be manually resolved by author, e.g. + /// + /// ```ignore + /// print!(r"{}", '"'); + /// ``` + Lint, + /// Should not be linted, e.g. + /// + /// ```ignore + /// print!(r"{}", '\r'); + /// ``` + Ignore, +} + +/// Unescape a normal string into a raw string +fn conservative_unescape(literal: &str) -> Result { + let mut unescaped = String::with_capacity(literal.len()); + let mut chars = literal.chars(); + let mut err = false; + + while let Some(ch) = chars.next() { + match ch { + '#' => err = true, + '\\' => match chars.next() { + Some('\\') => unescaped.push('\\'), + Some('"') => err = true, + _ => return Err(UnescapeErr::Ignore), + }, + _ => unescaped.push(ch), + } } - should_lint + if err { Err(UnescapeErr::Lint) } else { Ok(unescaped) } +} + +// Expand from `writeln!(o, "")` to `writeln!(o, "")` +// ^^ ^^^^ +fn expand_past_previous_comma(cx: &LateContext<'_>, span: Span) -> Span { + let extended = cx.sess().source_map().span_extend_to_prev_char(span, ',', true); + extended.with_lo(extended.lo() - BytePos(1)) } diff --git a/clippy_utils/src/consts.rs b/clippy_utils/src/consts.rs index 96c55111f..1b8a9c055 100644 --- a/clippy_utils/src/consts.rs +++ b/clippy_utils/src/consts.rs @@ -501,8 +501,8 @@ impl<'a, 'tcx> ConstEvalLateContext<'a, 'tcx> { BinOpKind::Mul => l.checked_mul(r).map(zext), BinOpKind::Div if r != 0 => l.checked_div(r).map(zext), BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext), - BinOpKind::Shr => l.checked_shr(r.try_into().expect("invalid shift")).map(zext), - BinOpKind::Shl => l.checked_shl(r.try_into().expect("invalid shift")).map(zext), + BinOpKind::Shr => l.checked_shr(r.try_into().ok()?).map(zext), + BinOpKind::Shl => l.checked_shl(r.try_into().ok()?).map(zext), BinOpKind::BitXor => Some(zext(l ^ r)), BinOpKind::BitOr => Some(zext(l | r)), BinOpKind::BitAnd => Some(zext(l & r)), @@ -521,8 +521,8 @@ impl<'a, 'tcx> ConstEvalLateContext<'a, 'tcx> { BinOpKind::Mul => l.checked_mul(r).map(Constant::Int), BinOpKind::Div => l.checked_div(r).map(Constant::Int), BinOpKind::Rem => l.checked_rem(r).map(Constant::Int), - BinOpKind::Shr => l.checked_shr(r.try_into().expect("shift too large")).map(Constant::Int), - BinOpKind::Shl => l.checked_shl(r.try_into().expect("shift too large")).map(Constant::Int), + BinOpKind::Shr => l.checked_shr(r.try_into().ok()?).map(Constant::Int), + BinOpKind::Shl => l.checked_shl(r.try_into().ok()?).map(Constant::Int), BinOpKind::BitXor => Some(Constant::Int(l ^ r)), BinOpKind::BitOr => Some(Constant::Int(l | r)), BinOpKind::BitAnd => Some(Constant::Int(l & r)), diff --git a/clippy_utils/src/macros.rs b/clippy_utils/src/macros.rs index bd89ff977..a1808c097 100644 --- a/clippy_utils/src/macros.rs +++ b/clippy_utils/src/macros.rs @@ -7,8 +7,8 @@ use crate::visitors::expr_visitor_no_bodies; use arrayvec::ArrayVec; use itertools::{izip, Either, Itertools}; use rustc_ast::ast::LitKind; -use rustc_hir::intravisit::Visitor; -use rustc_hir::{self as hir, Expr, ExprKind, HirId, Node, QPath}; +use rustc_hir::intravisit::{walk_expr, Visitor}; +use rustc_hir::{self as hir, Expr, ExprField, ExprKind, HirId, Node, QPath}; use rustc_lexer::unescape::unescape_literal; use rustc_lexer::{tokenize, unescape, LiteralKind, TokenKind}; use rustc_lint::LateContext; @@ -485,64 +485,49 @@ struct ParamPosition { precision: Option, } -/// Parses the `fmt` arg of `Arguments::new_v1_formatted(pieces, args, fmt, _)` -fn parse_rt_fmt<'tcx>(fmt_arg: &'tcx Expr<'tcx>) -> Option + 'tcx> { - fn parse_count(expr: &Expr<'_>) -> Option { - // ::core::fmt::rt::v1::Count::Param(1usize), - if let ExprKind::Call(ctor, [val]) = expr.kind - && let ExprKind::Path(QPath::Resolved(_, path)) = ctor.kind - && path.segments.last()?.ident.name == sym::Param - && let ExprKind::Lit(lit) = &val.kind - && let LitKind::Int(pos, _) = lit.node - { - Some(pos as usize) - } else { - None +impl<'tcx> Visitor<'tcx> for ParamPosition { + fn visit_expr_field(&mut self, field: &'tcx ExprField<'tcx>) { + fn parse_count(expr: &Expr<'_>) -> Option { + // ::core::fmt::rt::v1::Count::Param(1usize), + if let ExprKind::Call(ctor, [val]) = expr.kind + && let ExprKind::Path(QPath::Resolved(_, path)) = ctor.kind + && path.segments.last()?.ident.name == sym::Param + && let ExprKind::Lit(lit) = &val.kind + && let LitKind::Int(pos, _) = lit.node + { + Some(pos as usize) + } else { + None + } + } + + match field.ident.name { + sym::position => { + if let ExprKind::Lit(lit) = &field.expr.kind + && let LitKind::Int(pos, _) = lit.node + { + self.value = pos as usize; + } + }, + sym::precision => { + self.precision = parse_count(field.expr); + }, + sym::width => { + self.width = parse_count(field.expr); + }, + _ => walk_expr(self, field.expr), } } +} +/// Parses the `fmt` arg of `Arguments::new_v1_formatted(pieces, args, fmt, _)` +fn parse_rt_fmt<'tcx>(fmt_arg: &'tcx Expr<'tcx>) -> Option + 'tcx> { if let ExprKind::AddrOf(.., array) = fmt_arg.kind && let ExprKind::Array(specs) = array.kind { Some(specs.iter().map(|spec| { let mut position = ParamPosition::default(); - - // ::core::fmt::rt::v1::Argument { - // position: 0usize, - // format: ::core::fmt::rt::v1::FormatSpec { - // .. - // precision: ::core::fmt::rt::v1::Count::Implied, - // width: ::core::fmt::rt::v1::Count::Implied, - // }, - // } - - // TODO: this can be made much nicer next sync with `Visitor::visit_expr_field` - if let ExprKind::Struct(_, fields, _) = spec.kind { - for field in fields { - match (field.ident.name, &field.expr.kind) { - (sym::position, ExprKind::Lit(lit)) => { - if let LitKind::Int(pos, _) = lit.node { - position.value = pos as usize; - } - }, - (sym::format, &ExprKind::Struct(_, spec_fields, _)) => { - for spec_field in spec_fields { - match spec_field.ident.name { - sym::precision => { - position.precision = parse_count(spec_field.expr); - }, - sym::width => { - position.width = parse_count(spec_field.expr); - }, - _ => {}, - } - } - }, - _ => {}, - } - } - } - + position.visit_expr(spec); position })) } else { @@ -711,9 +696,14 @@ impl<'tcx> FormatSpec<'tcx> { }) } - /// Returns true if this format spec would change the contents of a string when formatted - pub fn has_string_formatting(&self) -> bool { - self.r#trait != sym::Display || !self.width.is_implied() || !self.precision.is_implied() + /// Returns true if this format spec is unchanged from the default. e.g. returns true for `{}`, + /// `{foo}` and `{2}`, but false for `{:?}`, `{foo:5}` and `{3:.5}` + pub fn is_default(&self) -> bool { + self.r#trait == sym::Display + && self.width.is_implied() + && self.precision.is_implied() + && self.align == Alignment::AlignUnknown + && self.flags == 0 } } diff --git a/clippy_utils/src/sugg.rs b/clippy_utils/src/sugg.rs index cca71bbf7..f08275a4a 100644 --- a/clippy_utils/src/sugg.rs +++ b/clippy_utils/src/sugg.rs @@ -22,7 +22,7 @@ use std::fmt::{Display, Write as _}; use std::ops::{Add, Neg, Not, Sub}; /// A helper type to build suggestion correctly handling parentheses. -#[derive(Clone, PartialEq)] +#[derive(Clone, Debug, PartialEq)] pub enum Sugg<'a> { /// An expression that never needs parentheses such as `1337` or `[0; 42]`. NonParen(Cow<'a, str>), @@ -155,8 +155,8 @@ impl<'a> Sugg<'a> { | hir::ExprKind::Ret(..) | hir::ExprKind::Struct(..) | hir::ExprKind::Tup(..) - | hir::ExprKind::DropTemps(_) | hir::ExprKind::Err => Sugg::NonParen(get_snippet(expr.span)), + hir::ExprKind::DropTemps(inner) => Self::hir_from_snippet(inner, get_snippet), hir::ExprKind::Assign(lhs, rhs, _) => { Sugg::BinOp(AssocOp::Assign, get_snippet(lhs.span), get_snippet(rhs.span)) }, @@ -177,11 +177,11 @@ impl<'a> Sugg<'a> { pub fn ast(cx: &EarlyContext<'_>, expr: &ast::Expr, default: &'a str) -> Self { use rustc_ast::ast::RangeLimits; - let get_whole_snippet = || { - if expr.span.from_expansion() { - snippet_with_macro_callsite(cx, expr.span, default) + let snippet_without_expansion = |cx, span: Span, default| { + if span.from_expansion() { + snippet_with_macro_callsite(cx, span, default) } else { - snippet(cx, expr.span, default) + snippet(cx, span, default) } }; @@ -192,7 +192,7 @@ impl<'a> Sugg<'a> { | ast::ExprKind::If(..) | ast::ExprKind::Let(..) | ast::ExprKind::Unary(..) - | ast::ExprKind::Match(..) => Sugg::MaybeParen(get_whole_snippet()), + | ast::ExprKind::Match(..) => Sugg::MaybeParen(snippet_without_expansion(cx, expr.span, default)), ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Break(..) @@ -221,41 +221,45 @@ impl<'a> Sugg<'a> { | ast::ExprKind::Array(..) | ast::ExprKind::While(..) | ast::ExprKind::Await(..) - | ast::ExprKind::Err => Sugg::NonParen(get_whole_snippet()), + | ast::ExprKind::Err => Sugg::NonParen(snippet_without_expansion(cx, expr.span, default)), ast::ExprKind::Range(ref lhs, ref rhs, RangeLimits::HalfOpen) => Sugg::BinOp( AssocOp::DotDot, - lhs.as_ref().map_or("".into(), |lhs| snippet(cx, lhs.span, default)), - rhs.as_ref().map_or("".into(), |rhs| snippet(cx, rhs.span, default)), + lhs.as_ref() + .map_or("".into(), |lhs| snippet_without_expansion(cx, lhs.span, default)), + rhs.as_ref() + .map_or("".into(), |rhs| snippet_without_expansion(cx, rhs.span, default)), ), ast::ExprKind::Range(ref lhs, ref rhs, RangeLimits::Closed) => Sugg::BinOp( AssocOp::DotDotEq, - lhs.as_ref().map_or("".into(), |lhs| snippet(cx, lhs.span, default)), - rhs.as_ref().map_or("".into(), |rhs| snippet(cx, rhs.span, default)), + lhs.as_ref() + .map_or("".into(), |lhs| snippet_without_expansion(cx, lhs.span, default)), + rhs.as_ref() + .map_or("".into(), |rhs| snippet_without_expansion(cx, rhs.span, default)), ), ast::ExprKind::Assign(ref lhs, ref rhs, _) => Sugg::BinOp( AssocOp::Assign, - snippet(cx, lhs.span, default), - snippet(cx, rhs.span, default), + snippet_without_expansion(cx, lhs.span, default), + snippet_without_expansion(cx, rhs.span, default), ), ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => Sugg::BinOp( astbinop2assignop(op), - snippet(cx, lhs.span, default), - snippet(cx, rhs.span, default), + snippet_without_expansion(cx, lhs.span, default), + snippet_without_expansion(cx, rhs.span, default), ), ast::ExprKind::Binary(op, ref lhs, ref rhs) => Sugg::BinOp( AssocOp::from_ast_binop(op.node), - snippet(cx, lhs.span, default), - snippet(cx, rhs.span, default), + snippet_without_expansion(cx, lhs.span, default), + snippet_without_expansion(cx, rhs.span, default), ), ast::ExprKind::Cast(ref lhs, ref ty) => Sugg::BinOp( AssocOp::As, - snippet(cx, lhs.span, default), - snippet(cx, ty.span, default), + snippet_without_expansion(cx, lhs.span, default), + snippet_without_expansion(cx, ty.span, default), ), ast::ExprKind::Type(ref lhs, ref ty) => Sugg::BinOp( AssocOp::Colon, - snippet(cx, lhs.span, default), - snippet(cx, ty.span, default), + snippet_without_expansion(cx, lhs.span, default), + snippet_without_expansion(cx, ty.span, default), ), } } diff --git a/clippy_utils/src/ty.rs b/clippy_utils/src/ty.rs index 926ecf965..563438803 100644 --- a/clippy_utils/src/ty.rs +++ b/clippy_utils/src/ty.rs @@ -31,6 +31,13 @@ pub fn is_copy<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { ty.is_copy_modulo_regions(cx.tcx.at(DUMMY_SP), cx.param_env) } +/// This checks whether a given type is known to implement Debug. +pub fn has_debug_impl<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { + cx.tcx + .get_diagnostic_item(sym::Debug) + .map_or(false, |debug| implements_trait(cx, ty, debug, &[])) +} + /// Checks whether a type can be partially moved. pub fn can_partially_move_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { if has_drop(cx, ty) || is_copy(cx, ty) { diff --git a/src/docs.rs b/src/docs.rs index f3a5048e7..6c89b4dde 100644 --- a/src/docs.rs +++ b/src/docs.rs @@ -221,6 +221,7 @@ docs! { "items_after_statements", "iter_cloned_collect", "iter_count", + "iter_kv_map", "iter_next_loop", "iter_next_slice", "iter_not_returning_iterator", @@ -391,7 +392,6 @@ docs! { "partialeq_to_none", "path_buf_push_overwrite", "pattern_type_mismatch", - "positional_named_format_parameters", "possible_missing_comma", "precedence", "print_in_format_impl", diff --git a/src/docs/iter_kv_map.txt b/src/docs/iter_kv_map.txt new file mode 100644 index 000000000..a063c8195 --- /dev/null +++ b/src/docs/iter_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 we only need the keys or the values. + +### Example + +``` +let map: HashMap = HashMap::new(); +let values = map.iter().map(|(_, value)| value).collect::>(); +``` + +Use instead: +``` +let map: HashMap = HashMap::new(); +let values = map.values().collect::>(); +``` \ No newline at end of file diff --git a/src/docs/positional_named_format_parameters.txt b/src/docs/positional_named_format_parameters.txt deleted file mode 100644 index e391d2406..000000000 --- a/src/docs/positional_named_format_parameters.txt +++ /dev/null @@ -1,15 +0,0 @@ -### 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/print_literal.txt b/src/docs/print_literal.txt index 160073414..a6252a687 100644 --- a/src/docs/print_literal.txt +++ b/src/docs/print_literal.txt @@ -6,10 +6,6 @@ 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"); diff --git a/src/docs/print_stderr.txt b/src/docs/print_stderr.txt index fc14511cd..9c6edeeef 100644 --- a/src/docs/print_stderr.txt +++ b/src/docs/print_stderr.txt @@ -7,13 +7,7 @@ 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 +Only catches `eprint!` and `eprintln!` calls. ### Example ``` diff --git a/src/docs/print_stdout.txt b/src/docs/print_stdout.txt index 6c9a4b98e..d2cbd811d 100644 --- a/src/docs/print_stdout.txt +++ b/src/docs/print_stdout.txt @@ -7,13 +7,7 @@ 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 +Only catches `print!` and `println!` calls. ### Example ``` diff --git a/src/docs/write_literal.txt b/src/docs/write_literal.txt index 9c41a48f9..a7a884d08 100644 --- a/src/docs/write_literal.txt +++ b/src/docs/write_literal.txt @@ -6,10 +6,6 @@ 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"); diff --git a/tests/ui-cargo/module_style/fail_mod_remap/Cargo.toml b/tests/ui-cargo/module_style/fail_mod_remap/Cargo.toml new file mode 100644 index 000000000..a822fad38 --- /dev/null +++ b/tests/ui-cargo/module_style/fail_mod_remap/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "fail-mod-remap" +version = "0.1.0" +edition = "2018" +publish = false + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/tests/ui-cargo/module_style/fail_mod_remap/src/bad.rs b/tests/ui-cargo/module_style/fail_mod_remap/src/bad.rs new file mode 100644 index 000000000..509aad186 --- /dev/null +++ b/tests/ui-cargo/module_style/fail_mod_remap/src/bad.rs @@ -0,0 +1 @@ +pub mod inner; diff --git a/tests/ui-cargo/module_style/fail_mod_remap/src/bad/inner.rs b/tests/ui-cargo/module_style/fail_mod_remap/src/bad/inner.rs new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/tests/ui-cargo/module_style/fail_mod_remap/src/bad/inner.rs @@ -0,0 +1 @@ + diff --git a/tests/ui-cargo/module_style/fail_mod_remap/src/main.rs b/tests/ui-cargo/module_style/fail_mod_remap/src/main.rs new file mode 100644 index 000000000..ba4c8c873 --- /dev/null +++ b/tests/ui-cargo/module_style/fail_mod_remap/src/main.rs @@ -0,0 +1,7 @@ +// compile-flags: --remap-path-prefix {{src-base}}=/remapped + +#![warn(clippy::self_named_module_files)] + +mod bad; + +fn main() {} diff --git a/tests/ui-cargo/module_style/fail_mod_remap/src/main.stderr b/tests/ui-cargo/module_style/fail_mod_remap/src/main.stderr new file mode 100644 index 000000000..46991ff66 --- /dev/null +++ b/tests/ui-cargo/module_style/fail_mod_remap/src/main.stderr @@ -0,0 +1,11 @@ +error: `mod.rs` files are required, found `bad.rs` + --> /remapped/module_style/fail_mod_remap/src/bad.rs:1:1 + | +LL | pub mod inner; + | ^ + | + = note: `-D clippy::self-named-module-files` implied by `-D warnings` + = help: move `bad.rs` to `bad/mod.rs` + +error: aborting due to previous error + diff --git a/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs b/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs index 5b4adc868..ed8161acc 100644 --- a/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs +++ b/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.rs @@ -42,6 +42,7 @@ macro_rules! printlnfoo { fn main() { let _ = vec! {1, 2, 3}; let _ = format!["ugh {} stop being such a good compiler", "hello"]; + let _ = matches!{{}, ()}; let _ = quote!(let x = 1;); let _ = quote::quote!(match match match); let _ = test!(); // trigger when macro def is inside our own crate diff --git a/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.stderr b/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.stderr index 039b23b1b..d80ad49f3 100644 --- a/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.stderr +++ b/tests/ui-toml/nonstandard_macro_braces/conf_nonstandard_macro_braces.stderr @@ -23,26 +23,38 @@ help: consider writing `format!("ugh () stop being such a good compiler", "hello LL | let _ = format!["ugh {} stop being such a good compiler", "hello"]; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: use of irregular braces for `quote!` macro +error: use of irregular braces for `matches!` macro --> $DIR/conf_nonstandard_macro_braces.rs:45:13 | +LL | let _ = matches!{{}, ()}; + | ^^^^^^^^^^^^^^^^ + | +help: consider writing `matches!((), ())` + --> $DIR/conf_nonstandard_macro_braces.rs:45:13 + | +LL | let _ = matches!{{}, ()}; + | ^^^^^^^^^^^^^^^^ + +error: use of irregular braces for `quote!` macro + --> $DIR/conf_nonstandard_macro_braces.rs:46:13 + | LL | let _ = quote!(let x = 1;); | ^^^^^^^^^^^^^^^^^^ | help: consider writing `quote! {let x = 1;}` - --> $DIR/conf_nonstandard_macro_braces.rs:45:13 + --> $DIR/conf_nonstandard_macro_braces.rs:46:13 | LL | let _ = quote!(let x = 1;); | ^^^^^^^^^^^^^^^^^^ error: use of irregular braces for `quote::quote!` macro - --> $DIR/conf_nonstandard_macro_braces.rs:46:13 + --> $DIR/conf_nonstandard_macro_braces.rs:47:13 | LL | let _ = quote::quote!(match match match); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: consider writing `quote::quote! {match match match}` - --> $DIR/conf_nonstandard_macro_braces.rs:46:13 + --> $DIR/conf_nonstandard_macro_braces.rs:47:13 | LL | let _ = quote::quote!(match match match); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -67,28 +79,28 @@ LL | let _ = test!(); // trigger when macro def is inside our own crate = note: this error originates in the macro `test` (in Nightly builds, run with -Z macro-backtrace for more info) error: use of irregular braces for `type_pos!` macro - --> $DIR/conf_nonstandard_macro_braces.rs:55:12 + --> $DIR/conf_nonstandard_macro_braces.rs:56:12 | LL | let _: type_pos!(usize) = vec![]; | ^^^^^^^^^^^^^^^^ | help: consider writing `type_pos![usize]` - --> $DIR/conf_nonstandard_macro_braces.rs:55:12 + --> $DIR/conf_nonstandard_macro_braces.rs:56:12 | LL | let _: type_pos!(usize) = vec![]; | ^^^^^^^^^^^^^^^^ error: use of irregular braces for `eprint!` macro - --> $DIR/conf_nonstandard_macro_braces.rs:57:5 + --> $DIR/conf_nonstandard_macro_braces.rs:58:5 | LL | eprint!("test if user config overrides defaults"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: consider writing `eprint!["test if user config overrides defaults"]` - --> $DIR/conf_nonstandard_macro_braces.rs:57:5 + --> $DIR/conf_nonstandard_macro_braces.rs:58:5 | LL | eprint!("test if user config overrides defaults"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 7 previous errors +error: aborting due to 8 previous errors diff --git a/tests/ui/almost_complete_letter_range.fixed b/tests/ui/almost_complete_letter_range.fixed index e69b40f35..079b7c000 100644 --- a/tests/ui/almost_complete_letter_range.fixed +++ b/tests/ui/almost_complete_letter_range.fixed @@ -1,5 +1,6 @@ // run-rustfix // edition:2018 +// aux-build:macro_rules.rs #![feature(custom_inner_attributes)] #![feature(exclusive_range_pattern)] @@ -8,12 +9,21 @@ #![allow(ellipsis_inclusive_range_patterns)] #![allow(clippy::needless_parens_on_range_literals)] +#[macro_use] +extern crate macro_rules; + macro_rules! a { () => { 'a' }; } +macro_rules! b { + () => { + let _ = 'a'..='z'; + }; +} + fn main() { #[rustfmt::skip] { @@ -47,6 +57,9 @@ fn main() { 'B'..'Z' => 4, _ => 5, }; + + almost_complete_letter_range!(); + b!(); } fn _under_msrv() { diff --git a/tests/ui/almost_complete_letter_range.rs b/tests/ui/almost_complete_letter_range.rs index f2240981d..a66900a97 100644 --- a/tests/ui/almost_complete_letter_range.rs +++ b/tests/ui/almost_complete_letter_range.rs @@ -1,5 +1,6 @@ // run-rustfix // edition:2018 +// aux-build:macro_rules.rs #![feature(custom_inner_attributes)] #![feature(exclusive_range_pattern)] @@ -8,12 +9,21 @@ #![allow(ellipsis_inclusive_range_patterns)] #![allow(clippy::needless_parens_on_range_literals)] +#[macro_use] +extern crate macro_rules; + macro_rules! a { () => { 'a' }; } +macro_rules! b { + () => { + let _ = 'a'..'z'; + }; +} + fn main() { #[rustfmt::skip] { @@ -47,6 +57,9 @@ fn main() { 'B'..'Z' => 4, _ => 5, }; + + almost_complete_letter_range!(); + b!(); } fn _under_msrv() { diff --git a/tests/ui/almost_complete_letter_range.stderr b/tests/ui/almost_complete_letter_range.stderr index 5b5dc40ee..3de44c72c 100644 --- a/tests/ui/almost_complete_letter_range.stderr +++ b/tests/ui/almost_complete_letter_range.stderr @@ -1,5 +1,5 @@ error: almost complete ascii letter range - --> $DIR/almost_complete_letter_range.rs:20:17 + --> $DIR/almost_complete_letter_range.rs:30:17 | LL | let _ = ('a') ..'z'; | ^^^^^^--^^^ @@ -9,7 +9,7 @@ LL | let _ = ('a') ..'z'; = note: `-D clippy::almost-complete-letter-range` implied by `-D warnings` error: almost complete ascii letter range - --> $DIR/almost_complete_letter_range.rs:21:17 + --> $DIR/almost_complete_letter_range.rs:31:17 | LL | let _ = 'A' .. ('Z'); | ^^^^--^^^^^^ @@ -17,7 +17,7 @@ LL | let _ = 'A' .. ('Z'); | help: use an inclusive range: `..=` error: almost complete ascii letter range - --> $DIR/almost_complete_letter_range.rs:27:13 + --> $DIR/almost_complete_letter_range.rs:37:13 | LL | let _ = (b'a')..(b'z'); | ^^^^^^--^^^^^^ @@ -25,7 +25,7 @@ LL | let _ = (b'a')..(b'z'); | help: use an inclusive range: `..=` error: almost complete ascii letter range - --> $DIR/almost_complete_letter_range.rs:28:13 + --> $DIR/almost_complete_letter_range.rs:38:13 | LL | let _ = b'A'..b'Z'; | ^^^^--^^^^ @@ -33,7 +33,7 @@ LL | let _ = b'A'..b'Z'; | help: use an inclusive range: `..=` error: almost complete ascii letter range - --> $DIR/almost_complete_letter_range.rs:33:13 + --> $DIR/almost_complete_letter_range.rs:43:13 | LL | let _ = a!()..'z'; | ^^^^--^^^ @@ -41,7 +41,7 @@ LL | let _ = a!()..'z'; | help: use an inclusive range: `..=` error: almost complete ascii letter range - --> $DIR/almost_complete_letter_range.rs:36:9 + --> $DIR/almost_complete_letter_range.rs:46:9 | LL | b'a'..b'z' if true => 1, | ^^^^--^^^^ @@ -49,7 +49,7 @@ LL | b'a'..b'z' if true => 1, | help: use an inclusive range: `..=` error: almost complete ascii letter range - --> $DIR/almost_complete_letter_range.rs:37:9 + --> $DIR/almost_complete_letter_range.rs:47:9 | LL | b'A'..b'Z' if true => 2, | ^^^^--^^^^ @@ -57,7 +57,7 @@ LL | b'A'..b'Z' if true => 2, | help: use an inclusive range: `..=` error: almost complete ascii letter range - --> $DIR/almost_complete_letter_range.rs:44:9 + --> $DIR/almost_complete_letter_range.rs:54:9 | LL | 'a'..'z' if true => 1, | ^^^--^^^ @@ -65,7 +65,7 @@ LL | 'a'..'z' if true => 1, | help: use an inclusive range: `..=` error: almost complete ascii letter range - --> $DIR/almost_complete_letter_range.rs:45:9 + --> $DIR/almost_complete_letter_range.rs:55:9 | LL | 'A'..'Z' if true => 2, | ^^^--^^^ @@ -73,7 +73,20 @@ LL | 'A'..'Z' if true => 2, | help: use an inclusive range: `..=` error: almost complete ascii letter range - --> $DIR/almost_complete_letter_range.rs:55:9 + --> $DIR/almost_complete_letter_range.rs:23:17 + | +LL | let _ = 'a'..'z'; + | ^^^--^^^ + | | + | help: use an inclusive range: `..=` +... +LL | b!(); + | ---- in this macro invocation + | + = note: this error originates in the macro `b` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: almost complete ascii letter range + --> $DIR/almost_complete_letter_range.rs:68:9 | LL | 'a'..'z' => 1, | ^^^--^^^ @@ -81,7 +94,7 @@ LL | 'a'..'z' => 1, | help: use an inclusive range: `...` error: almost complete ascii letter range - --> $DIR/almost_complete_letter_range.rs:62:13 + --> $DIR/almost_complete_letter_range.rs:75:13 | LL | let _ = 'a'..'z'; | ^^^--^^^ @@ -89,12 +102,12 @@ LL | let _ = 'a'..'z'; | help: use an inclusive range: `..=` error: almost complete ascii letter range - --> $DIR/almost_complete_letter_range.rs:64:9 + --> $DIR/almost_complete_letter_range.rs:77:9 | LL | 'a'..'z' => 1, | ^^^--^^^ | | | help: use an inclusive range: `..=` -error: aborting due to 12 previous errors +error: aborting due to 13 previous errors diff --git a/tests/ui/arithmetic_side_effects.rs b/tests/ui/arithmetic_side_effects.rs index f5390c746..dd24f5aa5 100644 --- a/tests/ui/arithmetic_side_effects.rs +++ b/tests/ui/arithmetic_side_effects.rs @@ -1,9 +1,49 @@ -#![allow(clippy::assign_op_pattern, clippy::unnecessary_owned_empty_strings)] +#![allow( + clippy::assign_op_pattern, + clippy::erasing_op, + clippy::identity_op, + clippy::unnecessary_owned_empty_strings, + arithmetic_overflow, + unconditional_panic +)] #![feature(inline_const, saturating_int_impl)] #![warn(clippy::arithmetic_side_effects)] use core::num::{Saturating, Wrapping}; +pub fn association_with_structures_should_not_trigger_the_lint() { + enum Foo { + Bar = -2, + } + + impl Trait for Foo { + const ASSOC: i32 = { + let _: [i32; 1 + 1]; + fn foo() {} + 1 + 1 + }; + } + + struct Baz([i32; 1 + 1]); + + trait Trait { + const ASSOC: i32 = 1 + 1; + } + + type Alias = [i32; 1 + 1]; + + union Qux { + field: [i32; 1 + 1], + } + + let _: [i32; 1 + 1] = [0, 0]; + + let _: [i32; 1 + 1] = { + let a: [i32; 1 + 1] = [0, 0]; + a + }; +} + pub fn hard_coded_allowed() { let _ = 1f32 + 1f32; let _ = 1f64 + 1f64; @@ -26,7 +66,7 @@ pub fn hard_coded_allowed() { } #[rustfmt::skip] -pub fn non_overflowing_ops() { +pub fn const_ops_should_not_trigger_the_lint() { const _: i32 = { let mut n = 1; n += 1; n }; let _ = const { let mut n = 1; n += 1; n }; @@ -37,21 +77,63 @@ pub fn non_overflowing_ops() { let _ = const { let mut n = 1; n = 1 + n; n }; const _: i32 = 1 + 1; - let _ = 1 + 1; let _ = const { 1 + 1 }; - let mut _a = 1; - _a *= 1; - _a /= 1; + const _: i32 = { let mut n = -1; n = -(-1); n = -n; n }; + let _ = const { let mut n = -1; n = -(-1); n = -n; n }; } -#[rustfmt::skip] -pub fn overflowing_ops() { - let mut _a = 1; _a += 1; +pub fn non_overflowing_runtime_ops_or_ops_already_handled_by_the_compiler() { + let mut _n = i32::MAX; - let mut _b = 1; _b = _b + 1; + // Assign + _n += 0; + _n -= 0; + _n /= 99; + _n %= 99; + _n *= 0; + _n *= 1; - let mut _c = 1; _c = 1 + _c; + // Binary + _n = _n + 0; + _n = 0 + _n; + _n = _n - 0; + _n = 0 - _n; + _n = _n / 99; + _n = _n % 99; + _n = _n * 0; + _n = 0 * _n; + _n = _n * 1; + _n = 1 * _n; + _n = 23 + 85; + + // Unary + _n = -1; + _n = -(-1); +} + +pub fn overflowing_runtime_ops() { + let mut _n = i32::MAX; + + // Assign + _n += 1; + _n -= 1; + _n /= 0; + _n %= 0; + _n *= 2; + + // Binary + _n = _n + 1; + _n = 1 + _n; + _n = _n - 1; + _n = 1 - _n; + _n = _n / 0; + _n = _n % 0; + _n = _n * 2; + _n = 2 * _n; + + // Unary + _n = -_n; } fn main() {} diff --git a/tests/ui/arithmetic_side_effects.stderr b/tests/ui/arithmetic_side_effects.stderr index 6c4c8bdec..a2a856efb 100644 --- a/tests/ui/arithmetic_side_effects.stderr +++ b/tests/ui/arithmetic_side_effects.stderr @@ -1,22 +1,88 @@ -error: arithmetic detected - --> $DIR/arithmetic_side_effects.rs:50:21 +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:119:5 | -LL | let mut _a = 1; _a += 1; - | ^^^^^^^ +LL | _n += 1; + | ^^^^^^^ | = note: `-D clippy::arithmetic-side-effects` implied by `-D warnings` -error: arithmetic detected - --> $DIR/arithmetic_side_effects.rs:52:26 +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:120:5 | -LL | let mut _b = 1; _b = _b + 1; - | ^^^^^^ +LL | _n -= 1; + | ^^^^^^^ -error: arithmetic detected - --> $DIR/arithmetic_side_effects.rs:54:26 +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:121:5 | -LL | let mut _c = 1; _c = 1 + _c; - | ^^^^^^ +LL | _n /= 0; + | ^^^^^^^ -error: aborting due to 3 previous errors +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:122:5 + | +LL | _n %= 0; + | ^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:123:5 + | +LL | _n *= 2; + | ^^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:126:10 + | +LL | _n = _n + 1; + | ^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:127:10 + | +LL | _n = 1 + _n; + | ^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:128:10 + | +LL | _n = _n - 1; + | ^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:129:10 + | +LL | _n = 1 - _n; + | ^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:130:10 + | +LL | _n = _n / 0; + | ^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:131:10 + | +LL | _n = _n % 0; + | ^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:132:10 + | +LL | _n = _n * 2; + | ^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:133:10 + | +LL | _n = 2 * _n; + | ^^^^^^ + +error: arithmetic operation that can potentially result in unexpected side-effects + --> $DIR/arithmetic_side_effects.rs:136:10 + | +LL | _n = -_n; + | ^^^ + +error: aborting due to 14 previous errors diff --git a/tests/ui/assertions_on_result_states.fixed b/tests/ui/assertions_on_result_states.fixed index 795f435f2..2bb755290 100644 --- a/tests/ui/assertions_on_result_states.fixed +++ b/tests/ui/assertions_on_result_states.fixed @@ -75,3 +75,9 @@ fn main() { let r: Result = Err(Foo); assert!(r.is_err()); } + +#[allow(dead_code)] +fn issue9450() { + let res: Result = Ok(1); + res.unwrap_err(); +} diff --git a/tests/ui/assertions_on_result_states.rs b/tests/ui/assertions_on_result_states.rs index 1101aec1e..d8a9bd2f1 100644 --- a/tests/ui/assertions_on_result_states.rs +++ b/tests/ui/assertions_on_result_states.rs @@ -75,3 +75,9 @@ fn main() { let r: Result = Err(Foo); assert!(r.is_err()); } + +#[allow(dead_code)] +fn issue9450() { + let res: Result = Ok(1); + assert!(res.is_err()) +} diff --git a/tests/ui/assertions_on_result_states.stderr b/tests/ui/assertions_on_result_states.stderr index 97a5f3dfc..298d63c9c 100644 --- a/tests/ui/assertions_on_result_states.stderr +++ b/tests/ui/assertions_on_result_states.stderr @@ -36,5 +36,11 @@ error: called `assert!` with `Result::is_err` LL | assert!(r.is_err()); | ^^^^^^^^^^^^^^^^^^^ help: replace with: `r.unwrap_err()` -error: aborting due to 6 previous errors +error: called `assert!` with `Result::is_err` + --> $DIR/assertions_on_result_states.rs:82:5 + | +LL | assert!(res.is_err()) + | ^^^^^^^^^^^^^^^^^^^^^ help: replace with: `res.unwrap_err();` + +error: aborting due to 7 previous errors diff --git a/tests/ui/auxiliary/macro_rules.rs b/tests/ui/auxiliary/macro_rules.rs index 83a0af6b8..ef3ca9aea 100644 --- a/tests/ui/auxiliary/macro_rules.rs +++ b/tests/ui/auxiliary/macro_rules.rs @@ -140,3 +140,10 @@ macro_rules! manual_rem_euclid { macro_rules! equatable_if_let { ($a:ident) => {{ if let 2 = $a {} }}; } + +#[macro_export] +macro_rules! almost_complete_letter_range { + () => { + let _ = 'a'..'z'; + }; +} diff --git a/tests/ui/bool_to_int_with_if.fixed b/tests/ui/bool_to_int_with_if.fixed index 9c1098dc4..2c8339cdd 100644 --- a/tests/ui/bool_to_int_with_if.fixed +++ b/tests/ui/bool_to_int_with_if.fixed @@ -14,6 +14,7 @@ fn main() { // precedence i32::from(a); i32::from(!a); + i32::from(!a); i32::from(a || b); i32::from(cond(a, b)); i32::from(x + y < 4); @@ -21,7 +22,12 @@ fn main() { // if else if if a { 123 - } else {i32::from(b)}; + } else { i32::from(b) }; + + // if else if inverted + if a { + 123 + } else { i32::from(!b) }; // Shouldn't lint diff --git a/tests/ui/bool_to_int_with_if.rs b/tests/ui/bool_to_int_with_if.rs index 0c967dac6..5d9496f01 100644 --- a/tests/ui/bool_to_int_with_if.rs +++ b/tests/ui/bool_to_int_with_if.rs @@ -17,6 +17,11 @@ fn main() { } else { 0 }; + if a { + 0 + } else { + 1 + }; if !a { 1 } else { @@ -47,6 +52,15 @@ fn main() { 0 }; + // if else if inverted + if a { + 123 + } else if b { + 0 + } else { + 1 + }; + // Shouldn't lint if a { diff --git a/tests/ui/bool_to_int_with_if.stderr b/tests/ui/bool_to_int_with_if.stderr index 8647a9cff..e695440f6 100644 --- a/tests/ui/bool_to_int_with_if.stderr +++ b/tests/ui/bool_to_int_with_if.stderr @@ -14,6 +14,18 @@ LL | | }; error: boolean to int conversion using if --> $DIR/bool_to_int_with_if.rs:20:5 | +LL | / if a { +LL | | 0 +LL | | } else { +LL | | 1 +LL | | }; + | |_____^ help: replace with from: `i32::from(!a)` + | + = note: `!a as i32` or `(!a).into()` can also be valid options + +error: boolean to int conversion using if + --> $DIR/bool_to_int_with_if.rs:25:5 + | LL | / if !a { LL | | 1 LL | | } else { @@ -21,10 +33,10 @@ LL | | 0 LL | | }; | |_____^ help: replace with from: `i32::from(!a)` | - = note: `!a as i32` or `!a.into()` can also be valid options + = note: `!a as i32` or `(!a).into()` can also be valid options error: boolean to int conversion using if - --> $DIR/bool_to_int_with_if.rs:25:5 + --> $DIR/bool_to_int_with_if.rs:30:5 | LL | / if a || b { LL | | 1 @@ -36,7 +48,7 @@ LL | | }; = note: `(a || b) as i32` or `(a || b).into()` can also be valid options error: boolean to int conversion using if - --> $DIR/bool_to_int_with_if.rs:30:5 + --> $DIR/bool_to_int_with_if.rs:35:5 | LL | / if cond(a, b) { LL | | 1 @@ -48,7 +60,7 @@ LL | | }; = note: `cond(a, b) as i32` or `cond(a, b).into()` can also be valid options error: boolean to int conversion using if - --> $DIR/bool_to_int_with_if.rs:35:5 + --> $DIR/bool_to_int_with_if.rs:40:5 | LL | / if x + y < 4 { LL | | 1 @@ -60,7 +72,7 @@ LL | | }; = note: `(x + y < 4) as i32` or `(x + y < 4).into()` can also be valid options error: boolean to int conversion using if - --> $DIR/bool_to_int_with_if.rs:44:12 + --> $DIR/bool_to_int_with_if.rs:49:12 | LL | } else if b { | ____________^ @@ -68,17 +80,30 @@ LL | | 1 LL | | } else { LL | | 0 LL | | }; - | |_____^ help: replace with from: `{i32::from(b)}` + | |_____^ help: replace with from: `{ i32::from(b) }` | = note: `b as i32` or `b.into()` can also be valid options error: boolean to int conversion using if - --> $DIR/bool_to_int_with_if.rs:102:5 + --> $DIR/bool_to_int_with_if.rs:58:12 + | +LL | } else if b { + | ____________^ +LL | | 0 +LL | | } else { +LL | | 1 +LL | | }; + | |_____^ help: replace with from: `{ i32::from(!b) }` + | + = note: `!b as i32` or `(!b).into()` can also be valid options + +error: boolean to int conversion using if + --> $DIR/bool_to_int_with_if.rs:116:5 | LL | if a { 1 } else { 0 } | ^^^^^^^^^^^^^^^^^^^^^ help: replace with from: `u8::from(a)` | = note: `a as u8` or `a.into()` can also be valid options -error: aborting due to 7 previous errors +error: aborting due to 9 previous errors diff --git a/tests/ui/collapsible_if.fixed b/tests/ui/collapsible_if.fixed index 5b0e4a473..6bb7682ba 100644 --- a/tests/ui/collapsible_if.fixed +++ b/tests/ui/collapsible_if.fixed @@ -139,6 +139,9 @@ fn main() { // Fix #5962 if matches!(true, true) && matches!(true, true) {} + // Issue #9375 + if matches!(true, true) && truth() && matches!(true, true) {} + if true { #[cfg(not(teehee))] if true { diff --git a/tests/ui/collapsible_if.rs b/tests/ui/collapsible_if.rs index cd231a5d7..e216a9ee5 100644 --- a/tests/ui/collapsible_if.rs +++ b/tests/ui/collapsible_if.rs @@ -155,6 +155,11 @@ fn main() { if matches!(true, true) {} } + // Issue #9375 + if matches!(true, true) && truth() { + if matches!(true, true) {} + } + if true { #[cfg(not(teehee))] if true { diff --git a/tests/ui/collapsible_if.stderr b/tests/ui/collapsible_if.stderr index 674961238..6327444df 100644 --- a/tests/ui/collapsible_if.stderr +++ b/tests/ui/collapsible_if.stderr @@ -126,5 +126,13 @@ LL | | if matches!(true, true) {} LL | | } | |_____^ help: collapse nested if block: `if matches!(true, true) && matches!(true, true) {}` -error: aborting due to 8 previous errors +error: this `if` statement can be collapsed + --> $DIR/collapsible_if.rs:159:5 + | +LL | / if matches!(true, true) && truth() { +LL | | if matches!(true, true) {} +LL | | } + | |_____^ help: collapse nested if block: `if matches!(true, true) && truth() && matches!(true, true) {}` + +error: aborting due to 9 previous errors diff --git a/tests/ui/crashes/ice-9463.rs b/tests/ui/crashes/ice-9463.rs new file mode 100644 index 000000000..41ef930d3 --- /dev/null +++ b/tests/ui/crashes/ice-9463.rs @@ -0,0 +1,5 @@ +#![deny(arithmetic_overflow, const_err)] +fn main() { + let _x = -1_i32 >> -1; + let _y = 1u32 >> 10000000000000u32; +} diff --git a/tests/ui/crashes/ice-9463.stderr b/tests/ui/crashes/ice-9463.stderr new file mode 100644 index 000000000..7daa08aeb --- /dev/null +++ b/tests/ui/crashes/ice-9463.stderr @@ -0,0 +1,29 @@ +error: this arithmetic operation will overflow + --> $DIR/ice-9463.rs:3:14 + | +LL | let _x = -1_i32 >> -1; + | ^^^^^^^^^^^^ attempt to shift right by `-1_i32`, which would overflow + | +note: the lint level is defined here + --> $DIR/ice-9463.rs:1:9 + | +LL | #![deny(arithmetic_overflow, const_err)] + | ^^^^^^^^^^^^^^^^^^^ + +error: this arithmetic operation will overflow + --> $DIR/ice-9463.rs:4:14 + | +LL | let _y = 1u32 >> 10000000000000u32; + | ^^^^^^^^^^^^^^^^^^^^^^^^^ attempt to shift right by `1316134912_u32`, which would overflow + +error: literal out of range for `u32` + --> $DIR/ice-9463.rs:4:22 + | +LL | let _y = 1u32 >> 10000000000000u32; + | ^^^^^^^^^^^^^^^^^ + | + = note: `#[deny(overflowing_literals)]` on by default + = note: the literal `10000000000000u32` does not fit into the type `u32` whose range is `0..=4294967295` + +error: aborting due to 3 previous errors + diff --git a/tests/ui/derivable_impls.fixed b/tests/ui/derivable_impls.fixed new file mode 100644 index 000000000..7dcdfb093 --- /dev/null +++ b/tests/ui/derivable_impls.fixed @@ -0,0 +1,213 @@ +// run-rustfix + +#![allow(dead_code)] + +use std::collections::HashMap; + +#[derive(Default)] +struct FooDefault<'a> { + a: bool, + b: i32, + c: u64, + d: Vec, + e: FooND1, + f: FooND2, + g: HashMap, + h: (i32, Vec), + i: [Vec; 3], + j: [i32; 5], + k: Option, + l: &'a [i32], +} + + + +#[derive(Default)] +struct TupleDefault(bool, i32, u64); + + + +struct FooND1 { + a: bool, +} + +impl std::default::Default for FooND1 { + fn default() -> Self { + Self { a: true } + } +} + +struct FooND2 { + a: i32, +} + +impl std::default::Default for FooND2 { + fn default() -> Self { + Self { a: 5 } + } +} + +struct FooNDNew { + a: bool, +} + +impl FooNDNew { + fn new() -> Self { + Self { a: true } + } +} + +impl Default for FooNDNew { + fn default() -> Self { + Self::new() + } +} + +struct FooNDVec(Vec); + +impl Default for FooNDVec { + fn default() -> Self { + Self(vec![5, 12]) + } +} + +#[derive(Default)] +struct StrDefault<'a>(&'a str); + + + +#[derive(Default)] +struct AlreadyDerived(i32, bool); + +macro_rules! mac { + () => { + 0 + }; + ($e:expr) => { + struct X(u32); + impl Default for X { + fn default() -> Self { + Self($e) + } + } + }; +} + +mac!(0); + +#[derive(Default)] +struct Y(u32); + + +struct RustIssue26925 { + a: Option, +} + +// We should watch out for cases where a manual impl is needed because a +// derive adds different type bounds (https://github.com/rust-lang/rust/issues/26925). +// For example, a struct with Option does not require T: Default, but a derive adds +// that type bound anyways. So until #26925 get fixed we should disable lint +// for the following case +impl Default for RustIssue26925 { + fn default() -> Self { + Self { a: None } + } +} + +struct SpecializedImpl { + a: A, + b: B, +} + +impl Default for SpecializedImpl { + fn default() -> Self { + Self { + a: T::default(), + b: T::default(), + } + } +} + +#[derive(Default)] +struct WithoutSelfCurly { + a: bool, +} + + + +#[derive(Default)] +struct WithoutSelfParan(bool); + + + +// https://github.com/rust-lang/rust-clippy/issues/7655 + +pub struct SpecializedImpl2 { + v: Vec, +} + +impl Default for SpecializedImpl2 { + fn default() -> Self { + Self { v: Vec::new() } + } +} + +// https://github.com/rust-lang/rust-clippy/issues/7654 + +pub struct Color { + pub r: u8, + pub g: u8, + pub b: u8, +} + +/// `#000000` +impl Default for Color { + fn default() -> Self { + Color { r: 0, g: 0, b: 0 } + } +} + +pub struct Color2 { + pub r: u8, + pub g: u8, + pub b: u8, +} + +impl Default for Color2 { + /// `#000000` + fn default() -> Self { + Self { r: 0, g: 0, b: 0 } + } +} + +#[derive(Default)] +pub struct RepeatDefault1 { + a: [i8; 32], +} + + + +pub struct RepeatDefault2 { + a: [i8; 33], +} + +impl Default for RepeatDefault2 { + fn default() -> Self { + RepeatDefault2 { a: [0; 33] } + } +} + +// https://github.com/rust-lang/rust-clippy/issues/7753 + +pub enum IntOrString { + Int(i32), + String(String), +} + +impl Default for IntOrString { + fn default() -> Self { + IntOrString::Int(0) + } +} + +fn main() {} diff --git a/tests/ui/derivable_impls.rs b/tests/ui/derivable_impls.rs index a64120047..625cbcdde 100644 --- a/tests/ui/derivable_impls.rs +++ b/tests/ui/derivable_impls.rs @@ -1,3 +1,7 @@ +// run-rustfix + +#![allow(dead_code)] + use std::collections::HashMap; struct FooDefault<'a> { diff --git a/tests/ui/derivable_impls.stderr b/tests/ui/derivable_impls.stderr index 49fb471a2..c1db5a58b 100644 --- a/tests/ui/derivable_impls.stderr +++ b/tests/ui/derivable_impls.stderr @@ -1,5 +1,5 @@ error: this `impl` can be derived - --> $DIR/derivable_impls.rs:18:1 + --> $DIR/derivable_impls.rs:22:1 | LL | / impl std::default::Default for FooDefault<'_> { LL | | fn default() -> Self { @@ -11,10 +11,14 @@ LL | | } | |_^ | = note: `-D clippy::derivable-impls` implied by `-D warnings` - = help: try annotating `FooDefault` with `#[derive(Default)]` + = help: remove the manual implementation... +help: ...and instead derive it + | +LL | #[derive(Default)] + | error: this `impl` can be derived - --> $DIR/derivable_impls.rs:39:1 + --> $DIR/derivable_impls.rs:43:1 | LL | / impl std::default::Default for TupleDefault { LL | | fn default() -> Self { @@ -23,10 +27,14 @@ LL | | } LL | | } | |_^ | - = help: try annotating `TupleDefault` with `#[derive(Default)]` + = help: remove the manual implementation... +help: ...and instead derive it + | +LL | #[derive(Default)] + | error: this `impl` can be derived - --> $DIR/derivable_impls.rs:91:1 + --> $DIR/derivable_impls.rs:95:1 | LL | / impl Default for StrDefault<'_> { LL | | fn default() -> Self { @@ -35,10 +43,14 @@ LL | | } LL | | } | |_^ | - = help: try annotating `StrDefault` with `#[derive(Default)]` + = help: remove the manual implementation... +help: ...and instead derive it + | +LL | #[derive(Default)] + | error: this `impl` can be derived - --> $DIR/derivable_impls.rs:117:1 + --> $DIR/derivable_impls.rs:121:1 | LL | / impl Default for Y { LL | | fn default() -> Self { @@ -47,10 +59,14 @@ LL | | } LL | | } | |_^ | - = help: try annotating `Y` with `#[derive(Default)]` + = help: remove the manual implementation... +help: ...and instead derive it + | +LL | #[derive(Default)] + | error: this `impl` can be derived - --> $DIR/derivable_impls.rs:156:1 + --> $DIR/derivable_impls.rs:160:1 | LL | / impl Default for WithoutSelfCurly { LL | | fn default() -> Self { @@ -59,10 +75,14 @@ LL | | } LL | | } | |_^ | - = help: try annotating `WithoutSelfCurly` with `#[derive(Default)]` + = help: remove the manual implementation... +help: ...and instead derive it + | +LL | #[derive(Default)] + | error: this `impl` can be derived - --> $DIR/derivable_impls.rs:164:1 + --> $DIR/derivable_impls.rs:168:1 | LL | / impl Default for WithoutSelfParan { LL | | fn default() -> Self { @@ -71,10 +91,14 @@ LL | | } LL | | } | |_^ | - = help: try annotating `WithoutSelfParan` with `#[derive(Default)]` + = help: remove the manual implementation... +help: ...and instead derive it + | +LL | #[derive(Default)] + | error: this `impl` can be derived - --> $DIR/derivable_impls.rs:214:1 + --> $DIR/derivable_impls.rs:218:1 | LL | / impl Default for RepeatDefault1 { LL | | fn default() -> Self { @@ -83,7 +107,11 @@ LL | | } LL | | } | |_^ | - = help: try annotating `RepeatDefault1` with `#[derive(Default)]` + = help: remove the manual implementation... +help: ...and instead derive it + | +LL | #[derive(Default)] + | error: aborting due to 7 previous errors diff --git a/tests/ui/eprint_with_newline.rs b/tests/ui/eprint_with_newline.rs index 8df32649a..de5e121be 100644 --- a/tests/ui/eprint_with_newline.rs +++ b/tests/ui/eprint_with_newline.rs @@ -45,5 +45,13 @@ fn main() { eprint!("\r\n"); eprint!("foo\r\n"); eprint!("\\r\n"); //~ ERROR - eprint!("foo\rbar\n") // ~ ERROR + eprint!("foo\rbar\n"); + + // Ignore expanded format strings + macro_rules! newline { + () => { + "\n" + }; + } + eprint!(newline!()); } diff --git a/tests/ui/eprint_with_newline.stderr b/tests/ui/eprint_with_newline.stderr index f137787bf..0eefb9f0c 100644 --- a/tests/ui/eprint_with_newline.stderr +++ b/tests/ui/eprint_with_newline.stderr @@ -83,7 +83,7 @@ LL | | ); help: use `eprintln!` instead | LL ~ eprintln!( -LL ~ "" +LL ~ | error: using `eprint!()` with a format string that ends in a single newline @@ -98,7 +98,7 @@ LL | | ); help: use `eprintln!` instead | LL ~ eprintln!( -LL ~ r"" +LL ~ | error: using `eprint!()` with a format string that ends in a single newline @@ -113,17 +113,5 @@ LL - eprint!("/r/n"); //~ ERROR LL + eprintln!("/r"); //~ ERROR | -error: using `eprint!()` with a format string that ends in a single newline - --> $DIR/eprint_with_newline.rs:48:5 - | -LL | eprint!("foo/rbar/n") // ~ ERROR - | ^^^^^^^^^^^^^^^^^^^^^ - | -help: use `eprintln!` instead - | -LL - eprint!("foo/rbar/n") // ~ ERROR -LL + eprintln!("foo/rbar") // ~ ERROR - | - -error: aborting due to 10 previous errors +error: aborting due to 9 previous errors diff --git a/tests/ui/explicit_write.fixed b/tests/ui/explicit_write.fixed index 74d0e5290..352837256 100644 --- a/tests/ui/explicit_write.fixed +++ b/tests/ui/explicit_write.fixed @@ -36,6 +36,8 @@ fn main() { eprintln!("with {} {}", 2, value); eprintln!("with {value}"); eprintln!("macro arg {}", one!()); + let width = 2; + eprintln!("{:w$}", value, w = width); } // these should not warn, different destination { diff --git a/tests/ui/explicit_write.rs b/tests/ui/explicit_write.rs index e7a698d3e..be864a55b 100644 --- a/tests/ui/explicit_write.rs +++ b/tests/ui/explicit_write.rs @@ -36,6 +36,8 @@ fn main() { writeln!(std::io::stderr(), "with {} {}", 2, value).unwrap(); writeln!(std::io::stderr(), "with {value}").unwrap(); writeln!(std::io::stderr(), "macro arg {}", one!()).unwrap(); + let width = 2; + writeln!(std::io::stderr(), "{:w$}", value, w = width).unwrap(); } // these should not warn, different destination { diff --git a/tests/ui/explicit_write.stderr b/tests/ui/explicit_write.stderr index 29ae0cdec..ff05f4343 100644 --- a/tests/ui/explicit_write.stderr +++ b/tests/ui/explicit_write.stderr @@ -72,5 +72,11 @@ error: use of `writeln!(stderr(), ...).unwrap()` LL | writeln!(std::io::stderr(), "macro arg {}", one!()).unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `eprintln!("macro arg {}", one!())` -error: aborting due to 12 previous errors +error: use of `writeln!(stderr(), ...).unwrap()` + --> $DIR/explicit_write.rs:40:9 + | +LL | writeln!(std::io::stderr(), "{:w$}", value, w = width).unwrap(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `eprintln!("{:w$}", value, w = width)` + +error: aborting due to 13 previous errors diff --git a/tests/ui/format.fixed b/tests/ui/format.fixed index b56d6aec5..e0c5f6927 100644 --- a/tests/ui/format.fixed +++ b/tests/ui/format.fixed @@ -28,8 +28,6 @@ fn main() { format!("{:?}", "foo"); // Don't warn about `Debug`. format!("{:8}", "foo"); format!("{:width$}", "foo", width = 8); - "foo".to_string(); // Warn when the format makes no difference. - "foo".to_string(); // Warn when the format makes no difference. format!("foo {}", "bar"); format!("{} bar", "foo"); @@ -38,8 +36,6 @@ fn main() { format!("{:?}", arg); // Don't warn about debug. format!("{:8}", arg); format!("{:width$}", arg, width = 8); - arg.to_string(); // Warn when the format makes no difference. - arg.to_string(); // Warn when the format makes no difference. format!("foo {}", arg); format!("{} bar", arg); diff --git a/tests/ui/format.rs b/tests/ui/format.rs index 4c1a3a840..ff83cd64b 100644 --- a/tests/ui/format.rs +++ b/tests/ui/format.rs @@ -30,8 +30,6 @@ fn main() { format!("{:?}", "foo"); // Don't warn about `Debug`. format!("{:8}", "foo"); format!("{:width$}", "foo", width = 8); - format!("{:+}", "foo"); // Warn when the format makes no difference. - format!("{:<}", "foo"); // Warn when the format makes no difference. format!("foo {}", "bar"); format!("{} bar", "foo"); @@ -40,8 +38,6 @@ fn main() { format!("{:?}", arg); // Don't warn about debug. format!("{:8}", arg); format!("{:width$}", arg, width = 8); - format!("{:+}", arg); // Warn when the format makes no difference. - format!("{:<}", arg); // Warn when the format makes no difference. format!("foo {}", arg); format!("{} bar", arg); diff --git a/tests/ui/format.stderr b/tests/ui/format.stderr index 6c35caeb0..0ef0ac655 100644 --- a/tests/ui/format.stderr +++ b/tests/ui/format.stderr @@ -46,82 +46,58 @@ LL | format!("{}", "foo"); | ^^^^^^^^^^^^^^^^^^^^ help: consider using `.to_string()`: `"foo".to_string()` error: useless use of `format!` - --> $DIR/format.rs:33:5 - | -LL | format!("{:+}", "foo"); // Warn when the format makes no difference. - | ^^^^^^^^^^^^^^^^^^^^^^ help: consider using `.to_string()`: `"foo".to_string()` - -error: useless use of `format!` - --> $DIR/format.rs:34:5 - | -LL | format!("{:<}", "foo"); // Warn when the format makes no difference. - | ^^^^^^^^^^^^^^^^^^^^^^ help: consider using `.to_string()`: `"foo".to_string()` - -error: useless use of `format!` - --> $DIR/format.rs:39:5 + --> $DIR/format.rs:37:5 | LL | format!("{}", arg); | ^^^^^^^^^^^^^^^^^^ help: consider using `.to_string()`: `arg.to_string()` error: useless use of `format!` - --> $DIR/format.rs:43:5 - | -LL | format!("{:+}", arg); // Warn when the format makes no difference. - | ^^^^^^^^^^^^^^^^^^^^ help: consider using `.to_string()`: `arg.to_string()` - -error: useless use of `format!` - --> $DIR/format.rs:44:5 - | -LL | format!("{:<}", arg); // Warn when the format makes no difference. - | ^^^^^^^^^^^^^^^^^^^^ help: consider using `.to_string()`: `arg.to_string()` - -error: useless use of `format!` - --> $DIR/format.rs:71:5 + --> $DIR/format.rs:67:5 | LL | format!("{}", 42.to_string()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using `.to_string()`: `42.to_string()` error: useless use of `format!` - --> $DIR/format.rs:73:5 + --> $DIR/format.rs:69:5 | LL | format!("{}", x.display().to_string()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using `.to_string()`: `x.display().to_string()` error: useless use of `format!` - --> $DIR/format.rs:77:18 + --> $DIR/format.rs:73:18 | LL | let _ = Some(format!("{}", a + "bar")); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using `.to_string()`: `a + "bar"` error: useless use of `format!` - --> $DIR/format.rs:81:22 + --> $DIR/format.rs:77:22 | LL | let _s: String = format!("{}", &*v.join("/n")); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using `.to_string()`: `(&*v.join("/n")).to_string()` error: useless use of `format!` - --> $DIR/format.rs:87:13 + --> $DIR/format.rs:83:13 | LL | let _ = format!("{x}"); | ^^^^^^^^^^^^^^ help: consider using `.to_string()`: `x.to_string()` error: useless use of `format!` - --> $DIR/format.rs:89:13 + --> $DIR/format.rs:85:13 | LL | let _ = format!("{y}", y = x); | ^^^^^^^^^^^^^^^^^^^^^ help: consider using `.to_string()`: `x.to_string()` error: useless use of `format!` - --> $DIR/format.rs:93:13 + --> $DIR/format.rs:89:13 | LL | let _ = format!("{abc}"); | ^^^^^^^^^^^^^^^^ help: consider using `.to_string()`: `abc.to_string()` error: useless use of `format!` - --> $DIR/format.rs:95:13 + --> $DIR/format.rs:91:13 | LL | let _ = format!("{xx}"); | ^^^^^^^^^^^^^^^ help: consider using `.to_string()`: `xx.to_string()` -error: aborting due to 19 previous errors +error: aborting due to 15 previous errors diff --git a/tests/ui/iter_kv_map.fixed b/tests/ui/iter_kv_map.fixed new file mode 100644 index 000000000..83fee0408 --- /dev/null +++ b/tests/ui/iter_kv_map.fixed @@ -0,0 +1,64 @@ +// run-rustfix + +#![warn(clippy::iter_kv_map)] +#![allow(clippy::redundant_clone)] +#![allow(clippy::suspicious_map)] +#![allow(clippy::map_identity)] + +use std::collections::{BTreeMap, HashMap}; + +fn main() { + let get_key = |(key, _val)| key; + + let map: HashMap = HashMap::new(); + + let _ = map.keys().collect::>(); + let _ = map.values().collect::>(); + let _ = map.values().map(|v| v + 2).collect::>(); + + let _ = map.clone().into_keys().collect::>(); + let _ = map.clone().into_keys().map(|key| key + 2).collect::>(); + + let _ = map.clone().into_values().collect::>(); + let _ = map.clone().into_values().map(|val| val + 2).collect::>(); + + let _ = map.clone().values().collect::>(); + let _ = map.keys().filter(|x| *x % 2 == 0).count(); + + // Don't lint + let _ = map.iter().filter(|(_, val)| *val % 2 == 0).map(|(key, _)| key).count(); + let _ = map.iter().map(get_key).collect::>(); + + // Linting the following could be an improvement to the lint + // map.iter().filter_map(|(_, val)| (val % 2 == 0).then(val * 17)).count(); + + // Lint + let _ = map.keys().map(|key| key * 9).count(); + let _ = map.values().map(|value| value * 17).count(); + + let map: BTreeMap = BTreeMap::new(); + + let _ = map.keys().collect::>(); + let _ = map.values().collect::>(); + let _ = map.values().map(|v| v + 2).collect::>(); + + let _ = map.clone().into_keys().collect::>(); + let _ = map.clone().into_keys().map(|key| key + 2).collect::>(); + + let _ = map.clone().into_values().collect::>(); + let _ = map.clone().into_values().map(|val| val + 2).collect::>(); + + let _ = map.clone().values().collect::>(); + let _ = map.keys().filter(|x| *x % 2 == 0).count(); + + // Don't lint + let _ = map.iter().filter(|(_, val)| *val % 2 == 0).map(|(key, _)| key).count(); + let _ = map.iter().map(get_key).collect::>(); + + // Linting the following could be an improvement to the lint + // map.iter().filter_map(|(_, val)| (val % 2 == 0).then(val * 17)).count(); + + // Lint + let _ = map.keys().map(|key| key * 9).count(); + let _ = map.values().map(|value| value * 17).count(); +} diff --git a/tests/ui/iter_kv_map.rs b/tests/ui/iter_kv_map.rs new file mode 100644 index 000000000..7a1f1fb01 --- /dev/null +++ b/tests/ui/iter_kv_map.rs @@ -0,0 +1,64 @@ +// run-rustfix + +#![warn(clippy::iter_kv_map)] +#![allow(clippy::redundant_clone)] +#![allow(clippy::suspicious_map)] +#![allow(clippy::map_identity)] + +use std::collections::{BTreeMap, HashMap}; + +fn main() { + let get_key = |(key, _val)| key; + + let map: HashMap = HashMap::new(); + + let _ = map.iter().map(|(key, _)| key).collect::>(); + let _ = map.iter().map(|(_, value)| value).collect::>(); + let _ = map.iter().map(|(_, v)| v + 2).collect::>(); + + let _ = map.clone().into_iter().map(|(key, _)| key).collect::>(); + let _ = map.clone().into_iter().map(|(key, _)| key + 2).collect::>(); + + let _ = map.clone().into_iter().map(|(_, val)| val).collect::>(); + let _ = map.clone().into_iter().map(|(_, val)| val + 2).collect::>(); + + let _ = map.clone().iter().map(|(_, val)| val).collect::>(); + let _ = map.iter().map(|(key, _)| key).filter(|x| *x % 2 == 0).count(); + + // Don't lint + let _ = map.iter().filter(|(_, val)| *val % 2 == 0).map(|(key, _)| key).count(); + let _ = map.iter().map(get_key).collect::>(); + + // Linting the following could be an improvement to the lint + // map.iter().filter_map(|(_, val)| (val % 2 == 0).then(val * 17)).count(); + + // Lint + let _ = map.iter().map(|(key, _value)| key * 9).count(); + let _ = map.iter().map(|(_key, value)| value * 17).count(); + + let map: BTreeMap = BTreeMap::new(); + + let _ = map.iter().map(|(key, _)| key).collect::>(); + let _ = map.iter().map(|(_, value)| value).collect::>(); + let _ = map.iter().map(|(_, v)| v + 2).collect::>(); + + let _ = map.clone().into_iter().map(|(key, _)| key).collect::>(); + let _ = map.clone().into_iter().map(|(key, _)| key + 2).collect::>(); + + let _ = map.clone().into_iter().map(|(_, val)| val).collect::>(); + let _ = map.clone().into_iter().map(|(_, val)| val + 2).collect::>(); + + let _ = map.clone().iter().map(|(_, val)| val).collect::>(); + let _ = map.iter().map(|(key, _)| key).filter(|x| *x % 2 == 0).count(); + + // Don't lint + let _ = map.iter().filter(|(_, val)| *val % 2 == 0).map(|(key, _)| key).count(); + let _ = map.iter().map(get_key).collect::>(); + + // Linting the following could be an improvement to the lint + // map.iter().filter_map(|(_, val)| (val % 2 == 0).then(val * 17)).count(); + + // Lint + let _ = map.iter().map(|(key, _value)| key * 9).count(); + let _ = map.iter().map(|(_key, value)| value * 17).count(); +} diff --git a/tests/ui/iter_kv_map.stderr b/tests/ui/iter_kv_map.stderr new file mode 100644 index 000000000..9b9b04c97 --- /dev/null +++ b/tests/ui/iter_kv_map.stderr @@ -0,0 +1,136 @@ +error: iterating on a map's keys + --> $DIR/iter_kv_map.rs:15:13 + | +LL | let _ = map.iter().map(|(key, _)| key).collect::>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.keys()` + | + = note: `-D clippy::iter-kv-map` implied by `-D warnings` + +error: iterating on a map's values + --> $DIR/iter_kv_map.rs:16:13 + | +LL | let _ = map.iter().map(|(_, value)| value).collect::>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.values()` + +error: iterating on a map's values + --> $DIR/iter_kv_map.rs:17:13 + | +LL | let _ = map.iter().map(|(_, v)| v + 2).collect::>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.values().map(|v| v + 2)` + +error: iterating on a map's keys + --> $DIR/iter_kv_map.rs:19:13 + | +LL | let _ = map.clone().into_iter().map(|(key, _)| key).collect::>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_keys()` + +error: iterating on a map's keys + --> $DIR/iter_kv_map.rs:20:13 + | +LL | let _ = map.clone().into_iter().map(|(key, _)| key + 2).collect::>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_keys().map(|key| key + 2)` + +error: iterating on a map's values + --> $DIR/iter_kv_map.rs:22:13 + | +LL | let _ = map.clone().into_iter().map(|(_, val)| val).collect::>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_values()` + +error: iterating on a map's values + --> $DIR/iter_kv_map.rs:23:13 + | +LL | let _ = map.clone().into_iter().map(|(_, val)| val + 2).collect::>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_values().map(|val| val + 2)` + +error: iterating on a map's values + --> $DIR/iter_kv_map.rs:25:13 + | +LL | let _ = map.clone().iter().map(|(_, val)| val).collect::>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().values()` + +error: iterating on a map's keys + --> $DIR/iter_kv_map.rs:26:13 + | +LL | let _ = map.iter().map(|(key, _)| key).filter(|x| *x % 2 == 0).count(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.keys()` + +error: iterating on a map's keys + --> $DIR/iter_kv_map.rs:36:13 + | +LL | let _ = map.iter().map(|(key, _value)| key * 9).count(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.keys().map(|key| key * 9)` + +error: iterating on a map's values + --> $DIR/iter_kv_map.rs:37:13 + | +LL | let _ = map.iter().map(|(_key, value)| value * 17).count(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.values().map(|value| value * 17)` + +error: iterating on a map's keys + --> $DIR/iter_kv_map.rs:41:13 + | +LL | let _ = map.iter().map(|(key, _)| key).collect::>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.keys()` + +error: iterating on a map's values + --> $DIR/iter_kv_map.rs:42:13 + | +LL | let _ = map.iter().map(|(_, value)| value).collect::>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.values()` + +error: iterating on a map's values + --> $DIR/iter_kv_map.rs:43:13 + | +LL | let _ = map.iter().map(|(_, v)| v + 2).collect::>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.values().map(|v| v + 2)` + +error: iterating on a map's keys + --> $DIR/iter_kv_map.rs:45:13 + | +LL | let _ = map.clone().into_iter().map(|(key, _)| key).collect::>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_keys()` + +error: iterating on a map's keys + --> $DIR/iter_kv_map.rs:46:13 + | +LL | let _ = map.clone().into_iter().map(|(key, _)| key + 2).collect::>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_keys().map(|key| key + 2)` + +error: iterating on a map's values + --> $DIR/iter_kv_map.rs:48:13 + | +LL | let _ = map.clone().into_iter().map(|(_, val)| val).collect::>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_values()` + +error: iterating on a map's values + --> $DIR/iter_kv_map.rs:49:13 + | +LL | let _ = map.clone().into_iter().map(|(_, val)| val + 2).collect::>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().into_values().map(|val| val + 2)` + +error: iterating on a map's values + --> $DIR/iter_kv_map.rs:51:13 + | +LL | let _ = map.clone().iter().map(|(_, val)| val).collect::>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.clone().values()` + +error: iterating on a map's keys + --> $DIR/iter_kv_map.rs:52:13 + | +LL | let _ = map.iter().map(|(key, _)| key).filter(|x| *x % 2 == 0).count(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.keys()` + +error: iterating on a map's keys + --> $DIR/iter_kv_map.rs:62:13 + | +LL | let _ = map.iter().map(|(key, _value)| key * 9).count(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.keys().map(|key| key * 9)` + +error: iterating on a map's values + --> $DIR/iter_kv_map.rs:63:13 + | +LL | let _ = map.iter().map(|(_key, value)| value * 17).count(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map.values().map(|value| value * 17)` + +error: aborting due to 22 previous errors + diff --git a/tests/ui/large_enum_variant.rs b/tests/ui/large_enum_variant.rs index 717009e4c..3b96f09d7 100644 --- a/tests/ui/large_enum_variant.rs +++ b/tests/ui/large_enum_variant.rs @@ -101,12 +101,12 @@ struct Struct2 { #[derive(Copy, Clone)] enum CopyableLargeEnum { A(bool), - B([u128; 4000]), + B([u64; 8000]), } enum ManuallyCopyLargeEnum { A(bool), - B([u128; 4000]), + B([u64; 8000]), } impl Clone for ManuallyCopyLargeEnum { diff --git a/tests/ui/large_enum_variant.stderr b/tests/ui/large_enum_variant.stderr index c6ed97487..709972b4a 100644 --- a/tests/ui/large_enum_variant.stderr +++ b/tests/ui/large_enum_variant.stderr @@ -167,8 +167,8 @@ error: large size difference between variants LL | / enum CopyableLargeEnum { LL | | A(bool), | | ------- the second-largest variant contains at least 1 bytes -LL | | B([u128; 4000]), - | | --------------- the largest variant contains at least 64000 bytes +LL | | B([u64; 8000]), + | | -------------- the largest variant contains at least 64000 bytes LL | | } | |_^ the entire enum is at least 64008 bytes | @@ -180,8 +180,8 @@ LL | enum CopyableLargeEnum { help: consider boxing the large fields to reduce the total size of the enum --> $DIR/large_enum_variant.rs:104:5 | -LL | B([u128; 4000]), - | ^^^^^^^^^^^^^^^ +LL | B([u64; 8000]), + | ^^^^^^^^^^^^^^ error: large size difference between variants --> $DIR/large_enum_variant.rs:107:1 @@ -189,8 +189,8 @@ error: large size difference between variants LL | / enum ManuallyCopyLargeEnum { LL | | A(bool), | | ------- the second-largest variant contains at least 1 bytes -LL | | B([u128; 4000]), - | | --------------- the largest variant contains at least 64000 bytes +LL | | B([u64; 8000]), + | | -------------- the largest variant contains at least 64000 bytes LL | | } | |_^ the entire enum is at least 64008 bytes | @@ -202,8 +202,8 @@ LL | enum ManuallyCopyLargeEnum { help: consider boxing the large fields to reduce the total size of the enum --> $DIR/large_enum_variant.rs:109:5 | -LL | B([u128; 4000]), - | ^^^^^^^^^^^^^^^ +LL | B([u64; 8000]), + | ^^^^^^^^^^^^^^ error: large size difference between variants --> $DIR/large_enum_variant.rs:120:1 diff --git a/tests/ui/large_stack_arrays.rs b/tests/ui/large_stack_arrays.rs index d9161bfcf..6790765f8 100644 --- a/tests/ui/large_stack_arrays.rs +++ b/tests/ui/large_stack_arrays.rs @@ -12,6 +12,12 @@ enum E { T(u32), } +pub static DOESNOTLINT: [u8; 512_001] = [0; 512_001]; +pub static DOESNOTLINT2: [u8; 512_001] = { + let x = 0; + [x; 512_001] +}; + fn main() { let bad = ( [0u32; 20_000_000], diff --git a/tests/ui/large_stack_arrays.stderr b/tests/ui/large_stack_arrays.stderr index 58c0a77c1..0d91b65b4 100644 --- a/tests/ui/large_stack_arrays.stderr +++ b/tests/ui/large_stack_arrays.stderr @@ -1,5 +1,5 @@ error: allocating a local array larger than 512000 bytes - --> $DIR/large_stack_arrays.rs:17:9 + --> $DIR/large_stack_arrays.rs:23:9 | LL | [0u32; 20_000_000], | ^^^^^^^^^^^^^^^^^^ @@ -8,7 +8,7 @@ LL | [0u32; 20_000_000], = help: consider allocating on the heap with `vec![0u32; 20_000_000].into_boxed_slice()` error: allocating a local array larger than 512000 bytes - --> $DIR/large_stack_arrays.rs:18:9 + --> $DIR/large_stack_arrays.rs:24:9 | LL | [S { data: [0; 32] }; 5000], | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -16,7 +16,7 @@ LL | [S { data: [0; 32] }; 5000], = help: consider allocating on the heap with `vec![S { data: [0; 32] }; 5000].into_boxed_slice()` error: allocating a local array larger than 512000 bytes - --> $DIR/large_stack_arrays.rs:19:9 + --> $DIR/large_stack_arrays.rs:25:9 | LL | [Some(""); 20_000_000], | ^^^^^^^^^^^^^^^^^^^^^^ @@ -24,7 +24,7 @@ LL | [Some(""); 20_000_000], = help: consider allocating on the heap with `vec![Some(""); 20_000_000].into_boxed_slice()` error: allocating a local array larger than 512000 bytes - --> $DIR/large_stack_arrays.rs:20:9 + --> $DIR/large_stack_arrays.rs:26:9 | LL | [E::T(0); 5000], | ^^^^^^^^^^^^^^^ diff --git a/tests/ui/len_without_is_empty.rs b/tests/ui/len_without_is_empty.rs index 1e938e72b..78397c2af 100644 --- a/tests/ui/len_without_is_empty.rs +++ b/tests/ui/len_without_is_empty.rs @@ -274,7 +274,7 @@ impl AsyncLen { } pub async fn len(&self) -> usize { - if self.async_task().await { 0 } else { 1 } + usize::from(!self.async_task().await) } pub async fn is_empty(&self) -> bool { diff --git a/tests/ui/nonminimal_bool.rs b/tests/ui/nonminimal_bool.rs index 24ae62bb0..e9b4367ca 100644 --- a/tests/ui/nonminimal_bool.rs +++ b/tests/ui/nonminimal_bool.rs @@ -57,3 +57,9 @@ fn check_expect() { #[expect(clippy::nonminimal_bool)] let _ = !!a; } + +fn issue9428() { + if matches!(true, true) && true { + println!("foo"); + } +} diff --git a/tests/ui/nonminimal_bool.stderr b/tests/ui/nonminimal_bool.stderr index fc6a5ce1d..91b5805aa 100644 --- a/tests/ui/nonminimal_bool.stderr +++ b/tests/ui/nonminimal_bool.stderr @@ -107,5 +107,11 @@ LL | let _ = !(a == b || c == d); LL | let _ = a != b && c != d; | ~~~~~~~~~~~~~~~~ -error: aborting due to 12 previous errors +error: this boolean expression can be simplified + --> $DIR/nonminimal_bool.rs:62:8 + | +LL | if matches!(true, true) && true { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `matches!(true, true)` + +error: aborting due to 13 previous errors diff --git a/tests/ui/positional_named_format_parameters.fixed b/tests/ui/positional_named_format_parameters.fixed deleted file mode 100644 index 4170e1098..000000000 --- a/tests/ui/positional_named_format_parameters.fixed +++ /dev/null @@ -1,56 +0,0 @@ -// run-rustfix -#![allow(unused_must_use)] -#![allow(named_arguments_used_positionally)] // Unstable at time of writing. -#![warn(clippy::positional_named_format_parameters)] - -use std::io::Write; - -fn main() { - let mut v = Vec::new(); - let hello = "Hello"; - - println!("{hello:.foo$}", foo = 2); - writeln!(v, "{hello:.foo$}", foo = 2); - - // Warnings - println!("{zero} {one:?}", zero = 0, one = 1); - println!("This is a test {zero} {one:?}", zero = 0, one = 1); - println!("Hello {one} is {two:.zero$}", zero = 5, one = hello, two = 0.01); - println!("Hello {one:zero$}!", zero = 5, one = 1); - println!("Hello {zero:one$}!", zero = 4, one = 1); - println!("Hello {zero:0one$}!", zero = 4, one = 1); - println!("Hello is {one:.zero$}", zero = 5, one = 0.01); - println!("Hello is {one:<6.zero$}", zero = 5, one = 0.01); - println!("{zero}, `{two:>8.one$}` has 3", zero = hello, one = 3, two = hello); - println!("Hello {one} is {two:.zero$}", zero = 5, one = hello, two = 0.01); - println!("Hello {world} {world}!", world = 5); - - writeln!(v, "{zero} {one:?}", zero = 0, one = 1); - writeln!(v, "This is a test {zero} {one:?}", zero = 0, one = 1); - writeln!(v, "Hello {one} is {two:.zero$}", zero = 5, one = hello, two = 0.01); - writeln!(v, "Hello {one:zero$}!", zero = 4, one = 1); - writeln!(v, "Hello {zero:one$}!", zero = 4, one = 1); - writeln!(v, "Hello {zero:0one$}!", zero = 4, one = 1); - writeln!(v, "Hello is {one:.zero$}", zero = 3, one = 0.01); - writeln!(v, "Hello is {one:<6.zero$}", zero = 2, one = 0.01); - writeln!(v, "{zero}, `{two:>8.one$}` has 3", zero = hello, one = 3, two = hello); - writeln!(v, "Hello {one} is {two:.zero$}", zero = 1, one = hello, two = 0.01); - writeln!(v, "Hello {world} {world}!", world = 0); - - // Tests from other files - println!("{w:w$}", w = 1); - println!("{p:.p$}", p = 1); - println!("{v}", v = 1); - println!("{v:v$}", v = 1); - println!("{v:v$}", v = 1); - println!("{v:v$.v$}", v = 1); - println!("{v:v$.v$}", v = 1); - println!("{v:v$.v$}", v = 1); - println!("{v:v$.v$}", v = 1); - println!("{v:v$.v$}", v = 1); - println!("{v:v$.v$}", v = 1); - println!("{v:v$.v$}", v = 1); - println!("{w:w$}", w = 1); - println!("{p:.p$}", p = 1); - println!("{:p$.w$}", 1, w = 1, p = 1); -} diff --git a/tests/ui/positional_named_format_parameters.rs b/tests/ui/positional_named_format_parameters.rs deleted file mode 100644 index 553d8494e..000000000 --- a/tests/ui/positional_named_format_parameters.rs +++ /dev/null @@ -1,56 +0,0 @@ -// run-rustfix -#![allow(unused_must_use)] -#![allow(named_arguments_used_positionally)] // Unstable at time of writing. -#![warn(clippy::positional_named_format_parameters)] - -use std::io::Write; - -fn main() { - let mut v = Vec::new(); - let hello = "Hello"; - - println!("{hello:.foo$}", foo = 2); - writeln!(v, "{hello:.foo$}", foo = 2); - - // Warnings - println!("{} {1:?}", zero = 0, one = 1); - println!("This is a test { } {000001:?}", zero = 0, one = 1); - println!("Hello {1} is {2:.0$}", zero = 5, one = hello, two = 0.01); - println!("Hello {1:0$}!", zero = 5, one = 1); - println!("Hello {0:1$}!", zero = 4, one = 1); - println!("Hello {0:01$}!", zero = 4, one = 1); - println!("Hello is {1:.*}", zero = 5, one = 0.01); - println!("Hello is {:<6.*}", zero = 5, one = 0.01); - println!("{}, `{two:>8.*}` has 3", zero = hello, one = 3, two = hello); - println!("Hello {1} is {2:.0$}", zero = 5, one = hello, two = 0.01); - println!("Hello {world} {}!", world = 5); - - writeln!(v, "{} {1:?}", zero = 0, one = 1); - writeln!(v, "This is a test { } {000001:?}", zero = 0, one = 1); - writeln!(v, "Hello {1} is {2:.0$}", zero = 5, one = hello, two = 0.01); - writeln!(v, "Hello {1:0$}!", zero = 4, one = 1); - writeln!(v, "Hello {0:1$}!", zero = 4, one = 1); - writeln!(v, "Hello {0:01$}!", zero = 4, one = 1); - writeln!(v, "Hello is {1:.*}", zero = 3, one = 0.01); - writeln!(v, "Hello is {:<6.*}", zero = 2, one = 0.01); - writeln!(v, "{}, `{two:>8.*}` has 3", zero = hello, one = 3, two = hello); - writeln!(v, "Hello {1} is {2:.0$}", zero = 1, one = hello, two = 0.01); - writeln!(v, "Hello {world} {}!", world = 0); - - // Tests from other files - println!("{:w$}", w = 1); - println!("{:.p$}", p = 1); - println!("{}", v = 1); - println!("{:0$}", v = 1); - println!("{0:0$}", v = 1); - println!("{:0$.0$}", v = 1); - println!("{0:0$.0$}", v = 1); - println!("{0:0$.v$}", v = 1); - println!("{0:v$.0$}", v = 1); - println!("{v:0$.0$}", v = 1); - println!("{v:v$.0$}", v = 1); - println!("{v:0$.v$}", v = 1); - println!("{:w$}", w = 1); - println!("{:.p$}", p = 1); - println!("{:p$.w$}", 1, w = 1, p = 1); -} diff --git a/tests/ui/positional_named_format_parameters.stderr b/tests/ui/positional_named_format_parameters.stderr deleted file mode 100644 index 48ddb6d67..000000000 --- a/tests/ui/positional_named_format_parameters.stderr +++ /dev/null @@ -1,418 +0,0 @@ -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:16:16 - | -LL | println!("{} {1:?}", zero = 0, one = 1); - | ^ help: replace it with: `zero` - | - = note: `-D clippy::positional-named-format-parameters` implied by `-D warnings` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:16:19 - | -LL | println!("{} {1:?}", zero = 0, one = 1); - | ^ help: replace it with: `one` - -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:17:31 - | -LL | println!("This is a test { } {000001:?}", zero = 0, one = 1); - | ^ help: replace it with: `zero` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:17:35 - | -LL | println!("This is a test { } {000001:?}", zero = 0, one = 1); - | ^^^^^^ help: replace it with: `one` - -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:18:32 - | -LL | println!("Hello {1} is {2:.0$}", zero = 5, one = hello, two = 0.01); - | ^ help: replace it with: `zero` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:18:22 - | -LL | println!("Hello {1} is {2:.0$}", zero = 5, one = hello, two = 0.01); - | ^ help: replace it with: `one` - -error: named parameter two is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:18:29 - | -LL | println!("Hello {1} is {2:.0$}", zero = 5, one = hello, two = 0.01); - | ^ help: replace it with: `two` - -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:19:24 - | -LL | println!("Hello {1:0$}!", zero = 5, one = 1); - | ^ help: replace it with: `zero` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:19:22 - | -LL | println!("Hello {1:0$}!", zero = 5, one = 1); - | ^ help: replace it with: `one` - -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:20:22 - | -LL | println!("Hello {0:1$}!", zero = 4, one = 1); - | ^ help: replace it with: `zero` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:20:24 - | -LL | println!("Hello {0:1$}!", zero = 4, one = 1); - | ^ help: replace it with: `one` - -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:21:22 - | -LL | println!("Hello {0:01$}!", zero = 4, one = 1); - | ^ help: replace it with: `zero` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:21:25 - | -LL | println!("Hello {0:01$}!", zero = 4, one = 1); - | ^ help: replace it with: `one` - -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:22:28 - | -LL | println!("Hello is {1:.*}", zero = 5, one = 0.01); - | ^ help: replace it with: `zero$` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:22:25 - | -LL | println!("Hello is {1:.*}", zero = 5, one = 0.01); - | ^ help: replace it with: `one` - -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:23:29 - | -LL | println!("Hello is {:<6.*}", zero = 5, one = 0.01); - | ^ help: replace it with: `zero$` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:23:25 - | -LL | println!("Hello is {:<6.*}", zero = 5, one = 0.01); - | ^ help: replace it with: `one` - -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:24:16 - | -LL | println!("{}, `{two:>8.*}` has 3", zero = hello, one = 3, two = hello); - | ^ help: replace it with: `zero` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:24:28 - | -LL | println!("{}, `{two:>8.*}` has 3", zero = hello, one = 3, two = hello); - | ^ help: replace it with: `one$` - -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:25:32 - | -LL | println!("Hello {1} is {2:.0$}", zero = 5, one = hello, two = 0.01); - | ^ help: replace it with: `zero` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:25:22 - | -LL | println!("Hello {1} is {2:.0$}", zero = 5, one = hello, two = 0.01); - | ^ help: replace it with: `one` - -error: named parameter two is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:25:29 - | -LL | println!("Hello {1} is {2:.0$}", zero = 5, one = hello, two = 0.01); - | ^ help: replace it with: `two` - -error: named parameter world is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:26:30 - | -LL | println!("Hello {world} {}!", world = 5); - | ^ help: replace it with: `world` - -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:28:19 - | -LL | writeln!(v, "{} {1:?}", zero = 0, one = 1); - | ^ help: replace it with: `zero` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:28:22 - | -LL | writeln!(v, "{} {1:?}", zero = 0, one = 1); - | ^ help: replace it with: `one` - -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:29:34 - | -LL | writeln!(v, "This is a test { } {000001:?}", zero = 0, one = 1); - | ^ help: replace it with: `zero` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:29:38 - | -LL | writeln!(v, "This is a test { } {000001:?}", zero = 0, one = 1); - | ^^^^^^ help: replace it with: `one` - -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:30:35 - | -LL | writeln!(v, "Hello {1} is {2:.0$}", zero = 5, one = hello, two = 0.01); - | ^ help: replace it with: `zero` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:30:25 - | -LL | writeln!(v, "Hello {1} is {2:.0$}", zero = 5, one = hello, two = 0.01); - | ^ help: replace it with: `one` - -error: named parameter two is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:30:32 - | -LL | writeln!(v, "Hello {1} is {2:.0$}", zero = 5, one = hello, two = 0.01); - | ^ help: replace it with: `two` - -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:31:27 - | -LL | writeln!(v, "Hello {1:0$}!", zero = 4, one = 1); - | ^ help: replace it with: `zero` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:31:25 - | -LL | writeln!(v, "Hello {1:0$}!", zero = 4, one = 1); - | ^ help: replace it with: `one` - -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:32:25 - | -LL | writeln!(v, "Hello {0:1$}!", zero = 4, one = 1); - | ^ help: replace it with: `zero` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:32:27 - | -LL | writeln!(v, "Hello {0:1$}!", zero = 4, one = 1); - | ^ help: replace it with: `one` - -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:33:25 - | -LL | writeln!(v, "Hello {0:01$}!", zero = 4, one = 1); - | ^ help: replace it with: `zero` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:33:28 - | -LL | writeln!(v, "Hello {0:01$}!", zero = 4, one = 1); - | ^ help: replace it with: `one` - -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:34:31 - | -LL | writeln!(v, "Hello is {1:.*}", zero = 3, one = 0.01); - | ^ help: replace it with: `zero$` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:34:28 - | -LL | writeln!(v, "Hello is {1:.*}", zero = 3, one = 0.01); - | ^ help: replace it with: `one` - -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:35:32 - | -LL | writeln!(v, "Hello is {:<6.*}", zero = 2, one = 0.01); - | ^ help: replace it with: `zero$` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:35:28 - | -LL | writeln!(v, "Hello is {:<6.*}", zero = 2, one = 0.01); - | ^ help: replace it with: `one` - -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:36:19 - | -LL | writeln!(v, "{}, `{two:>8.*}` has 3", zero = hello, one = 3, two = hello); - | ^ help: replace it with: `zero` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:36:31 - | -LL | writeln!(v, "{}, `{two:>8.*}` has 3", zero = hello, one = 3, two = hello); - | ^ help: replace it with: `one$` - -error: named parameter zero is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:37:35 - | -LL | writeln!(v, "Hello {1} is {2:.0$}", zero = 1, one = hello, two = 0.01); - | ^ help: replace it with: `zero` - -error: named parameter one is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:37:25 - | -LL | writeln!(v, "Hello {1} is {2:.0$}", zero = 1, one = hello, two = 0.01); - | ^ help: replace it with: `one` - -error: named parameter two is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:37:32 - | -LL | writeln!(v, "Hello {1} is {2:.0$}", zero = 1, one = hello, two = 0.01); - | ^ help: replace it with: `two` - -error: named parameter world is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:38:33 - | -LL | writeln!(v, "Hello {world} {}!", world = 0); - | ^ help: replace it with: `world` - -error: named parameter w is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:41:16 - | -LL | println!("{:w$}", w = 1); - | ^ help: replace it with: `w` - -error: named parameter p is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:42:16 - | -LL | println!("{:.p$}", p = 1); - | ^ help: replace it with: `p` - -error: named parameter v is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:43:16 - | -LL | println!("{}", v = 1); - | ^ help: replace it with: `v` - -error: named parameter v is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:44:16 - | -LL | println!("{:0$}", v = 1); - | ^ help: replace it with: `v` - -error: named parameter v is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:44:17 - | -LL | println!("{:0$}", v = 1); - | ^ help: replace it with: `v` - -error: named parameter v is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:45:16 - | -LL | println!("{0:0$}", v = 1); - | ^ help: replace it with: `v` - -error: named parameter v is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:45:18 - | -LL | println!("{0:0$}", v = 1); - | ^ help: replace it with: `v` - -error: named parameter v is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:46:16 - | -LL | println!("{:0$.0$}", v = 1); - | ^ help: replace it with: `v` - -error: named parameter v is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:46:20 - | -LL | println!("{:0$.0$}", v = 1); - | ^ help: replace it with: `v` - -error: named parameter v is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:46:17 - | -LL | println!("{:0$.0$}", v = 1); - | ^ help: replace it with: `v` - -error: named parameter v is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:47:16 - | -LL | println!("{0:0$.0$}", v = 1); - | ^ help: replace it with: `v` - -error: named parameter v is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:47:21 - | -LL | println!("{0:0$.0$}", v = 1); - | ^ help: replace it with: `v` - -error: named parameter v is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:47:18 - | -LL | println!("{0:0$.0$}", v = 1); - | ^ help: replace it with: `v` - -error: named parameter v is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:48:16 - | -LL | println!("{0:0$.v$}", v = 1); - | ^ help: replace it with: `v` - -error: named parameter v is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:48:18 - | -LL | println!("{0:0$.v$}", v = 1); - | ^ help: replace it with: `v` - -error: named parameter v is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:49:16 - | -LL | println!("{0:v$.0$}", v = 1); - | ^ help: replace it with: `v` - -error: named parameter v is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:49:21 - | -LL | println!("{0:v$.0$}", v = 1); - | ^ help: replace it with: `v` - -error: named parameter v is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:50:21 - | -LL | println!("{v:0$.0$}", v = 1); - | ^ help: replace it with: `v` - -error: named parameter v is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:50:18 - | -LL | println!("{v:0$.0$}", v = 1); - | ^ help: replace it with: `v` - -error: named parameter v is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:51:21 - | -LL | println!("{v:v$.0$}", v = 1); - | ^ help: replace it with: `v` - -error: named parameter v is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:52:18 - | -LL | println!("{v:0$.v$}", v = 1); - | ^ help: replace it with: `v` - -error: named parameter w is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:53:16 - | -LL | println!("{:w$}", w = 1); - | ^ help: replace it with: `w` - -error: named parameter p is used as a positional parameter - --> $DIR/positional_named_format_parameters.rs:54:16 - | -LL | println!("{:.p$}", p = 1); - | ^ help: replace it with: `p` - -error: aborting due to 69 previous errors - diff --git a/tests/ui/print_literal.rs b/tests/ui/print_literal.rs index 8665a3bb2..3f6639c14 100644 --- a/tests/ui/print_literal.rs +++ b/tests/ui/print_literal.rs @@ -20,11 +20,13 @@ fn main() { println!("{} of {:b} people know binary, the other half doesn't", 1, 2); println!("10 / 4 is {}", 2.5); println!("2 + 1 = {}", 3); + println!("From expansion {}", stringify!(not a string literal)); // these should throw warnings print!("Hello {}", "world"); println!("Hello {} {}", world, "world"); println!("Hello {}", "world"); + println!("{} {:.4}", "a literal", 5); // positional args don't change the fact // that we're using a literal -- this should diff --git a/tests/ui/print_literal.stderr b/tests/ui/print_literal.stderr index 72aae0756..23e6dbc3e 100644 --- a/tests/ui/print_literal.stderr +++ b/tests/ui/print_literal.stderr @@ -1,5 +1,5 @@ error: literal with an empty format string - --> $DIR/print_literal.rs:25:24 + --> $DIR/print_literal.rs:26:24 | LL | print!("Hello {}", "world"); | ^^^^^^^ @@ -12,7 +12,7 @@ LL + print!("Hello world"); | error: literal with an empty format string - --> $DIR/print_literal.rs:26:36 + --> $DIR/print_literal.rs:27:36 | LL | println!("Hello {} {}", world, "world"); | ^^^^^^^ @@ -24,7 +24,7 @@ LL + println!("Hello {} world", world); | error: literal with an empty format string - --> $DIR/print_literal.rs:27:26 + --> $DIR/print_literal.rs:28:26 | LL | println!("Hello {}", "world"); | ^^^^^^^ @@ -36,7 +36,19 @@ LL + println!("Hello world"); | error: literal with an empty format string - --> $DIR/print_literal.rs:32:25 + --> $DIR/print_literal.rs:29:26 + | +LL | println!("{} {:.4}", "a literal", 5); + | ^^^^^^^^^^^ + | +help: try this + | +LL - println!("{} {:.4}", "a literal", 5); +LL + println!("a literal {:.4}", 5); + | + +error: literal with an empty format string + --> $DIR/print_literal.rs:34:25 | LL | println!("{0} {1}", "hello", "world"); | ^^^^^^^ @@ -48,7 +60,7 @@ LL + println!("hello {1}", "world"); | error: literal with an empty format string - --> $DIR/print_literal.rs:32:34 + --> $DIR/print_literal.rs:34:34 | LL | println!("{0} {1}", "hello", "world"); | ^^^^^^^ @@ -60,19 +72,7 @@ LL + println!("{0} world", "hello"); | error: literal with an empty format string - --> $DIR/print_literal.rs:33:25 - | -LL | println!("{1} {0}", "hello", "world"); - | ^^^^^^^ - | -help: try this - | -LL - println!("{1} {0}", "hello", "world"); -LL + println!("{1} hello", "world"); - | - -error: literal with an empty format string - --> $DIR/print_literal.rs:33:34 + --> $DIR/print_literal.rs:35:34 | LL | println!("{1} {0}", "hello", "world"); | ^^^^^^^ @@ -84,10 +84,22 @@ LL + println!("world {0}", "hello"); | error: literal with an empty format string - --> $DIR/print_literal.rs:36:29 + --> $DIR/print_literal.rs:35:25 + | +LL | println!("{1} {0}", "hello", "world"); + | ^^^^^^^ + | +help: try this + | +LL - println!("{1} {0}", "hello", "world"); +LL + println!("{1} hello", "world"); + | + +error: literal with an empty format string + --> $DIR/print_literal.rs:38:35 | LL | println!("{foo} {bar}", foo = "hello", bar = "world"); - | ^^^^^^^^^^^^^ + | ^^^^^^^ | help: try this | @@ -96,10 +108,10 @@ LL + println!("hello {bar}", bar = "world"); | error: literal with an empty format string - --> $DIR/print_literal.rs:36:44 + --> $DIR/print_literal.rs:38:50 | LL | println!("{foo} {bar}", foo = "hello", bar = "world"); - | ^^^^^^^^^^^^^ + | ^^^^^^^ | help: try this | @@ -108,22 +120,10 @@ LL + println!("{foo} world", foo = "hello"); | error: literal with an empty format string - --> $DIR/print_literal.rs:37:29 + --> $DIR/print_literal.rs:39:50 | LL | println!("{bar} {foo}", foo = "hello", bar = "world"); - | ^^^^^^^^^^^^^ - | -help: try this - | -LL - println!("{bar} {foo}", foo = "hello", bar = "world"); -LL + println!("{bar} hello", bar = "world"); - | - -error: literal with an empty format string - --> $DIR/print_literal.rs:37:44 - | -LL | println!("{bar} {foo}", foo = "hello", bar = "world"); - | ^^^^^^^^^^^^^ + | ^^^^^^^ | help: try this | @@ -131,5 +131,17 @@ LL - println!("{bar} {foo}", foo = "hello", bar = "world"); LL + println!("world {foo}", foo = "hello"); | -error: aborting due to 11 previous errors +error: literal with an empty format string + --> $DIR/print_literal.rs:39:35 + | +LL | println!("{bar} {foo}", foo = "hello", bar = "world"); + | ^^^^^^^ + | +help: try this + | +LL - println!("{bar} {foo}", foo = "hello", bar = "world"); +LL + println!("{bar} hello", bar = "world"); + | + +error: aborting due to 12 previous errors diff --git a/tests/ui/print_with_newline.rs b/tests/ui/print_with_newline.rs index a43a1fc4f..b8c29d207 100644 --- a/tests/ui/print_with_newline.rs +++ b/tests/ui/print_with_newline.rs @@ -48,5 +48,13 @@ fn main() { print!("\r\n"); print!("foo\r\n"); print!("\\r\n"); //~ ERROR - print!("foo\rbar\n") // ~ ERROR + print!("foo\rbar\n"); + + // Ignore expanded format strings + macro_rules! newline { + () => { + "\n" + }; + } + print!(newline!()); } diff --git a/tests/ui/print_with_newline.stderr b/tests/ui/print_with_newline.stderr index edbaa1cdf..b9f5675fa 100644 --- a/tests/ui/print_with_newline.stderr +++ b/tests/ui/print_with_newline.stderr @@ -83,7 +83,7 @@ LL | | ); help: use `println!` instead | LL ~ println!( -LL ~ "" +LL ~ | error: using `print!()` with a format string that ends in a single newline @@ -98,7 +98,7 @@ LL | | ); help: use `println!` instead | LL ~ println!( -LL ~ r"" +LL ~ | error: using `print!()` with a format string that ends in a single newline @@ -113,17 +113,5 @@ LL - print!("/r/n"); //~ ERROR LL + println!("/r"); //~ ERROR | -error: using `print!()` with a format string that ends in a single newline - --> $DIR/print_with_newline.rs:51:5 - | -LL | print!("foo/rbar/n") // ~ ERROR - | ^^^^^^^^^^^^^^^^^^^^ - | -help: use `println!` instead - | -LL - print!("foo/rbar/n") // ~ ERROR -LL + println!("foo/rbar") // ~ ERROR - | - -error: aborting due to 10 previous errors +error: aborting due to 9 previous errors diff --git a/tests/ui/println_empty_string.stderr b/tests/ui/println_empty_string.stderr index 17fe4ea74..3cc8bb947 100644 --- a/tests/ui/println_empty_string.stderr +++ b/tests/ui/println_empty_string.stderr @@ -1,28 +1,36 @@ -error: using `println!("")` +error: empty string literal in `println!` --> $DIR/println_empty_string.rs:6:5 | LL | println!(""); - | ^^^^^^^^^^^^ help: replace it with: `println!()` + | ^^^^^^^^^--^ + | | + | help: remove the empty string | = note: `-D clippy::println-empty-string` implied by `-D warnings` -error: using `println!("")` +error: empty string literal in `println!` --> $DIR/println_empty_string.rs:9:14 | LL | _ => println!(""), - | ^^^^^^^^^^^^ help: replace it with: `println!()` + | ^^^^^^^^^--^ + | | + | help: remove the empty string -error: using `eprintln!("")` +error: empty string literal in `eprintln!` --> $DIR/println_empty_string.rs:13:5 | LL | eprintln!(""); - | ^^^^^^^^^^^^^ help: replace it with: `eprintln!()` + | ^^^^^^^^^^--^ + | | + | help: remove the empty string -error: using `eprintln!("")` +error: empty string literal in `eprintln!` --> $DIR/println_empty_string.rs:16:14 | LL | _ => eprintln!(""), - | ^^^^^^^^^^^^^ help: replace it with: `eprintln!()` + | ^^^^^^^^^^--^ + | | + | help: remove the empty string error: aborting due to 4 previous errors diff --git a/tests/ui/rename.fixed b/tests/ui/rename.fixed index 9cbad2269..a6e7bdba7 100644 --- a/tests/ui/rename.fixed +++ b/tests/ui/rename.fixed @@ -32,6 +32,7 @@ #![allow(invalid_value)] #![allow(enum_intrinsics_non_enums)] #![allow(non_fmt_panics)] +#![allow(named_arguments_used_positionally)] #![allow(temporary_cstring_as_ptr)] #![allow(unknown_lints)] #![allow(unused_labels)] @@ -69,6 +70,7 @@ #![warn(invalid_value)] #![warn(enum_intrinsics_non_enums)] #![warn(non_fmt_panics)] +#![warn(named_arguments_used_positionally)] #![warn(temporary_cstring_as_ptr)] #![warn(unknown_lints)] #![warn(unused_labels)] diff --git a/tests/ui/rename.rs b/tests/ui/rename.rs index 9153c0dab..e8f57597d 100644 --- a/tests/ui/rename.rs +++ b/tests/ui/rename.rs @@ -32,6 +32,7 @@ #![allow(invalid_value)] #![allow(enum_intrinsics_non_enums)] #![allow(non_fmt_panics)] +#![allow(named_arguments_used_positionally)] #![allow(temporary_cstring_as_ptr)] #![allow(unknown_lints)] #![allow(unused_labels)] @@ -69,6 +70,7 @@ #![warn(clippy::invalid_ref)] #![warn(clippy::mem_discriminant_non_enum)] #![warn(clippy::panic_params)] +#![warn(clippy::positional_named_format_parameters)] #![warn(clippy::temporary_cstring_as_ptr)] #![warn(clippy::unknown_clippy_lints)] #![warn(clippy::unused_label)] diff --git a/tests/ui/rename.stderr b/tests/ui/rename.stderr index 9c03ea914..31865a7f6 100644 --- a/tests/ui/rename.stderr +++ b/tests/ui/rename.stderr @@ -1,5 +1,5 @@ error: lint `clippy::blacklisted_name` has been renamed to `clippy::disallowed_names` - --> $DIR/rename.rs:38:9 + --> $DIR/rename.rs:39:9 | LL | #![warn(clippy::blacklisted_name)] | ^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::disallowed_names` @@ -7,220 +7,226 @@ LL | #![warn(clippy::blacklisted_name)] = note: `-D renamed-and-removed-lints` implied by `-D warnings` error: lint `clippy::block_in_if_condition_expr` has been renamed to `clippy::blocks_in_if_conditions` - --> $DIR/rename.rs:39:9 + --> $DIR/rename.rs:40:9 | LL | #![warn(clippy::block_in_if_condition_expr)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::blocks_in_if_conditions` error: lint `clippy::block_in_if_condition_stmt` has been renamed to `clippy::blocks_in_if_conditions` - --> $DIR/rename.rs:40:9 + --> $DIR/rename.rs:41:9 | LL | #![warn(clippy::block_in_if_condition_stmt)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::blocks_in_if_conditions` error: lint `clippy::box_vec` has been renamed to `clippy::box_collection` - --> $DIR/rename.rs:41:9 + --> $DIR/rename.rs:42:9 | LL | #![warn(clippy::box_vec)] | ^^^^^^^^^^^^^^^ help: use the new name: `clippy::box_collection` error: lint `clippy::const_static_lifetime` has been renamed to `clippy::redundant_static_lifetimes` - --> $DIR/rename.rs:42:9 + --> $DIR/rename.rs:43:9 | LL | #![warn(clippy::const_static_lifetime)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::redundant_static_lifetimes` error: lint `clippy::cyclomatic_complexity` has been renamed to `clippy::cognitive_complexity` - --> $DIR/rename.rs:43:9 + --> $DIR/rename.rs:44:9 | LL | #![warn(clippy::cyclomatic_complexity)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::cognitive_complexity` error: lint `clippy::disallowed_method` has been renamed to `clippy::disallowed_methods` - --> $DIR/rename.rs:44:9 + --> $DIR/rename.rs:45:9 | LL | #![warn(clippy::disallowed_method)] | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::disallowed_methods` error: lint `clippy::disallowed_type` has been renamed to `clippy::disallowed_types` - --> $DIR/rename.rs:45:9 + --> $DIR/rename.rs:46:9 | LL | #![warn(clippy::disallowed_type)] | ^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::disallowed_types` error: lint `clippy::eval_order_dependence` has been renamed to `clippy::mixed_read_write_in_expression` - --> $DIR/rename.rs:46:9 + --> $DIR/rename.rs:47:9 | LL | #![warn(clippy::eval_order_dependence)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::mixed_read_write_in_expression` error: lint `clippy::for_loop_over_option` has been renamed to `clippy::for_loops_over_fallibles` - --> $DIR/rename.rs:47:9 + --> $DIR/rename.rs:48:9 | LL | #![warn(clippy::for_loop_over_option)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::for_loops_over_fallibles` error: lint `clippy::for_loop_over_result` has been renamed to `clippy::for_loops_over_fallibles` - --> $DIR/rename.rs:48:9 + --> $DIR/rename.rs:49:9 | LL | #![warn(clippy::for_loop_over_result)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::for_loops_over_fallibles` error: lint `clippy::identity_conversion` has been renamed to `clippy::useless_conversion` - --> $DIR/rename.rs:49:9 + --> $DIR/rename.rs:50:9 | LL | #![warn(clippy::identity_conversion)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::useless_conversion` error: lint `clippy::if_let_some_result` has been renamed to `clippy::match_result_ok` - --> $DIR/rename.rs:50:9 + --> $DIR/rename.rs:51:9 | LL | #![warn(clippy::if_let_some_result)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::match_result_ok` error: lint `clippy::logic_bug` has been renamed to `clippy::overly_complex_bool_expr` - --> $DIR/rename.rs:51:9 + --> $DIR/rename.rs:52:9 | LL | #![warn(clippy::logic_bug)] | ^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::overly_complex_bool_expr` error: lint `clippy::new_without_default_derive` has been renamed to `clippy::new_without_default` - --> $DIR/rename.rs:52:9 + --> $DIR/rename.rs:53:9 | LL | #![warn(clippy::new_without_default_derive)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::new_without_default` error: lint `clippy::option_and_then_some` has been renamed to `clippy::bind_instead_of_map` - --> $DIR/rename.rs:53:9 + --> $DIR/rename.rs:54:9 | LL | #![warn(clippy::option_and_then_some)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::bind_instead_of_map` error: lint `clippy::option_expect_used` has been renamed to `clippy::expect_used` - --> $DIR/rename.rs:54:9 + --> $DIR/rename.rs:55:9 | LL | #![warn(clippy::option_expect_used)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::expect_used` error: lint `clippy::option_map_unwrap_or` has been renamed to `clippy::map_unwrap_or` - --> $DIR/rename.rs:55:9 + --> $DIR/rename.rs:56:9 | LL | #![warn(clippy::option_map_unwrap_or)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::map_unwrap_or` error: lint `clippy::option_map_unwrap_or_else` has been renamed to `clippy::map_unwrap_or` - --> $DIR/rename.rs:56:9 + --> $DIR/rename.rs:57:9 | LL | #![warn(clippy::option_map_unwrap_or_else)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::map_unwrap_or` error: lint `clippy::option_unwrap_used` has been renamed to `clippy::unwrap_used` - --> $DIR/rename.rs:57:9 + --> $DIR/rename.rs:58:9 | LL | #![warn(clippy::option_unwrap_used)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::unwrap_used` error: lint `clippy::ref_in_deref` has been renamed to `clippy::needless_borrow` - --> $DIR/rename.rs:58:9 + --> $DIR/rename.rs:59:9 | LL | #![warn(clippy::ref_in_deref)] | ^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::needless_borrow` error: lint `clippy::result_expect_used` has been renamed to `clippy::expect_used` - --> $DIR/rename.rs:59:9 + --> $DIR/rename.rs:60:9 | LL | #![warn(clippy::result_expect_used)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::expect_used` error: lint `clippy::result_map_unwrap_or_else` has been renamed to `clippy::map_unwrap_or` - --> $DIR/rename.rs:60:9 + --> $DIR/rename.rs:61:9 | LL | #![warn(clippy::result_map_unwrap_or_else)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::map_unwrap_or` error: lint `clippy::result_unwrap_used` has been renamed to `clippy::unwrap_used` - --> $DIR/rename.rs:61:9 + --> $DIR/rename.rs:62:9 | LL | #![warn(clippy::result_unwrap_used)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::unwrap_used` error: lint `clippy::single_char_push_str` has been renamed to `clippy::single_char_add_str` - --> $DIR/rename.rs:62:9 + --> $DIR/rename.rs:63:9 | LL | #![warn(clippy::single_char_push_str)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::single_char_add_str` error: lint `clippy::stutter` has been renamed to `clippy::module_name_repetitions` - --> $DIR/rename.rs:63:9 + --> $DIR/rename.rs:64:9 | LL | #![warn(clippy::stutter)] | ^^^^^^^^^^^^^^^ help: use the new name: `clippy::module_name_repetitions` error: lint `clippy::to_string_in_display` has been renamed to `clippy::recursive_format_impl` - --> $DIR/rename.rs:64:9 + --> $DIR/rename.rs:65:9 | LL | #![warn(clippy::to_string_in_display)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::recursive_format_impl` error: lint `clippy::zero_width_space` has been renamed to `clippy::invisible_characters` - --> $DIR/rename.rs:65:9 + --> $DIR/rename.rs:66:9 | LL | #![warn(clippy::zero_width_space)] | ^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `clippy::invisible_characters` error: lint `clippy::drop_bounds` has been renamed to `drop_bounds` - --> $DIR/rename.rs:66:9 + --> $DIR/rename.rs:67:9 | LL | #![warn(clippy::drop_bounds)] | ^^^^^^^^^^^^^^^^^^^ help: use the new name: `drop_bounds` error: lint `clippy::into_iter_on_array` has been renamed to `array_into_iter` - --> $DIR/rename.rs:67:9 + --> $DIR/rename.rs:68:9 | LL | #![warn(clippy::into_iter_on_array)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `array_into_iter` error: lint `clippy::invalid_atomic_ordering` has been renamed to `invalid_atomic_ordering` - --> $DIR/rename.rs:68:9 + --> $DIR/rename.rs:69:9 | LL | #![warn(clippy::invalid_atomic_ordering)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `invalid_atomic_ordering` error: lint `clippy::invalid_ref` has been renamed to `invalid_value` - --> $DIR/rename.rs:69:9 + --> $DIR/rename.rs:70:9 | LL | #![warn(clippy::invalid_ref)] | ^^^^^^^^^^^^^^^^^^^ help: use the new name: `invalid_value` error: lint `clippy::mem_discriminant_non_enum` has been renamed to `enum_intrinsics_non_enums` - --> $DIR/rename.rs:70:9 + --> $DIR/rename.rs:71:9 | LL | #![warn(clippy::mem_discriminant_non_enum)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `enum_intrinsics_non_enums` error: lint `clippy::panic_params` has been renamed to `non_fmt_panics` - --> $DIR/rename.rs:71:9 + --> $DIR/rename.rs:72:9 | LL | #![warn(clippy::panic_params)] | ^^^^^^^^^^^^^^^^^^^^ help: use the new name: `non_fmt_panics` +error: lint `clippy::positional_named_format_parameters` has been renamed to `named_arguments_used_positionally` + --> $DIR/rename.rs:73:9 + | +LL | #![warn(clippy::positional_named_format_parameters)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `named_arguments_used_positionally` + error: lint `clippy::temporary_cstring_as_ptr` has been renamed to `temporary_cstring_as_ptr` - --> $DIR/rename.rs:72:9 + --> $DIR/rename.rs:74:9 | LL | #![warn(clippy::temporary_cstring_as_ptr)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `temporary_cstring_as_ptr` error: lint `clippy::unknown_clippy_lints` has been renamed to `unknown_lints` - --> $DIR/rename.rs:73:9 + --> $DIR/rename.rs:75:9 | LL | #![warn(clippy::unknown_clippy_lints)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `unknown_lints` error: lint `clippy::unused_label` has been renamed to `unused_labels` - --> $DIR/rename.rs:74:9 + --> $DIR/rename.rs:76:9 | LL | #![warn(clippy::unused_label)] | ^^^^^^^^^^^^^^^^^^^^ help: use the new name: `unused_labels` -error: aborting due to 37 previous errors +error: aborting due to 38 previous errors diff --git a/tests/ui/unnecessary_to_owned.fixed b/tests/ui/unnecessary_to_owned.fixed index a920c63b1..f97583aa2 100644 --- a/tests/ui/unnecessary_to_owned.fixed +++ b/tests/ui/unnecessary_to_owned.fixed @@ -417,3 +417,12 @@ mod issue_9351 { predicates_are_satisfied(id("abc".to_string())); } } + +mod issue_9504 { + #![allow(dead_code)] + + async fn foo>(_: S) {} + async fn bar() { + foo(std::path::PathBuf::new().to_string_lossy().to_string()).await; + } +} diff --git a/tests/ui/unnecessary_to_owned.rs b/tests/ui/unnecessary_to_owned.rs index 2128bdacd..aa5394a56 100644 --- a/tests/ui/unnecessary_to_owned.rs +++ b/tests/ui/unnecessary_to_owned.rs @@ -417,3 +417,12 @@ mod issue_9351 { predicates_are_satisfied(id("abc".to_string())); } } + +mod issue_9504 { + #![allow(dead_code)] + + async fn foo>(_: S) {} + async fn bar() { + foo(std::path::PathBuf::new().to_string_lossy().to_string()).await; + } +} diff --git a/tests/ui/unused_peekable.rs b/tests/ui/unused_peekable.rs index 153457e36..7374dfdf9 100644 --- a/tests/ui/unused_peekable.rs +++ b/tests/ui/unused_peekable.rs @@ -57,12 +57,22 @@ fn valid() { impl PeekableConsumer { fn consume(&self, _: Peekable>) {} fn consume_mut_ref(&self, _: &mut Peekable>) {} + fn consume_assoc(_: Peekable>) {} + fn consume_assoc_mut_ref(_: &mut Peekable>) {} } - let peekable_consumer = PeekableConsumer; - let mut passed_along_to_method = std::iter::empty::().peekable(); - peekable_consumer.consume_mut_ref(&mut passed_along_to_method); - peekable_consumer.consume(passed_along_to_method); + + let peekable = std::iter::empty::().peekable(); + peekable_consumer.consume(peekable); + + let mut peekable = std::iter::empty::().peekable(); + peekable_consumer.consume_mut_ref(&mut peekable); + + let peekable = std::iter::empty::().peekable(); + PeekableConsumer::consume_assoc(peekable); + + let mut peekable = std::iter::empty::().peekable(); + PeekableConsumer::consume_assoc_mut_ref(&mut peekable); // `peek` called in another block let mut peekable_in_block = std::iter::empty::().peekable(); @@ -141,4 +151,19 @@ fn valid() { { peekable_last_expr.peek(); } + + let mut peek_in_closure = std::iter::empty::().peekable(); + let _ = || { + let _ = peek_in_closure.peek(); + }; + + trait PeekTrait {} + impl PeekTrait for Peekable where I: Iterator {} + + let mut peekable = std::iter::empty::().peekable(); + let _dyn = &mut peekable as &mut dyn PeekTrait; + + fn takes_dyn(_: &mut dyn PeekTrait) {} + let mut peekable = std::iter::empty::().peekable(); + takes_dyn(&mut peekable); } diff --git a/tests/ui/use_self.fixed b/tests/ui/use_self.fixed index 4f80aaecc..37986187d 100644 --- a/tests/ui/use_self.fixed +++ b/tests/ui/use_self.fixed @@ -608,3 +608,12 @@ mod issue8845 { } } } + +mod issue6902 { + use serde::Serialize; + + #[derive(Serialize)] + pub enum Foo { + Bar = 1, + } +} diff --git a/tests/ui/use_self.rs b/tests/ui/use_self.rs index 52da72db5..1b2b3337c 100644 --- a/tests/ui/use_self.rs +++ b/tests/ui/use_self.rs @@ -608,3 +608,12 @@ mod issue8845 { } } } + +mod issue6902 { + use serde::Serialize; + + #[derive(Serialize)] + pub enum Foo { + Bar = 1, + } +} diff --git a/tests/ui/write_literal.rs b/tests/ui/write_literal.rs index 446691744..5892818aa 100644 --- a/tests/ui/write_literal.rs +++ b/tests/ui/write_literal.rs @@ -25,11 +25,13 @@ fn main() { writeln!(v, "{} of {:b} people know binary, the other half doesn't", 1, 2); writeln!(v, "10 / 4 is {}", 2.5); writeln!(v, "2 + 1 = {}", 3); + writeln!(v, "From expansion {}", stringify!(not a string literal)); // these should throw warnings write!(v, "Hello {}", "world"); writeln!(v, "Hello {} {}", world, "world"); writeln!(v, "Hello {}", "world"); + writeln!(v, "{} {:.4}", "a literal", 5); // positional args don't change the fact // that we're using a literal -- this should diff --git a/tests/ui/write_literal.stderr b/tests/ui/write_literal.stderr index 3c5ec91d3..1e306ae28 100644 --- a/tests/ui/write_literal.stderr +++ b/tests/ui/write_literal.stderr @@ -1,5 +1,5 @@ error: literal with an empty format string - --> $DIR/write_literal.rs:30:27 + --> $DIR/write_literal.rs:31:27 | LL | write!(v, "Hello {}", "world"); | ^^^^^^^ @@ -12,7 +12,7 @@ LL + write!(v, "Hello world"); | error: literal with an empty format string - --> $DIR/write_literal.rs:31:39 + --> $DIR/write_literal.rs:32:39 | LL | writeln!(v, "Hello {} {}", world, "world"); | ^^^^^^^ @@ -24,7 +24,7 @@ LL + writeln!(v, "Hello {} world", world); | error: literal with an empty format string - --> $DIR/write_literal.rs:32:29 + --> $DIR/write_literal.rs:33:29 | LL | writeln!(v, "Hello {}", "world"); | ^^^^^^^ @@ -36,7 +36,19 @@ LL + writeln!(v, "Hello world"); | error: literal with an empty format string - --> $DIR/write_literal.rs:37:28 + --> $DIR/write_literal.rs:34:29 + | +LL | writeln!(v, "{} {:.4}", "a literal", 5); + | ^^^^^^^^^^^ + | +help: try this + | +LL - writeln!(v, "{} {:.4}", "a literal", 5); +LL + writeln!(v, "a literal {:.4}", 5); + | + +error: literal with an empty format string + --> $DIR/write_literal.rs:39:28 | LL | writeln!(v, "{0} {1}", "hello", "world"); | ^^^^^^^ @@ -48,7 +60,7 @@ LL + writeln!(v, "hello {1}", "world"); | error: literal with an empty format string - --> $DIR/write_literal.rs:37:37 + --> $DIR/write_literal.rs:39:37 | LL | writeln!(v, "{0} {1}", "hello", "world"); | ^^^^^^^ @@ -60,19 +72,7 @@ LL + writeln!(v, "{0} world", "hello"); | error: literal with an empty format string - --> $DIR/write_literal.rs:38:28 - | -LL | writeln!(v, "{1} {0}", "hello", "world"); - | ^^^^^^^ - | -help: try this - | -LL - writeln!(v, "{1} {0}", "hello", "world"); -LL + writeln!(v, "{1} hello", "world"); - | - -error: literal with an empty format string - --> $DIR/write_literal.rs:38:37 + --> $DIR/write_literal.rs:40:37 | LL | writeln!(v, "{1} {0}", "hello", "world"); | ^^^^^^^ @@ -84,10 +84,22 @@ LL + writeln!(v, "world {0}", "hello"); | error: literal with an empty format string - --> $DIR/write_literal.rs:41:32 + --> $DIR/write_literal.rs:40:28 + | +LL | writeln!(v, "{1} {0}", "hello", "world"); + | ^^^^^^^ + | +help: try this + | +LL - writeln!(v, "{1} {0}", "hello", "world"); +LL + writeln!(v, "{1} hello", "world"); + | + +error: literal with an empty format string + --> $DIR/write_literal.rs:43:38 | LL | writeln!(v, "{foo} {bar}", foo = "hello", bar = "world"); - | ^^^^^^^^^^^^^ + | ^^^^^^^ | help: try this | @@ -96,10 +108,10 @@ LL + writeln!(v, "hello {bar}", bar = "world"); | error: literal with an empty format string - --> $DIR/write_literal.rs:41:47 + --> $DIR/write_literal.rs:43:53 | LL | writeln!(v, "{foo} {bar}", foo = "hello", bar = "world"); - | ^^^^^^^^^^^^^ + | ^^^^^^^ | help: try this | @@ -108,22 +120,10 @@ LL + writeln!(v, "{foo} world", foo = "hello"); | error: literal with an empty format string - --> $DIR/write_literal.rs:42:32 + --> $DIR/write_literal.rs:44:53 | LL | writeln!(v, "{bar} {foo}", foo = "hello", bar = "world"); - | ^^^^^^^^^^^^^ - | -help: try this - | -LL - writeln!(v, "{bar} {foo}", foo = "hello", bar = "world"); -LL + writeln!(v, "{bar} hello", bar = "world"); - | - -error: literal with an empty format string - --> $DIR/write_literal.rs:42:47 - | -LL | writeln!(v, "{bar} {foo}", foo = "hello", bar = "world"); - | ^^^^^^^^^^^^^ + | ^^^^^^^ | help: try this | @@ -131,5 +131,17 @@ LL - writeln!(v, "{bar} {foo}", foo = "hello", bar = "world"); LL + writeln!(v, "world {foo}", foo = "hello"); | -error: aborting due to 11 previous errors +error: literal with an empty format string + --> $DIR/write_literal.rs:44:38 + | +LL | writeln!(v, "{bar} {foo}", foo = "hello", bar = "world"); + | ^^^^^^^ + | +help: try this + | +LL - writeln!(v, "{bar} {foo}", foo = "hello", bar = "world"); +LL + writeln!(v, "{bar} hello", bar = "world"); + | + +error: aborting due to 12 previous errors diff --git a/tests/ui/write_literal_2.rs b/tests/ui/write_literal_2.rs index ba0d7be5e..55a11daa1 100644 --- a/tests/ui/write_literal_2.rs +++ b/tests/ui/write_literal_2.rs @@ -10,7 +10,7 @@ fn main() { writeln!(v, r"{}", r"{hello}"); writeln!(v, "{}", '\''); writeln!(v, "{}", '"'); - writeln!(v, r"{}", '"'); // don't lint + writeln!(v, r"{}", '"'); writeln!(v, r"{}", '\''); writeln!( v, @@ -24,4 +24,11 @@ fn main() { {} \\ {}", "1", "2", "3", ); + writeln!(v, "{}", "\\"); + writeln!(v, r"{}", "\\"); + writeln!(v, r#"{}"#, "\\"); + writeln!(v, "{}", r"\"); + writeln!(v, "{}", "\r"); + writeln!(v, r#"{}{}"#, '#', '"'); // hard mode + writeln!(v, r"{}", "\r"); // should not lint } diff --git a/tests/ui/write_literal_2.stderr b/tests/ui/write_literal_2.stderr index 9ff297069..d5956db9f 100644 --- a/tests/ui/write_literal_2.stderr +++ b/tests/ui/write_literal_2.stderr @@ -47,6 +47,12 @@ LL - writeln!(v, "{}", '"'); LL + writeln!(v, "/""); | +error: literal with an empty format string + --> $DIR/write_literal_2.rs:13:24 + | +LL | writeln!(v, r"{}", '"'); + | ^^^ + error: literal with an empty format string --> $DIR/write_literal_2.rs:14:24 | @@ -108,5 +114,77 @@ LL ~ {} / 3", LL ~ "1", "2", | -error: aborting due to 9 previous errors +error: literal with an empty format string + --> $DIR/write_literal_2.rs:27:23 + | +LL | writeln!(v, "{}", "/"); + | ^^^^ + | +help: try this + | +LL - writeln!(v, "{}", "/"); +LL + writeln!(v, "/"); + | + +error: literal with an empty format string + --> $DIR/write_literal_2.rs:28:24 + | +LL | writeln!(v, r"{}", "/"); + | ^^^^ + | +help: try this + | +LL - writeln!(v, r"{}", "/"); +LL + writeln!(v, r"/"); + | + +error: literal with an empty format string + --> $DIR/write_literal_2.rs:29:26 + | +LL | writeln!(v, r#"{}"#, "/"); + | ^^^^ + | +help: try this + | +LL - writeln!(v, r#"{}"#, "/"); +LL + writeln!(v, r#"/"#); + | + +error: literal with an empty format string + --> $DIR/write_literal_2.rs:30:23 + | +LL | writeln!(v, "{}", r"/"); + | ^^^^ + | +help: try this + | +LL - writeln!(v, "{}", r"/"); +LL + writeln!(v, "/"); + | + +error: literal with an empty format string + --> $DIR/write_literal_2.rs:31:23 + | +LL | writeln!(v, "{}", "/r"); + | ^^^^ + | +help: try this + | +LL - writeln!(v, "{}", "/r"); +LL + writeln!(v, "/r"); + | + +error: literal with an empty format string + --> $DIR/write_literal_2.rs:32:28 + | +LL | writeln!(v, r#"{}{}"#, '#', '"'); // hard mode + | ^^^ + +error: literal with an empty format string + --> $DIR/write_literal_2.rs:32:33 + | +LL | writeln!(v, r#"{}{}"#, '#', '"'); // hard mode + | ^^^ + +error: aborting due to 17 previous errors diff --git a/tests/ui/write_with_newline.rs b/tests/ui/write_with_newline.rs index 446d6914d..b79364c87 100644 --- a/tests/ui/write_with_newline.rs +++ b/tests/ui/write_with_newline.rs @@ -56,4 +56,12 @@ fn main() { write!(v, "foo\r\n"); write!(v, "\\r\n"); //~ ERROR write!(v, "foo\rbar\n"); + + // Ignore expanded format strings + macro_rules! newline { + () => { + "\n" + }; + } + write!(v, newline!()); } diff --git a/tests/ui/write_with_newline.stderr b/tests/ui/write_with_newline.stderr index 5f55431be..2baaea166 100644 --- a/tests/ui/write_with_newline.stderr +++ b/tests/ui/write_with_newline.stderr @@ -5,7 +5,7 @@ LL | write!(v, "Hello/n"); | ^^^^^^^^^^^^^^^^^^^^ | = note: `-D clippy::write-with-newline` implied by `-D warnings` -help: use `writeln!()` instead +help: use `writeln!` instead | LL - write!(v, "Hello/n"); LL + writeln!(v, "Hello"); @@ -17,7 +17,7 @@ error: using `write!()` with a format string that ends in a single newline LL | write!(v, "Hello {}/n", "world"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: use `writeln!()` instead +help: use `writeln!` instead | LL - write!(v, "Hello {}/n", "world"); LL + writeln!(v, "Hello {}", "world"); @@ -29,7 +29,7 @@ error: using `write!()` with a format string that ends in a single newline LL | write!(v, "Hello {} {}/n", "world", "#2"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -help: use `writeln!()` instead +help: use `writeln!` instead | LL - write!(v, "Hello {} {}/n", "world", "#2"); LL + writeln!(v, "Hello {} {}", "world", "#2"); @@ -41,7 +41,7 @@ error: using `write!()` with a format string that ends in a single newline LL | write!(v, "{}/n", 1265); | ^^^^^^^^^^^^^^^^^^^^^^^ | -help: use `writeln!()` instead +help: use `writeln!` instead | LL - write!(v, "{}/n", 1265); LL + writeln!(v, "{}", 1265); @@ -53,7 +53,7 @@ error: using `write!()` with a format string that ends in a single newline LL | write!(v, "/n"); | ^^^^^^^^^^^^^^^ | -help: use `writeln!()` instead +help: use `writeln!` instead | LL - write!(v, "/n"); LL + writeln!(v); @@ -65,7 +65,7 @@ error: using `write!()` with a format string that ends in a single newline LL | write!(v, "//n"); // should fail | ^^^^^^^^^^^^^^^^^ | -help: use `writeln!()` instead +help: use `writeln!` instead | LL - write!(v, "//n"); // should fail LL + writeln!(v, "/"); // should fail @@ -81,11 +81,10 @@ LL | | " LL | | ); | |_____^ | -help: use `writeln!()` instead +help: use `writeln!` instead | LL ~ writeln!( -LL | v, -LL ~ "" +LL ~ v | error: using `write!()` with a format string that ends in a single newline @@ -98,11 +97,10 @@ LL | | " LL | | ); | |_____^ | -help: use `writeln!()` instead +help: use `writeln!` instead | LL ~ writeln!( -LL | v, -LL ~ r"" +LL ~ v | error: using `write!()` with a format string that ends in a single newline @@ -111,23 +109,11 @@ error: using `write!()` with a format string that ends in a single newline LL | write!(v, "/r/n"); //~ ERROR | ^^^^^^^^^^^^^^^^^^ | -help: use `writeln!()` instead +help: use `writeln!` instead | LL - write!(v, "/r/n"); //~ ERROR LL + writeln!(v, "/r"); //~ ERROR | -error: using `write!()` with a format string that ends in a single newline - --> $DIR/write_with_newline.rs:58:5 - | -LL | write!(v, "foo/rbar/n"); - | ^^^^^^^^^^^^^^^^^^^^^^^ - | -help: use `writeln!()` instead - | -LL - write!(v, "foo/rbar/n"); -LL + writeln!(v, "foo/rbar"); - | - -error: aborting due to 10 previous errors +error: aborting due to 9 previous errors diff --git a/tests/ui/writeln_empty_string.stderr b/tests/ui/writeln_empty_string.stderr index ac65aadfc..25e69ec48 100644 --- a/tests/ui/writeln_empty_string.stderr +++ b/tests/ui/writeln_empty_string.stderr @@ -1,16 +1,20 @@ -error: using `writeln!(v, "")` +error: empty string literal in `writeln!` --> $DIR/writeln_empty_string.rs:11:5 | LL | writeln!(v, ""); - | ^^^^^^^^^^^^^^^ help: replace it with: `writeln!(v)` + | ^^^^^^^^^^----^ + | | + | help: remove the empty string | = note: `-D clippy::writeln-empty-string` implied by `-D warnings` -error: using `writeln!(suggestion, "")` +error: empty string literal in `writeln!` --> $DIR/writeln_empty_string.rs:14:5 | LL | writeln!(suggestion, ""); - | ^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `writeln!(suggestion)` + | ^^^^^^^^^^^^^^^^^^^----^ + | | + | help: remove the empty string error: aborting due to 2 previous errors From 09b1e8ff3494a6fa92922ef992fb8fe861c87b28 Mon Sep 17 00:00:00 2001 From: Steve Heindel Date: Wed, 21 Sep 2022 19:45:57 -0400 Subject: [PATCH 22/34] Add note to clippy::non_expressive_names doc --- clippy_lints/src/non_expressive_names.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/clippy_lints/src/non_expressive_names.rs b/clippy_lints/src/non_expressive_names.rs index b96af06b8..a7cd1f6d0 100644 --- a/clippy_lints/src/non_expressive_names.rs +++ b/clippy_lints/src/non_expressive_names.rs @@ -15,6 +15,10 @@ declare_clippy_lint! { /// ### What it does /// Checks for names that are very similar and thus confusing. /// + /// Note: this lint looks for similar names throughout each + /// scope. To allow it, you need to allow it on the scope + /// level, not on the name that is reported. + /// /// ### Why is this bad? /// It's hard to distinguish between names that differ only /// by a single character. From adc7e3e679ff18653fe646326ff0f27eaccd5f70 Mon Sep 17 00:00:00 2001 From: b-naber Date: Mon, 19 Sep 2022 19:46:53 +0200 Subject: [PATCH 23/34] introduce mir::Unevaluated --- clippy_lints/src/non_copy_const.rs | 2 +- clippy_utils/src/consts.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/clippy_lints/src/non_copy_const.rs b/clippy_lints/src/non_copy_const.rs index 72c86f28b..85024b0b0 100644 --- a/clippy_lints/src/non_copy_const.rs +++ b/clippy_lints/src/non_copy_const.rs @@ -195,7 +195,7 @@ fn is_value_unfrozen_expr<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId, def_id: D let result = cx.tcx.const_eval_resolve( cx.param_env, - ty::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs), + mir::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs), None, ); is_value_unfrozen_raw(cx, result, ty) diff --git a/clippy_utils/src/consts.rs b/clippy_utils/src/consts.rs index 1b8a9c055..ac5bac371 100644 --- a/clippy_utils/src/consts.rs +++ b/clippy_utils/src/consts.rs @@ -424,7 +424,7 @@ impl<'a, 'tcx> ConstEvalLateContext<'a, 'tcx> { .tcx .const_eval_resolve( self.param_env, - ty::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs), + mir::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs), None, ) .ok() From 26861fbd7f5fa80928f2ccad750ec2cc9726862c Mon Sep 17 00:00:00 2001 From: b-naber Date: Thu, 22 Sep 2022 12:34:23 +0200 Subject: [PATCH 24/34] rename Unevaluated to UnevaluatedConst --- clippy_lints/src/non_copy_const.rs | 2 +- clippy_utils/src/consts.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/clippy_lints/src/non_copy_const.rs b/clippy_lints/src/non_copy_const.rs index 85024b0b0..b15884527 100644 --- a/clippy_lints/src/non_copy_const.rs +++ b/clippy_lints/src/non_copy_const.rs @@ -195,7 +195,7 @@ fn is_value_unfrozen_expr<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId, def_id: D let result = cx.tcx.const_eval_resolve( cx.param_env, - mir::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs), + mir::UnevaluatedConst::new(ty::WithOptConstParam::unknown(def_id), substs), None, ); is_value_unfrozen_raw(cx, result, ty) diff --git a/clippy_utils/src/consts.rs b/clippy_utils/src/consts.rs index ac5bac371..fa6766f7c 100644 --- a/clippy_utils/src/consts.rs +++ b/clippy_utils/src/consts.rs @@ -424,7 +424,7 @@ impl<'a, 'tcx> ConstEvalLateContext<'a, 'tcx> { .tcx .const_eval_resolve( self.param_env, - mir::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs), + mir::UnevaluatedConst::new(ty::WithOptConstParam::unknown(def_id), substs), None, ) .ok() From 781e45c224e2ae2f2d7876d2ebb3d0390db45a6c Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Thu, 22 Sep 2022 19:39:38 +0200 Subject: [PATCH 25/34] Bless clippy. --- tests/ui/inefficient_to_string.stderr | 8 ++++---- tests/ui/suspicious_to_owned.stderr | 8 ++++---- tests/ui/transmute_ptr_to_ref.stderr | 4 ++-- tests/ui/useless_conversion.stderr | 2 +- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/tests/ui/inefficient_to_string.stderr b/tests/ui/inefficient_to_string.stderr index 4be46161e..1c0490ffa 100644 --- a/tests/ui/inefficient_to_string.stderr +++ b/tests/ui/inefficient_to_string.stderr @@ -35,21 +35,21 @@ LL | let _: String = rrrstring.to_string(); | = help: `&&std::string::String` implements `ToString` through a slower blanket impl, but `std::string::String` has a fast specialization of `ToString` -error: calling `to_string` on `&&std::borrow::Cow` +error: calling `to_string` on `&&std::borrow::Cow<'_, str>` --> $DIR/inefficient_to_string.rs:29:21 | LL | let _: String = rrcow.to_string(); | ^^^^^^^^^^^^^^^^^ help: try dereferencing the receiver: `(*rrcow).to_string()` | - = help: `&std::borrow::Cow` implements `ToString` through a slower blanket impl, but `std::borrow::Cow` has a fast specialization of `ToString` + = help: `&std::borrow::Cow<'_, str>` implements `ToString` through a slower blanket impl, but `std::borrow::Cow<'_, str>` has a fast specialization of `ToString` -error: calling `to_string` on `&&&std::borrow::Cow` +error: calling `to_string` on `&&&std::borrow::Cow<'_, str>` --> $DIR/inefficient_to_string.rs:30:21 | LL | let _: String = rrrcow.to_string(); | ^^^^^^^^^^^^^^^^^^ help: try dereferencing the receiver: `(**rrrcow).to_string()` | - = help: `&&std::borrow::Cow` implements `ToString` through a slower blanket impl, but `std::borrow::Cow` has a fast specialization of `ToString` + = help: `&&std::borrow::Cow<'_, str>` implements `ToString` through a slower blanket impl, but `std::borrow::Cow<'_, str>` has a fast specialization of `ToString` error: aborting due to 6 previous errors diff --git a/tests/ui/suspicious_to_owned.stderr b/tests/ui/suspicious_to_owned.stderr index 92e1024bf..ae1aec34d 100644 --- a/tests/ui/suspicious_to_owned.stderr +++ b/tests/ui/suspicious_to_owned.stderr @@ -1,4 +1,4 @@ -error: this `to_owned` call clones the std::borrow::Cow itself and does not cause the std::borrow::Cow contents to become owned +error: this `to_owned` call clones the std::borrow::Cow<'_, str> itself and does not cause the std::borrow::Cow<'_, str> contents to become owned --> $DIR/suspicious_to_owned.rs:16:13 | LL | let _ = cow.to_owned(); @@ -6,19 +6,19 @@ LL | let _ = cow.to_owned(); | = note: `-D clippy::suspicious-to-owned` implied by `-D warnings` -error: this `to_owned` call clones the std::borrow::Cow<[char; 3]> itself and does not cause the std::borrow::Cow<[char; 3]> contents to become owned +error: this `to_owned` call clones the std::borrow::Cow<'_, [char; 3]> itself and does not cause the std::borrow::Cow<'_, [char; 3]> contents to become owned --> $DIR/suspicious_to_owned.rs:26:13 | LL | let _ = cow.to_owned(); | ^^^^^^^^^^^^^^ help: consider using, depending on intent: `cow.clone()` or `cow.into_owned()` -error: this `to_owned` call clones the std::borrow::Cow> itself and does not cause the std::borrow::Cow> contents to become owned +error: this `to_owned` call clones the std::borrow::Cow<'_, std::vec::Vec> itself and does not cause the std::borrow::Cow<'_, std::vec::Vec> contents to become owned --> $DIR/suspicious_to_owned.rs:36:13 | LL | let _ = cow.to_owned(); | ^^^^^^^^^^^^^^ help: consider using, depending on intent: `cow.clone()` or `cow.into_owned()` -error: this `to_owned` call clones the std::borrow::Cow itself and does not cause the std::borrow::Cow contents to become owned +error: this `to_owned` call clones the std::borrow::Cow<'_, str> itself and does not cause the std::borrow::Cow<'_, str> contents to become owned --> $DIR/suspicious_to_owned.rs:46:13 | LL | let _ = cow.to_owned(); diff --git a/tests/ui/transmute_ptr_to_ref.stderr b/tests/ui/transmute_ptr_to_ref.stderr index 2993e5e7b..10117ee91 100644 --- a/tests/ui/transmute_ptr_to_ref.stderr +++ b/tests/ui/transmute_ptr_to_ref.stderr @@ -42,13 +42,13 @@ error: transmute from a pointer type (`*mut U`) to a reference type (`&T`) LL | let _: &T = std::mem::transmute(om); | ^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(om as *const T)` -error: transmute from a pointer type (`*const i32`) to a reference type (`&_issue1231::Foo`) +error: transmute from a pointer type (`*const i32`) to a reference type (`&_issue1231::Foo<'_, u8>`) --> $DIR/transmute_ptr_to_ref.rs:36:32 | LL | let _: &Foo = unsafe { std::mem::transmute::<_, &Foo<_>>(raw) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*raw.cast::>()` -error: transmute from a pointer type (`*const i32`) to a reference type (`&_issue1231::Foo<&u8>`) +error: transmute from a pointer type (`*const i32`) to a reference type (`&_issue1231::Foo<'_, &u8>`) --> $DIR/transmute_ptr_to_ref.rs:38:33 | LL | let _: &Foo<&u8> = unsafe { std::mem::transmute::<_, &Foo<&_>>(raw) }; diff --git a/tests/ui/useless_conversion.stderr b/tests/ui/useless_conversion.stderr index e6760f700..65ee3807f 100644 --- a/tests/ui/useless_conversion.stderr +++ b/tests/ui/useless_conversion.stderr @@ -46,7 +46,7 @@ error: useless conversion to the same type: `std::string::String` LL | let _ = String::from(format!("A: {:04}", 123)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider removing `String::from()`: `format!("A: {:04}", 123)` -error: useless conversion to the same type: `std::str::Lines` +error: useless conversion to the same type: `std::str::Lines<'_>` --> $DIR/useless_conversion.rs:65:13 | LL | let _ = "".lines().into_iter(); From 334f4535bd51c550d014f408364390095d99cd30 Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Fri, 23 Sep 2022 18:03:44 +0200 Subject: [PATCH 26/34] Stabilize const `BTree{Map,Set}::new` Since `len` and `is_empty` are not const stable yet, this also creates a new feature for them since they previously used the same `const_btree_new` feature. --- tests/ui/crashes/ice-7126.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/ui/crashes/ice-7126.rs b/tests/ui/crashes/ice-7126.rs index ca563ba09..b2dc2248b 100644 --- a/tests/ui/crashes/ice-7126.rs +++ b/tests/ui/crashes/ice-7126.rs @@ -1,13 +1,13 @@ // This test requires a feature gated const fn and will stop working in the future. -#![feature(const_btree_new)] +#![feature(const_btree_len)] use std::collections::BTreeMap; -struct Foo(BTreeMap); +struct Foo(usize); impl Foo { fn new() -> Self { - Self(BTreeMap::new()) + Self(BTreeMap::len(&BTreeMap::::new())) } } From e30b37b84b75dca4622a210ad1ad116d05a1bae9 Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Fri, 23 Sep 2022 21:04:54 +0200 Subject: [PATCH 27/34] Fix clippy's const fn stability check for CURRENT_RUSTC_VERSION Since clippy can use a projects MSRV for its lints, it might not want to consider functions as const stable if they have been added lately. Functions that have been stabilized this version use CURRENT_RUSTC_VERSION as their version, which gets then turned into the current version, which might be something like `1.66.0-dev`. The version parser cannot deal with this version, so it has to be stripped off. --- clippy_utils/src/qualify_min_const_fn.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/clippy_utils/src/qualify_min_const_fn.rs b/clippy_utils/src/qualify_min_const_fn.rs index 405f02286..f7ce71917 100644 --- a/clippy_utils/src/qualify_min_const_fn.rs +++ b/clippy_utils/src/qualify_min_const_fn.rs @@ -367,10 +367,21 @@ fn is_const_fn(tcx: TyCtxt<'_>, def_id: DefId, msrv: Option) -> bo // Checking MSRV is manually necessary because `rustc` has no such concept. This entire // function could be removed if `rustc` provided a MSRV-aware version of `is_const_fn`. // as a part of an unimplemented MSRV check https://github.com/rust-lang/rust/issues/65262. + + // HACK(nilstrieb): CURRENT_RUSTC_VERSION can return versions like 1.66.0-dev. `rustc-semver` doesn't accept + // the `-dev` version number so we have to strip it off. + let short_version = since + .as_str() + .split('-') + .next() + .expect("rustc_attr::StabilityLevel::Stable::since` is empty"); + + let since = rustc_span::Symbol::intern(short_version); + crate::meets_msrv( msrv, RustcVersion::parse(since.as_str()) - .expect("`rustc_attr::StabilityLevel::Stable::since` is ill-formatted"), + .unwrap_or_else(|err| panic!("`rustc_attr::StabilityLevel::Stable::since` is ill-formatted: `{since}`, {err:?}")), ) } else { // Unstable const fn with the feature enabled. From ea75178219ab4fd12d035acfc3a0aedb04e91db7 Mon Sep 17 00:00:00 2001 From: Takayuki Maeda Date: Tue, 20 Sep 2022 14:11:23 +0900 Subject: [PATCH 28/34] separate definitions and `HIR` owners fix a ui test use `into` fix clippy ui test fix a run-make-fulldeps test implement `IntoQueryParam` for `OwnerId` use `OwnerId` for more queries change the type of `ParentOwnerIterator::Item` to `(OwnerId, OwnerNode)` --- clippy_lints/src/dereference.rs | 2 +- clippy_lints/src/doc.rs | 10 +++++----- clippy_lints/src/enum_variants.rs | 2 +- clippy_lints/src/escape.rs | 2 +- clippy_lints/src/exhaustive_items.rs | 2 +- clippy_lints/src/exit.rs | 2 +- clippy_lints/src/fallible_impl_from.rs | 2 +- clippy_lints/src/functions/must_use.rs | 20 +++++++++---------- .../src/functions/not_unsafe_ptr_arg_deref.rs | 2 +- clippy_lints/src/functions/result.rs | 14 ++++++------- clippy_lints/src/implicit_hasher.rs | 2 +- clippy_lints/src/inherent_to_string.rs | 2 +- .../src/iter_not_returning_iterator.rs | 4 ++-- clippy_lints/src/len_zero.rs | 4 ++-- clippy_lints/src/lifetimes.rs | 4 ++-- clippy_lints/src/loops/mut_range_bound.rs | 2 +- clippy_lints/src/manual_non_exhaustive.rs | 2 +- clippy_lints/src/methods/mod.rs | 8 ++++---- clippy_lints/src/missing_const_for_fn.rs | 2 +- clippy_lints/src/missing_doc.rs | 2 +- clippy_lints/src/missing_inline.rs | 6 +++--- clippy_lints/src/mut_key.rs | 2 +- clippy_lints/src/new_without_default.rs | 4 ++-- clippy_lints/src/non_copy_const.rs | 2 +- clippy_lints/src/only_used_in_recursion.rs | 2 +- .../src/operators/assign_op_pattern.rs | 2 +- clippy_lints/src/pass_by_ref_or_value.rs | 2 +- clippy_lints/src/redundant_pub_crate.rs | 6 +++--- clippy_lints/src/return_self_not_must_use.rs | 2 +- clippy_lints/src/self_named_constructors.rs | 2 +- clippy_lints/src/suspicious_trait_impl.rs | 4 ++-- clippy_lints/src/transmute/utils.rs | 2 +- clippy_lints/src/types/borrowed_box.rs | 2 +- clippy_lints/src/types/mod.rs | 8 ++++---- clippy_lints/src/unused_self.rs | 4 ++-- clippy_lints/src/unwrap_in_result.rs | 2 +- clippy_lints/src/upper_case_acronyms.rs | 2 +- clippy_lints/src/use_self.rs | 2 +- clippy_lints/src/utils/author.rs | 2 +- clippy_lints/src/wildcard_imports.rs | 6 +++--- clippy_lints/src/zero_sized_map_values.rs | 2 +- clippy_utils/src/lib.rs | 12 +++++------ clippy_utils/src/usage.rs | 2 +- 43 files changed, 85 insertions(+), 85 deletions(-) diff --git a/clippy_lints/src/dereference.rs b/clippy_lints/src/dereference.rs index 501f9ef78..e54d71fc8 100644 --- a/clippy_lints/src/dereference.rs +++ b/clippy_lints/src/dereference.rs @@ -704,7 +704,7 @@ fn walk_parents<'tcx>( span, .. }) if span.ctxt() == ctxt => { - let ty = cx.tcx.type_of(def_id); + let ty = cx.tcx.type_of(def_id.def_id); Some(ty_auto_deref_stability(cx, ty, precedence).position_for_result(cx)) }, diff --git a/clippy_lints/src/doc.rs b/clippy_lints/src/doc.rs index eb158d850..f48ba526d 100644 --- a/clippy_lints/src/doc.rs +++ b/clippy_lints/src/doc.rs @@ -233,11 +233,11 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { let body = cx.tcx.hir().body(body_id); let mut fpu = FindPanicUnwrap { cx, - typeck_results: cx.tcx.typeck(item.def_id), + typeck_results: cx.tcx.typeck(item.def_id.def_id), panic_span: None, }; fpu.visit_expr(body.value); - lint_for_missing_headers(cx, item.def_id, item.span, sig, headers, Some(body_id), fpu.panic_span); + lint_for_missing_headers(cx, item.def_id.def_id, item.span, sig, headers, Some(body_id), fpu.panic_span); } }, hir::ItemKind::Impl(impl_) => { @@ -268,7 +268,7 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { let headers = check_attrs(cx, &self.valid_idents, attrs); if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind { if !in_external_macro(cx.tcx.sess, item.span) { - lint_for_missing_headers(cx, item.def_id, item.span, sig, headers, None, None); + lint_for_missing_headers(cx, item.def_id.def_id, item.span, sig, headers, None, None); } } } @@ -283,11 +283,11 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { let body = cx.tcx.hir().body(body_id); let mut fpu = FindPanicUnwrap { cx, - typeck_results: cx.tcx.typeck(item.def_id), + typeck_results: cx.tcx.typeck(item.def_id.def_id), panic_span: None, }; fpu.visit_expr(body.value); - lint_for_missing_headers(cx, item.def_id, item.span, sig, headers, Some(body_id), fpu.panic_span); + lint_for_missing_headers(cx, item.def_id.def_id, item.span, sig, headers, Some(body_id), fpu.panic_span); } } } diff --git a/clippy_lints/src/enum_variants.rs b/clippy_lints/src/enum_variants.rs index cd36f9fcd..c39a909b3 100644 --- a/clippy_lints/src/enum_variants.rs +++ b/clippy_lints/src/enum_variants.rs @@ -297,7 +297,7 @@ impl LateLintPass<'_> for EnumVariantNames { } } if let ItemKind::Enum(ref def, _) = item.kind { - if !(self.avoid_breaking_exported_api && cx.access_levels.is_exported(item.def_id)) { + if !(self.avoid_breaking_exported_api && cx.access_levels.is_exported(item.def_id.def_id)) { check_variant(cx, self.threshold, def, item_name, item.span); } } diff --git a/clippy_lints/src/escape.rs b/clippy_lints/src/escape.rs index 327865e4c..a6ddb26e2 100644 --- a/clippy_lints/src/escape.rs +++ b/clippy_lints/src/escape.rs @@ -71,7 +71,7 @@ impl<'tcx> LateLintPass<'tcx> for BoxedLocal { } } - let parent_id = cx.tcx.hir().get_parent_item(hir_id); + let parent_id = cx.tcx.hir().get_parent_item(hir_id).def_id; let parent_node = cx.tcx.hir().find_by_def_id(parent_id); let mut trait_self_ty = None; diff --git a/clippy_lints/src/exhaustive_items.rs b/clippy_lints/src/exhaustive_items.rs index 173d41b4b..f3d9ebc5f 100644 --- a/clippy_lints/src/exhaustive_items.rs +++ b/clippy_lints/src/exhaustive_items.rs @@ -73,7 +73,7 @@ impl LateLintPass<'_> for ExhaustiveItems { fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { if_chain! { if let ItemKind::Enum(..) | ItemKind::Struct(..) = item.kind; - if cx.access_levels.is_exported(item.def_id); + if cx.access_levels.is_exported(item.def_id.def_id); let attrs = cx.tcx.hir().attrs(item.hir_id()); if !attrs.iter().any(|a| a.has_name(sym::non_exhaustive)); then { diff --git a/clippy_lints/src/exit.rs b/clippy_lints/src/exit.rs index cbf52d193..407dd1b39 100644 --- a/clippy_lints/src/exit.rs +++ b/clippy_lints/src/exit.rs @@ -33,7 +33,7 @@ impl<'tcx> LateLintPass<'tcx> for Exit { if let ExprKind::Path(ref path) = path_expr.kind; if let Some(def_id) = cx.qpath_res(path, path_expr.hir_id).opt_def_id(); if match_def_path(cx, def_id, &paths::EXIT); - let parent = cx.tcx.hir().get_parent_item(e.hir_id); + let parent = cx.tcx.hir().get_parent_item(e.hir_id).def_id; if let Some(Node::Item(Item{kind: ItemKind::Fn(..), ..})) = cx.tcx.hir().find_by_def_id(parent); // If the next item up is a function we check if it is an entry point // and only then emit a linter warning diff --git a/clippy_lints/src/fallible_impl_from.rs b/clippy_lints/src/fallible_impl_from.rs index 1f69f34a2..ef24a5d06 100644 --- a/clippy_lints/src/fallible_impl_from.rs +++ b/clippy_lints/src/fallible_impl_from.rs @@ -107,7 +107,7 @@ fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_items: &[h let body = cx.tcx.hir().body(body_id); let mut fpu = FindPanicUnwrap { lcx: cx, - typeck_results: cx.tcx.typeck(impl_item.id.def_id), + typeck_results: cx.tcx.typeck(impl_item.id.def_id.def_id), result: Vec::new(), }; fpu.visit_expr(body.value); diff --git a/clippy_lints/src/functions/must_use.rs b/clippy_lints/src/functions/must_use.rs index 00a493776..d6d33bda1 100644 --- a/clippy_lints/src/functions/must_use.rs +++ b/clippy_lints/src/functions/must_use.rs @@ -21,7 +21,7 @@ pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_> let attrs = cx.tcx.hir().attrs(item.hir_id()); let attr = cx.tcx.get_attr(item.def_id.to_def_id(), sym::must_use); if let hir::ItemKind::Fn(ref sig, _generics, ref body_id) = item.kind { - let is_public = cx.access_levels.is_exported(item.def_id); + let is_public = cx.access_levels.is_exported(item.def_id.def_id); let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); if let Some(attr) = attr { check_needless_must_use(cx, sig.decl, item.hir_id(), item.span, fn_header_span, attr); @@ -31,7 +31,7 @@ pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_> sig.decl, cx.tcx.hir().body(*body_id), item.span, - item.def_id, + item.def_id.def_id, item.span.with_hi(sig.decl.output.span().hi()), "this function could have a `#[must_use]` attribute", ); @@ -41,19 +41,19 @@ pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_> pub(super) fn check_impl_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) { if let hir::ImplItemKind::Fn(ref sig, ref body_id) = item.kind { - let is_public = cx.access_levels.is_exported(item.def_id); + let is_public = cx.access_levels.is_exported(item.def_id.def_id); let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); let attrs = cx.tcx.hir().attrs(item.hir_id()); let attr = cx.tcx.get_attr(item.def_id.to_def_id(), sym::must_use); if let Some(attr) = attr { check_needless_must_use(cx, sig.decl, item.hir_id(), item.span, fn_header_span, attr); - } else if is_public && !is_proc_macro(cx.sess(), attrs) && trait_ref_of_method(cx, item.def_id).is_none() { + } else if is_public && !is_proc_macro(cx.sess(), attrs) && trait_ref_of_method(cx, item.def_id.def_id).is_none() { check_must_use_candidate( cx, sig.decl, cx.tcx.hir().body(*body_id), item.span, - item.def_id, + item.def_id.def_id, item.span.with_hi(sig.decl.output.span().hi()), "this method could have a `#[must_use]` attribute", ); @@ -63,7 +63,7 @@ pub(super) fn check_impl_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Imp pub(super) fn check_trait_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) { if let hir::TraitItemKind::Fn(ref sig, ref eid) = item.kind { - let is_public = cx.access_levels.is_exported(item.def_id); + let is_public = cx.access_levels.is_exported(item.def_id.def_id); let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); let attrs = cx.tcx.hir().attrs(item.hir_id()); @@ -78,7 +78,7 @@ pub(super) fn check_trait_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Tr sig.decl, body, item.span, - item.def_id, + item.def_id.def_id, item.span.with_hi(sig.decl.output.span().hi()), "this method could have a `#[must_use]` attribute", ); @@ -171,7 +171,7 @@ fn is_mutable_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, tys: &mut DefIdSet) return false; // ignore `_` patterns } if cx.tcx.has_typeck_results(pat.hir_id.owner.to_def_id()) { - is_mutable_ty(cx, cx.tcx.typeck(pat.hir_id.owner).pat_ty(pat), pat.span, tys) + is_mutable_ty(cx, cx.tcx.typeck(pat.hir_id.owner.def_id).pat_ty(pat), pat.span, tys) } else { false } @@ -218,7 +218,7 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for StaticMutVisitor<'a, 'tcx> { if self.cx.tcx.has_typeck_results(arg.hir_id.owner.to_def_id()) && is_mutable_ty( self.cx, - self.cx.tcx.typeck(arg.hir_id.owner).expr_ty(arg), + self.cx.tcx.typeck(arg.hir_id.owner.def_id).expr_ty(arg), arg.span, &mut tys, ) @@ -236,7 +236,7 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for StaticMutVisitor<'a, 'tcx> { if self.cx.tcx.has_typeck_results(arg.hir_id.owner.to_def_id()) && is_mutable_ty( self.cx, - self.cx.tcx.typeck(arg.hir_id.owner).expr_ty(arg), + self.cx.tcx.typeck(arg.hir_id.owner.def_id).expr_ty(arg), arg.span, &mut tys, ) diff --git a/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs b/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs index 3bbfa52e8..0b50431fb 100644 --- a/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs +++ b/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs @@ -28,7 +28,7 @@ pub(super) fn check_fn<'tcx>( pub(super) fn check_trait_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) { if let hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(eid)) = item.kind { let body = cx.tcx.hir().body(eid); - check_raw_ptr(cx, sig.header.unsafety, sig.decl, body, item.def_id); + check_raw_ptr(cx, sig.header.unsafety, sig.decl, body, item.def_id.def_id); } } diff --git a/clippy_lints/src/functions/result.rs b/clippy_lints/src/functions/result.rs index 9591405cb..113c4e9f5 100644 --- a/clippy_lints/src/functions/result.rs +++ b/clippy_lints/src/functions/result.rs @@ -34,9 +34,9 @@ fn result_err_ty<'tcx>( pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::Item<'tcx>, large_err_threshold: u64) { if let hir::ItemKind::Fn(ref sig, _generics, _) = item.kind - && let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.def_id, item.span) + && let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.def_id.def_id, item.span) { - if cx.access_levels.is_exported(item.def_id) { + if cx.access_levels.is_exported(item.def_id.def_id) { let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); check_result_unit_err(cx, err_ty, fn_header_span); } @@ -47,10 +47,10 @@ pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::Item<'tcx>, l pub(super) fn check_impl_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::ImplItem<'tcx>, large_err_threshold: u64) { // Don't lint if method is a trait's implementation, we can't do anything about those if let hir::ImplItemKind::Fn(ref sig, _) = item.kind - && let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.def_id, item.span) - && trait_ref_of_method(cx, item.def_id).is_none() + && let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.def_id.def_id, item.span) + && trait_ref_of_method(cx, item.def_id.def_id).is_none() { - if cx.access_levels.is_exported(item.def_id) { + if cx.access_levels.is_exported(item.def_id.def_id) { let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); check_result_unit_err(cx, err_ty, fn_header_span); } @@ -61,8 +61,8 @@ pub(super) fn check_impl_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::ImplItem pub(super) fn check_trait_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::TraitItem<'tcx>, large_err_threshold: u64) { if let hir::TraitItemKind::Fn(ref sig, _) = item.kind { let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); - if let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.def_id, item.span) { - if cx.access_levels.is_exported(item.def_id) { + if let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.def_id.def_id, item.span) { + if cx.access_levels.is_exported(item.def_id.def_id) { check_result_unit_err(cx, err_ty, fn_header_span); } check_result_large_err(cx, err_ty, hir_ty.span, large_err_threshold); diff --git a/clippy_lints/src/implicit_hasher.rs b/clippy_lints/src/implicit_hasher.rs index 4f9680f60..804fdc2da 100644 --- a/clippy_lints/src/implicit_hasher.rs +++ b/clippy_lints/src/implicit_hasher.rs @@ -112,7 +112,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitHasher { } } - if !cx.access_levels.is_exported(item.def_id) { + if !cx.access_levels.is_exported(item.def_id.def_id) { return; } diff --git a/clippy_lints/src/inherent_to_string.rs b/clippy_lints/src/inherent_to_string.rs index 17d867aac..cb6c2ec0f 100644 --- a/clippy_lints/src/inherent_to_string.rs +++ b/clippy_lints/src/inherent_to_string.rs @@ -108,7 +108,7 @@ impl<'tcx> LateLintPass<'tcx> for InherentToString { if is_type_diagnostic_item(cx, return_ty(cx, impl_item.hir_id()), sym::String); // Filters instances of to_string which are required by a trait - if trait_ref_of_method(cx, impl_item.def_id).is_none(); + if trait_ref_of_method(cx, impl_item.def_id.def_id).is_none(); then { show_lint(cx, impl_item); diff --git a/clippy_lints/src/iter_not_returning_iterator.rs b/clippy_lints/src/iter_not_returning_iterator.rs index b56d87c53..2027c23d3 100644 --- a/clippy_lints/src/iter_not_returning_iterator.rs +++ b/clippy_lints/src/iter_not_returning_iterator.rs @@ -44,7 +44,7 @@ impl<'tcx> LateLintPass<'tcx> for IterNotReturningIterator { let name = item.ident.name.as_str(); if matches!(name, "iter" | "iter_mut") { if let TraitItemKind::Fn(fn_sig, _) = &item.kind { - check_sig(cx, name, fn_sig, item.def_id); + check_sig(cx, name, fn_sig, item.def_id.def_id); } } } @@ -58,7 +58,7 @@ impl<'tcx> LateLintPass<'tcx> for IterNotReturningIterator { ) { if let ImplItemKind::Fn(fn_sig, _) = &item.kind { - check_sig(cx, name, fn_sig, item.def_id); + check_sig(cx, name, fn_sig, item.def_id.def_id); } } } diff --git a/clippy_lints/src/len_zero.rs b/clippy_lints/src/len_zero.rs index 7ae8ef830..7d15dd4cb 100644 --- a/clippy_lints/src/len_zero.rs +++ b/clippy_lints/src/len_zero.rs @@ -134,7 +134,7 @@ impl<'tcx> LateLintPass<'tcx> for LenZero { if item.ident.name == sym::len; if let ImplItemKind::Fn(sig, _) = &item.kind; if sig.decl.implicit_self.has_implicit_self(); - if cx.access_levels.is_exported(item.def_id); + if cx.access_levels.is_exported(item.def_id.def_id); if matches!(sig.decl.output, FnRetTy::Return(_)); if let Some(imp) = get_parent_as_impl(cx.tcx, item.hir_id()); if imp.of_trait.is_none(); @@ -210,7 +210,7 @@ fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, trait_items } } - if cx.access_levels.is_exported(visited_trait.def_id) && trait_items.iter().any(|i| is_named_self(cx, i, sym::len)) + if cx.access_levels.is_exported(visited_trait.def_id.def_id) && trait_items.iter().any(|i| is_named_self(cx, i, sym::len)) { let mut current_and_super_traits = DefIdSet::default(); fill_trait_set(visited_trait.def_id.to_def_id(), &mut current_and_super_traits, cx); diff --git a/clippy_lints/src/lifetimes.rs b/clippy_lints/src/lifetimes.rs index 643a7cfd5..399a03187 100644 --- a/clippy_lints/src/lifetimes.rs +++ b/clippy_lints/src/lifetimes.rs @@ -102,7 +102,7 @@ impl<'tcx> LateLintPass<'tcx> for Lifetimes { fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) { if let ImplItemKind::Fn(ref sig, id) = item.kind { - let report_extra_lifetimes = trait_ref_of_method(cx, item.def_id).is_none(); + let report_extra_lifetimes = trait_ref_of_method(cx, item.def_id.def_id).is_none(); check_fn_inner( cx, sig.decl, @@ -276,7 +276,7 @@ fn could_use_elision<'tcx>( let mut checker = BodyLifetimeChecker { lifetimes_used_in_body: false, }; - checker.visit_expr(body.value); + checker.visit_expr(&body.value); if checker.lifetimes_used_in_body { return false; } diff --git a/clippy_lints/src/loops/mut_range_bound.rs b/clippy_lints/src/loops/mut_range_bound.rs index fce2d5463..be7f96e9b 100644 --- a/clippy_lints/src/loops/mut_range_bound.rs +++ b/clippy_lints/src/loops/mut_range_bound.rs @@ -69,7 +69,7 @@ fn check_for_mutation<'tcx>( ExprUseVisitor::new( &mut delegate, &infcx, - body.hir_id.owner, + body.hir_id.owner.def_id, cx.param_env, cx.typeck_results(), ) diff --git a/clippy_lints/src/manual_non_exhaustive.rs b/clippy_lints/src/manual_non_exhaustive.rs index 2b04475c7..53e7565bd 100644 --- a/clippy_lints/src/manual_non_exhaustive.rs +++ b/clippy_lints/src/manual_non_exhaustive.rs @@ -166,7 +166,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualNonExhaustiveEnum { if let Some((id, span)) = iter.next() && iter.next().is_none() { - self.potential_enums.push((item.def_id, id, item.span, span)); + self.potential_enums.push((item.def_id.def_id, id, item.span, span)); } } } diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index cdde4c54d..ddb6d1ca2 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -3250,7 +3250,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods { return; } let name = impl_item.ident.name.as_str(); - let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()); + let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()).def_id; let item = cx.tcx.hir().expect_item(parent); let self_ty = cx.tcx.type_of(item.def_id); @@ -3259,7 +3259,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods { if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind; if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next(); - let method_sig = cx.tcx.fn_sig(impl_item.def_id); + let method_sig = cx.tcx.fn_sig(impl_item.def_id.def_id); let method_sig = cx.tcx.erase_late_bound_regions(method_sig); let first_arg_ty = method_sig.inputs().iter().next(); @@ -3269,7 +3269,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods { then { // if this impl block implements a trait, lint in trait definition instead - if !implements_trait && cx.access_levels.is_exported(impl_item.def_id) { + if !implements_trait && cx.access_levels.is_exported(impl_item.def_id.def_id) { // check missing trait implementations for method_config in &TRAIT_METHODS { if name == method_config.method_name && @@ -3301,7 +3301,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods { if sig.decl.implicit_self.has_implicit_self() && !(self.avoid_breaking_exported_api - && cx.access_levels.is_exported(impl_item.def_id)) + && cx.access_levels.is_exported(impl_item.def_id.def_id)) { wrong_self_convention::check( cx, diff --git a/clippy_lints/src/missing_const_for_fn.rs b/clippy_lints/src/missing_const_for_fn.rs index bc304c081..f24b41411 100644 --- a/clippy_lints/src/missing_const_for_fn.rs +++ b/clippy_lints/src/missing_const_for_fn.rs @@ -136,7 +136,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingConstForFn { // Const fns are not allowed as methods in a trait. { - let parent = cx.tcx.hir().get_parent_item(hir_id); + let parent = cx.tcx.hir().get_parent_item(hir_id).def_id; if parent != CRATE_DEF_ID { if let hir::Node::Item(item) = cx.tcx.hir().get_by_def_id(parent) { if let hir::ItemKind::Trait(..) = &item.kind { diff --git a/clippy_lints/src/missing_doc.rs b/clippy_lints/src/missing_doc.rs index 3701fdb4a..472195566 100644 --- a/clippy_lints/src/missing_doc.rs +++ b/clippy_lints/src/missing_doc.rs @@ -131,7 +131,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { hir::ItemKind::Fn(..) => { // ignore main() if it.ident.name == sym::main { - let at_root = cx.tcx.local_parent(it.def_id) == CRATE_DEF_ID; + let at_root = cx.tcx.local_parent(it.def_id.def_id) == CRATE_DEF_ID; if at_root { return; } diff --git a/clippy_lints/src/missing_inline.rs b/clippy_lints/src/missing_inline.rs index 07bc2ca5d..9d5764ac0 100644 --- a/clippy_lints/src/missing_inline.rs +++ b/clippy_lints/src/missing_inline.rs @@ -88,7 +88,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingInline { return; } - if !cx.access_levels.is_exported(it.def_id) { + if !cx.access_levels.is_exported(it.def_id.def_id) { return; } match it.kind { @@ -142,7 +142,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingInline { } // If the item being implemented is not exported, then we don't need #[inline] - if !cx.access_levels.is_exported(impl_item.def_id) { + if !cx.access_levels.is_exported(impl_item.def_id.def_id) { return; } @@ -159,7 +159,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingInline { }; if let Some(trait_def_id) = trait_def_id { - if trait_def_id.is_local() && !cx.access_levels.is_exported(impl_item.def_id) { + if trait_def_id.is_local() && !cx.access_levels.is_exported(impl_item.def_id.def_id) { // If a trait is being implemented for an item, and the // trait is not exported, we don't need #[inline] return; diff --git a/clippy_lints/src/mut_key.rs b/clippy_lints/src/mut_key.rs index 4db103bbc..25d6ca83a 100644 --- a/clippy_lints/src/mut_key.rs +++ b/clippy_lints/src/mut_key.rs @@ -89,7 +89,7 @@ impl<'tcx> LateLintPass<'tcx> for MutableKeyType { fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'tcx>) { if let hir::ImplItemKind::Fn(ref sig, ..) = item.kind { - if trait_ref_of_method(cx, item.def_id).is_none() { + if trait_ref_of_method(cx, item.def_id.def_id).is_none() { check_sig(cx, item.hir_id(), sig.decl); } } diff --git a/clippy_lints/src/new_without_default.rs b/clippy_lints/src/new_without_default.rs index 5c45ee6d9..357a71693 100644 --- a/clippy_lints/src/new_without_default.rs +++ b/clippy_lints/src/new_without_default.rs @@ -84,7 +84,7 @@ impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault { // can't be implemented for unsafe new return; } - if cx.tcx.is_doc_hidden(impl_item.def_id) { + if cx.tcx.is_doc_hidden(impl_item.def_id.def_id) { // shouldn't be implemented when it is hidden in docs return; } @@ -96,7 +96,7 @@ impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault { if_chain! { if sig.decl.inputs.is_empty(); if name == sym::new; - if cx.access_levels.is_reachable(impl_item.def_id); + if cx.access_levels.is_reachable(impl_item.def_id.def_id); let self_def_id = cx.tcx.hir().get_parent_item(id); let self_ty = cx.tcx.type_of(self_def_id); if self_ty == return_ty(cx, id); diff --git a/clippy_lints/src/non_copy_const.rs b/clippy_lints/src/non_copy_const.rs index b15884527..616ef9e2f 100644 --- a/clippy_lints/src/non_copy_const.rs +++ b/clippy_lints/src/non_copy_const.rs @@ -286,7 +286,7 @@ impl<'tcx> LateLintPass<'tcx> for NonCopyConst { fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx ImplItem<'_>) { if let ImplItemKind::Const(hir_ty, body_id) = &impl_item.kind { - let item_def_id = cx.tcx.hir().get_parent_item(impl_item.hir_id()); + let item_def_id = cx.tcx.hir().get_parent_item(impl_item.hir_id()).def_id; let item = cx.tcx.hir().expect_item(item_def_id); match &item.kind { diff --git a/clippy_lints/src/only_used_in_recursion.rs b/clippy_lints/src/only_used_in_recursion.rs index 6217110a1..d64a9cf71 100644 --- a/clippy_lints/src/only_used_in_recursion.rs +++ b/clippy_lints/src/only_used_in_recursion.rs @@ -243,7 +243,7 @@ impl<'tcx> LateLintPass<'tcx> for OnlyUsedInRecursion { .. })) => { #[allow(trivial_casts)] - if let Some(Node::Item(item)) = get_parent_node(cx.tcx, cx.tcx.hir().local_def_id_to_hir_id(def_id)) + if let Some(Node::Item(item)) = get_parent_node(cx.tcx, def_id.into()) && let Some(trait_ref) = cx.tcx.impl_trait_ref(item.def_id) && let Some(trait_item_id) = cx.tcx.associated_item(def_id).trait_item_def_id { diff --git a/clippy_lints/src/operators/assign_op_pattern.rs b/clippy_lints/src/operators/assign_op_pattern.rs index 945a09a64..2c22c8b3d 100644 --- a/clippy_lints/src/operators/assign_op_pattern.rs +++ b/clippy_lints/src/operators/assign_op_pattern.rs @@ -28,7 +28,7 @@ pub(super) fn check<'tcx>( if_chain! { if let Some((_, lang_item)) = binop_traits(op.node); if let Ok(trait_id) = cx.tcx.lang_items().require(lang_item); - let parent_fn = cx.tcx.hir().get_parent_item(e.hir_id); + let parent_fn = cx.tcx.hir().get_parent_item(e.hir_id).def_id; if trait_ref_of_method(cx, parent_fn) .map_or(true, |t| t.path.res.def_id() != trait_id); if implements_trait(cx, ty, trait_id, &[rty.into()]); diff --git a/clippy_lints/src/pass_by_ref_or_value.rs b/clippy_lints/src/pass_by_ref_or_value.rs index 0960b050c..6b2eea489 100644 --- a/clippy_lints/src/pass_by_ref_or_value.rs +++ b/clippy_lints/src/pass_by_ref_or_value.rs @@ -261,7 +261,7 @@ impl<'tcx> LateLintPass<'tcx> for PassByRefOrValue { } if let hir::TraitItemKind::Fn(method_sig, _) = &item.kind { - self.check_poly_fn(cx, item.def_id, method_sig.decl, None); + self.check_poly_fn(cx, item.def_id.def_id, method_sig.decl, None); } } diff --git a/clippy_lints/src/redundant_pub_crate.rs b/clippy_lints/src/redundant_pub_crate.rs index 323326381..3c6ca9d98 100644 --- a/clippy_lints/src/redundant_pub_crate.rs +++ b/clippy_lints/src/redundant_pub_crate.rs @@ -46,8 +46,8 @@ impl_lint_pass!(RedundantPubCrate => [REDUNDANT_PUB_CRATE]); impl<'tcx> LateLintPass<'tcx> for RedundantPubCrate { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) { if_chain! { - if cx.tcx.visibility(item.def_id) == ty::Visibility::Restricted(CRATE_DEF_ID.to_def_id()); - if !cx.access_levels.is_exported(item.def_id) && self.is_exported.last() == Some(&false); + if cx.tcx.visibility(item.def_id.def_id) == ty::Visibility::Restricted(CRATE_DEF_ID.to_def_id()); + if !cx.access_levels.is_exported(item.def_id.def_id) && self.is_exported.last() == Some(&false); if is_not_macro_export(item); then { let span = item.span.with_hi(item.ident.span.hi()); @@ -70,7 +70,7 @@ impl<'tcx> LateLintPass<'tcx> for RedundantPubCrate { } if let ItemKind::Mod { .. } = item.kind { - self.is_exported.push(cx.access_levels.is_exported(item.def_id)); + self.is_exported.push(cx.access_levels.is_exported(item.def_id.def_id)); } } diff --git a/clippy_lints/src/return_self_not_must_use.rs b/clippy_lints/src/return_self_not_must_use.rs index 60be6bd33..16d702a38 100644 --- a/clippy_lints/src/return_self_not_must_use.rs +++ b/clippy_lints/src/return_self_not_must_use.rs @@ -128,7 +128,7 @@ impl<'tcx> LateLintPass<'tcx> for ReturnSelfNotMustUse { fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'tcx>) { if let TraitItemKind::Fn(ref sig, _) = item.kind { - check_method(cx, sig.decl, item.def_id, item.span, item.hir_id()); + check_method(cx, sig.decl, item.def_id.def_id, item.span, item.hir_id()); } } } diff --git a/clippy_lints/src/self_named_constructors.rs b/clippy_lints/src/self_named_constructors.rs index 9cea4d880..1ac538f4c 100644 --- a/clippy_lints/src/self_named_constructors.rs +++ b/clippy_lints/src/self_named_constructors.rs @@ -51,7 +51,7 @@ impl<'tcx> LateLintPass<'tcx> for SelfNamedConstructors { _ => return, } - let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()); + let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()).def_id; let item = cx.tcx.hir().expect_item(parent); let self_ty = cx.tcx.type_of(item.def_id); let ret_ty = return_ty(cx, impl_item.hir_id()); diff --git a/clippy_lints/src/suspicious_trait_impl.rs b/clippy_lints/src/suspicious_trait_impl.rs index 6add20c1f..d47ed4593 100644 --- a/clippy_lints/src/suspicious_trait_impl.rs +++ b/clippy_lints/src/suspicious_trait_impl.rs @@ -64,11 +64,11 @@ impl<'tcx> LateLintPass<'tcx> for SuspiciousImpl { // Check for more than one binary operation in the implemented function // Linting when multiple operations are involved can result in false positives - let parent_fn = cx.tcx.hir().get_parent_item(expr.hir_id); + let parent_fn = cx.tcx.hir().get_parent_item(expr.hir_id).def_id; if let hir::Node::ImplItem(impl_item) = cx.tcx.hir().get_by_def_id(parent_fn); if let hir::ImplItemKind::Fn(_, body_id) = impl_item.kind; let body = cx.tcx.hir().body(body_id); - let parent_fn = cx.tcx.hir().get_parent_item(expr.hir_id); + let parent_fn = cx.tcx.hir().get_parent_item(expr.hir_id).def_id; if let Some(trait_ref) = trait_ref_of_method(cx, parent_fn); let trait_id = trait_ref.path.res.def_id(); if ![binop_trait_id, op_assign_trait_id].contains(&trait_id); diff --git a/clippy_lints/src/transmute/utils.rs b/clippy_lints/src/transmute/utils.rs index 8bdadf244..8e90d2026 100644 --- a/clippy_lints/src/transmute/utils.rs +++ b/clippy_lints/src/transmute/utils.rs @@ -42,7 +42,7 @@ pub(super) fn can_be_expressed_as_pointer_cast<'tcx>( /// messages. This function will panic if that occurs. fn check_cast<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> Option { let hir_id = e.hir_id; - let local_def_id = hir_id.owner; + let local_def_id = hir_id.owner.def_id; Inherited::build(cx.tcx, local_def_id).enter(|inherited| { let fn_ctxt = FnCtxt::new(&inherited, cx.param_env, hir_id); diff --git a/clippy_lints/src/types/borrowed_box.rs b/clippy_lints/src/types/borrowed_box.rs index 94945b2e1..1268c2320 100644 --- a/clippy_lints/src/types/borrowed_box.rs +++ b/clippy_lints/src/types/borrowed_box.rs @@ -104,7 +104,7 @@ fn get_bounds_if_impl_trait<'tcx>(cx: &LateContext<'tcx>, qpath: &QPath<'_>, id: if let Some(Node::GenericParam(generic_param)) = cx.tcx.hir().get_if_local(did); if let GenericParamKind::Type { synthetic, .. } = generic_param.kind; if synthetic; - if let Some(generics) = cx.tcx.hir().get_generics(id.owner); + if let Some(generics) = cx.tcx.hir().get_generics(id.owner.def_id); if let Some(pred) = generics.bounds_for_param(did.expect_local()).next(); then { Some(pred.bounds) diff --git a/clippy_lints/src/types/mod.rs b/clippy_lints/src/types/mod.rs index 353a6f6b8..aca55817c 100644 --- a/clippy_lints/src/types/mod.rs +++ b/clippy_lints/src/types/mod.rs @@ -313,7 +313,7 @@ impl_lint_pass!(Types => [BOX_COLLECTION, VEC_BOX, OPTION_OPTION, LINKEDLIST, BO impl<'tcx> LateLintPass<'tcx> for Types { fn check_fn(&mut self, cx: &LateContext<'_>, _: FnKind<'_>, decl: &FnDecl<'_>, _: &Body<'_>, _: Span, id: HirId) { let is_in_trait_impl = - if let Some(hir::Node::Item(item)) = cx.tcx.hir().find_by_def_id(cx.tcx.hir().get_parent_item(id)) { + if let Some(hir::Node::Item(item)) = cx.tcx.hir().find_by_def_id(cx.tcx.hir().get_parent_item(id).def_id) { matches!(item.kind, ItemKind::Impl(hir::Impl { of_trait: Some(_), .. })) } else { false @@ -333,7 +333,7 @@ impl<'tcx> LateLintPass<'tcx> for Types { } fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { - let is_exported = cx.access_levels.is_exported(item.def_id); + let is_exported = cx.access_levels.is_exported(item.def_id.def_id); match item.kind { ItemKind::Static(ty, _, _) | ItemKind::Const(ty, _) => self.check_ty( @@ -353,7 +353,7 @@ impl<'tcx> LateLintPass<'tcx> for Types { match item.kind { ImplItemKind::Const(ty, _) => { let is_in_trait_impl = if let Some(hir::Node::Item(item)) = - cx.tcx.hir().find_by_def_id(cx.tcx.hir().get_parent_item(item.hir_id())) + cx.tcx.hir().find_by_def_id(cx.tcx.hir().get_parent_item(item.hir_id()).def_id) { matches!(item.kind, ItemKind::Impl(hir::Impl { of_trait: Some(_), .. })) } else { @@ -390,7 +390,7 @@ impl<'tcx> LateLintPass<'tcx> for Types { } fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &TraitItem<'_>) { - let is_exported = cx.access_levels.is_exported(item.def_id); + let is_exported = cx.access_levels.is_exported(item.def_id.def_id); let context = CheckTyContext { is_exported, diff --git a/clippy_lints/src/unused_self.rs b/clippy_lints/src/unused_self.rs index 51c65d898..713fe06ba 100644 --- a/clippy_lints/src/unused_self.rs +++ b/clippy_lints/src/unused_self.rs @@ -54,14 +54,14 @@ impl<'tcx> LateLintPass<'tcx> for UnusedSelf { if impl_item.span.from_expansion() { return; } - let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()); + let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()).def_id; let parent_item = cx.tcx.hir().expect_item(parent); let assoc_item = cx.tcx.associated_item(impl_item.def_id); if_chain! { if let ItemKind::Impl(Impl { of_trait: None, .. }) = parent_item.kind; if assoc_item.fn_has_self_parameter; if let ImplItemKind::Fn(.., body_id) = &impl_item.kind; - if !cx.access_levels.is_exported(impl_item.def_id) || !self.avoid_breaking_exported_api; + if !cx.access_levels.is_exported(impl_item.def_id.def_id) || !self.avoid_breaking_exported_api; let body = cx.tcx.hir().body(*body_id); if let [self_param, ..] = body.params; if !is_local_used(cx, body, self_param.pat.hir_id); diff --git a/clippy_lints/src/unwrap_in_result.rs b/clippy_lints/src/unwrap_in_result.rs index 46020adca..baa53ba66 100644 --- a/clippy_lints/src/unwrap_in_result.rs +++ b/clippy_lints/src/unwrap_in_result.rs @@ -111,7 +111,7 @@ fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_item: &'tc let body = cx.tcx.hir().body(body_id); let mut fpu = FindExpectUnwrap { lcx: cx, - typeck_results: cx.tcx.typeck(impl_item.def_id), + typeck_results: cx.tcx.typeck(impl_item.def_id.def_id), result: Vec::new(), }; fpu.visit_expr(body.value); diff --git a/clippy_lints/src/upper_case_acronyms.rs b/clippy_lints/src/upper_case_acronyms.rs index 02bf09ed5..2c71f35d4 100644 --- a/clippy_lints/src/upper_case_acronyms.rs +++ b/clippy_lints/src/upper_case_acronyms.rs @@ -105,7 +105,7 @@ impl LateLintPass<'_> for UpperCaseAcronyms { fn check_item(&mut self, cx: &LateContext<'_>, it: &Item<'_>) { // do not lint public items or in macros if in_external_macro(cx.sess(), it.span) - || (self.avoid_breaking_exported_api && cx.access_levels.is_exported(it.def_id)) + || (self.avoid_breaking_exported_api && cx.access_levels.is_exported(it.def_id.def_id)) { return; } diff --git a/clippy_lints/src/use_self.rs b/clippy_lints/src/use_self.rs index 44ab9bca7..ce51cb693 100644 --- a/clippy_lints/src/use_self.rs +++ b/clippy_lints/src/use_self.rs @@ -106,7 +106,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { if !is_from_proc_macro(cx, item); // expensive, should be last check then { StackItem::Check { - impl_id: item.def_id, + impl_id: item.def_id.def_id, in_body: 0, types_to_skip: std::iter::once(self_ty.hir_id).collect(), } diff --git a/clippy_lints/src/utils/author.rs b/clippy_lints/src/utils/author.rs index 4003fff27..1df3135c9 100644 --- a/clippy_lints/src/utils/author.rs +++ b/clippy_lints/src/utils/author.rs @@ -140,7 +140,7 @@ impl<'tcx> LateLintPass<'tcx> for Author { fn check_item(cx: &LateContext<'_>, hir_id: HirId) { let hir = cx.tcx.hir(); - if let Some(body_id) = hir.maybe_body_owned_by(hir_id.expect_owner()) { + if let Some(body_id) = hir.maybe_body_owned_by(hir_id.expect_owner().def_id) { check_node(cx, hir_id, |v| { v.expr(&v.bind("expr", hir.body(body_id).value)); }); diff --git a/clippy_lints/src/wildcard_imports.rs b/clippy_lints/src/wildcard_imports.rs index 5418eca38..2604b1ee7 100644 --- a/clippy_lints/src/wildcard_imports.rs +++ b/clippy_lints/src/wildcard_imports.rs @@ -120,14 +120,14 @@ impl LateLintPass<'_> for WildcardImports { if is_test_module_or_function(cx.tcx, item) { self.test_modules_deep = self.test_modules_deep.saturating_add(1); } - let module = cx.tcx.parent_module_from_def_id(item.def_id); - if cx.tcx.visibility(item.def_id) != ty::Visibility::Restricted(module.to_def_id()) { + let module = cx.tcx.parent_module_from_def_id(item.def_id.def_id); + if cx.tcx.visibility(item.def_id.def_id) != ty::Visibility::Restricted(module.to_def_id()) { return; } if_chain! { if let ItemKind::Use(use_path, UseKind::Glob) = &item.kind; if self.warn_on_all || !self.check_exceptions(item, use_path.segments); - let used_imports = cx.tcx.names_imported_by_glob_use(item.def_id); + let used_imports = cx.tcx.names_imported_by_glob_use(item.def_id.def_id); if !used_imports.is_empty(); // Already handled by `unused_imports` then { let mut applicability = Applicability::MachineApplicable; diff --git a/clippy_lints/src/zero_sized_map_values.rs b/clippy_lints/src/zero_sized_map_values.rs index 8dc43c0e2..386f3c527 100644 --- a/clippy_lints/src/zero_sized_map_values.rs +++ b/clippy_lints/src/zero_sized_map_values.rs @@ -72,7 +72,7 @@ fn in_trait_impl(cx: &LateContext<'_>, hir_id: HirId) -> bool { let second_parent_id = cx .tcx .hir() - .get_parent_item(cx.tcx.hir().local_def_id_to_hir_id(parent_id)); + .get_parent_item(parent_id.into()).def_id; if let Some(Node::Item(item)) = cx.tcx.hir().find_by_def_id(second_parent_id) { if let ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind { return true; diff --git a/clippy_utils/src/lib.rs b/clippy_utils/src/lib.rs index 62da850a1..9343cf457 100644 --- a/clippy_utils/src/lib.rs +++ b/clippy_utils/src/lib.rs @@ -78,7 +78,7 @@ use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::unhash::UnhashMap; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_ID}; +use rustc_hir::def_id::{CrateNum, DefId, LocalDefId}; use rustc_hir::hir_id::{HirIdMap, HirIdSet}; use rustc_hir::intravisit::{walk_expr, FnKind, Visitor}; use rustc_hir::LangItem::{OptionNone, ResultErr, ResultOk}; @@ -212,7 +212,7 @@ pub fn find_binding_init<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option< /// } /// ``` pub fn in_constant(cx: &LateContext<'_>, id: HirId) -> bool { - let parent_id = cx.tcx.hir().get_parent_item(id); + let parent_id = cx.tcx.hir().get_parent_item(id).def_id; match cx.tcx.hir().get_by_def_id(parent_id) { Node::Item(&Item { kind: ItemKind::Const(..) | ItemKind::Static(..), @@ -597,8 +597,8 @@ pub fn trait_ref_of_method<'tcx>(cx: &LateContext<'tcx>, def_id: LocalDefId) -> let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id); let parent_impl = cx.tcx.hir().get_parent_item(hir_id); if_chain! { - if parent_impl != CRATE_DEF_ID; - if let hir::Node::Item(item) = cx.tcx.hir().get_by_def_id(parent_impl); + if parent_impl != hir::CRATE_OWNER_ID; + if let hir::Node::Item(item) = cx.tcx.hir().get_by_def_id(parent_impl.def_id); if let hir::ItemKind::Impl(impl_) = &item.kind; then { return impl_.of_trait.as_ref(); @@ -1104,7 +1104,7 @@ pub fn is_in_panic_handler(cx: &LateContext<'_>, e: &Expr<'_>) -> bool { /// Gets the name of the item the expression is in, if available. pub fn get_item_name(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option { - let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id); + let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id).def_id; match cx.tcx.hir().find_by_def_id(parent_id) { Some( Node::Item(Item { ident, .. }) @@ -1648,7 +1648,7 @@ pub fn any_parent_has_attr(tcx: TyCtxt<'_>, node: HirId, symbol: Symbol) -> bool return true; } prev_enclosing_node = Some(enclosing_node); - enclosing_node = map.local_def_id_to_hir_id(map.get_parent_item(enclosing_node)); + enclosing_node = map.get_parent_item(enclosing_node).into(); } false diff --git a/clippy_utils/src/usage.rs b/clippy_utils/src/usage.rs index 3af5dfb62..a7c08839f 100644 --- a/clippy_utils/src/usage.rs +++ b/clippy_utils/src/usage.rs @@ -21,7 +21,7 @@ pub fn mutated_variables<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> ExprUseVisitor::new( &mut delegate, &infcx, - expr.hir_id.owner, + expr.hir_id.owner.def_id, cx.param_env, cx.typeck_results(), ) From 06568fd6c707b878ae69ede1532b82c7ba47e07e Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Tue, 20 Sep 2022 15:41:42 +0200 Subject: [PATCH 29/34] remove cfg(bootstrap) --- clippy_dev/src/lib.rs | 1 - clippy_lints/src/lib.rs | 1 - clippy_utils/src/lib.rs | 1 - 3 files changed, 3 deletions(-) diff --git a/clippy_dev/src/lib.rs b/clippy_dev/src/lib.rs index 54c7456a2..80bb83af4 100644 --- a/clippy_dev/src/lib.rs +++ b/clippy_dev/src/lib.rs @@ -1,5 +1,4 @@ #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(once_cell)] #![feature(rustc_private)] #![cfg_attr(feature = "deny-warnings", deny(warnings))] diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index 298566cb5..00bf6445c 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -5,7 +5,6 @@ #![feature(drain_filter)] #![feature(iter_intersperse)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(lint_reasons)] #![feature(never_type)] #![feature(once_cell)] diff --git a/clippy_utils/src/lib.rs b/clippy_utils/src/lib.rs index 9343cf457..b1abd3b04 100644 --- a/clippy_utils/src/lib.rs +++ b/clippy_utils/src/lib.rs @@ -3,7 +3,6 @@ #![feature(control_flow_enum)] #![feature(let_chains)] #![feature(lint_reasons)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(once_cell)] #![feature(rustc_private)] #![recursion_limit = "512"] From e5ce6d18df883f593e72f7958bebdc3ebcdbe85e Mon Sep 17 00:00:00 2001 From: lcnr Date: Mon, 26 Sep 2022 13:00:29 +0200 Subject: [PATCH 30/34] rustc_typeck to rustc_hir_analysis --- clippy_lints/src/default_union_representation.rs | 2 +- clippy_lints/src/escape.rs | 4 ++-- clippy_lints/src/implicit_hasher.rs | 2 +- clippy_lints/src/large_const_arrays.rs | 2 +- clippy_lints/src/lib.rs | 2 +- clippy_lints/src/loops/mut_range_bound.rs | 4 ++-- clippy_lints/src/loops/utils.rs | 2 +- clippy_lints/src/matches/needless_match.rs | 2 +- clippy_lints/src/methods/mod.rs | 2 +- clippy_lints/src/methods/unnecessary_to_owned.rs | 2 +- clippy_lints/src/missing_const_for_fn.rs | 2 +- clippy_lints/src/needless_pass_by_value.rs | 4 ++-- clippy_lints/src/non_copy_const.rs | 2 +- clippy_lints/src/operators/assign_op_pattern.rs | 2 +- clippy_lints/src/transmute/utils.rs | 2 +- clippy_lints/src/types/redundant_allocation.rs | 2 +- clippy_lints/src/types/vec_box.rs | 2 +- clippy_lints/src/use_self.rs | 2 +- clippy_lints/src/utils/internal_lints.rs | 2 +- clippy_lints/src/zero_sized_map_values.rs | 2 +- clippy_utils/src/lib.rs | 4 ++-- clippy_utils/src/sugg.rs | 4 ++-- clippy_utils/src/usage.rs | 4 ++-- tests/ui/transmutes_expressible_as_ptr_casts.fixed | 2 +- tests/ui/transmutes_expressible_as_ptr_casts.rs | 2 +- 25 files changed, 31 insertions(+), 31 deletions(-) diff --git a/clippy_lints/src/default_union_representation.rs b/clippy_lints/src/default_union_representation.rs index d559ad423..3905a6c2e 100644 --- a/clippy_lints/src/default_union_representation.rs +++ b/clippy_lints/src/default_union_representation.rs @@ -4,7 +4,7 @@ use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::layout::LayoutOf; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::sym; -use rustc_typeck::hir_ty_to_ty; +use rustc_hir_analysis::hir_ty_to_ty; declare_clippy_lint! { /// ### What it does diff --git a/clippy_lints/src/escape.rs b/clippy_lints/src/escape.rs index a6ddb26e2..8ccc96964 100644 --- a/clippy_lints/src/escape.rs +++ b/clippy_lints/src/escape.rs @@ -10,7 +10,7 @@ use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::source_map::Span; use rustc_span::symbol::kw; use rustc_target::spec::abi::Abi; -use rustc_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; +use rustc_hir_analysis::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; #[derive(Copy, Clone)] pub struct BoxedLocal { @@ -177,7 +177,7 @@ impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> { } } - fn fake_read(&mut self, _: &rustc_typeck::expr_use_visitor::PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {} + fn fake_read(&mut self, _: &rustc_hir_analysis::expr_use_visitor::PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {} } impl<'a, 'tcx> EscapeDelegate<'a, 'tcx> { diff --git a/clippy_lints/src/implicit_hasher.rs b/clippy_lints/src/implicit_hasher.rs index 804fdc2da..a920c3bba 100644 --- a/clippy_lints/src/implicit_hasher.rs +++ b/clippy_lints/src/implicit_hasher.rs @@ -12,7 +12,7 @@ use rustc_middle::ty::{Ty, TypeckResults}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::source_map::Span; use rustc_span::symbol::sym; -use rustc_typeck::hir_ty_to_ty; +use rustc_hir_analysis::hir_ty_to_ty; use if_chain::if_chain; diff --git a/clippy_lints/src/large_const_arrays.rs b/clippy_lints/src/large_const_arrays.rs index 984c5cd4e..d6eb53ae2 100644 --- a/clippy_lints/src/large_const_arrays.rs +++ b/clippy_lints/src/large_const_arrays.rs @@ -7,7 +7,7 @@ use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::{self, ConstKind}; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::{BytePos, Pos, Span}; -use rustc_typeck::hir_ty_to_ty; +use rustc_hir_analysis::hir_ty_to_ty; declare_clippy_lint! { /// ### What it does diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index 00bf6445c..c3db194c4 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -43,7 +43,7 @@ extern crate rustc_session; extern crate rustc_span; extern crate rustc_target; extern crate rustc_trait_selection; -extern crate rustc_typeck; +extern crate rustc_hir_analysis; #[macro_use] extern crate clippy_utils; diff --git a/clippy_lints/src/loops/mut_range_bound.rs b/clippy_lints/src/loops/mut_range_bound.rs index be7f96e9b..6d585c2e4 100644 --- a/clippy_lints/src/loops/mut_range_bound.rs +++ b/clippy_lints/src/loops/mut_range_bound.rs @@ -8,7 +8,7 @@ use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::LateContext; use rustc_middle::{mir::FakeReadCause, ty}; use rustc_span::source_map::Span; -use rustc_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; +use rustc_hir_analysis::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; pub(super) fn check(cx: &LateContext<'_>, arg: &Expr<'_>, body: &Expr<'_>) { if_chain! { @@ -114,7 +114,7 @@ impl<'tcx> Delegate<'tcx> for MutatePairDelegate<'_, 'tcx> { } } - fn fake_read(&mut self, _: &rustc_typeck::expr_use_visitor::PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {} + fn fake_read(&mut self, _: &rustc_hir_analysis::expr_use_visitor::PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {} } impl MutatePairDelegate<'_, '_> { diff --git a/clippy_lints/src/loops/utils.rs b/clippy_lints/src/loops/utils.rs index 4801a84eb..f1f58db80 100644 --- a/clippy_lints/src/loops/utils.rs +++ b/clippy_lints/src/loops/utils.rs @@ -10,7 +10,7 @@ use rustc_middle::hir::nested_filter; use rustc_middle::ty::{self, Ty}; use rustc_span::source_map::Spanned; use rustc_span::symbol::{sym, Symbol}; -use rustc_typeck::hir_ty_to_ty; +use rustc_hir_analysis::hir_ty_to_ty; use std::iter::Iterator; #[derive(Debug, PartialEq, Eq)] diff --git a/clippy_lints/src/matches/needless_match.rs b/clippy_lints/src/matches/needless_match.rs index 634eef82e..58ea43e69 100644 --- a/clippy_lints/src/matches/needless_match.rs +++ b/clippy_lints/src/matches/needless_match.rs @@ -11,7 +11,7 @@ use rustc_hir::LangItem::OptionNone; use rustc_hir::{Arm, BindingAnnotation, ByRef, Expr, ExprKind, FnRetTy, Guard, Node, Pat, PatKind, Path, QPath}; use rustc_lint::LateContext; use rustc_span::sym; -use rustc_typeck::hir_ty_to_ty; +use rustc_hir_analysis::hir_ty_to_ty; pub(crate) fn check_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) { if arms.len() > 1 && expr_ty_matches_p_ty(cx, ex, expr) && check_all_arms(cx, ex, arms) { diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index ddb6d1ca2..428a354ec 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -115,7 +115,7 @@ use rustc_middle::ty::{self, TraitRef, Ty}; use rustc_semver::RustcVersion; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::{sym, Span}; -use rustc_typeck::hir_ty_to_ty; +use rustc_hir_analysis::hir_ty_to_ty; declare_clippy_lint! { /// ### What it does diff --git a/clippy_lints/src/methods/unnecessary_to_owned.rs b/clippy_lints/src/methods/unnecessary_to_owned.rs index 79d784c34..559f32a56 100644 --- a/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/clippy_lints/src/methods/unnecessary_to_owned.rs @@ -18,7 +18,7 @@ use rustc_middle::ty::{self, ParamTy, PredicateKind, ProjectionPredicate, TraitP use rustc_semver::RustcVersion; use rustc_span::{sym, Symbol}; use rustc_trait_selection::traits::{query::evaluate_obligation::InferCtxtExt as _, Obligation, ObligationCause}; -use rustc_typeck::check::{FnCtxt, Inherited}; +use rustc_hir_analysis::check::{FnCtxt, Inherited}; use std::cmp::max; use super::UNNECESSARY_TO_OWNED; diff --git a/clippy_lints/src/missing_const_for_fn.rs b/clippy_lints/src/missing_const_for_fn.rs index f24b41411..00376f0d7 100644 --- a/clippy_lints/src/missing_const_for_fn.rs +++ b/clippy_lints/src/missing_const_for_fn.rs @@ -13,7 +13,7 @@ use rustc_middle::lint::in_external_macro; use rustc_semver::RustcVersion; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::Span; -use rustc_typeck::hir_ty_to_ty; +use rustc_hir_analysis::hir_ty_to_ty; declare_clippy_lint! { /// ### What it does diff --git a/clippy_lints/src/needless_pass_by_value.rs b/clippy_lints/src/needless_pass_by_value.rs index 060037ed4..4f4687243 100644 --- a/clippy_lints/src/needless_pass_by_value.rs +++ b/clippy_lints/src/needless_pass_by_value.rs @@ -22,7 +22,7 @@ use rustc_span::{sym, Span}; use rustc_target::spec::abi::Abi; use rustc_trait_selection::traits; use rustc_trait_selection::traits::misc::can_type_implement_copy; -use rustc_typeck::expr_use_visitor as euv; +use rustc_hir_analysis::expr_use_visitor as euv; use std::borrow::Cow; declare_clippy_lint! { @@ -341,5 +341,5 @@ impl<'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt { fn mutate(&mut self, _: &euv::PlaceWithHirId<'tcx>, _: HirId) {} - fn fake_read(&mut self, _: &rustc_typeck::expr_use_visitor::PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {} + fn fake_read(&mut self, _: &rustc_hir_analysis::expr_use_visitor::PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {} } diff --git a/clippy_lints/src/non_copy_const.rs b/clippy_lints/src/non_copy_const.rs index 616ef9e2f..48ff737da 100644 --- a/clippy_lints/src/non_copy_const.rs +++ b/clippy_lints/src/non_copy_const.rs @@ -20,7 +20,7 @@ use rustc_middle::ty::adjustment::Adjust; use rustc_middle::ty::{self, Ty}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::{sym, InnerSpan, Span, DUMMY_SP}; -use rustc_typeck::hir_ty_to_ty; +use rustc_hir_analysis::hir_ty_to_ty; // FIXME: this is a correctness problem but there's no suitable // warn-by-default category. diff --git a/clippy_lints/src/operators/assign_op_pattern.rs b/clippy_lints/src/operators/assign_op_pattern.rs index 2c22c8b3d..f134c6c4c 100644 --- a/clippy_lints/src/operators/assign_op_pattern.rs +++ b/clippy_lints/src/operators/assign_op_pattern.rs @@ -11,7 +11,7 @@ use rustc_lint::LateContext; use rustc_middle::mir::FakeReadCause; use rustc_middle::ty::BorrowKind; use rustc_trait_selection::infer::TyCtxtInferExt; -use rustc_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; +use rustc_hir_analysis::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; use super::ASSIGN_OP_PATTERN; diff --git a/clippy_lints/src/transmute/utils.rs b/clippy_lints/src/transmute/utils.rs index 8e90d2026..fdf847bf4 100644 --- a/clippy_lints/src/transmute/utils.rs +++ b/clippy_lints/src/transmute/utils.rs @@ -2,7 +2,7 @@ use rustc_hir::Expr; use rustc_lint::LateContext; use rustc_middle::ty::{cast::CastKind, Ty}; use rustc_span::DUMMY_SP; -use rustc_typeck::check::{cast::{self, CastCheckResult}, FnCtxt, Inherited}; +use rustc_hir_analysis::check::{cast::{self, CastCheckResult}, FnCtxt, Inherited}; // check if the component types of the transmuted collection and the result have different ABI, // size or alignment diff --git a/clippy_lints/src/types/redundant_allocation.rs b/clippy_lints/src/types/redundant_allocation.rs index a1312fcda..d81c5c838 100644 --- a/clippy_lints/src/types/redundant_allocation.rs +++ b/clippy_lints/src/types/redundant_allocation.rs @@ -5,7 +5,7 @@ use rustc_errors::Applicability; use rustc_hir::{self as hir, def_id::DefId, QPath, TyKind}; use rustc_lint::LateContext; use rustc_span::symbol::sym; -use rustc_typeck::hir_ty_to_ty; +use rustc_hir_analysis::hir_ty_to_ty; use super::{utils, REDUNDANT_ALLOCATION}; diff --git a/clippy_lints/src/types/vec_box.rs b/clippy_lints/src/types/vec_box.rs index b2f536ca7..236f99557 100644 --- a/clippy_lints/src/types/vec_box.rs +++ b/clippy_lints/src/types/vec_box.rs @@ -8,7 +8,7 @@ use rustc_lint::LateContext; use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::TypeVisitable; use rustc_span::symbol::sym; -use rustc_typeck::hir_ty_to_ty; +use rustc_hir_analysis::hir_ty_to_ty; use super::VEC_BOX; diff --git a/clippy_lints/src/use_self.rs b/clippy_lints/src/use_self.rs index ce51cb693..6a767967e 100644 --- a/clippy_lints/src/use_self.rs +++ b/clippy_lints/src/use_self.rs @@ -16,7 +16,7 @@ use rustc_lint::{LateContext, LateLintPass}; use rustc_semver::RustcVersion; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::Span; -use rustc_typeck::hir_ty_to_ty; +use rustc_hir_analysis::hir_ty_to_ty; declare_clippy_lint! { /// ### What it does diff --git a/clippy_lints/src/utils/internal_lints.rs b/clippy_lints/src/utils/internal_lints.rs index 17d9a0418..78c036186 100644 --- a/clippy_lints/src/utils/internal_lints.rs +++ b/clippy_lints/src/utils/internal_lints.rs @@ -32,7 +32,7 @@ use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass}; use rustc_span::source_map::Spanned; use rustc_span::symbol::Symbol; use rustc_span::{sym, BytePos, Span}; -use rustc_typeck::hir_ty_to_ty; +use rustc_hir_analysis::hir_ty_to_ty; use std::borrow::{Borrow, Cow}; diff --git a/clippy_lints/src/zero_sized_map_values.rs b/clippy_lints/src/zero_sized_map_values.rs index 386f3c527..703ba2ef4 100644 --- a/clippy_lints/src/zero_sized_map_values.rs +++ b/clippy_lints/src/zero_sized_map_values.rs @@ -7,7 +7,7 @@ use rustc_middle::ty::layout::LayoutOf as _; use rustc_middle::ty::{Adt, Ty, TypeVisitable}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::sym; -use rustc_typeck::hir_ty_to_ty; +use rustc_hir_analysis::hir_ty_to_ty; declare_clippy_lint! { /// ### What it does diff --git a/clippy_utils/src/lib.rs b/clippy_utils/src/lib.rs index b1abd3b04..627d6b519 100644 --- a/clippy_utils/src/lib.rs +++ b/clippy_utils/src/lib.rs @@ -32,7 +32,7 @@ extern crate rustc_session; extern crate rustc_span; extern crate rustc_target; extern crate rustc_trait_selection; -extern crate rustc_typeck; +extern crate rustc_hir_analysis; #[macro_use] pub mod sym_helper; @@ -1386,7 +1386,7 @@ pub fn is_integer_literal(expr: &Expr<'_>, value: u128) -> bool { /// Examples of coercions can be found in the Nomicon at /// . /// -/// See `rustc_middle::ty::adjustment::Adjustment` and `rustc_typeck::check::coercion` for more +/// See `rustc_middle::ty::adjustment::Adjustment` and `rustc_hir_analysis::check::coercion` for more /// information on adjustments and coercions. pub fn is_adjusted(cx: &LateContext<'_>, e: &Expr<'_>) -> bool { cx.typeck_results().adjustments().get(e.hir_id).is_some() diff --git a/clippy_utils/src/sugg.rs b/clippy_utils/src/sugg.rs index f08275a4a..e53c40e95 100644 --- a/clippy_utils/src/sugg.rs +++ b/clippy_utils/src/sugg.rs @@ -16,7 +16,7 @@ use rustc_middle::hir::place::ProjectionKind; use rustc_middle::mir::{FakeReadCause, Mutability}; use rustc_middle::ty; use rustc_span::source_map::{BytePos, CharPos, Pos, Span, SyntaxContext}; -use rustc_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; +use rustc_hir_analysis::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; use std::borrow::Cow; use std::fmt::{Display, Write as _}; use std::ops::{Add, Neg, Not, Sub}; @@ -1056,7 +1056,7 @@ impl<'tcx> Delegate<'tcx> for DerefDelegate<'_, 'tcx> { fn mutate(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {} - fn fake_read(&mut self, _: &rustc_typeck::expr_use_visitor::PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {} + fn fake_read(&mut self, _: &rustc_hir_analysis::expr_use_visitor::PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {} } #[cfg(test)] diff --git a/clippy_utils/src/usage.rs b/clippy_utils/src/usage.rs index a7c08839f..76bfec757 100644 --- a/clippy_utils/src/usage.rs +++ b/clippy_utils/src/usage.rs @@ -9,7 +9,7 @@ use rustc_lint::LateContext; use rustc_middle::hir::nested_filter; use rustc_middle::mir::FakeReadCause; use rustc_middle::ty; -use rustc_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; +use rustc_hir_analysis::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; /// Returns a set of mutated local variable IDs, or `None` if mutations could not be determined. pub fn mutated_variables<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> Option { @@ -73,7 +73,7 @@ impl<'tcx> Delegate<'tcx> for MutVarsDelegate { self.update(cmt); } - fn fake_read(&mut self, _: &rustc_typeck::expr_use_visitor::PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {} + fn fake_read(&mut self, _: &rustc_hir_analysis::expr_use_visitor::PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {} } pub struct ParamBindingIdCollector { diff --git a/tests/ui/transmutes_expressible_as_ptr_casts.fixed b/tests/ui/transmutes_expressible_as_ptr_casts.fixed index 539239fc1..7263abac1 100644 --- a/tests/ui/transmutes_expressible_as_ptr_casts.fixed +++ b/tests/ui/transmutes_expressible_as_ptr_casts.fixed @@ -8,7 +8,7 @@ use std::mem::{size_of, transmute}; -// rustc_typeck::check::cast contains documentation about when a cast `e as U` is +// rustc_hir_analysis::check::cast contains documentation about when a cast `e as U` is // valid, which we quote from below. fn main() { // We should see an error message for each transmute, and no error messages for diff --git a/tests/ui/transmutes_expressible_as_ptr_casts.rs b/tests/ui/transmutes_expressible_as_ptr_casts.rs index b9e446dc8..d8e4421d4 100644 --- a/tests/ui/transmutes_expressible_as_ptr_casts.rs +++ b/tests/ui/transmutes_expressible_as_ptr_casts.rs @@ -8,7 +8,7 @@ use std::mem::{size_of, transmute}; -// rustc_typeck::check::cast contains documentation about when a cast `e as U` is +// rustc_hir_analysis::check::cast contains documentation about when a cast `e as U` is // valid, which we quote from below. fn main() { // We should see an error message for each transmute, and no error messages for From 458e83291db2532fec8877c74aca872a35353328 Mon Sep 17 00:00:00 2001 From: Philipp Krones Date: Wed, 28 Sep 2022 14:27:50 +0200 Subject: [PATCH 31/34] Bump Clippy version -> 0.1.66 --- Cargo.toml | 2 +- clippy_lints/Cargo.toml | 2 +- clippy_utils/Cargo.toml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5e960fdbc..b1bec0c46 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "clippy" -version = "0.1.65" +version = "0.1.66" description = "A bunch of helpful lints to avoid common pitfalls in Rust" repository = "https://github.com/rust-lang/rust-clippy" readme = "README.md" diff --git a/clippy_lints/Cargo.toml b/clippy_lints/Cargo.toml index badd39130..1ff976f48 100644 --- a/clippy_lints/Cargo.toml +++ b/clippy_lints/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "clippy_lints" -version = "0.1.65" +version = "0.1.66" description = "A bunch of helpful lints to avoid common pitfalls in Rust" repository = "https://github.com/rust-lang/rust-clippy" readme = "README.md" diff --git a/clippy_utils/Cargo.toml b/clippy_utils/Cargo.toml index c36bca065..83fee7bb3 100644 --- a/clippy_utils/Cargo.toml +++ b/clippy_utils/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "clippy_utils" -version = "0.1.65" +version = "0.1.66" edition = "2021" publish = false From 579791178de9092be554d3751401fd58181a16c0 Mon Sep 17 00:00:00 2001 From: Philipp Krones Date: Wed, 28 Sep 2022 14:28:03 +0200 Subject: [PATCH 32/34] Bump nightly version -> 2022-09-29 --- rust-toolchain | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust-toolchain b/rust-toolchain index b6976366d..423d6425e 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2022-09-08" +channel = "nightly-2022-09-29" components = ["cargo", "llvm-tools-preview", "rust-src", "rust-std", "rustc", "rustc-dev", "rustfmt"] From 67af127f243e5a3abcdf95f395b1029560a63ac1 Mon Sep 17 00:00:00 2001 From: Philipp Krones Date: Wed, 28 Sep 2022 14:31:29 +0200 Subject: [PATCH 33/34] Fix dogfood --- clippy_lints/src/equatable_if_let.rs | 2 +- clippy_lints/src/lifetimes.rs | 2 +- clippy_lints/src/matches/redundant_pattern_match.rs | 12 ++++++------ clippy_lints/src/ptr.rs | 2 +- clippy_lints/src/types/mod.rs | 2 +- clippy_utils/src/hir_utils.rs | 4 ++-- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/clippy_lints/src/equatable_if_let.rs b/clippy_lints/src/equatable_if_let.rs index f5aa0dcf9..b40cb7cdd 100644 --- a/clippy_lints/src/equatable_if_let.rs +++ b/clippy_lints/src/equatable_if_let.rs @@ -51,7 +51,7 @@ fn unary_pattern(pat: &Pat<'_>) -> bool { false }, PatKind::Struct(_, a, etc) => !etc && a.iter().all(|x| unary_pattern(x.pat)), - PatKind::Tuple(a, etc) | PatKind::TupleStruct(_, a, etc) => !etc.as_opt_usize().is_some() && array_rec(a), + PatKind::Tuple(a, etc) | PatKind::TupleStruct(_, a, etc) => etc.as_opt_usize().is_none() && array_rec(a), PatKind::Ref(x, _) | PatKind::Box(x) => unary_pattern(x), PatKind::Path(_) | PatKind::Lit(_) => true, } diff --git a/clippy_lints/src/lifetimes.rs b/clippy_lints/src/lifetimes.rs index aef253303..13878eda0 100644 --- a/clippy_lints/src/lifetimes.rs +++ b/clippy_lints/src/lifetimes.rs @@ -461,7 +461,7 @@ impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> { sub_visitor.visit_fn_decl(decl); self.nested_elision_site_lts.append(&mut sub_visitor.all_lts()); }, - TyKind::TraitObject(bounds, ref lt, _) => { + TyKind::TraitObject(bounds, lt, _) => { if !lt.is_elided() { self.unelided_trait_object_lifetime = true; } diff --git a/clippy_lints/src/matches/redundant_pattern_match.rs b/clippy_lints/src/matches/redundant_pattern_match.rs index 11495cca9..6d6aa43df 100644 --- a/clippy_lints/src/matches/redundant_pattern_match.rs +++ b/clippy_lints/src/matches/redundant_pattern_match.rs @@ -308,15 +308,15 @@ fn find_good_method_for_match<'a>( should_be_left: &'a str, should_be_right: &'a str, ) -> Option<&'a str> { - let pat_left = arms[0].pat; - let pat_right = arms[1].pat; + let first_pat = arms[0].pat; + let second_pat = arms[1].pat; - let body_node_pair = if (is_pat_variant(cx, pat_left, path_left, expected_item_left)) - && (is_pat_variant(cx, pat_right, path_right, expected_item_right)) + let body_node_pair = if (is_pat_variant(cx, first_pat, path_left, expected_item_left)) + && (is_pat_variant(cx, second_pat, path_right, expected_item_right)) { (&arms[0].body.kind, &arms[1].body.kind) - } else if (is_pat_variant(cx, pat_left, path_left, expected_item_right)) - && (is_pat_variant(cx, pat_right, path_right, expected_item_left)) + } else if (is_pat_variant(cx, first_pat, path_left, expected_item_right)) + && (is_pat_variant(cx, second_pat, path_right, expected_item_left)) { (&arms[1].body.kind, &arms[0].body.kind) } else { diff --git a/clippy_lints/src/ptr.rs b/clippy_lints/src/ptr.rs index 85e0710eb..d296a150b 100644 --- a/clippy_lints/src/ptr.rs +++ b/clippy_lints/src/ptr.rs @@ -669,7 +669,7 @@ fn check_ptr_arg_usage<'tcx>(cx: &LateContext<'tcx>, body: &'tcx Body<'_>, args: } fn get_rptr_lm<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> Option<(&'tcx Lifetime, Mutability, Span)> { - if let TyKind::Rptr(ref lt, ref m) = ty.kind { + if let TyKind::Rptr(lt, ref m) = ty.kind { Some((lt, m.mutbl, ty.span)) } else { None diff --git a/clippy_lints/src/types/mod.rs b/clippy_lints/src/types/mod.rs index b81d2c1cb..79c31efb9 100644 --- a/clippy_lints/src/types/mod.rs +++ b/clippy_lints/src/types/mod.rs @@ -537,7 +537,7 @@ impl Types { QPath::LangItem(..) => {}, } }, - TyKind::Rptr(ref lt, ref mut_ty) => { + TyKind::Rptr(lt, ref mut_ty) => { context.is_nested_call = true; if !borrowed_box::check(cx, hir_ty, lt, mut_ty) { self.check_ty(cx, mut_ty.ty, context); diff --git a/clippy_utils/src/hir_utils.rs b/clippy_utils/src/hir_utils.rs index 7212d9cd7..cf24ec8b6 100644 --- a/clippy_utils/src/hir_utils.rs +++ b/clippy_utils/src/hir_utils.rs @@ -962,7 +962,7 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { mut_ty.mutbl.hash(&mut self.s); }, TyKind::Rptr(lifetime, ref mut_ty) => { - self.hash_lifetime(*lifetime); + self.hash_lifetime(lifetime); self.hash_ty(mut_ty.ty); mut_ty.mutbl.hash(&mut self.s); }, @@ -992,7 +992,7 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { in_trait.hash(&mut self.s); }, TyKind::TraitObject(_, lifetime, _) => { - self.hash_lifetime(*lifetime); + self.hash_lifetime(lifetime); }, TyKind::Typeof(anon_const) => { self.hash_body(anon_const.body); From 924c1ce97d33f75d6e9e92df1c523abdc7d90f02 Mon Sep 17 00:00:00 2001 From: Philipp Krones Date: Wed, 28 Sep 2022 14:36:56 +0200 Subject: [PATCH 34/34] Update lints after sync --- src/docs/arithmetic_side_effects.txt | 2 +- src/docs/similar_names.txt | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/docs/arithmetic_side_effects.txt b/src/docs/arithmetic_side_effects.txt index b8c087252..4ae8bce88 100644 --- a/src/docs/arithmetic_side_effects.txt +++ b/src/docs/arithmetic_side_effects.txt @@ -30,4 +30,4 @@ let _n = Decimal::MAX + Decimal::MAX; ``` ### Allowed types -Custom allowed types can be specified through the "arithmetic-side-effects-allowed" filter. +Custom allowed types can be specified through the "arithmetic-side-effects-allowed" filter. \ No newline at end of file diff --git a/src/docs/similar_names.txt b/src/docs/similar_names.txt index 13aca9c0b..f9eff21b6 100644 --- a/src/docs/similar_names.txt +++ b/src/docs/similar_names.txt @@ -1,6 +1,10 @@ ### What it does Checks for names that are very similar and thus confusing. +Note: this lint looks for similar names throughout each +scope. To allow it, you need to allow it on the scope +level, not on the name that is reported. + ### Why is this bad? It's hard to distinguish between names that differ only by a single character.