Skip to main content

rustc_parse/lexer/
unescape_error_reporting.rs

1//! Utilities for rendering escape sequence errors as diagnostics.
2
3use std::iter::once;
4use std::ops::Range;
5
6use rustc_errors::{Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed};
7use rustc_literal_escaper::{EscapeError, Mode};
8use rustc_span::{BytePos, Span};
9use rustc_unicode::{unicode_normalization, unicode_width};
10use tracing::debug;
11
12use crate::diagnostics::{
13    MoreThanOneCharNote, MoreThanOneCharSugg, NoBraceUnicodeSub, UnescapeError,
14};
15
16pub(crate) fn emit_unescape_error(
17    dcx: DiagCtxtHandle<'_>,
18    // interior part of the literal, between quotes
19    lit: &str,
20    // full span of the literal, including quotes and any prefix
21    full_lit_span: Span,
22    // span of the error part of the literal
23    err_span: Span,
24    mode: Mode,
25    // range of the error inside `lit`
26    range: Range<usize>,
27    error: EscapeError,
28) -> Option<ErrorGuaranteed> {
29    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs:29",
                        "rustc_parse::lexer::unescape_error_reporting",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs"),
                        ::tracing_core::__macro_support::Option::Some(29u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::lexer::unescape_error_reporting"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("emit_unescape_error: {0:?}, {1:?}, {2:?}, {3:?}, {4:?}",
                                                    lit, full_lit_span, mode, range, error) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
30        "emit_unescape_error: {:?}, {:?}, {:?}, {:?}, {:?}",
31        lit, full_lit_span, mode, range, error
32    );
33    let last_char = || {
34        let c = lit[range.clone()].chars().next_back().unwrap();
35        let span = err_span.with_lo(err_span.hi() - BytePos(c.len_utf8() as u32));
36        (c, span)
37    };
38    Some(match error {
39        EscapeError::LoneSurrogateUnicodeEscape => {
40            dcx.emit_err(UnescapeError::InvalidUnicodeEscape { span: err_span, surrogate: true })
41        }
42        EscapeError::OutOfRangeUnicodeEscape => {
43            dcx.emit_err(UnescapeError::InvalidUnicodeEscape { span: err_span, surrogate: false })
44        }
45        EscapeError::MoreThanOneChar => {
46            use unicode_normalization::UnicodeNormalization;
47            use unicode_normalization::char::is_combining_mark;
48            let mut sugg = None;
49            let mut note = None;
50
51            let lit_chars = lit.chars().collect::<Vec<_>>();
52            let (first, rest) = lit_chars.split_first().unwrap();
53            if rest.iter().copied().all(is_combining_mark) {
54                let normalized = lit.nfc().to_string();
55                if normalized.chars().count() == 1 {
56                    let ch = normalized.chars().next().unwrap().escape_default().to_string();
57                    sugg = Some(MoreThanOneCharSugg::NormalizedForm {
58                        span: err_span,
59                        ch,
60                        normalized,
61                    });
62                }
63                let escaped_marks =
64                    rest.iter().map(|c| c.escape_default().to_string()).collect::<Vec<_>>();
65                note = Some(MoreThanOneCharNote::AllCombining {
66                    span: err_span,
67                    chr: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", first))
    })format!("{first}"),
68                    len: escaped_marks.len(),
69                    escaped_marks: escaped_marks.join(""),
70                });
71            } else {
72                let printable: Vec<char> = lit
73                    .chars()
74                    .filter(|&x| {
75                        unicode_width::UnicodeWidthChar::width(x).unwrap_or(0) != 0
76                            && !x.is_whitespace()
77                    })
78                    .collect();
79
80                if let &[ch] = printable.as_slice() {
81                    sugg = Some(MoreThanOneCharSugg::RemoveNonPrinting {
82                        span: err_span,
83                        ch: ch.to_string(),
84                    });
85                    note = Some(MoreThanOneCharNote::NonPrinting {
86                        span: err_span,
87                        escaped: lit.escape_default().to_string(),
88                    });
89                }
90            };
91            let sugg = sugg.unwrap_or_else(|| {
92                let prefix = mode.prefix_noraw();
93                let mut escaped = String::with_capacity(lit.len());
94                let mut in_escape = false;
95                for c in lit.chars() {
96                    match c {
97                        '\\' => in_escape = !in_escape,
98                        '"' if !in_escape => escaped.push('\\'),
99                        _ => in_escape = false,
100                    }
101                    escaped.push(c);
102                }
103                if escaped.len() != lit.len() || full_lit_span.is_empty() {
104                    let sugg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}\"{1}\"", prefix, escaped))
    })format!("{prefix}\"{escaped}\"");
105                    MoreThanOneCharSugg::QuotesFull {
106                        span: full_lit_span,
107                        is_byte: mode == Mode::Byte,
108                        sugg,
109                    }
110                } else {
111                    MoreThanOneCharSugg::Quotes {
112                        start: full_lit_span
113                            .with_hi(full_lit_span.lo() + BytePos((prefix.len() + 1) as u32)),
114                        end: full_lit_span.with_lo(full_lit_span.hi() - BytePos(1)),
115                        is_byte: mode == Mode::Byte,
116                        prefix,
117                    }
118                }
119            });
120            dcx.emit_err(UnescapeError::MoreThanOneChar {
121                span: full_lit_span,
122                note,
123                suggestion: sugg,
124            })
125        }
126        EscapeError::EscapeOnlyChar => {
127            let (c, char_span) = last_char();
128            dcx.emit_err(UnescapeError::EscapeOnlyChar {
129                span: err_span,
130                char_span,
131                escaped_sugg: c.escape_default().to_string(),
132                escaped_msg: escaped_char(c),
133                byte: mode == Mode::Byte,
134            })
135        }
136        EscapeError::BareCarriageReturn => {
137            let double_quotes = mode.in_double_quotes();
138            dcx.emit_err(UnescapeError::BareCr { span: err_span, double_quotes })
139        }
140        EscapeError::BareCarriageReturnInRawString => {
141            if !mode.in_double_quotes() {
    ::core::panicking::panic("assertion failed: mode.in_double_quotes()")
};assert!(mode.in_double_quotes());
142            dcx.emit_err(UnescapeError::BareCrRawString(err_span))
143        }
144        EscapeError::InvalidEscape => {
145            let (c, span) = last_char();
146
147            let label = if mode == Mode::Byte || mode == Mode::ByteStr {
148                "unknown byte escape"
149            } else {
150                "unknown character escape"
151            };
152            let ec = escaped_char(c);
153            let mut diag = dcx.struct_span_err(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: `{1}`", label, ec))
    })format!("{label}: `{ec}`"));
154            diag.span_label(span, label);
155            if c == '{' || c == '}' && #[allow(non_exhaustive_omitted_patterns)] match mode {
    Mode::Str | Mode::RawStr => true,
    _ => false,
}matches!(mode, Mode::Str | Mode::RawStr) {
156                diag.help(
157                    "if used in a formatting string, curly braces are escaped with `{{` and `}}`",
158                );
159            } else if c == '\r' {
160                diag.help(
161                    "this is an isolated carriage return; consider checking your editor and \
162                     version control settings",
163                );
164            } else {
165                if mode == Mode::Str || mode == Mode::Char {
166                    diag.span_suggestion_verbose(
167                        full_lit_span,
168                        "if you meant to write a literal backslash (perhaps escaping in a regular expression), consider a raw string literal",
169                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("r\"{0}\"", lit))
    })format!("r\"{lit}\""),
170                        Applicability::MaybeIncorrect,
171                    );
172                }
173
174                diag.help(
175                    "for more information, visit \
176                     <https://doc.rust-lang.org/reference/tokens.html#literals>",
177                );
178
179                foreign_escape_suggestion(&mut diag, (&ec, span), err_span);
180            }
181            diag.emit_err()
182        }
183        EscapeError::TooShortHexEscape => dcx.emit_err(UnescapeError::TooShortHexEscape(err_span)),
184        EscapeError::InvalidCharInHexEscape | EscapeError::InvalidCharInUnicodeEscape => {
185            let (c, span) = last_char();
186            let is_hex = error == EscapeError::InvalidCharInHexEscape;
187            let ch = escaped_char(c);
188            dcx.emit_err(UnescapeError::InvalidCharInEscape { span, is_hex, ch })
189        }
190        EscapeError::NonAsciiCharInByte => {
191            let (c, span) = last_char();
192            let desc = match mode {
193                Mode::Byte => "byte literal",
194                Mode::ByteStr => "byte string literal",
195                Mode::RawByteStr => "raw byte string literal",
196                _ => {
    ::core::panicking::panic_fmt(format_args!("non-is_byte literal paired with NonAsciiCharInByte"));
}panic!("non-is_byte literal paired with NonAsciiCharInByte"),
197            };
198            let mut err = dcx.struct_span_err(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("non-ASCII character in {0}", desc))
    })format!("non-ASCII character in {desc}"));
199            let postfix = if unicode_width::UnicodeWidthChar::width(c).unwrap_or(1) == 0 {
200                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" but is {0:?}", c))
    })format!(" but is {c:?}")
201            } else {
202                String::new()
203            };
204            err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("must be ASCII{0}", postfix))
    })format!("must be ASCII{postfix}"));
205            // Note: the \\xHH suggestions are not given for raw byte string
206            // literals, because they are araw and so cannot use any escapes.
207            if (c as u32) <= 0xFF && mode != Mode::RawByteStr {
208                err.span_suggestion_verbose(
209                    span,
210                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if you meant to use the unicode code point for {0:?}, use a \\xHH escape",
                c))
    })format!(
211                        "if you meant to use the unicode code point for {c:?}, use a \\xHH escape"
212                    ),
213                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\\x{0:X}", c as u32))
    })format!("\\x{:X}", c as u32),
214                    Applicability::MaybeIncorrect,
215                );
216            } else if mode == Mode::Byte {
217                err.span_label(span, "this multibyte character does not fit into a single byte");
218            } else if mode != Mode::RawByteStr {
219                let mut utf8 = String::new();
220                utf8.push(c);
221                err.span_suggestion_verbose(
222                    span,
223                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if you meant to use the UTF-8 encoding of {0:?}, use \\xHH escapes",
                c))
    })format!("if you meant to use the UTF-8 encoding of {c:?}, use \\xHH escapes"),
224                    utf8.as_bytes()
225                        .iter()
226                        .map(|b: &u8| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\\x{0:X}", *b))
    })format!("\\x{:X}", *b))
227                        .fold("".to_string(), |a, c| a + &c),
228                    Applicability::MaybeIncorrect,
229                );
230            }
231            err.emit_err()
232        }
233        EscapeError::OutOfRangeHexEscape => {
234            let mut err = dcx.struct_span_err(err_span, "out of range hex escape");
235            err.span_label(err_span, "must be a character in the range [\\x00-\\x7f]");
236
237            let escape_str = &lit[range];
238            if lit.len() <= 4
239                && escape_str.len() == 4
240                && escape_str.starts_with("\\x")
241                && let Ok(value) = u8::from_str_radix(&escape_str[2..4], 16)
242                && #[allow(non_exhaustive_omitted_patterns)] match mode {
    Mode::Char | Mode::Str => true,
    _ => false,
}matches!(mode, Mode::Char | Mode::Str)
243            {
244                err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if you want to write a byte literal, use `b\'{0}\'`",
                escape_str))
    })format!("if you want to write a byte literal, use `b'{}'`", escape_str));
245                err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if you want to write a Unicode character, use `\'\\u{{{0:X}}}\'`",
                value))
    })format!(
246                    "if you want to write a Unicode character, use `'\\u{{{:X}}}'`",
247                    value
248                ));
249            }
250
251            err.emit_err()
252        }
253        EscapeError::LeadingUnderscoreUnicodeEscape => {
254            let (c, span) = last_char();
255            dcx.emit_err(UnescapeError::LeadingUnderscoreUnicodeEscape {
256                span,
257                ch: escaped_char(c),
258            })
259        }
260        EscapeError::OverlongUnicodeEscape => {
261            dcx.emit_err(UnescapeError::OverlongUnicodeEscape(err_span))
262        }
263        EscapeError::UnclosedUnicodeEscape => {
264            dcx.emit_err(UnescapeError::UnclosedUnicodeEscape(err_span, err_span.shrink_to_hi()))
265        }
266        EscapeError::NoBraceInUnicodeEscape => {
267            let mut suggestion = "\\u{".to_owned();
268            let mut suggestion_len = 0;
269            let (c, char_span) = last_char();
270            let chars = once(c).chain(lit[range.end..].chars());
271            for c in chars.take(6).take_while(|c| c.is_digit(16)) {
272                suggestion.push(c);
273                suggestion_len += c.len_utf8();
274            }
275
276            let (label, sub) = if suggestion_len > 0 {
277                suggestion.push('}');
278                let hi = char_span.lo() + BytePos(suggestion_len as u32);
279                (None, NoBraceUnicodeSub::Suggestion { span: err_span.with_hi(hi), suggestion })
280            } else {
281                (Some(err_span), NoBraceUnicodeSub::Help)
282            };
283            dcx.emit_err(UnescapeError::NoBraceInUnicodeEscape { span: err_span, label, sub })
284        }
285        EscapeError::UnicodeEscapeInByte => {
286            dcx.emit_err(UnescapeError::UnicodeEscapeInByte(err_span))
287        }
288        EscapeError::EmptyUnicodeEscape => {
289            dcx.emit_err(UnescapeError::EmptyUnicodeEscape(err_span))
290        }
291        EscapeError::ZeroChars => dcx.emit_err(UnescapeError::ZeroChars(err_span)),
292        EscapeError::LoneSlash => dcx.emit_err(UnescapeError::LoneSlash(err_span)),
293        EscapeError::NulInCStr => dcx.emit_err(UnescapeError::NulInCStr { span: err_span }),
294        EscapeError::UnskippedWhitespaceWarning => {
295            let (c, char_span) = last_char();
296            dcx.emit_warn(UnescapeError::UnskippedWhitespace {
297                span: err_span,
298                ch: escaped_char(c),
299                char_span,
300            });
301            return None;
302        }
303        EscapeError::MultipleSkippedLinesWarning => {
304            dcx.emit_warn(UnescapeError::MultipleSkippedLinesWarning(err_span));
305            return None;
306        }
307    })
308}
309
310/// Add additional suggestions for escapes that are supported by C.
311fn foreign_escape_suggestion(
312    diag: &mut Diag<'_>,
313    (escaped_char, escape_span): (&str, Span),
314    err_span: Span,
315) {
316    if escaped_char == "?" {
317        diag.span_suggestion_verbose(
318            err_span,
319            "if you meant to write a literal question mark, don't escape the character",
320            "?",
321            Applicability::MaybeIncorrect,
322        );
323        return;
324    }
325
326    if u8::from_str_radix(escaped_char, 8).is_ok() {
327        diag.help(r"if you meant to write an ASCII control code, use a `\xNN` hex escape");
328        return;
329    }
330
331    let (name, hex) = match escaped_char {
332        "a" => ("an audible bell", "07"),
333        "b" => ("a backspace", "08"),
334        "f" => ("a form feed", "0C"),
335        "v" => ("a vertical tab", "0B"),
336        "e" => ("an ANSI escape sequence", "1B"),
337        _ => return,
338    };
339
340    diag.span_suggestion_verbose(
341        escape_span,
342        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if you meant to write {0}, use a hex escape",
                name))
    })format!("if you meant to write {name}, use a hex escape"),
343        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("x{0}", hex))
    })format!("x{hex}"),
344        Applicability::MaybeIncorrect,
345    );
346}
347
348/// Pushes a character to a message string for error reporting
349pub(crate) fn escaped_char(c: char) -> String {
350    match c {
351        '\u{20}'..='\u{7e}' => {
352            // Don't escape \, ' or " for user-facing messages
353            c.to_string()
354        }
355        _ => c.escape_default().to_string(),
356    }
357}