1 use crate::utils::{snippet_opt, span_lint, span_lint_and_sugg};
2 use rustc_errors::Applicability;
3 use rustc_hir::{Expr, ExprKind};
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 /// **What it does:** Checks for usage of the `offset` pointer method with a `usize` casted to an
13 /// **Why is this bad?** If we’re always increasing the pointer address, we can avoid the numeric
14 /// cast by using the `add` method instead.
16 /// **Known problems:** None
20 /// let vec = vec![b'a', b'b', b'c'];
21 /// let ptr = vec.as_ptr();
22 /// let offset = 1_usize;
25 /// ptr.offset(offset as isize);
32 /// let vec = vec![b'a', b'b', b'c'];
33 /// let ptr = vec.as_ptr();
34 /// let offset = 1_usize;
40 pub PTR_OFFSET_WITH_CAST,
42 "unneeded pointer offset cast"
45 declare_lint_pass!(PtrOffsetWithCast => [PTR_OFFSET_WITH_CAST]);
47 impl<'tcx> LateLintPass<'tcx> for PtrOffsetWithCast {
48 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
49 // Check if the expressions is a ptr.offset or ptr.wrapping_offset method call
50 let (receiver_expr, arg_expr, method) = match expr_as_ptr_offset_call(cx, expr) {
51 Some(call_arg) => call_arg,
55 // Check if the argument to the method call is a cast from usize
56 let cast_lhs_expr = match expr_as_cast_from_usize(cx, arg_expr) {
57 Some(cast_lhs_expr) => cast_lhs_expr,
61 let msg = format!("use of `{}` with a `usize` casted to an `isize`", method);
62 if let Some(sugg) = build_suggestion(cx, method, receiver_expr, cast_lhs_expr) {
70 Applicability::MachineApplicable,
73 span_lint(cx, PTR_OFFSET_WITH_CAST, expr.span, &msg);
78 // If the given expression is a cast from a usize, return the lhs of the cast
79 fn expr_as_cast_from_usize<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
80 if let ExprKind::Cast(ref cast_lhs_expr, _) = expr.kind {
81 if is_expr_ty_usize(cx, &cast_lhs_expr) {
82 return Some(cast_lhs_expr);
88 // If the given expression is a ptr::offset or ptr::wrapping_offset method call, return the
89 // receiver, the arg of the method call, and the method.
90 fn expr_as_ptr_offset_call<'tcx>(
91 cx: &LateContext<'tcx>,
93 ) -> Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>, Method)> {
94 if let ExprKind::MethodCall(ref path_segment, _, ref args, _) = expr.kind {
95 if is_expr_ty_raw_ptr(cx, &args[0]) {
96 if path_segment.ident.name == sym::offset {
97 return Some((&args[0], &args[1], Method::Offset));
99 if path_segment.ident.name == sym!(wrapping_offset) {
100 return Some((&args[0], &args[1], Method::WrappingOffset));
107 // Is the type of the expression a usize?
108 fn is_expr_ty_usize<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> bool {
109 cx.typeck_results().expr_ty(expr) == cx.tcx.types.usize
112 // Is the type of the expression a raw pointer?
113 fn is_expr_ty_raw_ptr<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> bool {
114 cx.typeck_results().expr_ty(expr).is_unsafe_ptr()
117 fn build_suggestion<'tcx>(
118 cx: &LateContext<'tcx>,
120 receiver_expr: &Expr<'_>,
121 cast_lhs_expr: &Expr<'_>,
122 ) -> Option<String> {
123 let receiver = snippet_opt(cx, receiver_expr.span)?;
124 let cast_lhs = snippet_opt(cx, cast_lhs_expr.span)?;
125 Some(format!("{}.{}({})", receiver, method.suggestion(), cast_lhs))
128 #[derive(Copy, Clone)]
136 fn suggestion(self) -> &'static str {
138 Self::Offset => "add",
139 Self::WrappingOffset => "wrapping_add",
144 impl fmt::Display for Method {
145 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147 Self::Offset => write!(f, "offset"),
148 Self::WrappingOffset => write!(f, "wrapping_offset"),