Skip to main content

moxy_token/lit/
byte.rs

1use crate::lex::{Cursor, LexError, Scan};
2use crate::lit::Lit;
3use crate::parser::{ParseError, ParseStream};
4use crate::{Parse, Span, Spanner};
5
6#[derive(Debug, Clone)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize), serde(into = "String"))]
8pub struct LitByte {
9    value: u8,
10    repr: Box<str>,
11    span: Span,
12}
13
14impl LitByte {
15    #[inline]
16    pub(crate) fn from_parts(value: u8, repr: &str, span: Span) -> Self {
17        Self {
18            value,
19            repr: repr.into(),
20            span,
21        }
22    }
23
24    #[inline]
25    pub fn value(&self) -> u8 {
26        self.value
27    }
28
29    #[inline]
30    pub fn repr(&self) -> &str {
31        &self.repr
32    }
33
34    #[inline]
35    pub fn span(&self) -> Span {
36        self.span
37    }
38
39    #[inline]
40    pub fn set_span(&mut self, span: Span) {
41        self.span = span;
42    }
43}
44
45impl PartialEq for LitByte {
46    fn eq(&self, other: &Self) -> bool {
47        self.value == other.value
48    }
49}
50
51impl Eq for LitByte {}
52
53impl std::hash::Hash for LitByte {
54    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
55        self.value.hash(state);
56    }
57}
58
59impl std::fmt::Display for LitByte {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        f.write_str(&self.repr)
62    }
63}
64
65impl Spanner for LitByte {
66    fn span(&self) -> Span {
67        self.span
68    }
69}
70
71impl Scan for LitByte {
72    fn scan(cursor: Cursor<'_>) -> Result<(Cursor<'_>, Self), LexError> {
73        let end = scan(cursor, "b'")?;
74        let len = end.offset() as usize - cursor.offset() as usize;
75        let repr = &cursor.rest()[..len];
76        let span = cursor.span_to(&end);
77        let inner = repr.strip_prefix("b'").and_then(|r| r.strip_suffix('\''));
78
79        match inner.and_then(decode_one_char) {
80            Some(value) => Ok((end, Self::from_parts(value as u8, repr, span))),
81            _ => cursor.error().into(),
82        }
83    }
84}
85
86impl Parse for LitByte {
87    fn parse(stream: &mut ParseStream) -> Result<Self, ParseError> {
88        let at = stream.span();
89
90        match stream.parse::<Lit>()? {
91            Lit::Byte(v) => Ok(v),
92            _ => Err(LexError::new(at).message("expected byte literal").into()),
93        }
94    }
95}
96
97impl From<LitByte> for Lit {
98    fn from(value: LitByte) -> Self {
99        Self::Byte(value)
100    }
101}
102
103#[cfg(feature = "serde")]
104impl From<LitByte> for String {
105    fn from(value: LitByte) -> Self {
106        value.repr.into_string()
107    }
108}
109
110fn scan<'a>(c: Cursor<'a>, open: &str) -> Result<Cursor<'a>, LexError> {
111    if !c.starts_with(open) {
112        return c.error().into();
113    }
114
115    let start = c;
116    let c = c.advance(open.len());
117    let c = match c.first() {
118        None | Some('\'') => return start.error().into(),
119        Some('\\') => escape(c.advance(1))?,
120        Some(ch) => c.advance(ch.len_utf8()),
121    };
122
123    if !c.starts_with("'") {
124        return start.error().into();
125    }
126
127    Ok(c.advance(1))
128}
129
130fn escape(c: Cursor<'_>) -> Result<Cursor<'_>, LexError> {
131    match c.first() {
132        None => c.error().into(),
133        Some('n' | 'r' | 't' | '\\' | '\'' | '"' | '0') => Ok(c.advance(1)),
134        Some('x') => {
135            let c = c.advance(1);
136            let c = hex_digit(c)?;
137            hex_digit(c)
138        }
139        Some('u') => {
140            let c = c.advance(1);
141
142            if !c.starts_with("{") {
143                return c.error().into();
144            }
145
146            let mut c = c.advance(1);
147            let mut count = 0;
148
149            loop {
150                match c.first() {
151                    Some('}') if count > 0 => return Ok(c.advance(1)),
152                    Some(ch) if ch.is_ascii_hexdigit() && count < 6 => {
153                        count += 1;
154                        c = c.advance(1);
155                    }
156                    _ => return c.error().into(),
157                }
158            }
159        }
160        _ => c.error().into(),
161    }
162}
163
164fn hex_digit(c: Cursor<'_>) -> Result<Cursor<'_>, LexError> {
165    match c.first() {
166        Some(ch) if ch.is_ascii_hexdigit() => Ok(c.advance(1)),
167        _ => c.error().into(),
168    }
169}
170
171/// Decode a single (possibly escaped) char from a char-literal inner body.
172fn decode_one_char(inner: &str) -> Option<char> {
173    let mut chars = inner.chars();
174    let value = match chars.next()? {
175        '\\' => decode_escape(&mut chars)?,
176        c => c,
177    };
178
179    if chars.next().is_some() {
180        return None;
181    }
182
183    Some(value)
184}
185
186fn decode_escape(chars: &mut std::str::Chars<'_>) -> Option<char> {
187    match chars.next()? {
188        'n' => Some('\n'),
189        'r' => Some('\r'),
190        't' => Some('\t'),
191        '\\' => Some('\\'),
192        '\'' => Some('\''),
193        '"' => Some('"'),
194        '0' => Some('\0'),
195        'x' => {
196            let hi = chars.next()?.to_digit(16)?;
197            let lo = chars.next()?.to_digit(16)?;
198            char::from_u32(hi * 16 + lo)
199        }
200        'u' => {
201            if chars.next()? != '{' {
202                return None;
203            }
204
205            let mut value = 0u32;
206            let mut count = 0;
207
208            for c in chars.by_ref() {
209                if c == '}' {
210                    break;
211                }
212
213                value = value.checked_mul(16)?.checked_add(c.to_digit(16)?)?;
214                count += 1;
215
216                if count > 6 {
217                    return None;
218                }
219            }
220
221            char::from_u32(value)
222        }
223        _ => None,
224    }
225}