1use std::ops::Range;
4use std::{borrow::Cow, num::ParseIntError};
5
6use parser::SyntaxKind;
7use rustc_literal_escaper::{
8 EscapeError, MixedUnit, unescape_byte, unescape_byte_str, unescape_c_str, unescape_char,
9 unescape_str,
10};
11use stdx::always;
12
13use crate::{
14 SyntaxToken, TextRange, TextSize,
15 ast::{self, AstToken, AttrKind},
16};
17
18impl ast::Comment {
19 pub fn shape(&self) -> CommentShape {
20 CommentShape::from_text(self.text())
21 }
22
23 pub fn text_without_markers(&self) -> &str {
25 let text = self.text();
26 let shape = CommentShape::from_text(text);
27 let text = &text[2..];
28 match shape {
29 CommentShape::Block => text.strip_suffix("*/").unwrap_or(text),
30 CommentShape::Line => text,
31 }
32 }
33}
34
35#[derive(Debug, PartialEq, Eq, Clone, Copy)]
36pub struct CommentKind {
37 pub shape: CommentShape,
38 pub doc: Option<AttrKind>,
39}
40
41impl CommentKind {
42 pub fn prefix(&self) -> &'static str {
43 match (self.shape, self.doc) {
44 (CommentShape::Line, None) => "//",
45 (CommentShape::Line, Some(AttrKind::Inner)) => "//!",
46 (CommentShape::Line, Some(AttrKind::Outer)) => "///",
47 (CommentShape::Block, None) => "/*",
48 (CommentShape::Block, Some(AttrKind::Inner)) => "/*!",
49 (CommentShape::Block, Some(AttrKind::Outer)) => "/**",
50 }
51 }
52}
53
54#[derive(Debug, PartialEq, Eq, Clone, Copy)]
55pub enum CommentShape {
56 Line,
57 Block,
58}
59
60impl CommentShape {
61 #[inline]
62 pub fn from_text(text: &str) -> CommentShape {
63 if text.starts_with("/*") { CommentShape::Block } else { CommentShape::Line }
64 }
65
66 pub fn is_line(self) -> bool {
67 self == CommentShape::Line
68 }
69
70 pub fn is_block(self) -> bool {
71 self == CommentShape::Block
72 }
73}
74
75#[derive(Debug, Clone, PartialEq, Eq, Hash)]
76pub struct AnyComment {
77 syntax: SyntaxToken,
78}
79
80impl AstToken for AnyComment {
81 fn can_cast(kind: SyntaxKind) -> bool
82 where
83 Self: Sized,
84 {
85 matches!(
86 kind,
87 SyntaxKind::COMMENT | SyntaxKind::INNER_DOC_COMMENT | SyntaxKind::OUTER_DOC_COMMENT
88 )
89 }
90
91 fn cast(syntax: SyntaxToken) -> Option<Self>
92 where
93 Self: Sized,
94 {
95 if Self::can_cast(syntax.kind()) { Some(Self { syntax }) } else { None }
96 }
97
98 fn syntax(&self) -> &SyntaxToken {
99 &self.syntax
100 }
101}
102
103impl AnyComment {
104 pub fn shape(&self) -> CommentShape {
105 CommentShape::from_text(self.text_with_markers())
106 }
107
108 pub fn doc_kind(&self) -> Option<AttrKind> {
109 match self.syntax.kind() {
110 SyntaxKind::COMMENT => None,
111 SyntaxKind::INNER_DOC_COMMENT => Some(AttrKind::Inner),
112 SyntaxKind::OUTER_DOC_COMMENT => Some(AttrKind::Outer),
113 _ => unreachable!(),
114 }
115 }
116
117 pub fn kind(&self) -> CommentKind {
118 CommentKind { shape: self.shape(), doc: self.doc_kind() }
119 }
120
121 pub fn prefix(&self) -> &'static str {
122 self.kind().prefix()
123 }
124
125 pub fn is_inner(&self) -> bool {
126 self.doc_kind() == Some(AttrKind::Inner)
127 }
128
129 pub fn is_outer(&self) -> bool {
130 self.doc_kind() == Some(AttrKind::Outer)
131 }
132
133 pub fn text_with_markers(&self) -> &str {
135 self.syntax.text()
136 }
137
138 pub fn text(&self) -> &str {
140 let shape = self.shape();
141 let prefix_len = if self.doc_kind().is_some() { 3 } else { 2 };
142 let text = &self.text_with_markers()[prefix_len..];
143 if shape == CommentShape::Block {
144 text.strip_suffix("*/").unwrap_or(text)
146 } else {
147 text
148 }
149 }
150}
151
152impl ast::Whitespace {
153 pub fn spans_multiple_lines(&self) -> bool {
154 let text = self.text();
155 text.find('\n').is_some_and(|idx| text[idx + 1..].contains('\n'))
156 }
157}
158
159#[derive(Debug)]
160pub struct QuoteOffsets {
161 pub quotes: (TextRange, TextRange),
162 pub contents: TextRange,
163}
164
165impl QuoteOffsets {
166 fn new(literal: &str) -> Option<QuoteOffsets> {
167 let left_quote = literal.find('"')?;
168 let right_quote = literal.rfind('"')?;
169 if left_quote == right_quote {
170 return None;
172 }
173
174 let start = TextSize::from(0);
175 let left_quote = TextSize::try_from(left_quote).unwrap() + TextSize::of('"');
176 let right_quote = TextSize::try_from(right_quote).unwrap();
177 let end = TextSize::of(literal);
178
179 let res = QuoteOffsets {
180 quotes: (TextRange::new(start, left_quote), TextRange::new(right_quote, end)),
181 contents: TextRange::new(left_quote, right_quote),
182 };
183 Some(res)
184 }
185}
186
187pub trait IsString: AstToken {
188 fn raw_prefix(&self) -> &'static str;
189 fn unescape(&self, s: &str, callback: impl FnMut(Range<usize>, Result<char, EscapeError>));
190 fn is_raw(&self) -> bool {
191 self.text().starts_with(self.raw_prefix())
192 }
193 fn quote_offsets(&self) -> Option<QuoteOffsets> {
194 let text = self.text();
195 let offsets = QuoteOffsets::new(text)?;
196 let o = self.syntax().text_range().start();
197 let offsets = QuoteOffsets {
198 quotes: (offsets.quotes.0 + o, offsets.quotes.1 + o),
199 contents: offsets.contents + o,
200 };
201 Some(offsets)
202 }
203 fn text_range_between_quotes(&self) -> Option<TextRange> {
204 self.quote_offsets().map(|it| it.contents)
205 }
206 fn text_without_quotes(&self) -> &str {
207 let text = self.text();
208 let Some(offsets) = self.text_range_between_quotes() else { return text };
209 &text[offsets - self.syntax().text_range().start()]
210 }
211 fn open_quote_text_range(&self) -> Option<TextRange> {
212 self.quote_offsets().map(|it| it.quotes.0)
213 }
214 fn close_quote_text_range(&self) -> Option<TextRange> {
215 self.quote_offsets().map(|it| it.quotes.1)
216 }
217 fn escaped_char_ranges(&self, cb: &mut dyn FnMut(TextRange, Result<char, EscapeError>)) {
218 let Some(text_range_no_quotes) = self.text_range_between_quotes() else { return };
219
220 let start = self.syntax().text_range().start();
221 let text = &self.text()[text_range_no_quotes - start];
222 let offset = text_range_no_quotes.start() - start;
223
224 if self.is_raw() {
225 let mut pos = offset;
226 for c in text.chars() {
227 let len = TextSize::of(c);
228 cb(TextRange::at(pos, len), Ok(c));
229 pos += len;
230 }
231 return;
232 }
233
234 self.unescape(text, &mut |range: Range<usize>, unescaped_char| {
235 if let Some((s, e)) = range.start.try_into().ok().zip(range.end.try_into().ok()) {
236 cb(TextRange::new(s, e) + offset, unescaped_char);
237 }
238 });
239 }
240 fn map_range_up(&self, range: TextRange) -> Option<TextRange> {
241 let contents_range = self.text_range_between_quotes()?;
242 if always!(TextRange::up_to(contents_range.len()).contains_range(range)) {
243 Some(range + contents_range.start())
244 } else {
245 None
246 }
247 }
248 fn map_offset_down(&self, offset: TextSize) -> Option<TextSize> {
249 let contents_range = self.text_range_between_quotes()?;
250 offset.checked_sub(contents_range.start())
251 }
252}
253
254impl IsString for ast::String {
255 fn raw_prefix(&self) -> &'static str {
256 "r"
257 }
258 fn unescape(&self, s: &str, cb: impl FnMut(Range<usize>, Result<char, EscapeError>)) {
259 unescape_str(s, cb)
260 }
261}
262
263impl ast::String {
264 pub fn value(&self) -> Result<Cow<'_, str>, EscapeError> {
265 let text = self.text();
266 let text_range = self.text_range_between_quotes().ok_or(EscapeError::LoneSlash)?;
267 let text = &text[text_range - self.syntax().text_range().start()];
268 if self.is_raw() {
269 return Ok(Cow::Borrowed(text));
270 }
271
272 let mut buf = String::new();
273 let mut prev_end = 0;
274 let mut has_error = None;
275 unescape_str(text, |char_range, unescaped_char| {
276 match (unescaped_char, buf.capacity() == 0) {
277 (Ok(c), false) => buf.push(c),
278 (Ok(_), true) if char_range.len() == 1 && char_range.start == prev_end => {
279 prev_end = char_range.end
280 }
281 (Ok(c), true) => {
282 buf.reserve_exact(text.len());
283 buf.push_str(&text[..prev_end]);
284 buf.push(c);
285 }
286 (Err(e), _) => has_error = Some(e),
287 }
288 });
289
290 match (has_error, buf.capacity() == 0) {
291 (Some(e), _) => Err(e),
292 (None, true) => Ok(Cow::Borrowed(text)),
293 (None, false) => Ok(Cow::Owned(buf)),
294 }
295 }
296}
297
298impl IsString for ast::ByteString {
299 fn raw_prefix(&self) -> &'static str {
300 "br"
301 }
302 fn unescape(&self, s: &str, mut callback: impl FnMut(Range<usize>, Result<char, EscapeError>)) {
303 unescape_byte_str(s, |range, res| callback(range, res.map(char::from)))
304 }
305}
306
307impl ast::ByteString {
308 pub fn value(&self) -> Result<Cow<'_, [u8]>, EscapeError> {
309 let text = self.text();
310 let text_range = self.text_range_between_quotes().ok_or(EscapeError::LoneSlash)?;
311 let text = &text[text_range - self.syntax().text_range().start()];
312 if self.is_raw() {
313 return Ok(Cow::Borrowed(text.as_bytes()));
314 }
315
316 let mut buf: Vec<u8> = Vec::new();
317 let mut prev_end = 0;
318 let mut has_error = None;
319 unescape_byte_str(text, |char_range, unescaped_byte| {
320 match (unescaped_byte, buf.capacity() == 0) {
321 (Ok(b), false) => buf.push(b),
322 (Ok(_), true) if char_range.len() == 1 && char_range.start == prev_end => {
323 prev_end = char_range.end
324 }
325 (Ok(b), true) => {
326 buf.reserve_exact(text.len());
327 buf.extend_from_slice(&text.as_bytes()[..prev_end]);
328 buf.push(b);
329 }
330 (Err(e), _) => has_error = Some(e),
331 }
332 });
333
334 match (has_error, buf.capacity() == 0) {
335 (Some(e), _) => Err(e),
336 (None, true) => Ok(Cow::Borrowed(&text.as_bytes()[..prev_end])),
337 (None, false) => Ok(Cow::Owned(buf)),
338 }
339 }
340}
341
342impl IsString for ast::CString {
343 fn raw_prefix(&self) -> &'static str {
344 "cr"
345 }
346 fn unescape(&self, s: &str, mut callback: impl FnMut(Range<usize>, Result<char, EscapeError>)) {
349 unescape_c_str(s, |range, _res| callback(range, Ok('_')))
350 }
351}
352
353impl ast::CString {
354 pub fn value(&self) -> Result<Cow<'_, [u8]>, EscapeError> {
355 let text = self.text();
356 let text_range = self.text_range_between_quotes().ok_or(EscapeError::LoneSlash)?;
357 let text = &text[text_range - self.syntax().text_range().start()];
358 if self.is_raw() {
359 return Ok(Cow::Borrowed(text.as_bytes()));
360 }
361
362 let mut buf = Vec::new();
363 let mut prev_end = 0;
364 let mut has_error = None;
365 let extend_unit = |buf: &mut Vec<u8>, unit: MixedUnit| match unit {
366 MixedUnit::Char(c) => buf.extend(c.get().encode_utf8(&mut [0; 4]).as_bytes()),
367 MixedUnit::HighByte(b) => buf.push(b.get()),
368 };
369 unescape_c_str(text, |char_range, unescaped| match (unescaped, buf.capacity() == 0) {
370 (Ok(u), false) => extend_unit(&mut buf, u),
371 (Ok(_), true) if char_range.len() == 1 && char_range.start == prev_end => {
372 prev_end = char_range.end
373 }
374 (Ok(u), true) => {
375 buf.reserve_exact(text.len());
376 buf.extend(&text.as_bytes()[..prev_end]);
377 extend_unit(&mut buf, u);
378 }
379 (Err(e), _) => has_error = Some(e),
380 });
381
382 match (has_error, buf.capacity() == 0) {
383 (Some(e), _) => Err(e),
384 (None, true) => Ok(Cow::Borrowed(text.as_bytes())),
385 (None, false) => Ok(Cow::Owned(buf)),
386 }
387 }
388}
389
390impl ast::IntNumber {
391 pub fn radix(&self) -> Radix {
392 match self.text().get(..2).unwrap_or_default() {
393 "0b" => Radix::Binary,
394 "0o" => Radix::Octal,
395 "0x" => Radix::Hexadecimal,
396 _ => Radix::Decimal,
397 }
398 }
399
400 pub fn split_into_parts(&self) -> (&str, &str, &str) {
401 let radix = self.radix();
402 let (prefix, mut text) = self.text().split_at(radix.prefix_len());
403
404 let is_suffix_start: fn(&(usize, char)) -> bool = match radix {
405 Radix::Hexadecimal => |(_, c)| matches!(c, 'g'..='z' | 'G'..='Z'),
406 _ => |(_, c)| c.is_ascii_alphabetic(),
407 };
408
409 let mut suffix = "";
410 if let Some((suffix_start, _)) = text.char_indices().find(is_suffix_start) {
411 let (text2, suffix2) = text.split_at(suffix_start);
412 text = text2;
413 suffix = suffix2;
414 };
415
416 (prefix, text, suffix)
417 }
418
419 pub fn value(&self) -> Result<u128, ParseIntError> {
420 let (_, text, _) = self.split_into_parts();
421 u128::from_str_radix(&text.replace('_', ""), self.radix() as u32)
422 }
423
424 pub fn suffix(&self) -> Option<&str> {
425 let (_, _, suffix) = self.split_into_parts();
426 if suffix.is_empty() { None } else { Some(suffix) }
427 }
428
429 pub fn value_string(&self) -> String {
430 let (_, text, _) = self.split_into_parts();
431 text.replace('_', "")
432 }
433}
434
435impl ast::FloatNumber {
436 pub fn split_into_parts(&self) -> (&str, &str) {
437 let text = self.text();
438 let mut float_text = self.text();
439 let mut suffix = "";
440 let mut indices = text.char_indices();
441 if let Some((mut suffix_start, c)) = indices.by_ref().find(|(_, c)| c.is_ascii_alphabetic())
442 {
443 if c == 'e' || c == 'E' {
444 if let Some(suffix_start_tuple) = indices.find(|(_, c)| c.is_ascii_alphabetic()) {
445 suffix_start = suffix_start_tuple.0;
446
447 float_text = &text[..suffix_start];
448 suffix = &text[suffix_start..];
449 }
450 } else {
451 float_text = &text[..suffix_start];
452 suffix = &text[suffix_start..];
453 }
454 }
455
456 (float_text, suffix)
457 }
458
459 pub fn suffix(&self) -> Option<&str> {
460 let (_, suffix) = self.split_into_parts();
461 if suffix.is_empty() { None } else { Some(suffix) }
462 }
463
464 pub fn value_string(&self) -> String {
465 let (text, _) = self.split_into_parts();
466 text.replace('_', "")
467 }
468}
469
470#[derive(Debug, PartialEq, Eq, Copy, Clone)]
471pub enum Radix {
472 Binary = 2,
473 Octal = 8,
474 Decimal = 10,
475 Hexadecimal = 16,
476}
477
478impl Radix {
479 pub const ALL: &'static [Radix] =
480 &[Radix::Binary, Radix::Octal, Radix::Decimal, Radix::Hexadecimal];
481
482 const fn prefix_len(self) -> usize {
483 match self {
484 Self::Decimal => 0,
485 _ => 2,
486 }
487 }
488}
489
490impl ast::Char {
491 pub fn value(&self) -> Result<char, EscapeError> {
492 let mut text = self.text();
493 if text.starts_with('\'') {
494 text = &text[1..];
495 } else {
496 return Err(EscapeError::ZeroChars);
497 }
498 if text.ends_with('\'') {
499 text = &text[0..text.len() - 1];
500 }
501
502 unescape_char(text)
503 }
504}
505
506impl ast::Byte {
507 pub fn value(&self) -> Result<u8, EscapeError> {
508 let mut text = self.text();
509 if text.starts_with("b\'") {
510 text = &text[2..];
511 } else {
512 return Err(EscapeError::ZeroChars);
513 }
514 if text.ends_with('\'') {
515 text = &text[0..text.len() - 1];
516 }
517
518 unescape_byte(text)
519 }
520}
521
522pub enum AnyString {
523 ByteString(ast::ByteString),
524 CString(ast::CString),
525 String(ast::String),
526}
527
528impl AnyString {
529 pub fn value(&self) -> Result<Cow<'_, str>, EscapeError> {
530 fn from_utf8(s: Cow<'_, [u8]>) -> Result<Cow<'_, str>, EscapeError> {
531 match s {
532 Cow::Borrowed(s) => str::from_utf8(s)
533 .map_err(|_| EscapeError::NonAsciiCharInByte)
534 .map(Cow::Borrowed),
535 Cow::Owned(s) => String::from_utf8(s)
536 .map_err(|_| EscapeError::NonAsciiCharInByte)
537 .map(Cow::Owned),
538 }
539 }
540
541 match self {
542 AnyString::String(s) => s.value(),
543 AnyString::ByteString(s) => s.value().and_then(from_utf8),
544 AnyString::CString(s) => s.value().and_then(from_utf8),
545 }
546 }
547}
548
549impl ast::AstToken for AnyString {
550 fn can_cast(kind: crate::SyntaxKind) -> bool {
551 ast::String::can_cast(kind)
552 || ast::ByteString::can_cast(kind)
553 || ast::CString::can_cast(kind)
554 }
555
556 fn cast(syntax: crate::SyntaxToken) -> Option<Self> {
557 ast::String::cast(syntax.clone())
558 .map(Self::String)
559 .or_else(|| ast::ByteString::cast(syntax.clone()).map(Self::ByteString))
560 .or_else(|| ast::CString::cast(syntax).map(Self::CString))
561 }
562
563 fn syntax(&self) -> &crate::SyntaxToken {
564 match self {
565 Self::ByteString(it) => it.syntax(),
566 Self::CString(it) => it.syntax(),
567 Self::String(it) => it.syntax(),
568 }
569 }
570}
571
572impl IsString for AnyString {
573 fn raw_prefix(&self) -> &'static str {
574 match self {
575 AnyString::ByteString(s) => s.raw_prefix(),
576 AnyString::CString(s) => s.raw_prefix(),
577 AnyString::String(s) => s.raw_prefix(),
578 }
579 }
580
581 fn unescape(&self, s: &str, callback: impl FnMut(Range<usize>, Result<char, EscapeError>)) {
582 match self {
583 AnyString::ByteString(it) => it.unescape(s, callback),
584 AnyString::CString(it) => it.unescape(s, callback),
585 AnyString::String(it) => it.unescape(s, callback),
586 }
587 }
588}
589
590#[cfg(test)]
591mod tests {
592 use rustc_apfloat::ieee::Quad as f128;
593
594 use crate::ast::{self, FloatNumber, IntNumber, make};
595
596 fn check_float_suffix<'a>(lit: &str, expected: impl Into<Option<&'a str>>) {
597 assert_eq!(FloatNumber { syntax: make::tokens::literal(lit) }.suffix(), expected.into());
598 }
599
600 fn check_int_suffix<'a>(lit: &str, expected: impl Into<Option<&'a str>>) {
601 assert_eq!(IntNumber { syntax: make::tokens::literal(lit) }.suffix(), expected.into());
602 }
603
604 fn check_float_value(lit: &str, expected: &str) {
606 let expected = Some(expected.parse::<f128>().unwrap());
607 assert_eq!(
608 FloatNumber { syntax: make::tokens::literal(lit) }.value_string().parse::<f128>().ok(),
609 expected
610 );
611 assert_eq!(
612 IntNumber { syntax: make::tokens::literal(lit) }.value_string().parse::<f128>().ok(),
613 expected
614 );
615 }
616
617 fn check_int_value(lit: &str, expected: impl Into<Option<u128>>) {
618 assert_eq!(IntNumber { syntax: make::tokens::literal(lit) }.value().ok(), expected.into());
619 }
620
621 #[test]
622 fn test_float_number_suffix() {
623 check_float_suffix("123.0", None);
624 check_float_suffix("123f32", "f32");
625 check_float_suffix("123.0e", None);
626 check_float_suffix("123.0e4", None);
627 check_float_suffix("123.0ef16", "f16");
628 check_float_suffix("123.0E4f32", "f32");
629 check_float_suffix("1_2_3.0_f128", "f128");
630 }
631
632 #[test]
633 fn test_int_number_suffix() {
634 check_int_suffix("123", None);
635 check_int_suffix("123i32", "i32");
636 check_int_suffix("1_0_1_l_o_l", "l_o_l");
637 check_int_suffix("0b11", None);
638 check_int_suffix("0o11", None);
639 check_int_suffix("0xff", None);
640 check_int_suffix("0b11u32", "u32");
641 check_int_suffix("0o11u32", "u32");
642 check_int_suffix("0xffu32", "u32");
643 }
644
645 fn check_string_value<'a>(lit: &str, expected: impl Into<Option<&'a str>>) {
646 assert_eq!(
647 ast::String { syntax: make::tokens::literal(&format!("\"{lit}\"")) }
648 .value()
649 .as_deref()
650 .ok(),
651 expected.into()
652 );
653 }
654
655 #[test]
656 fn test_string_escape() {
657 check_string_value(r"foobar", "foobar");
658 check_string_value(r"\foobar", None);
659 check_string_value(r"\nfoobar", "\nfoobar");
660 check_string_value(r"C:\\Windows\\System32\\", "C:\\Windows\\System32\\");
661 check_string_value(r"\x61bcde", "abcde");
662 check_string_value(
663 r"a\
664bcde", "abcde",
665 );
666 }
667
668 fn check_byte_string_value<'a, const N: usize>(
669 lit: &str,
670 expected: impl Into<Option<&'a [u8; N]>>,
671 ) {
672 assert_eq!(
673 ast::ByteString { syntax: make::tokens::literal(&format!("b\"{lit}\"")) }
674 .value()
675 .as_deref()
676 .ok(),
677 expected.into().map(|value| &value[..])
678 );
679 }
680
681 #[test]
682 fn test_byte_string_escape() {
683 check_byte_string_value(r"foobar", b"foobar");
684 check_byte_string_value(r"\foobar", None::<&[u8; 0]>);
685 check_byte_string_value(r"\nfoobar", b"\nfoobar");
686 check_byte_string_value(r"C:\\Windows\\System32\\", b"C:\\Windows\\System32\\");
687 check_byte_string_value(r"\x61bcde", b"abcde");
688 check_byte_string_value(
689 r"a\
690bcde", b"abcde",
691 );
692 check_byte_string_value(
693 r"\
694 ", b"",
695 );
696 }
697
698 #[test]
699 fn test_value_underscores() {
700 check_float_value("1.3_4665449586950493453___6_f128", "1.346654495869504934536");
701 check_float_value("1.234567891011121_f64", "1.234567891011121");
702 check_float_value("1__0.__0__f32", "10.0");
703 check_float_value("3._0_f16", "3.0");
704 check_int_value("0b__1_0_", 2);
705 check_int_value("1_1_1_1_1_1", 111111);
706 }
707}