]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/ptr_offset_with_cast.rs
separate the receiver from arguments in HIR under /clippy
[rust.git] / clippy_lints / src / ptr_offset_with_cast.rs
1 use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg};
2 use clippy_utils::source::snippet_opt;
3 use rustc_errors::Applicability;
4 use rustc_hir::{Expr, ExprKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7 use rustc_span::sym;
8 use std::fmt;
9
10 declare_clippy_lint! {
11     /// ### What it does
12     /// Checks for usage of the `offset` pointer method with a `usize` casted to an
13     /// `isize`.
14     ///
15     /// ### Why is this bad?
16     /// If we’re always increasing the pointer address, we can avoid the numeric
17     /// cast by using the `add` method instead.
18     ///
19     /// ### Example
20     /// ```rust
21     /// let vec = vec![b'a', b'b', b'c'];
22     /// let ptr = vec.as_ptr();
23     /// let offset = 1_usize;
24     ///
25     /// unsafe {
26     ///     ptr.offset(offset as isize);
27     /// }
28     /// ```
29     ///
30     /// Could be written:
31     ///
32     /// ```rust
33     /// let vec = vec![b'a', b'b', b'c'];
34     /// let ptr = vec.as_ptr();
35     /// let offset = 1_usize;
36     ///
37     /// unsafe {
38     ///     ptr.add(offset);
39     /// }
40     /// ```
41     #[clippy::version = "1.30.0"]
42     pub PTR_OFFSET_WITH_CAST,
43     complexity,
44     "unneeded pointer offset cast"
45 }
46
47 declare_lint_pass!(PtrOffsetWithCast => [PTR_OFFSET_WITH_CAST]);
48
49 impl<'tcx> LateLintPass<'tcx> for PtrOffsetWithCast {
50     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
51         // Check if the expressions is a ptr.offset or ptr.wrapping_offset method call
52         let (receiver_expr, arg_expr, method) = match expr_as_ptr_offset_call(cx, expr) {
53             Some(call_arg) => call_arg,
54             None => return,
55         };
56
57         // Check if the argument to the method call is a cast from usize
58         let cast_lhs_expr = match expr_as_cast_from_usize(cx, arg_expr) {
59             Some(cast_lhs_expr) => cast_lhs_expr,
60             None => return,
61         };
62
63         let msg = format!("use of `{}` with a `usize` casted to an `isize`", method);
64         if let Some(sugg) = build_suggestion(cx, method, receiver_expr, cast_lhs_expr) {
65             span_lint_and_sugg(
66                 cx,
67                 PTR_OFFSET_WITH_CAST,
68                 expr.span,
69                 &msg,
70                 "try",
71                 sugg,
72                 Applicability::MachineApplicable,
73             );
74         } else {
75             span_lint(cx, PTR_OFFSET_WITH_CAST, expr.span, &msg);
76         }
77     }
78 }
79
80 // If the given expression is a cast from a usize, return the lhs of the cast
81 fn expr_as_cast_from_usize<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
82     if let ExprKind::Cast(cast_lhs_expr, _) = expr.kind {
83         if is_expr_ty_usize(cx, cast_lhs_expr) {
84             return Some(cast_lhs_expr);
85         }
86     }
87     None
88 }
89
90 // If the given expression is a ptr::offset  or ptr::wrapping_offset method call, return the
91 // receiver, the arg of the method call, and the method.
92 fn expr_as_ptr_offset_call<'tcx>(
93     cx: &LateContext<'tcx>,
94     expr: &'tcx Expr<'_>,
95 ) -> Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>, Method)> {
96     if let ExprKind::MethodCall(path_segment, arg_0, [arg_1, ..], _) = &expr.kind {
97         if is_expr_ty_raw_ptr(cx, arg_0) {
98             if path_segment.ident.name == sym::offset {
99                 return Some((arg_0, arg_1, Method::Offset));
100             }
101             if path_segment.ident.name == sym!(wrapping_offset) {
102                 return Some((arg_0, arg_1, Method::WrappingOffset));
103             }
104         }
105     }
106     None
107 }
108
109 // Is the type of the expression a usize?
110 fn is_expr_ty_usize<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> bool {
111     cx.typeck_results().expr_ty(expr) == cx.tcx.types.usize
112 }
113
114 // Is the type of the expression a raw pointer?
115 fn is_expr_ty_raw_ptr<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> bool {
116     cx.typeck_results().expr_ty(expr).is_unsafe_ptr()
117 }
118
119 fn build_suggestion<'tcx>(
120     cx: &LateContext<'tcx>,
121     method: Method,
122     receiver_expr: &Expr<'_>,
123     cast_lhs_expr: &Expr<'_>,
124 ) -> Option<String> {
125     let receiver = snippet_opt(cx, receiver_expr.span)?;
126     let cast_lhs = snippet_opt(cx, cast_lhs_expr.span)?;
127     Some(format!("{}.{}({})", receiver, method.suggestion(), cast_lhs))
128 }
129
130 #[derive(Copy, Clone)]
131 enum Method {
132     Offset,
133     WrappingOffset,
134 }
135
136 impl Method {
137     #[must_use]
138     fn suggestion(self) -> &'static str {
139         match self {
140             Self::Offset => "add",
141             Self::WrappingOffset => "wrapping_add",
142         }
143     }
144 }
145
146 impl fmt::Display for Method {
147     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148         match self {
149             Self::Offset => write!(f, "offset"),
150             Self::WrappingOffset => write!(f, "wrapping_offset"),
151         }
152     }
153 }