solar_parse/lexer/unescape/
errors.rs1use solar_interface::{BytePos, Span, diagnostics::DiagCtxt};
2use std::ops::Range;
3
4#[derive(Debug, PartialEq, Eq)]
6pub enum EscapeError {
7 LoneSlash,
9 InvalidEscape,
11 BareCarriageReturn,
13
14 HexEscapeTooShort,
16 InvalidHexEscape,
18
19 UnicodeEscapeTooShort,
21 InvalidUnicodeEscape,
23
24 StrNewline,
26 StrNonAsciiChar,
28
29 HexNotHexDigit,
31 HexBadUnderscore,
33 HexOddDigits,
35 HexPrefix,
37}
38
39impl EscapeError {
40 fn msg(&self) -> &'static str {
41 match self {
42 Self::LoneSlash => "invalid trailing slash in literal",
43 Self::InvalidEscape => "unknown character escape",
44 Self::BareCarriageReturn => "bare CR not allowed in string, use `\\r` instead",
45 Self::HexEscapeTooShort => "hex escape must be followed by 2 hex digits",
46 Self::InvalidHexEscape => "invalid character in hex escape",
47 Self::UnicodeEscapeTooShort => "unicode escape must be followed by 4 hex digits",
48 Self::InvalidUnicodeEscape => "invalid character in unicode escape",
49 Self::StrNewline => "unescaped newline",
50 Self::StrNonAsciiChar => {
51 "unicode characters are not allowed in string literals; use a `unicode\"...\"` literal instead"
52 }
53 Self::HexNotHexDigit => "invalid hex digit",
54 Self::HexBadUnderscore => "invalid underscore in hex literal",
55 Self::HexOddDigits => "odd number of hex nibbles",
56 Self::HexPrefix => "hex prefix is not allowed",
57 }
58 }
59}
60
61pub(crate) fn emit_unescape_error(
62 dcx: &DiagCtxt,
63 lit: &str,
65 err_span: Span,
67 range: Range<usize>,
69 error: EscapeError,
70) {
71 let last_char = || {
72 let c = lit[range.clone()].chars().next_back().unwrap();
73 let span = err_span.with_lo(err_span.hi() - BytePos(c.len_utf8() as u32));
74 (c, span)
75 };
76 let mut diag = dcx.err(error.msg()).span(err_span);
77 if matches!(
78 error,
79 EscapeError::InvalidEscape
80 | EscapeError::InvalidHexEscape
81 | EscapeError::InvalidUnicodeEscape
82 ) {
83 diag = diag.span(last_char().1);
84 }
85 diag.emit();
86}