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.
10 use crate::rustc::{declare_tool_lint, hir, lint, lint_array};
11 use crate::rustc_errors::Applicability;
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;
30 /// ptr.offset(offset as isize);
37 /// let vec = vec![b'a', b'b', b'c'];
38 /// let ptr = vec.as_ptr();
39 /// let offset = 1_usize;
45 declare_clippy_lint! {
46 pub PTR_OFFSET_WITH_CAST,
48 "unneeded pointer offset cast"
51 #[derive(Copy, Clone, Debug)]
54 impl lint::LintPass for Pass {
55 fn get_lints(&self) -> lint::LintArray {
56 lint_array!(PTR_OFFSET_WITH_CAST)
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,
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,
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(
83 Applicability::MachineApplicable,
86 utils::span_lint(cx, PTR_OFFSET_WITH_CAST, expr.span, &msg);
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);
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));
115 if path_segment.ident.name == "wrapping_offset" {
116 return Some((&args[0], &args[1], Method::WrappingOffset));
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
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()
133 fn build_suggestion<'a, 'tcx>(
134 cx: &lint::LateContext<'a, 'tcx>,
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))
144 #[derive(Copy, Clone)]
151 fn suggestion(self) -> &'static str {
153 Method::Offset => "add",
154 Method::WrappingOffset => "wrapping_add",
159 impl fmt::Display for Method {
160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162 Method::Offset => write!(f, "offset"),
163 Method::WrappingOffset => write!(f, "wrapping_offset"),