Skip to main content

moxy_token/lit/
str.rs

1use crate::lex::{Cursor, LexError, Scan};
2use crate::lit::Lit;
3use crate::{Span, Spanner};
4
5/// A parsed Rust str literal token.
6#[derive(Debug, Clone)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize), serde(into = "String"))]
8pub struct LitStr {
9    value: String,
10    repr: Box<str>,
11    span: Span,
12}
13
14impl LitStr {
15    #[inline]
16    pub fn new(value: &str, span: Span) -> Self {
17        Self {
18            value: value.to_string(),
19            repr: format!("{value:?}").into_boxed_str(),
20            span,
21        }
22    }
23
24    #[inline]
25    pub(crate) fn from_parts(value: String, repr: &str, span: Span) -> Self {
26        Self {
27            value,
28            repr: repr.into(),
29            span,
30        }
31    }
32
33    #[inline]
34    pub fn value(&self) -> &str {
35        &self.value
36    }
37
38    #[inline]
39    pub fn repr(&self) -> &str {
40        &self.repr
41    }
42
43    #[inline]
44    pub fn span(&self) -> Span {
45        self.span
46    }
47
48    #[inline]
49    pub fn set_span(&mut self, span: Span) {
50        self.span = span;
51    }
52}
53
54impl PartialEq for LitStr {
55    fn eq(&self, other: &Self) -> bool {
56        self.value == other.value
57    }
58}
59
60impl Eq for LitStr {}
61
62impl std::hash::Hash for LitStr {
63    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
64        self.value.hash(state);
65    }
66}
67
68impl std::fmt::Display for LitStr {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        f.write_str(&self.repr)
71    }
72}
73
74impl Spanner for LitStr {
75    fn span(&self) -> Span {
76        self.span
77    }
78}
79
80impl Scan for LitStr {
81    fn scan(cursor: Cursor<'_>) -> Result<(Cursor<'_>, Self), LexError> {
82        let end = scan_cooked(cursor, "\"").or_else(|_| scan_raw(cursor, "r"))?;
83        let len = end.offset() as usize - cursor.offset() as usize;
84        let repr = &cursor.rest()[..len];
85        let span = cursor.span_to(&end);
86
87        match decode_string_body(repr) {
88            Some(value) => Ok((end, Self::from_parts(value, repr, span))),
89            None => cursor.error().into(),
90        }
91    }
92}
93
94impl From<LitStr> for Lit {
95    fn from(value: LitStr) -> Self {
96        Self::Str(value)
97    }
98}
99
100#[cfg(feature = "serde")]
101impl From<LitStr> for String {
102    fn from(value: LitStr) -> Self {
103        value.repr.into_string()
104    }
105}
106
107fn scan_cooked<'a>(c: Cursor<'a>, open: &str) -> Result<Cursor<'a>, LexError> {
108    if !c.starts_with(open) {
109        return c.error().into();
110    }
111
112    let mut c = c.advance_by(open.len());
113
114    loop {
115        match c.first() {
116            None => return c.error().into(),
117            Some('"') => return Ok(c.advance()),
118            Some('\\') => c = escape(c.advance())?,
119            Some(ch) => c = c.advance_by(ch.len_utf8()),
120        }
121    }
122}
123
124fn scan_raw<'a>(start: Cursor<'a>, open: &str) -> Result<Cursor<'a>, LexError> {
125    if !start.starts_with(open) {
126        return start.error().into();
127    }
128
129    let mut cur = start.advance_by(open.len());
130    let mut hashes = 0u32;
131
132    while cur.starts_with("#") {
133        hashes += 1;
134        cur = cur.advance();
135    }
136
137    if !cur.starts_with("\"") {
138        return start.error().into();
139    }
140
141    cur = cur.advance();
142
143    let closing: String = std::iter::once('"')
144        .chain(std::iter::repeat_n('#', hashes as usize))
145        .collect();
146
147    loop {
148        if cur.is_empty() {
149            return start.error().into();
150        }
151
152        if cur.starts_with(&closing) {
153            return Ok(cur.advance_by(closing.len()));
154        }
155
156        if let Some(ch) = cur.first() {
157            cur = cur.advance_by(ch.len_utf8());
158        } else {
159            return start.error().into();
160        }
161    }
162}
163
164fn escape(c: Cursor<'_>) -> Result<Cursor<'_>, LexError> {
165    match c.first() {
166        None => c.error().into(),
167        Some('n' | 'r' | 't' | '\\' | '\'' | '"' | '0') => Ok(c.advance()),
168        Some('x') => {
169            let c = c.advance();
170            let c = hex_digit(c)?;
171            hex_digit(c)
172        }
173        Some('u') => {
174            let c = c.advance();
175
176            if !c.starts_with("{") {
177                return c.error().into();
178            }
179
180            let mut c = c.advance();
181            let mut count = 0;
182
183            loop {
184                match c.first() {
185                    Some('}') if count > 0 => return Ok(c.advance()),
186                    Some(ch) if ch.is_ascii_hexdigit() && count < 6 => {
187                        count += 1;
188                        c = c.advance();
189                    }
190                    _ => return c.error().into(),
191                }
192            }
193        }
194        _ => c.error().into(),
195    }
196}
197
198fn hex_digit(c: Cursor<'_>) -> Result<Cursor<'_>, LexError> {
199    match c.first() {
200        Some(ch) if ch.is_ascii_hexdigit() => Ok(c.advance()),
201        _ => c.error().into(),
202    }
203}
204
205/// Decode the body of a string repr (after any `b`/`c` prefix the caller strips).
206/// Handles cooked (`"…"`) and raw (`r"…"` / `r#"…"#`) forms.
207fn decode_string_body(repr: &str) -> Option<String> {
208    if let Some(rest) = repr.strip_prefix('r') {
209        let hashes = rest.bytes().take_while(|b| *b == b'#').count();
210        let open = 1 + hashes;
211        let inner = &rest[open..rest.len() - open];
212        return Some(inner.to_string());
213    }
214
215    let inner = repr.strip_prefix('"')?.strip_suffix('"')?;
216    let mut out = String::new();
217    let mut chars = inner.chars();
218
219    while let Some(c) = chars.next() {
220        if c == '\\' {
221            out.push(decode_escape(&mut chars)?);
222        } else {
223            out.push(c);
224        }
225    }
226
227    Some(out)
228}
229
230fn decode_escape(chars: &mut std::str::Chars<'_>) -> Option<char> {
231    match chars.next()? {
232        'n' => Some('\n'),
233        'r' => Some('\r'),
234        't' => Some('\t'),
235        '\\' => Some('\\'),
236        '\'' => Some('\''),
237        '"' => Some('"'),
238        '0' => Some('\0'),
239        'x' => {
240            let hi = chars.next()?.to_digit(16)?;
241            let lo = chars.next()?.to_digit(16)?;
242            char::from_u32(hi * 16 + lo)
243        }
244        'u' => {
245            if chars.next()? != '{' {
246                return None;
247            }
248            let mut value = 0u32;
249            let mut count = 0;
250            for c in chars.by_ref() {
251                if c == '}' {
252                    break;
253                }
254                value = value.checked_mul(16)?.checked_add(c.to_digit(16)?)?;
255                count += 1;
256                if count > 6 {
257                    return None;
258                }
259            }
260            char::from_u32(value)
261        }
262        _ => None,
263    }
264}