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