]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/unicode.rs
HirIdify some lints
[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;
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     fn name(&self) -> &'static str {
70         "Unicode"
71     }
72 }
73
74 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Unicode {
75     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
76         if let ExprKind::Lit(ref lit) = expr.node {
77             if let LitKind::Str(_, _) = lit.node {
78                 check_str(cx, lit.span, expr.hir_id)
79             }
80         }
81     }
82 }
83
84 fn escape<T: Iterator<Item = char>>(s: T) -> String {
85     let mut result = String::new();
86     for c in s {
87         if c as u32 > 0x7F {
88             for d in c.escape_unicode() {
89                 result.push(d)
90             }
91         } else {
92             result.push(c);
93         }
94     }
95     result
96 }
97
98 fn check_str(cx: &LateContext<'_, '_>, span: Span, id: HirId) {
99     let string = snippet(cx, span, "");
100     if string.contains('\u{200B}') {
101         span_help_and_lint(
102             cx,
103             ZERO_WIDTH_SPACE,
104             span,
105             "zero-width space detected",
106             &format!(
107                 "Consider replacing the string with:\n\"{}\"",
108                 string.replace("\u{200B}", "\\u{200B}")
109             ),
110         );
111     }
112     if string.chars().any(|c| c as u32 > 0x7F) {
113         span_help_and_lint(
114             cx,
115             NON_ASCII_LITERAL,
116             span,
117             "literal non-ASCII character detected",
118             &format!(
119                 "Consider replacing the string with:\n\"{}\"",
120                 if is_allowed(cx, UNICODE_NOT_NFC, id) {
121                     escape(string.chars())
122                 } else {
123                     escape(string.nfc())
124                 }
125             ),
126         );
127     }
128     if is_allowed(cx, NON_ASCII_LITERAL, id) && string.chars().zip(string.nfc()).any(|(a, b)| a != b) {
129         span_help_and_lint(
130             cx,
131             UNICODE_NOT_NFC,
132             span,
133             "non-nfc unicode sequence detected",
134             &format!(
135                 "Consider replacing the string with:\n\"{}\"",
136                 string.nfc().collect::<String>()
137             ),
138         );
139     }
140 }