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