]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/unicode.rs
Rollup merge of #88215 - jyn514:lazy-loading, r=petrochenkov
[rust.git] / src / tools / clippy / clippy_lints / src / unicode.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::is_lint_allowed;
3 use clippy_utils::source::snippet;
4 use rustc_ast::ast::LitKind;
5 use rustc_errors::Applicability;
6 use rustc_hir::{Expr, ExprKind, HirId};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::source_map::Span;
10 use unicode_normalization::UnicodeNormalization;
11
12 declare_clippy_lint! {
13     /// ### What it does
14     /// Checks for invisible Unicode characters in the code.
15     ///
16     /// ### Why is this bad?
17     /// Having an invisible character in the code makes for all
18     /// sorts of April fools, but otherwise is very much frowned upon.
19     ///
20     /// ### Example
21     /// You don't see it, but there may be a zero-width space or soft hyphen
22     /// some­where in this text.
23     pub INVISIBLE_CHARACTERS,
24     correctness,
25     "using an invisible character in a string literal, which is confusing"
26 }
27
28 declare_clippy_lint! {
29     /// ### What it does
30     /// Checks for non-ASCII characters in string literals.
31     ///
32     /// ### Why is this bad?
33     /// Yeah, we know, the 90's called and wanted their charset
34     /// back. Even so, there still are editors and other programs out there that
35     /// don't work well with Unicode. So if the code is meant to be used
36     /// internationally, on multiple operating systems, or has other portability
37     /// requirements, activating this lint could be useful.
38     ///
39     /// ### Example
40     /// ```rust
41     /// let x = String::from("€");
42     /// ```
43     /// Could be written as:
44     /// ```rust
45     /// let x = String::from("\u{20ac}");
46     /// ```
47     pub NON_ASCII_LITERAL,
48     pedantic,
49     "using any literal non-ASCII chars in a string literal instead of using the `\\u` escape"
50 }
51
52 declare_clippy_lint! {
53     /// ### What it does
54     /// Checks for string literals that contain Unicode in a form
55     /// that is not equal to its
56     /// [NFC-recomposition](http://www.unicode.org/reports/tr15/#Norm_Forms).
57     ///
58     /// ### Why is this bad?
59     /// If such a string is compared to another, the results
60     /// may be surprising.
61     ///
62     /// ### Example
63     /// You may not see it, but "à"" and "à"" aren't the same string. The
64     /// former when escaped is actually `"a\u{300}"` while the latter is `"\u{e0}"`.
65     pub UNICODE_NOT_NFC,
66     pedantic,
67     "using a Unicode literal not in NFC normal form (see [Unicode tr15](http://www.unicode.org/reports/tr15/) for further information)"
68 }
69
70 declare_lint_pass!(Unicode => [INVISIBLE_CHARACTERS, NON_ASCII_LITERAL, UNICODE_NOT_NFC]);
71
72 impl LateLintPass<'_> for Unicode {
73     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'_ Expr<'_>) {
74         if let ExprKind::Lit(ref lit) = expr.kind {
75             if let LitKind::Str(_, _) = lit.node {
76                 check_str(cx, lit.span, expr.hir_id);
77             }
78         }
79     }
80 }
81
82 fn escape<T: Iterator<Item = char>>(s: T) -> String {
83     let mut result = String::new();
84     for c in s {
85         if c as u32 > 0x7F {
86             for d in c.escape_unicode() {
87                 result.push(d);
88             }
89         } else {
90             result.push(c);
91         }
92     }
93     result
94 }
95
96 fn check_str(cx: &LateContext<'_>, span: Span, id: HirId) {
97     let string = snippet(cx, span, "");
98     if string.chars().any(|c| ['\u{200B}', '\u{ad}', '\u{2060}'].contains(&c)) {
99         span_lint_and_sugg(
100             cx,
101             INVISIBLE_CHARACTERS,
102             span,
103             "invisible character detected",
104             "consider replacing the string with",
105             string
106                 .replace("\u{200B}", "\\u{200B}")
107                 .replace("\u{ad}", "\\u{AD}")
108                 .replace("\u{2060}", "\\u{2060}"),
109             Applicability::MachineApplicable,
110         );
111     }
112     if string.chars().any(|c| c as u32 > 0x7F) {
113         span_lint_and_sugg(
114             cx,
115             NON_ASCII_LITERAL,
116             span,
117             "literal non-ASCII character detected",
118             "consider replacing the string with",
119             if is_lint_allowed(cx, UNICODE_NOT_NFC, id) {
120                 escape(string.chars())
121             } else {
122                 escape(string.nfc())
123             },
124             Applicability::MachineApplicable,
125         );
126     }
127     if is_lint_allowed(cx, NON_ASCII_LITERAL, id) && string.chars().zip(string.nfc()).any(|(a, b)| a != b) {
128         span_lint_and_sugg(
129             cx,
130             UNICODE_NOT_NFC,
131             span,
132             "non-NFC Unicode sequence detected",
133             "consider replacing the string with",
134             string.nfc().collect::<String>(),
135             Applicability::MachineApplicable,
136         );
137     }
138 }