]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse_format/src/lib.rs
rustdoc: Remove single-use `Lifetime::get_ref()` function
[rust.git] / compiler / rustc_parse_format / src / lib.rs
1 //! Macro support for format strings
2 //!
3 //! These structures are used when parsing format strings for the compiler.
4 //! Parsing does not happen at runtime: structures of `std::fmt::rt` are
5 //! generated instead.
6
7 #![doc(
8     html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/",
9     html_playground_url = "https://play.rust-lang.org/",
10     test(attr(deny(warnings)))
11 )]
12 #![feature(nll)]
13 #![feature(bool_to_option)]
14
15 pub use Alignment::*;
16 pub use Count::*;
17 pub use Flag::*;
18 pub use Piece::*;
19 pub use Position::*;
20
21 use std::iter;
22 use std::str;
23 use std::string;
24
25 use rustc_span::{InnerSpan, Symbol};
26
27 /// The type of format string that we are parsing.
28 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
29 pub enum ParseMode {
30     /// A normal format string as per `format_args!`.
31     Format,
32     /// An inline assembly template string for `asm!`.
33     InlineAsm,
34 }
35
36 #[derive(Copy, Clone)]
37 struct InnerOffset(usize);
38
39 impl InnerOffset {
40     fn to(self, end: InnerOffset) -> InnerSpan {
41         InnerSpan::new(self.0, end.0)
42     }
43 }
44
45 /// A piece is a portion of the format string which represents the next part
46 /// to emit. These are emitted as a stream by the `Parser` class.
47 #[derive(Copy, Clone, Debug, PartialEq)]
48 pub enum Piece<'a> {
49     /// A literal string which should directly be emitted
50     String(&'a str),
51     /// This describes that formatting should process the next argument (as
52     /// specified inside) for emission.
53     NextArgument(Argument<'a>),
54 }
55
56 /// Representation of an argument specification.
57 #[derive(Copy, Clone, Debug, PartialEq)]
58 pub struct Argument<'a> {
59     /// Where to find this argument
60     pub position: Position,
61     /// How to format the argument
62     pub format: FormatSpec<'a>,
63 }
64
65 /// Specification for the formatting of an argument in the format string.
66 #[derive(Copy, Clone, Debug, PartialEq)]
67 pub struct FormatSpec<'a> {
68     /// Optionally specified character to fill alignment with.
69     pub fill: Option<char>,
70     /// Optionally specified alignment.
71     pub align: Alignment,
72     /// Packed version of various flags provided.
73     pub flags: u32,
74     /// The integer precision to use.
75     pub precision: Count,
76     /// The span of the precision formatting flag (for diagnostics).
77     pub precision_span: Option<InnerSpan>,
78     /// The string width requested for the resulting format.
79     pub width: Count,
80     /// The span of the width formatting flag (for diagnostics).
81     pub width_span: Option<InnerSpan>,
82     /// The descriptor string representing the name of the format desired for
83     /// this argument, this can be empty or any number of characters, although
84     /// it is required to be one word.
85     pub ty: &'a str,
86     /// The span of the descriptor string (for diagnostics).
87     pub ty_span: Option<InnerSpan>,
88 }
89
90 /// Enum describing where an argument for a format can be located.
91 #[derive(Copy, Clone, Debug, PartialEq)]
92 pub enum Position {
93     /// The argument is implied to be located at an index
94     ArgumentImplicitlyIs(usize),
95     /// The argument is located at a specific index given in the format
96     ArgumentIs(usize),
97     /// The argument has a name.
98     ArgumentNamed(Symbol),
99 }
100
101 impl Position {
102     pub fn index(&self) -> Option<usize> {
103         match self {
104             ArgumentIs(i) | ArgumentImplicitlyIs(i) => Some(*i),
105             _ => None,
106         }
107     }
108 }
109
110 /// Enum of alignments which are supported.
111 #[derive(Copy, Clone, Debug, PartialEq)]
112 pub enum Alignment {
113     /// The value will be aligned to the left.
114     AlignLeft,
115     /// The value will be aligned to the right.
116     AlignRight,
117     /// The value will be aligned in the center.
118     AlignCenter,
119     /// The value will take on a default alignment.
120     AlignUnknown,
121 }
122
123 /// Various flags which can be applied to format strings. The meaning of these
124 /// flags is defined by the formatters themselves.
125 #[derive(Copy, Clone, Debug, PartialEq)]
126 pub enum Flag {
127     /// A `+` will be used to denote positive numbers.
128     FlagSignPlus,
129     /// A `-` will be used to denote negative numbers. This is the default.
130     FlagSignMinus,
131     /// An alternate form will be used for the value. In the case of numbers,
132     /// this means that the number will be prefixed with the supplied string.
133     FlagAlternate,
134     /// For numbers, this means that the number will be padded with zeroes,
135     /// and the sign (`+` or `-`) will precede them.
136     FlagSignAwareZeroPad,
137     /// For Debug / `?`, format integers in lower-case hexadecimal.
138     FlagDebugLowerHex,
139     /// For Debug / `?`, format integers in upper-case hexadecimal.
140     FlagDebugUpperHex,
141 }
142
143 /// A count is used for the precision and width parameters of an integer, and
144 /// can reference either an argument or a literal integer.
145 #[derive(Copy, Clone, Debug, PartialEq)]
146 pub enum Count {
147     /// The count is specified explicitly.
148     CountIs(usize),
149     /// The count is specified by the argument with the given name.
150     CountIsName(Symbol),
151     /// The count is specified by the argument at the given index.
152     CountIsParam(usize),
153     /// The count is implied and cannot be explicitly specified.
154     CountImplied,
155 }
156
157 pub struct ParseError {
158     pub description: string::String,
159     pub note: Option<string::String>,
160     pub label: string::String,
161     pub span: InnerSpan,
162     pub secondary_label: Option<(string::String, InnerSpan)>,
163 }
164
165 /// The parser structure for interpreting the input format string. This is
166 /// modeled as an iterator over `Piece` structures to form a stream of tokens
167 /// being output.
168 ///
169 /// This is a recursive-descent parser for the sake of simplicity, and if
170 /// necessary there's probably lots of room for improvement performance-wise.
171 pub struct Parser<'a> {
172     mode: ParseMode,
173     input: &'a str,
174     cur: iter::Peekable<str::CharIndices<'a>>,
175     /// Error messages accumulated during parsing
176     pub errors: Vec<ParseError>,
177     /// Current position of implicit positional argument pointer
178     pub curarg: usize,
179     /// `Some(raw count)` when the string is "raw", used to position spans correctly
180     style: Option<usize>,
181     /// Start and end byte offset of every successfully parsed argument
182     pub arg_places: Vec<InnerSpan>,
183     /// Characters that need to be shifted
184     skips: Vec<usize>,
185     /// Span of the last opening brace seen, used for error reporting
186     last_opening_brace: Option<InnerSpan>,
187     /// Whether the source string is comes from `println!` as opposed to `format!` or `print!`
188     append_newline: bool,
189     /// Whether this formatting string is a literal or it comes from a macro.
190     pub is_literal: bool,
191     /// Start position of the current line.
192     cur_line_start: usize,
193     /// Start and end byte offset of every line of the format string. Excludes
194     /// newline characters and leading whitespace.
195     pub line_spans: Vec<InnerSpan>,
196 }
197
198 impl<'a> Iterator for Parser<'a> {
199     type Item = Piece<'a>;
200
201     fn next(&mut self) -> Option<Piece<'a>> {
202         if let Some(&(pos, c)) = self.cur.peek() {
203             match c {
204                 '{' => {
205                     let curr_last_brace = self.last_opening_brace;
206                     let byte_pos = self.to_span_index(pos);
207                     self.last_opening_brace = Some(byte_pos.to(InnerOffset(byte_pos.0 + 1)));
208                     self.cur.next();
209                     if self.consume('{') {
210                         self.last_opening_brace = curr_last_brace;
211
212                         Some(String(self.string(pos + 1)))
213                     } else {
214                         let arg = self.argument();
215                         if let Some(rbrace_byte_idx) = self.must_consume('}') {
216                             let lbrace_inner_offset = self.to_span_index(pos);
217                             let rbrace_inner_offset = self.to_span_index(rbrace_byte_idx);
218                             if self.is_literal {
219                                 self.arg_places.push(
220                                     lbrace_inner_offset.to(InnerOffset(rbrace_inner_offset.0 + 1)),
221                                 );
222                             }
223                         }
224                         Some(NextArgument(arg))
225                     }
226                 }
227                 '}' => {
228                     self.cur.next();
229                     if self.consume('}') {
230                         Some(String(self.string(pos + 1)))
231                     } else {
232                         let err_pos = self.to_span_index(pos);
233                         self.err_with_note(
234                             "unmatched `}` found",
235                             "unmatched `}`",
236                             "if you intended to print `}`, you can escape it using `}}`",
237                             err_pos.to(err_pos),
238                         );
239                         None
240                     }
241                 }
242                 _ => Some(String(self.string(pos))),
243             }
244         } else {
245             if self.is_literal {
246                 let start = self.to_span_index(self.cur_line_start);
247                 let end = self.to_span_index(self.input.len());
248                 let span = start.to(end);
249                 if self.line_spans.last() != Some(&span) {
250                     self.line_spans.push(span);
251                 }
252             }
253             None
254         }
255     }
256 }
257
258 impl<'a> Parser<'a> {
259     /// Creates a new parser for the given format string
260     pub fn new(
261         s: &'a str,
262         style: Option<usize>,
263         snippet: Option<string::String>,
264         append_newline: bool,
265         mode: ParseMode,
266     ) -> Parser<'a> {
267         let (skips, is_literal) = find_skips_from_snippet(snippet, style);
268         Parser {
269             mode,
270             input: s,
271             cur: s.char_indices().peekable(),
272             errors: vec![],
273             curarg: 0,
274             style,
275             arg_places: vec![],
276             skips,
277             last_opening_brace: None,
278             append_newline,
279             is_literal,
280             cur_line_start: 0,
281             line_spans: vec![],
282         }
283     }
284
285     /// Notifies of an error. The message doesn't actually need to be of type
286     /// String, but I think it does when this eventually uses conditions so it
287     /// might as well start using it now.
288     fn err<S1: Into<string::String>, S2: Into<string::String>>(
289         &mut self,
290         description: S1,
291         label: S2,
292         span: InnerSpan,
293     ) {
294         self.errors.push(ParseError {
295             description: description.into(),
296             note: None,
297             label: label.into(),
298             span,
299             secondary_label: None,
300         });
301     }
302
303     /// Notifies of an error. The message doesn't actually need to be of type
304     /// String, but I think it does when this eventually uses conditions so it
305     /// might as well start using it now.
306     fn err_with_note<
307         S1: Into<string::String>,
308         S2: Into<string::String>,
309         S3: Into<string::String>,
310     >(
311         &mut self,
312         description: S1,
313         label: S2,
314         note: S3,
315         span: InnerSpan,
316     ) {
317         self.errors.push(ParseError {
318             description: description.into(),
319             note: Some(note.into()),
320             label: label.into(),
321             span,
322             secondary_label: None,
323         });
324     }
325
326     /// Optionally consumes the specified character. If the character is not at
327     /// the current position, then the current iterator isn't moved and `false` is
328     /// returned, otherwise the character is consumed and `true` is returned.
329     fn consume(&mut self, c: char) -> bool {
330         self.consume_pos(c).is_some()
331     }
332
333     /// Optionally consumes the specified character. If the character is not at
334     /// the current position, then the current iterator isn't moved and `None` is
335     /// returned, otherwise the character is consumed and the current position is
336     /// returned.
337     fn consume_pos(&mut self, c: char) -> Option<usize> {
338         if let Some(&(pos, maybe)) = self.cur.peek() {
339             if c == maybe {
340                 self.cur.next();
341                 return Some(pos);
342             }
343         }
344         None
345     }
346
347     fn to_span_index(&self, pos: usize) -> InnerOffset {
348         let mut pos = pos;
349         // This handles the raw string case, the raw argument is the number of #
350         // in r###"..."### (we need to add one because of the `r`).
351         let raw = self.style.map_or(0, |raw| raw + 1);
352         for skip in &self.skips {
353             if pos > *skip {
354                 pos += 1;
355             } else if pos == *skip && raw == 0 {
356                 pos += 1;
357             } else {
358                 break;
359             }
360         }
361         InnerOffset(raw + pos + 1)
362     }
363
364     /// Forces consumption of the specified character. If the character is not
365     /// found, an error is emitted.
366     fn must_consume(&mut self, c: char) -> Option<usize> {
367         self.ws();
368
369         if let Some(&(pos, maybe)) = self.cur.peek() {
370             if c == maybe {
371                 self.cur.next();
372                 Some(pos)
373             } else {
374                 let pos = self.to_span_index(pos);
375                 let description = format!("expected `'}}'`, found `{:?}`", maybe);
376                 let label = "expected `}`".to_owned();
377                 let (note, secondary_label) = if c == '}' {
378                     (
379                         Some(
380                             "if you intended to print `{`, you can escape it using `{{`".to_owned(),
381                         ),
382                         self.last_opening_brace
383                             .map(|sp| ("because of this opening brace".to_owned(), sp)),
384                     )
385                 } else {
386                     (None, None)
387                 };
388                 self.errors.push(ParseError {
389                     description,
390                     note,
391                     label,
392                     span: pos.to(pos),
393                     secondary_label,
394                 });
395                 None
396             }
397         } else {
398             let description = format!("expected `{:?}` but string was terminated", c);
399             // point at closing `"`
400             let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
401             let pos = self.to_span_index(pos);
402             if c == '}' {
403                 let label = format!("expected `{:?}`", c);
404                 let (note, secondary_label) = if c == '}' {
405                     (
406                         Some(
407                             "if you intended to print `{`, you can escape it using `{{`".to_owned(),
408                         ),
409                         self.last_opening_brace
410                             .map(|sp| ("because of this opening brace".to_owned(), sp)),
411                     )
412                 } else {
413                     (None, None)
414                 };
415                 self.errors.push(ParseError {
416                     description,
417                     note,
418                     label,
419                     span: pos.to(pos),
420                     secondary_label,
421                 });
422             } else {
423                 self.err(description, format!("expected `{:?}`", c), pos.to(pos));
424             }
425             None
426         }
427     }
428
429     /// Consumes all whitespace characters until the first non-whitespace character
430     fn ws(&mut self) {
431         while let Some(&(_, c)) = self.cur.peek() {
432             if c.is_whitespace() {
433                 self.cur.next();
434             } else {
435                 break;
436             }
437         }
438     }
439
440     /// Parses all of a string which is to be considered a "raw literal" in a
441     /// format string. This is everything outside of the braces.
442     fn string(&mut self, start: usize) -> &'a str {
443         // we may not consume the character, peek the iterator
444         while let Some(&(pos, c)) = self.cur.peek() {
445             match c {
446                 '{' | '}' => {
447                     return &self.input[start..pos];
448                 }
449                 '\n' if self.is_literal => {
450                     let start = self.to_span_index(self.cur_line_start);
451                     let end = self.to_span_index(pos);
452                     self.line_spans.push(start.to(end));
453                     self.cur_line_start = pos + 1;
454                     self.cur.next();
455                 }
456                 _ => {
457                     if self.is_literal && pos == self.cur_line_start && c.is_whitespace() {
458                         self.cur_line_start = pos + c.len_utf8();
459                     }
460                     self.cur.next();
461                 }
462             }
463         }
464         &self.input[start..self.input.len()]
465     }
466
467     /// Parses an `Argument` structure, or what's contained within braces inside the format string.
468     fn argument(&mut self) -> Argument<'a> {
469         let pos = self.position();
470         let format = match self.mode {
471             ParseMode::Format => self.format(),
472             ParseMode::InlineAsm => self.inline_asm(),
473         };
474
475         // Resolve position after parsing format spec.
476         let pos = match pos {
477             Some(position) => position,
478             None => {
479                 let i = self.curarg;
480                 self.curarg += 1;
481                 ArgumentImplicitlyIs(i)
482             }
483         };
484
485         Argument { position: pos, format }
486     }
487
488     /// Parses a positional argument for a format. This could either be an
489     /// integer index of an argument, a named argument, or a blank string.
490     /// Returns `Some(parsed_position)` if the position is not implicitly
491     /// consuming a macro argument, `None` if it's the case.
492     fn position(&mut self) -> Option<Position> {
493         if let Some(i) = self.integer() {
494             Some(ArgumentIs(i))
495         } else {
496             match self.cur.peek() {
497                 Some(&(_, c)) if rustc_lexer::is_id_start(c) => {
498                     Some(ArgumentNamed(Symbol::intern(self.word())))
499                 }
500
501                 // This is an `ArgumentNext`.
502                 // Record the fact and do the resolution after parsing the
503                 // format spec, to make things like `{:.*}` work.
504                 _ => None,
505             }
506         }
507     }
508
509     /// Parses a format specifier at the current position, returning all of the
510     /// relevant information in the `FormatSpec` struct.
511     fn format(&mut self) -> FormatSpec<'a> {
512         let mut spec = FormatSpec {
513             fill: None,
514             align: AlignUnknown,
515             flags: 0,
516             precision: CountImplied,
517             precision_span: None,
518             width: CountImplied,
519             width_span: None,
520             ty: &self.input[..0],
521             ty_span: None,
522         };
523         if !self.consume(':') {
524             return spec;
525         }
526
527         // fill character
528         if let Some(&(_, c)) = self.cur.peek() {
529             if let Some((_, '>' | '<' | '^')) = self.cur.clone().nth(1) {
530                 spec.fill = Some(c);
531                 self.cur.next();
532             }
533         }
534         // Alignment
535         if self.consume('<') {
536             spec.align = AlignLeft;
537         } else if self.consume('>') {
538             spec.align = AlignRight;
539         } else if self.consume('^') {
540             spec.align = AlignCenter;
541         }
542         // Sign flags
543         if self.consume('+') {
544             spec.flags |= 1 << (FlagSignPlus as u32);
545         } else if self.consume('-') {
546             spec.flags |= 1 << (FlagSignMinus as u32);
547         }
548         // Alternate marker
549         if self.consume('#') {
550             spec.flags |= 1 << (FlagAlternate as u32);
551         }
552         // Width and precision
553         let mut havewidth = false;
554
555         if self.consume('0') {
556             // small ambiguity with '0$' as a format string. In theory this is a
557             // '0' flag and then an ill-formatted format string with just a '$'
558             // and no count, but this is better if we instead interpret this as
559             // no '0' flag and '0$' as the width instead.
560             if self.consume('$') {
561                 spec.width = CountIsParam(0);
562                 havewidth = true;
563             } else {
564                 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
565             }
566         }
567         if !havewidth {
568             let width_span_start = if let Some((pos, _)) = self.cur.peek() { *pos } else { 0 };
569             let (w, sp) = self.count(width_span_start);
570             spec.width = w;
571             spec.width_span = sp;
572         }
573         if let Some(start) = self.consume_pos('.') {
574             if let Some(end) = self.consume_pos('*') {
575                 // Resolve `CountIsNextParam`.
576                 // We can do this immediately as `position` is resolved later.
577                 let i = self.curarg;
578                 self.curarg += 1;
579                 spec.precision = CountIsParam(i);
580                 spec.precision_span =
581                     Some(self.to_span_index(start).to(self.to_span_index(end + 1)));
582             } else {
583                 let (p, sp) = self.count(start);
584                 spec.precision = p;
585                 spec.precision_span = sp;
586             }
587         }
588         let ty_span_start = self.cur.peek().map(|(pos, _)| *pos);
589         // Optional radix followed by the actual format specifier
590         if self.consume('x') {
591             if self.consume('?') {
592                 spec.flags |= 1 << (FlagDebugLowerHex as u32);
593                 spec.ty = "?";
594             } else {
595                 spec.ty = "x";
596             }
597         } else if self.consume('X') {
598             if self.consume('?') {
599                 spec.flags |= 1 << (FlagDebugUpperHex as u32);
600                 spec.ty = "?";
601             } else {
602                 spec.ty = "X";
603             }
604         } else if self.consume('?') {
605             spec.ty = "?";
606         } else {
607             spec.ty = self.word();
608             let ty_span_end = self.cur.peek().map(|(pos, _)| *pos);
609             if !spec.ty.is_empty() {
610                 spec.ty_span = ty_span_start
611                     .and_then(|s| ty_span_end.map(|e| (s, e)))
612                     .map(|(start, end)| self.to_span_index(start).to(self.to_span_index(end)));
613             }
614         }
615         spec
616     }
617
618     /// Parses an inline assembly template modifier at the current position, returning the modifier
619     /// in the `ty` field of the `FormatSpec` struct.
620     fn inline_asm(&mut self) -> FormatSpec<'a> {
621         let mut spec = FormatSpec {
622             fill: None,
623             align: AlignUnknown,
624             flags: 0,
625             precision: CountImplied,
626             precision_span: None,
627             width: CountImplied,
628             width_span: None,
629             ty: &self.input[..0],
630             ty_span: None,
631         };
632         if !self.consume(':') {
633             return spec;
634         }
635
636         let ty_span_start = self.cur.peek().map(|(pos, _)| *pos);
637         spec.ty = self.word();
638         let ty_span_end = self.cur.peek().map(|(pos, _)| *pos);
639         if !spec.ty.is_empty() {
640             spec.ty_span = ty_span_start
641                 .and_then(|s| ty_span_end.map(|e| (s, e)))
642                 .map(|(start, end)| self.to_span_index(start).to(self.to_span_index(end)));
643         }
644
645         spec
646     }
647
648     /// Parses a `Count` parameter at the current position. This does not check
649     /// for 'CountIsNextParam' because that is only used in precision, not
650     /// width.
651     fn count(&mut self, start: usize) -> (Count, Option<InnerSpan>) {
652         if let Some(i) = self.integer() {
653             if let Some(end) = self.consume_pos('$') {
654                 let span = self.to_span_index(start).to(self.to_span_index(end + 1));
655                 (CountIsParam(i), Some(span))
656             } else {
657                 (CountIs(i), None)
658             }
659         } else {
660             let tmp = self.cur.clone();
661             let word = self.word();
662             if word.is_empty() {
663                 self.cur = tmp;
664                 (CountImplied, None)
665             } else if self.consume('$') {
666                 (CountIsName(Symbol::intern(word)), None)
667             } else {
668                 self.cur = tmp;
669                 (CountImplied, None)
670             }
671         }
672     }
673
674     /// Parses a word starting at the current position. A word is the same as
675     /// Rust identifier, except that it can't start with `_` character.
676     fn word(&mut self) -> &'a str {
677         let start = match self.cur.peek() {
678             Some(&(pos, c)) if rustc_lexer::is_id_start(c) => {
679                 self.cur.next();
680                 pos
681             }
682             _ => {
683                 return "";
684             }
685         };
686         let mut end = None;
687         while let Some(&(pos, c)) = self.cur.peek() {
688             if rustc_lexer::is_id_continue(c) {
689                 self.cur.next();
690             } else {
691                 end = Some(pos);
692                 break;
693             }
694         }
695         let end = end.unwrap_or(self.input.len());
696         let word = &self.input[start..end];
697         if word == "_" {
698             self.err_with_note(
699                 "invalid argument name `_`",
700                 "invalid argument name",
701                 "argument name cannot be a single underscore",
702                 self.to_span_index(start).to(self.to_span_index(end)),
703             );
704         }
705         word
706     }
707
708     /// Optionally parses an integer at the current position. This doesn't deal
709     /// with overflow at all, it's just accumulating digits.
710     fn integer(&mut self) -> Option<usize> {
711         let mut cur = 0;
712         let mut found = false;
713         while let Some(&(_, c)) = self.cur.peek() {
714             if let Some(i) = c.to_digit(10) {
715                 cur = cur * 10 + i as usize;
716                 found = true;
717                 self.cur.next();
718             } else {
719                 break;
720             }
721         }
722         found.then_some(cur)
723     }
724 }
725
726 /// Finds the indices of all characters that have been processed and differ between the actual
727 /// written code (code snippet) and the `InternedString` that gets processed in the `Parser`
728 /// in order to properly synthethise the intra-string `Span`s for error diagnostics.
729 fn find_skips_from_snippet(
730     snippet: Option<string::String>,
731     str_style: Option<usize>,
732 ) -> (Vec<usize>, bool) {
733     let snippet = match snippet {
734         Some(ref s) if s.starts_with('"') || s.starts_with("r\"") || s.starts_with("r#") => s,
735         _ => return (vec![], false),
736     };
737
738     fn find_skips(snippet: &str, is_raw: bool) -> Vec<usize> {
739         let mut s = snippet.char_indices().peekable();
740         let mut skips = vec![];
741         while let Some((pos, c)) = s.next() {
742             match (c, s.peek()) {
743                 // skip whitespace and empty lines ending in '\\'
744                 ('\\', Some((next_pos, '\n'))) if !is_raw => {
745                     skips.push(pos);
746                     skips.push(*next_pos);
747                     let _ = s.next();
748
749                     while let Some((pos, c)) = s.peek() {
750                         if matches!(c, ' ' | '\n' | '\t') {
751                             skips.push(*pos);
752                             let _ = s.next();
753                         } else {
754                             break;
755                         }
756                     }
757                 }
758                 ('\\', Some((next_pos, 'n' | 't' | 'r' | '0' | '\\' | '\'' | '\"'))) => {
759                     skips.push(*next_pos);
760                     let _ = s.next();
761                 }
762                 ('\\', Some((_, 'x'))) if !is_raw => {
763                     for _ in 0..3 {
764                         // consume `\xAB` literal
765                         if let Some((pos, _)) = s.next() {
766                             skips.push(pos);
767                         } else {
768                             break;
769                         }
770                     }
771                 }
772                 ('\\', Some((_, 'u'))) if !is_raw => {
773                     if let Some((pos, _)) = s.next() {
774                         skips.push(pos);
775                     }
776                     if let Some((next_pos, next_c)) = s.next() {
777                         if next_c == '{' {
778                             skips.push(next_pos);
779                             let mut i = 0; // consume up to 6 hexanumeric chars + closing `}`
780                             while let (Some((next_pos, c)), true) = (s.next(), i < 7) {
781                                 if c.is_digit(16) {
782                                     skips.push(next_pos);
783                                 } else if c == '}' {
784                                     skips.push(next_pos);
785                                     break;
786                                 } else {
787                                     break;
788                                 }
789                                 i += 1;
790                             }
791                         } else if next_c.is_digit(16) {
792                             skips.push(next_pos);
793                             // We suggest adding `{` and `}` when appropriate, accept it here as if
794                             // it were correct
795                             let mut i = 0; // consume up to 6 hexanumeric chars
796                             while let (Some((next_pos, c)), _) = (s.next(), i < 6) {
797                                 if c.is_digit(16) {
798                                     skips.push(next_pos);
799                                 } else {
800                                     break;
801                                 }
802                                 i += 1;
803                             }
804                         }
805                     }
806                 }
807                 _ => {}
808             }
809         }
810         skips
811     }
812
813     let r_start = str_style.map_or(0, |r| r + 1);
814     let r_end = str_style.unwrap_or(0);
815     let s = &snippet[r_start + 1..snippet.len() - r_end - 1];
816     (find_skips(s, str_style.is_some()), true)
817 }
818
819 #[cfg(test)]
820 mod tests;