]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/ptr_offset_with_cast.rs
panic at map_unit_fn.rs:202 for map() without args
[rust.git] / clippy_lints / src / ptr_offset_with_cast.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use crate::rustc::{declare_tool_lint, hir, lint, lint_array};
11 use crate::rustc_errors::Applicability;
12 use crate::utils;
13 use std::fmt;
14
15 /// **What it does:** Checks for usage of the `offset` pointer method with a `usize` casted to an
16 /// `isize`.
17 ///
18 /// **Why is this bad?** If we’re always increasing the pointer address, we can avoid the numeric
19 /// cast by using the `add` method instead.
20 ///
21 /// **Known problems:** None
22 ///
23 /// **Example:**
24 /// ```rust
25 /// let vec = vec![b'a', b'b', b'c'];
26 /// let ptr = vec.as_ptr();
27 /// let offset = 1_usize;
28 ///
29 /// unsafe {
30 ///     ptr.offset(offset as isize);
31 /// }
32 /// ```
33 ///
34 /// Could be written:
35 ///
36 /// ```rust
37 /// let vec = vec![b'a', b'b', b'c'];
38 /// let ptr = vec.as_ptr();
39 /// let offset = 1_usize;
40 ///
41 /// unsafe {
42 ///     ptr.add(offset);
43 /// }
44 /// ```
45 declare_clippy_lint! {
46     pub PTR_OFFSET_WITH_CAST,
47     complexity,
48     "unneeded pointer offset cast"
49 }
50
51 #[derive(Copy, Clone, Debug)]
52 pub struct Pass;
53
54 impl lint::LintPass for Pass {
55     fn get_lints(&self) -> lint::LintArray {
56         lint_array!(PTR_OFFSET_WITH_CAST)
57     }
58 }
59
60 impl<'a, 'tcx> lint::LateLintPass<'a, 'tcx> for Pass {
61     fn check_expr(&mut self, cx: &lint::LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
62         // Check if the expressions is a ptr.offset or ptr.wrapping_offset method call
63         let (receiver_expr, arg_expr, method) = match expr_as_ptr_offset_call(cx, expr) {
64             Some(call_arg) => call_arg,
65             None => return,
66         };
67
68         // Check if the argument to the method call is a cast from usize
69         let cast_lhs_expr = match expr_as_cast_from_usize(cx, arg_expr) {
70             Some(cast_lhs_expr) => cast_lhs_expr,
71             None => return,
72         };
73
74         let msg = format!("use of `{}` with a `usize` casted to an `isize`", method);
75         if let Some(sugg) = build_suggestion(cx, method, receiver_expr, cast_lhs_expr) {
76             utils::span_lint_and_sugg(
77                 cx,
78                 PTR_OFFSET_WITH_CAST,
79                 expr.span,
80                 &msg,
81                 "try",
82                 sugg,
83                 Applicability::MachineApplicable,
84             );
85         } else {
86             utils::span_lint(cx, PTR_OFFSET_WITH_CAST, expr.span, &msg);
87         }
88     }
89 }
90
91 // If the given expression is a cast from a usize, return the lhs of the cast
92 fn expr_as_cast_from_usize<'a, 'tcx>(
93     cx: &lint::LateContext<'a, 'tcx>,
94     expr: &'tcx hir::Expr,
95 ) -> Option<&'tcx hir::Expr> {
96     if let hir::ExprKind::Cast(ref cast_lhs_expr, _) = expr.node {
97         if is_expr_ty_usize(cx, &cast_lhs_expr) {
98             return Some(cast_lhs_expr);
99         }
100     }
101     None
102 }
103
104 // If the given expression is a ptr::offset  or ptr::wrapping_offset method call, return the
105 // receiver, the arg of the method call, and the method.
106 fn expr_as_ptr_offset_call<'a, 'tcx>(
107     cx: &lint::LateContext<'a, 'tcx>,
108     expr: &'tcx hir::Expr,
109 ) -> Option<(&'tcx hir::Expr, &'tcx hir::Expr, Method)> {
110     if let hir::ExprKind::MethodCall(ref path_segment, _, ref args) = expr.node {
111         if is_expr_ty_raw_ptr(cx, &args[0]) {
112             if path_segment.ident.name == "offset" {
113                 return Some((&args[0], &args[1], Method::Offset));
114             }
115             if path_segment.ident.name == "wrapping_offset" {
116                 return Some((&args[0], &args[1], Method::WrappingOffset));
117             }
118         }
119     }
120     None
121 }
122
123 // Is the type of the expression a usize?
124 fn is_expr_ty_usize<'a, 'tcx>(cx: &lint::LateContext<'a, 'tcx>, expr: &hir::Expr) -> bool {
125     cx.tables.expr_ty(expr) == cx.tcx.types.usize
126 }
127
128 // Is the type of the expression a raw pointer?
129 fn is_expr_ty_raw_ptr<'a, 'tcx>(cx: &lint::LateContext<'a, 'tcx>, expr: &hir::Expr) -> bool {
130     cx.tables.expr_ty(expr).is_unsafe_ptr()
131 }
132
133 fn build_suggestion<'a, 'tcx>(
134     cx: &lint::LateContext<'a, 'tcx>,
135     method: Method,
136     receiver_expr: &hir::Expr,
137     cast_lhs_expr: &hir::Expr,
138 ) -> Option<String> {
139     let receiver = utils::snippet_opt(cx, receiver_expr.span)?;
140     let cast_lhs = utils::snippet_opt(cx, cast_lhs_expr.span)?;
141     Some(format!("{}.{}({})", receiver, method.suggestion(), cast_lhs))
142 }
143
144 #[derive(Copy, Clone)]
145 enum Method {
146     Offset,
147     WrappingOffset,
148 }
149
150 impl Method {
151     fn suggestion(self) -> &'static str {
152         match self {
153             Method::Offset => "add",
154             Method::WrappingOffset => "wrapping_add",
155         }
156     }
157 }
158
159 impl fmt::Display for Method {
160     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161         match self {
162             Method::Offset => write!(f, "offset"),
163             Method::WrappingOffset => write!(f, "wrapping_offset"),
164         }
165     }
166 }