]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/clippy_lints/src/blacklisted_name.rs
New upstream version 1.55.0+dfsg1
[rustc.git] / src / tools / clippy / clippy_lints / src / blacklisted_name.rs
1 use clippy_utils::{diagnostics::span_lint, is_test_module_or_function};
2 use rustc_data_structures::fx::FxHashSet;
3 use rustc_hir::{Item, Pat, PatKind};
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_session::{declare_tool_lint, impl_lint_pass};
6
7 declare_clippy_lint! {
8 /// **What it does:** Checks for usage of blacklisted names for variables, such
9 /// as `foo`.
10 ///
11 /// **Why is this bad?** These names are usually placeholder names and should be
12 /// avoided.
13 ///
14 /// **Known problems:** None.
15 ///
16 /// **Example:**
17 /// ```rust
18 /// let foo = 3.14;
19 /// ```
20 pub BLACKLISTED_NAME,
21 style,
22 "usage of a blacklisted/placeholder name"
23 }
24
25 #[derive(Clone, Debug)]
26 pub struct BlacklistedName {
27 blacklist: FxHashSet<String>,
28 test_modules_deep: u32,
29 }
30
31 impl BlacklistedName {
32 pub fn new(blacklist: FxHashSet<String>) -> Self {
33 Self {
34 blacklist,
35 test_modules_deep: 0,
36 }
37 }
38
39 fn in_test_module(&self) -> bool {
40 self.test_modules_deep != 0
41 }
42 }
43
44 impl_lint_pass!(BlacklistedName => [BLACKLISTED_NAME]);
45
46 impl<'tcx> LateLintPass<'tcx> for BlacklistedName {
47 fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
48 if is_test_module_or_function(cx.tcx, item) {
49 self.test_modules_deep = self.test_modules_deep.saturating_add(1);
50 }
51 }
52
53 fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
54 // Check whether we are under the `test` attribute.
55 if self.in_test_module() {
56 return;
57 }
58
59 if let PatKind::Binding(.., ident, _) = pat.kind {
60 if self.blacklist.contains(&ident.name.to_string()) {
61 span_lint(
62 cx,
63 BLACKLISTED_NAME,
64 ident.span,
65 &format!("use of a blacklisted/placeholder name `{}`", ident.name),
66 );
67 }
68 }
69 }
70
71 fn check_item_post(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
72 if is_test_module_or_function(cx.tcx, item) {
73 self.test_modules_deep = self.test_modules_deep.saturating_sub(1);
74 }
75 }
76 }