rust/clippy_lints/src/ptr_offset_with_cast.rs

150 lines
4.6 KiB
Rust
Raw Normal View History

use crate::utils;
2019-04-08 15:43:55 -05:00
use rustc::hir::{Expr, ExprKind};
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
use rustc::{declare_lint_pass, declare_tool_lint};
use rustc_errors::Applicability;
2018-08-29 07:40:00 -05:00
use std::fmt;
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 were 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);
/// }
/// ```
pub PTR_OFFSET_WITH_CAST,
complexity,
"unneeded pointer offset cast"
}
2019-04-08 15:43:55 -05:00
declare_lint_pass!(PtrOffsetWithCast => [PTR_OFFSET_WITH_CAST]);
2019-04-08 15:43:55 -05:00
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PtrOffsetWithCast {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
2018-08-29 07:40:00 -05:00
// 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,
None => return,
};
2018-08-29 07:40:00 -05:00
// Check if the argument to the method call is a cast from usize
let cast_lhs_expr = match expr_as_cast_from_usize(cx, arg_expr) {
Some(cast_lhs_expr) => cast_lhs_expr,
None => return,
};
2018-08-29 07:40:00 -05:00
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(
cx,
PTR_OFFSET_WITH_CAST,
expr.span,
&msg,
"try",
sugg,
Applicability::MachineApplicable,
);
2018-08-29 07:12:22 -05:00
} else {
2018-08-29 07:40:00 -05:00
utils::span_lint(cx, PTR_OFFSET_WITH_CAST, expr.span, &msg);
2018-08-29 07:12:22 -05:00
}
}
}
// If the given expression is a cast from a usize, return the lhs of the cast
2019-04-08 15:43:55 -05:00
fn expr_as_cast_from_usize<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<&'tcx Expr> {
2019-09-27 10:16:06 -05:00
if let ExprKind::Cast(ref cast_lhs_expr, _) = expr.kind {
if is_expr_ty_usize(cx, &cast_lhs_expr) {
return Some(cast_lhs_expr);
}
}
None
}
2018-08-29 07:40:00 -05:00
// 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>(
2019-04-08 15:43:55 -05:00
cx: &LateContext<'a, 'tcx>,
expr: &'tcx Expr,
) -> Option<(&'tcx Expr, &'tcx Expr, Method)> {
2019-09-27 10:16:06 -05:00
if let ExprKind::MethodCall(ref path_segment, _, ref args) = expr.kind {
2018-08-29 07:40:00 -05:00
if is_expr_ty_raw_ptr(cx, &args[0]) {
2019-05-17 16:53:54 -05:00
if path_segment.ident.name == sym!(offset) {
2018-08-29 07:40:00 -05:00
return Some((&args[0], &args[1], Method::Offset));
}
2019-05-17 16:53:54 -05:00
if path_segment.ident.name == sym!(wrapping_offset) {
2018-08-29 07:40:00 -05:00
return Some((&args[0], &args[1], Method::WrappingOffset));
}
}
}
None
}
// Is the type of the expression a usize?
2019-04-08 15:43:55 -05:00
fn is_expr_ty_usize<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr) -> bool {
2018-08-29 07:07:23 -05:00
cx.tables.expr_ty(expr) == cx.tcx.types.usize
}
// Is the type of the expression a raw pointer?
2019-04-08 15:43:55 -05:00
fn is_expr_ty_raw_ptr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr) -> bool {
2018-08-29 07:08:59 -05:00
cx.tables.expr_ty(expr).is_unsafe_ptr()
}
fn build_suggestion<'a, 'tcx>(
2019-04-08 15:43:55 -05:00
cx: &LateContext<'a, 'tcx>,
2018-08-29 07:40:00 -05:00
method: Method,
2019-04-08 15:43:55 -05:00
receiver_expr: &Expr,
cast_lhs_expr: &Expr,
2018-08-29 07:12:22 -05:00
) -> Option<String> {
2018-08-29 07:42:43 -05:00
let receiver = utils::snippet_opt(cx, receiver_expr.span)?;
let cast_lhs = utils::snippet_opt(cx, cast_lhs_expr.span)?;
Some(format!("{}.{}({})", receiver, method.suggestion(), cast_lhs))
}
2018-08-29 07:40:00 -05:00
2018-08-29 08:01:05 -05:00
#[derive(Copy, Clone)]
2018-08-29 07:40:00 -05:00
enum Method {
Offset,
WrappingOffset,
}
impl Method {
2018-08-29 08:27:32 -05:00
fn suggestion(self) -> &'static str {
2018-08-29 08:59:38 -05:00
match self {
Self::Offset => "add",
Self::WrappingOffset => "wrapping_add",
2018-08-29 07:40:00 -05:00
}
}
}
impl fmt::Display for Method {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2018-08-29 08:59:38 -05:00
match self {
Self::Offset => write!(f, "offset"),
Self::WrappingOffset => write!(f, "wrapping_offset"),
2018-08-29 07:40:00 -05:00
}
}
2018-08-29 07:43:40 -05:00
}