]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/as_conversions.rs
rustup https://github.com/rust-lang/rust/pull/67455
[rust.git] / clippy_lints / src / as_conversions.rs
1 use rustc::declare_lint_pass;
2 use rustc::lint::{in_external_macro, EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass};
3 use rustc_session::declare_tool_lint;
4 use syntax::ast::*;
5
6 use crate::utils::span_help_and_lint;
7
8 declare_clippy_lint! {
9     /// **What it does:** Checks for usage of `as` conversions.
10     ///
11     /// **Why is this bad?** `as` conversions will perform many kinds of
12     /// conversions, including silently lossy conversions and dangerous coercions.
13     /// There are cases when it makes sense to use `as`, so the lint is
14     /// Allow by default.
15     ///
16     /// **Known problems:** None.
17     ///
18     /// **Example:**
19     /// ```rust,ignore
20     /// let a: u32;
21     /// ...
22     /// f(a as u16);
23     /// ```
24     ///
25     /// Usually better represents the semantics you expect:
26     /// ```rust,ignore
27     /// f(a.try_into()?);
28     /// ```
29     /// or
30     /// ```rust,ignore
31     /// f(a.try_into().expect("Unexpected u16 overflow in f"));
32     /// ```
33     ///
34     pub AS_CONVERSIONS,
35     restriction,
36     "using a potentially dangerous silent `as` conversion"
37 }
38
39 declare_lint_pass!(AsConversions => [AS_CONVERSIONS]);
40
41 impl EarlyLintPass for AsConversions {
42     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
43         if in_external_macro(cx.sess(), expr.span) {
44             return;
45         }
46
47         if let ExprKind::Cast(_, _) = expr.kind {
48             span_help_and_lint(
49                 cx,
50                 AS_CONVERSIONS,
51                 expr.span,
52                 "using a potentially dangerous silent `as` conversion",
53                 "consider using a safe wrapper for this conversion",
54             );
55         }
56     }
57 }