1 //! There are many AstNodes, but only a few tokens, so we hand-write them here.
5 convert::{TryFrom, TryInto},
8 use rustc_lexer::unescape::{unescape_literal, Mode};
11 ast::{self, AstToken},
16 pub fn kind(&self) -> CommentKind {
17 CommentKind::from_text(self.text())
20 pub fn is_inner(&self) -> bool {
21 self.kind().doc == Some(CommentPlacement::Inner)
24 pub fn is_outer(&self) -> bool {
25 self.kind().doc == Some(CommentPlacement::Outer)
28 pub fn prefix(&self) -> &'static str {
29 let &(prefix, _kind) = CommentKind::BY_PREFIX
31 .find(|&(prefix, kind)| self.kind() == *kind && self.text().starts_with(prefix))
36 /// Returns the textual content of a doc comment block as a single string.
37 /// That is, strips leading `///` (+ optional 1 character of whitespace),
38 /// trailing `*/`, trailing whitespace and then joins the lines.
39 pub fn doc_comment(&self) -> Option<&str> {
40 let kind = self.kind();
42 CommentKind { shape, doc: Some(_) } => {
43 let prefix = kind.prefix();
44 let text = &self.text()[prefix.len()..];
45 let ws = text.chars().next().filter(|c| c.is_whitespace());
46 let text = ws.map_or(text, |ws| &text[ws.len_utf8()..]);
48 CommentShape::Block if text.ends_with("*/") => {
49 Some(&text[..text.len() - "*/".len()])
59 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
60 pub struct CommentKind {
61 pub shape: CommentShape,
62 pub doc: Option<CommentPlacement>,
65 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
66 pub enum CommentShape {
72 pub fn is_line(self) -> bool {
73 self == CommentShape::Line
76 pub fn is_block(self) -> bool {
77 self == CommentShape::Block
81 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
82 pub enum CommentPlacement {
88 const BY_PREFIX: [(&'static str, CommentKind); 8] = [
89 ("/**/", CommentKind { shape: CommentShape::Block, doc: None }),
90 ("////", CommentKind { shape: CommentShape::Line, doc: None }),
91 ("///", CommentKind { shape: CommentShape::Line, doc: Some(CommentPlacement::Outer) }),
92 ("//!", CommentKind { shape: CommentShape::Line, doc: Some(CommentPlacement::Inner) }),
93 ("/**", CommentKind { shape: CommentShape::Block, doc: Some(CommentPlacement::Outer) }),
94 ("/*!", CommentKind { shape: CommentShape::Block, doc: Some(CommentPlacement::Inner) }),
95 ("//", CommentKind { shape: CommentShape::Line, doc: None }),
96 ("/*", CommentKind { shape: CommentShape::Block, doc: None }),
99 pub(crate) fn from_text(text: &str) -> CommentKind {
100 let &(_prefix, kind) = CommentKind::BY_PREFIX
102 .find(|&(prefix, _kind)| text.starts_with(prefix))
107 fn prefix(&self) -> &'static str {
108 let &(prefix, _) = CommentKind::BY_PREFIX.iter().find(|(_, kind)| kind == self).unwrap();
113 impl ast::Whitespace {
114 pub fn spans_multiple_lines(&self) -> bool {
115 let text = self.text();
116 text.find('\n').map_or(false, |idx| text[idx + 1..].contains('\n'))
120 pub struct QuoteOffsets {
121 pub quotes: (TextRange, TextRange),
122 pub contents: TextRange,
126 fn new(literal: &str) -> Option<QuoteOffsets> {
127 let left_quote = literal.find('"')?;
128 let right_quote = literal.rfind('"')?;
129 if left_quote == right_quote {
130 // `literal` only contains one quote
134 let start = TextSize::from(0);
135 let left_quote = TextSize::try_from(left_quote).unwrap() + TextSize::of('"');
136 let right_quote = TextSize::try_from(right_quote).unwrap();
137 let end = TextSize::of(literal);
139 let res = QuoteOffsets {
140 quotes: (TextRange::new(start, left_quote), TextRange::new(right_quote, end)),
141 contents: TextRange::new(left_quote, right_quote),
148 pub fn is_raw(&self) -> bool {
149 self.text().starts_with('r')
151 pub fn map_range_up(&self, range: TextRange) -> Option<TextRange> {
152 let contents_range = self.text_range_between_quotes()?;
153 assert!(TextRange::up_to(contents_range.len()).contains_range(range));
154 Some(range + contents_range.start())
157 pub fn value(&self) -> Option<Cow<'_, str>> {
159 let text = self.text();
161 &text[self.text_range_between_quotes()? - self.syntax().text_range().start()];
162 return Some(Cow::Borrowed(text));
165 let text = self.text();
166 let text = &text[self.text_range_between_quotes()? - self.syntax().text_range().start()];
168 let mut buf = String::new();
169 let mut text_iter = text.chars();
170 let mut has_error = false;
171 unescape_literal(text, Mode::Str, &mut |char_range, unescaped_char| match (
175 (Ok(c), false) => buf.push(c),
176 (Ok(c), true) if char_range.len() == 1 && Some(c) == text_iter.next() => (),
178 buf.reserve_exact(text.len());
179 buf.push_str(&text[..char_range.start]);
182 (Err(_), _) => has_error = true,
185 match (has_error, buf.capacity() == 0) {
187 (false, true) => Some(Cow::Borrowed(text)),
188 (false, false) => Some(Cow::Owned(buf)),
192 pub fn quote_offsets(&self) -> Option<QuoteOffsets> {
193 let text = self.text();
194 let offsets = QuoteOffsets::new(text)?;
195 let o = self.syntax().text_range().start();
196 let offsets = QuoteOffsets {
197 quotes: (offsets.quotes.0 + o, offsets.quotes.1 + o),
198 contents: offsets.contents + o,
202 pub fn text_range_between_quotes(&self) -> Option<TextRange> {
203 self.quote_offsets().map(|it| it.contents)
205 pub fn open_quote_text_range(&self) -> Option<TextRange> {
206 self.quote_offsets().map(|it| it.quotes.0)
208 pub fn close_quote_text_range(&self) -> Option<TextRange> {
209 self.quote_offsets().map(|it| it.quotes.1)
213 impl ast::ByteString {
214 pub fn is_raw(&self) -> bool {
215 self.text().starts_with("br")
220 pub enum FormatSpecifier {
237 pub trait HasFormatSpecifier: AstToken {
240 ) -> Option<Vec<(TextRange, Result<char, rustc_lexer::unescape::EscapeError>)>>;
242 fn lex_format_specifier<F>(&self, mut callback: F)
244 F: FnMut(TextRange, FormatSpecifier),
246 let char_ranges = if let Some(char_ranges) = self.char_ranges() {
251 let mut chars = char_ranges.iter().peekable();
253 while let Some((range, first_char)) = chars.next() {
256 // Format specifier, see syntax at https://doc.rust-lang.org/std/fmt/index.html#syntax
257 if let Some((_, Ok('{'))) = chars.peek() {
258 // Escaped format specifier, `{{`
263 callback(*range, FormatSpecifier::Open);
265 // check for integer/identifier
268 .and_then(|next| next.1.as_ref().ok())
274 read_integer(&mut chars, &mut callback);
276 c if c == '_' || c.is_alphabetic() => {
278 read_identifier(&mut chars, &mut callback);
283 if let Some((_, Ok(':'))) = chars.peek() {
284 skip_char_and_emit(&mut chars, FormatSpecifier::Colon, &mut callback);
286 // check for fill/align
287 let mut cloned = chars.clone().take(2);
290 .and_then(|next| next.1.as_ref().ok())
292 .unwrap_or_default();
295 .and_then(|next| next.1.as_ref().ok())
297 .unwrap_or_default();
300 // alignment specifier, first char specifies fillment
303 FormatSpecifier::Fill,
308 FormatSpecifier::Align,
316 FormatSpecifier::Align,
327 .and_then(|next| next.1.as_ref().ok())
334 FormatSpecifier::Sign,
342 if let Some((_, Ok('#'))) = chars.peek() {
345 FormatSpecifier::NumberSign,
351 let mut cloned = chars.clone().take(2);
352 let first = cloned.next().and_then(|next| next.1.as_ref().ok()).copied();
353 let second = cloned.next().and_then(|next| next.1.as_ref().ok()).copied();
355 if first == Some('0') && second != Some('$') {
356 skip_char_and_emit(&mut chars, FormatSpecifier::Zero, &mut callback);
362 .and_then(|next| next.1.as_ref().ok())
367 read_integer(&mut chars, &mut callback);
368 if let Some((_, Ok('$'))) = chars.peek() {
371 FormatSpecifier::DollarSign,
376 c if c == '_' || c.is_alphabetic() => {
377 read_identifier(&mut chars, &mut callback);
379 if chars.peek().and_then(|next| next.1.as_ref().ok()).copied()
384 FormatSpecifier::QuestionMark,
389 // can be either width (indicated by dollar sign, or type in which case
390 // the next sign has to be `}`)
392 chars.peek().and_then(|next| next.1.as_ref().ok()).copied();
395 Some('$') => skip_char_and_emit(
397 FormatSpecifier::DollarSign,
403 FormatSpecifier::Close,
415 if let Some((_, Ok('.'))) = chars.peek() {
416 skip_char_and_emit(&mut chars, FormatSpecifier::Dot, &mut callback);
420 .and_then(|next| next.1.as_ref().ok())
427 FormatSpecifier::Asterisk,
432 read_integer(&mut chars, &mut callback);
433 if let Some((_, Ok('$'))) = chars.peek() {
436 FormatSpecifier::DollarSign,
441 c if c == '_' || c.is_alphabetic() => {
442 read_identifier(&mut chars, &mut callback);
443 if chars.peek().and_then(|next| next.1.as_ref().ok()).copied()
450 FormatSpecifier::DollarSign,
463 .and_then(|next| next.1.as_ref().ok())
470 FormatSpecifier::QuestionMark,
474 c if c == '_' || c.is_alphabetic() => {
475 read_identifier(&mut chars, &mut callback);
477 if chars.peek().and_then(|next| next.1.as_ref().ok()).copied()
482 FormatSpecifier::QuestionMark,
491 if let Some((_, Ok('}'))) = chars.peek() {
492 skip_char_and_emit(&mut chars, FormatSpecifier::Close, &mut callback);
498 while let Some((_, Ok(next_char))) = chars.peek() {
509 fn skip_char_and_emit<'a, I, F>(
510 chars: &mut std::iter::Peekable<I>,
511 emit: FormatSpecifier,
514 I: Iterator<Item = &'a (TextRange, Result<char, rustc_lexer::unescape::EscapeError>)>,
515 F: FnMut(TextRange, FormatSpecifier),
517 let (range, _) = chars.next().unwrap();
518 callback(*range, emit);
521 fn read_integer<'a, I, F>(chars: &mut std::iter::Peekable<I>, callback: &mut F)
523 I: Iterator<Item = &'a (TextRange, Result<char, rustc_lexer::unescape::EscapeError>)>,
524 F: FnMut(TextRange, FormatSpecifier),
526 let (mut range, c) = chars.next().unwrap();
527 assert!(c.as_ref().unwrap().is_ascii_digit());
528 while let Some((r, Ok(next_char))) = chars.peek() {
529 if next_char.is_ascii_digit() {
531 range = range.cover(*r);
536 callback(range, FormatSpecifier::Integer);
539 fn read_identifier<'a, I, F>(chars: &mut std::iter::Peekable<I>, callback: &mut F)
541 I: Iterator<Item = &'a (TextRange, Result<char, rustc_lexer::unescape::EscapeError>)>,
542 F: FnMut(TextRange, FormatSpecifier),
544 let (mut range, c) = chars.next().unwrap();
545 assert!(c.as_ref().unwrap().is_alphabetic() || *c.as_ref().unwrap() == '_');
546 while let Some((r, Ok(next_char))) = chars.peek() {
547 if *next_char == '_' || next_char.is_ascii_digit() || next_char.is_alphabetic() {
549 range = range.cover(*r);
554 callback(range, FormatSpecifier::Identifier);
559 impl HasFormatSpecifier for ast::String {
562 ) -> Option<Vec<(TextRange, Result<char, rustc_lexer::unescape::EscapeError>)>> {
563 let text = self.text();
564 let text = &text[self.text_range_between_quotes()? - self.syntax().text_range().start()];
565 let offset = self.text_range_between_quotes()?.start() - self.syntax().text_range().start();
567 let mut res = Vec::with_capacity(text.len());
568 unescape_literal(text, Mode::Str, &mut |range, unescaped_char| {
570 TextRange::new(range.start.try_into().unwrap(), range.end.try_into().unwrap())
580 impl ast::IntNumber {
581 pub fn radix(&self) -> Radix {
582 match self.text().get(..2).unwrap_or_default() {
583 "0b" => Radix::Binary,
584 "0o" => Radix::Octal,
585 "0x" => Radix::Hexadecimal,
590 pub fn value(&self) -> Option<u128> {
591 let token = self.syntax();
593 let mut text = token.text();
594 if let Some(suffix) = self.suffix() {
595 text = &text[..text.len() - suffix.len()]
598 let radix = self.radix();
599 text = &text[radix.prefix_len()..];
602 if text.contains('_') {
603 buf = text.replace('_', "");
607 let value = u128::from_str_radix(text, radix as u32).ok()?;
611 pub fn suffix(&self) -> Option<&str> {
612 let text = self.text();
613 let radix = self.radix();
614 let mut indices = text.char_indices();
615 if radix != Radix::Decimal {
619 let is_suffix_start: fn(&(usize, char)) -> bool = match radix {
620 Radix::Hexadecimal => |(_, c)| matches!(c, 'g'..='z' | 'G'..='Z'),
621 _ => |(_, c)| c.is_ascii_alphabetic(),
623 let (suffix_start, _) = indices.find(is_suffix_start)?;
624 Some(&text[suffix_start..])
628 impl ast::FloatNumber {
629 pub fn suffix(&self) -> Option<&str> {
630 let text = self.text();
631 let mut indices = text.char_indices();
632 let (mut suffix_start, c) = indices.by_ref().find(|(_, c)| c.is_ascii_alphabetic())?;
633 if c == 'e' || c == 'E' {
634 suffix_start = indices.find(|(_, c)| c.is_ascii_alphabetic())?.0;
636 Some(&text[suffix_start..])
640 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
649 pub const ALL: &'static [Radix] =
650 &[Radix::Binary, Radix::Octal, Radix::Decimal, Radix::Hexadecimal];
652 const fn prefix_len(&self) -> usize {
662 use crate::ast::{self, make, FloatNumber, IntNumber};
664 fn check_float_suffix<'a>(lit: &str, expected: impl Into<Option<&'a str>>) {
665 assert_eq!(FloatNumber { syntax: make::tokens::literal(lit) }.suffix(), expected.into());
668 fn check_int_suffix<'a>(lit: &str, expected: impl Into<Option<&'a str>>) {
669 assert_eq!(IntNumber { syntax: make::tokens::literal(lit) }.suffix(), expected.into());
673 fn test_float_number_suffix() {
674 check_float_suffix("123.0", None);
675 check_float_suffix("123f32", "f32");
676 check_float_suffix("123.0e", None);
677 check_float_suffix("123.0e4", None);
678 check_float_suffix("123.0ef32", "f32");
679 check_float_suffix("123.0E4f32", "f32");
680 check_float_suffix("1_2_3.0_f32", "f32");
684 fn test_int_number_suffix() {
685 check_int_suffix("123", None);
686 check_int_suffix("123i32", "i32");
687 check_int_suffix("1_0_1_l_o_l", "l_o_l");
688 check_int_suffix("0b11", None);
689 check_int_suffix("0o11", None);
690 check_int_suffix("0xff", None);
691 check_int_suffix("0b11u32", "u32");
692 check_int_suffix("0o11u32", "u32");
693 check_int_suffix("0xffu32", "u32");
696 fn check_string_value<'a>(lit: &str, expected: impl Into<Option<&'a str>>) {
698 ast::String { syntax: make::tokens::literal(&format!("\"{}\"", lit)) }
706 fn test_string_escape() {
707 check_string_value(r"foobar", "foobar");
708 check_string_value(r"\foobar", None);
709 check_string_value(r"\nfoobar", "\nfoobar");
710 check_string_value(r"C:\\Windows\\System32\\", "C:\\Windows\\System32\\");