]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse_format/lib.rs
Rollup merge of #72497 - RalfJung:tag-term, r=oli-obk
[rust.git] / src / librustc_parse_format / 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/",
9     html_playground_url = "https://play.rust-lang.org/",
10     test(attr(deny(warnings)))
11 )]
12 #![feature(nll)]
13 #![feature(or_patterns)]
14 #![feature(rustc_private)]
15 #![feature(unicode_internals)]
16 #![feature(bool_to_option)]
17
18 pub use Alignment::*;
19 pub use Count::*;
20 pub use Flag::*;
21 pub use Piece::*;
22 pub use Position::*;
23
24 use std::iter;
25 use std::str;
26 use std::string;
27
28 use rustc_span::{InnerSpan, Symbol};
29
30 /// The type of format string that we are parsing.
31 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
32 pub enum ParseMode {
33     /// A normal format string as per `format_args!`.
34     Format,
35     /// An inline assembly template string for `asm!`.
36     InlineAsm,
37 }
38
39 #[derive(Copy, Clone)]
40 struct InnerOffset(usize);
41
42 impl InnerOffset {
43     fn to(self, end: InnerOffset) -> InnerSpan {
44         InnerSpan::new(self.0, end.0)
45     }
46 }
47
48 /// A piece is a portion of the format string which represents the next part
49 /// to emit. These are emitted as a stream by the `Parser` class.
50 #[derive(Copy, Clone, Debug, PartialEq)]
51 pub enum Piece<'a> {
52     /// A literal string which should directly be emitted
53     String(&'a str),
54     /// This describes that formatting should process the next argument (as
55     /// specified inside) for emission.
56     NextArgument(Argument<'a>),
57 }
58
59 /// Representation of an argument specification.
60 #[derive(Copy, Clone, Debug, PartialEq)]
61 pub struct Argument<'a> {
62     /// Where to find this argument
63     pub position: Position,
64     /// How to format the argument
65     pub format: FormatSpec<'a>,
66 }
67
68 /// Specification for the formatting of an argument in the format string.
69 #[derive(Copy, Clone, Debug, PartialEq)]
70 pub struct FormatSpec<'a> {
71     /// Optionally specified character to fill alignment with.
72     pub fill: Option<char>,
73     /// Optionally specified alignment.
74     pub align: Alignment,
75     /// Packed version of various flags provided.
76     pub flags: u32,
77     /// The integer precision to use.
78     pub precision: Count,
79     /// The span of the precision formatting flag (for diagnostics).
80     pub precision_span: Option<InnerSpan>,
81     /// The string width requested for the resulting format.
82     pub width: Count,
83     /// The span of the width formatting flag (for diagnostics).
84     pub width_span: Option<InnerSpan>,
85     /// The descriptor string representing the name of the format desired for
86     /// this argument, this can be empty or any number of characters, although
87     /// it is required to be one word.
88     pub ty: &'a str,
89     /// The span of the descriptor string (for diagnostics).
90     pub ty_span: Option<InnerSpan>,
91 }
92
93 /// Enum describing where an argument for a format can be located.
94 #[derive(Copy, Clone, Debug, PartialEq)]
95 pub enum Position {
96     /// The argument is implied to be located at an index
97     ArgumentImplicitlyIs(usize),
98     /// The argument is located at a specific index given in the format
99     ArgumentIs(usize),
100     /// The argument has a name.
101     ArgumentNamed(Symbol),
102 }
103
104 impl Position {
105     pub fn index(&self) -> Option<usize> {
106         match self {
107             ArgumentIs(i) | ArgumentImplicitlyIs(i) => Some(*i),
108             _ => None,
109         }
110     }
111 }
112
113 /// Enum of alignments which are supported.
114 #[derive(Copy, Clone, Debug, PartialEq)]
115 pub enum Alignment {
116     /// The value will be aligned to the left.
117     AlignLeft,
118     /// The value will be aligned to the right.
119     AlignRight,
120     /// The value will be aligned in the center.
121     AlignCenter,
122     /// The value will take on a default alignment.
123     AlignUnknown,
124 }
125
126 /// Various flags which can be applied to format strings. The meaning of these
127 /// flags is defined by the formatters themselves.
128 #[derive(Copy, Clone, Debug, PartialEq)]
129 pub enum Flag {
130     /// A `+` will be used to denote positive numbers.
131     FlagSignPlus,
132     /// A `-` will be used to denote negative numbers. This is the default.
133     FlagSignMinus,
134     /// An alternate form will be used for the value. In the case of numbers,
135     /// this means that the number will be prefixed with the supplied string.
136     FlagAlternate,
137     /// For numbers, this means that the number will be padded with zeroes,
138     /// and the sign (`+` or `-`) will precede them.
139     FlagSignAwareZeroPad,
140     /// For Debug / `?`, format integers in lower-case hexadecimal.
141     FlagDebugLowerHex,
142     /// For Debug / `?`, format integers in upper-case hexadecimal.
143     FlagDebugUpperHex,
144 }
145
146 /// A count is used for the precision and width parameters of an integer, and
147 /// can reference either an argument or a literal integer.
148 #[derive(Copy, Clone, Debug, PartialEq)]
149 pub enum Count {
150     /// The count is specified explicitly.
151     CountIs(usize),
152     /// The count is specified by the argument with the given name.
153     CountIsName(Symbol),
154     /// The count is specified by the argument at the given index.
155     CountIsParam(usize),
156     /// The count is implied and cannot be explicitly specified.
157     CountImplied,
158 }
159
160 pub struct ParseError {
161     pub description: string::String,
162     pub note: Option<string::String>,
163     pub label: string::String,
164     pub span: InnerSpan,
165     pub secondary_label: Option<(string::String, InnerSpan)>,
166 }
167
168 /// The parser structure for interpreting the input format string. This is
169 /// modeled as an iterator over `Piece` structures to form a stream of tokens
170 /// being output.
171 ///
172 /// This is a recursive-descent parser for the sake of simplicity, and if
173 /// necessary there's probably lots of room for improvement performance-wise.
174 pub struct Parser<'a> {
175     mode: ParseMode,
176     input: &'a str,
177     cur: iter::Peekable<str::CharIndices<'a>>,
178     /// Error messages accumulated during parsing
179     pub errors: Vec<ParseError>,
180     /// Current position of implicit positional argument pointer
181     curarg: usize,
182     /// `Some(raw count)` when the string is "raw", used to position spans correctly
183     style: Option<usize>,
184     /// Start and end byte offset of every successfully parsed argument
185     pub arg_places: Vec<InnerSpan>,
186     /// Characters that need to be shifted
187     skips: Vec<usize>,
188     /// Span of the last opening brace seen, used for error reporting
189     last_opening_brace: Option<InnerSpan>,
190     /// Whether the source string is comes from `println!` as opposed to `format!` or `print!`
191     append_newline: bool,
192     /// Whether this formatting string is a literal or it comes from a macro.
193     is_literal: bool,
194     /// Start position of the current line.
195     cur_line_start: usize,
196     /// Start and end byte offset of every line of the format string. Excludes
197     /// newline characters and leading whitespace.
198     pub line_spans: Vec<InnerSpan>,
199 }
200
201 impl<'a> Iterator for Parser<'a> {
202     type Item = Piece<'a>;
203
204     fn next(&mut self) -> Option<Piece<'a>> {
205         if let Some(&(pos, c)) = self.cur.peek() {
206             match c {
207                 '{' => {
208                     let curr_last_brace = self.last_opening_brace;
209                     let byte_pos = self.to_span_index(pos);
210                     self.last_opening_brace = Some(byte_pos.to(InnerOffset(byte_pos.0 + 1)));
211                     self.cur.next();
212                     if self.consume('{') {
213                         self.last_opening_brace = curr_last_brace;
214
215                         Some(String(self.string(pos + 1)))
216                     } else {
217                         let arg = self.argument();
218                         if let Some(end) = self.must_consume('}') {
219                             let start = self.to_span_index(pos);
220                             let end = self.to_span_index(end + 1);
221                             if self.is_literal {
222                                 self.arg_places.push(start.to(end));
223                             }
224                         }
225                         Some(NextArgument(arg))
226                     }
227                 }
228                 '}' => {
229                     self.cur.next();
230                     if self.consume('}') {
231                         Some(String(self.string(pos + 1)))
232                     } else {
233                         let err_pos = self.to_span_index(pos);
234                         self.err_with_note(
235                             "unmatched `}` found",
236                             "unmatched `}`",
237                             "if you intended to print `}`, you can escape it using `}}`",
238                             err_pos.to(err_pos),
239                         );
240                         None
241                     }
242                 }
243                 _ => Some(String(self.string(pos))),
244             }
245         } else {
246             if self.is_literal && self.cur_line_start != self.input.len() {
247                 let start = self.to_span_index(self.cur_line_start);
248                 let end = self.to_span_index(self.input.len());
249                 self.line_spans.push(start.to(end));
250                 self.cur_line_start = self.input.len();
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(|raw| raw + 1).unwrap_or(0);
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             match self.cur.clone().nth(1) {
529                 Some((_, '>' | '<' | '^')) => {
530                     spec.fill = Some(c);
531                     self.cur.next();
532                 }
533                 _ => {}
534             }
535         }
536         // Alignment
537         if self.consume('<') {
538             spec.align = AlignLeft;
539         } else if self.consume('>') {
540             spec.align = AlignRight;
541         } else if self.consume('^') {
542             spec.align = AlignCenter;
543         }
544         // Sign flags
545         if self.consume('+') {
546             spec.flags |= 1 << (FlagSignPlus as u32);
547         } else if self.consume('-') {
548             spec.flags |= 1 << (FlagSignMinus as u32);
549         }
550         // Alternate marker
551         if self.consume('#') {
552             spec.flags |= 1 << (FlagAlternate as u32);
553         }
554         // Width and precision
555         let mut havewidth = false;
556
557         if self.consume('0') {
558             // small ambiguity with '0$' as a format string. In theory this is a
559             // '0' flag and then an ill-formatted format string with just a '$'
560             // and no count, but this is better if we instead interpret this as
561             // no '0' flag and '0$' as the width instead.
562             if self.consume('$') {
563                 spec.width = CountIsParam(0);
564                 havewidth = true;
565             } else {
566                 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
567             }
568         }
569         if !havewidth {
570             let width_span_start = if let Some((pos, _)) = self.cur.peek() { *pos } else { 0 };
571             let (w, sp) = self.count(width_span_start);
572             spec.width = w;
573             spec.width_span = sp;
574         }
575         if let Some(start) = self.consume_pos('.') {
576             if let Some(end) = self.consume_pos('*') {
577                 // Resolve `CountIsNextParam`.
578                 // We can do this immediately as `position` is resolved later.
579                 let i = self.curarg;
580                 self.curarg += 1;
581                 spec.precision = CountIsParam(i);
582                 spec.precision_span =
583                     Some(self.to_span_index(start).to(self.to_span_index(end + 1)));
584             } else {
585                 let (p, sp) = self.count(start);
586                 spec.precision = p;
587                 spec.precision_span = sp;
588             }
589         }
590         let ty_span_start = self.cur.peek().map(|(pos, _)| *pos);
591         // Optional radix followed by the actual format specifier
592         if self.consume('x') {
593             if self.consume('?') {
594                 spec.flags |= 1 << (FlagDebugLowerHex as u32);
595                 spec.ty = "?";
596             } else {
597                 spec.ty = "x";
598             }
599         } else if self.consume('X') {
600             if self.consume('?') {
601                 spec.flags |= 1 << (FlagDebugUpperHex as u32);
602                 spec.ty = "?";
603             } else {
604                 spec.ty = "X";
605             }
606         } else if self.consume('?') {
607             spec.ty = "?";
608         } else {
609             spec.ty = self.word();
610             let ty_span_end = self.cur.peek().map(|(pos, _)| *pos);
611             if !spec.ty.is_empty() {
612                 spec.ty_span = ty_span_start
613                     .and_then(|s| ty_span_end.map(|e| (s, e)))
614                     .map(|(start, end)| self.to_span_index(start).to(self.to_span_index(end)));
615             }
616         }
617         spec
618     }
619
620     /// Parses an inline assembly template modifier at the current position, returning the modifier
621     /// in the `ty` field of the `FormatSpec` struct.
622     fn inline_asm(&mut self) -> FormatSpec<'a> {
623         let mut spec = FormatSpec {
624             fill: None,
625             align: AlignUnknown,
626             flags: 0,
627             precision: CountImplied,
628             precision_span: None,
629             width: CountImplied,
630             width_span: None,
631             ty: &self.input[..0],
632             ty_span: None,
633         };
634         if !self.consume(':') {
635             return spec;
636         }
637
638         let ty_span_start = self.cur.peek().map(|(pos, _)| *pos);
639         spec.ty = self.word();
640         let ty_span_end = self.cur.peek().map(|(pos, _)| *pos);
641         if !spec.ty.is_empty() {
642             spec.ty_span = ty_span_start
643                 .and_then(|s| ty_span_end.map(|e| (s, e)))
644                 .map(|(start, end)| self.to_span_index(start).to(self.to_span_index(end)));
645         }
646
647         spec
648     }
649
650     /// Parses a `Count` parameter at the current position. This does not check
651     /// for 'CountIsNextParam' because that is only used in precision, not
652     /// width.
653     fn count(&mut self, start: usize) -> (Count, Option<InnerSpan>) {
654         if let Some(i) = self.integer() {
655             if let Some(end) = self.consume_pos('$') {
656                 let span = self.to_span_index(start).to(self.to_span_index(end + 1));
657                 (CountIsParam(i), Some(span))
658             } else {
659                 (CountIs(i), None)
660             }
661         } else {
662             let tmp = self.cur.clone();
663             let word = self.word();
664             if word.is_empty() {
665                 self.cur = tmp;
666                 (CountImplied, None)
667             } else if self.consume('$') {
668                 (CountIsName(Symbol::intern(word)), None)
669             } else {
670                 self.cur = tmp;
671                 (CountImplied, None)
672             }
673         }
674     }
675
676     /// Parses a word starting at the current position. A word is the same as
677     /// Rust identifier, except that it can't start with `_` character.
678     fn word(&mut self) -> &'a str {
679         let start = match self.cur.peek() {
680             Some(&(pos, c)) if rustc_lexer::is_id_start(c) => {
681                 self.cur.next();
682                 pos
683             }
684             _ => {
685                 return "";
686             }
687         };
688         let mut end = None;
689         while let Some(&(pos, c)) = self.cur.peek() {
690             if rustc_lexer::is_id_continue(c) {
691                 self.cur.next();
692             } else {
693                 end = Some(pos);
694                 break;
695             }
696         }
697         let end = end.unwrap_or(self.input.len());
698         let word = &self.input[start..end];
699         if word == "_" {
700             self.err_with_note(
701                 "invalid argument name `_`",
702                 "invalid argument name",
703                 "argument name cannot be a single underscore",
704                 self.to_span_index(start).to(self.to_span_index(end)),
705             );
706         }
707         word
708     }
709
710     /// Optionally parses an integer at the current position. This doesn't deal
711     /// with overflow at all, it's just accumulating digits.
712     fn integer(&mut self) -> Option<usize> {
713         let mut cur = 0;
714         let mut found = false;
715         while let Some(&(_, c)) = self.cur.peek() {
716             if let Some(i) = c.to_digit(10) {
717                 cur = cur * 10 + i as usize;
718                 found = true;
719                 self.cur.next();
720             } else {
721                 break;
722             }
723         }
724         found.then_some(cur)
725     }
726 }
727
728 /// Finds the indices of all characters that have been processed and differ between the actual
729 /// written code (code snippet) and the `InternedString` that gets processed in the `Parser`
730 /// in order to properly synthethise the intra-string `Span`s for error diagnostics.
731 fn find_skips_from_snippet(
732     snippet: Option<string::String>,
733     str_style: Option<usize>,
734 ) -> (Vec<usize>, bool) {
735     let snippet = match snippet {
736         Some(ref s) if s.starts_with('"') || s.starts_with("r#") => s,
737         _ => return (vec![], false),
738     };
739
740     fn find_skips(snippet: &str, is_raw: bool) -> Vec<usize> {
741         let mut eat_ws = false;
742         let mut s = snippet.chars().enumerate().peekable();
743         let mut skips = vec![];
744         while let Some((pos, c)) = s.next() {
745             match (c, s.peek()) {
746                 // skip whitespace and empty lines ending in '\\'
747                 ('\\', Some((next_pos, '\n'))) if !is_raw => {
748                     eat_ws = true;
749                     skips.push(pos);
750                     skips.push(*next_pos);
751                     let _ = s.next();
752                 }
753                 ('\\', Some((next_pos, '\n' | 'n' | 't'))) if eat_ws => {
754                     skips.push(pos);
755                     skips.push(*next_pos);
756                     let _ = s.next();
757                 }
758                 (' ' | '\n' | '\t', _) if eat_ws => {
759                     skips.push(pos);
760                 }
761                 ('\\', Some((next_pos, 'n' | 't' | '0' | '\\' | '\'' | '\"'))) => {
762                     skips.push(*next_pos);
763                     let _ = s.next();
764                 }
765                 ('\\', Some((_, 'x'))) if !is_raw => {
766                     for _ in 0..3 {
767                         // consume `\xAB` literal
768                         if let Some((pos, _)) = s.next() {
769                             skips.push(pos);
770                         } else {
771                             break;
772                         }
773                     }
774                 }
775                 ('\\', Some((_, 'u'))) if !is_raw => {
776                     if let Some((pos, _)) = s.next() {
777                         skips.push(pos);
778                     }
779                     if let Some((next_pos, next_c)) = s.next() {
780                         if next_c == '{' {
781                             skips.push(next_pos);
782                             let mut i = 0; // consume up to 6 hexanumeric chars + closing `}`
783                             while let (Some((next_pos, c)), true) = (s.next(), i < 7) {
784                                 if c.is_digit(16) {
785                                     skips.push(next_pos);
786                                 } else if c == '}' {
787                                     skips.push(next_pos);
788                                     break;
789                                 } else {
790                                     break;
791                                 }
792                                 i += 1;
793                             }
794                         } else if next_c.is_digit(16) {
795                             skips.push(next_pos);
796                             // We suggest adding `{` and `}` when appropriate, accept it here as if
797                             // it were correct
798                             let mut i = 0; // consume up to 6 hexanumeric chars
799                             while let (Some((next_pos, c)), _) = (s.next(), i < 6) {
800                                 if c.is_digit(16) {
801                                     skips.push(next_pos);
802                                 } else {
803                                     break;
804                                 }
805                                 i += 1;
806                             }
807                         }
808                     }
809                 }
810                 _ if eat_ws => {
811                     // `take_while(|c| c.is_whitespace())`
812                     eat_ws = false;
813                 }
814                 _ => {}
815             }
816         }
817         skips
818     }
819
820     let r_start = str_style.map(|r| r + 1).unwrap_or(0);
821     let r_end = str_style.map(|r| r).unwrap_or(0);
822     let s = &snippet[r_start + 1..snippet.len() - r_end - 1];
823     (find_skips(s, str_style.is_some()), true)
824 }
825
826 #[cfg(test)]
827 mod tests;