Skip to content

unnecessary_ip_addr_parse: new lint #14794

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6383,6 +6383,7 @@ Released 2018-09-13
[`unnecessary_first_then_check`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_first_then_check
[`unnecessary_fold`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_fold
[`unnecessary_get_then_check`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_get_then_check
[`unnecessary_ip_addr_parse`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_ip_addr_parse
[`unnecessary_join`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_join
[`unnecessary_lazy_evaluations`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_lazy_evaluations
[`unnecessary_literal_bound`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_literal_bound
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/declared_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,7 @@ pub static LINTS: &[&crate::LintInfo] = &[
crate::methods::UNNECESSARY_FIRST_THEN_CHECK_INFO,
crate::methods::UNNECESSARY_FOLD_INFO,
crate::methods::UNNECESSARY_GET_THEN_CHECK_INFO,
crate::methods::UNNECESSARY_IP_ADDR_PARSE_INFO,
crate::methods::UNNECESSARY_JOIN_INFO,
crate::methods::UNNECESSARY_LAZY_EVALUATIONS_INFO,
crate::methods::UNNECESSARY_LITERAL_UNWRAP_INFO,
Expand Down
2 changes: 2 additions & 0 deletions clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
#![feature(array_windows)]
#![feature(box_patterns)]
#![feature(cow_is_borrowed)]
#![feature(macro_metavar_expr_concat)]
#![feature(f128)]
#![feature(f16)]
#![feature(if_let_guard)]
#![feature(ip_as_octets)]
#![feature(iter_intersperse)]
#![feature(iter_partition_in_place)]
#![feature(never_type)]
Expand Down
33 changes: 33 additions & 0 deletions clippy_lints/src/methods/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ mod unnecessary_filter_map;
mod unnecessary_first_then_check;
mod unnecessary_fold;
mod unnecessary_get_then_check;
mod unnecessary_ip_addr_parse;
mod unnecessary_iter_cloned;
mod unnecessary_join;
mod unnecessary_lazy_eval;
Expand Down Expand Up @@ -4528,6 +4529,34 @@ declare_clippy_lint! {
"detect swap with a temporary value"
}

declare_clippy_lint! {
/// ### What it does
/// Checks for parsing IPv4/IPv6 string literals
///
/// ### Why is this bad?
/// Parsing known-correct IP address at runtime consumes resources and forces to
/// handle the (non-existing) errors.
///
/// ### Example
/// ```no_run
/// use std::net::Ipv4Addr;
///
/// let addr1: Ipv4Addr = "10.2.3.4".parse().unwrap();
/// let addr2: Ipv4Addr = "127.0.0.1".parse().unwrap();
/// ```
/// Use instead:
/// ```no_run
/// use std::net::Ipv4Addr;
///
/// let addr1: Ipv4Addr = Ipv4Addr::new(10, 2, 3, 4);
/// let addr2: Ipv4Addr = Ipv4Addr::LOCALHOST;
/// ```
#[clippy::version = "1.88.0"]
pub UNNECESSARY_IP_ADDR_PARSE,
complexity,
"known-correct literal IP address parsing"
}

#[expect(clippy::struct_excessive_bools)]
pub struct Methods {
avoid_breaking_exported_api: bool,
Expand Down Expand Up @@ -4706,6 +4735,7 @@ impl_lint_pass!(Methods => [
MANUAL_CONTAINS,
IO_OTHER_ERROR,
SWAP_WITH_TEMPORARY,
UNNECESSARY_IP_ADDR_PARSE,
]);

/// Extracts a method call name, args, and `Span` of the method name.
Expand Down Expand Up @@ -5420,6 +5450,9 @@ impl Methods {
Some(("or", recv, [or_arg], or_span, _)) => {
or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
},
Some(("parse", recv, [], _, _)) => {
unnecessary_ip_addr_parse::check(cx, expr, recv, self.msrv);
},
_ => {},
}
unnecessary_literal_unwrap::check(cx, expr, recv, name, args);
Expand Down
91 changes: 91 additions & 0 deletions clippy_lints/src/methods/unnecessary_ip_addr_parse.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
use std::borrow::Cow;
use std::net::{Ipv4Addr, Ipv6Addr};

use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::msrvs::{self, Msrv};
use clippy_utils::source::snippet_opt;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::{paths, sym};
use rustc_ast::LitKind;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::LateContext;
use rustc_span::Symbol;

use super::UNNECESSARY_IP_ADDR_PARSE;

pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, msrv: Msrv) {
if let ExprKind::Lit(lit) = recv.kind
&& let LitKind::Str(str, _) = lit.node
{
let consts_available = || msrv.meets(cx, msrvs::IPADDR_CONSTANTS);
let ty = cx.typeck_results().expr_ty(expr);
if paths::IPV4_ADDR.matches_ty(cx, ty)
&& let Some(sugg) = ipv4_subst(str, consts_available())
{
maybe_emit_lint(cx, expr, sugg.is_borrowed(), sugg);
} else if paths::IPV6_ADDR.matches_ty(cx, ty)
&& let Some(sugg) = ipv6_subst(str, consts_available())
{
maybe_emit_lint(cx, expr, sugg.is_borrowed(), sugg);
} else if is_type_diagnostic_item(cx, ty, sym::IpAddr) {
let with_consts = consts_available();
if let Some(sugg) = ipv4_subst(str, with_consts) {
maybe_emit_lint(cx, expr, sugg.is_borrowed(), format!("IpAddr::V4({sugg})").into());
} else if let Some(sugg) = ipv6_subst(str, with_consts) {
maybe_emit_lint(cx, expr, sugg.is_borrowed(), format!("IpAddr::V6({sugg})").into());
}
}
}
}

/// Suggests a replacement if `addr` is a correct IPv4 address
fn ipv4_subst(addr: Symbol, with_consts: bool) -> Option<Cow<'static, str>> {
addr.as_str().parse().ok().map(|ipv4: Ipv4Addr| {
if with_consts && ipv4.as_octets() == &[127, 0, 0, 1] {
"Ipv4Addr::LOCALHOST".into()
} else if with_consts && ipv4.is_broadcast() {
"Ipv4Addr::BROADCAST".into()
} else if with_consts && ipv4.is_unspecified() {
"Ipv4Addr::UNSPECIFIED".into()
} else {
let ipv4 = ipv4.as_octets();
format!("Ipv4Addr::new({}, {}, {}, {})", ipv4[0], ipv4[1], ipv4[2], ipv4[3]).into()
}
})
}

/// Suggests a replacement if `addr` is a correct IPv6 address
fn ipv6_subst(addr: Symbol, with_consts: bool) -> Option<Cow<'static, str>> {
addr.as_str().parse().ok().map(|ipv6: Ipv6Addr| {
if with_consts && ipv6.is_loopback() {
"Ipv6Addr::LOCALHOST".into()
} else if with_consts && ipv6.is_unspecified() {
"Ipv6Addr::UNSPECIFIED".into()
} else {
format!(
"Ipv6Addr::new([{}])",
ipv6.segments()
.map(|n| if n < 2 { n.to_string() } else { format!("{n:#x}") })
.join(", ")
)
.into()
}
})
}

/// Emit the lint if the length of `sugg` is shorter than the original `expr` span, or if `force` is
/// set.
fn maybe_emit_lint(cx: &LateContext<'_>, expr: &Expr<'_>, force: bool, sugg: Cow<'_, str>) {
if force || snippet_opt(cx, expr.span).is_some_and(|snip| snip.len() >= sugg.len()) {
span_lint_and_sugg(
cx,
UNNECESSARY_IP_ADDR_PARSE,
expr.span,
"unnecessary runtime parsing of IP address",
"use",
sugg.into(),
Applicability::MaybeIncorrect,
);
}
}
2 changes: 1 addition & 1 deletion clippy_utils/src/msrvs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ msrv_aliases! {
1,33,0 { UNDERSCORE_IMPORTS }
1,32,0 { CONST_IS_POWER_OF_TWO }
1,31,0 { OPTION_REPLACE }
1,30,0 { ITERATOR_FIND_MAP, TOOL_ATTRIBUTES }
1,30,0 { ITERATOR_FIND_MAP, TOOL_ATTRIBUTES, IPADDR_CONSTANTS }
1,29,0 { ITER_FLATTEN }
1,28,0 { FROM_BOOL, REPEAT_WITH, SLICE_FROM_REF }
1,27,0 { ITERATOR_TRY_FOLD }
Expand Down
2 changes: 2 additions & 0 deletions clippy_utils/src/paths.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ pub static ALIGN_OF: PathLookup = value_path!(core::mem::align_of);
pub static CHAR_TO_DIGIT: PathLookup = value_path!(char::to_digit);
pub static IO_ERROR_NEW: PathLookup = value_path!(std::io::Error::new);
pub static IO_ERRORKIND_OTHER_CTOR: PathLookup = value_path!(std::io::ErrorKind::Other);
pub static IPV4_ADDR: PathLookup = type_path!(core::net::Ipv4Addr);
pub static IPV6_ADDR: PathLookup = type_path!(core::net::Ipv6Addr);
pub static ITER_STEP: PathLookup = type_path!(core::iter::Step);
pub static SLICE_FROM_REF: PathLookup = value_path!(core::slice::from_ref);

Expand Down
3 changes: 3 additions & 0 deletions clippy_utils/src/sym.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ generate! {
into_owned,
IntoIter,
io,
Ipv4Addr,
Ipv6Addr,
is_ascii,
is_empty,
is_err,
Expand Down Expand Up @@ -126,6 +128,7 @@ generate! {
mut_ptr,
mutex,
needless_return,
net,
next_tuple,
Octal,
once_cell,
Expand Down
42 changes: 42 additions & 0 deletions tests/ui/unnecessary_ip_addr_parse.fixed
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#![warn(clippy::unnecessary_ip_addr_parse)]

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

fn main() {
_ = Ipv4Addr::new(137, 194, 161, 2);
//~^ unnecessary_ip_addr_parse

_ = Ipv4Addr::LOCALHOST;
//~^ unnecessary_ip_addr_parse

_ = Ipv4Addr::BROADCAST;
//~^ unnecessary_ip_addr_parse

_ = Ipv4Addr::UNSPECIFIED;
//~^ unnecessary_ip_addr_parse

// Wrong address family
_ = "::1".parse::<Ipv4Addr>().unwrap();
_ = "127.0.0.1".parse::<Ipv6Addr>().unwrap();

_ = Ipv6Addr::LOCALHOST;
//~^ unnecessary_ip_addr_parse

_ = Ipv6Addr::UNSPECIFIED;
//~^ unnecessary_ip_addr_parse

_ = IpAddr::V6(Ipv6Addr::LOCALHOST);
//~^ unnecessary_ip_addr_parse

_ = IpAddr::V6(Ipv6Addr::UNSPECIFIED);
//~^ unnecessary_ip_addr_parse

// The substition text would be larger than the original and wouldn't use constants
_ = "2a04:8ec0:0:47::131".parse::<Ipv6Addr>().unwrap();
_ = "2a04:8ec0:0:47::131".parse::<IpAddr>().unwrap();
}

#[clippy::msrv = "1.29"]
fn msrv_under() {
_ = "::".parse::<IpAddr>().unwrap();
}
42 changes: 42 additions & 0 deletions tests/ui/unnecessary_ip_addr_parse.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#![warn(clippy::unnecessary_ip_addr_parse)]

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

fn main() {
_ = "137.194.161.2".parse::<Ipv4Addr>().unwrap();
//~^ unnecessary_ip_addr_parse

_ = "127.0.0.1".parse::<Ipv4Addr>().unwrap();
//~^ unnecessary_ip_addr_parse

_ = "255.255.255.255".parse::<Ipv4Addr>().unwrap();
//~^ unnecessary_ip_addr_parse

_ = "0.0.0.0".parse::<Ipv4Addr>().unwrap();
//~^ unnecessary_ip_addr_parse

// Wrong address family
_ = "::1".parse::<Ipv4Addr>().unwrap();
_ = "127.0.0.1".parse::<Ipv6Addr>().unwrap();

_ = "::1".parse::<Ipv6Addr>().unwrap();
//~^ unnecessary_ip_addr_parse

_ = "::".parse::<Ipv6Addr>().unwrap();
//~^ unnecessary_ip_addr_parse

_ = "::1".parse::<IpAddr>().unwrap();
//~^ unnecessary_ip_addr_parse

_ = "::".parse::<IpAddr>().unwrap();
//~^ unnecessary_ip_addr_parse

// The substition text would be larger than the original and wouldn't use constants
_ = "2a04:8ec0:0:47::131".parse::<Ipv6Addr>().unwrap();
_ = "2a04:8ec0:0:47::131".parse::<IpAddr>().unwrap();
}

#[clippy::msrv = "1.29"]
fn msrv_under() {
_ = "::".parse::<IpAddr>().unwrap();
}
53 changes: 53 additions & 0 deletions tests/ui/unnecessary_ip_addr_parse.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
error: unnecessary runtime parsing of IP address
--> tests/ui/unnecessary_ip_addr_parse.rs:6:9
|
LL | _ = "137.194.161.2".parse::<Ipv4Addr>().unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `Ipv4Addr::new(137, 194, 161, 2)`
|
= note: `-D clippy::unnecessary-ip-addr-parse` implied by `-D warnings`
= help: to override `-D warnings` add `#[allow(clippy::unnecessary_ip_addr_parse)]`

error: unnecessary runtime parsing of IP address
--> tests/ui/unnecessary_ip_addr_parse.rs:9:9
|
LL | _ = "127.0.0.1".parse::<Ipv4Addr>().unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `Ipv4Addr::LOCALHOST`

error: unnecessary runtime parsing of IP address
--> tests/ui/unnecessary_ip_addr_parse.rs:12:9
|
LL | _ = "255.255.255.255".parse::<Ipv4Addr>().unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `Ipv4Addr::BROADCAST`

error: unnecessary runtime parsing of IP address
--> tests/ui/unnecessary_ip_addr_parse.rs:15:9
|
LL | _ = "0.0.0.0".parse::<Ipv4Addr>().unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `Ipv4Addr::UNSPECIFIED`

error: unnecessary runtime parsing of IP address
--> tests/ui/unnecessary_ip_addr_parse.rs:22:9
|
LL | _ = "::1".parse::<Ipv6Addr>().unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `Ipv6Addr::LOCALHOST`

error: unnecessary runtime parsing of IP address
--> tests/ui/unnecessary_ip_addr_parse.rs:25:9
|
LL | _ = "::".parse::<Ipv6Addr>().unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `Ipv6Addr::UNSPECIFIED`

error: unnecessary runtime parsing of IP address
--> tests/ui/unnecessary_ip_addr_parse.rs:28:9
|
LL | _ = "::1".parse::<IpAddr>().unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `IpAddr::V6(Ipv6Addr::LOCALHOST)`

error: unnecessary runtime parsing of IP address
--> tests/ui/unnecessary_ip_addr_parse.rs:31:9
|
LL | _ = "::".parse::<IpAddr>().unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `IpAddr::V6(Ipv6Addr::UNSPECIFIED)`

error: aborting due to 8 previous errors