]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/ptr_offset_with_cast.rs
new_ret_no_self: add sample from #3313 to Known Problems section.
[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
11 use crate::rustc::{declare_tool_lint, hir, lint, lint_array};
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 { ptr.offset(offset as isize); }
30 /// ```
31 ///
32 /// Could be written:
33 ///
34 /// ```rust
35 /// let vec = vec![b'a', b'b', b'c'];
36 /// let ptr = vec.as_ptr();
37 /// let offset = 1_usize;
38 ///
39 /// unsafe { ptr.add(offset); }
40 /// ```
41 declare_clippy_lint! {
42     pub PTR_OFFSET_WITH_CAST,
43     complexity,
44     "unneeded pointer offset cast"
45 }
46
47 #[derive(Copy, Clone, Debug)]
48 pub struct Pass;
49
50 impl lint::LintPass for Pass {
51     fn get_lints(&self) -> lint::LintArray {
52         lint_array!(PTR_OFFSET_WITH_CAST)
53     }
54 }
55
56 impl<'a, 'tcx> lint::LateLintPass<'a, 'tcx> for Pass {
57     fn check_expr(&mut self, cx: &lint::LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
58         // Check if the expressions is a ptr.offset or ptr.wrapping_offset method call
59         let (receiver_expr, arg_expr, method) = match expr_as_ptr_offset_call(cx, expr) {
60             Some(call_arg) => call_arg,
61             None => return,
62         };
63
64         // Check if the argument to the method call is a cast from usize
65         let cast_lhs_expr = match expr_as_cast_from_usize(cx, arg_expr) {
66             Some(cast_lhs_expr) => cast_lhs_expr,
67             None => return,
68         };
69
70         let msg = format!("use of `{}` with a `usize` casted to an `isize`", method);
71         if let Some(sugg) = build_suggestion(cx, method, receiver_expr, cast_lhs_expr) {
72             utils::span_lint_and_sugg(cx, PTR_OFFSET_WITH_CAST, expr.span, &msg, "try", sugg);
73         } else {
74             utils::span_lint(cx, PTR_OFFSET_WITH_CAST, expr.span, &msg);
75         }
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<'a, 'tcx>(
82     cx: &lint::LateContext<'a, 'tcx>,
83     expr: &'tcx hir::Expr,
84 ) -> Option<&'tcx hir::Expr> {
85     if let hir::ExprKind::Cast(ref cast_lhs_expr, _) = expr.node {
86         if is_expr_ty_usize(cx, &cast_lhs_expr) {
87             return Some(cast_lhs_expr);
88         }
89     }
90     None
91 }
92
93 // If the given expression is a ptr::offset  or ptr::wrapping_offset method call, return the
94 // receiver, the arg of the method call, and the method.
95 fn expr_as_ptr_offset_call<'a, 'tcx>(
96     cx: &lint::LateContext<'a, 'tcx>,
97     expr: &'tcx hir::Expr,
98 ) -> Option<(&'tcx hir::Expr, &'tcx hir::Expr, Method)> {
99     if let hir::ExprKind::MethodCall(ref path_segment, _, ref args) = expr.node {
100         if is_expr_ty_raw_ptr(cx, &args[0]) {
101             if path_segment.ident.name == "offset" {
102                 return Some((&args[0], &args[1], Method::Offset));
103             }
104             if path_segment.ident.name == "wrapping_offset" {
105                 return Some((&args[0], &args[1], Method::WrappingOffset));
106             }
107         }
108     }
109     None
110 }
111
112 // Is the type of the expression a usize?
113 fn is_expr_ty_usize<'a, 'tcx>(
114     cx: &lint::LateContext<'a, 'tcx>,
115     expr: &hir::Expr,
116 ) -> bool {
117     cx.tables.expr_ty(expr) == cx.tcx.types.usize
118 }
119
120 // Is the type of the expression a raw pointer?
121 fn is_expr_ty_raw_ptr<'a, 'tcx>(
122     cx: &lint::LateContext<'a, 'tcx>,
123     expr: &hir::Expr,
124 ) -> bool {
125     cx.tables.expr_ty(expr).is_unsafe_ptr()
126 }
127
128 fn build_suggestion<'a, 'tcx>(
129     cx: &lint::LateContext<'a, 'tcx>,
130     method: Method,
131     receiver_expr: &hir::Expr,
132     cast_lhs_expr: &hir::Expr,
133 ) -> Option<String> {
134     let receiver = utils::snippet_opt(cx, receiver_expr.span)?;
135     let cast_lhs = utils::snippet_opt(cx, cast_lhs_expr.span)?;
136     Some(format!("{}.{}({})", receiver, method.suggestion(), cast_lhs))
137 }
138
139 #[derive(Copy, Clone)]
140 enum Method {
141     Offset,
142     WrappingOffset,
143 }
144
145 impl Method {
146     fn suggestion(self) -> &'static str {
147         match self {
148             Method::Offset => "add",
149             Method::WrappingOffset => "wrapping_add",
150         }
151     }
152 }
153
154 impl fmt::Display for Method {
155     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156         match self {
157             Method::Offset => write!(f, "offset"),
158             Method::WrappingOffset => write!(f, "wrapping_offset"),
159         }
160     }
161 }