1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::is_integer_literal;
3 use clippy_utils::sugg::Sugg;
4 use clippy_utils::ty::{is_type_diagnostic_item, is_type_lang_item};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::{def, Expr, ExprKind, LangItem, PrimTy, QPath, TyKind};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_middle::ty::Ty;
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 use rustc_span::symbol::sym;
13 declare_clippy_lint! {
16 /// Checks for function invocations of the form `primitive::from_str_radix(s, 10)`
18 /// ### Why is this bad?
20 /// This specific common use case can be rewritten as `s.parse::<primitive>()`
21 /// (and in most cases, the turbofish can be removed), which reduces code length
24 /// ### Known problems
26 /// This lint may suggest using (&<expression>).parse() instead of <expression>.parse() directly
27 /// in some cases, which is correct but adds unnecessary complexity to the code.
31 /// let input: &str = get_input();
32 /// let num = u16::from_str_radix(input, 10)?;
36 /// let input: &str = get_input();
37 /// let num: u16 = input.parse()?;
39 #[clippy::version = "1.52.0"]
40 pub FROM_STR_RADIX_10,
42 "from_str_radix with radix 10"
45 declare_lint_pass!(FromStrRadix10 => [FROM_STR_RADIX_10]);
47 impl<'tcx> LateLintPass<'tcx> for FromStrRadix10 {
48 fn check_expr(&mut self, cx: &LateContext<'tcx>, exp: &Expr<'tcx>) {
50 if let ExprKind::Call(maybe_path, [src, radix]) = &exp.kind;
51 if let ExprKind::Path(QPath::TypeRelative(ty, pathseg)) = &maybe_path.kind;
53 // check if the first part of the path is some integer primitive
54 if let TyKind::Path(ty_qpath) = &ty.kind;
55 let ty_res = cx.qpath_res(ty_qpath, ty.hir_id);
56 if let def::Res::PrimTy(prim_ty) = ty_res;
57 if matches!(prim_ty, PrimTy::Int(_) | PrimTy::Uint(_));
59 // check if the second part of the path indeed calls the associated
60 // function `from_str_radix`
61 if pathseg.ident.name.as_str() == "from_str_radix";
63 // check if the second argument is a primitive `10`
64 if is_integer_literal(radix, 10);
67 let expr = if let ExprKind::AddrOf(_, _, expr) = &src.kind {
68 let ty = cx.typeck_results().expr_ty(expr);
69 if is_ty_stringish(cx, ty) {
78 let sugg = Sugg::hir_with_applicability(
82 &mut Applicability::MachineApplicable
89 "this call to `from_str_radix` can be replaced with a call to `str::parse`",
91 format!("{sugg}.parse::<{}>()", prim_ty.name_str()),
92 Applicability::MaybeIncorrect
99 /// Checks if a Ty is `String` or `&str`
100 fn is_ty_stringish(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
101 is_type_lang_item(cx, ty, LangItem::String) || is_type_diagnostic_item(cx, ty, sym::str)