]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/casts/mod.rs
Auto merge of #85020 - lrh2000:named-upvars, r=tmandry
[rust.git] / src / tools / clippy / clippy_lints / src / casts / mod.rs
1 mod cast_lossless;
2 mod cast_possible_truncation;
3 mod cast_possible_wrap;
4 mod cast_precision_loss;
5 mod cast_ptr_alignment;
6 mod cast_ref_to_mut;
7 mod cast_sign_loss;
8 mod char_lit_as_u8;
9 mod fn_to_numeric_cast;
10 mod fn_to_numeric_cast_with_truncation;
11 mod ptr_as_ptr;
12 mod unnecessary_cast;
13 mod utils;
14
15 use clippy_utils::is_hir_ty_cfg_dependant;
16 use rustc_hir::{Expr, ExprKind};
17 use rustc_lint::{LateContext, LateLintPass, LintContext};
18 use rustc_middle::lint::in_external_macro;
19 use rustc_semver::RustcVersion;
20 use rustc_session::{declare_tool_lint, impl_lint_pass};
21
22 declare_clippy_lint! {
23     /// ### What it does
24     /// Checks for casts from any numerical to a float type where
25     /// the receiving type cannot store all values from the original type without
26     /// rounding errors. This possible rounding is to be expected, so this lint is
27     /// `Allow` by default.
28     ///
29     /// Basically, this warns on casting any integer with 32 or more bits to `f32`
30     /// or any 64-bit integer to `f64`.
31     ///
32     /// ### Why is this bad?
33     /// It's not bad at all. But in some applications it can be
34     /// helpful to know where precision loss can take place. This lint can help find
35     /// those places in the code.
36     ///
37     /// ### Example
38     /// ```rust
39     /// let x = u64::MAX;
40     /// x as f64;
41     /// ```
42     pub CAST_PRECISION_LOSS,
43     pedantic,
44     "casts that cause loss of precision, e.g., `x as f32` where `x: u64`"
45 }
46
47 declare_clippy_lint! {
48     /// ### What it does
49     /// Checks for casts from a signed to an unsigned numerical
50     /// type. In this case, negative values wrap around to large positive values,
51     /// which can be quite surprising in practice. However, as the cast works as
52     /// defined, this lint is `Allow` by default.
53     ///
54     /// ### Why is this bad?
55     /// Possibly surprising results. You can activate this lint
56     /// as a one-time check to see where numerical wrapping can arise.
57     ///
58     /// ### Example
59     /// ```rust
60     /// let y: i8 = -1;
61     /// y as u128; // will return 18446744073709551615
62     /// ```
63     pub CAST_SIGN_LOSS,
64     pedantic,
65     "casts from signed types to unsigned types, e.g., `x as u32` where `x: i32`"
66 }
67
68 declare_clippy_lint! {
69     /// ### What it does
70     /// Checks for casts between numerical types that may
71     /// truncate large values. This is expected behavior, so the cast is `Allow` by
72     /// default.
73     ///
74     /// ### Why is this bad?
75     /// In some problem domains, it is good practice to avoid
76     /// truncation. This lint can be activated to help assess where additional
77     /// checks could be beneficial.
78     ///
79     /// ### Example
80     /// ```rust
81     /// fn as_u8(x: u64) -> u8 {
82     ///     x as u8
83     /// }
84     /// ```
85     pub CAST_POSSIBLE_TRUNCATION,
86     pedantic,
87     "casts that may cause truncation of the value, e.g., `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
88 }
89
90 declare_clippy_lint! {
91     /// ### What it does
92     /// Checks for casts from an unsigned type to a signed type of
93     /// the same size. Performing such a cast is a 'no-op' for the compiler,
94     /// i.e., nothing is changed at the bit level, and the binary representation of
95     /// the value is reinterpreted. This can cause wrapping if the value is too big
96     /// for the target signed type. However, the cast works as defined, so this lint
97     /// is `Allow` by default.
98     ///
99     /// ### Why is this bad?
100     /// While such a cast is not bad in itself, the results can
101     /// be surprising when this is not the intended behavior, as demonstrated by the
102     /// example below.
103     ///
104     /// ### Example
105     /// ```rust
106     /// u32::MAX as i32; // will yield a value of `-1`
107     /// ```
108     pub CAST_POSSIBLE_WRAP,
109     pedantic,
110     "casts that may cause wrapping around the value, e.g., `x as i32` where `x: u32` and `x > i32::MAX`"
111 }
112
113 declare_clippy_lint! {
114     /// ### What it does
115     /// Checks for casts between numerical types that may
116     /// be replaced by safe conversion functions.
117     ///
118     /// ### Why is this bad?
119     /// Rust's `as` keyword will perform many kinds of
120     /// conversions, including silently lossy conversions. Conversion functions such
121     /// as `i32::from` will only perform lossless conversions. Using the conversion
122     /// functions prevents conversions from turning into silent lossy conversions if
123     /// the types of the input expressions ever change, and make it easier for
124     /// people reading the code to know that the conversion is lossless.
125     ///
126     /// ### Example
127     /// ```rust
128     /// fn as_u64(x: u8) -> u64 {
129     ///     x as u64
130     /// }
131     /// ```
132     ///
133     /// Using `::from` would look like this:
134     ///
135     /// ```rust
136     /// fn as_u64(x: u8) -> u64 {
137     ///     u64::from(x)
138     /// }
139     /// ```
140     pub CAST_LOSSLESS,
141     pedantic,
142     "casts using `as` that are known to be lossless, e.g., `x as u64` where `x: u8`"
143 }
144
145 declare_clippy_lint! {
146     /// ### What it does
147     /// Checks for casts to the same type, casts of int literals to integer types
148     /// and casts of float literals to float types.
149     ///
150     /// ### Why is this bad?
151     /// It's just unnecessary.
152     ///
153     /// ### Example
154     /// ```rust
155     /// let _ = 2i32 as i32;
156     /// let _ = 0.5 as f32;
157     /// ```
158     ///
159     /// Better:
160     ///
161     /// ```rust
162     /// let _ = 2_i32;
163     /// let _ = 0.5_f32;
164     /// ```
165     pub UNNECESSARY_CAST,
166     complexity,
167     "cast to the same type, e.g., `x as i32` where `x: i32`"
168 }
169
170 declare_clippy_lint! {
171     /// ### What it does
172     /// Checks for casts, using `as` or `pointer::cast`,
173     /// from a less-strictly-aligned pointer to a more-strictly-aligned pointer
174     ///
175     /// ### Why is this bad?
176     /// Dereferencing the resulting pointer may be undefined
177     /// behavior.
178     ///
179     /// ### Known problems
180     /// Using `std::ptr::read_unaligned` and `std::ptr::write_unaligned` or similar
181     /// on the resulting pointer is fine. Is over-zealous: Casts with manual alignment checks or casts like
182     /// u64-> u8 -> u16 can be fine. Miri is able to do a more in-depth analysis.
183     ///
184     /// ### Example
185     /// ```rust
186     /// let _ = (&1u8 as *const u8) as *const u16;
187     /// let _ = (&mut 1u8 as *mut u8) as *mut u16;
188     ///
189     /// (&1u8 as *const u8).cast::<u16>();
190     /// (&mut 1u8 as *mut u8).cast::<u16>();
191     /// ```
192     pub CAST_PTR_ALIGNMENT,
193     pedantic,
194     "cast from a pointer to a more-strictly-aligned pointer"
195 }
196
197 declare_clippy_lint! {
198     /// ### What it does
199     /// Checks for casts of function pointers to something other than usize
200     ///
201     /// ### Why is this bad?
202     /// Casting a function pointer to anything other than usize/isize is not portable across
203     /// architectures, because you end up losing bits if the target type is too small or end up with a
204     /// bunch of extra bits that waste space and add more instructions to the final binary than
205     /// strictly necessary for the problem
206     ///
207     /// Casting to isize also doesn't make sense since there are no signed addresses.
208     ///
209     /// ### Example
210     /// ```rust
211     /// // Bad
212     /// fn fun() -> i32 { 1 }
213     /// let a = fun as i64;
214     ///
215     /// // Good
216     /// fn fun2() -> i32 { 1 }
217     /// let a = fun2 as usize;
218     /// ```
219     pub FN_TO_NUMERIC_CAST,
220     style,
221     "casting a function pointer to a numeric type other than usize"
222 }
223
224 declare_clippy_lint! {
225     /// ### What it does
226     /// Checks for casts of a function pointer to a numeric type not wide enough to
227     /// store address.
228     ///
229     /// ### Why is this bad?
230     /// Such a cast discards some bits of the function's address. If this is intended, it would be more
231     /// clearly expressed by casting to usize first, then casting the usize to the intended type (with
232     /// a comment) to perform the truncation.
233     ///
234     /// ### Example
235     /// ```rust
236     /// // Bad
237     /// fn fn1() -> i16 {
238     ///     1
239     /// };
240     /// let _ = fn1 as i32;
241     ///
242     /// // Better: Cast to usize first, then comment with the reason for the truncation
243     /// fn fn2() -> i16 {
244     ///     1
245     /// };
246     /// let fn_ptr = fn2 as usize;
247     /// let fn_ptr_truncated = fn_ptr as i32;
248     /// ```
249     pub FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
250     style,
251     "casting a function pointer to a numeric type not wide enough to store the address"
252 }
253
254 declare_clippy_lint! {
255     /// ### What it does
256     /// Checks for casts of `&T` to `&mut T` anywhere in the code.
257     ///
258     /// ### Why is this bad?
259     /// It’s basically guaranteed to be undefined behaviour.
260     /// `UnsafeCell` is the only way to obtain aliasable data that is considered
261     /// mutable.
262     ///
263     /// ### Example
264     /// ```rust,ignore
265     /// fn x(r: &i32) {
266     ///     unsafe {
267     ///         *(r as *const _ as *mut _) += 1;
268     ///     }
269     /// }
270     /// ```
271     ///
272     /// Instead consider using interior mutability types.
273     ///
274     /// ```rust
275     /// use std::cell::UnsafeCell;
276     ///
277     /// fn x(r: &UnsafeCell<i32>) {
278     ///     unsafe {
279     ///         *r.get() += 1;
280     ///     }
281     /// }
282     /// ```
283     pub CAST_REF_TO_MUT,
284     correctness,
285     "a cast of reference to a mutable pointer"
286 }
287
288 declare_clippy_lint! {
289     /// ### What it does
290     /// Checks for expressions where a character literal is cast
291     /// to `u8` and suggests using a byte literal instead.
292     ///
293     /// ### Why is this bad?
294     /// In general, casting values to smaller types is
295     /// error-prone and should be avoided where possible. In the particular case of
296     /// converting a character literal to u8, it is easy to avoid by just using a
297     /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
298     /// than `'a' as u8`.
299     ///
300     /// ### Example
301     /// ```rust,ignore
302     /// 'x' as u8
303     /// ```
304     ///
305     /// A better version, using the byte literal:
306     ///
307     /// ```rust,ignore
308     /// b'x'
309     /// ```
310     pub CHAR_LIT_AS_U8,
311     complexity,
312     "casting a character literal to `u8` truncates"
313 }
314
315 declare_clippy_lint! {
316     /// ### What it does
317     /// Checks for `as` casts between raw pointers without changing its mutability,
318     /// namely `*const T` to `*const U` and `*mut T` to `*mut U`.
319     ///
320     /// ### Why is this bad?
321     /// Though `as` casts between raw pointers is not terrible, `pointer::cast` is safer because
322     /// it cannot accidentally change the pointer's mutability nor cast the pointer to other types like `usize`.
323     ///
324     /// ### Example
325     /// ```rust
326     /// let ptr: *const u32 = &42_u32;
327     /// let mut_ptr: *mut u32 = &mut 42_u32;
328     /// let _ = ptr as *const i32;
329     /// let _ = mut_ptr as *mut i32;
330     /// ```
331     /// Use instead:
332     /// ```rust
333     /// let ptr: *const u32 = &42_u32;
334     /// let mut_ptr: *mut u32 = &mut 42_u32;
335     /// let _ = ptr.cast::<i32>();
336     /// let _ = mut_ptr.cast::<i32>();
337     /// ```
338     pub PTR_AS_PTR,
339     pedantic,
340     "casting using `as` from and to raw pointers that doesn't change its mutability, where `pointer::cast` could take the place of `as`"
341 }
342
343 pub struct Casts {
344     msrv: Option<RustcVersion>,
345 }
346
347 impl Casts {
348     #[must_use]
349     pub fn new(msrv: Option<RustcVersion>) -> Self {
350         Self { msrv }
351     }
352 }
353
354 impl_lint_pass!(Casts => [
355     CAST_PRECISION_LOSS,
356     CAST_SIGN_LOSS,
357     CAST_POSSIBLE_TRUNCATION,
358     CAST_POSSIBLE_WRAP,
359     CAST_LOSSLESS,
360     CAST_REF_TO_MUT,
361     CAST_PTR_ALIGNMENT,
362     UNNECESSARY_CAST,
363     FN_TO_NUMERIC_CAST,
364     FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
365     CHAR_LIT_AS_U8,
366     PTR_AS_PTR,
367 ]);
368
369 impl<'tcx> LateLintPass<'tcx> for Casts {
370     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
371         if expr.span.from_expansion() {
372             return;
373         }
374
375         if let ExprKind::Cast(cast_expr, cast_to) = expr.kind {
376             if is_hir_ty_cfg_dependant(cx, cast_to) {
377                 return;
378             }
379             let (cast_from, cast_to) = (
380                 cx.typeck_results().expr_ty(cast_expr),
381                 cx.typeck_results().expr_ty(expr),
382             );
383
384             if unnecessary_cast::check(cx, expr, cast_expr, cast_from, cast_to) {
385                 return;
386             }
387
388             fn_to_numeric_cast::check(cx, expr, cast_expr, cast_from, cast_to);
389             fn_to_numeric_cast_with_truncation::check(cx, expr, cast_expr, cast_from, cast_to);
390             if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
391                 cast_possible_truncation::check(cx, expr, cast_from, cast_to);
392                 cast_possible_wrap::check(cx, expr, cast_from, cast_to);
393                 cast_precision_loss::check(cx, expr, cast_from, cast_to);
394                 cast_lossless::check(cx, expr, cast_expr, cast_from, cast_to);
395                 cast_sign_loss::check(cx, expr, cast_expr, cast_from, cast_to);
396             }
397         }
398
399         cast_ref_to_mut::check(cx, expr);
400         cast_ptr_alignment::check(cx, expr);
401         char_lit_as_u8::check(cx, expr);
402         ptr_as_ptr::check(cx, expr, &self.msrv);
403     }
404
405     extract_msrv_attr!(LateContext);
406 }