1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
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.
11 use crate::rustc::{declare_tool_lint, hir, lint, lint_array};
15 /// **What it does:** Checks for usage of the `offset` pointer method with a `usize` casted to an
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.
21 /// **Known problems:** None
25 /// let vec = vec![b'a', b'b', b'c'];
26 /// let ptr = vec.as_ptr();
27 /// let offset = 1_usize;
29 /// unsafe { ptr.offset(offset as isize); }
35 /// let vec = vec![b'a', b'b', b'c'];
36 /// let ptr = vec.as_ptr();
37 /// let offset = 1_usize;
39 /// unsafe { ptr.add(offset); }
41 declare_clippy_lint! {
42 pub PTR_OFFSET_WITH_CAST,
44 "unneeded pointer offset cast"
47 #[derive(Copy, Clone, Debug)]
50 impl lint::LintPass for Pass {
51 fn get_lints(&self) -> lint::LintArray {
52 lint_array!(PTR_OFFSET_WITH_CAST)
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,
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,
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);
74 utils::span_lint(cx, PTR_OFFSET_WITH_CAST, expr.span, &msg);
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);
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));
104 if path_segment.ident.name == "wrapping_offset" {
105 return Some((&args[0], &args[1], Method::WrappingOffset));
112 // Is the type of the expression a usize?
113 fn is_expr_ty_usize<'a, 'tcx>(
114 cx: &lint::LateContext<'a, 'tcx>,
117 cx.tables.expr_ty(expr) == cx.tcx.types.usize
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>,
125 cx.tables.expr_ty(expr).is_unsafe_ptr()
128 fn build_suggestion<'a, 'tcx>(
129 cx: &lint::LateContext<'a, 'tcx>,
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))
139 #[derive(Copy, Clone)]
146 fn suggestion(self) -> &'static str {
148 Method::Offset => "add",
149 Method::WrappingOffset => "wrapping_add",
154 impl fmt::Display for Method {
155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157 Method::Offset => write!(f, "offset"),
158 Method::WrappingOffset => write!(f, "wrapping_offset"),