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};
9 /// **What it does:** Checks for usage of the `offset` pointer method with a `usize` casted to an
12 /// **Why is this bad?** If we’re always increasing the pointer address, we can avoid the numeric
13 /// cast by using the `add` method instead.
15 /// **Known problems:** None
19 /// let vec = vec![b'a', b'b', b'c'];
20 /// let ptr = vec.as_ptr();
21 /// let offset = 1_usize;
24 /// ptr.offset(offset as isize);
31 /// let vec = vec![b'a', b'b', b'c'];
32 /// let ptr = vec.as_ptr();
33 /// let offset = 1_usize;
39 pub PTR_OFFSET_WITH_CAST,
41 "unneeded pointer offset cast"
44 declare_lint_pass!(PtrOffsetWithCast => [PTR_OFFSET_WITH_CAST]);
46 impl<'tcx> LateLintPass<'tcx> for PtrOffsetWithCast {
47 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
48 // Check if the expressions is a ptr.offset or ptr.wrapping_offset method call
49 let (receiver_expr, arg_expr, method) = match expr_as_ptr_offset_call(cx, expr) {
50 Some(call_arg) => call_arg,
54 // Check if the argument to the method call is a cast from usize
55 let cast_lhs_expr = match expr_as_cast_from_usize(cx, arg_expr) {
56 Some(cast_lhs_expr) => cast_lhs_expr,
60 let msg = format!("use of `{}` with a `usize` casted to an `isize`", method);
61 if let Some(sugg) = build_suggestion(cx, method, receiver_expr, cast_lhs_expr) {
69 Applicability::MachineApplicable,
72 span_lint(cx, PTR_OFFSET_WITH_CAST, expr.span, &msg);
77 // If the given expression is a cast from a usize, return the lhs of the cast
78 fn expr_as_cast_from_usize<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
79 if let ExprKind::Cast(ref cast_lhs_expr, _) = expr.kind {
80 if is_expr_ty_usize(cx, &cast_lhs_expr) {
81 return Some(cast_lhs_expr);
87 // If the given expression is a ptr::offset or ptr::wrapping_offset method call, return the
88 // receiver, the arg of the method call, and the method.
89 fn expr_as_ptr_offset_call<'tcx>(
90 cx: &LateContext<'tcx>,
92 ) -> Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>, Method)> {
93 if let ExprKind::MethodCall(ref path_segment, _, ref args, _) = expr.kind {
94 if is_expr_ty_raw_ptr(cx, &args[0]) {
95 if path_segment.ident.name == sym!(offset) {
96 return Some((&args[0], &args[1], Method::Offset));
98 if path_segment.ident.name == sym!(wrapping_offset) {
99 return Some((&args[0], &args[1], Method::WrappingOffset));
106 // Is the type of the expression a usize?
107 fn is_expr_ty_usize<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> bool {
108 cx.typeck_results().expr_ty(expr) == cx.tcx.types.usize
111 // Is the type of the expression a raw pointer?
112 fn is_expr_ty_raw_ptr<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> bool {
113 cx.typeck_results().expr_ty(expr).is_unsafe_ptr()
116 fn build_suggestion<'tcx>(
117 cx: &LateContext<'tcx>,
119 receiver_expr: &Expr<'_>,
120 cast_lhs_expr: &Expr<'_>,
121 ) -> Option<String> {
122 let receiver = snippet_opt(cx, receiver_expr.span)?;
123 let cast_lhs = snippet_opt(cx, cast_lhs_expr.span)?;
124 Some(format!("{}.{}({})", receiver, method.suggestion(), cast_lhs))
127 #[derive(Copy, Clone)]
135 fn suggestion(self) -> &'static str {
137 Self::Offset => "add",
138 Self::WrappingOffset => "wrapping_add",
143 impl fmt::Display for Method {
144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146 Self::Offset => write!(f, "offset"),
147 Self::WrappingOffset => write!(f, "wrapping_offset"),