]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/unicode.rs
Auto merge of #3646 - matthiaskrgr:travis, r=phansch
[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_tool_lint, lint_array};
5 use syntax::ast::{LitKind, NodeId};
6 use syntax::source_map::Span;
7 use unicode_normalization::UnicodeNormalization;
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 using the `\\u` escape"
42 }
43
44 /// **What it does:** Checks for string literals that contain Unicode in a form
45 /// that is not equal to its
46 /// [NFC-recomposition](http://www.unicode.org/reports/tr15/#Norm_Forms).
47 ///
48 /// **Why is this bad?** If such a string is compared to another, the results
49 /// may be surprising.
50 ///
51 /// **Known problems** None.
52 ///
53 /// **Example:** You may not see it, but “à” and “à” aren't the same string. The
54 /// former when escaped is actually `"a\u{300}"` while the latter is `"\u{e0}"`.
55 declare_clippy_lint! {
56     pub UNICODE_NOT_NFC,
57     pedantic,
58     "using a unicode literal not in NFC normal form (see [unicode tr15](http://www.unicode.org/reports/tr15/) for further information)"
59 }
60
61 #[derive(Copy, Clone)]
62 pub struct Unicode;
63
64 impl LintPass for Unicode {
65     fn get_lints(&self) -> LintArray {
66         lint_array!(ZERO_WIDTH_SPACE, NON_ASCII_LITERAL, UNICODE_NOT_NFC)
67     }
68 }
69
70 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Unicode {
71     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
72         if let ExprKind::Lit(ref lit) = expr.node {
73             if let LitKind::Str(_, _) = lit.node {
74                 check_str(cx, lit.span, expr.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: NodeId) {
95     let string = snippet(cx, span, "");
96     if string.contains('\u{200B}') {
97         span_help_and_lint(
98             cx,
99             ZERO_WIDTH_SPACE,
100             span,
101             "zero-width space detected",
102             &format!(
103                 "Consider replacing the string with:\n\"{}\"",
104                 string.replace("\u{200B}", "\\u{200B}")
105             ),
106         );
107     }
108     if string.chars().any(|c| c as u32 > 0x7F) {
109         span_help_and_lint(
110             cx,
111             NON_ASCII_LITERAL,
112             span,
113             "literal non-ASCII character detected",
114             &format!(
115                 "Consider replacing the string with:\n\"{}\"",
116                 if is_allowed(cx, UNICODE_NOT_NFC, id) {
117                     escape(string.chars())
118                 } else {
119                     escape(string.nfc())
120                 }
121             ),
122         );
123     }
124     if is_allowed(cx, NON_ASCII_LITERAL, id) && string.chars().zip(string.nfc()).any(|(a, b)| a != b) {
125         span_help_and_lint(
126             cx,
127             UNICODE_NOT_NFC,
128             span,
129             "non-nfc unicode sequence detected",
130             &format!(
131                 "Consider replacing the string with:\n\"{}\"",
132                 string.nfc().collect::<String>()
133             ),
134         );
135     }
136 }