|
| 1 | +use std::borrow::Cow; |
| 2 | +use std::fmt::Display; |
| 3 | +use std::net::{Ipv4Addr, Ipv6Addr}; |
| 4 | +use std::str::FromStr; |
| 5 | + |
| 6 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 7 | +use clippy_utils::msrvs::{self, Msrv}; |
| 8 | +use clippy_utils::source::SpanRangeExt; |
| 9 | +use clippy_utils::sym; |
| 10 | +use clippy_utils::ty::is_type_diagnostic_item; |
| 11 | +use rustc_ast::LitKind; |
| 12 | +use rustc_errors::Applicability; |
| 13 | +use rustc_hir::{Expr, ExprKind}; |
| 14 | +use rustc_lint::LateContext; |
| 15 | +use rustc_middle::ty::{self, Ty}; |
| 16 | +use rustc_span::Symbol; |
| 17 | + |
| 18 | +use super::PARSED_STRING_LITERALS; |
| 19 | + |
| 20 | +pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, msrv: Msrv) { |
| 21 | + if let ExprKind::Lit(lit) = recv.kind |
| 22 | + && let LitKind::Str(lit, _) = lit.node |
| 23 | + { |
| 24 | + let ty = cx.typeck_results().expr_ty(expr); |
| 25 | + if !check_primitive(cx, expr, lit, ty) { |
| 26 | + check_ipaddr(cx, expr, lit, ty, msrv); |
| 27 | + } |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +fn check_primitive(cx: &LateContext<'_>, expr: &Expr<'_>, lit: Symbol, ty: Ty<'_>) -> bool { |
| 32 | + macro_rules! number { |
| 33 | + ($kind:ident, $expr:expr, $msg:expr, [$($subkind:ident => $ty:ident),*$(,)?]$(,)?) => {{ |
| 34 | + match $expr { |
| 35 | + $(ty::$kind::$subkind => (try_parse::<$ty>(lit, Some(stringify!($ty))), $msg),)* |
| 36 | + #[allow(unreachable_patterns)] |
| 37 | + _ => return false, |
| 38 | + } |
| 39 | + }}; |
| 40 | + } |
| 41 | + |
| 42 | + if let (Some(subst), entity) = match ty.kind() { |
| 43 | + ty::Int(int_ty) => number!(IntTy, int_ty, "a signed integer", |
| 44 | + [Isize => isize, I8 => i8, I16 => i16, I32 => i32, I64 => i64, I128 => i128]), |
| 45 | + ty::Uint(uint_ty) => number!(UintTy, uint_ty, "an unsigned integer", |
| 46 | + [Usize => usize, U8 => u8, U16 => u16, U32 => u32, U64 => u64, U128 => u128]), |
| 47 | + // FIXME: ignore `f16` and `f128` for now as they cannot use the default formatter |
| 48 | + ty::Float(float_ty) => number!(FloatTy, float_ty, "a real number", |
| 49 | + [F32 => f32, F64 => f64]), |
| 50 | + ty::Bool => (try_parse::<bool>(lit, None), "a boolean"), |
| 51 | + ty::Char if let Ok(ch) = lit.as_str().parse::<char>() => (Some(format!("{:?}", ch)), "a character"), |
| 52 | + _ => return false, |
| 53 | + } { |
| 54 | + maybe_emit_lint(cx, expr, false, entity, subst.into(), Applicability::MachineApplicable); |
| 55 | + } |
| 56 | + true |
| 57 | +} |
| 58 | + |
| 59 | +fn check_ipaddr(cx: &LateContext<'_>, expr: &Expr<'_>, lit: Symbol, ty: Ty<'_>, msrv: Msrv) { |
| 60 | + static IPV4_ENTITY: &str = "an IPv4 address"; |
| 61 | + static IPV6_ENTITY: &str = "an IPv6 address"; |
| 62 | + let ipaddr_consts_available = || msrv.meets(cx, msrvs::IPADDR_CONSTANTS); |
| 63 | + if is_type_diagnostic_item(cx, ty, sym::Ipv4Addr) |
| 64 | + && let Some(sugg) = ipv4_subst(lit, ipaddr_consts_available()) |
| 65 | + { |
| 66 | + maybe_emit_lint( |
| 67 | + cx, |
| 68 | + expr, |
| 69 | + sugg.is_borrowed(), |
| 70 | + IPV4_ENTITY, |
| 71 | + sugg, |
| 72 | + Applicability::MaybeIncorrect, |
| 73 | + ); |
| 74 | + } else if is_type_diagnostic_item(cx, ty, sym::Ipv6Addr) |
| 75 | + && let Some(sugg) = ipv6_subst(lit, ipaddr_consts_available()) |
| 76 | + { |
| 77 | + maybe_emit_lint( |
| 78 | + cx, |
| 79 | + expr, |
| 80 | + sugg.is_borrowed(), |
| 81 | + IPV6_ENTITY, |
| 82 | + sugg, |
| 83 | + Applicability::MaybeIncorrect, |
| 84 | + ); |
| 85 | + } else if is_type_diagnostic_item(cx, ty, sym::IpAddr) { |
| 86 | + let with_consts = ipaddr_consts_available(); |
| 87 | + if let Some(sugg) = ipv4_subst(lit, with_consts) { |
| 88 | + maybe_emit_lint( |
| 89 | + cx, |
| 90 | + expr, |
| 91 | + sugg.is_borrowed(), |
| 92 | + IPV4_ENTITY, |
| 93 | + format!("IpAddr::V4({sugg})").into(), |
| 94 | + Applicability::MaybeIncorrect, |
| 95 | + ); |
| 96 | + } else if let Some(sugg) = ipv6_subst(lit, with_consts) { |
| 97 | + maybe_emit_lint( |
| 98 | + cx, |
| 99 | + expr, |
| 100 | + sugg.is_borrowed(), |
| 101 | + IPV6_ENTITY, |
| 102 | + format!("IpAddr::V6({sugg})").into(), |
| 103 | + Applicability::MaybeIncorrect, |
| 104 | + ); |
| 105 | + } |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +/// Suggests a replacement if `addr` is a correct IPv4 address |
| 110 | +fn ipv4_subst(addr: Symbol, with_consts: bool) -> Option<Cow<'static, str>> { |
| 111 | + addr.as_str().parse().ok().map(|ipv4: Ipv4Addr| { |
| 112 | + if with_consts && ipv4.as_octets() == &[127, 0, 0, 1] { |
| 113 | + "Ipv4Addr::LOCALHOST".into() |
| 114 | + } else if with_consts && ipv4.is_broadcast() { |
| 115 | + "Ipv4Addr::BROADCAST".into() |
| 116 | + } else if with_consts && ipv4.is_unspecified() { |
| 117 | + "Ipv4Addr::UNSPECIFIED".into() |
| 118 | + } else { |
| 119 | + let ipv4 = ipv4.as_octets(); |
| 120 | + format!("Ipv4Addr::new({}, {}, {}, {})", ipv4[0], ipv4[1], ipv4[2], ipv4[3]).into() |
| 121 | + } |
| 122 | + }) |
| 123 | +} |
| 124 | + |
| 125 | +/// Suggests a replacement if `addr` is a correct IPv6 address |
| 126 | +fn ipv6_subst(addr: Symbol, with_consts: bool) -> Option<Cow<'static, str>> { |
| 127 | + addr.as_str().parse().ok().map(|ipv6: Ipv6Addr| { |
| 128 | + if with_consts && ipv6.is_loopback() { |
| 129 | + "Ipv6Addr::LOCALHOST".into() |
| 130 | + } else if with_consts && ipv6.is_unspecified() { |
| 131 | + "Ipv6Addr::UNSPECIFIED".into() |
| 132 | + } else { |
| 133 | + format!( |
| 134 | + "Ipv6Addr::new([{}])", |
| 135 | + ipv6.segments() |
| 136 | + .map(|n| if n < 2 { n.to_string() } else { format!("{n:#x}") }) |
| 137 | + .join(", ") |
| 138 | + ) |
| 139 | + .into() |
| 140 | + } |
| 141 | + }) |
| 142 | +} |
| 143 | + |
| 144 | +fn try_parse<T: FromStr + Display>(lit: Symbol, suffix: Option<&str>) -> Option<String> { |
| 145 | + lit.as_str() |
| 146 | + .parse::<T>() |
| 147 | + .ok() |
| 148 | + .map(|_| suffix.map_or_else(|| lit.to_string(), |suffix| format!("{lit}_{suffix}"))) |
| 149 | +} |
| 150 | + |
| 151 | +/// Emit the lint if the length of `sugg` is no longer than the original `expr` span, or if `force` |
| 152 | +/// is set. |
| 153 | +fn maybe_emit_lint( |
| 154 | + cx: &LateContext<'_>, |
| 155 | + expr: &Expr<'_>, |
| 156 | + force: bool, |
| 157 | + entity: &str, |
| 158 | + sugg: Cow<'_, str>, |
| 159 | + applicability: Applicability, |
| 160 | +) { |
| 161 | + if force || expr.span.check_source_text(cx, |snip| snip.len() >= sugg.len()) { |
| 162 | + span_lint_and_sugg( |
| 163 | + cx, |
| 164 | + PARSED_STRING_LITERALS, |
| 165 | + expr.span, |
| 166 | + format!("unnecessary runtime parsing of {entity}"), |
| 167 | + "use", |
| 168 | + sugg.into(), |
| 169 | + applicability, |
| 170 | + ); |
| 171 | + } |
| 172 | +} |
0 commit comments