]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse_format/src/lib.rs
Rollup merge of #93613 - crlf0710:rename_to_async_iter, r=yaahc
[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, InnerSpan),
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, InnerSpan),
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(&(start, c)) if rustc_lexer::is_id_start(c) => {
498                     let word = self.word();
499                     let end = start + word.len();
500                     let span = self.to_span_index(start).to(self.to_span_index(end));
501                     Some(ArgumentNamed(Symbol::intern(word), span))
502                 }
503
504                 // This is an `ArgumentNext`.
505                 // Record the fact and do the resolution after parsing the
506                 // format spec, to make things like `{:.*}` work.
507                 _ => None,
508             }
509         }
510     }
511
512     /// Parses a format specifier at the current position, returning all of the
513     /// relevant information in the `FormatSpec` struct.
514     fn format(&mut self) -> FormatSpec<'a> {
515         let mut spec = FormatSpec {
516             fill: None,
517             align: AlignUnknown,
518             flags: 0,
519             precision: CountImplied,
520             precision_span: None,
521             width: CountImplied,
522             width_span: None,
523             ty: &self.input[..0],
524             ty_span: None,
525         };
526         if !self.consume(':') {
527             return spec;
528         }
529
530         // fill character
531         if let Some(&(_, c)) = self.cur.peek() {
532             if let Some((_, '>' | '<' | '^')) = self.cur.clone().nth(1) {
533                 spec.fill = Some(c);
534                 self.cur.next();
535             }
536         }
537         // Alignment
538         if self.consume('<') {
539             spec.align = AlignLeft;
540         } else if self.consume('>') {
541             spec.align = AlignRight;
542         } else if self.consume('^') {
543             spec.align = AlignCenter;
544         }
545         // Sign flags
546         if self.consume('+') {
547             spec.flags |= 1 << (FlagSignPlus as u32);
548         } else if self.consume('-') {
549             spec.flags |= 1 << (FlagSignMinus as u32);
550         }
551         // Alternate marker
552         if self.consume('#') {
553             spec.flags |= 1 << (FlagAlternate as u32);
554         }
555         // Width and precision
556         let mut havewidth = false;
557
558         if self.consume('0') {
559             // small ambiguity with '0$' as a format string. In theory this is a
560             // '0' flag and then an ill-formatted format string with just a '$'
561             // and no count, but this is better if we instead interpret this as
562             // no '0' flag and '0$' as the width instead.
563             if self.consume('$') {
564                 spec.width = CountIsParam(0);
565                 havewidth = true;
566             } else {
567                 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
568             }
569         }
570         if !havewidth {
571             let width_span_start = if let Some((pos, _)) = self.cur.peek() { *pos } else { 0 };
572             let (w, sp) = self.count(width_span_start);
573             spec.width = w;
574             spec.width_span = sp;
575         }
576         if let Some(start) = self.consume_pos('.') {
577             if let Some(end) = self.consume_pos('*') {
578                 // Resolve `CountIsNextParam`.
579                 // We can do this immediately as `position` is resolved later.
580                 let i = self.curarg;
581                 self.curarg += 1;
582                 spec.precision = CountIsParam(i);
583                 spec.precision_span =
584                     Some(self.to_span_index(start).to(self.to_span_index(end + 1)));
585             } else {
586                 let (p, sp) = self.count(start);
587                 spec.precision = p;
588                 spec.precision_span = sp;
589             }
590         }
591         let ty_span_start = self.cur.peek().map(|(pos, _)| *pos);
592         // Optional radix followed by the actual format specifier
593         if self.consume('x') {
594             if self.consume('?') {
595                 spec.flags |= 1 << (FlagDebugLowerHex as u32);
596                 spec.ty = "?";
597             } else {
598                 spec.ty = "x";
599             }
600         } else if self.consume('X') {
601             if self.consume('?') {
602                 spec.flags |= 1 << (FlagDebugUpperHex as u32);
603                 spec.ty = "?";
604             } else {
605                 spec.ty = "X";
606             }
607         } else if self.consume('?') {
608             spec.ty = "?";
609         } else {
610             spec.ty = self.word();
611             let ty_span_end = self.cur.peek().map(|(pos, _)| *pos);
612             if !spec.ty.is_empty() {
613                 spec.ty_span = ty_span_start
614                     .and_then(|s| ty_span_end.map(|e| (s, e)))
615                     .map(|(start, end)| self.to_span_index(start).to(self.to_span_index(end)));
616             }
617         }
618         spec
619     }
620
621     /// Parses an inline assembly template modifier at the current position, returning the modifier
622     /// in the `ty` field of the `FormatSpec` struct.
623     fn inline_asm(&mut self) -> FormatSpec<'a> {
624         let mut spec = FormatSpec {
625             fill: None,
626             align: AlignUnknown,
627             flags: 0,
628             precision: CountImplied,
629             precision_span: None,
630             width: CountImplied,
631             width_span: None,
632             ty: &self.input[..0],
633             ty_span: None,
634         };
635         if !self.consume(':') {
636             return spec;
637         }
638
639         let ty_span_start = self.cur.peek().map(|(pos, _)| *pos);
640         spec.ty = self.word();
641         let ty_span_end = self.cur.peek().map(|(pos, _)| *pos);
642         if !spec.ty.is_empty() {
643             spec.ty_span = ty_span_start
644                 .and_then(|s| ty_span_end.map(|e| (s, e)))
645                 .map(|(start, end)| self.to_span_index(start).to(self.to_span_index(end)));
646         }
647
648         spec
649     }
650
651     /// Parses a `Count` parameter at the current position. This does not check
652     /// for 'CountIsNextParam' because that is only used in precision, not
653     /// width.
654     fn count(&mut self, start: usize) -> (Count, Option<InnerSpan>) {
655         if let Some(i) = self.integer() {
656             if let Some(end) = self.consume_pos('$') {
657                 let span = self.to_span_index(start).to(self.to_span_index(end + 1));
658                 (CountIsParam(i), Some(span))
659             } else {
660                 (CountIs(i), None)
661             }
662         } else {
663             let tmp = self.cur.clone();
664             let word = self.word();
665             if word.is_empty() {
666                 self.cur = tmp;
667                 (CountImplied, None)
668             } else if let Some(end) = self.consume_pos('$') {
669                 let span = self.to_span_index(start + 1).to(self.to_span_index(end));
670                 (CountIsName(Symbol::intern(word), span), None)
671             } else {
672                 self.cur = tmp;
673                 (CountImplied, None)
674             }
675         }
676     }
677
678     /// Parses a word starting at the current position. A word is the same as
679     /// Rust identifier, except that it can't start with `_` character.
680     fn word(&mut self) -> &'a str {
681         let start = match self.cur.peek() {
682             Some(&(pos, c)) if rustc_lexer::is_id_start(c) => {
683                 self.cur.next();
684                 pos
685             }
686             _ => {
687                 return "";
688             }
689         };
690         let mut end = None;
691         while let Some(&(pos, c)) = self.cur.peek() {
692             if rustc_lexer::is_id_continue(c) {
693                 self.cur.next();
694             } else {
695                 end = Some(pos);
696                 break;
697             }
698         }
699         let end = end.unwrap_or(self.input.len());
700         let word = &self.input[start..end];
701         if word == "_" {
702             self.err_with_note(
703                 "invalid argument name `_`",
704                 "invalid argument name",
705                 "argument name cannot be a single underscore",
706                 self.to_span_index(start).to(self.to_span_index(end)),
707             );
708         }
709         word
710     }
711
712     /// Optionally parses an integer at the current position. This doesn't deal
713     /// with overflow at all, it's just accumulating digits.
714     fn integer(&mut self) -> Option<usize> {
715         let mut cur = 0;
716         let mut found = false;
717         while let Some(&(_, c)) = self.cur.peek() {
718             if let Some(i) = c.to_digit(10) {
719                 cur = cur * 10 + i as usize;
720                 found = true;
721                 self.cur.next();
722             } else {
723                 break;
724             }
725         }
726         found.then_some(cur)
727     }
728 }
729
730 /// Finds the indices of all characters that have been processed and differ between the actual
731 /// written code (code snippet) and the `InternedString` that gets processed in the `Parser`
732 /// in order to properly synthethise the intra-string `Span`s for error diagnostics.
733 fn find_skips_from_snippet(
734     snippet: Option<string::String>,
735     str_style: Option<usize>,
736 ) -> (Vec<usize>, bool) {
737     let snippet = match snippet {
738         Some(ref s) if s.starts_with('"') || s.starts_with("r\"") || s.starts_with("r#") => s,
739         _ => return (vec![], false),
740     };
741
742     fn find_skips(snippet: &str, is_raw: bool) -> Vec<usize> {
743         let mut s = snippet.char_indices().peekable();
744         let mut skips = vec![];
745         while let Some((pos, c)) = s.next() {
746             match (c, s.peek()) {
747                 // skip whitespace and empty lines ending in '\\'
748                 ('\\', Some((next_pos, '\n'))) if !is_raw => {
749                     skips.push(pos);
750                     skips.push(*next_pos);
751                     let _ = s.next();
752
753                     while let Some((pos, c)) = s.peek() {
754                         if matches!(c, ' ' | '\n' | '\t') {
755                             skips.push(*pos);
756                             let _ = s.next();
757                         } else {
758                             break;
759                         }
760                     }
761                 }
762                 ('\\', Some((next_pos, 'n' | 't' | 'r' | '0' | '\\' | '\'' | '\"'))) => {
763                     skips.push(*next_pos);
764                     let _ = s.next();
765                 }
766                 ('\\', Some((_, 'x'))) if !is_raw => {
767                     for _ in 0..3 {
768                         // consume `\xAB` literal
769                         if let Some((pos, _)) = s.next() {
770                             skips.push(pos);
771                         } else {
772                             break;
773                         }
774                     }
775                 }
776                 ('\\', Some((_, 'u'))) if !is_raw => {
777                     if let Some((pos, _)) = s.next() {
778                         skips.push(pos);
779                     }
780                     if let Some((next_pos, next_c)) = s.next() {
781                         if next_c == '{' {
782                             skips.push(next_pos);
783                             let mut i = 0; // consume up to 6 hexanumeric chars + closing `}`
784                             while let (Some((next_pos, c)), true) = (s.next(), i < 7) {
785                                 if c.is_digit(16) {
786                                     skips.push(next_pos);
787                                 } else if c == '}' {
788                                     skips.push(next_pos);
789                                     break;
790                                 } else {
791                                     break;
792                                 }
793                                 i += 1;
794                             }
795                         } else if next_c.is_digit(16) {
796                             skips.push(next_pos);
797                             // We suggest adding `{` and `}` when appropriate, accept it here as if
798                             // it were correct
799                             let mut i = 0; // consume up to 6 hexanumeric chars
800                             while let (Some((next_pos, c)), _) = (s.next(), i < 6) {
801                                 if c.is_digit(16) {
802                                     skips.push(next_pos);
803                                 } else {
804                                     break;
805                                 }
806                                 i += 1;
807                             }
808                         }
809                     }
810                 }
811                 _ => {}
812             }
813         }
814         skips
815     }
816
817     let r_start = str_style.map_or(0, |r| r + 1);
818     let r_end = str_style.unwrap_or(0);
819     let s = &snippet[r_start + 1..snippet.len() - r_end - 1];
820     (find_skips(s, str_style.is_some()), true)
821 }
822
823 #[cfg(test)]
824 mod tests;