1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
use std::fmt;
use crate::{
Buffer, ParseError,
err::{perr, ParseErrorKind::*},
escape::unescape,
parse::first_byte_or_empty,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CharLit<B: Buffer> {
raw: B,
value: char,
}
impl<B: Buffer> CharLit<B> {
pub fn parse(input: B) -> Result<Self, ParseError> {
match first_byte_or_empty(&input)? {
b'\'' => Self::parse_impl(input),
_ => Err(perr(0, DoesNotStartWithQuote)),
}
}
pub fn value(&self) -> char {
self.value
}
pub(crate) fn parse_impl(input: B) -> Result<Self, ParseError> {
if input.len() == 1 {
return Err(perr(None, UnterminatedCharLiteral));
}
if *input.as_bytes().last().unwrap() != b'\'' {
return Err(perr(None, UnterminatedCharLiteral));
}
let inner = &input[1..input.len() - 1];
let first = inner.chars().nth(0).ok_or(perr(None, EmptyCharLiteral))?;
let (c, len) = match first {
'\'' => return Err(perr(1, UnescapedSingleQuote)),
'\n' | '\t' | '\r'
=> return Err(perr(1, UnescapedSpecialWhitespace)),
'\\' => unescape::<char>(inner, 1)?,
other => (other, other.len_utf8()),
};
let rest = &inner[len..];
if !rest.is_empty() {
return Err(perr(len + 1..input.len() - 1, OverlongCharLiteral));
}
Ok(Self {
raw: input,
value: c,
})
}
}
impl CharLit<&str> {
pub fn to_owned(&self) -> CharLit<String> {
CharLit {
raw: self.raw.to_owned(),
value: self.value,
}
}
}
impl<B: Buffer> fmt::Display for CharLit<B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad(&self.raw)
}
}
#[cfg(test)]
mod tests;