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