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