1 use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg};
2 use clippy_utils::source::snippet_opt;
3 use rustc_errors::Applicability;
4 use rustc_hir::{Expr, ExprKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 declare_clippy_lint! {
12 /// Checks for usage of the `offset` pointer method with a `usize` casted to an
15 /// ### Why is this bad?
16 /// If we’re always increasing the pointer address, we can avoid the numeric
17 /// cast by using the `add` method instead.
21 /// let vec = vec![b'a', b'b', b'c'];
22 /// let ptr = vec.as_ptr();
23 /// let offset = 1_usize;
26 /// ptr.offset(offset as isize);
33 /// let vec = vec![b'a', b'b', b'c'];
34 /// let ptr = vec.as_ptr();
35 /// let offset = 1_usize;
41 pub PTR_OFFSET_WITH_CAST,
43 "unneeded pointer offset cast"
46 declare_lint_pass!(PtrOffsetWithCast => [PTR_OFFSET_WITH_CAST]);
48 impl<'tcx> LateLintPass<'tcx> for PtrOffsetWithCast {
49 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
50 // Check if the expressions is a ptr.offset or ptr.wrapping_offset method call
51 let (receiver_expr, arg_expr, method) = match expr_as_ptr_offset_call(cx, expr) {
52 Some(call_arg) => call_arg,
56 // Check if the argument to the method call is a cast from usize
57 let cast_lhs_expr = match expr_as_cast_from_usize(cx, arg_expr) {
58 Some(cast_lhs_expr) => cast_lhs_expr,
62 let msg = format!("use of `{}` with a `usize` casted to an `isize`", method);
63 if let Some(sugg) = build_suggestion(cx, method, receiver_expr, cast_lhs_expr) {
71 Applicability::MachineApplicable,
74 span_lint(cx, PTR_OFFSET_WITH_CAST, expr.span, &msg);
79 // If the given expression is a cast from a usize, return the lhs of the cast
80 fn expr_as_cast_from_usize<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
81 if let ExprKind::Cast(cast_lhs_expr, _) = expr.kind {
82 if is_expr_ty_usize(cx, cast_lhs_expr) {
83 return Some(cast_lhs_expr);
89 // If the given expression is a ptr::offset or ptr::wrapping_offset method call, return the
90 // receiver, the arg of the method call, and the method.
91 fn expr_as_ptr_offset_call<'tcx>(
92 cx: &LateContext<'tcx>,
94 ) -> Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>, Method)> {
95 if let ExprKind::MethodCall(path_segment, _, [arg_0, arg_1, ..], _) = &expr.kind {
96 if is_expr_ty_raw_ptr(cx, arg_0) {
97 if path_segment.ident.name == sym::offset {
98 return Some((arg_0, arg_1, Method::Offset));
100 if path_segment.ident.name == sym!(wrapping_offset) {
101 return Some((arg_0, arg_1, Method::WrappingOffset));
108 // Is the type of the expression a usize?
109 fn is_expr_ty_usize<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> bool {
110 cx.typeck_results().expr_ty(expr) == cx.tcx.types.usize
113 // Is the type of the expression a raw pointer?
114 fn is_expr_ty_raw_ptr<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> bool {
115 cx.typeck_results().expr_ty(expr).is_unsafe_ptr()
118 fn build_suggestion<'tcx>(
119 cx: &LateContext<'tcx>,
121 receiver_expr: &Expr<'_>,
122 cast_lhs_expr: &Expr<'_>,
123 ) -> Option<String> {
124 let receiver = snippet_opt(cx, receiver_expr.span)?;
125 let cast_lhs = snippet_opt(cx, cast_lhs_expr.span)?;
126 Some(format!("{}.{}({})", receiver, method.suggestion(), cast_lhs))
129 #[derive(Copy, Clone)]
137 fn suggestion(self) -> &'static str {
139 Self::Offset => "add",
140 Self::WrappingOffset => "wrapping_add",
145 impl fmt::Display for Method {
146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148 Self::Offset => write!(f, "offset"),
149 Self::WrappingOffset => write!(f, "wrapping_offset"),