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