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