]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/unsafe_removed_from_name.rs
Auto merge of #104673 - matthiaskrgr:rollup-85f65ov, r=matthiaskrgr
[rust.git] / src / tools / clippy / 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     #[clippy::version = "pre 1.29.0"]
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!("removed `unsafe` from the name of `{old_str}` in use as `{new_str}`"),
69         );
70     }
71 }
72
73 #[must_use]
74 fn contains_unsafe(name: &str) -> bool {
75     name.contains("Unsafe") || name.contains("unsafe")
76 }