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