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