]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/hidden_unicode_codepoints.rs
8f22221324a6e64343208b0bc84987485fffd145
[rust.git] / compiler / rustc_lint / src / hidden_unicode_codepoints.rs
1 use crate::{EarlyContext, EarlyLintPass, LintContext};
2 use ast::util::unicode::{contains_text_flow_control_chars, TEXT_FLOW_CONTROL_CHARS};
3 use rustc_ast as ast;
4 use rustc_errors::{fluent, Applicability, SuggestionStyle};
5 use rustc_span::{BytePos, Span, Symbol};
6
7 declare_lint! {
8     /// The `text_direction_codepoint_in_literal` lint detects Unicode codepoints that change the
9     /// visual representation of text on screen in a way that does not correspond to their on
10     /// memory representation.
11     ///
12     /// ### Explanation
13     ///
14     /// The unicode characters `\u{202A}`, `\u{202B}`, `\u{202D}`, `\u{202E}`, `\u{2066}`,
15     /// `\u{2067}`, `\u{2068}`, `\u{202C}` and `\u{2069}` make the flow of text on screen change
16     /// its direction on software that supports these codepoints. This makes the text "abc" display
17     /// as "cba" on screen. By leveraging software that supports these, people can write specially
18     /// crafted literals that make the surrounding code seem like it's performing one action, when
19     /// in reality it is performing another. Because of this, we proactively lint against their
20     /// presence to avoid surprises.
21     ///
22     /// ### Example
23     ///
24     /// ```rust,compile_fail
25     /// #![deny(text_direction_codepoint_in_literal)]
26     /// fn main() {
27     ///     println!("{:?}", '‮');
28     /// }
29     /// ```
30     ///
31     /// {{produces}}
32     ///
33     pub TEXT_DIRECTION_CODEPOINT_IN_LITERAL,
34     Deny,
35     "detect special Unicode codepoints that affect the visual representation of text on screen, \
36      changing the direction in which text flows",
37 }
38
39 declare_lint_pass!(HiddenUnicodeCodepoints => [TEXT_DIRECTION_CODEPOINT_IN_LITERAL]);
40
41 impl HiddenUnicodeCodepoints {
42     fn lint_text_direction_codepoint(
43         &self,
44         cx: &EarlyContext<'_>,
45         text: Symbol,
46         span: Span,
47         padding: u32,
48         point_at_inner_spans: bool,
49         label: &str,
50     ) {
51         // Obtain the `Span`s for each of the forbidden chars.
52         let spans: Vec<_> = text
53             .as_str()
54             .char_indices()
55             .filter_map(|(i, c)| {
56                 TEXT_FLOW_CONTROL_CHARS.contains(&c).then(|| {
57                     let lo = span.lo() + BytePos(i as u32 + padding);
58                     (c, span.with_lo(lo).with_hi(lo + BytePos(c.len_utf8() as u32)))
59                 })
60             })
61             .collect();
62
63         cx.struct_span_lint(TEXT_DIRECTION_CODEPOINT_IN_LITERAL, span, |lint| {
64             let mut err = lint.build(fluent::lint::hidden_unicode_codepoints);
65             err.set_arg("label", label);
66             err.set_arg("count", spans.len());
67             err.span_label(span, fluent::lint::label);
68             err.note(fluent::lint::note);
69             if point_at_inner_spans {
70                 for (c, span) in &spans {
71                     err.span_label(*span, format!("{:?}", c));
72                 }
73             }
74             if point_at_inner_spans && !spans.is_empty() {
75                 err.multipart_suggestion_with_style(
76                     fluent::lint::suggestion_remove,
77                     spans.iter().map(|(_, span)| (*span, "".to_string())).collect(),
78                     Applicability::MachineApplicable,
79                     SuggestionStyle::HideCodeAlways,
80                 );
81                 err.multipart_suggestion(
82                     fluent::lint::suggestion_escape,
83                     spans
84                         .into_iter()
85                         .map(|(c, span)| {
86                             let c = format!("{:?}", c);
87                             (span, c[1..c.len() - 1].to_string())
88                         })
89                         .collect(),
90                     Applicability::MachineApplicable,
91                 );
92             } else {
93                 // FIXME: in other suggestions we've reversed the inner spans of doc comments. We
94                 // should do the same here to provide the same good suggestions as we do for
95                 // literals above.
96                 err.set_arg(
97                     "escaped",
98                     spans
99                         .into_iter()
100                         .map(|(c, _)| format!("{:?}", c))
101                         .collect::<Vec<String>>()
102                         .join(", "),
103                 );
104                 err.note(fluent::lint::suggestion_remove);
105                 err.note(fluent::lint::no_suggestion_note_escape);
106             }
107             err.emit();
108         });
109     }
110 }
111 impl EarlyLintPass for HiddenUnicodeCodepoints {
112     fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
113         if let ast::AttrKind::DocComment(_, comment) = attr.kind {
114             if contains_text_flow_control_chars(comment.as_str()) {
115                 self.lint_text_direction_codepoint(cx, comment, attr.span, 0, false, "doc comment");
116             }
117         }
118     }
119
120     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
121         // byte strings are already handled well enough by `EscapeError::NonAsciiCharInByteString`
122         let (text, span, padding) = match &expr.kind {
123             ast::ExprKind::Lit(ast::Lit { token_lit, kind, span }) => {
124                 let text = token_lit.symbol;
125                 if !contains_text_flow_control_chars(text.as_str()) {
126                     return;
127                 }
128                 let padding = match kind {
129                     // account for `"` or `'`
130                     ast::LitKind::Str(_, ast::StrStyle::Cooked) | ast::LitKind::Char(_) => 1,
131                     // account for `r###"`
132                     ast::LitKind::Str(_, ast::StrStyle::Raw(val)) => *val as u32 + 2,
133                     _ => return,
134                 };
135                 (text, span, padding)
136             }
137             _ => return,
138         };
139         self.lint_text_direction_codepoint(cx, text, *span, padding, true, "literal");
140     }
141 }