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 node as a single string with prefix and suffix
38 pub fn doc_comment(&self) -> Option<&str> {
39 let kind = self.kind();
41 CommentKind { shape, doc: Some(_) } => {
42 let prefix = kind.prefix();
43 let text = &self.text()[prefix.len()..];
44 let text = if shape == CommentShape::Block {
45 text.strip_suffix("*/").unwrap_or(text)
56 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
57 pub struct CommentKind {
58 pub shape: CommentShape,
59 pub doc: Option<CommentPlacement>,
62 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
63 pub enum CommentShape {
69 pub fn is_line(self) -> bool {
70 self == CommentShape::Line
73 pub fn is_block(self) -> bool {
74 self == CommentShape::Block
78 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
79 pub enum CommentPlacement {
85 const BY_PREFIX: [(&'static str, CommentKind); 9] = [
86 ("/**/", CommentKind { shape: CommentShape::Block, doc: None }),
87 ("/***", CommentKind { shape: CommentShape::Block, doc: None }),
88 ("////", CommentKind { shape: CommentShape::Line, doc: None }),
89 ("///", CommentKind { shape: CommentShape::Line, doc: Some(CommentPlacement::Outer) }),
90 ("//!", CommentKind { shape: CommentShape::Line, doc: Some(CommentPlacement::Inner) }),
91 ("/**", CommentKind { shape: CommentShape::Block, doc: Some(CommentPlacement::Outer) }),
92 ("/*!", CommentKind { shape: CommentShape::Block, doc: Some(CommentPlacement::Inner) }),
93 ("//", CommentKind { shape: CommentShape::Line, doc: None }),
94 ("/*", CommentKind { shape: CommentShape::Block, doc: None }),
97 pub(crate) fn from_text(text: &str) -> CommentKind {
98 let &(_prefix, kind) = CommentKind::BY_PREFIX
100 .find(|&(prefix, _kind)| text.starts_with(prefix))
105 fn prefix(&self) -> &'static str {
106 let &(prefix, _) = CommentKind::BY_PREFIX.iter().find(|(_, kind)| kind == self).unwrap();
111 impl ast::Whitespace {
112 pub fn spans_multiple_lines(&self) -> bool {
113 let text = self.text();
114 text.find('\n').map_or(false, |idx| text[idx + 1..].contains('\n'))
118 pub struct QuoteOffsets {
119 pub quotes: (TextRange, TextRange),
120 pub contents: TextRange,
124 fn new(literal: &str) -> Option<QuoteOffsets> {
125 let left_quote = literal.find('"')?;
126 let right_quote = literal.rfind('"')?;
127 if left_quote == right_quote {
128 // `literal` only contains one quote
132 let start = TextSize::from(0);
133 let left_quote = TextSize::try_from(left_quote).unwrap() + TextSize::of('"');
134 let right_quote = TextSize::try_from(right_quote).unwrap();
135 let end = TextSize::of(literal);
137 let res = QuoteOffsets {
138 quotes: (TextRange::new(start, left_quote), TextRange::new(right_quote, end)),
139 contents: TextRange::new(left_quote, right_quote),
146 pub fn is_raw(&self) -> bool {
147 self.text().starts_with('r')
149 pub fn map_range_up(&self, range: TextRange) -> Option<TextRange> {
150 let contents_range = self.text_range_between_quotes()?;
151 assert!(TextRange::up_to(contents_range.len()).contains_range(range));
152 Some(range + contents_range.start())
155 pub fn value(&self) -> Option<Cow<'_, str>> {
157 let text = self.text();
159 &text[self.text_range_between_quotes()? - self.syntax().text_range().start()];
160 return Some(Cow::Borrowed(text));
163 let text = self.text();
164 let text = &text[self.text_range_between_quotes()? - self.syntax().text_range().start()];
166 let mut buf = String::new();
167 let mut text_iter = text.chars();
168 let mut has_error = false;
169 unescape_literal(text, Mode::Str, &mut |char_range, unescaped_char| match (
173 (Ok(c), false) => buf.push(c),
174 (Ok(c), true) if char_range.len() == 1 && Some(c) == text_iter.next() => (),
176 buf.reserve_exact(text.len());
177 buf.push_str(&text[..char_range.start]);
180 (Err(_), _) => has_error = true,
183 match (has_error, buf.capacity() == 0) {
185 (false, true) => Some(Cow::Borrowed(text)),
186 (false, false) => Some(Cow::Owned(buf)),
190 pub fn quote_offsets(&self) -> Option<QuoteOffsets> {
191 let text = self.text();
192 let offsets = QuoteOffsets::new(text)?;
193 let o = self.syntax().text_range().start();
194 let offsets = QuoteOffsets {
195 quotes: (offsets.quotes.0 + o, offsets.quotes.1 + o),
196 contents: offsets.contents + o,
200 pub fn text_range_between_quotes(&self) -> Option<TextRange> {
201 self.quote_offsets().map(|it| it.contents)
203 pub fn open_quote_text_range(&self) -> Option<TextRange> {
204 self.quote_offsets().map(|it| it.quotes.0)
206 pub fn close_quote_text_range(&self) -> Option<TextRange> {
207 self.quote_offsets().map(|it| it.quotes.1)
211 impl ast::ByteString {
212 pub fn is_raw(&self) -> bool {
213 self.text().starts_with("br")
218 pub enum FormatSpecifier {
235 pub trait HasFormatSpecifier: AstToken {
238 ) -> Option<Vec<(TextRange, Result<char, rustc_lexer::unescape::EscapeError>)>>;
240 fn lex_format_specifier<F>(&self, mut callback: F)
242 F: FnMut(TextRange, FormatSpecifier),
244 let char_ranges = if let Some(char_ranges) = self.char_ranges() {
249 let mut chars = char_ranges.iter().peekable();
251 while let Some((range, first_char)) = chars.next() {
254 // Format specifier, see syntax at https://doc.rust-lang.org/std/fmt/index.html#syntax
255 if let Some((_, Ok('{'))) = chars.peek() {
256 // Escaped format specifier, `{{`
261 callback(*range, FormatSpecifier::Open);
263 // check for integer/identifier
266 .and_then(|next| next.1.as_ref().ok())
272 read_integer(&mut chars, &mut callback);
274 c if c == '_' || c.is_alphabetic() => {
276 read_identifier(&mut chars, &mut callback);
281 if let Some((_, Ok(':'))) = chars.peek() {
282 skip_char_and_emit(&mut chars, FormatSpecifier::Colon, &mut callback);
284 // check for fill/align
285 let mut cloned = chars.clone().take(2);
288 .and_then(|next| next.1.as_ref().ok())
290 .unwrap_or_default();
293 .and_then(|next| next.1.as_ref().ok())
295 .unwrap_or_default();
298 // alignment specifier, first char specifies fillment
301 FormatSpecifier::Fill,
306 FormatSpecifier::Align,
314 FormatSpecifier::Align,
325 .and_then(|next| next.1.as_ref().ok())
332 FormatSpecifier::Sign,
340 if let Some((_, Ok('#'))) = chars.peek() {
343 FormatSpecifier::NumberSign,
349 let mut cloned = chars.clone().take(2);
350 let first = cloned.next().and_then(|next| next.1.as_ref().ok()).copied();
351 let second = cloned.next().and_then(|next| next.1.as_ref().ok()).copied();
353 if first == Some('0') && second != Some('$') {
354 skip_char_and_emit(&mut chars, FormatSpecifier::Zero, &mut callback);
360 .and_then(|next| next.1.as_ref().ok())
365 read_integer(&mut chars, &mut callback);
366 if let Some((_, Ok('$'))) = chars.peek() {
369 FormatSpecifier::DollarSign,
374 c if c == '_' || c.is_alphabetic() => {
375 read_identifier(&mut chars, &mut callback);
377 if chars.peek().and_then(|next| next.1.as_ref().ok()).copied()
382 FormatSpecifier::QuestionMark,
387 // can be either width (indicated by dollar sign, or type in which case
388 // the next sign has to be `}`)
390 chars.peek().and_then(|next| next.1.as_ref().ok()).copied();
393 Some('$') => skip_char_and_emit(
395 FormatSpecifier::DollarSign,
401 FormatSpecifier::Close,
413 if let Some((_, Ok('.'))) = chars.peek() {
414 skip_char_and_emit(&mut chars, FormatSpecifier::Dot, &mut callback);
418 .and_then(|next| next.1.as_ref().ok())
425 FormatSpecifier::Asterisk,
430 read_integer(&mut chars, &mut callback);
431 if let Some((_, Ok('$'))) = chars.peek() {
434 FormatSpecifier::DollarSign,
439 c if c == '_' || c.is_alphabetic() => {
440 read_identifier(&mut chars, &mut callback);
441 if chars.peek().and_then(|next| next.1.as_ref().ok()).copied()
448 FormatSpecifier::DollarSign,
461 .and_then(|next| next.1.as_ref().ok())
468 FormatSpecifier::QuestionMark,
472 c if c == '_' || c.is_alphabetic() => {
473 read_identifier(&mut chars, &mut callback);
475 if chars.peek().and_then(|next| next.1.as_ref().ok()).copied()
480 FormatSpecifier::QuestionMark,
489 if let Some((_, Ok('}'))) = chars.peek() {
490 skip_char_and_emit(&mut chars, FormatSpecifier::Close, &mut callback);
496 while let Some((_, Ok(next_char))) = chars.peek() {
507 fn skip_char_and_emit<'a, I, F>(
508 chars: &mut std::iter::Peekable<I>,
509 emit: FormatSpecifier,
512 I: Iterator<Item = &'a (TextRange, Result<char, rustc_lexer::unescape::EscapeError>)>,
513 F: FnMut(TextRange, FormatSpecifier),
515 let (range, _) = chars.next().unwrap();
516 callback(*range, emit);
519 fn read_integer<'a, I, F>(chars: &mut std::iter::Peekable<I>, callback: &mut F)
521 I: Iterator<Item = &'a (TextRange, Result<char, rustc_lexer::unescape::EscapeError>)>,
522 F: FnMut(TextRange, FormatSpecifier),
524 let (mut range, c) = chars.next().unwrap();
525 assert!(c.as_ref().unwrap().is_ascii_digit());
526 while let Some((r, Ok(next_char))) = chars.peek() {
527 if next_char.is_ascii_digit() {
529 range = range.cover(*r);
534 callback(range, FormatSpecifier::Integer);
537 fn read_identifier<'a, I, F>(chars: &mut std::iter::Peekable<I>, callback: &mut F)
539 I: Iterator<Item = &'a (TextRange, Result<char, rustc_lexer::unescape::EscapeError>)>,
540 F: FnMut(TextRange, FormatSpecifier),
542 let (mut range, c) = chars.next().unwrap();
543 assert!(c.as_ref().unwrap().is_alphabetic() || *c.as_ref().unwrap() == '_');
544 while let Some((r, Ok(next_char))) = chars.peek() {
545 if *next_char == '_' || next_char.is_ascii_digit() || next_char.is_alphabetic() {
547 range = range.cover(*r);
552 callback(range, FormatSpecifier::Identifier);
557 impl HasFormatSpecifier for ast::String {
560 ) -> Option<Vec<(TextRange, Result<char, rustc_lexer::unescape::EscapeError>)>> {
561 let text = self.text();
562 let text = &text[self.text_range_between_quotes()? - self.syntax().text_range().start()];
563 let offset = self.text_range_between_quotes()?.start() - self.syntax().text_range().start();
565 let mut res = Vec::with_capacity(text.len());
566 unescape_literal(text, Mode::Str, &mut |range, unescaped_char| {
568 TextRange::new(range.start.try_into().unwrap(), range.end.try_into().unwrap())
578 impl ast::IntNumber {
579 pub fn radix(&self) -> Radix {
580 match self.text().get(..2).unwrap_or_default() {
581 "0b" => Radix::Binary,
582 "0o" => Radix::Octal,
583 "0x" => Radix::Hexadecimal,
588 pub fn value(&self) -> Option<u128> {
589 let token = self.syntax();
591 let mut text = token.text();
592 if let Some(suffix) = self.suffix() {
593 text = &text[..text.len() - suffix.len()]
596 let radix = self.radix();
597 text = &text[radix.prefix_len()..];
600 if text.contains('_') {
601 buf = text.replace('_', "");
605 let value = u128::from_str_radix(text, radix as u32).ok()?;
609 pub fn suffix(&self) -> Option<&str> {
610 let text = self.text();
611 let radix = self.radix();
612 let mut indices = text.char_indices();
613 if radix != Radix::Decimal {
617 let is_suffix_start: fn(&(usize, char)) -> bool = match radix {
618 Radix::Hexadecimal => |(_, c)| matches!(c, 'g'..='z' | 'G'..='Z'),
619 _ => |(_, c)| c.is_ascii_alphabetic(),
621 let (suffix_start, _) = indices.find(is_suffix_start)?;
622 Some(&text[suffix_start..])
626 impl ast::FloatNumber {
627 pub fn suffix(&self) -> Option<&str> {
628 let text = self.text();
629 let mut indices = text.char_indices();
630 let (mut suffix_start, c) = indices.by_ref().find(|(_, c)| c.is_ascii_alphabetic())?;
631 if c == 'e' || c == 'E' {
632 suffix_start = indices.find(|(_, c)| c.is_ascii_alphabetic())?.0;
634 Some(&text[suffix_start..])
638 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
647 pub const ALL: &'static [Radix] =
648 &[Radix::Binary, Radix::Octal, Radix::Decimal, Radix::Hexadecimal];
650 const fn prefix_len(&self) -> usize {
660 use crate::ast::{self, make, FloatNumber, IntNumber};
662 fn check_float_suffix<'a>(lit: &str, expected: impl Into<Option<&'a str>>) {
663 assert_eq!(FloatNumber { syntax: make::tokens::literal(lit) }.suffix(), expected.into());
666 fn check_int_suffix<'a>(lit: &str, expected: impl Into<Option<&'a str>>) {
667 assert_eq!(IntNumber { syntax: make::tokens::literal(lit) }.suffix(), expected.into());
671 fn test_float_number_suffix() {
672 check_float_suffix("123.0", None);
673 check_float_suffix("123f32", "f32");
674 check_float_suffix("123.0e", None);
675 check_float_suffix("123.0e4", None);
676 check_float_suffix("123.0ef32", "f32");
677 check_float_suffix("123.0E4f32", "f32");
678 check_float_suffix("1_2_3.0_f32", "f32");
682 fn test_int_number_suffix() {
683 check_int_suffix("123", None);
684 check_int_suffix("123i32", "i32");
685 check_int_suffix("1_0_1_l_o_l", "l_o_l");
686 check_int_suffix("0b11", None);
687 check_int_suffix("0o11", None);
688 check_int_suffix("0xff", None);
689 check_int_suffix("0b11u32", "u32");
690 check_int_suffix("0o11u32", "u32");
691 check_int_suffix("0xffu32", "u32");
694 fn check_string_value<'a>(lit: &str, expected: impl Into<Option<&'a str>>) {
696 ast::String { syntax: make::tokens::literal(&format!("\"{}\"", lit)) }
704 fn test_string_escape() {
705 check_string_value(r"foobar", "foobar");
706 check_string_value(r"\foobar", None);
707 check_string_value(r"\nfoobar", "\nfoobar");
708 check_string_value(r"C:\\Windows\\System32\\", "C:\\Windows\\System32\\");