]> git.lizzy.rs Git - rust.git/blobdiff - clippy_lints/src/ptr_offset_with_cast.rs
separate the receiver from arguments in HIR under /clippy
[rust.git] / clippy_lints / src / ptr_offset_with_cast.rs
index 8d6bca8b6894b6c836b6d25f52f86961b6c6066a..4dc65da3ea1fd9fd8227823a0ce416c6c573a466 100644 (file)
@@ -1,64 +1,53 @@
-// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-use crate::utils;
-use rustc::{declare_tool_lint, hir, lint, lint_array};
+use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg};
+use clippy_utils::source::snippet_opt;
 use rustc_errors::Applicability;
+use rustc_hir::{Expr, ExprKind};
+use rustc_lint::{LateContext, LateLintPass};
+use rustc_session::{declare_lint_pass, declare_tool_lint};
+use rustc_span::sym;
 use std::fmt;
 
-/// **What it does:** Checks for usage of the `offset` pointer method with a `usize` casted to an
-/// `isize`.
-///
-/// **Why is this bad?** If we’re always increasing the pointer address, we can avoid the numeric
-/// cast by using the `add` method instead.
-///
-/// **Known problems:** None
-///
-/// **Example:**
-/// ```rust
-/// let vec = vec![b'a', b'b', b'c'];
-/// let ptr = vec.as_ptr();
-/// let offset = 1_usize;
-///
-/// unsafe {
-///     ptr.offset(offset as isize);
-/// }
-/// ```
-///
-/// Could be written:
-///
-/// ```rust
-/// let vec = vec![b'a', b'b', b'c'];
-/// let ptr = vec.as_ptr();
-/// let offset = 1_usize;
-///
-/// unsafe {
-///     ptr.add(offset);
-/// }
-/// ```
 declare_clippy_lint! {
+    /// ### What it does
+    /// Checks for usage of the `offset` pointer method with a `usize` casted to an
+    /// `isize`.
+    ///
+    /// ### Why is this bad?
+    /// If we’re always increasing the pointer address, we can avoid the numeric
+    /// cast by using the `add` method instead.
+    ///
+    /// ### Example
+    /// ```rust
+    /// let vec = vec![b'a', b'b', b'c'];
+    /// let ptr = vec.as_ptr();
+    /// let offset = 1_usize;
+    ///
+    /// unsafe {
+    ///     ptr.offset(offset as isize);
+    /// }
+    /// ```
+    ///
+    /// Could be written:
+    ///
+    /// ```rust
+    /// let vec = vec![b'a', b'b', b'c'];
+    /// let ptr = vec.as_ptr();
+    /// let offset = 1_usize;
+    ///
+    /// unsafe {
+    ///     ptr.add(offset);
+    /// }
+    /// ```
+    #[clippy::version = "1.30.0"]
     pub PTR_OFFSET_WITH_CAST,
     complexity,
     "unneeded pointer offset cast"
 }
 
-#[derive(Copy, Clone, Debug)]
-pub struct Pass;
-
-impl lint::LintPass for Pass {
-    fn get_lints(&self) -> lint::LintArray {
-        lint_array!(PTR_OFFSET_WITH_CAST)
-    }
-}
+declare_lint_pass!(PtrOffsetWithCast => [PTR_OFFSET_WITH_CAST]);
 
-impl<'a, 'tcx> lint::LateLintPass<'a, 'tcx> for Pass {
-    fn check_expr(&mut self, cx: &lint::LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
+impl<'tcx> LateLintPass<'tcx> for PtrOffsetWithCast {
+    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
         // Check if the expressions is a ptr.offset or ptr.wrapping_offset method call
         let (receiver_expr, arg_expr, method) = match expr_as_ptr_offset_call(cx, expr) {
             Some(call_arg) => call_arg,
@@ -73,7 +62,7 @@ fn check_expr(&mut self, cx: &lint::LateContext<'a, 'tcx>, expr: &'tcx hir::Expr
 
         let msg = format!("use of `{}` with a `usize` casted to an `isize`", method);
         if let Some(sugg) = build_suggestion(cx, method, receiver_expr, cast_lhs_expr) {
-            utils::span_lint_and_sugg(
+            span_lint_and_sugg(
                 cx,
                 PTR_OFFSET_WITH_CAST,
                 expr.span,
@@ -83,18 +72,15 @@ fn check_expr(&mut self, cx: &lint::LateContext<'a, 'tcx>, expr: &'tcx hir::Expr
                 Applicability::MachineApplicable,
             );
         } else {
-            utils::span_lint(cx, PTR_OFFSET_WITH_CAST, expr.span, &msg);
+            span_lint(cx, PTR_OFFSET_WITH_CAST, expr.span, &msg);
         }
     }
 }
 
 // If the given expression is a cast from a usize, return the lhs of the cast
-fn expr_as_cast_from_usize<'a, 'tcx>(
-    cx: &lint::LateContext<'a, 'tcx>,
-    expr: &'tcx hir::Expr,
-) -> Option<&'tcx hir::Expr> {
-    if let hir::ExprKind::Cast(ref cast_lhs_expr, _) = expr.node {
-        if is_expr_ty_usize(cx, &cast_lhs_expr) {
+fn expr_as_cast_from_usize<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
+    if let ExprKind::Cast(cast_lhs_expr, _) = expr.kind {
+        if is_expr_ty_usize(cx, cast_lhs_expr) {
             return Some(cast_lhs_expr);
         }
     }
@@ -103,17 +89,17 @@ fn expr_as_cast_from_usize<'a, 'tcx>(
 
 // If the given expression is a ptr::offset  or ptr::wrapping_offset method call, return the
 // receiver, the arg of the method call, and the method.
-fn expr_as_ptr_offset_call<'a, 'tcx>(
-    cx: &lint::LateContext<'a, 'tcx>,
-    expr: &'tcx hir::Expr,
-) -> Option<(&'tcx hir::Expr, &'tcx hir::Expr, Method)> {
-    if let hir::ExprKind::MethodCall(ref path_segment, _, ref args) = expr.node {
-        if is_expr_ty_raw_ptr(cx, &args[0]) {
-            if path_segment.ident.name == "offset" {
-                return Some((&args[0], &args[1], Method::Offset));
+fn expr_as_ptr_offset_call<'tcx>(
+    cx: &LateContext<'tcx>,
+    expr: &'tcx Expr<'_>,
+) -> Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>, Method)> {
+    if let ExprKind::MethodCall(path_segment, arg_0, [arg_1, ..], _) = &expr.kind {
+        if is_expr_ty_raw_ptr(cx, arg_0) {
+            if path_segment.ident.name == sym::offset {
+                return Some((arg_0, arg_1, Method::Offset));
             }
-            if path_segment.ident.name == "wrapping_offset" {
-                return Some((&args[0], &args[1], Method::WrappingOffset));
+            if path_segment.ident.name == sym!(wrapping_offset) {
+                return Some((arg_0, arg_1, Method::WrappingOffset));
             }
         }
     }
@@ -121,23 +107,23 @@ fn expr_as_ptr_offset_call<'a, 'tcx>(
 }
 
 // Is the type of the expression a usize?
-fn is_expr_ty_usize<'a, 'tcx>(cx: &lint::LateContext<'a, 'tcx>, expr: &hir::Expr) -> bool {
-    cx.tables.expr_ty(expr) == cx.tcx.types.usize
+fn is_expr_ty_usize<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> bool {
+    cx.typeck_results().expr_ty(expr) == cx.tcx.types.usize
 }
 
 // Is the type of the expression a raw pointer?
-fn is_expr_ty_raw_ptr<'a, 'tcx>(cx: &lint::LateContext<'a, 'tcx>, expr: &hir::Expr) -> bool {
-    cx.tables.expr_ty(expr).is_unsafe_ptr()
+fn is_expr_ty_raw_ptr<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> bool {
+    cx.typeck_results().expr_ty(expr).is_unsafe_ptr()
 }
 
-fn build_suggestion<'a, 'tcx>(
-    cx: &lint::LateContext<'a, 'tcx>,
+fn build_suggestion<'tcx>(
+    cx: &LateContext<'tcx>,
     method: Method,
-    receiver_expr: &hir::Expr,
-    cast_lhs_expr: &hir::Expr,
+    receiver_expr: &Expr<'_>,
+    cast_lhs_expr: &Expr<'_>,
 ) -> Option<String> {
-    let receiver = utils::snippet_opt(cx, receiver_expr.span)?;
-    let cast_lhs = utils::snippet_opt(cx, cast_lhs_expr.span)?;
+    let receiver = snippet_opt(cx, receiver_expr.span)?;
+    let cast_lhs = snippet_opt(cx, cast_lhs_expr.span)?;
     Some(format!("{}.{}({})", receiver, method.suggestion(), cast_lhs))
 }
 
@@ -148,10 +134,11 @@ enum Method {
 }
 
 impl Method {
+    #[must_use]
     fn suggestion(self) -> &'static str {
         match self {
-            Method::Offset => "add",
-            Method::WrappingOffset => "wrapping_add",
+            Self::Offset => "add",
+            Self::WrappingOffset => "wrapping_add",
         }
     }
 }
@@ -159,8 +146,8 @@ fn suggestion(self) -> &'static str {
 impl fmt::Display for Method {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match self {
-            Method::Offset => write!(f, "offset"),
-            Method::WrappingOffset => write!(f, "wrapping_offset"),
+            Self::Offset => write!(f, "offset"),
+            Self::WrappingOffset => write!(f, "wrapping_offset"),
         }
     }
 }