|
| 1 | +use std::borrow::Cow; |
| 2 | + |
| 3 | +use rustc_span::Symbol; |
| 4 | + |
| 5 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 6 | +use clippy_utils::sym; |
| 7 | +use clippy_utils::ty::is_type_diagnostic_item; |
| 8 | +use rustc_errors::Applicability; |
| 9 | +use rustc_hir as hir; |
| 10 | +use rustc_lint::LateContext; |
| 11 | +use rustc_middle::ty::{self, Ty}; |
| 12 | +use rustc_span::Span; |
| 13 | + |
| 14 | +use super::CONCEALED_OBVIOUS_DEFAULT; |
| 15 | + |
| 16 | +pub(super) fn check(cx: &LateContext<'_>, recv: &hir::Expr<'_>, method_name: Symbol, call_span: Span) { |
| 17 | + // Type of the expression which invoked the method |
| 18 | + let recv_ty = cx.typeck_results().expr_ty(recv); |
| 19 | + |
| 20 | + // Only consider algebraic data types e.g. an `Option`. |
| 21 | + // Their generics are represented by `generic_args` |
| 22 | + if let ty::Adt(adt, generic_args) = recv_ty.kind() |
| 23 | + // `name_of_generic`, is e.g. a `sym::Option` |
| 24 | + && let Some(name_of_generic) = cx.tcx.get_diagnostic_name(adt.did()) |
| 25 | + && let Some((message, suggestion)) = CONCEALING_METHODS.into_iter().find_map(|concealing| { |
| 26 | + (name_of_generic == concealing.ty && method_name == concealing.method) |
| 27 | + .then(|| { |
| 28 | + generic_args.get(concealing.generic_index).and_then(|entry| { |
| 29 | + entry.as_type().and_then(|ty| { |
| 30 | + extract_obvious_default(cx, ty).map(|(default, ty)| { |
| 31 | + let method = (concealing.fmt_msg)(ty); |
| 32 | + ( |
| 33 | + format!("method {method} conceals the underlying type"), |
| 34 | + (concealing.fmt_sugg)(default), |
| 35 | + ) |
| 36 | + }) |
| 37 | + }) |
| 38 | + }) |
| 39 | + }) |
| 40 | + .flatten() |
| 41 | + }) |
| 42 | + { |
| 43 | + span_lint_and_sugg( |
| 44 | + cx, |
| 45 | + CONCEALED_OBVIOUS_DEFAULT, |
| 46 | + call_span, |
| 47 | + message, |
| 48 | + "write the default type explicitly".to_string(), |
| 49 | + suggestion, |
| 50 | + Applicability::MachineApplicable, |
| 51 | + ); |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +/// Method which conceals an underlying type of a generic |
| 56 | +struct ConcealingMethod { |
| 57 | + /// Generic which contains the concealing method, e.g. `Option<T>` |
| 58 | + ty: Symbol, |
| 59 | + /// Index of the concealed generic type, e.g. `0` for `Option<T>` |
| 60 | + generic_index: usize, |
| 61 | + /// The concealing method, e.g. `unwrap_or_default` |
| 62 | + method: Symbol, |
| 63 | + /// Format the lint's message |
| 64 | + /// |
| 65 | + /// Receives the concealed type, e.g. for `Option<bool>` receives `bool` |
| 66 | + fmt_msg: fn(Cow<'static, str>) -> String, |
| 67 | + /// Format the lint's suggestion |
| 68 | + /// |
| 69 | + /// Receives the default of the concealed type, e.g. for `Option<bool>` receives `false`, |
| 70 | + /// as `bool::default()` is `false` |
| 71 | + fmt_sugg: fn(&'static str) -> String, |
| 72 | +} |
| 73 | + |
| 74 | +/// List of methods which use `Default` trait under the hood, |
| 75 | +/// but they have an alternative non-`Default` method |
| 76 | +/// |
| 77 | +/// For example, there is `Option::unwrap_or_default` which is almost the same |
| 78 | +/// as `Option::unwrap_or`, but the type does not have to be provided and the |
| 79 | +/// `Default` implementation is used. |
| 80 | +const CONCEALING_METHODS: [ConcealingMethod; 4] = [ |
| 81 | + ConcealingMethod { |
| 82 | + ty: sym::Result, |
| 83 | + // Result<T, E> |
| 84 | + // ^ want |
| 85 | + generic_index: 0, |
| 86 | + method: sym::unwrap_or_default, |
| 87 | + fmt_msg: |ty| format!("Result::<{ty}, _>::unwrap_or_default()"), |
| 88 | + fmt_sugg: |val| format!("unwrap_or({val})"), |
| 89 | + }, |
| 90 | + ConcealingMethod { |
| 91 | + ty: sym::Option, |
| 92 | + // Option<T> |
| 93 | + // ^ want |
| 94 | + generic_index: 0, |
| 95 | + method: sym::unwrap_or_default, |
| 96 | + fmt_msg: |ty| format!("Option::<{ty}>::unwrap_or_default()"), |
| 97 | + fmt_sugg: |val| format!("unwrap_or({val})"), |
| 98 | + }, |
| 99 | + ConcealingMethod { |
| 100 | + ty: sym::HashMapEntry, |
| 101 | + // Entry<'a, K, V, A = Global> |
| 102 | + // ^ want |
| 103 | + generic_index: 2, |
| 104 | + method: sym::or_default, |
| 105 | + fmt_msg: |ty| format!("hash_map::Entry::<'_, _, {ty}>::or_default()"), |
| 106 | + fmt_sugg: |val| format!("or_insert({val})"), |
| 107 | + }, |
| 108 | + ConcealingMethod { |
| 109 | + ty: sym::BTreeEntry, |
| 110 | + // Entry<'a, K, V, A = Global> |
| 111 | + // ^ want |
| 112 | + generic_index: 2, |
| 113 | + method: sym::or_default, |
| 114 | + fmt_msg: |ty| format!("btree_map::Entry::<'_, _, {ty}>::or_default()"), |
| 115 | + fmt_sugg: |val| format!("or_insert({val})"), |
| 116 | + }, |
| 117 | +]; |
| 118 | + |
| 119 | +/// Get default value of a type with an obvious default. |
| 120 | +/// |
| 121 | +/// # Returns |
| 122 | +/// |
| 123 | +/// If the type has an obvious default: |
| 124 | +/// |
| 125 | +/// - Default for the type |
| 126 | +/// - The type as it should be displayed in the lint message |
| 127 | +/// |
| 128 | +/// If the type is not considered to have an obvious default, return `None`. |
| 129 | +fn extract_obvious_default(cx: &LateContext<'_>, ty: Ty<'_>) -> Option<(&'static str, Cow<'static, str>)> { |
| 130 | + let ty = ty.peel_refs(); |
| 131 | + Some(if ty.is_char() { |
| 132 | + ("'\\0'", "char".into()) |
| 133 | + } else if ty.is_floating_point() { |
| 134 | + ("0.0", ty.to_string().into()) |
| 135 | + } else if ty.is_integral() { |
| 136 | + ("0", ty.to_string().into()) |
| 137 | + } else if ty.is_str() { |
| 138 | + ("\"\"", "&str".into()) |
| 139 | + } else if ty.is_bool() { |
| 140 | + ("false", "bool".into()) |
| 141 | + } else if ty.is_unit() { |
| 142 | + ("()", "()".into()) |
| 143 | + } else if is_type_diagnostic_item(cx, ty, sym::Option) { |
| 144 | + ("None", "Option<_>".into()) |
| 145 | + } else { |
| 146 | + return None; |
| 147 | + }) |
| 148 | +} |
0 commit comments