]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/from_str_radix_10.rs
Rollup merge of #105123 - BlackHoleFox:fixing-the-macos-deployment, r=oli-obk
[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::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;
12
13 declare_clippy_lint! {
14     /// ### What it does
15     ///
16     /// Checks for function invocations of the form `primitive::from_str_radix(s, 10)`
17     ///
18     /// ### Why is this bad?
19     ///
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
22     /// and complexity.
23     ///
24     /// ### Known problems
25     ///
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.
28     ///
29     /// ### Example
30     /// ```ignore
31     /// let input: &str = get_input();
32     /// let num = u16::from_str_radix(input, 10)?;
33     /// ```
34     /// Use instead:
35     /// ```ignore
36     /// let input: &str = get_input();
37     /// let num: u16 = input.parse()?;
38     /// ```
39     #[clippy::version = "1.52.0"]
40     pub FROM_STR_RADIX_10,
41     style,
42     "from_str_radix with radix 10"
43 }
44
45 declare_lint_pass!(FromStrRadix10 => [FROM_STR_RADIX_10]);
46
47 impl<'tcx> LateLintPass<'tcx> for FromStrRadix10 {
48     fn check_expr(&mut self, cx: &LateContext<'tcx>, exp: &Expr<'tcx>) {
49         if_chain! {
50             if let ExprKind::Call(maybe_path, [src, radix]) = &exp.kind;
51             if let ExprKind::Path(QPath::TypeRelative(ty, pathseg)) = &maybe_path.kind;
52
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(_));
58
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";
62
63             // check if the second argument is a primitive `10`
64             if is_integer_literal(radix, 10);
65
66             then {
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) {
70                         expr
71                     } else {
72                         &src
73                     }
74                 } else {
75                     &src
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!("{sugg}.parse::<{}>()", 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_lang_item(cx, ty, LangItem::String) || is_type_diagnostic_item(cx, ty, sym::str)
102 }