--- /dev/null
- [c2c07fa...master](https://github.com/rust-lang/rust-clippy/compare/c2c07fa...master)
+# Changelog
+
+All notable changes to this project will be documented in this file.
+See [Changelog Update](doc/changelog_update.md) if you want to update this
+document.
+
+## Unreleased / In Rust Nightly
+
- Current beta, release 2020-08-27
++[09bd400...master](https://github.com/rust-lang/rust-clippy/compare/09bd400...master)
++
++## Rust 1.47
++
++Current beta, release 2020-10-08
++
++[c2c07fa...09bd400](https://github.com/rust-lang/rust-clippy/compare/c2c07fa...09bd400)
++
++### New lints
++
++* [`derive_ord_xor_partial_ord`] [#5848](https://github.com/rust-lang/rust-clippy/pull/5848)
++* [`trait_duplication_in_bounds`] [#5852](https://github.com/rust-lang/rust-clippy/pull/5852)
++* [`map_identity`] [#5694](https://github.com/rust-lang/rust-clippy/pull/5694)
++* [`unit_return_expecting_ord`] [#5737](https://github.com/rust-lang/rust-clippy/pull/5737)
++* [`pattern_type_mismatch`] [#4841](https://github.com/rust-lang/rust-clippy/pull/4841)
++* [`repeat_once`] [#5773](https://github.com/rust-lang/rust-clippy/pull/5773)
++* [`same_item_push`] [#5825](https://github.com/rust-lang/rust-clippy/pull/5825)
++* [`needless_arbitrary_self_type`] [#5869](https://github.com/rust-lang/rust-clippy/pull/5869)
++* [`match_like_matches_macro`] [#5769](https://github.com/rust-lang/rust-clippy/pull/5769)
++* [`stable_sort_primitive`] [#5809](https://github.com/rust-lang/rust-clippy/pull/5809)
++* [`blanket_clippy_restriction_lints`] [#5750](https://github.com/rust-lang/rust-clippy/pull/5750)
++* [`option_if_let_else`] [#5301](https://github.com/rust-lang/rust-clippy/pull/5301)
++
++### Moves and Deprecations
++
++* Deprecate [`regex_macro`] lint
++ [#5760](https://github.com/rust-lang/rust-clippy/pull/5760)
++* Move [`range_minus_one`] to `pedantic`
++ [#5752](https://github.com/rust-lang/rust-clippy/pull/5752)
++
++### Enhancements
++
++* Improve [`needless_collect`] by catching `collect` calls followed by `iter` or `into_iter` calls
++ [#5837](https://github.com/rust-lang/rust-clippy/pull/5837)
++* [`panic`], [`todo`], [`unimplemented`] and [`unreachable`] now detect calls with formatting
++ [#5811](https://github.com/rust-lang/rust-clippy/pull/5811)
++* Detect more cases of [`suboptimal_flops`] and [`imprecise_flops`]
++ [#5443](https://github.com/rust-lang/rust-clippy/pull/5443)
++* Handle asymmetrical implementations of `PartialEq` in [`cmp_owned`]
++ [#5701](https://github.com/rust-lang/rust-clippy/pull/5701)
++* Make it possible to allow [`unsafe_derive_deserialize`]
++ [#5870](https://github.com/rust-lang/rust-clippy/pull/5870)
++* Catch `ord.min(a).max(b)` where a < b in [`min_max`]
++ [#5871](https://github.com/rust-lang/rust-clippy/pull/5871)
++* Make [`clone_on_copy`] suggestion machine applicable
++ [#5745](https://github.com/rust-lang/rust-clippy/pull/5745)
++* Enable [`len_zero`] on ranges now that `is_empty` is stable on them
++ [#5961](https://github.com/rust-lang/rust-clippy/pull/5961)
++
++### False Positive Fixes
++
++* Avoid triggering [`or_fun_call`] with const fns that take no arguments
++ [#5889](https://github.com/rust-lang/rust-clippy/pull/5889)
++* Fix [`redundant_closure_call`] false positive for closures that have multiple calls
++ [#5800](https://github.com/rust-lang/rust-clippy/pull/5800)
++* Don't lint cases involving `ManuallyDrop` in [`redundant_clone`]
++ [#5824](https://github.com/rust-lang/rust-clippy/pull/5824)
++* Treat a single expression the same as a single statement in the 2nd arm of a match in [`single_match_else`]
++ [#5771](https://github.com/rust-lang/rust-clippy/pull/5771)
++* Don't trigger [`unnested_or_patterns`] if the feature `or_patterns` is not enabled
++ [#5758](https://github.com/rust-lang/rust-clippy/pull/5758)
++* Avoid linting if key borrows in [`unnecessary_sort_by`]
++ [#5756](https://github.com/rust-lang/rust-clippy/pull/5756)
++* Consider `Try` impl for `Poll` when generating suggestions in [`try_err`]
++ [#5857](https://github.com/rust-lang/rust-clippy/pull/5857)
++* Take input lifetimes into account in `manual_async_fn`
++ [#5859](https://github.com/rust-lang/rust-clippy/pull/5859)
++* Fix multiple false positives in [`type_repetition_in_bounds`] and add a configuration option
++ [#5761](https://github.com/rust-lang/rust-clippy/pull/5761)
++* Limit the [`suspicious_arithmetic_impl`] lint to one binary operation
++ [#5820](https://github.com/rust-lang/rust-clippy/pull/5820)
++
++### Suggestion Fixes/Improvements
++
++* Improve readability of [`shadow_unrelated`] suggestion by truncating the RHS snippet
++ [#5788](https://github.com/rust-lang/rust-clippy/pull/5788)
++* Suggest `filter_map` instead of `flat_map` when mapping to `Option` in [`map_flatten`]
++ [#5846](https://github.com/rust-lang/rust-clippy/pull/5846)
++* Ensure suggestion is shown correctly for long method call chains in [`iter_nth_zero`]
++ [#5793](https://github.com/rust-lang/rust-clippy/pull/5793)
++* Drop borrow operator in suggestions of [`redundant_pattern_matching`]
++ [#5815](https://github.com/rust-lang/rust-clippy/pull/5815)
++* Add suggestion for [`iter_skip_next`]
++ [#5843](https://github.com/rust-lang/rust-clippy/pull/5843)
++* Improve [`collapsible_if`] fix suggestion
++ [#5732](https://github.com/rust-lang/rust-clippy/pull/5732)
++
++### ICE Fixes
++
++* Fix ICE caused by [`needless_collect`]
++ [#5877](https://github.com/rust-lang/rust-clippy/pull/5877)
++* Fix ICE caused by [`unnested_or_patterns`]
++ [#5784](https://github.com/rust-lang/rust-clippy/pull/5784)
++
++### Documentation Improvements
++
++* Fix grammar of [`await_holding_lock`] documentation
++ [#5748](https://github.com/rust-lang/rust-clippy/pull/5748)
++
++### Others
++
++* Make lints adhere to the rustc dev guide
++ [#5888](https://github.com/rust-lang/rust-clippy/pull/5888)
+
+## Rust 1.46
+
- Current stable, released 2020-07-16
++Current stable, released 2020-08-27
+
+[7ea7cd1...c2c07fa](https://github.com/rust-lang/rust-clippy/compare/7ea7cd1...c2c07fa)
+
+### New lints
+
+* [`unnested_or_patterns`] [#5378](https://github.com/rust-lang/rust-clippy/pull/5378)
+* [`iter_next_slice`] [#5597](https://github.com/rust-lang/rust-clippy/pull/5597)
+* [`unnecessary_sort_by`] [#5623](https://github.com/rust-lang/rust-clippy/pull/5623)
+* [`vec_resize_to_zero`] [#5637](https://github.com/rust-lang/rust-clippy/pull/5637)
+
+### Moves and Deprecations
+
+* Move [`cast_ptr_alignment`] to pedantic [#5667](https://github.com/rust-lang/rust-clippy/pull/5667)
+
+### Enhancements
+
+* Improve [`mem_replace_with_uninit`] lint [#5695](https://github.com/rust-lang/rust-clippy/pull/5695)
+
+### False Positive Fixes
+
+* [`len_zero`]: Avoid linting ranges when the `range_is_empty` feature is not enabled
+ [#5656](https://github.com/rust-lang/rust-clippy/pull/5656)
+* [`let_and_return`]: Don't lint if a temporary borrow is involved
+ [#5680](https://github.com/rust-lang/rust-clippy/pull/5680)
+* [`reversed_empty_ranges`]: Avoid linting `N..N` in for loop arguments in
+ [#5692](https://github.com/rust-lang/rust-clippy/pull/5692)
+* [`if_same_then_else`]: Don't assume multiplication is always commutative
+ [#5702](https://github.com/rust-lang/rust-clippy/pull/5702)
+* [`blacklisted_name`]: Remove `bar` from the default configuration
+ [#5712](https://github.com/rust-lang/rust-clippy/pull/5712)
+* [`redundant_pattern_matching`]: Avoid suggesting non-`const fn` calls in const contexts
+ [#5724](https://github.com/rust-lang/rust-clippy/pull/5724)
+
+### Suggestion Fixes/Improvements
+
+* Fix suggestion of [`unit_arg`] lint, so that it suggest semantic equivalent code
+ [#4455](https://github.com/rust-lang/rust-clippy/pull/4455)
+* Add auto applicable suggestion to [`macro_use_imports`]
+ [#5279](https://github.com/rust-lang/rust-clippy/pull/5279)
+
+### ICE Fixes
+
+* Fix ICE in the `consts` module of Clippy [#5709](https://github.com/rust-lang/rust-clippy/pull/5709)
+
+### Documentation Improvements
+
+* Improve code examples across multiple lints [#5664](https://github.com/rust-lang/rust-clippy/pull/5664)
+
+### Others
+
+* Introduce a `--rustc` flag to `clippy-driver`, which turns `clippy-driver`
+ into `rustc` and passes all the given arguments to `rustc`. This is especially
+ useful for tools that need the `rustc` version Clippy was compiled with,
+ instead of the Clippy version. E.g. `clippy-driver --rustc --version` will
+ print the output of `rustc --version`.
+ [#5178](https://github.com/rust-lang/rust-clippy/pull/5178)
+* New issue templates now make it easier to complain if Clippy is too annoying
+ or not annoying enough! [#5735](https://github.com/rust-lang/rust-clippy/pull/5735)
+
+## Rust 1.45
+
++Released 2020-07-16
+
+[891e1a8...7ea7cd1](https://github.com/rust-lang/rust-clippy/compare/891e1a8...7ea7cd1)
+
+### New lints
+
+* [`match_wildcard_for_single_variants`] [#5582](https://github.com/rust-lang/rust-clippy/pull/5582)
+* [`unsafe_derive_deserialize`] [#5493](https://github.com/rust-lang/rust-clippy/pull/5493)
+* [`if_let_mutex`] [#5332](https://github.com/rust-lang/rust-clippy/pull/5332)
+* [`mismatched_target_os`] [#5506](https://github.com/rust-lang/rust-clippy/pull/5506)
+* [`await_holding_lock`] [#5439](https://github.com/rust-lang/rust-clippy/pull/5439)
+* [`match_on_vec_items`] [#5522](https://github.com/rust-lang/rust-clippy/pull/5522)
+* [`manual_async_fn`] [#5576](https://github.com/rust-lang/rust-clippy/pull/5576)
+* [`reversed_empty_ranges`] [#5583](https://github.com/rust-lang/rust-clippy/pull/5583)
+* [`manual_non_exhaustive`] [#5550](https://github.com/rust-lang/rust-clippy/pull/5550)
+
+### Moves and Deprecations
+
+* Downgrade [`match_bool`] to pedantic [#5408](https://github.com/rust-lang/rust-clippy/pull/5408)
+* Downgrade [`match_wild_err_arm`] to pedantic and update help messages. [#5622](https://github.com/rust-lang/rust-clippy/pull/5622)
+* Downgrade [`useless_let_if_seq`] to nursery. [#5599](https://github.com/rust-lang/rust-clippy/pull/5599)
+* Generalize `option_and_then_some` and rename to [`bind_instead_of_map`]. [#5529](https://github.com/rust-lang/rust-clippy/pull/5529)
+* Rename `identity_conversion` to [`useless_conversion`]. [#5568](https://github.com/rust-lang/rust-clippy/pull/5568)
+* Merge `block_in_if_condition_expr` and `block_in_if_condition_stmt` into [`blocks_in_if_conditions`].
+[#5563](https://github.com/rust-lang/rust-clippy/pull/5563)
+* Merge `option_map_unwrap_or`, `option_map_unwrap_or_else` and `result_map_unwrap_or_else` into [`map_unwrap_or`].
+[#5563](https://github.com/rust-lang/rust-clippy/pull/5563)
+* Merge `option_unwrap_used` and `result_unwrap_used` into [`unwrap_used`].
+[#5563](https://github.com/rust-lang/rust-clippy/pull/5563)
+* Merge `option_expect_used` and `result_expect_used` into [`expect_used`].
+[#5563](https://github.com/rust-lang/rust-clippy/pull/5563)
+* Merge `for_loop_over_option` and `for_loop_over_result` into [`for_loops_over_fallibles`].
+[#5563](https://github.com/rust-lang/rust-clippy/pull/5563)
+
+### Enhancements
+
+* Avoid running cargo lints when not enabled to improve performance. [#5505](https://github.com/rust-lang/rust-clippy/pull/5505)
+* Extend [`useless_conversion`] with `TryFrom` and `TryInto`. [#5631](https://github.com/rust-lang/rust-clippy/pull/5631)
+* Lint also in type parameters and where clauses in [`unused_unit`]. [#5592](https://github.com/rust-lang/rust-clippy/pull/5592)
+* Do not suggest deriving `Default` in [`new_without_default`]. [#5616](https://github.com/rust-lang/rust-clippy/pull/5616)
+
+### False Positive Fixes
+
+* [`while_let_on_iterator`] [#5525](https://github.com/rust-lang/rust-clippy/pull/5525)
+* [`empty_line_after_outer_attr`] [#5609](https://github.com/rust-lang/rust-clippy/pull/5609)
+* [`unnecessary_unwrap`] [#5558](https://github.com/rust-lang/rust-clippy/pull/5558)
+* [`comparison_chain`] [#5596](https://github.com/rust-lang/rust-clippy/pull/5596)
+* Don't trigger [`used_underscore_binding`] in await desugaring. [#5535](https://github.com/rust-lang/rust-clippy/pull/5535)
+* Don't trigger [`borrowed_box`] on mutable references. [#5491](https://github.com/rust-lang/rust-clippy/pull/5491)
+* Allow `1 << 0` in [`identity_op`]. [#5602](https://github.com/rust-lang/rust-clippy/pull/5602)
+* Allow `use super::*;` glob imports in [`wildcard_imports`]. [#5564](https://github.com/rust-lang/rust-clippy/pull/5564)
+* Whitelist more words in [`doc_markdown`]. [#5611](https://github.com/rust-lang/rust-clippy/pull/5611)
+* Skip dev and build deps in [`multiple_crate_versions`]. [#5636](https://github.com/rust-lang/rust-clippy/pull/5636)
+* Honor `allow` attribute on arguments in [`ptr_arg`]. [#5647](https://github.com/rust-lang/rust-clippy/pull/5647)
+* Honor lint level attributes for [`redundant_field_names`], [`just_underscores_and_digits`], [`many_single_char_names`]
+and [`similar_names`]. [#5651](https://github.com/rust-lang/rust-clippy/pull/5651)
+* Ignore calls to `len` in [`or_fun_call`]. [#4429](https://github.com/rust-lang/rust-clippy/pull/4429)
+
+### Suggestion Improvements
+
+* Simplify suggestions in [`manual_memcpy`]. [#5536](https://github.com/rust-lang/rust-clippy/pull/5536)
+* Fix suggestion in [`redundant_pattern_matching`] for macros. [#5511](https://github.com/rust-lang/rust-clippy/pull/5511)
+* Avoid suggesting `copied()` for mutable references in [`map_clone`]. [#5530](https://github.com/rust-lang/rust-clippy/pull/5530)
+* Improve help message for [`clone_double_ref`]. [#5547](https://github.com/rust-lang/rust-clippy/pull/5547)
+
+### ICE Fixes
+
+* Fix ICE caused in unwrap module. [#5590](https://github.com/rust-lang/rust-clippy/pull/5590)
+* Fix ICE on rustc test issue-69020-assoc-const-arith-overflow.rs [#5499](https://github.com/rust-lang/rust-clippy/pull/5499)
+
+### Documentation
+
+* Clarify the documentation of [`unnecessary_mut_passed`]. [#5639](https://github.com/rust-lang/rust-clippy/pull/5639)
+* Extend example for [`unneeded_field_pattern`]. [#5541](https://github.com/rust-lang/rust-clippy/pull/5541)
+
+## Rust 1.44
+
+Released 2020-06-04
+
+[204bb9b...891e1a8](https://github.com/rust-lang/rust-clippy/compare/204bb9b...891e1a8)
+
+### New lints
+
+* [`explicit_deref_methods`] [#5226](https://github.com/rust-lang/rust-clippy/pull/5226)
+* [`implicit_saturating_sub`] [#5427](https://github.com/rust-lang/rust-clippy/pull/5427)
+* [`macro_use_imports`] [#5230](https://github.com/rust-lang/rust-clippy/pull/5230)
+* [`verbose_file_reads`] [#5272](https://github.com/rust-lang/rust-clippy/pull/5272)
+* [`future_not_send`] [#5423](https://github.com/rust-lang/rust-clippy/pull/5423)
+* [`redundant_pub_crate`] [#5319](https://github.com/rust-lang/rust-clippy/pull/5319)
+* [`large_const_arrays`] [#5248](https://github.com/rust-lang/rust-clippy/pull/5248)
+* [`result_map_or_into_option`] [#5415](https://github.com/rust-lang/rust-clippy/pull/5415)
+* [`redundant_allocation`] [#5349](https://github.com/rust-lang/rust-clippy/pull/5349)
+* [`fn_address_comparisons`] [#5294](https://github.com/rust-lang/rust-clippy/pull/5294)
+* [`vtable_address_comparisons`] [#5294](https://github.com/rust-lang/rust-clippy/pull/5294)
+
+
+### Moves and Deprecations
+
+* Deprecate [`replace_consts`] lint [#5380](https://github.com/rust-lang/rust-clippy/pull/5380)
+* Move [`cognitive_complexity`] to nursery [#5428](https://github.com/rust-lang/rust-clippy/pull/5428)
+* Move [`useless_transmute`] to nursery [#5364](https://github.com/rust-lang/rust-clippy/pull/5364)
+* Downgrade [`inefficient_to_string`] to pedantic [#5412](https://github.com/rust-lang/rust-clippy/pull/5412)
+* Downgrade [`option_option`] to pedantic [#5401](https://github.com/rust-lang/rust-clippy/pull/5401)
+* Downgrade [`unreadable_literal`] to pedantic [#5419](https://github.com/rust-lang/rust-clippy/pull/5419)
+* Downgrade [`let_unit_value`] to pedantic [#5409](https://github.com/rust-lang/rust-clippy/pull/5409)
+* Downgrade [`trivially_copy_pass_by_ref`] to pedantic [#5410](https://github.com/rust-lang/rust-clippy/pull/5410)
+* Downgrade [`implicit_hasher`] to pedantic [#5411](https://github.com/rust-lang/rust-clippy/pull/5411)
+
+### Enhancements
+
+* On _nightly_ you can now use `cargo clippy --fix -Z unstable-options` to
+ auto-fix lints that support this [#5363](https://github.com/rust-lang/rust-clippy/pull/5363)
+* Make [`redundant_clone`] also trigger on cases where the cloned value is not
+ consumed. [#5304](https://github.com/rust-lang/rust-clippy/pull/5304)
+* Expand [`integer_arithmetic`] to also disallow bit-shifting [#5430](https://github.com/rust-lang/rust-clippy/pull/5430)
+* [`option_as_ref_deref`] now detects more deref cases [#5425](https://github.com/rust-lang/rust-clippy/pull/5425)
+* [`large_enum_variant`] now report the sizes of the largest and second-largest variants [#5466](https://github.com/rust-lang/rust-clippy/pull/5466)
+* [`bool_comparison`] now also checks for inequality comparisons that can be
+ written more concisely [#5365](https://github.com/rust-lang/rust-clippy/pull/5365)
+* Expand [`clone_on_copy`] to work in method call arguments as well [#5441](https://github.com/rust-lang/rust-clippy/pull/5441)
+* [`redundant_pattern_matching`] now also handles `while let` [#5483](https://github.com/rust-lang/rust-clippy/pull/5483)
+* [`integer_arithmetic`] now also lints references of integers [#5329](https://github.com/rust-lang/rust-clippy/pull/5329)
+* Expand [`float_cmp_const`] to also work on arrays [#5345](https://github.com/rust-lang/rust-clippy/pull/5345)
+* Trigger [`map_flatten`] when map is called on an `Option` [#5473](https://github.com/rust-lang/rust-clippy/pull/5473)
+
+### False Positive Fixes
+
+* [`many_single_char_names`] [#5468](https://github.com/rust-lang/rust-clippy/pull/5468)
+* [`should_implement_trait`] [#5437](https://github.com/rust-lang/rust-clippy/pull/5437)
+* [`unused_self`] [#5387](https://github.com/rust-lang/rust-clippy/pull/5387)
+* [`redundant_clone`] [#5453](https://github.com/rust-lang/rust-clippy/pull/5453)
+* [`precedence`] [#5445](https://github.com/rust-lang/rust-clippy/pull/5445)
+* [`suspicious_op_assign_impl`] [#5424](https://github.com/rust-lang/rust-clippy/pull/5424)
+* [`needless_lifetimes`] [#5293](https://github.com/rust-lang/rust-clippy/pull/5293)
+* [`redundant_pattern`] [#5287](https://github.com/rust-lang/rust-clippy/pull/5287)
+* [`inconsistent_digit_grouping`] [#5451](https://github.com/rust-lang/rust-clippy/pull/5451)
+
+
+### Suggestion Improvements
+
+* Improved [`question_mark`] lint suggestion so that it doesn't add redundant `as_ref()` [#5481](https://github.com/rust-lang/rust-clippy/pull/5481)
+* Improve the suggested placeholder in [`option_map_unit_fn`] [#5292](https://github.com/rust-lang/rust-clippy/pull/5292)
+* Improve suggestion for [`match_single_binding`] when triggered inside a closure [#5350](https://github.com/rust-lang/rust-clippy/pull/5350)
+
+### ICE Fixes
+
+* Handle the unstable `trivial_bounds` feature [#5296](https://github.com/rust-lang/rust-clippy/pull/5296)
+* `shadow_*` lints [#5297](https://github.com/rust-lang/rust-clippy/pull/5297)
+
+### Documentation
+
+* Fix documentation generation for configurable lints [#5353](https://github.com/rust-lang/rust-clippy/pull/5353)
+* Update documentation for [`new_ret_no_self`] [#5448](https://github.com/rust-lang/rust-clippy/pull/5448)
+* The documentation for [`option_option`] now suggest using a tri-state enum [#5403](https://github.com/rust-lang/rust-clippy/pull/5403)
+* Fix bit mask example in [`verbose_bit_mask`] documentation [#5454](https://github.com/rust-lang/rust-clippy/pull/5454)
+* [`wildcard_imports`] documentation now mentions that `use ...::prelude::*` is
+ not linted [#5312](https://github.com/rust-lang/rust-clippy/pull/5312)
+
+## Rust 1.43
+
+Released 2020-04-23
+
+[4ee1206...204bb9b](https://github.com/rust-lang/rust-clippy/compare/4ee1206...204bb9b)
+
+### New lints
+
+* [`imprecise_flops`] [#4897](https://github.com/rust-lang/rust-clippy/pull/4897)
+* [`suboptimal_flops`] [#4897](https://github.com/rust-lang/rust-clippy/pull/4897)
+* [`wildcard_imports`] [#5029](https://github.com/rust-lang/rust-clippy/pull/5029)
+* [`single_component_path_imports`] [#5058](https://github.com/rust-lang/rust-clippy/pull/5058)
+* [`match_single_binding`] [#5061](https://github.com/rust-lang/rust-clippy/pull/5061)
+* [`let_underscore_lock`] [#5101](https://github.com/rust-lang/rust-clippy/pull/5101)
+* [`struct_excessive_bools`] [#5125](https://github.com/rust-lang/rust-clippy/pull/5125)
+* [`fn_params_excessive_bools`] [#5125](https://github.com/rust-lang/rust-clippy/pull/5125)
+* [`option_env_unwrap`] [#5148](https://github.com/rust-lang/rust-clippy/pull/5148)
+* [`lossy_float_literal`] [#5202](https://github.com/rust-lang/rust-clippy/pull/5202)
+* [`rest_pat_in_fully_bound_structs`] [#5258](https://github.com/rust-lang/rust-clippy/pull/5258)
+
+### Moves and Deprecations
+
+* Move [`unneeded_field_pattern`] to pedantic group [#5200](https://github.com/rust-lang/rust-clippy/pull/5200)
+
+### Enhancements
+
+* Make [`missing_errors_doc`] lint also trigger on `async` functions
+ [#5181](https://github.com/rust-lang/rust-clippy/pull/5181)
+* Add more constants to [`approx_constant`] [#5193](https://github.com/rust-lang/rust-clippy/pull/5193)
+* Extend [`question_mark`] lint [#5266](https://github.com/rust-lang/rust-clippy/pull/5266)
+
+### False Positive Fixes
+
+* [`use_debug`] [#5047](https://github.com/rust-lang/rust-clippy/pull/5047)
+* [`unnecessary_unwrap`] [#5132](https://github.com/rust-lang/rust-clippy/pull/5132)
+* [`zero_prefixed_literal`] [#5170](https://github.com/rust-lang/rust-clippy/pull/5170)
+* [`missing_const_for_fn`] [#5216](https://github.com/rust-lang/rust-clippy/pull/5216)
+
+### Suggestion Improvements
+
+* Improve suggestion when blocks of code are suggested [#5134](https://github.com/rust-lang/rust-clippy/pull/5134)
+
+### ICE Fixes
+
+* `misc_early` lints [#5129](https://github.com/rust-lang/rust-clippy/pull/5129)
+* [`missing_errors_doc`] [#5213](https://github.com/rust-lang/rust-clippy/pull/5213)
+* Fix ICE when evaluating `usize`s [#5256](https://github.com/rust-lang/rust-clippy/pull/5256)
+
+### Documentation
+
+* Improve documentation of [`iter_nth_zero`]
+* Add documentation pages for stable releases [#5171](https://github.com/rust-lang/rust-clippy/pull/5171)
+
+### Others
+
+* Clippy now completely runs on GitHub Actions [#5190](https://github.com/rust-lang/rust-clippy/pull/5190)
+
+
+## Rust 1.42
+
+Released 2020-03-12
+
+[69f99e7...4ee1206](https://github.com/rust-lang/rust-clippy/compare/69f99e7...4ee1206)
+
+### New lints
+
+* [`filetype_is_file`] [#4543](https://github.com/rust-lang/rust-clippy/pull/4543)
+* [`let_underscore_must_use`] [#4823](https://github.com/rust-lang/rust-clippy/pull/4823)
+* [`modulo_arithmetic`] [#4867](https://github.com/rust-lang/rust-clippy/pull/4867)
+* [`mem_replace_with_default`] [#4881](https://github.com/rust-lang/rust-clippy/pull/4881)
+* [`mutable_key_type`] [#4885](https://github.com/rust-lang/rust-clippy/pull/4885)
+* [`option_as_ref_deref`] [#4945](https://github.com/rust-lang/rust-clippy/pull/4945)
+* [`wildcard_in_or_patterns`] [#4960](https://github.com/rust-lang/rust-clippy/pull/4960)
+* [`iter_nth_zero`] [#4966](https://github.com/rust-lang/rust-clippy/pull/4966)
+* [`invalid_atomic_ordering`] [#4999](https://github.com/rust-lang/rust-clippy/pull/4999)
+* [`skip_while_next`] [#5067](https://github.com/rust-lang/rust-clippy/pull/5067)
+
+### Moves and Deprecations
+
+* Move [`transmute_float_to_int`] from nursery to complexity group
+ [#5015](https://github.com/rust-lang/rust-clippy/pull/5015)
+* Move [`range_plus_one`] to pedantic group [#5057](https://github.com/rust-lang/rust-clippy/pull/5057)
+* Move [`debug_assert_with_mut_call`] to nursery group [#5106](https://github.com/rust-lang/rust-clippy/pull/5106)
+* Deprecate [`unused_label`] [#4930](https://github.com/rust-lang/rust-clippy/pull/4930)
+
+### Enhancements
+
+* Lint vectored IO in [`unused_io_amount`] [#5027](https://github.com/rust-lang/rust-clippy/pull/5027)
+* Make [`vec_box`] configurable by adding a size threshold [#5081](https://github.com/rust-lang/rust-clippy/pull/5081)
+* Also lint constants in [`cmp_nan`] [#4910](https://github.com/rust-lang/rust-clippy/pull/4910)
+* Fix false negative in [`expect_fun_call`] [#4915](https://github.com/rust-lang/rust-clippy/pull/4915)
+* Fix false negative in [`redundant_clone`] [#5017](https://github.com/rust-lang/rust-clippy/pull/5017)
+
+### False Positive Fixes
+
+* [`map_clone`] [#4937](https://github.com/rust-lang/rust-clippy/pull/4937)
+* [`replace_consts`] [#4977](https://github.com/rust-lang/rust-clippy/pull/4977)
+* [`let_and_return`] [#5008](https://github.com/rust-lang/rust-clippy/pull/5008)
+* [`eq_op`] [#5079](https://github.com/rust-lang/rust-clippy/pull/5079)
+* [`possible_missing_comma`] [#5083](https://github.com/rust-lang/rust-clippy/pull/5083)
+* [`debug_assert_with_mut_call`] [#5106](https://github.com/rust-lang/rust-clippy/pull/5106)
+* Don't trigger [`let_underscore_must_use`] in external macros
+ [#5082](https://github.com/rust-lang/rust-clippy/pull/5082)
+* Don't trigger [`empty_loop`] in `no_std` crates [#5086](https://github.com/rust-lang/rust-clippy/pull/5086)
+
+### Suggestion Improvements
+
+* `option_map_unwrap_or` [#4634](https://github.com/rust-lang/rust-clippy/pull/4634)
+* [`wildcard_enum_match_arm`] [#4934](https://github.com/rust-lang/rust-clippy/pull/4934)
+* [`cognitive_complexity`] [#4935](https://github.com/rust-lang/rust-clippy/pull/4935)
+* [`decimal_literal_representation`] [#4956](https://github.com/rust-lang/rust-clippy/pull/4956)
+* [`unknown_clippy_lints`] [#4963](https://github.com/rust-lang/rust-clippy/pull/4963)
+* [`explicit_into_iter_loop`] [#4978](https://github.com/rust-lang/rust-clippy/pull/4978)
+* [`useless_attribute`] [#5022](https://github.com/rust-lang/rust-clippy/pull/5022)
+* [`if_let_some_result`] [#5032](https://github.com/rust-lang/rust-clippy/pull/5032)
+
+### ICE fixes
+
+* [`unsound_collection_transmute`] [#4975](https://github.com/rust-lang/rust-clippy/pull/4975)
+
+### Documentation
+
+* Improve documentation of [`empty_enum`], [`replace_consts`], [`redundant_clone`], and [`iterator_step_by_zero`]
+
+
+## Rust 1.41
+
+Released 2020-01-30
+
+[c8e3cfb...69f99e7](https://github.com/rust-lang/rust-clippy/compare/c8e3cfb...69f99e7)
+
+* New Lints:
+ * [`exit`] [#4697](https://github.com/rust-lang/rust-clippy/pull/4697)
+ * [`to_digit_is_some`] [#4801](https://github.com/rust-lang/rust-clippy/pull/4801)
+ * [`tabs_in_doc_comments`] [#4806](https://github.com/rust-lang/rust-clippy/pull/4806)
+ * [`large_stack_arrays`] [#4807](https://github.com/rust-lang/rust-clippy/pull/4807)
+ * [`same_functions_in_if_condition`] [#4814](https://github.com/rust-lang/rust-clippy/pull/4814)
+ * [`zst_offset`] [#4816](https://github.com/rust-lang/rust-clippy/pull/4816)
+ * [`as_conversions`] [#4821](https://github.com/rust-lang/rust-clippy/pull/4821)
+ * [`missing_errors_doc`] [#4884](https://github.com/rust-lang/rust-clippy/pull/4884)
+ * [`transmute_float_to_int`] [#4889](https://github.com/rust-lang/rust-clippy/pull/4889)
+* Remove plugin interface, see
+ [Inside Rust Blog](https://blog.rust-lang.org/inside-rust/2019/11/04/Clippy-removes-plugin-interface.html) for
+ details [#4714](https://github.com/rust-lang/rust-clippy/pull/4714)
+* Move [`use_self`] to nursery group [#4863](https://github.com/rust-lang/rust-clippy/pull/4863)
+* Deprecate [`into_iter_on_array`] [#4788](https://github.com/rust-lang/rust-clippy/pull/4788)
+* Expand [`string_lit_as_bytes`] to also trigger when literal has escapes
+ [#4808](https://github.com/rust-lang/rust-clippy/pull/4808)
+* Fix false positive in `comparison_chain` [#4842](https://github.com/rust-lang/rust-clippy/pull/4842)
+* Fix false positive in `while_immutable_condition` [#4730](https://github.com/rust-lang/rust-clippy/pull/4730)
+* Fix false positive in `explicit_counter_loop` [#4803](https://github.com/rust-lang/rust-clippy/pull/4803)
+* Fix false positive in `must_use_candidate` [#4794](https://github.com/rust-lang/rust-clippy/pull/4794)
+* Fix false positive in `print_with_newline` and `write_with_newline`
+ [#4769](https://github.com/rust-lang/rust-clippy/pull/4769)
+* Fix false positive in `derive_hash_xor_eq` [#4766](https://github.com/rust-lang/rust-clippy/pull/4766)
+* Fix false positive in `missing_inline_in_public_items` [#4870](https://github.com/rust-lang/rust-clippy/pull/4870)
+* Fix false positive in `string_add` [#4880](https://github.com/rust-lang/rust-clippy/pull/4880)
+* Fix false positive in `float_arithmetic` [#4851](https://github.com/rust-lang/rust-clippy/pull/4851)
+* Fix false positive in `cast_sign_loss` [#4883](https://github.com/rust-lang/rust-clippy/pull/4883)
+* Fix false positive in `manual_swap` [#4877](https://github.com/rust-lang/rust-clippy/pull/4877)
+* Fix ICEs occurring while checking some block expressions [#4772](https://github.com/rust-lang/rust-clippy/pull/4772)
+* Fix ICE in `use_self` [#4776](https://github.com/rust-lang/rust-clippy/pull/4776)
+* Fix ICEs related to `const_generics` [#4780](https://github.com/rust-lang/rust-clippy/pull/4780)
+* Display help when running `clippy-driver` without arguments, instead of ICEing
+ [#4810](https://github.com/rust-lang/rust-clippy/pull/4810)
+* Clippy has its own ICE message now [#4588](https://github.com/rust-lang/rust-clippy/pull/4588)
+* Show deprecated lints in the documentation again [#4757](https://github.com/rust-lang/rust-clippy/pull/4757)
+* Improve Documentation by adding positive examples to some lints
+ [#4832](https://github.com/rust-lang/rust-clippy/pull/4832)
+
+## Rust 1.40
+
+Released 2019-12-19
+
+[4e7e71b...c8e3cfb](https://github.com/rust-lang/rust-clippy/compare/4e7e71b...c8e3cfb)
+
+* New Lints:
+ * [`unneeded_wildcard_pattern`] [#4537](https://github.com/rust-lang/rust-clippy/pull/4537)
+ * [`needless_doctest_main`] [#4603](https://github.com/rust-lang/rust-clippy/pull/4603)
+ * [`suspicious_unary_op_formatting`] [#4615](https://github.com/rust-lang/rust-clippy/pull/4615)
+ * [`debug_assert_with_mut_call`] [#4680](https://github.com/rust-lang/rust-clippy/pull/4680)
+ * [`unused_self`] [#4619](https://github.com/rust-lang/rust-clippy/pull/4619)
+ * [`inefficient_to_string`] [#4683](https://github.com/rust-lang/rust-clippy/pull/4683)
+ * [`must_use_unit`] [#4560](https://github.com/rust-lang/rust-clippy/pull/4560)
+ * [`must_use_candidate`] [#4560](https://github.com/rust-lang/rust-clippy/pull/4560)
+ * [`double_must_use`] [#4560](https://github.com/rust-lang/rust-clippy/pull/4560)
+ * [`comparison_chain`] [#4569](https://github.com/rust-lang/rust-clippy/pull/4569)
+ * [`unsound_collection_transmute`] [#4592](https://github.com/rust-lang/rust-clippy/pull/4592)
+ * [`panic`] [#4657](https://github.com/rust-lang/rust-clippy/pull/4657)
+ * [`unreachable`] [#4657](https://github.com/rust-lang/rust-clippy/pull/4657)
+ * [`todo`] [#4657](https://github.com/rust-lang/rust-clippy/pull/4657)
+ * `option_expect_used` [#4657](https://github.com/rust-lang/rust-clippy/pull/4657)
+ * `result_expect_used` [#4657](https://github.com/rust-lang/rust-clippy/pull/4657)
+* Move `redundant_clone` to perf group [#4509](https://github.com/rust-lang/rust-clippy/pull/4509)
+* Move `manual_mul_add` to nursery group [#4736](https://github.com/rust-lang/rust-clippy/pull/4736)
+* Expand `unit_cmp` to also work with `assert_eq!`, `debug_assert_eq!`, `assert_ne!` and `debug_assert_ne!` [#4613](https://github.com/rust-lang/rust-clippy/pull/4613)
+* Expand `integer_arithmetic` to also detect mutating arithmetic like `+=` [#4585](https://github.com/rust-lang/rust-clippy/pull/4585)
+* Fix false positive in `nonminimal_bool` [#4568](https://github.com/rust-lang/rust-clippy/pull/4568)
+* Fix false positive in `missing_safety_doc` [#4611](https://github.com/rust-lang/rust-clippy/pull/4611)
+* Fix false positive in `cast_sign_loss` [#4614](https://github.com/rust-lang/rust-clippy/pull/4614)
+* Fix false positive in `redundant_clone` [#4509](https://github.com/rust-lang/rust-clippy/pull/4509)
+* Fix false positive in `try_err` [#4721](https://github.com/rust-lang/rust-clippy/pull/4721)
+* Fix false positive in `toplevel_ref_arg` [#4570](https://github.com/rust-lang/rust-clippy/pull/4570)
+* Fix false positive in `multiple_inherent_impl` [#4593](https://github.com/rust-lang/rust-clippy/pull/4593)
+* Improve more suggestions and tests in preparation for the unstable `cargo fix --clippy` [#4575](https://github.com/rust-lang/rust-clippy/pull/4575)
+* Improve suggestion for `zero_ptr` [#4599](https://github.com/rust-lang/rust-clippy/pull/4599)
+* Improve suggestion for `explicit_counter_loop` [#4691](https://github.com/rust-lang/rust-clippy/pull/4691)
+* Improve suggestion for `mul_add` [#4602](https://github.com/rust-lang/rust-clippy/pull/4602)
+* Improve suggestion for `assertions_on_constants` [#4635](https://github.com/rust-lang/rust-clippy/pull/4635)
+* Fix ICE in `use_self` [#4671](https://github.com/rust-lang/rust-clippy/pull/4671)
+* Fix ICE when encountering const casts [#4590](https://github.com/rust-lang/rust-clippy/pull/4590)
+
+## Rust 1.39
+
+Released 2019-11-07
+
+[3aea860...4e7e71b](https://github.com/rust-lang/rust-clippy/compare/3aea860...4e7e71b)
+
+* New Lints:
+ * [`uninit_assumed_init`] [#4479](https://github.com/rust-lang/rust-clippy/pull/4479)
+ * [`flat_map_identity`] [#4231](https://github.com/rust-lang/rust-clippy/pull/4231)
+ * [`missing_safety_doc`] [#4535](https://github.com/rust-lang/rust-clippy/pull/4535)
+ * [`mem_replace_with_uninit`] [#4511](https://github.com/rust-lang/rust-clippy/pull/4511)
+ * [`suspicious_map`] [#4394](https://github.com/rust-lang/rust-clippy/pull/4394)
+ * `option_and_then_some` [#4386](https://github.com/rust-lang/rust-clippy/pull/4386)
+ * [`manual_saturating_arithmetic`] [#4498](https://github.com/rust-lang/rust-clippy/pull/4498)
+* Deprecate `unused_collect` lint. This is fully covered by rustc's `#[must_use]` on `collect` [#4348](https://github.com/rust-lang/rust-clippy/pull/4348)
+* Move `type_repetition_in_bounds` to pedantic group [#4403](https://github.com/rust-lang/rust-clippy/pull/4403)
+* Move `cast_lossless` to pedantic group [#4539](https://github.com/rust-lang/rust-clippy/pull/4539)
+* `temporary_cstring_as_ptr` now catches more cases [#4425](https://github.com/rust-lang/rust-clippy/pull/4425)
+* `use_self` now works in constructors, too [#4525](https://github.com/rust-lang/rust-clippy/pull/4525)
+* `cargo_common_metadata` now checks for license files [#4518](https://github.com/rust-lang/rust-clippy/pull/4518)
+* `cognitive_complexity` now includes the measured complexity in the warning message [#4469](https://github.com/rust-lang/rust-clippy/pull/4469)
+* Fix false positives in `block_in_if_*` lints [#4458](https://github.com/rust-lang/rust-clippy/pull/4458)
+* Fix false positive in `cast_lossless` [#4473](https://github.com/rust-lang/rust-clippy/pull/4473)
+* Fix false positive in `clone_on_copy` [#4411](https://github.com/rust-lang/rust-clippy/pull/4411)
+* Fix false positive in `deref_addrof` [#4487](https://github.com/rust-lang/rust-clippy/pull/4487)
+* Fix false positive in `too_many_lines` [#4490](https://github.com/rust-lang/rust-clippy/pull/4490)
+* Fix false positive in `new_ret_no_self` [#4365](https://github.com/rust-lang/rust-clippy/pull/4365)
+* Fix false positive in `manual_swap` [#4478](https://github.com/rust-lang/rust-clippy/pull/4478)
+* Fix false positive in `missing_const_for_fn` [#4450](https://github.com/rust-lang/rust-clippy/pull/4450)
+* Fix false positive in `extra_unused_lifetimes` [#4477](https://github.com/rust-lang/rust-clippy/pull/4477)
+* Fix false positive in `inherent_to_string` [#4460](https://github.com/rust-lang/rust-clippy/pull/4460)
+* Fix false positive in `map_entry` [#4495](https://github.com/rust-lang/rust-clippy/pull/4495)
+* Fix false positive in `unused_unit` [#4445](https://github.com/rust-lang/rust-clippy/pull/4445)
+* Fix false positive in `redundant_pattern` [#4489](https://github.com/rust-lang/rust-clippy/pull/4489)
+* Fix false positive in `wrong_self_convention` [#4369](https://github.com/rust-lang/rust-clippy/pull/4369)
+* Improve various suggestions and tests in preparation for the unstable `cargo fix --clippy` [#4558](https://github.com/rust-lang/rust-clippy/pull/4558)
+* Improve suggestions for `redundant_pattern_matching` [#4352](https://github.com/rust-lang/rust-clippy/pull/4352)
+* Improve suggestions for `explicit_write` [#4544](https://github.com/rust-lang/rust-clippy/pull/4544)
+* Improve suggestion for `or_fun_call` [#4522](https://github.com/rust-lang/rust-clippy/pull/4522)
+* Improve suggestion for `match_as_ref` [#4446](https://github.com/rust-lang/rust-clippy/pull/4446)
+* Improve suggestion for `unnecessary_fold_span` [#4382](https://github.com/rust-lang/rust-clippy/pull/4382)
+* Add suggestions for `unseparated_literal_suffix` [#4401](https://github.com/rust-lang/rust-clippy/pull/4401)
+* Add suggestions for `char_lit_as_u8` [#4418](https://github.com/rust-lang/rust-clippy/pull/4418)
+
+## Rust 1.38
+
+Released 2019-09-26
+
+[e3cb40e...3aea860](https://github.com/rust-lang/rust-clippy/compare/e3cb40e...3aea860)
+
+* New Lints:
+ * [`main_recursion`] [#4203](https://github.com/rust-lang/rust-clippy/pull/4203)
+ * [`inherent_to_string`] [#4259](https://github.com/rust-lang/rust-clippy/pull/4259)
+ * [`inherent_to_string_shadow_display`] [#4259](https://github.com/rust-lang/rust-clippy/pull/4259)
+ * [`type_repetition_in_bounds`] [#3766](https://github.com/rust-lang/rust-clippy/pull/3766)
+ * [`try_err`] [#4222](https://github.com/rust-lang/rust-clippy/pull/4222)
+* Move `{unnnecessary,panicking}_unwrap` out of nursery [#4307](https://github.com/rust-lang/rust-clippy/pull/4307)
+* Extend the `use_self` lint to suggest uses of `Self::Variant` [#4308](https://github.com/rust-lang/rust-clippy/pull/4308)
+* Improve suggestion for needless return [#4262](https://github.com/rust-lang/rust-clippy/pull/4262)
+* Add auto-fixable suggestion for `let_unit` [#4337](https://github.com/rust-lang/rust-clippy/pull/4337)
+* Fix false positive in `pub_enum_variant_names` and `enum_variant_names` [#4345](https://github.com/rust-lang/rust-clippy/pull/4345)
+* Fix false positive in `cast_ptr_alignment` [#4257](https://github.com/rust-lang/rust-clippy/pull/4257)
+* Fix false positive in `string_lit_as_bytes` [#4233](https://github.com/rust-lang/rust-clippy/pull/4233)
+* Fix false positive in `needless_lifetimes` [#4266](https://github.com/rust-lang/rust-clippy/pull/4266)
+* Fix false positive in `float_cmp` [#4275](https://github.com/rust-lang/rust-clippy/pull/4275)
+* Fix false positives in `needless_return` [#4274](https://github.com/rust-lang/rust-clippy/pull/4274)
+* Fix false negative in `match_same_arms` [#4246](https://github.com/rust-lang/rust-clippy/pull/4246)
+* Fix incorrect suggestion for `needless_bool` [#4335](https://github.com/rust-lang/rust-clippy/pull/4335)
+* Improve suggestion for `cast_ptr_alignment` [#4257](https://github.com/rust-lang/rust-clippy/pull/4257)
+* Improve suggestion for `single_char_literal` [#4361](https://github.com/rust-lang/rust-clippy/pull/4361)
+* Improve suggestion for `len_zero` [#4314](https://github.com/rust-lang/rust-clippy/pull/4314)
+* Fix ICE in `implicit_hasher` [#4268](https://github.com/rust-lang/rust-clippy/pull/4268)
+* Fix allow bug in `trivially_copy_pass_by_ref` [#4250](https://github.com/rust-lang/rust-clippy/pull/4250)
+
+## Rust 1.37
+
+Released 2019-08-15
+
+[082cfa7...e3cb40e](https://github.com/rust-lang/rust-clippy/compare/082cfa7...e3cb40e)
+
+* New Lints:
+ * [`checked_conversions`] [#4088](https://github.com/rust-lang/rust-clippy/pull/4088)
+ * [`get_last_with_len`] [#3832](https://github.com/rust-lang/rust-clippy/pull/3832)
+ * [`integer_division`] [#4195](https://github.com/rust-lang/rust-clippy/pull/4195)
+* Renamed Lint: `const_static_lifetime` is now called [`redundant_static_lifetimes`].
+ The lint now covers statics in addition to consts [#4162](https://github.com/rust-lang/rust-clippy/pull/4162)
+* [`match_same_arms`] now warns for all identical arms, instead of only the first one [#4102](https://github.com/rust-lang/rust-clippy/pull/4102)
+* [`needless_return`] now works with void functions [#4220](https://github.com/rust-lang/rust-clippy/pull/4220)
+* Fix false positive in [`redundant_closure`] [#4190](https://github.com/rust-lang/rust-clippy/pull/4190)
+* Fix false positive in [`useless_attribute`] [#4107](https://github.com/rust-lang/rust-clippy/pull/4107)
+* Fix incorrect suggestion for [`float_cmp`] [#4214](https://github.com/rust-lang/rust-clippy/pull/4214)
+* Add suggestions for [`print_with_newline`] and [`write_with_newline`] [#4136](https://github.com/rust-lang/rust-clippy/pull/4136)
+* Improve suggestions for `option_map_unwrap_or_else` and `result_map_unwrap_or_else` [#4164](https://github.com/rust-lang/rust-clippy/pull/4164)
+* Improve suggestions for [`non_ascii_literal`] [#4119](https://github.com/rust-lang/rust-clippy/pull/4119)
+* Improve diagnostics for [`let_and_return`] [#4137](https://github.com/rust-lang/rust-clippy/pull/4137)
+* Improve diagnostics for [`trivially_copy_pass_by_ref`] [#4071](https://github.com/rust-lang/rust-clippy/pull/4071)
+* Add macro check for [`unreadable_literal`] [#4099](https://github.com/rust-lang/rust-clippy/pull/4099)
+
+## Rust 1.36
+
+Released 2019-07-04
+
+[eb9f9b1...082cfa7](https://github.com/rust-lang/rust-clippy/compare/eb9f9b1...082cfa7)
+
+* New lints: [`find_map`], [`filter_map_next`] [#4039](https://github.com/rust-lang/rust-clippy/pull/4039)
+* New lint: [`path_buf_push_overwrite`] [#3954](https://github.com/rust-lang/rust-clippy/pull/3954)
+* Move `path_buf_push_overwrite` to the nursery [#4013](https://github.com/rust-lang/rust-clippy/pull/4013)
+* Split [`redundant_closure`] into [`redundant_closure`] and [`redundant_closure_for_method_calls`] [#4110](https://github.com/rust-lang/rust-clippy/pull/4101)
+* Allow allowing of [`toplevel_ref_arg`] lint [#4007](https://github.com/rust-lang/rust-clippy/pull/4007)
+* Fix false negative in [`or_fun_call`] pertaining to nested constructors [#4084](https://github.com/rust-lang/rust-clippy/pull/4084)
+* Fix false positive in [`or_fun_call`] pertaining to enum variant constructors [#4018](https://github.com/rust-lang/rust-clippy/pull/4018)
+* Fix false positive in [`useless_let_if_seq`] pertaining to interior mutability [#4035](https://github.com/rust-lang/rust-clippy/pull/4035)
+* Fix false positive in [`redundant_closure`] pertaining to non-function types [#4008](https://github.com/rust-lang/rust-clippy/pull/4008)
+* Fix false positive in [`let_and_return`] pertaining to attributes on `let`s [#4024](https://github.com/rust-lang/rust-clippy/pull/4024)
+* Fix false positive in [`module_name_repetitions`] lint pertaining to attributes [#4006](https://github.com/rust-lang/rust-clippy/pull/4006)
+* Fix false positive on [`assertions_on_constants`] pertaining to `debug_assert!` [#3989](https://github.com/rust-lang/rust-clippy/pull/3989)
+* Improve suggestion in [`map_clone`] to suggest `.copied()` where applicable [#3970](https://github.com/rust-lang/rust-clippy/pull/3970) [#4043](https://github.com/rust-lang/rust-clippy/pull/4043)
+* Improve suggestion for [`search_is_some`] [#4049](https://github.com/rust-lang/rust-clippy/pull/4049)
+* Improve suggestion applicability for [`naive_bytecount`] [#3984](https://github.com/rust-lang/rust-clippy/pull/3984)
+* Improve suggestion applicability for [`while_let_loop`] [#3975](https://github.com/rust-lang/rust-clippy/pull/3975)
+* Improve diagnostics for [`too_many_arguments`] [#4053](https://github.com/rust-lang/rust-clippy/pull/4053)
+* Improve diagnostics for [`cast_lossless`] [#4021](https://github.com/rust-lang/rust-clippy/pull/4021)
+* Deal with macro checks in desugarings better [#4082](https://github.com/rust-lang/rust-clippy/pull/4082)
+* Add macro check for [`unnecessary_cast`] [#4026](https://github.com/rust-lang/rust-clippy/pull/4026)
+* Remove [`approx_constant`]'s documentation's "Known problems" section. [#4027](https://github.com/rust-lang/rust-clippy/pull/4027)
+* Fix ICE in [`suspicious_else_formatting`] [#3960](https://github.com/rust-lang/rust-clippy/pull/3960)
+* Fix ICE in [`decimal_literal_representation`] [#3931](https://github.com/rust-lang/rust-clippy/pull/3931)
+
+
+## Rust 1.35
+
+Released 2019-05-20
+
+[1fac380..37f5c1e](https://github.com/rust-lang/rust-clippy/compare/1fac380...37f5c1e)
+
+* New lint: [`drop_bounds`] to detect `T: Drop` bounds
+* Split [`redundant_closure`] into [`redundant_closure`] and [`redundant_closure_for_method_calls`] [#4110](https://github.com/rust-lang/rust-clippy/pull/4101)
+* Rename `cyclomatic_complexity` to [`cognitive_complexity`], start work on making lint more practical for Rust code
+* Move [`get_unwrap`] to the restriction category
+* Improve suggestions for [`iter_cloned_collect`]
+* Improve suggestions for [`cast_lossless`] to suggest suffixed literals
+* Fix false positives in [`print_with_newline`] and [`write_with_newline`] pertaining to raw strings
+* Fix false positive in [`needless_range_loop`] pertaining to structs without a `.iter()`
+* Fix false positive in [`bool_comparison`] pertaining to non-bool types
+* Fix false positive in [`redundant_closure`] pertaining to differences in borrows
+* Fix false positive in `option_map_unwrap_or` on non-copy types
+* Fix false positives in [`missing_const_for_fn`] pertaining to macros and trait method impls
+* Fix false positive in [`needless_pass_by_value`] pertaining to procedural macros
+* Fix false positive in [`needless_continue`] pertaining to loop labels
+* Fix false positive for [`boxed_local`] pertaining to arguments moved into closures
+* Fix false positive for [`use_self`] in nested functions
+* Fix suggestion for [`expect_fun_call`] (https://github.com/rust-lang/rust-clippy/pull/3846)
+* Fix suggestion for [`explicit_counter_loop`] to deal with parenthesizing range variables
+* Fix suggestion for [`single_char_pattern`] to correctly escape single quotes
+* Avoid triggering [`redundant_closure`] in macros
+* ICE fixes: [#3805](https://github.com/rust-lang/rust-clippy/pull/3805), [#3772](https://github.com/rust-lang/rust-clippy/pull/3772), [#3741](https://github.com/rust-lang/rust-clippy/pull/3741)
+
+## Rust 1.34
+
+Released 2019-04-10
+
+[1b89724...1fac380](https://github.com/rust-lang/rust-clippy/compare/1b89724...1fac380)
+
+* New lint: [`assertions_on_constants`] to detect for example `assert!(true)`
+* New lint: [`dbg_macro`] to detect uses of the `dbg!` macro
+* New lint: [`missing_const_for_fn`] that can suggest functions to be made `const`
+* New lint: [`too_many_lines`] to detect functions with excessive LOC. It can be
+ configured using the `too-many-lines-threshold` configuration.
+* New lint: [`wildcard_enum_match_arm`] to check for wildcard enum matches using `_`
+* Expand `redundant_closure` to also work for methods (not only functions)
+* Fix ICEs in `vec_box`, `needless_pass_by_value` and `implicit_hasher`
+* Fix false positive in `cast_sign_loss`
+* Fix false positive in `integer_arithmetic`
+* Fix false positive in `unit_arg`
+* Fix false positives in `implicit_return`
+* Add suggestion to `explicit_write`
+* Improve suggestions for `question_mark` lint
+* Fix incorrect suggestion for `cast_lossless`
+* Fix incorrect suggestion for `expect_fun_call`
+* Fix incorrect suggestion for `needless_bool`
+* Fix incorrect suggestion for `needless_range_loop`
+* Fix incorrect suggestion for `use_self`
+* Fix incorrect suggestion for `while_let_on_iterator`
+* Clippy is now slightly easier to invoke in non-cargo contexts. See
+ [#3665][pull3665] for more details.
+* We now have [improved documentation][adding_lints] on how to add new lints
+
+## Rust 1.33
+
+Released 2019-02-26
+
+[b2601be...1b89724](https://github.com/rust-lang/rust-clippy/compare/b2601be...1b89724)
+
+* New lints: [`implicit_return`], [`vec_box`], [`cast_ref_to_mut`]
+* The `rust-clippy` repository is now part of the `rust-lang` org.
+* Rename `stutter` to `module_name_repetitions`
+* Merge `new_without_default_derive` into `new_without_default` lint
+* Move `large_digit_groups` from `style` group to `pedantic`
+* Expand `bool_comparison` to check for `<`, `<=`, `>`, `>=`, and `!=`
+ comparisons against booleans
+* Expand `no_effect` to detect writes to constants such as `A_CONST.field = 2`
+* Expand `redundant_clone` to work on struct fields
+* Expand `suspicious_else_formatting` to detect `if .. {..} {..}`
+* Expand `use_self` to work on tuple structs and also in local macros
+* Fix ICE in `result_map_unit_fn` and `option_map_unit_fn`
+* Fix false positives in `implicit_return`
+* Fix false positives in `use_self`
+* Fix false negative in `clone_on_copy`
+* Fix false positive in `doc_markdown`
+* Fix false positive in `empty_loop`
+* Fix false positive in `if_same_then_else`
+* Fix false positive in `infinite_iter`
+* Fix false positive in `question_mark`
+* Fix false positive in `useless_asref`
+* Fix false positive in `wildcard_dependencies`
+* Fix false positive in `write_with_newline`
+* Add suggestion to `explicit_write`
+* Improve suggestions for `question_mark` lint
+* Fix incorrect suggestion for `get_unwrap`
+
+## Rust 1.32
+
+Released 2019-01-17
+
+[2e26fdc2...b2601be](https://github.com/rust-lang/rust-clippy/compare/2e26fdc2...b2601be)
+
+* New lints: [`slow_vector_initialization`], [`mem_discriminant_non_enum`],
+ [`redundant_clone`], [`wildcard_dependencies`],
+ [`into_iter_on_ref`], [`into_iter_on_array`], [`deprecated_cfg_attr`],
+ [`mem_discriminant_non_enum`], [`cargo_common_metadata`]
+* Add support for `u128` and `i128` to integer related lints
+* Add float support to `mistyped_literal_suffixes`
+* Fix false positives in `use_self`
+* Fix false positives in `missing_comma`
+* Fix false positives in `new_ret_no_self`
+* Fix false positives in `possible_missing_comma`
+* Fix false positive in `integer_arithmetic` in constant items
+* Fix false positive in `needless_borrow`
+* Fix false positive in `out_of_bounds_indexing`
+* Fix false positive in `new_without_default_derive`
+* Fix false positive in `string_lit_as_bytes`
+* Fix false negative in `out_of_bounds_indexing`
+* Fix false negative in `use_self`. It will now also check existential types
+* Fix incorrect suggestion for `redundant_closure_call`
+* Fix various suggestions that contained expanded macros
+* Fix `bool_comparison` triggering 3 times on on on the same code
+* Expand `trivially_copy_pass_by_ref` to work on trait methods
+* Improve suggestion for `needless_range_loop`
+* Move `needless_pass_by_value` from `pedantic` group to `style`
+
+## Rust 1.31
+
+Released 2018-12-06
+
+[125907ad..2e26fdc2](https://github.com/rust-lang/rust-clippy/compare/125907ad..2e26fdc2)
+
+* Clippy has been relicensed under a dual MIT / Apache license.
+ See [#3093](https://github.com/rust-lang/rust-clippy/issues/3093) for more
+ information.
+* With Rust 1.31, Clippy is no longer available via crates.io. The recommended
+ installation method is via `rustup component add clippy`.
+* New lints: [`redundant_pattern_matching`], [`unnecessary_filter_map`],
+ [`unused_unit`], [`map_flatten`], [`mem_replace_option_with_none`]
+* Fix ICE in `if_let_redundant_pattern_matching`
+* Fix ICE in `needless_pass_by_value` when encountering a generic function
+ argument with a lifetime parameter
+* Fix ICE in `needless_range_loop`
+* Fix ICE in `single_char_pattern` when encountering a constant value
+* Fix false positive in `assign_op_pattern`
+* Fix false positive in `boxed_local` on trait implementations
+* Fix false positive in `cmp_owned`
+* Fix false positive in `collapsible_if` when conditionals have comments
+* Fix false positive in `double_parens`
+* Fix false positive in `excessive_precision`
+* Fix false positive in `explicit_counter_loop`
+* Fix false positive in `fn_to_numeric_cast_with_truncation`
+* Fix false positive in `map_clone`
+* Fix false positive in `new_ret_no_self`
+* Fix false positive in `new_without_default` when `new` is unsafe
+* Fix false positive in `type_complexity` when using extern types
+* Fix false positive in `useless_format`
+* Fix false positive in `wrong_self_convention`
+* Fix incorrect suggestion for `excessive_precision`
+* Fix incorrect suggestion for `expect_fun_call`
+* Fix incorrect suggestion for `get_unwrap`
+* Fix incorrect suggestion for `useless_format`
+* `fn_to_numeric_cast_with_truncation` lint can be disabled again
+* Improve suggestions for `manual_memcpy`
+* Improve help message for `needless_lifetimes`
+
+## Rust 1.30
+
+Released 2018-10-25
+
+[14207503...125907ad](https://github.com/rust-lang/rust-clippy/compare/14207503...125907ad)
+
+* Deprecate `assign_ops` lint
+* New lints: [`mistyped_literal_suffixes`], [`ptr_offset_with_cast`],
+ [`needless_collect`], [`copy_iterator`]
+* `cargo clippy -V` now includes the Clippy commit hash of the Rust
+ Clippy component
+* Fix ICE in `implicit_hasher`
+* Fix ICE when encountering `println!("{}" a);`
+* Fix ICE when encountering a macro call in match statements
+* Fix false positive in `default_trait_access`
+* Fix false positive in `trivially_copy_pass_by_ref`
+* Fix false positive in `similar_names`
+* Fix false positive in `redundant_field_name`
+* Fix false positive in `expect_fun_call`
+* Fix false negative in `identity_conversion`
+* Fix false negative in `explicit_counter_loop`
+* Fix `range_plus_one` suggestion and false negative
+* `print_with_newline` / `write_with_newline`: don't warn about string with several `\n`s in them
+* Fix `useless_attribute` to also whitelist `unused_extern_crates`
+* Fix incorrect suggestion for `single_char_pattern`
+* Improve suggestion for `identity_conversion` lint
+* Move `explicit_iter_loop` and `explicit_into_iter_loop` from `style` group to `pedantic`
+* Move `range_plus_one` and `range_minus_one` from `nursery` group to `complexity`
+* Move `shadow_unrelated` from `restriction` group to `pedantic`
+* Move `indexing_slicing` from `pedantic` group to `restriction`
+
+## Rust 1.29
+
+Released 2018-09-13
+
+[v0.0.212...14207503](https://github.com/rust-lang/rust-clippy/compare/v0.0.212...14207503)
+
+* :tada: :tada: **Rust 1.29 is the first stable Rust that includes a bundled Clippy** :tada:
+ :tada:
+ You can now run `rustup component add clippy-preview` and then `cargo
+ clippy` to run Clippy. This should put an end to the continuous nightly
+ upgrades for Clippy users.
+* Clippy now follows the Rust versioning scheme instead of its own
+* Fix ICE when encountering a `while let (..) = x.iter()` construct
+* Fix false positives in `use_self`
+* Fix false positive in `trivially_copy_pass_by_ref`
+* Fix false positive in `useless_attribute` lint
+* Fix false positive in `print_literal`
+* Fix `use_self` regressions
+* Improve lint message for `neg_cmp_op_on_partial_ord`
+* Improve suggestion highlight for `single_char_pattern`
+* Improve suggestions for various print/write macro lints
+* Improve website header
+
+## 0.0.212 (2018-07-10)
+* Rustup to *rustc 1.29.0-nightly (e06c87544 2018-07-06)*
+
+## 0.0.211
+* Rustup to *rustc 1.28.0-nightly (e3bf634e0 2018-06-28)*
+
+## 0.0.210
+* Rustup to *rustc 1.28.0-nightly (01cc982e9 2018-06-24)*
+
+## 0.0.209
+* Rustup to *rustc 1.28.0-nightly (523097979 2018-06-18)*
+
+## 0.0.208
+* Rustup to *rustc 1.28.0-nightly (86a8f1a63 2018-06-17)*
+
+## 0.0.207
+* Rustup to *rustc 1.28.0-nightly (2a0062974 2018-06-09)*
+
+## 0.0.206
+* Rustup to *rustc 1.28.0-nightly (5bf68db6e 2018-05-28)*
+
+## 0.0.205
+* Rustup to *rustc 1.28.0-nightly (990d8aa74 2018-05-25)*
+* Rename `unused_lifetimes` to `extra_unused_lifetimes` because of naming conflict with new rustc lint
+
+## 0.0.204
+* Rustup to *rustc 1.28.0-nightly (71e87be38 2018-05-22)*
+
+## 0.0.203
+* Rustup to *rustc 1.28.0-nightly (a3085756e 2018-05-19)*
+* Clippy attributes are now of the form `clippy::cyclomatic_complexity` instead of `clippy(cyclomatic_complexity)`
+
+## 0.0.202
+* Rustup to *rustc 1.28.0-nightly (952f344cd 2018-05-18)*
+
+## 0.0.201
+* Rustup to *rustc 1.27.0-nightly (2f2a11dfc 2018-05-16)*
+
+## 0.0.200
+* Rustup to *rustc 1.27.0-nightly (9fae15374 2018-05-13)*
+
+## 0.0.199
+* Rustup to *rustc 1.27.0-nightly (ff2ac35db 2018-05-12)*
+
+## 0.0.198
+* Rustup to *rustc 1.27.0-nightly (acd3871ba 2018-05-10)*
+
+## 0.0.197
+* Rustup to *rustc 1.27.0-nightly (428ea5f6b 2018-05-06)*
+
+## 0.0.196
+* Rustup to *rustc 1.27.0-nightly (e82261dfb 2018-05-03)*
+
+## 0.0.195
+* Rustup to *rustc 1.27.0-nightly (ac3c2288f 2018-04-18)*
+
+## 0.0.194
+* Rustup to *rustc 1.27.0-nightly (bd40cbbe1 2018-04-14)*
+* New lints: [`cast_ptr_alignment`], [`transmute_ptr_to_ptr`], [`write_literal`], [`write_with_newline`], [`writeln_empty_string`]
+
+## 0.0.193
+* Rustup to *rustc 1.27.0-nightly (eeea94c11 2018-04-06)*
+
+## 0.0.192
+* Rustup to *rustc 1.27.0-nightly (fb44b4c0e 2018-04-04)*
+* New lint: [`print_literal`]
+
+## 0.0.191
+* Rustup to *rustc 1.26.0-nightly (ae544ee1c 2018-03-29)*
+* Lint audit; categorize lints as style, correctness, complexity, pedantic, nursery, restriction.
+
+## 0.0.190
+* Fix a bunch of intermittent cargo bugs
+
+## 0.0.189
+* Rustup to *rustc 1.26.0-nightly (5508b2714 2018-03-18)*
+
+## 0.0.188
+* Rustup to *rustc 1.26.0-nightly (392645394 2018-03-15)*
+* New lint: [`while_immutable_condition`]
+
+## 0.0.187
+* Rustup to *rustc 1.26.0-nightly (322d7f7b9 2018-02-25)*
+* New lints: [`redundant_field_names`], [`suspicious_arithmetic_impl`], [`suspicious_op_assign_impl`]
+
+## 0.0.186
+* Rustup to *rustc 1.25.0-nightly (0c6091fbd 2018-02-04)*
+* Various false positive fixes
+
+## 0.0.185
+* Rustup to *rustc 1.25.0-nightly (56733bc9f 2018-02-01)*
+* New lint: [`question_mark`]
+
+## 0.0.184
+* Rustup to *rustc 1.25.0-nightly (90eb44a58 2018-01-29)*
+* New lints: [`double_comparisons`], [`empty_line_after_outer_attr`]
+
+## 0.0.183
+* Rustup to *rustc 1.25.0-nightly (21882aad7 2018-01-28)*
+* New lint: [`misaligned_transmute`]
+
+## 0.0.182
+* Rustup to *rustc 1.25.0-nightly (a0dcecff9 2018-01-24)*
+* New lint: [`decimal_literal_representation`]
+
+## 0.0.181
+* Rustup to *rustc 1.25.0-nightly (97520ccb1 2018-01-21)*
+* New lints: [`else_if_without_else`], [`option_option`], [`unit_arg`], [`unnecessary_fold`]
+* Removed `unit_expr`
+* Various false positive fixes for [`needless_pass_by_value`]
+
+## 0.0.180
+* Rustup to *rustc 1.25.0-nightly (3f92e8d89 2018-01-14)*
+
+## 0.0.179
+* Rustup to *rustc 1.25.0-nightly (61452e506 2018-01-09)*
+
+## 0.0.178
+* Rustup to *rustc 1.25.0-nightly (ee220daca 2018-01-07)*
+
+## 0.0.177
+* Rustup to *rustc 1.24.0-nightly (250b49205 2017-12-21)*
+* New lint: [`match_as_ref`]
+
+## 0.0.176
+* Rustup to *rustc 1.24.0-nightly (0077d128d 2017-12-14)*
+
+## 0.0.175
+* Rustup to *rustc 1.24.0-nightly (bb42071f6 2017-12-01)*
+
+## 0.0.174
+* Rustup to *rustc 1.23.0-nightly (63739ab7b 2017-11-21)*
+
+## 0.0.173
+* Rustup to *rustc 1.23.0-nightly (33374fa9d 2017-11-20)*
+
+## 0.0.172
+* Rustup to *rustc 1.23.0-nightly (d0f8e2913 2017-11-16)*
+
+## 0.0.171
+* Rustup to *rustc 1.23.0-nightly (ff0f5de3b 2017-11-14)*
+
+## 0.0.170
+* Rustup to *rustc 1.23.0-nightly (d6b06c63a 2017-11-09)*
+
+## 0.0.169
+* Rustup to *rustc 1.23.0-nightly (3b82e4c74 2017-11-05)*
+* New lints: [`just_underscores_and_digits`], `result_map_unwrap_or_else`, [`transmute_bytes_to_str`]
+
+## 0.0.168
+* Rustup to *rustc 1.23.0-nightly (f0fe716db 2017-10-30)*
+
+## 0.0.167
+* Rustup to *rustc 1.23.0-nightly (90ef3372e 2017-10-29)*
+* New lints: `const_static_lifetime`, [`erasing_op`], [`fallible_impl_from`], [`println_empty_string`], [`useless_asref`]
+
+## 0.0.166
+* Rustup to *rustc 1.22.0-nightly (b7960878b 2017-10-18)*
+* New lints: [`explicit_write`], `identity_conversion`, [`implicit_hasher`], [`invalid_ref`], [`option_map_or_none`],
+ [`range_minus_one`], [`range_plus_one`], [`transmute_int_to_bool`], [`transmute_int_to_char`],
+ [`transmute_int_to_float`]
+
+## 0.0.165
+* Rust upgrade to rustc 1.22.0-nightly (0e6f4cf51 2017-09-27)
+* New lint: [`mut_range_bound`]
+
+## 0.0.164
+* Update to *rustc 1.22.0-nightly (6c476ce46 2017-09-25)*
+* New lint: [`int_plus_one`]
+
+## 0.0.163
+* Update to *rustc 1.22.0-nightly (14039a42a 2017-09-22)*
+
+## 0.0.162
+* Update to *rustc 1.22.0-nightly (0701b37d9 2017-09-18)*
+* New lint: [`chars_last_cmp`]
+* Improved suggestions for [`needless_borrow`], [`ptr_arg`],
+
+## 0.0.161
+* Update to *rustc 1.22.0-nightly (539f2083d 2017-09-13)*
+
+## 0.0.160
+* Update to *rustc 1.22.0-nightly (dd08c3070 2017-09-12)*
+
+## 0.0.159
+* Update to *rustc 1.22.0-nightly (eba374fb2 2017-09-11)*
+* New lint: [`clone_on_ref_ptr`]
+
+## 0.0.158
+* New lint: [`manual_memcpy`]
+* [`cast_lossless`] no longer has redundant parentheses in its suggestions
+* Update to *rustc 1.22.0-nightly (dead08cb3 2017-09-08)*
+
+## 0.0.157 - 2017-09-04
+* Update to *rustc 1.22.0-nightly (981ce7d8d 2017-09-03)*
+* New lint: `unit_expr`
+
+## 0.0.156 - 2017-09-03
+* Update to *rustc 1.22.0-nightly (744dd6c1d 2017-09-02)*
+
+## 0.0.155
+* Update to *rustc 1.21.0-nightly (c11f689d2 2017-08-29)*
+* New lint: [`infinite_iter`], [`maybe_infinite_iter`], [`cast_lossless`]
+
+## 0.0.154
+* Update to *rustc 1.21.0-nightly (2c0558f63 2017-08-24)*
+* Fix [`use_self`] triggering inside derives
+* Add support for linting an entire workspace with `cargo clippy --all`
+* New lint: [`naive_bytecount`]
+
+## 0.0.153
+* Update to *rustc 1.21.0-nightly (8c303ed87 2017-08-20)*
+* New lint: [`use_self`]
+
+## 0.0.152
+* Update to *rustc 1.21.0-nightly (df511d554 2017-08-14)*
+
+## 0.0.151
+* Update to *rustc 1.21.0-nightly (13d94d5fa 2017-08-10)*
+
+## 0.0.150
+* Update to *rustc 1.21.0-nightly (215e0b10e 2017-08-08)*
+
+## 0.0.148
+* Update to *rustc 1.21.0-nightly (37c7d0ebb 2017-07-31)*
+* New lints: [`unreadable_literal`], [`inconsistent_digit_grouping`], [`large_digit_groups`]
+
+## 0.0.147
+* Update to *rustc 1.21.0-nightly (aac223f4f 2017-07-30)*
+
+## 0.0.146
+* Update to *rustc 1.21.0-nightly (52a330969 2017-07-27)*
+* Fixes false positives in `inline_always`
+* Fixes false negatives in `panic_params`
+
+## 0.0.145
+* Update to *rustc 1.20.0-nightly (afe145d22 2017-07-23)*
+
+## 0.0.144
+* Update to *rustc 1.20.0-nightly (086eaa78e 2017-07-15)*
+
+## 0.0.143
+* Update to *rustc 1.20.0-nightly (d84693b93 2017-07-09)*
+* Fix `cargo clippy` crashing on `dylib` projects
+* Fix false positives around `nested_while_let` and `never_loop`
+
+## 0.0.142
+* Update to *rustc 1.20.0-nightly (067971139 2017-07-02)*
+
+## 0.0.141
+* Rewrite of the `doc_markdown` lint.
+* Deprecated [`range_step_by_zero`]
+* New lint: [`iterator_step_by_zero`]
+* New lint: [`needless_borrowed_reference`]
+* Update to *rustc 1.20.0-nightly (69c65d296 2017-06-28)*
+
+## 0.0.140 - 2017-06-16
+* Update to *rustc 1.19.0-nightly (258ae6dd9 2017-06-15)*
+
+## 0.0.139 — 2017-06-10
+* Update to *rustc 1.19.0-nightly (4bf5c99af 2017-06-10)*
+* Fix bugs with for loop desugaring
+* Check for [`AsRef`]/[`AsMut`] arguments in [`wrong_self_convention`]
+
+## 0.0.138 — 2017-06-05
+* Update to *rustc 1.19.0-nightly (0418fa9d3 2017-06-04)*
+
+## 0.0.137 — 2017-06-05
+* Update to *rustc 1.19.0-nightly (6684d176c 2017-06-03)*
+
+## 0.0.136 — 2017—05—26
+* Update to *rustc 1.19.0-nightly (557967766 2017-05-26)*
+
+## 0.0.135 — 2017—05—24
+* Update to *rustc 1.19.0-nightly (5b13bff52 2017-05-23)*
+
+## 0.0.134 — 2017—05—19
+* Update to *rustc 1.19.0-nightly (0ed1ec9f9 2017-05-18)*
+
+## 0.0.133 — 2017—05—14
+* Update to *rustc 1.19.0-nightly (826d8f385 2017-05-13)*
+
+## 0.0.132 — 2017—05—05
+* Fix various bugs and some ices
+
+## 0.0.131 — 2017—05—04
+* Update to *rustc 1.19.0-nightly (2d4ed8e0c 2017-05-03)*
+
+## 0.0.130 — 2017—05—03
+* Update to *rustc 1.19.0-nightly (6a5fc9eec 2017-05-02)*
+
+## 0.0.129 — 2017-05-01
+* Update to *rustc 1.19.0-nightly (06fb4d256 2017-04-30)*
+
+## 0.0.128 — 2017-04-28
+* Update to *rustc 1.18.0-nightly (94e884b63 2017-04-27)*
+
+## 0.0.127 — 2017-04-27
+* Update to *rustc 1.18.0-nightly (036983201 2017-04-26)*
+* New lint: [`needless_continue`]
+
+## 0.0.126 — 2017-04-24
+* Update to *rustc 1.18.0-nightly (2bd4b5c6d 2017-04-23)*
+
+## 0.0.125 — 2017-04-19
+* Update to *rustc 1.18.0-nightly (9f2abadca 2017-04-18)*
+
+## 0.0.124 — 2017-04-16
+* Update to *rustc 1.18.0-nightly (d5cf1cb64 2017-04-15)*
+
+## 0.0.123 — 2017-04-07
+* Fix various false positives
+
+## 0.0.122 — 2017-04-07
+* Rustup to *rustc 1.18.0-nightly (91ae22a01 2017-04-05)*
+* New lint: [`op_ref`]
+
+## 0.0.121 — 2017-03-21
+* Rustup to *rustc 1.17.0-nightly (134c4a0f0 2017-03-20)*
+
+## 0.0.120 — 2017-03-17
+* Rustup to *rustc 1.17.0-nightly (0aeb9c129 2017-03-15)*
+
+## 0.0.119 — 2017-03-13
+* Rustup to *rustc 1.17.0-nightly (824c9ebbd 2017-03-12)*
+
+## 0.0.118 — 2017-03-05
+* Rustup to *rustc 1.17.0-nightly (b1e31766d 2017-03-03)*
+
+## 0.0.117 — 2017-03-01
+* Rustup to *rustc 1.17.0-nightly (be760566c 2017-02-28)*
+
+## 0.0.116 — 2017-02-28
+* Fix `cargo clippy` on 64 bit windows systems
+
+## 0.0.115 — 2017-02-27
+* Rustup to *rustc 1.17.0-nightly (60a0edc6c 2017-02-26)*
+* New lints: [`zero_ptr`], [`never_loop`], [`mut_from_ref`]
+
+## 0.0.114 — 2017-02-08
+* Rustup to *rustc 1.17.0-nightly (c49d10207 2017-02-07)*
+* Tests are now ui tests (testing the exact output of rustc)
+
+## 0.0.113 — 2017-02-04
+* Rustup to *rustc 1.16.0-nightly (eedaa94e3 2017-02-02)*
+* New lint: [`large_enum_variant`]
+* `explicit_into_iter_loop` provides suggestions
+
+## 0.0.112 — 2017-01-27
+* Rustup to *rustc 1.16.0-nightly (df8debf6d 2017-01-25)*
+
+## 0.0.111 — 2017-01-21
+* Rustup to *rustc 1.16.0-nightly (a52da95ce 2017-01-20)*
+
+## 0.0.110 — 2017-01-20
+* Add badges and categories to `Cargo.toml`
+
+## 0.0.109 — 2017-01-19
+* Update to *rustc 1.16.0-nightly (c07a6ae77 2017-01-17)*
+
+## 0.0.108 — 2017-01-12
+* Update to *rustc 1.16.0-nightly (2782e8f8f 2017-01-12)*
+
+## 0.0.107 — 2017-01-11
+* Update regex dependency
+* Fix FP when matching `&&mut` by `&ref`
+* Reintroduce `for (_, x) in &mut hash_map` -> `for x in hash_map.values_mut()`
+* New lints: [`unused_io_amount`], [`forget_ref`], [`short_circuit_statement`]
+
+## 0.0.106 — 2017-01-04
+* Fix FP introduced by rustup in [`wrong_self_convention`]
+
+## 0.0.105 — 2017-01-04
+* Update to *rustc 1.16.0-nightly (468227129 2017-01-03)*
+* New lints: [`deref_addrof`], [`double_parens`], [`pub_enum_variant_names`]
+* Fix suggestion in [`new_without_default`]
+* FP fix in [`absurd_extreme_comparisons`]
+
+## 0.0.104 — 2016-12-15
+* Update to *rustc 1.15.0-nightly (8f02c429a 2016-12-15)*
+
+## 0.0.103 — 2016-11-25
+* Update to *rustc 1.15.0-nightly (d5814b03e 2016-11-23)*
+
+## 0.0.102 — 2016-11-24
+* Update to *rustc 1.15.0-nightly (3bf2be9ce 2016-11-22)*
+
+## 0.0.101 — 2016-11-23
+* Update to *rustc 1.15.0-nightly (7b3eeea22 2016-11-21)*
+* New lint: [`string_extend_chars`]
+
+## 0.0.100 — 2016-11-20
+* Update to *rustc 1.15.0-nightly (ac635aa95 2016-11-18)*
+
+## 0.0.99 — 2016-11-18
+* Update to rustc 1.15.0-nightly (0ed951993 2016-11-14)
+* New lint: [`get_unwrap`]
+
+## 0.0.98 — 2016-11-08
+* Fixes an issue due to a change in how cargo handles `--sysroot`, which broke `cargo clippy`
+
+## 0.0.97 — 2016-11-03
+* For convenience, `cargo clippy` defines a `cargo-clippy` feature. This was
+ previously added for a short time under the name `clippy` but removed for
+ compatibility.
+* `cargo clippy --help` is more helping (and less helpful :smile:)
+* Rustup to *rustc 1.14.0-nightly (5665bdf3e 2016-11-02)*
+* New lints: [`if_let_redundant_pattern_matching`], [`partialeq_ne_impl`]
+
+## 0.0.96 — 2016-10-22
+* Rustup to *rustc 1.14.0-nightly (f09420685 2016-10-20)*
+* New lint: [`iter_skip_next`]
+
+## 0.0.95 — 2016-10-06
+* Rustup to *rustc 1.14.0-nightly (3210fd5c2 2016-10-05)*
+
+## 0.0.94 — 2016-10-04
+* Fixes bustage on Windows due to forbidden directory name
+
+## 0.0.93 — 2016-10-03
+* Rustup to *rustc 1.14.0-nightly (144af3e97 2016-10-02)*
+* `option_map_unwrap_or` and `option_map_unwrap_or_else` are now
+ allowed by default.
+* New lint: [`explicit_into_iter_loop`]
+
+## 0.0.92 — 2016-09-30
+* Rustup to *rustc 1.14.0-nightly (289f3a4ca 2016-09-29)*
+
+## 0.0.91 — 2016-09-28
+* Rustup to *rustc 1.13.0-nightly (d0623cf7b 2016-09-26)*
+
+## 0.0.90 — 2016-09-09
+* Rustup to *rustc 1.13.0-nightly (f1f40f850 2016-09-09)*
+
+## 0.0.89 — 2016-09-06
+* Rustup to *rustc 1.13.0-nightly (cbe4de78e 2016-09-05)*
+
+## 0.0.88 — 2016-09-04
+* Rustup to *rustc 1.13.0-nightly (70598e04f 2016-09-03)*
+* The following lints are not new but were only usable through the `clippy`
+ lint groups: [`filter_next`], `for_loop_over_option`,
+ `for_loop_over_result` and [`match_overlapping_arm`]. You should now be
+ able to `#[allow/deny]` them individually and they are available directly
+ through `cargo clippy`.
+
+## 0.0.87 — 2016-08-31
+* Rustup to *rustc 1.13.0-nightly (eac41469d 2016-08-30)*
+* New lints: [`builtin_type_shadow`]
+* Fix FP in [`zero_prefixed_literal`] and `0b`/`0o`
+
+## 0.0.86 — 2016-08-28
+* Rustup to *rustc 1.13.0-nightly (a23064af5 2016-08-27)*
+* New lints: [`missing_docs_in_private_items`], [`zero_prefixed_literal`]
+
+## 0.0.85 — 2016-08-19
+* Fix ICE with [`useless_attribute`]
+* [`useless_attribute`] ignores `unused_imports` on `use` statements
+
+## 0.0.84 — 2016-08-18
+* Rustup to *rustc 1.13.0-nightly (aef6971ca 2016-08-17)*
+
+## 0.0.83 — 2016-08-17
+* Rustup to *rustc 1.12.0-nightly (1bf5fa326 2016-08-16)*
+* New lints: [`print_with_newline`], [`useless_attribute`]
+
+## 0.0.82 — 2016-08-17
+* Rustup to *rustc 1.12.0-nightly (197be89f3 2016-08-15)*
+* New lint: [`module_inception`]
+
+## 0.0.81 — 2016-08-14
+* Rustup to *rustc 1.12.0-nightly (1deb02ea6 2016-08-12)*
+* New lints: [`eval_order_dependence`], [`mixed_case_hex_literals`], [`unseparated_literal_suffix`]
+* False positive fix in [`too_many_arguments`]
+* Addition of functionality to [`needless_borrow`]
+* Suggestions for [`clone_on_copy`]
+* Bug fix in [`wrong_self_convention`]
+* Doc improvements
+
+## 0.0.80 — 2016-07-31
+* Rustup to *rustc 1.12.0-nightly (1225e122f 2016-07-30)*
+* New lints: [`misrefactored_assign_op`], [`serde_api_misuse`]
+
+## 0.0.79 — 2016-07-10
+* Rustup to *rustc 1.12.0-nightly (f93aaf84c 2016-07-09)*
+* Major suggestions refactoring
+
+## 0.0.78 — 2016-07-02
+* Rustup to *rustc 1.11.0-nightly (01411937f 2016-07-01)*
+* New lints: [`wrong_transmute`], [`double_neg`], [`filter_map`]
+* For compatibility, `cargo clippy` does not defines the `clippy` feature
+ introduced in 0.0.76 anymore
+* [`collapsible_if`] now considers `if let`
+
+## 0.0.77 — 2016-06-21
+* Rustup to *rustc 1.11.0-nightly (5522e678b 2016-06-20)*
+* New lints: `stutter` and [`iter_nth`]
+
+## 0.0.76 — 2016-06-10
+* Rustup to *rustc 1.11.0-nightly (7d2f75a95 2016-06-09)*
+* `cargo clippy` now automatically defines the `clippy` feature
+* New lint: [`not_unsafe_ptr_arg_deref`]
+
+## 0.0.75 — 2016-06-08
+* Rustup to *rustc 1.11.0-nightly (763f9234b 2016-06-06)*
+
+## 0.0.74 — 2016-06-07
+* Fix bug with `cargo-clippy` JSON parsing
+* Add the `CLIPPY_DISABLE_DOCS_LINKS` environment variable to deactivate the
+ “for further information visit *lint-link*” message.
+
+## 0.0.73 — 2016-06-05
+* Fix false positives in [`useless_let_if_seq`]
+
+## 0.0.72 — 2016-06-04
+* Fix false positives in [`useless_let_if_seq`]
+
+## 0.0.71 — 2016-05-31
+* Rustup to *rustc 1.11.0-nightly (a967611d8 2016-05-30)*
+* New lint: [`useless_let_if_seq`]
+
+## 0.0.70 — 2016-05-28
+* Rustup to *rustc 1.10.0-nightly (7bddce693 2016-05-27)*
+* [`invalid_regex`] and [`trivial_regex`] can now warn on `RegexSet::new`,
+ `RegexBuilder::new` and byte regexes
+
+## 0.0.69 — 2016-05-20
+* Rustup to *rustc 1.10.0-nightly (476fe6eef 2016-05-21)*
+* [`used_underscore_binding`] has been made `Allow` temporarily
+
+## 0.0.68 — 2016-05-17
+* Rustup to *rustc 1.10.0-nightly (cd6a40017 2016-05-16)*
+* New lint: [`unnecessary_operation`]
+
+## 0.0.67 — 2016-05-12
+* Rustup to *rustc 1.10.0-nightly (22ac88f1a 2016-05-11)*
+
+## 0.0.66 — 2016-05-11
+* New `cargo clippy` subcommand
+* New lints: [`assign_op_pattern`], [`assign_ops`], [`needless_borrow`]
+
+## 0.0.65 — 2016-05-08
+* Rustup to *rustc 1.10.0-nightly (62e2b2fb7 2016-05-06)*
+* New lints: [`float_arithmetic`], [`integer_arithmetic`]
+
+## 0.0.64 — 2016-04-26
+* Rustup to *rustc 1.10.0-nightly (645dd013a 2016-04-24)*
+* New lints: [`temporary_cstring_as_ptr`], [`unsafe_removed_from_name`], and [`mem_forget`]
+
+## 0.0.63 — 2016-04-08
+* Rustup to *rustc 1.9.0-nightly (7979dd608 2016-04-07)*
+
+## 0.0.62 — 2016-04-07
+* Rustup to *rustc 1.9.0-nightly (bf5da36f1 2016-04-06)*
+
+## 0.0.61 — 2016-04-03
+* Rustup to *rustc 1.9.0-nightly (5ab11d72c 2016-04-02)*
+* New lint: [`invalid_upcast_comparisons`]
+
+## 0.0.60 — 2016-04-01
+* Rustup to *rustc 1.9.0-nightly (e1195c24b 2016-03-31)*
+
+## 0.0.59 — 2016-03-31
+* Rustup to *rustc 1.9.0-nightly (30a3849f2 2016-03-30)*
+* New lints: [`logic_bug`], [`nonminimal_bool`]
+* Fixed: [`match_same_arms`] now ignores arms with guards
+* Improved: [`useless_vec`] now warns on `for … in vec![…]`
+
+## 0.0.58 — 2016-03-27
+* Rustup to *rustc 1.9.0-nightly (d5a91e695 2016-03-26)*
+* New lint: [`doc_markdown`]
+
+## 0.0.57 — 2016-03-27
+* Update to *rustc 1.9.0-nightly (a1e29daf1 2016-03-25)*
+* Deprecated lints: [`str_to_string`], [`string_to_string`], [`unstable_as_slice`], [`unstable_as_mut_slice`]
+* New lint: [`crosspointer_transmute`]
+
+## 0.0.56 — 2016-03-23
+* Update to *rustc 1.9.0-nightly (0dcc413e4 2016-03-22)*
+* New lints: [`many_single_char_names`] and [`similar_names`]
+
+## 0.0.55 — 2016-03-21
+* Update to *rustc 1.9.0-nightly (02310fd31 2016-03-19)*
+
+## 0.0.54 — 2016-03-16
+* Update to *rustc 1.9.0-nightly (c66d2380a 2016-03-15)*
+
+## 0.0.53 — 2016-03-15
+* Add a [configuration file]
+
+## ~~0.0.52~~
+
+## 0.0.51 — 2016-03-13
+* Add `str` to types considered by [`len_zero`]
+* New lints: [`indexing_slicing`]
+
+## 0.0.50 — 2016-03-11
+* Update to *rustc 1.9.0-nightly (c9629d61c 2016-03-10)*
+
+## 0.0.49 — 2016-03-09
+* Update to *rustc 1.9.0-nightly (eabfc160f 2016-03-08)*
+* New lints: [`overflow_check_conditional`], [`unused_label`], [`new_without_default`]
+
+## 0.0.48 — 2016-03-07
+* Fixed: ICE in [`needless_range_loop`] with globals
+
+## 0.0.47 — 2016-03-07
+* Update to *rustc 1.9.0-nightly (998a6720b 2016-03-07)*
+* New lint: [`redundant_closure_call`]
+
+[`AsMut`]: https://doc.rust-lang.org/std/convert/trait.AsMut.html
+[`AsRef`]: https://doc.rust-lang.org/std/convert/trait.AsRef.html
+[configuration file]: ./rust-clippy#configuration
+[pull3665]: https://github.com/rust-lang/rust-clippy/pull/3665
+[adding_lints]: https://github.com/rust-lang/rust-clippy/blob/master/doc/adding_lints.md
+
+<!-- lint disable no-unused-definitions -->
+<!-- begin autogenerated links to lint list -->
+[`absurd_extreme_comparisons`]: https://rust-lang.github.io/rust-clippy/master/index.html#absurd_extreme_comparisons
+[`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
+[`as_conversions`]: https://rust-lang.github.io/rust-clippy/master/index.html#as_conversions
+[`assertions_on_constants`]: https://rust-lang.github.io/rust-clippy/master/index.html#assertions_on_constants
+[`assign_op_pattern`]: https://rust-lang.github.io/rust-clippy/master/index.html#assign_op_pattern
+[`assign_ops`]: https://rust-lang.github.io/rust-clippy/master/index.html#assign_ops
++[`async_yields_async`]: https://rust-lang.github.io/rust-clippy/master/index.html#async_yields_async
+[`await_holding_lock`]: https://rust-lang.github.io/rust-clippy/master/index.html#await_holding_lock
+[`bad_bit_mask`]: https://rust-lang.github.io/rust-clippy/master/index.html#bad_bit_mask
+[`bind_instead_of_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#bind_instead_of_map
+[`blacklisted_name`]: https://rust-lang.github.io/rust-clippy/master/index.html#blacklisted_name
+[`blanket_clippy_restriction_lints`]: https://rust-lang.github.io/rust-clippy/master/index.html#blanket_clippy_restriction_lints
+[`blocks_in_if_conditions`]: https://rust-lang.github.io/rust-clippy/master/index.html#blocks_in_if_conditions
+[`bool_comparison`]: https://rust-lang.github.io/rust-clippy/master/index.html#bool_comparison
+[`borrow_interior_mutable_const`]: https://rust-lang.github.io/rust-clippy/master/index.html#borrow_interior_mutable_const
+[`borrowed_box`]: https://rust-lang.github.io/rust-clippy/master/index.html#borrowed_box
+[`box_vec`]: https://rust-lang.github.io/rust-clippy/master/index.html#box_vec
+[`boxed_local`]: https://rust-lang.github.io/rust-clippy/master/index.html#boxed_local
+[`builtin_type_shadow`]: https://rust-lang.github.io/rust-clippy/master/index.html#builtin_type_shadow
+[`cargo_common_metadata`]: https://rust-lang.github.io/rust-clippy/master/index.html#cargo_common_metadata
+[`cast_lossless`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_lossless
+[`cast_possible_truncation`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_possible_truncation
+[`cast_possible_wrap`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_possible_wrap
+[`cast_precision_loss`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_precision_loss
+[`cast_ptr_alignment`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_ptr_alignment
+[`cast_ref_to_mut`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_ref_to_mut
+[`cast_sign_loss`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_sign_loss
+[`char_lit_as_u8`]: https://rust-lang.github.io/rust-clippy/master/index.html#char_lit_as_u8
+[`chars_last_cmp`]: https://rust-lang.github.io/rust-clippy/master/index.html#chars_last_cmp
+[`chars_next_cmp`]: https://rust-lang.github.io/rust-clippy/master/index.html#chars_next_cmp
+[`checked_conversions`]: https://rust-lang.github.io/rust-clippy/master/index.html#checked_conversions
+[`clone_double_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#clone_double_ref
+[`clone_on_copy`]: https://rust-lang.github.io/rust-clippy/master/index.html#clone_on_copy
+[`clone_on_ref_ptr`]: https://rust-lang.github.io/rust-clippy/master/index.html#clone_on_ref_ptr
+[`cmp_nan`]: https://rust-lang.github.io/rust-clippy/master/index.html#cmp_nan
+[`cmp_null`]: https://rust-lang.github.io/rust-clippy/master/index.html#cmp_null
+[`cmp_owned`]: https://rust-lang.github.io/rust-clippy/master/index.html#cmp_owned
+[`cognitive_complexity`]: https://rust-lang.github.io/rust-clippy/master/index.html#cognitive_complexity
+[`collapsible_if`]: https://rust-lang.github.io/rust-clippy/master/index.html#collapsible_if
+[`comparison_chain`]: https://rust-lang.github.io/rust-clippy/master/index.html#comparison_chain
+[`copy_iterator`]: https://rust-lang.github.io/rust-clippy/master/index.html#copy_iterator
++[`create_dir`]: https://rust-lang.github.io/rust-clippy/master/index.html#create_dir
+[`crosspointer_transmute`]: https://rust-lang.github.io/rust-clippy/master/index.html#crosspointer_transmute
+[`dbg_macro`]: https://rust-lang.github.io/rust-clippy/master/index.html#dbg_macro
+[`debug_assert_with_mut_call`]: https://rust-lang.github.io/rust-clippy/master/index.html#debug_assert_with_mut_call
+[`decimal_literal_representation`]: https://rust-lang.github.io/rust-clippy/master/index.html#decimal_literal_representation
+[`declare_interior_mutable_const`]: https://rust-lang.github.io/rust-clippy/master/index.html#declare_interior_mutable_const
+[`default_trait_access`]: https://rust-lang.github.io/rust-clippy/master/index.html#default_trait_access
+[`deprecated_cfg_attr`]: https://rust-lang.github.io/rust-clippy/master/index.html#deprecated_cfg_attr
+[`deprecated_semver`]: https://rust-lang.github.io/rust-clippy/master/index.html#deprecated_semver
+[`deref_addrof`]: https://rust-lang.github.io/rust-clippy/master/index.html#deref_addrof
+[`derive_hash_xor_eq`]: https://rust-lang.github.io/rust-clippy/master/index.html#derive_hash_xor_eq
+[`derive_ord_xor_partial_ord`]: https://rust-lang.github.io/rust-clippy/master/index.html#derive_ord_xor_partial_ord
+[`diverging_sub_expression`]: https://rust-lang.github.io/rust-clippy/master/index.html#diverging_sub_expression
+[`doc_markdown`]: https://rust-lang.github.io/rust-clippy/master/index.html#doc_markdown
+[`double_comparisons`]: https://rust-lang.github.io/rust-clippy/master/index.html#double_comparisons
+[`double_must_use`]: https://rust-lang.github.io/rust-clippy/master/index.html#double_must_use
+[`double_neg`]: https://rust-lang.github.io/rust-clippy/master/index.html#double_neg
+[`double_parens`]: https://rust-lang.github.io/rust-clippy/master/index.html#double_parens
+[`drop_bounds`]: https://rust-lang.github.io/rust-clippy/master/index.html#drop_bounds
+[`drop_copy`]: https://rust-lang.github.io/rust-clippy/master/index.html#drop_copy
+[`drop_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#drop_ref
+[`duplicate_underscore_argument`]: https://rust-lang.github.io/rust-clippy/master/index.html#duplicate_underscore_argument
+[`duration_subsec`]: https://rust-lang.github.io/rust-clippy/master/index.html#duration_subsec
+[`else_if_without_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#else_if_without_else
+[`empty_enum`]: https://rust-lang.github.io/rust-clippy/master/index.html#empty_enum
+[`empty_line_after_outer_attr`]: https://rust-lang.github.io/rust-clippy/master/index.html#empty_line_after_outer_attr
+[`empty_loop`]: https://rust-lang.github.io/rust-clippy/master/index.html#empty_loop
+[`enum_clike_unportable_variant`]: https://rust-lang.github.io/rust-clippy/master/index.html#enum_clike_unportable_variant
+[`enum_glob_use`]: https://rust-lang.github.io/rust-clippy/master/index.html#enum_glob_use
+[`enum_variant_names`]: https://rust-lang.github.io/rust-clippy/master/index.html#enum_variant_names
+[`eq_op`]: https://rust-lang.github.io/rust-clippy/master/index.html#eq_op
+[`erasing_op`]: https://rust-lang.github.io/rust-clippy/master/index.html#erasing_op
+[`eval_order_dependence`]: https://rust-lang.github.io/rust-clippy/master/index.html#eval_order_dependence
+[`excessive_precision`]: https://rust-lang.github.io/rust-clippy/master/index.html#excessive_precision
+[`exit`]: https://rust-lang.github.io/rust-clippy/master/index.html#exit
+[`expect_fun_call`]: https://rust-lang.github.io/rust-clippy/master/index.html#expect_fun_call
+[`expect_used`]: https://rust-lang.github.io/rust-clippy/master/index.html#expect_used
+[`expl_impl_clone_on_copy`]: https://rust-lang.github.io/rust-clippy/master/index.html#expl_impl_clone_on_copy
+[`explicit_counter_loop`]: https://rust-lang.github.io/rust-clippy/master/index.html#explicit_counter_loop
+[`explicit_deref_methods`]: https://rust-lang.github.io/rust-clippy/master/index.html#explicit_deref_methods
+[`explicit_into_iter_loop`]: https://rust-lang.github.io/rust-clippy/master/index.html#explicit_into_iter_loop
+[`explicit_iter_loop`]: https://rust-lang.github.io/rust-clippy/master/index.html#explicit_iter_loop
+[`explicit_write`]: https://rust-lang.github.io/rust-clippy/master/index.html#explicit_write
+[`extend_from_slice`]: https://rust-lang.github.io/rust-clippy/master/index.html#extend_from_slice
+[`extra_unused_lifetimes`]: https://rust-lang.github.io/rust-clippy/master/index.html#extra_unused_lifetimes
+[`fallible_impl_from`]: https://rust-lang.github.io/rust-clippy/master/index.html#fallible_impl_from
+[`filetype_is_file`]: https://rust-lang.github.io/rust-clippy/master/index.html#filetype_is_file
+[`filter_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#filter_map
+[`filter_map_next`]: https://rust-lang.github.io/rust-clippy/master/index.html#filter_map_next
+[`filter_next`]: https://rust-lang.github.io/rust-clippy/master/index.html#filter_next
+[`find_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#find_map
+[`flat_map_identity`]: https://rust-lang.github.io/rust-clippy/master/index.html#flat_map_identity
+[`float_arithmetic`]: https://rust-lang.github.io/rust-clippy/master/index.html#float_arithmetic
+[`float_cmp`]: https://rust-lang.github.io/rust-clippy/master/index.html#float_cmp
+[`float_cmp_const`]: https://rust-lang.github.io/rust-clippy/master/index.html#float_cmp_const
+[`float_equality_without_abs`]: https://rust-lang.github.io/rust-clippy/master/index.html#float_equality_without_abs
+[`fn_address_comparisons`]: https://rust-lang.github.io/rust-clippy/master/index.html#fn_address_comparisons
+[`fn_params_excessive_bools`]: https://rust-lang.github.io/rust-clippy/master/index.html#fn_params_excessive_bools
+[`fn_to_numeric_cast`]: https://rust-lang.github.io/rust-clippy/master/index.html#fn_to_numeric_cast
+[`fn_to_numeric_cast_with_truncation`]: https://rust-lang.github.io/rust-clippy/master/index.html#fn_to_numeric_cast_with_truncation
+[`for_kv_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#for_kv_map
+[`for_loops_over_fallibles`]: https://rust-lang.github.io/rust-clippy/master/index.html#for_loops_over_fallibles
+[`forget_copy`]: https://rust-lang.github.io/rust-clippy/master/index.html#forget_copy
+[`forget_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#forget_ref
+[`future_not_send`]: https://rust-lang.github.io/rust-clippy/master/index.html#future_not_send
+[`get_last_with_len`]: https://rust-lang.github.io/rust-clippy/master/index.html#get_last_with_len
+[`get_unwrap`]: https://rust-lang.github.io/rust-clippy/master/index.html#get_unwrap
+[`identity_op`]: https://rust-lang.github.io/rust-clippy/master/index.html#identity_op
+[`if_let_mutex`]: https://rust-lang.github.io/rust-clippy/master/index.html#if_let_mutex
+[`if_let_redundant_pattern_matching`]: https://rust-lang.github.io/rust-clippy/master/index.html#if_let_redundant_pattern_matching
+[`if_let_some_result`]: https://rust-lang.github.io/rust-clippy/master/index.html#if_let_some_result
+[`if_not_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#if_not_else
+[`if_same_then_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#if_same_then_else
+[`ifs_same_cond`]: https://rust-lang.github.io/rust-clippy/master/index.html#ifs_same_cond
+[`implicit_hasher`]: https://rust-lang.github.io/rust-clippy/master/index.html#implicit_hasher
+[`implicit_return`]: https://rust-lang.github.io/rust-clippy/master/index.html#implicit_return
+[`implicit_saturating_sub`]: https://rust-lang.github.io/rust-clippy/master/index.html#implicit_saturating_sub
+[`imprecise_flops`]: https://rust-lang.github.io/rust-clippy/master/index.html#imprecise_flops
+[`inconsistent_digit_grouping`]: https://rust-lang.github.io/rust-clippy/master/index.html#inconsistent_digit_grouping
+[`indexing_slicing`]: https://rust-lang.github.io/rust-clippy/master/index.html#indexing_slicing
+[`ineffective_bit_mask`]: https://rust-lang.github.io/rust-clippy/master/index.html#ineffective_bit_mask
+[`inefficient_to_string`]: https://rust-lang.github.io/rust-clippy/master/index.html#inefficient_to_string
+[`infallible_destructuring_match`]: https://rust-lang.github.io/rust-clippy/master/index.html#infallible_destructuring_match
+[`infinite_iter`]: https://rust-lang.github.io/rust-clippy/master/index.html#infinite_iter
+[`inherent_to_string`]: https://rust-lang.github.io/rust-clippy/master/index.html#inherent_to_string
+[`inherent_to_string_shadow_display`]: https://rust-lang.github.io/rust-clippy/master/index.html#inherent_to_string_shadow_display
+[`inline_always`]: https://rust-lang.github.io/rust-clippy/master/index.html#inline_always
+[`inline_fn_without_body`]: https://rust-lang.github.io/rust-clippy/master/index.html#inline_fn_without_body
+[`int_plus_one`]: https://rust-lang.github.io/rust-clippy/master/index.html#int_plus_one
+[`integer_arithmetic`]: https://rust-lang.github.io/rust-clippy/master/index.html#integer_arithmetic
+[`integer_division`]: https://rust-lang.github.io/rust-clippy/master/index.html#integer_division
+[`into_iter_on_array`]: https://rust-lang.github.io/rust-clippy/master/index.html#into_iter_on_array
+[`into_iter_on_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#into_iter_on_ref
+[`invalid_atomic_ordering`]: https://rust-lang.github.io/rust-clippy/master/index.html#invalid_atomic_ordering
+[`invalid_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#invalid_ref
+[`invalid_regex`]: https://rust-lang.github.io/rust-clippy/master/index.html#invalid_regex
+[`invalid_upcast_comparisons`]: https://rust-lang.github.io/rust-clippy/master/index.html#invalid_upcast_comparisons
+[`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_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_nth`]: https://rust-lang.github.io/rust-clippy/master/index.html#iter_nth
+[`iter_nth_zero`]: https://rust-lang.github.io/rust-clippy/master/index.html#iter_nth_zero
+[`iter_skip_next`]: https://rust-lang.github.io/rust-clippy/master/index.html#iter_skip_next
+[`iterator_step_by_zero`]: https://rust-lang.github.io/rust-clippy/master/index.html#iterator_step_by_zero
+[`just_underscores_and_digits`]: https://rust-lang.github.io/rust-clippy/master/index.html#just_underscores_and_digits
+[`large_const_arrays`]: https://rust-lang.github.io/rust-clippy/master/index.html#large_const_arrays
+[`large_digit_groups`]: https://rust-lang.github.io/rust-clippy/master/index.html#large_digit_groups
+[`large_enum_variant`]: https://rust-lang.github.io/rust-clippy/master/index.html#large_enum_variant
+[`large_stack_arrays`]: https://rust-lang.github.io/rust-clippy/master/index.html#large_stack_arrays
+[`len_without_is_empty`]: https://rust-lang.github.io/rust-clippy/master/index.html#len_without_is_empty
+[`len_zero`]: https://rust-lang.github.io/rust-clippy/master/index.html#len_zero
+[`let_and_return`]: https://rust-lang.github.io/rust-clippy/master/index.html#let_and_return
+[`let_underscore_lock`]: https://rust-lang.github.io/rust-clippy/master/index.html#let_underscore_lock
+[`let_underscore_must_use`]: https://rust-lang.github.io/rust-clippy/master/index.html#let_underscore_must_use
+[`let_unit_value`]: https://rust-lang.github.io/rust-clippy/master/index.html#let_unit_value
+[`linkedlist`]: https://rust-lang.github.io/rust-clippy/master/index.html#linkedlist
+[`logic_bug`]: https://rust-lang.github.io/rust-clippy/master/index.html#logic_bug
+[`lossy_float_literal`]: https://rust-lang.github.io/rust-clippy/master/index.html#lossy_float_literal
+[`macro_use_imports`]: https://rust-lang.github.io/rust-clippy/master/index.html#macro_use_imports
+[`main_recursion`]: https://rust-lang.github.io/rust-clippy/master/index.html#main_recursion
+[`manual_async_fn`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_async_fn
+[`manual_memcpy`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_memcpy
+[`manual_non_exhaustive`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_non_exhaustive
+[`manual_saturating_arithmetic`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_saturating_arithmetic
+[`manual_swap`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_swap
+[`many_single_char_names`]: https://rust-lang.github.io/rust-clippy/master/index.html#many_single_char_names
+[`map_clone`]: https://rust-lang.github.io/rust-clippy/master/index.html#map_clone
+[`map_entry`]: https://rust-lang.github.io/rust-clippy/master/index.html#map_entry
+[`map_flatten`]: https://rust-lang.github.io/rust-clippy/master/index.html#map_flatten
+[`map_identity`]: https://rust-lang.github.io/rust-clippy/master/index.html#map_identity
+[`map_unwrap_or`]: https://rust-lang.github.io/rust-clippy/master/index.html#map_unwrap_or
+[`match_as_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#match_as_ref
+[`match_bool`]: https://rust-lang.github.io/rust-clippy/master/index.html#match_bool
+[`match_like_matches_macro`]: https://rust-lang.github.io/rust-clippy/master/index.html#match_like_matches_macro
+[`match_on_vec_items`]: https://rust-lang.github.io/rust-clippy/master/index.html#match_on_vec_items
+[`match_overlapping_arm`]: https://rust-lang.github.io/rust-clippy/master/index.html#match_overlapping_arm
+[`match_ref_pats`]: https://rust-lang.github.io/rust-clippy/master/index.html#match_ref_pats
+[`match_same_arms`]: https://rust-lang.github.io/rust-clippy/master/index.html#match_same_arms
+[`match_single_binding`]: https://rust-lang.github.io/rust-clippy/master/index.html#match_single_binding
+[`match_wild_err_arm`]: https://rust-lang.github.io/rust-clippy/master/index.html#match_wild_err_arm
+[`match_wildcard_for_single_variants`]: https://rust-lang.github.io/rust-clippy/master/index.html#match_wildcard_for_single_variants
+[`maybe_infinite_iter`]: https://rust-lang.github.io/rust-clippy/master/index.html#maybe_infinite_iter
+[`mem_discriminant_non_enum`]: https://rust-lang.github.io/rust-clippy/master/index.html#mem_discriminant_non_enum
+[`mem_forget`]: https://rust-lang.github.io/rust-clippy/master/index.html#mem_forget
+[`mem_replace_option_with_none`]: https://rust-lang.github.io/rust-clippy/master/index.html#mem_replace_option_with_none
+[`mem_replace_with_default`]: https://rust-lang.github.io/rust-clippy/master/index.html#mem_replace_with_default
+[`mem_replace_with_uninit`]: https://rust-lang.github.io/rust-clippy/master/index.html#mem_replace_with_uninit
+[`min_max`]: https://rust-lang.github.io/rust-clippy/master/index.html#min_max
+[`misaligned_transmute`]: https://rust-lang.github.io/rust-clippy/master/index.html#misaligned_transmute
+[`mismatched_target_os`]: https://rust-lang.github.io/rust-clippy/master/index.html#mismatched_target_os
+[`misrefactored_assign_op`]: https://rust-lang.github.io/rust-clippy/master/index.html#misrefactored_assign_op
+[`missing_const_for_fn`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_const_for_fn
+[`missing_docs_in_private_items`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_docs_in_private_items
+[`missing_errors_doc`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_errors_doc
+[`missing_inline_in_public_items`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_inline_in_public_items
+[`missing_safety_doc`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_safety_doc
+[`mistyped_literal_suffixes`]: https://rust-lang.github.io/rust-clippy/master/index.html#mistyped_literal_suffixes
+[`mixed_case_hex_literals`]: https://rust-lang.github.io/rust-clippy/master/index.html#mixed_case_hex_literals
+[`module_inception`]: https://rust-lang.github.io/rust-clippy/master/index.html#module_inception
+[`module_name_repetitions`]: https://rust-lang.github.io/rust-clippy/master/index.html#module_name_repetitions
+[`modulo_arithmetic`]: https://rust-lang.github.io/rust-clippy/master/index.html#modulo_arithmetic
+[`modulo_one`]: https://rust-lang.github.io/rust-clippy/master/index.html#modulo_one
+[`multiple_crate_versions`]: https://rust-lang.github.io/rust-clippy/master/index.html#multiple_crate_versions
+[`multiple_inherent_impl`]: https://rust-lang.github.io/rust-clippy/master/index.html#multiple_inherent_impl
+[`must_use_candidate`]: https://rust-lang.github.io/rust-clippy/master/index.html#must_use_candidate
+[`must_use_unit`]: https://rust-lang.github.io/rust-clippy/master/index.html#must_use_unit
+[`mut_from_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#mut_from_ref
+[`mut_mut`]: https://rust-lang.github.io/rust-clippy/master/index.html#mut_mut
+[`mut_range_bound`]: https://rust-lang.github.io/rust-clippy/master/index.html#mut_range_bound
+[`mutable_key_type`]: https://rust-lang.github.io/rust-clippy/master/index.html#mutable_key_type
+[`mutex_atomic`]: https://rust-lang.github.io/rust-clippy/master/index.html#mutex_atomic
+[`mutex_integer`]: https://rust-lang.github.io/rust-clippy/master/index.html#mutex_integer
+[`naive_bytecount`]: https://rust-lang.github.io/rust-clippy/master/index.html#naive_bytecount
+[`needless_arbitrary_self_type`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_arbitrary_self_type
+[`needless_bool`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_bool
+[`needless_borrow`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow
+[`needless_borrowed_reference`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrowed_reference
+[`needless_collect`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_collect
+[`needless_continue`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_continue
+[`needless_doctest_main`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_doctest_main
+[`needless_lifetimes`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_lifetimes
+[`needless_pass_by_value`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_value
+[`needless_range_loop`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_range_loop
+[`needless_return`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_return
+[`needless_update`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_update
+[`neg_cmp_op_on_partial_ord`]: https://rust-lang.github.io/rust-clippy/master/index.html#neg_cmp_op_on_partial_ord
+[`neg_multiply`]: https://rust-lang.github.io/rust-clippy/master/index.html#neg_multiply
+[`never_loop`]: https://rust-lang.github.io/rust-clippy/master/index.html#never_loop
+[`new_ret_no_self`]: https://rust-lang.github.io/rust-clippy/master/index.html#new_ret_no_self
+[`new_without_default`]: https://rust-lang.github.io/rust-clippy/master/index.html#new_without_default
+[`no_effect`]: https://rust-lang.github.io/rust-clippy/master/index.html#no_effect
+[`non_ascii_literal`]: https://rust-lang.github.io/rust-clippy/master/index.html#non_ascii_literal
+[`nonminimal_bool`]: https://rust-lang.github.io/rust-clippy/master/index.html#nonminimal_bool
+[`nonsensical_open_options`]: https://rust-lang.github.io/rust-clippy/master/index.html#nonsensical_open_options
+[`not_unsafe_ptr_arg_deref`]: https://rust-lang.github.io/rust-clippy/master/index.html#not_unsafe_ptr_arg_deref
+[`ok_expect`]: https://rust-lang.github.io/rust-clippy/master/index.html#ok_expect
+[`op_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#op_ref
+[`option_as_ref_deref`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_as_ref_deref
+[`option_env_unwrap`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_env_unwrap
+[`option_if_let_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_if_let_else
+[`option_map_or_none`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_map_or_none
+[`option_map_unit_fn`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_map_unit_fn
+[`option_option`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_option
+[`or_fun_call`]: https://rust-lang.github.io/rust-clippy/master/index.html#or_fun_call
+[`out_of_bounds_indexing`]: https://rust-lang.github.io/rust-clippy/master/index.html#out_of_bounds_indexing
+[`overflow_check_conditional`]: https://rust-lang.github.io/rust-clippy/master/index.html#overflow_check_conditional
+[`panic`]: https://rust-lang.github.io/rust-clippy/master/index.html#panic
+[`panic_params`]: https://rust-lang.github.io/rust-clippy/master/index.html#panic_params
+[`panicking_unwrap`]: https://rust-lang.github.io/rust-clippy/master/index.html#panicking_unwrap
+[`partialeq_ne_impl`]: https://rust-lang.github.io/rust-clippy/master/index.html#partialeq_ne_impl
+[`path_buf_push_overwrite`]: https://rust-lang.github.io/rust-clippy/master/index.html#path_buf_push_overwrite
+[`pattern_type_mismatch`]: https://rust-lang.github.io/rust-clippy/master/index.html#pattern_type_mismatch
+[`possible_missing_comma`]: https://rust-lang.github.io/rust-clippy/master/index.html#possible_missing_comma
+[`precedence`]: https://rust-lang.github.io/rust-clippy/master/index.html#precedence
+[`print_literal`]: https://rust-lang.github.io/rust-clippy/master/index.html#print_literal
+[`print_stdout`]: https://rust-lang.github.io/rust-clippy/master/index.html#print_stdout
+[`print_with_newline`]: https://rust-lang.github.io/rust-clippy/master/index.html#print_with_newline
+[`println_empty_string`]: https://rust-lang.github.io/rust-clippy/master/index.html#println_empty_string
+[`ptr_arg`]: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_arg
+[`ptr_offset_with_cast`]: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_offset_with_cast
+[`pub_enum_variant_names`]: https://rust-lang.github.io/rust-clippy/master/index.html#pub_enum_variant_names
+[`question_mark`]: https://rust-lang.github.io/rust-clippy/master/index.html#question_mark
+[`range_minus_one`]: https://rust-lang.github.io/rust-clippy/master/index.html#range_minus_one
+[`range_plus_one`]: https://rust-lang.github.io/rust-clippy/master/index.html#range_plus_one
+[`range_step_by_zero`]: https://rust-lang.github.io/rust-clippy/master/index.html#range_step_by_zero
+[`range_zip_with_len`]: https://rust-lang.github.io/rust-clippy/master/index.html#range_zip_with_len
+[`redundant_allocation`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_allocation
+[`redundant_clone`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_clone
+[`redundant_closure`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_closure
+[`redundant_closure_call`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_closure_call
+[`redundant_closure_for_method_calls`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_closure_for_method_calls
+[`redundant_field_names`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_field_names
+[`redundant_pattern`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_pattern
+[`redundant_pattern_matching`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_pattern_matching
+[`redundant_pub_crate`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_pub_crate
+[`redundant_static_lifetimes`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_static_lifetimes
+[`ref_in_deref`]: https://rust-lang.github.io/rust-clippy/master/index.html#ref_in_deref
+[`regex_macro`]: https://rust-lang.github.io/rust-clippy/master/index.html#regex_macro
+[`repeat_once`]: https://rust-lang.github.io/rust-clippy/master/index.html#repeat_once
+[`replace_consts`]: https://rust-lang.github.io/rust-clippy/master/index.html#replace_consts
+[`rest_pat_in_fully_bound_structs`]: https://rust-lang.github.io/rust-clippy/master/index.html#rest_pat_in_fully_bound_structs
+[`result_map_or_into_option`]: https://rust-lang.github.io/rust-clippy/master/index.html#result_map_or_into_option
+[`result_map_unit_fn`]: https://rust-lang.github.io/rust-clippy/master/index.html#result_map_unit_fn
+[`reversed_empty_ranges`]: https://rust-lang.github.io/rust-clippy/master/index.html#reversed_empty_ranges
+[`same_functions_in_if_condition`]: https://rust-lang.github.io/rust-clippy/master/index.html#same_functions_in_if_condition
+[`same_item_push`]: https://rust-lang.github.io/rust-clippy/master/index.html#same_item_push
+[`search_is_some`]: https://rust-lang.github.io/rust-clippy/master/index.html#search_is_some
+[`self_assignment`]: https://rust-lang.github.io/rust-clippy/master/index.html#self_assignment
+[`serde_api_misuse`]: https://rust-lang.github.io/rust-clippy/master/index.html#serde_api_misuse
+[`shadow_reuse`]: https://rust-lang.github.io/rust-clippy/master/index.html#shadow_reuse
+[`shadow_same`]: https://rust-lang.github.io/rust-clippy/master/index.html#shadow_same
+[`shadow_unrelated`]: https://rust-lang.github.io/rust-clippy/master/index.html#shadow_unrelated
+[`short_circuit_statement`]: https://rust-lang.github.io/rust-clippy/master/index.html#short_circuit_statement
+[`should_assert_eq`]: https://rust-lang.github.io/rust-clippy/master/index.html#should_assert_eq
+[`should_implement_trait`]: https://rust-lang.github.io/rust-clippy/master/index.html#should_implement_trait
+[`similar_names`]: https://rust-lang.github.io/rust-clippy/master/index.html#similar_names
+[`single_char_pattern`]: https://rust-lang.github.io/rust-clippy/master/index.html#single_char_pattern
+[`single_char_push_str`]: https://rust-lang.github.io/rust-clippy/master/index.html#single_char_push_str
+[`single_component_path_imports`]: https://rust-lang.github.io/rust-clippy/master/index.html#single_component_path_imports
+[`single_match`]: https://rust-lang.github.io/rust-clippy/master/index.html#single_match
+[`single_match_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#single_match_else
+[`skip_while_next`]: https://rust-lang.github.io/rust-clippy/master/index.html#skip_while_next
+[`slow_vector_initialization`]: https://rust-lang.github.io/rust-clippy/master/index.html#slow_vector_initialization
+[`stable_sort_primitive`]: https://rust-lang.github.io/rust-clippy/master/index.html#stable_sort_primitive
+[`str_to_string`]: https://rust-lang.github.io/rust-clippy/master/index.html#str_to_string
+[`string_add`]: https://rust-lang.github.io/rust-clippy/master/index.html#string_add
+[`string_add_assign`]: https://rust-lang.github.io/rust-clippy/master/index.html#string_add_assign
+[`string_extend_chars`]: https://rust-lang.github.io/rust-clippy/master/index.html#string_extend_chars
+[`string_lit_as_bytes`]: https://rust-lang.github.io/rust-clippy/master/index.html#string_lit_as_bytes
+[`string_to_string`]: https://rust-lang.github.io/rust-clippy/master/index.html#string_to_string
+[`struct_excessive_bools`]: https://rust-lang.github.io/rust-clippy/master/index.html#struct_excessive_bools
+[`suboptimal_flops`]: https://rust-lang.github.io/rust-clippy/master/index.html#suboptimal_flops
+[`suspicious_arithmetic_impl`]: https://rust-lang.github.io/rust-clippy/master/index.html#suspicious_arithmetic_impl
+[`suspicious_assignment_formatting`]: https://rust-lang.github.io/rust-clippy/master/index.html#suspicious_assignment_formatting
+[`suspicious_else_formatting`]: https://rust-lang.github.io/rust-clippy/master/index.html#suspicious_else_formatting
+[`suspicious_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#suspicious_map
+[`suspicious_op_assign_impl`]: https://rust-lang.github.io/rust-clippy/master/index.html#suspicious_op_assign_impl
+[`suspicious_unary_op_formatting`]: https://rust-lang.github.io/rust-clippy/master/index.html#suspicious_unary_op_formatting
+[`tabs_in_doc_comments`]: https://rust-lang.github.io/rust-clippy/master/index.html#tabs_in_doc_comments
+[`temporary_assignment`]: https://rust-lang.github.io/rust-clippy/master/index.html#temporary_assignment
+[`temporary_cstring_as_ptr`]: https://rust-lang.github.io/rust-clippy/master/index.html#temporary_cstring_as_ptr
+[`to_digit_is_some`]: https://rust-lang.github.io/rust-clippy/master/index.html#to_digit_is_some
+[`to_string_in_display`]: https://rust-lang.github.io/rust-clippy/master/index.html#to_string_in_display
+[`todo`]: https://rust-lang.github.io/rust-clippy/master/index.html#todo
+[`too_many_arguments`]: https://rust-lang.github.io/rust-clippy/master/index.html#too_many_arguments
+[`too_many_lines`]: https://rust-lang.github.io/rust-clippy/master/index.html#too_many_lines
+[`toplevel_ref_arg`]: https://rust-lang.github.io/rust-clippy/master/index.html#toplevel_ref_arg
+[`trait_duplication_in_bounds`]: https://rust-lang.github.io/rust-clippy/master/index.html#trait_duplication_in_bounds
+[`transmute_bytes_to_str`]: https://rust-lang.github.io/rust-clippy/master/index.html#transmute_bytes_to_str
+[`transmute_float_to_int`]: https://rust-lang.github.io/rust-clippy/master/index.html#transmute_float_to_int
+[`transmute_int_to_bool`]: https://rust-lang.github.io/rust-clippy/master/index.html#transmute_int_to_bool
+[`transmute_int_to_char`]: https://rust-lang.github.io/rust-clippy/master/index.html#transmute_int_to_char
+[`transmute_int_to_float`]: https://rust-lang.github.io/rust-clippy/master/index.html#transmute_int_to_float
+[`transmute_ptr_to_ptr`]: https://rust-lang.github.io/rust-clippy/master/index.html#transmute_ptr_to_ptr
+[`transmute_ptr_to_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#transmute_ptr_to_ref
+[`transmutes_expressible_as_ptr_casts`]: https://rust-lang.github.io/rust-clippy/master/index.html#transmutes_expressible_as_ptr_casts
+[`transmuting_null`]: https://rust-lang.github.io/rust-clippy/master/index.html#transmuting_null
+[`trivial_regex`]: https://rust-lang.github.io/rust-clippy/master/index.html#trivial_regex
+[`trivially_copy_pass_by_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#trivially_copy_pass_by_ref
+[`try_err`]: https://rust-lang.github.io/rust-clippy/master/index.html#try_err
+[`type_complexity`]: https://rust-lang.github.io/rust-clippy/master/index.html#type_complexity
+[`type_repetition_in_bounds`]: https://rust-lang.github.io/rust-clippy/master/index.html#type_repetition_in_bounds
+[`unicode_not_nfc`]: https://rust-lang.github.io/rust-clippy/master/index.html#unicode_not_nfc
+[`unimplemented`]: https://rust-lang.github.io/rust-clippy/master/index.html#unimplemented
+[`uninit_assumed_init`]: https://rust-lang.github.io/rust-clippy/master/index.html#uninit_assumed_init
+[`unit_arg`]: https://rust-lang.github.io/rust-clippy/master/index.html#unit_arg
+[`unit_cmp`]: https://rust-lang.github.io/rust-clippy/master/index.html#unit_cmp
+[`unit_return_expecting_ord`]: https://rust-lang.github.io/rust-clippy/master/index.html#unit_return_expecting_ord
+[`unknown_clippy_lints`]: https://rust-lang.github.io/rust-clippy/master/index.html#unknown_clippy_lints
+[`unnecessary_cast`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast
+[`unnecessary_filter_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_filter_map
+[`unnecessary_fold`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_fold
+[`unnecessary_lazy_evaluations`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_lazy_evaluations
+[`unnecessary_mut_passed`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_mut_passed
+[`unnecessary_operation`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_operation
+[`unnecessary_sort_by`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_sort_by
+[`unnecessary_unwrap`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_unwrap
+[`unneeded_field_pattern`]: https://rust-lang.github.io/rust-clippy/master/index.html#unneeded_field_pattern
+[`unneeded_wildcard_pattern`]: https://rust-lang.github.io/rust-clippy/master/index.html#unneeded_wildcard_pattern
+[`unnested_or_patterns`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnested_or_patterns
+[`unreachable`]: https://rust-lang.github.io/rust-clippy/master/index.html#unreachable
+[`unreadable_literal`]: https://rust-lang.github.io/rust-clippy/master/index.html#unreadable_literal
+[`unsafe_derive_deserialize`]: https://rust-lang.github.io/rust-clippy/master/index.html#unsafe_derive_deserialize
+[`unsafe_removed_from_name`]: https://rust-lang.github.io/rust-clippy/master/index.html#unsafe_removed_from_name
+[`unsafe_vector_initialization`]: https://rust-lang.github.io/rust-clippy/master/index.html#unsafe_vector_initialization
+[`unseparated_literal_suffix`]: https://rust-lang.github.io/rust-clippy/master/index.html#unseparated_literal_suffix
+[`unsound_collection_transmute`]: https://rust-lang.github.io/rust-clippy/master/index.html#unsound_collection_transmute
+[`unstable_as_mut_slice`]: https://rust-lang.github.io/rust-clippy/master/index.html#unstable_as_mut_slice
+[`unstable_as_slice`]: https://rust-lang.github.io/rust-clippy/master/index.html#unstable_as_slice
+[`unused_collect`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_collect
+[`unused_io_amount`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_io_amount
+[`unused_label`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_label
+[`unused_self`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_self
+[`unused_unit`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_unit
+[`unwrap_in_result`]: https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_in_result
+[`unwrap_used`]: https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_used
+[`use_debug`]: https://rust-lang.github.io/rust-clippy/master/index.html#use_debug
+[`use_self`]: https://rust-lang.github.io/rust-clippy/master/index.html#use_self
+[`used_underscore_binding`]: https://rust-lang.github.io/rust-clippy/master/index.html#used_underscore_binding
+[`useless_asref`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_asref
+[`useless_attribute`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_attribute
+[`useless_conversion`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_conversion
+[`useless_format`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_format
+[`useless_let_if_seq`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_let_if_seq
+[`useless_transmute`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_transmute
+[`useless_vec`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_vec
+[`vec_box`]: https://rust-lang.github.io/rust-clippy/master/index.html#vec_box
+[`vec_resize_to_zero`]: https://rust-lang.github.io/rust-clippy/master/index.html#vec_resize_to_zero
+[`verbose_bit_mask`]: https://rust-lang.github.io/rust-clippy/master/index.html#verbose_bit_mask
+[`verbose_file_reads`]: https://rust-lang.github.io/rust-clippy/master/index.html#verbose_file_reads
+[`vtable_address_comparisons`]: https://rust-lang.github.io/rust-clippy/master/index.html#vtable_address_comparisons
+[`while_immutable_condition`]: https://rust-lang.github.io/rust-clippy/master/index.html#while_immutable_condition
+[`while_let_loop`]: https://rust-lang.github.io/rust-clippy/master/index.html#while_let_loop
+[`while_let_on_iterator`]: https://rust-lang.github.io/rust-clippy/master/index.html#while_let_on_iterator
+[`wildcard_dependencies`]: https://rust-lang.github.io/rust-clippy/master/index.html#wildcard_dependencies
+[`wildcard_enum_match_arm`]: https://rust-lang.github.io/rust-clippy/master/index.html#wildcard_enum_match_arm
+[`wildcard_imports`]: https://rust-lang.github.io/rust-clippy/master/index.html#wildcard_imports
+[`wildcard_in_or_patterns`]: https://rust-lang.github.io/rust-clippy/master/index.html#wildcard_in_or_patterns
+[`write_literal`]: https://rust-lang.github.io/rust-clippy/master/index.html#write_literal
+[`write_with_newline`]: https://rust-lang.github.io/rust-clippy/master/index.html#write_with_newline
+[`writeln_empty_string`]: https://rust-lang.github.io/rust-clippy/master/index.html#writeln_empty_string
+[`wrong_pub_self_convention`]: https://rust-lang.github.io/rust-clippy/master/index.html#wrong_pub_self_convention
+[`wrong_self_convention`]: https://rust-lang.github.io/rust-clippy/master/index.html#wrong_self_convention
+[`wrong_transmute`]: https://rust-lang.github.io/rust-clippy/master/index.html#wrong_transmute
+[`zero_divided_by_zero`]: https://rust-lang.github.io/rust-clippy/master/index.html#zero_divided_by_zero
+[`zero_prefixed_literal`]: https://rust-lang.github.io/rust-clippy/master/index.html#zero_prefixed_literal
+[`zero_ptr`]: https://rust-lang.github.io/rust-clippy/master/index.html#zero_ptr
+[`zero_width_space`]: https://rust-lang.github.io/rust-clippy/master/index.html#zero_width_space
+[`zst_offset`]: https://rust-lang.github.io/rust-clippy/master/index.html#zst_offset
+<!-- end autogenerated links to lint list -->
--- /dev/null
--- /dev/null
++use crate::utils::{implements_trait, snippet, span_lint_and_then};
++use rustc_errors::Applicability;
++use rustc_hir::{AsyncGeneratorKind, Body, BodyId, ExprKind, GeneratorKind, QPath};
++use rustc_lint::{LateContext, LateLintPass};
++use rustc_session::{declare_lint_pass, declare_tool_lint};
++
++declare_clippy_lint! {
++ /// **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.
++ ///
++ /// **Known problems:** None.
++ ///
++ /// **Example:**
++ ///
++ /// ```rust
++ /// async fn foo() {}
++ ///
++ /// fn bar() {
++ /// let x = async {
++ /// foo()
++ /// };
++ /// }
++ /// ```
++ /// Use instead:
++ /// ```rust
++ /// async fn foo() {}
++ ///
++ /// fn bar() {
++ /// let x = async {
++ /// foo().await
++ /// };
++ /// }
++ /// ```
++ pub ASYNC_YIELDS_ASYNC,
++ correctness,
++ "async blocks that return a type that can be awaited"
++}
++
++declare_lint_pass!(AsyncYieldsAsync => [ASYNC_YIELDS_ASYNC]);
++
++impl<'tcx> LateLintPass<'tcx> for AsyncYieldsAsync {
++ fn check_body(&mut self, cx: &LateContext<'tcx>, body: &'tcx Body<'_>) {
++ use AsyncGeneratorKind::{Block, Closure};
++ // For functions, with explicitly defined types, don't warn.
++ // XXXkhuey maybe we should?
++ if let Some(GeneratorKind::Async(Block | Closure)) = body.generator_kind {
++ if let Some(future_trait_def_id) = cx.tcx.lang_items().future_trait() {
++ let body_id = BodyId {
++ hir_id: body.value.hir_id,
++ };
++ let def_id = cx.tcx.hir().body_owner_def_id(body_id);
++ let typeck_results = cx.tcx.typeck(def_id);
++ 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 {
++ // XXXkhuey there has to be a better way.
++ ExprKind::Block(block, _) => block.expr.map(|e| e.span),
++ ExprKind::Path(QPath::Resolved(_, path)) => Some(path.span),
++ _ => None,
++ };
++ if let Some(return_expr_span) = return_expr_span {
++ span_lint_and_then(
++ cx,
++ ASYNC_YIELDS_ASYNC,
++ return_expr_span,
++ "an async construct yields a type which is itself awaitable",
++ |db| {
++ db.span_label(body.value.span, "outer async construct");
++ db.span_label(return_expr_span, "awaitable value not awaited");
++ db.span_suggestion(
++ return_expr_span,
++ "consider awaiting this value",
++ format!("{}.await", snippet(cx, return_expr_span, "..")),
++ Applicability::MaybeIncorrect,
++ );
++ },
++ );
++ }
++ }
++ }
++ }
++ }
++}
--- /dev/null
- /// This lint permits `#[allow(unused_imports)]`, `#[allow(deprecated)]` and
- /// `#[allow(unreachable_pub)]` on `use` items and `#[allow(unused_imports)]` on
+//! checks for attributes
+
+use crate::utils::{
+ first_line_of_span, is_present_in_source, match_def_path, paths, snippet_opt, span_lint, span_lint_and_help,
+ span_lint_and_sugg, span_lint_and_then, without_block_comments,
+};
+use if_chain::if_chain;
+use rustc_ast::util::lev_distance::find_best_match_for_name;
+use rustc_ast::{AttrKind, AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem};
+use rustc_errors::Applicability;
+use rustc_hir::{
+ Block, Expr, ExprKind, ImplItem, ImplItemKind, Item, ItemKind, StmtKind, TraitFn, TraitItem, TraitItemKind,
+};
+use rustc_lint::{CheckLintNameResult, EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
+use rustc_middle::lint::in_external_macro;
+use rustc_middle::ty;
+use rustc_session::{declare_lint_pass, declare_tool_lint};
+use rustc_span::source_map::Span;
+use rustc_span::symbol::{Symbol, SymbolStr};
+use semver::Version;
+
+static UNIX_SYSTEMS: &[&str] = &[
+ "android",
+ "dragonfly",
+ "emscripten",
+ "freebsd",
+ "fuchsia",
+ "haiku",
+ "illumos",
+ "ios",
+ "l4re",
+ "linux",
+ "macos",
+ "netbsd",
+ "openbsd",
+ "redox",
+ "solaris",
+ "vxworks",
+];
+
+// NOTE: windows is excluded from the list because it's also a valid target family.
+static NON_UNIX_SYSTEMS: &[&str] = &["cloudabi", "hermit", "none", "wasi"];
+
+declare_clippy_lint! {
+ /// **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:**
+ /// ```ignore
+ /// #[inline(always)]
+ /// fn not_quite_hot_code(..) { ... }
+ /// ```
+ pub INLINE_ALWAYS,
+ pedantic,
+ "use of `#[inline(always)]`"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for `extern crate` and `use` items annotated with
+ /// lint attributes.
+ ///
- // permit `unused_imports`, `deprecated` and `unreachable_pub` for `use` items
++ /// This lint permits `#[allow(unused_imports)]`, `#[allow(deprecated)]`,
++ /// `#[allow(unreachable_pub)]`, `#[allow(clippy::wildcard_imports)]` and
++ /// `#[allow(clippy::enum_glob_use)]` on `use` items and `#[allow(unused_imports)]` on
+ /// `extern crate` items with a `#[macro_use]` attribute.
+ ///
+ /// **Why is this bad?** Lint attributes have no effect on crate imports. Most
+ /// likely a `!` was forgotten.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```ignore
+ /// // Bad
+ /// #[deny(dead_code)]
+ /// extern crate foo;
+ /// #[forbid(dead_code)]
+ /// use foo::bar;
+ ///
+ /// // Ok
+ /// #[allow(unused_imports)]
+ /// use foo::baz;
+ /// #[allow(unused_imports)]
+ /// #[macro_use]
+ /// extern crate baz;
+ /// ```
+ pub USELESS_ATTRIBUTE,
+ correctness,
+ "use of lint attributes on `extern crate` items"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// #[deprecated(since = "forever")]
+ /// fn something_else() { /* ... */ }
+ /// ```
+ pub DEPRECATED_SEMVER,
+ correctness,
+ "use of `#[deprecated(since = \"x\")]` where x is not semver"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ /// ```rust
+ /// // Good (as inner attribute)
+ /// #![inline(always)]
+ ///
+ /// fn this_is_fine() { }
+ ///
+ /// // Bad
+ /// #[inline(always)]
+ ///
+ /// fn not_quite_good_code() { }
+ ///
+ /// // Good (as outer attribute)
+ /// #[inline(always)]
+ /// fn this_is_fine_too() { }
+ /// ```
+ pub EMPTY_LINE_AFTER_OUTER_ATTR,
+ nursery,
+ "empty line after outer attribute"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for `allow`/`warn`/`deny`/`forbid` attributes with scoped clippy
+ /// lints and if those lints exist in clippy. If there is an uppercase letter in the lint name
+ /// (not the tool name) and a lowercase version of this lint exists, it will suggest to lowercase
+ /// the lint name.
+ ///
+ /// **Why is this bad?** A lint attribute with a mistyped lint name won't have an effect.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// Bad:
+ /// ```rust
+ /// #![warn(if_not_els)]
+ /// #![deny(clippy::All)]
+ /// ```
+ ///
+ /// Good:
+ /// ```rust
+ /// #![warn(if_not_else)]
+ /// #![deny(clippy::all)]
+ /// ```
+ pub UNKNOWN_CLIPPY_LINTS,
+ style,
+ "unknown_lints for scoped Clippy lints"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// Bad:
+ /// ```rust
+ /// #![deny(clippy::restriction)]
+ /// ```
+ ///
+ /// Good:
+ /// ```rust
+ /// #![deny(clippy::as_conversions)]
+ /// ```
+ pub BLANKET_CLIPPY_RESTRICTION_LINTS,
+ style,
+ "enabling the complete restriction group"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ ///
+ /// Bad:
+ /// ```rust
+ /// #[cfg_attr(rustfmt, rustfmt_skip)]
+ /// fn main() { }
+ /// ```
+ ///
+ /// Good:
+ /// ```rust
+ /// #[rustfmt::skip]
+ /// fn main() { }
+ /// ```
+ pub DEPRECATED_CFG_ATTR,
+ complexity,
+ "usage of `cfg_attr(rustfmt)` instead of tool attributes"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ ///
+ /// Bad:
+ /// ```rust
+ /// #[cfg(linux)]
+ /// fn conditional() { }
+ /// ```
+ ///
+ /// Good:
+ /// ```rust
+ /// #[cfg(target_os = "linux")]
+ /// fn conditional() { }
+ /// ```
+ ///
+ /// Or:
+ /// ```rust
+ /// #[cfg(unix)]
+ /// fn conditional() { }
+ /// ```
+ /// Check the [Rust Reference](https://doc.rust-lang.org/reference/conditional-compilation.html#target_os) for more details.
+ pub MISMATCHED_TARGET_OS,
+ correctness,
+ "usage of `cfg(operating_system)` instead of `cfg(target_os = \"operating_system\")`"
+}
+
+declare_lint_pass!(Attributes => [
+ INLINE_ALWAYS,
+ DEPRECATED_SEMVER,
+ USELESS_ATTRIBUTE,
+ UNKNOWN_CLIPPY_LINTS,
+ BLANKET_CLIPPY_RESTRICTION_LINTS,
+]);
+
+impl<'tcx> LateLintPass<'tcx> for Attributes {
+ fn check_attribute(&mut self, cx: &LateContext<'tcx>, attr: &'tcx Attribute) {
+ if let Some(items) = &attr.meta_item_list() {
+ if let Some(ident) = attr.ident() {
+ let ident = &*ident.as_str();
+ match ident {
+ "allow" | "warn" | "deny" | "forbid" => {
+ check_clippy_lint_names(cx, ident, items);
+ },
+ _ => {},
+ }
+ if items.is_empty() || !attr.has_name(sym!(deprecated)) {
+ return;
+ }
+ for item in items {
+ if_chain! {
+ if let NestedMetaItem::MetaItem(mi) = &item;
+ if let MetaItemKind::NameValue(lit) = &mi.kind;
+ if mi.has_name(sym!(since));
+ then {
+ check_semver(cx, item.span(), lit);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
+ if is_relevant_item(cx, item) {
+ check_attrs(cx, item.span, item.ident.name, &item.attrs)
+ }
+ match item.kind {
+ ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
+ let skip_unused_imports = item.attrs.iter().any(|attr| attr.has_name(sym!(macro_use)));
+
+ for attr in item.attrs {
+ if in_external_macro(cx.sess(), attr.span) {
+ return;
+ }
+ if let Some(lint_list) = &attr.meta_item_list() {
+ if let Some(ident) = attr.ident() {
+ match &*ident.as_str() {
+ "allow" | "warn" | "deny" | "forbid" => {
- fn check_clippy_lint_names(cx: &LateContext<'_>, ident: &str, items: &[NestedMetaItem]) {
- fn extract_name(lint: &NestedMetaItem) -> Option<SymbolStr> {
- if_chain! {
- if let Some(meta_item) = lint.meta_item();
- if meta_item.path.segments.len() > 1;
- if let tool_name = meta_item.path.segments[0].ident;
- if tool_name.as_str() == "clippy";
- let lint_name = meta_item.path.segments.last().unwrap().ident.name;
- then {
- return Some(lint_name.as_str());
- }
++ // permit `unused_imports`, `deprecated`, `unreachable_pub`,
++ // `clippy::wildcard_imports`, and `clippy::enum_glob_use` for `use` items
+ // and `unused_imports` for `extern crate` items with `macro_use`
+ for lint in lint_list {
+ match item.kind {
+ ItemKind::Use(..) => {
+ if is_word(lint, sym!(unused_imports))
+ || is_word(lint, sym!(deprecated))
+ || is_word(lint, sym!(unreachable_pub))
+ || is_word(lint, sym!(unused))
++ || extract_clippy_lint(lint)
++ .map_or(false, |s| s == "wildcard_imports")
++ || extract_clippy_lint(lint).map_or(false, |s| s == "enum_glob_use")
+ {
+ return;
+ }
+ },
+ ItemKind::ExternCrate(..) => {
+ if is_word(lint, sym!(unused_imports)) && skip_unused_imports {
+ return;
+ }
+ if is_word(lint, sym!(unused_extern_crates)) {
+ return;
+ }
+ },
+ _ => {},
+ }
+ }
+ let line_span = first_line_of_span(cx, attr.span);
+
+ if let Some(mut sugg) = snippet_opt(cx, line_span) {
+ if sugg.contains("#[") {
+ span_lint_and_then(
+ cx,
+ USELESS_ATTRIBUTE,
+ line_span,
+ "useless lint attribute",
+ |diag| {
+ sugg = sugg.replacen("#[", "#![", 1);
+ diag.span_suggestion(
+ line_span,
+ "if you just forgot a `!`, use",
+ sugg,
+ Applicability::MaybeIncorrect,
+ );
+ },
+ );
+ }
+ }
+ },
+ _ => {},
+ }
+ }
+ }
+ }
+ },
+ _ => {},
+ }
+ }
+
+ fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
+ if is_relevant_impl(cx, item) {
+ check_attrs(cx, item.span, item.ident.name, &item.attrs)
+ }
+ }
+
+ fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
+ if is_relevant_trait(cx, item) {
+ check_attrs(cx, item.span, item.ident.name, &item.attrs)
+ }
+ }
+}
+
- None
++/// Returns the lint name if it is clippy lint.
++fn extract_clippy_lint(lint: &NestedMetaItem) -> Option<SymbolStr> {
++ if_chain! {
++ if let Some(meta_item) = lint.meta_item();
++ if meta_item.path.segments.len() > 1;
++ if let tool_name = meta_item.path.segments[0].ident;
++ if tool_name.as_str() == "clippy";
++ let lint_name = meta_item.path.segments.last().unwrap().ident.name;
++ then {
++ return Some(lint_name.as_str());
+ }
- if let Some(lint_name) = extract_name(lint) {
+ }
++ None
++}
+
++fn check_clippy_lint_names(cx: &LateContext<'_>, ident: &str, items: &[NestedMetaItem]) {
+ let lint_store = cx.lints();
+ for lint in items {
++ if let Some(lint_name) = extract_clippy_lint(lint) {
+ if let CheckLintNameResult::Tool(Err((None, _))) =
+ lint_store.check_lint_name(&lint_name, Some(sym!(clippy)))
+ {
+ span_lint_and_then(
+ cx,
+ UNKNOWN_CLIPPY_LINTS,
+ lint.span(),
+ &format!("unknown clippy lint: clippy::{}", lint_name),
+ |diag| {
+ let name_lower = lint_name.to_lowercase();
+ let symbols = lint_store
+ .get_lints()
+ .iter()
+ .map(|l| Symbol::intern(&l.name_lower()))
+ .collect::<Vec<_>>();
+ let sugg = find_best_match_for_name(
+ symbols.iter(),
+ Symbol::intern(&format!("clippy::{}", name_lower)),
+ None,
+ );
+ if lint_name.chars().any(char::is_uppercase)
+ && lint_store.find_lints(&format!("clippy::{}", name_lower)).is_ok()
+ {
+ diag.span_suggestion(
+ lint.span(),
+ "lowercase the lint name",
+ format!("clippy::{}", name_lower),
+ Applicability::MachineApplicable,
+ );
+ } else if let Some(sugg) = sugg {
+ diag.span_suggestion(
+ lint.span(),
+ "did you mean",
+ sugg.to_string(),
+ Applicability::MachineApplicable,
+ );
+ }
+ },
+ );
+ } else if lint_name == "restriction" && ident != "allow" {
+ span_lint_and_help(
+ cx,
+ BLANKET_CLIPPY_RESTRICTION_LINTS,
+ lint.span(),
+ "restriction lints are not meant to be all enabled",
+ None,
+ "try enabling only the lints you really need",
+ );
+ }
+ }
+ }
+}
+
+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)
+ } else {
+ true
+ }
+}
+
+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),
+ _ => false,
+ }
+}
+
+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)
+ },
+ _ => false,
+ }
+}
+
+fn is_relevant_block(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, block: &Block<'_>) -> bool {
+ block.stmts.first().map_or(
+ block
+ .expr
+ .as_ref()
+ .map_or(false, |e| is_relevant_expr(cx, typeck_results, e)),
+ |stmt| match &stmt.kind {
+ StmtKind::Local(_) => true,
+ StmtKind::Expr(expr) | StmtKind::Semi(expr) => is_relevant_expr(cx, typeck_results, expr),
+ _ => false,
+ },
+ )
+}
+
+fn is_relevant_expr(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, expr: &Expr<'_>) -> bool {
+ match &expr.kind {
+ ExprKind::Block(block, _) => is_relevant_block(cx, typeck_results, block),
+ ExprKind::Ret(Some(e)) => is_relevant_expr(cx, typeck_results, e),
+ ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
+ ExprKind::Call(path_expr, _) => {
+ if let ExprKind::Path(qpath) = &path_expr.kind {
+ typeck_results
+ .qpath_res(qpath, path_expr.hir_id)
+ .opt_def_id()
+ .map_or(true, |fun_id| !match_def_path(cx, fun_id, &paths::BEGIN_PANIC))
+ } else {
+ true
+ }
+ },
+ _ => true,
+ }
+}
+
+fn check_attrs(cx: &LateContext<'_>, span: Span, name: Symbol, attrs: &[Attribute]) {
+ if span.from_expansion() {
+ return;
+ }
+
+ for attr in attrs {
+ if let Some(values) = attr.meta_item_list() {
+ if values.len() != 1 || !attr.has_name(sym!(inline)) {
+ continue;
+ }
+ if is_word(&values[0], sym!(always)) {
+ span_lint(
+ cx,
+ INLINE_ALWAYS,
+ attr.span,
+ &format!(
+ "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
+ name
+ ),
+ );
+ }
+ }
+ }
+}
+
+fn check_semver(cx: &LateContext<'_>, span: Span, lit: &Lit) {
+ if let LitKind::Str(is, _) = lit.kind {
+ if Version::parse(&is.as_str()).is_ok() {
+ return;
+ }
+ }
+ span_lint(
+ cx,
+ DEPRECATED_SEMVER,
+ span,
+ "the since field must contain a semver-compliant version",
+ );
+}
+
+fn is_word(nmi: &NestedMetaItem, expected: Symbol) -> bool {
+ if let NestedMetaItem::MetaItem(mi) = &nmi {
+ mi.is_word() && mi.has_name(expected)
+ } else {
+ false
+ }
+}
+
+declare_lint_pass!(EarlyAttributes => [
+ DEPRECATED_CFG_ATTR,
+ MISMATCHED_TARGET_OS,
+ EMPTY_LINE_AFTER_OUTER_ATTR,
+]);
+
+impl EarlyLintPass for EarlyAttributes {
+ fn check_item(&mut self, cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
+ check_empty_line_after_outer_attr(cx, item);
+ }
+
+ fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) {
+ check_deprecated_cfg_attr(cx, attr);
+ check_mismatched_target_os(cx, attr);
+ }
+}
+
+fn check_empty_line_after_outer_attr(cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
+ for attr in &item.attrs {
+ let attr_item = if let AttrKind::Normal(ref attr) = attr.kind {
+ attr
+ } else {
+ return;
+ };
+
+ if attr.style == AttrStyle::Outer {
+ if attr_item.args.inner_tokens().is_empty() || !is_present_in_source(cx, attr.span) {
+ return;
+ }
+
+ let begin_of_attr_to_item = Span::new(attr.span.lo(), item.span.lo(), item.span.ctxt());
+ let end_of_attr_to_item = Span::new(attr.span.hi(), item.span.lo(), item.span.ctxt());
+
+ if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
+ let lines = snippet.split('\n').collect::<Vec<_>>();
+ let lines = without_block_comments(lines);
+
+ if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
+ span_lint(
+ cx,
+ EMPTY_LINE_AFTER_OUTER_ATTR,
+ begin_of_attr_to_item,
+ "found an empty line after an outer attribute. \
+ Perhaps you forgot to add a `!` to make it an inner attribute?",
+ );
+ }
+ }
+ }
+ }
+}
+
+fn check_deprecated_cfg_attr(cx: &EarlyContext<'_>, attr: &Attribute) {
+ if_chain! {
+ // check cfg_attr
+ if attr.has_name(sym!(cfg_attr));
+ if let Some(items) = attr.meta_item_list();
+ if items.len() == 2;
+ // check for `rustfmt`
+ if let Some(feature_item) = items[0].meta_item();
+ if feature_item.has_name(sym!(rustfmt));
+ // check for `rustfmt_skip` and `rustfmt::skip`
+ if let Some(skip_item) = &items[1].meta_item();
+ if skip_item.has_name(sym!(rustfmt_skip)) ||
+ skip_item.path.segments.last().expect("empty path in attribute").ident.name == sym!(skip);
+ // Only lint outer attributes, because custom inner attributes are unstable
+ // Tracking issue: https://github.com/rust-lang/rust/issues/54726
+ if let AttrStyle::Outer = attr.style;
+ then {
+ span_lint_and_sugg(
+ cx,
+ DEPRECATED_CFG_ATTR,
+ attr.span,
+ "`cfg_attr` is deprecated for rustfmt and got replaced by tool attributes",
+ "use",
+ "#[rustfmt::skip]".to_string(),
+ Applicability::MachineApplicable,
+ );
+ }
+ }
+}
+
+fn check_mismatched_target_os(cx: &EarlyContext<'_>, attr: &Attribute) {
+ fn find_os(name: &str) -> Option<&'static str> {
+ UNIX_SYSTEMS
+ .iter()
+ .chain(NON_UNIX_SYSTEMS.iter())
+ .find(|&&os| os == name)
+ .copied()
+ }
+
+ fn is_unix(name: &str) -> bool {
+ UNIX_SYSTEMS.iter().any(|&os| os == name)
+ }
+
+ fn find_mismatched_target_os(items: &[NestedMetaItem]) -> Vec<(&str, Span)> {
+ let mut mismatched = Vec::new();
+
+ for item in items {
+ if let NestedMetaItem::MetaItem(meta) = item {
+ match &meta.kind {
+ MetaItemKind::List(list) => {
+ mismatched.extend(find_mismatched_target_os(&list));
+ },
+ MetaItemKind::Word => {
+ if_chain! {
+ if let Some(ident) = meta.ident();
+ if let Some(os) = find_os(&*ident.name.as_str());
+ then {
+ mismatched.push((os, ident.span));
+ }
+ }
+ },
+ _ => {},
+ }
+ }
+ }
+
+ mismatched
+ }
+
+ if_chain! {
+ if attr.has_name(sym!(cfg));
+ if let Some(list) = attr.meta_item_list();
+ let mismatched = find_mismatched_target_os(&list);
+ if !mismatched.is_empty();
+ then {
+ let mess = "operating system used in target family position";
+
+ span_lint_and_then(cx, MISMATCHED_TARGET_OS, attr.span, &mess, |diag| {
+ // Avoid showing the unix suggestion multiple times in case
+ // we have more than one mismatch for unix-like systems
+ let mut unix_suggested = false;
+
+ for (os, span) in mismatched {
+ let sugg = format!("target_os = \"{}\"", os);
+ diag.span_suggestion(span, "try", sugg, Applicability::MaybeIncorrect);
+
+ if !unix_suggested && is_unix(os) {
+ diag.help("Did you mean `unix`?");
+ unix_suggested = true;
+ }
+ }
+ });
+ }
+ }
+}
--- /dev/null
--- /dev/null
++use crate::utils::{match_def_path, paths, snippet, span_lint_and_sugg};
++use if_chain::if_chain;
++use rustc_errors::Applicability;
++use rustc_hir::{Expr, ExprKind};
++use rustc_lint::{LateContext, LateLintPass};
++use rustc_session::{declare_lint_pass, declare_tool_lint};
++
++declare_clippy_lint! {
++ /// **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::crate_dir` is mistakenly chosen over `std::fs::create_dir_all`.
++ ///
++ /// **Known problems:** None.
++ ///
++ /// **Example:**
++ ///
++ /// ```rust
++ /// std::fs::create_dir("foo");
++ /// ```
++ /// Use instead:
++ /// ```rust
++ /// std::fs::create_dir_all("foo");
++ /// ```
++ pub CREATE_DIR,
++ restriction,
++ "calling `std::fs::create_dir` instead of `std::fs::create_dir_all`"
++}
++
++declare_lint_pass!(CreateDir => [CREATE_DIR]);
++
++impl LateLintPass<'_> for CreateDir {
++ fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
++ if_chain! {
++ if let ExprKind::Call(ref func, ref args) = expr.kind;
++ if let ExprKind::Path(ref path) = func.kind;
++ if let Some(def_id) = cx.qpath_res(path, func.hir_id).opt_def_id();
++ if match_def_path(cx, def_id, &paths::STD_FS_CREATE_DIR);
++ then {
++ span_lint_and_sugg(
++ cx,
++ CREATE_DIR,
++ expr.span,
++ "calling `std::fs::create_dir` where there may be a better way",
++ "consider calling `std::fs::create_dir_all` instead",
++ format!("create_dir_all({})", snippet(cx, args[0].span, "..")),
++ Applicability::MaybeIncorrect,
++ )
++ }
++ }
++ }
++}
--- /dev/null
- match qpath {
- QPath::Resolved(..) => {
- if_chain! {
- // Detect and ignore <Foo as Default>::default() because these calls do
- // explicitly name the type.
- if let ExprKind::Call(ref method, ref _args) = expr.kind;
- if let ExprKind::Path(ref p) = method.kind;
- if let QPath::Resolved(Some(_ty), _path) = p;
- then {
- return;
- }
- }
-
- // TODO: Work out a way to put "whatever the imported way of referencing
- // this type in this file" rather than a fully-qualified type.
- let expr_ty = cx.typeck_results().expr_ty(expr);
- if let ty::Adt(..) = expr_ty.kind() {
- let replacement = format!("{}::default()", expr_ty);
- span_lint_and_sugg(
- cx,
- DEFAULT_TRAIT_ACCESS,
- expr.span,
- &format!("calling `{}` is more clear than this expression", replacement),
- "try",
- replacement,
- Applicability::Unspecified, // First resolve the TODO above
- );
- }
- },
- QPath::TypeRelative(..) | QPath::LangItem(..) => {},
+use if_chain::if_chain;
+use rustc_errors::Applicability;
+use rustc_hir::{Expr, ExprKind, QPath};
+use rustc_lint::{LateContext, LateLintPass};
+use rustc_middle::ty;
+use rustc_session::{declare_lint_pass, declare_tool_lint};
+
+use crate::utils::{any_parent_is_automatically_derived, match_def_path, paths, span_lint_and_sugg};
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for literal calls to `Default::default()`.
+ ///
+ /// **Why is this bad?** It's more clear to the reader to use the name of the type whose default is
+ /// being gotten than the generic `Default`.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// // Bad
+ /// let s: String = Default::default();
+ ///
+ /// // Good
+ /// let s = String::default();
+ /// ```
+ pub DEFAULT_TRAIT_ACCESS,
+ pedantic,
+ "checks for literal calls to `Default::default()`"
+}
+
+declare_lint_pass!(DefaultTraitAccess => [DEFAULT_TRAIT_ACCESS]);
+
+impl<'tcx> LateLintPass<'tcx> for DefaultTraitAccess {
+ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
+ if_chain! {
+ if let ExprKind::Call(ref path, ..) = expr.kind;
+ if !any_parent_is_automatically_derived(cx.tcx, expr.hir_id);
+ if let ExprKind::Path(ref qpath) = path.kind;
+ if let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id();
+ if match_def_path(cx, def_id, &paths::DEFAULT_TRAIT_METHOD);
++ // Detect and ignore <Foo as Default>::default() because these calls do explicitly name the type.
++ if let QPath::Resolved(None, _path) = qpath;
+ then {
++ let expr_ty = cx.typeck_results().expr_ty(expr);
++ if let ty::Adt(def, ..) = expr_ty.kind() {
++ // TODO: Work out a way to put "whatever the imported way of referencing
++ // this type in this file" rather than a fully-qualified type.
++ let replacement = format!("{}::default()", cx.tcx.def_path_str(def.did));
++ span_lint_and_sugg(
++ cx,
++ DEFAULT_TRAIT_ACCESS,
++ expr.span,
++ &format!("calling `{}` is more clear than this expression", replacement),
++ "try",
++ replacement,
++ Applicability::Unspecified, // First resolve the TODO above
++ );
+ }
+ }
+ }
+ }
+}
--- /dev/null
- span_lint(cx, TOO_MANY_LINES, span, "this function has a large number of lines")
+use crate::utils::{
+ attr_by_name, attrs::is_proc_macro, is_must_use_ty, is_trait_impl_item, iter_input_pats, match_def_path,
+ must_use_attr, qpath_res, return_ty, snippet, snippet_opt, span_lint, span_lint_and_help, span_lint_and_then,
+ trait_ref_of_method, type_is_unsafe_function,
+};
+use rustc_ast::ast::Attribute;
+use rustc_data_structures::fx::FxHashSet;
+use rustc_errors::Applicability;
+use rustc_hir as hir;
+use rustc_hir::intravisit;
+use rustc_hir::{def::Res, def_id::DefId};
+use rustc_lint::{LateContext, LateLintPass, LintContext};
+use rustc_middle::hir::map::Map;
+use rustc_middle::lint::in_external_macro;
+use rustc_middle::ty::{self, Ty};
+use rustc_session::{declare_tool_lint, impl_lint_pass};
+use rustc_span::source_map::Span;
+use rustc_target::spec::abi::Abi;
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # struct Color;
+ /// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) {
+ /// // ..
+ /// }
+ /// ```
+ pub TOO_MANY_ARGUMENTS,
+ complexity,
+ "functions with too many arguments"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// fn im_too_long() {
+ /// println!("");
+ /// // ... 100 more LoC
+ /// println!("");
+ /// }
+ /// ```
+ pub TOO_MANY_LINES,
+ pedantic,
+ "functions with too many lines"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ /// ```rust,ignore
+ /// // Bad
+ /// pub fn foo(x: *const u8) {
+ /// println!("{}", unsafe { *x });
+ /// }
+ ///
+ /// // Good
+ /// pub unsafe fn foo(x: *const u8) {
+ /// println!("{}", unsafe { *x });
+ /// }
+ /// ```
+ pub NOT_UNSAFE_PTR_ARG_DEREF,
+ correctness,
+ "public functions dereferencing raw pointer arguments but not marked `unsafe`"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for a [`#[must_use]`] attribute on
+ /// unit-returning functions and methods.
+ ///
+ /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
+ ///
+ /// **Why is this bad?** Unit values are useless. The attribute is likely
+ /// a remnant of a refactoring that removed the return type.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Examples:**
+ /// ```rust
+ /// #[must_use]
+ /// fn useless() { }
+ /// ```
+ pub MUST_USE_UNIT,
+ style,
+ "`#[must_use]` attribute on a unit-returning function / method"
+}
+
+declare_clippy_lint! {
+ /// **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]`.
+ ///
+ /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
+ ///
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Examples:**
+ /// ```rust
+ /// #[must_use]
+ /// fn double_must_use() -> Result<(), ()> {
+ /// unimplemented!();
+ /// }
+ /// ```
+ pub DOUBLE_MUST_USE,
+ style,
+ "`#[must_use]` attribute on a `#[must_use]`-returning function / method"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
+ ///
+ /// **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:**
+ /// ```rust
+ /// // this could be annotated with `#[must_use]`.
+ /// fn id<T>(t: T) -> T { t }
+ /// ```
+ pub MUST_USE_CANDIDATE,
+ pedantic,
+ "function or method that could take a `#[must_use]` attribute"
+}
+
+#[derive(Copy, Clone)]
+pub struct Functions {
+ threshold: u64,
+ max_lines: u64,
+}
+
+impl Functions {
+ pub fn new(threshold: u64, max_lines: u64) -> Self {
+ Self { threshold, max_lines }
+ }
+}
+
+impl_lint_pass!(Functions => [
+ TOO_MANY_ARGUMENTS,
+ TOO_MANY_LINES,
+ NOT_UNSAFE_PTR_ARG_DEREF,
+ MUST_USE_UNIT,
+ DOUBLE_MUST_USE,
+ MUST_USE_CANDIDATE,
+]);
+
+impl<'tcx> LateLintPass<'tcx> for Functions {
+ fn check_fn(
+ &mut self,
+ cx: &LateContext<'tcx>,
+ kind: intravisit::FnKind<'tcx>,
+ decl: &'tcx hir::FnDecl<'_>,
+ body: &'tcx hir::Body<'_>,
+ span: Span,
+ hir_id: hir::HirId,
+ ) {
+ let unsafety = match kind {
+ intravisit::FnKind::ItemFn(_, _, hir::FnHeader { unsafety, .. }, _, _) => unsafety,
+ intravisit::FnKind::Method(_, sig, _, _) => sig.header.unsafety,
+ intravisit::FnKind::Closure(_) => return,
+ };
+
+ // don't warn for implementations, it's not their fault
+ if !is_trait_impl_item(cx, hir_id) {
+ // don't lint extern functions decls, it's not their fault either
+ match kind {
+ intravisit::FnKind::Method(
+ _,
+ &hir::FnSig {
+ header: hir::FnHeader { abi: Abi::Rust, .. },
+ ..
+ },
+ _,
+ _,
+ )
+ | intravisit::FnKind::ItemFn(_, _, hir::FnHeader { abi: Abi::Rust, .. }, _, _) => {
+ self.check_arg_number(cx, decl, span.with_hi(decl.output.span().hi()))
+ },
+ _ => {},
+ }
+ }
+
+ Self::check_raw_ptr(cx, unsafety, decl, body, hir_id);
+ self.check_line_number(cx, span, body);
+ }
+
+ fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
+ let attr = must_use_attr(&item.attrs);
+ if let hir::ItemKind::Fn(ref sig, ref _generics, ref body_id) = item.kind {
+ if let Some(attr) = attr {
+ let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
+ check_needless_must_use(cx, &sig.decl, item.hir_id, item.span, fn_header_span, attr);
+ return;
+ }
+ if cx.access_levels.is_exported(item.hir_id)
+ && !is_proc_macro(cx.sess(), &item.attrs)
+ && attr_by_name(&item.attrs, "no_mangle").is_none()
+ {
+ check_must_use_candidate(
+ cx,
+ &sig.decl,
+ cx.tcx.hir().body(*body_id),
+ item.span,
+ item.hir_id,
+ item.span.with_hi(sig.decl.output.span().hi()),
+ "this function could have a `#[must_use]` attribute",
+ );
+ }
+ }
+ }
+
+ fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
+ if let hir::ImplItemKind::Fn(ref sig, ref body_id) = item.kind {
+ let attr = must_use_attr(&item.attrs);
+ if let Some(attr) = attr {
+ let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
+ check_needless_must_use(cx, &sig.decl, item.hir_id, item.span, fn_header_span, attr);
+ } else if cx.access_levels.is_exported(item.hir_id)
+ && !is_proc_macro(cx.sess(), &item.attrs)
+ && trait_ref_of_method(cx, item.hir_id).is_none()
+ {
+ check_must_use_candidate(
+ cx,
+ &sig.decl,
+ cx.tcx.hir().body(*body_id),
+ item.span,
+ item.hir_id,
+ item.span.with_hi(sig.decl.output.span().hi()),
+ "this method could have a `#[must_use]` attribute",
+ );
+ }
+ }
+ }
+
+ fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
+ if let hir::TraitItemKind::Fn(ref sig, ref eid) = item.kind {
+ // don't lint extern functions decls, it's not their fault
+ if sig.header.abi == Abi::Rust {
+ self.check_arg_number(cx, &sig.decl, item.span.with_hi(sig.decl.output.span().hi()));
+ }
+
+ let attr = must_use_attr(&item.attrs);
+ if let Some(attr) = attr {
+ let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
+ check_needless_must_use(cx, &sig.decl, item.hir_id, item.span, fn_header_span, attr);
+ }
+ if let hir::TraitFn::Provided(eid) = *eid {
+ let body = cx.tcx.hir().body(eid);
+ Self::check_raw_ptr(cx, sig.header.unsafety, &sig.decl, body, item.hir_id);
+
+ if attr.is_none() && cx.access_levels.is_exported(item.hir_id) && !is_proc_macro(cx.sess(), &item.attrs)
+ {
+ check_must_use_candidate(
+ cx,
+ &sig.decl,
+ body,
+ item.span,
+ item.hir_id,
+ item.span.with_hi(sig.decl.output.span().hi()),
+ "this method could have a `#[must_use]` attribute",
+ );
+ }
+ }
+ }
+ }
+}
+
+impl<'tcx> Functions {
+ fn check_arg_number(self, cx: &LateContext<'_>, decl: &hir::FnDecl<'_>, fn_span: Span) {
+ let args = decl.inputs.len() as u64;
+ if args > self.threshold {
+ span_lint(
+ cx,
+ TOO_MANY_ARGUMENTS,
+ fn_span,
+ &format!("this function has too many arguments ({}/{})", args, self.threshold),
+ );
+ }
+ }
+
+ fn check_line_number(self, cx: &LateContext<'_>, span: Span, body: &'tcx hir::Body<'_>) {
+ if in_external_macro(cx.sess(), span) {
+ return;
+ }
+
+ let code_snippet = snippet(cx, body.value.span, "..");
+ let mut line_count: u64 = 0;
+ let mut in_comment = false;
+ let mut code_in_line;
+
+ // Skip the surrounding function decl.
+ let start_brace_idx = code_snippet.find('{').map_or(0, |i| i + 1);
+ let end_brace_idx = code_snippet.rfind('}').unwrap_or_else(|| code_snippet.len());
+ let function_lines = code_snippet[start_brace_idx..end_brace_idx].lines();
+
+ for mut line in function_lines {
+ code_in_line = false;
+ loop {
+ line = line.trim_start();
+ if line.is_empty() {
+ break;
+ }
+ if in_comment {
+ match line.find("*/") {
+ Some(i) => {
+ line = &line[i + 2..];
+ in_comment = false;
+ continue;
+ },
+ None => break,
+ }
+ } else {
+ let multi_idx = line.find("/*").unwrap_or_else(|| line.len());
+ let single_idx = line.find("//").unwrap_or_else(|| line.len());
+ code_in_line |= multi_idx > 0 && single_idx > 0;
+ // Implies multi_idx is below line.len()
+ if multi_idx < single_idx {
+ line = &line[multi_idx + 2..];
+ in_comment = true;
+ continue;
+ }
+ break;
+ }
+ }
+ if code_in_line {
+ line_count += 1;
+ }
+ }
+
+ if line_count > self.max_lines {
++ span_lint(
++ cx,
++ TOO_MANY_LINES,
++ span,
++ &format!("this function has too many lines ({}/{})", line_count, self.max_lines),
++ )
+ }
+ }
+
+ fn check_raw_ptr(
+ cx: &LateContext<'tcx>,
+ unsafety: hir::Unsafety,
+ decl: &'tcx hir::FnDecl<'_>,
+ body: &'tcx hir::Body<'_>,
+ hir_id: hir::HirId,
+ ) {
+ let expr = &body.value;
+ if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(hir_id) {
+ let raw_ptrs = iter_input_pats(decl, body)
+ .zip(decl.inputs.iter())
+ .filter_map(|(arg, ty)| raw_ptr_arg(arg, ty))
+ .collect::<FxHashSet<_>>();
+
+ if !raw_ptrs.is_empty() {
+ let typeck_results = cx.tcx.typeck_body(body.id());
+ let mut v = DerefVisitor {
+ cx,
+ ptrs: raw_ptrs,
+ typeck_results,
+ };
+
+ intravisit::walk_expr(&mut v, expr);
+ }
+ }
+ }
+}
+
+fn check_needless_must_use(
+ cx: &LateContext<'_>,
+ decl: &hir::FnDecl<'_>,
+ item_id: hir::HirId,
+ item_span: Span,
+ fn_header_span: Span,
+ attr: &Attribute,
+) {
+ if in_external_macro(cx.sess(), item_span) {
+ return;
+ }
+ if returns_unit(decl) {
+ span_lint_and_then(
+ cx,
+ MUST_USE_UNIT,
+ fn_header_span,
+ "this unit-returning function has a `#[must_use]` attribute",
+ |diag| {
+ diag.span_suggestion(
+ attr.span,
+ "remove the attribute",
+ "".into(),
+ Applicability::MachineApplicable,
+ );
+ },
+ );
+ } else if !attr.is_value_str() && is_must_use_ty(cx, return_ty(cx, item_id)) {
+ span_lint_and_help(
+ cx,
+ DOUBLE_MUST_USE,
+ fn_header_span,
+ "this function has an empty `#[must_use]` attribute, but returns a type already marked as `#[must_use]`",
+ None,
+ "either add some descriptive text or remove the attribute",
+ );
+ }
+}
+
+fn check_must_use_candidate<'tcx>(
+ cx: &LateContext<'tcx>,
+ decl: &'tcx hir::FnDecl<'_>,
+ body: &'tcx hir::Body<'_>,
+ item_span: Span,
+ item_id: hir::HirId,
+ fn_span: Span,
+ msg: &str,
+) {
+ if has_mutable_arg(cx, body)
+ || mutates_static(cx, body)
+ || in_external_macro(cx.sess(), item_span)
+ || returns_unit(decl)
+ || !cx.access_levels.is_exported(item_id)
+ || is_must_use_ty(cx, return_ty(cx, item_id))
+ {
+ return;
+ }
+ span_lint_and_then(cx, MUST_USE_CANDIDATE, fn_span, msg, |diag| {
+ if let Some(snippet) = snippet_opt(cx, fn_span) {
+ diag.span_suggestion(
+ fn_span,
+ "add the attribute",
+ format!("#[must_use] {}", snippet),
+ Applicability::MachineApplicable,
+ );
+ }
+ });
+}
+
+fn returns_unit(decl: &hir::FnDecl<'_>) -> bool {
+ match decl.output {
+ hir::FnRetTy::DefaultReturn(_) => true,
+ hir::FnRetTy::Return(ref ty) => match ty.kind {
+ hir::TyKind::Tup(ref tys) => tys.is_empty(),
+ hir::TyKind::Never => true,
+ _ => false,
+ },
+ }
+}
+
+fn has_mutable_arg(cx: &LateContext<'_>, body: &hir::Body<'_>) -> bool {
+ let mut tys = FxHashSet::default();
+ body.params.iter().any(|param| is_mutable_pat(cx, ¶m.pat, &mut tys))
+}
+
+fn is_mutable_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, tys: &mut FxHashSet<DefId>) -> bool {
+ if let hir::PatKind::Wild = pat.kind {
+ return false; // ignore `_` patterns
+ }
+ let def_id = pat.hir_id.owner.to_def_id();
+ if cx.tcx.has_typeck_results(def_id) {
+ is_mutable_ty(cx, &cx.tcx.typeck(def_id.expect_local()).pat_ty(pat), pat.span, tys)
+ } else {
+ false
+ }
+}
+
+static KNOWN_WRAPPER_TYS: &[&[&str]] = &[&["alloc", "rc", "Rc"], &["std", "sync", "Arc"]];
+
+fn is_mutable_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, span: Span, tys: &mut FxHashSet<DefId>) -> bool {
+ match *ty.kind() {
+ // primitive types are never mutable
+ ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => false,
+ ty::Adt(ref adt, ref substs) => {
+ tys.insert(adt.did) && !ty.is_freeze(cx.tcx.at(span), cx.param_env)
+ || KNOWN_WRAPPER_TYS.iter().any(|path| match_def_path(cx, adt.did, path))
+ && substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys))
+ },
+ ty::Tuple(ref substs) => substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys)),
+ ty::Array(ty, _) | ty::Slice(ty) => is_mutable_ty(cx, ty, span, tys),
+ ty::RawPtr(ty::TypeAndMut { ty, mutbl }) | ty::Ref(_, ty, mutbl) => {
+ mutbl == hir::Mutability::Mut || is_mutable_ty(cx, ty, span, tys)
+ },
+ // calling something constitutes a side effect, so return true on all callables
+ // also never calls need not be used, so return true for them, too
+ _ => true,
+ }
+}
+
+fn raw_ptr_arg(arg: &hir::Param<'_>, ty: &hir::Ty<'_>) -> Option<hir::HirId> {
+ if let (&hir::PatKind::Binding(_, id, _, _), &hir::TyKind::Ptr(_)) = (&arg.pat.kind, &ty.kind) {
+ Some(id)
+ } else {
+ None
+ }
+}
+
+struct DerefVisitor<'a, 'tcx> {
+ cx: &'a LateContext<'tcx>,
+ ptrs: FxHashSet<hir::HirId>,
+ typeck_results: &'a ty::TypeckResults<'tcx>,
+}
+
+impl<'a, 'tcx> intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
+ type Map = Map<'tcx>;
+
+ fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
+ match expr.kind {
+ hir::ExprKind::Call(ref f, args) => {
+ let ty = self.typeck_results.expr_ty(f);
+
+ if type_is_unsafe_function(self.cx, ty) {
+ for arg in args {
+ self.check_arg(arg);
+ }
+ }
+ },
+ hir::ExprKind::MethodCall(_, _, args, _) => {
+ let def_id = self.typeck_results.type_dependent_def_id(expr.hir_id).unwrap();
+ let base_type = self.cx.tcx.type_of(def_id);
+
+ if type_is_unsafe_function(self.cx, base_type) {
+ for arg in args {
+ self.check_arg(arg);
+ }
+ }
+ },
+ hir::ExprKind::Unary(hir::UnOp::UnDeref, ref ptr) => self.check_arg(ptr),
+ _ => (),
+ }
+
+ intravisit::walk_expr(self, expr);
+ }
+
+ fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
+ intravisit::NestedVisitorMap::None
+ }
+}
+
+impl<'a, 'tcx> DerefVisitor<'a, 'tcx> {
+ fn check_arg(&self, ptr: &hir::Expr<'_>) {
+ if let hir::ExprKind::Path(ref qpath) = ptr.kind {
+ if let Res::Local(id) = qpath_res(self.cx, qpath, ptr.hir_id) {
+ if self.ptrs.contains(&id) {
+ span_lint(
+ self.cx,
+ NOT_UNSAFE_PTR_ARG_DEREF,
+ ptr.span,
+ "this public function dereferences a raw pointer but is not marked `unsafe`",
+ );
+ }
+ }
+ }
+ }
+}
+
+struct StaticMutVisitor<'a, 'tcx> {
+ cx: &'a LateContext<'tcx>,
+ mutates_static: bool,
+}
+
+impl<'a, 'tcx> intravisit::Visitor<'tcx> for StaticMutVisitor<'a, 'tcx> {
+ type Map = Map<'tcx>;
+
+ fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
+ use hir::ExprKind::{AddrOf, Assign, AssignOp, Call, MethodCall};
+
+ if self.mutates_static {
+ return;
+ }
+ match expr.kind {
+ Call(_, args) | MethodCall(_, _, args, _) => {
+ let mut tys = FxHashSet::default();
+ for arg in args {
+ let def_id = arg.hir_id.owner.to_def_id();
+ if self.cx.tcx.has_typeck_results(def_id)
+ && is_mutable_ty(
+ self.cx,
+ self.cx.tcx.typeck(def_id.expect_local()).expr_ty(arg),
+ arg.span,
+ &mut tys,
+ )
+ && is_mutated_static(self.cx, arg)
+ {
+ self.mutates_static = true;
+ return;
+ }
+ tys.clear();
+ }
+ },
+ Assign(ref target, ..) | AssignOp(_, ref target, _) | AddrOf(_, hir::Mutability::Mut, ref target) => {
+ self.mutates_static |= is_mutated_static(self.cx, target)
+ },
+ _ => {},
+ }
+ }
+
+ fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
+ intravisit::NestedVisitorMap::None
+ }
+}
+
+fn is_mutated_static(cx: &LateContext<'_>, e: &hir::Expr<'_>) -> bool {
+ use hir::ExprKind::{Field, Index, Path};
+
+ match e.kind {
+ Path(ref qpath) => !matches!(qpath_res(cx, qpath, e.hir_id), Res::Local(_)),
+ Field(ref inner, _) | Index(ref inner, _) => is_mutated_static(cx, inner),
+ _ => false,
+ }
+}
+
+fn mutates_static<'tcx>(cx: &LateContext<'tcx>, body: &'tcx hir::Body<'_>) -> bool {
+ let mut v = StaticMutVisitor {
+ cx,
+ mutates_static: false,
+ };
+ intravisit::walk_expr(&mut v, &body.value);
+ v.mutates_static
+}
--- /dev/null
+// error-pattern:cargo-clippy
+
+#![feature(bindings_after_at)]
+#![feature(box_patterns)]
+#![feature(box_syntax)]
+#![feature(concat_idents)]
+#![feature(crate_visibility_modifier)]
+#![feature(drain_filter)]
+#![feature(or_patterns)]
+#![feature(rustc_private)]
+#![feature(stmt_expr_attributes)]
+#![recursion_limit = "512"]
+#![cfg_attr(feature = "deny-warnings", deny(warnings))]
+#![allow(clippy::missing_docs_in_private_items, clippy::must_use_candidate)]
+#![warn(trivial_casts, trivial_numeric_casts)]
+// warn on lints, that are included in `rust-lang/rust`s bootstrap
+#![warn(rust_2018_idioms, unused_lifetimes)]
+// warn on rustc internal lints
+#![deny(rustc::internal)]
+
+// FIXME: switch to something more ergonomic here, once available.
+// (Currently there is no way to opt into sysroot crates without `extern crate`.)
+extern crate rustc_ast;
+extern crate rustc_ast_pretty;
+extern crate rustc_attr;
+extern crate rustc_data_structures;
+extern crate rustc_errors;
+extern crate rustc_hir;
+extern crate rustc_hir_pretty;
+extern crate rustc_index;
+extern crate rustc_infer;
+extern crate rustc_lexer;
+extern crate rustc_lint;
+extern crate rustc_middle;
+extern crate rustc_mir;
+extern crate rustc_parse;
+extern crate rustc_parse_format;
+extern crate rustc_session;
+extern crate rustc_span;
+extern crate rustc_target;
+extern crate rustc_trait_selection;
+extern crate rustc_typeck;
+
+use rustc_data_structures::fx::FxHashSet;
+use rustc_lint::LintId;
+use rustc_session::Session;
+
+/// Macro used to declare a Clippy lint.
+///
+/// Every lint declaration consists of 4 parts:
+///
+/// 1. The documentation, which is used for the website
+/// 2. The `LINT_NAME`. See [lint naming][lint_naming] on lint naming conventions.
+/// 3. The `lint_level`, which is a mapping from *one* of our lint groups to `Allow`, `Warn` or
+/// `Deny`. The lint level here has nothing to do with what lint groups the lint is a part of.
+/// 4. The `description` that contains a short explanation on what's wrong with code where the
+/// lint is triggered.
+///
+/// Currently the categories `style`, `correctness`, `complexity` and `perf` are enabled by default.
+/// As said in the README.md of this repository, if the lint level mapping changes, please update
+/// README.md.
+///
+/// # Example
+///
+/// ```
+/// #![feature(rustc_private)]
+/// extern crate rustc_session;
+/// use rustc_session::declare_tool_lint;
+/// use clippy_lints::declare_clippy_lint;
+///
+/// declare_clippy_lint! {
+/// /// **What it does:** Checks for ... (describe what the lint matches).
+/// ///
+/// /// **Why is this bad?** Supply the reason for linting the code.
+/// ///
+/// /// **Known problems:** None. (Or describe where it could go wrong.)
+/// ///
+/// /// **Example:**
+/// ///
+/// /// ```rust
+/// /// // Bad
+/// /// Insert a short example of code that triggers the lint
+/// ///
+/// /// // Good
+/// /// Insert a short example of improved code that doesn't trigger the lint
+/// /// ```
+/// pub LINT_NAME,
+/// pedantic,
+/// "description"
+/// }
+/// ```
+/// [lint_naming]: https://rust-lang.github.io/rfcs/0344-conventions-galore.html#lints
+#[macro_export]
+macro_rules! declare_clippy_lint {
+ { $(#[$attr:meta])* pub $name:tt, style, $description:tt } => {
+ declare_tool_lint! {
+ $(#[$attr])* pub clippy::$name, Warn, $description, report_in_external_macro: true
+ }
+ };
+ { $(#[$attr:meta])* pub $name:tt, correctness, $description:tt } => {
+ declare_tool_lint! {
+ $(#[$attr])* pub clippy::$name, Deny, $description, report_in_external_macro: true
+ }
+ };
+ { $(#[$attr:meta])* pub $name:tt, complexity, $description:tt } => {
+ declare_tool_lint! {
+ $(#[$attr])* pub clippy::$name, Warn, $description, report_in_external_macro: true
+ }
+ };
+ { $(#[$attr:meta])* pub $name:tt, perf, $description:tt } => {
+ declare_tool_lint! {
+ $(#[$attr])* pub clippy::$name, Warn, $description, report_in_external_macro: true
+ }
+ };
+ { $(#[$attr:meta])* pub $name:tt, pedantic, $description:tt } => {
+ declare_tool_lint! {
+ $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true
+ }
+ };
+ { $(#[$attr:meta])* pub $name:tt, restriction, $description:tt } => {
+ declare_tool_lint! {
+ $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true
+ }
+ };
+ { $(#[$attr:meta])* pub $name:tt, cargo, $description:tt } => {
+ declare_tool_lint! {
+ $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true
+ }
+ };
+ { $(#[$attr:meta])* pub $name:tt, nursery, $description:tt } => {
+ declare_tool_lint! {
+ $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true
+ }
+ };
+ { $(#[$attr:meta])* pub $name:tt, internal, $description:tt } => {
+ declare_tool_lint! {
+ $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true
+ }
+ };
+ { $(#[$attr:meta])* pub $name:tt, internal_warn, $description:tt } => {
+ declare_tool_lint! {
+ $(#[$attr])* pub clippy::$name, Warn, $description, report_in_external_macro: true
+ }
+ };
+}
+
+mod consts;
+#[macro_use]
+mod utils;
+
+// begin lints modules, do not remove this comment, it’s used in `update_lints`
+mod approx_const;
+mod arithmetic;
+mod as_conversions;
+mod assertions_on_constants;
+mod assign_ops;
++mod async_yields_async;
+mod atomic_ordering;
+mod attrs;
+mod await_holding_lock;
+mod bit_mask;
+mod blacklisted_name;
+mod blocks_in_if_conditions;
+mod booleans;
+mod bytecount;
+mod cargo_common_metadata;
+mod checked_conversions;
+mod cognitive_complexity;
+mod collapsible_if;
+mod comparison_chain;
+mod copies;
+mod copy_iterator;
++mod create_dir;
+mod dbg_macro;
+mod default_trait_access;
+mod dereference;
+mod derive;
+mod doc;
+mod double_comparison;
+mod double_parens;
+mod drop_bounds;
+mod drop_forget_ref;
+mod duration_subsec;
+mod else_if_without_else;
+mod empty_enum;
+mod entry;
+mod enum_clike;
+mod enum_variants;
+mod eq_op;
+mod erasing_op;
+mod escape;
+mod eta_reduction;
+mod eval_order_dependence;
+mod excessive_bools;
+mod exit;
+mod explicit_write;
+mod fallible_impl_from;
+mod float_equality_without_abs;
+mod float_literal;
+mod floating_point_arithmetic;
+mod format;
+mod formatting;
+mod functions;
+mod future_not_send;
+mod get_last_with_len;
+mod identity_op;
+mod if_let_mutex;
+mod if_let_some_result;
+mod if_not_else;
+mod implicit_return;
+mod implicit_saturating_sub;
+mod indexing_slicing;
+mod infinite_iter;
+mod inherent_impl;
+mod inherent_to_string;
+mod inline_fn_without_body;
+mod int_plus_one;
+mod integer_division;
+mod items_after_statements;
+mod large_const_arrays;
+mod large_enum_variant;
+mod large_stack_arrays;
+mod len_zero;
+mod let_if_seq;
+mod let_underscore;
+mod lifetimes;
+mod literal_representation;
+mod loops;
+mod macro_use;
+mod main_recursion;
+mod manual_async_fn;
+mod manual_non_exhaustive;
+mod map_clone;
+mod map_identity;
+mod map_unit_fn;
+mod match_on_vec_items;
+mod matches;
+mod mem_discriminant;
+mod mem_forget;
+mod mem_replace;
+mod methods;
+mod minmax;
+mod misc;
+mod misc_early;
+mod missing_const_for_fn;
+mod missing_doc;
+mod missing_inline;
+mod modulo_arithmetic;
+mod multiple_crate_versions;
+mod mut_key;
+mod mut_mut;
+mod mut_reference;
+mod mutable_debug_assertion;
+mod mutex_atomic;
+mod needless_arbitrary_self_type;
+mod needless_bool;
+mod needless_borrow;
+mod needless_borrowed_ref;
+mod needless_continue;
+mod needless_pass_by_value;
+mod needless_update;
+mod neg_cmp_op_on_partial_ord;
+mod neg_multiply;
+mod new_without_default;
+mod no_effect;
+mod non_copy_const;
+mod non_expressive_names;
+mod open_options;
+mod option_env_unwrap;
+mod option_if_let_else;
+mod overflow_check_conditional;
+mod panic_unimplemented;
+mod partialeq_ne_impl;
+mod path_buf_push_overwrite;
+mod pattern_type_mismatch;
+mod precedence;
+mod ptr;
+mod ptr_offset_with_cast;
+mod question_mark;
+mod ranges;
+mod redundant_clone;
+mod redundant_closure_call;
+mod redundant_field_names;
+mod redundant_pub_crate;
+mod redundant_static_lifetimes;
+mod reference;
+mod regex;
+mod repeat_once;
+mod returns;
+mod self_assignment;
+mod serde_api;
+mod shadow;
+mod single_component_path_imports;
+mod slow_vector_initialization;
+mod stable_sort_primitive;
+mod strings;
+mod suspicious_trait_impl;
+mod swap;
+mod tabs_in_doc_comments;
+mod temporary_assignment;
+mod to_digit_is_some;
+mod to_string_in_display;
+mod trait_bounds;
+mod transmute;
+mod transmuting_null;
+mod trivially_copy_pass_by_ref;
+mod try_err;
+mod types;
+mod unicode;
+mod unit_return_expecting_ord;
+mod unnamed_address;
+mod unnecessary_sort_by;
+mod unnested_or_patterns;
+mod unsafe_removed_from_name;
+mod unused_io_amount;
+mod unused_self;
+mod unused_unit;
+mod unwrap;
+mod unwrap_in_result;
+mod use_self;
+mod useless_conversion;
+mod vec;
+mod vec_resize_to_zero;
+mod verbose_file_reads;
+mod wildcard_dependencies;
+mod wildcard_imports;
+mod write;
+mod zero_div_zero;
+// end lints modules, do not remove this comment, it’s used in `update_lints`
+
+pub use crate::utils::conf::Conf;
+
+/// Register all pre expansion lints
+///
+/// Pre-expansion lints run before any macro expansion has happened.
+///
+/// Note that due to the architecture of the compiler, currently `cfg_attr` attributes on crate
+/// level (i.e `#![cfg_attr(...)]`) will still be expanded even when using a pre-expansion pass.
+///
+/// Used in `./src/driver.rs`.
+pub fn register_pre_expansion_lints(store: &mut rustc_lint::LintStore) {
+ store.register_pre_expansion_pass(|| box write::Write::default());
+ store.register_pre_expansion_pass(|| box attrs::EarlyAttributes);
+ store.register_pre_expansion_pass(|| box dbg_macro::DbgMacro);
+}
+
+#[doc(hidden)]
+pub fn read_conf(args: &[rustc_ast::NestedMetaItem], sess: &Session) -> Conf {
+ use std::path::Path;
+ match utils::conf::file_from_args(args) {
+ Ok(file_name) => {
+ // if the user specified a file, it must exist, otherwise default to `clippy.toml` but
+ // do not require the file to exist
+ let file_name = match file_name {
+ Some(file_name) => file_name,
+ None => match utils::conf::lookup_conf_file() {
+ Ok(Some(path)) => path,
+ Ok(None) => return Conf::default(),
+ Err(error) => {
+ sess.struct_err(&format!("error finding Clippy's configuration file: {}", error))
+ .emit();
+ return Conf::default();
+ },
+ },
+ };
+
+ let file_name = if file_name.is_relative() {
+ sess.local_crate_source_file
+ .as_deref()
+ .and_then(Path::parent)
+ .unwrap_or_else(|| Path::new(""))
+ .join(file_name)
+ } else {
+ file_name
+ };
+
+ let (conf, errors) = utils::conf::read(&file_name);
+
+ // all conf errors are non-fatal, we just use the default conf in case of error
+ for error in errors {
+ sess.struct_err(&format!(
+ "error reading Clippy's configuration file `{}`: {}",
+ file_name.display(),
+ error
+ ))
+ .emit();
+ }
+
+ conf
+ },
+ Err((err, span)) => {
+ sess.struct_span_err(span, err)
+ .span_note(span, "Clippy will use default configuration")
+ .emit();
+ Conf::default()
+ },
+ }
+}
+
+/// Register all lints and lint groups with the rustc plugin registry
+///
+/// Used in `./src/driver.rs`.
+#[allow(clippy::too_many_lines)]
+#[rustfmt::skip]
+pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: &Conf) {
+ register_removed_non_tool_lints(store);
+
+ // begin deprecated lints, do not remove this comment, it’s used in `update_lints`
+ store.register_removed(
+ "clippy::should_assert_eq",
+ "`assert!()` will be more flexible with RFC 2011",
+ );
+ store.register_removed(
+ "clippy::extend_from_slice",
+ "`.extend_from_slice(_)` is a faster way to extend a Vec by a slice",
+ );
+ store.register_removed(
+ "clippy::range_step_by_zero",
+ "`iterator.step_by(0)` panics nowadays",
+ );
+ store.register_removed(
+ "clippy::unstable_as_slice",
+ "`Vec::as_slice` has been stabilized in 1.7",
+ );
+ store.register_removed(
+ "clippy::unstable_as_mut_slice",
+ "`Vec::as_mut_slice` has been stabilized in 1.7",
+ );
+ store.register_removed(
+ "clippy::str_to_string",
+ "using `str::to_string` is common even today and specialization will likely happen soon",
+ );
+ store.register_removed(
+ "clippy::string_to_string",
+ "using `string::to_string` is common even today and specialization will likely happen soon",
+ );
+ store.register_removed(
+ "clippy::misaligned_transmute",
+ "this lint has been split into cast_ptr_alignment and transmute_ptr_to_ptr",
+ );
+ store.register_removed(
+ "clippy::assign_ops",
+ "using compound assignment operators (e.g., `+=`) is harmless",
+ );
+ store.register_removed(
+ "clippy::if_let_redundant_pattern_matching",
+ "this lint has been changed to redundant_pattern_matching",
+ );
+ store.register_removed(
+ "clippy::unsafe_vector_initialization",
+ "the replacement suggested by this lint had substantially different behavior",
+ );
+ store.register_removed(
+ "clippy::invalid_ref",
+ "superseded by rustc lint `invalid_value`",
+ );
+ store.register_removed(
+ "clippy::unused_collect",
+ "`collect` has been marked as #[must_use] in rustc and that covers all cases of this lint",
+ );
+ store.register_removed(
+ "clippy::into_iter_on_array",
+ "this lint has been uplifted to rustc and is now called `array_into_iter`",
+ );
+ store.register_removed(
+ "clippy::unused_label",
+ "this lint has been uplifted to rustc and is now called `unused_labels`",
+ );
+ store.register_removed(
+ "clippy::replace_consts",
+ "associated-constants `MIN`/`MAX` of integers are preferred to `{min,max}_value()` and module constants",
+ );
+ store.register_removed(
+ "clippy::regex_macro",
+ "the regex! macro has been removed from the regex crate in 2018",
+ );
+ // end deprecated lints, do not remove this comment, it’s used in `update_lints`
+
+ // begin register lints, do not remove this comment, it’s used in `update_lints`
+ store.register_lints(&[
+ &approx_const::APPROX_CONSTANT,
+ &arithmetic::FLOAT_ARITHMETIC,
+ &arithmetic::INTEGER_ARITHMETIC,
+ &as_conversions::AS_CONVERSIONS,
+ &assertions_on_constants::ASSERTIONS_ON_CONSTANTS,
+ &assign_ops::ASSIGN_OP_PATTERN,
+ &assign_ops::MISREFACTORED_ASSIGN_OP,
++ &async_yields_async::ASYNC_YIELDS_ASYNC,
+ &atomic_ordering::INVALID_ATOMIC_ORDERING,
+ &attrs::BLANKET_CLIPPY_RESTRICTION_LINTS,
+ &attrs::DEPRECATED_CFG_ATTR,
+ &attrs::DEPRECATED_SEMVER,
+ &attrs::EMPTY_LINE_AFTER_OUTER_ATTR,
+ &attrs::INLINE_ALWAYS,
+ &attrs::MISMATCHED_TARGET_OS,
+ &attrs::UNKNOWN_CLIPPY_LINTS,
+ &attrs::USELESS_ATTRIBUTE,
+ &await_holding_lock::AWAIT_HOLDING_LOCK,
+ &bit_mask::BAD_BIT_MASK,
+ &bit_mask::INEFFECTIVE_BIT_MASK,
+ &bit_mask::VERBOSE_BIT_MASK,
+ &blacklisted_name::BLACKLISTED_NAME,
+ &blocks_in_if_conditions::BLOCKS_IN_IF_CONDITIONS,
+ &booleans::LOGIC_BUG,
+ &booleans::NONMINIMAL_BOOL,
+ &bytecount::NAIVE_BYTECOUNT,
+ &cargo_common_metadata::CARGO_COMMON_METADATA,
+ &checked_conversions::CHECKED_CONVERSIONS,
+ &cognitive_complexity::COGNITIVE_COMPLEXITY,
+ &collapsible_if::COLLAPSIBLE_IF,
+ &comparison_chain::COMPARISON_CHAIN,
+ &copies::IFS_SAME_COND,
+ &copies::IF_SAME_THEN_ELSE,
+ &copies::MATCH_SAME_ARMS,
+ &copies::SAME_FUNCTIONS_IN_IF_CONDITION,
+ ©_iterator::COPY_ITERATOR,
++ &create_dir::CREATE_DIR,
+ &dbg_macro::DBG_MACRO,
+ &default_trait_access::DEFAULT_TRAIT_ACCESS,
+ &dereference::EXPLICIT_DEREF_METHODS,
+ &derive::DERIVE_HASH_XOR_EQ,
+ &derive::DERIVE_ORD_XOR_PARTIAL_ORD,
+ &derive::EXPL_IMPL_CLONE_ON_COPY,
+ &derive::UNSAFE_DERIVE_DESERIALIZE,
+ &doc::DOC_MARKDOWN,
+ &doc::MISSING_ERRORS_DOC,
+ &doc::MISSING_SAFETY_DOC,
+ &doc::NEEDLESS_DOCTEST_MAIN,
+ &double_comparison::DOUBLE_COMPARISONS,
+ &double_parens::DOUBLE_PARENS,
+ &drop_bounds::DROP_BOUNDS,
+ &drop_forget_ref::DROP_COPY,
+ &drop_forget_ref::DROP_REF,
+ &drop_forget_ref::FORGET_COPY,
+ &drop_forget_ref::FORGET_REF,
+ &duration_subsec::DURATION_SUBSEC,
+ &else_if_without_else::ELSE_IF_WITHOUT_ELSE,
+ &empty_enum::EMPTY_ENUM,
+ &entry::MAP_ENTRY,
+ &enum_clike::ENUM_CLIKE_UNPORTABLE_VARIANT,
+ &enum_variants::ENUM_VARIANT_NAMES,
+ &enum_variants::MODULE_INCEPTION,
+ &enum_variants::MODULE_NAME_REPETITIONS,
+ &enum_variants::PUB_ENUM_VARIANT_NAMES,
+ &eq_op::EQ_OP,
+ &eq_op::OP_REF,
+ &erasing_op::ERASING_OP,
+ &escape::BOXED_LOCAL,
+ &eta_reduction::REDUNDANT_CLOSURE,
+ &eta_reduction::REDUNDANT_CLOSURE_FOR_METHOD_CALLS,
+ &eval_order_dependence::DIVERGING_SUB_EXPRESSION,
+ &eval_order_dependence::EVAL_ORDER_DEPENDENCE,
+ &excessive_bools::FN_PARAMS_EXCESSIVE_BOOLS,
+ &excessive_bools::STRUCT_EXCESSIVE_BOOLS,
+ &exit::EXIT,
+ &explicit_write::EXPLICIT_WRITE,
+ &fallible_impl_from::FALLIBLE_IMPL_FROM,
+ &float_equality_without_abs::FLOAT_EQUALITY_WITHOUT_ABS,
+ &float_literal::EXCESSIVE_PRECISION,
+ &float_literal::LOSSY_FLOAT_LITERAL,
+ &floating_point_arithmetic::IMPRECISE_FLOPS,
+ &floating_point_arithmetic::SUBOPTIMAL_FLOPS,
+ &format::USELESS_FORMAT,
+ &formatting::POSSIBLE_MISSING_COMMA,
+ &formatting::SUSPICIOUS_ASSIGNMENT_FORMATTING,
+ &formatting::SUSPICIOUS_ELSE_FORMATTING,
+ &formatting::SUSPICIOUS_UNARY_OP_FORMATTING,
+ &functions::DOUBLE_MUST_USE,
+ &functions::MUST_USE_CANDIDATE,
+ &functions::MUST_USE_UNIT,
+ &functions::NOT_UNSAFE_PTR_ARG_DEREF,
+ &functions::TOO_MANY_ARGUMENTS,
+ &functions::TOO_MANY_LINES,
+ &future_not_send::FUTURE_NOT_SEND,
+ &get_last_with_len::GET_LAST_WITH_LEN,
+ &identity_op::IDENTITY_OP,
+ &if_let_mutex::IF_LET_MUTEX,
+ &if_let_some_result::IF_LET_SOME_RESULT,
+ &if_not_else::IF_NOT_ELSE,
+ &implicit_return::IMPLICIT_RETURN,
+ &implicit_saturating_sub::IMPLICIT_SATURATING_SUB,
+ &indexing_slicing::INDEXING_SLICING,
+ &indexing_slicing::OUT_OF_BOUNDS_INDEXING,
+ &infinite_iter::INFINITE_ITER,
+ &infinite_iter::MAYBE_INFINITE_ITER,
+ &inherent_impl::MULTIPLE_INHERENT_IMPL,
+ &inherent_to_string::INHERENT_TO_STRING,
+ &inherent_to_string::INHERENT_TO_STRING_SHADOW_DISPLAY,
+ &inline_fn_without_body::INLINE_FN_WITHOUT_BODY,
+ &int_plus_one::INT_PLUS_ONE,
+ &integer_division::INTEGER_DIVISION,
+ &items_after_statements::ITEMS_AFTER_STATEMENTS,
+ &large_const_arrays::LARGE_CONST_ARRAYS,
+ &large_enum_variant::LARGE_ENUM_VARIANT,
+ &large_stack_arrays::LARGE_STACK_ARRAYS,
+ &len_zero::LEN_WITHOUT_IS_EMPTY,
+ &len_zero::LEN_ZERO,
+ &let_if_seq::USELESS_LET_IF_SEQ,
+ &let_underscore::LET_UNDERSCORE_LOCK,
+ &let_underscore::LET_UNDERSCORE_MUST_USE,
+ &lifetimes::EXTRA_UNUSED_LIFETIMES,
+ &lifetimes::NEEDLESS_LIFETIMES,
+ &literal_representation::DECIMAL_LITERAL_REPRESENTATION,
+ &literal_representation::INCONSISTENT_DIGIT_GROUPING,
+ &literal_representation::LARGE_DIGIT_GROUPS,
+ &literal_representation::MISTYPED_LITERAL_SUFFIXES,
+ &literal_representation::UNREADABLE_LITERAL,
+ &loops::EMPTY_LOOP,
+ &loops::EXPLICIT_COUNTER_LOOP,
+ &loops::EXPLICIT_INTO_ITER_LOOP,
+ &loops::EXPLICIT_ITER_LOOP,
+ &loops::FOR_KV_MAP,
+ &loops::FOR_LOOPS_OVER_FALLIBLES,
+ &loops::ITER_NEXT_LOOP,
+ &loops::MANUAL_MEMCPY,
+ &loops::MUT_RANGE_BOUND,
+ &loops::NEEDLESS_COLLECT,
+ &loops::NEEDLESS_RANGE_LOOP,
+ &loops::NEVER_LOOP,
+ &loops::SAME_ITEM_PUSH,
+ &loops::WHILE_IMMUTABLE_CONDITION,
+ &loops::WHILE_LET_LOOP,
+ &loops::WHILE_LET_ON_ITERATOR,
+ ¯o_use::MACRO_USE_IMPORTS,
+ &main_recursion::MAIN_RECURSION,
+ &manual_async_fn::MANUAL_ASYNC_FN,
+ &manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE,
+ &map_clone::MAP_CLONE,
+ &map_identity::MAP_IDENTITY,
+ &map_unit_fn::OPTION_MAP_UNIT_FN,
+ &map_unit_fn::RESULT_MAP_UNIT_FN,
+ &match_on_vec_items::MATCH_ON_VEC_ITEMS,
+ &matches::INFALLIBLE_DESTRUCTURING_MATCH,
+ &matches::MATCH_AS_REF,
+ &matches::MATCH_BOOL,
+ &matches::MATCH_LIKE_MATCHES_MACRO,
+ &matches::MATCH_OVERLAPPING_ARM,
+ &matches::MATCH_REF_PATS,
+ &matches::MATCH_SINGLE_BINDING,
+ &matches::MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
+ &matches::MATCH_WILD_ERR_ARM,
+ &matches::REDUNDANT_PATTERN_MATCHING,
+ &matches::REST_PAT_IN_FULLY_BOUND_STRUCTS,
+ &matches::SINGLE_MATCH,
+ &matches::SINGLE_MATCH_ELSE,
+ &matches::WILDCARD_ENUM_MATCH_ARM,
+ &matches::WILDCARD_IN_OR_PATTERNS,
+ &mem_discriminant::MEM_DISCRIMINANT_NON_ENUM,
+ &mem_forget::MEM_FORGET,
+ &mem_replace::MEM_REPLACE_OPTION_WITH_NONE,
+ &mem_replace::MEM_REPLACE_WITH_DEFAULT,
+ &mem_replace::MEM_REPLACE_WITH_UNINIT,
+ &methods::BIND_INSTEAD_OF_MAP,
+ &methods::CHARS_LAST_CMP,
+ &methods::CHARS_NEXT_CMP,
+ &methods::CLONE_DOUBLE_REF,
+ &methods::CLONE_ON_COPY,
+ &methods::CLONE_ON_REF_PTR,
+ &methods::EXPECT_FUN_CALL,
+ &methods::EXPECT_USED,
+ &methods::FILETYPE_IS_FILE,
+ &methods::FILTER_MAP,
+ &methods::FILTER_MAP_NEXT,
+ &methods::FILTER_NEXT,
+ &methods::FIND_MAP,
+ &methods::FLAT_MAP_IDENTITY,
+ &methods::GET_UNWRAP,
+ &methods::INEFFICIENT_TO_STRING,
+ &methods::INTO_ITER_ON_REF,
+ &methods::ITERATOR_STEP_BY_ZERO,
+ &methods::ITER_CLONED_COLLECT,
+ &methods::ITER_NEXT_SLICE,
+ &methods::ITER_NTH,
+ &methods::ITER_NTH_ZERO,
+ &methods::ITER_SKIP_NEXT,
+ &methods::MANUAL_SATURATING_ARITHMETIC,
+ &methods::MAP_FLATTEN,
+ &methods::MAP_UNWRAP_OR,
+ &methods::NEW_RET_NO_SELF,
+ &methods::OK_EXPECT,
+ &methods::OPTION_AS_REF_DEREF,
+ &methods::OPTION_MAP_OR_NONE,
+ &methods::OR_FUN_CALL,
+ &methods::RESULT_MAP_OR_INTO_OPTION,
+ &methods::SEARCH_IS_SOME,
+ &methods::SHOULD_IMPLEMENT_TRAIT,
+ &methods::SINGLE_CHAR_PATTERN,
+ &methods::SINGLE_CHAR_PUSH_STR,
+ &methods::SKIP_WHILE_NEXT,
+ &methods::STRING_EXTEND_CHARS,
+ &methods::SUSPICIOUS_MAP,
+ &methods::TEMPORARY_CSTRING_AS_PTR,
+ &methods::UNINIT_ASSUMED_INIT,
+ &methods::UNNECESSARY_FILTER_MAP,
+ &methods::UNNECESSARY_FOLD,
+ &methods::UNNECESSARY_LAZY_EVALUATIONS,
+ &methods::UNWRAP_USED,
+ &methods::USELESS_ASREF,
+ &methods::WRONG_PUB_SELF_CONVENTION,
+ &methods::WRONG_SELF_CONVENTION,
+ &methods::ZST_OFFSET,
+ &minmax::MIN_MAX,
+ &misc::CMP_NAN,
+ &misc::CMP_OWNED,
+ &misc::FLOAT_CMP,
+ &misc::FLOAT_CMP_CONST,
+ &misc::MODULO_ONE,
+ &misc::SHORT_CIRCUIT_STATEMENT,
+ &misc::TOPLEVEL_REF_ARG,
+ &misc::USED_UNDERSCORE_BINDING,
+ &misc::ZERO_PTR,
+ &misc_early::BUILTIN_TYPE_SHADOW,
+ &misc_early::DOUBLE_NEG,
+ &misc_early::DUPLICATE_UNDERSCORE_ARGUMENT,
+ &misc_early::MIXED_CASE_HEX_LITERALS,
+ &misc_early::REDUNDANT_PATTERN,
+ &misc_early::UNNEEDED_FIELD_PATTERN,
+ &misc_early::UNNEEDED_WILDCARD_PATTERN,
+ &misc_early::UNSEPARATED_LITERAL_SUFFIX,
+ &misc_early::ZERO_PREFIXED_LITERAL,
+ &missing_const_for_fn::MISSING_CONST_FOR_FN,
+ &missing_doc::MISSING_DOCS_IN_PRIVATE_ITEMS,
+ &missing_inline::MISSING_INLINE_IN_PUBLIC_ITEMS,
+ &modulo_arithmetic::MODULO_ARITHMETIC,
+ &multiple_crate_versions::MULTIPLE_CRATE_VERSIONS,
+ &mut_key::MUTABLE_KEY_TYPE,
+ &mut_mut::MUT_MUT,
+ &mut_reference::UNNECESSARY_MUT_PASSED,
+ &mutable_debug_assertion::DEBUG_ASSERT_WITH_MUT_CALL,
+ &mutex_atomic::MUTEX_ATOMIC,
+ &mutex_atomic::MUTEX_INTEGER,
+ &needless_arbitrary_self_type::NEEDLESS_ARBITRARY_SELF_TYPE,
+ &needless_bool::BOOL_COMPARISON,
+ &needless_bool::NEEDLESS_BOOL,
+ &needless_borrow::NEEDLESS_BORROW,
+ &needless_borrowed_ref::NEEDLESS_BORROWED_REFERENCE,
+ &needless_continue::NEEDLESS_CONTINUE,
+ &needless_pass_by_value::NEEDLESS_PASS_BY_VALUE,
+ &needless_update::NEEDLESS_UPDATE,
+ &neg_cmp_op_on_partial_ord::NEG_CMP_OP_ON_PARTIAL_ORD,
+ &neg_multiply::NEG_MULTIPLY,
+ &new_without_default::NEW_WITHOUT_DEFAULT,
+ &no_effect::NO_EFFECT,
+ &no_effect::UNNECESSARY_OPERATION,
+ &non_copy_const::BORROW_INTERIOR_MUTABLE_CONST,
+ &non_copy_const::DECLARE_INTERIOR_MUTABLE_CONST,
+ &non_expressive_names::JUST_UNDERSCORES_AND_DIGITS,
+ &non_expressive_names::MANY_SINGLE_CHAR_NAMES,
+ &non_expressive_names::SIMILAR_NAMES,
+ &open_options::NONSENSICAL_OPEN_OPTIONS,
+ &option_env_unwrap::OPTION_ENV_UNWRAP,
+ &option_if_let_else::OPTION_IF_LET_ELSE,
+ &overflow_check_conditional::OVERFLOW_CHECK_CONDITIONAL,
+ &panic_unimplemented::PANIC,
+ &panic_unimplemented::PANIC_PARAMS,
+ &panic_unimplemented::TODO,
+ &panic_unimplemented::UNIMPLEMENTED,
+ &panic_unimplemented::UNREACHABLE,
+ &partialeq_ne_impl::PARTIALEQ_NE_IMPL,
+ &path_buf_push_overwrite::PATH_BUF_PUSH_OVERWRITE,
+ &pattern_type_mismatch::PATTERN_TYPE_MISMATCH,
+ &precedence::PRECEDENCE,
+ &ptr::CMP_NULL,
+ &ptr::MUT_FROM_REF,
+ &ptr::PTR_ARG,
+ &ptr_offset_with_cast::PTR_OFFSET_WITH_CAST,
+ &question_mark::QUESTION_MARK,
+ &ranges::RANGE_MINUS_ONE,
+ &ranges::RANGE_PLUS_ONE,
+ &ranges::RANGE_ZIP_WITH_LEN,
+ &ranges::REVERSED_EMPTY_RANGES,
+ &redundant_clone::REDUNDANT_CLONE,
+ &redundant_closure_call::REDUNDANT_CLOSURE_CALL,
+ &redundant_field_names::REDUNDANT_FIELD_NAMES,
+ &redundant_pub_crate::REDUNDANT_PUB_CRATE,
+ &redundant_static_lifetimes::REDUNDANT_STATIC_LIFETIMES,
+ &reference::DEREF_ADDROF,
+ &reference::REF_IN_DEREF,
+ ®ex::INVALID_REGEX,
+ ®ex::TRIVIAL_REGEX,
+ &repeat_once::REPEAT_ONCE,
+ &returns::LET_AND_RETURN,
+ &returns::NEEDLESS_RETURN,
+ &self_assignment::SELF_ASSIGNMENT,
+ &serde_api::SERDE_API_MISUSE,
+ &shadow::SHADOW_REUSE,
+ &shadow::SHADOW_SAME,
+ &shadow::SHADOW_UNRELATED,
+ &single_component_path_imports::SINGLE_COMPONENT_PATH_IMPORTS,
+ &slow_vector_initialization::SLOW_VECTOR_INITIALIZATION,
+ &stable_sort_primitive::STABLE_SORT_PRIMITIVE,
+ &strings::STRING_ADD,
+ &strings::STRING_ADD_ASSIGN,
+ &strings::STRING_LIT_AS_BYTES,
+ &suspicious_trait_impl::SUSPICIOUS_ARITHMETIC_IMPL,
+ &suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL,
+ &swap::ALMOST_SWAPPED,
+ &swap::MANUAL_SWAP,
+ &tabs_in_doc_comments::TABS_IN_DOC_COMMENTS,
+ &temporary_assignment::TEMPORARY_ASSIGNMENT,
+ &to_digit_is_some::TO_DIGIT_IS_SOME,
+ &to_string_in_display::TO_STRING_IN_DISPLAY,
+ &trait_bounds::TRAIT_DUPLICATION_IN_BOUNDS,
+ &trait_bounds::TYPE_REPETITION_IN_BOUNDS,
+ &transmute::CROSSPOINTER_TRANSMUTE,
+ &transmute::TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
+ &transmute::TRANSMUTE_BYTES_TO_STR,
+ &transmute::TRANSMUTE_FLOAT_TO_INT,
+ &transmute::TRANSMUTE_INT_TO_BOOL,
+ &transmute::TRANSMUTE_INT_TO_CHAR,
+ &transmute::TRANSMUTE_INT_TO_FLOAT,
+ &transmute::TRANSMUTE_PTR_TO_PTR,
+ &transmute::TRANSMUTE_PTR_TO_REF,
+ &transmute::UNSOUND_COLLECTION_TRANSMUTE,
+ &transmute::USELESS_TRANSMUTE,
+ &transmute::WRONG_TRANSMUTE,
+ &transmuting_null::TRANSMUTING_NULL,
+ &trivially_copy_pass_by_ref::TRIVIALLY_COPY_PASS_BY_REF,
+ &try_err::TRY_ERR,
+ &types::ABSURD_EXTREME_COMPARISONS,
+ &types::BORROWED_BOX,
+ &types::BOX_VEC,
+ &types::CAST_LOSSLESS,
+ &types::CAST_POSSIBLE_TRUNCATION,
+ &types::CAST_POSSIBLE_WRAP,
+ &types::CAST_PRECISION_LOSS,
+ &types::CAST_PTR_ALIGNMENT,
+ &types::CAST_REF_TO_MUT,
+ &types::CAST_SIGN_LOSS,
+ &types::CHAR_LIT_AS_U8,
+ &types::FN_TO_NUMERIC_CAST,
+ &types::FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
+ &types::IMPLICIT_HASHER,
+ &types::INVALID_UPCAST_COMPARISONS,
+ &types::LET_UNIT_VALUE,
+ &types::LINKEDLIST,
+ &types::OPTION_OPTION,
+ &types::REDUNDANT_ALLOCATION,
+ &types::TYPE_COMPLEXITY,
+ &types::UNIT_ARG,
+ &types::UNIT_CMP,
+ &types::UNNECESSARY_CAST,
+ &types::VEC_BOX,
+ &unicode::NON_ASCII_LITERAL,
+ &unicode::UNICODE_NOT_NFC,
+ &unicode::ZERO_WIDTH_SPACE,
+ &unit_return_expecting_ord::UNIT_RETURN_EXPECTING_ORD,
+ &unnamed_address::FN_ADDRESS_COMPARISONS,
+ &unnamed_address::VTABLE_ADDRESS_COMPARISONS,
+ &unnecessary_sort_by::UNNECESSARY_SORT_BY,
+ &unnested_or_patterns::UNNESTED_OR_PATTERNS,
+ &unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME,
+ &unused_io_amount::UNUSED_IO_AMOUNT,
+ &unused_self::UNUSED_SELF,
+ &unused_unit::UNUSED_UNIT,
+ &unwrap::PANICKING_UNWRAP,
+ &unwrap::UNNECESSARY_UNWRAP,
+ &unwrap_in_result::UNWRAP_IN_RESULT,
+ &use_self::USE_SELF,
+ &useless_conversion::USELESS_CONVERSION,
+ &utils::internal_lints::CLIPPY_LINTS_INTERNAL,
+ &utils::internal_lints::COLLAPSIBLE_SPAN_LINT_CALLS,
+ &utils::internal_lints::COMPILER_LINT_FUNCTIONS,
+ &utils::internal_lints::DEFAULT_LINT,
+ &utils::internal_lints::LINT_WITHOUT_LINT_PASS,
+ &utils::internal_lints::OUTER_EXPN_EXPN_DATA,
+ &utils::internal_lints::PRODUCE_ICE,
+ &vec::USELESS_VEC,
+ &vec_resize_to_zero::VEC_RESIZE_TO_ZERO,
+ &verbose_file_reads::VERBOSE_FILE_READS,
+ &wildcard_dependencies::WILDCARD_DEPENDENCIES,
+ &wildcard_imports::ENUM_GLOB_USE,
+ &wildcard_imports::WILDCARD_IMPORTS,
+ &write::PRINTLN_EMPTY_STRING,
+ &write::PRINT_LITERAL,
+ &write::PRINT_STDOUT,
+ &write::PRINT_WITH_NEWLINE,
+ &write::USE_DEBUG,
+ &write::WRITELN_EMPTY_STRING,
+ &write::WRITE_LITERAL,
+ &write::WRITE_WITH_NEWLINE,
+ &zero_div_zero::ZERO_DIVIDED_BY_ZERO,
+ ]);
+ // end register lints, do not remove this comment, it’s used in `update_lints`
+
+ store.register_late_pass(|| box await_holding_lock::AwaitHoldingLock);
+ store.register_late_pass(|| box serde_api::SerdeAPI);
+ store.register_late_pass(|| box utils::internal_lints::CompilerLintFunctions::new());
+ store.register_late_pass(|| box utils::internal_lints::LintWithoutLintPass::default());
+ store.register_late_pass(|| box utils::internal_lints::OuterExpnDataPass);
+ store.register_late_pass(|| box utils::inspector::DeepCodeInspector);
+ store.register_late_pass(|| box utils::author::Author);
+ let vec_box_size_threshold = conf.vec_box_size_threshold;
+ store.register_late_pass(move || box types::Types::new(vec_box_size_threshold));
+ store.register_late_pass(|| box booleans::NonminimalBool);
+ store.register_late_pass(|| box eq_op::EqOp);
+ store.register_late_pass(|| box enum_clike::UnportableVariant);
+ store.register_late_pass(|| box float_literal::FloatLiteral);
+ let verbose_bit_mask_threshold = conf.verbose_bit_mask_threshold;
+ store.register_late_pass(move || box bit_mask::BitMask::new(verbose_bit_mask_threshold));
+ store.register_late_pass(|| box ptr::Ptr);
+ store.register_late_pass(|| box needless_bool::NeedlessBool);
+ store.register_late_pass(|| box needless_bool::BoolComparison);
+ store.register_late_pass(|| box approx_const::ApproxConstant);
+ store.register_late_pass(|| box misc::MiscLints);
+ store.register_late_pass(|| box eta_reduction::EtaReduction);
+ store.register_late_pass(|| box identity_op::IdentityOp);
+ store.register_late_pass(|| box erasing_op::ErasingOp);
+ store.register_late_pass(|| box mut_mut::MutMut);
+ store.register_late_pass(|| box mut_reference::UnnecessaryMutPassed);
+ store.register_late_pass(|| box len_zero::LenZero);
+ store.register_late_pass(|| box attrs::Attributes);
+ store.register_late_pass(|| box blocks_in_if_conditions::BlocksInIfConditions);
+ store.register_late_pass(|| box unicode::Unicode);
+ store.register_late_pass(|| box unit_return_expecting_ord::UnitReturnExpectingOrd);
+ store.register_late_pass(|| box strings::StringAdd);
+ store.register_late_pass(|| box implicit_return::ImplicitReturn);
+ store.register_late_pass(|| box implicit_saturating_sub::ImplicitSaturatingSub);
+ store.register_late_pass(|| box methods::Methods);
+ store.register_late_pass(|| box map_clone::MapClone);
+ store.register_late_pass(|| box shadow::Shadow);
+ store.register_late_pass(|| box types::LetUnitValue);
+ store.register_late_pass(|| box types::UnitCmp);
+ store.register_late_pass(|| box loops::Loops);
+ store.register_late_pass(|| box main_recursion::MainRecursion::default());
+ store.register_late_pass(|| box lifetimes::Lifetimes);
+ store.register_late_pass(|| box entry::HashMapPass);
+ store.register_late_pass(|| box ranges::Ranges);
+ store.register_late_pass(|| box types::Casts);
+ let type_complexity_threshold = conf.type_complexity_threshold;
+ store.register_late_pass(move || box types::TypeComplexity::new(type_complexity_threshold));
+ store.register_late_pass(|| box matches::Matches::default());
+ store.register_late_pass(|| box minmax::MinMaxPass);
+ store.register_late_pass(|| box open_options::OpenOptions);
+ store.register_late_pass(|| box zero_div_zero::ZeroDiv);
+ store.register_late_pass(|| box mutex_atomic::Mutex);
+ store.register_late_pass(|| box needless_update::NeedlessUpdate);
+ store.register_late_pass(|| box needless_borrow::NeedlessBorrow::default());
+ store.register_late_pass(|| box needless_borrowed_ref::NeedlessBorrowedRef);
+ store.register_late_pass(|| box no_effect::NoEffect);
+ store.register_late_pass(|| box temporary_assignment::TemporaryAssignment);
+ store.register_late_pass(|| box transmute::Transmute);
+ let cognitive_complexity_threshold = conf.cognitive_complexity_threshold;
+ store.register_late_pass(move || box cognitive_complexity::CognitiveComplexity::new(cognitive_complexity_threshold));
+ let too_large_for_stack = conf.too_large_for_stack;
+ store.register_late_pass(move || box escape::BoxedLocal{too_large_for_stack});
+ store.register_late_pass(move || box vec::UselessVec{too_large_for_stack});
+ store.register_late_pass(|| box panic_unimplemented::PanicUnimplemented);
+ store.register_late_pass(|| box strings::StringLitAsBytes);
+ store.register_late_pass(|| box derive::Derive);
+ store.register_late_pass(|| box types::CharLitAsU8);
+ store.register_late_pass(|| box drop_bounds::DropBounds);
+ store.register_late_pass(|| box get_last_with_len::GetLastWithLen);
+ store.register_late_pass(|| box drop_forget_ref::DropForgetRef);
+ store.register_late_pass(|| box empty_enum::EmptyEnum);
+ store.register_late_pass(|| box types::AbsurdExtremeComparisons);
+ store.register_late_pass(|| box types::InvalidUpcastComparisons);
+ store.register_late_pass(|| box regex::Regex::default());
+ store.register_late_pass(|| box copies::CopyAndPaste);
+ store.register_late_pass(|| box copy_iterator::CopyIterator);
+ store.register_late_pass(|| box format::UselessFormat);
+ store.register_late_pass(|| box swap::Swap);
+ store.register_late_pass(|| box overflow_check_conditional::OverflowCheckConditional);
+ store.register_late_pass(|| box new_without_default::NewWithoutDefault::default());
+ let blacklisted_names = conf.blacklisted_names.iter().cloned().collect::<FxHashSet<_>>();
+ store.register_late_pass(move || box blacklisted_name::BlacklistedName::new(blacklisted_names.clone()));
+ let too_many_arguments_threshold1 = conf.too_many_arguments_threshold;
+ let too_many_lines_threshold2 = conf.too_many_lines_threshold;
+ store.register_late_pass(move || box functions::Functions::new(too_many_arguments_threshold1, too_many_lines_threshold2));
+ let doc_valid_idents = conf.doc_valid_idents.iter().cloned().collect::<FxHashSet<_>>();
+ store.register_late_pass(move || box doc::DocMarkdown::new(doc_valid_idents.clone()));
+ store.register_late_pass(|| box neg_multiply::NegMultiply);
+ store.register_late_pass(|| box mem_discriminant::MemDiscriminant);
+ store.register_late_pass(|| box mem_forget::MemForget);
+ store.register_late_pass(|| box mem_replace::MemReplace);
+ store.register_late_pass(|| box arithmetic::Arithmetic::default());
+ store.register_late_pass(|| box assign_ops::AssignOps);
+ store.register_late_pass(|| box let_if_seq::LetIfSeq);
+ store.register_late_pass(|| box eval_order_dependence::EvalOrderDependence);
+ store.register_late_pass(|| box missing_doc::MissingDoc::new());
+ store.register_late_pass(|| box missing_inline::MissingInline);
+ store.register_late_pass(|| box if_let_some_result::OkIfLet);
+ store.register_late_pass(|| box partialeq_ne_impl::PartialEqNeImpl);
+ store.register_late_pass(|| box unused_io_amount::UnusedIoAmount);
+ let enum_variant_size_threshold = conf.enum_variant_size_threshold;
+ store.register_late_pass(move || box large_enum_variant::LargeEnumVariant::new(enum_variant_size_threshold));
+ store.register_late_pass(|| box explicit_write::ExplicitWrite);
+ store.register_late_pass(|| box needless_pass_by_value::NeedlessPassByValue);
+ let trivially_copy_pass_by_ref = trivially_copy_pass_by_ref::TriviallyCopyPassByRef::new(
+ conf.trivial_copy_size_limit,
+ &sess.target,
+ );
+ store.register_late_pass(move || box trivially_copy_pass_by_ref);
+ store.register_late_pass(|| box try_err::TryErr);
+ store.register_late_pass(|| box use_self::UseSelf);
+ store.register_late_pass(|| box bytecount::ByteCount);
+ store.register_late_pass(|| box infinite_iter::InfiniteIter);
+ store.register_late_pass(|| box inline_fn_without_body::InlineFnWithoutBody);
+ store.register_late_pass(|| box useless_conversion::UselessConversion::default());
+ store.register_late_pass(|| box types::ImplicitHasher);
+ store.register_late_pass(|| box fallible_impl_from::FallibleImplFrom);
+ store.register_late_pass(|| box types::UnitArg);
+ store.register_late_pass(|| box double_comparison::DoubleComparisons);
+ store.register_late_pass(|| box question_mark::QuestionMark);
+ store.register_late_pass(|| box suspicious_trait_impl::SuspiciousImpl);
+ store.register_late_pass(|| box map_unit_fn::MapUnit);
+ store.register_late_pass(|| box inherent_impl::MultipleInherentImpl::default());
+ store.register_late_pass(|| box neg_cmp_op_on_partial_ord::NoNegCompOpForPartialOrd);
+ store.register_late_pass(|| box unwrap::Unwrap);
+ store.register_late_pass(|| box duration_subsec::DurationSubsec);
+ store.register_late_pass(|| box default_trait_access::DefaultTraitAccess);
+ store.register_late_pass(|| box indexing_slicing::IndexingSlicing);
+ store.register_late_pass(|| box non_copy_const::NonCopyConst);
+ store.register_late_pass(|| box ptr_offset_with_cast::PtrOffsetWithCast);
+ store.register_late_pass(|| box redundant_clone::RedundantClone);
+ store.register_late_pass(|| box slow_vector_initialization::SlowVectorInit);
+ store.register_late_pass(|| box unnecessary_sort_by::UnnecessarySortBy);
+ store.register_late_pass(|| box types::RefToMut);
+ store.register_late_pass(|| box assertions_on_constants::AssertionsOnConstants);
+ store.register_late_pass(|| box missing_const_for_fn::MissingConstForFn);
+ store.register_late_pass(|| box transmuting_null::TransmutingNull);
+ store.register_late_pass(|| box path_buf_push_overwrite::PathBufPushOverwrite);
+ store.register_late_pass(|| box checked_conversions::CheckedConversions);
+ store.register_late_pass(|| box integer_division::IntegerDivision);
+ store.register_late_pass(|| box inherent_to_string::InherentToString);
+ let max_trait_bounds = conf.max_trait_bounds;
+ store.register_late_pass(move || box trait_bounds::TraitBounds::new(max_trait_bounds));
+ store.register_late_pass(|| box comparison_chain::ComparisonChain);
+ store.register_late_pass(|| box mut_key::MutableKeyType);
+ store.register_late_pass(|| box modulo_arithmetic::ModuloArithmetic);
+ store.register_early_pass(|| box reference::DerefAddrOf);
+ store.register_early_pass(|| box reference::RefInDeref);
+ store.register_early_pass(|| box double_parens::DoubleParens);
+ store.register_late_pass(|| box to_string_in_display::ToStringInDisplay::new());
+ store.register_early_pass(|| box unsafe_removed_from_name::UnsafeNameRemoval);
+ store.register_early_pass(|| box if_not_else::IfNotElse);
+ store.register_early_pass(|| box else_if_without_else::ElseIfWithoutElse);
+ store.register_early_pass(|| box int_plus_one::IntPlusOne);
+ store.register_early_pass(|| box formatting::Formatting);
+ store.register_early_pass(|| box misc_early::MiscEarlyLints);
+ store.register_early_pass(|| box redundant_closure_call::RedundantClosureCall);
+ store.register_late_pass(|| box redundant_closure_call::RedundantClosureCall);
+ store.register_early_pass(|| box unused_unit::UnusedUnit);
+ store.register_late_pass(|| box returns::Return);
+ store.register_early_pass(|| box collapsible_if::CollapsibleIf);
+ store.register_early_pass(|| box items_after_statements::ItemsAfterStatements);
+ store.register_early_pass(|| box precedence::Precedence);
+ store.register_early_pass(|| box needless_continue::NeedlessContinue);
++ store.register_late_pass(|| box create_dir::CreateDir);
+ store.register_early_pass(|| box needless_arbitrary_self_type::NeedlessArbitrarySelfType);
+ store.register_early_pass(|| box redundant_static_lifetimes::RedundantStaticLifetimes);
+ store.register_late_pass(|| box cargo_common_metadata::CargoCommonMetadata);
+ store.register_late_pass(|| box multiple_crate_versions::MultipleCrateVersions);
+ store.register_late_pass(|| box wildcard_dependencies::WildcardDependencies);
+ store.register_early_pass(|| box literal_representation::LiteralDigitGrouping);
+ let literal_representation_threshold = conf.literal_representation_threshold;
+ store.register_early_pass(move || box literal_representation::DecimalLiteralRepresentation::new(literal_representation_threshold));
+ store.register_early_pass(|| box utils::internal_lints::ClippyLintsInternal);
+ let enum_variant_name_threshold = conf.enum_variant_name_threshold;
+ store.register_early_pass(move || box enum_variants::EnumVariantNames::new(enum_variant_name_threshold));
+ store.register_early_pass(|| box tabs_in_doc_comments::TabsInDocComments);
+ store.register_late_pass(|| box unused_self::UnusedSelf);
+ store.register_late_pass(|| box mutable_debug_assertion::DebugAssertWithMutCall);
+ store.register_late_pass(|| box exit::Exit);
+ store.register_late_pass(|| box to_digit_is_some::ToDigitIsSome);
+ let array_size_threshold = conf.array_size_threshold;
+ store.register_late_pass(move || box large_stack_arrays::LargeStackArrays::new(array_size_threshold));
+ store.register_late_pass(move || box large_const_arrays::LargeConstArrays::new(array_size_threshold));
+ store.register_late_pass(|| box floating_point_arithmetic::FloatingPointArithmetic);
+ store.register_early_pass(|| box as_conversions::AsConversions);
+ store.register_early_pass(|| box utils::internal_lints::ProduceIce);
+ store.register_late_pass(|| box let_underscore::LetUnderscore);
+ store.register_late_pass(|| box atomic_ordering::AtomicOrdering);
+ store.register_early_pass(|| box single_component_path_imports::SingleComponentPathImports);
+ let max_fn_params_bools = conf.max_fn_params_bools;
+ let max_struct_bools = conf.max_struct_bools;
+ store.register_early_pass(move || box excessive_bools::ExcessiveBools::new(max_struct_bools, max_fn_params_bools));
+ store.register_early_pass(|| box option_env_unwrap::OptionEnvUnwrap);
+ let warn_on_all_wildcard_imports = conf.warn_on_all_wildcard_imports;
+ store.register_late_pass(move || box wildcard_imports::WildcardImports::new(warn_on_all_wildcard_imports));
+ store.register_late_pass(|| box verbose_file_reads::VerboseFileReads);
+ store.register_late_pass(|| box redundant_pub_crate::RedundantPubCrate::default());
+ store.register_late_pass(|| box unnamed_address::UnnamedAddress);
+ store.register_late_pass(|| box dereference::Dereferencing);
+ store.register_late_pass(|| box option_if_let_else::OptionIfLetElse);
+ store.register_late_pass(|| box future_not_send::FutureNotSend);
+ store.register_late_pass(|| box utils::internal_lints::CollapsibleCalls);
+ store.register_late_pass(|| box if_let_mutex::IfLetMutex);
+ store.register_late_pass(|| box match_on_vec_items::MatchOnVecItems);
+ store.register_early_pass(|| box manual_non_exhaustive::ManualNonExhaustive);
+ store.register_late_pass(|| box manual_async_fn::ManualAsyncFn);
+ store.register_early_pass(|| box redundant_field_names::RedundantFieldNames);
+ store.register_late_pass(|| box vec_resize_to_zero::VecResizeToZero);
+ let single_char_binding_names_threshold = conf.single_char_binding_names_threshold;
+ store.register_early_pass(move || box non_expressive_names::NonExpressiveNames {
+ single_char_binding_names_threshold,
+ });
+ store.register_early_pass(|| box unnested_or_patterns::UnnestedOrPatterns);
+ store.register_late_pass(|| box macro_use::MacroUseImports::default());
+ store.register_late_pass(|| box map_identity::MapIdentity);
+ store.register_late_pass(|| box pattern_type_mismatch::PatternTypeMismatch);
+ store.register_late_pass(|| box stable_sort_primitive::StableSortPrimitive);
+ store.register_late_pass(|| box repeat_once::RepeatOnce);
+ store.register_late_pass(|| box unwrap_in_result::UnwrapInResult);
+ store.register_late_pass(|| box self_assignment::SelfAssignment);
+ store.register_late_pass(|| box float_equality_without_abs::FloatEqualityWithoutAbs);
++ store.register_late_pass(|| box async_yields_async::AsyncYieldsAsync);
+
+ store.register_group(true, "clippy::restriction", Some("clippy_restriction"), vec![
+ LintId::of(&arithmetic::FLOAT_ARITHMETIC),
+ LintId::of(&arithmetic::INTEGER_ARITHMETIC),
+ LintId::of(&as_conversions::AS_CONVERSIONS),
++ LintId::of(&create_dir::CREATE_DIR),
+ LintId::of(&dbg_macro::DBG_MACRO),
+ LintId::of(&else_if_without_else::ELSE_IF_WITHOUT_ELSE),
+ LintId::of(&exit::EXIT),
+ LintId::of(&float_literal::LOSSY_FLOAT_LITERAL),
+ LintId::of(&implicit_return::IMPLICIT_RETURN),
+ LintId::of(&indexing_slicing::INDEXING_SLICING),
+ LintId::of(&inherent_impl::MULTIPLE_INHERENT_IMPL),
+ LintId::of(&integer_division::INTEGER_DIVISION),
+ LintId::of(&let_underscore::LET_UNDERSCORE_MUST_USE),
+ LintId::of(&literal_representation::DECIMAL_LITERAL_REPRESENTATION),
+ LintId::of(&matches::REST_PAT_IN_FULLY_BOUND_STRUCTS),
+ LintId::of(&matches::WILDCARD_ENUM_MATCH_ARM),
+ LintId::of(&mem_forget::MEM_FORGET),
+ LintId::of(&methods::CLONE_ON_REF_PTR),
+ LintId::of(&methods::EXPECT_USED),
+ LintId::of(&methods::FILETYPE_IS_FILE),
+ LintId::of(&methods::GET_UNWRAP),
+ LintId::of(&methods::UNWRAP_USED),
+ LintId::of(&methods::WRONG_PUB_SELF_CONVENTION),
+ LintId::of(&misc::FLOAT_CMP_CONST),
+ LintId::of(&misc_early::UNNEEDED_FIELD_PATTERN),
+ LintId::of(&missing_doc::MISSING_DOCS_IN_PRIVATE_ITEMS),
+ LintId::of(&missing_inline::MISSING_INLINE_IN_PUBLIC_ITEMS),
+ LintId::of(&modulo_arithmetic::MODULO_ARITHMETIC),
+ LintId::of(&panic_unimplemented::PANIC),
+ LintId::of(&panic_unimplemented::TODO),
+ LintId::of(&panic_unimplemented::UNIMPLEMENTED),
+ LintId::of(&panic_unimplemented::UNREACHABLE),
+ LintId::of(&pattern_type_mismatch::PATTERN_TYPE_MISMATCH),
+ LintId::of(&shadow::SHADOW_REUSE),
+ LintId::of(&shadow::SHADOW_SAME),
+ LintId::of(&strings::STRING_ADD),
+ LintId::of(&unwrap_in_result::UNWRAP_IN_RESULT),
+ LintId::of(&verbose_file_reads::VERBOSE_FILE_READS),
+ LintId::of(&write::PRINT_STDOUT),
+ LintId::of(&write::USE_DEBUG),
+ ]);
+
+ store.register_group(true, "clippy::pedantic", Some("clippy_pedantic"), vec![
+ LintId::of(&attrs::INLINE_ALWAYS),
+ LintId::of(&await_holding_lock::AWAIT_HOLDING_LOCK),
+ LintId::of(&checked_conversions::CHECKED_CONVERSIONS),
+ LintId::of(&copies::MATCH_SAME_ARMS),
+ LintId::of(&copies::SAME_FUNCTIONS_IN_IF_CONDITION),
+ LintId::of(©_iterator::COPY_ITERATOR),
+ LintId::of(&default_trait_access::DEFAULT_TRAIT_ACCESS),
+ LintId::of(&dereference::EXPLICIT_DEREF_METHODS),
+ LintId::of(&derive::EXPL_IMPL_CLONE_ON_COPY),
+ LintId::of(&derive::UNSAFE_DERIVE_DESERIALIZE),
+ LintId::of(&doc::DOC_MARKDOWN),
+ LintId::of(&doc::MISSING_ERRORS_DOC),
+ LintId::of(&empty_enum::EMPTY_ENUM),
+ LintId::of(&enum_variants::MODULE_NAME_REPETITIONS),
+ LintId::of(&enum_variants::PUB_ENUM_VARIANT_NAMES),
+ LintId::of(&eta_reduction::REDUNDANT_CLOSURE_FOR_METHOD_CALLS),
+ LintId::of(&excessive_bools::FN_PARAMS_EXCESSIVE_BOOLS),
+ LintId::of(&excessive_bools::STRUCT_EXCESSIVE_BOOLS),
+ LintId::of(&functions::MUST_USE_CANDIDATE),
+ LintId::of(&functions::TOO_MANY_LINES),
+ LintId::of(&if_not_else::IF_NOT_ELSE),
+ LintId::of(&implicit_saturating_sub::IMPLICIT_SATURATING_SUB),
+ LintId::of(&infinite_iter::MAYBE_INFINITE_ITER),
+ LintId::of(&items_after_statements::ITEMS_AFTER_STATEMENTS),
+ LintId::of(&large_stack_arrays::LARGE_STACK_ARRAYS),
+ LintId::of(&literal_representation::LARGE_DIGIT_GROUPS),
+ LintId::of(&literal_representation::UNREADABLE_LITERAL),
+ LintId::of(&loops::EXPLICIT_INTO_ITER_LOOP),
+ LintId::of(&loops::EXPLICIT_ITER_LOOP),
+ LintId::of(¯o_use::MACRO_USE_IMPORTS),
+ LintId::of(&match_on_vec_items::MATCH_ON_VEC_ITEMS),
+ LintId::of(&matches::MATCH_BOOL),
+ LintId::of(&matches::MATCH_WILDCARD_FOR_SINGLE_VARIANTS),
+ LintId::of(&matches::MATCH_WILD_ERR_ARM),
+ LintId::of(&matches::SINGLE_MATCH_ELSE),
+ LintId::of(&methods::FILTER_MAP),
+ LintId::of(&methods::FILTER_MAP_NEXT),
+ LintId::of(&methods::FIND_MAP),
+ LintId::of(&methods::INEFFICIENT_TO_STRING),
+ LintId::of(&methods::MAP_FLATTEN),
+ LintId::of(&methods::MAP_UNWRAP_OR),
+ LintId::of(&misc::USED_UNDERSCORE_BINDING),
+ LintId::of(&misc_early::UNSEPARATED_LITERAL_SUFFIX),
+ LintId::of(&mut_mut::MUT_MUT),
+ LintId::of(&needless_continue::NEEDLESS_CONTINUE),
+ LintId::of(&needless_pass_by_value::NEEDLESS_PASS_BY_VALUE),
+ LintId::of(&non_expressive_names::SIMILAR_NAMES),
+ LintId::of(&option_if_let_else::OPTION_IF_LET_ELSE),
+ LintId::of(&ranges::RANGE_MINUS_ONE),
+ LintId::of(&ranges::RANGE_PLUS_ONE),
+ LintId::of(&shadow::SHADOW_UNRELATED),
+ LintId::of(&strings::STRING_ADD_ASSIGN),
+ LintId::of(&trait_bounds::TRAIT_DUPLICATION_IN_BOUNDS),
+ LintId::of(&trait_bounds::TYPE_REPETITION_IN_BOUNDS),
+ LintId::of(&trivially_copy_pass_by_ref::TRIVIALLY_COPY_PASS_BY_REF),
+ LintId::of(&types::CAST_LOSSLESS),
+ LintId::of(&types::CAST_POSSIBLE_TRUNCATION),
+ LintId::of(&types::CAST_POSSIBLE_WRAP),
+ LintId::of(&types::CAST_PRECISION_LOSS),
+ LintId::of(&types::CAST_PTR_ALIGNMENT),
+ LintId::of(&types::CAST_SIGN_LOSS),
+ LintId::of(&types::IMPLICIT_HASHER),
+ LintId::of(&types::INVALID_UPCAST_COMPARISONS),
+ LintId::of(&types::LET_UNIT_VALUE),
+ LintId::of(&types::LINKEDLIST),
+ LintId::of(&types::OPTION_OPTION),
+ LintId::of(&unicode::NON_ASCII_LITERAL),
+ LintId::of(&unicode::UNICODE_NOT_NFC),
+ LintId::of(&unnested_or_patterns::UNNESTED_OR_PATTERNS),
+ LintId::of(&unused_self::UNUSED_SELF),
+ LintId::of(&wildcard_imports::ENUM_GLOB_USE),
+ LintId::of(&wildcard_imports::WILDCARD_IMPORTS),
+ ]);
+
+ store.register_group(true, "clippy::internal", Some("clippy_internal"), vec![
+ LintId::of(&utils::internal_lints::CLIPPY_LINTS_INTERNAL),
+ LintId::of(&utils::internal_lints::COLLAPSIBLE_SPAN_LINT_CALLS),
+ LintId::of(&utils::internal_lints::COMPILER_LINT_FUNCTIONS),
+ LintId::of(&utils::internal_lints::DEFAULT_LINT),
+ LintId::of(&utils::internal_lints::LINT_WITHOUT_LINT_PASS),
+ LintId::of(&utils::internal_lints::OUTER_EXPN_EXPN_DATA),
+ LintId::of(&utils::internal_lints::PRODUCE_ICE),
+ ]);
+
+ store.register_group(true, "clippy::all", Some("clippy"), vec![
+ LintId::of(&approx_const::APPROX_CONSTANT),
+ LintId::of(&assertions_on_constants::ASSERTIONS_ON_CONSTANTS),
+ LintId::of(&assign_ops::ASSIGN_OP_PATTERN),
+ LintId::of(&assign_ops::MISREFACTORED_ASSIGN_OP),
++ LintId::of(&async_yields_async::ASYNC_YIELDS_ASYNC),
+ LintId::of(&atomic_ordering::INVALID_ATOMIC_ORDERING),
+ LintId::of(&attrs::BLANKET_CLIPPY_RESTRICTION_LINTS),
+ LintId::of(&attrs::DEPRECATED_CFG_ATTR),
+ LintId::of(&attrs::DEPRECATED_SEMVER),
+ LintId::of(&attrs::MISMATCHED_TARGET_OS),
+ LintId::of(&attrs::UNKNOWN_CLIPPY_LINTS),
+ LintId::of(&attrs::USELESS_ATTRIBUTE),
+ LintId::of(&bit_mask::BAD_BIT_MASK),
+ LintId::of(&bit_mask::INEFFECTIVE_BIT_MASK),
+ LintId::of(&bit_mask::VERBOSE_BIT_MASK),
+ LintId::of(&blacklisted_name::BLACKLISTED_NAME),
+ LintId::of(&blocks_in_if_conditions::BLOCKS_IN_IF_CONDITIONS),
+ LintId::of(&booleans::LOGIC_BUG),
+ LintId::of(&booleans::NONMINIMAL_BOOL),
+ LintId::of(&bytecount::NAIVE_BYTECOUNT),
+ LintId::of(&collapsible_if::COLLAPSIBLE_IF),
+ LintId::of(&comparison_chain::COMPARISON_CHAIN),
+ LintId::of(&copies::IFS_SAME_COND),
+ LintId::of(&copies::IF_SAME_THEN_ELSE),
+ LintId::of(&derive::DERIVE_HASH_XOR_EQ),
+ LintId::of(&derive::DERIVE_ORD_XOR_PARTIAL_ORD),
+ LintId::of(&doc::MISSING_SAFETY_DOC),
+ LintId::of(&doc::NEEDLESS_DOCTEST_MAIN),
+ LintId::of(&double_comparison::DOUBLE_COMPARISONS),
+ LintId::of(&double_parens::DOUBLE_PARENS),
+ LintId::of(&drop_bounds::DROP_BOUNDS),
+ LintId::of(&drop_forget_ref::DROP_COPY),
+ LintId::of(&drop_forget_ref::DROP_REF),
+ LintId::of(&drop_forget_ref::FORGET_COPY),
+ LintId::of(&drop_forget_ref::FORGET_REF),
+ LintId::of(&duration_subsec::DURATION_SUBSEC),
+ LintId::of(&entry::MAP_ENTRY),
+ LintId::of(&enum_clike::ENUM_CLIKE_UNPORTABLE_VARIANT),
+ LintId::of(&enum_variants::ENUM_VARIANT_NAMES),
+ LintId::of(&enum_variants::MODULE_INCEPTION),
+ LintId::of(&eq_op::EQ_OP),
+ LintId::of(&eq_op::OP_REF),
+ LintId::of(&erasing_op::ERASING_OP),
+ LintId::of(&escape::BOXED_LOCAL),
+ LintId::of(&eta_reduction::REDUNDANT_CLOSURE),
+ LintId::of(&eval_order_dependence::DIVERGING_SUB_EXPRESSION),
+ LintId::of(&eval_order_dependence::EVAL_ORDER_DEPENDENCE),
+ LintId::of(&explicit_write::EXPLICIT_WRITE),
+ LintId::of(&float_equality_without_abs::FLOAT_EQUALITY_WITHOUT_ABS),
+ LintId::of(&float_literal::EXCESSIVE_PRECISION),
+ LintId::of(&format::USELESS_FORMAT),
+ LintId::of(&formatting::POSSIBLE_MISSING_COMMA),
+ LintId::of(&formatting::SUSPICIOUS_ASSIGNMENT_FORMATTING),
+ LintId::of(&formatting::SUSPICIOUS_ELSE_FORMATTING),
+ LintId::of(&formatting::SUSPICIOUS_UNARY_OP_FORMATTING),
+ LintId::of(&functions::DOUBLE_MUST_USE),
+ LintId::of(&functions::MUST_USE_UNIT),
+ LintId::of(&functions::NOT_UNSAFE_PTR_ARG_DEREF),
+ LintId::of(&functions::TOO_MANY_ARGUMENTS),
+ LintId::of(&get_last_with_len::GET_LAST_WITH_LEN),
+ LintId::of(&identity_op::IDENTITY_OP),
+ LintId::of(&if_let_mutex::IF_LET_MUTEX),
+ LintId::of(&if_let_some_result::IF_LET_SOME_RESULT),
+ LintId::of(&indexing_slicing::OUT_OF_BOUNDS_INDEXING),
+ LintId::of(&infinite_iter::INFINITE_ITER),
+ LintId::of(&inherent_to_string::INHERENT_TO_STRING),
+ LintId::of(&inherent_to_string::INHERENT_TO_STRING_SHADOW_DISPLAY),
+ LintId::of(&inline_fn_without_body::INLINE_FN_WITHOUT_BODY),
+ LintId::of(&int_plus_one::INT_PLUS_ONE),
+ LintId::of(&large_const_arrays::LARGE_CONST_ARRAYS),
+ LintId::of(&large_enum_variant::LARGE_ENUM_VARIANT),
+ LintId::of(&len_zero::LEN_WITHOUT_IS_EMPTY),
+ LintId::of(&len_zero::LEN_ZERO),
+ LintId::of(&let_underscore::LET_UNDERSCORE_LOCK),
+ LintId::of(&lifetimes::EXTRA_UNUSED_LIFETIMES),
+ LintId::of(&lifetimes::NEEDLESS_LIFETIMES),
+ LintId::of(&literal_representation::INCONSISTENT_DIGIT_GROUPING),
+ LintId::of(&literal_representation::MISTYPED_LITERAL_SUFFIXES),
+ LintId::of(&loops::EMPTY_LOOP),
+ LintId::of(&loops::EXPLICIT_COUNTER_LOOP),
+ LintId::of(&loops::FOR_KV_MAP),
+ LintId::of(&loops::FOR_LOOPS_OVER_FALLIBLES),
+ LintId::of(&loops::ITER_NEXT_LOOP),
+ LintId::of(&loops::MANUAL_MEMCPY),
+ LintId::of(&loops::MUT_RANGE_BOUND),
+ LintId::of(&loops::NEEDLESS_COLLECT),
+ LintId::of(&loops::NEEDLESS_RANGE_LOOP),
+ LintId::of(&loops::NEVER_LOOP),
+ LintId::of(&loops::SAME_ITEM_PUSH),
+ LintId::of(&loops::WHILE_IMMUTABLE_CONDITION),
+ LintId::of(&loops::WHILE_LET_LOOP),
+ LintId::of(&loops::WHILE_LET_ON_ITERATOR),
+ LintId::of(&main_recursion::MAIN_RECURSION),
+ LintId::of(&manual_async_fn::MANUAL_ASYNC_FN),
+ LintId::of(&manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE),
+ LintId::of(&map_clone::MAP_CLONE),
+ LintId::of(&map_identity::MAP_IDENTITY),
+ LintId::of(&map_unit_fn::OPTION_MAP_UNIT_FN),
+ LintId::of(&map_unit_fn::RESULT_MAP_UNIT_FN),
+ LintId::of(&matches::INFALLIBLE_DESTRUCTURING_MATCH),
+ LintId::of(&matches::MATCH_AS_REF),
+ LintId::of(&matches::MATCH_LIKE_MATCHES_MACRO),
+ LintId::of(&matches::MATCH_OVERLAPPING_ARM),
+ LintId::of(&matches::MATCH_REF_PATS),
+ LintId::of(&matches::MATCH_SINGLE_BINDING),
+ LintId::of(&matches::REDUNDANT_PATTERN_MATCHING),
+ LintId::of(&matches::SINGLE_MATCH),
+ LintId::of(&matches::WILDCARD_IN_OR_PATTERNS),
+ LintId::of(&mem_discriminant::MEM_DISCRIMINANT_NON_ENUM),
+ LintId::of(&mem_replace::MEM_REPLACE_OPTION_WITH_NONE),
+ LintId::of(&mem_replace::MEM_REPLACE_WITH_DEFAULT),
+ LintId::of(&mem_replace::MEM_REPLACE_WITH_UNINIT),
+ LintId::of(&methods::BIND_INSTEAD_OF_MAP),
+ LintId::of(&methods::CHARS_LAST_CMP),
+ LintId::of(&methods::CHARS_NEXT_CMP),
+ LintId::of(&methods::CLONE_DOUBLE_REF),
+ LintId::of(&methods::CLONE_ON_COPY),
+ LintId::of(&methods::EXPECT_FUN_CALL),
+ LintId::of(&methods::FILTER_NEXT),
+ LintId::of(&methods::FLAT_MAP_IDENTITY),
+ LintId::of(&methods::INTO_ITER_ON_REF),
+ LintId::of(&methods::ITERATOR_STEP_BY_ZERO),
+ LintId::of(&methods::ITER_CLONED_COLLECT),
+ LintId::of(&methods::ITER_NEXT_SLICE),
+ LintId::of(&methods::ITER_NTH),
+ LintId::of(&methods::ITER_NTH_ZERO),
+ LintId::of(&methods::ITER_SKIP_NEXT),
+ LintId::of(&methods::MANUAL_SATURATING_ARITHMETIC),
+ LintId::of(&methods::NEW_RET_NO_SELF),
+ LintId::of(&methods::OK_EXPECT),
+ LintId::of(&methods::OPTION_AS_REF_DEREF),
+ LintId::of(&methods::OPTION_MAP_OR_NONE),
+ LintId::of(&methods::OR_FUN_CALL),
+ LintId::of(&methods::RESULT_MAP_OR_INTO_OPTION),
+ LintId::of(&methods::SEARCH_IS_SOME),
+ LintId::of(&methods::SHOULD_IMPLEMENT_TRAIT),
+ LintId::of(&methods::SINGLE_CHAR_PATTERN),
+ LintId::of(&methods::SINGLE_CHAR_PUSH_STR),
+ LintId::of(&methods::SKIP_WHILE_NEXT),
+ LintId::of(&methods::STRING_EXTEND_CHARS),
+ LintId::of(&methods::SUSPICIOUS_MAP),
+ LintId::of(&methods::TEMPORARY_CSTRING_AS_PTR),
+ LintId::of(&methods::UNINIT_ASSUMED_INIT),
+ LintId::of(&methods::UNNECESSARY_FILTER_MAP),
+ LintId::of(&methods::UNNECESSARY_FOLD),
+ LintId::of(&methods::UNNECESSARY_LAZY_EVALUATIONS),
+ LintId::of(&methods::USELESS_ASREF),
+ LintId::of(&methods::WRONG_SELF_CONVENTION),
+ LintId::of(&methods::ZST_OFFSET),
+ LintId::of(&minmax::MIN_MAX),
+ LintId::of(&misc::CMP_NAN),
+ LintId::of(&misc::CMP_OWNED),
+ LintId::of(&misc::FLOAT_CMP),
+ LintId::of(&misc::MODULO_ONE),
+ LintId::of(&misc::SHORT_CIRCUIT_STATEMENT),
+ LintId::of(&misc::TOPLEVEL_REF_ARG),
+ LintId::of(&misc::ZERO_PTR),
+ LintId::of(&misc_early::BUILTIN_TYPE_SHADOW),
+ LintId::of(&misc_early::DOUBLE_NEG),
+ LintId::of(&misc_early::DUPLICATE_UNDERSCORE_ARGUMENT),
+ LintId::of(&misc_early::MIXED_CASE_HEX_LITERALS),
+ LintId::of(&misc_early::REDUNDANT_PATTERN),
+ LintId::of(&misc_early::UNNEEDED_WILDCARD_PATTERN),
+ LintId::of(&misc_early::ZERO_PREFIXED_LITERAL),
+ LintId::of(&mut_key::MUTABLE_KEY_TYPE),
+ LintId::of(&mut_reference::UNNECESSARY_MUT_PASSED),
+ LintId::of(&mutex_atomic::MUTEX_ATOMIC),
+ LintId::of(&needless_arbitrary_self_type::NEEDLESS_ARBITRARY_SELF_TYPE),
+ LintId::of(&needless_bool::BOOL_COMPARISON),
+ LintId::of(&needless_bool::NEEDLESS_BOOL),
+ LintId::of(&needless_borrowed_ref::NEEDLESS_BORROWED_REFERENCE),
+ LintId::of(&needless_update::NEEDLESS_UPDATE),
+ LintId::of(&neg_cmp_op_on_partial_ord::NEG_CMP_OP_ON_PARTIAL_ORD),
+ LintId::of(&neg_multiply::NEG_MULTIPLY),
+ LintId::of(&new_without_default::NEW_WITHOUT_DEFAULT),
+ LintId::of(&no_effect::NO_EFFECT),
+ LintId::of(&no_effect::UNNECESSARY_OPERATION),
+ LintId::of(&non_copy_const::BORROW_INTERIOR_MUTABLE_CONST),
+ LintId::of(&non_copy_const::DECLARE_INTERIOR_MUTABLE_CONST),
+ LintId::of(&non_expressive_names::JUST_UNDERSCORES_AND_DIGITS),
+ LintId::of(&non_expressive_names::MANY_SINGLE_CHAR_NAMES),
+ LintId::of(&open_options::NONSENSICAL_OPEN_OPTIONS),
+ LintId::of(&option_env_unwrap::OPTION_ENV_UNWRAP),
+ LintId::of(&overflow_check_conditional::OVERFLOW_CHECK_CONDITIONAL),
+ LintId::of(&panic_unimplemented::PANIC_PARAMS),
+ LintId::of(&partialeq_ne_impl::PARTIALEQ_NE_IMPL),
+ LintId::of(&precedence::PRECEDENCE),
+ LintId::of(&ptr::CMP_NULL),
+ LintId::of(&ptr::MUT_FROM_REF),
+ LintId::of(&ptr::PTR_ARG),
+ LintId::of(&ptr_offset_with_cast::PTR_OFFSET_WITH_CAST),
+ LintId::of(&question_mark::QUESTION_MARK),
+ LintId::of(&ranges::RANGE_ZIP_WITH_LEN),
+ LintId::of(&ranges::REVERSED_EMPTY_RANGES),
+ LintId::of(&redundant_clone::REDUNDANT_CLONE),
+ LintId::of(&redundant_closure_call::REDUNDANT_CLOSURE_CALL),
+ LintId::of(&redundant_field_names::REDUNDANT_FIELD_NAMES),
+ LintId::of(&redundant_static_lifetimes::REDUNDANT_STATIC_LIFETIMES),
+ LintId::of(&reference::DEREF_ADDROF),
+ LintId::of(&reference::REF_IN_DEREF),
+ LintId::of(®ex::INVALID_REGEX),
+ LintId::of(®ex::TRIVIAL_REGEX),
+ LintId::of(&repeat_once::REPEAT_ONCE),
+ LintId::of(&returns::LET_AND_RETURN),
+ LintId::of(&returns::NEEDLESS_RETURN),
+ LintId::of(&self_assignment::SELF_ASSIGNMENT),
+ LintId::of(&serde_api::SERDE_API_MISUSE),
+ LintId::of(&single_component_path_imports::SINGLE_COMPONENT_PATH_IMPORTS),
+ LintId::of(&slow_vector_initialization::SLOW_VECTOR_INITIALIZATION),
+ LintId::of(&stable_sort_primitive::STABLE_SORT_PRIMITIVE),
+ LintId::of(&strings::STRING_LIT_AS_BYTES),
+ LintId::of(&suspicious_trait_impl::SUSPICIOUS_ARITHMETIC_IMPL),
+ LintId::of(&suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL),
+ LintId::of(&swap::ALMOST_SWAPPED),
+ LintId::of(&swap::MANUAL_SWAP),
+ LintId::of(&tabs_in_doc_comments::TABS_IN_DOC_COMMENTS),
+ LintId::of(&temporary_assignment::TEMPORARY_ASSIGNMENT),
+ LintId::of(&to_digit_is_some::TO_DIGIT_IS_SOME),
+ LintId::of(&to_string_in_display::TO_STRING_IN_DISPLAY),
+ LintId::of(&transmute::CROSSPOINTER_TRANSMUTE),
+ LintId::of(&transmute::TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS),
+ LintId::of(&transmute::TRANSMUTE_BYTES_TO_STR),
+ LintId::of(&transmute::TRANSMUTE_FLOAT_TO_INT),
+ LintId::of(&transmute::TRANSMUTE_INT_TO_BOOL),
+ LintId::of(&transmute::TRANSMUTE_INT_TO_CHAR),
+ LintId::of(&transmute::TRANSMUTE_INT_TO_FLOAT),
+ LintId::of(&transmute::TRANSMUTE_PTR_TO_PTR),
+ LintId::of(&transmute::TRANSMUTE_PTR_TO_REF),
+ LintId::of(&transmute::UNSOUND_COLLECTION_TRANSMUTE),
+ LintId::of(&transmute::WRONG_TRANSMUTE),
+ LintId::of(&transmuting_null::TRANSMUTING_NULL),
+ LintId::of(&try_err::TRY_ERR),
+ LintId::of(&types::ABSURD_EXTREME_COMPARISONS),
+ LintId::of(&types::BORROWED_BOX),
+ LintId::of(&types::BOX_VEC),
+ LintId::of(&types::CAST_REF_TO_MUT),
+ LintId::of(&types::CHAR_LIT_AS_U8),
+ LintId::of(&types::FN_TO_NUMERIC_CAST),
+ LintId::of(&types::FN_TO_NUMERIC_CAST_WITH_TRUNCATION),
+ LintId::of(&types::REDUNDANT_ALLOCATION),
+ LintId::of(&types::TYPE_COMPLEXITY),
+ LintId::of(&types::UNIT_ARG),
+ LintId::of(&types::UNIT_CMP),
+ LintId::of(&types::UNNECESSARY_CAST),
+ LintId::of(&types::VEC_BOX),
+ LintId::of(&unicode::ZERO_WIDTH_SPACE),
+ LintId::of(&unit_return_expecting_ord::UNIT_RETURN_EXPECTING_ORD),
+ LintId::of(&unnamed_address::FN_ADDRESS_COMPARISONS),
+ LintId::of(&unnamed_address::VTABLE_ADDRESS_COMPARISONS),
+ LintId::of(&unnecessary_sort_by::UNNECESSARY_SORT_BY),
+ LintId::of(&unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME),
+ LintId::of(&unused_io_amount::UNUSED_IO_AMOUNT),
+ LintId::of(&unused_unit::UNUSED_UNIT),
+ LintId::of(&unwrap::PANICKING_UNWRAP),
+ LintId::of(&unwrap::UNNECESSARY_UNWRAP),
+ LintId::of(&useless_conversion::USELESS_CONVERSION),
+ LintId::of(&vec::USELESS_VEC),
+ LintId::of(&vec_resize_to_zero::VEC_RESIZE_TO_ZERO),
+ LintId::of(&write::PRINTLN_EMPTY_STRING),
+ LintId::of(&write::PRINT_LITERAL),
+ LintId::of(&write::PRINT_WITH_NEWLINE),
+ LintId::of(&write::WRITELN_EMPTY_STRING),
+ LintId::of(&write::WRITE_LITERAL),
+ LintId::of(&write::WRITE_WITH_NEWLINE),
+ LintId::of(&zero_div_zero::ZERO_DIVIDED_BY_ZERO),
+ ]);
+
+ store.register_group(true, "clippy::style", Some("clippy_style"), vec![
+ LintId::of(&assertions_on_constants::ASSERTIONS_ON_CONSTANTS),
+ LintId::of(&assign_ops::ASSIGN_OP_PATTERN),
+ LintId::of(&attrs::BLANKET_CLIPPY_RESTRICTION_LINTS),
+ LintId::of(&attrs::UNKNOWN_CLIPPY_LINTS),
+ LintId::of(&bit_mask::VERBOSE_BIT_MASK),
+ LintId::of(&blacklisted_name::BLACKLISTED_NAME),
+ LintId::of(&blocks_in_if_conditions::BLOCKS_IN_IF_CONDITIONS),
+ LintId::of(&collapsible_if::COLLAPSIBLE_IF),
+ LintId::of(&comparison_chain::COMPARISON_CHAIN),
+ LintId::of(&doc::MISSING_SAFETY_DOC),
+ LintId::of(&doc::NEEDLESS_DOCTEST_MAIN),
+ LintId::of(&enum_variants::ENUM_VARIANT_NAMES),
+ LintId::of(&enum_variants::MODULE_INCEPTION),
+ LintId::of(&eq_op::OP_REF),
+ LintId::of(&eta_reduction::REDUNDANT_CLOSURE),
+ LintId::of(&float_literal::EXCESSIVE_PRECISION),
+ LintId::of(&formatting::SUSPICIOUS_ASSIGNMENT_FORMATTING),
+ LintId::of(&formatting::SUSPICIOUS_ELSE_FORMATTING),
+ LintId::of(&formatting::SUSPICIOUS_UNARY_OP_FORMATTING),
+ LintId::of(&functions::DOUBLE_MUST_USE),
+ LintId::of(&functions::MUST_USE_UNIT),
+ LintId::of(&if_let_some_result::IF_LET_SOME_RESULT),
+ LintId::of(&inherent_to_string::INHERENT_TO_STRING),
+ LintId::of(&len_zero::LEN_WITHOUT_IS_EMPTY),
+ LintId::of(&len_zero::LEN_ZERO),
+ LintId::of(&literal_representation::INCONSISTENT_DIGIT_GROUPING),
+ LintId::of(&loops::EMPTY_LOOP),
+ LintId::of(&loops::FOR_KV_MAP),
+ LintId::of(&loops::NEEDLESS_RANGE_LOOP),
+ LintId::of(&loops::SAME_ITEM_PUSH),
+ LintId::of(&loops::WHILE_LET_ON_ITERATOR),
+ LintId::of(&main_recursion::MAIN_RECURSION),
+ LintId::of(&manual_async_fn::MANUAL_ASYNC_FN),
+ LintId::of(&manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE),
+ LintId::of(&map_clone::MAP_CLONE),
+ LintId::of(&matches::INFALLIBLE_DESTRUCTURING_MATCH),
+ LintId::of(&matches::MATCH_LIKE_MATCHES_MACRO),
+ LintId::of(&matches::MATCH_OVERLAPPING_ARM),
+ LintId::of(&matches::MATCH_REF_PATS),
+ LintId::of(&matches::REDUNDANT_PATTERN_MATCHING),
+ LintId::of(&matches::SINGLE_MATCH),
+ LintId::of(&mem_replace::MEM_REPLACE_OPTION_WITH_NONE),
+ LintId::of(&mem_replace::MEM_REPLACE_WITH_DEFAULT),
+ LintId::of(&methods::CHARS_LAST_CMP),
+ LintId::of(&methods::CHARS_NEXT_CMP),
+ LintId::of(&methods::INTO_ITER_ON_REF),
+ LintId::of(&methods::ITER_CLONED_COLLECT),
+ LintId::of(&methods::ITER_NEXT_SLICE),
+ LintId::of(&methods::ITER_NTH_ZERO),
+ LintId::of(&methods::ITER_SKIP_NEXT),
+ LintId::of(&methods::MANUAL_SATURATING_ARITHMETIC),
+ LintId::of(&methods::NEW_RET_NO_SELF),
+ LintId::of(&methods::OK_EXPECT),
+ LintId::of(&methods::OPTION_MAP_OR_NONE),
+ LintId::of(&methods::RESULT_MAP_OR_INTO_OPTION),
+ LintId::of(&methods::SHOULD_IMPLEMENT_TRAIT),
+ LintId::of(&methods::SINGLE_CHAR_PUSH_STR),
+ LintId::of(&methods::STRING_EXTEND_CHARS),
+ LintId::of(&methods::UNNECESSARY_FOLD),
+ LintId::of(&methods::UNNECESSARY_LAZY_EVALUATIONS),
+ LintId::of(&methods::WRONG_SELF_CONVENTION),
+ LintId::of(&misc::TOPLEVEL_REF_ARG),
+ LintId::of(&misc::ZERO_PTR),
+ LintId::of(&misc_early::BUILTIN_TYPE_SHADOW),
+ LintId::of(&misc_early::DOUBLE_NEG),
+ LintId::of(&misc_early::DUPLICATE_UNDERSCORE_ARGUMENT),
+ LintId::of(&misc_early::MIXED_CASE_HEX_LITERALS),
+ LintId::of(&misc_early::REDUNDANT_PATTERN),
+ LintId::of(&mut_reference::UNNECESSARY_MUT_PASSED),
+ LintId::of(&neg_multiply::NEG_MULTIPLY),
+ LintId::of(&new_without_default::NEW_WITHOUT_DEFAULT),
+ LintId::of(&non_expressive_names::JUST_UNDERSCORES_AND_DIGITS),
+ LintId::of(&non_expressive_names::MANY_SINGLE_CHAR_NAMES),
+ LintId::of(&panic_unimplemented::PANIC_PARAMS),
+ LintId::of(&ptr::CMP_NULL),
+ LintId::of(&ptr::PTR_ARG),
+ LintId::of(&question_mark::QUESTION_MARK),
+ LintId::of(&redundant_field_names::REDUNDANT_FIELD_NAMES),
+ LintId::of(&redundant_static_lifetimes::REDUNDANT_STATIC_LIFETIMES),
+ LintId::of(®ex::TRIVIAL_REGEX),
+ LintId::of(&returns::LET_AND_RETURN),
+ LintId::of(&returns::NEEDLESS_RETURN),
+ LintId::of(&single_component_path_imports::SINGLE_COMPONENT_PATH_IMPORTS),
+ LintId::of(&strings::STRING_LIT_AS_BYTES),
+ LintId::of(&tabs_in_doc_comments::TABS_IN_DOC_COMMENTS),
+ LintId::of(&to_digit_is_some::TO_DIGIT_IS_SOME),
+ LintId::of(&try_err::TRY_ERR),
+ LintId::of(&types::FN_TO_NUMERIC_CAST),
+ LintId::of(&types::FN_TO_NUMERIC_CAST_WITH_TRUNCATION),
+ LintId::of(&unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME),
+ LintId::of(&unused_unit::UNUSED_UNIT),
+ LintId::of(&write::PRINTLN_EMPTY_STRING),
+ LintId::of(&write::PRINT_LITERAL),
+ LintId::of(&write::PRINT_WITH_NEWLINE),
+ LintId::of(&write::WRITELN_EMPTY_STRING),
+ LintId::of(&write::WRITE_LITERAL),
+ LintId::of(&write::WRITE_WITH_NEWLINE),
+ ]);
+
+ store.register_group(true, "clippy::complexity", Some("clippy_complexity"), vec![
+ LintId::of(&assign_ops::MISREFACTORED_ASSIGN_OP),
+ LintId::of(&attrs::DEPRECATED_CFG_ATTR),
+ LintId::of(&booleans::NONMINIMAL_BOOL),
+ LintId::of(&double_comparison::DOUBLE_COMPARISONS),
+ LintId::of(&double_parens::DOUBLE_PARENS),
+ LintId::of(&duration_subsec::DURATION_SUBSEC),
+ LintId::of(&eval_order_dependence::DIVERGING_SUB_EXPRESSION),
+ LintId::of(&eval_order_dependence::EVAL_ORDER_DEPENDENCE),
+ LintId::of(&explicit_write::EXPLICIT_WRITE),
+ LintId::of(&format::USELESS_FORMAT),
+ LintId::of(&functions::TOO_MANY_ARGUMENTS),
+ LintId::of(&get_last_with_len::GET_LAST_WITH_LEN),
+ LintId::of(&identity_op::IDENTITY_OP),
+ LintId::of(&int_plus_one::INT_PLUS_ONE),
+ LintId::of(&lifetimes::EXTRA_UNUSED_LIFETIMES),
+ LintId::of(&lifetimes::NEEDLESS_LIFETIMES),
+ LintId::of(&loops::EXPLICIT_COUNTER_LOOP),
+ LintId::of(&loops::MUT_RANGE_BOUND),
+ LintId::of(&loops::WHILE_LET_LOOP),
+ LintId::of(&map_identity::MAP_IDENTITY),
+ LintId::of(&map_unit_fn::OPTION_MAP_UNIT_FN),
+ LintId::of(&map_unit_fn::RESULT_MAP_UNIT_FN),
+ LintId::of(&matches::MATCH_AS_REF),
+ LintId::of(&matches::MATCH_SINGLE_BINDING),
+ LintId::of(&matches::WILDCARD_IN_OR_PATTERNS),
+ LintId::of(&methods::BIND_INSTEAD_OF_MAP),
+ LintId::of(&methods::CLONE_ON_COPY),
+ LintId::of(&methods::FILTER_NEXT),
+ LintId::of(&methods::FLAT_MAP_IDENTITY),
+ LintId::of(&methods::OPTION_AS_REF_DEREF),
+ LintId::of(&methods::SEARCH_IS_SOME),
+ LintId::of(&methods::SKIP_WHILE_NEXT),
+ LintId::of(&methods::SUSPICIOUS_MAP),
+ LintId::of(&methods::UNNECESSARY_FILTER_MAP),
+ LintId::of(&methods::USELESS_ASREF),
+ LintId::of(&misc::SHORT_CIRCUIT_STATEMENT),
+ LintId::of(&misc_early::UNNEEDED_WILDCARD_PATTERN),
+ LintId::of(&misc_early::ZERO_PREFIXED_LITERAL),
+ LintId::of(&needless_arbitrary_self_type::NEEDLESS_ARBITRARY_SELF_TYPE),
+ LintId::of(&needless_bool::BOOL_COMPARISON),
+ LintId::of(&needless_bool::NEEDLESS_BOOL),
+ LintId::of(&needless_borrowed_ref::NEEDLESS_BORROWED_REFERENCE),
+ LintId::of(&needless_update::NEEDLESS_UPDATE),
+ LintId::of(&neg_cmp_op_on_partial_ord::NEG_CMP_OP_ON_PARTIAL_ORD),
+ LintId::of(&no_effect::NO_EFFECT),
+ LintId::of(&no_effect::UNNECESSARY_OPERATION),
+ LintId::of(&overflow_check_conditional::OVERFLOW_CHECK_CONDITIONAL),
+ LintId::of(&partialeq_ne_impl::PARTIALEQ_NE_IMPL),
+ LintId::of(&precedence::PRECEDENCE),
+ LintId::of(&ptr_offset_with_cast::PTR_OFFSET_WITH_CAST),
+ LintId::of(&ranges::RANGE_ZIP_WITH_LEN),
+ LintId::of(&redundant_closure_call::REDUNDANT_CLOSURE_CALL),
+ LintId::of(&reference::DEREF_ADDROF),
+ LintId::of(&reference::REF_IN_DEREF),
+ LintId::of(&repeat_once::REPEAT_ONCE),
+ LintId::of(&swap::MANUAL_SWAP),
+ LintId::of(&temporary_assignment::TEMPORARY_ASSIGNMENT),
+ LintId::of(&transmute::CROSSPOINTER_TRANSMUTE),
+ LintId::of(&transmute::TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS),
+ LintId::of(&transmute::TRANSMUTE_BYTES_TO_STR),
+ LintId::of(&transmute::TRANSMUTE_FLOAT_TO_INT),
+ LintId::of(&transmute::TRANSMUTE_INT_TO_BOOL),
+ LintId::of(&transmute::TRANSMUTE_INT_TO_CHAR),
+ LintId::of(&transmute::TRANSMUTE_INT_TO_FLOAT),
+ LintId::of(&transmute::TRANSMUTE_PTR_TO_PTR),
+ LintId::of(&transmute::TRANSMUTE_PTR_TO_REF),
+ LintId::of(&types::BORROWED_BOX),
+ LintId::of(&types::CHAR_LIT_AS_U8),
+ LintId::of(&types::TYPE_COMPLEXITY),
+ LintId::of(&types::UNIT_ARG),
+ LintId::of(&types::UNNECESSARY_CAST),
+ LintId::of(&types::VEC_BOX),
+ LintId::of(&unnecessary_sort_by::UNNECESSARY_SORT_BY),
+ LintId::of(&unwrap::UNNECESSARY_UNWRAP),
+ LintId::of(&useless_conversion::USELESS_CONVERSION),
+ LintId::of(&zero_div_zero::ZERO_DIVIDED_BY_ZERO),
+ ]);
+
+ store.register_group(true, "clippy::correctness", Some("clippy_correctness"), vec![
+ LintId::of(&approx_const::APPROX_CONSTANT),
++ LintId::of(&async_yields_async::ASYNC_YIELDS_ASYNC),
+ LintId::of(&atomic_ordering::INVALID_ATOMIC_ORDERING),
+ LintId::of(&attrs::DEPRECATED_SEMVER),
+ LintId::of(&attrs::MISMATCHED_TARGET_OS),
+ LintId::of(&attrs::USELESS_ATTRIBUTE),
+ LintId::of(&bit_mask::BAD_BIT_MASK),
+ LintId::of(&bit_mask::INEFFECTIVE_BIT_MASK),
+ LintId::of(&booleans::LOGIC_BUG),
+ LintId::of(&copies::IFS_SAME_COND),
+ LintId::of(&copies::IF_SAME_THEN_ELSE),
+ LintId::of(&derive::DERIVE_HASH_XOR_EQ),
+ LintId::of(&derive::DERIVE_ORD_XOR_PARTIAL_ORD),
+ LintId::of(&drop_bounds::DROP_BOUNDS),
+ LintId::of(&drop_forget_ref::DROP_COPY),
+ LintId::of(&drop_forget_ref::DROP_REF),
+ LintId::of(&drop_forget_ref::FORGET_COPY),
+ LintId::of(&drop_forget_ref::FORGET_REF),
+ LintId::of(&enum_clike::ENUM_CLIKE_UNPORTABLE_VARIANT),
+ LintId::of(&eq_op::EQ_OP),
+ LintId::of(&erasing_op::ERASING_OP),
+ LintId::of(&float_equality_without_abs::FLOAT_EQUALITY_WITHOUT_ABS),
+ LintId::of(&formatting::POSSIBLE_MISSING_COMMA),
+ LintId::of(&functions::NOT_UNSAFE_PTR_ARG_DEREF),
+ LintId::of(&if_let_mutex::IF_LET_MUTEX),
+ LintId::of(&indexing_slicing::OUT_OF_BOUNDS_INDEXING),
+ LintId::of(&infinite_iter::INFINITE_ITER),
+ LintId::of(&inherent_to_string::INHERENT_TO_STRING_SHADOW_DISPLAY),
+ LintId::of(&inline_fn_without_body::INLINE_FN_WITHOUT_BODY),
+ LintId::of(&let_underscore::LET_UNDERSCORE_LOCK),
+ LintId::of(&literal_representation::MISTYPED_LITERAL_SUFFIXES),
+ LintId::of(&loops::FOR_LOOPS_OVER_FALLIBLES),
+ LintId::of(&loops::ITER_NEXT_LOOP),
+ LintId::of(&loops::NEVER_LOOP),
+ LintId::of(&loops::WHILE_IMMUTABLE_CONDITION),
+ LintId::of(&mem_discriminant::MEM_DISCRIMINANT_NON_ENUM),
+ LintId::of(&mem_replace::MEM_REPLACE_WITH_UNINIT),
+ LintId::of(&methods::CLONE_DOUBLE_REF),
+ LintId::of(&methods::ITERATOR_STEP_BY_ZERO),
+ LintId::of(&methods::TEMPORARY_CSTRING_AS_PTR),
+ LintId::of(&methods::UNINIT_ASSUMED_INIT),
+ LintId::of(&methods::ZST_OFFSET),
+ LintId::of(&minmax::MIN_MAX),
+ LintId::of(&misc::CMP_NAN),
+ LintId::of(&misc::FLOAT_CMP),
+ LintId::of(&misc::MODULO_ONE),
+ LintId::of(&mut_key::MUTABLE_KEY_TYPE),
+ LintId::of(&non_copy_const::BORROW_INTERIOR_MUTABLE_CONST),
+ LintId::of(&non_copy_const::DECLARE_INTERIOR_MUTABLE_CONST),
+ LintId::of(&open_options::NONSENSICAL_OPEN_OPTIONS),
+ LintId::of(&option_env_unwrap::OPTION_ENV_UNWRAP),
+ LintId::of(&ptr::MUT_FROM_REF),
+ LintId::of(&ranges::REVERSED_EMPTY_RANGES),
+ LintId::of(®ex::INVALID_REGEX),
+ LintId::of(&self_assignment::SELF_ASSIGNMENT),
+ LintId::of(&serde_api::SERDE_API_MISUSE),
+ LintId::of(&suspicious_trait_impl::SUSPICIOUS_ARITHMETIC_IMPL),
+ LintId::of(&suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL),
+ LintId::of(&swap::ALMOST_SWAPPED),
+ LintId::of(&to_string_in_display::TO_STRING_IN_DISPLAY),
+ LintId::of(&transmute::UNSOUND_COLLECTION_TRANSMUTE),
+ LintId::of(&transmute::WRONG_TRANSMUTE),
+ LintId::of(&transmuting_null::TRANSMUTING_NULL),
+ LintId::of(&types::ABSURD_EXTREME_COMPARISONS),
+ LintId::of(&types::CAST_REF_TO_MUT),
+ LintId::of(&types::UNIT_CMP),
+ LintId::of(&unicode::ZERO_WIDTH_SPACE),
+ LintId::of(&unit_return_expecting_ord::UNIT_RETURN_EXPECTING_ORD),
+ LintId::of(&unnamed_address::FN_ADDRESS_COMPARISONS),
+ LintId::of(&unnamed_address::VTABLE_ADDRESS_COMPARISONS),
+ LintId::of(&unused_io_amount::UNUSED_IO_AMOUNT),
+ LintId::of(&unwrap::PANICKING_UNWRAP),
+ LintId::of(&vec_resize_to_zero::VEC_RESIZE_TO_ZERO),
+ ]);
+
+ store.register_group(true, "clippy::perf", Some("clippy_perf"), vec![
+ LintId::of(&bytecount::NAIVE_BYTECOUNT),
+ LintId::of(&entry::MAP_ENTRY),
+ LintId::of(&escape::BOXED_LOCAL),
+ LintId::of(&large_const_arrays::LARGE_CONST_ARRAYS),
+ LintId::of(&large_enum_variant::LARGE_ENUM_VARIANT),
+ LintId::of(&loops::MANUAL_MEMCPY),
+ LintId::of(&loops::NEEDLESS_COLLECT),
+ LintId::of(&methods::EXPECT_FUN_CALL),
+ LintId::of(&methods::ITER_NTH),
+ LintId::of(&methods::OR_FUN_CALL),
+ LintId::of(&methods::SINGLE_CHAR_PATTERN),
+ LintId::of(&misc::CMP_OWNED),
+ LintId::of(&mutex_atomic::MUTEX_ATOMIC),
+ LintId::of(&redundant_clone::REDUNDANT_CLONE),
+ LintId::of(&slow_vector_initialization::SLOW_VECTOR_INITIALIZATION),
+ LintId::of(&stable_sort_primitive::STABLE_SORT_PRIMITIVE),
+ LintId::of(&types::BOX_VEC),
+ LintId::of(&types::REDUNDANT_ALLOCATION),
+ LintId::of(&vec::USELESS_VEC),
+ ]);
+
+ store.register_group(true, "clippy::cargo", Some("clippy_cargo"), vec![
+ LintId::of(&cargo_common_metadata::CARGO_COMMON_METADATA),
+ LintId::of(&multiple_crate_versions::MULTIPLE_CRATE_VERSIONS),
+ LintId::of(&wildcard_dependencies::WILDCARD_DEPENDENCIES),
+ ]);
+
+ store.register_group(true, "clippy::nursery", Some("clippy_nursery"), vec![
+ LintId::of(&attrs::EMPTY_LINE_AFTER_OUTER_ATTR),
+ LintId::of(&cognitive_complexity::COGNITIVE_COMPLEXITY),
+ LintId::of(&fallible_impl_from::FALLIBLE_IMPL_FROM),
+ LintId::of(&floating_point_arithmetic::IMPRECISE_FLOPS),
+ LintId::of(&floating_point_arithmetic::SUBOPTIMAL_FLOPS),
+ LintId::of(&future_not_send::FUTURE_NOT_SEND),
+ LintId::of(&let_if_seq::USELESS_LET_IF_SEQ),
+ LintId::of(&missing_const_for_fn::MISSING_CONST_FOR_FN),
+ LintId::of(&mutable_debug_assertion::DEBUG_ASSERT_WITH_MUT_CALL),
+ LintId::of(&mutex_atomic::MUTEX_INTEGER),
+ LintId::of(&needless_borrow::NEEDLESS_BORROW),
+ LintId::of(&path_buf_push_overwrite::PATH_BUF_PUSH_OVERWRITE),
+ LintId::of(&redundant_pub_crate::REDUNDANT_PUB_CRATE),
+ LintId::of(&transmute::USELESS_TRANSMUTE),
+ LintId::of(&use_self::USE_SELF),
+ ]);
+}
+
+#[rustfmt::skip]
+fn register_removed_non_tool_lints(store: &mut rustc_lint::LintStore) {
+ store.register_removed(
+ "should_assert_eq",
+ "`assert!()` will be more flexible with RFC 2011",
+ );
+ store.register_removed(
+ "extend_from_slice",
+ "`.extend_from_slice(_)` is a faster way to extend a Vec by a slice",
+ );
+ store.register_removed(
+ "range_step_by_zero",
+ "`iterator.step_by(0)` panics nowadays",
+ );
+ store.register_removed(
+ "unstable_as_slice",
+ "`Vec::as_slice` has been stabilized in 1.7",
+ );
+ store.register_removed(
+ "unstable_as_mut_slice",
+ "`Vec::as_mut_slice` has been stabilized in 1.7",
+ );
+ store.register_removed(
+ "str_to_string",
+ "using `str::to_string` is common even today and specialization will likely happen soon",
+ );
+ store.register_removed(
+ "string_to_string",
+ "using `string::to_string` is common even today and specialization will likely happen soon",
+ );
+ store.register_removed(
+ "misaligned_transmute",
+ "this lint has been split into cast_ptr_alignment and transmute_ptr_to_ptr",
+ );
+ store.register_removed(
+ "assign_ops",
+ "using compound assignment operators (e.g., `+=`) is harmless",
+ );
+ store.register_removed(
+ "if_let_redundant_pattern_matching",
+ "this lint has been changed to redundant_pattern_matching",
+ );
+ store.register_removed(
+ "unsafe_vector_initialization",
+ "the replacement suggested by this lint had substantially different behavior",
+ );
+ store.register_removed(
+ "reverse_range_loop",
+ "this lint is now included in reversed_empty_ranges",
+ );
+}
+
+/// Register renamed lints.
+///
+/// Used in `./src/driver.rs`.
+pub fn register_renamed(ls: &mut rustc_lint::LintStore) {
+ ls.register_renamed("clippy::stutter", "clippy::module_name_repetitions");
+ ls.register_renamed("clippy::new_without_default_derive", "clippy::new_without_default");
+ ls.register_renamed("clippy::cyclomatic_complexity", "clippy::cognitive_complexity");
+ ls.register_renamed("clippy::const_static_lifetime", "clippy::redundant_static_lifetimes");
+ ls.register_renamed("clippy::option_and_then_some", "clippy::bind_instead_of_map");
+ ls.register_renamed("clippy::block_in_if_condition_expr", "clippy::blocks_in_if_conditions");
+ ls.register_renamed("clippy::block_in_if_condition_stmt", "clippy::blocks_in_if_conditions");
+ ls.register_renamed("clippy::option_map_unwrap_or", "clippy::map_unwrap_or");
+ ls.register_renamed("clippy::option_map_unwrap_or_else", "clippy::map_unwrap_or");
+ ls.register_renamed("clippy::result_map_unwrap_or_else", "clippy::map_unwrap_or");
+ ls.register_renamed("clippy::option_unwrap_used", "clippy::unwrap_used");
+ ls.register_renamed("clippy::result_unwrap_used", "clippy::unwrap_used");
+ ls.register_renamed("clippy::option_expect_used", "clippy::expect_used");
+ ls.register_renamed("clippy::result_expect_used", "clippy::expect_used");
+ ls.register_renamed("clippy::for_loop_over_option", "clippy::for_loops_over_fallibles");
+ ls.register_renamed("clippy::for_loop_over_result", "clippy::for_loops_over_fallibles");
+ ls.register_renamed("clippy::identity_conversion", "clippy::useless_conversion");
+}
+
+// only exists to let the dogfood integration test works.
+// Don't run clippy as an executable directly
+#[allow(dead_code)]
+fn main() {
+ panic!("Please use the cargo-clippy executable");
+}
--- /dev/null
- // Make sure that the push does not involve possibly mutating values
- if let PatKind::Wild = pat.kind {
- let vec_str = snippet_with_macro_callsite(cx, vec.span, "");
- let item_str = snippet_with_macro_callsite(cx, pushed_item.span, "");
- if let ExprKind::Path(ref qpath) = pushed_item.kind {
- if_chain! {
- if let Res::Local(hir_id) = qpath_res(cx, qpath, pushed_item.hir_id);
- let node = cx.tcx.hir().get(hir_id);
- if let Node::Binding(pat) = node;
- if let PatKind::Binding(bind_ann, ..) = pat.kind;
- if !matches!(bind_ann, BindingAnnotation::RefMut | BindingAnnotation::Mutable);
- then {
- span_lint_and_help(
- cx,
- SAME_ITEM_PUSH,
- vec.span,
- "it looks like the same item is being pushed into this Vec",
- None,
- &format!(
- "try using vec![{};SIZE] or {}.resize(NEW_SIZE, {})",
- item_str, vec_str, item_str
- ),
- )
+use crate::consts::constant;
+use crate::utils::paths;
+use crate::utils::sugg::Sugg;
+use crate::utils::usage::{is_unused, mutated_variables};
+use crate::utils::{
+ get_enclosing_block, get_parent_expr, get_trait_def_id, has_iter_method, higher, implements_trait,
+ is_integer_const, is_no_std_crate, is_refutable, is_type_diagnostic_item, last_path_segment, match_trait_method,
+ match_type, match_var, multispan_sugg, qpath_res, snippet, snippet_opt, snippet_with_applicability,
+ snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, sugg,
+ SpanlessEq,
+};
+use if_chain::if_chain;
+use rustc_ast::ast;
+use rustc_data_structures::fx::{FxHashMap, FxHashSet};
+use rustc_errors::Applicability;
+use rustc_hir::def::{DefKind, Res};
+use rustc_hir::intravisit::{walk_block, walk_expr, walk_pat, walk_stmt, NestedVisitorMap, Visitor};
+use rustc_hir::{
+ def_id, BinOpKind, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, GenericArg, HirId, InlineAsmOperand,
+ Local, LoopSource, MatchSource, Mutability, Node, Pat, PatKind, QPath, Stmt, StmtKind,
+};
+use rustc_infer::infer::TyCtxtInferExt;
+use rustc_lint::{LateContext, LateLintPass, LintContext};
+use rustc_middle::hir::map::Map;
+use rustc_middle::lint::in_external_macro;
+use rustc_middle::middle::region;
+use rustc_middle::ty::{self, Ty, TyS};
+use rustc_session::{declare_lint_pass, declare_tool_lint};
+use rustc_span::source_map::Span;
+use rustc_span::symbol::{sym, Ident, Symbol};
+use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
+use std::iter::{once, Iterator};
+use std::mem;
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # let src = vec![1];
+ /// # let mut dst = vec![0; 65];
+ /// for i in 0..src.len() {
+ /// dst[i + 64] = src[i];
+ /// }
+ /// ```
+ /// Could be written as:
+ /// ```rust
+ /// # let src = vec![1];
+ /// # let mut dst = vec![0; 65];
+ /// dst[64..(src.len() + 64)].clone_from_slice(&src[..]);
+ /// ```
+ pub MANUAL_MEMCPY,
+ perf,
+ "manually copying items between slices"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// let vec = vec!['a', 'b', 'c'];
+ /// for i in 0..vec.len() {
+ /// println!("{}", vec[i]);
+ /// }
+ /// ```
+ /// Could be written as:
+ /// ```rust
+ /// let vec = vec!['a', 'b', 'c'];
+ /// for i in vec {
+ /// println!("{}", i);
+ /// }
+ /// ```
+ pub NEEDLESS_RANGE_LOOP,
+ style,
+ "for-looping over a range of indices where an iterator over items would do"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ /// ```rust
+ /// // with `y` a `Vec` or slice:
+ /// # let y = vec![1];
+ /// for x in y.iter() {
+ /// // ..
+ /// }
+ /// ```
+ /// can be rewritten to
+ /// ```rust
+ /// # let y = vec![1];
+ /// for x in &y {
+ /// // ..
+ /// }
+ /// ```
+ pub EXPLICIT_ITER_LOOP,
+ pedantic,
+ "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for loops on `y.into_iter()` where `y` will do, and
+ /// suggests the latter.
+ ///
+ /// **Why is this bad?** Readability.
+ ///
+ /// **Known problems:** None
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # let y = vec![1];
+ /// // with `y` a `Vec` or slice:
+ /// for x in y.into_iter() {
+ /// // ..
+ /// }
+ /// ```
+ /// can be rewritten to
+ /// ```rust
+ /// # let y = vec![1];
+ /// for x in y {
+ /// // ..
+ /// }
+ /// ```
+ pub EXPLICIT_INTO_ITER_LOOP,
+ pedantic,
+ "for-looping over `_.into_iter()` when `_` would do"
+}
+
+declare_clippy_lint! {
+ /// **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).
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```ignore
+ /// for x in y.next() {
+ /// ..
+ /// }
+ /// ```
+ pub ITER_NEXT_LOOP,
+ correctness,
+ "for-looping over `_.next()` which is probably not intended"
+}
+
+declare_clippy_lint! {
+ /// **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`.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # let opt = Some(1);
+ ///
+ /// // Bad
+ /// for x in opt {
+ /// // ..
+ /// }
+ ///
+ /// // Good
+ /// if let Some(x) = opt {
+ /// // ..
+ /// }
+ /// ```
+ ///
+ /// // or
+ ///
+ /// ```rust
+ /// # let res: Result<i32, std::io::Error> = Ok(1);
+ ///
+ /// // Bad
+ /// for x in &res {
+ /// // ..
+ /// }
+ ///
+ /// // Good
+ /// if let Ok(x) = res {
+ /// // ..
+ /// }
+ /// ```
+ pub FOR_LOOPS_OVER_FALLIBLES,
+ correctness,
+ "for-looping over an `Option` or a `Result`, which is more clearly expressed as an `if let`"
+}
+
+declare_clippy_lint! {
+ /// **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).
+ ///
+ /// **Example:**
+ /// ```rust,no_run
+ /// # let y = Some(1);
+ /// 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
+ /// };
+ /// ```
+ pub WHILE_LET_LOOP,
+ complexity,
+ "`loop { if let { ... } else break }`, which can be written as a `while let` loop"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:**
+ /// None
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # let iterator = vec![1].into_iter();
+ /// let len = iterator.clone().collect::<Vec<_>>().len();
+ /// // should be
+ /// let len = iterator.count();
+ /// ```
+ pub NEEDLESS_COLLECT,
+ perf,
+ "collecting an iterator when collect is not needed"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks `for` loops over slices with an explicit counter
+ /// and suggests the use of `.enumerate()`.
+ ///
+ /// **Why is it bad?** Using `.enumerate()` makes the intent more clear,
+ /// declutters the code and may be faster in some instances.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # let v = vec![1];
+ /// # fn bar(bar: usize, baz: usize) {}
+ /// let mut i = 0;
+ /// for item in &v {
+ /// bar(i, *item);
+ /// i += 1;
+ /// }
+ /// ```
+ /// Could be written as
+ /// ```rust
+ /// # let v = vec![1];
+ /// # fn bar(bar: usize, baz: usize) {}
+ /// for (i, item) in v.iter().enumerate() { bar(i, *item); }
+ /// ```
+ pub EXPLICIT_COUNTER_LOOP,
+ complexity,
+ "for-looping with an explicit counter when `_.enumerate()` would do"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for empty `loop` expressions.
+ ///
+ /// **Why is this bad?** Those busy loops burn CPU cycles without doing
+ /// anything. Think of the environment and either block on something or at least
+ /// make the thread sleep for some microseconds.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```no_run
+ /// loop {}
+ /// ```
+ pub EMPTY_LOOP,
+ style,
+ "empty `loop {}`, which should block or sleep"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```ignore
+ /// while let Some(val) = iter() {
+ /// ..
+ /// }
+ /// ```
+ pub WHILE_LET_ON_ITERATOR,
+ style,
+ "using a while-let loop instead of a for loop on an iterator"
+}
+
+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 don't need the values or keys.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```ignore
+ /// for (k, _) in &map {
+ /// ..
+ /// }
+ /// ```
+ ///
+ /// could be replaced by
+ ///
+ /// ```ignore
+ /// for k in map.keys() {
+ /// ..
+ /// }
+ /// ```
+ pub FOR_KV_MAP,
+ style,
+ "looping on a map using `iter` when `keys` or `values` would do"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None
+ ///
+ /// **Example:**
+ /// ```rust
+ /// loop {
+ /// ..;
+ /// break;
+ /// }
+ /// ```
+ pub NEVER_LOOP,
+ correctness,
+ "any loop that will always `break` or `return`"
+}
+
+declare_clippy_lint! {
+ /// **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:** None
+ ///
+ /// **Example:**
+ /// ```rust
+ /// let mut foo = 42;
+ /// for i in 0..foo {
+ /// foo -= 1;
+ /// println!("{}", i); // prints numbers from 0 to 42, not 0 to 21
+ /// }
+ /// ```
+ pub MUT_RANGE_BOUND,
+ complexity,
+ "for loop over a range where one of the bounds is a mutable variable"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ /// ```rust
+ /// let i = 0;
+ /// while i > 10 {
+ /// println!("let me loop forever!");
+ /// }
+ /// ```
+ pub WHILE_IMMUTABLE_CONDITION,
+ correctness,
+ "variables used within while expression are not mutated in the body"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ /// **Known problems:** None
+ ///
+ /// **Example:**
+ /// ```rust
+ /// let item1 = 2;
+ /// let item2 = 3;
+ /// let mut vec: Vec<u8> = Vec::new();
+ /// for _ in 0..20 {
+ /// vec.push(item1);
+ /// }
+ /// for _ in 0..30 {
+ /// vec.push(item2);
+ /// }
+ /// ```
+ /// could be written as
+ /// ```rust
+ /// let item1 = 2;
+ /// let item2 = 3;
+ /// let mut vec: Vec<u8> = vec![item1; 20];
+ /// vec.resize(20 + 30, item2);
+ /// ```
+ pub SAME_ITEM_PUSH,
+ style,
+ "the same item is pushed inside of a for loop"
+}
+
+declare_lint_pass!(Loops => [
+ MANUAL_MEMCPY,
+ NEEDLESS_RANGE_LOOP,
+ EXPLICIT_ITER_LOOP,
+ EXPLICIT_INTO_ITER_LOOP,
+ ITER_NEXT_LOOP,
+ FOR_LOOPS_OVER_FALLIBLES,
+ WHILE_LET_LOOP,
+ NEEDLESS_COLLECT,
+ EXPLICIT_COUNTER_LOOP,
+ EMPTY_LOOP,
+ WHILE_LET_ON_ITERATOR,
+ FOR_KV_MAP,
+ NEVER_LOOP,
+ MUT_RANGE_BOUND,
+ WHILE_IMMUTABLE_CONDITION,
+ SAME_ITEM_PUSH,
+]);
+
+impl<'tcx> LateLintPass<'tcx> for Loops {
+ #[allow(clippy::too_many_lines)]
+ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
+ if let Some((pat, arg, body)) = higher::for_loop(expr) {
+ // we don't want to check expanded macros
+ // this check is not at the top of the function
+ // since higher::for_loop expressions are marked as expansions
+ if body.span.from_expansion() {
+ return;
+ }
+ check_for_loop(cx, pat, arg, body, expr);
+ }
+
+ // we don't want to check expanded macros
+ if expr.span.from_expansion() {
+ return;
+ }
+
+ // check for never_loop
+ if let ExprKind::Loop(ref block, _, _) = expr.kind {
+ match never_loop_block(block, expr.hir_id) {
+ NeverLoopResult::AlwaysBreak => span_lint(cx, NEVER_LOOP, expr.span, "this loop never actually loops"),
+ NeverLoopResult::MayContinueMainLoop | NeverLoopResult::Otherwise => (),
+ }
+ }
+
+ // check for `loop { if let {} else break }` that could be `while let`
+ // (also matches an explicit "match" instead of "if let")
+ // (even if the "match" or "if let" is used for declaration)
+ if let ExprKind::Loop(ref block, _, LoopSource::Loop) = expr.kind {
+ // also check for empty `loop {}` statements
+ if block.stmts.is_empty() && block.expr.is_none() && !is_no_std_crate(cx.tcx.hir().krate()) {
+ span_lint(
+ cx,
+ EMPTY_LOOP,
+ expr.span,
+ "empty `loop {}` detected. You may want to either use `panic!()` or add \
+ `std::thread::sleep(..);` to the loop body.",
+ );
+ }
+
+ // extract the expression from the first statement (if any) in a block
+ let inner_stmt_expr = extract_expr_from_first_stmt(block);
+ // or extract the first expression (if any) from the block
+ if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(block)) {
+ if let ExprKind::Match(ref matchexpr, ref arms, ref source) = inner.kind {
+ // ensure "if let" compatible match structure
+ match *source {
+ MatchSource::Normal | MatchSource::IfLetDesugar { .. } => {
+ if arms.len() == 2
+ && arms[0].guard.is_none()
+ && arms[1].guard.is_none()
+ && is_simple_break_expr(&arms[1].body)
+ {
+ if in_external_macro(cx.sess(), expr.span) {
+ return;
+ }
+
+ // NOTE: we used to build a body here instead of using
+ // ellipsis, this was removed because:
+ // 1) it was ugly with big bodies;
+ // 2) it was not indented properly;
+ // 3) it wasn’t very smart (see #675).
+ let mut applicability = Applicability::HasPlaceholders;
+ span_lint_and_sugg(
+ cx,
+ WHILE_LET_LOOP,
+ expr.span,
+ "this loop could be written as a `while let` loop",
+ "try",
+ format!(
+ "while let {} = {} {{ .. }}",
+ snippet_with_applicability(cx, arms[0].pat.span, "..", &mut applicability),
+ snippet_with_applicability(cx, matchexpr.span, "..", &mut applicability),
+ ),
+ applicability,
+ );
+ }
+ },
+ _ => (),
+ }
+ }
+ }
+ }
+ if let ExprKind::Match(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.kind {
+ let pat = &arms[0].pat.kind;
+ if let (
+ &PatKind::TupleStruct(ref qpath, ref pat_args, _),
+ &ExprKind::MethodCall(ref method_path, _, ref method_args, _),
+ ) = (pat, &match_expr.kind)
+ {
+ let iter_expr = &method_args[0];
+
+ // Don't lint when the iterator is recreated on every iteration
+ if_chain! {
+ if let ExprKind::MethodCall(..) | ExprKind::Call(..) = iter_expr.kind;
+ if let Some(iter_def_id) = get_trait_def_id(cx, &paths::ITERATOR);
+ if implements_trait(cx, cx.typeck_results().expr_ty(iter_expr), iter_def_id, &[]);
+ then {
+ return;
+ }
+ }
+
+ let lhs_constructor = last_path_segment(qpath);
+ if method_path.ident.name == sym!(next)
+ && match_trait_method(cx, match_expr, &paths::ITERATOR)
+ && lhs_constructor.ident.name == sym!(Some)
+ && (pat_args.is_empty()
+ || !is_refutable(cx, &pat_args[0])
+ && !is_used_inside(cx, iter_expr, &arms[0].body)
+ && !is_iterator_used_after_while_let(cx, iter_expr)
+ && !is_nested(cx, expr, &method_args[0]))
+ {
+ let mut applicability = Applicability::MachineApplicable;
+ let iterator = snippet_with_applicability(cx, method_args[0].span, "_", &mut applicability);
+ let loop_var = if pat_args.is_empty() {
+ "_".to_string()
+ } else {
+ snippet_with_applicability(cx, pat_args[0].span, "_", &mut applicability).into_owned()
+ };
+ span_lint_and_sugg(
+ cx,
+ WHILE_LET_ON_ITERATOR,
+ expr.span.with_hi(match_expr.span.hi()),
+ "this loop could be written as a `for` loop",
+ "try",
+ format!("for {} in {}", loop_var, iterator),
+ applicability,
+ );
+ }
+ }
+ }
+
+ if let Some((cond, body)) = higher::while_loop(&expr) {
+ check_infinite_loop(cx, cond, body);
+ }
+
+ check_needless_collect(expr, cx);
+ }
+}
+
+enum NeverLoopResult {
+ // A break/return always get triggered but not necessarily for the main loop.
+ AlwaysBreak,
+ // A continue may occur for the main loop.
+ MayContinueMainLoop,
+ Otherwise,
+}
+
+#[must_use]
+fn absorb_break(arg: &NeverLoopResult) -> NeverLoopResult {
+ match *arg {
+ NeverLoopResult::AlwaysBreak | NeverLoopResult::Otherwise => NeverLoopResult::Otherwise,
+ NeverLoopResult::MayContinueMainLoop => NeverLoopResult::MayContinueMainLoop,
+ }
+}
+
+// Combine two results for parts that are called in order.
+#[must_use]
+fn combine_seq(first: NeverLoopResult, second: NeverLoopResult) -> NeverLoopResult {
+ match first {
+ NeverLoopResult::AlwaysBreak | NeverLoopResult::MayContinueMainLoop => first,
+ NeverLoopResult::Otherwise => second,
+ }
+}
+
+// Combine two results where both parts are called but not necessarily in order.
+#[must_use]
+fn combine_both(left: NeverLoopResult, right: NeverLoopResult) -> NeverLoopResult {
+ match (left, right) {
+ (NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) => {
+ NeverLoopResult::MayContinueMainLoop
+ },
+ (NeverLoopResult::AlwaysBreak, _) | (_, NeverLoopResult::AlwaysBreak) => NeverLoopResult::AlwaysBreak,
+ (NeverLoopResult::Otherwise, NeverLoopResult::Otherwise) => NeverLoopResult::Otherwise,
+ }
+}
+
+// Combine two results where only one of the part may have been executed.
+#[must_use]
+fn combine_branches(b1: NeverLoopResult, b2: NeverLoopResult) -> NeverLoopResult {
+ match (b1, b2) {
+ (NeverLoopResult::AlwaysBreak, NeverLoopResult::AlwaysBreak) => NeverLoopResult::AlwaysBreak,
+ (NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) => {
+ NeverLoopResult::MayContinueMainLoop
+ },
+ (NeverLoopResult::Otherwise, _) | (_, NeverLoopResult::Otherwise) => NeverLoopResult::Otherwise,
+ }
+}
+
+fn never_loop_block(block: &Block<'_>, main_loop_id: HirId) -> NeverLoopResult {
+ let stmts = block.stmts.iter().map(stmt_to_expr);
+ let expr = once(block.expr.as_deref());
+ let mut iter = stmts.chain(expr).filter_map(|e| e);
+ never_loop_expr_seq(&mut iter, main_loop_id)
+}
+
+fn stmt_to_expr<'tcx>(stmt: &Stmt<'tcx>) -> Option<&'tcx Expr<'tcx>> {
+ match stmt.kind {
+ StmtKind::Semi(ref e, ..) | StmtKind::Expr(ref e, ..) => Some(e),
+ StmtKind::Local(ref local) => local.init.as_deref(),
+ _ => None,
+ }
+}
+
+fn never_loop_expr(expr: &Expr<'_>, main_loop_id: HirId) -> NeverLoopResult {
+ match expr.kind {
+ ExprKind::Box(ref e)
+ | ExprKind::Unary(_, ref e)
+ | ExprKind::Cast(ref e, _)
+ | ExprKind::Type(ref e, _)
+ | ExprKind::Field(ref e, _)
+ | ExprKind::AddrOf(_, _, ref e)
+ | ExprKind::Struct(_, _, Some(ref e))
+ | ExprKind::Repeat(ref e, _)
+ | ExprKind::DropTemps(ref e) => never_loop_expr(e, main_loop_id),
+ ExprKind::Array(ref es) | ExprKind::MethodCall(_, _, ref es, _) | ExprKind::Tup(ref es) => {
+ never_loop_expr_all(&mut es.iter(), main_loop_id)
+ },
+ ExprKind::Call(ref e, ref es) => never_loop_expr_all(&mut once(&**e).chain(es.iter()), main_loop_id),
+ ExprKind::Binary(_, ref e1, ref e2)
+ | ExprKind::Assign(ref e1, ref e2, _)
+ | ExprKind::AssignOp(_, ref e1, ref e2)
+ | ExprKind::Index(ref e1, ref e2) => never_loop_expr_all(&mut [&**e1, &**e2].iter().cloned(), main_loop_id),
+ ExprKind::Loop(ref b, _, _) => {
+ // Break can come from the inner loop so remove them.
+ absorb_break(&never_loop_block(b, main_loop_id))
+ },
+ ExprKind::Match(ref e, ref arms, _) => {
+ let e = never_loop_expr(e, main_loop_id);
+ if arms.is_empty() {
+ e
+ } else {
+ let arms = never_loop_expr_branch(&mut arms.iter().map(|a| &*a.body), main_loop_id);
+ combine_seq(e, arms)
+ }
+ },
+ ExprKind::Block(ref b, _) => never_loop_block(b, main_loop_id),
+ ExprKind::Continue(d) => {
+ let id = d
+ .target_id
+ .expect("target ID can only be missing in the presence of compilation errors");
+ if id == main_loop_id {
+ NeverLoopResult::MayContinueMainLoop
+ } else {
+ NeverLoopResult::AlwaysBreak
+ }
+ },
+ ExprKind::Break(_, ref e) | ExprKind::Ret(ref e) => e.as_ref().map_or(NeverLoopResult::AlwaysBreak, |e| {
+ combine_seq(never_loop_expr(e, main_loop_id), NeverLoopResult::AlwaysBreak)
+ }),
+ ExprKind::InlineAsm(ref asm) => asm
+ .operands
+ .iter()
+ .map(|o| match o {
+ InlineAsmOperand::In { expr, .. }
+ | InlineAsmOperand::InOut { expr, .. }
+ | InlineAsmOperand::Const { expr }
+ | InlineAsmOperand::Sym { expr } => never_loop_expr(expr, main_loop_id),
+ InlineAsmOperand::Out { expr, .. } => never_loop_expr_all(&mut expr.iter(), main_loop_id),
+ InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
+ never_loop_expr_all(&mut once(in_expr).chain(out_expr.iter()), main_loop_id)
+ },
+ })
+ .fold(NeverLoopResult::Otherwise, combine_both),
+ ExprKind::Struct(_, _, None)
+ | ExprKind::Yield(_, _)
+ | ExprKind::Closure(_, _, _, _, _)
+ | ExprKind::LlvmInlineAsm(_)
+ | ExprKind::Path(_)
+ | ExprKind::Lit(_)
+ | ExprKind::Err => NeverLoopResult::Otherwise,
+ }
+}
+
+fn never_loop_expr_seq<'a, T: Iterator<Item = &'a Expr<'a>>>(es: &mut T, main_loop_id: HirId) -> NeverLoopResult {
+ es.map(|e| never_loop_expr(e, main_loop_id))
+ .fold(NeverLoopResult::Otherwise, combine_seq)
+}
+
+fn never_loop_expr_all<'a, T: Iterator<Item = &'a Expr<'a>>>(es: &mut T, main_loop_id: HirId) -> NeverLoopResult {
+ es.map(|e| never_loop_expr(e, main_loop_id))
+ .fold(NeverLoopResult::Otherwise, combine_both)
+}
+
+fn never_loop_expr_branch<'a, T: Iterator<Item = &'a Expr<'a>>>(e: &mut T, main_loop_id: HirId) -> NeverLoopResult {
+ e.map(|e| never_loop_expr(e, main_loop_id))
+ .fold(NeverLoopResult::AlwaysBreak, combine_branches)
+}
+
+fn check_for_loop<'tcx>(
+ cx: &LateContext<'tcx>,
+ pat: &'tcx Pat<'_>,
+ arg: &'tcx Expr<'_>,
+ body: &'tcx Expr<'_>,
+ expr: &'tcx Expr<'_>,
+) {
+ check_for_loop_range(cx, pat, arg, body, expr);
+ check_for_loop_arg(cx, pat, arg, expr);
+ check_for_loop_explicit_counter(cx, pat, arg, body, expr);
+ check_for_loop_over_map_kv(cx, pat, arg, body, expr);
+ check_for_mut_range_bound(cx, arg, body);
+ detect_manual_memcpy(cx, pat, arg, body, expr);
+ detect_same_item_push(cx, pat, arg, body, expr);
+}
+
+fn same_var<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, var: HirId) -> bool {
+ if_chain! {
+ if let ExprKind::Path(qpath) = &expr.kind;
+ if let QPath::Resolved(None, path) = qpath;
+ if path.segments.len() == 1;
+ if let Res::Local(local_id) = qpath_res(cx, qpath, expr.hir_id);
+ then {
+ // our variable!
+ local_id == var
+ } else {
+ false
+ }
+ }
+}
+
+#[derive(Clone, Copy)]
+enum OffsetSign {
+ Positive,
+ Negative,
+}
+
+struct Offset {
+ value: String,
+ sign: OffsetSign,
+}
+
+impl Offset {
+ fn negative(value: String) -> Self {
+ Self {
+ value,
+ sign: OffsetSign::Negative,
+ }
+ }
+
+ fn positive(value: String) -> Self {
+ Self {
+ value,
+ sign: OffsetSign::Positive,
+ }
+ }
+}
+
+struct FixedOffsetVar<'hir> {
+ var: &'hir Expr<'hir>,
+ offset: Offset,
+}
+
+fn is_slice_like<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'_>) -> bool {
+ let is_slice = match ty.kind() {
+ ty::Ref(_, subty, _) => is_slice_like(cx, subty),
+ ty::Slice(..) | ty::Array(..) => true,
+ _ => false,
+ };
+
+ is_slice || is_type_diagnostic_item(cx, ty, sym!(vec_type)) || is_type_diagnostic_item(cx, ty, sym!(vecdeque_type))
+}
+
+fn fetch_cloned_expr<'tcx>(expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
+ if_chain! {
+ if let ExprKind::MethodCall(method, _, args, _) = expr.kind;
+ if method.ident.name == sym!(clone);
+ if args.len() == 1;
+ if let Some(arg) = args.get(0);
+ then { arg } else { expr }
+ }
+}
+
+fn get_offset<'tcx>(cx: &LateContext<'tcx>, idx: &Expr<'_>, var: HirId) -> Option<Offset> {
+ fn extract_offset<'tcx>(cx: &LateContext<'tcx>, e: &Expr<'_>, var: HirId) -> Option<String> {
+ match &e.kind {
+ ExprKind::Lit(l) => match l.node {
+ ast::LitKind::Int(x, _ty) => Some(x.to_string()),
+ _ => None,
+ },
+ ExprKind::Path(..) if !same_var(cx, e, var) => Some(snippet_opt(cx, e.span).unwrap_or_else(|| "??".into())),
+ _ => None,
+ }
+ }
+
+ match idx.kind {
+ ExprKind::Binary(op, lhs, rhs) => match op.node {
+ BinOpKind::Add => {
+ let offset_opt = if same_var(cx, lhs, var) {
+ extract_offset(cx, rhs, var)
+ } else if same_var(cx, rhs, var) {
+ extract_offset(cx, lhs, var)
+ } else {
+ None
+ };
+
+ offset_opt.map(Offset::positive)
+ },
+ BinOpKind::Sub if same_var(cx, lhs, var) => extract_offset(cx, rhs, var).map(Offset::negative),
+ _ => None,
+ },
+ ExprKind::Path(..) if same_var(cx, idx, var) => Some(Offset::positive("0".into())),
+ _ => None,
+ }
+}
+
+fn get_assignments<'tcx>(body: &'tcx Expr<'tcx>) -> impl Iterator<Item = Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)>> {
+ fn get_assignment<'tcx>(e: &'tcx Expr<'tcx>) -> Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)> {
+ if let ExprKind::Assign(lhs, rhs, _) = e.kind {
+ Some((lhs, rhs))
+ } else {
+ None
+ }
+ }
+
+ // This is one of few ways to return different iterators
+ // derived from: https://stackoverflow.com/questions/29760668/conditionally-iterate-over-one-of-several-possible-iterators/52064434#52064434
+ let mut iter_a = None;
+ let mut iter_b = None;
+
+ if let ExprKind::Block(b, _) = body.kind {
+ let Block { stmts, expr, .. } = *b;
+
+ iter_a = stmts
+ .iter()
+ .filter_map(|stmt| match stmt.kind {
+ StmtKind::Local(..) | StmtKind::Item(..) => None,
+ StmtKind::Expr(e) | StmtKind::Semi(e) => Some(e),
+ })
+ .chain(expr.into_iter())
+ .map(get_assignment)
+ .into()
+ } else {
+ iter_b = Some(get_assignment(body))
+ }
+
+ iter_a.into_iter().flatten().chain(iter_b.into_iter())
+}
+
+fn build_manual_memcpy_suggestion<'tcx>(
+ cx: &LateContext<'tcx>,
+ start: &Expr<'_>,
+ end: &Expr<'_>,
+ limits: ast::RangeLimits,
+ dst_var: FixedOffsetVar<'_>,
+ src_var: FixedOffsetVar<'_>,
+) -> String {
+ fn print_sum(arg1: &str, arg2: &Offset) -> String {
+ match (arg1, &arg2.value[..], arg2.sign) {
+ ("0", "0", _) => "0".into(),
+ ("0", x, OffsetSign::Positive) | (x, "0", _) => x.into(),
+ ("0", x, OffsetSign::Negative) => format!("-{}", x),
+ (x, y, OffsetSign::Positive) => format!("({} + {})", x, y),
+ (x, y, OffsetSign::Negative) => {
+ if x == y {
+ "0".into()
+ } else {
+ format!("({} - {})", x, y)
+ }
+ },
+ }
+ }
+
+ fn print_offset(start_str: &str, inline_offset: &Offset) -> String {
+ let offset = print_sum(start_str, inline_offset);
+ if offset.as_str() == "0" {
+ "".into()
+ } else {
+ offset
+ }
+ }
+
+ let print_limit = |end: &Expr<'_>, offset: Offset, var: &Expr<'_>| {
+ if_chain! {
+ if let ExprKind::MethodCall(method, _, len_args, _) = end.kind;
+ if method.ident.name == sym!(len);
+ if len_args.len() == 1;
+ if let Some(arg) = len_args.get(0);
+ if var_def_id(cx, arg) == var_def_id(cx, var);
+ then {
+ match offset.sign {
+ OffsetSign::Negative => format!("({} - {})", snippet(cx, end.span, "<src>.len()"), offset.value),
+ OffsetSign::Positive => "".into(),
+ }
+ } else {
+ let end_str = match limits {
+ ast::RangeLimits::Closed => {
+ let end = sugg::Sugg::hir(cx, end, "<count>");
+ format!("{}", end + sugg::ONE)
+ },
+ ast::RangeLimits::HalfOpen => format!("{}", snippet(cx, end.span, "..")),
+ };
+
+ print_sum(&end_str, &offset)
+ }
+ }
+ };
+
+ let start_str = snippet(cx, start.span, "").to_string();
+ let dst_offset = print_offset(&start_str, &dst_var.offset);
+ let dst_limit = print_limit(end, dst_var.offset, dst_var.var);
+ let src_offset = print_offset(&start_str, &src_var.offset);
+ let src_limit = print_limit(end, src_var.offset, src_var.var);
+
+ let dst_var_name = snippet_opt(cx, dst_var.var.span).unwrap_or_else(|| "???".into());
+ let src_var_name = snippet_opt(cx, src_var.var.span).unwrap_or_else(|| "???".into());
+
+ let dst = if dst_offset == "" && dst_limit == "" {
+ dst_var_name
+ } else {
+ format!("{}[{}..{}]", dst_var_name, dst_offset, dst_limit)
+ };
+
+ format!(
+ "{}.clone_from_slice(&{}[{}..{}])",
+ dst, src_var_name, src_offset, src_limit
+ )
+}
+/// Checks for for loops that sequentially copy items from one slice-like
+/// object to another.
+fn detect_manual_memcpy<'tcx>(
+ cx: &LateContext<'tcx>,
+ pat: &'tcx Pat<'_>,
+ arg: &'tcx Expr<'_>,
+ body: &'tcx Expr<'_>,
+ expr: &'tcx Expr<'_>,
+) {
+ if let Some(higher::Range {
+ start: Some(start),
+ end: Some(end),
+ limits,
+ }) = higher::range(arg)
+ {
+ // the var must be a single name
+ if let PatKind::Binding(_, canonical_id, _, _) = pat.kind {
+ // The only statements in the for loops can be indexed assignments from
+ // indexed retrievals.
+ let big_sugg = get_assignments(body)
+ .map(|o| {
+ o.and_then(|(lhs, rhs)| {
+ let rhs = fetch_cloned_expr(rhs);
+ if_chain! {
+ if let ExprKind::Index(seqexpr_left, idx_left) = lhs.kind;
+ if let ExprKind::Index(seqexpr_right, idx_right) = rhs.kind;
+ if is_slice_like(cx, cx.typeck_results().expr_ty(seqexpr_left))
+ && is_slice_like(cx, cx.typeck_results().expr_ty(seqexpr_right));
+ if let Some(offset_left) = get_offset(cx, &idx_left, canonical_id);
+ if let Some(offset_right) = get_offset(cx, &idx_right, canonical_id);
+
+ // Source and destination must be different
+ if var_def_id(cx, seqexpr_left) != var_def_id(cx, seqexpr_right);
+ then {
+ Some((FixedOffsetVar { var: seqexpr_left, offset: offset_left },
+ FixedOffsetVar { var: seqexpr_right, offset: offset_right }))
+ } else {
+ None
+ }
+ }
+ })
+ })
+ .map(|o| o.map(|(dst, src)| build_manual_memcpy_suggestion(cx, start, end, limits, dst, src)))
+ .collect::<Option<Vec<_>>>()
+ .filter(|v| !v.is_empty())
+ .map(|v| v.join("\n "));
+
+ if let Some(big_sugg) = big_sugg {
+ span_lint_and_sugg(
+ cx,
+ MANUAL_MEMCPY,
+ expr.span,
+ "it looks like you're manually copying between slices",
+ "try replacing the loop by",
+ big_sugg,
+ Applicability::Unspecified,
+ );
+ }
+ }
+ }
+}
+
+// Scans the body of the for loop and determines whether lint should be given
+struct SameItemPushVisitor<'a, 'tcx> {
+ should_lint: bool,
+ // this field holds the last vec push operation visited, which should be the only push seen
+ vec_push: Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)>,
+ cx: &'a LateContext<'tcx>,
+}
+
+impl<'a, 'tcx> Visitor<'tcx> for SameItemPushVisitor<'a, 'tcx> {
+ type Map = Map<'tcx>;
+
+ fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
+ match &expr.kind {
+ // Non-determinism may occur ... don't give a lint
+ ExprKind::Loop(_, _, _) | ExprKind::Match(_, _, _) => self.should_lint = false,
+ ExprKind::Block(block, _) => self.visit_block(block),
+ _ => {},
+ }
+ }
+
+ fn visit_block(&mut self, b: &'tcx Block<'_>) {
+ for stmt in b.stmts.iter() {
+ self.visit_stmt(stmt);
+ }
+ }
+
+ fn visit_stmt(&mut self, s: &'tcx Stmt<'_>) {
+ let vec_push_option = get_vec_push(self.cx, s);
+ if vec_push_option.is_none() {
+ // Current statement is not a push so visit inside
+ match &s.kind {
+ StmtKind::Expr(expr) | StmtKind::Semi(expr) => self.visit_expr(&expr),
+ _ => {},
+ }
+ } else {
+ // Current statement is a push ...check whether another
+ // push had been previously done
+ if self.vec_push.is_none() {
+ self.vec_push = vec_push_option;
+ } else {
+ // There are multiple pushes ... don't lint
+ self.should_lint = false;
+ }
+ }
+ }
+
+ fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+ NestedVisitorMap::None
+ }
+}
+
+// Given some statement, determine if that statement is a push on a Vec. If it is, return
+// the Vec being pushed into and the item being pushed
+fn get_vec_push<'tcx>(cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) -> Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)> {
+ if_chain! {
+ // Extract method being called
+ if let StmtKind::Semi(semi_stmt) = &stmt.kind;
+ if let ExprKind::MethodCall(path, _, args, _) = &semi_stmt.kind;
+ // Figure out the parameters for the method call
+ if let Some(self_expr) = args.get(0);
+ if let Some(pushed_item) = args.get(1);
+ // Check that the method being called is push() on a Vec
+ if match_type(cx, cx.typeck_results().expr_ty(self_expr), &paths::VEC);
+ if path.ident.name.as_str() == "push";
+ then {
+ return Some((self_expr, pushed_item))
+ }
+ }
+ None
+}
+
+/// Detects for loop pushing the same item into a Vec
+fn detect_same_item_push<'tcx>(
+ cx: &LateContext<'tcx>,
+ pat: &'tcx Pat<'_>,
+ _: &'tcx Expr<'_>,
+ body: &'tcx Expr<'_>,
+ _: &'tcx Expr<'_>,
+) {
++ fn emit_lint(cx: &LateContext<'_>, vec: &Expr<'_>, pushed_item: &Expr<'_>) {
++ let vec_str = snippet_with_macro_callsite(cx, vec.span, "");
++ let item_str = snippet_with_macro_callsite(cx, pushed_item.span, "");
++
++ span_lint_and_help(
++ cx,
++ SAME_ITEM_PUSH,
++ vec.span,
++ "it looks like the same item is being pushed into this Vec",
++ None,
++ &format!(
++ "try using vec![{};SIZE] or {}.resize(NEW_SIZE, {})",
++ item_str, vec_str, item_str
++ ),
++ )
++ }
++
++ if !matches!(pat.kind, PatKind::Wild) {
++ return;
++ }
++
+ // Determine whether it is safe to lint the body
+ let mut same_item_push_visitor = SameItemPushVisitor {
+ should_lint: true,
+ vec_push: None,
+ cx,
+ };
+ walk_expr(&mut same_item_push_visitor, body);
+ if same_item_push_visitor.should_lint {
+ if let Some((vec, pushed_item)) = same_item_push_visitor.vec_push {
- }
- } else if mutated_variables(pushed_item, cx).map_or(false, |mutvars| mutvars.is_empty()) {
- span_lint_and_help(
- cx,
- SAME_ITEM_PUSH,
- vec.span,
- "it looks like the same item is being pushed into this Vec",
- None,
- &format!(
- "try using vec![{};SIZE] or {}.resize(NEW_SIZE, {})",
- item_str, vec_str, item_str
- ),
- )
++ let vec_ty = cx.typeck_results().expr_ty(vec);
++ let ty = vec_ty.walk().nth(1).unwrap().expect_ty();
++ if cx
++ .tcx
++ .lang_items()
++ .clone_trait()
++ .map_or(false, |id| implements_trait(cx, ty, id, &[]))
++ {
++ // Make sure that the push does not involve possibly mutating values
++ match pushed_item.kind {
++ ExprKind::Path(ref qpath) => {
++ match qpath_res(cx, qpath, pushed_item.hir_id) {
++ // immutable bindings that are initialized with literal or constant
++ Res::Local(hir_id) => {
++ if_chain! {
++ let node = cx.tcx.hir().get(hir_id);
++ if let Node::Binding(pat) = node;
++ if let PatKind::Binding(bind_ann, ..) = pat.kind;
++ if !matches!(bind_ann, BindingAnnotation::RefMut | BindingAnnotation::Mutable);
++ let parent_node = cx.tcx.hir().get_parent_node(hir_id);
++ if let Some(Node::Local(parent_let_expr)) = cx.tcx.hir().find(parent_node);
++ if let Some(init) = parent_let_expr.init;
++ then {
++ match init.kind {
++ // immutable bindings that are initialized with literal
++ ExprKind::Lit(..) => emit_lint(cx, vec, pushed_item),
++ // immutable bindings that are initialized with constant
++ ExprKind::Path(ref path) => {
++ if let Res::Def(DefKind::Const, ..) = qpath_res(cx, path, init.hir_id) {
++ emit_lint(cx, vec, pushed_item);
++ }
++ }
++ _ => {},
++ }
++ }
++ }
++ },
++ // constant
++ Res::Def(DefKind::Const, ..) => emit_lint(cx, vec, pushed_item),
++ _ => {},
+ }
++ },
++ ExprKind::Lit(..) => emit_lint(cx, vec, pushed_item),
++ _ => {},
+ }
+ }
+ }
+ }
+}
+
+/// Checks for looping over a range and then indexing a sequence with it.
+/// The iteratee must be a range literal.
+#[allow(clippy::too_many_lines)]
+fn check_for_loop_range<'tcx>(
+ cx: &LateContext<'tcx>,
+ pat: &'tcx Pat<'_>,
+ arg: &'tcx Expr<'_>,
+ body: &'tcx Expr<'_>,
+ expr: &'tcx Expr<'_>,
+) {
+ if let Some(higher::Range {
+ start: Some(start),
+ ref end,
+ limits,
+ }) = higher::range(arg)
+ {
+ // the var must be a single name
+ if let PatKind::Binding(_, canonical_id, ident, _) = pat.kind {
+ let mut visitor = VarVisitor {
+ cx,
+ var: canonical_id,
+ indexed_mut: FxHashSet::default(),
+ indexed_indirectly: FxHashMap::default(),
+ indexed_directly: FxHashMap::default(),
+ referenced: FxHashSet::default(),
+ nonindex: false,
+ prefer_mutable: false,
+ };
+ walk_expr(&mut visitor, body);
+
+ // linting condition: we only indexed one variable, and indexed it directly
+ if visitor.indexed_indirectly.is_empty() && visitor.indexed_directly.len() == 1 {
+ let (indexed, (indexed_extent, indexed_ty)) = visitor
+ .indexed_directly
+ .into_iter()
+ .next()
+ .expect("already checked that we have exactly 1 element");
+
+ // ensure that the indexed variable was declared before the loop, see #601
+ if let Some(indexed_extent) = indexed_extent {
+ let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id);
+ let parent_def_id = cx.tcx.hir().local_def_id(parent_id);
+ let region_scope_tree = cx.tcx.region_scope_tree(parent_def_id);
+ let pat_extent = region_scope_tree.var_scope(pat.hir_id.local_id);
+ if region_scope_tree.is_subscope_of(indexed_extent, pat_extent) {
+ return;
+ }
+ }
+
+ // don't lint if the container that is indexed does not have .iter() method
+ let has_iter = has_iter_method(cx, indexed_ty);
+ if has_iter.is_none() {
+ return;
+ }
+
+ // don't lint if the container that is indexed into is also used without
+ // indexing
+ if visitor.referenced.contains(&indexed) {
+ return;
+ }
+
+ let starts_at_zero = is_integer_const(cx, start, 0);
+
+ let skip = if starts_at_zero {
+ String::new()
+ } else {
+ format!(".skip({})", snippet(cx, start.span, ".."))
+ };
+
+ let mut end_is_start_plus_val = false;
+
+ let take = if let Some(end) = *end {
+ let mut take_expr = end;
+
+ if let ExprKind::Binary(ref op, ref left, ref right) = end.kind {
+ if let BinOpKind::Add = op.node {
+ let start_equal_left = SpanlessEq::new(cx).eq_expr(start, left);
+ let start_equal_right = SpanlessEq::new(cx).eq_expr(start, right);
+
+ if start_equal_left {
+ take_expr = right;
+ } else if start_equal_right {
+ take_expr = left;
+ }
+
+ end_is_start_plus_val = start_equal_left | start_equal_right;
+ }
+ }
+
+ if is_len_call(end, indexed) || is_end_eq_array_len(cx, end, limits, indexed_ty) {
+ String::new()
+ } else {
+ match limits {
+ ast::RangeLimits::Closed => {
+ let take_expr = sugg::Sugg::hir(cx, take_expr, "<count>");
+ format!(".take({})", take_expr + sugg::ONE)
+ },
+ ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, take_expr.span, "..")),
+ }
+ }
+ } else {
+ String::new()
+ };
+
+ let (ref_mut, method) = if visitor.indexed_mut.contains(&indexed) {
+ ("mut ", "iter_mut")
+ } else {
+ ("", "iter")
+ };
+
+ let take_is_empty = take.is_empty();
+ let mut method_1 = take;
+ let mut method_2 = skip;
+
+ if end_is_start_plus_val {
+ mem::swap(&mut method_1, &mut method_2);
+ }
+
+ if visitor.nonindex {
+ span_lint_and_then(
+ cx,
+ NEEDLESS_RANGE_LOOP,
+ expr.span,
+ &format!("the loop variable `{}` is used to index `{}`", ident.name, indexed),
+ |diag| {
+ multispan_sugg(
+ diag,
+ "consider using an iterator",
+ vec![
+ (pat.span, format!("({}, <item>)", ident.name)),
+ (
+ arg.span,
+ format!("{}.{}().enumerate(){}{}", indexed, method, method_1, method_2),
+ ),
+ ],
+ );
+ },
+ );
+ } else {
+ let repl = if starts_at_zero && take_is_empty {
+ format!("&{}{}", ref_mut, indexed)
+ } else {
+ format!("{}.{}(){}{}", indexed, method, method_1, method_2)
+ };
+
+ span_lint_and_then(
+ cx,
+ NEEDLESS_RANGE_LOOP,
+ expr.span,
+ &format!(
+ "the loop variable `{}` is only used to index `{}`.",
+ ident.name, indexed
+ ),
+ |diag| {
+ multispan_sugg(
+ diag,
+ "consider using an iterator",
+ vec![(pat.span, "<item>".to_string()), (arg.span, repl)],
+ );
+ },
+ );
+ }
+ }
+ }
+ }
+}
+
+fn is_len_call(expr: &Expr<'_>, var: Symbol) -> bool {
+ if_chain! {
+ if let ExprKind::MethodCall(ref method, _, ref len_args, _) = expr.kind;
+ if len_args.len() == 1;
+ if method.ident.name == sym!(len);
+ if let ExprKind::Path(QPath::Resolved(_, ref path)) = len_args[0].kind;
+ if path.segments.len() == 1;
+ if path.segments[0].ident.name == var;
+ then {
+ return true;
+ }
+ }
+
+ false
+}
+
+fn is_end_eq_array_len<'tcx>(
+ cx: &LateContext<'tcx>,
+ end: &Expr<'_>,
+ limits: ast::RangeLimits,
+ indexed_ty: Ty<'tcx>,
+) -> bool {
+ if_chain! {
+ if let ExprKind::Lit(ref lit) = end.kind;
+ if let ast::LitKind::Int(end_int, _) = lit.node;
+ if let ty::Array(_, arr_len_const) = indexed_ty.kind();
+ if let Some(arr_len) = arr_len_const.try_eval_usize(cx.tcx, cx.param_env);
+ then {
+ return match limits {
+ ast::RangeLimits::Closed => end_int + 1 >= arr_len.into(),
+ ast::RangeLimits::HalfOpen => end_int >= arr_len.into(),
+ };
+ }
+ }
+
+ false
+}
+
+fn lint_iter_method(cx: &LateContext<'_>, args: &[Expr<'_>], arg: &Expr<'_>, method_name: &str) {
+ let mut applicability = Applicability::MachineApplicable;
+ let object = snippet_with_applicability(cx, args[0].span, "_", &mut applicability);
+ let muta = if method_name == "iter_mut" { "mut " } else { "" };
+ span_lint_and_sugg(
+ cx,
+ EXPLICIT_ITER_LOOP,
+ arg.span,
+ "it is more concise to loop over references to containers instead of using explicit \
+ iteration methods",
+ "to write this more concisely, try",
+ format!("&{}{}", muta, object),
+ applicability,
+ )
+}
+
+fn check_for_loop_arg(cx: &LateContext<'_>, pat: &Pat<'_>, arg: &Expr<'_>, expr: &Expr<'_>) {
+ let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
+ if let ExprKind::MethodCall(ref method, _, ref args, _) = arg.kind {
+ // just the receiver, no arguments
+ if args.len() == 1 {
+ let method_name = &*method.ident.as_str();
+ // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
+ if method_name == "iter" || method_name == "iter_mut" {
+ if is_ref_iterable_type(cx, &args[0]) {
+ lint_iter_method(cx, args, arg, method_name);
+ }
+ } else if method_name == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
+ let receiver_ty = cx.typeck_results().expr_ty(&args[0]);
+ let receiver_ty_adjusted = cx.typeck_results().expr_ty_adjusted(&args[0]);
+ if TyS::same_type(receiver_ty, receiver_ty_adjusted) {
+ let mut applicability = Applicability::MachineApplicable;
+ let object = snippet_with_applicability(cx, args[0].span, "_", &mut applicability);
+ span_lint_and_sugg(
+ cx,
+ EXPLICIT_INTO_ITER_LOOP,
+ arg.span,
+ "it is more concise to loop over containers instead of using explicit \
+ iteration methods",
+ "to write this more concisely, try",
+ object.to_string(),
+ applicability,
+ );
+ } else {
+ let ref_receiver_ty = cx.tcx.mk_ref(
+ cx.tcx.lifetimes.re_erased,
+ ty::TypeAndMut {
+ ty: receiver_ty,
+ mutbl: Mutability::Not,
+ },
+ );
+ if TyS::same_type(receiver_ty_adjusted, ref_receiver_ty) {
+ lint_iter_method(cx, args, arg, method_name)
+ }
+ }
+ } else if method_name == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
+ span_lint(
+ cx,
+ ITER_NEXT_LOOP,
+ expr.span,
+ "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
+ probably not what you want",
+ );
+ next_loop_linted = true;
+ }
+ }
+ }
+ if !next_loop_linted {
+ check_arg_type(cx, pat, arg);
+ }
+}
+
+/// Checks for `for` loops over `Option`s and `Result`s.
+fn check_arg_type(cx: &LateContext<'_>, pat: &Pat<'_>, arg: &Expr<'_>) {
+ let ty = cx.typeck_results().expr_ty(arg);
+ if is_type_diagnostic_item(cx, ty, sym!(option_type)) {
+ span_lint_and_help(
+ cx,
+ FOR_LOOPS_OVER_FALLIBLES,
+ arg.span,
+ &format!(
+ "for loop over `{0}`, which is an `Option`. This is more readably written as an \
+ `if let` statement.",
+ snippet(cx, arg.span, "_")
+ ),
+ None,
+ &format!(
+ "consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
+ snippet(cx, pat.span, "_"),
+ snippet(cx, arg.span, "_")
+ ),
+ );
+ } else if is_type_diagnostic_item(cx, ty, sym!(result_type)) {
+ span_lint_and_help(
+ cx,
+ FOR_LOOPS_OVER_FALLIBLES,
+ arg.span,
+ &format!(
+ "for loop over `{0}`, which is a `Result`. This is more readably written as an \
+ `if let` statement.",
+ snippet(cx, arg.span, "_")
+ ),
+ None,
+ &format!(
+ "consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
+ snippet(cx, pat.span, "_"),
+ snippet(cx, arg.span, "_")
+ ),
+ );
+ }
+}
+
+fn check_for_loop_explicit_counter<'tcx>(
+ cx: &LateContext<'tcx>,
+ pat: &'tcx Pat<'_>,
+ arg: &'tcx Expr<'_>,
+ body: &'tcx Expr<'_>,
+ expr: &'tcx Expr<'_>,
+) {
+ // Look for variables that are incremented once per loop iteration.
+ let mut visitor = IncrementVisitor {
+ cx,
+ states: FxHashMap::default(),
+ depth: 0,
+ done: false,
+ };
+ walk_expr(&mut visitor, body);
+
+ // For each candidate, check the parent block to see if
+ // it's initialized to zero at the start of the loop.
+ if let Some(block) = get_enclosing_block(&cx, expr.hir_id) {
+ for (id, _) in visitor.states.iter().filter(|&(_, v)| *v == VarState::IncrOnce) {
+ let mut visitor2 = InitializeVisitor {
+ cx,
+ end_expr: expr,
+ var_id: *id,
+ state: VarState::IncrOnce,
+ name: None,
+ depth: 0,
+ past_loop: false,
+ };
+ walk_block(&mut visitor2, block);
+
+ if visitor2.state == VarState::Warn {
+ if let Some(name) = visitor2.name {
+ let mut applicability = Applicability::MachineApplicable;
+
+ // for some reason this is the only way to get the `Span`
+ // of the entire `for` loop
+ let for_span = if let ExprKind::Match(_, arms, _) = &expr.kind {
+ arms[0].body.span
+ } else {
+ unreachable!()
+ };
+
+ span_lint_and_sugg(
+ cx,
+ EXPLICIT_COUNTER_LOOP,
+ for_span.with_hi(arg.span.hi()),
+ &format!("the variable `{}` is used as a loop counter.", name),
+ "consider using",
+ format!(
+ "for ({}, {}) in {}.enumerate()",
+ name,
+ snippet_with_applicability(cx, pat.span, "item", &mut applicability),
+ make_iterator_snippet(cx, arg, &mut applicability),
+ ),
+ applicability,
+ );
+ }
+ }
+ }
+ }
+}
+
+/// If `arg` was the argument to a `for` loop, return the "cleanest" way of writing the
+/// actual `Iterator` that the loop uses.
+fn make_iterator_snippet(cx: &LateContext<'_>, arg: &Expr<'_>, applic_ref: &mut Applicability) -> String {
+ let impls_iterator = get_trait_def_id(cx, &paths::ITERATOR).map_or(false, |id| {
+ implements_trait(cx, cx.typeck_results().expr_ty(arg), id, &[])
+ });
+ if impls_iterator {
+ format!(
+ "{}",
+ sugg::Sugg::hir_with_applicability(cx, arg, "_", applic_ref).maybe_par()
+ )
+ } else {
+ // (&x).into_iter() ==> x.iter()
+ // (&mut x).into_iter() ==> x.iter_mut()
+ match &arg.kind {
+ ExprKind::AddrOf(BorrowKind::Ref, mutability, arg_inner)
+ if has_iter_method(cx, cx.typeck_results().expr_ty(&arg_inner)).is_some() =>
+ {
+ let meth_name = match mutability {
+ Mutability::Mut => "iter_mut",
+ Mutability::Not => "iter",
+ };
+ format!(
+ "{}.{}()",
+ sugg::Sugg::hir_with_applicability(cx, &arg_inner, "_", applic_ref).maybe_par(),
+ meth_name,
+ )
+ }
+ _ => format!(
+ "{}.into_iter()",
+ sugg::Sugg::hir_with_applicability(cx, arg, "_", applic_ref).maybe_par()
+ ),
+ }
+ }
+}
+
+/// Checks for the `FOR_KV_MAP` lint.
+fn check_for_loop_over_map_kv<'tcx>(
+ cx: &LateContext<'tcx>,
+ pat: &'tcx Pat<'_>,
+ arg: &'tcx Expr<'_>,
+ body: &'tcx Expr<'_>,
+ expr: &'tcx Expr<'_>,
+) {
+ let pat_span = pat.span;
+
+ if let PatKind::Tuple(ref pat, _) = pat.kind {
+ if pat.len() == 2 {
+ let arg_span = arg.span;
+ let (new_pat_span, kind, ty, mutbl) = match *cx.typeck_results().expr_ty(arg).kind() {
+ ty::Ref(_, ty, mutbl) => match (&pat[0].kind, &pat[1].kind) {
+ (key, _) if pat_is_wild(key, body) => (pat[1].span, "value", ty, mutbl),
+ (_, value) if pat_is_wild(value, body) => (pat[0].span, "key", ty, Mutability::Not),
+ _ => return,
+ },
+ _ => return,
+ };
+ let mutbl = match mutbl {
+ Mutability::Not => "",
+ Mutability::Mut => "_mut",
+ };
+ let arg = match arg.kind {
+ ExprKind::AddrOf(BorrowKind::Ref, _, ref expr) => &**expr,
+ _ => arg,
+ };
+
+ if is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) || match_type(cx, ty, &paths::BTREEMAP) {
+ span_lint_and_then(
+ cx,
+ FOR_KV_MAP,
+ expr.span,
+ &format!("you seem to want to iterate on a map's {}s", kind),
+ |diag| {
+ let map = sugg::Sugg::hir(cx, arg, "map");
+ multispan_sugg(
+ diag,
+ "use the corresponding method",
+ vec![
+ (pat_span, snippet(cx, new_pat_span, kind).into_owned()),
+ (arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl)),
+ ],
+ );
+ },
+ );
+ }
+ }
+ }
+}
+
+struct MutatePairDelegate<'a, 'tcx> {
+ cx: &'a LateContext<'tcx>,
+ hir_id_low: Option<HirId>,
+ hir_id_high: Option<HirId>,
+ span_low: Option<Span>,
+ span_high: Option<Span>,
+}
+
+impl<'tcx> Delegate<'tcx> for MutatePairDelegate<'_, 'tcx> {
+ fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: ConsumeMode) {}
+
+ fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, bk: ty::BorrowKind) {
+ if let ty::BorrowKind::MutBorrow = bk {
+ if let PlaceBase::Local(id) = cmt.place.base {
+ if Some(id) == self.hir_id_low {
+ self.span_low = Some(self.cx.tcx.hir().span(cmt.hir_id))
+ }
+ if Some(id) == self.hir_id_high {
+ self.span_high = Some(self.cx.tcx.hir().span(cmt.hir_id))
+ }
+ }
+ }
+ }
+
+ fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>) {
+ if let PlaceBase::Local(id) = cmt.place.base {
+ if Some(id) == self.hir_id_low {
+ self.span_low = Some(self.cx.tcx.hir().span(cmt.hir_id))
+ }
+ if Some(id) == self.hir_id_high {
+ self.span_high = Some(self.cx.tcx.hir().span(cmt.hir_id))
+ }
+ }
+ }
+}
+
+impl MutatePairDelegate<'_, '_> {
+ fn mutation_span(&self) -> (Option<Span>, Option<Span>) {
+ (self.span_low, self.span_high)
+ }
+}
+
+fn check_for_mut_range_bound(cx: &LateContext<'_>, arg: &Expr<'_>, body: &Expr<'_>) {
+ if let Some(higher::Range {
+ start: Some(start),
+ end: Some(end),
+ ..
+ }) = higher::range(arg)
+ {
+ let mut_ids = vec![check_for_mutability(cx, start), check_for_mutability(cx, end)];
+ if mut_ids[0].is_some() || mut_ids[1].is_some() {
+ let (span_low, span_high) = check_for_mutation(cx, body, &mut_ids);
+ mut_warn_with_span(cx, span_low);
+ mut_warn_with_span(cx, span_high);
+ }
+ }
+}
+
+fn mut_warn_with_span(cx: &LateContext<'_>, span: Option<Span>) {
+ if let Some(sp) = span {
+ span_lint(
+ cx,
+ MUT_RANGE_BOUND,
+ sp,
+ "attempt to mutate range bound within loop; note that the range of the loop is unchanged",
+ );
+ }
+}
+
+fn check_for_mutability(cx: &LateContext<'_>, bound: &Expr<'_>) -> Option<HirId> {
+ if_chain! {
+ if let ExprKind::Path(ref qpath) = bound.kind;
+ if let QPath::Resolved(None, _) = *qpath;
+ then {
+ let res = qpath_res(cx, qpath, bound.hir_id);
+ if let Res::Local(hir_id) = res {
+ let node_str = cx.tcx.hir().get(hir_id);
+ if_chain! {
+ if let Node::Binding(pat) = node_str;
+ if let PatKind::Binding(bind_ann, ..) = pat.kind;
+ if let BindingAnnotation::Mutable = bind_ann;
+ then {
+ return Some(hir_id);
+ }
+ }
+ }
+ }
+ }
+ None
+}
+
+fn check_for_mutation<'tcx>(
+ cx: &LateContext<'tcx>,
+ body: &Expr<'_>,
+ bound_ids: &[Option<HirId>],
+) -> (Option<Span>, Option<Span>) {
+ let mut delegate = MutatePairDelegate {
+ cx,
+ hir_id_low: bound_ids[0],
+ hir_id_high: bound_ids[1],
+ span_low: None,
+ span_high: None,
+ };
+ let def_id = body.hir_id.owner.to_def_id();
+ cx.tcx.infer_ctxt().enter(|infcx| {
+ ExprUseVisitor::new(
+ &mut delegate,
+ &infcx,
+ def_id.expect_local(),
+ cx.param_env,
+ cx.typeck_results(),
+ )
+ .walk_expr(body);
+ });
+ delegate.mutation_span()
+}
+
+/// Returns `true` if the pattern is a `PatWild` or an ident prefixed with `_`.
+fn pat_is_wild<'tcx>(pat: &'tcx PatKind<'_>, body: &'tcx Expr<'_>) -> bool {
+ match *pat {
+ PatKind::Wild => true,
+ PatKind::Binding(.., ident, None) if ident.as_str().starts_with('_') => is_unused(&ident, body),
+ _ => false,
+ }
+}
+
+struct LocalUsedVisitor<'a, 'tcx> {
+ cx: &'a LateContext<'tcx>,
+ local: HirId,
+ used: bool,
+}
+
+impl<'a, 'tcx> Visitor<'tcx> for LocalUsedVisitor<'a, 'tcx> {
+ type Map = Map<'tcx>;
+
+ fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
+ if same_var(self.cx, expr, self.local) {
+ self.used = true;
+ } else {
+ walk_expr(self, expr);
+ }
+ }
+
+ fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+ NestedVisitorMap::None
+ }
+}
+
+struct VarVisitor<'a, 'tcx> {
+ /// context reference
+ cx: &'a LateContext<'tcx>,
+ /// var name to look for as index
+ var: HirId,
+ /// indexed variables that are used mutably
+ indexed_mut: FxHashSet<Symbol>,
+ /// indirectly indexed variables (`v[(i + 4) % N]`), the extend is `None` for global
+ indexed_indirectly: FxHashMap<Symbol, Option<region::Scope>>,
+ /// subset of `indexed` of vars that are indexed directly: `v[i]`
+ /// this will not contain cases like `v[calc_index(i)]` or `v[(i + 4) % N]`
+ indexed_directly: FxHashMap<Symbol, (Option<region::Scope>, Ty<'tcx>)>,
+ /// Any names that are used outside an index operation.
+ /// Used to detect things like `&mut vec` used together with `vec[i]`
+ referenced: FxHashSet<Symbol>,
+ /// has the loop variable been used in expressions other than the index of
+ /// an index op?
+ nonindex: bool,
+ /// Whether we are inside the `$` in `&mut $` or `$ = foo` or `$.bar`, where bar
+ /// takes `&mut self`
+ prefer_mutable: bool,
+}
+
+impl<'a, 'tcx> VarVisitor<'a, 'tcx> {
+ fn check(&mut self, idx: &'tcx Expr<'_>, seqexpr: &'tcx Expr<'_>, expr: &'tcx Expr<'_>) -> bool {
+ if_chain! {
+ // the indexed container is referenced by a name
+ if let ExprKind::Path(ref seqpath) = seqexpr.kind;
+ if let QPath::Resolved(None, ref seqvar) = *seqpath;
+ if seqvar.segments.len() == 1;
+ then {
+ let index_used_directly = same_var(self.cx, idx, self.var);
+ let indexed_indirectly = {
+ let mut used_visitor = LocalUsedVisitor {
+ cx: self.cx,
+ local: self.var,
+ used: false,
+ };
+ walk_expr(&mut used_visitor, idx);
+ used_visitor.used
+ };
+
+ if indexed_indirectly || index_used_directly {
+ if self.prefer_mutable {
+ self.indexed_mut.insert(seqvar.segments[0].ident.name);
+ }
+ let res = qpath_res(self.cx, seqpath, seqexpr.hir_id);
+ match res {
+ Res::Local(hir_id) => {
+ let parent_id = self.cx.tcx.hir().get_parent_item(expr.hir_id);
+ let parent_def_id = self.cx.tcx.hir().local_def_id(parent_id);
+ let extent = self.cx.tcx.region_scope_tree(parent_def_id).var_scope(hir_id.local_id);
+ if indexed_indirectly {
+ self.indexed_indirectly.insert(seqvar.segments[0].ident.name, Some(extent));
+ }
+ if index_used_directly {
+ self.indexed_directly.insert(
+ seqvar.segments[0].ident.name,
+ (Some(extent), self.cx.typeck_results().node_type(seqexpr.hir_id)),
+ );
+ }
+ return false; // no need to walk further *on the variable*
+ }
+ Res::Def(DefKind::Static | DefKind::Const, ..) => {
+ if indexed_indirectly {
+ self.indexed_indirectly.insert(seqvar.segments[0].ident.name, None);
+ }
+ if index_used_directly {
+ self.indexed_directly.insert(
+ seqvar.segments[0].ident.name,
+ (None, self.cx.typeck_results().node_type(seqexpr.hir_id)),
+ );
+ }
+ return false; // no need to walk further *on the variable*
+ }
+ _ => (),
+ }
+ }
+ }
+ }
+ true
+ }
+}
+
+impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> {
+ type Map = Map<'tcx>;
+
+ fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
+ if_chain! {
+ // a range index op
+ if let ExprKind::MethodCall(ref meth, _, ref args, _) = expr.kind;
+ if (meth.ident.name == sym!(index) && match_trait_method(self.cx, expr, &paths::INDEX))
+ || (meth.ident.name == sym!(index_mut) && match_trait_method(self.cx, expr, &paths::INDEX_MUT));
+ if !self.check(&args[1], &args[0], expr);
+ then { return }
+ }
+
+ if_chain! {
+ // an index op
+ if let ExprKind::Index(ref seqexpr, ref idx) = expr.kind;
+ if !self.check(idx, seqexpr, expr);
+ then { return }
+ }
+
+ if_chain! {
+ // directly using a variable
+ if let ExprKind::Path(ref qpath) = expr.kind;
+ if let QPath::Resolved(None, ref path) = *qpath;
+ if path.segments.len() == 1;
+ then {
+ if let Res::Local(local_id) = qpath_res(self.cx, qpath, expr.hir_id) {
+ if local_id == self.var {
+ self.nonindex = true;
+ } else {
+ // not the correct variable, but still a variable
+ self.referenced.insert(path.segments[0].ident.name);
+ }
+ }
+ }
+ }
+
+ let old = self.prefer_mutable;
+ match expr.kind {
+ ExprKind::AssignOp(_, ref lhs, ref rhs) | ExprKind::Assign(ref lhs, ref rhs, _) => {
+ self.prefer_mutable = true;
+ self.visit_expr(lhs);
+ self.prefer_mutable = false;
+ self.visit_expr(rhs);
+ },
+ ExprKind::AddrOf(BorrowKind::Ref, mutbl, ref expr) => {
+ if mutbl == Mutability::Mut {
+ self.prefer_mutable = true;
+ }
+ self.visit_expr(expr);
+ },
+ ExprKind::Call(ref f, args) => {
+ self.visit_expr(f);
+ for expr in args {
+ let ty = self.cx.typeck_results().expr_ty_adjusted(expr);
+ self.prefer_mutable = false;
+ if let ty::Ref(_, _, mutbl) = *ty.kind() {
+ if mutbl == Mutability::Mut {
+ self.prefer_mutable = true;
+ }
+ }
+ self.visit_expr(expr);
+ }
+ },
+ ExprKind::MethodCall(_, _, args, _) => {
+ let def_id = self.cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap();
+ for (ty, expr) in self.cx.tcx.fn_sig(def_id).inputs().skip_binder().iter().zip(args) {
+ self.prefer_mutable = false;
+ if let ty::Ref(_, _, mutbl) = *ty.kind() {
+ if mutbl == Mutability::Mut {
+ self.prefer_mutable = true;
+ }
+ }
+ self.visit_expr(expr);
+ }
+ },
+ ExprKind::Closure(_, _, body_id, ..) => {
+ let body = self.cx.tcx.hir().body(body_id);
+ self.visit_expr(&body.value);
+ },
+ _ => walk_expr(self, expr),
+ }
+ self.prefer_mutable = old;
+ }
+ fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+ NestedVisitorMap::None
+ }
+}
+
+fn is_used_inside<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, container: &'tcx Expr<'_>) -> bool {
+ let def_id = match var_def_id(cx, expr) {
+ Some(id) => id,
+ None => return false,
+ };
+ if let Some(used_mutably) = mutated_variables(container, cx) {
+ if used_mutably.contains(&def_id) {
+ return true;
+ }
+ }
+ false
+}
+
+fn is_iterator_used_after_while_let<'tcx>(cx: &LateContext<'tcx>, iter_expr: &'tcx Expr<'_>) -> bool {
+ let def_id = match var_def_id(cx, iter_expr) {
+ Some(id) => id,
+ None => return false,
+ };
+ let mut visitor = VarUsedAfterLoopVisitor {
+ cx,
+ def_id,
+ iter_expr_id: iter_expr.hir_id,
+ past_while_let: false,
+ var_used_after_while_let: false,
+ };
+ if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
+ walk_block(&mut visitor, enclosing_block);
+ }
+ visitor.var_used_after_while_let
+}
+
+struct VarUsedAfterLoopVisitor<'a, 'tcx> {
+ cx: &'a LateContext<'tcx>,
+ def_id: HirId,
+ iter_expr_id: HirId,
+ past_while_let: bool,
+ var_used_after_while_let: bool,
+}
+
+impl<'a, 'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor<'a, 'tcx> {
+ type Map = Map<'tcx>;
+
+ fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
+ if self.past_while_let {
+ if Some(self.def_id) == var_def_id(self.cx, expr) {
+ self.var_used_after_while_let = true;
+ }
+ } else if self.iter_expr_id == expr.hir_id {
+ self.past_while_let = true;
+ }
+ walk_expr(self, expr);
+ }
+ fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+ NestedVisitorMap::None
+ }
+}
+
+/// Returns `true` if the type of expr is one that provides `IntoIterator` impls
+/// for `&T` and `&mut T`, such as `Vec`.
+#[rustfmt::skip]
+fn is_ref_iterable_type(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
+ // no walk_ptrs_ty: calling iter() on a reference can make sense because it
+ // will allow further borrows afterwards
+ let ty = cx.typeck_results().expr_ty(e);
+ is_iterable_array(ty, cx) ||
+ is_type_diagnostic_item(cx, ty, sym!(vec_type)) ||
+ match_type(cx, ty, &paths::LINKED_LIST) ||
+ is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) ||
+ is_type_diagnostic_item(cx, ty, sym!(hashset_type)) ||
+ is_type_diagnostic_item(cx, ty, sym!(vecdeque_type)) ||
+ match_type(cx, ty, &paths::BINARY_HEAP) ||
+ match_type(cx, ty, &paths::BTREEMAP) ||
+ match_type(cx, ty, &paths::BTREESET)
+}
+
+fn is_iterable_array<'tcx>(ty: Ty<'tcx>, cx: &LateContext<'tcx>) -> bool {
+ // IntoIterator is currently only implemented for array sizes <= 32 in rustc
+ match ty.kind() {
+ ty::Array(_, n) => n
+ .try_eval_usize(cx.tcx, cx.param_env)
+ .map_or(false, |val| (0..=32).contains(&val)),
+ _ => false,
+ }
+}
+
+/// If a block begins with a statement (possibly a `let` binding) and has an
+/// expression, return it.
+fn extract_expr_from_first_stmt<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
+ if block.stmts.is_empty() {
+ return None;
+ }
+ if let StmtKind::Local(ref local) = block.stmts[0].kind {
+ local.init //.map(|expr| expr)
+ } else {
+ None
+ }
+}
+
+/// If a block begins with an expression (with or without semicolon), return it.
+fn extract_first_expr<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
+ match block.expr {
+ Some(ref expr) if block.stmts.is_empty() => Some(expr),
+ None if !block.stmts.is_empty() => match block.stmts[0].kind {
+ StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => Some(expr),
+ StmtKind::Local(..) | StmtKind::Item(..) => None,
+ },
+ _ => None,
+ }
+}
+
+/// Returns `true` if expr contains a single break expr without destination label
+/// and
+/// passed expression. The expression may be within a block.
+fn is_simple_break_expr(expr: &Expr<'_>) -> bool {
+ match expr.kind {
+ ExprKind::Break(dest, ref passed_expr) if dest.label.is_none() && passed_expr.is_none() => true,
+ ExprKind::Block(ref b, _) => extract_first_expr(b).map_or(false, |subexpr| is_simple_break_expr(subexpr)),
+ _ => false,
+ }
+}
+
+// To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
+// incremented exactly once in the loop body, and initialized to zero
+// at the start of the loop.
+#[derive(Debug, PartialEq)]
+enum VarState {
+ Initial, // Not examined yet
+ IncrOnce, // Incremented exactly once, may be a loop counter
+ Declared, // Declared but not (yet) initialized to zero
+ Warn,
+ DontWarn,
+}
+
+/// Scan a for loop for variables that are incremented exactly once.
+struct IncrementVisitor<'a, 'tcx> {
+ cx: &'a LateContext<'tcx>, // context reference
+ states: FxHashMap<HirId, VarState>, // incremented variables
+ depth: u32, // depth of conditional expressions
+ done: bool,
+}
+
+impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
+ type Map = Map<'tcx>;
+
+ fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
+ if self.done {
+ return;
+ }
+
+ // If node is a variable
+ if let Some(def_id) = var_def_id(self.cx, expr) {
+ if let Some(parent) = get_parent_expr(self.cx, expr) {
+ let state = self.states.entry(def_id).or_insert(VarState::Initial);
+
+ match parent.kind {
+ ExprKind::AssignOp(op, ref lhs, ref rhs) => {
+ if lhs.hir_id == expr.hir_id {
+ if op.node == BinOpKind::Add && is_integer_const(self.cx, rhs, 1) {
+ *state = match *state {
+ VarState::Initial if self.depth == 0 => VarState::IncrOnce,
+ _ => VarState::DontWarn,
+ };
+ } else {
+ // Assigned some other value
+ *state = VarState::DontWarn;
+ }
+ }
+ },
+ ExprKind::Assign(ref lhs, _, _) if lhs.hir_id == expr.hir_id => *state = VarState::DontWarn,
+ ExprKind::AddrOf(BorrowKind::Ref, mutability, _) if mutability == Mutability::Mut => {
+ *state = VarState::DontWarn
+ },
+ _ => (),
+ }
+ }
+ } else if is_loop(expr) || is_conditional(expr) {
+ self.depth += 1;
+ walk_expr(self, expr);
+ self.depth -= 1;
+ return;
+ } else if let ExprKind::Continue(_) = expr.kind {
+ self.done = true;
+ return;
+ }
+ walk_expr(self, expr);
+ }
+ fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+ NestedVisitorMap::None
+ }
+}
+
+/// Checks whether a variable is initialized to zero at the start of a loop.
+struct InitializeVisitor<'a, 'tcx> {
+ cx: &'a LateContext<'tcx>, // context reference
+ end_expr: &'tcx Expr<'tcx>, // the for loop. Stop scanning here.
+ var_id: HirId,
+ state: VarState,
+ name: Option<Symbol>,
+ depth: u32, // depth of conditional expressions
+ past_loop: bool,
+}
+
+impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
+ type Map = Map<'tcx>;
+
+ fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
+ // Look for declarations of the variable
+ if let StmtKind::Local(ref local) = stmt.kind {
+ if local.pat.hir_id == self.var_id {
+ if let PatKind::Binding(.., ident, _) = local.pat.kind {
+ self.name = Some(ident.name);
+
+ self.state = local.init.as_ref().map_or(VarState::Declared, |init| {
+ if is_integer_const(&self.cx, init, 0) {
+ VarState::Warn
+ } else {
+ VarState::Declared
+ }
+ })
+ }
+ }
+ }
+ walk_stmt(self, stmt);
+ }
+
+ fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
+ if self.state == VarState::DontWarn {
+ return;
+ }
+ if expr.hir_id == self.end_expr.hir_id {
+ self.past_loop = true;
+ return;
+ }
+ // No need to visit expressions before the variable is
+ // declared
+ if self.state == VarState::IncrOnce {
+ return;
+ }
+
+ // If node is the desired variable, see how it's used
+ if var_def_id(self.cx, expr) == Some(self.var_id) {
+ if let Some(parent) = get_parent_expr(self.cx, expr) {
+ match parent.kind {
+ ExprKind::AssignOp(_, ref lhs, _) if lhs.hir_id == expr.hir_id => {
+ self.state = VarState::DontWarn;
+ },
+ ExprKind::Assign(ref lhs, ref rhs, _) if lhs.hir_id == expr.hir_id => {
+ self.state = if is_integer_const(&self.cx, rhs, 0) && self.depth == 0 {
+ VarState::Warn
+ } else {
+ VarState::DontWarn
+ }
+ },
+ ExprKind::AddrOf(BorrowKind::Ref, mutability, _) if mutability == Mutability::Mut => {
+ self.state = VarState::DontWarn
+ },
+ _ => (),
+ }
+ }
+
+ if self.past_loop {
+ self.state = VarState::DontWarn;
+ return;
+ }
+ } else if !self.past_loop && is_loop(expr) {
+ self.state = VarState::DontWarn;
+ return;
+ } else if is_conditional(expr) {
+ self.depth += 1;
+ walk_expr(self, expr);
+ self.depth -= 1;
+ return;
+ }
+ walk_expr(self, expr);
+ }
+
+ fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+ NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
+ }
+}
+
+fn var_def_id(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<HirId> {
+ if let ExprKind::Path(ref qpath) = expr.kind {
+ let path_res = qpath_res(cx, qpath, expr.hir_id);
+ if let Res::Local(hir_id) = path_res {
+ return Some(hir_id);
+ }
+ }
+ None
+}
+
+fn is_loop(expr: &Expr<'_>) -> bool {
+ matches!(expr.kind, ExprKind::Loop(..))
+}
+
+fn is_conditional(expr: &Expr<'_>) -> bool {
+ matches!(expr.kind, ExprKind::Match(..))
+}
+
+fn is_nested(cx: &LateContext<'_>, match_expr: &Expr<'_>, iter_expr: &Expr<'_>) -> bool {
+ if_chain! {
+ if let Some(loop_block) = get_enclosing_block(cx, match_expr.hir_id);
+ let parent_node = cx.tcx.hir().get_parent_node(loop_block.hir_id);
+ if let Some(Node::Expr(loop_expr)) = cx.tcx.hir().find(parent_node);
+ then {
+ return is_loop_nested(cx, loop_expr, iter_expr)
+ }
+ }
+ false
+}
+
+fn is_loop_nested(cx: &LateContext<'_>, loop_expr: &Expr<'_>, iter_expr: &Expr<'_>) -> bool {
+ let mut id = loop_expr.hir_id;
+ let iter_name = if let Some(name) = path_name(iter_expr) {
+ name
+ } else {
+ return true;
+ };
+ loop {
+ let parent = cx.tcx.hir().get_parent_node(id);
+ if parent == id {
+ return false;
+ }
+ match cx.tcx.hir().find(parent) {
+ Some(Node::Expr(expr)) => {
+ if let ExprKind::Loop(..) = expr.kind {
+ return true;
+ };
+ },
+ Some(Node::Block(block)) => {
+ let mut block_visitor = LoopNestVisitor {
+ hir_id: id,
+ iterator: iter_name,
+ nesting: Unknown,
+ };
+ walk_block(&mut block_visitor, block);
+ if block_visitor.nesting == RuledOut {
+ return false;
+ }
+ },
+ Some(Node::Stmt(_)) => (),
+ _ => {
+ return false;
+ },
+ }
+ id = parent;
+ }
+}
+
+#[derive(PartialEq, Eq)]
+enum Nesting {
+ Unknown, // no nesting detected yet
+ RuledOut, // the iterator is initialized or assigned within scope
+ LookFurther, // no nesting detected, no further walk required
+}
+
+use self::Nesting::{LookFurther, RuledOut, Unknown};
+
+struct LoopNestVisitor {
+ hir_id: HirId,
+ iterator: Symbol,
+ nesting: Nesting,
+}
+
+impl<'tcx> Visitor<'tcx> for LoopNestVisitor {
+ type Map = Map<'tcx>;
+
+ fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
+ if stmt.hir_id == self.hir_id {
+ self.nesting = LookFurther;
+ } else if self.nesting == Unknown {
+ walk_stmt(self, stmt);
+ }
+ }
+
+ fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
+ if self.nesting != Unknown {
+ return;
+ }
+ if expr.hir_id == self.hir_id {
+ self.nesting = LookFurther;
+ return;
+ }
+ match expr.kind {
+ ExprKind::Assign(ref path, _, _) | ExprKind::AssignOp(_, ref path, _) => {
+ if match_var(path, self.iterator) {
+ self.nesting = RuledOut;
+ }
+ },
+ _ => walk_expr(self, expr),
+ }
+ }
+
+ fn visit_pat(&mut self, pat: &'tcx Pat<'_>) {
+ if self.nesting != Unknown {
+ return;
+ }
+ if let PatKind::Binding(.., span_name, _) = pat.kind {
+ if self.iterator == span_name.name {
+ self.nesting = RuledOut;
+ return;
+ }
+ }
+ walk_pat(self, pat)
+ }
+
+ fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+ NestedVisitorMap::None
+ }
+}
+
+fn path_name(e: &Expr<'_>) -> Option<Symbol> {
+ if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.kind {
+ let segments = &path.segments;
+ if segments.len() == 1 {
+ return Some(segments[0].ident.name);
+ }
+ };
+ None
+}
+
+fn check_infinite_loop<'tcx>(cx: &LateContext<'tcx>, cond: &'tcx Expr<'_>, expr: &'tcx Expr<'_>) {
+ if constant(cx, cx.typeck_results(), cond).is_some() {
+ // A pure constant condition (e.g., `while false`) is not linted.
+ return;
+ }
+
+ let mut var_visitor = VarCollectorVisitor {
+ cx,
+ ids: FxHashSet::default(),
+ def_ids: FxHashMap::default(),
+ skip: false,
+ };
+ var_visitor.visit_expr(cond);
+ if var_visitor.skip {
+ return;
+ }
+ let used_in_condition = &var_visitor.ids;
+ let no_cond_variable_mutated = if let Some(used_mutably) = mutated_variables(expr, cx) {
+ used_in_condition.is_disjoint(&used_mutably)
+ } else {
+ return;
+ };
+ let mutable_static_in_cond = var_visitor.def_ids.iter().any(|(_, v)| *v);
+
+ let mut has_break_or_return_visitor = HasBreakOrReturnVisitor {
+ has_break_or_return: false,
+ };
+ has_break_or_return_visitor.visit_expr(expr);
+ let has_break_or_return = has_break_or_return_visitor.has_break_or_return;
+
+ if no_cond_variable_mutated && !mutable_static_in_cond {
+ span_lint_and_then(
+ cx,
+ WHILE_IMMUTABLE_CONDITION,
+ cond.span,
+ "variables in the condition are not mutated in the loop body",
+ |diag| {
+ diag.note("this may lead to an infinite or to a never running loop");
+
+ if has_break_or_return {
+ diag.note("this loop contains `return`s or `break`s");
+ diag.help("rewrite it as `if cond { loop { } }`");
+ }
+ },
+ );
+ }
+}
+
+struct HasBreakOrReturnVisitor {
+ has_break_or_return: bool,
+}
+
+impl<'tcx> Visitor<'tcx> for HasBreakOrReturnVisitor {
+ type Map = Map<'tcx>;
+
+ fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
+ if self.has_break_or_return {
+ return;
+ }
+
+ match expr.kind {
+ ExprKind::Ret(_) | ExprKind::Break(_, _) => {
+ self.has_break_or_return = true;
+ return;
+ },
+ _ => {},
+ }
+
+ walk_expr(self, expr);
+ }
+
+ fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+ NestedVisitorMap::None
+ }
+}
+
+/// Collects the set of variables in an expression
+/// Stops analysis if a function call is found
+/// Note: In some cases such as `self`, there are no mutable annotation,
+/// All variables definition IDs are collected
+struct VarCollectorVisitor<'a, 'tcx> {
+ cx: &'a LateContext<'tcx>,
+ ids: FxHashSet<HirId>,
+ def_ids: FxHashMap<def_id::DefId, bool>,
+ skip: bool,
+}
+
+impl<'a, 'tcx> VarCollectorVisitor<'a, 'tcx> {
+ fn insert_def_id(&mut self, ex: &'tcx Expr<'_>) {
+ if_chain! {
+ if let ExprKind::Path(ref qpath) = ex.kind;
+ if let QPath::Resolved(None, _) = *qpath;
+ let res = qpath_res(self.cx, qpath, ex.hir_id);
+ then {
+ match res {
+ Res::Local(hir_id) => {
+ self.ids.insert(hir_id);
+ },
+ Res::Def(DefKind::Static, def_id) => {
+ let mutable = self.cx.tcx.is_mutable_static(def_id);
+ self.def_ids.insert(def_id, mutable);
+ },
+ _ => {},
+ }
+ }
+ }
+ }
+}
+
+impl<'a, 'tcx> Visitor<'tcx> for VarCollectorVisitor<'a, 'tcx> {
+ type Map = Map<'tcx>;
+
+ fn visit_expr(&mut self, ex: &'tcx Expr<'_>) {
+ match ex.kind {
+ ExprKind::Path(_) => self.insert_def_id(ex),
+ // If there is any function/method call… we just stop analysis
+ ExprKind::Call(..) | ExprKind::MethodCall(..) => self.skip = true,
+
+ _ => walk_expr(self, ex),
+ }
+ }
+
+ fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+ NestedVisitorMap::None
+ }
+}
+
+const NEEDLESS_COLLECT_MSG: &str = "avoid using `collect()` when not needed";
+
+fn check_needless_collect<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) {
+ check_needless_collect_direct_usage(expr, cx);
+ check_needless_collect_indirect_usage(expr, cx);
+}
+fn check_needless_collect_direct_usage<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) {
+ if_chain! {
+ if let ExprKind::MethodCall(ref method, _, ref args, _) = expr.kind;
+ if let ExprKind::MethodCall(ref chain_method, _, _, _) = args[0].kind;
+ if chain_method.ident.name == sym!(collect) && match_trait_method(cx, &args[0], &paths::ITERATOR);
+ if let Some(ref generic_args) = chain_method.args;
+ if let Some(GenericArg::Type(ref ty)) = generic_args.args.get(0);
+ then {
+ let ty = cx.typeck_results().node_type(ty.hir_id);
+ if is_type_diagnostic_item(cx, ty, sym!(vec_type)) ||
+ is_type_diagnostic_item(cx, ty, sym!(vecdeque_type)) ||
+ match_type(cx, ty, &paths::BTREEMAP) ||
+ is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) {
+ if method.ident.name == sym!(len) {
+ let span = shorten_needless_collect_span(expr);
+ span_lint_and_sugg(
+ cx,
+ NEEDLESS_COLLECT,
+ span,
+ NEEDLESS_COLLECT_MSG,
+ "replace with",
+ "count()".to_string(),
+ Applicability::MachineApplicable,
+ );
+ }
+ if method.ident.name == sym!(is_empty) {
+ let span = shorten_needless_collect_span(expr);
+ span_lint_and_sugg(
+ cx,
+ NEEDLESS_COLLECT,
+ span,
+ NEEDLESS_COLLECT_MSG,
+ "replace with",
+ "next().is_none()".to_string(),
+ Applicability::MachineApplicable,
+ );
+ }
+ if method.ident.name == sym!(contains) {
+ let contains_arg = snippet(cx, args[1].span, "??");
+ let span = shorten_needless_collect_span(expr);
+ span_lint_and_then(
+ cx,
+ NEEDLESS_COLLECT,
+ span,
+ NEEDLESS_COLLECT_MSG,
+ |diag| {
+ let (arg, pred) = if contains_arg.starts_with('&') {
+ ("x", &contains_arg[1..])
+ } else {
+ ("&x", &*contains_arg)
+ };
+ diag.span_suggestion(
+ span,
+ "replace with",
+ format!(
+ "any(|{}| x == {})",
+ arg, pred
+ ),
+ Applicability::MachineApplicable,
+ );
+ }
+ );
+ }
+ }
+ }
+ }
+}
+
+fn check_needless_collect_indirect_usage<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) {
+ if let ExprKind::Block(ref block, _) = expr.kind {
+ for ref stmt in block.stmts {
+ if_chain! {
+ if let StmtKind::Local(
+ Local { pat: Pat { kind: PatKind::Binding(_, _, ident, .. ), .. },
+ init: Some(ref init_expr), .. }
+ ) = stmt.kind;
+ if let ExprKind::MethodCall(ref method_name, _, &[ref iter_source], ..) = init_expr.kind;
+ if method_name.ident.name == sym!(collect) && match_trait_method(cx, &init_expr, &paths::ITERATOR);
+ if let Some(ref generic_args) = method_name.args;
+ if let Some(GenericArg::Type(ref ty)) = generic_args.args.get(0);
+ if let ty = cx.typeck_results().node_type(ty.hir_id);
+ if is_type_diagnostic_item(cx, ty, sym::vec_type) ||
+ is_type_diagnostic_item(cx, ty, sym!(vecdeque_type)) ||
+ match_type(cx, ty, &paths::LINKED_LIST);
+ if let Some(iter_calls) = detect_iter_and_into_iters(block, *ident);
+ if iter_calls.len() == 1;
+ then {
+ // Suggest replacing iter_call with iter_replacement, and removing stmt
+ let iter_call = &iter_calls[0];
+ span_lint_and_then(
+ cx,
+ NEEDLESS_COLLECT,
+ stmt.span.until(iter_call.span),
+ NEEDLESS_COLLECT_MSG,
+ |diag| {
+ let iter_replacement = format!("{}{}", Sugg::hir(cx, iter_source, ".."), iter_call.get_iter_method(cx));
+ diag.multipart_suggestion(
+ iter_call.get_suggestion_text(),
+ vec![
+ (stmt.span, String::new()),
+ (iter_call.span, iter_replacement)
+ ],
+ Applicability::MachineApplicable,// MaybeIncorrect,
+ ).emit();
+ },
+ );
+ }
+ }
+ }
+ }
+}
+
+struct IterFunction {
+ func: IterFunctionKind,
+ span: Span,
+}
+impl IterFunction {
+ fn get_iter_method(&self, cx: &LateContext<'_>) -> String {
+ match &self.func {
+ IterFunctionKind::IntoIter => String::new(),
+ IterFunctionKind::Len => String::from(".count()"),
+ IterFunctionKind::IsEmpty => String::from(".next().is_none()"),
+ IterFunctionKind::Contains(span) => format!(".any(|x| x == {})", snippet(cx, *span, "..")),
+ }
+ }
+ fn get_suggestion_text(&self) -> &'static str {
+ match &self.func {
+ IterFunctionKind::IntoIter => {
+ "Use the original Iterator instead of collecting it and then producing a new one"
+ },
+ IterFunctionKind::Len => {
+ "Take the original Iterator's count instead of collecting it and finding the length"
+ },
+ IterFunctionKind::IsEmpty => {
+ "Check if the original Iterator has anything instead of collecting it and seeing if it's empty"
+ },
+ IterFunctionKind::Contains(_) => {
+ "Check if the original Iterator contains an element instead of collecting then checking"
+ },
+ }
+ }
+}
+enum IterFunctionKind {
+ IntoIter,
+ Len,
+ IsEmpty,
+ Contains(Span),
+}
+
+struct IterFunctionVisitor {
+ uses: Vec<IterFunction>,
+ seen_other: bool,
+ target: Ident,
+}
+impl<'tcx> Visitor<'tcx> for IterFunctionVisitor {
+ fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
+ // Check function calls on our collection
+ if_chain! {
+ if let ExprKind::MethodCall(method_name, _, ref args, _) = &expr.kind;
+ if let Some(Expr { kind: ExprKind::Path(QPath::Resolved(_, ref path)), .. }) = args.get(0);
+ if let &[name] = &path.segments;
+ if name.ident == self.target;
+ then {
+ let len = sym!(len);
+ let is_empty = sym!(is_empty);
+ let contains = sym!(contains);
+ match method_name.ident.name {
+ sym::into_iter => self.uses.push(
+ IterFunction { func: IterFunctionKind::IntoIter, span: expr.span }
+ ),
+ name if name == len => self.uses.push(
+ IterFunction { func: IterFunctionKind::Len, span: expr.span }
+ ),
+ name if name == is_empty => self.uses.push(
+ IterFunction { func: IterFunctionKind::IsEmpty, span: expr.span }
+ ),
+ name if name == contains => self.uses.push(
+ IterFunction { func: IterFunctionKind::Contains(args[1].span), span: expr.span }
+ ),
+ _ => self.seen_other = true,
+ }
+ return
+ }
+ }
+ // Check if the collection is used for anything else
+ if_chain! {
+ if let Expr { kind: ExprKind::Path(QPath::Resolved(_, ref path)), .. } = expr;
+ if let &[name] = &path.segments;
+ if name.ident == self.target;
+ then {
+ self.seen_other = true;
+ } else {
+ walk_expr(self, expr);
+ }
+ }
+ }
+
+ type Map = Map<'tcx>;
+ fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+ NestedVisitorMap::None
+ }
+}
+
+/// Detect the occurences of calls to `iter` or `into_iter` for the
+/// given identifier
+fn detect_iter_and_into_iters<'tcx>(block: &'tcx Block<'tcx>, identifier: Ident) -> Option<Vec<IterFunction>> {
+ let mut visitor = IterFunctionVisitor {
+ uses: Vec::new(),
+ target: identifier,
+ seen_other: false,
+ };
+ visitor.visit_block(block);
+ if visitor.seen_other {
+ None
+ } else {
+ Some(visitor.uses)
+ }
+}
+
+fn shorten_needless_collect_span(expr: &Expr<'_>) -> Span {
+ if_chain! {
+ if let ExprKind::MethodCall(.., args, _) = &expr.kind;
+ if let ExprKind::MethodCall(_, span, ..) = &args[0].kind;
+ then {
+ return expr.span.with_lo(span.lo());
+ }
+ }
+ unreachable!();
+}
--- /dev/null
- /// or closure that returns the unit type.
+use crate::utils::{is_type_diagnostic_item, iter_input_pats, method_chain_args, snippet, span_lint_and_then};
+use if_chain::if_chain;
+use rustc_errors::Applicability;
+use rustc_hir as hir;
+use rustc_lint::{LateContext, LateLintPass};
+use rustc_middle::ty::{self, Ty};
+use rustc_session::{declare_lint_pass, declare_tool_lint};
+use rustc_span::source_map::Span;
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for usage of `option.map(f)` where f is a function
- /// or closure that returns the unit type.
++ /// or closure that returns the unit type `()`.
+ ///
+ /// **Why is this bad?** Readability, this can be written more clearly with
+ /// an if let statement
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ ///
+ /// ```rust
+ /// # fn do_stuff() -> Option<String> { Some(String::new()) }
+ /// # fn log_err_msg(foo: String) -> Option<String> { Some(foo) }
+ /// # fn format_msg(foo: String) -> String { String::new() }
+ /// let x: Option<String> = do_stuff();
+ /// x.map(log_err_msg);
+ /// # let x: Option<String> = do_stuff();
+ /// x.map(|msg| log_err_msg(format_msg(msg)));
+ /// ```
+ ///
+ /// The correct use would be:
+ ///
+ /// ```rust
+ /// # fn do_stuff() -> Option<String> { Some(String::new()) }
+ /// # fn log_err_msg(foo: String) -> Option<String> { Some(foo) }
+ /// # fn format_msg(foo: String) -> String { String::new() }
+ /// let x: Option<String> = do_stuff();
+ /// if let Some(msg) = x {
+ /// log_err_msg(msg);
+ /// }
+ ///
+ /// # let x: Option<String> = do_stuff();
+ /// if let Some(msg) = x {
+ /// log_err_msg(format_msg(msg));
+ /// }
+ /// ```
+ pub OPTION_MAP_UNIT_FN,
+ complexity,
+ "using `option.map(f)`, where `f` is a function or closure that returns `()`"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for usage of `result.map(f)` where f is a function
- "called `map(f)` on an `{0}` value where `f` is a {1} that returns the unit type",
++ /// or closure that returns the unit type `()`.
+ ///
+ /// **Why is this bad?** Readability, this can be written more clearly with
+ /// an if let statement
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ ///
+ /// ```rust
+ /// # fn do_stuff() -> Result<String, String> { Ok(String::new()) }
+ /// # fn log_err_msg(foo: String) -> Result<String, String> { Ok(foo) }
+ /// # fn format_msg(foo: String) -> String { String::new() }
+ /// let x: Result<String, String> = do_stuff();
+ /// x.map(log_err_msg);
+ /// # let x: Result<String, String> = do_stuff();
+ /// x.map(|msg| log_err_msg(format_msg(msg)));
+ /// ```
+ ///
+ /// The correct use would be:
+ ///
+ /// ```rust
+ /// # fn do_stuff() -> Result<String, String> { Ok(String::new()) }
+ /// # fn log_err_msg(foo: String) -> Result<String, String> { Ok(foo) }
+ /// # fn format_msg(foo: String) -> String { String::new() }
+ /// let x: Result<String, String> = do_stuff();
+ /// if let Ok(msg) = x {
+ /// log_err_msg(msg);
+ /// };
+ /// # let x: Result<String, String> = do_stuff();
+ /// if let Ok(msg) = x {
+ /// log_err_msg(format_msg(msg));
+ /// };
+ /// ```
+ pub RESULT_MAP_UNIT_FN,
+ complexity,
+ "using `result.map(f)`, where `f` is a function or closure that returns `()`"
+}
+
+declare_lint_pass!(MapUnit => [OPTION_MAP_UNIT_FN, RESULT_MAP_UNIT_FN]);
+
+fn is_unit_type(ty: Ty<'_>) -> bool {
+ match ty.kind() {
+ ty::Tuple(slice) => slice.is_empty(),
+ ty::Never => true,
+ _ => false,
+ }
+}
+
+fn is_unit_function(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
+ let ty = cx.typeck_results().expr_ty(expr);
+
+ if let ty::FnDef(id, _) = *ty.kind() {
+ if let Some(fn_type) = cx.tcx.fn_sig(id).no_bound_vars() {
+ return is_unit_type(fn_type.output());
+ }
+ }
+ false
+}
+
+fn is_unit_expression(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
+ is_unit_type(cx.typeck_results().expr_ty(expr))
+}
+
+/// The expression inside a closure may or may not have surrounding braces and
+/// semicolons, which causes problems when generating a suggestion. Given an
+/// expression that evaluates to '()' or '!', recursively remove useless braces
+/// and semi-colons until is suitable for including in the suggestion template
+fn reduce_unit_expression<'a>(cx: &LateContext<'_>, expr: &'a hir::Expr<'_>) -> Option<Span> {
+ if !is_unit_expression(cx, expr) {
+ return None;
+ }
+
+ match expr.kind {
+ hir::ExprKind::Call(_, _) | hir::ExprKind::MethodCall(_, _, _, _) => {
+ // Calls can't be reduced any more
+ Some(expr.span)
+ },
+ hir::ExprKind::Block(ref block, _) => {
+ match (&block.stmts[..], block.expr.as_ref()) {
+ (&[], Some(inner_expr)) => {
+ // If block only contains an expression,
+ // reduce `{ X }` to `X`
+ reduce_unit_expression(cx, inner_expr)
+ },
+ (&[ref inner_stmt], None) => {
+ // If block only contains statements,
+ // reduce `{ X; }` to `X` or `X;`
+ match inner_stmt.kind {
+ hir::StmtKind::Local(ref local) => Some(local.span),
+ hir::StmtKind::Expr(ref e) => Some(e.span),
+ hir::StmtKind::Semi(..) => Some(inner_stmt.span),
+ hir::StmtKind::Item(..) => None,
+ }
+ },
+ _ => {
+ // For closures that contain multiple statements
+ // it's difficult to get a correct suggestion span
+ // for all cases (multi-line closures specifically)
+ //
+ // We do not attempt to build a suggestion for those right now.
+ None
+ },
+ }
+ },
+ _ => None,
+ }
+}
+
+fn unit_closure<'tcx>(
+ cx: &LateContext<'tcx>,
+ expr: &hir::Expr<'_>,
+) -> Option<(&'tcx hir::Param<'tcx>, &'tcx hir::Expr<'tcx>)> {
+ if let hir::ExprKind::Closure(_, ref decl, inner_expr_id, _, _) = expr.kind {
+ let body = cx.tcx.hir().body(inner_expr_id);
+ let body_expr = &body.value;
+
+ if_chain! {
+ if decl.inputs.len() == 1;
+ if is_unit_expression(cx, body_expr);
+ if let Some(binding) = iter_input_pats(&decl, body).next();
+ then {
+ return Some((binding, body_expr));
+ }
+ }
+ }
+ None
+}
+
+/// Builds a name for the let binding variable (`var_arg`)
+///
+/// `x.field` => `x_field`
+/// `y` => `_y`
+///
+/// Anything else will return `a`.
+fn let_binding_name(cx: &LateContext<'_>, var_arg: &hir::Expr<'_>) -> String {
+ match &var_arg.kind {
+ hir::ExprKind::Field(_, _) => snippet(cx, var_arg.span, "_").replace(".", "_"),
+ hir::ExprKind::Path(_) => format!("_{}", snippet(cx, var_arg.span, "")),
+ _ => "a".to_string(),
+ }
+}
+
+#[must_use]
+fn suggestion_msg(function_type: &str, map_type: &str) -> String {
+ format!(
++ "called `map(f)` on an `{0}` value where `f` is a {1} that returns the unit type `()`",
+ map_type, function_type
+ )
+}
+
+fn lint_map_unit_fn(cx: &LateContext<'_>, stmt: &hir::Stmt<'_>, expr: &hir::Expr<'_>, map_args: &[hir::Expr<'_>]) {
+ let var_arg = &map_args[0];
+
+ let (map_type, variant, lint) =
+ if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(var_arg), sym!(option_type)) {
+ ("Option", "Some", OPTION_MAP_UNIT_FN)
+ } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(var_arg), sym!(result_type)) {
+ ("Result", "Ok", RESULT_MAP_UNIT_FN)
+ } else {
+ return;
+ };
+ let fn_arg = &map_args[1];
+
+ if is_unit_function(cx, fn_arg) {
+ let msg = suggestion_msg("function", map_type);
+ let suggestion = format!(
+ "if let {0}({binding}) = {1} {{ {2}({binding}) }}",
+ variant,
+ snippet(cx, var_arg.span, "_"),
+ snippet(cx, fn_arg.span, "_"),
+ binding = let_binding_name(cx, var_arg)
+ );
+
+ span_lint_and_then(cx, lint, expr.span, &msg, |diag| {
+ diag.span_suggestion(stmt.span, "try this", suggestion, Applicability::MachineApplicable);
+ });
+ } else if let Some((binding, closure_expr)) = unit_closure(cx, fn_arg) {
+ let msg = suggestion_msg("closure", map_type);
+
+ span_lint_and_then(cx, lint, expr.span, &msg, |diag| {
+ if let Some(reduced_expr_span) = reduce_unit_expression(cx, closure_expr) {
+ let suggestion = format!(
+ "if let {0}({1}) = {2} {{ {3} }}",
+ variant,
+ snippet(cx, binding.pat.span, "_"),
+ snippet(cx, var_arg.span, "_"),
+ snippet(cx, reduced_expr_span, "_")
+ );
+ diag.span_suggestion(
+ stmt.span,
+ "try this",
+ suggestion,
+ Applicability::MachineApplicable, // snippet
+ );
+ } else {
+ let suggestion = format!(
+ "if let {0}({1}) = {2} {{ ... }}",
+ variant,
+ snippet(cx, binding.pat.span, "_"),
+ snippet(cx, var_arg.span, "_"),
+ );
+ diag.span_suggestion(stmt.span, "try this", suggestion, Applicability::HasPlaceholders);
+ }
+ });
+ }
+}
+
+impl<'tcx> LateLintPass<'tcx> for MapUnit {
+ fn check_stmt(&mut self, cx: &LateContext<'_>, stmt: &hir::Stmt<'_>) {
+ if stmt.span.from_expansion() {
+ return;
+ }
+
+ if let hir::StmtKind::Semi(ref expr) = stmt.kind {
+ if let Some(arglists) = method_chain_args(expr, &["map"]) {
+ lint_map_unit_fn(cx, stmt, expr, arglists[0]);
+ }
+ }
+ }
+}
--- /dev/null
- /// **What it does:** Warns when using push_str with a single-character string literal,
- /// and push with a char would work fine.
+mod bind_instead_of_map;
+mod inefficient_to_string;
+mod manual_saturating_arithmetic;
+mod option_map_unwrap_or;
+mod unnecessary_filter_map;
+mod unnecessary_lazy_eval;
+
+use std::borrow::Cow;
+use std::fmt;
+use std::iter;
+
+use bind_instead_of_map::BindInsteadOfMap;
+use if_chain::if_chain;
+use rustc_ast::ast;
+use rustc_errors::Applicability;
+use rustc_hir as hir;
+use rustc_hir::intravisit::{self, Visitor};
+use rustc_hir::{TraitItem, TraitItemKind};
+use rustc_lint::{LateContext, LateLintPass, Lint, LintContext};
+use rustc_middle::hir::map::Map;
+use rustc_middle::lint::in_external_macro;
+use rustc_middle::ty::{self, TraitRef, Ty, TyS};
+use rustc_session::{declare_lint_pass, declare_tool_lint};
+use rustc_span::source_map::Span;
+use rustc_span::symbol::{sym, SymbolStr};
+
+use crate::consts::{constant, Constant};
+use crate::utils::usage::mutated_variables;
+use crate::utils::{
+ contains_ty, get_arg_name, get_parent_expr, get_trait_def_id, has_iter_method, higher, implements_trait, in_macro,
+ is_copy, is_ctor_or_promotable_const_function, is_expn_of, is_type_diagnostic_item, iter_input_pats,
+ last_path_segment, match_def_path, match_qpath, match_trait_method, match_type, match_var, method_calls,
+ method_chain_args, paths, remove_blocks, return_ty, single_segment_path, snippet, snippet_with_applicability,
+ snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_note, span_lint_and_sugg,
+ span_lint_and_then, sugg, walk_ptrs_ty, walk_ptrs_ty_depth, SpanlessEq,
+};
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for `.unwrap()` calls on `Option`s and on `Result`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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Examples:**
+ /// ```rust
+ /// # let opt = Some(1);
+ ///
+ /// // Bad
+ /// opt.unwrap();
+ ///
+ /// // Good
+ /// opt.expect("more helpful message");
+ /// ```
+ ///
+ /// // or
+ ///
+ /// ```rust
+ /// # let res: Result<usize, ()> = Ok(1);
+ ///
+ /// // Bad
+ /// res.unwrap();
+ ///
+ /// // Good
+ /// res.expect("more helpful message");
+ /// ```
+ pub UNWRAP_USED,
+ restriction,
+ "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for `.expect()` calls on `Option`s and `Result`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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Examples:**
+ /// ```rust,ignore
+ /// # let opt = Some(1);
+ ///
+ /// // Bad
+ /// opt.expect("one");
+ ///
+ /// // Good
+ /// let opt = Some(1);
+ /// opt?;
+ /// ```
+ ///
+ /// // or
+ ///
+ /// ```rust
+ /// # let res: Result<usize, ()> = Ok(1);
+ ///
+ /// // Bad
+ /// res.expect("one");
+ ///
+ /// // Good
+ /// res?;
+ /// # Ok::<(), ()>(())
+ /// ```
+ pub EXPECT_USED,
+ restriction,
+ "using `.expect()` on `Result` or `Option`, which might be better handled"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// struct X;
+ /// impl X {
+ /// fn add(&self, other: &X) -> X {
+ /// // ..
+ /// # X
+ /// }
+ /// }
+ /// ```
+ pub SHOULD_IMPLEMENT_TRAIT,
+ style,
+ "defining a method that should be implementing a std trait"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for methods with certain name prefixes and which
+ /// doesn't match how self is taken. The actual rules are:
+ ///
+ /// |Prefix |`self` taken |
+ /// |-------|----------------------|
+ /// |`as_` |`&self` or `&mut self`|
+ /// |`from_`| none |
+ /// |`into_`|`self` |
+ /// |`is_` |`&self` or none |
+ /// |`to_` |`&self` |
+ ///
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # struct X;
+ /// impl X {
+ /// fn as_str(self) -> &'static str {
+ /// // ..
+ /// # ""
+ /// }
+ /// }
+ /// ```
+ pub WRONG_SELF_CONVENTION,
+ style,
+ "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** This is the same as
+ /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
+ ///
+ /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
+ ///
+ /// **Known problems:** Actually *renaming* the function may break clients if
+ /// the function is part of the public interface. In that case, be mindful of
+ /// the stability guarantees you've given your users.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # struct X;
+ /// impl<'a> X {
+ /// pub fn as_str(self) -> &'a str {
+ /// "foo"
+ /// }
+ /// }
+ /// ```
+ pub WRONG_PUB_SELF_CONVENTION,
+ restriction,
+ "defining a public method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ /// ```rust
+ /// # let x = Ok::<_, ()>(());
+ ///
+ /// // Bad
+ /// x.ok().expect("why did I do this again?");
+ ///
+ /// // Good
+ /// x.expect("why did I do this again?");
+ /// ```
+ pub OK_EXPECT,
+ style,
+ "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ /// ```rust
+ /// # let x = Some(1);
+ ///
+ /// // Bad
+ /// x.map(|a| a + 1).unwrap_or(0);
+ ///
+ /// // Good
+ /// x.map_or(0, |a| a + 1);
+ /// ```
+ ///
+ /// // or
+ ///
+ /// ```rust
+ /// # let x: Result<usize, ()> = Ok(1);
+ /// # fn some_function(foo: ()) -> usize { 1 }
+ ///
+ /// // Bad
+ /// x.map(|a| a + 1).unwrap_or_else(some_function);
+ ///
+ /// // Good
+ /// x.map_or_else(some_function, |a| a + 1);
+ /// ```
+ pub MAP_UNWRAP_OR,
+ pedantic,
+ "using `.map(f).unwrap_or(a)` or `.map(f).unwrap_or_else(func)`, which are more succinctly expressed as `map_or(a, f)` or `map_or_else(a, f)`"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ /// ```rust
+ /// # let opt = Some(1);
+ ///
+ /// // Bad
+ /// opt.map_or(None, |a| Some(a + 1));
+ ///
+ /// // Good
+ /// opt.and_then(|a| Some(a + 1));
+ /// ```
+ pub OPTION_MAP_OR_NONE,
+ style,
+ "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for usage of `_.map_or(None, Some)`.
+ ///
+ /// **Why is this bad?** Readability, this can be written more concisely as
+ /// `_.ok()`.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ ///
+ /// Bad:
+ /// ```rust
+ /// # let r: Result<u32, &str> = Ok(1);
+ /// assert_eq!(Some(1), r.map_or(None, Some));
+ /// ```
+ ///
+ /// Good:
+ /// ```rust
+ /// # let r: Result<u32, &str> = Ok(1);
+ /// assert_eq!(Some(1), r.ok());
+ /// ```
+ pub RESULT_MAP_OR_INTO_OPTION,
+ style,
+ "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
+}
+
+declare_clippy_lint! {
+ /// **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)`.
+ ///
+ /// **Known problems:** None
+ ///
+ /// **Example:**
+ ///
+ /// ```rust
+ /// # fn opt() -> Option<&'static str> { Some("42") }
+ /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
+ /// 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:
+ ///
+ /// ```rust
+ /// # fn opt() -> Option<&'static str> { Some("42") }
+ /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
+ /// 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 });
+ /// ```
+ pub BIND_INSTEAD_OF_MAP,
+ complexity,
+ "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for usage of `_.filter(_).next()`.
+ ///
+ /// **Why is this bad?** Readability, this can be written more concisely as
+ /// `_.find(_)`.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # let vec = vec![1];
+ /// vec.iter().filter(|x| **x == 0).next();
+ /// ```
+ /// Could be written as
+ /// ```rust
+ /// # let vec = vec![1];
+ /// vec.iter().find(|x| **x == 0);
+ /// ```
+ pub FILTER_NEXT,
+ complexity,
+ "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
+}
+
+declare_clippy_lint! {
+ /// **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)`.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # let vec = vec![1];
+ /// vec.iter().skip_while(|x| **x == 0).next();
+ /// ```
+ /// Could be written as
+ /// ```rust
+ /// # let vec = vec![1];
+ /// vec.iter().find(|x| **x != 0);
+ /// ```
+ pub SKIP_WHILE_NEXT,
+ complexity,
+ "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for usage of `_.map(_).flatten(_)`,
+ ///
+ /// **Why is this bad?** Readability, this can be written more concisely as a
+ /// single method call using `_.flat_map(_)`
+ ///
+ /// **Known problems:**
+ ///
+ /// **Example:**
+ /// ```rust
+ /// let vec = vec![vec![1]];
+ ///
+ /// // Bad
+ /// vec.iter().map(|x| x.iter()).flatten();
+ ///
+ /// // Good
+ /// vec.iter().flat_map(|x| x.iter());
+ /// ```
+ pub MAP_FLATTEN,
+ pedantic,
+ "using combinations of `flatten` and `map` which can usually be written as a single method call"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
+ /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
+ ///
+ /// **Why is this bad?** Readability, this can be written more concisely as a
+ /// single method call.
+ ///
+ /// **Known problems:** Often requires a condition + Option/Iterator creation
+ /// inside the closure.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// let vec = vec![1];
+ ///
+ /// // Bad
+ /// vec.iter().filter(|x| **x == 0).map(|x| *x * 2);
+ ///
+ /// // Good
+ /// vec.iter().filter_map(|x| if *x == 0 {
+ /// Some(*x * 2)
+ /// } else {
+ /// None
+ /// });
+ /// ```
+ pub FILTER_MAP,
+ pedantic,
+ "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can usually be written as a single method call"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for usage of `_.filter_map(_).next()`.
+ ///
+ /// **Why is this bad?** Readability, this can be written more concisely as a
+ /// single method call.
+ ///
+ /// **Known problems:** None
+ ///
+ /// **Example:**
+ /// ```rust
+ /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
+ /// ```
+ /// Can be written as
+ ///
+ /// ```rust
+ /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
+ /// ```
+ pub FILTER_MAP_NEXT,
+ pedantic,
+ "using combination of `filter_map` and `next` which can usually be written as a single method call"
+}
+
+declare_clippy_lint! {
+ /// **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`.
+ ///
+ /// **Known problems:** None
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # let iter = vec![vec![0]].into_iter();
+ /// iter.flat_map(|x| x);
+ /// ```
+ /// Can be written as
+ /// ```rust
+ /// # let iter = vec![vec![0]].into_iter();
+ /// iter.flatten();
+ /// ```
+ pub FLAT_MAP_IDENTITY,
+ complexity,
+ "call to `flat_map` where `flatten` is sufficient"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for usage of `_.find(_).map(_)`.
+ ///
+ /// **Why is this bad?** Readability, this can be written more concisely as a
+ /// single method call.
+ ///
+ /// **Known problems:** Often requires a condition + Option/Iterator creation
+ /// inside the closure.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// (0..3).find(|x| *x == 2).map(|x| x * 2);
+ /// ```
+ /// Can be written as
+ /// ```rust
+ /// (0..3).find_map(|x| if x == 2 { Some(x * 2) } else { None });
+ /// ```
+ pub FIND_MAP,
+ pedantic,
+ "using a combination of `find` and `map` can usually be written as a single method call"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for an iterator search (such as `find()`,
+ /// `position()`, or `rposition()`) followed by a call to `is_some()`.
+ ///
+ /// **Why is this bad?** Readability, this can be written more concisely as
+ /// `_.any(_)`.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # let vec = vec![1];
+ /// vec.iter().find(|x| **x == 0).is_some();
+ /// ```
+ /// Could be written as
+ /// ```rust
+ /// # let vec = vec![1];
+ /// vec.iter().any(|x| *x == 0);
+ /// ```
+ pub SEARCH_IS_SOME,
+ complexity,
+ "using an iterator search followed by `is_some()`, which is more succinctly expressed as a call to `any()`"
+}
+
+declare_clippy_lint! {
+ /// **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(_)`.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// let name = "foo";
+ /// if name.chars().next() == Some('_') {};
+ /// ```
+ /// Could be written as
+ /// ```rust
+ /// let name = "foo";
+ /// if name.starts_with('_') {};
+ /// ```
+ pub CHARS_NEXT_CMP,
+ style,
+ "using `.chars().next()` to check if a string starts with a char"
+}
+
+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.
+ ///
+ /// **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:**
+ /// ```rust
+ /// # let foo = Some(String::new());
+ /// foo.unwrap_or(String::new());
+ /// ```
+ /// this can instead be written:
+ /// ```rust
+ /// # let foo = Some(String::new());
+ /// foo.unwrap_or_else(String::new);
+ /// ```
+ /// or
+ /// ```rust
+ /// # let foo = Some(String::new());
+ /// foo.unwrap_or_default();
+ /// ```
+ pub OR_FUN_CALL,
+ perf,
+ "using any `*or` method with a function call, which suggests `*or_else`"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ /// ```rust
+ /// # let foo = Some(String::new());
+ /// # let err_code = "418";
+ /// # let err_msg = "I'm a teapot";
+ /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
+ /// ```
+ /// or
+ /// ```rust
+ /// # let foo = Some(String::new());
+ /// # let err_code = "418";
+ /// # let err_msg = "I'm a teapot";
+ /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
+ /// ```
+ /// this can instead be written:
+ /// ```rust
+ /// # let foo = Some(String::new());
+ /// # let err_code = "418";
+ /// # let err_msg = "I'm a teapot";
+ /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
+ /// ```
+ pub EXPECT_FUN_CALL,
+ perf,
+ "using any `expect` method with a function call"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// 42u64.clone();
+ /// ```
+ pub CLONE_ON_COPY,
+ complexity,
+ "using `clone` on a `Copy` type"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ /// ```rust
+ /// # use std::rc::Rc;
+ /// let x = Rc::new(1);
+ ///
+ /// // Bad
+ /// x.clone();
+ ///
+ /// // Good
+ /// Rc::clone(&x);
+ /// ```
+ pub CLONE_ON_REF_PTR,
+ restriction,
+ "using 'clone' on a ref-counted pointer"
+}
+
+declare_clippy_lint! {
+ /// **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`.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// fn main() {
+ /// let x = vec![1];
+ /// let y = &&x;
+ /// let z = y.clone();
+ /// println!("{:p} {:p}", *y, z); // prints out the same pointer
+ /// }
+ /// ```
+ pub CLONE_DOUBLE_REF,
+ correctness,
+ "using `clone` on `&&T`"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// // 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());
+ /// ```
+ pub INEFFICIENT_TO_STRING,
+ pedantic,
+ "using `to_string` on `&&T` where `T: ToString`"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// In an impl block:
+ /// ```rust
+ /// # struct Foo;
+ /// # struct NotAFoo;
+ /// impl Foo {
+ /// fn new() -> NotAFoo {
+ /// # NotAFoo
+ /// }
+ /// }
+ /// ```
+ ///
+ /// ```rust
+ /// # struct Foo;
+ /// struct Bar(Foo);
+ /// impl Foo {
+ /// // Bad. The type name must contain `Self`
+ /// fn new() -> Bar {
+ /// # Bar(Foo)
+ /// }
+ /// }
+ /// ```
+ ///
+ /// ```rust
+ /// # struct Foo;
+ /// # struct FooError;
+ /// impl Foo {
+ /// // Good. Return type contains `Self`
+ /// fn new() -> Result<Foo, FooError> {
+ /// # Ok(Foo)
+ /// }
+ /// }
+ /// ```
+ ///
+ /// Or in a trait definition:
+ /// ```rust
+ /// pub trait Trait {
+ /// // Bad. The type name must contain `Self`
+ /// fn new();
+ /// }
+ /// ```
+ ///
+ /// ```rust
+ /// pub trait Trait {
+ /// // Good. Return type contains `Self`
+ /// fn new() -> Self;
+ /// }
+ /// ```
+ pub NEW_RET_NO_SELF,
+ style,
+ "not returning type containing `Self` in a `new` method"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ /// ```rust,ignore
+ /// // Bad
+ /// _.split("x");
+ ///
+ /// // Good
+ /// _.split('x');
+ pub SINGLE_CHAR_PATTERN,
+ perf,
+ "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for getting the inner pointer of a temporary
+ /// `CString`.
+ ///
+ /// **Why is this bad?** The inner pointer of a `CString` is only valid as long
+ /// as the `CString` is alive.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # use std::ffi::CString;
+ /// # fn call_some_ffi_func(_: *const i8) {}
+ /// #
+ /// let c_str = CString::new("foo").unwrap().as_ptr();
+ /// unsafe {
+ /// call_some_ffi_func(c_str);
+ /// }
+ /// ```
+ /// Here `c_str` points to a freed address. The correct use would be:
+ /// ```rust
+ /// # use std::ffi::CString;
+ /// # fn call_some_ffi_func(_: *const i8) {}
+ /// #
+ /// let c_str = CString::new("foo").unwrap();
+ /// unsafe {
+ /// call_some_ffi_func(c_str.as_ptr());
+ /// }
+ /// ```
+ pub TEMPORARY_CSTRING_AS_PTR,
+ correctness,
+ "getting the inner pointer of a temporary `CString`"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust,should_panic
+ /// for x in (0..100).step_by(0) {
+ /// //..
+ /// }
+ /// ```
+ pub ITERATOR_STEP_BY_ZERO,
+ correctness,
+ "using `Iterator::step_by(0)`, which will panic at runtime"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ ///
+ /// ```rust
+ /// # use std::collections::HashSet;
+ /// // Bad
+ /// # let mut s = HashSet::new();
+ /// # s.insert(1);
+ /// let x = s.iter().nth(0);
+ ///
+ /// // Good
+ /// # let mut s = HashSet::new();
+ /// # s.insert(1);
+ /// let x = s.iter().next();
+ /// ```
+ pub ITER_NTH_ZERO,
+ style,
+ "replace `iter.nth(0)` with `iter.next()`"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// 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:
+ /// ```rust
+ /// let some_vec = vec![0, 1, 2, 3];
+ /// let bad_vec = some_vec.get(3);
+ /// let bad_slice = &some_vec[..].get(3);
+ /// ```
+ pub ITER_NTH,
+ perf,
+ "using `.iter().nth()` on a standard library type with O(1) element access"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
+ ///
+ /// **Why is this bad?** `.nth(x)` is cleaner
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// 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:
+ /// ```rust
+ /// let some_vec = vec![0, 1, 2, 3];
+ /// let bad_vec = some_vec.iter().nth(3);
+ /// let bad_slice = &some_vec[..].iter().nth(3);
+ /// ```
+ pub ITER_SKIP_NEXT,
+ style,
+ "using `.skip(x).next()` on an iterator"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ /// ```rust
+ /// 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:
+ /// ```rust
+ /// let mut some_vec = vec![0, 1, 2, 3];
+ /// let last = some_vec[3];
+ /// some_vec[0] = 1;
+ /// ```
+ pub GET_UNWRAP,
+ restriction,
+ "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
+}
+
+declare_clippy_lint! {
+ /// **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
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// 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:
+ /// ```rust
+ /// let abc = "abc";
+ /// let def = String::from("def");
+ /// let mut s = String::new();
+ /// s.push_str(abc);
+ /// s.push_str(&def);
+ /// ```
+ pub STRING_EXTEND_CHARS,
+ style,
+ "using `x.extend(s.chars())` where s is a `&str` or `String`"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
+ /// create a `Vec`.
+ ///
+ /// **Why is this bad?** `.to_vec()` is clearer
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// let s = [1, 2, 3, 4, 5];
+ /// let s2: Vec<isize> = s[..].iter().cloned().collect();
+ /// ```
+ /// The better use would be:
+ /// ```rust
+ /// let s = [1, 2, 3, 4, 5];
+ /// let s2: Vec<isize> = s.to_vec();
+ /// ```
+ pub ITER_CLONED_COLLECT,
+ style,
+ "using `.cloned().collect()` on slice to create a `Vec`"
+}
+
+declare_clippy_lint! {
+ /// **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(_)`.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # let name = "_";
+ ///
+ /// // Bad
+ /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
+ ///
+ /// // Good
+ /// name.ends_with('_') || name.ends_with('-');
+ /// ```
+ pub CHARS_LAST_CMP,
+ style,
+ "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # fn do_stuff(x: &[i32]) {}
+ /// let x: &[i32] = &[1, 2, 3, 4, 5];
+ /// do_stuff(x.as_ref());
+ /// ```
+ /// The correct use would be:
+ /// ```rust
+ /// # fn do_stuff(x: &[i32]) {}
+ /// let x: &[i32] = &[1, 2, 3, 4, 5];
+ /// do_stuff(x);
+ /// ```
+ pub USELESS_ASREF,
+ complexity,
+ "using `as_ref` where the types before and after the call are the same"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
+ /// ```
+ /// This could be written as:
+ /// ```rust
+ /// let _ = (0..3).any(|x| x > 2);
+ /// ```
+ pub UNNECESSARY_FOLD,
+ style,
+ "using `fold` when a more succinct alternative exists"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for `filter_map` calls which 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.
+ ///
+ /// **Known problems:** None
+ ///
+ /// **Example:**
+ /// ```rust
+ /// 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);
+ /// ```
+ ///
+ /// ```rust
+ /// 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);
+ /// ```
+ pub UNNECESSARY_FILTER_MAP,
+ complexity,
+ "using `filter_map` when a more succinct alternative exists"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None
+ ///
+ /// **Example:**
+ ///
+ /// ```rust
+ /// // Bad
+ /// let _ = (&vec![3, 4, 5]).into_iter();
+ ///
+ /// // Good
+ /// let _ = (&vec![3, 4, 5]).iter();
+ /// ```
+ pub INTO_ITER_ON_REF,
+ style,
+ "using `.into_iter()` on a reference"
+}
+
+declare_clippy_lint! {
+ /// **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. Or, if you intend to
+ /// drive the iterator to completion, you can just use `for_each` instead.
+ ///
+ /// **Known problems:** None
+ ///
+ /// **Example:**
+ ///
+ /// ```rust
+ /// let _ = (0..3).map(|x| x + 2).count();
+ /// ```
+ pub SUSPICIOUS_MAP,
+ complexity,
+ "suspicious usage of map"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ ///
+ /// ```rust
+ /// // Beware the UB
+ /// use std::mem::MaybeUninit;
+ ///
+ /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
+ /// ```
+ ///
+ /// Note that the following is OK:
+ ///
+ /// ```rust
+ /// use std::mem::MaybeUninit;
+ ///
+ /// let _: [MaybeUninit<bool>; 5] = unsafe {
+ /// MaybeUninit::uninit().assume_init()
+ /// };
+ /// ```
+ pub UNINIT_ASSUMED_INIT,
+ correctness,
+ "`MaybeUninit::uninit().assume_init()`"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ ///
+ /// ```rust
+ /// # let y: u32 = 0;
+ /// # let x: u32 = 100;
+ /// 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:
+ ///
+ /// ```rust
+ /// # let y: u32 = 0;
+ /// # let x: u32 = 100;
+ /// let add = x.saturating_add(y);
+ /// let sub = x.saturating_sub(y);
+ /// ```
+ pub MANUAL_SATURATING_ARITHMETIC,
+ style,
+ "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
+}
+
+declare_clippy_lint! {
+ /// **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
+ ///
+ /// **Known problems:** None
+ ///
+ /// **Example:**
+ /// ```rust
+ /// unsafe { (&() as *const ()).offset(1) };
+ /// ```
+ pub ZST_OFFSET,
+ correctness,
+ "Check for offset calculations on raw pointers to zero-sized types"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ ///
+ /// ```rust
+ /// # || {
+ /// let metadata = std::fs::metadata("foo.txt")?;
+ /// let filetype = metadata.file_type();
+ ///
+ /// if filetype.is_file() {
+ /// // read file
+ /// }
+ /// # Ok::<_, std::io::Error>(())
+ /// # };
+ /// ```
+ ///
+ /// should be written as:
+ ///
+ /// ```rust
+ /// # || {
+ /// let metadata = std::fs::metadata("foo.txt")?;
+ /// let filetype = metadata.file_type();
+ ///
+ /// if !filetype.is_dir() {
+ /// // read file
+ /// }
+ /// # Ok::<_, std::io::Error>(())
+ /// # };
+ /// ```
+ pub FILETYPE_IS_FILE,
+ restriction,
+ "`FileType::is_file` is not recommended to test for readable file type"
+}
+
+declare_clippy_lint! {
+ /// **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 a
+ /// single method call.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # let opt = Some("".to_string());
+ /// opt.as_ref().map(String::as_str)
+ /// # ;
+ /// ```
+ /// Can be written as
+ /// ```rust
+ /// # let opt = Some("".to_string());
+ /// opt.as_deref()
+ /// # ;
+ /// ```
+ pub OPTION_AS_REF_DEREF,
+ complexity,
+ "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
+}
+
+declare_clippy_lint! {
+ /// **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()`
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # let a = [1, 2, 3];
+ /// # let b = vec![1, 2, 3];
+ /// a[2..].iter().next();
+ /// b.iter().next();
+ /// ```
+ /// should be written as:
+ /// ```rust
+ /// # let a = [1, 2, 3];
+ /// # let b = vec![1, 2, 3];
+ /// a.get(2);
+ /// b.get(0);
+ /// ```
+ pub ITER_NEXT_SLICE,
+ style,
+ "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
+}
+
+declare_clippy_lint! {
- /// **Why is this bad?** It's less clear that we are pushing a single character
++ /// **What it does:** Warns when using `push_str` with a single-character string literal,
++ /// and `push` with a `char` would work fine.
+ ///
- /// ```
++ /// **Why is this bad?** It's less clear that we are pushing a single character.
+ ///
+ /// **Known problems:** None
+ ///
+ /// **Example:**
- /// ```
++ /// ```rust
+ /// let mut string = String::new();
+ /// string.push_str("R");
+ /// ```
+ /// Could be written as
++ /// ```rust
+ /// let mut string = String::new();
+ /// string.push('R');
+ /// ```
+ pub SINGLE_CHAR_PUSH_STR,
+ style,
+ "`push_str()` used with a single-character string literal as parameter"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ ///
+ /// ```rust
+ /// // example code where clippy issues a warning
+ /// let opt: Option<u32> = None;
+ ///
+ /// opt.unwrap_or_else(|| 42);
+ /// ```
+ /// Use instead:
+ /// ```rust
+ /// let opt: Option<u32> = None;
+ ///
+ /// opt.unwrap_or(42);
+ /// ```
+ pub UNNECESSARY_LAZY_EVALUATIONS,
+ style,
+ "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
+}
+
+declare_lint_pass!(Methods => [
+ UNWRAP_USED,
+ EXPECT_USED,
+ SHOULD_IMPLEMENT_TRAIT,
+ WRONG_SELF_CONVENTION,
+ WRONG_PUB_SELF_CONVENTION,
+ OK_EXPECT,
+ MAP_UNWRAP_OR,
+ RESULT_MAP_OR_INTO_OPTION,
+ OPTION_MAP_OR_NONE,
+ BIND_INSTEAD_OF_MAP,
+ OR_FUN_CALL,
+ EXPECT_FUN_CALL,
+ CHARS_NEXT_CMP,
+ CHARS_LAST_CMP,
+ CLONE_ON_COPY,
+ CLONE_ON_REF_PTR,
+ CLONE_DOUBLE_REF,
+ INEFFICIENT_TO_STRING,
+ NEW_RET_NO_SELF,
+ SINGLE_CHAR_PATTERN,
+ SINGLE_CHAR_PUSH_STR,
+ SEARCH_IS_SOME,
+ TEMPORARY_CSTRING_AS_PTR,
+ FILTER_NEXT,
+ SKIP_WHILE_NEXT,
+ FILTER_MAP,
+ FILTER_MAP_NEXT,
+ FLAT_MAP_IDENTITY,
+ FIND_MAP,
+ MAP_FLATTEN,
+ ITERATOR_STEP_BY_ZERO,
+ ITER_NEXT_SLICE,
+ ITER_NTH,
+ ITER_NTH_ZERO,
+ ITER_SKIP_NEXT,
+ GET_UNWRAP,
+ STRING_EXTEND_CHARS,
+ ITER_CLONED_COLLECT,
+ USELESS_ASREF,
+ UNNECESSARY_FOLD,
+ UNNECESSARY_FILTER_MAP,
+ INTO_ITER_ON_REF,
+ SUSPICIOUS_MAP,
+ UNINIT_ASSUMED_INIT,
+ MANUAL_SATURATING_ARITHMETIC,
+ ZST_OFFSET,
+ FILETYPE_IS_FILE,
+ OPTION_AS_REF_DEREF,
+ UNNECESSARY_LAZY_EVALUATIONS,
+]);
+
+impl<'tcx> LateLintPass<'tcx> for Methods {
+ #[allow(clippy::too_many_lines)]
+ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
+ if in_macro(expr.span) {
+ return;
+ }
+
+ let (method_names, arg_lists, method_spans) = method_calls(expr, 2);
+ let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
+ let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
+
+ match method_names.as_slice() {
+ ["unwrap", "get"] => lint_get_unwrap(cx, expr, arg_lists[1], false),
+ ["unwrap", "get_mut"] => lint_get_unwrap(cx, expr, arg_lists[1], true),
+ ["unwrap", ..] => lint_unwrap(cx, expr, arg_lists[0]),
+ ["expect", "ok"] => lint_ok_expect(cx, expr, arg_lists[1]),
+ ["expect", ..] => lint_expect(cx, expr, arg_lists[0]),
+ ["unwrap_or", "map"] => option_map_unwrap_or::lint(cx, expr, arg_lists[1], arg_lists[0], method_spans[1]),
+ ["unwrap_or_else", "map"] => {
+ if !lint_map_unwrap_or_else(cx, expr, arg_lists[1], arg_lists[0]) {
+ unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], true, "unwrap_or");
+ }
+ },
+ ["map_or", ..] => lint_map_or_none(cx, expr, arg_lists[0]),
+ ["and_then", ..] => {
+ unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], false, "and");
+ bind_instead_of_map::OptionAndThenSome::lint(cx, expr, arg_lists[0]);
+ bind_instead_of_map::ResultAndThenOk::lint(cx, expr, arg_lists[0]);
+ },
+ ["or_else", ..] => {
+ unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], false, "or");
+ bind_instead_of_map::ResultOrElseErrInfo::lint(cx, expr, arg_lists[0]);
+ },
+ ["next", "filter"] => lint_filter_next(cx, expr, arg_lists[1]),
+ ["next", "skip_while"] => lint_skip_while_next(cx, expr, arg_lists[1]),
+ ["next", "iter"] => lint_iter_next(cx, expr, arg_lists[1]),
+ ["map", "filter"] => lint_filter_map(cx, expr, arg_lists[1], arg_lists[0]),
+ ["map", "filter_map"] => lint_filter_map_map(cx, expr, arg_lists[1], arg_lists[0]),
+ ["next", "filter_map"] => lint_filter_map_next(cx, expr, arg_lists[1]),
+ ["map", "find"] => lint_find_map(cx, expr, arg_lists[1], arg_lists[0]),
+ ["flat_map", "filter"] => lint_filter_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
+ ["flat_map", "filter_map"] => lint_filter_map_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
+ ["flat_map", ..] => lint_flat_map_identity(cx, expr, arg_lists[0], method_spans[0]),
+ ["flatten", "map"] => lint_map_flatten(cx, expr, arg_lists[1]),
+ ["is_some", "find"] => lint_search_is_some(cx, expr, "find", arg_lists[1], arg_lists[0], method_spans[1]),
+ ["is_some", "position"] => {
+ lint_search_is_some(cx, expr, "position", arg_lists[1], arg_lists[0], method_spans[1])
+ },
+ ["is_some", "rposition"] => {
+ lint_search_is_some(cx, expr, "rposition", arg_lists[1], arg_lists[0], method_spans[1])
+ },
+ ["extend", ..] => lint_extend(cx, expr, arg_lists[0]),
+ ["as_ptr", "unwrap" | "expect"] => lint_cstring_as_ptr(cx, expr, &arg_lists[1][0], &arg_lists[0][0]),
+ ["nth", "iter"] => lint_iter_nth(cx, expr, &arg_lists, false),
+ ["nth", "iter_mut"] => lint_iter_nth(cx, expr, &arg_lists, true),
+ ["nth", ..] => lint_iter_nth_zero(cx, expr, arg_lists[0]),
+ ["step_by", ..] => lint_step_by(cx, expr, arg_lists[0]),
+ ["next", "skip"] => lint_iter_skip_next(cx, expr, arg_lists[1]),
+ ["collect", "cloned"] => lint_iter_cloned_collect(cx, expr, arg_lists[1]),
+ ["as_ref"] => lint_asref(cx, expr, "as_ref", arg_lists[0]),
+ ["as_mut"] => lint_asref(cx, expr, "as_mut", arg_lists[0]),
+ ["fold", ..] => lint_unnecessary_fold(cx, expr, arg_lists[0], method_spans[0]),
+ ["filter_map", ..] => unnecessary_filter_map::lint(cx, expr, arg_lists[0]),
+ ["count", "map"] => lint_suspicious_map(cx, expr),
+ ["assume_init"] => lint_maybe_uninit(cx, &arg_lists[0][0], expr),
+ ["unwrap_or", arith @ ("checked_add" | "checked_sub" | "checked_mul")] => {
+ manual_saturating_arithmetic::lint(cx, expr, &arg_lists, &arith["checked_".len()..])
+ },
+ ["add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub"] => {
+ check_pointer_offset(cx, expr, arg_lists[0])
+ },
+ ["is_file", ..] => lint_filetype_is_file(cx, expr, arg_lists[0]),
+ ["map", "as_ref"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], false),
+ ["map", "as_mut"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], true),
+ ["unwrap_or_else", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], true, "unwrap_or"),
+ ["get_or_insert_with", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], true, "get_or_insert"),
+ ["ok_or_else", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], true, "ok_or"),
+ _ => {},
+ }
+
+ match expr.kind {
+ hir::ExprKind::MethodCall(ref method_call, ref method_span, ref args, _) => {
+ lint_or_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
+ lint_expect_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
+
+ let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0]);
+ if args.len() == 1 && method_call.ident.name == sym!(clone) {
+ lint_clone_on_copy(cx, expr, &args[0], self_ty);
+ lint_clone_on_ref_ptr(cx, expr, &args[0]);
+ }
+ if args.len() == 1 && method_call.ident.name == sym!(to_string) {
+ inefficient_to_string::lint(cx, expr, &args[0], self_ty);
+ }
+
+ if let Some(fn_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) {
+ if match_def_path(cx, fn_def_id, &paths::PUSH_STR) {
+ lint_single_char_push_string(cx, expr, args);
+ }
+ }
+
+ match self_ty.kind() {
+ ty::Ref(_, ty, _) if *ty.kind() == ty::Str => {
+ for &(method, pos) in &PATTERN_METHODS {
+ if method_call.ident.name.as_str() == method && args.len() > pos {
+ lint_single_char_pattern(cx, expr, &args[pos]);
+ }
+ }
+ },
+ ty::Ref(..) if method_call.ident.name == sym!(into_iter) => {
+ lint_into_iter(cx, expr, self_ty, *method_span);
+ },
+ _ => (),
+ }
+ },
+ hir::ExprKind::Binary(op, ref lhs, ref rhs)
+ if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne =>
+ {
+ let mut info = BinaryExprInfo {
+ expr,
+ chain: lhs,
+ other: rhs,
+ eq: op.node == hir::BinOpKind::Eq,
+ };
+ lint_binary_expr_with_method_call(cx, &mut info);
+ }
+ _ => (),
+ }
+ }
+
+ #[allow(clippy::too_many_lines)]
+ fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
+ if in_external_macro(cx.sess(), impl_item.span) {
+ return;
+ }
+ let name = impl_item.ident.name.as_str();
+ let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id);
+ let item = cx.tcx.hir().expect_item(parent);
+ let def_id = cx.tcx.hir().local_def_id(item.hir_id);
+ let self_ty = cx.tcx.type_of(def_id);
+ if_chain! {
+ 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();
+ if let hir::ItemKind::Impl{ of_trait: None, .. } = item.kind;
+
+ let method_def_id = cx.tcx.hir().local_def_id(impl_item.hir_id);
+ let method_sig = cx.tcx.fn_sig(method_def_id);
+ let method_sig = cx.tcx.erase_late_bound_regions(&method_sig);
+
+ let first_arg_ty = &method_sig.inputs().iter().next();
+
+ // check conventions w.r.t. conversion method names and predicates
+ if let Some(first_arg_ty) = first_arg_ty;
+
+ then {
+ if cx.access_levels.is_exported(impl_item.hir_id) {
+ // check missing trait implementations
+ for method_config in &TRAIT_METHODS {
+ if name == method_config.method_name &&
+ sig.decl.inputs.len() == method_config.param_count &&
+ method_config.output_type.matches(cx, &sig.decl.output) &&
+ method_config.self_kind.matches(cx, self_ty, first_arg_ty) &&
+ fn_header_equals(method_config.fn_header, sig.header) &&
+ method_config.lifetime_param_cond(&impl_item)
+ {
+ span_lint_and_help(
+ cx,
+ SHOULD_IMPLEMENT_TRAIT,
+ impl_item.span,
+ &format!(
+ "method `{}` can be confused for the standard trait method `{}::{}`",
+ method_config.method_name,
+ method_config.trait_name,
+ method_config.method_name
+ ),
+ None,
+ &format!(
+ "consider implementing the trait `{}` or choosing a less ambiguous method name",
+ method_config.trait_name
+ )
+ );
+ }
+ }
+ }
+
+ if let Some((ref conv, self_kinds)) = &CONVENTIONS
+ .iter()
+ .find(|(ref conv, _)| conv.check(&name))
+ {
+ if !self_kinds.iter().any(|k| k.matches(cx, self_ty, first_arg_ty)) {
+ let lint = if item.vis.node.is_pub() {
+ WRONG_PUB_SELF_CONVENTION
+ } else {
+ WRONG_SELF_CONVENTION
+ };
+
+ span_lint(
+ cx,
+ lint,
+ first_arg.pat.span,
+ &format!("methods called `{}` usually take {}; consider choosing a less ambiguous name",
+ conv,
+ &self_kinds
+ .iter()
+ .map(|k| k.description())
+ .collect::<Vec<_>>()
+ .join(" or ")
+ ),
+ );
+ }
+ }
+ }
+ }
+
+ // if this impl block implements a trait, lint in trait definition instead
+ if let hir::ItemKind::Impl { of_trait: Some(_), .. } = item.kind {
+ return;
+ }
+
+ if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
+ let ret_ty = return_ty(cx, impl_item.hir_id);
+
+ // walk the return type and check for Self (this does not check associated types)
+ if contains_ty(ret_ty, self_ty) {
+ return;
+ }
+
+ // if return type is impl trait, check the associated types
+ if let ty::Opaque(def_id, _) = *ret_ty.kind() {
+ // one of the associated types must be Self
+ for &(predicate, _span) in cx.tcx.predicates_of(def_id).predicates {
+ if let ty::PredicateAtom::Projection(projection_predicate) = predicate.skip_binders() {
+ // walk the associated type and check for Self
+ if contains_ty(projection_predicate.ty, self_ty) {
+ return;
+ }
+ }
+ }
+ }
+
+ if name == "new" && !TyS::same_type(ret_ty, self_ty) {
+ span_lint(
+ cx,
+ NEW_RET_NO_SELF,
+ impl_item.span,
+ "methods called `new` usually return `Self`",
+ );
+ }
+ }
+ }
+
+ fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
+ if_chain! {
+ if !in_external_macro(cx.tcx.sess, item.span);
+ if item.ident.name == sym!(new);
+ if let TraitItemKind::Fn(_, _) = item.kind;
+ let ret_ty = return_ty(cx, item.hir_id);
+ let self_ty = TraitRef::identity(cx.tcx, item.hir_id.owner.to_def_id()).self_ty();
+ if !contains_ty(ret_ty, self_ty);
+
+ then {
+ span_lint(
+ cx,
+ NEW_RET_NO_SELF,
+ item.span,
+ "methods called `new` usually return `Self`",
+ );
+ }
+ }
+ }
+}
+
+/// Checks for the `OR_FUN_CALL` lint.
+#[allow(clippy::too_many_lines)]
+fn lint_or_fun_call<'tcx>(
+ cx: &LateContext<'tcx>,
+ expr: &hir::Expr<'_>,
+ method_span: Span,
+ name: &str,
+ args: &'tcx [hir::Expr<'_>],
+) {
+ // Searches an expression for method calls or function calls that aren't ctors
+ struct FunCallFinder<'a, 'tcx> {
+ cx: &'a LateContext<'tcx>,
+ found: bool,
+ }
+
+ impl<'a, 'tcx> intravisit::Visitor<'tcx> for FunCallFinder<'a, 'tcx> {
+ type Map = Map<'tcx>;
+
+ fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
+ let call_found = match &expr.kind {
+ // ignore enum and struct constructors
+ hir::ExprKind::Call(..) => !is_ctor_or_promotable_const_function(self.cx, expr),
+ hir::ExprKind::MethodCall(..) => true,
+ _ => false,
+ };
+
+ if call_found {
+ self.found |= true;
+ }
+
+ if !self.found {
+ intravisit::walk_expr(self, expr);
+ }
+ }
+
+ fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
+ intravisit::NestedVisitorMap::None
+ }
+ }
+
+ /// Checks for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
+ fn check_unwrap_or_default(
+ cx: &LateContext<'_>,
+ name: &str,
+ fun: &hir::Expr<'_>,
+ self_expr: &hir::Expr<'_>,
+ arg: &hir::Expr<'_>,
+ or_has_args: bool,
+ span: Span,
+ ) -> bool {
+ if_chain! {
+ if !or_has_args;
+ if name == "unwrap_or";
+ if let hir::ExprKind::Path(ref qpath) = fun.kind;
+ let path = &*last_path_segment(qpath).ident.as_str();
+ if ["default", "new"].contains(&path);
+ let arg_ty = cx.typeck_results().expr_ty(arg);
+ if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
+ if implements_trait(cx, arg_ty, default_trait_id, &[]);
+
+ then {
+ let mut applicability = Applicability::MachineApplicable;
+ span_lint_and_sugg(
+ cx,
+ OR_FUN_CALL,
+ span,
+ &format!("use of `{}` followed by a call to `{}`", name, path),
+ "try this",
+ format!(
+ "{}.unwrap_or_default()",
+ snippet_with_applicability(cx, self_expr.span, "_", &mut applicability)
+ ),
+ applicability,
+ );
+
+ true
+ } else {
+ false
+ }
+ }
+ }
+
+ /// Checks for `*or(foo())`.
+ #[allow(clippy::too_many_arguments)]
+ fn check_general_case<'tcx>(
+ cx: &LateContext<'tcx>,
+ name: &str,
+ method_span: Span,
+ fun_span: Span,
+ self_expr: &hir::Expr<'_>,
+ arg: &'tcx hir::Expr<'_>,
+ or_has_args: bool,
+ span: Span,
+ ) {
+ if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = &arg.kind {
+ if path.ident.as_str() == "len" {
+ let ty = walk_ptrs_ty(cx.typeck_results().expr_ty(&args[0]));
+
+ match ty.kind() {
+ ty::Slice(_) | ty::Array(_, _) => return,
+ _ => (),
+ }
+
+ if match_type(cx, ty, &paths::VEC) {
+ return;
+ }
+ }
+ }
+
+ // (path, fn_has_argument, methods, suffix)
+ let know_types: &[(&[_], _, &[_], _)] = &[
+ (&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"),
+ (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
+ ];
+
+ if_chain! {
+ if know_types.iter().any(|k| k.2.contains(&name));
+
+ let mut finder = FunCallFinder { cx: &cx, found: false };
+ if { finder.visit_expr(&arg); finder.found };
+ if !contains_return(&arg);
+
+ let self_ty = cx.typeck_results().expr_ty(self_expr);
+
+ if let Some(&(_, fn_has_arguments, poss, suffix)) =
+ know_types.iter().find(|&&i| match_type(cx, self_ty, i.0));
+
+ if poss.contains(&name);
+
+ then {
+ let sugg: Cow<'_, _> = match (fn_has_arguments, !or_has_args) {
+ (true, _) => format!("|_| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
+ (false, false) => format!("|| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
+ (false, true) => snippet_with_macro_callsite(cx, fun_span, ".."),
+ };
+ let span_replace_word = method_span.with_hi(span.hi());
+ span_lint_and_sugg(
+ cx,
+ OR_FUN_CALL,
+ span_replace_word,
+ &format!("use of `{}` followed by a function call", name),
+ "try this",
+ format!("{}_{}({})", name, suffix, sugg),
+ Applicability::HasPlaceholders,
+ );
+ }
+ }
+ }
+
+ if args.len() == 2 {
+ match args[1].kind {
+ hir::ExprKind::Call(ref fun, ref or_args) => {
+ let or_has_args = !or_args.is_empty();
+ if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
+ check_general_case(
+ cx,
+ name,
+ method_span,
+ fun.span,
+ &args[0],
+ &args[1],
+ or_has_args,
+ expr.span,
+ );
+ }
+ },
+ hir::ExprKind::MethodCall(_, span, ref or_args, _) => check_general_case(
+ cx,
+ name,
+ method_span,
+ span,
+ &args[0],
+ &args[1],
+ !or_args.is_empty(),
+ expr.span,
+ ),
+ _ => {},
+ }
+ }
+}
+
+/// Checks for the `EXPECT_FUN_CALL` lint.
+#[allow(clippy::too_many_lines)]
+fn lint_expect_fun_call(
+ cx: &LateContext<'_>,
+ expr: &hir::Expr<'_>,
+ method_span: Span,
+ name: &str,
+ args: &[hir::Expr<'_>],
+) {
+ // Strip `&`, `as_ref()` and `as_str()` off `arg` until we're left with either a `String` or
+ // `&str`
+ fn get_arg_root<'a>(cx: &LateContext<'_>, arg: &'a hir::Expr<'a>) -> &'a hir::Expr<'a> {
+ let mut arg_root = arg;
+ loop {
+ arg_root = match &arg_root.kind {
+ hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => expr,
+ hir::ExprKind::MethodCall(method_name, _, call_args, _) => {
+ if call_args.len() == 1
+ && (method_name.ident.name == sym!(as_str) || method_name.ident.name == sym!(as_ref))
+ && {
+ let arg_type = cx.typeck_results().expr_ty(&call_args[0]);
+ let base_type = walk_ptrs_ty(arg_type);
+ *base_type.kind() == ty::Str || is_type_diagnostic_item(cx, base_type, sym!(string_type))
+ }
+ {
+ &call_args[0]
+ } else {
+ break;
+ }
+ },
+ _ => break,
+ };
+ }
+ arg_root
+ }
+
+ // Only `&'static str` or `String` can be used directly in the `panic!`. Other types should be
+ // converted to string.
+ fn requires_to_string(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool {
+ let arg_ty = cx.typeck_results().expr_ty(arg);
+ if is_type_diagnostic_item(cx, arg_ty, sym!(string_type)) {
+ return false;
+ }
+ if let ty::Ref(_, ty, ..) = arg_ty.kind() {
+ if *ty.kind() == ty::Str && can_be_static_str(cx, arg) {
+ return false;
+ }
+ };
+ true
+ }
+
+ // Check if an expression could have type `&'static str`, knowing that it
+ // has type `&str` for some lifetime.
+ fn can_be_static_str(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool {
+ match arg.kind {
+ hir::ExprKind::Lit(_) => true,
+ hir::ExprKind::Call(fun, _) => {
+ if let hir::ExprKind::Path(ref p) = fun.kind {
+ match cx.qpath_res(p, fun.hir_id) {
+ hir::def::Res::Def(hir::def::DefKind::Fn | hir::def::DefKind::AssocFn, def_id) => matches!(
+ cx.tcx.fn_sig(def_id).output().skip_binder().kind(),
+ ty::Ref(ty::ReStatic, ..)
+ ),
+ _ => false,
+ }
+ } else {
+ false
+ }
+ },
+ hir::ExprKind::MethodCall(..) => {
+ cx.typeck_results()
+ .type_dependent_def_id(arg.hir_id)
+ .map_or(false, |method_id| {
+ matches!(
+ cx.tcx.fn_sig(method_id).output().skip_binder().kind(),
+ ty::Ref(ty::ReStatic, ..)
+ )
+ })
+ },
+ hir::ExprKind::Path(ref p) => matches!(
+ cx.qpath_res(p, arg.hir_id),
+ hir::def::Res::Def(hir::def::DefKind::Const | hir::def::DefKind::Static, _)
+ ),
+ _ => false,
+ }
+ }
+
+ fn generate_format_arg_snippet(
+ cx: &LateContext<'_>,
+ a: &hir::Expr<'_>,
+ applicability: &mut Applicability,
+ ) -> Vec<String> {
+ if_chain! {
+ if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref format_arg) = a.kind;
+ if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.kind;
+ if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.kind;
+
+ then {
+ format_arg_expr_tup
+ .iter()
+ .map(|a| snippet_with_applicability(cx, a.span, "..", applicability).into_owned())
+ .collect()
+ } else {
+ unreachable!()
+ }
+ }
+ }
+
+ fn is_call(node: &hir::ExprKind<'_>) -> bool {
+ match node {
+ hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => {
+ is_call(&expr.kind)
+ },
+ hir::ExprKind::Call(..)
+ | hir::ExprKind::MethodCall(..)
+ // These variants are debatable or require further examination
+ | hir::ExprKind::Match(..)
+ | hir::ExprKind::Block{ .. } => true,
+ _ => false,
+ }
+ }
+
+ if args.len() != 2 || name != "expect" || !is_call(&args[1].kind) {
+ return;
+ }
+
+ let receiver_type = cx.typeck_results().expr_ty_adjusted(&args[0]);
+ let closure_args = if is_type_diagnostic_item(cx, receiver_type, sym!(option_type)) {
+ "||"
+ } else if is_type_diagnostic_item(cx, receiver_type, sym!(result_type)) {
+ "|_|"
+ } else {
+ return;
+ };
+
+ let arg_root = get_arg_root(cx, &args[1]);
+
+ let span_replace_word = method_span.with_hi(expr.span.hi());
+
+ let mut applicability = Applicability::MachineApplicable;
+
+ //Special handling for `format!` as arg_root
+ if_chain! {
+ if let hir::ExprKind::Block(block, None) = &arg_root.kind;
+ if block.stmts.len() == 1;
+ if let hir::StmtKind::Local(local) = &block.stmts[0].kind;
+ if let Some(arg_root) = &local.init;
+ if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = arg_root.kind;
+ if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1;
+ if let hir::ExprKind::Call(_, format_args) = &inner_args[0].kind;
+ then {
+ let fmt_spec = &format_args[0];
+ let fmt_args = &format_args[1];
+
+ let mut args = vec![snippet(cx, fmt_spec.span, "..").into_owned()];
+
+ args.extend(generate_format_arg_snippet(cx, fmt_args, &mut applicability));
+
+ let sugg = args.join(", ");
+
+ span_lint_and_sugg(
+ cx,
+ EXPECT_FUN_CALL,
+ span_replace_word,
+ &format!("use of `{}` followed by a function call", name),
+ "try this",
+ format!("unwrap_or_else({} panic!({}))", closure_args, sugg),
+ applicability,
+ );
+
+ return;
+ }
+ }
+
+ let mut arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability);
+ if requires_to_string(cx, arg_root) {
+ arg_root_snippet.to_mut().push_str(".to_string()");
+ }
+
+ span_lint_and_sugg(
+ cx,
+ EXPECT_FUN_CALL,
+ span_replace_word,
+ &format!("use of `{}` followed by a function call", name),
+ "try this",
+ format!("unwrap_or_else({} {{ panic!({}) }})", closure_args, arg_root_snippet),
+ applicability,
+ );
+}
+
+/// Checks for the `CLONE_ON_COPY` lint.
+fn lint_clone_on_copy(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>, arg_ty: Ty<'_>) {
+ let ty = cx.typeck_results().expr_ty(expr);
+ if let ty::Ref(_, inner, _) = arg_ty.kind() {
+ if let ty::Ref(_, innermost, _) = inner.kind() {
+ span_lint_and_then(
+ cx,
+ CLONE_DOUBLE_REF,
+ expr.span,
+ "using `clone` on a double-reference; \
+ this will copy the reference instead of cloning the inner type",
+ |diag| {
+ if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
+ let mut ty = innermost;
+ let mut n = 0;
+ while let ty::Ref(_, inner, _) = ty.kind() {
+ ty = inner;
+ n += 1;
+ }
+ let refs: String = iter::repeat('&').take(n + 1).collect();
+ let derefs: String = iter::repeat('*').take(n).collect();
+ let explicit = format!("<{}{}>::clone({})", refs, ty, snip);
+ diag.span_suggestion(
+ expr.span,
+ "try dereferencing it",
+ format!("{}({}{}).clone()", refs, derefs, snip.deref()),
+ Applicability::MaybeIncorrect,
+ );
+ diag.span_suggestion(
+ expr.span,
+ "or try being explicit if you are sure, that you want to clone a reference",
+ explicit,
+ Applicability::MaybeIncorrect,
+ );
+ }
+ },
+ );
+ return; // don't report clone_on_copy
+ }
+ }
+
+ if is_copy(cx, ty) {
+ let snip;
+ if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
+ let parent = cx.tcx.hir().get_parent_node(expr.hir_id);
+ match &cx.tcx.hir().get(parent) {
+ hir::Node::Expr(parent) => match parent.kind {
+ // &*x is a nop, &x.clone() is not
+ hir::ExprKind::AddrOf(..) => return,
+ // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
+ hir::ExprKind::MethodCall(_, _, parent_args, _) if expr.hir_id == parent_args[0].hir_id => {
+ return;
+ },
+
+ _ => {},
+ },
+ hir::Node::Stmt(stmt) => {
+ if let hir::StmtKind::Local(ref loc) = stmt.kind {
+ if let hir::PatKind::Ref(..) = loc.pat.kind {
+ // let ref y = *x borrows x, let ref y = x.clone() does not
+ return;
+ }
+ }
+ },
+ _ => {},
+ }
+
+ // x.clone() might have dereferenced x, possibly through Deref impls
+ if cx.typeck_results().expr_ty(arg) == ty {
+ snip = Some(("try removing the `clone` call", format!("{}", snippet)));
+ } else {
+ let deref_count = cx
+ .typeck_results()
+ .expr_adjustments(arg)
+ .iter()
+ .filter(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
+ .count();
+ let derefs: String = iter::repeat('*').take(deref_count).collect();
+ snip = Some(("try dereferencing it", format!("{}{}", derefs, snippet)));
+ }
+ } else {
+ snip = None;
+ }
+ span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |diag| {
+ if let Some((text, snip)) = snip {
+ diag.span_suggestion(expr.span, text, snip, Applicability::MachineApplicable);
+ }
+ });
+ }
+}
+
+fn lint_clone_on_ref_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
+ let obj_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(arg));
+
+ if let ty::Adt(_, subst) = obj_ty.kind() {
+ let caller_type = if is_type_diagnostic_item(cx, obj_ty, sym::Rc) {
+ "Rc"
+ } else if is_type_diagnostic_item(cx, obj_ty, sym::Arc) {
+ "Arc"
+ } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
+ "Weak"
+ } else {
+ return;
+ };
+
+ let snippet = snippet_with_macro_callsite(cx, arg.span, "_");
+
+ span_lint_and_sugg(
+ cx,
+ CLONE_ON_REF_PTR,
+ expr.span,
+ "using `.clone()` on a ref-counted pointer",
+ "try this",
+ format!("{}::<{}>::clone(&{})", caller_type, subst.type_at(0), snippet),
+ Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
+ );
+ }
+}
+
+fn lint_string_extend(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
+ let arg = &args[1];
+ if let Some(arglists) = method_chain_args(arg, &["chars"]) {
+ let target = &arglists[0][0];
+ let self_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(target));
+ let ref_str = if *self_ty.kind() == ty::Str {
+ ""
+ } else if is_type_diagnostic_item(cx, self_ty, sym!(string_type)) {
+ "&"
+ } else {
+ return;
+ };
+
+ let mut applicability = Applicability::MachineApplicable;
+ span_lint_and_sugg(
+ cx,
+ STRING_EXTEND_CHARS,
+ expr.span,
+ "calling `.extend(_.chars())`",
+ "try this",
+ format!(
+ "{}.push_str({}{})",
+ snippet_with_applicability(cx, args[0].span, "_", &mut applicability),
+ ref_str,
+ snippet_with_applicability(cx, target.span, "_", &mut applicability)
+ ),
+ applicability,
+ );
+ }
+}
+
+fn lint_extend(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
+ let obj_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(&args[0]));
+ if is_type_diagnostic_item(cx, obj_ty, sym!(string_type)) {
+ lint_string_extend(cx, expr, args);
+ }
+}
+
+fn lint_cstring_as_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, source: &hir::Expr<'_>, unwrap: &hir::Expr<'_>) {
+ if_chain! {
+ let source_type = cx.typeck_results().expr_ty(source);
+ if let ty::Adt(def, substs) = source_type.kind();
+ if cx.tcx.is_diagnostic_item(sym!(result_type), def.did);
+ if match_type(cx, substs.type_at(0), &paths::CSTRING);
+ then {
+ span_lint_and_then(
+ cx,
+ TEMPORARY_CSTRING_AS_PTR,
+ expr.span,
+ "you are getting the inner pointer of a temporary `CString`",
+ |diag| {
+ diag.note("that pointer will be invalid outside this expression");
+ diag.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
+ });
+ }
+ }
+}
+
+fn lint_iter_cloned_collect<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, iter_args: &'tcx [hir::Expr<'_>]) {
+ if_chain! {
+ if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym!(vec_type));
+ if let Some(slice) = derefs_to_slice(cx, &iter_args[0], cx.typeck_results().expr_ty(&iter_args[0]));
+ if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite());
+
+ then {
+ span_lint_and_sugg(
+ cx,
+ ITER_CLONED_COLLECT,
+ to_replace,
+ "called `iter().cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
+ more readable",
+ "try",
+ ".to_vec()".to_string(),
+ Applicability::MachineApplicable,
+ );
+ }
+ }
+}
+
+fn lint_unnecessary_fold(cx: &LateContext<'_>, expr: &hir::Expr<'_>, fold_args: &[hir::Expr<'_>], fold_span: Span) {
+ fn check_fold_with_op(
+ cx: &LateContext<'_>,
+ expr: &hir::Expr<'_>,
+ fold_args: &[hir::Expr<'_>],
+ fold_span: Span,
+ op: hir::BinOpKind,
+ replacement_method_name: &str,
+ replacement_has_args: bool,
+ ) {
+ if_chain! {
+ // Extract the body of the closure passed to fold
+ if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].kind;
+ let closure_body = cx.tcx.hir().body(body_id);
+ let closure_expr = remove_blocks(&closure_body.value);
+
+ // Check if the closure body is of the form `acc <op> some_expr(x)`
+ if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.kind;
+ if bin_op.node == op;
+
+ // Extract the names of the two arguments to the closure
+ if let Some(first_arg_ident) = get_arg_name(&closure_body.params[0].pat);
+ if let Some(second_arg_ident) = get_arg_name(&closure_body.params[1].pat);
+
+ if match_var(&*left_expr, first_arg_ident);
+ if replacement_has_args || match_var(&*right_expr, second_arg_ident);
+
+ then {
+ let mut applicability = Applicability::MachineApplicable;
+ let sugg = if replacement_has_args {
+ format!(
+ "{replacement}(|{s}| {r})",
+ replacement = replacement_method_name,
+ s = second_arg_ident,
+ r = snippet_with_applicability(cx, right_expr.span, "EXPR", &mut applicability),
+ )
+ } else {
+ format!(
+ "{replacement}()",
+ replacement = replacement_method_name,
+ )
+ };
+
+ span_lint_and_sugg(
+ cx,
+ UNNECESSARY_FOLD,
+ fold_span.with_hi(expr.span.hi()),
+ // TODO #2371 don't suggest e.g., .any(|x| f(x)) if we can suggest .any(f)
+ "this `.fold` can be written more succinctly using another method",
+ "try",
+ sugg,
+ applicability,
+ );
+ }
+ }
+ }
+
+ // Check that this is a call to Iterator::fold rather than just some function called fold
+ if !match_trait_method(cx, expr, &paths::ITERATOR) {
+ return;
+ }
+
+ assert!(
+ fold_args.len() == 3,
+ "Expected fold_args to have three entries - the receiver, the initial value and the closure"
+ );
+
+ // Check if the first argument to .fold is a suitable literal
+ if let hir::ExprKind::Lit(ref lit) = fold_args[1].kind {
+ match lit.node {
+ ast::LitKind::Bool(false) => {
+ check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Or, "any", true)
+ },
+ ast::LitKind::Bool(true) => {
+ check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::And, "all", true)
+ },
+ ast::LitKind::Int(0, _) => {
+ check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Add, "sum", false)
+ },
+ ast::LitKind::Int(1, _) => {
+ check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Mul, "product", false)
+ },
+ _ => (),
+ }
+ }
+}
+
+fn lint_step_by<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, args: &'tcx [hir::Expr<'_>]) {
+ if match_trait_method(cx, expr, &paths::ITERATOR) {
+ if let Some((Constant::Int(0), _)) = constant(cx, cx.typeck_results(), &args[1]) {
+ span_lint(
+ cx,
+ ITERATOR_STEP_BY_ZERO,
+ expr.span,
+ "Iterator::step_by(0) will panic at runtime",
+ );
+ }
+ }
+}
+
+fn lint_iter_next<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, iter_args: &'tcx [hir::Expr<'_>]) {
+ let caller_expr = &iter_args[0];
+
+ // Skip lint if the `iter().next()` expression is a for loop argument,
+ // since it is already covered by `&loops::ITER_NEXT_LOOP`
+ let mut parent_expr_opt = get_parent_expr(cx, expr);
+ while let Some(parent_expr) = parent_expr_opt {
+ if higher::for_loop(parent_expr).is_some() {
+ return;
+ }
+ parent_expr_opt = get_parent_expr(cx, parent_expr);
+ }
+
+ if derefs_to_slice(cx, caller_expr, cx.typeck_results().expr_ty(caller_expr)).is_some() {
+ // caller is a Slice
+ if_chain! {
+ if let hir::ExprKind::Index(ref caller_var, ref index_expr) = &caller_expr.kind;
+ if let Some(higher::Range { start: Some(start_expr), end: None, limits: ast::RangeLimits::HalfOpen })
+ = higher::range(index_expr);
+ if let hir::ExprKind::Lit(ref start_lit) = &start_expr.kind;
+ if let ast::LitKind::Int(start_idx, _) = start_lit.node;
+ then {
+ let mut applicability = Applicability::MachineApplicable;
+ span_lint_and_sugg(
+ cx,
+ ITER_NEXT_SLICE,
+ expr.span,
+ "using `.iter().next()` on a Slice without end index",
+ "try calling",
+ format!("{}.get({})", snippet_with_applicability(cx, caller_var.span, "..", &mut applicability), start_idx),
+ applicability,
+ );
+ }
+ }
+ } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(caller_expr), sym!(vec_type))
+ || matches!(
+ &walk_ptrs_ty(cx.typeck_results().expr_ty(caller_expr)).kind(),
+ ty::Array(_, _)
+ )
+ {
+ // caller is a Vec or an Array
+ let mut applicability = Applicability::MachineApplicable;
+ span_lint_and_sugg(
+ cx,
+ ITER_NEXT_SLICE,
+ expr.span,
+ "using `.iter().next()` on an array",
+ "try calling",
+ format!(
+ "{}.get(0)",
+ snippet_with_applicability(cx, caller_expr.span, "..", &mut applicability)
+ ),
+ applicability,
+ );
+ }
+}
+
+fn lint_iter_nth<'tcx>(
+ cx: &LateContext<'tcx>,
+ expr: &hir::Expr<'_>,
+ nth_and_iter_args: &[&'tcx [hir::Expr<'tcx>]],
+ is_mut: bool,
+) {
+ let iter_args = nth_and_iter_args[1];
+ let mut_str = if is_mut { "_mut" } else { "" };
+ let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.typeck_results().expr_ty(&iter_args[0])).is_some() {
+ "slice"
+ } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&iter_args[0]), sym!(vec_type)) {
+ "Vec"
+ } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&iter_args[0]), sym!(vecdeque_type)) {
+ "VecDeque"
+ } else {
+ let nth_args = nth_and_iter_args[0];
+ lint_iter_nth_zero(cx, expr, &nth_args);
+ return; // caller is not a type that we want to lint
+ };
+
+ span_lint_and_help(
+ cx,
+ ITER_NTH,
+ expr.span,
+ &format!("called `.iter{0}().nth()` on a {1}", mut_str, caller_type),
+ None,
+ &format!("calling `.get{}()` is both faster and more readable", mut_str),
+ );
+}
+
+fn lint_iter_nth_zero<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, nth_args: &'tcx [hir::Expr<'_>]) {
+ if_chain! {
+ if match_trait_method(cx, expr, &paths::ITERATOR);
+ if let Some((Constant::Int(0), _)) = constant(cx, cx.typeck_results(), &nth_args[1]);
+ then {
+ let mut applicability = Applicability::MachineApplicable;
+ span_lint_and_sugg(
+ cx,
+ ITER_NTH_ZERO,
+ expr.span,
+ "called `.nth(0)` on a `std::iter::Iterator`, when `.next()` is equivalent",
+ "try calling `.next()` instead of `.nth(0)`",
+ format!("{}.next()", snippet_with_applicability(cx, nth_args[0].span, "..", &mut applicability)),
+ applicability,
+ );
+ }
+ }
+}
+
+fn lint_get_unwrap<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, get_args: &'tcx [hir::Expr<'_>], is_mut: bool) {
+ // Note: we don't want to lint `get_mut().unwrap` for `HashMap` or `BTreeMap`,
+ // because they do not implement `IndexMut`
+ let mut applicability = Applicability::MachineApplicable;
+ let expr_ty = cx.typeck_results().expr_ty(&get_args[0]);
+ let get_args_str = if get_args.len() > 1 {
+ snippet_with_applicability(cx, get_args[1].span, "_", &mut applicability)
+ } else {
+ return; // not linting on a .get().unwrap() chain or variant
+ };
+ let mut needs_ref;
+ let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
+ needs_ref = get_args_str.parse::<usize>().is_ok();
+ "slice"
+ } else if is_type_diagnostic_item(cx, expr_ty, sym!(vec_type)) {
+ needs_ref = get_args_str.parse::<usize>().is_ok();
+ "Vec"
+ } else if is_type_diagnostic_item(cx, expr_ty, sym!(vecdeque_type)) {
+ needs_ref = get_args_str.parse::<usize>().is_ok();
+ "VecDeque"
+ } else if !is_mut && is_type_diagnostic_item(cx, expr_ty, sym!(hashmap_type)) {
+ needs_ref = true;
+ "HashMap"
+ } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
+ needs_ref = true;
+ "BTreeMap"
+ } else {
+ return; // caller is not a type that we want to lint
+ };
+
+ let mut span = expr.span;
+
+ // Handle the case where the result is immediately dereferenced
+ // by not requiring ref and pulling the dereference into the
+ // suggestion.
+ if_chain! {
+ if needs_ref;
+ if let Some(parent) = get_parent_expr(cx, expr);
+ if let hir::ExprKind::Unary(hir::UnOp::UnDeref, _) = parent.kind;
+ then {
+ needs_ref = false;
+ span = parent.span;
+ }
+ }
+
+ let mut_str = if is_mut { "_mut" } else { "" };
+ let borrow_str = if !needs_ref {
+ ""
+ } else if is_mut {
+ "&mut "
+ } else {
+ "&"
+ };
+
+ span_lint_and_sugg(
+ cx,
+ GET_UNWRAP,
+ span,
+ &format!(
+ "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
+ mut_str, caller_type
+ ),
+ "try this",
+ format!(
+ "{}{}[{}]",
+ borrow_str,
+ snippet_with_applicability(cx, get_args[0].span, "_", &mut applicability),
+ get_args_str
+ ),
+ applicability,
+ );
+}
+
+fn lint_iter_skip_next(cx: &LateContext<'_>, expr: &hir::Expr<'_>, skip_args: &[hir::Expr<'_>]) {
+ // lint if caller of skip is an Iterator
+ if match_trait_method(cx, expr, &paths::ITERATOR) {
+ if let [caller, n] = skip_args {
+ let hint = format!(".nth({})", snippet(cx, n.span, ".."));
+ span_lint_and_sugg(
+ cx,
+ ITER_SKIP_NEXT,
+ expr.span.trim_start(caller.span).unwrap(),
+ "called `skip(x).next()` on an iterator",
+ "use `nth` instead",
+ hint,
+ Applicability::MachineApplicable,
+ );
+ }
+ }
+}
+
+fn derefs_to_slice<'tcx>(
+ cx: &LateContext<'tcx>,
+ expr: &'tcx hir::Expr<'tcx>,
+ ty: Ty<'tcx>,
+) -> Option<&'tcx hir::Expr<'tcx>> {
+ fn may_slice<'a>(cx: &LateContext<'a>, ty: Ty<'a>) -> bool {
+ match ty.kind() {
+ ty::Slice(_) => true,
+ ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
+ ty::Adt(..) => is_type_diagnostic_item(cx, ty, sym!(vec_type)),
+ ty::Array(_, size) => size
+ .try_eval_usize(cx.tcx, cx.param_env)
+ .map_or(false, |size| size < 32),
+ ty::Ref(_, inner, _) => may_slice(cx, inner),
+ _ => false,
+ }
+ }
+
+ if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind {
+ if path.ident.name == sym!(iter) && may_slice(cx, cx.typeck_results().expr_ty(&args[0])) {
+ Some(&args[0])
+ } else {
+ None
+ }
+ } else {
+ match ty.kind() {
+ ty::Slice(_) => Some(expr),
+ ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr),
+ ty::Ref(_, inner, _) => {
+ if may_slice(cx, inner) {
+ Some(expr)
+ } else {
+ None
+ }
+ },
+ _ => None,
+ }
+ }
+}
+
+/// lint use of `unwrap()` for `Option`s and `Result`s
+fn lint_unwrap(cx: &LateContext<'_>, expr: &hir::Expr<'_>, unwrap_args: &[hir::Expr<'_>]) {
+ let obj_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(&unwrap_args[0]));
+
+ let mess = if is_type_diagnostic_item(cx, obj_ty, sym!(option_type)) {
+ Some((UNWRAP_USED, "an Option", "None"))
+ } else if is_type_diagnostic_item(cx, obj_ty, sym!(result_type)) {
+ Some((UNWRAP_USED, "a Result", "Err"))
+ } else {
+ None
+ };
+
+ if let Some((lint, kind, none_value)) = mess {
+ span_lint_and_help(
+ cx,
+ lint,
+ expr.span,
+ &format!("used `unwrap()` on `{}` value", kind,),
+ None,
+ &format!(
+ "if you don't want to handle the `{}` case gracefully, consider \
+ using `expect()` to provide a better panic message",
+ none_value,
+ ),
+ );
+ }
+}
+
+/// lint use of `expect()` for `Option`s and `Result`s
+fn lint_expect(cx: &LateContext<'_>, expr: &hir::Expr<'_>, expect_args: &[hir::Expr<'_>]) {
+ let obj_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(&expect_args[0]));
+
+ let mess = if is_type_diagnostic_item(cx, obj_ty, sym!(option_type)) {
+ Some((EXPECT_USED, "an Option", "None"))
+ } else if is_type_diagnostic_item(cx, obj_ty, sym!(result_type)) {
+ Some((EXPECT_USED, "a Result", "Err"))
+ } else {
+ None
+ };
+
+ if let Some((lint, kind, none_value)) = mess {
+ span_lint_and_help(
+ cx,
+ lint,
+ expr.span,
+ &format!("used `expect()` on `{}` value", kind,),
+ None,
+ &format!("if this value is an `{}`, it will panic", none_value,),
+ );
+ }
+}
+
+/// lint use of `ok().expect()` for `Result`s
+fn lint_ok_expect(cx: &LateContext<'_>, expr: &hir::Expr<'_>, ok_args: &[hir::Expr<'_>]) {
+ if_chain! {
+ // lint if the caller of `ok()` is a `Result`
+ if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&ok_args[0]), sym!(result_type));
+ let result_type = cx.typeck_results().expr_ty(&ok_args[0]);
+ if let Some(error_type) = get_error_type(cx, result_type);
+ if has_debug_impl(error_type, cx);
+
+ then {
+ span_lint_and_help(
+ cx,
+ OK_EXPECT,
+ expr.span,
+ "called `ok().expect()` on a `Result` value",
+ None,
+ "you can call `expect()` directly on the `Result`",
+ );
+ }
+ }
+}
+
+/// lint use of `map().flatten()` for `Iterators` and 'Options'
+fn lint_map_flatten<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map_args: &'tcx [hir::Expr<'_>]) {
+ // lint if caller of `.map().flatten()` is an Iterator
+ if match_trait_method(cx, expr, &paths::ITERATOR) {
+ let map_closure_ty = cx.typeck_results().expr_ty(&map_args[1]);
+ let is_map_to_option = match map_closure_ty.kind() {
+ ty::Closure(_, _) | ty::FnDef(_, _) | ty::FnPtr(_) => {
+ let map_closure_sig = match map_closure_ty.kind() {
+ ty::Closure(_, substs) => substs.as_closure().sig(),
+ _ => map_closure_ty.fn_sig(cx.tcx),
+ };
+ let map_closure_return_ty = cx.tcx.erase_late_bound_regions(&map_closure_sig.output());
+ is_type_diagnostic_item(cx, map_closure_return_ty, sym!(option_type))
+ },
+ _ => false,
+ };
+
+ let method_to_use = if is_map_to_option {
+ // `(...).map(...)` has type `impl Iterator<Item=Option<...>>
+ "filter_map"
+ } else {
+ // `(...).map(...)` has type `impl Iterator<Item=impl Iterator<...>>
+ "flat_map"
+ };
+ let func_snippet = snippet(cx, map_args[1].span, "..");
+ let hint = format!(".{0}({1})", method_to_use, func_snippet);
+ span_lint_and_sugg(
+ cx,
+ MAP_FLATTEN,
+ expr.span.with_lo(map_args[0].span.hi()),
+ "called `map(..).flatten()` on an `Iterator`",
+ &format!("try using `{}` instead", method_to_use),
+ hint,
+ Applicability::MachineApplicable,
+ );
+ }
+
+ // lint if caller of `.map().flatten()` is an Option
+ if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym!(option_type)) {
+ let func_snippet = snippet(cx, map_args[1].span, "..");
+ let hint = format!(".and_then({})", func_snippet);
+ span_lint_and_sugg(
+ cx,
+ MAP_FLATTEN,
+ expr.span.with_lo(map_args[0].span.hi()),
+ "called `map(..).flatten()` on an `Option`",
+ "try using `and_then` instead",
+ hint,
+ Applicability::MachineApplicable,
+ );
+ }
+}
+
+/// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
+/// Return true if lint triggered
+fn lint_map_unwrap_or_else<'tcx>(
+ cx: &LateContext<'tcx>,
+ expr: &'tcx hir::Expr<'_>,
+ map_args: &'tcx [hir::Expr<'_>],
+ unwrap_args: &'tcx [hir::Expr<'_>],
+) -> bool {
+ // lint if the caller of `map()` is an `Option`
+ let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym!(option_type));
+ let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym!(result_type));
+
+ if is_option || is_result {
+ // Don't make a suggestion that may fail to compile due to mutably borrowing
+ // the same variable twice.
+ let map_mutated_vars = mutated_variables(&map_args[0], cx);
+ let unwrap_mutated_vars = mutated_variables(&unwrap_args[1], cx);
+ if let (Some(map_mutated_vars), Some(unwrap_mutated_vars)) = (map_mutated_vars, unwrap_mutated_vars) {
+ if map_mutated_vars.intersection(&unwrap_mutated_vars).next().is_some() {
+ return false;
+ }
+ } else {
+ return false;
+ }
+
+ // lint message
+ let msg = if is_option {
+ "called `map(f).unwrap_or_else(g)` on an `Option` value. This can be done more directly by calling \
+ `map_or_else(g, f)` instead"
+ } else {
+ "called `map(f).unwrap_or_else(g)` on a `Result` value. This can be done more directly by calling \
+ `.map_or_else(g, f)` instead"
+ };
+ // get snippets for args to map() and unwrap_or_else()
+ let map_snippet = snippet(cx, map_args[1].span, "..");
+ let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
+ // lint, with note if neither arg is > 1 line and both map() and
+ // unwrap_or_else() have the same span
+ let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
+ let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
+ if same_span && !multiline {
+ span_lint_and_note(
+ cx,
+ MAP_UNWRAP_OR,
+ expr.span,
+ msg,
+ None,
+ &format!(
+ "replace `map({0}).unwrap_or_else({1})` with `map_or_else({1}, {0})`",
+ map_snippet, unwrap_snippet,
+ ),
+ );
+ return true;
+ } else if same_span && multiline {
+ span_lint(cx, MAP_UNWRAP_OR, expr.span, msg);
+ return true;
+ }
+ }
+
+ false
+}
+
+/// lint use of `_.map_or(None, _)` for `Option`s and `Result`s
+fn lint_map_or_none<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map_or_args: &'tcx [hir::Expr<'_>]) {
+ let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_or_args[0]), sym!(option_type));
+ let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_or_args[0]), sym!(result_type));
+
+ // There are two variants of this `map_or` lint:
+ // (1) using `map_or` as an adapter from `Result<T,E>` to `Option<T>`
+ // (2) using `map_or` as a combinator instead of `and_then`
+ //
+ // (For this lint) we don't care if any other type calls `map_or`
+ if !is_option && !is_result {
+ return;
+ }
+
+ let (lint_name, msg, instead, hint) = {
+ let default_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].kind {
+ match_qpath(qpath, &paths::OPTION_NONE)
+ } else {
+ return;
+ };
+
+ if !default_arg_is_none {
+ // nothing to lint!
+ return;
+ }
+
+ let f_arg_is_some = if let hir::ExprKind::Path(ref qpath) = map_or_args[2].kind {
+ match_qpath(qpath, &paths::OPTION_SOME)
+ } else {
+ false
+ };
+
+ if is_option {
+ let self_snippet = snippet(cx, map_or_args[0].span, "..");
+ let func_snippet = snippet(cx, map_or_args[2].span, "..");
+ let msg = "called `map_or(None, f)` on an `Option` value. This can be done more directly by calling \
+ `and_then(f)` instead";
+ (
+ OPTION_MAP_OR_NONE,
+ msg,
+ "try using `and_then` instead",
+ format!("{0}.and_then({1})", self_snippet, func_snippet),
+ )
+ } else if f_arg_is_some {
+ let msg = "called `map_or(None, Some)` on a `Result` value. This can be done more directly by calling \
+ `ok()` instead";
+ let self_snippet = snippet(cx, map_or_args[0].span, "..");
+ (
+ RESULT_MAP_OR_INTO_OPTION,
+ msg,
+ "try using `ok` instead",
+ format!("{0}.ok()", self_snippet),
+ )
+ } else {
+ // nothing to lint!
+ return;
+ }
+ };
+
+ span_lint_and_sugg(
+ cx,
+ lint_name,
+ expr.span,
+ msg,
+ instead,
+ hint,
+ Applicability::MachineApplicable,
+ );
+}
+
+/// lint use of `filter().next()` for `Iterators`
+fn lint_filter_next<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, filter_args: &'tcx [hir::Expr<'_>]) {
+ // lint if caller of `.filter().next()` is an Iterator
+ if match_trait_method(cx, expr, &paths::ITERATOR) {
+ let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
+ `.find(p)` instead.";
+ let filter_snippet = snippet(cx, filter_args[1].span, "..");
+ if filter_snippet.lines().count() <= 1 {
+ // add note if not multi-line
+ span_lint_and_note(
+ cx,
+ FILTER_NEXT,
+ expr.span,
+ msg,
+ None,
+ &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
+ );
+ } else {
+ span_lint(cx, FILTER_NEXT, expr.span, msg);
+ }
+ }
+}
+
+/// lint use of `skip_while().next()` for `Iterators`
+fn lint_skip_while_next<'tcx>(
+ cx: &LateContext<'tcx>,
+ expr: &'tcx hir::Expr<'_>,
+ _skip_while_args: &'tcx [hir::Expr<'_>],
+) {
+ // lint if caller of `.skip_while().next()` is an Iterator
+ if match_trait_method(cx, expr, &paths::ITERATOR) {
+ span_lint_and_help(
+ cx,
+ SKIP_WHILE_NEXT,
+ expr.span,
+ "called `skip_while(p).next()` on an `Iterator`",
+ None,
+ "this is more succinctly expressed by calling `.find(!p)` instead",
+ );
+ }
+}
+
+/// lint use of `filter().map()` for `Iterators`
+fn lint_filter_map<'tcx>(
+ cx: &LateContext<'tcx>,
+ expr: &'tcx hir::Expr<'_>,
+ _filter_args: &'tcx [hir::Expr<'_>],
+ _map_args: &'tcx [hir::Expr<'_>],
+) {
+ // lint if caller of `.filter().map()` is an Iterator
+ if match_trait_method(cx, expr, &paths::ITERATOR) {
+ let msg = "called `filter(p).map(q)` on an `Iterator`";
+ let hint = "this is more succinctly expressed by calling `.filter_map(..)` instead";
+ span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
+ }
+}
+
+/// lint use of `filter_map().next()` for `Iterators`
+fn lint_filter_map_next<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, filter_args: &'tcx [hir::Expr<'_>]) {
+ if match_trait_method(cx, expr, &paths::ITERATOR) {
+ let msg = "called `filter_map(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
+ `.find_map(p)` instead.";
+ let filter_snippet = snippet(cx, filter_args[1].span, "..");
+ if filter_snippet.lines().count() <= 1 {
+ span_lint_and_note(
+ cx,
+ FILTER_MAP_NEXT,
+ expr.span,
+ msg,
+ None,
+ &format!("replace `filter_map({0}).next()` with `find_map({0})`", filter_snippet),
+ );
+ } else {
+ span_lint(cx, FILTER_MAP_NEXT, expr.span, msg);
+ }
+ }
+}
+
+/// lint use of `find().map()` for `Iterators`
+fn lint_find_map<'tcx>(
+ cx: &LateContext<'tcx>,
+ expr: &'tcx hir::Expr<'_>,
+ _find_args: &'tcx [hir::Expr<'_>],
+ map_args: &'tcx [hir::Expr<'_>],
+) {
+ // lint if caller of `.filter().map()` is an Iterator
+ if match_trait_method(cx, &map_args[0], &paths::ITERATOR) {
+ let msg = "called `find(p).map(q)` on an `Iterator`";
+ let hint = "this is more succinctly expressed by calling `.find_map(..)` instead";
+ span_lint_and_help(cx, FIND_MAP, expr.span, msg, None, hint);
+ }
+}
+
+/// lint use of `filter_map().map()` for `Iterators`
+fn lint_filter_map_map<'tcx>(
+ cx: &LateContext<'tcx>,
+ expr: &'tcx hir::Expr<'_>,
+ _filter_args: &'tcx [hir::Expr<'_>],
+ _map_args: &'tcx [hir::Expr<'_>],
+) {
+ // lint if caller of `.filter().map()` is an Iterator
+ if match_trait_method(cx, expr, &paths::ITERATOR) {
+ let msg = "called `filter_map(p).map(q)` on an `Iterator`";
+ let hint = "this is more succinctly expressed by only calling `.filter_map(..)` instead";
+ span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
+ }
+}
+
+/// lint use of `filter().flat_map()` for `Iterators`
+fn lint_filter_flat_map<'tcx>(
+ cx: &LateContext<'tcx>,
+ expr: &'tcx hir::Expr<'_>,
+ _filter_args: &'tcx [hir::Expr<'_>],
+ _map_args: &'tcx [hir::Expr<'_>],
+) {
+ // lint if caller of `.filter().flat_map()` is an Iterator
+ if match_trait_method(cx, expr, &paths::ITERATOR) {
+ let msg = "called `filter(p).flat_map(q)` on an `Iterator`";
+ let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
+ and filtering by returning `iter::empty()`";
+ span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
+ }
+}
+
+/// lint use of `filter_map().flat_map()` for `Iterators`
+fn lint_filter_map_flat_map<'tcx>(
+ cx: &LateContext<'tcx>,
+ expr: &'tcx hir::Expr<'_>,
+ _filter_args: &'tcx [hir::Expr<'_>],
+ _map_args: &'tcx [hir::Expr<'_>],
+) {
+ // lint if caller of `.filter_map().flat_map()` is an Iterator
+ if match_trait_method(cx, expr, &paths::ITERATOR) {
+ let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`";
+ let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
+ and filtering by returning `iter::empty()`";
+ span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
+ }
+}
+
+/// lint use of `flat_map` for `Iterators` where `flatten` would be sufficient
+fn lint_flat_map_identity<'tcx>(
+ cx: &LateContext<'tcx>,
+ expr: &'tcx hir::Expr<'_>,
+ flat_map_args: &'tcx [hir::Expr<'_>],
+ flat_map_span: Span,
+) {
+ if match_trait_method(cx, expr, &paths::ITERATOR) {
+ let arg_node = &flat_map_args[1].kind;
+
+ let apply_lint = |message: &str| {
+ span_lint_and_sugg(
+ cx,
+ FLAT_MAP_IDENTITY,
+ flat_map_span.with_hi(expr.span.hi()),
+ message,
+ "try",
+ "flatten()".to_string(),
+ Applicability::MachineApplicable,
+ );
+ };
+
+ if_chain! {
+ if let hir::ExprKind::Closure(_, _, body_id, _, _) = arg_node;
+ let body = cx.tcx.hir().body(*body_id);
+
+ if let hir::PatKind::Binding(_, _, binding_ident, _) = body.params[0].pat.kind;
+ if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = body.value.kind;
+
+ if path.segments.len() == 1;
+ if path.segments[0].ident.as_str() == binding_ident.as_str();
+
+ then {
+ apply_lint("called `flat_map(|x| x)` on an `Iterator`");
+ }
+ }
+
+ if_chain! {
+ if let hir::ExprKind::Path(ref qpath) = arg_node;
+
+ if match_qpath(qpath, &paths::STD_CONVERT_IDENTITY);
+
+ then {
+ apply_lint("called `flat_map(std::convert::identity)` on an `Iterator`");
+ }
+ }
+ }
+}
+
+/// lint searching an Iterator followed by `is_some()`
+fn lint_search_is_some<'tcx>(
+ cx: &LateContext<'tcx>,
+ expr: &'tcx hir::Expr<'_>,
+ search_method: &str,
+ search_args: &'tcx [hir::Expr<'_>],
+ is_some_args: &'tcx [hir::Expr<'_>],
+ method_span: Span,
+) {
+ // lint if caller of search is an Iterator
+ if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
+ let msg = format!(
+ "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
+ expressed by calling `any()`.",
+ search_method
+ );
+ let search_snippet = snippet(cx, search_args[1].span, "..");
+ if search_snippet.lines().count() <= 1 {
+ // suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()`
+ // suggest `any(|..| *..)` instead of `any(|..| **..)` for `find(|..| **..).is_some()`
+ let any_search_snippet = if_chain! {
+ if search_method == "find";
+ if let hir::ExprKind::Closure(_, _, body_id, ..) = search_args[1].kind;
+ let closure_body = cx.tcx.hir().body(body_id);
+ if let Some(closure_arg) = closure_body.params.get(0);
+ then {
+ if let hir::PatKind::Ref(..) = closure_arg.pat.kind {
+ Some(search_snippet.replacen('&', "", 1))
+ } else if let Some(name) = get_arg_name(&closure_arg.pat) {
+ Some(search_snippet.replace(&format!("*{}", name), &name.as_str()))
+ } else {
+ None
+ }
+ } else {
+ None
+ }
+ };
+ // add note if not multi-line
+ span_lint_and_sugg(
+ cx,
+ SEARCH_IS_SOME,
+ method_span.with_hi(expr.span.hi()),
+ &msg,
+ "try this",
+ format!(
+ "any({})",
+ any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
+ ),
+ Applicability::MachineApplicable,
+ );
+ } else {
+ span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
+ }
+ }
+}
+
+/// Used for `lint_binary_expr_with_method_call`.
+#[derive(Copy, Clone)]
+struct BinaryExprInfo<'a> {
+ expr: &'a hir::Expr<'a>,
+ chain: &'a hir::Expr<'a>,
+ other: &'a hir::Expr<'a>,
+ eq: bool,
+}
+
+/// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
+fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
+ macro_rules! lint_with_both_lhs_and_rhs {
+ ($func:ident, $cx:expr, $info:ident) => {
+ if !$func($cx, $info) {
+ ::std::mem::swap(&mut $info.chain, &mut $info.other);
+ if $func($cx, $info) {
+ return;
+ }
+ }
+ };
+ }
+
+ lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
+ lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
+ lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
+ lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
+}
+
+/// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
+fn lint_chars_cmp(
+ cx: &LateContext<'_>,
+ info: &BinaryExprInfo<'_>,
+ chain_methods: &[&str],
+ lint: &'static Lint,
+ suggest: &str,
+) -> bool {
+ if_chain! {
+ if let Some(args) = method_chain_args(info.chain, chain_methods);
+ if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.kind;
+ if arg_char.len() == 1;
+ if let hir::ExprKind::Path(ref qpath) = fun.kind;
+ if let Some(segment) = single_segment_path(qpath);
+ if segment.ident.name == sym!(Some);
+ then {
+ let mut applicability = Applicability::MachineApplicable;
+ let self_ty = walk_ptrs_ty(cx.typeck_results().expr_ty_adjusted(&args[0][0]));
+
+ if *self_ty.kind() != ty::Str {
+ return false;
+ }
+
+ span_lint_and_sugg(
+ cx,
+ lint,
+ info.expr.span,
+ &format!("you should use the `{}` method", suggest),
+ "like this",
+ format!("{}{}.{}({})",
+ if info.eq { "" } else { "!" },
+ snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
+ suggest,
+ snippet_with_applicability(cx, arg_char[0].span, "_", &mut applicability)),
+ applicability,
+ );
+
+ return true;
+ }
+ }
+
+ false
+}
+
+/// Checks for the `CHARS_NEXT_CMP` lint.
+fn lint_chars_next_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
+ lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
+}
+
+/// Checks for the `CHARS_LAST_CMP` lint.
+fn lint_chars_last_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
+ if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_LAST_CMP, "ends_with") {
+ true
+ } else {
+ lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_LAST_CMP, "ends_with")
+ }
+}
+
+/// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
+fn lint_chars_cmp_with_unwrap<'tcx>(
+ cx: &LateContext<'tcx>,
+ info: &BinaryExprInfo<'_>,
+ chain_methods: &[&str],
+ lint: &'static Lint,
+ suggest: &str,
+) -> bool {
+ if_chain! {
+ if let Some(args) = method_chain_args(info.chain, chain_methods);
+ if let hir::ExprKind::Lit(ref lit) = info.other.kind;
+ if let ast::LitKind::Char(c) = lit.node;
+ then {
+ let mut applicability = Applicability::MachineApplicable;
+ span_lint_and_sugg(
+ cx,
+ lint,
+ info.expr.span,
+ &format!("you should use the `{}` method", suggest),
+ "like this",
+ format!("{}{}.{}('{}')",
+ if info.eq { "" } else { "!" },
+ snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
+ suggest,
+ c),
+ applicability,
+ );
+
+ true
+ } else {
+ false
+ }
+ }
+}
+
+/// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
+fn lint_chars_next_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
+ lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
+}
+
+/// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
+fn lint_chars_last_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
+ if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
+ true
+ } else {
+ lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
+ }
+}
+
+fn get_hint_if_single_char_arg(
+ cx: &LateContext<'_>,
+ arg: &hir::Expr<'_>,
+ applicability: &mut Applicability,
+) -> Option<String> {
+ if_chain! {
+ if let hir::ExprKind::Lit(lit) = &arg.kind;
+ if let ast::LitKind::Str(r, style) = lit.node;
+ let string = r.as_str();
+ if string.len() == 1;
+ then {
+ let snip = snippet_with_applicability(cx, arg.span, &string, applicability);
+ let ch = if let ast::StrStyle::Raw(nhash) = style {
+ let nhash = nhash as usize;
+ // for raw string: r##"a"##
+ &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
+ } else {
+ // for regular string: "a"
+ &snip[1..(snip.len() - 1)]
+ };
+ let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });
+ Some(hint)
+ } else {
+ None
+ }
+ }
+}
+
+/// lint for length-1 `str`s for methods in `PATTERN_METHODS`
+fn lint_single_char_pattern(cx: &LateContext<'_>, _expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
+ let mut applicability = Applicability::MachineApplicable;
+ if let Some(hint) = get_hint_if_single_char_arg(cx, arg, &mut applicability) {
+ span_lint_and_sugg(
+ cx,
+ SINGLE_CHAR_PATTERN,
+ arg.span,
+ "single-character string constant used as pattern",
+ "try using a `char` instead",
+ hint,
+ applicability,
+ );
+ }
+}
+
+/// lint for length-1 `str`s as argument for `push_str`
+fn lint_single_char_push_string(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
+ let mut applicability = Applicability::MachineApplicable;
+ if let Some(extension_string) = get_hint_if_single_char_arg(cx, &args[1], &mut applicability) {
+ let base_string_snippet = snippet_with_applicability(cx, args[0].span, "_", &mut applicability);
+ let sugg = format!("{}.push({})", base_string_snippet, extension_string);
+ span_lint_and_sugg(
+ cx,
+ SINGLE_CHAR_PUSH_STR,
+ expr.span,
+ "calling `push_str()` using a single-character string literal",
+ "consider using `push` with a character literal",
+ sugg,
+ applicability,
+ );
+ }
+}
+
+/// Checks for the `USELESS_ASREF` lint.
+fn lint_asref(cx: &LateContext<'_>, expr: &hir::Expr<'_>, call_name: &str, as_ref_args: &[hir::Expr<'_>]) {
+ // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
+ // check if the call is to the actual `AsRef` or `AsMut` trait
+ if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
+ // check if the type after `as_ref` or `as_mut` is the same as before
+ let recvr = &as_ref_args[0];
+ let rcv_ty = cx.typeck_results().expr_ty(recvr);
+ let res_ty = cx.typeck_results().expr_ty(expr);
+ let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
+ let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
+ if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
+ // allow the `as_ref` or `as_mut` if it is followed by another method call
+ if_chain! {
+ if let Some(parent) = get_parent_expr(cx, expr);
+ if let hir::ExprKind::MethodCall(_, ref span, _, _) = parent.kind;
+ if span != &expr.span;
+ then {
+ return;
+ }
+ }
+
+ let mut applicability = Applicability::MachineApplicable;
+ span_lint_and_sugg(
+ cx,
+ USELESS_ASREF,
+ expr.span,
+ &format!("this call to `{}` does nothing", call_name),
+ "try this",
+ snippet_with_applicability(cx, recvr.span, "_", &mut applicability).to_string(),
+ applicability,
+ );
+ }
+ }
+}
+
+fn ty_has_iter_method(cx: &LateContext<'_>, self_ref_ty: Ty<'_>) -> Option<(&'static str, &'static str)> {
+ has_iter_method(cx, self_ref_ty).map(|ty_name| {
+ let mutbl = match self_ref_ty.kind() {
+ ty::Ref(_, _, mutbl) => mutbl,
+ _ => unreachable!(),
+ };
+ let method_name = match mutbl {
+ hir::Mutability::Not => "iter",
+ hir::Mutability::Mut => "iter_mut",
+ };
+ (ty_name, method_name)
+ })
+}
+
+fn lint_into_iter(cx: &LateContext<'_>, expr: &hir::Expr<'_>, self_ref_ty: Ty<'_>, method_span: Span) {
+ if !match_trait_method(cx, expr, &paths::INTO_ITERATOR) {
+ return;
+ }
+ if let Some((kind, method_name)) = ty_has_iter_method(cx, self_ref_ty) {
+ span_lint_and_sugg(
+ cx,
+ INTO_ITER_ON_REF,
+ method_span,
+ &format!(
+ "this `.into_iter()` call is equivalent to `.{}()` and will not move the `{}`",
+ method_name, kind,
+ ),
+ "call directly",
+ method_name.to_string(),
+ Applicability::MachineApplicable,
+ );
+ }
+}
+
+/// lint for `MaybeUninit::uninit().assume_init()` (we already have the latter)
+fn lint_maybe_uninit(cx: &LateContext<'_>, expr: &hir::Expr<'_>, outer: &hir::Expr<'_>) {
+ if_chain! {
+ if let hir::ExprKind::Call(ref callee, ref args) = expr.kind;
+ if args.is_empty();
+ if let hir::ExprKind::Path(ref path) = callee.kind;
+ if match_qpath(path, &paths::MEM_MAYBEUNINIT_UNINIT);
+ if !is_maybe_uninit_ty_valid(cx, cx.typeck_results().expr_ty_adjusted(outer));
+ then {
+ span_lint(
+ cx,
+ UNINIT_ASSUMED_INIT,
+ outer.span,
+ "this call for this type may be undefined behavior"
+ );
+ }
+ }
+}
+
+fn is_maybe_uninit_ty_valid(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
+ match ty.kind() {
+ ty::Array(ref component, _) => is_maybe_uninit_ty_valid(cx, component),
+ ty::Tuple(ref types) => types.types().all(|ty| is_maybe_uninit_ty_valid(cx, ty)),
+ ty::Adt(ref adt, _) => match_def_path(cx, adt.did, &paths::MEM_MAYBEUNINIT),
+ _ => false,
+ }
+}
+
+fn lint_suspicious_map(cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
+ span_lint_and_help(
+ cx,
+ SUSPICIOUS_MAP,
+ expr.span,
+ "this call to `map()` won't have an effect on the call to `count()`",
+ None,
+ "make sure you did not confuse `map` with `filter` or `for_each`",
+ );
+}
+
+/// lint use of `_.as_ref().map(Deref::deref)` for `Option`s
+fn lint_option_as_ref_deref<'tcx>(
+ cx: &LateContext<'tcx>,
+ expr: &hir::Expr<'_>,
+ as_ref_args: &[hir::Expr<'_>],
+ map_args: &[hir::Expr<'_>],
+ is_mut: bool,
+) {
+ let same_mutability = |m| (is_mut && m == &hir::Mutability::Mut) || (!is_mut && m == &hir::Mutability::Not);
+
+ let option_ty = cx.typeck_results().expr_ty(&as_ref_args[0]);
+ if !is_type_diagnostic_item(cx, option_ty, sym!(option_type)) {
+ return;
+ }
+
+ let deref_aliases: [&[&str]; 9] = [
+ &paths::DEREF_TRAIT_METHOD,
+ &paths::DEREF_MUT_TRAIT_METHOD,
+ &paths::CSTRING_AS_C_STR,
+ &paths::OS_STRING_AS_OS_STR,
+ &paths::PATH_BUF_AS_PATH,
+ &paths::STRING_AS_STR,
+ &paths::STRING_AS_MUT_STR,
+ &paths::VEC_AS_SLICE,
+ &paths::VEC_AS_MUT_SLICE,
+ ];
+
+ let is_deref = match map_args[1].kind {
+ hir::ExprKind::Path(ref expr_qpath) => cx
+ .qpath_res(expr_qpath, map_args[1].hir_id)
+ .opt_def_id()
+ .map_or(false, |fun_def_id| {
+ deref_aliases.iter().any(|path| match_def_path(cx, fun_def_id, path))
+ }),
+ hir::ExprKind::Closure(_, _, body_id, _, _) => {
+ let closure_body = cx.tcx.hir().body(body_id);
+ let closure_expr = remove_blocks(&closure_body.value);
+
+ match &closure_expr.kind {
+ hir::ExprKind::MethodCall(_, _, args, _) => {
+ if_chain! {
+ if args.len() == 1;
+ if let hir::ExprKind::Path(qpath) = &args[0].kind;
+ if let hir::def::Res::Local(local_id) = cx.qpath_res(qpath, args[0].hir_id);
+ if closure_body.params[0].pat.hir_id == local_id;
+ let adj = cx
+ .typeck_results()
+ .expr_adjustments(&args[0])
+ .iter()
+ .map(|x| &x.kind)
+ .collect::<Box<[_]>>();
+ if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj;
+ then {
+ let method_did = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id).unwrap();
+ deref_aliases.iter().any(|path| match_def_path(cx, method_did, path))
+ } else {
+ false
+ }
+ }
+ },
+ hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, ref inner) if same_mutability(m) => {
+ if_chain! {
+ if let hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner1) = inner.kind;
+ if let hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner2) = inner1.kind;
+ if let hir::ExprKind::Path(ref qpath) = inner2.kind;
+ if let hir::def::Res::Local(local_id) = cx.qpath_res(qpath, inner2.hir_id);
+ then {
+ closure_body.params[0].pat.hir_id == local_id
+ } else {
+ false
+ }
+ }
+ },
+ _ => false,
+ }
+ },
+ _ => false,
+ };
+
+ if is_deref {
+ let current_method = if is_mut {
+ format!(".as_mut().map({})", snippet(cx, map_args[1].span, ".."))
+ } else {
+ format!(".as_ref().map({})", snippet(cx, map_args[1].span, ".."))
+ };
+ let method_hint = if is_mut { "as_deref_mut" } else { "as_deref" };
+ let hint = format!("{}.{}()", snippet(cx, as_ref_args[0].span, ".."), method_hint);
+ let suggestion = format!("try using {} instead", method_hint);
+
+ let msg = format!(
+ "called `{0}` on an Option value. This can be done more directly \
+ by calling `{1}` instead",
+ current_method, hint
+ );
+ span_lint_and_sugg(
+ cx,
+ OPTION_AS_REF_DEREF,
+ expr.span,
+ &msg,
+ &suggestion,
+ hint,
+ Applicability::MachineApplicable,
+ );
+ }
+}
+
+/// Given a `Result<T, E>` type, return its error type (`E`).
+fn get_error_type<'a>(cx: &LateContext<'_>, ty: Ty<'a>) -> Option<Ty<'a>> {
+ match ty.kind() {
+ ty::Adt(_, substs) if is_type_diagnostic_item(cx, ty, sym!(result_type)) => substs.types().nth(1),
+ _ => 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_trait)
+ .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))
+}
+
+enum Convention {
+ Eq(&'static str),
+ StartsWith(&'static str),
+}
+
+#[rustfmt::skip]
+const CONVENTIONS: [(Convention, &[SelfKind]); 7] = [
+ (Convention::Eq("new"), &[SelfKind::No]),
+ (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
+ (Convention::StartsWith("from_"), &[SelfKind::No]),
+ (Convention::StartsWith("into_"), &[SelfKind::Value]),
+ (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
+ (Convention::Eq("to_mut"), &[SelfKind::RefMut]),
+ (Convention::StartsWith("to_"), &[SelfKind::Ref]),
+];
+
+const FN_HEADER: hir::FnHeader = hir::FnHeader {
+ unsafety: hir::Unsafety::Normal,
+ constness: hir::Constness::NotConst,
+ asyncness: hir::IsAsync::NotAsync,
+ abi: rustc_target::spec::abi::Abi::Rust,
+};
+
+struct ShouldImplTraitCase {
+ trait_name: &'static str,
+ method_name: &'static str,
+ param_count: usize,
+ fn_header: hir::FnHeader,
+ // implicit self kind expected (none, self, &self, ...)
+ self_kind: SelfKind,
+ // checks against the output type
+ output_type: OutType,
+ // certain methods with explicit lifetimes can't implement the equivalent trait method
+ lint_explicit_lifetime: bool,
+}
+impl ShouldImplTraitCase {
+ const fn new(
+ trait_name: &'static str,
+ method_name: &'static str,
+ param_count: usize,
+ fn_header: hir::FnHeader,
+ self_kind: SelfKind,
+ output_type: OutType,
+ lint_explicit_lifetime: bool,
+ ) -> ShouldImplTraitCase {
+ ShouldImplTraitCase {
+ trait_name,
+ method_name,
+ param_count,
+ fn_header,
+ self_kind,
+ output_type,
+ lint_explicit_lifetime,
+ }
+ }
+
+ fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
+ self.lint_explicit_lifetime
+ || !impl_item.generics.params.iter().any(|p| {
+ matches!(
+ p.kind,
+ hir::GenericParamKind::Lifetime {
+ kind: hir::LifetimeParamKind::Explicit
+ }
+ )
+ })
+ }
+}
+
+#[rustfmt::skip]
+const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
+ ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
+ ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
+ ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
+ ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
+ ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
+ ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
+ ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
+ ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
+ ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
+ ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
+ // FIXME: default doesn't work
+ ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
+ ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
+ ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
+ ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
+ ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
+ ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
+ ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
+ ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
+ ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
+ ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
+ ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
+ ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
+ ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
+ ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
+ ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
+ ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
+ ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
+ ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
+ ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
+ ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
+];
+
+#[rustfmt::skip]
+const PATTERN_METHODS: [(&str, usize); 17] = [
+ ("contains", 1),
+ ("starts_with", 1),
+ ("ends_with", 1),
+ ("find", 1),
+ ("rfind", 1),
+ ("split", 1),
+ ("rsplit", 1),
+ ("split_terminator", 1),
+ ("rsplit_terminator", 1),
+ ("splitn", 2),
+ ("rsplitn", 2),
+ ("matches", 1),
+ ("rmatches", 1),
+ ("match_indices", 1),
+ ("rmatch_indices", 1),
+ ("trim_start_matches", 1),
+ ("trim_end_matches", 1),
+];
+
+#[derive(Clone, Copy, PartialEq, Debug)]
+enum SelfKind {
+ Value,
+ Ref,
+ RefMut,
+ No,
+}
+
+impl SelfKind {
+ fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
+ fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
+ if ty == parent_ty {
+ true
+ } else if ty.is_box() {
+ ty.boxed_ty() == parent_ty
+ } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
+ if let ty::Adt(_, substs) = ty.kind() {
+ substs.types().next().map_or(false, |t| t == parent_ty)
+ } else {
+ false
+ }
+ } else {
+ false
+ }
+ }
+
+ fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
+ if let ty::Ref(_, t, m) = *ty.kind() {
+ return m == mutability && t == parent_ty;
+ }
+
+ let trait_path = match mutability {
+ hir::Mutability::Not => &paths::ASREF_TRAIT,
+ hir::Mutability::Mut => &paths::ASMUT_TRAIT,
+ };
+
+ let trait_def_id = match get_trait_def_id(cx, trait_path) {
+ Some(did) => did,
+ None => return false,
+ };
+ implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
+ }
+
+ match self {
+ Self::Value => matches_value(cx, parent_ty, ty),
+ Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
+ Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
+ Self::No => ty != parent_ty,
+ }
+ }
+
+ #[must_use]
+ fn description(self) -> &'static str {
+ match self {
+ Self::Value => "self by value",
+ Self::Ref => "self by reference",
+ Self::RefMut => "self by mutable reference",
+ Self::No => "no self",
+ }
+ }
+}
+
+impl Convention {
+ #[must_use]
+ fn check(&self, other: &str) -> bool {
+ match *self {
+ Self::Eq(this) => this == other,
+ Self::StartsWith(this) => other.starts_with(this) && this != other,
+ }
+ }
+}
+
+impl fmt::Display for Convention {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
+ match *self {
+ Self::Eq(this) => this.fmt(f),
+ Self::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
+ }
+ }
+}
+
+#[derive(Clone, Copy)]
+enum OutType {
+ Unit,
+ Bool,
+ Any,
+ Ref,
+}
+
+impl OutType {
+ fn matches(self, cx: &LateContext<'_>, ty: &hir::FnRetTy<'_>) -> bool {
+ let is_unit = |ty: &hir::Ty<'_>| SpanlessEq::new(cx).eq_ty_kind(&ty.kind, &hir::TyKind::Tup(&[]));
+ match (self, ty) {
+ (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
+ (Self::Unit, &hir::FnRetTy::Return(ref ty)) if is_unit(ty) => true,
+ (Self::Bool, &hir::FnRetTy::Return(ref ty)) if is_bool(ty) => true,
+ (Self::Any, &hir::FnRetTy::Return(ref ty)) if !is_unit(ty) => true,
+ (Self::Ref, &hir::FnRetTy::Return(ref ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
+ _ => false,
+ }
+ }
+}
+
+fn is_bool(ty: &hir::Ty<'_>) -> bool {
+ if let hir::TyKind::Path(ref p) = ty.kind {
+ match_qpath(p, &["bool"])
+ } else {
+ false
+ }
+}
+
+// Returns `true` if `expr` contains a return expression
+fn contains_return(expr: &hir::Expr<'_>) -> bool {
+ struct RetCallFinder {
+ found: bool,
+ }
+
+ impl<'tcx> intravisit::Visitor<'tcx> for RetCallFinder {
+ type Map = Map<'tcx>;
+
+ fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
+ if self.found {
+ return;
+ }
+ if let hir::ExprKind::Ret(..) = &expr.kind {
+ self.found = true;
+ } else {
+ intravisit::walk_expr(self, expr);
+ }
+ }
+
+ fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
+ intravisit::NestedVisitorMap::None
+ }
+ }
+
+ let mut visitor = RetCallFinder { found: false };
+ visitor.visit_expr(expr);
+ visitor.found
+}
+
+fn check_pointer_offset(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
+ if_chain! {
+ if args.len() == 2;
+ if let ty::RawPtr(ty::TypeAndMut { ref ty, .. }) = cx.typeck_results().expr_ty(&args[0]).kind();
+ if let Ok(layout) = cx.tcx.layout_of(cx.param_env.and(ty));
+ if layout.is_zst();
+ then {
+ span_lint(cx, ZST_OFFSET, expr.span, "offset calculation on zero-sized value");
+ }
+ }
+}
+
+fn lint_filetype_is_file(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
+ let ty = cx.typeck_results().expr_ty(&args[0]);
+
+ if !match_type(cx, ty, &paths::FILE_TYPE) {
+ return;
+ }
+
+ let span: Span;
+ let verb: &str;
+ let lint_unary: &str;
+ let help_unary: &str;
+ if_chain! {
+ if let Some(parent) = get_parent_expr(cx, expr);
+ if let hir::ExprKind::Unary(op, _) = parent.kind;
+ if op == hir::UnOp::UnNot;
+ then {
+ lint_unary = "!";
+ verb = "denies";
+ help_unary = "";
+ span = parent.span;
+ } else {
+ lint_unary = "";
+ verb = "covers";
+ help_unary = "!";
+ span = expr.span;
+ }
+ }
+ let lint_msg = format!("`{}FileType::is_file()` only {} regular files", lint_unary, verb);
+ let help_msg = format!("use `{}FileType::is_dir()` instead", help_unary);
+ span_lint_and_help(cx, FILETYPE_IS_FILE, span, &lint_msg, None, &help_msg);
+}
+
+fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
+ expected.constness == actual.constness
+ && expected.unsafety == actual.unsafety
+ && expected.asyncness == actual.asyncness
+}
--- /dev/null
- fn is_temporary(_cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
- match &expr.kind {
- ExprKind::Struct(..) | ExprKind::Tup(..) => true,
- _ => false,
- }
+use crate::utils::{is_adjusted, span_lint};
+use rustc_hir::{Expr, ExprKind};
+use rustc_lint::{LateContext, LateLintPass};
+use rustc_session::{declare_lint_pass, declare_tool_lint};
+
+declare_clippy_lint! {
+ /// **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?
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// (0, 0).0 = 1
+ /// ```
+ pub TEMPORARY_ASSIGNMENT,
+ complexity,
+ "assignments to temporaries"
+}
+
- if is_temporary(cx, base) && !is_adjusted(cx, base) {
++fn is_temporary(expr: &Expr<'_>) -> bool {
++ matches!(&expr.kind, ExprKind::Struct(..) | ExprKind::Tup(..))
+}
+
+declare_lint_pass!(TemporaryAssignment => [TEMPORARY_ASSIGNMENT]);
+
+impl<'tcx> LateLintPass<'tcx> for TemporaryAssignment {
+ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
+ if let ExprKind::Assign(target, ..) = &expr.kind {
+ let mut base = target;
+ while let ExprKind::Field(f, _) | ExprKind::Index(f, _) = &base.kind {
+ base = f;
+ }
++ if is_temporary(base) && !is_adjusted(cx, base) {
+ span_lint(cx, TEMPORARY_ASSIGNMENT, expr.span, "assignment to temporary");
+ }
+ }
+ }
+}
--- /dev/null
- // Avoid suggesting from/to bits in const contexts.
+use crate::utils::{
+ in_constant, is_normalizable, last_path_segment, match_def_path, paths, snippet, span_lint, span_lint_and_sugg,
+ span_lint_and_then, sugg,
+};
+use if_chain::if_chain;
+use rustc_ast as ast;
+use rustc_errors::Applicability;
+use rustc_hir::{Expr, ExprKind, GenericArg, Mutability, QPath, TyKind, UnOp};
+use rustc_lint::{LateContext, LateLintPass};
+use rustc_middle::ty::{self, cast::CastKind, Ty};
+use rustc_session::{declare_lint_pass, declare_tool_lint};
+use rustc_span::DUMMY_SP;
+use rustc_typeck::check::{cast::CastCheck, FnCtxt, Inherited};
+use std::borrow::Cow;
+
+declare_clippy_lint! {
+ /// **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 behaviour.
+ ///
+ /// **Known problems:** When accessing C, users might want to store pointer
+ /// sized objects in `extradata` arguments to save an allocation.
+ ///
+ /// **Example:**
+ /// ```ignore
+ /// let ptr: *const T = core::intrinsics::transmute('x')
+ /// ```
+ pub WRONG_TRANSMUTE,
+ correctness,
+ "transmutes that are confusing at best, undefined behaviour at worst and always useless"
+}
+
+// FIXME: Move this to `complexity` again, after #5343 is fixed
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust,ignore
+ /// core::intrinsics::transmute(t); // where the result type is the same as `t`'s
+ /// ```
+ pub USELESS_TRANSMUTE,
+ nursery,
+ "transmutes that have the same to and from types or could be a cast/coercion"
+}
+
+// FIXME: Merge this lint with USELESS_TRANSMUTE once that is out of the nursery.
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ ///
+ /// ```rust
+ /// # let p: *const [i32] = &[];
+ /// unsafe { std::mem::transmute::<*const [i32], *const [u16]>(p) };
+ /// ```
+ /// Use instead:
+ /// ```rust
+ /// # let p: *const [i32] = &[];
+ /// p as *const [u16];
+ /// ```
+ pub TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
+ complexity,
+ "transmutes that could be a pointer cast"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust,ignore
+ /// core::intrinsics::transmute(t) // where the result type is the same as
+ /// // `*t` or `&t`'s
+ /// ```
+ pub CROSSPOINTER_TRANSMUTE,
+ complexity,
+ "transmutes that have to or from types that are a pointer to the other"
+}
+
+declare_clippy_lint! {
+ /// **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:** None.
+ ///
+ /// **Example:**
+ /// ```rust,ignore
+ /// unsafe {
+ /// let _: &T = std::mem::transmute(p); // where p: *const T
+ /// }
+ ///
+ /// // can be written:
+ /// let _: &T = &*p;
+ /// ```
+ pub TRANSMUTE_PTR_TO_REF,
+ complexity,
+ "transmutes from a pointer to a reference type"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ /// ```rust
+ /// let x = 1_u32;
+ /// unsafe {
+ /// let _: char = std::mem::transmute(x); // where x: u32
+ /// }
+ ///
+ /// // should be:
+ /// let _ = std::char::from_u32(x).unwrap();
+ /// ```
+ pub TRANSMUTE_INT_TO_CHAR,
+ complexity,
+ "transmutes from an integer to a `char`"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ /// ```rust
+ /// 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();
+ /// ```
+ pub TRANSMUTE_BYTES_TO_STR,
+ complexity,
+ "transmutes from a `&[u8]` to a `&str`"
+}
+
+declare_clippy_lint! {
+ /// **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`.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// let x = 1_u8;
+ /// unsafe {
+ /// let _: bool = std::mem::transmute(x); // where x: u8
+ /// }
+ ///
+ /// // should be:
+ /// let _: bool = x != 0;
+ /// ```
+ pub TRANSMUTE_INT_TO_BOOL,
+ complexity,
+ "transmutes from an integer to a `bool`"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// unsafe {
+ /// let _: f32 = std::mem::transmute(1_u32); // where x: u32
+ /// }
+ ///
+ /// // should be:
+ /// let _: f32 = f32::from_bits(1_u32);
+ /// ```
+ pub TRANSMUTE_INT_TO_FLOAT,
+ complexity,
+ "transmutes from an integer to a float"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// unsafe {
+ /// let _: u32 = std::mem::transmute(1f32);
+ /// }
+ ///
+ /// // should be:
+ /// let _: u32 = 1f32.to_bits();
+ /// ```
+ pub TRANSMUTE_FLOAT_TO_INT,
+ complexity,
+ "transmutes from a float to an integer"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// 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) };
+ /// ```
+ pub TRANSMUTE_PTR_TO_PTR,
+ complexity,
+ "transmutes from a pointer to a pointer / a reference to a reference"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ /// ```rust
+ /// // different size, therefore likely out-of-bounds memory access
+ /// // You absolutely do not want this in your code!
+ /// unsafe {
+ /// std::mem::transmute::<_, Vec<u32>>(vec![2_u16])
+ /// };
+ /// ```
+ ///
+ /// You must always iterate, map and collect the values:
+ ///
+ /// ```rust
+ /// vec![2_u16].into_iter().map(u32::from).collect::<Vec<_>>();
+ /// ```
+ pub UNSOUND_COLLECTION_TRANSMUTE,
+ correctness,
+ "transmute between collections of layout-incompatible types"
+}
+
+declare_lint_pass!(Transmute => [
+ CROSSPOINTER_TRANSMUTE,
+ TRANSMUTE_PTR_TO_REF,
+ TRANSMUTE_PTR_TO_PTR,
+ USELESS_TRANSMUTE,
+ WRONG_TRANSMUTE,
+ TRANSMUTE_INT_TO_CHAR,
+ TRANSMUTE_BYTES_TO_STR,
+ TRANSMUTE_INT_TO_BOOL,
+ TRANSMUTE_INT_TO_FLOAT,
+ TRANSMUTE_FLOAT_TO_INT,
+ UNSOUND_COLLECTION_TRANSMUTE,
+ TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
+]);
+
+// used to check for UNSOUND_COLLECTION_TRANSMUTE
+static COLLECTIONS: &[&[&str]] = &[
+ &paths::VEC,
+ &paths::VEC_DEQUE,
+ &paths::BINARY_HEAP,
+ &paths::BTREESET,
+ &paths::BTREEMAP,
+ &paths::HASHSET,
+ &paths::HASHMAP,
+];
+impl<'tcx> LateLintPass<'tcx> for Transmute {
+ #[allow(clippy::similar_names, clippy::too_many_lines)]
+ fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
+ if_chain! {
+ if let ExprKind::Call(ref path_expr, ref args) = e.kind;
+ if let ExprKind::Path(ref qpath) = path_expr.kind;
+ if let Some(def_id) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id();
+ if match_def_path(cx, def_id, &paths::TRANSMUTE);
+ then {
- if cx.tcx.erase_regions(&from_ty) != cx.tcx.erase_regions(&to_ty) {
++ // Avoid suggesting from/to bits and dereferencing raw pointers in const contexts.
+ // See https://github.com/rust-lang/rust/issues/73736 for progress on making them `const fn`.
++ // And see https://github.com/rust-lang/rust/issues/51911 for dereferencing raw pointers.
+ let const_context = in_constant(cx, e.hir_id);
+
+ let from_ty = cx.typeck_results().expr_ty(&args[0]);
+ let to_ty = cx.typeck_results().expr_ty(e);
+
+ match (&from_ty.kind(), &to_ty.kind()) {
+ _ if from_ty == to_ty => span_lint(
+ cx,
+ USELESS_TRANSMUTE,
+ e.span,
+ &format!("transmute from a type (`{}`) to itself", from_ty),
+ ),
+ (ty::Ref(_, rty, rty_mutbl), ty::RawPtr(ptr_ty)) => span_lint_and_then(
+ cx,
+ USELESS_TRANSMUTE,
+ e.span,
+ "transmute from a reference to a pointer",
+ |diag| {
+ if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
+ let rty_and_mut = ty::TypeAndMut {
+ ty: rty,
+ mutbl: *rty_mutbl,
+ };
+
+ let sugg = if *ptr_ty == rty_and_mut {
+ arg.as_ty(to_ty)
+ } else {
+ arg.as_ty(cx.tcx.mk_ptr(rty_and_mut)).as_ty(to_ty)
+ };
+
+ diag.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
+ }
+ },
+ ),
+ (ty::Int(_) | ty::Uint(_), ty::RawPtr(_)) => span_lint_and_then(
+ cx,
+ USELESS_TRANSMUTE,
+ e.span,
+ "transmute from an integer to a pointer",
+ |diag| {
+ if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
+ diag.span_suggestion(
+ e.span,
+ "try",
+ arg.as_ty(&to_ty.to_string()).to_string(),
+ Applicability::Unspecified,
+ );
+ }
+ },
+ ),
+ (ty::Float(_) | ty::Char, ty::Ref(..) | ty::RawPtr(_)) => span_lint(
+ cx,
+ WRONG_TRANSMUTE,
+ e.span,
+ &format!("transmute from a `{}` to a pointer", from_ty),
+ ),
+ (ty::RawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
+ cx,
+ CROSSPOINTER_TRANSMUTE,
+ e.span,
+ &format!(
+ "transmute from a type (`{}`) to the type that it points to (`{}`)",
+ from_ty, to_ty
+ ),
+ ),
+ (_, ty::RawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
+ cx,
+ CROSSPOINTER_TRANSMUTE,
+ e.span,
+ &format!(
+ "transmute from a type (`{}`) to a pointer to that type (`{}`)",
+ from_ty, to_ty
+ ),
+ ),
+ (ty::RawPtr(from_pty), ty::Ref(_, to_ref_ty, mutbl)) => span_lint_and_then(
+ cx,
+ TRANSMUTE_PTR_TO_REF,
+ e.span,
+ &format!(
+ "transmute from a pointer type (`{}`) to a reference type \
+ (`{}`)",
+ from_ty, to_ty
+ ),
+ |diag| {
+ let arg = sugg::Sugg::hir(cx, &args[0], "..");
+ let (deref, cast) = if *mutbl == Mutability::Mut {
+ ("&mut *", "*mut")
+ } else {
+ ("&*", "*const")
+ };
+
+ let arg = if from_pty.ty == *to_ref_ty {
+ arg
+ } else {
+ arg.as_ty(&format!("{} {}", cast, get_type_snippet(cx, qpath, to_ref_ty)))
+ };
+
+ diag.span_suggestion(
+ e.span,
+ "try",
+ sugg::make_unop(deref, arg).to_string(),
+ Applicability::Unspecified,
+ );
+ },
+ ),
+ (ty::Int(ast::IntTy::I32) | ty::Uint(ast::UintTy::U32), &ty::Char) => {
+ span_lint_and_then(
+ cx,
+ TRANSMUTE_INT_TO_CHAR,
+ e.span,
+ &format!("transmute from a `{}` to a `char`", from_ty),
+ |diag| {
+ let arg = sugg::Sugg::hir(cx, &args[0], "..");
+ let arg = if let ty::Int(_) = from_ty.kind() {
+ arg.as_ty(ast::UintTy::U32.name_str())
+ } else {
+ arg
+ };
+ diag.span_suggestion(
+ e.span,
+ "consider using",
+ format!("std::char::from_u32({}).unwrap()", arg.to_string()),
+ Applicability::Unspecified,
+ );
+ },
+ )
+ },
+ (ty::Ref(_, ty_from, from_mutbl), ty::Ref(_, ty_to, to_mutbl)) => {
+ if_chain! {
+ if let (&ty::Slice(slice_ty), &ty::Str) = (&ty_from.kind(), &ty_to.kind());
+ if let ty::Uint(ast::UintTy::U8) = slice_ty.kind();
+ if from_mutbl == to_mutbl;
+ then {
+ let postfix = if *from_mutbl == Mutability::Mut {
+ "_mut"
+ } else {
+ ""
+ };
+
+ span_lint_and_sugg(
+ cx,
+ TRANSMUTE_BYTES_TO_STR,
+ e.span,
+ &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
+ "consider using",
+ format!(
+ "std::str::from_utf8{}({}).unwrap()",
+ postfix,
+ snippet(cx, args[0].span, ".."),
+ ),
+ Applicability::Unspecified,
+ );
+ } else {
++ if (cx.tcx.erase_regions(&from_ty) != cx.tcx.erase_regions(&to_ty))
++ && !const_context {
+ span_lint_and_then(
+ cx,
+ TRANSMUTE_PTR_TO_PTR,
+ e.span,
+ "transmute from a reference to a reference",
+ |diag| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
+ let ty_from_and_mut = ty::TypeAndMut {
+ ty: ty_from,
+ mutbl: *from_mutbl
+ };
+ let ty_to_and_mut = ty::TypeAndMut { ty: ty_to, mutbl: *to_mutbl };
+ let sugg_paren = arg
+ .as_ty(cx.tcx.mk_ptr(ty_from_and_mut))
+ .as_ty(cx.tcx.mk_ptr(ty_to_and_mut));
+ let sugg = if *to_mutbl == Mutability::Mut {
+ sugg_paren.mut_addr_deref()
+ } else {
+ sugg_paren.addr_deref()
+ };
+ diag.span_suggestion(
+ e.span,
+ "try",
+ sugg.to_string(),
+ Applicability::Unspecified,
+ );
+ },
+ )
+ }
+ }
+ }
+ },
+ (ty::RawPtr(_), ty::RawPtr(to_ty)) => span_lint_and_then(
+ cx,
+ TRANSMUTE_PTR_TO_PTR,
+ e.span,
+ "transmute from a pointer to a pointer",
+ |diag| {
+ if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
+ let sugg = arg.as_ty(cx.tcx.mk_ptr(*to_ty));
+ diag.span_suggestion(e.span, "try", sugg.to_string(), Applicability::Unspecified);
+ }
+ },
+ ),
+ (ty::Int(ast::IntTy::I8) | ty::Uint(ast::UintTy::U8), ty::Bool) => {
+ span_lint_and_then(
+ cx,
+ TRANSMUTE_INT_TO_BOOL,
+ e.span,
+ &format!("transmute from a `{}` to a `bool`", from_ty),
+ |diag| {
+ let arg = sugg::Sugg::hir(cx, &args[0], "..");
+ let zero = sugg::Sugg::NonParen(Cow::from("0"));
+ diag.span_suggestion(
+ e.span,
+ "consider using",
+ sugg::make_binop(ast::BinOpKind::Ne, &arg, &zero).to_string(),
+ Applicability::Unspecified,
+ );
+ },
+ )
+ },
+ (ty::Int(_) | ty::Uint(_), ty::Float(_)) if !const_context => span_lint_and_then(
+ cx,
+ TRANSMUTE_INT_TO_FLOAT,
+ e.span,
+ &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
+ |diag| {
+ let arg = sugg::Sugg::hir(cx, &args[0], "..");
+ let arg = if let ty::Int(int_ty) = from_ty.kind() {
+ arg.as_ty(format!(
+ "u{}",
+ int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
+ ))
+ } else {
+ arg
+ };
+ diag.span_suggestion(
+ e.span,
+ "consider using",
+ format!("{}::from_bits({})", to_ty, arg.to_string()),
+ Applicability::Unspecified,
+ );
+ },
+ ),
+ (ty::Float(float_ty), ty::Int(_) | ty::Uint(_)) if !const_context => span_lint_and_then(
+ cx,
+ TRANSMUTE_FLOAT_TO_INT,
+ e.span,
+ &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
+ |diag| {
+ let mut expr = &args[0];
+ let mut arg = sugg::Sugg::hir(cx, expr, "..");
+
+ if let ExprKind::Unary(UnOp::UnNeg, inner_expr) = &expr.kind {
+ expr = &inner_expr;
+ }
+
+ if_chain! {
+ // if the expression is a float literal and it is unsuffixed then
+ // add a suffix so the suggestion is valid and unambiguous
+ let op = format!("{}{}", arg, float_ty.name_str()).into();
+ if let ExprKind::Lit(lit) = &expr.kind;
+ if let ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) = lit.node;
+ then {
+ match arg {
+ sugg::Sugg::MaybeParen(_) => arg = sugg::Sugg::MaybeParen(op),
+ _ => arg = sugg::Sugg::NonParen(op)
+ }
+ }
+ }
+
+ arg = sugg::Sugg::NonParen(format!("{}.to_bits()", arg.maybe_par()).into());
+
+ // cast the result of `to_bits` if `to_ty` is signed
+ arg = if let ty::Int(int_ty) = to_ty.kind() {
+ arg.as_ty(int_ty.name_str().to_string())
+ } else {
+ arg
+ };
+
+ diag.span_suggestion(
+ e.span,
+ "consider using",
+ arg.to_string(),
+ Applicability::Unspecified,
+ );
+ },
+ ),
+ (ty::Adt(from_adt, from_substs), ty::Adt(to_adt, to_substs)) => {
+ if from_adt.did != to_adt.did ||
+ !COLLECTIONS.iter().any(|path| match_def_path(cx, to_adt.did, path)) {
+ return;
+ }
+ if from_substs.types().zip(to_substs.types())
+ .any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty)) {
+ span_lint(
+ cx,
+ UNSOUND_COLLECTION_TRANSMUTE,
+ e.span,
+ &format!(
+ "transmute from `{}` to `{}` with mismatched layout is unsound",
+ from_ty,
+ to_ty
+ )
+ );
+ }
+ },
+ (_, _) if can_be_expressed_as_pointer_cast(cx, e, from_ty, to_ty) => span_lint_and_then(
+ cx,
+ TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS,
+ e.span,
+ &format!(
+ "transmute from `{}` to `{}` which could be expressed as a pointer cast instead",
+ from_ty,
+ to_ty
+ ),
+ |diag| {
+ if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
+ let sugg = arg.as_ty(&to_ty.to_string()).to_string();
+ diag.span_suggestion(e.span, "try", sugg, Applicability::MachineApplicable);
+ }
+ }
+ ),
+ _ => {
+ return;
+ },
+ }
+ }
+ }
+ }
+}
+
+/// Gets the snippet of `Bar` in `…::transmute<Foo, &Bar>`. If that snippet is
+/// not available , use
+/// the type's `ToString` implementation. In weird cases it could lead to types
+/// with invalid `'_`
+/// lifetime, but it should be rare.
+fn get_type_snippet(cx: &LateContext<'_>, path: &QPath<'_>, to_ref_ty: Ty<'_>) -> String {
+ let seg = last_path_segment(path);
+ if_chain! {
+ if let Some(ref params) = seg.args;
+ if !params.parenthesized;
+ if let Some(to_ty) = params.args.iter().filter_map(|arg| match arg {
+ GenericArg::Type(ty) => Some(ty),
+ _ => None,
+ }).nth(1);
+ if let TyKind::Rptr(_, ref to_ty) = to_ty.kind;
+ then {
+ return snippet(cx, to_ty.ty.span, &to_ref_ty.to_string()).to_string();
+ }
+ }
+
+ to_ref_ty.to_string()
+}
+
+// check if the component types of the transmuted collection and the result have different ABI,
+// size or alignment
+fn is_layout_incompatible<'tcx>(cx: &LateContext<'tcx>, from: Ty<'tcx>, to: Ty<'tcx>) -> bool {
+ let empty_param_env = ty::ParamEnv::empty();
+ // check if `from` and `to` are normalizable to avoid ICE (#4968)
+ if !(is_normalizable(cx, empty_param_env, from) && is_normalizable(cx, empty_param_env, to)) {
+ return false;
+ }
+ let from_ty_layout = cx.tcx.layout_of(empty_param_env.and(from));
+ let to_ty_layout = cx.tcx.layout_of(empty_param_env.and(to));
+ if let (Ok(from_layout), Ok(to_layout)) = (from_ty_layout, to_ty_layout) {
+ from_layout.size != to_layout.size || from_layout.align != to_layout.align || from_layout.abi != to_layout.abi
+ } else {
+ // no idea about layout, so don't lint
+ false
+ }
+}
+
+/// Check if the type conversion can be expressed as a pointer cast, instead of
+/// a transmute. 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 can_be_expressed_as_pointer_cast<'tcx>(
+ cx: &LateContext<'tcx>,
+ e: &'tcx Expr<'_>,
+ from_ty: Ty<'tcx>,
+ to_ty: Ty<'tcx>,
+) -> bool {
+ use CastKind::{AddrPtrCast, ArrayPtrCast, FnPtrAddrCast, FnPtrPtrCast, PtrAddrCast, PtrPtrCast};
+ matches!(
+ check_cast(cx, e, from_ty, to_ty),
+ Some(PtrPtrCast | PtrAddrCast | AddrPtrCast | ArrayPtrCast | FnPtrPtrCast | FnPtrAddrCast)
+ )
+}
+
+/// If a cast from `from_ty` to `to_ty` is valid, returns an Ok containing the kind of
+/// 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<CastKind> {
+ let hir_id = e.hir_id;
+ let local_def_id = hir_id.owner;
+
+ Inherited::build(cx.tcx, local_def_id).enter(|inherited| {
+ 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"
+ );
+
+ if let Ok(check) = CastCheck::new(
+ &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,
+ ) {
+ let res = check.do_check(&fn_ctxt);
+
+ // do_check's documentation says that it might return Ok and create
+ // errors in the fcx instead of returing Err in some cases. Those cases
+ // should be filtered out before getting here.
+ assert!(
+ !fn_ctxt.errors_reported_since_creation(),
+ "`fn_ctxt` contained errors after cast check!"
+ );
+
+ res.ok()
+ } else {
+ None
+ }
+ })
+}
--- /dev/null
- ImplItemKind, Item, ItemKind, Lifetime, Local, MatchSource, MutTy, Mutability, QPath, Stmt, StmtKind, TraitFn,
- TraitItem, TraitItemKind, TyKind, UnOp,
+#![allow(rustc::default_hash_types)]
+
+use std::borrow::Cow;
+use std::cmp::Ordering;
+use std::collections::BTreeMap;
+
+use if_chain::if_chain;
+use rustc_ast::{FloatTy, IntTy, LitFloatType, LitIntType, LitKind, UintTy};
+use rustc_errors::{Applicability, DiagnosticBuilder};
+use rustc_hir as hir;
+use rustc_hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
+use rustc_hir::{
+ BinOpKind, Block, Body, Expr, ExprKind, FnDecl, FnRetTy, FnSig, GenericArg, GenericParamKind, HirId, ImplItem,
- qpath_res, sext, snippet, snippet_block_with_applicability, snippet_opt, snippet_with_applicability,
- snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, unsext,
++ ImplItemKind, Item, ItemKind, Lifetime, Local, MatchSource, MutTy, Mutability, Node, QPath, Stmt, StmtKind,
++ TraitFn, TraitItem, TraitItemKind, TyKind, UnOp,
+};
+use rustc_lint::{LateContext, LateLintPass, LintContext};
+use rustc_middle::hir::map::Map;
+use rustc_middle::lint::in_external_macro;
+use rustc_middle::ty::{self, InferTy, Ty, TyCtxt, TyS, TypeckResults};
+use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
+use rustc_span::hygiene::{ExpnKind, MacroKind};
+use rustc_span::source_map::Span;
+use rustc_span::symbol::sym;
+use rustc_target::abi::LayoutOf;
+use rustc_target::spec::abi::Abi;
+use rustc_typeck::hir_ty_to_ty;
+
+use crate::consts::{constant, Constant};
+use crate::utils::paths;
+use crate::utils::{
+ clip, comparisons, differing_macro_contexts, higher, in_constant, indent_of, int_bits, is_type_diagnostic_item,
+ last_path_segment, match_def_path, match_path, method_chain_args, multispan_sugg, numeric_literal::NumericLiteral,
- let sugg = args_to_recover
++ qpath_res, reindent_multiline, sext, snippet, snippet_opt, snippet_with_applicability, snippet_with_macro_callsite,
++ span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, unsext,
+};
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for use of `Box<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?** `Vec` already keeps its contents in a separate area on
+ /// the heap. So if you `Box` it, you just add another level of indirection
+ /// without any benefit whatsoever.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust,ignore
+ /// struct X {
+ /// values: Box<Vec<Foo>>,
+ /// }
+ /// ```
+ ///
+ /// Better:
+ ///
+ /// ```rust,ignore
+ /// struct X {
+ /// values: Vec<Foo>,
+ /// }
+ /// ```
+ pub BOX_VEC,
+ perf,
+ "usage of `Box<Vec<T>>`, vector elements are already on the heap"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for use of `Vec<Box<T>>` 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<Box<T: Sized>> makes sense if T is a large type (see #3530,
+ /// 1st comment).
+ ///
+ /// **Example:**
+ /// ```rust
+ /// struct X {
+ /// values: Vec<Box<i32>>,
+ /// }
+ /// ```
+ ///
+ /// Better:
+ ///
+ /// ```rust
+ /// struct X {
+ /// values: Vec<i32>,
+ /// }
+ /// ```
+ pub VEC_BOX,
+ complexity,
+ "usage of `Vec<Box<T>>` where T: Sized, vector elements are already on the heap"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
+ /// definitions
+ ///
+ /// **Why is this bad?** `Option<_>` represents an optional value. `Option<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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example**
+ /// ```rust
+ /// fn get_data() -> Option<Option<u32>> {
+ /// None
+ /// }
+ /// ```
+ ///
+ /// Better:
+ ///
+ /// ```rust
+ /// pub enum Contents {
+ /// Data(Vec<u8>), // Was Some(Some(Vec<u8>))
+ /// NotYetFetched, // Was Some(None)
+ /// None, // Was None
+ /// }
+ ///
+ /// fn get_data() -> Contents {
+ /// Contents::None
+ /// }
+ /// ```
+ pub OPTION_OPTION,
+ pedantic,
+ "usage of `Option<Option<T>>`"
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ /// ```rust
+ /// # use std::collections::LinkedList;
+ /// let x: LinkedList<usize> = LinkedList::new();
+ /// ```
+ pub LINKEDLIST,
+ pedantic,
+ "usage of LinkedList, usually a vector is faster, or a more specialized data structure like a `VecDeque`"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
++ /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
+ ///
+ /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
+ /// general.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust,ignore
+ /// fn foo(bar: &Box<T>) { ... }
+ /// ```
+ ///
+ /// Better:
+ ///
+ /// ```rust,ignore
+ /// fn foo(bar: &T) { ... }
+ /// ```
+ pub BORROWED_BOX,
+ complexity,
+ "a borrow of a boxed type"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for use of redundant allocations anywhere in the code.
+ ///
+ /// **Why is this bad?** Expressions such as `Rc<&T>`, `Rc<Rc<T>>`, `Rc<Box<T>>`, `Box<&T>`
+ /// add an unnecessary level of indirection.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # use std::rc::Rc;
+ /// fn foo(bar: Rc<&usize>) {}
+ /// ```
+ ///
+ /// Better:
+ ///
+ /// ```rust
+ /// fn foo(bar: &usize) {}
+ /// ```
+ pub REDUNDANT_ALLOCATION,
+ perf,
+ "redundant allocation"
+}
+
+pub struct Types {
+ vec_box_size_threshold: u64,
+}
+
+impl_lint_pass!(Types => [BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX, REDUNDANT_ALLOCATION]);
+
+impl<'tcx> LateLintPass<'tcx> for Types {
+ fn check_fn(&mut self, cx: &LateContext<'_>, _: FnKind<'_>, decl: &FnDecl<'_>, _: &Body<'_>, _: Span, id: HirId) {
+ // Skip trait implementations; see issue #605.
+ if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(id)) {
+ if let ItemKind::Impl { of_trait: Some(_), .. } = item.kind {
+ return;
+ }
+ }
+
+ self.check_fn_decl(cx, decl);
+ }
+
+ fn check_struct_field(&mut self, cx: &LateContext<'_>, field: &hir::StructField<'_>) {
+ self.check_ty(cx, &field.ty, false);
+ }
+
+ fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &TraitItem<'_>) {
+ match item.kind {
+ TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_ty(cx, ty, false),
+ TraitItemKind::Fn(ref sig, _) => self.check_fn_decl(cx, &sig.decl),
+ _ => (),
+ }
+ }
+
+ fn check_local(&mut self, cx: &LateContext<'_>, local: &Local<'_>) {
+ if let Some(ref ty) = local.ty {
+ self.check_ty(cx, ty, true);
+ }
+ }
+}
+
+/// Checks if `qpath` has last segment with type parameter matching `path`
+fn match_type_parameter(cx: &LateContext<'_>, qpath: &QPath<'_>, path: &[&str]) -> Option<Span> {
+ let last = last_path_segment(qpath);
+ if_chain! {
+ if let Some(ref params) = last.args;
+ if !params.parenthesized;
+ if let Some(ty) = params.args.iter().find_map(|arg| match arg {
+ GenericArg::Type(ty) => Some(ty),
+ _ => None,
+ });
+ if let TyKind::Path(ref qpath) = ty.kind;
+ if let Some(did) = qpath_res(cx, qpath, ty.hir_id).opt_def_id();
+ if match_def_path(cx, did, path);
+ then {
+ return Some(ty.span);
+ }
+ }
+ None
+}
+
+fn match_borrows_parameter(_cx: &LateContext<'_>, qpath: &QPath<'_>) -> Option<Span> {
+ let last = last_path_segment(qpath);
+ if_chain! {
+ if let Some(ref params) = last.args;
+ if !params.parenthesized;
+ if let Some(ty) = params.args.iter().find_map(|arg| match arg {
+ GenericArg::Type(ty) => Some(ty),
+ _ => None,
+ });
+ if let TyKind::Rptr(..) = ty.kind;
+ then {
+ return Some(ty.span);
+ }
+ }
+ None
+}
+
+impl Types {
+ pub fn new(vec_box_size_threshold: u64) -> Self {
+ Self { vec_box_size_threshold }
+ }
+
+ fn check_fn_decl(&mut self, cx: &LateContext<'_>, decl: &FnDecl<'_>) {
+ for input in decl.inputs {
+ self.check_ty(cx, input, false);
+ }
+
+ if let FnRetTy::Return(ref ty) = decl.output {
+ self.check_ty(cx, ty, false);
+ }
+ }
+
+ /// Recursively check for `TypePass` lints in the given type. Stop at the first
+ /// lint found.
+ ///
+ /// The parameter `is_local` distinguishes the context of the type; types from
+ /// local bindings should only be checked for the `BORROWED_BOX` lint.
+ #[allow(clippy::too_many_lines)]
+ fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, is_local: bool) {
+ if hir_ty.span.from_expansion() {
+ return;
+ }
+ match hir_ty.kind {
+ TyKind::Path(ref qpath) if !is_local => {
+ let hir_id = hir_ty.hir_id;
+ let res = qpath_res(cx, qpath, hir_id);
+ if let Some(def_id) = res.opt_def_id() {
+ if Some(def_id) == cx.tcx.lang_items().owned_box() {
+ if let Some(span) = match_borrows_parameter(cx, qpath) {
+ span_lint_and_sugg(
+ cx,
+ REDUNDANT_ALLOCATION,
+ hir_ty.span,
+ "usage of `Box<&T>`",
+ "try",
+ snippet(cx, span, "..").to_string(),
+ Applicability::MachineApplicable,
+ );
+ return; // don't recurse into the type
+ }
+ if match_type_parameter(cx, qpath, &paths::VEC).is_some() {
+ span_lint_and_help(
+ cx,
+ BOX_VEC,
+ hir_ty.span,
+ "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
+ None,
+ "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.",
+ );
+ return; // don't recurse into the type
+ }
+ } else if cx.tcx.is_diagnostic_item(sym::Rc, def_id) {
+ if let Some(span) = match_type_parameter(cx, qpath, &paths::RC) {
+ span_lint_and_sugg(
+ cx,
+ REDUNDANT_ALLOCATION,
+ hir_ty.span,
+ "usage of `Rc<Rc<T>>`",
+ "try",
+ snippet(cx, span, "..").to_string(),
+ Applicability::MachineApplicable,
+ );
+ return; // don't recurse into the type
+ }
+ if match_type_parameter(cx, qpath, &paths::BOX).is_some() {
+ let box_ty = match &last_path_segment(qpath).args.unwrap().args[0] {
+ GenericArg::Type(ty) => match &ty.kind {
+ TyKind::Path(qpath) => qpath,
+ _ => return,
+ },
+ _ => return,
+ };
+ let inner_span = match &last_path_segment(&box_ty).args.unwrap().args[0] {
+ GenericArg::Type(ty) => ty.span,
+ _ => return,
+ };
+ span_lint_and_sugg(
+ cx,
+ REDUNDANT_ALLOCATION,
+ hir_ty.span,
+ "usage of `Rc<Box<T>>`",
+ "try",
+ format!("Rc<{}>", snippet(cx, inner_span, "..")),
+ Applicability::MachineApplicable,
+ );
+ return; // don't recurse into the type
+ }
+ if let Some(span) = match_borrows_parameter(cx, qpath) {
+ span_lint_and_sugg(
+ cx,
+ REDUNDANT_ALLOCATION,
+ hir_ty.span,
+ "usage of `Rc<&T>`",
+ "try",
+ snippet(cx, span, "..").to_string(),
+ Applicability::MachineApplicable,
+ );
+ return; // don't recurse into the type
+ }
+ } else if cx.tcx.is_diagnostic_item(sym!(vec_type), def_id) {
+ if_chain! {
+ // Get the _ part of Vec<_>
+ if let Some(ref last) = last_path_segment(qpath).args;
+ if let Some(ty) = last.args.iter().find_map(|arg| match arg {
+ GenericArg::Type(ty) => Some(ty),
+ _ => None,
+ });
+ // ty is now _ at this point
+ if let TyKind::Path(ref ty_qpath) = ty.kind;
+ let res = qpath_res(cx, ty_qpath, ty.hir_id);
+ if let Some(def_id) = res.opt_def_id();
+ if Some(def_id) == cx.tcx.lang_items().owned_box();
+ // At this point, we know ty is Box<T>, now get T
+ if let Some(ref last) = last_path_segment(ty_qpath).args;
+ if let Some(boxed_ty) = last.args.iter().find_map(|arg| match arg {
+ GenericArg::Type(ty) => Some(ty),
+ _ => None,
+ });
+ let ty_ty = hir_ty_to_ty(cx.tcx, boxed_ty);
+ if ty_ty.is_sized(cx.tcx.at(ty.span), cx.param_env);
+ if let Ok(ty_ty_size) = cx.layout_of(ty_ty).map(|l| l.size.bytes());
+ if ty_ty_size <= self.vec_box_size_threshold;
+ then {
+ span_lint_and_sugg(
+ cx,
+ VEC_BOX,
+ hir_ty.span,
+ "`Vec<T>` is already on the heap, the boxing is unnecessary.",
+ "try",
+ format!("Vec<{}>", ty_ty),
+ Applicability::MachineApplicable,
+ );
+ return; // don't recurse into the type
+ }
+ }
+ } else if cx.tcx.is_diagnostic_item(sym!(option_type), def_id) {
+ if match_type_parameter(cx, qpath, &paths::OPTION).is_some() {
+ span_lint(
+ cx,
+ OPTION_OPTION,
+ hir_ty.span,
+ "consider using `Option<T>` instead of `Option<Option<T>>` or a custom \
+ enum if you need to distinguish all 3 cases",
+ );
+ return; // don't recurse into the type
+ }
+ } else if match_def_path(cx, def_id, &paths::LINKED_LIST) {
+ span_lint_and_help(
+ cx,
+ LINKEDLIST,
+ hir_ty.span,
+ "I see you're using a LinkedList! Perhaps you meant some other data structure?",
+ None,
+ "a `VecDeque` might work",
+ );
+ return; // don't recurse into the type
+ }
+ }
+ match *qpath {
+ QPath::Resolved(Some(ref ty), ref p) => {
+ self.check_ty(cx, ty, is_local);
+ for ty in p.segments.iter().flat_map(|seg| {
+ seg.args
+ .as_ref()
+ .map_or_else(|| [].iter(), |params| params.args.iter())
+ .filter_map(|arg| match arg {
+ GenericArg::Type(ty) => Some(ty),
+ _ => None,
+ })
+ }) {
+ self.check_ty(cx, ty, is_local);
+ }
+ },
+ QPath::Resolved(None, ref p) => {
+ for ty in p.segments.iter().flat_map(|seg| {
+ seg.args
+ .as_ref()
+ .map_or_else(|| [].iter(), |params| params.args.iter())
+ .filter_map(|arg| match arg {
+ GenericArg::Type(ty) => Some(ty),
+ _ => None,
+ })
+ }) {
+ self.check_ty(cx, ty, is_local);
+ }
+ },
+ QPath::TypeRelative(ref ty, ref seg) => {
+ self.check_ty(cx, ty, is_local);
+ if let Some(ref params) = seg.args {
+ for ty in params.args.iter().filter_map(|arg| match arg {
+ GenericArg::Type(ty) => Some(ty),
+ _ => None,
+ }) {
+ self.check_ty(cx, ty, is_local);
+ }
+ }
+ },
+ QPath::LangItem(..) => {},
+ }
+ },
+ TyKind::Rptr(ref lt, ref mut_ty) => self.check_ty_rptr(cx, hir_ty, is_local, lt, mut_ty),
+ // recurse
+ TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => {
+ self.check_ty(cx, ty, is_local)
+ },
+ TyKind::Tup(tys) => {
+ for ty in tys {
+ self.check_ty(cx, ty, is_local);
+ }
+ },
+ _ => {},
+ }
+ }
+
+ fn check_ty_rptr(
+ &mut self,
+ cx: &LateContext<'_>,
+ hir_ty: &hir::Ty<'_>,
+ is_local: bool,
+ lt: &Lifetime,
+ mut_ty: &MutTy<'_>,
+ ) {
+ match mut_ty.ty.kind {
+ TyKind::Path(ref qpath) => {
+ let hir_id = mut_ty.ty.hir_id;
+ let def = qpath_res(cx, qpath, hir_id);
+ if_chain! {
+ if let Some(def_id) = def.opt_def_id();
+ if Some(def_id) == cx.tcx.lang_items().owned_box();
+ if let QPath::Resolved(None, ref path) = *qpath;
+ if let [ref bx] = *path.segments;
+ if let Some(ref params) = bx.args;
+ if !params.parenthesized;
+ if let Some(inner) = params.args.iter().find_map(|arg| match arg {
+ GenericArg::Type(ty) => Some(ty),
+ _ => None,
+ });
+ then {
+ if is_any_trait(inner) {
+ // Ignore `Box<Any>` types; see issue #1884 for details.
+ return;
+ }
+
+ let ltopt = if lt.is_elided() {
+ String::new()
+ } else {
+ format!("{} ", lt.name.ident().as_str())
+ };
+
+ if mut_ty.mutbl == Mutability::Mut {
+ // Ignore `&mut Box<T>` types; see issue #2907 for
+ // details.
+ return;
+ }
+ let mut applicability = Applicability::MachineApplicable;
+ span_lint_and_sugg(
+ cx,
+ BORROWED_BOX,
+ hir_ty.span,
+ "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
+ "try",
+ format!(
+ "&{}{}",
+ ltopt,
+ &snippet_with_applicability(cx, inner.span, "..", &mut applicability)
+ ),
+ Applicability::Unspecified,
+ );
+ return; // don't recurse into the type
+ }
+ };
+ self.check_ty(cx, &mut_ty.ty, is_local);
+ },
+ _ => self.check_ty(cx, &mut_ty.ty, is_local),
+ }
+ }
+}
+
+// Returns true if given type is `Any` trait.
+fn is_any_trait(t: &hir::Ty<'_>) -> bool {
+ if_chain! {
+ if let TyKind::TraitObject(ref traits, _) = t.kind;
+ if !traits.is_empty();
+ // Only Send/Sync can be used as additional traits, so it is enough to
+ // check only the first trait.
+ if match_path(&traits[0].trait_ref.path, &paths::ANY_TRAIT);
+ then {
+ return true;
+ }
+ }
+
+ false
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// let x = {
+ /// 1;
+ /// };
+ /// ```
+ pub LET_UNIT_VALUE,
+ pedantic,
+ "creating a `let` binding to a value of unit type, which usually can't be used afterwards"
+}
+
+declare_lint_pass!(LetUnitValue => [LET_UNIT_VALUE]);
+
+impl<'tcx> LateLintPass<'tcx> for LetUnitValue {
+ fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
+ if let StmtKind::Local(ref local) = stmt.kind {
+ if is_unit(cx.typeck_results().pat_ty(&local.pat)) {
+ if in_external_macro(cx.sess(), stmt.span) || local.pat.span.from_expansion() {
+ return;
+ }
+ if higher::is_from_for_desugar(local) {
+ return;
+ }
+ span_lint_and_then(
+ cx,
+ LET_UNIT_VALUE,
+ stmt.span,
+ "this let-binding has unit value",
+ |diag| {
+ if let Some(expr) = &local.init {
+ let snip = snippet_with_macro_callsite(cx, expr.span, "()");
+ diag.span_suggestion(
+ stmt.span,
+ "omit the `let` binding",
+ format!("{};", snip),
+ Applicability::MachineApplicable, // snippet
+ );
+ }
+ },
+ );
+ }
+ }
+ }
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # fn foo() {};
+ /// # fn bar() {};
+ /// # fn baz() {};
+ /// if {
+ /// foo();
+ /// } == {
+ /// bar();
+ /// } {
+ /// baz();
+ /// }
+ /// ```
+ /// is equal to
+ /// ```rust
+ /// # fn foo() {};
+ /// # fn bar() {};
+ /// # fn baz() {};
+ /// {
+ /// foo();
+ /// bar();
+ /// baz();
+ /// }
+ /// ```
+ ///
+ /// For asserts:
+ /// ```rust
+ /// # fn foo() {};
+ /// # fn bar() {};
+ /// assert_eq!({ foo(); }, { bar(); });
+ /// ```
+ /// will always succeed
+ pub UNIT_CMP,
+ correctness,
+ "comparing unit values"
+}
+
+declare_lint_pass!(UnitCmp => [UNIT_CMP]);
+
+impl<'tcx> LateLintPass<'tcx> for UnitCmp {
+ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
+ if expr.span.from_expansion() {
+ if let Some(callee) = expr.span.source_callee() {
+ if let ExpnKind::Macro(MacroKind::Bang, symbol) = callee.kind {
+ if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
+ let op = cmp.node;
+ if op.is_comparison() && is_unit(cx.typeck_results().expr_ty(left)) {
+ let result = match &*symbol.as_str() {
+ "assert_eq" | "debug_assert_eq" => "succeed",
+ "assert_ne" | "debug_assert_ne" => "fail",
+ _ => return,
+ };
+ span_lint(
+ cx,
+ UNIT_CMP,
+ expr.span,
+ &format!(
+ "`{}` of unit values detected. This will always {}",
+ symbol.as_str(),
+ result
+ ),
+ );
+ }
+ }
+ }
+ }
+ return;
+ }
+ if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
+ let op = cmp.node;
+ if op.is_comparison() && is_unit(cx.typeck_results().expr_ty(left)) {
+ let result = match op {
+ BinOpKind::Eq | BinOpKind::Le | BinOpKind::Ge => "true",
+ _ => "false",
+ };
+ span_lint(
+ cx,
+ UNIT_CMP,
+ expr.span,
+ &format!(
+ "{}-comparison of unit values detected. This will always be {}",
+ op.as_str(),
+ result
+ ),
+ );
+ }
+ }
+ }
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust,ignore
+ /// foo({
+ /// let a = bar();
+ /// baz(a);
+ /// })
+ /// ```
+ pub UNIT_ARG,
+ complexity,
+ "passing unit to a function"
+}
+
+declare_lint_pass!(UnitArg => [UNIT_ARG]);
+
+impl<'tcx> LateLintPass<'tcx> for UnitArg {
+ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
+ if expr.span.from_expansion() {
+ return;
+ }
+
+ // apparently stuff in the desugaring of `?` can trigger this
+ // so check for that here
+ // only the calls to `Try::from_error` is marked as desugared,
+ // so we need to check both the current Expr and its parent.
+ if is_questionmark_desugar_marked_call(expr) {
+ return;
+ }
+ if_chain! {
+ let map = &cx.tcx.hir();
+ let opt_parent_node = map.find(map.get_parent_node(expr.hir_id));
+ if let Some(hir::Node::Expr(parent_expr)) = opt_parent_node;
+ if is_questionmark_desugar_marked_call(parent_expr);
+ then {
+ return;
+ }
+ }
+
+ match expr.kind {
+ ExprKind::Call(_, args) | ExprKind::MethodCall(_, _, args, _) => {
+ let args_to_recover = args
+ .iter()
+ .filter(|arg| {
+ if is_unit(cx.typeck_results().expr_ty(arg)) && !is_unit_literal(arg) {
+ !matches!(&arg.kind, ExprKind::Match(.., MatchSource::TryDesugar))
+ } else {
+ false
+ }
+ })
+ .collect::<Vec<_>>();
+ if !args_to_recover.is_empty() {
+ lint_unit_args(cx, expr, &args_to_recover);
+ }
+ },
+ _ => (),
+ }
+ }
+}
+
++fn fmt_stmts_and_call(
++ cx: &LateContext<'_>,
++ call_expr: &Expr<'_>,
++ call_snippet: &str,
++ args_snippets: &[impl AsRef<str>],
++ non_empty_block_args_snippets: &[impl AsRef<str>],
++) -> String {
++ let call_expr_indent = indent_of(cx, call_expr.span).unwrap_or(0);
++ let call_snippet_with_replacements = args_snippets
++ .iter()
++ .fold(call_snippet.to_owned(), |acc, arg| acc.replacen(arg.as_ref(), "()", 1));
++
++ let mut stmts_and_call = non_empty_block_args_snippets
++ .iter()
++ .map(|it| it.as_ref().to_owned())
++ .collect::<Vec<_>>();
++ stmts_and_call.push(call_snippet_with_replacements);
++ stmts_and_call = stmts_and_call
++ .into_iter()
++ .map(|v| reindent_multiline(v.into(), true, Some(call_expr_indent)).into_owned())
++ .collect();
++
++ let mut stmts_and_call_snippet = stmts_and_call.join(&format!("{}{}", ";\n", " ".repeat(call_expr_indent)));
++ // expr is not in a block statement or result expression position, wrap in a block
++ let parent_node = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(call_expr.hir_id));
++ if !matches!(parent_node, Some(Node::Block(_))) && !matches!(parent_node, Some(Node::Stmt(_))) {
++ let block_indent = call_expr_indent + 4;
++ stmts_and_call_snippet =
++ reindent_multiline(stmts_and_call_snippet.into(), true, Some(block_indent)).into_owned();
++ stmts_and_call_snippet = format!(
++ "{{\n{}{}\n{}}}",
++ " ".repeat(block_indent),
++ &stmts_and_call_snippet,
++ " ".repeat(call_expr_indent)
++ );
++ }
++ stmts_and_call_snippet
++}
++
+fn lint_unit_args(cx: &LateContext<'_>, expr: &Expr<'_>, args_to_recover: &[&Expr<'_>]) {
+ let mut applicability = Applicability::MachineApplicable;
+ let (singular, plural) = if args_to_recover.len() > 1 {
+ ("", "s")
+ } else {
+ ("a ", "")
+ };
+ span_lint_and_then(
+ cx,
+ UNIT_ARG,
+ expr.span,
+ &format!("passing {}unit value{} to a function", singular, plural),
+ |db| {
+ let mut or = "";
+ args_to_recover
+ .iter()
+ .filter_map(|arg| {
+ if_chain! {
+ if let ExprKind::Block(block, _) = arg.kind;
+ if block.expr.is_none();
+ if let Some(last_stmt) = block.stmts.iter().last();
+ if let StmtKind::Semi(last_expr) = last_stmt.kind;
+ if let Some(snip) = snippet_opt(cx, last_expr.span);
+ then {
+ Some((
+ last_stmt.span,
+ snip,
+ ))
+ }
+ else {
+ None
+ }
+ }
+ })
+ .for_each(|(span, sugg)| {
+ db.span_suggestion(
+ span,
+ "remove the semicolon from the last statement in the block",
+ sugg,
+ Applicability::MaybeIncorrect,
+ );
+ or = "or ";
++ applicability = Applicability::MaybeIncorrect;
+ });
- .enumerate()
- .map(|(i, arg)| {
- let indent = if i == 0 {
- 0
- } else {
- indent_of(cx, expr.span).unwrap_or(0)
- };
- format!(
- "{}{};",
- " ".repeat(indent),
- snippet_block_with_applicability(cx, arg.span, "..", Some(expr.span), &mut applicability)
- )
- })
- .collect::<Vec<String>>();
- let mut and = "";
- if !sugg.is_empty() {
- let plural = if sugg.len() > 1 { "s" } else { "" };
- db.span_suggestion(
- expr.span.with_hi(expr.span.lo()),
- &format!("{}move the expression{} in front of the call...", or, plural),
- format!("{}\n", sugg.join("\n")),
- applicability,
++
++ let arg_snippets: Vec<String> = args_to_recover
++ .iter()
++ .filter_map(|arg| snippet_opt(cx, arg.span))
++ .collect();
++ let arg_snippets_without_empty_blocks: Vec<String> = args_to_recover
+ .iter()
+ .filter(|arg| !is_empty_block(arg))
- and = "...and "
++ .filter_map(|arg| snippet_opt(cx, arg.span))
++ .collect();
++
++ if let Some(call_snippet) = snippet_opt(cx, expr.span) {
++ let sugg = fmt_stmts_and_call(
++ cx,
++ expr,
++ &call_snippet,
++ &arg_snippets,
++ &arg_snippets_without_empty_blocks,
+ );
- db.multipart_suggestion(
- &format!("{}use {}unit literal{} instead", and, singular, plural),
- args_to_recover
- .iter()
- .map(|arg| (arg.span, "()".to_string()))
- .collect::<Vec<_>>(),
- applicability,
- );
++
++ if arg_snippets_without_empty_blocks.is_empty() {
++ db.multipart_suggestion(
++ &format!("use {}unit literal{} instead", singular, plural),
++ args_to_recover
++ .iter()
++ .map(|arg| (arg.span, "()".to_string()))
++ .collect::<Vec<_>>(),
++ applicability,
++ );
++ } else {
++ let plural = arg_snippets_without_empty_blocks.len() > 1;
++ let empty_or_s = if plural { "s" } else { "" };
++ let it_or_them = if plural { "them" } else { "it" };
++ db.span_suggestion(
++ expr.span,
++ &format!(
++ "{}move the expression{} in front of the call and replace {} with the unit literal `()`",
++ or, empty_or_s, it_or_them
++ ),
++ sugg,
++ applicability,
++ );
++ }
+ }
+ },
+ );
+}
+
+fn is_empty_block(expr: &Expr<'_>) -> bool {
+ matches!(
+ expr.kind,
+ ExprKind::Block(
+ Block {
+ stmts: &[], expr: None, ..
+ },
+ _,
+ )
+ )
+}
+
+fn is_questionmark_desugar_marked_call(expr: &Expr<'_>) -> bool {
+ use rustc_span::hygiene::DesugaringKind;
+ if let ExprKind::Call(ref callee, _) = expr.kind {
+ callee.span.is_desugaring(DesugaringKind::QuestionMark)
+ } else {
+ false
+ }
+}
+
+fn is_unit(ty: Ty<'_>) -> bool {
+ matches!(ty.kind(), ty::Tuple(slice) if slice.is_empty())
+}
+
+fn is_unit_literal(expr: &Expr<'_>) -> bool {
+ matches!(expr.kind, ExprKind::Tup(ref slice) if slice.is_empty())
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// let x = u64::MAX;
+ /// x as f64;
+ /// ```
+ pub CAST_PRECISION_LOSS,
+ pedantic,
+ "casts that cause loss of precision, e.g., `x as f32` where `x: u64`"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// let y: i8 = -1;
+ /// y as u128; // will return 18446744073709551615
+ /// ```
+ pub CAST_SIGN_LOSS,
+ pedantic,
+ "casts from signed types to unsigned types, e.g., `x as u32` where `x: i32`"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// fn as_u8(x: u64) -> u8 {
+ /// x as u8
+ /// }
+ /// ```
+ pub CAST_POSSIBLE_TRUNCATION,
+ pedantic,
+ "casts that may cause truncation of the value, e.g., `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// u32::MAX as i32; // will yield a value of `-1`
+ /// ```
+ pub CAST_POSSIBLE_WRAP,
+ pedantic,
+ "casts that may cause wrapping around the value, e.g., `x as i32` where `x: u32` and `x > i32::MAX`"
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// fn as_u64(x: u8) -> u64 {
+ /// x as u64
+ /// }
+ /// ```
+ ///
+ /// Using `::from` would look like this:
+ ///
+ /// ```rust
+ /// fn as_u64(x: u8) -> u64 {
+ /// u64::from(x)
+ /// }
+ /// ```
+ pub CAST_LOSSLESS,
+ pedantic,
+ "casts using `as` that are known to be lossless, e.g., `x as u64` where `x: u8`"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for casts to the same type.
+ ///
+ /// **Why is this bad?** It's just unnecessary.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// let _ = 2i32 as i32;
+ /// ```
+ pub UNNECESSARY_CAST,
+ complexity,
+ "cast to the same type, e.g., `x as i32` where `x: i32`"
+}
+
+declare_clippy_lint! {
+ /// **What it does:** Checks for casts 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:**
+ /// ```rust
+ /// let _ = (&1u8 as *const u8) as *const u16;
+ /// let _ = (&mut 1u8 as *mut u8) as *mut u16;
+ /// ```
+ pub CAST_PTR_ALIGNMENT,
+ pedantic,
+ "cast from a pointer to a more-strictly-aligned pointer"
+}
+
+declare_clippy_lint! {
+ /// **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**
+ ///
+ /// ```rust
+ /// // Bad
+ /// fn fun() -> i32 { 1 }
+ /// let a = fun as i64;
+ ///
+ /// // Good
+ /// fn fun2() -> i32 { 1 }
+ /// let a = fun2 as usize;
+ /// ```
+ pub FN_TO_NUMERIC_CAST,
+ style,
+ "casting a function pointer to a numeric type other than usize"
+}
+
+declare_clippy_lint! {
+ /// **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**
+ ///
+ /// ```rust
+ /// // Bad
+ /// fn fn1() -> i16 {
+ /// 1
+ /// };
+ /// let _ = fn1 as i32;
+ ///
+ /// // Better: Cast to usize first, then comment with the reason for the truncation
+ /// fn fn2() -> i16 {
+ /// 1
+ /// };
+ /// let fn_ptr = fn2 as usize;
+ /// let fn_ptr_truncated = fn_ptr as i32;
+ /// ```
+ pub FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
+ style,
+ "casting a function pointer to a numeric type not wide enough to store the address"
+}
+
+/// Returns the size in bits of an integral type.
+/// Will return 0 if the type is not an int or uint variant
+fn int_ty_to_nbits(typ: Ty<'_>, tcx: TyCtxt<'_>) -> u64 {
+ match typ.kind() {
+ ty::Int(i) => match i {
+ IntTy::Isize => tcx.data_layout.pointer_size.bits(),
+ IntTy::I8 => 8,
+ IntTy::I16 => 16,
+ IntTy::I32 => 32,
+ IntTy::I64 => 64,
+ IntTy::I128 => 128,
+ },
+ ty::Uint(i) => match i {
+ UintTy::Usize => tcx.data_layout.pointer_size.bits(),
+ UintTy::U8 => 8,
+ UintTy::U16 => 16,
+ UintTy::U32 => 32,
+ UintTy::U64 => 64,
+ UintTy::U128 => 128,
+ },
+ _ => 0,
+ }
+}
+
+fn is_isize_or_usize(typ: Ty<'_>) -> bool {
+ matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
+}
+
+fn span_precision_loss_lint(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to_f64: bool) {
+ let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
+ let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
+ let arch_dependent_str = "on targets with 64-bit wide pointers ";
+ let from_nbits_str = if arch_dependent {
+ "64".to_owned()
+ } else if is_isize_or_usize(cast_from) {
+ "32 or 64".to_owned()
+ } else {
+ int_ty_to_nbits(cast_from, cx.tcx).to_string()
+ };
+ span_lint(
+ cx,
+ CAST_PRECISION_LOSS,
+ expr.span,
+ &format!(
+ "casting `{0}` to `{1}` causes a loss of precision {2}(`{0}` is {3} bits wide, \
+ but `{1}`'s mantissa is only {4} bits wide)",
+ cast_from,
+ if cast_to_f64 { "f64" } else { "f32" },
+ if arch_dependent { arch_dependent_str } else { "" },
+ from_nbits_str,
+ mantissa_nbits
+ ),
+ );
+}
+
+fn should_strip_parens(op: &Expr<'_>, snip: &str) -> bool {
+ if let ExprKind::Binary(_, _, _) = op.kind {
+ if snip.starts_with('(') && snip.ends_with(')') {
+ return true;
+ }
+ }
+ false
+}
+
+fn span_lossless_lint(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
+ // Do not suggest using From in consts/statics until it is valid to do so (see #2267).
+ if in_constant(cx, expr.hir_id) {
+ return;
+ }
+ // The suggestion is to use a function call, so if the original expression
+ // has parens on the outside, they are no longer needed.
+ let mut applicability = Applicability::MachineApplicable;
+ let opt = snippet_opt(cx, op.span);
+ let sugg = opt.as_ref().map_or_else(
+ || {
+ applicability = Applicability::HasPlaceholders;
+ ".."
+ },
+ |snip| {
+ if should_strip_parens(op, snip) {
+ &snip[1..snip.len() - 1]
+ } else {
+ snip.as_str()
+ }
+ },
+ );
+
+ span_lint_and_sugg(
+ cx,
+ CAST_LOSSLESS,
+ expr.span,
+ &format!(
+ "casting `{}` to `{}` may become silently lossy if you later change the type",
+ cast_from, cast_to
+ ),
+ "try",
+ format!("{}::from({})", cast_to, sugg),
+ applicability,
+ );
+}
+
+enum ArchSuffix {
+ _32,
+ _64,
+ None,
+}
+
+fn check_loss_of_sign(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
+ if !cast_from.is_signed() || cast_to.is_signed() {
+ return;
+ }
+
+ // don't lint for positive constants
+ let const_val = constant(cx, &cx.typeck_results(), op);
+ if_chain! {
+ if let Some((const_val, _)) = const_val;
+ if let Constant::Int(n) = const_val;
+ if let ty::Int(ity) = *cast_from.kind();
+ if sext(cx.tcx, n, ity) >= 0;
+ then {
+ return
+ }
+ }
+
+ // don't lint for the result of methods that always return non-negative values
+ if let ExprKind::MethodCall(ref path, _, _, _) = op.kind {
+ let mut method_name = path.ident.name.as_str();
+ let allowed_methods = ["abs", "checked_abs", "rem_euclid", "checked_rem_euclid"];
+
+ if_chain! {
+ if method_name == "unwrap";
+ if let Some(arglist) = method_chain_args(op, &["unwrap"]);
+ if let ExprKind::MethodCall(ref inner_path, _, _, _) = &arglist[0][0].kind;
+ then {
+ method_name = inner_path.ident.name.as_str();
+ }
+ }
+
+ if allowed_methods.iter().any(|&name| method_name == name) {
+ return;
+ }
+ }
+
+ span_lint(
+ cx,
+ CAST_SIGN_LOSS,
+ expr.span,
+ &format!(
+ "casting `{}` to `{}` may lose the sign of the value",
+ cast_from, cast_to
+ ),
+ );
+}
+
+fn check_truncation_and_wrapping(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
+ let arch_64_suffix = " on targets with 64-bit wide pointers";
+ let arch_32_suffix = " on targets with 32-bit wide pointers";
+ let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
+ let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
+ let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
+ let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
+ match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
+ (true, true) | (false, false) => (
+ to_nbits < from_nbits,
+ ArchSuffix::None,
+ to_nbits == from_nbits && cast_unsigned_to_signed,
+ ArchSuffix::None,
+ ),
+ (true, false) => (
+ to_nbits <= 32,
+ if to_nbits == 32 {
+ ArchSuffix::_64
+ } else {
+ ArchSuffix::None
+ },
+ to_nbits <= 32 && cast_unsigned_to_signed,
+ ArchSuffix::_32,
+ ),
+ (false, true) => (
+ from_nbits == 64,
+ ArchSuffix::_32,
+ cast_unsigned_to_signed,
+ if from_nbits == 64 {
+ ArchSuffix::_64
+ } else {
+ ArchSuffix::_32
+ },
+ ),
+ };
+ if span_truncation {
+ span_lint(
+ cx,
+ CAST_POSSIBLE_TRUNCATION,
+ expr.span,
+ &format!(
+ "casting `{}` to `{}` may truncate the value{}",
+ cast_from,
+ cast_to,
+ match suffix_truncation {
+ ArchSuffix::_32 => arch_32_suffix,
+ ArchSuffix::_64 => arch_64_suffix,
+ ArchSuffix::None => "",
+ }
+ ),
+ );
+ }
+ if span_wrap {
+ span_lint(
+ cx,
+ CAST_POSSIBLE_WRAP,
+ expr.span,
+ &format!(
+ "casting `{}` to `{}` may wrap around the value{}",
+ cast_from,
+ cast_to,
+ match suffix_wrap {
+ ArchSuffix::_32 => arch_32_suffix,
+ ArchSuffix::_64 => arch_64_suffix,
+ ArchSuffix::None => "",
+ }
+ ),
+ );
+ }
+}
+
+fn check_lossless(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
+ let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed();
+ let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
+ let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
+ if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && !cast_signed_to_unsigned
+ {
+ span_lossless_lint(cx, expr, op, cast_from, cast_to);
+ }
+}
+
+declare_lint_pass!(Casts => [
+ CAST_PRECISION_LOSS,
+ CAST_SIGN_LOSS,
+ CAST_POSSIBLE_TRUNCATION,
+ CAST_POSSIBLE_WRAP,
+ CAST_LOSSLESS,
+ UNNECESSARY_CAST,
+ CAST_PTR_ALIGNMENT,
+ FN_TO_NUMERIC_CAST,
+ FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
+]);
+
+// Check if the given type is either `core::ffi::c_void` or
+// one of the platform specific `libc::<platform>::c_void` of libc.
+fn is_c_void(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
+ if let ty::Adt(adt, _) = ty.kind() {
+ let names = cx.get_def_path(adt.did);
+
+ if names.is_empty() {
+ return false;
+ }
+ if names[0] == sym!(libc) || names[0] == sym::core && *names.last().unwrap() == sym!(c_void) {
+ return true;
+ }
+ }
+ false
+}
+
+/// Returns the mantissa bits wide of a fp type.
+/// Will return 0 if the type is not a fp
+fn fp_ty_mantissa_nbits(typ: Ty<'_>) -> u32 {
+ match typ.kind() {
+ ty::Float(FloatTy::F32) => 23,
+ ty::Float(FloatTy::F64) | ty::Infer(InferTy::FloatVar(_)) => 52,
+ _ => 0,
+ }
+}
+
+impl<'tcx> LateLintPass<'tcx> for Casts {
+ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
+ if expr.span.from_expansion() {
+ return;
+ }
+ if let ExprKind::Cast(ref ex, _) = expr.kind {
+ let (cast_from, cast_to) = (cx.typeck_results().expr_ty(ex), cx.typeck_results().expr_ty(expr));
+ lint_fn_to_numeric_cast(cx, expr, ex, cast_from, cast_to);
+ if let ExprKind::Lit(ref lit) = ex.kind {
+ if_chain! {
+ if let LitKind::Int(n, _) = lit.node;
+ if let Some(src) = snippet_opt(cx, lit.span);
+ if cast_to.is_floating_point();
+ if let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node);
+ let from_nbits = 128 - n.leading_zeros();
+ let to_nbits = fp_ty_mantissa_nbits(cast_to);
+ if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits && num_lit.is_decimal();
+ then {
+ span_lint_and_sugg(
+ cx,
+ UNNECESSARY_CAST,
+ expr.span,
+ &format!("casting integer literal to `{}` is unnecessary", cast_to),
+ "try",
+ format!("{}_{}", n, cast_to),
+ Applicability::MachineApplicable,
+ );
+ return;
+ }
+ }
+ match lit.node {
+ LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) => {},
+ _ => {
+ if cast_from.kind() == cast_to.kind() && !in_external_macro(cx.sess(), expr.span) {
+ span_lint(
+ cx,
+ UNNECESSARY_CAST,
+ expr.span,
+ &format!(
+ "casting to the same type is unnecessary (`{}` -> `{}`)",
+ cast_from, cast_to
+ ),
+ );
+ }
+ },
+ }
+ }
+ if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
+ lint_numeric_casts(cx, expr, ex, cast_from, cast_to);
+ }
+
+ lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
+ }
+ }
+}
+
+fn lint_numeric_casts<'tcx>(
+ cx: &LateContext<'tcx>,
+ expr: &Expr<'tcx>,
+ cast_expr: &Expr<'_>,
+ cast_from: Ty<'tcx>,
+ cast_to: Ty<'tcx>,
+) {
+ match (cast_from.is_integral(), cast_to.is_integral()) {
+ (true, false) => {
+ let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
+ let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.kind() {
+ 32
+ } else {
+ 64
+ };
+ if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
+ span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
+ }
+ if from_nbits < to_nbits {
+ span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
+ }
+ },
+ (false, true) => {
+ span_lint(
+ cx,
+ CAST_POSSIBLE_TRUNCATION,
+ expr.span,
+ &format!("casting `{}` to `{}` may truncate the value", cast_from, cast_to),
+ );
+ if !cast_to.is_signed() {
+ span_lint(
+ cx,
+ CAST_SIGN_LOSS,
+ expr.span,
+ &format!(
+ "casting `{}` to `{}` may lose the sign of the value",
+ cast_from, cast_to
+ ),
+ );
+ }
+ },
+ (true, true) => {
+ check_loss_of_sign(cx, expr, cast_expr, cast_from, cast_to);
+ check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
+ check_lossless(cx, expr, cast_expr, cast_from, cast_to);
+ },
+ (false, false) => {
+ if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.kind(), &cast_to.kind()) {
+ span_lint(
+ cx,
+ CAST_POSSIBLE_TRUNCATION,
+ expr.span,
+ "casting `f64` to `f32` may truncate the value",
+ );
+ }
+ if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.kind(), &cast_to.kind()) {
+ span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
+ }
+ },
+ }
+}
+
+fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, cast_from: Ty<'tcx>, cast_to: Ty<'tcx>) {
+ if_chain! {
+ if let ty::RawPtr(from_ptr_ty) = &cast_from.kind();
+ if let ty::RawPtr(to_ptr_ty) = &cast_to.kind();
+ if let Ok(from_layout) = cx.layout_of(from_ptr_ty.ty);
+ if let Ok(to_layout) = cx.layout_of(to_ptr_ty.ty);
+ if from_layout.align.abi < to_layout.align.abi;
+ // with c_void, we inherently need to trust the user
+ if !is_c_void(cx, from_ptr_ty.ty);
+ // when casting from a ZST, we don't know enough to properly lint
+ if !from_layout.is_zst();
+ then {
+ span_lint(
+ cx,
+ CAST_PTR_ALIGNMENT,
+ expr.span,
+ &format!(
+ "casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)",
+ cast_from,
+ cast_to,
+ from_layout.align.abi.bytes(),
+ to_layout.align.abi.bytes(),
+ ),
+ );
+ }
+ }
+}
+
+fn lint_fn_to_numeric_cast(
+ cx: &LateContext<'_>,
+ expr: &Expr<'_>,
+ cast_expr: &Expr<'_>,
+ cast_from: Ty<'_>,
+ cast_to: Ty<'_>,
+) {
+ // We only want to check casts to `ty::Uint` or `ty::Int`
+ match cast_to.kind() {
+ ty::Uint(_) | ty::Int(..) => { /* continue on */ },
+ _ => return,
+ }
+ match cast_from.kind() {
+ ty::FnDef(..) | ty::FnPtr(_) => {
+ let mut applicability = Applicability::MaybeIncorrect;
+ let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability);
+
+ let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
+ if to_nbits < cx.tcx.data_layout.pointer_size.bits() {
+ span_lint_and_sugg(
+ cx,
+ FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
+ expr.span,
+ &format!(
+ "casting function pointer `{}` to `{}`, which truncates the value",
+ from_snippet, cast_to
+ ),
+ "try",
+ format!("{} as usize", from_snippet),
+ applicability,
+ );
+ } else if *cast_to.kind() != ty::Uint(UintTy::Usize) {
+ span_lint_and_sugg(
+ cx,
+ FN_TO_NUMERIC_CAST,
+ expr.span,
+ &format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
+ "try",
+ format!("{} as usize", from_snippet),
+ applicability,
+ );
+ }
+ },
+ _ => {},
+ }
+}
+
+declare_clippy_lint! {
+ /// **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.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust
+ /// # use std::rc::Rc;
+ /// struct Foo {
+ /// inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
+ /// }
+ /// ```
+ pub TYPE_COMPLEXITY,
+ complexity,
+ "usage of very complex types that might be better factored into `type` definitions"
+}
+
+pub struct TypeComplexity {
+ threshold: u64,
+}
+
+impl TypeComplexity {
+ #[must_use]
+ pub fn new(threshold: u64) -> Self {
+ Self { threshold }
+ }
+}
+
+impl_lint_pass!(TypeComplexity => [TYPE_COMPLEXITY]);
+
+impl<'tcx> LateLintPass<'tcx> for TypeComplexity {
+ fn check_fn(
+ &mut self,
+ cx: &LateContext<'tcx>,
+ _: FnKind<'tcx>,
+ decl: &'tcx FnDecl<'_>,
+ _: &'tcx Body<'_>,
+ _: Span,
+ _: HirId,
+ ) {
+ self.check_fndecl(cx, decl);
+ }
+
+ fn check_struct_field(&mut self, cx: &LateContext<'tcx>, field: &'tcx hir::StructField<'_>) {
+ // enum variants are also struct fields now
+ self.check_type(cx, &field.ty);
+ }
+
+ fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
+ match item.kind {
+ ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
+ // functions, enums, structs, impls and traits are covered
+ _ => (),
+ }
+ }
+
+ fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
+ match item.kind {
+ TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
+ TraitItemKind::Fn(FnSig { ref decl, .. }, TraitFn::Required(_)) => self.check_fndecl(cx, decl),
+ // methods with default impl are covered by check_fn
+ _ => (),
+ }
+ }
+
+ fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
+ match item.kind {
+ ImplItemKind::Const(ref ty, _) | ImplItemKind::TyAlias(ref ty) => self.check_type(cx, ty),
+ // methods are covered by check_fn
+ _ => (),
+ }
+ }
+
+ fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
+ if let Some(ref ty) = local.ty {
+ self.check_type(cx, ty);
+ }
+ }
+}
+
+impl<'tcx> TypeComplexity {
+ fn check_fndecl(&self, cx: &LateContext<'tcx>, decl: &'tcx FnDecl<'_>) {
+ for arg in decl.inputs {
+ self.check_type(cx, arg);
+ }
+ if let FnRetTy::Return(ref ty) = decl.output {
+ self.check_type(cx, ty);
+ }
+ }
+
+ fn check_type(&self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) {
+ if ty.span.from_expansion() {
+ return;
+ }
+ let score = {
+ let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
+ visitor.visit_ty(ty);
+ visitor.score
+ };
+
+ if score > self.threshold {
+ span_lint(
+ cx,
+ TYPE_COMPLEXITY,
+ ty.span,
+ "very complex type used. Consider factoring parts into `type` definitions",
+ );
+ }
+ }
+}
+
+/// Walks a type and assigns a complexity score to it.
+struct TypeComplexityVisitor {
+ /// total complexity score of the type
+ score: u64,
+ /// current nesting level
+ nest: u64,
+}
+
+impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
+ type Map = Map<'tcx>;
+
+ fn visit_ty(&mut self, ty: &'tcx hir::Ty<'_>) {
+ let (add_score, sub_nest) = match ty.kind {
+ // _, &x and *x have only small overhead; don't mess with nesting level
+ TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0),
+
+ // the "normal" components of a type: named types, arrays/tuples
+ TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
+
+ // function types bring a lot of overhead
+ TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1),
+
+ TyKind::TraitObject(ref param_bounds, _) => {
+ let has_lifetime_parameters = param_bounds.iter().any(|bound| {
+ bound
+ .bound_generic_params
+ .iter()
+ .any(|gen| matches!(gen.kind, GenericParamKind::Lifetime { .. }))
+ });
+ if has_lifetime_parameters {
+ // complex trait bounds like A<'a, 'b>
+ (50 * self.nest, 1)
+ } else {
+ // simple trait bounds like A + B
+ (20 * self.nest, 0)
+ }
+ },
+
+ _ => (0, 0),
+ };
+ self.score += add_score;
+ self.nest += sub_nest;
+ walk_ty(self, ty);
+ self.nest -= sub_nest;
+ }
+ fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+ NestedVisitorMap::None
+ }
+}
+
+declare_clippy_lint! {
+ /// **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`.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust,ignore
+ /// 'x' as u8
+ /// ```
+ ///
+ /// A better version, using the byte literal:
+ ///
+ /// ```rust,ignore
+ /// b'x'
+ /// ```
+ pub CHAR_LIT_AS_U8,
+ complexity,
+ "casting a character literal to `u8` truncates"
+}
+
+declare_lint_pass!(CharLitAsU8 => [CHAR_LIT_AS_U8]);
+
+impl<'tcx> LateLintPass<'tcx> for CharLitAsU8 {
+ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
+ if_chain! {
+ if !expr.span.from_expansion();
+ if let ExprKind::Cast(e, _) = &expr.kind;
+ if let ExprKind::Lit(l) = &e.kind;
+ if let LitKind::Char(c) = l.node;
+ if ty::Uint(UintTy::U8) == *cx.typeck_results().expr_ty(expr).kind();
+ then {
+ let mut applicability = Applicability::MachineApplicable;
+ let snippet = snippet_with_applicability(cx, e.span, "'x'", &mut applicability);
+
+ span_lint_and_then(
+ cx,
+ CHAR_LIT_AS_U8,
+ expr.span,
+ "casting a character literal to `u8` truncates",
+ |diag| {
+ diag.note("`char` is four bytes wide, but `u8` is a single byte");
+
+ if c.is_ascii() {
+ diag.span_suggestion(
+ expr.span,
+ "use a byte literal instead",
+ format!("b{}", snippet),
+ applicability,
+ );
+ }
+ });
+ }
+ }
+ }
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ ///
+ /// ```rust
+ /// let vec: Vec<isize> = Vec::new();
+ /// if vec.len() <= 0 {}
+ /// if 100 > i32::MAX {}
+ /// ```
+ pub ABSURD_EXTREME_COMPARISONS,
+ correctness,
+ "a comparison with a maximum or minimum value that is always true or false"
+}
+
+declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]);
+
+enum ExtremeType {
+ Minimum,
+ Maximum,
+}
+
+struct ExtremeExpr<'a> {
+ which: ExtremeType,
+ expr: &'a Expr<'a>,
+}
+
+enum AbsurdComparisonResult {
+ AlwaysFalse,
+ AlwaysTrue,
+ InequalityImpossible,
+}
+
+fn is_cast_between_fixed_and_target<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
+ if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
+ let precast_ty = cx.typeck_results().expr_ty(cast_exp);
+ let cast_ty = cx.typeck_results().expr_ty(expr);
+
+ return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
+ }
+
+ false
+}
+
+fn detect_absurd_comparison<'tcx>(
+ cx: &LateContext<'tcx>,
+ op: BinOpKind,
+ lhs: &'tcx Expr<'_>,
+ rhs: &'tcx Expr<'_>,
+) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
+ use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
+ use crate::types::ExtremeType::{Maximum, Minimum};
+ use crate::utils::comparisons::{normalize_comparison, Rel};
+
+ // absurd comparison only makes sense on primitive types
+ // primitive types don't implement comparison operators with each other
+ if cx.typeck_results().expr_ty(lhs) != cx.typeck_results().expr_ty(rhs) {
+ return None;
+ }
+
+ // comparisons between fix sized types and target sized types are considered unanalyzable
+ if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
+ return None;
+ }
+
+ let (rel, normalized_lhs, normalized_rhs) = normalize_comparison(op, lhs, rhs)?;
+
+ let lx = detect_extreme_expr(cx, normalized_lhs);
+ let rx = detect_extreme_expr(cx, normalized_rhs);
+
+ Some(match rel {
+ Rel::Lt => {
+ match (lx, rx) {
+ (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
+ (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
+ _ => return None,
+ }
+ },
+ Rel::Le => {
+ match (lx, rx) {
+ (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
+ (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
+ (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
+ (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
+ _ => return None,
+ }
+ },
+ Rel::Ne | Rel::Eq => return None,
+ })
+}
+
+fn detect_extreme_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> {
+ use crate::types::ExtremeType::{Maximum, Minimum};
+
+ let ty = cx.typeck_results().expr_ty(expr);
+
+ let cv = constant(cx, cx.typeck_results(), expr)?.0;
+
+ let which = match (ty.kind(), cv) {
+ (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => Minimum,
+ (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MIN >> (128 - int_bits(cx.tcx, ity)), ity) => {
+ Minimum
+ },
+
+ (&ty::Bool, Constant::Bool(true)) => Maximum,
+ (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MAX >> (128 - int_bits(cx.tcx, ity)), ity) => {
+ Maximum
+ },
+ (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::MAX, uty) == i => Maximum,
+
+ _ => return None,
+ };
+ Some(ExtremeExpr { which, expr })
+}
+
+impl<'tcx> LateLintPass<'tcx> for AbsurdExtremeComparisons {
+ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
+ use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
+ use crate::types::ExtremeType::{Maximum, Minimum};
+
+ if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
+ if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
+ if !expr.span.from_expansion() {
+ let msg = "this comparison involving the minimum or maximum element for this \
+ type contains a case that is always true or always false";
+
+ let conclusion = match result {
+ AlwaysFalse => "this comparison is always false".to_owned(),
+ AlwaysTrue => "this comparison is always true".to_owned(),
+ InequalityImpossible => format!(
+ "the case where the two sides are not equal never occurs, consider using `{} == {}` \
+ instead",
+ snippet(cx, lhs.span, "lhs"),
+ snippet(cx, rhs.span, "rhs")
+ ),
+ };
+
+ let help = format!(
+ "because `{}` is the {} value for this type, {}",
+ snippet(cx, culprit.expr.span, "x"),
+ match culprit.which {
+ Minimum => "minimum",
+ Maximum => "maximum",
+ },
+ conclusion
+ );
+
+ span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, None, &help);
+ }
+ }
+ }
+ }
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ /// ```rust
+ /// let x: u8 = 1;
+ /// (x as u32) > 300;
+ /// ```
+ pub INVALID_UPCAST_COMPARISONS,
+ pedantic,
+ "a comparison involving an upcast which is always true or false"
+}
+
+declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
+
+#[derive(Copy, Clone, Debug, Eq)]
+enum FullInt {
+ S(i128),
+ U(u128),
+}
+
+impl FullInt {
+ #[allow(clippy::cast_sign_loss)]
+ #[must_use]
+ fn cmp_s_u(s: i128, u: u128) -> Ordering {
+ if s < 0 {
+ Ordering::Less
+ } else if u > (i128::MAX as u128) {
+ Ordering::Greater
+ } else {
+ (s as u128).cmp(&u)
+ }
+ }
+}
+
+impl PartialEq for FullInt {
+ #[must_use]
+ fn eq(&self, other: &Self) -> bool {
+ self.partial_cmp(other).expect("`partial_cmp` only returns `Some(_)`") == Ordering::Equal
+ }
+}
+
+impl PartialOrd for FullInt {
+ #[must_use]
+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+ Some(match (self, other) {
+ (&Self::S(s), &Self::S(o)) => s.cmp(&o),
+ (&Self::U(s), &Self::U(o)) => s.cmp(&o),
+ (&Self::S(s), &Self::U(o)) => Self::cmp_s_u(s, o),
+ (&Self::U(s), &Self::S(o)) => Self::cmp_s_u(o, s).reverse(),
+ })
+ }
+}
++
+impl Ord for FullInt {
+ #[must_use]
+ fn cmp(&self, other: &Self) -> Ordering {
+ self.partial_cmp(other)
+ .expect("`partial_cmp` for FullInt can never return `None`")
+ }
+}
+
+fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> {
+ if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
+ let pre_cast_ty = cx.typeck_results().expr_ty(cast_exp);
+ let cast_ty = cx.typeck_results().expr_ty(expr);
+ // if it's a cast from i32 to u32 wrapping will invalidate all these checks
+ if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
+ return None;
+ }
+ match pre_cast_ty.kind() {
+ ty::Int(int_ty) => Some(match int_ty {
+ IntTy::I8 => (FullInt::S(i128::from(i8::MIN)), FullInt::S(i128::from(i8::MAX))),
+ IntTy::I16 => (FullInt::S(i128::from(i16::MIN)), FullInt::S(i128::from(i16::MAX))),
+ IntTy::I32 => (FullInt::S(i128::from(i32::MIN)), FullInt::S(i128::from(i32::MAX))),
+ IntTy::I64 => (FullInt::S(i128::from(i64::MIN)), FullInt::S(i128::from(i64::MAX))),
+ IntTy::I128 => (FullInt::S(i128::MIN), FullInt::S(i128::MAX)),
+ IntTy::Isize => (FullInt::S(isize::MIN as i128), FullInt::S(isize::MAX as i128)),
+ }),
+ ty::Uint(uint_ty) => Some(match uint_ty {
+ UintTy::U8 => (FullInt::U(u128::from(u8::MIN)), FullInt::U(u128::from(u8::MAX))),
+ UintTy::U16 => (FullInt::U(u128::from(u16::MIN)), FullInt::U(u128::from(u16::MAX))),
+ UintTy::U32 => (FullInt::U(u128::from(u32::MIN)), FullInt::U(u128::from(u32::MAX))),
+ UintTy::U64 => (FullInt::U(u128::from(u64::MIN)), FullInt::U(u128::from(u64::MAX))),
+ UintTy::U128 => (FullInt::U(u128::MIN), FullInt::U(u128::MAX)),
+ UintTy::Usize => (FullInt::U(usize::MIN as u128), FullInt::U(usize::MAX as u128)),
+ }),
+ _ => None,
+ }
+ } else {
+ None
+ }
+}
+
+fn node_as_const_fullint<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<FullInt> {
+ let val = constant(cx, cx.typeck_results(), expr)?.0;
+ if let Constant::Int(const_int) = val {
+ match *cx.typeck_results().expr_ty(expr).kind() {
+ ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
+ ty::Uint(_) => Some(FullInt::U(const_int)),
+ _ => None,
+ }
+ } else {
+ None
+ }
+}
+
+fn err_upcast_comparison(cx: &LateContext<'_>, span: Span, expr: &Expr<'_>, always: bool) {
+ if let ExprKind::Cast(ref cast_val, _) = expr.kind {
+ span_lint(
+ cx,
+ INVALID_UPCAST_COMPARISONS,
+ span,
+ &format!(
+ "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
+ snippet(cx, cast_val.span, "the expression"),
+ if always { "true" } else { "false" },
+ ),
+ );
+ }
+}
+
+fn upcast_comparison_bounds_err<'tcx>(
+ cx: &LateContext<'tcx>,
+ span: Span,
+ rel: comparisons::Rel,
+ lhs_bounds: Option<(FullInt, FullInt)>,
+ lhs: &'tcx Expr<'_>,
+ rhs: &'tcx Expr<'_>,
+ invert: bool,
+) {
+ use crate::utils::comparisons::Rel;
+
+ if let Some((lb, ub)) = lhs_bounds {
+ if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
+ if rel == Rel::Eq || rel == Rel::Ne {
+ if norm_rhs_val < lb || norm_rhs_val > ub {
+ err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
+ }
+ } else if match rel {
+ Rel::Lt => {
+ if invert {
+ norm_rhs_val < lb
+ } else {
+ ub < norm_rhs_val
+ }
+ },
+ Rel::Le => {
+ if invert {
+ norm_rhs_val <= lb
+ } else {
+ ub <= norm_rhs_val
+ }
+ },
+ Rel::Eq | Rel::Ne => unreachable!(),
+ } {
+ err_upcast_comparison(cx, span, lhs, true)
+ } else if match rel {
+ Rel::Lt => {
+ if invert {
+ norm_rhs_val >= ub
+ } else {
+ lb >= norm_rhs_val
+ }
+ },
+ Rel::Le => {
+ if invert {
+ norm_rhs_val > ub
+ } else {
+ lb > norm_rhs_val
+ }
+ },
+ Rel::Eq | Rel::Ne => unreachable!(),
+ } {
+ err_upcast_comparison(cx, span, lhs, false)
+ }
+ }
+ }
+}
+
+impl<'tcx> LateLintPass<'tcx> for InvalidUpcastComparisons {
+ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
+ if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
+ let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
+ let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
+ val
+ } else {
+ return;
+ };
+
+ let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
+ let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
+
+ upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
+ upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
+ }
+ }
+}
+
+declare_clippy_lint! {
+ /// **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:**
+ /// ```rust
+ /// # use std::collections::HashMap;
+ /// # use std::hash::{Hash, BuildHasher};
+ /// # trait Serialize {};
+ /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { }
+ ///
+ /// pub fn foo(map: &mut HashMap<i32, i32>) { }
+ /// ```
+ /// could be rewritten as
+ /// ```rust
+ /// # use std::collections::HashMap;
+ /// # use std::hash::{Hash, BuildHasher};
+ /// # trait Serialize {};
+ /// impl<K: Hash + Eq, V, S: BuildHasher> Serialize for HashMap<K, V, S> { }
+ ///
+ /// pub fn foo<S: BuildHasher>(map: &mut HashMap<i32, i32, S>) { }
+ /// ```
+ pub IMPLICIT_HASHER,
+ pedantic,
+ "missing generalization over different hashers"
+}
+
+declare_lint_pass!(ImplicitHasher => [IMPLICIT_HASHER]);
+
+impl<'tcx> LateLintPass<'tcx> for ImplicitHasher {
+ #[allow(clippy::cast_possible_truncation, clippy::too_many_lines)]
+ fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
+ use rustc_span::BytePos;
+
+ fn suggestion<'tcx>(
+ cx: &LateContext<'tcx>,
+ diag: &mut DiagnosticBuilder<'_>,
+ generics_span: Span,
+ generics_suggestion_span: Span,
+ target: &ImplicitHasherType<'_>,
+ vis: ImplicitHasherConstructorVisitor<'_, '_, '_>,
+ ) {
+ let generics_snip = snippet(cx, generics_span, "");
+ // trim `<` `>`
+ let generics_snip = if generics_snip.is_empty() {
+ ""
+ } else {
+ &generics_snip[1..generics_snip.len() - 1]
+ };
+
+ multispan_sugg(
+ diag,
+ "consider adding a type parameter",
+ vec![
+ (
+ generics_suggestion_span,
+ format!(
+ "<{}{}S: ::std::hash::BuildHasher{}>",
+ generics_snip,
+ if generics_snip.is_empty() { "" } else { ", " },
+ if vis.suggestions.is_empty() {
+ ""
+ } else {
+ // request users to add `Default` bound so that generic constructors can be used
+ " + Default"
+ },
+ ),
+ ),
+ (
+ target.span(),
+ format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
+ ),
+ ],
+ );
+
+ if !vis.suggestions.is_empty() {
+ multispan_sugg(diag, "...and use generic constructor", vis.suggestions);
+ }
+ }
+
+ if !cx.access_levels.is_exported(item.hir_id) {
+ return;
+ }
+
+ match item.kind {
+ ItemKind::Impl {
+ ref generics,
+ self_ty: ref ty,
+ ref items,
+ ..
+ } => {
+ let mut vis = ImplicitHasherTypeVisitor::new(cx);
+ vis.visit_ty(ty);
+
+ for target in &vis.found {
+ if differing_macro_contexts(item.span, target.span()) {
+ return;
+ }
+
+ let generics_suggestion_span = generics.span.substitute_dummy({
+ let pos = snippet_opt(cx, item.span.until(target.span()))
+ .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)));
+ if let Some(pos) = pos {
+ Span::new(pos, pos, item.span.data().ctxt)
+ } else {
+ return;
+ }
+ });
+
+ let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
+ for item in items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) {
+ ctr_vis.visit_impl_item(item);
+ }
+
+ span_lint_and_then(
+ cx,
+ IMPLICIT_HASHER,
+ target.span(),
+ &format!(
+ "impl for `{}` should be generalized over different hashers",
+ target.type_name()
+ ),
+ move |diag| {
+ suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis);
+ },
+ );
+ }
+ },
+ ItemKind::Fn(ref sig, ref generics, body_id) => {
+ let body = cx.tcx.hir().body(body_id);
+
+ for ty in sig.decl.inputs {
+ let mut vis = ImplicitHasherTypeVisitor::new(cx);
+ vis.visit_ty(ty);
+
+ for target in &vis.found {
+ if in_external_macro(cx.sess(), generics.span) {
+ continue;
+ }
+ let generics_suggestion_span = generics.span.substitute_dummy({
+ let pos = snippet_opt(cx, item.span.until(body.params[0].pat.span))
+ .and_then(|snip| {
+ let i = snip.find("fn")?;
+ Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
+ })
+ .expect("failed to create span for type parameters");
+ Span::new(pos, pos, item.span.data().ctxt)
+ });
+
+ let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
+ ctr_vis.visit_body(body);
+
+ span_lint_and_then(
+ cx,
+ IMPLICIT_HASHER,
+ target.span(),
+ &format!(
+ "parameter of type `{}` should be generalized over different hashers",
+ target.type_name()
+ ),
+ move |diag| {
+ suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis);
+ },
+ );
+ }
+ }
+ },
+ _ => {},
+ }
+ }
+}
+
+enum ImplicitHasherType<'tcx> {
+ HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
+ HashSet(Span, Ty<'tcx>, Cow<'static, str>),
+}
+
+impl<'tcx> ImplicitHasherType<'tcx> {
+ /// Checks that `ty` is a target type without a `BuildHasher`.
+ fn new(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'_>) -> Option<Self> {
+ if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.kind {
+ let params: Vec<_> = path
+ .segments
+ .last()
+ .as_ref()?
+ .args
+ .as_ref()?
+ .args
+ .iter()
+ .filter_map(|arg| match arg {
+ GenericArg::Type(ty) => Some(ty),
+ _ => None,
+ })
+ .collect();
+ let params_len = params.len();
+
+ let ty = hir_ty_to_ty(cx.tcx, hir_ty);
+
+ if is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) && params_len == 2 {
+ Some(ImplicitHasherType::HashMap(
+ hir_ty.span,
+ ty,
+ snippet(cx, params[0].span, "K"),
+ snippet(cx, params[1].span, "V"),
+ ))
+ } else if is_type_diagnostic_item(cx, ty, sym!(hashset_type)) && params_len == 1 {
+ Some(ImplicitHasherType::HashSet(
+ hir_ty.span,
+ ty,
+ snippet(cx, params[0].span, "T"),
+ ))
+ } else {
+ None
+ }
+ } else {
+ None
+ }
+ }
+
+ fn type_name(&self) -> &'static str {
+ match *self {
+ ImplicitHasherType::HashMap(..) => "HashMap",
+ ImplicitHasherType::HashSet(..) => "HashSet",
+ }
+ }
+
+ fn type_arguments(&self) -> String {
+ match *self {
+ ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
+ ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
+ }
+ }
+
+ fn ty(&self) -> Ty<'tcx> {
+ match *self {
+ ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
+ }
+ }
+
+ fn span(&self) -> Span {
+ match *self {
+ ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
+ }
+ }
+}
+
+struct ImplicitHasherTypeVisitor<'a, 'tcx> {
+ cx: &'a LateContext<'tcx>,
+ found: Vec<ImplicitHasherType<'tcx>>,
+}
+
+impl<'a, 'tcx> ImplicitHasherTypeVisitor<'a, 'tcx> {
+ fn new(cx: &'a LateContext<'tcx>) -> Self {
+ Self { cx, found: vec![] }
+ }
+}
+
+impl<'a, 'tcx> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
+ type Map = Map<'tcx>;
+
+ fn visit_ty(&mut self, t: &'tcx hir::Ty<'_>) {
+ if let Some(target) = ImplicitHasherType::new(self.cx, t) {
+ self.found.push(target);
+ }
+
+ walk_ty(self, t);
+ }
+
+ fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+ NestedVisitorMap::None
+ }
+}
+
+/// Looks for default-hasher-dependent constructors like `HashMap::new`.
+struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
+ cx: &'a LateContext<'tcx>,
+ maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
+ target: &'b ImplicitHasherType<'tcx>,
+ suggestions: BTreeMap<Span, String>,
+}
+
+impl<'a, 'b, 'tcx> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
+ fn new(cx: &'a LateContext<'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
+ Self {
+ cx,
+ maybe_typeck_results: cx.maybe_typeck_results(),
+ target,
+ suggestions: BTreeMap::new(),
+ }
+ }
+}
+
+impl<'a, 'b, 'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
+ type Map = Map<'tcx>;
+
+ fn visit_body(&mut self, body: &'tcx Body<'_>) {
+ let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body.id()));
+ walk_body(self, body);
+ self.maybe_typeck_results = old_maybe_typeck_results;
+ }
+
+ fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
+ if_chain! {
+ if let ExprKind::Call(ref fun, ref args) = e.kind;
+ if let ExprKind::Path(QPath::TypeRelative(ref ty, ref method)) = fun.kind;
+ if let TyKind::Path(QPath::Resolved(None, ty_path)) = ty.kind;
+ then {
+ if !TyS::same_type(self.target.ty(), self.maybe_typeck_results.unwrap().expr_ty(e)) {
+ return;
+ }
+
+ if match_path(ty_path, &paths::HASHMAP) {
+ if method.ident.name == sym!(new) {
+ self.suggestions
+ .insert(e.span, "HashMap::default()".to_string());
+ } else if method.ident.name == sym!(with_capacity) {
+ self.suggestions.insert(
+ e.span,
+ format!(
+ "HashMap::with_capacity_and_hasher({}, Default::default())",
+ snippet(self.cx, args[0].span, "capacity"),
+ ),
+ );
+ }
+ } else if match_path(ty_path, &paths::HASHSET) {
+ if method.ident.name == sym!(new) {
+ self.suggestions
+ .insert(e.span, "HashSet::default()".to_string());
+ } else if method.ident.name == sym!(with_capacity) {
+ self.suggestions.insert(
+ e.span,
+ format!(
+ "HashSet::with_capacity_and_hasher({}, Default::default())",
+ snippet(self.cx, args[0].span, "capacity"),
+ ),
+ );
+ }
+ }
+ }
+ }
+
+ walk_expr(self, e);
+ }
+
+ fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+ NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
+ }
+}
+
+declare_clippy_lint! {
+ /// **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 behaviour.
+ /// `UnsafeCell` is the only way to obtain aliasable data that is considered
+ /// mutable.
+ ///
+ /// **Known problems:** None.
+ ///
+ /// **Example:**
+ /// ```rust,ignore
+ /// fn x(r: &i32) {
+ /// unsafe {
+ /// *(r as *const _ as *mut _) += 1;
+ /// }
+ /// }
+ /// ```
+ ///
+ /// Instead consider using interior mutability types.
+ ///
+ /// ```rust
+ /// use std::cell::UnsafeCell;
+ ///
+ /// fn x(r: &UnsafeCell<i32>) {
+ /// unsafe {
+ /// *r.get() += 1;
+ /// }
+ /// }
+ /// ```
+ pub CAST_REF_TO_MUT,
+ correctness,
+ "a cast of reference to a mutable pointer"
+}
+
+declare_lint_pass!(RefToMut => [CAST_REF_TO_MUT]);
+
+impl<'tcx> LateLintPass<'tcx> for RefToMut {
+ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
+ if_chain! {
+ if let ExprKind::Unary(UnOp::UnDeref, e) = &expr.kind;
+ if let ExprKind::Cast(e, t) = &e.kind;
+ if let TyKind::Ptr(MutTy { mutbl: Mutability::Mut, .. }) = t.kind;
+ if let ExprKind::Cast(e, t) = &e.kind;
+ if let TyKind::Ptr(MutTy { mutbl: Mutability::Not, .. }) = t.kind;
+ if let ty::Ref(..) = cx.typeck_results().node_type(e.hir_id).kind();
+ then {
+ span_lint(
+ cx,
+ CAST_REF_TO_MUT,
+ expr.span,
+ "casting `&T` to `&mut T` may cause undefined behavior, consider instead using an `UnsafeCell`",
+ );
+ }
+ }
+ }
+}
--- /dev/null
- use crate::utils::paths;
+use crate::utils;
- if utils::match_type(cx, &cx.typeck_results().expr_ty(vec), &paths::VEC);
+use crate::utils::sugg::Sugg;
+use if_chain::if_chain;
+use rustc_errors::Applicability;
+use rustc_hir::{Expr, ExprKind, Mutability, Param, Pat, PatKind, Path, PathSegment, QPath};
+use rustc_lint::{LateContext, LateLintPass};
+use rustc_middle::ty::{self, subst::GenericArgKind};
+use rustc_session::{declare_lint_pass, declare_tool_lint};
+use rustc_span::symbol::Ident;
+
+declare_clippy_lint! {
+ /// **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:**
+ ///
+ /// ```rust
+ /// # struct A;
+ /// # impl A { fn foo(&self) {} }
+ /// # let mut vec: Vec<A> = Vec::new();
+ /// vec.sort_by(|a, b| a.foo().cmp(&b.foo()));
+ /// ```
+ /// Use instead:
+ /// ```rust
+ /// # struct A;
+ /// # impl A { fn foo(&self) {} }
+ /// # let mut vec: Vec<A> = Vec::new();
+ /// vec.sort_by_key(|a| a.foo());
+ /// ```
+ pub UNNECESSARY_SORT_BY,
+ complexity,
+ "Use of `Vec::sort_by` when `Vec::sort_by_key` or `Vec::sort` would be clearer"
+}
+
+declare_lint_pass!(UnnecessarySortBy => [UNNECESSARY_SORT_BY]);
+
+enum LintTrigger {
+ Sort(SortDetection),
+ SortByKey(SortByKeyDetection),
+}
+
+struct SortDetection {
+ vec_name: String,
+ unstable: bool,
+}
+
+struct SortByKeyDetection {
+ vec_name: String,
+ closure_arg: String,
+ closure_body: String,
+ reverse: bool,
+ unstable: bool,
+}
+
+/// Detect if the two expressions are mirrored (identical, except one
+/// contains a and the other replaces it with b)
+fn mirrored_exprs(
+ cx: &LateContext<'_>,
+ a_expr: &Expr<'_>,
+ a_ident: &Ident,
+ b_expr: &Expr<'_>,
+ b_ident: &Ident,
+) -> bool {
+ match (&a_expr.kind, &b_expr.kind) {
+ // Two boxes with mirrored contents
+ (ExprKind::Box(left_expr), ExprKind::Box(right_expr)) => {
+ mirrored_exprs(cx, left_expr, a_ident, right_expr, b_ident)
+ },
+ // Two arrays with mirrored contents
+ (ExprKind::Array(left_exprs), ExprKind::Array(right_exprs)) => left_exprs
+ .iter()
+ .zip(right_exprs.iter())
+ .all(|(left, right)| mirrored_exprs(cx, left, a_ident, right, b_ident)),
+ // The two exprs are function calls.
+ // Check to see that the function itself and its arguments are mirrored
+ (ExprKind::Call(left_expr, left_args), ExprKind::Call(right_expr, right_args)) => {
+ mirrored_exprs(cx, left_expr, a_ident, right_expr, b_ident)
+ && left_args
+ .iter()
+ .zip(right_args.iter())
+ .all(|(left, right)| mirrored_exprs(cx, left, a_ident, right, b_ident))
+ },
+ // The two exprs are method calls.
+ // Check to see that the function is the same and the arguments are mirrored
+ // This is enough because the receiver of the method is listed in the arguments
+ (
+ ExprKind::MethodCall(left_segment, _, left_args, _),
+ ExprKind::MethodCall(right_segment, _, right_args, _),
+ ) => {
+ left_segment.ident == right_segment.ident
+ && left_args
+ .iter()
+ .zip(right_args.iter())
+ .all(|(left, right)| mirrored_exprs(cx, left, a_ident, right, b_ident))
+ },
+ // Two tuples with mirrored contents
+ (ExprKind::Tup(left_exprs), ExprKind::Tup(right_exprs)) => left_exprs
+ .iter()
+ .zip(right_exprs.iter())
+ .all(|(left, right)| mirrored_exprs(cx, left, a_ident, right, b_ident)),
+ // Two binary ops, which are the same operation and which have mirrored arguments
+ (ExprKind::Binary(left_op, left_left, left_right), ExprKind::Binary(right_op, right_left, right_right)) => {
+ left_op.node == right_op.node
+ && mirrored_exprs(cx, left_left, a_ident, right_left, b_ident)
+ && mirrored_exprs(cx, left_right, a_ident, right_right, b_ident)
+ },
+ // Two unary ops, which are the same operation and which have the same argument
+ (ExprKind::Unary(left_op, left_expr), ExprKind::Unary(right_op, right_expr)) => {
+ left_op == right_op && mirrored_exprs(cx, left_expr, a_ident, right_expr, b_ident)
+ },
+ // The two exprs are literals of some kind
+ (ExprKind::Lit(left_lit), ExprKind::Lit(right_lit)) => left_lit.node == right_lit.node,
+ (ExprKind::Cast(left, _), ExprKind::Cast(right, _)) => mirrored_exprs(cx, left, a_ident, right, b_ident),
+ (ExprKind::DropTemps(left_block), ExprKind::DropTemps(right_block)) => {
+ mirrored_exprs(cx, left_block, a_ident, right_block, b_ident)
+ },
+ (ExprKind::Field(left_expr, left_ident), ExprKind::Field(right_expr, right_ident)) => {
+ left_ident.name == right_ident.name && mirrored_exprs(cx, left_expr, a_ident, right_expr, right_ident)
+ },
+ // Two paths: either one is a and the other is b, or they're identical to each other
+ (
+ ExprKind::Path(QPath::Resolved(
+ _,
+ Path {
+ segments: left_segments,
+ ..
+ },
+ )),
+ ExprKind::Path(QPath::Resolved(
+ _,
+ Path {
+ segments: right_segments,
+ ..
+ },
+ )),
+ ) => {
+ (left_segments
+ .iter()
+ .zip(right_segments.iter())
+ .all(|(left, right)| left.ident == right.ident)
+ && left_segments
+ .iter()
+ .all(|seg| &seg.ident != a_ident && &seg.ident != b_ident))
+ || (left_segments.len() == 1
+ && &left_segments[0].ident == a_ident
+ && right_segments.len() == 1
+ && &right_segments[0].ident == b_ident)
+ },
+ // Matching expressions, but one or both is borrowed
+ (
+ ExprKind::AddrOf(left_kind, Mutability::Not, left_expr),
+ ExprKind::AddrOf(right_kind, Mutability::Not, right_expr),
+ ) => left_kind == right_kind && mirrored_exprs(cx, left_expr, a_ident, right_expr, b_ident),
+ (_, ExprKind::AddrOf(_, Mutability::Not, right_expr)) => {
+ mirrored_exprs(cx, a_expr, a_ident, right_expr, b_ident)
+ },
+ (ExprKind::AddrOf(_, Mutability::Not, left_expr), _) => mirrored_exprs(cx, left_expr, a_ident, b_expr, b_ident),
+ _ => false,
+ }
+}
+
+fn detect_lint(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<LintTrigger> {
++ // NOTE: Vectors of references are not supported. In order to avoid hitting https://github.com/rust-lang/rust/issues/34162,
++ // (different unnamed lifetimes for closure arg and return type) we need to make sure the suggested
++ // closure parameter is not a reference in case we suggest `Reverse`. Trying to destructure more
++ // than one level of references would add some extra complexity as we would have to compensate
++ // in the closure body.
++
+ if_chain! {
+ if let ExprKind::MethodCall(name_ident, _, args, _) = &expr.kind;
+ if let name = name_ident.ident.name.to_ident_string();
+ if name == "sort_by" || name == "sort_unstable_by";
+ if let [vec, Expr { kind: ExprKind::Closure(_, _, closure_body_id, _, _), .. }] = args;
++ let vec_ty = cx.typeck_results().expr_ty(vec);
++ if utils::is_type_diagnostic_item(cx, vec_ty, sym!(vec_type));
++ let ty = vec_ty.walk().nth(1).unwrap().expect_ty(); // T in Vec<T>
++ if !matches!(&ty.kind(), ty::Ref(..));
++ if utils::is_copy(cx, ty);
+ if let closure_body = cx.tcx.hir().body(*closure_body_id);
+ if let &[
+ Param { pat: Pat { kind: PatKind::Binding(_, _, left_ident, _), .. }, ..},
+ Param { pat: Pat { kind: PatKind::Binding(_, _, right_ident, _), .. }, .. }
+ ] = &closure_body.params;
+ if let ExprKind::MethodCall(method_path, _, [ref left_expr, ref right_expr], _) = &closure_body.value.kind;
+ if method_path.ident.name.to_ident_string() == "cmp";
+ then {
+ let (closure_body, closure_arg, reverse) = if mirrored_exprs(
+ &cx,
+ &left_expr,
+ &left_ident,
+ &right_expr,
+ &right_ident
+ ) {
+ (Sugg::hir(cx, &left_expr, "..").to_string(), left_ident.name.to_string(), false)
+ } else if mirrored_exprs(&cx, &left_expr, &right_ident, &right_expr, &left_ident) {
+ (Sugg::hir(cx, &left_expr, "..").to_string(), right_ident.name.to_string(), true)
+ } else {
+ return None;
+ };
+ let vec_name = Sugg::hir(cx, &args[0], "..").to_string();
+ let unstable = name == "sort_unstable_by";
+
+ if_chain! {
+ if let ExprKind::Path(QPath::Resolved(_, Path {
+ segments: [PathSegment { ident: left_name, .. }], ..
+ })) = &left_expr.kind;
+ if left_name == left_ident;
+ then {
+ return Some(LintTrigger::Sort(SortDetection { vec_name, unstable }))
+ } else {
+ if !key_returns_borrow(cx, left_expr) {
+ return Some(LintTrigger::SortByKey(SortByKeyDetection {
+ vec_name,
+ unstable,
+ closure_arg,
+ closure_body,
+ reverse
+ }))
+ }
+ }
+ }
+ }
+ }
+
+ None
+}
+
+fn key_returns_borrow(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
+ if let Some(def_id) = utils::fn_def_id(cx, expr) {
+ let output = cx.tcx.fn_sig(def_id).output();
+ let ty = output.skip_binder();
+ return matches!(ty.kind(), ty::Ref(..))
+ || ty.walk().any(|arg| matches!(arg.unpack(), GenericArgKind::Lifetime(_)));
+ }
+
+ false
+}
+
+impl LateLintPass<'_> for UnnecessarySortBy {
+ fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
+ match detect_lint(cx, expr) {
+ Some(LintTrigger::SortByKey(trigger)) => utils::span_lint_and_sugg(
+ cx,
+ UNNECESSARY_SORT_BY,
+ expr.span,
+ "use Vec::sort_by_key here instead",
+ "try",
+ format!(
+ "{}.sort{}_by_key(|&{}| {})",
+ trigger.vec_name,
+ if trigger.unstable { "_unstable" } else { "" },
+ trigger.closure_arg,
+ if trigger.reverse {
+ format!("Reverse({})", trigger.closure_body)
+ } else {
+ trigger.closure_body.to_string()
+ },
+ ),
+ if trigger.reverse {
+ Applicability::MaybeIncorrect
+ } else {
+ Applicability::MachineApplicable
+ },
+ ),
+ Some(LintTrigger::Sort(trigger)) => utils::span_lint_and_sugg(
+ cx,
+ UNNECESSARY_SORT_BY,
+ expr.span,
+ "use Vec::sort here instead",
+ "try",
+ format!(
+ "{}.sort{}()",
+ trigger.vec_name,
+ if trigger.unstable { "_unstable" } else { "" },
+ ),
+ Applicability::MachineApplicable,
+ ),
+ None => {},
+ }
+ }
+}
--- /dev/null
- (MacCall(l), MacCall(r)) => l.style == r.style && eq_mac_call(&l.mac, &r.mac) && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r)),
+//! Utilities for manipulating and extracting information from `rustc_ast::ast`.
+//!
+//! - The `eq_foobar` functions test for semantic equality but ignores `NodeId`s and `Span`s.
+
+#![allow(clippy::similar_names, clippy::wildcard_imports, clippy::enum_glob_use)]
+
+use crate::utils::{both, over};
+use rustc_ast::ptr::P;
+use rustc_ast::{self as ast, *};
+use rustc_span::symbol::Ident;
+use std::mem;
+
+/// Checks if each element in the first slice is contained within the latter as per `eq_fn`.
+pub fn unordered_over<X>(left: &[X], right: &[X], mut eq_fn: impl FnMut(&X, &X) -> bool) -> bool {
+ left.len() == right.len() && left.iter().all(|l| right.iter().any(|r| eq_fn(l, r)))
+}
+
+pub fn eq_id(l: Ident, r: Ident) -> bool {
+ l.name == r.name
+}
+
+pub fn eq_pat(l: &Pat, r: &Pat) -> bool {
+ use PatKind::*;
+ match (&l.kind, &r.kind) {
+ (Paren(l), _) => eq_pat(l, r),
+ (_, Paren(r)) => eq_pat(l, r),
+ (Wild, Wild) | (Rest, Rest) => true,
+ (Lit(l), Lit(r)) => eq_expr(l, r),
+ (Ident(b1, i1, s1), Ident(b2, i2, s2)) => b1 == b2 && eq_id(*i1, *i2) && both(s1, s2, |l, r| eq_pat(l, r)),
+ (Range(lf, lt, le), Range(rf, rt, re)) => {
+ eq_expr_opt(lf, rf) && eq_expr_opt(lt, rt) && eq_range_end(&le.node, &re.node)
+ },
+ (Box(l), Box(r))
+ | (Ref(l, Mutability::Not), Ref(r, Mutability::Not))
+ | (Ref(l, Mutability::Mut), Ref(r, Mutability::Mut)) => eq_pat(l, r),
+ (Tuple(l), Tuple(r)) | (Slice(l), Slice(r)) => over(l, r, |l, r| eq_pat(l, r)),
+ (Path(lq, lp), Path(rq, rp)) => both(lq, rq, |l, r| eq_qself(l, r)) && eq_path(lp, rp),
+ (TupleStruct(lp, lfs), TupleStruct(rp, rfs)) => eq_path(lp, rp) && over(lfs, rfs, |l, r| eq_pat(l, r)),
+ (Struct(lp, lfs, lr), Struct(rp, rfs, rr)) => {
+ lr == rr && eq_path(lp, rp) && unordered_over(lfs, rfs, |lf, rf| eq_field_pat(lf, rf))
+ },
+ (Or(ls), Or(rs)) => unordered_over(ls, rs, |l, r| eq_pat(l, r)),
+ (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
+ _ => false,
+ }
+}
+
+pub fn eq_range_end(l: &RangeEnd, r: &RangeEnd) -> bool {
+ match (l, r) {
+ (RangeEnd::Excluded, RangeEnd::Excluded) => true,
+ (RangeEnd::Included(l), RangeEnd::Included(r)) => {
+ matches!(l, RangeSyntax::DotDotEq) == matches!(r, RangeSyntax::DotDotEq)
+ },
+ _ => false,
+ }
+}
+
+pub fn eq_field_pat(l: &FieldPat, r: &FieldPat) -> bool {
+ l.is_placeholder == r.is_placeholder
+ && eq_id(l.ident, r.ident)
+ && eq_pat(&l.pat, &r.pat)
+ && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
+}
+
+pub fn eq_qself(l: &QSelf, r: &QSelf) -> bool {
+ l.position == r.position && eq_ty(&l.ty, &r.ty)
+}
+
+pub fn eq_path(l: &Path, r: &Path) -> bool {
+ over(&l.segments, &r.segments, |l, r| eq_path_seg(l, r))
+}
+
+pub fn eq_path_seg(l: &PathSegment, r: &PathSegment) -> bool {
+ eq_id(l.ident, r.ident) && both(&l.args, &r.args, |l, r| eq_generic_args(l, r))
+}
+
+pub fn eq_generic_args(l: &GenericArgs, r: &GenericArgs) -> bool {
+ match (l, r) {
+ (GenericArgs::AngleBracketed(l), GenericArgs::AngleBracketed(r)) => {
+ over(&l.args, &r.args, |l, r| eq_angle_arg(l, r))
+ },
+ (GenericArgs::Parenthesized(l), GenericArgs::Parenthesized(r)) => {
+ over(&l.inputs, &r.inputs, |l, r| eq_ty(l, r)) && eq_fn_ret_ty(&l.output, &r.output)
+ },
+ _ => false,
+ }
+}
+
+pub fn eq_angle_arg(l: &AngleBracketedArg, r: &AngleBracketedArg) -> bool {
+ match (l, r) {
+ (AngleBracketedArg::Arg(l), AngleBracketedArg::Arg(r)) => eq_generic_arg(l, r),
+ (AngleBracketedArg::Constraint(l), AngleBracketedArg::Constraint(r)) => eq_assoc_constraint(l, r),
+ _ => false,
+ }
+}
+
+pub fn eq_generic_arg(l: &GenericArg, r: &GenericArg) -> bool {
+ match (l, r) {
+ (GenericArg::Lifetime(l), GenericArg::Lifetime(r)) => eq_id(l.ident, r.ident),
+ (GenericArg::Type(l), GenericArg::Type(r)) => eq_ty(l, r),
+ (GenericArg::Const(l), GenericArg::Const(r)) => eq_expr(&l.value, &r.value),
+ _ => false,
+ }
+}
+
+pub fn eq_expr_opt(l: &Option<P<Expr>>, r: &Option<P<Expr>>) -> bool {
+ both(l, r, |l, r| eq_expr(l, r))
+}
+
+pub fn eq_expr(l: &Expr, r: &Expr) -> bool {
+ use ExprKind::*;
+ if !over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r)) {
+ return false;
+ }
+ match (&l.kind, &r.kind) {
+ (Paren(l), _) => eq_expr(l, r),
+ (_, Paren(r)) => eq_expr(l, r),
+ (Err, Err) => true,
+ (Box(l), Box(r)) | (Try(l), Try(r)) | (Await(l), Await(r)) => eq_expr(l, r),
+ (Array(l), Array(r)) | (Tup(l), Tup(r)) => over(l, r, |l, r| eq_expr(l, r)),
+ (Repeat(le, ls), Repeat(re, rs)) => eq_expr(le, re) && eq_expr(&ls.value, &rs.value),
+ (Call(lc, la), Call(rc, ra)) => eq_expr(lc, rc) && over(la, ra, |l, r| eq_expr(l, r)),
+ (MethodCall(lc, la, _), MethodCall(rc, ra, _)) => eq_path_seg(lc, rc) && over(la, ra, |l, r| eq_expr(l, r)),
+ (Binary(lo, ll, lr), Binary(ro, rl, rr)) => lo.node == ro.node && eq_expr(ll, rl) && eq_expr(lr, rr),
+ (Unary(lo, l), Unary(ro, r)) => mem::discriminant(lo) == mem::discriminant(ro) && eq_expr(l, r),
+ (Lit(l), Lit(r)) => l.kind == r.kind,
+ (Cast(l, lt), Cast(r, rt)) | (Type(l, lt), Type(r, rt)) => eq_expr(l, r) && eq_ty(lt, rt),
+ (Let(lp, le), Let(rp, re)) => eq_pat(lp, rp) && eq_expr(le, re),
+ (If(lc, lt, le), If(rc, rt, re)) => eq_expr(lc, rc) && eq_block(lt, rt) && eq_expr_opt(le, re),
+ (While(lc, lt, ll), While(rc, rt, rl)) => eq_label(ll, rl) && eq_expr(lc, rc) && eq_block(lt, rt),
+ (ForLoop(lp, li, lt, ll), ForLoop(rp, ri, rt, rl)) => {
+ eq_label(ll, rl) && eq_pat(lp, rp) && eq_expr(li, ri) && eq_block(lt, rt)
+ },
+ (Loop(lt, ll), Loop(rt, rl)) => eq_label(ll, rl) && eq_block(lt, rt),
+ (Block(lb, ll), Block(rb, rl)) => eq_label(ll, rl) && eq_block(lb, rb),
+ (TryBlock(l), TryBlock(r)) => eq_block(l, r),
+ (Yield(l), Yield(r)) | (Ret(l), Ret(r)) => eq_expr_opt(l, r),
+ (Break(ll, le), Break(rl, re)) => eq_label(ll, rl) && eq_expr_opt(le, re),
+ (Continue(ll), Continue(rl)) => eq_label(ll, rl),
+ (Assign(l1, l2, _), Assign(r1, r2, _)) | (Index(l1, l2), Index(r1, r2)) => eq_expr(l1, r1) && eq_expr(l2, r2),
+ (AssignOp(lo, lp, lv), AssignOp(ro, rp, rv)) => lo.node == ro.node && eq_expr(lp, rp) && eq_expr(lv, rv),
+ (Field(lp, lf), Field(rp, rf)) => eq_id(*lf, *rf) && eq_expr(lp, rp),
+ (Match(ls, la), Match(rs, ra)) => eq_expr(ls, rs) && over(la, ra, |l, r| eq_arm(l, r)),
+ (Closure(lc, la, lm, lf, lb, _), Closure(rc, ra, rm, rf, rb, _)) => {
+ lc == rc && la.is_async() == ra.is_async() && lm == rm && eq_fn_decl(lf, rf) && eq_expr(lb, rb)
+ },
+ (Async(lc, _, lb), Async(rc, _, rb)) => lc == rc && eq_block(lb, rb),
+ (Range(lf, lt, ll), Range(rf, rt, rl)) => ll == rl && eq_expr_opt(lf, rf) && eq_expr_opt(lt, rt),
+ (AddrOf(lbk, lm, le), AddrOf(rbk, rm, re)) => lbk == rbk && lm == rm && eq_expr(le, re),
+ (Path(lq, lp), Path(rq, rp)) => both(lq, rq, |l, r| eq_qself(l, r)) && eq_path(lp, rp),
+ (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
+ (Struct(lp, lfs, lb), Struct(rp, rfs, rb)) => {
+ eq_path(lp, rp) && eq_expr_opt(lb, rb) && unordered_over(lfs, rfs, |l, r| eq_field(l, r))
+ },
+ _ => false,
+ }
+}
+
+pub fn eq_field(l: &Field, r: &Field) -> bool {
+ l.is_placeholder == r.is_placeholder
+ && eq_id(l.ident, r.ident)
+ && eq_expr(&l.expr, &r.expr)
+ && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
+}
+
+pub fn eq_arm(l: &Arm, r: &Arm) -> bool {
+ l.is_placeholder == r.is_placeholder
+ && eq_pat(&l.pat, &r.pat)
+ && eq_expr(&l.body, &r.body)
+ && eq_expr_opt(&l.guard, &r.guard)
+ && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
+}
+
+pub fn eq_label(l: &Option<Label>, r: &Option<Label>) -> bool {
+ both(l, r, |l, r| eq_id(l.ident, r.ident))
+}
+
+pub fn eq_block(l: &Block, r: &Block) -> bool {
+ l.rules == r.rules && over(&l.stmts, &r.stmts, |l, r| eq_stmt(l, r))
+}
+
+pub fn eq_stmt(l: &Stmt, r: &Stmt) -> bool {
+ use StmtKind::*;
+ match (&l.kind, &r.kind) {
+ (Local(l), Local(r)) => {
+ eq_pat(&l.pat, &r.pat)
+ && both(&l.ty, &r.ty, |l, r| eq_ty(l, r))
+ && eq_expr_opt(&l.init, &r.init)
+ && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
+ },
+ (Item(l), Item(r)) => eq_item(l, r, eq_item_kind),
+ (Expr(l), Expr(r)) | (Semi(l), Semi(r)) => eq_expr(l, r),
+ (Empty, Empty) => true,
++ (MacCall(l), MacCall(r)) => {
++ l.style == r.style && eq_mac_call(&l.mac, &r.mac) && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
++ },
+ _ => false,
+ }
+}
+
+pub fn eq_item<K>(l: &Item<K>, r: &Item<K>, mut eq_kind: impl FnMut(&K, &K) -> bool) -> bool {
+ eq_id(l.ident, r.ident)
+ && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
+ && eq_vis(&l.vis, &r.vis)
+ && eq_kind(&l.kind, &r.kind)
+}
+
+pub fn eq_item_kind(l: &ItemKind, r: &ItemKind) -> bool {
+ use ItemKind::*;
+ match (l, r) {
+ (ExternCrate(l), ExternCrate(r)) => l == r,
+ (Use(l), Use(r)) => eq_use_tree(l, r),
+ (Static(lt, lm, le), Static(rt, rm, re)) => lm == rm && eq_ty(lt, rt) && eq_expr_opt(le, re),
+ (Const(ld, lt, le), Const(rd, rt, re)) => eq_defaultness(*ld, *rd) && eq_ty(lt, rt) && eq_expr_opt(le, re),
+ (Fn(ld, lf, lg, lb), Fn(rd, rf, rg, rb)) => {
+ eq_defaultness(*ld, *rd) && eq_fn_sig(lf, rf) && eq_generics(lg, rg) && both(lb, rb, |l, r| eq_block(l, r))
+ },
+ (Mod(l), Mod(r)) => l.inline == r.inline && over(&l.items, &r.items, |l, r| eq_item(l, r, eq_item_kind)),
+ (ForeignMod(l), ForeignMod(r)) => {
+ both(&l.abi, &r.abi, |l, r| eq_str_lit(l, r))
+ && over(&l.items, &r.items, |l, r| eq_item(l, r, eq_foreign_item_kind))
+ },
+ (TyAlias(ld, lg, lb, lt), TyAlias(rd, rg, rb, rt)) => {
+ eq_defaultness(*ld, *rd)
+ && eq_generics(lg, rg)
+ && over(lb, rb, |l, r| eq_generic_bound(l, r))
+ && both(lt, rt, |l, r| eq_ty(l, r))
+ },
+ (Enum(le, lg), Enum(re, rg)) => {
+ over(&le.variants, &re.variants, |l, r| eq_variant(l, r)) && eq_generics(lg, rg)
+ },
+ (Struct(lv, lg), Struct(rv, rg)) | (Union(lv, lg), Union(rv, rg)) => {
+ eq_variant_data(lv, rv) && eq_generics(lg, rg)
+ },
+ (Trait(la, lu, lg, lb, li), Trait(ra, ru, rg, rb, ri)) => {
+ la == ra
+ && matches!(lu, Unsafe::No) == matches!(ru, Unsafe::No)
+ && eq_generics(lg, rg)
+ && over(lb, rb, |l, r| eq_generic_bound(l, r))
+ && over(li, ri, |l, r| eq_item(l, r, eq_assoc_item_kind))
+ },
+ (TraitAlias(lg, lb), TraitAlias(rg, rb)) => eq_generics(lg, rg) && over(lb, rb, |l, r| eq_generic_bound(l, r)),
+ (
+ Impl {
+ unsafety: lu,
+ polarity: lp,
+ defaultness: ld,
+ constness: lc,
+ generics: lg,
+ of_trait: lot,
+ self_ty: lst,
+ items: li,
+ },
+ Impl {
+ unsafety: ru,
+ polarity: rp,
+ defaultness: rd,
+ constness: rc,
+ generics: rg,
+ of_trait: rot,
+ self_ty: rst,
+ items: ri,
+ },
+ ) => {
+ matches!(lu, Unsafe::No) == matches!(ru, Unsafe::No)
+ && matches!(lp, ImplPolarity::Positive) == matches!(rp, ImplPolarity::Positive)
+ && eq_defaultness(*ld, *rd)
+ && matches!(lc, ast::Const::No) == matches!(rc, ast::Const::No)
+ && eq_generics(lg, rg)
+ && both(lot, rot, |l, r| eq_path(&l.path, &r.path))
+ && eq_ty(lst, rst)
+ && over(li, ri, |l, r| eq_item(l, r, eq_assoc_item_kind))
+ },
+ (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
+ (MacroDef(l), MacroDef(r)) => l.macro_rules == r.macro_rules && eq_mac_args(&l.body, &r.body),
+ _ => false,
+ }
+}
+
+pub fn eq_foreign_item_kind(l: &ForeignItemKind, r: &ForeignItemKind) -> bool {
+ use ForeignItemKind::*;
+ match (l, r) {
+ (Static(lt, lm, le), Static(rt, rm, re)) => lm == rm && eq_ty(lt, rt) && eq_expr_opt(le, re),
+ (Fn(ld, lf, lg, lb), Fn(rd, rf, rg, rb)) => {
+ eq_defaultness(*ld, *rd) && eq_fn_sig(lf, rf) && eq_generics(lg, rg) && both(lb, rb, |l, r| eq_block(l, r))
+ },
+ (TyAlias(ld, lg, lb, lt), TyAlias(rd, rg, rb, rt)) => {
+ eq_defaultness(*ld, *rd)
+ && eq_generics(lg, rg)
+ && over(lb, rb, |l, r| eq_generic_bound(l, r))
+ && both(lt, rt, |l, r| eq_ty(l, r))
+ },
+ (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
+ _ => false,
+ }
+}
+
+pub fn eq_assoc_item_kind(l: &AssocItemKind, r: &AssocItemKind) -> bool {
+ use AssocItemKind::*;
+ match (l, r) {
+ (Const(ld, lt, le), Const(rd, rt, re)) => eq_defaultness(*ld, *rd) && eq_ty(lt, rt) && eq_expr_opt(le, re),
+ (Fn(ld, lf, lg, lb), Fn(rd, rf, rg, rb)) => {
+ eq_defaultness(*ld, *rd) && eq_fn_sig(lf, rf) && eq_generics(lg, rg) && both(lb, rb, |l, r| eq_block(l, r))
+ },
+ (TyAlias(ld, lg, lb, lt), TyAlias(rd, rg, rb, rt)) => {
+ eq_defaultness(*ld, *rd)
+ && eq_generics(lg, rg)
+ && over(lb, rb, |l, r| eq_generic_bound(l, r))
+ && both(lt, rt, |l, r| eq_ty(l, r))
+ },
+ (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
+ _ => false,
+ }
+}
+
+pub fn eq_variant(l: &Variant, r: &Variant) -> bool {
+ l.is_placeholder == r.is_placeholder
+ && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
+ && eq_vis(&l.vis, &r.vis)
+ && eq_id(l.ident, r.ident)
+ && eq_variant_data(&l.data, &r.data)
+ && both(&l.disr_expr, &r.disr_expr, |l, r| eq_expr(&l.value, &r.value))
+}
+
+pub fn eq_variant_data(l: &VariantData, r: &VariantData) -> bool {
+ use VariantData::*;
+ match (l, r) {
+ (Unit(_), Unit(_)) => true,
+ (Struct(l, _), Struct(r, _)) | (Tuple(l, _), Tuple(r, _)) => over(l, r, |l, r| eq_struct_field(l, r)),
+ _ => false,
+ }
+}
+
+pub fn eq_struct_field(l: &StructField, r: &StructField) -> bool {
+ l.is_placeholder == r.is_placeholder
+ && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
+ && eq_vis(&l.vis, &r.vis)
+ && both(&l.ident, &r.ident, |l, r| eq_id(*l, *r))
+ && eq_ty(&l.ty, &r.ty)
+}
+
+pub fn eq_fn_sig(l: &FnSig, r: &FnSig) -> bool {
+ eq_fn_decl(&l.decl, &r.decl) && eq_fn_header(&l.header, &r.header)
+}
+
+pub fn eq_fn_header(l: &FnHeader, r: &FnHeader) -> bool {
+ matches!(l.unsafety, Unsafe::No) == matches!(r.unsafety, Unsafe::No)
+ && l.asyncness.is_async() == r.asyncness.is_async()
+ && matches!(l.constness, Const::No) == matches!(r.constness, Const::No)
+ && eq_ext(&l.ext, &r.ext)
+}
+
+pub fn eq_generics(l: &Generics, r: &Generics) -> bool {
+ over(&l.params, &r.params, |l, r| eq_generic_param(l, r))
+ && over(&l.where_clause.predicates, &r.where_clause.predicates, |l, r| {
+ eq_where_predicate(l, r)
+ })
+}
+
+pub fn eq_where_predicate(l: &WherePredicate, r: &WherePredicate) -> bool {
+ use WherePredicate::*;
+ match (l, r) {
+ (BoundPredicate(l), BoundPredicate(r)) => {
+ over(&l.bound_generic_params, &r.bound_generic_params, |l, r| {
+ eq_generic_param(l, r)
+ }) && eq_ty(&l.bounded_ty, &r.bounded_ty)
+ && over(&l.bounds, &r.bounds, |l, r| eq_generic_bound(l, r))
+ },
+ (RegionPredicate(l), RegionPredicate(r)) => {
+ eq_id(l.lifetime.ident, r.lifetime.ident) && over(&l.bounds, &r.bounds, |l, r| eq_generic_bound(l, r))
+ },
+ (EqPredicate(l), EqPredicate(r)) => eq_ty(&l.lhs_ty, &r.lhs_ty) && eq_ty(&l.rhs_ty, &r.rhs_ty),
+ _ => false,
+ }
+}
+
+pub fn eq_use_tree(l: &UseTree, r: &UseTree) -> bool {
+ eq_path(&l.prefix, &r.prefix) && eq_use_tree_kind(&l.kind, &r.kind)
+}
+
+pub fn eq_use_tree_kind(l: &UseTreeKind, r: &UseTreeKind) -> bool {
+ use UseTreeKind::*;
+ match (l, r) {
+ (Glob, Glob) => true,
+ (Simple(l, _, _), Simple(r, _, _)) => both(l, r, |l, r| eq_id(*l, *r)),
+ (Nested(l), Nested(r)) => over(l, r, |(l, _), (r, _)| eq_use_tree(l, r)),
+ _ => false,
+ }
+}
+
+pub fn eq_defaultness(l: Defaultness, r: Defaultness) -> bool {
+ matches!((l, r), (Defaultness::Final, Defaultness::Final) | (Defaultness::Default(_), Defaultness::Default(_)))
+}
+
+pub fn eq_vis(l: &Visibility, r: &Visibility) -> bool {
+ use VisibilityKind::*;
+ match (&l.node, &r.node) {
+ (Public, Public) | (Inherited, Inherited) | (Crate(_), Crate(_)) => true,
+ (Restricted { path: l, .. }, Restricted { path: r, .. }) => eq_path(l, r),
+ _ => false,
+ }
+}
+
+pub fn eq_fn_decl(l: &FnDecl, r: &FnDecl) -> bool {
+ eq_fn_ret_ty(&l.output, &r.output)
+ && over(&l.inputs, &r.inputs, |l, r| {
+ l.is_placeholder == r.is_placeholder
+ && eq_pat(&l.pat, &r.pat)
+ && eq_ty(&l.ty, &r.ty)
+ && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
+ })
+}
+
+pub fn eq_fn_ret_ty(l: &FnRetTy, r: &FnRetTy) -> bool {
+ match (l, r) {
+ (FnRetTy::Default(_), FnRetTy::Default(_)) => true,
+ (FnRetTy::Ty(l), FnRetTy::Ty(r)) => eq_ty(l, r),
+ _ => false,
+ }
+}
+
+pub fn eq_ty(l: &Ty, r: &Ty) -> bool {
+ use TyKind::*;
+ match (&l.kind, &r.kind) {
+ (Paren(l), _) => eq_ty(l, r),
+ (_, Paren(r)) => eq_ty(l, r),
+ (Never, Never) | (Infer, Infer) | (ImplicitSelf, ImplicitSelf) | (Err, Err) | (CVarArgs, CVarArgs) => true,
+ (Slice(l), Slice(r)) => eq_ty(l, r),
+ (Array(le, ls), Array(re, rs)) => eq_ty(le, re) && eq_expr(&ls.value, &rs.value),
+ (Ptr(l), Ptr(r)) => l.mutbl == r.mutbl && eq_ty(&l.ty, &r.ty),
+ (Rptr(ll, l), Rptr(rl, r)) => {
+ both(ll, rl, |l, r| eq_id(l.ident, r.ident)) && l.mutbl == r.mutbl && eq_ty(&l.ty, &r.ty)
+ },
+ (BareFn(l), BareFn(r)) => {
+ l.unsafety == r.unsafety
+ && eq_ext(&l.ext, &r.ext)
+ && over(&l.generic_params, &r.generic_params, |l, r| eq_generic_param(l, r))
+ && eq_fn_decl(&l.decl, &r.decl)
+ },
+ (Tup(l), Tup(r)) => over(l, r, |l, r| eq_ty(l, r)),
+ (Path(lq, lp), Path(rq, rp)) => both(lq, rq, |l, r| eq_qself(l, r)) && eq_path(lp, rp),
+ (TraitObject(lg, ls), TraitObject(rg, rs)) => ls == rs && over(lg, rg, |l, r| eq_generic_bound(l, r)),
+ (ImplTrait(_, lg), ImplTrait(_, rg)) => over(lg, rg, |l, r| eq_generic_bound(l, r)),
+ (Typeof(l), Typeof(r)) => eq_expr(&l.value, &r.value),
+ (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
+ _ => false,
+ }
+}
+
+pub fn eq_ext(l: &Extern, r: &Extern) -> bool {
+ use Extern::*;
+ match (l, r) {
+ (None, None) | (Implicit, Implicit) => true,
+ (Explicit(l), Explicit(r)) => eq_str_lit(l, r),
+ _ => false,
+ }
+}
+
+pub fn eq_str_lit(l: &StrLit, r: &StrLit) -> bool {
+ l.style == r.style && l.symbol == r.symbol && l.suffix == r.suffix
+}
+
+pub fn eq_poly_ref_trait(l: &PolyTraitRef, r: &PolyTraitRef) -> bool {
+ eq_path(&l.trait_ref.path, &r.trait_ref.path)
+ && over(&l.bound_generic_params, &r.bound_generic_params, |l, r| {
+ eq_generic_param(l, r)
+ })
+}
+
+pub fn eq_generic_param(l: &GenericParam, r: &GenericParam) -> bool {
+ use GenericParamKind::*;
+ l.is_placeholder == r.is_placeholder
+ && eq_id(l.ident, r.ident)
+ && over(&l.bounds, &r.bounds, |l, r| eq_generic_bound(l, r))
+ && match (&l.kind, &r.kind) {
+ (Lifetime, Lifetime) => true,
+ (Type { default: l }, Type { default: r }) => both(l, r, |l, r| eq_ty(l, r)),
+ (Const { ty: l, kw_span: _ }, Const { ty: r, kw_span: _ }) => eq_ty(l, r),
+ _ => false,
+ }
+ && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
+}
+
+pub fn eq_generic_bound(l: &GenericBound, r: &GenericBound) -> bool {
+ use GenericBound::*;
+ match (l, r) {
+ (Trait(ptr1, tbm1), Trait(ptr2, tbm2)) => tbm1 == tbm2 && eq_poly_ref_trait(ptr1, ptr2),
+ (Outlives(l), Outlives(r)) => eq_id(l.ident, r.ident),
+ _ => false,
+ }
+}
+
+pub fn eq_assoc_constraint(l: &AssocTyConstraint, r: &AssocTyConstraint) -> bool {
+ use AssocTyConstraintKind::*;
+ eq_id(l.ident, r.ident)
+ && match (&l.kind, &r.kind) {
+ (Equality { ty: l }, Equality { ty: r }) => eq_ty(l, r),
+ (Bound { bounds: l }, Bound { bounds: r }) => over(l, r, |l, r| eq_generic_bound(l, r)),
+ _ => false,
+ }
+}
+
+pub fn eq_mac_call(l: &MacCall, r: &MacCall) -> bool {
+ eq_path(&l.path, &r.path) && eq_mac_args(&l.args, &r.args)
+}
+
+pub fn eq_attr(l: &Attribute, r: &Attribute) -> bool {
+ use AttrKind::*;
+ l.style == r.style
+ && match (&l.kind, &r.kind) {
+ (DocComment(l1, l2), DocComment(r1, r2)) => l1 == r1 && l2 == r2,
+ (Normal(l), Normal(r)) => eq_path(&l.path, &r.path) && eq_mac_args(&l.args, &r.args),
+ _ => false,
+ }
+}
+
+pub fn eq_mac_args(l: &MacArgs, r: &MacArgs) -> bool {
+ use MacArgs::*;
+ match (l, r) {
+ (Empty, Empty) => true,
+ (Delimited(_, ld, lts), Delimited(_, rd, rts)) => ld == rd && lts.eq_unspanned(rts),
+ (Eq(_, lts), Eq(_, rts)) => lts.eq_unspanned(rts),
+ _ => false,
+ }
+}
--- /dev/null
- "OAuth",
+//! Read configurations files.
+
+#![deny(clippy::missing_docs_in_private_items)]
+
+use lazy_static::lazy_static;
+use rustc_ast::ast::{LitKind, MetaItemKind, NestedMetaItem};
+use rustc_span::source_map;
+use source_map::Span;
+use std::path::{Path, PathBuf};
+use std::sync::Mutex;
+use std::{env, fmt, fs, io};
+
+/// Gets the configuration file from arguments.
+pub fn file_from_args(args: &[NestedMetaItem]) -> Result<Option<PathBuf>, (&'static str, Span)> {
+ for arg in args.iter().filter_map(NestedMetaItem::meta_item) {
+ if arg.has_name(sym!(conf_file)) {
+ return match arg.kind {
+ MetaItemKind::Word | MetaItemKind::List(_) => Err(("`conf_file` must be a named value", arg.span)),
+ MetaItemKind::NameValue(ref value) => {
+ if let LitKind::Str(ref file, _) = value.kind {
+ Ok(Some(file.to_string().into()))
+ } else {
+ Err(("`conf_file` value must be a string", value.span))
+ }
+ },
+ };
+ }
+ }
+
+ Ok(None)
+}
+
+/// Error from reading a configuration file.
+#[derive(Debug)]
+pub enum Error {
+ /// An I/O error.
+ Io(io::Error),
+ /// Not valid toml or doesn't fit the expected config format
+ Toml(String),
+}
+
+impl fmt::Display for Error {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::Io(err) => err.fmt(f),
+ Self::Toml(err) => err.fmt(f),
+ }
+ }
+}
+
+impl From<io::Error> for Error {
+ fn from(e: io::Error) -> Self {
+ Self::Io(e)
+ }
+}
+
+lazy_static! {
+ static ref ERRORS: Mutex<Vec<Error>> = Mutex::new(Vec::new());
+}
+
+macro_rules! define_Conf {
+ ($(#[$doc:meta] ($config:ident, $config_str:literal: $Ty:ty, $default:expr),)+) => {
+ mod helpers {
+ use serde::Deserialize;
+ /// Type used to store lint configuration.
+ #[derive(Deserialize)]
+ #[serde(rename_all = "kebab-case", deny_unknown_fields)]
+ pub struct Conf {
+ $(
+ #[$doc]
+ #[serde(default = $config_str)]
+ #[serde(with = $config_str)]
+ pub $config: $Ty,
+ )+
+ #[allow(dead_code)]
+ #[serde(default)]
+ third_party: Option<::toml::Value>,
+ }
+
+ $(
+ mod $config {
+ use serde::Deserialize;
+ pub fn deserialize<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<$Ty, D::Error> {
+ use super::super::{ERRORS, Error};
+ Ok(
+ <$Ty>::deserialize(deserializer).unwrap_or_else(|e| {
+ ERRORS
+ .lock()
+ .expect("no threading here")
+ .push(Error::Toml(e.to_string()));
+ super::$config()
+ })
+ )
+ }
+ }
+
+ #[must_use]
+ fn $config() -> $Ty {
+ let x = $default;
+ x
+ }
+ )+
+ }
+ };
+}
+
+pub use self::helpers::Conf;
+define_Conf! {
+ /// Lint: BLACKLISTED_NAME. The list of blacklisted names to lint about. NB: `bar` is not here since it has legitimate uses
+ (blacklisted_names, "blacklisted_names": Vec<String>, ["foo", "baz", "quux"].iter().map(ToString::to_string).collect()),
+ /// Lint: COGNITIVE_COMPLEXITY. The maximum cognitive complexity a function can have
+ (cognitive_complexity_threshold, "cognitive_complexity_threshold": u64, 25),
+ /// DEPRECATED LINT: CYCLOMATIC_COMPLEXITY. Use the Cognitive Complexity lint instead.
+ (cyclomatic_complexity_threshold, "cyclomatic_complexity_threshold": Option<u64>, None),
+ /// Lint: DOC_MARKDOWN. The list of words this lint should not consider as identifiers needing ticks
+ (doc_valid_idents, "doc_valid_idents": Vec<String>, [
+ "KiB", "MiB", "GiB", "TiB", "PiB", "EiB",
+ "DirectX",
+ "ECMAScript",
+ "GPLv2", "GPLv3",
+ "GitHub", "GitLab",
+ "IPv4", "IPv6",
+ "ClojureScript", "CoffeeScript", "JavaScript", "PureScript", "TypeScript",
+ "NaN", "NaNs",
++ "OAuth", "GraphQL",
+ "OCaml",
+ "OpenGL", "OpenMP", "OpenSSH", "OpenSSL", "OpenStreetMap",
+ "TensorFlow",
+ "TrueType",
+ "iOS", "macOS",
+ "TeX", "LaTeX", "BibTeX", "BibLaTeX",
+ "MinGW",
+ "CamelCase",
+ ].iter().map(ToString::to_string).collect()),
+ /// Lint: TOO_MANY_ARGUMENTS. The maximum number of argument a function or method can have
+ (too_many_arguments_threshold, "too_many_arguments_threshold": u64, 7),
+ /// Lint: TYPE_COMPLEXITY. The maximum complexity a type can have
+ (type_complexity_threshold, "type_complexity_threshold": u64, 250),
+ /// Lint: MANY_SINGLE_CHAR_NAMES. The maximum number of single char bindings a scope may have
+ (single_char_binding_names_threshold, "single_char_binding_names_threshold": u64, 4),
+ /// Lint: BOXED_LOCAL, USELESS_VEC. The maximum size of objects (in bytes) that will be linted. Larger objects are ok on the heap
+ (too_large_for_stack, "too_large_for_stack": u64, 200),
+ /// Lint: ENUM_VARIANT_NAMES. The minimum number of enum variants for the lints about variant names to trigger
+ (enum_variant_name_threshold, "enum_variant_name_threshold": u64, 3),
+ /// Lint: LARGE_ENUM_VARIANT. The maximum size of a enum's variant to avoid box suggestion
+ (enum_variant_size_threshold, "enum_variant_size_threshold": u64, 200),
+ /// Lint: VERBOSE_BIT_MASK. The maximum allowed size of a bit mask before suggesting to use 'trailing_zeros'
+ (verbose_bit_mask_threshold, "verbose_bit_mask_threshold": u64, 1),
+ /// Lint: DECIMAL_LITERAL_REPRESENTATION. The lower bound for linting decimal literals
+ (literal_representation_threshold, "literal_representation_threshold": u64, 16384),
+ /// Lint: TRIVIALLY_COPY_PASS_BY_REF. The maximum size (in bytes) to consider a `Copy` type for passing by value instead of by reference.
+ (trivial_copy_size_limit, "trivial_copy_size_limit": Option<u64>, None),
+ /// Lint: TOO_MANY_LINES. The maximum number of lines a function or method can have
+ (too_many_lines_threshold, "too_many_lines_threshold": u64, 100),
+ /// Lint: LARGE_STACK_ARRAYS, LARGE_CONST_ARRAYS. The maximum allowed size for arrays on the stack
+ (array_size_threshold, "array_size_threshold": u64, 512_000),
+ /// Lint: VEC_BOX. The size of the boxed type in bytes, where boxing in a `Vec` is allowed
+ (vec_box_size_threshold, "vec_box_size_threshold": u64, 4096),
+ /// Lint: TYPE_REPETITION_IN_BOUNDS. The maximum number of bounds a trait can have to be linted
+ (max_trait_bounds, "max_trait_bounds": u64, 3),
+ /// Lint: STRUCT_EXCESSIVE_BOOLS. The maximum number of bools a struct can have
+ (max_struct_bools, "max_struct_bools": u64, 3),
+ /// Lint: FN_PARAMS_EXCESSIVE_BOOLS. The maximum number of bools function parameters can have
+ (max_fn_params_bools, "max_fn_params_bools": u64, 3),
+ /// Lint: WILDCARD_IMPORTS. Whether to allow certain wildcard imports (prelude, super in tests).
+ (warn_on_all_wildcard_imports, "warn_on_all_wildcard_imports": bool, false),
+}
+
+impl Default for Conf {
+ #[must_use]
+ fn default() -> Self {
+ toml::from_str("").expect("we never error on empty config files")
+ }
+}
+
+/// Search for the configuration file.
+pub fn lookup_conf_file() -> io::Result<Option<PathBuf>> {
+ /// Possible filename to search for.
+ const CONFIG_FILE_NAMES: [&str; 2] = [".clippy.toml", "clippy.toml"];
+
+ // Start looking for a config file in CLIPPY_CONF_DIR, or failing that, CARGO_MANIFEST_DIR.
+ // If neither of those exist, use ".".
+ let mut current = env::var_os("CLIPPY_CONF_DIR")
+ .or_else(|| env::var_os("CARGO_MANIFEST_DIR"))
+ .map_or_else(|| PathBuf::from("."), PathBuf::from);
+ loop {
+ for config_file_name in &CONFIG_FILE_NAMES {
+ let config_file = current.join(config_file_name);
+ match fs::metadata(&config_file) {
+ // Only return if it's a file to handle the unlikely situation of a directory named
+ // `clippy.toml`.
+ Ok(ref md) if !md.is_dir() => return Ok(Some(config_file)),
+ // Return the error if it's something other than `NotFound`; otherwise we didn't
+ // find the project file yet, and continue searching.
+ Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
+ _ => {},
+ }
+ }
+
+ // If the current directory has no parent, we're done searching.
+ if !current.pop() {
+ return Ok(None);
+ }
+ }
+}
+
+/// Produces a `Conf` filled with the default values and forwards the errors
+///
+/// Used internally for convenience
+fn default(errors: Vec<Error>) -> (Conf, Vec<Error>) {
+ (Conf::default(), errors)
+}
+
+/// Read the `toml` configuration file.
+///
+/// In case of error, the function tries to continue as much as possible.
+pub fn read(path: &Path) -> (Conf, Vec<Error>) {
+ let content = match fs::read_to_string(path) {
+ Ok(content) => content,
+ Err(err) => return default(vec![err.into()]),
+ };
+
+ assert!(ERRORS.lock().expect("no threading -> mutex always safe").is_empty());
+ match toml::from_str(&content) {
+ Ok(toml) => {
+ let mut errors = ERRORS.lock().expect("no threading -> mutex always safe").split_off(0);
+
+ let toml_ref: &Conf = &toml;
+
+ let cyc_field: Option<u64> = toml_ref.cyclomatic_complexity_threshold;
+
+ if cyc_field.is_some() {
+ let cyc_err = "found deprecated field `cyclomatic-complexity-threshold`. Please use `cognitive-complexity-threshold` instead.".to_string();
+ errors.push(Error::Toml(cyc_err));
+ }
+
+ (toml, errors)
+ },
+ Err(e) => {
+ let mut errors = ERRORS.lock().expect("no threading -> mutex always safe").split_off(0);
+ errors.push(Error::Toml(e.to_string()));
+
+ default(errors)
+ },
+ }
+}
--- /dev/null
- trim_multiline(snip, true, indent)
+#[macro_use]
+pub mod sym;
+
+#[allow(clippy::module_name_repetitions)]
+pub mod ast_utils;
+pub mod attrs;
+pub mod author;
+pub mod camel_case;
+pub mod comparisons;
+pub mod conf;
+pub mod constants;
+mod diagnostics;
+pub mod higher;
+mod hir_utils;
+pub mod inspector;
+pub mod internal_lints;
+pub mod numeric_literal;
+pub mod paths;
+pub mod ptr;
+pub mod sugg;
+pub mod usage;
++
+pub use self::attrs::*;
+pub use self::diagnostics::*;
+pub use self::hir_utils::{both, eq_expr_value, over, SpanlessEq, SpanlessHash};
+
+use std::borrow::Cow;
+use std::mem;
+
+use if_chain::if_chain;
+use rustc_ast::ast::{self, Attribute, LitKind};
+use rustc_attr as attr;
+use rustc_errors::Applicability;
+use rustc_hir as hir;
+use rustc_hir::def::{DefKind, Res};
+use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
+use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
+use rustc_hir::Node;
+use rustc_hir::{
+ def, Arm, Block, Body, Constness, Crate, Expr, ExprKind, FnDecl, HirId, ImplItem, ImplItemKind, Item, ItemKind,
+ MatchSource, Param, Pat, PatKind, Path, PathSegment, QPath, TraitItem, TraitItemKind, TraitRef, TyKind, Unsafety,
+};
+use rustc_infer::infer::TyCtxtInferExt;
+use rustc_lint::{LateContext, Level, Lint, LintContext};
+use rustc_middle::hir::map::Map;
+use rustc_middle::ty::subst::{GenericArg, GenericArgKind};
+use rustc_middle::ty::{self, layout::IntegerExt, Ty, TyCtxt, TypeFoldable};
+use rustc_mir::const_eval;
+use rustc_span::hygiene::{ExpnKind, MacroKind};
+use rustc_span::source_map::original_sp;
+use rustc_span::symbol::{self, kw, Symbol};
+use rustc_span::{BytePos, Pos, Span, DUMMY_SP};
+use rustc_target::abi::Integer;
+use rustc_trait_selection::traits::query::normalize::AtExt;
+use smallvec::SmallVec;
+
+use crate::consts::{constant, Constant};
+
+/// Returns `true` if the two spans come from differing expansions (i.e., one is
+/// from a macro and one isn't).
+#[must_use]
+pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
+ rhs.ctxt() != lhs.ctxt()
+}
+
+/// Returns `true` if the given `NodeId` is inside a constant context
+///
+/// # Example
+///
+/// ```rust,ignore
+/// if in_constant(cx, expr.hir_id) {
+/// // Do something
+/// }
+/// ```
+pub fn in_constant(cx: &LateContext<'_>, id: HirId) -> bool {
+ let parent_id = cx.tcx.hir().get_parent_item(id);
+ match cx.tcx.hir().get(parent_id) {
+ Node::Item(&Item {
+ kind: ItemKind::Const(..) | ItemKind::Static(..),
+ ..
+ })
+ | Node::TraitItem(&TraitItem {
+ kind: TraitItemKind::Const(..),
+ ..
+ })
+ | Node::ImplItem(&ImplItem {
+ kind: ImplItemKind::Const(..),
+ ..
+ })
+ | Node::AnonConst(_) => true,
+ Node::Item(&Item {
+ kind: ItemKind::Fn(ref sig, ..),
+ ..
+ })
+ | Node::ImplItem(&ImplItem {
+ kind: ImplItemKind::Fn(ref sig, _),
+ ..
+ }) => sig.header.constness == Constness::Const,
+ _ => false,
+ }
+}
+
+/// Returns `true` if this `span` was expanded by any macro.
+#[must_use]
+pub fn in_macro(span: Span) -> bool {
+ if span.from_expansion() {
+ !matches!(span.ctxt().outer_expn_data().kind, ExpnKind::Desugaring(..))
+ } else {
+ false
+ }
+}
++
+// If the snippet is empty, it's an attribute that was inserted during macro
+// expansion and we want to ignore those, because they could come from external
+// sources that the user has no control over.
+// For some reason these attributes don't have any expansion info on them, so
+// we have to check it this way until there is a better way.
+pub fn is_present_in_source<T: LintContext>(cx: &T, span: Span) -> bool {
+ if let Some(snippet) = snippet_opt(cx, span) {
+ if snippet.is_empty() {
+ return false;
+ }
+ }
+ true
+}
+
+/// Checks if given pattern is a wildcard (`_`)
+pub fn is_wild<'tcx>(pat: &impl std::ops::Deref<Target = Pat<'tcx>>) -> bool {
+ matches!(pat.kind, PatKind::Wild)
+}
+
+/// Checks if type is struct, enum or union type with the given def path.
+pub fn match_type(cx: &LateContext<'_>, ty: Ty<'_>, path: &[&str]) -> bool {
+ match ty.kind() {
+ ty::Adt(adt, _) => match_def_path(cx, adt.did, path),
+ _ => false,
+ }
+}
+
+/// Checks if the type is equal to a diagnostic item
+pub fn is_type_diagnostic_item(cx: &LateContext<'_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
+ match ty.kind() {
+ ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did),
+ _ => false,
+ }
+}
+
+/// Checks if the type is equal to a lang item
+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).unwrap() == adt.did,
+ _ => false,
+ }
+}
+
+/// Checks if the method call given in `expr` belongs to the given trait.
+pub fn match_trait_method(cx: &LateContext<'_>, expr: &Expr<'_>, path: &[&str]) -> bool {
+ let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap();
+ let trt_id = cx.tcx.trait_of_item(def_id);
+ trt_id.map_or(false, |trt_id| match_def_path(cx, trt_id, path))
+}
+
+/// Checks if an expression references a variable of the given name.
+pub fn match_var(expr: &Expr<'_>, var: Symbol) -> bool {
+ if let ExprKind::Path(QPath::Resolved(None, ref path)) = expr.kind {
+ if let [p] = path.segments {
+ return p.ident.name == var;
+ }
+ }
+ false
+}
+
+pub fn last_path_segment<'tcx>(path: &QPath<'tcx>) -> &'tcx PathSegment<'tcx> {
+ match *path {
+ QPath::Resolved(_, ref path) => path.segments.last().expect("A path must have at least one segment"),
+ QPath::TypeRelative(_, ref seg) => seg,
+ QPath::LangItem(..) => panic!("last_path_segment: lang item has no path segments"),
+ }
+}
+
+pub fn single_segment_path<'tcx>(path: &QPath<'tcx>) -> Option<&'tcx PathSegment<'tcx>> {
+ match *path {
+ QPath::Resolved(_, ref path) => path.segments.get(0),
+ QPath::TypeRelative(_, ref seg) => Some(seg),
+ QPath::LangItem(..) => None,
+ }
+}
+
+/// Matches a `QPath` against a slice of segment string literals.
+///
+/// There is also `match_path` if you are dealing with a `rustc_hir::Path` instead of a
+/// `rustc_hir::QPath`.
+///
+/// # Examples
+/// ```rust,ignore
+/// match_qpath(path, &["std", "rt", "begin_unwind"])
+/// ```
+pub fn match_qpath(path: &QPath<'_>, segments: &[&str]) -> bool {
+ match *path {
+ QPath::Resolved(_, ref path) => match_path(path, segments),
+ QPath::TypeRelative(ref ty, ref segment) => match ty.kind {
+ TyKind::Path(ref inner_path) => {
+ if let [prefix @ .., end] = segments {
+ if match_qpath(inner_path, prefix) {
+ return segment.ident.name.as_str() == *end;
+ }
+ }
+ false
+ },
+ _ => false,
+ },
+ QPath::LangItem(..) => false,
+ }
+}
+
+/// Matches a `Path` against a slice of segment string literals.
+///
+/// There is also `match_qpath` if you are dealing with a `rustc_hir::QPath` instead of a
+/// `rustc_hir::Path`.
+///
+/// # Examples
+///
+/// ```rust,ignore
+/// if match_path(&trait_ref.path, &paths::HASH) {
+/// // This is the `std::hash::Hash` trait.
+/// }
+///
+/// if match_path(ty_path, &["rustc", "lint", "Lint"]) {
+/// // This is a `rustc_middle::lint::Lint`.
+/// }
+/// ```
+pub fn match_path(path: &Path<'_>, segments: &[&str]) -> bool {
+ path.segments
+ .iter()
+ .rev()
+ .zip(segments.iter().rev())
+ .all(|(a, b)| a.ident.name.as_str() == *b)
+}
+
+/// Matches a `Path` against a slice of segment string literals, e.g.
+///
+/// # Examples
+/// ```rust,ignore
+/// match_path_ast(path, &["std", "rt", "begin_unwind"])
+/// ```
+pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
+ path.segments
+ .iter()
+ .rev()
+ .zip(segments.iter().rev())
+ .all(|(a, b)| a.ident.name.as_str() == *b)
+}
+
+/// Gets the definition associated to a path.
+pub fn path_to_res(cx: &LateContext<'_>, path: &[&str]) -> Option<def::Res> {
+ let crates = cx.tcx.crates();
+ let krate = crates
+ .iter()
+ .find(|&&krate| cx.tcx.crate_name(krate).as_str() == path[0]);
+ if let Some(krate) = krate {
+ let krate = DefId {
+ krate: *krate,
+ index: CRATE_DEF_INDEX,
+ };
+ let mut items = cx.tcx.item_children(krate);
+ let mut path_it = path.iter().skip(1).peekable();
+
+ loop {
+ let segment = match path_it.next() {
+ Some(segment) => segment,
+ None => return None,
+ };
+
+ let result = SmallVec::<[_; 8]>::new();
+ for item in mem::replace(&mut items, cx.tcx.arena.alloc_slice(&result)).iter() {
+ if item.ident.name.as_str() == *segment {
+ if path_it.peek().is_none() {
+ return Some(item.res);
+ }
+
+ items = cx.tcx.item_children(item.res.def_id());
+ break;
+ }
+ }
+ }
+ } else {
+ None
+ }
+}
+
+pub fn qpath_res(cx: &LateContext<'_>, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
+ match qpath {
+ hir::QPath::Resolved(_, path) => path.res,
+ hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => {
+ if cx.tcx.has_typeck_results(id.owner.to_def_id()) {
+ cx.tcx.typeck(id.owner.to_def_id().expect_local()).qpath_res(qpath, id)
+ } else {
+ Res::Err
+ }
+ },
+ }
+}
+
+/// Convenience function to get the `DefId` of a trait by path.
+/// It could be a trait or trait alias.
+pub fn get_trait_def_id(cx: &LateContext<'_>, path: &[&str]) -> Option<DefId> {
+ let res = match path_to_res(cx, path) {
+ Some(res) => res,
+ None => return None,
+ };
+
+ match res {
+ Res::Def(DefKind::Trait | DefKind::TraitAlias, trait_id) => Some(trait_id),
+ Res::Err => unreachable!("this trait resolution is impossible: {:?}", &path),
+ _ => None,
+ }
+}
+
+/// Checks whether a type implements a trait.
+/// See also `get_trait_def_id`.
+pub fn implements_trait<'tcx>(
+ cx: &LateContext<'tcx>,
+ ty: Ty<'tcx>,
+ trait_id: DefId,
+ ty_params: &[GenericArg<'tcx>],
+) -> bool {
+ // Do not check on infer_types to avoid panic in evaluate_obligation.
+ if ty.has_infer_types() {
+ return false;
+ }
+ let ty = cx.tcx.erase_regions(&ty);
+ let ty_params = cx.tcx.mk_substs(ty_params.iter());
+ cx.tcx.type_implements_trait((trait_id, ty, ty_params, cx.param_env))
+}
+
+/// Gets the `hir::TraitRef` of the trait the given method is implemented for.
+///
+/// Use this if you want to find the `TraitRef` of the `Add` trait in this example:
+///
+/// ```rust
+/// struct Point(isize, isize);
+///
+/// impl std::ops::Add for Point {
+/// type Output = Self;
+///
+/// fn add(self, other: Self) -> Self {
+/// Point(0, 0)
+/// }
+/// }
+/// ```
+pub fn trait_ref_of_method<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx TraitRef<'tcx>> {
+ // Get the implemented trait for the current function
+ let parent_impl = cx.tcx.hir().get_parent_item(hir_id);
+ if_chain! {
+ if parent_impl != hir::CRATE_HIR_ID;
+ if let hir::Node::Item(item) = cx.tcx.hir().get(parent_impl);
+ if let hir::ItemKind::Impl{ of_trait: trait_ref, .. } = &item.kind;
+ then { return trait_ref.as_ref(); }
+ }
+ None
+}
+
+/// Checks whether this type implements `Drop`.
+pub fn has_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
+ match ty.ty_adt_def() {
+ Some(def) => def.has_dtor(cx.tcx),
+ None => false,
+ }
+}
+
+/// 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<Symbol>, Vec<&'tcx [Expr<'tcx>]>, Vec<Span>) {
+ 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);
+
+ let mut current = expr;
+ for _ in 0..max_depth {
+ if let ExprKind::MethodCall(path, span, args, _) = ¤t.kind {
+ if args.iter().any(|e| e.span.from_expansion()) {
+ break;
+ }
+ method_names.push(path.ident.name);
+ arg_lists.push(&**args);
+ spans.push(*span);
+ current = &args[0];
+ } else {
+ break;
+ }
+ }
+
+ (method_names, arg_lists, spans)
+}
+
+/// Matches an `Expr` against a chain of methods, and return the matched `Expr`s.
+///
+/// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
+/// `method_chain_args(expr, &["bar", "baz"])` will return a `Vec`
+/// containing the `Expr`s for
+/// `.bar()` and `.baz()`
+pub fn method_chain_args<'a>(expr: &'a Expr<'_>, methods: &[&str]) -> Option<Vec<&'a [Expr<'a>]>> {
+ let mut current = expr;
+ let mut matched = Vec::with_capacity(methods.len());
+ for method_name in methods.iter().rev() {
+ // method chains are stored last -> first
+ if let ExprKind::MethodCall(ref path, _, ref args, _) = current.kind {
+ if path.ident.name.as_str() == *method_name {
+ if args.iter().any(|e| e.span.from_expansion()) {
+ return None;
+ }
+ matched.push(&**args); // build up `matched` backwards
+ current = &args[0] // go to parent expression
+ } else {
+ return None;
+ }
+ } else {
+ return None;
+ }
+ }
+ // Reverse `matched` so that it is in the same order as `methods`.
+ matched.reverse();
+ Some(matched)
+}
+
+/// Returns `true` if the provided `def_id` is an entrypoint to a program.
+pub fn is_entrypoint_fn(cx: &LateContext<'_>, def_id: DefId) -> bool {
+ cx.tcx
+ .entry_fn(LOCAL_CRATE)
+ .map_or(false, |(entry_fn_def_id, _)| def_id == entry_fn_def_id.to_def_id())
+}
+
+/// Gets the name of the item the expression is in, if available.
+pub fn get_item_name(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<Symbol> {
+ let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id);
+ match cx.tcx.hir().find(parent_id) {
+ Some(
+ Node::Item(Item { ident, .. })
+ | Node::TraitItem(TraitItem { ident, .. })
+ | Node::ImplItem(ImplItem { ident, .. }),
+ ) => Some(ident.name),
+ _ => None,
+ }
+}
+
+/// Gets the name of a `Pat`, if any.
+pub fn get_pat_name(pat: &Pat<'_>) -> Option<Symbol> {
+ match pat.kind {
+ PatKind::Binding(.., ref spname, _) => Some(spname.name),
+ PatKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.ident.name),
+ PatKind::Box(ref p) | PatKind::Ref(ref p, _) => get_pat_name(&*p),
+ _ => None,
+ }
+}
+
+struct ContainsName {
+ name: Symbol,
+ result: bool,
+}
+
+impl<'tcx> Visitor<'tcx> for ContainsName {
+ type Map = Map<'tcx>;
+
+ fn visit_name(&mut self, _: Span, name: Symbol) {
+ if self.name == name {
+ self.result = true;
+ }
+ }
+ fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+ NestedVisitorMap::None
+ }
+}
+
+/// Checks if an `Expr` contains a certain name.
+pub fn contains_name(name: Symbol, expr: &Expr<'_>) -> bool {
+ let mut cn = ContainsName { name, result: false };
+ cn.visit_expr(expr);
+ cn.result
+}
+
+/// Converts a span to a code snippet if available, otherwise use default.
+///
+/// This is useful if you want to provide suggestions for your lint or more generally, if you want
+/// to convert a given `Span` to a `str`.
+///
+/// # Example
+/// ```rust,ignore
+/// snippet(cx, expr.span, "..")
+/// ```
+pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
+ snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
+}
+
+/// Same as `snippet`, but it adapts the applicability level by following rules:
+///
+/// - Applicability level `Unspecified` will never be changed.
+/// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
+/// - If the default value is used and the applicability level is `MachineApplicable`, change it to
+/// `HasPlaceholders`
+pub fn snippet_with_applicability<'a, T: LintContext>(
+ cx: &T,
+ span: Span,
+ default: &'a str,
+ applicability: &mut Applicability,
+) -> Cow<'a, str> {
+ if *applicability != Applicability::Unspecified && span.from_expansion() {
+ *applicability = Applicability::MaybeIncorrect;
+ }
+ snippet_opt(cx, span).map_or_else(
+ || {
+ if *applicability == Applicability::MachineApplicable {
+ *applicability = Applicability::HasPlaceholders;
+ }
+ Cow::Borrowed(default)
+ },
+ From::from,
+ )
+}
+
+/// Same as `snippet`, but should only be used when it's clear that the input span is
+/// not a macro argument.
+pub fn snippet_with_macro_callsite<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
+ snippet(cx, span.source_callsite(), default)
+}
+
+/// Converts a span to a code snippet. Returns `None` if not available.
+pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
+ cx.sess().source_map().span_to_snippet(span).ok()
+}
+
+/// Converts a span (from a block) to a code snippet if available, otherwise use default.
+///
+/// This trims the code of indentation, except for the first line. Use it for blocks or block-like
+/// things which need to be printed as such.
+///
+/// The `indent_relative_to` arg can be used, to provide a span, where the indentation of the
+/// resulting snippet of the given span.
+///
+/// # Example
+///
+/// ```rust,ignore
+/// snippet_block(cx, block.span, "..", None)
+/// // where, `block` is the block of the if expr
+/// if x {
+/// y;
+/// }
+/// // will return the snippet
+/// {
+/// y;
+/// }
+/// ```
+///
+/// ```rust,ignore
+/// snippet_block(cx, block.span, "..", Some(if_expr.span))
+/// // where, `block` is the block of the if expr
+/// if x {
+/// y;
+/// }
+/// // will return the snippet
+/// {
+/// y;
+/// } // aligned with `if`
+/// ```
+/// Note that the first line of the snippet always has 0 indentation.
+pub fn snippet_block<'a, T: LintContext>(
+ cx: &T,
+ span: Span,
+ default: &'a str,
+ indent_relative_to: Option<Span>,
+) -> Cow<'a, str> {
+ let snip = snippet(cx, span, default);
+ let indent = indent_relative_to.and_then(|s| indent_of(cx, s));
- trim_multiline(snip, true, indent)
++ reindent_multiline(snip, true, indent)
+}
+
+/// Same as `snippet_block`, but adapts the applicability level by the rules of
+/// `snippet_with_applicability`.
+pub fn snippet_block_with_applicability<'a, T: LintContext>(
+ cx: &T,
+ span: Span,
+ default: &'a str,
+ indent_relative_to: Option<Span>,
+ applicability: &mut Applicability,
+) -> Cow<'a, str> {
+ let snip = snippet_with_applicability(cx, span, default, applicability);
+ let indent = indent_relative_to.and_then(|s| indent_of(cx, s));
- /// Trim indentation from a multiline string with possibility of ignoring the
- /// first line.
- fn trim_multiline(s: Cow<'_, str>, ignore_first: bool, indent: Option<usize>) -> Cow<'_, str> {
- let s_space = trim_multiline_inner(s, ignore_first, indent, ' ');
- let s_tab = trim_multiline_inner(s_space, ignore_first, indent, '\t');
- trim_multiline_inner(s_tab, ignore_first, indent, ' ')
++ reindent_multiline(snip, true, indent)
+}
+
+/// Returns a new Span that extends the original Span to the first non-whitespace char of the first
+/// line.
+///
+/// ```rust,ignore
+/// let x = ();
+/// // ^^
+/// // will be converted to
+/// let x = ();
+/// // ^^^^^^^^^^
+/// ```
+pub fn first_line_of_span<T: LintContext>(cx: &T, span: Span) -> Span {
+ first_char_in_first_line(cx, span).map_or(span, |first_char_pos| span.with_lo(first_char_pos))
+}
+
+fn first_char_in_first_line<T: LintContext>(cx: &T, span: Span) -> Option<BytePos> {
+ let line_span = line_span(cx, span);
+ snippet_opt(cx, line_span).and_then(|snip| {
+ snip.find(|c: char| !c.is_whitespace())
+ .map(|pos| line_span.lo() + BytePos::from_usize(pos))
+ })
+}
+
+/// Returns the indentation of the line of a span
+///
+/// ```rust,ignore
+/// let x = ();
+/// // ^^ -- will return 0
+/// let x = ();
+/// // ^^ -- will return 4
+/// ```
+pub fn indent_of<T: LintContext>(cx: &T, span: Span) -> Option<usize> {
+ snippet_opt(cx, line_span(cx, span)).and_then(|snip| snip.find(|c: char| !c.is_whitespace()))
+}
+
+/// Extends the span to the beginning of the spans line, incl. whitespaces.
+///
+/// ```rust,ignore
+/// let x = ();
+/// // ^^
+/// // will be converted to
+/// let x = ();
+/// // ^^^^^^^^^^^^^^
+/// ```
+fn line_span<T: LintContext>(cx: &T, span: Span) -> Span {
+ let span = original_sp(span, DUMMY_SP);
+ let source_map_and_line = cx.sess().source_map().lookup_line(span.lo()).unwrap();
+ let line_no = source_map_and_line.line;
+ let line_start = source_map_and_line.sf.lines[line_no];
+ Span::new(line_start, span.hi(), span.ctxt())
+}
+
+/// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`.
+/// Also takes an `Option<String>` which can be put inside the braces.
+pub fn expr_block<'a, T: LintContext>(
+ cx: &T,
+ expr: &Expr<'_>,
+ option: Option<String>,
+ default: &'a str,
+ indent_relative_to: Option<Span>,
+) -> Cow<'a, str> {
+ let code = snippet_block(cx, expr.span, default, indent_relative_to);
+ let string = option.unwrap_or_default();
+ if expr.span.from_expansion() {
+ Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default)))
+ } else if let ExprKind::Block(_, _) = expr.kind {
+ Cow::Owned(format!("{}{}", code, string))
+ } else if string.is_empty() {
+ Cow::Owned(format!("{{ {} }}", code))
+ } else {
+ Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
+ }
+}
+
- fn trim_multiline_inner(s: Cow<'_, str>, ignore_first: bool, indent: Option<usize>, ch: char) -> Cow<'_, str> {
- let mut x = s
++/// Reindent a multiline string with possibility of ignoring the first line.
++#[allow(clippy::needless_pass_by_value)]
++pub fn reindent_multiline(s: Cow<'_, str>, ignore_first: bool, indent: Option<usize>) -> Cow<'_, str> {
++ let s_space = reindent_multiline_inner(&s, ignore_first, indent, ' ');
++ let s_tab = reindent_multiline_inner(&s_space, ignore_first, indent, '\t');
++ reindent_multiline_inner(&s_tab, ignore_first, indent, ' ').into()
+}
+
- if let Some(indent) = indent {
- x = x.saturating_sub(indent);
- }
- if x > 0 {
- Cow::Owned(
- s.lines()
- .enumerate()
- .map(|(i, l)| {
- if (ignore_first && i == 0) || l.is_empty() {
- l
- } else {
- l.split_at(x).1
- }
- })
- .collect::<Vec<_>>()
- .join("\n"),
- )
- } else {
- s
- }
++fn reindent_multiline_inner(s: &str, ignore_first: bool, indent: Option<usize>, ch: char) -> String {
++ let x = s
+ .lines()
+ .skip(ignore_first as usize)
+ .filter_map(|l| {
+ if l.is_empty() {
+ None
+ } else {
+ // ignore empty lines
+ Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
+ }
+ })
+ .min()
+ .unwrap_or(0);
- def::Res::Def(DefKind::Fn, def_id) if has_no_arguments(cx, def_id) => {
++ let indent = indent.unwrap_or(0);
++ s.lines()
++ .enumerate()
++ .map(|(i, l)| {
++ if (ignore_first && i == 0) || l.is_empty() {
++ l.to_owned()
++ } else if x > indent {
++ l.split_at(x - indent).1.to_owned()
++ } else {
++ " ".repeat(indent - x) + l
++ }
++ })
++ .collect::<Vec<String>>()
++ .join("\n")
+}
+
+/// Gets the parent expression, if any –- this is useful to constrain a lint.
+pub fn get_parent_expr<'c>(cx: &'c LateContext<'_>, e: &Expr<'_>) -> Option<&'c Expr<'c>> {
+ let map = &cx.tcx.hir();
+ let hir_id = e.hir_id;
+ let parent_id = map.get_parent_node(hir_id);
+ if hir_id == parent_id {
+ return None;
+ }
+ map.find(parent_id).and_then(|node| {
+ if let Node::Expr(parent) = node {
+ Some(parent)
+ } else {
+ None
+ }
+ })
+}
+
+pub fn get_enclosing_block<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx Block<'tcx>> {
+ let map = &cx.tcx.hir();
+ let enclosing_node = map
+ .get_enclosing_scope(hir_id)
+ .and_then(|enclosing_id| map.find(enclosing_id));
+ enclosing_node.and_then(|node| match node {
+ Node::Block(block) => Some(block),
+ Node::Item(&Item {
+ kind: ItemKind::Fn(_, _, eid),
+ ..
+ })
+ | Node::ImplItem(&ImplItem {
+ kind: ImplItemKind::Fn(_, eid),
+ ..
+ }) => match cx.tcx.hir().body(eid).value.kind {
+ ExprKind::Block(ref block, _) => Some(block),
+ _ => None,
+ },
+ _ => None,
+ })
+}
+
+/// Returns the base type for HIR references and pointers.
+pub fn walk_ptrs_hir_ty<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
+ match ty.kind {
+ TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(&mut_ty.ty),
+ _ => ty,
+ }
+}
+
+/// Returns the base type for references and raw pointers.
+pub fn walk_ptrs_ty(ty: Ty<'_>) -> Ty<'_> {
+ match ty.kind() {
+ ty::Ref(_, ty, _) => walk_ptrs_ty(ty),
+ _ => ty,
+ }
+}
+
+/// Returns the base type for references and raw pointers, and count reference
+/// depth.
+pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
+ fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
+ match ty.kind() {
+ ty::Ref(_, ty, _) => inner(ty, depth + 1),
+ _ => (ty, depth),
+ }
+ }
+ inner(ty, 0)
+}
+
+/// Checks whether the given expression is a constant integer of the given value.
+/// unlike `is_integer_literal`, this version does const folding
+pub fn is_integer_const(cx: &LateContext<'_>, e: &Expr<'_>, value: u128) -> bool {
+ if is_integer_literal(e, value) {
+ return true;
+ }
+ let map = cx.tcx.hir();
+ let parent_item = map.get_parent_item(e.hir_id);
+ if let Some((Constant::Int(v), _)) = map
+ .maybe_body_owned_by(parent_item)
+ .and_then(|body_id| constant(cx, cx.tcx.typeck_body(body_id), e))
+ {
+ value == v
+ } else {
+ false
+ }
+}
+
+/// Checks whether the given expression is a constant literal of the given value.
+pub fn is_integer_literal(expr: &Expr<'_>, value: u128) -> bool {
+ // FIXME: use constant folding
+ if let ExprKind::Lit(ref spanned) = expr.kind {
+ if let LitKind::Int(v, _) = spanned.node {
+ return v == value;
+ }
+ }
+ false
+}
+
+/// Returns `true` if the given `Expr` has been coerced before.
+///
+/// Examples of coercions can be found in the Nomicon at
+/// <https://doc.rust-lang.org/nomicon/coercions.html>.
+///
+/// See `rustc_middle::ty::adjustment::Adjustment` and `rustc_typeck::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()
+}
+
+/// Returns the pre-expansion span if is this comes from an expansion of the
+/// macro `name`.
+/// See also `is_direct_expn_of`.
+#[must_use]
+pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
+ loop {
+ if span.from_expansion() {
+ let data = span.ctxt().outer_expn_data();
+ let new_span = data.call_site;
+
+ if let ExpnKind::Macro(MacroKind::Bang, mac_name) = data.kind {
+ if mac_name.as_str() == name {
+ return Some(new_span);
+ }
+ }
+
+ span = new_span;
+ } else {
+ return None;
+ }
+ }
+}
+
+/// Returns the pre-expansion span if the span directly comes from an expansion
+/// of the macro `name`.
+/// The difference with `is_expn_of` is that in
+/// ```rust,ignore
+/// foo!(bar!(42));
+/// ```
+/// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
+/// `bar!` by
+/// `is_direct_expn_of`.
+#[must_use]
+pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
+ if span.from_expansion() {
+ let data = span.ctxt().outer_expn_data();
+ let new_span = data.call_site;
+
+ if let ExpnKind::Macro(MacroKind::Bang, mac_name) = data.kind {
+ if mac_name.as_str() == name {
+ return Some(new_span);
+ }
+ }
+ }
+
+ None
+}
+
+/// Convenience function to get the return type of a function.
+pub fn return_ty<'tcx>(cx: &LateContext<'tcx>, fn_item: hir::HirId) -> Ty<'tcx> {
+ let fn_def_id = cx.tcx.hir().local_def_id(fn_item);
+ let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
+ cx.tcx.erase_late_bound_regions(&ret_ty)
+}
+
+/// Walks into `ty` and returns `true` if any inner type is the same as `other_ty`
+pub fn contains_ty(ty: Ty<'_>, other_ty: Ty<'_>) -> bool {
+ ty.walk().any(|inner| match inner.unpack() {
+ GenericArgKind::Type(inner_ty) => ty::TyS::same_type(other_ty, inner_ty),
+ GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
+ })
+}
+
+/// Returns `true` if the given type is an `unsafe` function.
+pub fn type_is_unsafe_function<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
+ match ty.kind() {
+ ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
+ _ => false,
+ }
+}
+
+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)
+}
+
+/// Checks if an expression is constructing a tuple-like enum variant or struct
+pub fn is_ctor_or_promotable_const_function(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
+ fn has_no_arguments(cx: &LateContext<'_>, def_id: DefId) -> bool {
+ cx.tcx.fn_sig(def_id).skip_binder().inputs().is_empty()
+ }
+
+ if let ExprKind::Call(ref fun, _) = expr.kind {
+ if let ExprKind::Path(ref qp) = fun.kind {
+ let res = cx.qpath_res(qp, fun.hir_id);
+ return match res {
+ def::Res::Def(DefKind::Variant | DefKind::Ctor(..), ..) => true,
+ // FIXME: check the constness of the arguments, see https://github.com/rust-lang/rust-clippy/pull/5682#issuecomment-638681210
- }
++ def::Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) if has_no_arguments(cx, def_id) => {
+ const_eval::is_const_fn(cx.tcx, def_id)
+ },
+ def::Res::Def(_, def_id) => cx.tcx.is_promotable_const_fn(def_id),
+ _ => false,
+ };
+ }
+ }
+ false
+}
+
+/// Returns `true` if a pattern is refutable.
+// TODO: should be implemented using rustc/mir_build/thir machinery
+pub fn is_refutable(cx: &LateContext<'_>, pat: &Pat<'_>) -> bool {
+ fn is_enum_variant(cx: &LateContext<'_>, qpath: &QPath<'_>, id: HirId) -> bool {
+ matches!(
+ cx.qpath_res(qpath, id),
+ def::Res::Def(DefKind::Variant, ..) | Res::Def(DefKind::Ctor(def::CtorOf::Variant, _), _)
+ )
+ }
+
+ fn are_refutable<'a, I: Iterator<Item = &'a Pat<'a>>>(cx: &LateContext<'_>, mut i: I) -> bool {
+ i.any(|pat| is_refutable(cx, pat))
+ }
+
+ match pat.kind {
+ PatKind::Wild => false,
+ PatKind::Binding(_, _, _, pat) => pat.map_or(false, |pat| is_refutable(cx, pat)),
+ PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
+ PatKind::Lit(..) | PatKind::Range(..) => true,
+ PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
+ PatKind::Or(ref pats) => {
+ // TODO: should be the honest check, that pats is exhaustive set
+ are_refutable(cx, pats.iter().map(|pat| &**pat))
+ },
+ PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
+ PatKind::Struct(ref qpath, ref fields, _) => {
+ is_enum_variant(cx, qpath, pat.hir_id) || are_refutable(cx, fields.iter().map(|field| &*field.pat))
+ },
+ PatKind::TupleStruct(ref qpath, ref pats, _) => {
+ is_enum_variant(cx, qpath, pat.hir_id) || are_refutable(cx, pats.iter().map(|pat| &**pat))
+ },
+ PatKind::Slice(ref head, ref middle, ref tail) => {
+ match &cx.typeck_results().node_type(pat.hir_id).kind() {
+ ty::Slice(..) => {
+ // [..] is the only irrefutable slice pattern.
+ !head.is_empty() || middle.is_none() || !tail.is_empty()
+ },
+ ty::Array(..) => are_refutable(cx, head.iter().chain(middle).chain(tail.iter()).map(|pat| &**pat)),
+ _ => {
+ // unreachable!()
+ true
+ },
+ }
+ },
+ }
+}
+
+/// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
+/// implementations have.
+pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
+ attrs.iter().any(|attr| attr.has_name(sym!(automatically_derived)))
+}
+
+/// Remove blocks around an expression.
+///
+/// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
+/// themselves.
+pub fn remove_blocks<'tcx>(mut expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
+ while let ExprKind::Block(ref block, ..) = expr.kind {
+ match (block.stmts.is_empty(), block.expr.as_ref()) {
+ (true, Some(e)) => expr = e,
+ _ => break,
+ }
+ }
+ expr
+}
+
+pub fn is_self(slf: &Param<'_>) -> bool {
+ if let PatKind::Binding(.., name, _) = slf.pat.kind {
+ name.name == kw::SelfLower
+ } else {
+ false
+ }
+}
+
+pub fn is_self_ty(slf: &hir::Ty<'_>) -> bool {
+ if_chain! {
+ if let TyKind::Path(ref qp) = slf.kind;
+ if let QPath::Resolved(None, ref path) = *qp;
+ if let Res::SelfTy(..) = path.res;
+ then {
+ return true
+ }
+ }
+ false
+}
+
+pub fn iter_input_pats<'tcx>(decl: &FnDecl<'_>, body: &'tcx Body<'_>) -> impl Iterator<Item = &'tcx Param<'tcx>> {
+ (0..decl.inputs.len()).map(move |i| &body.params[i])
+}
+
+/// Checks if a given expression is a match expression expanded from the `?`
+/// operator or the `try` macro.
+pub fn is_try<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
+ fn is_ok(arm: &Arm<'_>) -> bool {
+ if_chain! {
+ if let PatKind::TupleStruct(ref path, ref pat, None) = arm.pat.kind;
+ if match_qpath(path, &paths::RESULT_OK[1..]);
+ if let PatKind::Binding(_, hir_id, _, None) = pat[0].kind;
+ if let ExprKind::Path(QPath::Resolved(None, ref path)) = arm.body.kind;
+ if let Res::Local(lid) = path.res;
+ if lid == hir_id;
+ then {
+ return true;
+ }
+ }
+ false
+ }
+
+ fn is_err(arm: &Arm<'_>) -> bool {
+ if let PatKind::TupleStruct(ref path, _, _) = arm.pat.kind {
+ match_qpath(path, &paths::RESULT_ERR[1..])
+ } else {
+ false
+ }
+ }
+
+ if let ExprKind::Match(_, ref arms, ref source) = expr.kind {
+ // desugared from a `?` operator
+ if let MatchSource::TryDesugar = *source {
+ return Some(expr);
+ }
+
+ if_chain! {
+ if arms.len() == 2;
+ if arms[0].guard.is_none();
+ if arms[1].guard.is_none();
+ if (is_ok(&arms[0]) && is_err(&arms[1])) ||
+ (is_ok(&arms[1]) && is_err(&arms[0]));
+ then {
+ return Some(expr);
+ }
+ }
+ }
+
+ None
+}
+
+/// Returns `true` if the lint is allowed in the current context
+///
+/// Useful for skipping long running code when it's unnecessary
+pub fn is_allowed(cx: &LateContext<'_>, lint: &'static Lint, id: HirId) -> bool {
+ cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow
+}
+
+pub fn get_arg_name(pat: &Pat<'_>) -> Option<Symbol> {
+ match pat.kind {
+ PatKind::Binding(.., ident, None) => Some(ident.name),
+ PatKind::Ref(ref subpat, _) => get_arg_name(subpat),
+ _ => None,
+ }
+}
+
+pub fn int_bits(tcx: TyCtxt<'_>, ity: ast::IntTy) -> u64 {
+ Integer::from_attr(&tcx, attr::IntType::SignedInt(ity)).size().bits()
+}
+
+#[allow(clippy::cast_possible_wrap)]
+/// Turn a constant int byte representation into an i128
+pub fn sext(tcx: TyCtxt<'_>, u: u128, ity: ast::IntTy) -> i128 {
+ let amt = 128 - int_bits(tcx, ity);
+ ((u as i128) << amt) >> amt
+}
+
+#[allow(clippy::cast_sign_loss)]
+/// clip unused bytes
+pub fn unsext(tcx: TyCtxt<'_>, u: i128, ity: ast::IntTy) -> u128 {
+ let amt = 128 - int_bits(tcx, ity);
+ ((u as u128) << amt) >> amt
+}
+
+/// clip unused bytes
+pub fn clip(tcx: TyCtxt<'_>, u: u128, ity: ast::UintTy) -> u128 {
+ let bits = Integer::from_attr(&tcx, attr::IntType::UnsignedInt(ity)).size().bits();
+ let amt = 128 - bits;
+ (u << amt) >> amt
+}
+
+/// Removes block comments from the given `Vec` of lines.
+///
+/// # Examples
+///
+/// ```rust,ignore
+/// without_block_comments(vec!["/*", "foo", "*/"]);
+/// // => vec![]
+///
+/// without_block_comments(vec!["bar", "/*", "foo", "*/"]);
+/// // => vec!["bar"]
+/// ```
+pub fn without_block_comments(lines: Vec<&str>) -> Vec<&str> {
+ let mut without = vec![];
+
+ let mut nest_level = 0;
+
+ for line in lines {
+ if line.contains("/*") {
+ nest_level += 1;
+ continue;
+ } else if line.contains("*/") {
+ nest_level -= 1;
+ continue;
+ }
+
+ if nest_level == 0 {
+ without.push(line);
+ }
+ }
+
+ without
+}
+
+pub fn any_parent_is_automatically_derived(tcx: TyCtxt<'_>, node: HirId) -> bool {
+ let map = &tcx.hir();
+ let mut prev_enclosing_node = None;
+ let mut enclosing_node = node;
+ while Some(enclosing_node) != prev_enclosing_node {
+ if is_automatically_derived(map.attrs(enclosing_node)) {
+ return true;
+ }
+ prev_enclosing_node = Some(enclosing_node);
+ enclosing_node = map.get_parent_item(enclosing_node);
+ }
+ false
+}
+
+/// Returns true if ty has `iter` or `iter_mut` methods
+pub fn has_iter_method(cx: &LateContext<'_>, probably_ref_ty: Ty<'_>) -> Option<&'static str> {
+ // FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
+ // exists and has the desired signature. Unfortunately FnCtxt is not exported
+ // so we can't use its `lookup_method` method.
+ let into_iter_collections: [&[&str]; 13] = [
+ &paths::VEC,
+ &paths::OPTION,
+ &paths::RESULT,
+ &paths::BTREESET,
+ &paths::BTREEMAP,
+ &paths::VEC_DEQUE,
+ &paths::LINKED_LIST,
+ &paths::BINARY_HEAP,
+ &paths::HASHSET,
+ &paths::HASHMAP,
+ &paths::PATH_BUF,
+ &paths::PATH,
+ &paths::RECEIVER,
+ ];
+
+ let ty_to_check = match probably_ref_ty.kind() {
+ ty::Ref(_, ty_to_check, _) => ty_to_check,
+ _ => probably_ref_ty,
+ };
+
+ let def_id = match ty_to_check.kind() {
+ ty::Array(..) => return Some("array"),
+ ty::Slice(..) => return Some("slice"),
+ ty::Adt(adt, _) => adt.did,
+ _ => return None,
+ };
+
+ for path in &into_iter_collections {
+ if match_def_path(cx, def_id, path) {
+ return Some(*path.last().unwrap());
+ }
+ }
+ None
+}
+
+/// Matches a function call with the given path and returns the arguments.
+///
+/// Usage:
+///
+/// ```rust,ignore
+/// if let Some(args) = match_function_call(cx, begin_panic_call, &paths::BEGIN_PANIC);
+/// ```
+pub fn match_function_call<'tcx>(
+ cx: &LateContext<'tcx>,
+ expr: &'tcx Expr<'_>,
+ path: &[&str],
+) -> Option<&'tcx [Expr<'tcx>]> {
+ if_chain! {
+ if let ExprKind::Call(ref fun, ref args) = expr.kind;
+ if let ExprKind::Path(ref qpath) = fun.kind;
+ if let Some(fun_def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
+ if match_def_path(cx, fun_def_id, path);
+ then {
+ return Some(&args)
+ }
+ };
+ None
+}
+
+/// 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 {
+ cx.tcx.infer_ctxt().enter(|infcx| {
+ let cause = rustc_middle::traits::ObligationCause::dummy();
+ infcx.at(&cause, param_env).normalize(&ty).is_ok()
+ })
+}
+
+pub fn match_def_path<'tcx>(cx: &LateContext<'tcx>, did: DefId, syms: &[&str]) -> bool {
+ // We have to convert `syms` to `&[Symbol]` here because rustc's `match_def_path`
+ // accepts only that. We should probably move to Symbols in Clippy as well.
+ let syms = syms.iter().map(|p| Symbol::intern(p)).collect::<Vec<Symbol>>();
+ cx.match_def_path(did, &syms)
+}
+
+/// Returns the list of condition expressions and the list of blocks in a
+/// sequence of `if/else`.
+/// E.g., this returns `([a, b], [c, d, e])` for the expression
+/// `if a { c } else if b { d } else { e }`.
+pub fn if_sequence<'tcx>(
+ mut expr: &'tcx Expr<'tcx>,
+) -> (SmallVec<[&'tcx Expr<'tcx>; 1]>, SmallVec<[&'tcx Block<'tcx>; 1]>) {
+ let mut conds = SmallVec::new();
+ let mut blocks: SmallVec<[&Block<'_>; 1]> = SmallVec::new();
+
+ while let Some((ref cond, ref then_expr, ref else_expr)) = higher::if_block(&expr) {
+ conds.push(&**cond);
+ if let ExprKind::Block(ref block, _) = then_expr.kind {
+ blocks.push(block);
+ } else {
+ panic!("ExprKind::If node is not an ExprKind::Block");
+ }
+
+ if let Some(ref else_expr) = *else_expr {
+ expr = else_expr;
+ } else {
+ break;
+ }
+ }
+
+ // final `else {..}`
+ if !blocks.is_empty() {
+ if let ExprKind::Block(ref block, _) = expr.kind {
+ blocks.push(&**block);
+ }
+ }
+
+ (conds, blocks)
+}
+
+pub fn parent_node_is_if_expr(expr: &Expr<'_>, cx: &LateContext<'_>) -> bool {
+ let map = cx.tcx.hir();
+ let parent_id = map.get_parent_node(expr.hir_id);
+ let parent_node = map.get(parent_id);
+
+ match parent_node {
+ Node::Expr(e) => higher::if_block(&e).is_some(),
+ Node::Arm(e) => higher::if_block(&e.body).is_some(),
+ _ => false,
+ }
+}
+
+// Finds the attribute with the given name, if any
+pub fn attr_by_name<'a>(attrs: &'a [Attribute], name: &'_ str) -> Option<&'a Attribute> {
+ attrs
+ .iter()
+ .find(|attr| attr.ident().map_or(false, |ident| ident.as_str() == name))
+}
+
+// Finds the `#[must_use]` attribute, if any
+pub fn must_use_attr(attrs: &[Attribute]) -> Option<&Attribute> {
+ attr_by_name(attrs, "must_use")
+}
+
+// Returns whether the type has #[must_use] attribute
+pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
+ match ty.kind() {
+ ty::Adt(ref adt, _) => must_use_attr(&cx.tcx.get_attrs(adt.did)).is_some(),
+ ty::Foreign(ref did) => must_use_attr(&cx.tcx.get_attrs(*did)).is_some(),
+ ty::Slice(ref ty)
+ | ty::Array(ref ty, _)
+ | ty::RawPtr(ty::TypeAndMut { ref ty, .. })
+ | ty::Ref(_, 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(ref substs) => substs.types().any(|ty| is_must_use_ty(cx, ty)),
+ ty::Opaque(ref def_id, _) => {
+ for (predicate, _) in cx.tcx.predicates_of(*def_id).predicates {
+ if let ty::PredicateAtom::Trait(trait_predicate, _) = predicate.skip_binders() {
+ if must_use_attr(&cx.tcx.get_attrs(trait_predicate.trait_ref.def_id)).is_some() {
+ return true;
+ }
+ }
+ }
+ false
+ },
+ ty::Dynamic(binder, _) => {
+ for predicate in binder.skip_binder().iter() {
+ if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate {
+ if must_use_attr(&cx.tcx.get_attrs(trait_ref.def_id)).is_some() {
+ return true;
+ }
+ }
+ }
+ false
+ },
+ _ => false,
+ }
+}
+
+// check if expr is calling method or function with #[must_use] attribute
+pub fn is_must_use_func_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
+ let did = match expr.kind {
+ ExprKind::Call(ref path, _) => if_chain! {
+ if let ExprKind::Path(ref qpath) = path.kind;
+ if let def::Res::Def(_, did) = cx.qpath_res(qpath, path.hir_id);
+ then {
+ Some(did)
+ } else {
+ None
+ }
+ },
+ ExprKind::MethodCall(_, _, _, _) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
+ _ => None,
+ };
+
+ did.map_or(false, |did| must_use_attr(&cx.tcx.get_attrs(did)).is_some())
+}
+
+pub fn is_no_std_crate(krate: &Crate<'_>) -> bool {
+ krate.item.attrs.iter().any(|attr| {
+ if let ast::AttrKind::Normal(ref attr) = attr.kind {
+ attr.path == symbol::sym::no_std
+ } else {
+ false
+ }
+ })
+}
+
+/// Check if parent of a hir node is a trait implementation block.
+/// For example, `f` in
+/// ```rust,ignore
+/// impl Trait for S {
+/// fn f() {}
+/// }
+/// ```
+pub fn is_trait_impl_item(cx: &LateContext<'_>, hir_id: HirId) -> bool {
+ if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
+ matches!(item.kind, ItemKind::Impl{ of_trait: Some(_), .. })
+ } else {
+ false
+ }
+}
+
+/// Check if it's even possible to satisfy the `where` clause for the item.
+///
+/// `trivial_bounds` feature allows functions with unsatisfiable bounds, for example:
+///
+/// ```ignore
+/// fn foo() where i32: Iterator {
+/// for _ in 2i32 {}
+/// }
+/// ```
+pub fn fn_has_unsatisfiable_preds(cx: &LateContext<'_>, did: DefId) -> bool {
+ use rustc_trait_selection::traits;
+ let predicates =
+ cx.tcx
+ .predicates_of(did)
+ .predicates
+ .iter()
+ .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
+ traits::impossible_predicates(
+ cx.tcx,
+ traits::elaborate_predicates(cx.tcx, predicates)
+ .map(|o| o.predicate)
+ .collect::<Vec<_>>(),
+ )
+}
+
+/// Returns the `DefId` of the callee if the given expression is a function or method call.
+pub fn fn_def_id(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<DefId> {
+ match &expr.kind {
+ ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
+ ExprKind::Call(
+ Expr {
+ kind: ExprKind::Path(qpath),
+ ..
+ },
+ ..,
+ ) => cx.typeck_results().qpath_res(qpath, expr.hir_id).opt_def_id(),
+ _ => None,
+ }
+}
+
+pub fn run_lints(cx: &LateContext<'_>, lints: &[&'static Lint], id: HirId) -> bool {
+ lints.iter().any(|lint| {
+ matches!(
+ cx.tcx.lint_level_at_node(lint, id),
+ (Level::Forbid | Level::Deny | Level::Warn, _)
+ )
+ })
+}
+
+/// Returns true iff the given type is a primitive (a bool or char, any integer or floating-point
+/// number type, a str, or an array, slice, or tuple of those types).
+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::Tuple(inner_types) => inner_types.types().all(is_recursively_primitive_type),
+ _ => false,
+ }
+}
+
+/// Returns Option<String> where String is a textual representation of the type encapsulated in the
+/// slice iff the given expression is a slice of primitives (as defined in the
+/// `is_recursively_primitive_type` function) and None otherwise.
+pub fn is_slice_of_primitives(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<String> {
+ let expr_type = cx.typeck_results().expr_ty_adjusted(expr);
+ let expr_kind = expr_type.kind();
+ let is_primitive = match expr_kind {
+ ty::Slice(element_type) => is_recursively_primitive_type(element_type),
+ ty::Ref(_, inner_ty, _) if matches!(inner_ty.kind(), &ty::Slice(_)) => {
+ if let ty::Slice(element_type) = inner_ty.kind() {
+ is_recursively_primitive_type(element_type)
+ } else {
+ unreachable!()
+ }
- use super::{trim_multiline, without_block_comments};
++ },
+ _ => false,
+ };
+
+ if is_primitive {
+ // if we have wrappers like Array, Slice or Tuple, print these
+ // and get the type enclosed in the slice ref
+ match expr_type.peel_refs().walk().nth(1).unwrap().expect_ty().kind() {
+ ty::Slice(..) => return Some("slice".into()),
+ ty::Array(..) => return Some("array".into()),
+ ty::Tuple(..) => return Some("tuple".into()),
+ _ => {
+ // is_recursively_primitive_type() should have taken care
+ // of the rest and we can rely on the type that is found
+ let refs_peeled = expr_type.peel_refs();
+ return Some(refs_peeled.walk().last().unwrap().to_string());
+ },
+ }
+ }
+ None
+}
+
+#[macro_export]
+macro_rules! unwrap_cargo_metadata {
+ ($cx: ident, $lint: ident, $deps: expr) => {{
+ let mut command = cargo_metadata::MetadataCommand::new();
+ if !$deps {
+ command.no_deps();
+ }
+
+ match command.exec() {
+ Ok(metadata) => metadata,
+ Err(err) => {
+ span_lint($cx, $lint, DUMMY_SP, &format!("could not read cargo metadata: {}", err));
+ return;
+ },
+ }
+ }};
+}
+
+#[cfg(test)]
+mod test {
- fn test_trim_multiline_single_line() {
- assert_eq!("", trim_multiline("".into(), false, None));
- assert_eq!("...", trim_multiline("...".into(), false, None));
- assert_eq!("...", trim_multiline(" ...".into(), false, None));
- assert_eq!("...", trim_multiline("\t...".into(), false, None));
- assert_eq!("...", trim_multiline("\t\t...".into(), false, None));
++ use super::{reindent_multiline, without_block_comments};
+
+ #[test]
- fn test_trim_multiline_block() {
++ fn test_reindent_multiline_single_line() {
++ assert_eq!("", reindent_multiline("".into(), false, None));
++ assert_eq!("...", reindent_multiline("...".into(), false, None));
++ assert_eq!("...", reindent_multiline(" ...".into(), false, None));
++ assert_eq!("...", reindent_multiline("\t...".into(), false, None));
++ assert_eq!("...", reindent_multiline("\t\t...".into(), false, None));
+ }
+
+ #[test]
+ #[rustfmt::skip]
- }", trim_multiline(" if x {
++ fn test_reindent_multiline_block() {
+ assert_eq!("\
+ if x {
+ y
+ } else {
+ z
- }", trim_multiline(" if x {
++ }", reindent_multiline(" if x {
+ y
+ } else {
+ z
+ }".into(), false, None));
+ assert_eq!("\
+ if x {
+ \ty
+ } else {
+ \tz
- fn test_trim_multiline_empty_line() {
++ }", reindent_multiline(" if x {
+ \ty
+ } else {
+ \tz
+ }".into(), false, None));
+ }
+
+ #[test]
+ #[rustfmt::skip]
- }", trim_multiline(" if x {
++ fn test_reindent_multiline_empty_line() {
+ assert_eq!("\
+ if x {
+ y
+
+ } else {
+ z
++ }", reindent_multiline(" if x {
+ y
+
+ } else {
+ z
+ }".into(), false, None));
+ }
+
++ #[test]
++ #[rustfmt::skip]
++ fn test_reindent_multiline_lines_deeper() {
++ assert_eq!("\
++ if x {
++ y
++ } else {
++ z
++ }", reindent_multiline("\
++ if x {
++ y
++ } else {
++ z
++ }".into(), true, Some(8)));
++ }
++
+ #[test]
+ fn test_without_block_comments_lines_without_block_comments() {
+ let result = without_block_comments(vec!["/*", "", "*/"]);
+ println!("result: {:?}", result);
+ assert!(result.is_empty());
+
+ let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
+ assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
+
+ let result = without_block_comments(vec!["/* rust", "", "*/"]);
+ assert!(result.is_empty());
+
+ let result = without_block_comments(vec!["/* one-line comment */"]);
+ assert!(result.is_empty());
+
+ let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
+ assert!(result.is_empty());
+
+ let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);
+ assert!(result.is_empty());
+
+ let result = without_block_comments(vec!["foo", "bar", "baz"]);
+ assert_eq!(result, vec!["foo", "bar", "baz"]);
+ }
+}
--- /dev/null
+//! This module contains paths to types and functions Clippy needs to know
+//! about.
+//!
+//! Whenever possible, please consider diagnostic items over hardcoded paths.
+//! See <https://github.com/rust-lang/rust-clippy/issues/5393> for more information.
+
+pub const ANY_TRAIT: [&str; 3] = ["std", "any", "Any"];
+pub const ARC_PTR_EQ: [&str; 4] = ["alloc", "sync", "Arc", "ptr_eq"];
+pub const ASMUT_TRAIT: [&str; 3] = ["core", "convert", "AsMut"];
+pub const ASREF_TRAIT: [&str; 3] = ["core", "convert", "AsRef"];
+pub const BEGIN_PANIC: [&str; 3] = ["std", "panicking", "begin_panic"];
+pub const BEGIN_PANIC_FMT: [&str; 3] = ["std", "panicking", "begin_panic_fmt"];
+pub const BINARY_HEAP: [&str; 4] = ["alloc", "collections", "binary_heap", "BinaryHeap"];
+pub const BORROW_TRAIT: [&str; 3] = ["core", "borrow", "Borrow"];
+pub const BOX: [&str; 3] = ["alloc", "boxed", "Box"];
+pub const BTREEMAP: [&str; 5] = ["alloc", "collections", "btree", "map", "BTreeMap"];
+pub const BTREEMAP_ENTRY: [&str; 5] = ["alloc", "collections", "btree", "map", "Entry"];
+pub const BTREESET: [&str; 5] = ["alloc", "collections", "btree", "set", "BTreeSet"];
+pub const CLONE_TRAIT: [&str; 3] = ["core", "clone", "Clone"];
+pub const CLONE_TRAIT_METHOD: [&str; 4] = ["core", "clone", "Clone", "clone"];
+pub const CMP_MAX: [&str; 3] = ["core", "cmp", "max"];
+pub const CMP_MIN: [&str; 3] = ["core", "cmp", "min"];
+pub const COW: [&str; 3] = ["alloc", "borrow", "Cow"];
+pub const CSTRING: [&str; 4] = ["std", "ffi", "c_str", "CString"];
+pub const CSTRING_AS_C_STR: [&str; 5] = ["std", "ffi", "c_str", "CString", "as_c_str"];
+pub const DEFAULT_TRAIT: [&str; 3] = ["core", "default", "Default"];
+pub const DEFAULT_TRAIT_METHOD: [&str; 4] = ["core", "default", "Default", "default"];
+pub const DEREF_MUT_TRAIT_METHOD: [&str; 5] = ["core", "ops", "deref", "DerefMut", "deref_mut"];
+pub const DEREF_TRAIT_METHOD: [&str; 5] = ["core", "ops", "deref", "Deref", "deref"];
+pub const DISPLAY_FMT_METHOD: [&str; 4] = ["core", "fmt", "Display", "fmt"];
+pub const DISPLAY_TRAIT: [&str; 3] = ["core", "fmt", "Display"];
+pub const DOUBLE_ENDED_ITERATOR: [&str; 4] = ["core", "iter", "traits", "DoubleEndedIterator"];
+pub const DROP: [&str; 3] = ["core", "mem", "drop"];
+pub const DROP_TRAIT: [&str; 4] = ["core", "ops", "drop", "Drop"];
+pub const DURATION: [&str; 3] = ["core", "time", "Duration"];
+pub const EARLY_CONTEXT: [&str; 4] = ["rustc", "lint", "context", "EarlyContext"];
+pub const EXIT: [&str; 3] = ["std", "process", "exit"];
+pub const F32_EPSILON: [&str; 2] = ["f32", "EPSILON"];
+pub const F64_EPSILON: [&str; 2] = ["f64", "EPSILON"];
+pub const FILE: [&str; 3] = ["std", "fs", "File"];
+pub const FILE_TYPE: [&str; 3] = ["std", "fs", "FileType"];
+pub const FMT_ARGUMENTS_NEW_V1: [&str; 4] = ["core", "fmt", "Arguments", "new_v1"];
+pub const FMT_ARGUMENTS_NEW_V1_FORMATTED: [&str; 4] = ["core", "fmt", "Arguments", "new_v1_formatted"];
+pub const FMT_ARGUMENTV1_NEW: [&str; 4] = ["core", "fmt", "ArgumentV1", "new"];
+pub const FROM_FROM: [&str; 4] = ["core", "convert", "From", "from"];
+pub const FROM_TRAIT: [&str; 3] = ["core", "convert", "From"];
+pub const FUTURE_FROM_GENERATOR: [&str; 3] = ["core", "future", "from_generator"];
+pub const HASH: [&str; 2] = ["hash", "Hash"];
+pub const HASHMAP: [&str; 5] = ["std", "collections", "hash", "map", "HashMap"];
+pub const HASHMAP_ENTRY: [&str; 5] = ["std", "collections", "hash", "map", "Entry"];
+pub const HASHSET: [&str; 5] = ["std", "collections", "hash", "set", "HashSet"];
+pub const INDEX: [&str; 3] = ["core", "ops", "Index"];
+pub const INDEX_MUT: [&str; 3] = ["core", "ops", "IndexMut"];
+pub const INTO: [&str; 3] = ["core", "convert", "Into"];
+pub const INTO_ITERATOR: [&str; 5] = ["core", "iter", "traits", "collect", "IntoIterator"];
+pub const IO_READ: [&str; 3] = ["std", "io", "Read"];
+pub const IO_WRITE: [&str; 3] = ["std", "io", "Write"];
+pub const ITERATOR: [&str; 5] = ["core", "iter", "traits", "iterator", "Iterator"];
+pub const LATE_CONTEXT: [&str; 4] = ["rustc", "lint", "context", "LateContext"];
+pub const LINKED_LIST: [&str; 4] = ["alloc", "collections", "linked_list", "LinkedList"];
+pub const LINT: [&str; 3] = ["rustc_session", "lint", "Lint"];
+pub const MEM_DISCRIMINANT: [&str; 3] = ["core", "mem", "discriminant"];
+pub const MEM_FORGET: [&str; 3] = ["core", "mem", "forget"];
+pub const MEM_MANUALLY_DROP: [&str; 4] = ["core", "mem", "manually_drop", "ManuallyDrop"];
+pub const MEM_MAYBEUNINIT: [&str; 4] = ["core", "mem", "maybe_uninit", "MaybeUninit"];
+pub const MEM_MAYBEUNINIT_UNINIT: [&str; 5] = ["core", "mem", "maybe_uninit", "MaybeUninit", "uninit"];
+pub const MEM_REPLACE: [&str; 3] = ["core", "mem", "replace"];
+pub const MUTEX_GUARD: [&str; 4] = ["std", "sync", "mutex", "MutexGuard"];
+pub const OPEN_OPTIONS: [&str; 3] = ["std", "fs", "OpenOptions"];
+pub const OPS_MODULE: [&str; 2] = ["core", "ops"];
+pub const OPTION: [&str; 3] = ["core", "option", "Option"];
+pub const OPTION_NONE: [&str; 4] = ["core", "option", "Option", "None"];
+pub const OPTION_SOME: [&str; 4] = ["core", "option", "Option", "Some"];
+pub const ORD: [&str; 3] = ["core", "cmp", "Ord"];
+pub const OS_STRING: [&str; 4] = ["std", "ffi", "os_str", "OsString"];
+pub const OS_STRING_AS_OS_STR: [&str; 5] = ["std", "ffi", "os_str", "OsString", "as_os_str"];
+pub const OS_STR_TO_OS_STRING: [&str; 5] = ["std", "ffi", "os_str", "OsStr", "to_os_string"];
+pub const PARKING_LOT_MUTEX_GUARD: [&str; 2] = ["parking_lot", "MutexGuard"];
+pub const PARKING_LOT_RWLOCK_READ_GUARD: [&str; 2] = ["parking_lot", "RwLockReadGuard"];
+pub const PARKING_LOT_RWLOCK_WRITE_GUARD: [&str; 2] = ["parking_lot", "RwLockWriteGuard"];
+pub const PATH: [&str; 3] = ["std", "path", "Path"];
+pub const PATH_BUF: [&str; 3] = ["std", "path", "PathBuf"];
+pub const PATH_BUF_AS_PATH: [&str; 4] = ["std", "path", "PathBuf", "as_path"];
+pub const PATH_TO_PATH_BUF: [&str; 4] = ["std", "path", "Path", "to_path_buf"];
+pub const POLL: [&str; 4] = ["core", "task", "poll", "Poll"];
+pub const PTR_EQ: [&str; 3] = ["core", "ptr", "eq"];
+pub const PTR_NULL: [&str; 2] = ["ptr", "null"];
+pub const PTR_NULL_MUT: [&str; 2] = ["ptr", "null_mut"];
+pub const PUSH_STR: [&str; 4] = ["alloc", "string", "String", "push_str"];
+pub const RANGE_ARGUMENT_TRAIT: [&str; 3] = ["core", "ops", "RangeBounds"];
+pub const RC: [&str; 3] = ["alloc", "rc", "Rc"];
+pub const RC_PTR_EQ: [&str; 4] = ["alloc", "rc", "Rc", "ptr_eq"];
+pub const RECEIVER: [&str; 4] = ["std", "sync", "mpsc", "Receiver"];
+pub const REGEX_BUILDER_NEW: [&str; 5] = ["regex", "re_builder", "unicode", "RegexBuilder", "new"];
+pub const REGEX_BYTES_BUILDER_NEW: [&str; 5] = ["regex", "re_builder", "bytes", "RegexBuilder", "new"];
+pub const REGEX_BYTES_NEW: [&str; 4] = ["regex", "re_bytes", "Regex", "new"];
+pub const REGEX_BYTES_SET_NEW: [&str; 5] = ["regex", "re_set", "bytes", "RegexSet", "new"];
+pub const REGEX_NEW: [&str; 4] = ["regex", "re_unicode", "Regex", "new"];
+pub const REGEX_SET_NEW: [&str; 5] = ["regex", "re_set", "unicode", "RegexSet", "new"];
+pub const REPEAT: [&str; 3] = ["core", "iter", "repeat"];
+pub const RESULT: [&str; 3] = ["core", "result", "Result"];
+pub const RESULT_ERR: [&str; 4] = ["core", "result", "Result", "Err"];
+pub const RESULT_OK: [&str; 4] = ["core", "result", "Result", "Ok"];
+pub const RWLOCK_READ_GUARD: [&str; 4] = ["std", "sync", "rwlock", "RwLockReadGuard"];
+pub const RWLOCK_WRITE_GUARD: [&str; 4] = ["std", "sync", "rwlock", "RwLockWriteGuard"];
+pub const SERDE_DESERIALIZE: [&str; 2] = ["_serde", "Deserialize"];
+pub const SERDE_DE_VISITOR: [&str; 3] = ["serde", "de", "Visitor"];
+pub const SLICE_INTO_VEC: [&str; 4] = ["alloc", "slice", "<impl [T]>", "into_vec"];
+pub const SLICE_ITER: [&str; 3] = ["core", "slice", "Iter"];
+pub const STDERR: [&str; 4] = ["std", "io", "stdio", "stderr"];
+pub const STDOUT: [&str; 4] = ["std", "io", "stdio", "stdout"];
+pub const STD_CONVERT_IDENTITY: [&str; 3] = ["std", "convert", "identity"];
++pub const STD_FS_CREATE_DIR: [&str; 3] = ["std", "fs", "create_dir"];
+pub const STD_MEM_TRANSMUTE: [&str; 3] = ["std", "mem", "transmute"];
+pub const STD_PTR_NULL: [&str; 3] = ["std", "ptr", "null"];
+pub const STRING_AS_MUT_STR: [&str; 4] = ["alloc", "string", "String", "as_mut_str"];
+pub const STRING_AS_STR: [&str; 4] = ["alloc", "string", "String", "as_str"];
+pub const SYNTAX_CONTEXT: [&str; 3] = ["rustc_span", "hygiene", "SyntaxContext"];
+pub const TO_OWNED: [&str; 3] = ["alloc", "borrow", "ToOwned"];
+pub const TO_OWNED_METHOD: [&str; 4] = ["alloc", "borrow", "ToOwned", "to_owned"];
+pub const TO_STRING: [&str; 3] = ["alloc", "string", "ToString"];
+pub const TO_STRING_METHOD: [&str; 4] = ["alloc", "string", "ToString", "to_string"];
+pub const TRANSMUTE: [&str; 4] = ["core", "intrinsics", "", "transmute"];
+pub const TRY_FROM: [&str; 4] = ["core", "convert", "TryFrom", "try_from"];
+pub const TRY_INTO_TRAIT: [&str; 3] = ["core", "convert", "TryInto"];
+pub const VEC: [&str; 3] = ["alloc", "vec", "Vec"];
+pub const VEC_AS_MUT_SLICE: [&str; 4] = ["alloc", "vec", "Vec", "as_mut_slice"];
+pub const VEC_AS_SLICE: [&str; 4] = ["alloc", "vec", "Vec", "as_slice"];
+pub const VEC_DEQUE: [&str; 4] = ["alloc", "collections", "vec_deque", "VecDeque"];
+pub const VEC_FROM_ELEM: [&str; 3] = ["alloc", "vec", "from_elem"];
+pub const VEC_NEW: [&str; 4] = ["alloc", "vec", "Vec", "new"];
+pub const VEC_RESIZE: [&str; 4] = ["alloc", "vec", "Vec", "resize"];
+pub const WEAK_ARC: [&str; 3] = ["alloc", "sync", "Weak"];
+pub const WEAK_RC: [&str; 3] = ["alloc", "rc", "Weak"];
--- /dev/null
- let snippet = snippet(cx, expr.span, default);
+//! Contains utility functions to generate suggestions.
+#![deny(clippy::missing_docs_in_private_items)]
+
+use crate::utils::{higher, snippet, snippet_opt, snippet_with_macro_callsite};
+use rustc_ast::util::parser::AssocOp;
+use rustc_ast::{ast, token};
+use rustc_ast_pretty::pprust::token_kind_to_string;
+use rustc_errors::Applicability;
+use rustc_hir as hir;
+use rustc_lint::{EarlyContext, LateContext, LintContext};
+use rustc_span::source_map::{CharPos, Span};
+use rustc_span::{BytePos, Pos};
+use std::borrow::Cow;
+use std::convert::TryInto;
+use std::fmt::Display;
+
+/// A helper type to build suggestion correctly handling parenthesis.
+pub enum Sugg<'a> {
+ /// An expression that never needs parenthesis such as `1337` or `[0; 42]`.
+ NonParen(Cow<'a, str>),
+ /// An expression that does not fit in other variants.
+ MaybeParen(Cow<'a, str>),
+ /// A binary operator expression, including `as`-casts and explicit type
+ /// coercion.
+ BinOp(AssocOp, Cow<'a, str>),
+}
+
+/// Literal constant `1`, for convenience.
+pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
+
+impl Display for Sugg<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
+ match *self {
+ Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) | Sugg::BinOp(_, ref s) => s.fmt(f),
+ }
+ }
+}
+
+#[allow(clippy::wrong_self_convention)] // ok, because of the function `as_ty` method
+impl<'a> Sugg<'a> {
+ /// Prepare a suggestion from an expression.
+ pub fn hir_opt(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Self> {
+ snippet_opt(cx, expr.span).map(|snippet| {
+ let snippet = Cow::Owned(snippet);
+ Self::hir_from_snippet(expr, snippet)
+ })
+ }
+
+ /// Convenience function around `hir_opt` for suggestions with a default
+ /// text.
+ pub fn hir(cx: &LateContext<'_>, expr: &hir::Expr<'_>, default: &'a str) -> Self {
+ Self::hir_opt(cx, expr).unwrap_or_else(|| Sugg::NonParen(Cow::Borrowed(default)))
+ }
+
+ /// Same as `hir`, but it adapts the applicability level by following rules:
+ ///
+ /// - Applicability level `Unspecified` will never be changed.
+ /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
+ /// - If the default value is used and the applicability level is `MachineApplicable`, change it
+ /// to
+ /// `HasPlaceholders`
+ pub fn hir_with_applicability(
+ cx: &LateContext<'_>,
+ expr: &hir::Expr<'_>,
+ default: &'a str,
+ applicability: &mut Applicability,
+ ) -> Self {
+ if *applicability != Applicability::Unspecified && expr.span.from_expansion() {
+ *applicability = Applicability::MaybeIncorrect;
+ }
+ Self::hir_opt(cx, expr).unwrap_or_else(|| {
+ if *applicability == Applicability::MachineApplicable {
+ *applicability = Applicability::HasPlaceholders;
+ }
+ Sugg::NonParen(Cow::Borrowed(default))
+ })
+ }
+
+ /// Same as `hir`, but will use the pre expansion span if the `expr` was in a macro.
+ pub fn hir_with_macro_callsite(cx: &LateContext<'_>, expr: &hir::Expr<'_>, default: &'a str) -> Self {
+ let snippet = snippet_with_macro_callsite(cx, expr.span, default);
+
+ Self::hir_from_snippet(expr, snippet)
+ }
+
+ /// Generate a suggestion for an expression with the given snippet. This is used by the `hir_*`
+ /// function variants of `Sugg`, since these use different snippet functions.
+ fn hir_from_snippet(expr: &hir::Expr<'_>, snippet: Cow<'a, str>) -> Self {
+ if let Some(range) = higher::range(expr) {
+ let op = match range.limits {
+ ast::RangeLimits::HalfOpen => AssocOp::DotDot,
+ ast::RangeLimits::Closed => AssocOp::DotDotEq,
+ };
+ return Sugg::BinOp(op, snippet);
+ }
+
+ match expr.kind {
+ hir::ExprKind::AddrOf(..)
+ | hir::ExprKind::Box(..)
+ | hir::ExprKind::Closure(..)
+ | hir::ExprKind::Unary(..)
+ | hir::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
+ hir::ExprKind::Continue(..)
+ | hir::ExprKind::Yield(..)
+ | hir::ExprKind::Array(..)
+ | hir::ExprKind::Block(..)
+ | hir::ExprKind::Break(..)
+ | hir::ExprKind::Call(..)
+ | hir::ExprKind::Field(..)
+ | hir::ExprKind::Index(..)
+ | hir::ExprKind::InlineAsm(..)
+ | hir::ExprKind::LlvmInlineAsm(..)
+ | hir::ExprKind::Lit(..)
+ | hir::ExprKind::Loop(..)
+ | hir::ExprKind::MethodCall(..)
+ | hir::ExprKind::Path(..)
+ | hir::ExprKind::Repeat(..)
+ | hir::ExprKind::Ret(..)
+ | hir::ExprKind::Struct(..)
+ | hir::ExprKind::Tup(..)
+ | hir::ExprKind::DropTemps(_)
+ | hir::ExprKind::Err => Sugg::NonParen(snippet),
+ hir::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
+ hir::ExprKind::AssignOp(op, ..) => Sugg::BinOp(hirbinop2assignop(op), snippet),
+ hir::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(higher::binop(op.node)), snippet),
+ hir::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
+ hir::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
+ }
+ }
+
+ /// Prepare a suggestion from an expression.
+ pub fn ast(cx: &EarlyContext<'_>, expr: &ast::Expr, default: &'a str) -> Self {
+ use rustc_ast::ast::RangeLimits;
+
++ let snippet = if expr.span.from_expansion() {
++ snippet_with_macro_callsite(cx, expr.span, default)
++ } else {
++ snippet(cx, expr.span, default)
++ };
+
+ match expr.kind {
+ ast::ExprKind::AddrOf(..)
+ | ast::ExprKind::Box(..)
+ | ast::ExprKind::Closure(..)
+ | ast::ExprKind::If(..)
+ | ast::ExprKind::Let(..)
+ | ast::ExprKind::Unary(..)
+ | ast::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
+ ast::ExprKind::Async(..)
+ | ast::ExprKind::Block(..)
+ | ast::ExprKind::Break(..)
+ | ast::ExprKind::Call(..)
+ | ast::ExprKind::Continue(..)
+ | ast::ExprKind::Yield(..)
+ | ast::ExprKind::Field(..)
+ | ast::ExprKind::ForLoop(..)
+ | ast::ExprKind::Index(..)
+ | ast::ExprKind::InlineAsm(..)
+ | ast::ExprKind::LlvmInlineAsm(..)
+ | ast::ExprKind::Lit(..)
+ | ast::ExprKind::Loop(..)
+ | ast::ExprKind::MacCall(..)
+ | ast::ExprKind::MethodCall(..)
+ | ast::ExprKind::Paren(..)
+ | ast::ExprKind::Path(..)
+ | ast::ExprKind::Repeat(..)
+ | ast::ExprKind::Ret(..)
+ | ast::ExprKind::Struct(..)
+ | ast::ExprKind::Try(..)
+ | ast::ExprKind::TryBlock(..)
+ | ast::ExprKind::Tup(..)
+ | ast::ExprKind::Array(..)
+ | ast::ExprKind::While(..)
+ | ast::ExprKind::Await(..)
+ | ast::ExprKind::Err => Sugg::NonParen(snippet),
+ ast::ExprKind::Range(.., RangeLimits::HalfOpen) => Sugg::BinOp(AssocOp::DotDot, snippet),
+ ast::ExprKind::Range(.., RangeLimits::Closed) => Sugg::BinOp(AssocOp::DotDotEq, snippet),
+ ast::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
+ ast::ExprKind::AssignOp(op, ..) => Sugg::BinOp(astbinop2assignop(op), snippet),
+ ast::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(op.node), snippet),
+ ast::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
+ ast::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
+ }
+ }
+
+ /// Convenience method to create the `<lhs> && <rhs>` suggestion.
+ pub fn and(self, rhs: &Self) -> Sugg<'static> {
+ make_binop(ast::BinOpKind::And, &self, rhs)
+ }
+
+ /// Convenience method to create the `<lhs> & <rhs>` suggestion.
+ pub fn bit_and(self, rhs: &Self) -> Sugg<'static> {
+ make_binop(ast::BinOpKind::BitAnd, &self, rhs)
+ }
+
+ /// Convenience method to create the `<lhs> as <rhs>` suggestion.
+ pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
+ make_assoc(AssocOp::As, &self, &Sugg::NonParen(rhs.to_string().into()))
+ }
+
+ /// Convenience method to create the `&<expr>` suggestion.
+ pub fn addr(self) -> Sugg<'static> {
+ make_unop("&", self)
+ }
+
+ /// Convenience method to create the `&mut <expr>` suggestion.
+ pub fn mut_addr(self) -> Sugg<'static> {
+ make_unop("&mut ", self)
+ }
+
+ /// Convenience method to create the `*<expr>` suggestion.
+ pub fn deref(self) -> Sugg<'static> {
+ make_unop("*", self)
+ }
+
+ /// Convenience method to create the `&*<expr>` suggestion. Currently this
+ /// is needed because `sugg.deref().addr()` produces an unnecessary set of
+ /// parentheses around the deref.
+ pub fn addr_deref(self) -> Sugg<'static> {
+ make_unop("&*", self)
+ }
+
+ /// Convenience method to create the `&mut *<expr>` suggestion. Currently
+ /// this is needed because `sugg.deref().mut_addr()` produces an unnecessary
+ /// set of parentheses around the deref.
+ pub fn mut_addr_deref(self) -> Sugg<'static> {
+ make_unop("&mut *", self)
+ }
+
+ /// Convenience method to transform suggestion into a return call
+ pub fn make_return(self) -> Sugg<'static> {
+ Sugg::NonParen(Cow::Owned(format!("return {}", self)))
+ }
+
+ /// Convenience method to transform suggestion into a block
+ /// where the suggestion is a trailing expression
+ pub fn blockify(self) -> Sugg<'static> {
+ Sugg::NonParen(Cow::Owned(format!("{{ {} }}", self)))
+ }
+
+ /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>`
+ /// suggestion.
+ #[allow(dead_code)]
+ pub fn range(self, end: &Self, limit: ast::RangeLimits) -> Sugg<'static> {
+ match limit {
+ ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, end),
+ ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotEq, &self, end),
+ }
+ }
+
+ /// Adds parenthesis to any expression that might need them. Suitable to the
+ /// `self` argument of a method call
+ /// (e.g., to build `bar.foo()` or `(1 + 2).foo()`).
+ pub fn maybe_par(self) -> Self {
+ match self {
+ Sugg::NonParen(..) => self,
+ // `(x)` and `(x).y()` both don't need additional parens.
+ Sugg::MaybeParen(sugg) => {
+ if sugg.starts_with('(') && sugg.ends_with(')') {
+ Sugg::MaybeParen(sugg)
+ } else {
+ Sugg::NonParen(format!("({})", sugg).into())
+ }
+ },
+ Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
+ }
+ }
+}
+
+impl<'a, 'b> std::ops::Add<Sugg<'b>> for Sugg<'a> {
+ type Output = Sugg<'static>;
+ fn add(self, rhs: Sugg<'b>) -> Sugg<'static> {
+ make_binop(ast::BinOpKind::Add, &self, &rhs)
+ }
+}
+
+impl<'a, 'b> std::ops::Sub<Sugg<'b>> for Sugg<'a> {
+ type Output = Sugg<'static>;
+ fn sub(self, rhs: Sugg<'b>) -> Sugg<'static> {
+ make_binop(ast::BinOpKind::Sub, &self, &rhs)
+ }
+}
+
+impl<'a> std::ops::Not for Sugg<'a> {
+ type Output = Sugg<'static>;
+ fn not(self) -> Sugg<'static> {
+ make_unop("!", self)
+ }
+}
+
+/// Helper type to display either `foo` or `(foo)`.
+struct ParenHelper<T> {
+ /// `true` if parentheses are needed.
+ paren: bool,
+ /// The main thing to display.
+ wrapped: T,
+}
+
+impl<T> ParenHelper<T> {
+ /// Builds a `ParenHelper`.
+ fn new(paren: bool, wrapped: T) -> Self {
+ Self { paren, wrapped }
+ }
+}
+
+impl<T: Display> Display for ParenHelper<T> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
+ if self.paren {
+ write!(f, "({})", self.wrapped)
+ } else {
+ self.wrapped.fmt(f)
+ }
+ }
+}
+
+/// Builds the string for `<op><expr>` adding parenthesis when necessary.
+///
+/// For convenience, the operator is taken as a string because all unary
+/// operators have the same
+/// precedence.
+pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
+ Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
+}
+
+/// Builds the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
+///
+/// Precedence of shift operator relative to other arithmetic operation is
+/// often confusing so
+/// parenthesis will always be added for a mix of these.
+pub fn make_assoc(op: AssocOp, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
+ /// Returns `true` if the operator is a shift operator `<<` or `>>`.
+ fn is_shift(op: AssocOp) -> bool {
+ matches!(op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
+ }
+
+ /// Returns `true` if the operator is a arithmetic operator
+ /// (i.e., `+`, `-`, `*`, `/`, `%`).
+ fn is_arith(op: AssocOp) -> bool {
+ matches!(
+ op,
+ AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus
+ )
+ }
+
+ /// Returns `true` if the operator `op` needs parenthesis with the operator
+ /// `other` in the direction `dir`.
+ fn needs_paren(op: AssocOp, other: AssocOp, dir: Associativity) -> bool {
+ other.precedence() < op.precedence()
+ || (other.precedence() == op.precedence()
+ && ((op != other && associativity(op) != dir)
+ || (op == other && associativity(op) != Associativity::Both)))
+ || is_shift(op) && is_arith(other)
+ || is_shift(other) && is_arith(op)
+ }
+
+ let lhs_paren = if let Sugg::BinOp(lop, _) = *lhs {
+ needs_paren(op, lop, Associativity::Left)
+ } else {
+ false
+ };
+
+ let rhs_paren = if let Sugg::BinOp(rop, _) = *rhs {
+ needs_paren(op, rop, Associativity::Right)
+ } else {
+ false
+ };
+
+ let lhs = ParenHelper::new(lhs_paren, lhs);
+ let rhs = ParenHelper::new(rhs_paren, rhs);
+ let sugg = match op {
+ AssocOp::Add
+ | AssocOp::BitAnd
+ | AssocOp::BitOr
+ | AssocOp::BitXor
+ | AssocOp::Divide
+ | AssocOp::Equal
+ | AssocOp::Greater
+ | AssocOp::GreaterEqual
+ | AssocOp::LAnd
+ | AssocOp::LOr
+ | AssocOp::Less
+ | AssocOp::LessEqual
+ | AssocOp::Modulus
+ | AssocOp::Multiply
+ | AssocOp::NotEqual
+ | AssocOp::ShiftLeft
+ | AssocOp::ShiftRight
+ | AssocOp::Subtract => format!(
+ "{} {} {}",
+ lhs,
+ op.to_ast_binop().expect("Those are AST ops").to_string(),
+ rhs
+ ),
+ AssocOp::Assign => format!("{} = {}", lhs, rhs),
+ AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, token_kind_to_string(&token::BinOp(op)), rhs),
+ AssocOp::As => format!("{} as {}", lhs, rhs),
+ AssocOp::DotDot => format!("{}..{}", lhs, rhs),
+ AssocOp::DotDotEq => format!("{}..={}", lhs, rhs),
+ AssocOp::Colon => format!("{}: {}", lhs, rhs),
+ };
+
+ Sugg::BinOp(op, sugg.into())
+}
+
+/// Convenience wrapper around `make_assoc` and `AssocOp::from_ast_binop`.
+pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
+ make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
+}
+
+#[derive(PartialEq, Eq, Clone, Copy)]
+/// Operator associativity.
+enum Associativity {
+ /// The operator is both left-associative and right-associative.
+ Both,
+ /// The operator is left-associative.
+ Left,
+ /// The operator is not associative.
+ None,
+ /// The operator is right-associative.
+ Right,
+}
+
+/// Returns the associativity/fixity of an operator. The difference with
+/// `AssocOp::fixity` is that an operator can be both left and right associative
+/// (such as `+`: `a + b + c == (a + b) + c == a + (b + c)`.
+///
+/// Chained `as` and explicit `:` type coercion never need inner parenthesis so
+/// they are considered
+/// associative.
+#[must_use]
+fn associativity(op: AssocOp) -> Associativity {
+ use rustc_ast::util::parser::AssocOp::{
+ Add, As, Assign, AssignOp, BitAnd, BitOr, BitXor, Colon, Divide, DotDot, DotDotEq, Equal, Greater,
+ GreaterEqual, LAnd, LOr, Less, LessEqual, Modulus, Multiply, NotEqual, ShiftLeft, ShiftRight, Subtract,
+ };
+
+ match op {
+ Assign | AssignOp(_) => Associativity::Right,
+ Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both,
+ Divide | Equal | Greater | GreaterEqual | Less | LessEqual | Modulus | NotEqual | ShiftLeft | ShiftRight
+ | Subtract => Associativity::Left,
+ DotDot | DotDotEq => Associativity::None,
+ }
+}
+
+/// Converts a `hir::BinOp` to the corresponding assigning binary operator.
+fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
+ use rustc_ast::token::BinOpToken::{And, Caret, Minus, Or, Percent, Plus, Shl, Shr, Slash, Star};
+
+ AssocOp::AssignOp(match op.node {
+ hir::BinOpKind::Add => Plus,
+ hir::BinOpKind::BitAnd => And,
+ hir::BinOpKind::BitOr => Or,
+ hir::BinOpKind::BitXor => Caret,
+ hir::BinOpKind::Div => Slash,
+ hir::BinOpKind::Mul => Star,
+ hir::BinOpKind::Rem => Percent,
+ hir::BinOpKind::Shl => Shl,
+ hir::BinOpKind::Shr => Shr,
+ hir::BinOpKind::Sub => Minus,
+
+ hir::BinOpKind::And
+ | hir::BinOpKind::Eq
+ | hir::BinOpKind::Ge
+ | hir::BinOpKind::Gt
+ | hir::BinOpKind::Le
+ | hir::BinOpKind::Lt
+ | hir::BinOpKind::Ne
+ | hir::BinOpKind::Or => panic!("This operator does not exist"),
+ })
+}
+
+/// Converts an `ast::BinOp` to the corresponding assigning binary operator.
+fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
+ use rustc_ast::ast::BinOpKind::{
+ Add, And, BitAnd, BitOr, BitXor, Div, Eq, Ge, Gt, Le, Lt, Mul, Ne, Or, Rem, Shl, Shr, Sub,
+ };
+ use rustc_ast::token::BinOpToken;
+
+ AssocOp::AssignOp(match op.node {
+ Add => BinOpToken::Plus,
+ BitAnd => BinOpToken::And,
+ BitOr => BinOpToken::Or,
+ BitXor => BinOpToken::Caret,
+ Div => BinOpToken::Slash,
+ Mul => BinOpToken::Star,
+ Rem => BinOpToken::Percent,
+ Shl => BinOpToken::Shl,
+ Shr => BinOpToken::Shr,
+ Sub => BinOpToken::Minus,
+ And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
+ })
+}
+
+/// Returns the indentation before `span` if there are nothing but `[ \t]`
+/// before it on its line.
+fn indentation<T: LintContext>(cx: &T, span: Span) -> Option<String> {
+ let lo = cx.sess().source_map().lookup_char_pos(span.lo());
+ lo.file
+ .get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */)
+ .and_then(|line| {
+ if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
+ // We can mix char and byte positions here because we only consider `[ \t]`.
+ if lo.col == CharPos(pos) {
+ Some(line[..pos].into())
+ } else {
+ None
+ }
+ } else {
+ None
+ }
+ })
+}
+
+/// Convenience extension trait for `DiagnosticBuilder`.
+pub trait DiagnosticBuilderExt<T: LintContext> {
+ /// Suggests to add an attribute to an item.
+ ///
+ /// Correctly handles indentation of the attribute and item.
+ ///
+ /// # Example
+ ///
+ /// ```rust,ignore
+ /// diag.suggest_item_with_attr(cx, item, "#[derive(Default)]");
+ /// ```
+ fn suggest_item_with_attr<D: Display + ?Sized>(
+ &mut self,
+ cx: &T,
+ item: Span,
+ msg: &str,
+ attr: &D,
+ applicability: Applicability,
+ );
+
+ /// Suggest to add an item before another.
+ ///
+ /// The item should not be indented (except for inner indentation).
+ ///
+ /// # Example
+ ///
+ /// ```rust,ignore
+ /// diag.suggest_prepend_item(cx, item,
+ /// "fn foo() {
+ /// bar();
+ /// }");
+ /// ```
+ fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability);
+
+ /// Suggest to completely remove an item.
+ ///
+ /// This will remove an item and all following whitespace until the next non-whitespace
+ /// character. This should work correctly if item is on the same indentation level as the
+ /// following item.
+ ///
+ /// # Example
+ ///
+ /// ```rust,ignore
+ /// diag.suggest_remove_item(cx, item, "remove this")
+ /// ```
+ fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability);
+}
+
+impl<T: LintContext> DiagnosticBuilderExt<T> for rustc_errors::DiagnosticBuilder<'_> {
+ fn suggest_item_with_attr<D: Display + ?Sized>(
+ &mut self,
+ cx: &T,
+ item: Span,
+ msg: &str,
+ attr: &D,
+ applicability: Applicability,
+ ) {
+ if let Some(indent) = indentation(cx, item) {
+ let span = item.with_hi(item.lo());
+
+ self.span_suggestion(span, msg, format!("{}\n{}", attr, indent), applicability);
+ }
+ }
+
+ fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability) {
+ if let Some(indent) = indentation(cx, item) {
+ let span = item.with_hi(item.lo());
+
+ let mut first = true;
+ let new_item = new_item
+ .lines()
+ .map(|l| {
+ if first {
+ first = false;
+ format!("{}\n", l)
+ } else {
+ format!("{}{}\n", indent, l)
+ }
+ })
+ .collect::<String>();
+
+ self.span_suggestion(span, msg, format!("{}\n{}", new_item, indent), applicability);
+ }
+ }
+
+ fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability) {
+ let mut remove_span = item;
+ let hi = cx.sess().source_map().next_point(remove_span).hi();
+ let fmpos = cx.sess().source_map().lookup_byte_offset(hi);
+
+ if let Some(ref src) = fmpos.sf.src {
+ let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n');
+
+ if let Some(non_whitespace_offset) = non_whitespace_offset {
+ remove_span = remove_span
+ .with_hi(remove_span.hi() + BytePos(non_whitespace_offset.try_into().expect("offset too large")))
+ }
+ }
+
+ self.span_suggestion(remove_span, msg, String::new(), applicability);
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::Sugg;
+ use std::borrow::Cow;
+
+ const SUGGESTION: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("function_call()"));
+
+ #[test]
+ fn make_return_transform_sugg_into_a_return_call() {
+ assert_eq!("return function_call()", SUGGESTION.make_return().to_string());
+ }
+
+ #[test]
+ fn blockify_transforms_sugg_into_a_block() {
+ assert_eq!("{ function_call() }", SUGGESTION.blockify().to_string());
+ }
+}
--- /dev/null
+//! This file is managed by `cargo dev update_lints`. Do not edit.
+
+use lazy_static::lazy_static;
+
+pub mod lint;
+pub use lint::Level;
+pub use lint::Lint;
+pub use lint::LINT_LEVELS;
+
+lazy_static! {
+// begin lint list, do not remove this comment, it’s used in `update_lints`
+pub static ref ALL_LINTS: Vec<Lint> = vec![
+ Lint {
+ name: "absurd_extreme_comparisons",
+ group: "correctness",
+ desc: "a comparison with a maximum or minimum value that is always true or false",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "almost_swapped",
+ group: "correctness",
+ desc: "`foo = bar; bar = foo` sequence",
+ deprecation: None,
+ module: "swap",
+ },
+ Lint {
+ name: "approx_constant",
+ group: "correctness",
+ desc: "the approximate of a known float constant (in `std::fXX::consts`)",
+ deprecation: None,
+ module: "approx_const",
+ },
+ Lint {
+ name: "as_conversions",
+ group: "restriction",
+ desc: "using a potentially dangerous silent `as` conversion",
+ deprecation: None,
+ module: "as_conversions",
+ },
+ Lint {
+ name: "assertions_on_constants",
+ group: "style",
+ desc: "`assert!(true)` / `assert!(false)` will be optimized out by the compiler, and should probably be replaced by a `panic!()` or `unreachable!()`",
+ deprecation: None,
+ module: "assertions_on_constants",
+ },
+ Lint {
+ name: "assign_op_pattern",
+ group: "style",
+ desc: "assigning the result of an operation on a variable to that same variable",
+ deprecation: None,
+ module: "assign_ops",
+ },
++ Lint {
++ name: "async_yields_async",
++ group: "correctness",
++ desc: "async blocks that return a type that can be awaited",
++ deprecation: None,
++ module: "async_yields_async",
++ },
+ Lint {
+ name: "await_holding_lock",
+ group: "pedantic",
+ desc: "Inside an async function, holding a MutexGuard while calling await",
+ deprecation: None,
+ module: "await_holding_lock",
+ },
+ Lint {
+ name: "bad_bit_mask",
+ group: "correctness",
+ desc: "expressions of the form `_ & mask == select` that will only ever return `true` or `false`",
+ deprecation: None,
+ module: "bit_mask",
+ },
+ Lint {
+ name: "bind_instead_of_map",
+ group: "complexity",
+ desc: "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "blacklisted_name",
+ group: "style",
+ desc: "usage of a blacklisted/placeholder name",
+ deprecation: None,
+ module: "blacklisted_name",
+ },
+ Lint {
+ name: "blanket_clippy_restriction_lints",
+ group: "style",
+ desc: "enabling the complete restriction group",
+ deprecation: None,
+ module: "attrs",
+ },
+ Lint {
+ name: "blocks_in_if_conditions",
+ group: "style",
+ desc: "useless or complex blocks that can be eliminated in conditions",
+ deprecation: None,
+ module: "blocks_in_if_conditions",
+ },
+ Lint {
+ name: "bool_comparison",
+ group: "complexity",
+ desc: "comparing a variable to a boolean, e.g., `if x == true` or `if x != true`",
+ deprecation: None,
+ module: "needless_bool",
+ },
+ Lint {
+ name: "borrow_interior_mutable_const",
+ group: "correctness",
+ desc: "referencing `const` with interior mutability",
+ deprecation: None,
+ module: "non_copy_const",
+ },
+ Lint {
+ name: "borrowed_box",
+ group: "complexity",
+ desc: "a borrow of a boxed type",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "box_vec",
+ group: "perf",
+ desc: "usage of `Box<Vec<T>>`, vector elements are already on the heap",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "boxed_local",
+ group: "perf",
+ desc: "using `Box<T>` where unnecessary",
+ deprecation: None,
+ module: "escape",
+ },
+ Lint {
+ name: "builtin_type_shadow",
+ group: "style",
+ desc: "shadowing a builtin type",
+ deprecation: None,
+ module: "misc_early",
+ },
+ Lint {
+ name: "cargo_common_metadata",
+ group: "cargo",
+ desc: "common metadata is defined in `Cargo.toml`",
+ deprecation: None,
+ module: "cargo_common_metadata",
+ },
+ Lint {
+ name: "cast_lossless",
+ group: "pedantic",
+ desc: "casts using `as` that are known to be lossless, e.g., `x as u64` where `x: u8`",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "cast_possible_truncation",
+ group: "pedantic",
+ desc: "casts that may cause truncation of the value, e.g., `x as u8` where `x: u32`, or `x as i32` where `x: f32`",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "cast_possible_wrap",
+ group: "pedantic",
+ desc: "casts that may cause wrapping around the value, e.g., `x as i32` where `x: u32` and `x > i32::MAX`",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "cast_precision_loss",
+ group: "pedantic",
+ desc: "casts that cause loss of precision, e.g., `x as f32` where `x: u64`",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "cast_ptr_alignment",
+ group: "pedantic",
+ desc: "cast from a pointer to a more-strictly-aligned pointer",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "cast_ref_to_mut",
+ group: "correctness",
+ desc: "a cast of reference to a mutable pointer",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "cast_sign_loss",
+ group: "pedantic",
+ desc: "casts from signed types to unsigned types, e.g., `x as u32` where `x: i32`",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "char_lit_as_u8",
+ group: "complexity",
+ desc: "casting a character literal to `u8` truncates",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "chars_last_cmp",
+ group: "style",
+ desc: "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "chars_next_cmp",
+ group: "style",
+ desc: "using `.chars().next()` to check if a string starts with a char",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "checked_conversions",
+ group: "pedantic",
+ desc: "`try_from` could replace manual bounds checking when casting",
+ deprecation: None,
+ module: "checked_conversions",
+ },
+ Lint {
+ name: "clone_double_ref",
+ group: "correctness",
+ desc: "using `clone` on `&&T`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "clone_on_copy",
+ group: "complexity",
+ desc: "using `clone` on a `Copy` type",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "clone_on_ref_ptr",
+ group: "restriction",
+ desc: "using \'clone\' on a ref-counted pointer",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "cmp_nan",
+ group: "correctness",
+ desc: "comparisons to `NAN`, which will always return false, probably not intended",
+ deprecation: None,
+ module: "misc",
+ },
+ Lint {
+ name: "cmp_null",
+ group: "style",
+ desc: "comparing a pointer to a null pointer, suggesting to use `.is_null()` instead.",
+ deprecation: None,
+ module: "ptr",
+ },
+ Lint {
+ name: "cmp_owned",
+ group: "perf",
+ desc: "creating owned instances for comparing with others, e.g., `x == \"foo\".to_string()`",
+ deprecation: None,
+ module: "misc",
+ },
+ Lint {
+ name: "cognitive_complexity",
+ group: "nursery",
+ desc: "functions that should be split up into multiple functions",
+ deprecation: None,
+ module: "cognitive_complexity",
+ },
+ Lint {
+ name: "collapsible_if",
+ group: "style",
+ desc: "`if`s that can be collapsed (e.g., `if x { if y { ... } }` and `else { if x { ... } }`)",
+ deprecation: None,
+ module: "collapsible_if",
+ },
+ Lint {
+ name: "comparison_chain",
+ group: "style",
+ desc: "`if`s that can be rewritten with `match` and `cmp`",
+ deprecation: None,
+ module: "comparison_chain",
+ },
+ Lint {
+ name: "copy_iterator",
+ group: "pedantic",
+ desc: "implementing `Iterator` on a `Copy` type",
+ deprecation: None,
+ module: "copy_iterator",
+ },
++ Lint {
++ name: "create_dir",
++ group: "restriction",
++ desc: "calling `std::fs::create_dir` instead of `std::fs::create_dir_all`",
++ deprecation: None,
++ module: "create_dir",
++ },
+ Lint {
+ name: "crosspointer_transmute",
+ group: "complexity",
+ desc: "transmutes that have to or from types that are a pointer to the other",
+ deprecation: None,
+ module: "transmute",
+ },
+ Lint {
+ name: "dbg_macro",
+ group: "restriction",
+ desc: "`dbg!` macro is intended as a debugging tool",
+ deprecation: None,
+ module: "dbg_macro",
+ },
+ Lint {
+ name: "debug_assert_with_mut_call",
+ group: "nursery",
+ desc: "mutable arguments in `debug_assert{,_ne,_eq}!`",
+ deprecation: None,
+ module: "mutable_debug_assertion",
+ },
+ Lint {
+ name: "decimal_literal_representation",
+ group: "restriction",
+ desc: "using decimal representation when hexadecimal would be better",
+ deprecation: None,
+ module: "literal_representation",
+ },
+ Lint {
+ name: "declare_interior_mutable_const",
+ group: "correctness",
+ desc: "declaring `const` with interior mutability",
+ deprecation: None,
+ module: "non_copy_const",
+ },
+ Lint {
+ name: "default_trait_access",
+ group: "pedantic",
+ desc: "checks for literal calls to `Default::default()`",
+ deprecation: None,
+ module: "default_trait_access",
+ },
+ Lint {
+ name: "deprecated_cfg_attr",
+ group: "complexity",
+ desc: "usage of `cfg_attr(rustfmt)` instead of tool attributes",
+ deprecation: None,
+ module: "attrs",
+ },
+ Lint {
+ name: "deprecated_semver",
+ group: "correctness",
+ desc: "use of `#[deprecated(since = \"x\")]` where x is not semver",
+ deprecation: None,
+ module: "attrs",
+ },
+ Lint {
+ name: "deref_addrof",
+ group: "complexity",
+ desc: "use of `*&` or `*&mut` in an expression",
+ deprecation: None,
+ module: "reference",
+ },
+ Lint {
+ name: "derive_hash_xor_eq",
+ group: "correctness",
+ desc: "deriving `Hash` but implementing `PartialEq` explicitly",
+ deprecation: None,
+ module: "derive",
+ },
+ Lint {
+ name: "derive_ord_xor_partial_ord",
+ group: "correctness",
+ desc: "deriving `Ord` but implementing `PartialOrd` explicitly",
+ deprecation: None,
+ module: "derive",
+ },
+ Lint {
+ name: "diverging_sub_expression",
+ group: "complexity",
+ desc: "whether an expression contains a diverging sub expression",
+ deprecation: None,
+ module: "eval_order_dependence",
+ },
+ Lint {
+ name: "doc_markdown",
+ group: "pedantic",
+ desc: "presence of `_`, `::` or camel-case outside backticks in documentation",
+ deprecation: None,
+ module: "doc",
+ },
+ Lint {
+ name: "double_comparisons",
+ group: "complexity",
+ desc: "unnecessary double comparisons that can be simplified",
+ deprecation: None,
+ module: "double_comparison",
+ },
+ Lint {
+ name: "double_must_use",
+ group: "style",
+ desc: "`#[must_use]` attribute on a `#[must_use]`-returning function / method",
+ deprecation: None,
+ module: "functions",
+ },
+ Lint {
+ name: "double_neg",
+ group: "style",
+ desc: "`--x`, which is a double negation of `x` and not a pre-decrement as in C/C++",
+ deprecation: None,
+ module: "misc_early",
+ },
+ Lint {
+ name: "double_parens",
+ group: "complexity",
+ desc: "Warn on unnecessary double parentheses",
+ deprecation: None,
+ module: "double_parens",
+ },
+ Lint {
+ name: "drop_bounds",
+ group: "correctness",
+ desc: "bounds of the form `T: Drop` are useless",
+ deprecation: None,
+ module: "drop_bounds",
+ },
+ Lint {
+ name: "drop_copy",
+ group: "correctness",
+ desc: "calls to `std::mem::drop` with a value that implements Copy",
+ deprecation: None,
+ module: "drop_forget_ref",
+ },
+ Lint {
+ name: "drop_ref",
+ group: "correctness",
+ desc: "calls to `std::mem::drop` with a reference instead of an owned value",
+ deprecation: None,
+ module: "drop_forget_ref",
+ },
+ Lint {
+ name: "duplicate_underscore_argument",
+ group: "style",
+ desc: "function arguments having names which only differ by an underscore",
+ deprecation: None,
+ module: "misc_early",
+ },
+ Lint {
+ name: "duration_subsec",
+ group: "complexity",
+ desc: "checks for calculation of subsecond microseconds or milliseconds",
+ deprecation: None,
+ module: "duration_subsec",
+ },
+ Lint {
+ name: "else_if_without_else",
+ group: "restriction",
+ desc: "`if` expression with an `else if`, but without a final `else` branch",
+ deprecation: None,
+ module: "else_if_without_else",
+ },
+ Lint {
+ name: "empty_enum",
+ group: "pedantic",
+ desc: "enum with no variants",
+ deprecation: None,
+ module: "empty_enum",
+ },
+ Lint {
+ name: "empty_line_after_outer_attr",
+ group: "nursery",
+ desc: "empty line after outer attribute",
+ deprecation: None,
+ module: "attrs",
+ },
+ Lint {
+ name: "empty_loop",
+ group: "style",
+ desc: "empty `loop {}`, which should block or sleep",
+ deprecation: None,
+ module: "loops",
+ },
+ Lint {
+ name: "enum_clike_unportable_variant",
+ group: "correctness",
+ desc: "C-like enums that are `repr(isize/usize)` and have values that don\'t fit into an `i32`",
+ deprecation: None,
+ module: "enum_clike",
+ },
+ Lint {
+ name: "enum_glob_use",
+ group: "pedantic",
+ desc: "use items that import all variants of an enum",
+ deprecation: None,
+ module: "wildcard_imports",
+ },
+ Lint {
+ name: "enum_variant_names",
+ group: "style",
+ desc: "enums where all variants share a prefix/postfix",
+ deprecation: None,
+ module: "enum_variants",
+ },
+ Lint {
+ name: "eq_op",
+ group: "correctness",
+ desc: "equal operands on both sides of a comparison or bitwise combination (e.g., `x == x`)",
+ deprecation: None,
+ module: "eq_op",
+ },
+ Lint {
+ name: "erasing_op",
+ group: "correctness",
+ desc: "using erasing operations, e.g., `x * 0` or `y & 0`",
+ deprecation: None,
+ module: "erasing_op",
+ },
+ Lint {
+ name: "eval_order_dependence",
+ group: "complexity",
+ desc: "whether a variable read occurs before a write depends on sub-expression evaluation order",
+ deprecation: None,
+ module: "eval_order_dependence",
+ },
+ Lint {
+ name: "excessive_precision",
+ group: "style",
+ desc: "excessive precision for float literal",
+ deprecation: None,
+ module: "float_literal",
+ },
+ Lint {
+ name: "exit",
+ group: "restriction",
+ desc: "`std::process::exit` is called, terminating the program",
+ deprecation: None,
+ module: "exit",
+ },
+ Lint {
+ name: "expect_fun_call",
+ group: "perf",
+ desc: "using any `expect` method with a function call",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "expect_used",
+ group: "restriction",
+ desc: "using `.expect()` on `Result` or `Option`, which might be better handled",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "expl_impl_clone_on_copy",
+ group: "pedantic",
+ desc: "implementing `Clone` explicitly on `Copy` types",
+ deprecation: None,
+ module: "derive",
+ },
+ Lint {
+ name: "explicit_counter_loop",
+ group: "complexity",
+ desc: "for-looping with an explicit counter when `_.enumerate()` would do",
+ deprecation: None,
+ module: "loops",
+ },
+ Lint {
+ name: "explicit_deref_methods",
+ group: "pedantic",
+ desc: "Explicit use of deref or deref_mut method while not in a method chain.",
+ deprecation: None,
+ module: "dereference",
+ },
+ Lint {
+ name: "explicit_into_iter_loop",
+ group: "pedantic",
+ desc: "for-looping over `_.into_iter()` when `_` would do",
+ deprecation: None,
+ module: "loops",
+ },
+ Lint {
+ name: "explicit_iter_loop",
+ group: "pedantic",
+ desc: "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do",
+ deprecation: None,
+ module: "loops",
+ },
+ Lint {
+ name: "explicit_write",
+ group: "complexity",
+ desc: "using the `write!()` family of functions instead of the `print!()` family of functions, when using the latter would work",
+ deprecation: None,
+ module: "explicit_write",
+ },
+ Lint {
+ name: "extra_unused_lifetimes",
+ group: "complexity",
+ desc: "unused lifetimes in function definitions",
+ deprecation: None,
+ module: "lifetimes",
+ },
+ Lint {
+ name: "fallible_impl_from",
+ group: "nursery",
+ desc: "Warn on impls of `From<..>` that contain `panic!()` or `unwrap()`",
+ deprecation: None,
+ module: "fallible_impl_from",
+ },
+ Lint {
+ name: "filetype_is_file",
+ group: "restriction",
+ desc: "`FileType::is_file` is not recommended to test for readable file type",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "filter_map",
+ group: "pedantic",
+ desc: "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can usually be written as a single method call",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "filter_map_next",
+ group: "pedantic",
+ desc: "using combination of `filter_map` and `next` which can usually be written as a single method call",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "filter_next",
+ group: "complexity",
+ desc: "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "find_map",
+ group: "pedantic",
+ desc: "using a combination of `find` and `map` can usually be written as a single method call",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "flat_map_identity",
+ group: "complexity",
+ desc: "call to `flat_map` where `flatten` is sufficient",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "float_arithmetic",
+ group: "restriction",
+ desc: "any floating-point arithmetic statement",
+ deprecation: None,
+ module: "arithmetic",
+ },
+ Lint {
+ name: "float_cmp",
+ group: "correctness",
+ desc: "using `==` or `!=` on float values instead of comparing difference with an epsilon",
+ deprecation: None,
+ module: "misc",
+ },
+ Lint {
+ name: "float_cmp_const",
+ group: "restriction",
+ desc: "using `==` or `!=` on float constants instead of comparing difference with an epsilon",
+ deprecation: None,
+ module: "misc",
+ },
+ Lint {
+ name: "float_equality_without_abs",
+ group: "correctness",
+ desc: "float equality check without `.abs()`",
+ deprecation: None,
+ module: "float_equality_without_abs",
+ },
+ Lint {
+ name: "fn_address_comparisons",
+ group: "correctness",
+ desc: "comparison with an address of a function item",
+ deprecation: None,
+ module: "unnamed_address",
+ },
+ Lint {
+ name: "fn_params_excessive_bools",
+ group: "pedantic",
+ desc: "using too many bools in function parameters",
+ deprecation: None,
+ module: "excessive_bools",
+ },
+ Lint {
+ name: "fn_to_numeric_cast",
+ group: "style",
+ desc: "casting a function pointer to a numeric type other than usize",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "fn_to_numeric_cast_with_truncation",
+ group: "style",
+ desc: "casting a function pointer to a numeric type not wide enough to store the address",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "for_kv_map",
+ group: "style",
+ desc: "looping on a map using `iter` when `keys` or `values` would do",
+ deprecation: None,
+ module: "loops",
+ },
+ Lint {
+ name: "for_loops_over_fallibles",
+ group: "correctness",
+ desc: "for-looping over an `Option` or a `Result`, which is more clearly expressed as an `if let`",
+ deprecation: None,
+ module: "loops",
+ },
+ Lint {
+ name: "forget_copy",
+ group: "correctness",
+ desc: "calls to `std::mem::forget` with a value that implements Copy",
+ deprecation: None,
+ module: "drop_forget_ref",
+ },
+ Lint {
+ name: "forget_ref",
+ group: "correctness",
+ desc: "calls to `std::mem::forget` with a reference instead of an owned value",
+ deprecation: None,
+ module: "drop_forget_ref",
+ },
+ Lint {
+ name: "future_not_send",
+ group: "nursery",
+ desc: "public Futures must be Send",
+ deprecation: None,
+ module: "future_not_send",
+ },
+ Lint {
+ name: "get_last_with_len",
+ group: "complexity",
+ desc: "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler",
+ deprecation: None,
+ module: "get_last_with_len",
+ },
+ Lint {
+ name: "get_unwrap",
+ group: "restriction",
+ desc: "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "identity_op",
+ group: "complexity",
+ desc: "using identity operations, e.g., `x + 0` or `y / 1`",
+ deprecation: None,
+ module: "identity_op",
+ },
+ Lint {
+ name: "if_let_mutex",
+ group: "correctness",
+ desc: "locking a `Mutex` in an `if let` block can cause deadlocks",
+ deprecation: None,
+ module: "if_let_mutex",
+ },
+ Lint {
+ name: "if_let_some_result",
+ group: "style",
+ desc: "usage of `ok()` in `if let Some(pat)` statements is unnecessary, match on `Ok(pat)` instead",
+ deprecation: None,
+ module: "if_let_some_result",
+ },
+ Lint {
+ name: "if_not_else",
+ group: "pedantic",
+ desc: "`if` branches that could be swapped so no negation operation is necessary on the condition",
+ deprecation: None,
+ module: "if_not_else",
+ },
+ Lint {
+ name: "if_same_then_else",
+ group: "correctness",
+ desc: "`if` with the same `then` and `else` blocks",
+ deprecation: None,
+ module: "copies",
+ },
+ Lint {
+ name: "ifs_same_cond",
+ group: "correctness",
+ desc: "consecutive `if`s with the same condition",
+ deprecation: None,
+ module: "copies",
+ },
+ Lint {
+ name: "implicit_hasher",
+ group: "pedantic",
+ desc: "missing generalization over different hashers",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "implicit_return",
+ group: "restriction",
+ desc: "use a return statement like `return expr` instead of an expression",
+ deprecation: None,
+ module: "implicit_return",
+ },
+ Lint {
+ name: "implicit_saturating_sub",
+ group: "pedantic",
+ desc: "Perform saturating subtraction instead of implicitly checking lower bound of data type",
+ deprecation: None,
+ module: "implicit_saturating_sub",
+ },
+ Lint {
+ name: "imprecise_flops",
+ group: "nursery",
+ desc: "usage of imprecise floating point operations",
+ deprecation: None,
+ module: "floating_point_arithmetic",
+ },
+ Lint {
+ name: "inconsistent_digit_grouping",
+ group: "style",
+ desc: "integer literals with digits grouped inconsistently",
+ deprecation: None,
+ module: "literal_representation",
+ },
+ Lint {
+ name: "indexing_slicing",
+ group: "restriction",
+ desc: "indexing/slicing usage",
+ deprecation: None,
+ module: "indexing_slicing",
+ },
+ Lint {
+ name: "ineffective_bit_mask",
+ group: "correctness",
+ desc: "expressions where a bit mask will be rendered useless by a comparison, e.g., `(x | 1) > 2`",
+ deprecation: None,
+ module: "bit_mask",
+ },
+ Lint {
+ name: "inefficient_to_string",
+ group: "pedantic",
+ desc: "using `to_string` on `&&T` where `T: ToString`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "infallible_destructuring_match",
+ group: "style",
+ desc: "a `match` statement with a single infallible arm instead of a `let`",
+ deprecation: None,
+ module: "matches",
+ },
+ Lint {
+ name: "infinite_iter",
+ group: "correctness",
+ desc: "infinite iteration",
+ deprecation: None,
+ module: "infinite_iter",
+ },
+ Lint {
+ name: "inherent_to_string",
+ group: "style",
+ desc: "type implements inherent method `to_string()`, but should instead implement the `Display` trait",
+ deprecation: None,
+ module: "inherent_to_string",
+ },
+ Lint {
+ name: "inherent_to_string_shadow_display",
+ group: "correctness",
+ desc: "type implements inherent method `to_string()`, which gets shadowed by the implementation of the `Display` trait",
+ deprecation: None,
+ module: "inherent_to_string",
+ },
+ Lint {
+ name: "inline_always",
+ group: "pedantic",
+ desc: "use of `#[inline(always)]`",
+ deprecation: None,
+ module: "attrs",
+ },
+ Lint {
+ name: "inline_fn_without_body",
+ group: "correctness",
+ desc: "use of `#[inline]` on trait methods without bodies",
+ deprecation: None,
+ module: "inline_fn_without_body",
+ },
+ Lint {
+ name: "int_plus_one",
+ group: "complexity",
+ desc: "instead of using `x >= y + 1`, use `x > y`",
+ deprecation: None,
+ module: "int_plus_one",
+ },
+ Lint {
+ name: "integer_arithmetic",
+ group: "restriction",
+ desc: "any integer arithmetic expression which could overflow or panic",
+ deprecation: None,
+ module: "arithmetic",
+ },
+ Lint {
+ name: "integer_division",
+ group: "restriction",
+ desc: "integer division may cause loss of precision",
+ deprecation: None,
+ module: "integer_division",
+ },
+ Lint {
+ name: "into_iter_on_ref",
+ group: "style",
+ desc: "using `.into_iter()` on a reference",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "invalid_atomic_ordering",
+ group: "correctness",
+ desc: "usage of invalid atomic ordering in atomic loads/stores and memory fences",
+ deprecation: None,
+ module: "atomic_ordering",
+ },
+ Lint {
+ name: "invalid_regex",
+ group: "correctness",
+ desc: "invalid regular expressions",
+ deprecation: None,
+ module: "regex",
+ },
+ Lint {
+ name: "invalid_upcast_comparisons",
+ group: "pedantic",
+ desc: "a comparison involving an upcast which is always true or false",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "items_after_statements",
+ group: "pedantic",
+ desc: "blocks where an item comes after a statement",
+ deprecation: None,
+ module: "items_after_statements",
+ },
+ Lint {
+ name: "iter_cloned_collect",
+ group: "style",
+ desc: "using `.cloned().collect()` on slice to create a `Vec`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "iter_next_loop",
+ group: "correctness",
+ desc: "for-looping over `_.next()` which is probably not intended",
+ deprecation: None,
+ module: "loops",
+ },
+ Lint {
+ name: "iter_next_slice",
+ group: "style",
+ desc: "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "iter_nth",
+ group: "perf",
+ desc: "using `.iter().nth()` on a standard library type with O(1) element access",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "iter_nth_zero",
+ group: "style",
+ desc: "replace `iter.nth(0)` with `iter.next()`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "iter_skip_next",
+ group: "style",
+ desc: "using `.skip(x).next()` on an iterator",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "iterator_step_by_zero",
+ group: "correctness",
+ desc: "using `Iterator::step_by(0)`, which will panic at runtime",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "just_underscores_and_digits",
+ group: "style",
+ desc: "unclear name",
+ deprecation: None,
+ module: "non_expressive_names",
+ },
+ Lint {
+ name: "large_const_arrays",
+ group: "perf",
+ desc: "large non-scalar const array may cause performance overhead",
+ deprecation: None,
+ module: "large_const_arrays",
+ },
+ Lint {
+ name: "large_digit_groups",
+ group: "pedantic",
+ desc: "grouping digits into groups that are too large",
+ deprecation: None,
+ module: "literal_representation",
+ },
+ Lint {
+ name: "large_enum_variant",
+ group: "perf",
+ desc: "large size difference between variants on an enum",
+ deprecation: None,
+ module: "large_enum_variant",
+ },
+ Lint {
+ name: "large_stack_arrays",
+ group: "pedantic",
+ desc: "allocating large arrays on stack may cause stack overflow",
+ deprecation: None,
+ module: "large_stack_arrays",
+ },
+ Lint {
+ name: "len_without_is_empty",
+ group: "style",
+ desc: "traits or impls with a public `len` method but no corresponding `is_empty` method",
+ deprecation: None,
+ module: "len_zero",
+ },
+ Lint {
+ name: "len_zero",
+ group: "style",
+ desc: "checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` could be used instead",
+ deprecation: None,
+ module: "len_zero",
+ },
+ Lint {
+ name: "let_and_return",
+ group: "style",
+ desc: "creating a let-binding and then immediately returning it like `let x = expr; x` at the end of a block",
+ deprecation: None,
+ module: "returns",
+ },
+ Lint {
+ name: "let_underscore_lock",
+ group: "correctness",
+ desc: "non-binding let on a synchronization lock",
+ deprecation: None,
+ module: "let_underscore",
+ },
+ Lint {
+ name: "let_underscore_must_use",
+ group: "restriction",
+ desc: "non-binding let on a `#[must_use]` expression",
+ deprecation: None,
+ module: "let_underscore",
+ },
+ Lint {
+ name: "let_unit_value",
+ group: "pedantic",
+ desc: "creating a `let` binding to a value of unit type, which usually can\'t be used afterwards",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "linkedlist",
+ group: "pedantic",
+ desc: "usage of LinkedList, usually a vector is faster, or a more specialized data structure like a `VecDeque`",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "logic_bug",
+ group: "correctness",
+ desc: "boolean expressions that contain terminals which can be eliminated",
+ deprecation: None,
+ module: "booleans",
+ },
+ Lint {
+ name: "lossy_float_literal",
+ group: "restriction",
+ desc: "lossy whole number float literals",
+ deprecation: None,
+ module: "float_literal",
+ },
+ Lint {
+ name: "macro_use_imports",
+ group: "pedantic",
+ desc: "#[macro_use] is no longer needed",
+ deprecation: None,
+ module: "macro_use",
+ },
+ Lint {
+ name: "main_recursion",
+ group: "style",
+ desc: "recursion using the entrypoint",
+ deprecation: None,
+ module: "main_recursion",
+ },
+ Lint {
+ name: "manual_async_fn",
+ group: "style",
+ desc: "manual implementations of `async` functions can be simplified using the dedicated syntax",
+ deprecation: None,
+ module: "manual_async_fn",
+ },
+ Lint {
+ name: "manual_memcpy",
+ group: "perf",
+ desc: "manually copying items between slices",
+ deprecation: None,
+ module: "loops",
+ },
+ Lint {
+ name: "manual_non_exhaustive",
+ group: "style",
+ desc: "manual implementations of the non-exhaustive pattern can be simplified using #[non_exhaustive]",
+ deprecation: None,
+ module: "manual_non_exhaustive",
+ },
+ Lint {
+ name: "manual_saturating_arithmetic",
+ group: "style",
+ desc: "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "manual_swap",
+ group: "complexity",
+ desc: "manual swap of two variables",
+ deprecation: None,
+ module: "swap",
+ },
+ Lint {
+ name: "many_single_char_names",
+ group: "style",
+ desc: "too many single character bindings",
+ deprecation: None,
+ module: "non_expressive_names",
+ },
+ Lint {
+ name: "map_clone",
+ group: "style",
+ desc: "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types",
+ deprecation: None,
+ module: "map_clone",
+ },
+ Lint {
+ name: "map_entry",
+ group: "perf",
+ desc: "use of `contains_key` followed by `insert` on a `HashMap` or `BTreeMap`",
+ deprecation: None,
+ module: "entry",
+ },
+ Lint {
+ name: "map_flatten",
+ group: "pedantic",
+ desc: "using combinations of `flatten` and `map` which can usually be written as a single method call",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "map_identity",
+ group: "complexity",
+ desc: "using iterator.map(|x| x)",
+ deprecation: None,
+ module: "map_identity",
+ },
+ Lint {
+ name: "map_unwrap_or",
+ group: "pedantic",
+ desc: "using `.map(f).unwrap_or(a)` or `.map(f).unwrap_or_else(func)`, which are more succinctly expressed as `map_or(a, f)` or `map_or_else(a, f)`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "match_as_ref",
+ group: "complexity",
+ desc: "a `match` on an Option value instead of using `as_ref()` or `as_mut`",
+ deprecation: None,
+ module: "matches",
+ },
+ Lint {
+ name: "match_bool",
+ group: "pedantic",
+ desc: "a `match` on a boolean expression instead of an `if..else` block",
+ deprecation: None,
+ module: "matches",
+ },
+ Lint {
+ name: "match_like_matches_macro",
+ group: "style",
+ desc: "a match that could be written with the matches! macro",
+ deprecation: None,
+ module: "matches",
+ },
+ Lint {
+ name: "match_on_vec_items",
+ group: "pedantic",
+ desc: "matching on vector elements can panic",
+ deprecation: None,
+ module: "match_on_vec_items",
+ },
+ Lint {
+ name: "match_overlapping_arm",
+ group: "style",
+ desc: "a `match` with overlapping arms",
+ deprecation: None,
+ module: "matches",
+ },
+ Lint {
+ name: "match_ref_pats",
+ group: "style",
+ desc: "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression",
+ deprecation: None,
+ module: "matches",
+ },
+ Lint {
+ name: "match_same_arms",
+ group: "pedantic",
+ desc: "`match` with identical arm bodies",
+ deprecation: None,
+ module: "copies",
+ },
+ Lint {
+ name: "match_single_binding",
+ group: "complexity",
+ desc: "a match with a single binding instead of using `let` statement",
+ deprecation: None,
+ module: "matches",
+ },
+ Lint {
+ name: "match_wild_err_arm",
+ group: "pedantic",
+ desc: "a `match` with `Err(_)` arm and take drastic actions",
+ deprecation: None,
+ module: "matches",
+ },
+ Lint {
+ name: "match_wildcard_for_single_variants",
+ group: "pedantic",
+ desc: "a wildcard enum match for a single variant",
+ deprecation: None,
+ module: "matches",
+ },
+ Lint {
+ name: "maybe_infinite_iter",
+ group: "pedantic",
+ desc: "possible infinite iteration",
+ deprecation: None,
+ module: "infinite_iter",
+ },
+ Lint {
+ name: "mem_discriminant_non_enum",
+ group: "correctness",
+ desc: "calling `mem::descriminant` on non-enum type",
+ deprecation: None,
+ module: "mem_discriminant",
+ },
+ Lint {
+ name: "mem_forget",
+ group: "restriction",
+ desc: "`mem::forget` usage on `Drop` types, likely to cause memory leaks",
+ deprecation: None,
+ module: "mem_forget",
+ },
+ Lint {
+ name: "mem_replace_option_with_none",
+ group: "style",
+ desc: "replacing an `Option` with `None` instead of `take()`",
+ deprecation: None,
+ module: "mem_replace",
+ },
+ Lint {
+ name: "mem_replace_with_default",
+ group: "style",
+ desc: "replacing a value of type `T` with `T::default()` instead of using `std::mem::take`",
+ deprecation: None,
+ module: "mem_replace",
+ },
+ Lint {
+ name: "mem_replace_with_uninit",
+ group: "correctness",
+ desc: "`mem::replace(&mut _, mem::uninitialized())` or `mem::replace(&mut _, mem::zeroed())`",
+ deprecation: None,
+ module: "mem_replace",
+ },
+ Lint {
+ name: "min_max",
+ group: "correctness",
+ desc: "`min(_, max(_, _))` (or vice versa) with bounds clamping the result to a constant",
+ deprecation: None,
+ module: "minmax",
+ },
+ Lint {
+ name: "mismatched_target_os",
+ group: "correctness",
+ desc: "usage of `cfg(operating_system)` instead of `cfg(target_os = \"operating_system\")`",
+ deprecation: None,
+ module: "attrs",
+ },
+ Lint {
+ name: "misrefactored_assign_op",
+ group: "complexity",
+ desc: "having a variable on both sides of an assign op",
+ deprecation: None,
+ module: "assign_ops",
+ },
+ Lint {
+ name: "missing_const_for_fn",
+ group: "nursery",
+ desc: "Lint functions definitions that could be made `const fn`",
+ deprecation: None,
+ module: "missing_const_for_fn",
+ },
+ Lint {
+ name: "missing_docs_in_private_items",
+ group: "restriction",
+ desc: "detects missing documentation for public and private members",
+ deprecation: None,
+ module: "missing_doc",
+ },
+ Lint {
+ name: "missing_errors_doc",
+ group: "pedantic",
+ desc: "`pub fn` returns `Result` without `# Errors` in doc comment",
+ deprecation: None,
+ module: "doc",
+ },
+ Lint {
+ name: "missing_inline_in_public_items",
+ group: "restriction",
+ desc: "detects missing `#[inline]` attribute for public callables (functions, trait methods, methods...)",
+ deprecation: None,
+ module: "missing_inline",
+ },
+ Lint {
+ name: "missing_safety_doc",
+ group: "style",
+ desc: "`pub unsafe fn` without `# Safety` docs",
+ deprecation: None,
+ module: "doc",
+ },
+ Lint {
+ name: "mistyped_literal_suffixes",
+ group: "correctness",
+ desc: "mistyped literal suffix",
+ deprecation: None,
+ module: "literal_representation",
+ },
+ Lint {
+ name: "mixed_case_hex_literals",
+ group: "style",
+ desc: "hex literals whose letter digits are not consistently upper- or lowercased",
+ deprecation: None,
+ module: "misc_early",
+ },
+ Lint {
+ name: "module_inception",
+ group: "style",
+ desc: "modules that have the same name as their parent module",
+ deprecation: None,
+ module: "enum_variants",
+ },
+ Lint {
+ name: "module_name_repetitions",
+ group: "pedantic",
+ desc: "type names prefixed/postfixed with their containing module\'s name",
+ deprecation: None,
+ module: "enum_variants",
+ },
+ Lint {
+ name: "modulo_arithmetic",
+ group: "restriction",
+ desc: "any modulo arithmetic statement",
+ deprecation: None,
+ module: "modulo_arithmetic",
+ },
+ Lint {
+ name: "modulo_one",
+ group: "correctness",
+ desc: "taking a number modulo 1, which always returns 0",
+ deprecation: None,
+ module: "misc",
+ },
+ Lint {
+ name: "multiple_crate_versions",
+ group: "cargo",
+ desc: "multiple versions of the same crate being used",
+ deprecation: None,
+ module: "multiple_crate_versions",
+ },
+ Lint {
+ name: "multiple_inherent_impl",
+ group: "restriction",
+ desc: "Multiple inherent impl that could be grouped",
+ deprecation: None,
+ module: "inherent_impl",
+ },
+ Lint {
+ name: "must_use_candidate",
+ group: "pedantic",
+ desc: "function or method that could take a `#[must_use]` attribute",
+ deprecation: None,
+ module: "functions",
+ },
+ Lint {
+ name: "must_use_unit",
+ group: "style",
+ desc: "`#[must_use]` attribute on a unit-returning function / method",
+ deprecation: None,
+ module: "functions",
+ },
+ Lint {
+ name: "mut_from_ref",
+ group: "correctness",
+ desc: "fns that create mutable refs from immutable ref args",
+ deprecation: None,
+ module: "ptr",
+ },
+ Lint {
+ name: "mut_mut",
+ group: "pedantic",
+ desc: "usage of double-mut refs, e.g., `&mut &mut ...`",
+ deprecation: None,
+ module: "mut_mut",
+ },
+ Lint {
+ name: "mut_range_bound",
+ group: "complexity",
+ desc: "for loop over a range where one of the bounds is a mutable variable",
+ deprecation: None,
+ module: "loops",
+ },
+ Lint {
+ name: "mutable_key_type",
+ group: "correctness",
+ desc: "Check for mutable `Map`/`Set` key type",
+ deprecation: None,
+ module: "mut_key",
+ },
+ Lint {
+ name: "mutex_atomic",
+ group: "perf",
+ desc: "using a mutex where an atomic value could be used instead",
+ deprecation: None,
+ module: "mutex_atomic",
+ },
+ Lint {
+ name: "mutex_integer",
+ group: "nursery",
+ desc: "using a mutex for an integer type",
+ deprecation: None,
+ module: "mutex_atomic",
+ },
+ Lint {
+ name: "naive_bytecount",
+ group: "perf",
+ desc: "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values",
+ deprecation: None,
+ module: "bytecount",
+ },
+ Lint {
+ name: "needless_arbitrary_self_type",
+ group: "complexity",
+ desc: "type of `self` parameter is already by default `Self`",
+ deprecation: None,
+ module: "needless_arbitrary_self_type",
+ },
+ Lint {
+ name: "needless_bool",
+ group: "complexity",
+ desc: "if-statements with plain booleans in the then- and else-clause, e.g., `if p { true } else { false }`",
+ deprecation: None,
+ module: "needless_bool",
+ },
+ Lint {
+ name: "needless_borrow",
+ group: "nursery",
+ desc: "taking a reference that is going to be automatically dereferenced",
+ deprecation: None,
+ module: "needless_borrow",
+ },
+ Lint {
+ name: "needless_borrowed_reference",
+ group: "complexity",
+ desc: "taking a needless borrowed reference",
+ deprecation: None,
+ module: "needless_borrowed_ref",
+ },
+ Lint {
+ name: "needless_collect",
+ group: "perf",
+ desc: "collecting an iterator when collect is not needed",
+ deprecation: None,
+ module: "loops",
+ },
+ Lint {
+ name: "needless_continue",
+ group: "pedantic",
+ desc: "`continue` statements that can be replaced by a rearrangement of code",
+ deprecation: None,
+ module: "needless_continue",
+ },
+ Lint {
+ name: "needless_doctest_main",
+ group: "style",
+ desc: "presence of `fn main() {` in code examples",
+ deprecation: None,
+ module: "doc",
+ },
+ Lint {
+ name: "needless_lifetimes",
+ group: "complexity",
+ desc: "using explicit lifetimes for references in function arguments when elision rules would allow omitting them",
+ deprecation: None,
+ module: "lifetimes",
+ },
+ Lint {
+ name: "needless_pass_by_value",
+ group: "pedantic",
+ desc: "functions taking arguments by value, but not consuming them in its body",
+ deprecation: None,
+ module: "needless_pass_by_value",
+ },
+ Lint {
+ name: "needless_range_loop",
+ group: "style",
+ desc: "for-looping over a range of indices where an iterator over items would do",
+ deprecation: None,
+ module: "loops",
+ },
+ Lint {
+ name: "needless_return",
+ group: "style",
+ desc: "using a return statement like `return expr;` where an expression would suffice",
+ deprecation: None,
+ module: "returns",
+ },
+ Lint {
+ name: "needless_update",
+ group: "complexity",
+ desc: "using `Foo { ..base }` when there are no missing fields",
+ deprecation: None,
+ module: "needless_update",
+ },
+ Lint {
+ name: "neg_cmp_op_on_partial_ord",
+ group: "complexity",
+ desc: "The use of negated comparison operators on partially ordered types may produce confusing code.",
+ deprecation: None,
+ module: "neg_cmp_op_on_partial_ord",
+ },
+ Lint {
+ name: "neg_multiply",
+ group: "style",
+ desc: "multiplying integers with `-1`",
+ deprecation: None,
+ module: "neg_multiply",
+ },
+ Lint {
+ name: "never_loop",
+ group: "correctness",
+ desc: "any loop that will always `break` or `return`",
+ deprecation: None,
+ module: "loops",
+ },
+ Lint {
+ name: "new_ret_no_self",
+ group: "style",
+ desc: "not returning type containing `Self` in a `new` method",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "new_without_default",
+ group: "style",
+ desc: "`fn new() -> Self` method without `Default` implementation",
+ deprecation: None,
+ module: "new_without_default",
+ },
+ Lint {
+ name: "no_effect",
+ group: "complexity",
+ desc: "statements with no effect",
+ deprecation: None,
+ module: "no_effect",
+ },
+ Lint {
+ name: "non_ascii_literal",
+ group: "pedantic",
+ desc: "using any literal non-ASCII chars in a string literal instead of using the `\\\\u` escape",
+ deprecation: None,
+ module: "unicode",
+ },
+ Lint {
+ name: "nonminimal_bool",
+ group: "complexity",
+ desc: "boolean expressions that can be written more concisely",
+ deprecation: None,
+ module: "booleans",
+ },
+ Lint {
+ name: "nonsensical_open_options",
+ group: "correctness",
+ desc: "nonsensical combination of options for opening a file",
+ deprecation: None,
+ module: "open_options",
+ },
+ Lint {
+ name: "not_unsafe_ptr_arg_deref",
+ group: "correctness",
+ desc: "public functions dereferencing raw pointer arguments but not marked `unsafe`",
+ deprecation: None,
+ module: "functions",
+ },
+ Lint {
+ name: "ok_expect",
+ group: "style",
+ desc: "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "op_ref",
+ group: "style",
+ desc: "taking a reference to satisfy the type constraints on `==`",
+ deprecation: None,
+ module: "eq_op",
+ },
+ Lint {
+ name: "option_as_ref_deref",
+ group: "complexity",
+ desc: "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "option_env_unwrap",
+ group: "correctness",
+ desc: "using `option_env!(...).unwrap()` to get environment variable",
+ deprecation: None,
+ module: "option_env_unwrap",
+ },
+ Lint {
+ name: "option_if_let_else",
+ group: "pedantic",
+ desc: "reimplementation of Option::map_or",
+ deprecation: None,
+ module: "option_if_let_else",
+ },
+ Lint {
+ name: "option_map_or_none",
+ group: "style",
+ desc: "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "option_map_unit_fn",
+ group: "complexity",
+ desc: "using `option.map(f)`, where `f` is a function or closure that returns `()`",
+ deprecation: None,
+ module: "map_unit_fn",
+ },
+ Lint {
+ name: "option_option",
+ group: "pedantic",
+ desc: "usage of `Option<Option<T>>`",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "or_fun_call",
+ group: "perf",
+ desc: "using any `*or` method with a function call, which suggests `*or_else`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "out_of_bounds_indexing",
+ group: "correctness",
+ desc: "out of bounds constant indexing",
+ deprecation: None,
+ module: "indexing_slicing",
+ },
+ Lint {
+ name: "overflow_check_conditional",
+ group: "complexity",
+ desc: "overflow checks inspired by C which are likely to panic",
+ deprecation: None,
+ module: "overflow_check_conditional",
+ },
+ Lint {
+ name: "panic",
+ group: "restriction",
+ desc: "usage of the `panic!` macro",
+ deprecation: None,
+ module: "panic_unimplemented",
+ },
+ Lint {
+ name: "panic_params",
+ group: "style",
+ desc: "missing parameters in `panic!` calls",
+ deprecation: None,
+ module: "panic_unimplemented",
+ },
+ Lint {
+ name: "panicking_unwrap",
+ group: "correctness",
+ desc: "checks for calls of `unwrap[_err]()` that will always fail",
+ deprecation: None,
+ module: "unwrap",
+ },
+ Lint {
+ name: "partialeq_ne_impl",
+ group: "complexity",
+ desc: "re-implementing `PartialEq::ne`",
+ deprecation: None,
+ module: "partialeq_ne_impl",
+ },
+ Lint {
+ name: "path_buf_push_overwrite",
+ group: "nursery",
+ desc: "calling `push` with file system root on `PathBuf` can overwrite it",
+ deprecation: None,
+ module: "path_buf_push_overwrite",
+ },
+ Lint {
+ name: "pattern_type_mismatch",
+ group: "restriction",
+ desc: "type of pattern does not match the expression type",
+ deprecation: None,
+ module: "pattern_type_mismatch",
+ },
+ Lint {
+ name: "possible_missing_comma",
+ group: "correctness",
+ desc: "possible missing comma in array",
+ deprecation: None,
+ module: "formatting",
+ },
+ Lint {
+ name: "precedence",
+ group: "complexity",
+ desc: "operations where precedence may be unclear",
+ deprecation: None,
+ module: "precedence",
+ },
+ Lint {
+ name: "print_literal",
+ group: "style",
+ desc: "printing a literal with a format string",
+ deprecation: None,
+ module: "write",
+ },
+ Lint {
+ name: "print_stdout",
+ group: "restriction",
+ desc: "printing on stdout",
+ deprecation: None,
+ module: "write",
+ },
+ Lint {
+ name: "print_with_newline",
+ group: "style",
+ desc: "using `print!()` with a format string that ends in a single newline",
+ deprecation: None,
+ module: "write",
+ },
+ Lint {
+ name: "println_empty_string",
+ group: "style",
+ desc: "using `println!(\"\")` with an empty string",
+ deprecation: None,
+ module: "write",
+ },
+ Lint {
+ name: "ptr_arg",
+ group: "style",
+ desc: "fn arguments of the type `&Vec<...>` or `&String`, suggesting to use `&[...]` or `&str` instead, respectively",
+ deprecation: None,
+ module: "ptr",
+ },
+ Lint {
+ name: "ptr_offset_with_cast",
+ group: "complexity",
+ desc: "unneeded pointer offset cast",
+ deprecation: None,
+ module: "ptr_offset_with_cast",
+ },
+ Lint {
+ name: "pub_enum_variant_names",
+ group: "pedantic",
+ desc: "public enums where all variants share a prefix/postfix",
+ deprecation: None,
+ module: "enum_variants",
+ },
+ Lint {
+ name: "question_mark",
+ group: "style",
+ desc: "checks for expressions that could be replaced by the question mark operator",
+ deprecation: None,
+ module: "question_mark",
+ },
+ Lint {
+ name: "range_minus_one",
+ group: "pedantic",
+ desc: "`x..=(y-1)` reads better as `x..y`",
+ deprecation: None,
+ module: "ranges",
+ },
+ Lint {
+ name: "range_plus_one",
+ group: "pedantic",
+ desc: "`x..(y+1)` reads better as `x..=y`",
+ deprecation: None,
+ module: "ranges",
+ },
+ Lint {
+ name: "range_zip_with_len",
+ group: "complexity",
+ desc: "zipping iterator with a range when `enumerate()` would do",
+ deprecation: None,
+ module: "ranges",
+ },
+ Lint {
+ name: "redundant_allocation",
+ group: "perf",
+ desc: "redundant allocation",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "redundant_clone",
+ group: "perf",
+ desc: "`clone()` of an owned value that is going to be dropped immediately",
+ deprecation: None,
+ module: "redundant_clone",
+ },
+ Lint {
+ name: "redundant_closure",
+ group: "style",
+ desc: "redundant closures, i.e., `|a| foo(a)` (which can be written as just `foo`)",
+ deprecation: None,
+ module: "eta_reduction",
+ },
+ Lint {
+ name: "redundant_closure_call",
+ group: "complexity",
+ desc: "throwaway closures called in the expression they are defined",
+ deprecation: None,
+ module: "redundant_closure_call",
+ },
+ Lint {
+ name: "redundant_closure_for_method_calls",
+ group: "pedantic",
+ desc: "redundant closures for method calls",
+ deprecation: None,
+ module: "eta_reduction",
+ },
+ Lint {
+ name: "redundant_field_names",
+ group: "style",
+ desc: "checks for fields in struct literals where shorthands could be used",
+ deprecation: None,
+ module: "redundant_field_names",
+ },
+ Lint {
+ name: "redundant_pattern",
+ group: "style",
+ desc: "using `name @ _` in a pattern",
+ deprecation: None,
+ module: "misc_early",
+ },
+ Lint {
+ name: "redundant_pattern_matching",
+ group: "style",
+ desc: "use the proper utility function avoiding an `if let`",
+ deprecation: None,
+ module: "matches",
+ },
+ Lint {
+ name: "redundant_pub_crate",
+ group: "nursery",
+ desc: "Using `pub(crate)` visibility on items that are not crate visible due to the visibility of the module that contains them.",
+ deprecation: None,
+ module: "redundant_pub_crate",
+ },
+ Lint {
+ name: "redundant_static_lifetimes",
+ group: "style",
+ desc: "Using explicit `\'static` lifetime for constants or statics when elision rules would allow omitting them.",
+ deprecation: None,
+ module: "redundant_static_lifetimes",
+ },
+ Lint {
+ name: "ref_in_deref",
+ group: "complexity",
+ desc: "Use of reference in auto dereference expression.",
+ deprecation: None,
+ module: "reference",
+ },
+ Lint {
+ name: "repeat_once",
+ group: "complexity",
+ desc: "using `.repeat(1)` instead of `String.clone()`, `str.to_string()` or `slice.to_vec()` ",
+ deprecation: None,
+ module: "repeat_once",
+ },
+ Lint {
+ name: "rest_pat_in_fully_bound_structs",
+ group: "restriction",
+ desc: "a match on a struct that binds all fields but still uses the wildcard pattern",
+ deprecation: None,
+ module: "matches",
+ },
+ Lint {
+ name: "result_map_or_into_option",
+ group: "style",
+ desc: "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "result_map_unit_fn",
+ group: "complexity",
+ desc: "using `result.map(f)`, where `f` is a function or closure that returns `()`",
+ deprecation: None,
+ module: "map_unit_fn",
+ },
+ Lint {
+ name: "reversed_empty_ranges",
+ group: "correctness",
+ desc: "reversing the limits of range expressions, resulting in empty ranges",
+ deprecation: None,
+ module: "ranges",
+ },
+ Lint {
+ name: "same_functions_in_if_condition",
+ group: "pedantic",
+ desc: "consecutive `if`s with the same function call",
+ deprecation: None,
+ module: "copies",
+ },
+ Lint {
+ name: "same_item_push",
+ group: "style",
+ desc: "the same item is pushed inside of a for loop",
+ deprecation: None,
+ module: "loops",
+ },
+ Lint {
+ name: "search_is_some",
+ group: "complexity",
+ desc: "using an iterator search followed by `is_some()`, which is more succinctly expressed as a call to `any()`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "self_assignment",
+ group: "correctness",
+ desc: "explicit self-assignment",
+ deprecation: None,
+ module: "self_assignment",
+ },
+ Lint {
+ name: "serde_api_misuse",
+ group: "correctness",
+ desc: "various things that will negatively affect your serde experience",
+ deprecation: None,
+ module: "serde_api",
+ },
+ Lint {
+ name: "shadow_reuse",
+ group: "restriction",
+ desc: "rebinding a name to an expression that re-uses the original value, e.g., `let x = x + 1`",
+ deprecation: None,
+ module: "shadow",
+ },
+ Lint {
+ name: "shadow_same",
+ group: "restriction",
+ desc: "rebinding a name to itself, e.g., `let mut x = &mut x`",
+ deprecation: None,
+ module: "shadow",
+ },
+ Lint {
+ name: "shadow_unrelated",
+ group: "pedantic",
+ desc: "rebinding a name without even using the original value",
+ deprecation: None,
+ module: "shadow",
+ },
+ Lint {
+ name: "short_circuit_statement",
+ group: "complexity",
+ desc: "using a short circuit boolean condition as a statement",
+ deprecation: None,
+ module: "misc",
+ },
+ Lint {
+ name: "should_implement_trait",
+ group: "style",
+ desc: "defining a method that should be implementing a std trait",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "similar_names",
+ group: "pedantic",
+ desc: "similarly named items and bindings",
+ deprecation: None,
+ module: "non_expressive_names",
+ },
+ Lint {
+ name: "single_char_pattern",
+ group: "perf",
+ desc: "using a single-character str where a char could be used, e.g., `_.split(\"x\")`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "single_char_push_str",
+ group: "style",
+ desc: "`push_str()` used with a single-character string literal as parameter",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "single_component_path_imports",
+ group: "style",
+ desc: "imports with single component path are redundant",
+ deprecation: None,
+ module: "single_component_path_imports",
+ },
+ Lint {
+ name: "single_match",
+ group: "style",
+ desc: "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`",
+ deprecation: None,
+ module: "matches",
+ },
+ Lint {
+ name: "single_match_else",
+ group: "pedantic",
+ desc: "a `match` statement with two arms where the second arm\'s pattern is a placeholder instead of a specific match pattern",
+ deprecation: None,
+ module: "matches",
+ },
+ Lint {
+ name: "skip_while_next",
+ group: "complexity",
+ desc: "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "slow_vector_initialization",
+ group: "perf",
+ desc: "slow vector initialization",
+ deprecation: None,
+ module: "slow_vector_initialization",
+ },
+ Lint {
+ name: "stable_sort_primitive",
+ group: "perf",
+ desc: "use of sort() when sort_unstable() is equivalent",
+ deprecation: None,
+ module: "stable_sort_primitive",
+ },
+ Lint {
+ name: "string_add",
+ group: "restriction",
+ desc: "using `x + ..` where x is a `String` instead of `push_str()`",
+ deprecation: None,
+ module: "strings",
+ },
+ Lint {
+ name: "string_add_assign",
+ group: "pedantic",
+ desc: "using `x = x + ..` where x is a `String` instead of `push_str()`",
+ deprecation: None,
+ module: "strings",
+ },
+ Lint {
+ name: "string_extend_chars",
+ group: "style",
+ desc: "using `x.extend(s.chars())` where s is a `&str` or `String`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "string_lit_as_bytes",
+ group: "style",
+ desc: "calling `as_bytes` on a string literal instead of using a byte string literal",
+ deprecation: None,
+ module: "strings",
+ },
+ Lint {
+ name: "struct_excessive_bools",
+ group: "pedantic",
+ desc: "using too many bools in a struct",
+ deprecation: None,
+ module: "excessive_bools",
+ },
+ Lint {
+ name: "suboptimal_flops",
+ group: "nursery",
+ desc: "usage of sub-optimal floating point operations",
+ deprecation: None,
+ module: "floating_point_arithmetic",
+ },
+ Lint {
+ name: "suspicious_arithmetic_impl",
+ group: "correctness",
+ desc: "suspicious use of operators in impl of arithmetic trait",
+ deprecation: None,
+ module: "suspicious_trait_impl",
+ },
+ Lint {
+ name: "suspicious_assignment_formatting",
+ group: "style",
+ desc: "suspicious formatting of `*=`, `-=` or `!=`",
+ deprecation: None,
+ module: "formatting",
+ },
+ Lint {
+ name: "suspicious_else_formatting",
+ group: "style",
+ desc: "suspicious formatting of `else`",
+ deprecation: None,
+ module: "formatting",
+ },
+ Lint {
+ name: "suspicious_map",
+ group: "complexity",
+ desc: "suspicious usage of map",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "suspicious_op_assign_impl",
+ group: "correctness",
+ desc: "suspicious use of operators in impl of OpAssign trait",
+ deprecation: None,
+ module: "suspicious_trait_impl",
+ },
+ Lint {
+ name: "suspicious_unary_op_formatting",
+ group: "style",
+ desc: "suspicious formatting of unary `-` or `!` on the RHS of a BinOp",
+ deprecation: None,
+ module: "formatting",
+ },
+ Lint {
+ name: "tabs_in_doc_comments",
+ group: "style",
+ desc: "using tabs in doc comments is not recommended",
+ deprecation: None,
+ module: "tabs_in_doc_comments",
+ },
+ Lint {
+ name: "temporary_assignment",
+ group: "complexity",
+ desc: "assignments to temporaries",
+ deprecation: None,
+ module: "temporary_assignment",
+ },
+ Lint {
+ name: "temporary_cstring_as_ptr",
+ group: "correctness",
+ desc: "getting the inner pointer of a temporary `CString`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "to_digit_is_some",
+ group: "style",
+ desc: "`char.is_digit()` is clearer",
+ deprecation: None,
+ module: "to_digit_is_some",
+ },
+ Lint {
+ name: "to_string_in_display",
+ group: "correctness",
+ desc: "`to_string` method used while implementing `Display` trait",
+ deprecation: None,
+ module: "to_string_in_display",
+ },
+ Lint {
+ name: "todo",
+ group: "restriction",
+ desc: "`todo!` should not be present in production code",
+ deprecation: None,
+ module: "panic_unimplemented",
+ },
+ Lint {
+ name: "too_many_arguments",
+ group: "complexity",
+ desc: "functions with too many arguments",
+ deprecation: None,
+ module: "functions",
+ },
+ Lint {
+ name: "too_many_lines",
+ group: "pedantic",
+ desc: "functions with too many lines",
+ deprecation: None,
+ module: "functions",
+ },
+ Lint {
+ name: "toplevel_ref_arg",
+ group: "style",
+ desc: "an entire binding declared as `ref`, in a function argument or a `let` statement",
+ deprecation: None,
+ module: "misc",
+ },
+ Lint {
+ name: "trait_duplication_in_bounds",
+ group: "pedantic",
+ desc: "Check if the same trait bounds are specified twice during a function declaration",
+ deprecation: None,
+ module: "trait_bounds",
+ },
+ Lint {
+ name: "transmute_bytes_to_str",
+ group: "complexity",
+ desc: "transmutes from a `&[u8]` to a `&str`",
+ deprecation: None,
+ module: "transmute",
+ },
+ Lint {
+ name: "transmute_float_to_int",
+ group: "complexity",
+ desc: "transmutes from a float to an integer",
+ deprecation: None,
+ module: "transmute",
+ },
+ Lint {
+ name: "transmute_int_to_bool",
+ group: "complexity",
+ desc: "transmutes from an integer to a `bool`",
+ deprecation: None,
+ module: "transmute",
+ },
+ Lint {
+ name: "transmute_int_to_char",
+ group: "complexity",
+ desc: "transmutes from an integer to a `char`",
+ deprecation: None,
+ module: "transmute",
+ },
+ Lint {
+ name: "transmute_int_to_float",
+ group: "complexity",
+ desc: "transmutes from an integer to a float",
+ deprecation: None,
+ module: "transmute",
+ },
+ Lint {
+ name: "transmute_ptr_to_ptr",
+ group: "complexity",
+ desc: "transmutes from a pointer to a pointer / a reference to a reference",
+ deprecation: None,
+ module: "transmute",
+ },
+ Lint {
+ name: "transmute_ptr_to_ref",
+ group: "complexity",
+ desc: "transmutes from a pointer to a reference type",
+ deprecation: None,
+ module: "transmute",
+ },
+ Lint {
+ name: "transmutes_expressible_as_ptr_casts",
+ group: "complexity",
+ desc: "transmutes that could be a pointer cast",
+ deprecation: None,
+ module: "transmute",
+ },
+ Lint {
+ name: "transmuting_null",
+ group: "correctness",
+ desc: "transmutes from a null pointer to a reference, which is undefined behavior",
+ deprecation: None,
+ module: "transmuting_null",
+ },
+ Lint {
+ name: "trivial_regex",
+ group: "style",
+ desc: "trivial regular expressions",
+ deprecation: None,
+ module: "regex",
+ },
+ Lint {
+ name: "trivially_copy_pass_by_ref",
+ group: "pedantic",
+ desc: "functions taking small copyable arguments by reference",
+ deprecation: None,
+ module: "trivially_copy_pass_by_ref",
+ },
+ Lint {
+ name: "try_err",
+ group: "style",
+ desc: "return errors explicitly rather than hiding them behind a `?`",
+ deprecation: None,
+ module: "try_err",
+ },
+ Lint {
+ name: "type_complexity",
+ group: "complexity",
+ desc: "usage of very complex types that might be better factored into `type` definitions",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "type_repetition_in_bounds",
+ group: "pedantic",
+ desc: "Types are repeated unnecessary in trait bounds use `+` instead of using `T: _, T: _`",
+ deprecation: None,
+ module: "trait_bounds",
+ },
+ Lint {
+ name: "unicode_not_nfc",
+ group: "pedantic",
+ desc: "using a Unicode literal not in NFC normal form (see [Unicode tr15](http://www.unicode.org/reports/tr15/) for further information)",
+ deprecation: None,
+ module: "unicode",
+ },
+ Lint {
+ name: "unimplemented",
+ group: "restriction",
+ desc: "`unimplemented!` should not be present in production code",
+ deprecation: None,
+ module: "panic_unimplemented",
+ },
+ Lint {
+ name: "uninit_assumed_init",
+ group: "correctness",
+ desc: "`MaybeUninit::uninit().assume_init()`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "unit_arg",
+ group: "complexity",
+ desc: "passing unit to a function",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "unit_cmp",
+ group: "correctness",
+ desc: "comparing unit values",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "unit_return_expecting_ord",
+ group: "correctness",
+ desc: "fn arguments of type Fn(...) -> Ord returning the unit type ().",
+ deprecation: None,
+ module: "unit_return_expecting_ord",
+ },
+ Lint {
+ name: "unknown_clippy_lints",
+ group: "style",
+ desc: "unknown_lints for scoped Clippy lints",
+ deprecation: None,
+ module: "attrs",
+ },
+ Lint {
+ name: "unnecessary_cast",
+ group: "complexity",
+ desc: "cast to the same type, e.g., `x as i32` where `x: i32`",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "unnecessary_filter_map",
+ group: "complexity",
+ desc: "using `filter_map` when a more succinct alternative exists",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "unnecessary_fold",
+ group: "style",
+ desc: "using `fold` when a more succinct alternative exists",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "unnecessary_lazy_evaluations",
+ group: "style",
+ desc: "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "unnecessary_mut_passed",
+ group: "style",
+ desc: "an argument passed as a mutable reference although the callee only demands an immutable reference",
+ deprecation: None,
+ module: "mut_reference",
+ },
+ Lint {
+ name: "unnecessary_operation",
+ group: "complexity",
+ desc: "outer expressions with no effect",
+ deprecation: None,
+ module: "no_effect",
+ },
+ Lint {
+ name: "unnecessary_sort_by",
+ group: "complexity",
+ desc: "Use of `Vec::sort_by` when `Vec::sort_by_key` or `Vec::sort` would be clearer",
+ deprecation: None,
+ module: "unnecessary_sort_by",
+ },
+ Lint {
+ name: "unnecessary_unwrap",
+ group: "complexity",
+ desc: "checks for calls of `unwrap[_err]()` that cannot fail",
+ deprecation: None,
+ module: "unwrap",
+ },
+ Lint {
+ name: "unneeded_field_pattern",
+ group: "restriction",
+ desc: "struct fields bound to a wildcard instead of using `..`",
+ deprecation: None,
+ module: "misc_early",
+ },
+ Lint {
+ name: "unneeded_wildcard_pattern",
+ group: "complexity",
+ desc: "tuple patterns with a wildcard pattern (`_`) is next to a rest pattern (`..`)",
+ deprecation: None,
+ module: "misc_early",
+ },
+ Lint {
+ name: "unnested_or_patterns",
+ group: "pedantic",
+ desc: "unnested or-patterns, e.g., `Foo(Bar) | Foo(Baz) instead of `Foo(Bar | Baz)`",
+ deprecation: None,
+ module: "unnested_or_patterns",
+ },
+ Lint {
+ name: "unreachable",
+ group: "restriction",
+ desc: "`unreachable!` should not be present in production code",
+ deprecation: None,
+ module: "panic_unimplemented",
+ },
+ Lint {
+ name: "unreadable_literal",
+ group: "pedantic",
+ desc: "long integer literal without underscores",
+ deprecation: None,
+ module: "literal_representation",
+ },
+ Lint {
+ name: "unsafe_derive_deserialize",
+ group: "pedantic",
+ desc: "deriving `serde::Deserialize` on a type that has methods using `unsafe`",
+ deprecation: None,
+ module: "derive",
+ },
+ Lint {
+ name: "unsafe_removed_from_name",
+ group: "style",
+ desc: "`unsafe` removed from API names on import",
+ deprecation: None,
+ module: "unsafe_removed_from_name",
+ },
+ Lint {
+ name: "unseparated_literal_suffix",
+ group: "pedantic",
+ desc: "literals whose suffix is not separated by an underscore",
+ deprecation: None,
+ module: "misc_early",
+ },
+ Lint {
+ name: "unsound_collection_transmute",
+ group: "correctness",
+ desc: "transmute between collections of layout-incompatible types",
+ deprecation: None,
+ module: "transmute",
+ },
+ Lint {
+ name: "unused_io_amount",
+ group: "correctness",
+ desc: "unused written/read amount",
+ deprecation: None,
+ module: "unused_io_amount",
+ },
+ Lint {
+ name: "unused_self",
+ group: "pedantic",
+ desc: "methods that contain a `self` argument but don\'t use it",
+ deprecation: None,
+ module: "unused_self",
+ },
+ Lint {
+ name: "unused_unit",
+ group: "style",
+ desc: "needless unit expression",
+ deprecation: None,
+ module: "unused_unit",
+ },
+ Lint {
+ name: "unwrap_in_result",
+ group: "restriction",
+ desc: "functions of type `Result<..>` or `Option`<...> that contain `expect()` or `unwrap()`",
+ deprecation: None,
+ module: "unwrap_in_result",
+ },
+ Lint {
+ name: "unwrap_used",
+ group: "restriction",
+ desc: "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "use_debug",
+ group: "restriction",
+ desc: "use of `Debug`-based formatting",
+ deprecation: None,
+ module: "write",
+ },
+ Lint {
+ name: "use_self",
+ group: "nursery",
+ desc: "unnecessary structure name repetition whereas `Self` is applicable",
+ deprecation: None,
+ module: "use_self",
+ },
+ Lint {
+ name: "used_underscore_binding",
+ group: "pedantic",
+ desc: "using a binding which is prefixed with an underscore",
+ deprecation: None,
+ module: "misc",
+ },
+ Lint {
+ name: "useless_asref",
+ group: "complexity",
+ desc: "using `as_ref` where the types before and after the call are the same",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "useless_attribute",
+ group: "correctness",
+ desc: "use of lint attributes on `extern crate` items",
+ deprecation: None,
+ module: "attrs",
+ },
+ Lint {
+ name: "useless_conversion",
+ group: "complexity",
+ desc: "calls to `Into`, `TryInto`, `From`, `TryFrom`, `IntoIter` that performs useless conversions to the same type",
+ deprecation: None,
+ module: "useless_conversion",
+ },
+ Lint {
+ name: "useless_format",
+ group: "complexity",
+ desc: "useless use of `format!`",
+ deprecation: None,
+ module: "format",
+ },
+ Lint {
+ name: "useless_let_if_seq",
+ group: "nursery",
+ desc: "unidiomatic `let mut` declaration followed by initialization in `if`",
+ deprecation: None,
+ module: "let_if_seq",
+ },
+ Lint {
+ name: "useless_transmute",
+ group: "nursery",
+ desc: "transmutes that have the same to and from types or could be a cast/coercion",
+ deprecation: None,
+ module: "transmute",
+ },
+ Lint {
+ name: "useless_vec",
+ group: "perf",
+ desc: "useless `vec!`",
+ deprecation: None,
+ module: "vec",
+ },
+ Lint {
+ name: "vec_box",
+ group: "complexity",
+ desc: "usage of `Vec<Box<T>>` where T: Sized, vector elements are already on the heap",
+ deprecation: None,
+ module: "types",
+ },
+ Lint {
+ name: "vec_resize_to_zero",
+ group: "correctness",
+ desc: "emptying a vector with `resize(0, an_int)` instead of `clear()` is probably an argument inversion mistake",
+ deprecation: None,
+ module: "vec_resize_to_zero",
+ },
+ Lint {
+ name: "verbose_bit_mask",
+ group: "style",
+ desc: "expressions where a bit mask is less readable than the corresponding method call",
+ deprecation: None,
+ module: "bit_mask",
+ },
+ Lint {
+ name: "verbose_file_reads",
+ group: "restriction",
+ desc: "use of `File::read_to_end` or `File::read_to_string`",
+ deprecation: None,
+ module: "verbose_file_reads",
+ },
+ Lint {
+ name: "vtable_address_comparisons",
+ group: "correctness",
+ desc: "comparison with an address of a trait vtable",
+ deprecation: None,
+ module: "unnamed_address",
+ },
+ Lint {
+ name: "while_immutable_condition",
+ group: "correctness",
+ desc: "variables used within while expression are not mutated in the body",
+ deprecation: None,
+ module: "loops",
+ },
+ Lint {
+ name: "while_let_loop",
+ group: "complexity",
+ desc: "`loop { if let { ... } else break }`, which can be written as a `while let` loop",
+ deprecation: None,
+ module: "loops",
+ },
+ Lint {
+ name: "while_let_on_iterator",
+ group: "style",
+ desc: "using a while-let loop instead of a for loop on an iterator",
+ deprecation: None,
+ module: "loops",
+ },
+ Lint {
+ name: "wildcard_dependencies",
+ group: "cargo",
+ desc: "wildcard dependencies being used",
+ deprecation: None,
+ module: "wildcard_dependencies",
+ },
+ Lint {
+ name: "wildcard_enum_match_arm",
+ group: "restriction",
+ desc: "a wildcard enum match arm using `_`",
+ deprecation: None,
+ module: "matches",
+ },
+ Lint {
+ name: "wildcard_imports",
+ group: "pedantic",
+ desc: "lint `use _::*` statements",
+ deprecation: None,
+ module: "wildcard_imports",
+ },
+ Lint {
+ name: "wildcard_in_or_patterns",
+ group: "complexity",
+ desc: "a wildcard pattern used with others patterns in same match arm",
+ deprecation: None,
+ module: "matches",
+ },
+ Lint {
+ name: "write_literal",
+ group: "style",
+ desc: "writing a literal with a format string",
+ deprecation: None,
+ module: "write",
+ },
+ Lint {
+ name: "write_with_newline",
+ group: "style",
+ desc: "using `write!()` with a format string that ends in a single newline",
+ deprecation: None,
+ module: "write",
+ },
+ Lint {
+ name: "writeln_empty_string",
+ group: "style",
+ desc: "using `writeln!(buf, \"\")` with an empty string",
+ deprecation: None,
+ module: "write",
+ },
+ Lint {
+ name: "wrong_pub_self_convention",
+ group: "restriction",
+ desc: "defining a public method named with an established prefix (like \"into_\") that takes `self` with the wrong convention",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "wrong_self_convention",
+ group: "style",
+ desc: "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention",
+ deprecation: None,
+ module: "methods",
+ },
+ Lint {
+ name: "wrong_transmute",
+ group: "correctness",
+ desc: "transmutes that are confusing at best, undefined behaviour at worst and always useless",
+ deprecation: None,
+ module: "transmute",
+ },
+ Lint {
+ name: "zero_divided_by_zero",
+ group: "complexity",
+ desc: "usage of `0.0 / 0.0` to obtain NaN instead of `f32::NAN` or `f64::NAN`",
+ deprecation: None,
+ module: "zero_div_zero",
+ },
+ Lint {
+ name: "zero_prefixed_literal",
+ group: "complexity",
+ desc: "integer literals starting with `0`",
+ deprecation: None,
+ module: "misc_early",
+ },
+ Lint {
+ name: "zero_ptr",
+ group: "style",
+ desc: "using `0 as *{const, mut} T`",
+ deprecation: None,
+ module: "misc",
+ },
+ Lint {
+ name: "zero_width_space",
+ group: "correctness",
+ desc: "using a zero-width space in a string literal, which is confusing",
+ deprecation: None,
+ module: "unicode",
+ },
+ Lint {
+ name: "zst_offset",
+ group: "correctness",
+ desc: "Check for offset calculations on raw pointers to zero-sized types",
+ deprecation: None,
+ module: "methods",
+ },
+];
+// end lint list, do not remove this comment, it’s used in `update_lints`
+}
--- /dev/null
- error: this function has a large number of lines
++error: this function has too many lines (2/1)
+ --> $DIR/test.rs:18:1
+ |
+LL | / fn too_many_lines() {
+LL | | println!("This is bad.");
+LL | | println!("This is bad.");
+LL | | }
+ | |_^
+ |
+ = note: `-D clippy::too-many-lines` implied by `-D warnings`
+
- error: this function has a large number of lines
++error: this function has too many lines (2/1)
+ --> $DIR/test.rs:38:1
+ |
+LL | / fn comment_before_code() {
+LL | | let _ = "test";
+LL | | /* This comment extends to the front of
+LL | | the code but this line should still count. */ let _ = 5;
+LL | | }
+ | |_^
+
+error: aborting due to 2 previous errors
+
--- /dev/null
--- /dev/null
++// run-rustfix
++// edition:2018
++
++#![feature(async_closure)]
++#![warn(clippy::async_yields_async)]
++
++use core::future::Future;
++use core::pin::Pin;
++use core::task::{Context, Poll};
++
++struct CustomFutureType;
++
++impl Future for CustomFutureType {
++ type Output = u8;
++
++ fn poll(self: Pin<&mut Self>, _: &mut Context) -> Poll<Self::Output> {
++ Poll::Ready(3)
++ }
++}
++
++fn custom_future_type_ctor() -> CustomFutureType {
++ CustomFutureType
++}
++
++async fn f() -> CustomFutureType {
++ // Don't warn for functions since you have to explicitly declare their
++ // return types.
++ CustomFutureType
++}
++
++#[rustfmt::skip]
++fn main() {
++ let _f = {
++ 3
++ };
++ let _g = async {
++ 3
++ };
++ let _h = async {
++ async {
++ 3
++ }.await
++ };
++ let _i = async {
++ CustomFutureType.await
++ };
++ let _i = async || {
++ 3
++ };
++ let _j = async || {
++ async {
++ 3
++ }.await
++ };
++ let _k = async || {
++ CustomFutureType.await
++ };
++ let _l = async || CustomFutureType.await;
++ let _m = async || {
++ println!("I'm bored");
++ // Some more stuff
++
++ // Finally something to await
++ CustomFutureType.await
++ };
++ let _n = async || custom_future_type_ctor();
++ let _o = async || f();
++}
--- /dev/null
--- /dev/null
++// run-rustfix
++// edition:2018
++
++#![feature(async_closure)]
++#![warn(clippy::async_yields_async)]
++
++use core::future::Future;
++use core::pin::Pin;
++use core::task::{Context, Poll};
++
++struct CustomFutureType;
++
++impl Future for CustomFutureType {
++ type Output = u8;
++
++ fn poll(self: Pin<&mut Self>, _: &mut Context) -> Poll<Self::Output> {
++ Poll::Ready(3)
++ }
++}
++
++fn custom_future_type_ctor() -> CustomFutureType {
++ CustomFutureType
++}
++
++async fn f() -> CustomFutureType {
++ // Don't warn for functions since you have to explicitly declare their
++ // return types.
++ CustomFutureType
++}
++
++#[rustfmt::skip]
++fn main() {
++ let _f = {
++ 3
++ };
++ let _g = async {
++ 3
++ };
++ let _h = async {
++ async {
++ 3
++ }
++ };
++ let _i = async {
++ CustomFutureType
++ };
++ let _i = async || {
++ 3
++ };
++ let _j = async || {
++ async {
++ 3
++ }
++ };
++ let _k = async || {
++ CustomFutureType
++ };
++ let _l = async || CustomFutureType;
++ let _m = async || {
++ println!("I'm bored");
++ // Some more stuff
++
++ // Finally something to await
++ CustomFutureType
++ };
++ let _n = async || custom_future_type_ctor();
++ let _o = async || f();
++}
--- /dev/null
--- /dev/null
++error: an async construct yields a type which is itself awaitable
++ --> $DIR/async_yields_async.rs:40:9
++ |
++LL | let _h = async {
++ | ____________________-
++LL | | async {
++ | |_________^
++LL | || 3
++LL | || }
++ | ||_________^ awaitable value not awaited
++LL | | };
++ | |_____- outer async construct
++ |
++ = note: `-D clippy::async-yields-async` implied by `-D warnings`
++help: consider awaiting this value
++ |
++LL | async {
++LL | 3
++LL | }.await
++ |
++
++error: an async construct yields a type which is itself awaitable
++ --> $DIR/async_yields_async.rs:45:9
++ |
++LL | let _i = async {
++ | ____________________-
++LL | | CustomFutureType
++ | | ^^^^^^^^^^^^^^^^
++ | | |
++ | | awaitable value not awaited
++ | | help: consider awaiting this value: `CustomFutureType.await`
++LL | | };
++ | |_____- outer async construct
++
++error: an async construct yields a type which is itself awaitable
++ --> $DIR/async_yields_async.rs:51:9
++ |
++LL | let _j = async || {
++ | _______________________-
++LL | | async {
++ | |_________^
++LL | || 3
++LL | || }
++ | ||_________^ awaitable value not awaited
++LL | | };
++ | |_____- outer async construct
++ |
++help: consider awaiting this value
++ |
++LL | async {
++LL | 3
++LL | }.await
++ |
++
++error: an async construct yields a type which is itself awaitable
++ --> $DIR/async_yields_async.rs:56:9
++ |
++LL | let _k = async || {
++ | _______________________-
++LL | | CustomFutureType
++ | | ^^^^^^^^^^^^^^^^
++ | | |
++ | | awaitable value not awaited
++ | | help: consider awaiting this value: `CustomFutureType.await`
++LL | | };
++ | |_____- outer async construct
++
++error: an async construct yields a type which is itself awaitable
++ --> $DIR/async_yields_async.rs:58:23
++ |
++LL | let _l = async || CustomFutureType;
++ | ^^^^^^^^^^^^^^^^
++ | |
++ | outer async construct
++ | awaitable value not awaited
++ | help: consider awaiting this value: `CustomFutureType.await`
++
++error: an async construct yields a type which is itself awaitable
++ --> $DIR/async_yields_async.rs:64:9
++ |
++LL | let _m = async || {
++ | _______________________-
++LL | | println!("I'm bored");
++LL | | // Some more stuff
++LL | |
++LL | | // Finally something to await
++LL | | CustomFutureType
++ | | ^^^^^^^^^^^^^^^^
++ | | |
++ | | awaitable value not awaited
++ | | help: consider awaiting this value: `CustomFutureType.await`
++LL | | };
++ | |_____- outer async construct
++
++error: aborting due to 6 previous errors
++
--- /dev/null
+// run-rustfix
+#![allow(clippy::assertions_on_constants)]
+
+#[rustfmt::skip]
+#[warn(clippy::collapsible_if)]
+fn main() {
+ let x = "hello";
+ let y = "world";
+ if x == "hello" && y == "world" {
+ println!("Hello world!");
+ }
+
+ if (x == "hello" || x == "world") && (y == "world" || y == "hello") {
+ println!("Hello world!");
+ }
+
+ if x == "hello" && x == "world" && (y == "world" || y == "hello") {
+ println!("Hello world!");
+ }
+
+ if (x == "hello" || x == "world") && y == "world" && y == "hello" {
+ println!("Hello world!");
+ }
+
+ if x == "hello" && x == "world" && y == "world" && y == "hello" {
+ println!("Hello world!");
+ }
+
+ if 42 == 1337 && 'a' != 'A' {
+ println!("world!")
+ }
+
+ // Works because any if with an else statement cannot be collapsed.
+ if x == "hello" {
+ if y == "world" {
+ println!("Hello world!");
+ }
+ } else {
+ println!("Not Hello world");
+ }
+
+ if x == "hello" {
+ if y == "world" {
+ println!("Hello world!");
+ } else {
+ println!("Hello something else");
+ }
+ }
+
+ if x == "hello" {
+ print!("Hello ");
+ if y == "world" {
+ println!("world!")
+ }
+ }
+
+ if true {
+ } else {
+ assert!(true); // assert! is just an `if`
+ }
+
+
+ // The following tests check for the fix of https://github.com/rust-lang/rust-clippy/issues/798
+ if x == "hello" {// Not collapsible
+ if y == "world" {
+ println!("Hello world!");
+ }
+ }
+
+ if x == "hello" { // Not collapsible
+ if y == "world" {
+ println!("Hello world!");
+ }
+ }
+
+ if x == "hello" {
+ // Not collapsible
+ if y == "world" {
+ println!("Hello world!");
+ }
+ }
+
+ if x == "hello" && y == "world" { // Collapsible
+ println!("Hello world!");
+ }
+
+ if x == "hello" {
+ print!("Hello ");
+ } else {
+ // Not collapsible
+ if y == "world" {
+ println!("world!")
+ }
+ }
+
+ if x == "hello" {
+ print!("Hello ");
+ } else {
+ // Not collapsible
+ if let Some(42) = Some(42) {
+ println!("world!")
+ }
+ }
+
+ if x == "hello" {
+ /* Not collapsible */
+ if y == "world" {
+ println!("Hello world!");
+ }
+ }
+
+ if x == "hello" { /* Not collapsible */
+ if y == "world" {
+ println!("Hello world!");
+ }
+ }
+
+ // Test behavior wrt. `let_chains`.
+ // None of the cases below should be collapsed.
+ fn truth() -> bool { true }
+
+ // Prefix:
+ if let 0 = 1 {
+ if truth() {}
+ }
+
+ // Suffix:
+ if truth() {
+ if let 0 = 1 {}
+ }
+
+ // Midfix:
+ if truth() {
+ if let 0 = 1 {
+ if truth() {}
+ }
+ }
++
++ // Fix #5962
++ if matches!(true, true) && matches!(true, true) {}
+}
--- /dev/null
+// run-rustfix
+#![allow(clippy::assertions_on_constants)]
+
+#[rustfmt::skip]
+#[warn(clippy::collapsible_if)]
+fn main() {
+ let x = "hello";
+ let y = "world";
+ if x == "hello" {
+ if y == "world" {
+ println!("Hello world!");
+ }
+ }
+
+ if x == "hello" || x == "world" {
+ if y == "world" || y == "hello" {
+ println!("Hello world!");
+ }
+ }
+
+ if x == "hello" && x == "world" {
+ if y == "world" || y == "hello" {
+ println!("Hello world!");
+ }
+ }
+
+ if x == "hello" || x == "world" {
+ if y == "world" && y == "hello" {
+ println!("Hello world!");
+ }
+ }
+
+ if x == "hello" && x == "world" {
+ if y == "world" && y == "hello" {
+ println!("Hello world!");
+ }
+ }
+
+ if 42 == 1337 {
+ if 'a' != 'A' {
+ println!("world!")
+ }
+ }
+
+ // Works because any if with an else statement cannot be collapsed.
+ if x == "hello" {
+ if y == "world" {
+ println!("Hello world!");
+ }
+ } else {
+ println!("Not Hello world");
+ }
+
+ if x == "hello" {
+ if y == "world" {
+ println!("Hello world!");
+ } else {
+ println!("Hello something else");
+ }
+ }
+
+ if x == "hello" {
+ print!("Hello ");
+ if y == "world" {
+ println!("world!")
+ }
+ }
+
+ if true {
+ } else {
+ assert!(true); // assert! is just an `if`
+ }
+
+
+ // The following tests check for the fix of https://github.com/rust-lang/rust-clippy/issues/798
+ if x == "hello" {// Not collapsible
+ if y == "world" {
+ println!("Hello world!");
+ }
+ }
+
+ if x == "hello" { // Not collapsible
+ if y == "world" {
+ println!("Hello world!");
+ }
+ }
+
+ if x == "hello" {
+ // Not collapsible
+ if y == "world" {
+ println!("Hello world!");
+ }
+ }
+
+ if x == "hello" {
+ if y == "world" { // Collapsible
+ println!("Hello world!");
+ }
+ }
+
+ if x == "hello" {
+ print!("Hello ");
+ } else {
+ // Not collapsible
+ if y == "world" {
+ println!("world!")
+ }
+ }
+
+ if x == "hello" {
+ print!("Hello ");
+ } else {
+ // Not collapsible
+ if let Some(42) = Some(42) {
+ println!("world!")
+ }
+ }
+
+ if x == "hello" {
+ /* Not collapsible */
+ if y == "world" {
+ println!("Hello world!");
+ }
+ }
+
+ if x == "hello" { /* Not collapsible */
+ if y == "world" {
+ println!("Hello world!");
+ }
+ }
+
+ // Test behavior wrt. `let_chains`.
+ // None of the cases below should be collapsed.
+ fn truth() -> bool { true }
+
+ // Prefix:
+ if let 0 = 1 {
+ if truth() {}
+ }
+
+ // Suffix:
+ if truth() {
+ if let 0 = 1 {}
+ }
+
+ // Midfix:
+ if truth() {
+ if let 0 = 1 {
+ if truth() {}
+ }
+ }
++
++ // Fix #5962
++ if matches!(true, true) {
++ if matches!(true, true) {}
++ }
+}
--- /dev/null
- error: aborting due to 7 previous errors
+error: this `if` statement can be collapsed
+ --> $DIR/collapsible_if.rs:9:5
+ |
+LL | / if x == "hello" {
+LL | | if y == "world" {
+LL | | println!("Hello world!");
+LL | | }
+LL | | }
+ | |_____^
+ |
+ = note: `-D clippy::collapsible-if` implied by `-D warnings`
+help: collapse nested if block
+ |
+LL | if x == "hello" && y == "world" {
+LL | println!("Hello world!");
+LL | }
+ |
+
+error: this `if` statement can be collapsed
+ --> $DIR/collapsible_if.rs:15:5
+ |
+LL | / if x == "hello" || x == "world" {
+LL | | if y == "world" || y == "hello" {
+LL | | println!("Hello world!");
+LL | | }
+LL | | }
+ | |_____^
+ |
+help: collapse nested if block
+ |
+LL | if (x == "hello" || x == "world") && (y == "world" || y == "hello") {
+LL | println!("Hello world!");
+LL | }
+ |
+
+error: this `if` statement can be collapsed
+ --> $DIR/collapsible_if.rs:21:5
+ |
+LL | / if x == "hello" && x == "world" {
+LL | | if y == "world" || y == "hello" {
+LL | | println!("Hello world!");
+LL | | }
+LL | | }
+ | |_____^
+ |
+help: collapse nested if block
+ |
+LL | if x == "hello" && x == "world" && (y == "world" || y == "hello") {
+LL | println!("Hello world!");
+LL | }
+ |
+
+error: this `if` statement can be collapsed
+ --> $DIR/collapsible_if.rs:27:5
+ |
+LL | / if x == "hello" || x == "world" {
+LL | | if y == "world" && y == "hello" {
+LL | | println!("Hello world!");
+LL | | }
+LL | | }
+ | |_____^
+ |
+help: collapse nested if block
+ |
+LL | if (x == "hello" || x == "world") && y == "world" && y == "hello" {
+LL | println!("Hello world!");
+LL | }
+ |
+
+error: this `if` statement can be collapsed
+ --> $DIR/collapsible_if.rs:33:5
+ |
+LL | / if x == "hello" && x == "world" {
+LL | | if y == "world" && y == "hello" {
+LL | | println!("Hello world!");
+LL | | }
+LL | | }
+ | |_____^
+ |
+help: collapse nested if block
+ |
+LL | if x == "hello" && x == "world" && y == "world" && y == "hello" {
+LL | println!("Hello world!");
+LL | }
+ |
+
+error: this `if` statement can be collapsed
+ --> $DIR/collapsible_if.rs:39:5
+ |
+LL | / if 42 == 1337 {
+LL | | if 'a' != 'A' {
+LL | | println!("world!")
+LL | | }
+LL | | }
+ | |_____^
+ |
+help: collapse nested if block
+ |
+LL | if 42 == 1337 && 'a' != 'A' {
+LL | println!("world!")
+LL | }
+ |
+
+error: this `if` statement can be collapsed
+ --> $DIR/collapsible_if.rs:95:5
+ |
+LL | / if x == "hello" {
+LL | | if y == "world" { // Collapsible
+LL | | println!("Hello world!");
+LL | | }
+LL | | }
+ | |_____^
+ |
+help: collapse nested if block
+ |
+LL | if x == "hello" && y == "world" { // Collapsible
+LL | println!("Hello world!");
+LL | }
+ |
+
++error: this `if` statement can be collapsed
++ --> $DIR/collapsible_if.rs:154:5
++ |
++LL | / if matches!(true, true) {
++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
+
--- /dev/null
--- /dev/null
++// run-rustfix
++#![allow(unused_must_use)]
++#![warn(clippy::create_dir)]
++
++use std::fs::create_dir_all;
++
++fn create_dir() {}
++
++fn main() {
++ // Should be warned
++ create_dir_all("foo");
++ create_dir_all("bar").unwrap();
++
++ // Shouldn't be warned
++ create_dir();
++ std::fs::create_dir_all("foobar");
++}
--- /dev/null
--- /dev/null
++// run-rustfix
++#![allow(unused_must_use)]
++#![warn(clippy::create_dir)]
++
++use std::fs::create_dir_all;
++
++fn create_dir() {}
++
++fn main() {
++ // Should be warned
++ std::fs::create_dir("foo");
++ std::fs::create_dir("bar").unwrap();
++
++ // Shouldn't be warned
++ create_dir();
++ std::fs::create_dir_all("foobar");
++}
--- /dev/null
--- /dev/null
++error: calling `std::fs::create_dir` where there may be a better way
++ --> $DIR/create_dir.rs:11:5
++ |
++LL | std::fs::create_dir("foo");
++ | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider calling `std::fs::create_dir_all` instead: `create_dir_all("foo")`
++ |
++ = note: `-D clippy::create-dir` implied by `-D warnings`
++
++error: calling `std::fs::create_dir` where there may be a better way
++ --> $DIR/create_dir.rs:12:5
++ |
++LL | std::fs::create_dir("bar").unwrap();
++ | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider calling `std::fs::create_dir_all` instead: `create_dir_all("bar")`
++
++error: aborting due to 2 previous errors
++
--- /dev/null
--- /dev/null
++// run-rustfix
++
++#![allow(unused_imports)]
++#![deny(clippy::default_trait_access)]
++
++use std::default;
++use std::default::Default as D2;
++use std::string;
++
++fn main() {
++ let s1: String = std::string::String::default();
++
++ let s2 = String::default();
++
++ let s3: String = std::string::String::default();
++
++ let s4: String = std::string::String::default();
++
++ let s5 = string::String::default();
++
++ let s6: String = std::string::String::default();
++
++ let s7 = std::string::String::default();
++
++ let s8: String = DefaultFactory::make_t_badly();
++
++ let s9: String = DefaultFactory::make_t_nicely();
++
++ let s10 = DerivedDefault::default();
++
++ let s11: GenericDerivedDefault<String> = GenericDerivedDefault::default();
++
++ let s12 = GenericDerivedDefault::<String>::default();
++
++ let s13 = TupleDerivedDefault::default();
++
++ let s14: TupleDerivedDefault = TupleDerivedDefault::default();
++
++ let s15: ArrayDerivedDefault = ArrayDerivedDefault::default();
++
++ let s16 = ArrayDerivedDefault::default();
++
++ let s17: TupleStructDerivedDefault = TupleStructDerivedDefault::default();
++
++ let s18 = TupleStructDerivedDefault::default();
++
++ let s19 = <DerivedDefault as Default>::default();
++
++ println!(
++ "[{}] [{}] [{}] [{}] [{}] [{}] [{}] [{}] [{}] [{:?}] [{:?}] [{:?}] [{:?}] [{:?}] [{:?}] [{:?}] [{:?}] [{:?}], [{:?}]",
++ s1,
++ s2,
++ s3,
++ s4,
++ s5,
++ s6,
++ s7,
++ s8,
++ s9,
++ s10,
++ s11,
++ s12,
++ s13,
++ s14,
++ s15,
++ s16,
++ s17,
++ s18,
++ s19,
++ );
++}
++
++struct DefaultFactory;
++
++impl DefaultFactory {
++ pub fn make_t_badly<T: Default>() -> T {
++ Default::default()
++ }
++
++ pub fn make_t_nicely<T: Default>() -> T {
++ T::default()
++ }
++}
++
++#[derive(Debug, Default)]
++struct DerivedDefault {
++ pub s: String,
++}
++
++#[derive(Debug, Default)]
++struct GenericDerivedDefault<T: Default + std::fmt::Debug> {
++ pub s: T,
++}
++
++#[derive(Debug, Default)]
++struct TupleDerivedDefault {
++ pub s: (String, String),
++}
++
++#[derive(Debug, Default)]
++struct ArrayDerivedDefault {
++ pub s: [String; 10],
++}
++
++#[derive(Debug, Default)]
++struct TupleStructDerivedDefault(String);
--- /dev/null
- #![warn(clippy::default_trait_access)]
++// run-rustfix
++
++#![allow(unused_imports)]
++#![deny(clippy::default_trait_access)]
+
+use std::default;
+use std::default::Default as D2;
+use std::string;
+
+fn main() {
+ let s1: String = Default::default();
+
+ let s2 = String::default();
+
+ let s3: String = D2::default();
+
+ let s4: String = std::default::Default::default();
+
+ let s5 = string::String::default();
+
+ let s6: String = default::Default::default();
+
+ let s7 = std::string::String::default();
+
+ let s8: String = DefaultFactory::make_t_badly();
+
+ let s9: String = DefaultFactory::make_t_nicely();
+
+ let s10 = DerivedDefault::default();
+
+ let s11: GenericDerivedDefault<String> = Default::default();
+
+ let s12 = GenericDerivedDefault::<String>::default();
+
+ let s13 = TupleDerivedDefault::default();
+
+ let s14: TupleDerivedDefault = Default::default();
+
+ let s15: ArrayDerivedDefault = Default::default();
+
+ let s16 = ArrayDerivedDefault::default();
+
+ let s17: TupleStructDerivedDefault = Default::default();
+
+ let s18 = TupleStructDerivedDefault::default();
+
+ let s19 = <DerivedDefault as Default>::default();
+
+ println!(
+ "[{}] [{}] [{}] [{}] [{}] [{}] [{}] [{}] [{}] [{:?}] [{:?}] [{:?}] [{:?}] [{:?}] [{:?}] [{:?}] [{:?}] [{:?}], [{:?}]",
+ s1,
+ s2,
+ s3,
+ s4,
+ s5,
+ s6,
+ s7,
+ s8,
+ s9,
+ s10,
+ s11,
+ s12,
+ s13,
+ s14,
+ s15,
+ s16,
+ s17,
+ s18,
+ s19,
+ );
+}
+
+struct DefaultFactory;
+
+impl DefaultFactory {
+ pub fn make_t_badly<T: Default>() -> T {
+ Default::default()
+ }
+
+ pub fn make_t_nicely<T: Default>() -> T {
+ T::default()
+ }
+}
+
+#[derive(Debug, Default)]
+struct DerivedDefault {
+ pub s: String,
+}
+
+#[derive(Debug, Default)]
+struct GenericDerivedDefault<T: Default + std::fmt::Debug> {
+ pub s: T,
+}
+
+#[derive(Debug, Default)]
+struct TupleDerivedDefault {
+ pub s: (String, String),
+}
+
+#[derive(Debug, Default)]
+struct ArrayDerivedDefault {
+ pub s: [String; 10],
+}
+
+#[derive(Debug, Default)]
+struct TupleStructDerivedDefault(String);
--- /dev/null
- --> $DIR/default_trait_access.rs:8:22
+error: calling `std::string::String::default()` is more clear than this expression
- = note: `-D clippy::default-trait-access` implied by `-D warnings`
++ --> $DIR/default_trait_access.rs:11:22
+ |
+LL | let s1: String = Default::default();
+ | ^^^^^^^^^^^^^^^^^^ help: try: `std::string::String::default()`
+ |
- --> $DIR/default_trait_access.rs:12:22
++note: the lint level is defined here
++ --> $DIR/default_trait_access.rs:4:9
++ |
++LL | #![deny(clippy::default_trait_access)]
++ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+error: calling `std::string::String::default()` is more clear than this expression
- --> $DIR/default_trait_access.rs:14:22
++ --> $DIR/default_trait_access.rs:15:22
+ |
+LL | let s3: String = D2::default();
+ | ^^^^^^^^^^^^^ help: try: `std::string::String::default()`
+
+error: calling `std::string::String::default()` is more clear than this expression
- --> $DIR/default_trait_access.rs:18:22
++ --> $DIR/default_trait_access.rs:17:22
+ |
+LL | let s4: String = std::default::Default::default();
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `std::string::String::default()`
+
+error: calling `std::string::String::default()` is more clear than this expression
- error: calling `GenericDerivedDefault<std::string::String>::default()` is more clear than this expression
- --> $DIR/default_trait_access.rs:28:46
++ --> $DIR/default_trait_access.rs:21:22
+ |
+LL | let s6: String = default::Default::default();
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `std::string::String::default()`
+
- | ^^^^^^^^^^^^^^^^^^ help: try: `GenericDerivedDefault<std::string::String>::default()`
++error: calling `GenericDerivedDefault::default()` is more clear than this expression
++ --> $DIR/default_trait_access.rs:31:46
+ |
+LL | let s11: GenericDerivedDefault<String> = Default::default();
- --> $DIR/default_trait_access.rs:34:36
++ | ^^^^^^^^^^^^^^^^^^ help: try: `GenericDerivedDefault::default()`
+
+error: calling `TupleDerivedDefault::default()` is more clear than this expression
- --> $DIR/default_trait_access.rs:36:36
++ --> $DIR/default_trait_access.rs:37:36
+ |
+LL | let s14: TupleDerivedDefault = Default::default();
+ | ^^^^^^^^^^^^^^^^^^ help: try: `TupleDerivedDefault::default()`
+
+error: calling `ArrayDerivedDefault::default()` is more clear than this expression
- --> $DIR/default_trait_access.rs:40:42
++ --> $DIR/default_trait_access.rs:39:36
+ |
+LL | let s15: ArrayDerivedDefault = Default::default();
+ | ^^^^^^^^^^^^^^^^^^ help: try: `ArrayDerivedDefault::default()`
+
+error: calling `TupleStructDerivedDefault::default()` is more clear than this expression
++ --> $DIR/default_trait_access.rs:43:42
+ |
+LL | let s17: TupleStructDerivedDefault = Default::default();
+ | ^^^^^^^^^^^^^^^^^^ help: try: `TupleStructDerivedDefault::default()`
+
+error: aborting due to 8 previous errors
+
--- /dev/null
- /// Ok: CamelCase (It should not be surrounded by backticks)
- fn issue_2395() {}
-
+//! This file tests for the `DOC_MARKDOWN` lint.
+
+#![allow(dead_code)]
+#![warn(clippy::doc_markdown)]
+#![feature(custom_inner_attributes)]
+#![rustfmt::skip]
+
+/// The foo_bar function does _nothing_. See also foo::bar. (note the dot there)
+/// Markdown is _weird_. I mean _really weird_. This \_ is ok. So is `_`. But not Foo::some_fun
+/// which should be reported only once despite being __doubly bad__.
+/// Here be ::a::global:path.
+/// That's not code ~NotInCodeBlock~.
+/// be_sure_we_got_to_the_end_of_it
+fn foo_bar() {
+}
+
+/// That one tests multiline ticks.
+/// ```rust
+/// foo_bar FOO_BAR
+/// _foo bar_
+/// ```
+///
+/// ~~~rust
+/// foo_bar FOO_BAR
+/// _foo bar_
+/// ~~~
+/// be_sure_we_got_to_the_end_of_it
+fn multiline_codeblock() {
+}
+
+/// This _is a test for
+/// multiline
+/// emphasis_.
+/// be_sure_we_got_to_the_end_of_it
+fn test_emphasis() {
+}
+
+/// This tests units. See also #835.
+/// kiB MiB GiB TiB PiB EiB
+/// kib Mib Gib Tib Pib Eib
+/// kB MB GB TB PB EB
+/// kb Mb Gb Tb Pb Eb
+/// 32kiB 32MiB 32GiB 32TiB 32PiB 32EiB
+/// 32kib 32Mib 32Gib 32Tib 32Pib 32Eib
+/// 32kB 32MB 32GB 32TB 32PB 32EB
+/// 32kb 32Mb 32Gb 32Tb 32Pb 32Eb
+/// NaN
+/// be_sure_we_got_to_the_end_of_it
+fn test_units() {
+}
+
++/// This tests allowed identifiers.
++/// DirectX
++/// ECMAScript
++/// OAuth GraphQL
++/// TeX LaTeX BibTeX BibLaTeX
++/// CamelCase (see also #2395)
++/// be_sure_we_got_to_the_end_of_it
++fn test_allowed() {
++}
++
+/// This test has [a link_with_underscores][chunked-example] inside it. See #823.
+/// See also [the issue tracker](https://github.com/rust-lang/rust-clippy/search?q=clippy::doc_markdown&type=Issues)
+/// on GitHub (which is a camel-cased word, but is OK). And here is another [inline link][inline_link].
+/// It can also be [inline_link2].
+///
+/// [chunked-example]: https://en.wikipedia.org/wiki/Chunked_transfer_encoding#Example
+/// [inline_link]: https://foobar
+/// [inline_link2]: https://foobar
+/// The `main` function is the entry point of the program. Here it only calls the `foo_bar` and
+/// `multiline_ticks` functions.
+///
+/// expression of the type `_ <bit_op> m <cmp_op> c` (where `<bit_op>`
+/// is one of {`&`, '|'} and `<cmp_op>` is one of {`!=`, `>=`, `>` ,
+/// be_sure_we_got_to_the_end_of_it
+fn main() {
+ foo_bar();
+ multiline_codeblock();
+ test_emphasis();
+ test_units();
+}
+
+/// ## CamelCaseThing
+/// Talks about `CamelCaseThing`. Titles should be ignored; see issue #897.
+///
+/// # CamelCaseThing
+///
+/// Not a title #897 CamelCaseThing
+/// be_sure_we_got_to_the_end_of_it
+fn issue897() {
+}
+
+/// I am confused by brackets? (`x_y`)
+/// I am confused by brackets? (foo `x_y`)
+/// I am confused by brackets? (`x_y` foo)
+/// be_sure_we_got_to_the_end_of_it
+fn issue900() {
+}
+
+/// Diesel queries also have a similar problem to [Iterator][iterator], where
+/// /// More talking
+/// returning them from a function requires exposing the implementation of that
+/// function. The [`helper_types`][helper_types] module exists to help with this,
+/// but you might want to hide the return type or have it conditionally change.
+/// Boxing can achieve both.
+///
+/// [iterator]: https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html
+/// [helper_types]: ../helper_types/index.html
+/// be_sure_we_got_to_the_end_of_it
+fn issue883() {
+}
+
+/// `foo_bar
+/// baz_quz`
+/// [foo
+/// bar](https://doc.rust-lang.org/stable/std/iter/trait.IteratorFooBar.html)
+fn multiline() {
+}
+
+/** E.g., serialization of an empty list: FooBar
+```
+That's in a code block: `PackedNode`
+```
+
+And BarQuz too.
+be_sure_we_got_to_the_end_of_it
+*/
+fn issue1073() {
+}
+
+/** E.g., serialization of an empty list: FooBar
+```
+That's in a code block: PackedNode
+```
+
+And BarQuz too.
+be_sure_we_got_to_the_end_of_it
+*/
+fn issue1073_alt() {
+}
+
+/// Tests more than three quotes:
+/// ````
+/// DoNotWarn
+/// ```
+/// StillDont
+/// ````
+/// be_sure_we_got_to_the_end_of_it
+fn four_quotes() {
+}
+
+/// See [NIST SP 800-56A, revision 2].
+///
+/// [NIST SP 800-56A, revision 2]:
+/// https://github.com/rust-lang/rust-clippy/issues/902#issuecomment-261919419
+fn issue_902_comment() {}
+
+#[cfg_attr(feature = "a", doc = " ```")]
+#[cfg_attr(not(feature = "a"), doc = " ```ignore")]
+/// fn main() {
+/// let s = "localhost:10000".to_string();
+/// println!("{}", s);
+/// }
+/// ```
+fn issue_1469() {}
+
+/**
+ * This is a doc comment that should not be a list
+ *This would also be an error under a strict common mark interpretation
+ */
+fn issue_1920() {}
+
+/// Ok: <http://www.unicode.org/reports/tr9/#Reordering_Resolved_Levels>
+///
+/// Not ok: http://www.unicode.org
+/// Not ok: https://www.unicode.org
+/// Not ok: http://www.unicode.org/
+/// Not ok: http://www.unicode.org/reports/tr9/#Reordering_Resolved_Levels
+fn issue_1832() {}
+
+/// An iterator over mycrate::Collection's values.
+/// It should not lint a `'static` lifetime in ticks.
+fn issue_2210() {}
+
+/// This should not cause the lint to trigger:
+/// #REQ-data-family.lint_partof_exists
+fn issue_2343() {}
+
+/// This should not cause an ICE:
+/// __|_ _|__||_|
+fn pulldown_cmark_crash() {}
--- /dev/null
- --> $DIR/doc.rs:52:22
+error: you should put `foo_bar` between ticks in the documentation
+ --> $DIR/doc.rs:8:9
+ |
+LL | /// The foo_bar function does _nothing_. See also foo::bar. (note the dot there)
+ | ^^^^^^^
+ |
+ = note: `-D clippy::doc-markdown` implied by `-D warnings`
+
+error: you should put `foo::bar` between ticks in the documentation
+ --> $DIR/doc.rs:8:51
+ |
+LL | /// The foo_bar function does _nothing_. See also foo::bar. (note the dot there)
+ | ^^^^^^^^
+
+error: you should put `Foo::some_fun` between ticks in the documentation
+ --> $DIR/doc.rs:9:83
+ |
+LL | /// Markdown is _weird_. I mean _really weird_. This /_ is ok. So is `_`. But not Foo::some_fun
+ | ^^^^^^^^^^^^^
+
+error: you should put `a::global:path` between ticks in the documentation
+ --> $DIR/doc.rs:11:15
+ |
+LL | /// Here be ::a::global:path.
+ | ^^^^^^^^^^^^^^
+
+error: you should put `NotInCodeBlock` between ticks in the documentation
+ --> $DIR/doc.rs:12:22
+ |
+LL | /// That's not code ~NotInCodeBlock~.
+ | ^^^^^^^^^^^^^^
+
+error: you should put `be_sure_we_got_to_the_end_of_it` between ticks in the documentation
+ --> $DIR/doc.rs:13:5
+ |
+LL | /// be_sure_we_got_to_the_end_of_it
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+error: you should put `be_sure_we_got_to_the_end_of_it` between ticks in the documentation
+ --> $DIR/doc.rs:27:5
+ |
+LL | /// be_sure_we_got_to_the_end_of_it
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+error: you should put `be_sure_we_got_to_the_end_of_it` between ticks in the documentation
+ --> $DIR/doc.rs:34:5
+ |
+LL | /// be_sure_we_got_to_the_end_of_it
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+error: you should put `be_sure_we_got_to_the_end_of_it` between ticks in the documentation
+ --> $DIR/doc.rs:48:5
+ |
+LL | /// be_sure_we_got_to_the_end_of_it
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
++error: you should put `be_sure_we_got_to_the_end_of_it` between ticks in the documentation
++ --> $DIR/doc.rs:58:5
++ |
++LL | /// be_sure_we_got_to_the_end_of_it
++ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
++
+error: you should put `link_with_underscores` between ticks in the documentation
- --> $DIR/doc.rs:55:21
++ --> $DIR/doc.rs:62:22
+ |
+LL | /// This test has [a link_with_underscores][chunked-example] inside it. See #823.
+ | ^^^^^^^^^^^^^^^^^^^^^
+
+error: you should put `inline_link2` between ticks in the documentation
- --> $DIR/doc.rs:65:5
++ --> $DIR/doc.rs:65:21
+ |
+LL | /// It can also be [inline_link2].
+ | ^^^^^^^^^^^^
+
+error: you should put `be_sure_we_got_to_the_end_of_it` between ticks in the documentation
- --> $DIR/doc.rs:73:8
++ --> $DIR/doc.rs:75:5
+ |
+LL | /// be_sure_we_got_to_the_end_of_it
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+error: you should put `CamelCaseThing` between ticks in the documentation
- --> $DIR/doc.rs:76:7
++ --> $DIR/doc.rs:83:8
+ |
+LL | /// ## CamelCaseThing
+ | ^^^^^^^^^^^^^^
+
+error: you should put `CamelCaseThing` between ticks in the documentation
- --> $DIR/doc.rs:78:22
++ --> $DIR/doc.rs:86:7
+ |
+LL | /// # CamelCaseThing
+ | ^^^^^^^^^^^^^^
+
+error: you should put `CamelCaseThing` between ticks in the documentation
- --> $DIR/doc.rs:79:5
++ --> $DIR/doc.rs:88:22
+ |
+LL | /// Not a title #897 CamelCaseThing
+ | ^^^^^^^^^^^^^^
+
+error: you should put `be_sure_we_got_to_the_end_of_it` between ticks in the documentation
- --> $DIR/doc.rs:86:5
++ --> $DIR/doc.rs:89:5
+ |
+LL | /// be_sure_we_got_to_the_end_of_it
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+error: you should put `be_sure_we_got_to_the_end_of_it` between ticks in the documentation
- --> $DIR/doc.rs:99:5
++ --> $DIR/doc.rs:96:5
+ |
+LL | /// be_sure_we_got_to_the_end_of_it
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+error: you should put `be_sure_we_got_to_the_end_of_it` between ticks in the documentation
- --> $DIR/doc.rs:110:43
++ --> $DIR/doc.rs:109:5
+ |
+LL | /// be_sure_we_got_to_the_end_of_it
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+error: you should put `FooBar` between ticks in the documentation
- --> $DIR/doc.rs:115:5
++ --> $DIR/doc.rs:120:43
+ |
+LL | /** E.g., serialization of an empty list: FooBar
+ | ^^^^^^
+
+error: you should put `BarQuz` between ticks in the documentation
- --> $DIR/doc.rs:116:1
++ --> $DIR/doc.rs:125:5
+ |
+LL | And BarQuz too.
+ | ^^^^^^
+
+error: you should put `be_sure_we_got_to_the_end_of_it` between ticks in the documentation
- --> $DIR/doc.rs:121:43
++ --> $DIR/doc.rs:126:1
+ |
+LL | be_sure_we_got_to_the_end_of_it
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+error: you should put `FooBar` between ticks in the documentation
- --> $DIR/doc.rs:126:5
++ --> $DIR/doc.rs:131:43
+ |
+LL | /** E.g., serialization of an empty list: FooBar
+ | ^^^^^^
+
+error: you should put `BarQuz` between ticks in the documentation
- --> $DIR/doc.rs:127:1
++ --> $DIR/doc.rs:136:5
+ |
+LL | And BarQuz too.
+ | ^^^^^^
+
+error: you should put `be_sure_we_got_to_the_end_of_it` between ticks in the documentation
- --> $DIR/doc.rs:138:5
++ --> $DIR/doc.rs:137:1
+ |
+LL | be_sure_we_got_to_the_end_of_it
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+error: you should put `be_sure_we_got_to_the_end_of_it` between ticks in the documentation
- --> $DIR/doc.rs:165:13
++ --> $DIR/doc.rs:148:5
+ |
+LL | /// be_sure_we_got_to_the_end_of_it
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+error: you should put bare URLs between `<`/`>` or make a proper Markdown link
- --> $DIR/doc.rs:166:13
++ --> $DIR/doc.rs:175:13
+ |
+LL | /// Not ok: http://www.unicode.org
+ | ^^^^^^^^^^^^^^^^^^^^^^
+
+error: you should put bare URLs between `<`/`>` or make a proper Markdown link
- --> $DIR/doc.rs:167:13
++ --> $DIR/doc.rs:176:13
+ |
+LL | /// Not ok: https://www.unicode.org
+ | ^^^^^^^^^^^^^^^^^^^^^^^
+
+error: you should put bare URLs between `<`/`>` or make a proper Markdown link
- --> $DIR/doc.rs:168:13
++ --> $DIR/doc.rs:177:13
+ |
+LL | /// Not ok: http://www.unicode.org/
+ | ^^^^^^^^^^^^^^^^^^^^^^
+
+error: you should put bare URLs between `<`/`>` or make a proper Markdown link
- --> $DIR/doc.rs:174:22
++ --> $DIR/doc.rs:178:13
+ |
+LL | /// Not ok: http://www.unicode.org/reports/tr9/#Reordering_Resolved_Levels
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+error: you should put `mycrate::Collection` between ticks in the documentation
- error: aborting due to 30 previous errors
++ --> $DIR/doc.rs:181:22
+ |
+LL | /// An iterator over mycrate::Collection's values.
+ | ^^^^^^^^^^^^^^^^^^^
+
++error: aborting due to 31 previous errors
+
--- /dev/null
- error: this function has a large number of lines
++error: this function has too many lines (102/100)
+ --> $DIR/functions_maxlines.rs:58:1
+ |
+LL | / fn bad_lines() {
+LL | | println!("Dont get confused by braces: {{}}");
+LL | | println!("This is bad.");
+LL | | println!("This is bad.");
+... |
+LL | | println!("This is bad.");
+LL | | }
+ | |_^
+ |
+ = note: `-D clippy::too-many-lines` implied by `-D warnings`
+
+error: aborting due to previous error
+
--- /dev/null
- error: called `map(f)` on an `Option` value where `f` is a function that returns the unit type
++error: called `map(f)` on an `Option` value where `f` is a function that returns the unit type `()`
+ --> $DIR/option_map_unit_fn_fixable.rs:38:5
+ |
+LL | x.field.map(do_nothing);
+ | ^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Some(x_field) = x.field { do_nothing(x_field) }`
+ |
+ = note: `-D clippy::option-map-unit-fn` implied by `-D warnings`
+
- error: called `map(f)` on an `Option` value where `f` is a function that returns the unit type
++error: called `map(f)` on an `Option` value where `f` is a function that returns the unit type `()`
+ --> $DIR/option_map_unit_fn_fixable.rs:40:5
+ |
+LL | x.field.map(do_nothing);
+ | ^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Some(x_field) = x.field { do_nothing(x_field) }`
+
- error: called `map(f)` on an `Option` value where `f` is a function that returns the unit type
++error: called `map(f)` on an `Option` value where `f` is a function that returns the unit type `()`
+ --> $DIR/option_map_unit_fn_fixable.rs:42:5
+ |
+LL | x.field.map(diverge);
+ | ^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Some(x_field) = x.field { diverge(x_field) }`
+
- error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/option_map_unit_fn_fixable.rs:48:5
+ |
+LL | x.field.map(|value| x.do_option_nothing(value + captured));
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Some(value) = x.field { x.do_option_nothing(value + captured) }`
+
- error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/option_map_unit_fn_fixable.rs:50:5
+ |
+LL | x.field.map(|value| { x.do_option_plus_one(value + captured); });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Some(value) = x.field { x.do_option_plus_one(value + captured); }`
+
- error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/option_map_unit_fn_fixable.rs:53:5
+ |
+LL | x.field.map(|value| do_nothing(value + captured));
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Some(value) = x.field { do_nothing(value + captured) }`
+
- error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/option_map_unit_fn_fixable.rs:55:5
+ |
+LL | x.field.map(|value| { do_nothing(value + captured) });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Some(value) = x.field { do_nothing(value + captured) }`
+
- error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/option_map_unit_fn_fixable.rs:57:5
+ |
+LL | x.field.map(|value| { do_nothing(value + captured); });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Some(value) = x.field { do_nothing(value + captured); }`
+
- error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/option_map_unit_fn_fixable.rs:59:5
+ |
+LL | x.field.map(|value| { { do_nothing(value + captured); } });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Some(value) = x.field { do_nothing(value + captured); }`
+
- error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/option_map_unit_fn_fixable.rs:62:5
+ |
+LL | x.field.map(|value| diverge(value + captured));
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Some(value) = x.field { diverge(value + captured) }`
+
- error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/option_map_unit_fn_fixable.rs:64:5
+ |
+LL | x.field.map(|value| { diverge(value + captured) });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Some(value) = x.field { diverge(value + captured) }`
+
- error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/option_map_unit_fn_fixable.rs:66:5
+ |
+LL | x.field.map(|value| { diverge(value + captured); });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Some(value) = x.field { diverge(value + captured); }`
+
- error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/option_map_unit_fn_fixable.rs:68:5
+ |
+LL | x.field.map(|value| { { diverge(value + captured); } });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Some(value) = x.field { diverge(value + captured); }`
+
- error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/option_map_unit_fn_fixable.rs:73:5
+ |
+LL | x.field.map(|value| { let y = plus_one(value + captured); });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Some(value) = x.field { let y = plus_one(value + captured); }`
+
- error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/option_map_unit_fn_fixable.rs:75:5
+ |
+LL | x.field.map(|value| { plus_one(value + captured); });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Some(value) = x.field { plus_one(value + captured); }`
+
- error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/option_map_unit_fn_fixable.rs:77:5
+ |
+LL | x.field.map(|value| { { plus_one(value + captured); } });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Some(value) = x.field { plus_one(value + captured); }`
+
- error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Option` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/option_map_unit_fn_fixable.rs:80:5
+ |
+LL | x.field.map(|ref value| { do_nothing(value + captured) });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Some(ref value) = x.field { do_nothing(value + captured) }`
+
- error: called `map(f)` on an `Option` value where `f` is a function that returns the unit type
++error: called `map(f)` on an `Option` value where `f` is a function that returns the unit type `()`
+ --> $DIR/option_map_unit_fn_fixable.rs:82:5
+ |
+LL | option().map(do_nothing);}
+ | ^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Some(a) = option() { do_nothing(a) }`
+
+error: aborting due to 18 previous errors
+
--- /dev/null
- let mut map = HashMap::<u64, String>::new();
- map.entry(42).or_insert_with(String::new);
-
- let mut btree = BTreeMap::<u64, String>::new();
- btree.entry(42).or_insert_with(String::new);
-
+// run-rustfix
+
+#![warn(clippy::or_fun_call)]
+#![allow(dead_code)]
+
+use std::collections::BTreeMap;
+use std::collections::HashMap;
+use std::time::Duration;
+
+/// Checks implementation of the `OR_FUN_CALL` lint.
+fn or_fun_call() {
+ struct Foo;
+
+ impl Foo {
+ fn new() -> Foo {
+ Foo
+ }
+ }
+
+ enum Enum {
+ A(i32),
+ }
+
+ fn make<T>() -> T {
+ unimplemented!();
+ }
+
+ let with_enum = Some(Enum::A(1));
+ with_enum.unwrap_or(Enum::A(5));
+
+ let with_const_fn = Some(Duration::from_secs(1));
+ with_const_fn.unwrap_or_else(|| Duration::from_secs(5));
+
+ let with_constructor = Some(vec![1]);
+ with_constructor.unwrap_or_else(make);
+
+ let with_new = Some(vec![1]);
+ with_new.unwrap_or_default();
+
+ let with_const_args = Some(vec![1]);
+ with_const_args.unwrap_or_else(|| Vec::with_capacity(12));
+
+ let with_err: Result<_, ()> = Ok(vec![1]);
+ with_err.unwrap_or_else(|_| make());
+
+ let with_err_args: Result<_, ()> = Ok(vec![1]);
+ with_err_args.unwrap_or_else(|_| Vec::with_capacity(12));
+
+ let with_default_trait = Some(1);
+ with_default_trait.unwrap_or_default();
+
+ let with_default_type = Some(1);
+ with_default_type.unwrap_or_default();
+
+ let with_vec = Some(vec![1]);
+ with_vec.unwrap_or_default();
+
+ let without_default = Some(Foo);
+ without_default.unwrap_or_else(Foo::new);
+
+ let stringy = Some(String::from(""));
+ let _ = stringy.unwrap_or_else(|| "".to_owned());
+
+ let opt = Some(1);
+ let hello = "Hello";
+ let _ = opt.ok_or(format!("{} world.", hello));
+}
+
+struct Foo(u8);
+struct Bar(String, Duration);
+#[rustfmt::skip]
+fn test_or_with_ctors() {
+ let opt = Some(1);
+ let opt_opt = Some(Some(1));
+ // we also test for const promotion, this makes sure we don't hit that
+ let two = 2;
+
+ let _ = opt_opt.unwrap_or(Some(2));
+ let _ = opt_opt.unwrap_or(Some(two));
+ let _ = opt.ok_or(Some(2));
+ let _ = opt.ok_or(Some(two));
+ let _ = opt.ok_or(Foo(2));
+ let _ = opt.ok_or(Foo(two));
+ let _ = opt.or(Some(2));
+ let _ = opt.or(Some(two));
+
+ let _ = Some("a".to_string()).or_else(|| Some("b".to_string()));
+
+ let b = "b".to_string();
+ let _ = Some(Bar("a".to_string(), Duration::from_secs(1)))
+ .or_else(|| Some(Bar(b, Duration::from_secs(2))));
+
+ let vec = vec!["foo"];
+ let _ = opt.ok_or(vec.len());
+
+ let array = ["foo"];
+ let _ = opt.ok_or(array.len());
+
+ let slice = &["foo"][..];
+ let _ = opt.ok_or(slice.len());
+}
+
+// Issue 4514 - early return
+fn f() -> Option<()> {
+ let a = Some(1);
+ let b = 1i32;
+
+ let _ = a.unwrap_or(b.checked_mul(3)?.min(240));
+
+ Some(())
+}
+
+// Issue 5886 - const fn (with no arguments)
+pub fn skip_const_fn_with_no_args() {
+ const fn foo() -> Option<i32> {
+ Some(42)
+ }
+ let _ = None.or(foo());
++
++ // See issue #5693.
++ let mut map = std::collections::HashMap::new();
++ map.insert(1, vec![1]);
++ map.entry(1).or_insert(vec![]);
++
++ let mut map = HashMap::<u64, String>::new();
++ map.entry(42).or_insert(String::new());
++
++ let mut btree = BTreeMap::<u64, String>::new();
++ btree.entry(42).or_insert(String::new());
+}
+
+fn main() {}
--- /dev/null
- let mut map = HashMap::<u64, String>::new();
- map.entry(42).or_insert(String::new());
-
- let mut btree = BTreeMap::<u64, String>::new();
- btree.entry(42).or_insert(String::new());
-
+// run-rustfix
+
+#![warn(clippy::or_fun_call)]
+#![allow(dead_code)]
+
+use std::collections::BTreeMap;
+use std::collections::HashMap;
+use std::time::Duration;
+
+/// Checks implementation of the `OR_FUN_CALL` lint.
+fn or_fun_call() {
+ struct Foo;
+
+ impl Foo {
+ fn new() -> Foo {
+ Foo
+ }
+ }
+
+ enum Enum {
+ A(i32),
+ }
+
+ fn make<T>() -> T {
+ unimplemented!();
+ }
+
+ let with_enum = Some(Enum::A(1));
+ with_enum.unwrap_or(Enum::A(5));
+
+ let with_const_fn = Some(Duration::from_secs(1));
+ with_const_fn.unwrap_or(Duration::from_secs(5));
+
+ let with_constructor = Some(vec![1]);
+ with_constructor.unwrap_or(make());
+
+ let with_new = Some(vec![1]);
+ with_new.unwrap_or(Vec::new());
+
+ let with_const_args = Some(vec![1]);
+ with_const_args.unwrap_or(Vec::with_capacity(12));
+
+ let with_err: Result<_, ()> = Ok(vec![1]);
+ with_err.unwrap_or(make());
+
+ let with_err_args: Result<_, ()> = Ok(vec![1]);
+ with_err_args.unwrap_or(Vec::with_capacity(12));
+
+ let with_default_trait = Some(1);
+ with_default_trait.unwrap_or(Default::default());
+
+ let with_default_type = Some(1);
+ with_default_type.unwrap_or(u64::default());
+
+ let with_vec = Some(vec![1]);
+ with_vec.unwrap_or(vec![]);
+
+ let without_default = Some(Foo);
+ without_default.unwrap_or(Foo::new());
+
+ let stringy = Some(String::from(""));
+ let _ = stringy.unwrap_or("".to_owned());
+
+ let opt = Some(1);
+ let hello = "Hello";
+ let _ = opt.ok_or(format!("{} world.", hello));
+}
+
+struct Foo(u8);
+struct Bar(String, Duration);
+#[rustfmt::skip]
+fn test_or_with_ctors() {
+ let opt = Some(1);
+ let opt_opt = Some(Some(1));
+ // we also test for const promotion, this makes sure we don't hit that
+ let two = 2;
+
+ let _ = opt_opt.unwrap_or(Some(2));
+ let _ = opt_opt.unwrap_or(Some(two));
+ let _ = opt.ok_or(Some(2));
+ let _ = opt.ok_or(Some(two));
+ let _ = opt.ok_or(Foo(2));
+ let _ = opt.ok_or(Foo(two));
+ let _ = opt.or(Some(2));
+ let _ = opt.or(Some(two));
+
+ let _ = Some("a".to_string()).or(Some("b".to_string()));
+
+ let b = "b".to_string();
+ let _ = Some(Bar("a".to_string(), Duration::from_secs(1)))
+ .or(Some(Bar(b, Duration::from_secs(2))));
+
+ let vec = vec!["foo"];
+ let _ = opt.ok_or(vec.len());
+
+ let array = ["foo"];
+ let _ = opt.ok_or(array.len());
+
+ let slice = &["foo"][..];
+ let _ = opt.ok_or(slice.len());
+}
+
+// Issue 4514 - early return
+fn f() -> Option<()> {
+ let a = Some(1);
+ let b = 1i32;
+
+ let _ = a.unwrap_or(b.checked_mul(3)?.min(240));
+
+ Some(())
+}
+
+// Issue 5886 - const fn (with no arguments)
+pub fn skip_const_fn_with_no_args() {
+ const fn foo() -> Option<i32> {
+ Some(42)
+ }
+ let _ = None.or(foo());
++
++ // See issue #5693.
++ let mut map = std::collections::HashMap::new();
++ map.insert(1, vec![1]);
++ map.entry(1).or_insert(vec![]);
++
++ let mut map = HashMap::<u64, String>::new();
++ map.entry(42).or_insert(String::new());
++
++ let mut btree = BTreeMap::<u64, String>::new();
++ btree.entry(42).or_insert(String::new());
+}
+
+fn main() {}
--- /dev/null
- error: use of `or_insert` followed by a function call
- --> $DIR/or_fun_call.rs:62:19
- |
- LL | map.entry(42).or_insert(String::new());
- | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `or_insert_with(String::new)`
-
- error: use of `or_insert` followed by a function call
- --> $DIR/or_fun_call.rs:65:21
- |
- LL | btree.entry(42).or_insert(String::new());
- | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `or_insert_with(String::new)`
-
+error: use of `unwrap_or` followed by a function call
+ --> $DIR/or_fun_call.rs:32:19
+ |
+LL | with_const_fn.unwrap_or(Duration::from_secs(5));
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `unwrap_or_else(|| Duration::from_secs(5))`
+ |
+ = note: `-D clippy::or-fun-call` implied by `-D warnings`
+
+error: use of `unwrap_or` followed by a function call
+ --> $DIR/or_fun_call.rs:35:22
+ |
+LL | with_constructor.unwrap_or(make());
+ | ^^^^^^^^^^^^^^^^^ help: try this: `unwrap_or_else(make)`
+
+error: use of `unwrap_or` followed by a call to `new`
+ --> $DIR/or_fun_call.rs:38:5
+ |
+LL | with_new.unwrap_or(Vec::new());
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `with_new.unwrap_or_default()`
+
+error: use of `unwrap_or` followed by a function call
+ --> $DIR/or_fun_call.rs:41:21
+ |
+LL | with_const_args.unwrap_or(Vec::with_capacity(12));
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `unwrap_or_else(|| Vec::with_capacity(12))`
+
+error: use of `unwrap_or` followed by a function call
+ --> $DIR/or_fun_call.rs:44:14
+ |
+LL | with_err.unwrap_or(make());
+ | ^^^^^^^^^^^^^^^^^ help: try this: `unwrap_or_else(|_| make())`
+
+error: use of `unwrap_or` followed by a function call
+ --> $DIR/or_fun_call.rs:47:19
+ |
+LL | with_err_args.unwrap_or(Vec::with_capacity(12));
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `unwrap_or_else(|_| Vec::with_capacity(12))`
+
+error: use of `unwrap_or` followed by a call to `default`
+ --> $DIR/or_fun_call.rs:50:5
+ |
+LL | with_default_trait.unwrap_or(Default::default());
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `with_default_trait.unwrap_or_default()`
+
+error: use of `unwrap_or` followed by a call to `default`
+ --> $DIR/or_fun_call.rs:53:5
+ |
+LL | with_default_type.unwrap_or(u64::default());
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `with_default_type.unwrap_or_default()`
+
+error: use of `unwrap_or` followed by a call to `new`
+ --> $DIR/or_fun_call.rs:56:5
+ |
+LL | with_vec.unwrap_or(vec![]);
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `with_vec.unwrap_or_default()`
+
+error: use of `unwrap_or` followed by a function call
+ --> $DIR/or_fun_call.rs:59:21
+ |
+LL | without_default.unwrap_or(Foo::new());
+ | ^^^^^^^^^^^^^^^^^^^^^ help: try this: `unwrap_or_else(Foo::new)`
+
- --> $DIR/or_fun_call.rs:68:21
+error: use of `unwrap_or` followed by a function call
- --> $DIR/or_fun_call.rs:93:35
++ --> $DIR/or_fun_call.rs:62:21
+ |
+LL | let _ = stringy.unwrap_or("".to_owned());
+ | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `unwrap_or_else(|| "".to_owned())`
+
+error: use of `or` followed by a function call
- --> $DIR/or_fun_call.rs:97:10
++ --> $DIR/or_fun_call.rs:87:35
+ |
+LL | let _ = Some("a".to_string()).or(Some("b".to_string()));
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `or_else(|| Some("b".to_string()))`
+
+error: use of `or` followed by a function call
- error: aborting due to 15 previous errors
++ --> $DIR/or_fun_call.rs:91:10
+ |
+LL | .or(Some(Bar(b, Duration::from_secs(2))));
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `or_else(|| Some(Bar(b, Duration::from_secs(2))))`
+
++error: aborting due to 13 previous errors
+
--- /dev/null
- error: called `map(f)` on an `Result` value where `f` is a function that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a function that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_fixable.rs:35:5
+ |
+LL | x.field.map(do_nothing);
+ | ^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(x_field) = x.field { do_nothing(x_field) }`
+ |
+ = note: `-D clippy::result-map-unit-fn` implied by `-D warnings`
+
- error: called `map(f)` on an `Result` value where `f` is a function that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a function that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_fixable.rs:37:5
+ |
+LL | x.field.map(do_nothing);
+ | ^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(x_field) = x.field { do_nothing(x_field) }`
+
- error: called `map(f)` on an `Result` value where `f` is a function that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a function that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_fixable.rs:39:5
+ |
+LL | x.field.map(diverge);
+ | ^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(x_field) = x.field { diverge(x_field) }`
+
- error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_fixable.rs:45:5
+ |
+LL | x.field.map(|value| x.do_result_nothing(value + captured));
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(value) = x.field { x.do_result_nothing(value + captured) }`
+
- error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_fixable.rs:47:5
+ |
+LL | x.field.map(|value| { x.do_result_plus_one(value + captured); });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(value) = x.field { x.do_result_plus_one(value + captured); }`
+
- error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_fixable.rs:50:5
+ |
+LL | x.field.map(|value| do_nothing(value + captured));
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(value) = x.field { do_nothing(value + captured) }`
+
- error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_fixable.rs:52:5
+ |
+LL | x.field.map(|value| { do_nothing(value + captured) });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(value) = x.field { do_nothing(value + captured) }`
+
- error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_fixable.rs:54:5
+ |
+LL | x.field.map(|value| { do_nothing(value + captured); });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(value) = x.field { do_nothing(value + captured); }`
+
- error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_fixable.rs:56:5
+ |
+LL | x.field.map(|value| { { do_nothing(value + captured); } });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(value) = x.field { do_nothing(value + captured); }`
+
- error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_fixable.rs:59:5
+ |
+LL | x.field.map(|value| diverge(value + captured));
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(value) = x.field { diverge(value + captured) }`
+
- error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_fixable.rs:61:5
+ |
+LL | x.field.map(|value| { diverge(value + captured) });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(value) = x.field { diverge(value + captured) }`
+
- error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_fixable.rs:63:5
+ |
+LL | x.field.map(|value| { diverge(value + captured); });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(value) = x.field { diverge(value + captured); }`
+
- error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_fixable.rs:65:5
+ |
+LL | x.field.map(|value| { { diverge(value + captured); } });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(value) = x.field { diverge(value + captured); }`
+
- error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_fixable.rs:70:5
+ |
+LL | x.field.map(|value| { let y = plus_one(value + captured); });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(value) = x.field { let y = plus_one(value + captured); }`
+
- error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_fixable.rs:72:5
+ |
+LL | x.field.map(|value| { plus_one(value + captured); });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(value) = x.field { plus_one(value + captured); }`
+
- error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_fixable.rs:74:5
+ |
+LL | x.field.map(|value| { { plus_one(value + captured); } });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(value) = x.field { plus_one(value + captured); }`
+
- error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_fixable.rs:77:5
+ |
+LL | x.field.map(|ref value| { do_nothing(value + captured) });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(ref value) = x.field { do_nothing(value + captured) }`
+
+error: aborting due to 17 previous errors
+
--- /dev/null
- error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_unfixable.rs:23:5
+ |
+LL | x.field.map(|value| { do_nothing(value); do_nothing(value) });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(value) = x.field { ... }`
+ |
+ = note: `-D clippy::result-map-unit-fn` implied by `-D warnings`
+
- error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_unfixable.rs:25:5
+ |
+LL | x.field.map(|value| if value > 0 { do_nothing(value); do_nothing(value) });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(value) = x.field { ... }`
+
- error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_unfixable.rs:29:5
+ |
+LL | x.field.map(|value| {
+ | _____^
+ | |_____|
+ | ||
+LL | || do_nothing(value);
+LL | || do_nothing(value)
+LL | || });
+ | ||______^- help: try this: `if let Ok(value) = x.field { ... }`
+ | |_______|
+ |
+
- error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a closure that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_unfixable.rs:33:5
+ |
+LL | x.field.map(|value| { do_nothing(value); do_nothing(value); });
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(value) = x.field { ... }`
+
- error: called `map(f)` on an `Result` value where `f` is a function that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a function that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_unfixable.rs:37:5
+ |
+LL | "12".parse::<i32>().map(diverge);
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(a) = "12".parse::<i32>() { diverge(a) }`
+
- error: called `map(f)` on an `Result` value where `f` is a function that returns the unit type
++error: called `map(f)` on an `Result` value where `f` is a function that returns the unit type `()`
+ --> $DIR/result_map_unit_fn_unfixable.rs:43:5
+ |
+LL | y.map(do_nothing);
+ | ^^^^^^^^^^^^^^^^^-
+ | |
+ | help: try this: `if let Ok(_y) = y { do_nothing(_y) }`
+
+error: aborting due to 6 previous errors
+
--- /dev/null
- fn main() {
- // Test for basic case
- let mut spaces = Vec::with_capacity(10);
- for _ in 0..10 {
- spaces.push(vec![b' ']);
- }
+#![warn(clippy::same_item_push)]
+
++const VALUE: u8 = 7;
++
+fn mutate_increment(x: &mut u8) -> u8 {
+ *x += 1;
+ *x
+}
+
+fn increment(x: u8) -> u8 {
+ x + 1
+}
+
- let mut vec2: Vec<u8> = Vec::new();
++fn fun() -> usize {
++ 42
++}
+
- vec2.push(item);
++fn main() {
++ // ** linted cases **
++ let mut vec: Vec<u8> = Vec::new();
+ let item = 2;
+ for _ in 5..=20 {
- let mut vec3: Vec<u8> = Vec::new();
++ vec.push(item);
+ }
+
- vec3.push(item);
++ let mut vec: Vec<u8> = Vec::new();
+ for _ in 0..15 {
+ let item = 2;
- let mut vec4: Vec<u8> = Vec::new();
++ vec.push(item);
+ }
+
- vec4.push(13);
++ let mut vec: Vec<u8> = Vec::new();
+ for _ in 0..15 {
- let mut vec5: Vec<u8> = Vec::new();
++ vec.push(13);
++ }
++
++ let mut vec = Vec::new();
++ for _ in 0..20 {
++ vec.push(VALUE);
++ }
++
++ let mut vec = Vec::new();
++ let item = VALUE;
++ for _ in 0..20 {
++ vec.push(item);
++ }
++
++ // ** non-linted cases **
++ let mut spaces = Vec::with_capacity(10);
++ for _ in 0..10 {
++ spaces.push(vec![b' ']);
+ }
+
+ // Suggestion should not be given as pushed variable can mutate
- vec5.push(mutate_increment(&mut item));
++ let mut vec: Vec<u8> = Vec::new();
+ let mut item: u8 = 2;
+ for _ in 0..30 {
- let mut vec6: Vec<u8> = Vec::new();
++ vec.push(mutate_increment(&mut item));
+ }
+
- vec6.push(mutate_increment(item2));
++ let mut vec: Vec<u8> = Vec::new();
+ let mut item: u8 = 2;
+ let mut item2 = &mut mutate_increment(&mut item);
+ for _ in 0..30 {
- let mut vec7: Vec<usize> = Vec::new();
++ vec.push(mutate_increment(item2));
+ }
+
- vec7.push(a);
++ let mut vec: Vec<usize> = Vec::new();
+ for (a, b) in [0, 1, 4, 9, 16].iter().enumerate() {
- let mut vec8: Vec<u8> = Vec::new();
++ vec.push(a);
+ }
+
- vec8.push(increment(i));
++ let mut vec: Vec<u8> = Vec::new();
+ for i in 0..30 {
- let mut vec9: Vec<u8> = Vec::new();
++ vec.push(increment(i));
+ }
+
- vec9.push(i + i * i);
++ let mut vec: Vec<u8> = Vec::new();
+ for i in 0..30 {
- let mut vec10: Vec<u8> = Vec::new();
++ vec.push(i + i * i);
+ }
+
+ // Suggestion should not be given as there are multiple pushes that are not the same
- vec10.push(item);
- vec10.push(item * 2);
++ let mut vec: Vec<u8> = Vec::new();
+ let item: u8 = 2;
+ for _ in 0..30 {
- let mut vec12: Vec<u8> = Vec::new();
++ vec.push(item);
++ vec.push(item * 2);
+ }
+
+ // Suggestion should not be given as Vec is not involved
+ for _ in 0..5 {
+ println!("Same Item Push");
+ }
+
+ struct A {
+ kind: u32,
+ }
+ let mut vec_a: Vec<A> = Vec::new();
+ for i in 0..30 {
+ vec_a.push(A { kind: i });
+ }
- vec12.push(2u8.pow(a.kind));
++ let mut vec: Vec<u8> = Vec::new();
+ for a in vec_a {
- let mut vec13: Vec<u8> = Vec::new();
++ vec.push(2u8.pow(a.kind));
+ }
+
+ // Fix #5902
- vec13.push(item);
++ let mut vec: Vec<u8> = Vec::new();
+ let mut item = 0;
+ for _ in 0..10 {
++ vec.push(item);
+ item += 10;
+ }
++
++ // Fix #5979
++ let mut vec: Vec<std::fs::File> = Vec::new();
++ for _ in 0..10 {
++ vec.push(std::fs::File::open("foobar").unwrap());
++ }
++ // Fix #5979
++ #[derive(Clone)]
++ struct S {}
++
++ trait T {}
++ impl T for S {}
++
++ let mut vec: Vec<Box<dyn T>> = Vec::new();
++ for _ in 0..10 {
++ vec.push(Box::new(S {}));
++ }
++
++ // Fix #5985
++ let mut vec = Vec::new();
++ let item = 42;
++ let item = fun();
++ for _ in 0..20 {
++ vec.push(item);
++ }
++
++ // Fix #5985
++ let mut vec = Vec::new();
++ let key = 1;
++ for _ in 0..20 {
++ let item = match key {
++ 1 => 10,
++ _ => 0,
++ };
++ vec.push(item);
++ }
+}
--- /dev/null
- --> $DIR/same_item_push.rs:16:9
+error: it looks like the same item is being pushed into this Vec
- LL | spaces.push(vec![b' ']);
- | ^^^^^^
++ --> $DIR/same_item_push.rs:23:9
+ |
- = help: try using vec![vec![b' '];SIZE] or spaces.resize(NEW_SIZE, vec![b' '])
++LL | vec.push(item);
++ | ^^^
+ |
+ = note: `-D clippy::same-item-push` implied by `-D warnings`
- --> $DIR/same_item_push.rs:22:9
++ = help: try using vec![item;SIZE] or vec.resize(NEW_SIZE, item)
+
+error: it looks like the same item is being pushed into this Vec
- LL | vec2.push(item);
- | ^^^^
++ --> $DIR/same_item_push.rs:29:9
+ |
- = help: try using vec![item;SIZE] or vec2.resize(NEW_SIZE, item)
++LL | vec.push(item);
++ | ^^^
+ |
- --> $DIR/same_item_push.rs:28:9
++ = help: try using vec![item;SIZE] or vec.resize(NEW_SIZE, item)
+
+error: it looks like the same item is being pushed into this Vec
- LL | vec3.push(item);
- | ^^^^
++ --> $DIR/same_item_push.rs:34:9
+ |
- = help: try using vec![item;SIZE] or vec3.resize(NEW_SIZE, item)
++LL | vec.push(13);
++ | ^^^
+ |
- --> $DIR/same_item_push.rs:33:9
++ = help: try using vec![13;SIZE] or vec.resize(NEW_SIZE, 13)
+
+error: it looks like the same item is being pushed into this Vec
- LL | vec4.push(13);
- | ^^^^
++ --> $DIR/same_item_push.rs:39:9
+ |
- = help: try using vec![13;SIZE] or vec4.resize(NEW_SIZE, 13)
++LL | vec.push(VALUE);
++ | ^^^
+ |
- error: aborting due to 4 previous errors
++ = help: try using vec![VALUE;SIZE] or vec.resize(NEW_SIZE, VALUE)
+
++error: it looks like the same item is being pushed into this Vec
++ --> $DIR/same_item_push.rs:45:9
++ |
++LL | vec.push(item);
++ | ^^^
++ |
++ = help: try using vec![item;SIZE] or vec.resize(NEW_SIZE, item)
++
++error: aborting due to 5 previous errors
+
--- /dev/null
- A.0 = 2;
- B.field = 2;
- C.structure.field = 2;
- D.array[0] = 2;
-
+#![warn(clippy::temporary_assignment)]
+#![allow(const_item_mutation)]
+
+use std::ops::{Deref, DerefMut};
+
+struct TupleStruct(i32);
+
+struct Struct {
+ field: i32,
+}
+
+struct MultiStruct {
+ structure: Struct,
+}
+
+struct Wrapper<'a> {
+ inner: &'a mut Struct,
+}
+
+impl<'a> Deref for Wrapper<'a> {
+ type Target = Struct;
+ fn deref(&self) -> &Struct {
+ self.inner
+ }
+}
+
+impl<'a> DerefMut for Wrapper<'a> {
+ fn deref_mut(&mut self) -> &mut Struct {
+ self.inner
+ }
+}
+
+struct ArrayStruct {
+ array: [i32; 1],
+}
+
+const A: TupleStruct = TupleStruct(1);
+const B: Struct = Struct { field: 1 };
+const C: MultiStruct = MultiStruct {
+ structure: Struct { field: 1 },
+};
+const D: ArrayStruct = ArrayStruct { array: [1] };
+
+fn main() {
+ let mut s = Struct { field: 0 };
+ let mut t = (0, 0);
+
+ Struct { field: 0 }.field = 1;
+ MultiStruct {
+ structure: Struct { field: 0 },
+ }
+ .structure
+ .field = 1;
+ ArrayStruct { array: [0] }.array[0] = 1;
+ (0, 0).0 = 1;
+
+ // no error
+ s.field = 1;
+ t.0 = 1;
+ Wrapper { inner: &mut s }.field = 1;
+ let mut a_mut = TupleStruct(1);
+ a_mut.0 = 2;
+ let mut b_mut = Struct { field: 1 };
+ b_mut.field = 2;
+ let mut c_mut = MultiStruct {
+ structure: Struct { field: 1 },
+ };
+ c_mut.structure.field = 2;
+ let mut d_mut = ArrayStruct { array: [1] };
+ d_mut.array[0] = 2;
+}
--- /dev/null
+#![warn(clippy::transmute_ptr_to_ptr)]
+
+// Make sure we can modify lifetimes, which is one of the recommended uses
+// of transmute
+
+// Make sure we can do static lifetime transmutes
+unsafe fn transmute_lifetime_to_static<'a, T>(t: &'a T) -> &'static T {
+ std::mem::transmute::<&'a T, &'static T>(t)
+}
+
+// Make sure we can do non-static lifetime transmutes
+unsafe fn transmute_lifetime<'a, 'b, T>(t: &'a T, u: &'b T) -> &'b T {
+ std::mem::transmute::<&'a T, &'b T>(t)
+}
+
+struct LifetimeParam<'a> {
+ s: &'a str,
+}
+
+struct GenericParam<T> {
+ t: T,
+}
+
+fn transmute_ptr_to_ptr() {
+ let ptr = &1u32 as *const u32;
+ let mut_ptr = &mut 1u32 as *mut u32;
+ unsafe {
+ // pointer-to-pointer transmutes; bad
+ let _: *const f32 = std::mem::transmute(ptr);
+ let _: *mut f32 = std::mem::transmute(mut_ptr);
+ // ref-ref transmutes; bad
+ let _: &f32 = std::mem::transmute(&1u32);
+ let _: &f64 = std::mem::transmute(&1f32);
+ // ^ this test is here because both f32 and f64 are the same TypeVariant, but they are not
+ // the same type
+ let _: &mut f32 = std::mem::transmute(&mut 1u32);
+ let _: &GenericParam<f32> = std::mem::transmute(&GenericParam { t: 1u32 });
+ }
+
+ // these are recommendations for solving the above; if these lint we need to update
+ // those suggestions
+ let _ = ptr as *const f32;
+ let _ = mut_ptr as *mut f32;
+ let _ = unsafe { &*(&1u32 as *const u32 as *const f32) };
+ let _ = unsafe { &mut *(&mut 1u32 as *mut u32 as *mut f32) };
+
+ // transmute internal lifetimes, should not lint
+ let s = "hello world".to_owned();
+ let lp = LifetimeParam { s: &s };
+ let _: &LifetimeParam<'static> = unsafe { std::mem::transmute(&lp) };
+ let _: &GenericParam<&LifetimeParam<'static>> = unsafe { std::mem::transmute(&GenericParam { t: &lp }) };
+}
+
++// dereferencing raw pointers in const contexts, should not lint as it's unstable (issue 5959)
++const _: &() = {
++ struct ZST;
++ let zst = &ZST;
++
++ unsafe { std::mem::transmute::<&'static ZST, &'static ()>(zst) }
++};
++
+fn main() {}
--- /dev/null
- #![allow(clippy::no_effect, unused_must_use, unused_variables)]
+#![warn(clippy::unit_arg)]
++#![allow(
++ clippy::no_effect,
++ unused_must_use,
++ unused_variables,
++ clippy::unused_unit,
++ clippy::or_fun_call
++)]
+
+use std::fmt::Debug;
+
+fn foo<T: Debug>(t: T) {
+ println!("{:?}", t);
+}
+
+fn foo3<T1: Debug, T2: Debug, T3: Debug>(t1: T1, t2: T2, t3: T3) {
+ println!("{:?}, {:?}, {:?}", t1, t2, t3);
+}
+
+struct Bar;
+
+impl Bar {
+ fn bar<T: Debug>(&self, t: T) {
+ println!("{:?}", t);
+ }
+}
+
+fn bad() {
+ foo({
+ 1;
+ });
+ foo(foo(1));
+ foo({
+ foo(1);
+ foo(2);
+ });
+ let b = Bar;
+ b.bar({
+ 1;
+ });
+ taking_multiple_units(foo(0), foo(1));
+ taking_multiple_units(foo(0), {
+ foo(1);
+ foo(2);
+ });
+ taking_multiple_units(
+ {
+ foo(0);
+ foo(1);
+ },
+ {
+ foo(2);
+ foo(3);
+ },
+ );
++ // here Some(foo(2)) isn't the top level statement expression, wrap the suggestion in a block
++ None.or(Some(foo(2)));
++ // in this case, the suggestion can be inlined, no need for a surrounding block
++ // foo(()); foo(()) instead of { foo(()); foo(()) }
++ foo(foo(()))
+}
+
+fn ok() {
+ foo(());
+ foo(1);
+ foo({ 1 });
+ foo3("a", 3, vec![3]);
+ let b = Bar;
+ b.bar({ 1 });
+ b.bar(());
+ question_mark();
+}
+
+fn question_mark() -> Result<(), ()> {
+ Ok(Ok(())?)?;
+ Ok(Ok(()))??;
+ Ok(())
+}
+
+#[allow(dead_code)]
+mod issue_2945 {
+ fn unit_fn() -> Result<(), i32> {
+ Ok(())
+ }
+
+ fn fallible() -> Result<(), i32> {
+ Ok(unit_fn()?)
+ }
+}
+
+#[allow(dead_code)]
+fn returning_expr() -> Option<()> {
+ Some(foo(1))
+}
+
+fn taking_multiple_units(a: (), b: ()) {}
+
+fn main() {
+ bad();
+ ok();
+}
--- /dev/null
- --> $DIR/unit_arg.rs:23:5
+error: passing a unit value to a function
- help: or move the expression in front of the call...
++ --> $DIR/unit_arg.rs:29:5
+ |
+LL | / foo({
+LL | | 1;
+LL | | });
+ | |______^
+ |
+ = note: `-D clippy::unit-arg` implied by `-D warnings`
+help: remove the semicolon from the last statement in the block
+ |
+LL | 1
+ |
- |
- help: ...and use a unit literal instead
- |
++help: or move the expression in front of the call and replace it with the unit literal `()`
+ |
+LL | {
+LL | 1;
+LL | };
- | ^^
+LL | foo(());
- --> $DIR/unit_arg.rs:26:5
++ |
+
+error: passing a unit value to a function
- help: move the expression in front of the call...
++ --> $DIR/unit_arg.rs:32:5
+ |
+LL | foo(foo(1));
+ | ^^^^^^^^^^^
+ |
- |
- help: ...and use a unit literal instead
- |
++help: move the expression in front of the call and replace it with the unit literal `()`
+ |
+LL | foo(1);
- | ^^
+LL | foo(());
- --> $DIR/unit_arg.rs:27:5
++ |
+
+error: passing a unit value to a function
- help: or move the expression in front of the call...
++ --> $DIR/unit_arg.rs:33:5
+ |
+LL | / foo({
+LL | | foo(1);
+LL | | foo(2);
+LL | | });
+ | |______^
+ |
+help: remove the semicolon from the last statement in the block
+ |
+LL | foo(2)
+ |
- |
- help: ...and use a unit literal instead
- |
++help: or move the expression in front of the call and replace it with the unit literal `()`
+ |
+LL | {
+LL | foo(1);
+LL | foo(2);
+LL | };
- | ^^
+LL | foo(());
- --> $DIR/unit_arg.rs:32:5
++ |
+
+error: passing a unit value to a function
- help: or move the expression in front of the call...
++ --> $DIR/unit_arg.rs:38:5
+ |
+LL | / b.bar({
+LL | | 1;
+LL | | });
+ | |______^
+ |
+help: remove the semicolon from the last statement in the block
+ |
+LL | 1
+ |
- |
- help: ...and use a unit literal instead
- |
++help: or move the expression in front of the call and replace it with the unit literal `()`
+ |
+LL | {
+LL | 1;
+LL | };
- | ^^
+LL | b.bar(());
- --> $DIR/unit_arg.rs:35:5
++ |
+
+error: passing unit values to a function
- help: move the expressions in front of the call...
++ --> $DIR/unit_arg.rs:41:5
+ |
+LL | taking_multiple_units(foo(0), foo(1));
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ |
- |
- help: ...and use unit literals instead
- |
++help: move the expressions in front of the call and replace them with the unit literal `()`
+ |
+LL | foo(0);
+LL | foo(1);
- | ^^ ^^
+LL | taking_multiple_units((), ());
- --> $DIR/unit_arg.rs:36:5
++ |
+
+error: passing unit values to a function
- help: or move the expressions in front of the call...
++ --> $DIR/unit_arg.rs:42:5
+ |
+LL | / taking_multiple_units(foo(0), {
+LL | | foo(1);
+LL | | foo(2);
+LL | | });
+ | |______^
+ |
+help: remove the semicolon from the last statement in the block
+ |
+LL | foo(2)
+ |
- |
- help: ...and use unit literals instead
- |
++help: or move the expressions in front of the call and replace them with the unit literal `()`
+ |
+LL | foo(0);
+LL | {
+LL | foo(1);
+LL | foo(2);
+LL | };
- | ^^ ^^
+LL | taking_multiple_units((), ());
- --> $DIR/unit_arg.rs:40:5
++ |
+
+error: passing unit values to a function
- help: or move the expressions in front of the call...
++ --> $DIR/unit_arg.rs:46:5
+ |
+LL | / taking_multiple_units(
+LL | | {
+LL | | foo(0);
+LL | | foo(1);
+... |
+LL | | },
+LL | | );
+ | |_____^
+ |
+help: remove the semicolon from the last statement in the block
+ |
+LL | foo(1)
+ |
+help: remove the semicolon from the last statement in the block
+ |
+LL | foo(3)
+ |
- help: ...and use unit literals instead
++help: or move the expressions in front of the call and replace them with the unit literal `()`
+ |
+LL | {
+LL | foo(0);
+LL | foo(1);
+LL | };
+LL | {
+LL | foo(2);
+ ...
- LL | (),
- LL | (),
++
++error: passing a unit value to a function
++ --> $DIR/unit_arg.rs:57:13
++ |
++LL | None.or(Some(foo(2)));
++ | ^^^^^^^^^^^^
+ |
- --> $DIR/unit_arg.rs:82:5
++help: move the expression in front of the call and replace it with the unit literal `()`
++ |
++LL | None.or({
++LL | foo(2);
++LL | Some(())
++LL | });
+ |
+
+error: passing a unit value to a function
- LL | Some(foo(1))
++ --> $DIR/unit_arg.rs:60:5
+ |
- help: move the expression in front of the call...
++LL | foo(foo(()))
+ | ^^^^^^^^^^^^
+ |
- LL | foo(1);
++help: move the expression in front of the call and replace it with the unit literal `()`
+ |
- help: ...and use a unit literal instead
++LL | foo(());
++LL | foo(())
+ |
- | ^^
++
++error: passing a unit value to a function
++ --> $DIR/unit_arg.rs:93:5
+ |
++LL | Some(foo(1))
++ | ^^^^^^^^^^^^
++ |
++help: move the expression in front of the call and replace it with the unit literal `()`
++ |
++LL | foo(1);
+LL | Some(())
- error: aborting due to 8 previous errors
++ |
+
++error: aborting due to 10 previous errors
+
--- /dev/null
- help: move the expression in front of the call...
+error: passing a unit value to a function
+ --> $DIR/unit_arg_empty_blocks.rs:15:5
+ |
+LL | foo({});
+ | ^^^^--^
+ | |
+ | help: use a unit literal instead: `()`
+ |
+ = note: `-D clippy::unit-arg` implied by `-D warnings`
+
+error: passing a unit value to a function
+ --> $DIR/unit_arg_empty_blocks.rs:16:5
+ |
+LL | foo3({}, 2, 2);
+ | ^^^^^--^^^^^^^
+ | |
+ | help: use a unit literal instead: `()`
+
+error: passing unit values to a function
+ --> $DIR/unit_arg_empty_blocks.rs:17:5
+ |
+LL | taking_two_units({}, foo(0));
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ |
- |
- help: ...and use unit literals instead
- |
++help: move the expression in front of the call and replace it with the unit literal `()`
+ |
+LL | foo(0);
- | ^^ ^^
+LL | taking_two_units((), ());
- help: move the expressions in front of the call...
++ |
+
+error: passing unit values to a function
+ --> $DIR/unit_arg_empty_blocks.rs:18:5
+ |
+LL | taking_three_units({}, foo(0), foo(1));
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ |
- |
- help: ...and use unit literals instead
- |
++help: move the expressions in front of the call and replace them with the unit literal `()`
+ |
+LL | foo(0);
+LL | foo(1);
- | ^^ ^^ ^^
+LL | taking_three_units((), (), ());
++ |
+
+error: aborting due to 4 previous errors
+
--- /dev/null
- // Should not be linted to avoid hitting https://github.com/rust-lang/rust/issues/34162
+// run-rustfix
+
+#![allow(clippy::stable_sort_primitive)]
+
+use std::cmp::Reverse;
+
+fn unnecessary_sort_by() {
+ fn id(x: isize) -> isize {
+ x
+ }
+
+ let mut vec: Vec<isize> = vec![3, 6, 1, 2, 5];
+ // Forward examples
+ vec.sort();
+ vec.sort_unstable();
+ vec.sort_by_key(|&a| (a + 5).abs());
+ vec.sort_unstable_by_key(|&a| id(-a));
+ // Reverse examples
+ vec.sort_by_key(|&b| Reverse(b));
+ vec.sort_by_key(|&b| Reverse((b + 5).abs()));
+ vec.sort_unstable_by_key(|&b| Reverse(id(-b)));
+ // Negative examples (shouldn't be changed)
+ let c = &7;
+ vec.sort_by(|a, b| (b - a).cmp(&(a - b)));
+ vec.sort_by(|_, b| b.cmp(&5));
+ vec.sort_by(|_, b| b.cmp(c));
+ vec.sort_unstable_by(|a, _| a.cmp(c));
++
++ // Ignore vectors of references
++ let mut vec: Vec<&&&isize> = vec![&&&3, &&&6, &&&1, &&&2, &&&5];
++ vec.sort_by(|a, b| (***a).abs().cmp(&(***b).abs()));
++ vec.sort_unstable_by(|a, b| (***a).abs().cmp(&(***b).abs()));
++ vec.sort_by(|a, b| b.cmp(a));
++ vec.sort_unstable_by(|a, b| b.cmp(a));
+}
+
- struct Test(String);
++// Do not suggest returning a reference to the closure parameter of `Vec::sort_by_key`
+mod issue_5754 {
- struct Wrapper<'a>(&'a str);
++ #[derive(Clone, Copy)]
++ struct Test(usize);
+
+ #[derive(PartialOrd, Ord, PartialEq, Eq)]
- fn name(&self) -> &str {
++ struct Wrapper<'a>(&'a usize);
+
+ impl Test {
++ fn name(&self) -> &usize {
+ &self.0
+ }
+
+ fn wrapped(&self) -> Wrapper<'_> {
+ Wrapper(&self.0)
+ }
+ }
+
+ pub fn test() {
+ let mut args: Vec<Test> = vec![];
+
+ // Forward
+ args.sort_by(|a, b| a.name().cmp(b.name()));
+ args.sort_by(|a, b| a.wrapped().cmp(&b.wrapped()));
+ args.sort_unstable_by(|a, b| a.name().cmp(b.name()));
+ args.sort_unstable_by(|a, b| a.wrapped().cmp(&b.wrapped()));
+ // Reverse
+ args.sort_by(|a, b| b.name().cmp(a.name()));
+ args.sort_by(|a, b| b.wrapped().cmp(&a.wrapped()));
+ args.sort_unstable_by(|a, b| b.name().cmp(a.name()));
+ args.sort_unstable_by(|a, b| b.wrapped().cmp(&a.wrapped()));
+ }
+}
+
++// `Vec::sort_by_key` closure parameter is `F: FnMut(&T) -> K`
++// The suggestion is destructuring T and we know T is not a reference, so test that non-Copy T are
++// not linted.
++mod issue_6001 {
++ struct Test(String);
++
++ impl Test {
++ // Return an owned type so that we don't hit the fix for 5754
++ fn name(&self) -> String {
++ self.0.clone()
++ }
++ }
++
++ pub fn test() {
++ let mut args: Vec<Test> = vec![];
++
++ // Forward
++ args.sort_by(|a, b| a.name().cmp(&b.name()));
++ args.sort_unstable_by(|a, b| a.name().cmp(&b.name()));
++ // Reverse
++ args.sort_by(|a, b| b.name().cmp(&a.name()));
++ args.sort_unstable_by(|a, b| b.name().cmp(&a.name()));
++ }
++}
++
+fn main() {
+ unnecessary_sort_by();
+ issue_5754::test();
++ issue_6001::test();
+}
--- /dev/null
- // Should not be linted to avoid hitting https://github.com/rust-lang/rust/issues/34162
+// run-rustfix
+
+#![allow(clippy::stable_sort_primitive)]
+
+use std::cmp::Reverse;
+
+fn unnecessary_sort_by() {
+ fn id(x: isize) -> isize {
+ x
+ }
+
+ let mut vec: Vec<isize> = vec![3, 6, 1, 2, 5];
+ // Forward examples
+ vec.sort_by(|a, b| a.cmp(b));
+ vec.sort_unstable_by(|a, b| a.cmp(b));
+ vec.sort_by(|a, b| (a + 5).abs().cmp(&(b + 5).abs()));
+ vec.sort_unstable_by(|a, b| id(-a).cmp(&id(-b)));
+ // Reverse examples
+ vec.sort_by(|a, b| b.cmp(a));
+ vec.sort_by(|a, b| (b + 5).abs().cmp(&(a + 5).abs()));
+ vec.sort_unstable_by(|a, b| id(-b).cmp(&id(-a)));
+ // Negative examples (shouldn't be changed)
+ let c = &7;
+ vec.sort_by(|a, b| (b - a).cmp(&(a - b)));
+ vec.sort_by(|_, b| b.cmp(&5));
+ vec.sort_by(|_, b| b.cmp(c));
+ vec.sort_unstable_by(|a, _| a.cmp(c));
++
++ // Ignore vectors of references
++ let mut vec: Vec<&&&isize> = vec![&&&3, &&&6, &&&1, &&&2, &&&5];
++ vec.sort_by(|a, b| (***a).abs().cmp(&(***b).abs()));
++ vec.sort_unstable_by(|a, b| (***a).abs().cmp(&(***b).abs()));
++ vec.sort_by(|a, b| b.cmp(a));
++ vec.sort_unstable_by(|a, b| b.cmp(a));
+}
+
- struct Test(String);
++// Do not suggest returning a reference to the closure parameter of `Vec::sort_by_key`
+mod issue_5754 {
- struct Wrapper<'a>(&'a str);
++ #[derive(Clone, Copy)]
++ struct Test(usize);
+
+ #[derive(PartialOrd, Ord, PartialEq, Eq)]
- fn name(&self) -> &str {
++ struct Wrapper<'a>(&'a usize);
+
+ impl Test {
++ fn name(&self) -> &usize {
+ &self.0
+ }
+
+ fn wrapped(&self) -> Wrapper<'_> {
+ Wrapper(&self.0)
+ }
+ }
+
+ pub fn test() {
+ let mut args: Vec<Test> = vec![];
+
+ // Forward
+ args.sort_by(|a, b| a.name().cmp(b.name()));
+ args.sort_by(|a, b| a.wrapped().cmp(&b.wrapped()));
+ args.sort_unstable_by(|a, b| a.name().cmp(b.name()));
+ args.sort_unstable_by(|a, b| a.wrapped().cmp(&b.wrapped()));
+ // Reverse
+ args.sort_by(|a, b| b.name().cmp(a.name()));
+ args.sort_by(|a, b| b.wrapped().cmp(&a.wrapped()));
+ args.sort_unstable_by(|a, b| b.name().cmp(a.name()));
+ args.sort_unstable_by(|a, b| b.wrapped().cmp(&a.wrapped()));
+ }
+}
+
++// `Vec::sort_by_key` closure parameter is `F: FnMut(&T) -> K`
++// The suggestion is destructuring T and we know T is not a reference, so test that non-Copy T are
++// not linted.
++mod issue_6001 {
++ struct Test(String);
++
++ impl Test {
++ // Return an owned type so that we don't hit the fix for 5754
++ fn name(&self) -> String {
++ self.0.clone()
++ }
++ }
++
++ pub fn test() {
++ let mut args: Vec<Test> = vec![];
++
++ // Forward
++ args.sort_by(|a, b| a.name().cmp(&b.name()));
++ args.sort_unstable_by(|a, b| a.name().cmp(&b.name()));
++ // Reverse
++ args.sort_by(|a, b| b.name().cmp(&a.name()));
++ args.sort_unstable_by(|a, b| b.name().cmp(&a.name()));
++ }
++}
++
+fn main() {
+ unnecessary_sort_by();
+ issue_5754::test();
++ issue_6001::test();
+}
--- /dev/null
+// run-rustfix
+// aux-build:proc_macro_derive.rs
+
+#![warn(clippy::useless_attribute)]
+#![warn(unreachable_pub)]
+#![feature(rustc_private)]
+
+#![allow(dead_code)]
+#![cfg_attr(feature = "cargo-clippy", allow(dead_code))]
+#[rustfmt::skip]
+#[allow(unused_imports)]
+#[allow(unused_extern_crates)]
+#[macro_use]
+extern crate rustc_middle;
+
+#[macro_use]
+extern crate proc_macro_derive;
+
+// don't lint on unused_import for `use` items
+#[allow(unused_imports)]
+use std::collections;
+
+// don't lint on unused for `use` items
+#[allow(unused)]
+use std::option;
+
+// don't lint on deprecated for `use` items
+mod foo {
+ #[deprecated]
+ pub struct Bar;
+}
+#[allow(deprecated)]
+pub use foo::Bar;
+
+// This should not trigger the lint. There's lint level definitions inside the external derive
+// that would trigger the useless_attribute lint.
+#[derive(DeriveSomething)]
+struct Baz;
+
+// don't lint on unreachable_pub for `use` items
+mod a {
+ mod b {
+ #[allow(dead_code)]
+ #[allow(unreachable_pub)]
+ pub struct C {}
+ }
+
+ #[allow(unreachable_pub)]
+ pub use self::b::C;
+}
+
++// don't lint on clippy::wildcard_imports for `use` items
++#[allow(clippy::wildcard_imports)]
++pub use std::io::prelude::*;
++
++// don't lint on clippy::enum_glob_use for `use` items
++#[allow(clippy::enum_glob_use)]
++pub use std::cmp::Ordering::*;
++
+fn test_indented_attr() {
+ #![allow(clippy::almost_swapped)]
+ use std::collections::HashSet;
+
+ let _ = HashSet::<u32>::default();
+}
+
+fn main() {
+ test_indented_attr();
+}
--- /dev/null
+// run-rustfix
+// aux-build:proc_macro_derive.rs
+
+#![warn(clippy::useless_attribute)]
+#![warn(unreachable_pub)]
+#![feature(rustc_private)]
+
+#[allow(dead_code)]
+#[cfg_attr(feature = "cargo-clippy", allow(dead_code))]
+#[rustfmt::skip]
+#[allow(unused_imports)]
+#[allow(unused_extern_crates)]
+#[macro_use]
+extern crate rustc_middle;
+
+#[macro_use]
+extern crate proc_macro_derive;
+
+// don't lint on unused_import for `use` items
+#[allow(unused_imports)]
+use std::collections;
+
+// don't lint on unused for `use` items
+#[allow(unused)]
+use std::option;
+
+// don't lint on deprecated for `use` items
+mod foo {
+ #[deprecated]
+ pub struct Bar;
+}
+#[allow(deprecated)]
+pub use foo::Bar;
+
+// This should not trigger the lint. There's lint level definitions inside the external derive
+// that would trigger the useless_attribute lint.
+#[derive(DeriveSomething)]
+struct Baz;
+
+// don't lint on unreachable_pub for `use` items
+mod a {
+ mod b {
+ #[allow(dead_code)]
+ #[allow(unreachable_pub)]
+ pub struct C {}
+ }
+
+ #[allow(unreachable_pub)]
+ pub use self::b::C;
+}
+
++// don't lint on clippy::wildcard_imports for `use` items
++#[allow(clippy::wildcard_imports)]
++pub use std::io::prelude::*;
++
++// don't lint on clippy::enum_glob_use for `use` items
++#[allow(clippy::enum_glob_use)]
++pub use std::cmp::Ordering::*;
++
+fn test_indented_attr() {
+ #[allow(clippy::almost_swapped)]
+ use std::collections::HashSet;
+
+ let _ = HashSet::<u32>::default();
+}
+
+fn main() {
+ test_indented_attr();
+}
--- /dev/null
- --> $DIR/useless_attribute.rs:53:5
+error: useless lint attribute
+ --> $DIR/useless_attribute.rs:8:1
+ |
+LL | #[allow(dead_code)]
+ | ^^^^^^^^^^^^^^^^^^^ help: if you just forgot a `!`, use: `#![allow(dead_code)]`
+ |
+ = note: `-D clippy::useless-attribute` implied by `-D warnings`
+
+error: useless lint attribute
+ --> $DIR/useless_attribute.rs:9:1
+ |
+LL | #[cfg_attr(feature = "cargo-clippy", allow(dead_code))]
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: if you just forgot a `!`, use: `#![cfg_attr(feature = "cargo-clippy", allow(dead_code)`
+
+error: useless lint attribute
++ --> $DIR/useless_attribute.rs:61:5
+ |
+LL | #[allow(clippy::almost_swapped)]
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: if you just forgot a `!`, use: `#![allow(clippy::almost_swapped)]`
+
+error: aborting due to 3 previous errors
+