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