1 //! Utilities for rendering escape sequence errors as diagnostics.
6 use rustc_errors::{pluralize, Applicability, Handler};
7 use rustc_lexer::unescape::{EscapeError, Mode};
8 use rustc_span::{BytePos, Span};
10 pub(crate) fn emit_unescape_error(
12 // interior part of the literal, without quotes
14 // full span of the literal, including quotes
15 span_with_quotes: Span,
16 // interior span of the literal, without quotes
19 // range of the error inside `lit`
24 "emit_unescape_error: {:?}, {:?}, {:?}, {:?}, {:?}",
25 lit, span_with_quotes, mode, range, error
28 let c = lit[range.clone()].chars().rev().next().unwrap();
29 let span = span.with_lo(span.hi() - BytePos(c.len_utf8() as u32));
33 EscapeError::LoneSurrogateUnicodeEscape => {
35 .struct_span_err(span, "invalid unicode character escape")
36 .span_label(span, "invalid escape")
37 .help("unicode escape must not be a surrogate")
40 EscapeError::OutOfRangeUnicodeEscape => {
42 .struct_span_err(span, "invalid unicode character escape")
43 .span_label(span, "invalid escape")
44 .help("unicode escape must be at most 10FFFF")
47 EscapeError::MoreThanOneChar => {
48 use unicode_normalization::{char::is_combining_mark, UnicodeNormalization};
50 let mut has_help = false;
51 let mut handler = handler.struct_span_err(
53 "character literal may only contain one codepoint",
56 if lit.chars().skip(1).all(|c| is_combining_mark(c)) {
58 lit.chars().skip(1).map(|c| c.escape_default().to_string()).collect::<Vec<_>>();
62 "this `{}` is followed by the combining mark{} `{}`",
63 lit.chars().next().unwrap(),
64 pluralize!(escaped_marks.len()),
65 escaped_marks.join(""),
68 let normalized = lit.nfc().to_string();
69 if normalized.chars().count() == 1 {
71 handler.span_suggestion(
74 "consider using the normalized form `{}` of this character",
75 normalized.chars().next().unwrap().escape_default()
78 Applicability::MachineApplicable,
82 let printable: Vec<char> = lit
85 unicode_width::UnicodeWidthChar::width(x).unwrap_or(0) != 0
90 if let [ch] = printable.as_slice() {
96 "there are non-printing characters, the full sequence is `{}`",
101 handler.span_suggestion(
103 "consider removing the non-printing characters",
105 Applicability::MaybeIncorrect,
111 let (prefix, msg) = if mode.is_bytes() {
112 ("b", "if you meant to write a byte string literal, use double quotes")
114 ("", "if you meant to write a `str` literal, use double quotes")
117 handler.span_suggestion(
120 format!("{}\"{}\"", prefix, lit),
121 Applicability::MachineApplicable,
127 EscapeError::EscapeOnlyChar => {
128 let (c, char_span) = last_char();
130 let msg = if mode.is_bytes() {
131 "byte constant must be escaped"
133 "character constant must be escaped"
136 .struct_span_err(span, &format!("{}: `{}`", msg, escaped_char(c)))
139 "escape the character",
141 Applicability::MachineApplicable,
145 EscapeError::BareCarriageReturn => {
146 let msg = if mode.in_double_quotes() {
147 "bare CR not allowed in string, use `\\r` instead"
149 "character constant must be escaped: `\\r`"
152 .struct_span_err(span, msg)
155 "escape the character",
157 Applicability::MachineApplicable,
161 EscapeError::BareCarriageReturnInRawString => {
162 assert!(mode.in_double_quotes());
163 let msg = "bare CR not allowed in raw string";
164 handler.span_err(span, msg);
166 EscapeError::InvalidEscape => {
167 let (c, span) = last_char();
170 if mode.is_bytes() { "unknown byte escape" } else { "unknown character escape" };
171 let ec = escaped_char(c);
172 let mut diag = handler.struct_span_err(span, &format!("{}: `{}`", label, ec));
173 diag.span_label(span, label);
174 if c == '{' || c == '}' && !mode.is_bytes() {
176 "if used in a formatting string, curly braces are escaped with `{{` and `}}`",
178 } else if c == '\r' {
180 "this is an isolated carriage return; consider checking your editor and \
181 version control settings",
184 if !mode.is_bytes() {
185 diag.span_suggestion(
187 "if you meant to write a literal backslash (perhaps escaping in a regular expression), consider a raw string literal",
188 format!("r\"{}\"", lit),
189 Applicability::MaybeIncorrect,
194 "for more information, visit \
195 <https://static.rust-lang.org/doc/master/reference.html#literals>",
200 EscapeError::TooShortHexEscape => {
201 handler.span_err(span, "numeric character escape is too short");
203 EscapeError::InvalidCharInHexEscape | EscapeError::InvalidCharInUnicodeEscape => {
204 let (c, span) = last_char();
206 let msg = if error == EscapeError::InvalidCharInHexEscape {
207 "invalid character in numeric character escape"
209 "invalid character in unicode escape"
211 let c = escaped_char(c);
214 .struct_span_err(span, &format!("{}: `{}`", msg, c))
215 .span_label(span, msg)
218 EscapeError::NonAsciiCharInByte => {
219 assert!(mode.is_bytes());
220 let (c, span) = last_char();
221 let mut err = handler.struct_span_err(span, "non-ASCII character in byte constant");
222 let postfix = if unicode_width::UnicodeWidthChar::width(c).unwrap_or(1) == 0 {
223 format!(" but is {:?}", c)
227 err.span_label(span, &format!("byte constant must be ASCII{}", postfix));
228 if (c as u32) <= 0xFF {
232 "if you meant to use the unicode code point for {:?}, use a \\xHH escape",
235 format!("\\x{:X}", c as u32),
236 Applicability::MaybeIncorrect,
238 } else if matches!(mode, Mode::Byte) {
239 err.span_label(span, "this multibyte character does not fit into a single byte");
240 } else if matches!(mode, Mode::ByteStr) {
241 let mut utf8 = String::new();
246 "if you meant to use the UTF-8 encoding of {:?}, use \\xHH escapes",
251 .map(|b: &u8| format!("\\x{:X}", *b))
252 .fold("".to_string(), |a, c| a + &c),
253 Applicability::MaybeIncorrect,
258 EscapeError::NonAsciiCharInByteString => {
259 assert!(mode.is_bytes());
260 let (c, span) = last_char();
261 let postfix = if unicode_width::UnicodeWidthChar::width(c).unwrap_or(1) == 0 {
262 format!(" but is {:?}", c)
267 .struct_span_err(span, "raw byte string must be ASCII")
268 .span_label(span, &format!("must be ASCII{}", postfix))
271 EscapeError::OutOfRangeHexEscape => {
273 .struct_span_err(span, "out of range hex escape")
274 .span_label(span, "must be a character in the range [\\x00-\\x7f]")
277 EscapeError::LeadingUnderscoreUnicodeEscape => {
278 let (c, span) = last_char();
279 let msg = "invalid start of unicode escape";
281 .struct_span_err(span, &format!("{}: `{}`", msg, c))
282 .span_label(span, msg)
285 EscapeError::OverlongUnicodeEscape => {
287 .struct_span_err(span, "overlong unicode escape")
288 .span_label(span, "must have at most 6 hex digits")
291 EscapeError::UnclosedUnicodeEscape => {
293 .struct_span_err(span, "unterminated unicode escape")
294 .span_label(span, "missing a closing `}`")
295 .span_suggestion_verbose(
297 "terminate the unicode escape",
299 Applicability::MaybeIncorrect,
303 EscapeError::NoBraceInUnicodeEscape => {
304 let msg = "incorrect unicode escape sequence";
305 let mut diag = handler.struct_span_err(span, msg);
307 let mut suggestion = "\\u{".to_owned();
308 let mut suggestion_len = 0;
309 let (c, char_span) = last_char();
310 let chars = once(c).chain(lit[range.end..].chars());
311 for c in chars.take(6).take_while(|c| c.is_digit(16)) {
313 suggestion_len += c.len_utf8();
316 if suggestion_len > 0 {
317 suggestion.push('}');
318 let hi = char_span.lo() + BytePos(suggestion_len as u32);
319 diag.span_suggestion(
321 "format of unicode escape sequences uses braces",
323 Applicability::MaybeIncorrect,
326 diag.span_label(span, msg);
327 diag.help("format of unicode escape sequences is `\\u{...}`");
332 EscapeError::UnicodeEscapeInByte => {
333 let msg = "unicode escape in byte string";
335 .struct_span_err(span, msg)
336 .span_label(span, msg)
337 .help("unicode escape sequences cannot be used as a byte or in a byte string")
340 EscapeError::EmptyUnicodeEscape => {
342 .struct_span_err(span, "empty unicode escape")
343 .span_label(span, "this escape must have at least 1 hex digit")
346 EscapeError::ZeroChars => {
347 let msg = "empty character literal";
348 handler.struct_span_err(span, msg).span_label(span, msg).emit();
350 EscapeError::LoneSlash => {
351 let msg = "invalid trailing slash in literal";
352 handler.struct_span_err(span, msg).span_label(span, msg).emit();
354 EscapeError::UnskippedWhitespaceWarning => {
355 let (c, char_span) = last_char();
357 format!("non-ASCII whitespace symbol '{}' is not skipped", c.escape_unicode());
358 handler.struct_span_warn(span, &msg).span_label(char_span, &msg).emit();
360 EscapeError::MultipleSkippedLinesWarning => {
361 let msg = "multiple lines skipped by escaped newline";
362 let bottom_msg = "skipping everything up to and including this point";
363 handler.struct_span_warn(span, msg).span_label(span, bottom_msg).emit();
368 /// Pushes a character to a message string for error reporting
369 pub(crate) fn escaped_char(c: char) -> String {
371 '\u{20}'..='\u{7e}' => {
372 // Don't escape \, ' or " for user-facing messages
375 _ => c.escape_default().to_string(),