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