-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathunnecessary_cast.rs
328 lines (302 loc) · 12 KB
/
unnecessary_cast.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::numeric_literal::NumericLiteral;
use clippy_utils::source::{SpanRangeExt, snippet_opt};
use clippy_utils::visitors::{Visitable, for_each_expr_without_closures};
use clippy_utils::{get_parent_expr, is_hir_ty_cfg_dependant, is_ty_alias, path_to_local};
use rustc_ast::{LitFloatType, LitIntType, LitKind};
use rustc_errors::Applicability;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::{Expr, ExprKind, Lit, Node, Path, QPath, TyKind, UnOp};
use rustc_lint::{LateContext, LintContext};
use rustc_middle::ty::adjustment::Adjust;
use rustc_middle::ty::{self, FloatTy, InferTy, Ty};
use rustc_span::{Symbol, sym};
use std::ops::ControlFlow;
use super::UNNECESSARY_CAST;
#[expect(clippy::too_many_lines)]
pub(super) fn check<'tcx>(
cx: &LateContext<'tcx>,
expr: &Expr<'tcx>,
cast_expr: &Expr<'tcx>,
cast_from: Ty<'tcx>,
cast_to: Ty<'tcx>,
) -> bool {
let cast_str = snippet_opt(cx, cast_expr.span).unwrap_or_default();
if let ty::RawPtr(..) = cast_from.kind()
// check both mutability and type are the same
&& cast_from.kind() == cast_to.kind()
&& let ExprKind::Cast(_, cast_to_hir) = expr.kind
// Ignore casts to e.g. type aliases and infer types
// - p as pointer_alias
// - p as _
&& let TyKind::Ptr(to_pointee) = cast_to_hir.kind
{
match to_pointee.ty.kind {
// Ignore casts to pointers that are aliases or cfg dependant, e.g.
// - p as *const std::ffi::c_char (alias)
// - p as *const std::os::raw::c_char (cfg dependant)
TyKind::Path(qpath) => {
if is_ty_alias(&qpath) || is_hir_ty_cfg_dependant(cx, to_pointee.ty) {
return false;
}
},
// Ignore `p as *const _`
TyKind::Infer(()) => return false,
_ => {},
}
span_lint_and_sugg(
cx,
UNNECESSARY_CAST,
expr.span,
format!(
"casting raw pointers to the same type and constness is unnecessary (`{cast_from}` -> `{cast_to}`)"
),
"try",
cast_str.clone(),
Applicability::MaybeIncorrect,
);
}
// skip cast of local that is a type alias
if let ExprKind::Cast(inner, ..) = expr.kind
&& let ExprKind::Path(qpath) = inner.kind
&& let QPath::Resolved(None, Path { res, .. }) = qpath
&& let Res::Local(hir_id) = res
&& let parent = cx.tcx.parent_hir_node(*hir_id)
&& let Node::LetStmt(local) = parent
{
if let Some(ty) = local.ty
&& let TyKind::Path(qpath) = ty.kind
&& is_ty_alias(&qpath)
{
return false;
}
if let Some(expr) = local.init
&& let ExprKind::Cast(.., cast_to) = expr.kind
&& let TyKind::Path(qpath) = cast_to.kind
&& is_ty_alias(&qpath)
{
return false;
}
}
// skip cast to non-primitive type
if let ExprKind::Cast(_, cast_to) = expr.kind
&& let TyKind::Path(QPath::Resolved(_, path)) = &cast_to.kind
&& let Res::PrimTy(_) = path.res
{
} else {
return false;
}
// skip cast of fn call that returns type alias
if let ExprKind::Cast(inner, ..) = expr.kind
&& is_cast_from_ty_alias(cx, inner, cast_from)
{
return false;
}
if let Some(lit) = get_numeric_literal(cast_expr) {
let literal_str = &cast_str;
if let LitKind::Int(n, _) = lit.node
&& let Some(src) = cast_expr.span.get_source_text(cx)
&& cast_to.is_floating_point()
&& let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node)
&& let from_nbits = 128 - n.get().leading_zeros()
&& let to_nbits = fp_ty_mantissa_nbits(cast_to)
&& from_nbits != 0
&& to_nbits != 0
&& from_nbits <= to_nbits
&& num_lit.is_decimal()
{
lint_unnecessary_cast(cx, expr, num_lit.integer, cast_from, cast_to);
return true;
}
match lit.node {
LitKind::Int(_, LitIntType::Unsuffixed) if cast_to.is_integral() => {
lint_unnecessary_cast(cx, expr, literal_str, cast_from, cast_to);
return false;
},
LitKind::Float(_, LitFloatType::Unsuffixed) if cast_to.is_floating_point() => {
lint_unnecessary_cast(cx, expr, literal_str, cast_from, cast_to);
return false;
},
LitKind::Int(_, LitIntType::Signed(_) | LitIntType::Unsigned(_))
| LitKind::Float(_, LitFloatType::Suffixed(_))
if cast_from.kind() == cast_to.kind() =>
{
if let Some(src) = cast_expr.span.get_source_text(cx)
&& let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node)
{
lint_unnecessary_cast(cx, expr, num_lit.integer, cast_from, cast_to);
return true;
}
},
_ => {},
}
}
if cast_from.kind() == cast_to.kind() && !expr.span.in_external_macro(cx.sess().source_map()) {
enum MaybeParenOrBlock {
Paren,
Block,
Nothing,
}
fn is_borrow_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
matches!(expr.kind, ExprKind::AddrOf(..))
|| cx
.typeck_results()
.expr_adjustments(expr)
.first()
.is_some_and(|adj| matches!(adj.kind, Adjust::Borrow(_)))
}
fn is_in_allowed_macro(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
const ALLOWED_MACROS: &[Symbol] = &[
sym::format_args_macro,
sym::assert_eq_macro,
sym::debug_assert_eq_macro,
sym::assert_ne_macro,
sym::debug_assert_ne_macro,
];
matches!(expr.span.ctxt().outer_expn_data().macro_def_id, Some(def_id) if
cx.tcx.get_diagnostic_name(def_id).is_some_and(|sym| ALLOWED_MACROS.contains(&sym)))
}
if let Some(id) = path_to_local(cast_expr)
&& !cx.tcx.hir_span(id).eq_ctxt(cast_expr.span)
{
// Binding context is different than the identifiers context.
// Weird macro wizardry could be involved here.
return false;
}
// Changing `&(x as i32)` to `&x` would change the meaning of the code because the previous creates
// a reference to the temporary while the latter creates a reference to the original value.
let surrounding = match cx.tcx.parent_hir_node(expr.hir_id) {
Node::Expr(parent) if is_borrow_expr(cx, parent) && !is_in_allowed_macro(cx, parent) => {
MaybeParenOrBlock::Block
},
Node::Expr(parent) if cast_expr.precedence() < parent.precedence() => MaybeParenOrBlock::Paren,
_ => MaybeParenOrBlock::Nothing,
};
span_lint_and_sugg(
cx,
UNNECESSARY_CAST,
expr.span,
format!("casting to the same type is unnecessary (`{cast_from}` -> `{cast_to}`)"),
"try",
match surrounding {
MaybeParenOrBlock::Paren => format!("({cast_str})"),
MaybeParenOrBlock::Block => format!("{{ {cast_str} }}"),
MaybeParenOrBlock::Nothing => cast_str,
},
Applicability::MachineApplicable,
);
return true;
}
false
}
fn lint_unnecessary_cast(
cx: &LateContext<'_>,
expr: &Expr<'_>,
raw_literal_str: &str,
cast_from: Ty<'_>,
cast_to: Ty<'_>,
) {
let literal_kind_name = if cast_from.is_integral() { "integer" } else { "float" };
// first we remove all matches so `-(1)` become `-1`, and remove trailing dots, so `1.` become `1`
let literal_str = raw_literal_str
.replace(['(', ')'], "")
.trim_end_matches('.')
.to_string();
// we know need to check if the parent is a method call, to add parenthesis accordingly (eg:
// (-1).foo() instead of -1.foo())
let sugg = if let Some(parent_expr) = get_parent_expr(cx, expr)
&& let ExprKind::MethodCall(..) = parent_expr.kind
&& literal_str.starts_with('-')
{
format!("({literal_str}_{cast_to})")
} else {
format!("{literal_str}_{cast_to}")
};
span_lint_and_sugg(
cx,
UNNECESSARY_CAST,
expr.span,
format!("casting {literal_kind_name} literal to `{cast_to}` is unnecessary"),
"try",
sugg,
Applicability::MachineApplicable,
);
}
fn get_numeric_literal<'e>(expr: &'e Expr<'e>) -> Option<&'e Lit> {
match expr.kind {
ExprKind::Lit(lit) => Some(lit),
ExprKind::Unary(UnOp::Neg, e) => {
if let ExprKind::Lit(lit) = e.kind {
Some(lit)
} else {
None
}
},
_ => None,
}
}
/// Returns the mantissa bits wide of a fp type.
/// Will return 0 if the type is not a fp
fn fp_ty_mantissa_nbits(typ: Ty<'_>) -> u32 {
match typ.kind() {
ty::Float(FloatTy::F32) => 23,
ty::Float(FloatTy::F64) | ty::Infer(InferTy::FloatVar(_)) => 52,
_ => 0,
}
}
/// Finds whether an `Expr` returns a type alias.
///
/// TODO: Maybe we should move this to `clippy_utils` so others won't need to go down this dark,
/// dark path reimplementing this (or something similar).
fn is_cast_from_ty_alias<'tcx>(cx: &LateContext<'tcx>, expr: impl Visitable<'tcx>, cast_from: Ty<'tcx>) -> bool {
for_each_expr_without_closures(expr, |expr| {
// Calls are a `Path`, and usage of locals are a `Path`. So, this checks
// - call() as i32
// - local as i32
if let ExprKind::Path(qpath) = expr.kind {
let res = cx.qpath_res(&qpath, expr.hir_id);
// Function call
if let Res::Def(DefKind::Fn, def_id) = res {
let Some(snippet) = cx.tcx.def_span(def_id).get_source_text(cx) else {
return ControlFlow::Continue(());
};
// This is the worst part of this entire function. This is the only way I know of to
// check whether a function returns a type alias. Sure, you can get the return type
// from a function in the current crate as an hir ty, but how do you get it for
// external functions?? Simple: It's impossible. So, we check whether a part of the
// function's declaration snippet is exactly equal to the `Ty`. That way, we can
// see whether it's a type alias.
//
// FIXME: This won't work if the type is given an alias through `use`, should we
// consider this a type alias as well?
if !snippet
.split("->")
.skip(1)
.any(|s| snippet_eq_ty(s, cast_from) || s.split("where").any(|ty| snippet_eq_ty(ty, cast_from)))
{
return ControlFlow::Break(());
}
// Local usage
} else if let Res::Local(hir_id) = res
&& let Node::LetStmt(l) = cx.tcx.parent_hir_node(hir_id)
{
if let Some(e) = l.init
&& is_cast_from_ty_alias(cx, e, cast_from)
{
return ControlFlow::Break::<()>(());
}
if let Some(ty) = l.ty
&& let TyKind::Path(qpath) = ty.kind
&& is_ty_alias(&qpath)
{
return ControlFlow::Break::<()>(());
}
}
}
ControlFlow::Continue(())
})
.is_some()
}
fn snippet_eq_ty(snippet: &str, ty: Ty<'_>) -> bool {
snippet.trim() == ty.to_string() || snippet.trim().contains(&format!("::{ty}"))
}