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