]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/as_conversions.rs
Rollup merge of #91313 - petrochenkov:cratexp, r=Aaron1011
[rust.git] / src / tools / clippy / clippy_lints / src / as_conversions.rs
1 use clippy_utils::diagnostics::span_lint_and_help;
2 use rustc_ast::ast::{Expr, ExprKind};
3 use rustc_lint::{EarlyContext, EarlyLintPass};
4 use rustc_middle::lint::in_external_macro;
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
6
7 declare_clippy_lint! {
8     /// ### What it does
9     /// Checks for usage of `as` conversions.
10     ///
11     /// Note that this lint is specialized in linting *every single* use of `as`
12     /// regardless of whether good alternatives exist or not.
13     /// If you want more precise lints for `as`, please consider using these separate lints:
14     /// `unnecessary_cast`, `cast_lossless/possible_truncation/possible_wrap/precision_loss/sign_loss`,
15     /// `fn_to_numeric_cast(_with_truncation)`, `char_lit_as_u8`, `ref_to_mut` and `ptr_as_ptr`.
16     /// There is a good explanation the reason why this lint should work in this way and how it is useful
17     /// [in this issue](https://github.com/rust-lang/rust-clippy/issues/5122).
18     ///
19     /// ### Why is this bad?
20     /// `as` conversions will perform many kinds of
21     /// conversions, including silently lossy conversions and dangerous coercions.
22     /// There are cases when it makes sense to use `as`, so the lint is
23     /// Allow by default.
24     ///
25     /// ### Example
26     /// ```rust,ignore
27     /// let a: u32;
28     /// ...
29     /// f(a as u16);
30     /// ```
31     ///
32     /// Usually better represents the semantics you expect:
33     /// ```rust,ignore
34     /// f(a.try_into()?);
35     /// ```
36     /// or
37     /// ```rust,ignore
38     /// f(a.try_into().expect("Unexpected u16 overflow in f"));
39     /// ```
40     ///
41     pub AS_CONVERSIONS,
42     restriction,
43     "using a potentially dangerous silent `as` conversion"
44 }
45
46 declare_lint_pass!(AsConversions => [AS_CONVERSIONS]);
47
48 impl EarlyLintPass for AsConversions {
49     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
50         if in_external_macro(cx.sess, expr.span) {
51             return;
52         }
53
54         if let ExprKind::Cast(_, _) = expr.kind {
55             span_lint_and_help(
56                 cx,
57                 AS_CONVERSIONS,
58                 expr.span,
59                 "using a potentially dangerous silent `as` conversion",
60                 None,
61                 "consider using a safe wrapper for this conversion",
62             );
63         }
64     }
65 }