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