]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/from_str_radix_10.rs
Auto merge of #85690 - bstrie:m2_arena, r=jackh726,nagisa
[rust.git] / src / tools / clippy / clippy_lints / src / from_str_radix_10.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::sugg::Sugg;
3 use clippy_utils::ty::is_type_diagnostic_item;
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir::{def, Expr, ExprKind, PrimTy, QPath, TyKind};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_middle::ty::Ty;
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use rustc_span::symbol::sym;
11
12 declare_clippy_lint! {
13     /// ### What it does
14     ///
15     /// Checks for function invocations of the form `primitive::from_str_radix(s, 10)`
16     ///
17     /// ### Why is this bad?
18     ///
19     /// This specific common use case can be rewritten as `s.parse::<primitive>()`
20     /// (and in most cases, the turbofish can be removed), which reduces code length
21     /// and complexity.
22     ///
23     /// ### Known problems
24     ///
25     /// This lint may suggest using (&<expression>).parse() instead of <expression>.parse() directly
26     /// in some cases, which is correct but adds unnecessary complexity to the code.
27     ///
28     /// ### Example
29     /// ```ignore
30     /// let input: &str = get_input();
31     /// let num = u16::from_str_radix(input, 10)?;
32     /// ```
33     /// Use instead:
34     /// ```ignore
35     /// let input: &str = get_input();
36     /// let num: u16 = input.parse()?;
37     /// ```
38     pub FROM_STR_RADIX_10,
39     style,
40     "from_str_radix with radix 10"
41 }
42
43 declare_lint_pass!(FromStrRadix10 => [FROM_STR_RADIX_10]);
44
45 impl LateLintPass<'tcx> for FromStrRadix10 {
46     fn check_expr(&mut self, cx: &LateContext<'tcx>, exp: &Expr<'tcx>) {
47         if_chain! {
48             if let ExprKind::Call(maybe_path, arguments) = &exp.kind;
49             if let ExprKind::Path(QPath::TypeRelative(ty, pathseg)) = &maybe_path.kind;
50
51             // check if the first part of the path is some integer primitive
52             if let TyKind::Path(ty_qpath) = &ty.kind;
53             let ty_res = cx.qpath_res(ty_qpath, ty.hir_id);
54             if let def::Res::PrimTy(prim_ty) = ty_res;
55             if matches!(prim_ty, PrimTy::Int(_) | PrimTy::Uint(_));
56
57             // check if the second part of the path indeed calls the associated
58             // function `from_str_radix`
59             if pathseg.ident.name.as_str() == "from_str_radix";
60
61             // check if the second argument is a primitive `10`
62             if arguments.len() == 2;
63             if let ExprKind::Lit(lit) = &arguments[1].kind;
64             if let rustc_ast::ast::LitKind::Int(10, _) = lit.node;
65
66             then {
67                 let expr = if let ExprKind::AddrOf(_, _, expr) = &arguments[0].kind {
68                     let ty = cx.typeck_results().expr_ty(expr);
69                     if is_ty_stringish(cx, ty) {
70                         expr
71                     } else {
72                         &arguments[0]
73                     }
74                 } else {
75                     &arguments[0]
76                 };
77
78                 let sugg = Sugg::hir_with_applicability(
79                     cx,
80                     expr,
81                     "<string>",
82                     &mut Applicability::MachineApplicable
83                 ).maybe_par();
84
85                 span_lint_and_sugg(
86                     cx,
87                     FROM_STR_RADIX_10,
88                     exp.span,
89                     "this call to `from_str_radix` can be replaced with a call to `str::parse`",
90                     "try",
91                     format!("{}.parse::<{}>()", sugg, prim_ty.name_str()),
92                     Applicability::MaybeIncorrect
93                 );
94             }
95         }
96     }
97 }
98
99 /// Checks if a Ty is `String` or `&str`
100 fn is_ty_stringish(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
101     is_type_diagnostic_item(cx, ty, sym::string_type) || is_type_diagnostic_item(cx, ty, sym::str)
102 }