|
| 1 | +use clippy_utils::{diagnostics::span_lint_and_help, is_lang_item_or_ctor, last_path_segment, match_def_path, paths}; |
| 2 | +use rustc_hir::{ |
| 3 | + def::{DefKind, Res}, |
| 4 | + GenericArg, LangItem, Ty, TyKind, |
| 5 | +}; |
| 6 | +use rustc_lint::{LateContext, LateLintPass}; |
| 7 | +use rustc_session::{declare_tool_lint, impl_lint_pass}; |
| 8 | + |
| 9 | +declare_clippy_lint! { |
| 10 | + /// ### What it does |
| 11 | + /// Checks for `T<Option<U>>` where `T` is a type that has |
| 12 | + /// [null pointer optimization](https://doc.rust-lang.org/core/option/#representation). |
| 13 | + /// |
| 14 | + /// ### Why is this bad? |
| 15 | + /// It's slower, as `Option` can use `null` as `None`, instead of adding another layer of |
| 16 | + /// indirection. |
| 17 | + /// |
| 18 | + /// ### Example |
| 19 | + /// ```rust |
| 20 | + /// struct MyWrapperType<T>(Box<Option<T>>); |
| 21 | + /// ``` |
| 22 | + /// Use instead: |
| 23 | + /// ```rust |
| 24 | + /// struct MyWrapperType<T>(Option<Box<T>>); |
| 25 | + /// ``` |
| 26 | + #[clippy::version = "1.72.0"] |
| 27 | + pub NULL_POINTER_OPTIMIZATION, |
| 28 | + perf, |
| 29 | + "checks for `U<Option<T>>` where `U` is a type that has null pointer optimization" |
| 30 | +} |
| 31 | +impl_lint_pass!(NullPointerOptimization => [NULL_POINTER_OPTIMIZATION]); |
| 32 | + |
| 33 | +#[derive(Clone, Copy)] |
| 34 | +pub struct NullPointerOptimization { |
| 35 | + pub avoid_breaking_exported_api: bool, |
| 36 | +} |
| 37 | + |
| 38 | +impl LateLintPass<'_> for NullPointerOptimization { |
| 39 | + fn check_ty(&mut self, cx: &LateContext<'_>, ty: &Ty<'_>) { |
| 40 | + if let TyKind::Path(qpath) = ty.kind |
| 41 | + && let res = cx.qpath_res(&qpath, ty.hir_id) |
| 42 | + && let Res::Def(DefKind::Struct, def_id) = res |
| 43 | + { |
| 44 | + if !(is_lang_item_or_ctor(cx, def_id, LangItem::OwnedBox) |
| 45 | + || match_def_path(cx, def_id, &paths::PTR_NON_NULL)) |
| 46 | + { |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + if let Some(args) = last_path_segment(&qpath).args |
| 51 | + && let GenericArg::Type(option_ty) = args.args[0] |
| 52 | + && let TyKind::Path(option_qpath) = option_ty.kind |
| 53 | + && let res = cx.qpath_res(&option_qpath, option_ty.hir_id) |
| 54 | + && let Res::Def(.., def_id) = res |
| 55 | + && is_lang_item_or_ctor(cx, def_id, LangItem::Option) |
| 56 | + { |
| 57 | + let outer_ty = last_path_segment(&qpath).ident.name; |
| 58 | + span_lint_and_help( |
| 59 | + cx, |
| 60 | + NULL_POINTER_OPTIMIZATION, |
| 61 | + ty.span, |
| 62 | + &format!("usage of `{outer_ty}<Option<T>>`"), |
| 63 | + None, |
| 64 | + &format!("consider using `Option<{outer_ty}<T>>` instead, as it will grant better performance. For more information, see\n\ |
| 65 | + https://doc.rust-lang.org/core/option/#representation"), |
| 66 | + ); |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments