]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/unsafe_removed_from_name.rs
Normalize lint messages
[rust.git] / clippy_lints / src / unsafe_removed_from_name.rs
1 use crate::utils::span_lint;
2 use rustc::declare_lint_pass;
3 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
4 use rustc_session::declare_tool_lint;
5 use rustc_span::source_map::Span;
6 use rustc_span::symbol::SymbolStr;
7 use syntax::ast::*;
8
9 declare_clippy_lint! {
10     /// **What it does:** Checks for imports that remove "unsafe" from an item's
11     /// name.
12     ///
13     /// **Why is this bad?** Renaming makes it less clear which traits and
14     /// structures are unsafe.
15     ///
16     /// **Known problems:** None.
17     ///
18     /// **Example:**
19     /// ```rust,ignore
20     /// use std::cell::{UnsafeCell as TotallySafeCell};
21     ///
22     /// extern crate crossbeam;
23     /// use crossbeam::{spawn_unsafe as spawn};
24     /// ```
25     pub UNSAFE_REMOVED_FROM_NAME,
26     style,
27     "`unsafe` removed from API names on import"
28 }
29
30 declare_lint_pass!(UnsafeNameRemoval => [UNSAFE_REMOVED_FROM_NAME]);
31
32 impl EarlyLintPass for UnsafeNameRemoval {
33     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
34         if let ItemKind::Use(ref use_tree) = item.kind {
35             check_use_tree(use_tree, cx, item.span);
36         }
37     }
38 }
39
40 fn check_use_tree(use_tree: &UseTree, cx: &EarlyContext<'_>, span: Span) {
41     match use_tree.kind {
42         UseTreeKind::Simple(Some(new_name), ..) => {
43             let old_name = use_tree
44                 .prefix
45                 .segments
46                 .last()
47                 .expect("use paths cannot be empty")
48                 .ident;
49             unsafe_to_safe_check(old_name, new_name, cx, span);
50         },
51         UseTreeKind::Simple(None, ..) | UseTreeKind::Glob => {},
52         UseTreeKind::Nested(ref nested_use_tree) => {
53             for &(ref use_tree, _) in nested_use_tree {
54                 check_use_tree(use_tree, cx, span);
55             }
56         },
57     }
58 }
59
60 fn unsafe_to_safe_check(old_name: Ident, new_name: Ident, cx: &EarlyContext<'_>, span: Span) {
61     let old_str = old_name.name.as_str();
62     let new_str = new_name.name.as_str();
63     if contains_unsafe(&old_str) && !contains_unsafe(&new_str) {
64         span_lint(
65             cx,
66             UNSAFE_REMOVED_FROM_NAME,
67             span,
68             &format!(
69                 "removed `unsafe` from the name of `{}` in use as `{}`",
70                 old_str, new_str
71             ),
72         );
73     }
74 }
75
76 #[must_use]
77 fn contains_unsafe(name: &SymbolStr) -> bool {
78     name.contains("Unsafe") || name.contains("unsafe")
79 }