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