7 mod redundant_allocation;
13 use rustc_hir::intravisit::FnKind;
15 Body, FnDecl, FnRetTy, GenericArg, HirId, ImplItem, ImplItemKind, Item, ItemKind, Local, MutTy, QPath, TraitItem,
16 TraitItemKind, TyKind,
18 use rustc_lint::{LateContext, LateLintPass};
19 use rustc_session::{declare_tool_lint, impl_lint_pass};
20 use rustc_span::source_map::Span;
22 declare_clippy_lint! {
24 /// Checks for use of `Box<T>` where T is a collection such as Vec anywhere in the code.
25 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
27 /// ### Why is this bad?
28 /// Collections already keeps their contents in a separate area on
29 /// the heap. So if you `Box` them, you just add another level of indirection
30 /// without any benefit whatsoever.
35 /// values: Box<Vec<Foo>>,
46 #[clippy::version = "1.57.0"]
49 "usage of `Box<Vec<T>>`, vector elements are already on the heap"
52 declare_clippy_lint! {
54 /// Checks for use of `Vec<Box<T>>` where T: Sized anywhere in the code.
55 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
57 /// ### Why is this bad?
58 /// `Vec` already keeps its contents in a separate area on
59 /// the heap. So if you `Box` its contents, you just add another level of indirection.
61 /// ### Known problems
62 /// Vec<Box<T: Sized>> makes sense if T is a large type (see [#3530](https://github.com/rust-lang/rust-clippy/issues/3530),
68 /// values: Vec<Box<i32>>,
79 #[clippy::version = "1.33.0"]
82 "usage of `Vec<Box<T>>` where T: Sized, vector elements are already on the heap"
85 declare_clippy_lint! {
87 /// Checks for use of `Option<Option<_>>` in function signatures and type
90 /// ### Why is this bad?
91 /// `Option<_>` represents an optional value. `Option<Option<_>>`
92 /// represents an optional optional value which is logically the same thing as an optional
93 /// value but has an unneeded extra level of wrapping.
95 /// If you have a case where `Some(Some(_))`, `Some(None)` and `None` are distinct cases,
96 /// consider a custom `enum` instead, with clear names for each case.
100 /// fn get_data() -> Option<Option<u32>> {
108 /// pub enum Contents {
109 /// Data(Vec<u8>), // Was Some(Some(Vec<u8>))
110 /// NotYetFetched, // Was Some(None)
111 /// None, // Was None
114 /// fn get_data() -> Contents {
118 #[clippy::version = "pre 1.29.0"]
121 "usage of `Option<Option<T>>`"
124 declare_clippy_lint! {
126 /// Checks for usage of any `LinkedList`, suggesting to use a
127 /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
129 /// ### Why is this bad?
132 /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
133 /// pointers and indirection.
134 /// > It wastes memory, it has terrible cache locality, and is all-around slow.
136 /// > "only" amortized for push/pop, should be faster in the general case for
137 /// almost every possible
138 /// > workload, and isn't even amortized at all if you can predict the capacity
141 /// > `LinkedList`s are only really good if you're doing a lot of merging or
142 /// splitting of lists.
143 /// > This is because they can just mangle some pointers instead of actually
144 /// copying the data. Even
145 /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
146 /// can still be better
147 /// > because of how expensive it is to seek to the middle of a `LinkedList`.
149 /// ### Known problems
150 /// False positives – the instances where using a
151 /// `LinkedList` makes sense are few and far between, but they can still happen.
155 /// # use std::collections::LinkedList;
156 /// let x: LinkedList<usize> = LinkedList::new();
158 #[clippy::version = "pre 1.29.0"]
161 "usage of LinkedList, usually a vector is faster, or a more specialized data structure like a `VecDeque`"
164 declare_clippy_lint! {
166 /// Checks for use of `&Box<T>` anywhere in the code.
167 /// Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.
169 /// ### Why is this bad?
170 /// Any `&Box<T>` can also be a `&T`, which is more
175 /// fn foo(bar: &Box<T>) { ... }
181 /// fn foo(bar: &T) { ... }
183 #[clippy::version = "pre 1.29.0"]
186 "a borrow of a boxed type"
189 declare_clippy_lint! {
191 /// Checks for use of redundant allocations anywhere in the code.
193 /// ### Why is this bad?
194 /// Expressions such as `Rc<&T>`, `Rc<Rc<T>>`, `Rc<Arc<T>>`, `Rc<Box<T>>`, `Arc<&T>`, `Arc<Rc<T>>`,
195 /// `Arc<Arc<T>>`, `Arc<Box<T>>`, `Box<&T>`, `Box<Rc<T>>`, `Box<Arc<T>>`, `Box<Box<T>>`, add an unnecessary level of indirection.
199 /// # use std::rc::Rc;
200 /// fn foo(bar: Rc<&usize>) {}
206 /// fn foo(bar: &usize) {}
208 #[clippy::version = "1.44.0"]
209 pub REDUNDANT_ALLOCATION,
211 "redundant allocation"
214 declare_clippy_lint! {
216 /// Checks for `Rc<T>` and `Arc<T>` when `T` is a mutable buffer type such as `String` or `Vec`.
218 /// ### Why is this bad?
219 /// Expressions such as `Rc<String>` usually have no advantage over `Rc<str>`, since
220 /// it is larger and involves an extra level of indirection, and doesn't implement `Borrow<str>`.
222 /// While mutating a buffer type would still be possible with `Rc::get_mut()`, it only
223 /// works if there are no additional references yet, which usually defeats the purpose of
224 /// enclosing it in a shared ownership type. Instead, additionally wrapping the inner
225 /// type with an interior mutable container (such as `RefCell` or `Mutex`) would normally
228 /// ### Known problems
229 /// This pattern can be desirable to avoid the overhead of a `RefCell` or `Mutex` for
230 /// cases where mutation only happens before there are any additional references.
234 /// # use std::rc::Rc;
235 /// fn foo(interned: Rc<String>) { ... }
241 /// fn foo(interned: Rc<str>) { ... }
243 #[clippy::version = "1.48.0"]
246 "shared ownership of a buffer type"
249 declare_clippy_lint! {
251 /// Checks for types used in structs, parameters and `let`
252 /// declarations above a certain complexity threshold.
254 /// ### Why is this bad?
255 /// Too complex types make the code less readable. Consider
256 /// using a `type` definition to simplify them.
260 /// # use std::rc::Rc;
262 /// inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
265 #[clippy::version = "pre 1.29.0"]
268 "usage of very complex types that might be better factored into `type` definitions"
271 declare_clippy_lint! {
273 /// Checks for `Rc<Mutex<T>>`.
275 /// ### Why is this bad?
276 /// `Rc` is used in single thread and `Mutex` is used in multi thread.
277 /// Consider using `Rc<RefCell<T>>` in single thread or `Arc<Mutex<T>>` in multi thread.
279 /// ### Known problems
280 /// Sometimes combining generic types can lead to the requirement that a
281 /// type use Rc in conjunction with Mutex. We must consider those cases false positives, but
282 /// alas they are quite hard to rule out. Luckily they are also rare.
287 /// use std::sync::Mutex;
288 /// fn foo(interned: Rc<Mutex<i32>>) { ... }
295 /// use std::cell::RefCell
296 /// fn foo(interned: Rc<RefCell<i32>>) { ... }
298 #[clippy::version = "1.55.0"]
301 "usage of `Rc<Mutex<T>>`"
305 vec_box_size_threshold: u64,
306 type_complexity_threshold: u64,
307 avoid_breaking_exported_api: bool,
310 impl_lint_pass!(Types => [BOX_COLLECTION, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX, REDUNDANT_ALLOCATION, RC_BUFFER, RC_MUTEX, TYPE_COMPLEXITY]);
312 impl<'tcx> LateLintPass<'tcx> for Types {
313 fn check_fn(&mut self, cx: &LateContext<'_>, _: FnKind<'_>, decl: &FnDecl<'_>, _: &Body<'_>, _: Span, id: HirId) {
314 let is_in_trait_impl = if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(id))
316 matches!(item.kind, ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }))
321 let is_exported = cx.access_levels.is_exported(cx.tcx.hir().local_def_id(id));
329 ..CheckTyContext::default()
334 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
335 let is_exported = cx.access_levels.is_exported(item.def_id);
338 ItemKind::Static(ty, _, _) | ItemKind::Const(ty, _) => self.check_ty(
343 ..CheckTyContext::default()
346 // functions, enums, structs, impls and traits are covered
351 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
353 ImplItemKind::Const(ty, _) | ImplItemKind::TyAlias(ty) => self.check_ty(
357 is_in_trait_impl: true,
358 ..CheckTyContext::default()
361 // methods are covered by check_fn
362 ImplItemKind::Fn(..) => (),
366 fn check_field_def(&mut self, cx: &LateContext<'_>, field: &hir::FieldDef<'_>) {
367 let is_exported = cx.access_levels.is_exported(cx.tcx.hir().local_def_id(field.hir_id));
374 ..CheckTyContext::default()
379 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &TraitItem<'_>) {
380 let is_exported = cx.access_levels.is_exported(item.def_id);
382 let context = CheckTyContext {
384 ..CheckTyContext::default()
388 TraitItemKind::Const(ty, _) | TraitItemKind::Type(_, Some(ty)) => {
389 self.check_ty(cx, ty, context);
391 TraitItemKind::Fn(ref sig, _) => self.check_fn_decl(cx, sig.decl, context),
392 TraitItemKind::Type(..) => (),
396 fn check_local(&mut self, cx: &LateContext<'_>, local: &Local<'_>) {
397 if let Some(ty) = local.ty {
403 ..CheckTyContext::default()
411 pub fn new(vec_box_size_threshold: u64, type_complexity_threshold: u64, avoid_breaking_exported_api: bool) -> Self {
413 vec_box_size_threshold,
414 type_complexity_threshold,
415 avoid_breaking_exported_api,
419 fn check_fn_decl(&mut self, cx: &LateContext<'_>, decl: &FnDecl<'_>, context: CheckTyContext) {
420 for input in decl.inputs {
421 self.check_ty(cx, input, context);
424 if let FnRetTy::Return(ty) = decl.output {
425 self.check_ty(cx, ty, context);
429 /// Recursively check for `TypePass` lints in the given type. Stop at the first
432 /// The parameter `is_local` distinguishes the context of the type.
433 fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, mut context: CheckTyContext) {
434 if hir_ty.span.from_expansion() {
438 if !context.is_nested_call && type_complexity::check(cx, hir_ty, self.type_complexity_threshold) {
442 // Skip trait implementations; see issue #605.
443 if context.is_in_trait_impl {
448 TyKind::Path(ref qpath) if !context.is_local => {
449 let hir_id = hir_ty.hir_id;
450 let res = cx.qpath_res(qpath, hir_id);
451 if let Some(def_id) = res.opt_def_id() {
452 if self.is_type_change_allowed(context) {
453 // All lints that are being checked in this block are guarded by
454 // the `avoid_breaking_exported_api` configuration. When adding a
455 // new lint, please also add the name to the configuration documentation
456 // in `clippy_lints::utils::conf.rs`
458 let mut triggered = false;
459 triggered |= box_collection::check(cx, hir_ty, qpath, def_id);
460 triggered |= redundant_allocation::check(cx, hir_ty, qpath, def_id);
461 triggered |= rc_buffer::check(cx, hir_ty, qpath, def_id);
462 triggered |= vec_box::check(cx, hir_ty, qpath, def_id, self.vec_box_size_threshold);
463 triggered |= option_option::check(cx, hir_ty, qpath, def_id);
464 triggered |= linked_list::check(cx, hir_ty, def_id);
465 triggered |= rc_mutex::check(cx, hir_ty, qpath, def_id);
473 QPath::Resolved(Some(ty), p) => {
474 context.is_nested_call = true;
475 self.check_ty(cx, ty, context);
476 for ty in p.segments.iter().flat_map(|seg| {
479 .map_or_else(|| [].iter(), |params| params.args.iter())
480 .filter_map(|arg| match arg {
481 GenericArg::Type(ty) => Some(ty),
485 self.check_ty(cx, ty, context);
488 QPath::Resolved(None, p) => {
489 context.is_nested_call = true;
490 for ty in p.segments.iter().flat_map(|seg| {
493 .map_or_else(|| [].iter(), |params| params.args.iter())
494 .filter_map(|arg| match arg {
495 GenericArg::Type(ty) => Some(ty),
499 self.check_ty(cx, ty, context);
502 QPath::TypeRelative(ty, seg) => {
503 context.is_nested_call = true;
504 self.check_ty(cx, ty, context);
505 if let Some(params) = seg.args {
506 for ty in params.args.iter().filter_map(|arg| match arg {
507 GenericArg::Type(ty) => Some(ty),
510 self.check_ty(cx, ty, context);
514 QPath::LangItem(..) => {},
517 TyKind::Rptr(ref lt, ref mut_ty) => {
518 context.is_nested_call = true;
519 if !borrowed_box::check(cx, hir_ty, lt, mut_ty) {
520 self.check_ty(cx, mut_ty.ty, context);
523 TyKind::Slice(ty) | TyKind::Array(ty, _) | TyKind::Ptr(MutTy { ty, .. }) => {
524 context.is_nested_call = true;
525 self.check_ty(cx, ty, context);
527 TyKind::Tup(tys) => {
528 context.is_nested_call = true;
530 self.check_ty(cx, ty, context);
537 /// This function checks if the type is allowed to change in the current context
538 /// based on the `avoid_breaking_exported_api` configuration
539 fn is_type_change_allowed(&self, context: CheckTyContext) -> bool {
540 !(context.is_exported && self.avoid_breaking_exported_api)
544 #[allow(clippy::struct_excessive_bools)]
545 #[derive(Clone, Copy, Default)]
546 struct CheckTyContext {
547 is_in_trait_impl: bool,
548 /// `true` for types on local variables.
550 /// `true` for types that are part of the public API.
552 is_nested_call: bool,