1use crate::lex::{Cursor, LexError, Scan};
2use crate::lit::Lit;
3use crate::{Span, Spanner, ToTokens, TokenStream, TokenTree};
4
5#[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 ToTokens for LitStr {
81 fn to_tokens(&self, tokens: &mut TokenStream) {
82 tokens.extend_one(TokenTree::Literal(self.clone().into()));
83 }
84}
85
86impl Scan for LitStr {
87 fn scan(cursor: Cursor<'_>) -> Result<(Cursor<'_>, Self), LexError> {
88 let end = scan_cooked(cursor, "\"").or_else(|_| scan_raw(cursor, "r"))?;
89 let len = end.offset() as usize - cursor.offset() as usize;
90 let repr = &cursor.rest()[..len];
91 let span = cursor.span_to(&end);
92
93 match decode_string_body(repr) {
94 Some(value) => Ok((end, Self::from_parts(value, repr, span))),
95 None => cursor.error().into(),
96 }
97 }
98}
99
100impl From<LitStr> for Lit {
101 fn from(value: LitStr) -> Self {
102 Self::Str(value)
103 }
104}
105
106#[cfg(feature = "serde")]
107impl From<LitStr> for String {
108 fn from(value: LitStr) -> Self {
109 value.repr.into_string()
110 }
111}
112
113fn scan_cooked<'a>(c: Cursor<'a>, open: &str) -> Result<Cursor<'a>, LexError> {
114 if !c.starts_with(open) {
115 return c.error().into();
116 }
117
118 let mut c = c.advance_by(open.len());
119
120 loop {
121 match c.first() {
122 None => return c.error().into(),
123 Some('"') => return Ok(c.advance()),
124 Some('\\') => c = escape(c.advance())?,
125 Some(ch) => c = c.advance_by(ch.len_utf8()),
126 }
127 }
128}
129
130fn scan_raw<'a>(start: Cursor<'a>, open: &str) -> Result<Cursor<'a>, LexError> {
131 if !start.starts_with(open) {
132 return start.error().into();
133 }
134
135 let mut cur = start.advance_by(open.len());
136 let mut hashes = 0u32;
137
138 while cur.starts_with("#") {
139 hashes += 1;
140 cur = cur.advance();
141 }
142
143 if !cur.starts_with("\"") {
144 return start.error().into();
145 }
146
147 cur = cur.advance();
148
149 let closing: String = std::iter::once('"')
150 .chain(std::iter::repeat_n('#', hashes as usize))
151 .collect();
152
153 loop {
154 if cur.is_empty() {
155 return start.error().into();
156 }
157
158 if cur.starts_with(&closing) {
159 return Ok(cur.advance_by(closing.len()));
160 }
161
162 if let Some(ch) = cur.first() {
163 cur = cur.advance_by(ch.len_utf8());
164 } else {
165 return start.error().into();
166 }
167 }
168}
169
170fn escape(c: Cursor<'_>) -> Result<Cursor<'_>, LexError> {
171 match c.first() {
172 None => c.error().into(),
173 Some('n' | 'r' | 't' | '\\' | '\'' | '"' | '0') => Ok(c.advance()),
174 Some('x') => {
175 let c = c.advance();
176 let c = hex_digit(c)?;
177 hex_digit(c)
178 }
179 Some('u') => {
180 let c = c.advance();
181
182 if !c.starts_with("{") {
183 return c.error().into();
184 }
185
186 let mut c = c.advance();
187 let mut count = 0;
188
189 loop {
190 match c.first() {
191 Some('}') if count > 0 => return Ok(c.advance()),
192 Some(ch) if ch.is_ascii_hexdigit() && count < 6 => {
193 count += 1;
194 c = c.advance();
195 }
196 _ => return c.error().into(),
197 }
198 }
199 }
200 _ => c.error().into(),
201 }
202}
203
204fn hex_digit(c: Cursor<'_>) -> Result<Cursor<'_>, LexError> {
205 match c.first() {
206 Some(ch) if ch.is_ascii_hexdigit() => Ok(c.advance()),
207 _ => c.error().into(),
208 }
209}
210
211fn decode_string_body(repr: &str) -> Option<String> {
214 if let Some(rest) = repr.strip_prefix('r') {
215 let hashes = rest.bytes().take_while(|b| *b == b'#').count();
216 let open = 1 + hashes;
217 let inner = &rest[open..rest.len() - open];
218 return Some(inner.to_string());
219 }
220
221 let inner = repr.strip_prefix('"')?.strip_suffix('"')?;
222 let mut out = String::new();
223 let mut chars = inner.chars();
224
225 while let Some(c) = chars.next() {
226 if c == '\\' {
227 out.push(decode_escape(&mut chars)?);
228 } else {
229 out.push(c);
230 }
231 }
232
233 Some(out)
234}
235
236fn decode_escape(chars: &mut std::str::Chars<'_>) -> Option<char> {
237 match chars.next()? {
238 'n' => Some('\n'),
239 'r' => Some('\r'),
240 't' => Some('\t'),
241 '\\' => Some('\\'),
242 '\'' => Some('\''),
243 '"' => Some('"'),
244 '0' => Some('\0'),
245 'x' => {
246 let hi = chars.next()?.to_digit(16)?;
247 let lo = chars.next()?.to_digit(16)?;
248 char::from_u32(hi * 16 + lo)
249 }
250 'u' => {
251 if chars.next()? != '{' {
252 return None;
253 }
254 let mut value = 0u32;
255 let mut count = 0;
256 for c in chars.by_ref() {
257 if c == '}' {
258 break;
259 }
260 value = value.checked_mul(16)?.checked_add(c.to_digit(16)?)?;
261 count += 1;
262 if count > 6 {
263 return None;
264 }
265 }
266 char::from_u32(value)
267 }
268 _ => None,
269 }
270}