]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_lint/src/hidden_unicode_codepoints.rs
New upstream version 1.66.0+dfsg1
[rustc.git] / compiler / rustc_lint / src / hidden_unicode_codepoints.rs
CommitLineData
c295e0f8 1use crate::{EarlyContext, EarlyLintPass, LintContext};
3c0e092e 2use ast::util::unicode::{contains_text_flow_control_chars, TEXT_FLOW_CONTROL_CHARS};
c295e0f8 3use rustc_ast as ast;
064997fb 4use rustc_errors::{fluent, Applicability, SuggestionStyle};
c295e0f8
XL
5use rustc_span::{BytePos, Span, Symbol};
6
7declare_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
39declare_lint_pass!(HiddenUnicodeCodepoints => [TEXT_DIRECTION_CODEPOINT_IN_LITERAL]);
40
c295e0f8
XL
41impl 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)| {
3c0e092e 56 TEXT_FLOW_CONTROL_CHARS.contains(&c).then(|| {
c295e0f8
XL
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
2b03887a
FG
63 cx.struct_span_lint(
64 TEXT_DIRECTION_CODEPOINT_IN_LITERAL,
65 span,
66 fluent::lint_hidden_unicode_codepoints,
67 |lint| {
68 lint.set_arg("label", label);
69 lint.set_arg("count", spans.len());
70 lint.span_label(span, fluent::label);
71 lint.note(fluent::note);
72 if point_at_inner_spans {
73 for (c, span) in &spans {
74 lint.span_label(*span, format!("{:?}", c));
75 }
c295e0f8 76 }
2b03887a
FG
77 if point_at_inner_spans && !spans.is_empty() {
78 lint.multipart_suggestion_with_style(
79 fluent::suggestion_remove,
80 spans.iter().map(|(_, span)| (*span, "".to_string())).collect(),
81 Applicability::MachineApplicable,
82 SuggestionStyle::HideCodeAlways,
83 );
84 lint.multipart_suggestion(
85 fluent::suggestion_escape,
86 spans
87 .into_iter()
88 .map(|(c, span)| {
89 let c = format!("{:?}", c);
90 (span, c[1..c.len() - 1].to_string())
91 })
92 .collect(),
93 Applicability::MachineApplicable,
94 );
95 } else {
96 // FIXME: in other suggestions we've reversed the inner spans of doc comments. We
97 // should do the same here to provide the same good suggestions as we do for
98 // literals above.
99 lint.set_arg(
100 "escaped",
101 spans
102 .into_iter()
103 .map(|(c, _)| format!("{:?}", c))
104 .collect::<Vec<String>>()
105 .join(", "),
106 );
107 lint.note(fluent::suggestion_remove);
108 lint.note(fluent::no_suggestion_note_escape);
109 }
110 lint
111 },
112 );
c295e0f8
XL
113 }
114}
115impl EarlyLintPass for HiddenUnicodeCodepoints {
116 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
117 if let ast::AttrKind::DocComment(_, comment) = attr.kind {
a2a8927a 118 if contains_text_flow_control_chars(comment.as_str()) {
c295e0f8
XL
119 self.lint_text_direction_codepoint(cx, comment, attr.span, 0, false, "doc comment");
120 }
121 }
122 }
123
124 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
125 // byte strings are already handled well enough by `EscapeError::NonAsciiCharInByteString`
126 let (text, span, padding) = match &expr.kind {
f2b60f7d
FG
127 ast::ExprKind::Lit(ast::Lit { token_lit, kind, span }) => {
128 let text = token_lit.symbol;
a2a8927a 129 if !contains_text_flow_control_chars(text.as_str()) {
c295e0f8
XL
130 return;
131 }
132 let padding = match kind {
133 // account for `"` or `'`
134 ast::LitKind::Str(_, ast::StrStyle::Cooked) | ast::LitKind::Char(_) => 1,
135 // account for `r###"`
136 ast::LitKind::Str(_, ast::StrStyle::Raw(val)) => *val as u32 + 2,
137 _ => return,
138 };
139 (text, span, padding)
140 }
141 _ => return,
142 };
143 self.lint_text_direction_codepoint(cx, text, *span, padding, true, "literal");
144 }
145}