]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse_format/lib.rs
Auto merge of #72717 - poliorcetics:try-from-int-to-nzint, r=dtolnay
[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     pub 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 {
247                 let start = self.to_span_index(self.cur_line_start);
248                 let end = self.to_span_index(self.input.len());
249                 let span = start.to(end);
250                 if self.line_spans.last() != Some(&span) {
251                     self.line_spans.push(span);
252                 }
253             }
254             None
255         }
256     }
257 }
258
259 impl<'a> Parser<'a> {
260     /// Creates a new parser for the given format string
261     pub fn new(
262         s: &'a str,
263         style: Option<usize>,
264         snippet: Option<string::String>,
265         append_newline: bool,
266         mode: ParseMode,
267     ) -> Parser<'a> {
268         let (skips, is_literal) = find_skips_from_snippet(snippet, style);
269         Parser {
270             mode,
271             input: s,
272             cur: s.char_indices().peekable(),
273             errors: vec![],
274             curarg: 0,
275             style,
276             arg_places: vec![],
277             skips,
278             last_opening_brace: None,
279             append_newline,
280             is_literal,
281             cur_line_start: 0,
282             line_spans: vec![],
283         }
284     }
285
286     /// Notifies of an error. The message doesn't actually need to be of type
287     /// String, but I think it does when this eventually uses conditions so it
288     /// might as well start using it now.
289     fn err<S1: Into<string::String>, S2: Into<string::String>>(
290         &mut self,
291         description: S1,
292         label: S2,
293         span: InnerSpan,
294     ) {
295         self.errors.push(ParseError {
296             description: description.into(),
297             note: None,
298             label: label.into(),
299             span,
300             secondary_label: None,
301         });
302     }
303
304     /// Notifies of an error. The message doesn't actually need to be of type
305     /// String, but I think it does when this eventually uses conditions so it
306     /// might as well start using it now.
307     fn err_with_note<
308         S1: Into<string::String>,
309         S2: Into<string::String>,
310         S3: Into<string::String>,
311     >(
312         &mut self,
313         description: S1,
314         label: S2,
315         note: S3,
316         span: InnerSpan,
317     ) {
318         self.errors.push(ParseError {
319             description: description.into(),
320             note: Some(note.into()),
321             label: label.into(),
322             span,
323             secondary_label: None,
324         });
325     }
326
327     /// Optionally consumes the specified character. If the character is not at
328     /// the current position, then the current iterator isn't moved and `false` is
329     /// returned, otherwise the character is consumed and `true` is returned.
330     fn consume(&mut self, c: char) -> bool {
331         self.consume_pos(c).is_some()
332     }
333
334     /// Optionally consumes the specified character. If the character is not at
335     /// the current position, then the current iterator isn't moved and `None` is
336     /// returned, otherwise the character is consumed and the current position is
337     /// returned.
338     fn consume_pos(&mut self, c: char) -> Option<usize> {
339         if let Some(&(pos, maybe)) = self.cur.peek() {
340             if c == maybe {
341                 self.cur.next();
342                 return Some(pos);
343             }
344         }
345         None
346     }
347
348     fn to_span_index(&self, pos: usize) -> InnerOffset {
349         let mut pos = pos;
350         // This handles the raw string case, the raw argument is the number of #
351         // in r###"..."### (we need to add one because of the `r`).
352         let raw = self.style.map(|raw| raw + 1).unwrap_or(0);
353         for skip in &self.skips {
354             if pos > *skip {
355                 pos += 1;
356             } else if pos == *skip && raw == 0 {
357                 pos += 1;
358             } else {
359                 break;
360             }
361         }
362         InnerOffset(raw + pos + 1)
363     }
364
365     /// Forces consumption of the specified character. If the character is not
366     /// found, an error is emitted.
367     fn must_consume(&mut self, c: char) -> Option<usize> {
368         self.ws();
369
370         if let Some(&(pos, maybe)) = self.cur.peek() {
371             if c == maybe {
372                 self.cur.next();
373                 Some(pos)
374             } else {
375                 let pos = self.to_span_index(pos);
376                 let description = format!("expected `'}}'`, found `{:?}`", maybe);
377                 let label = "expected `}`".to_owned();
378                 let (note, secondary_label) = if c == '}' {
379                     (
380                         Some(
381                             "if you intended to print `{`, you can escape it using `{{`".to_owned(),
382                         ),
383                         self.last_opening_brace
384                             .map(|sp| ("because of this opening brace".to_owned(), sp)),
385                     )
386                 } else {
387                     (None, None)
388                 };
389                 self.errors.push(ParseError {
390                     description,
391                     note,
392                     label,
393                     span: pos.to(pos),
394                     secondary_label,
395                 });
396                 None
397             }
398         } else {
399             let description = format!("expected `{:?}` but string was terminated", c);
400             // point at closing `"`
401             let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
402             let pos = self.to_span_index(pos);
403             if c == '}' {
404                 let label = format!("expected `{:?}`", c);
405                 let (note, secondary_label) = if c == '}' {
406                     (
407                         Some(
408                             "if you intended to print `{`, you can escape it using `{{`".to_owned(),
409                         ),
410                         self.last_opening_brace
411                             .map(|sp| ("because of this opening brace".to_owned(), sp)),
412                     )
413                 } else {
414                     (None, None)
415                 };
416                 self.errors.push(ParseError {
417                     description,
418                     note,
419                     label,
420                     span: pos.to(pos),
421                     secondary_label,
422                 });
423             } else {
424                 self.err(description, format!("expected `{:?}`", c), pos.to(pos));
425             }
426             None
427         }
428     }
429
430     /// Consumes all whitespace characters until the first non-whitespace character
431     fn ws(&mut self) {
432         while let Some(&(_, c)) = self.cur.peek() {
433             if c.is_whitespace() {
434                 self.cur.next();
435             } else {
436                 break;
437             }
438         }
439     }
440
441     /// Parses all of a string which is to be considered a "raw literal" in a
442     /// format string. This is everything outside of the braces.
443     fn string(&mut self, start: usize) -> &'a str {
444         // we may not consume the character, peek the iterator
445         while let Some(&(pos, c)) = self.cur.peek() {
446             match c {
447                 '{' | '}' => {
448                     return &self.input[start..pos];
449                 }
450                 '\n' if self.is_literal => {
451                     let start = self.to_span_index(self.cur_line_start);
452                     let end = self.to_span_index(pos);
453                     self.line_spans.push(start.to(end));
454                     self.cur_line_start = pos + 1;
455                     self.cur.next();
456                 }
457                 _ => {
458                     if self.is_literal && pos == self.cur_line_start && c.is_whitespace() {
459                         self.cur_line_start = pos + c.len_utf8();
460                     }
461                     self.cur.next();
462                 }
463             }
464         }
465         &self.input[start..self.input.len()]
466     }
467
468     /// Parses an `Argument` structure, or what's contained within braces inside the format string.
469     fn argument(&mut self) -> Argument<'a> {
470         let pos = self.position();
471         let format = match self.mode {
472             ParseMode::Format => self.format(),
473             ParseMode::InlineAsm => self.inline_asm(),
474         };
475
476         // Resolve position after parsing format spec.
477         let pos = match pos {
478             Some(position) => position,
479             None => {
480                 let i = self.curarg;
481                 self.curarg += 1;
482                 ArgumentImplicitlyIs(i)
483             }
484         };
485
486         Argument { position: pos, format }
487     }
488
489     /// Parses a positional argument for a format. This could either be an
490     /// integer index of an argument, a named argument, or a blank string.
491     /// Returns `Some(parsed_position)` if the position is not implicitly
492     /// consuming a macro argument, `None` if it's the case.
493     fn position(&mut self) -> Option<Position> {
494         if let Some(i) = self.integer() {
495             Some(ArgumentIs(i))
496         } else {
497             match self.cur.peek() {
498                 Some(&(_, c)) if rustc_lexer::is_id_start(c) => {
499                     Some(ArgumentNamed(Symbol::intern(self.word())))
500                 }
501
502                 // This is an `ArgumentNext`.
503                 // Record the fact and do the resolution after parsing the
504                 // format spec, to make things like `{:.*}` work.
505                 _ => None,
506             }
507         }
508     }
509
510     /// Parses a format specifier at the current position, returning all of the
511     /// relevant information in the `FormatSpec` struct.
512     fn format(&mut self) -> FormatSpec<'a> {
513         let mut spec = FormatSpec {
514             fill: None,
515             align: AlignUnknown,
516             flags: 0,
517             precision: CountImplied,
518             precision_span: None,
519             width: CountImplied,
520             width_span: None,
521             ty: &self.input[..0],
522             ty_span: None,
523         };
524         if !self.consume(':') {
525             return spec;
526         }
527
528         // fill character
529         if let Some(&(_, c)) = self.cur.peek() {
530             match self.cur.clone().nth(1) {
531                 Some((_, '>' | '<' | '^')) => {
532                     spec.fill = Some(c);
533                     self.cur.next();
534                 }
535                 _ => {}
536             }
537         }
538         // Alignment
539         if self.consume('<') {
540             spec.align = AlignLeft;
541         } else if self.consume('>') {
542             spec.align = AlignRight;
543         } else if self.consume('^') {
544             spec.align = AlignCenter;
545         }
546         // Sign flags
547         if self.consume('+') {
548             spec.flags |= 1 << (FlagSignPlus as u32);
549         } else if self.consume('-') {
550             spec.flags |= 1 << (FlagSignMinus as u32);
551         }
552         // Alternate marker
553         if self.consume('#') {
554             spec.flags |= 1 << (FlagAlternate as u32);
555         }
556         // Width and precision
557         let mut havewidth = false;
558
559         if self.consume('0') {
560             // small ambiguity with '0$' as a format string. In theory this is a
561             // '0' flag and then an ill-formatted format string with just a '$'
562             // and no count, but this is better if we instead interpret this as
563             // no '0' flag and '0$' as the width instead.
564             if self.consume('$') {
565                 spec.width = CountIsParam(0);
566                 havewidth = true;
567             } else {
568                 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
569             }
570         }
571         if !havewidth {
572             let width_span_start = if let Some((pos, _)) = self.cur.peek() { *pos } else { 0 };
573             let (w, sp) = self.count(width_span_start);
574             spec.width = w;
575             spec.width_span = sp;
576         }
577         if let Some(start) = self.consume_pos('.') {
578             if let Some(end) = self.consume_pos('*') {
579                 // Resolve `CountIsNextParam`.
580                 // We can do this immediately as `position` is resolved later.
581                 let i = self.curarg;
582                 self.curarg += 1;
583                 spec.precision = CountIsParam(i);
584                 spec.precision_span =
585                     Some(self.to_span_index(start).to(self.to_span_index(end + 1)));
586             } else {
587                 let (p, sp) = self.count(start);
588                 spec.precision = p;
589                 spec.precision_span = sp;
590             }
591         }
592         let ty_span_start = self.cur.peek().map(|(pos, _)| *pos);
593         // Optional radix followed by the actual format specifier
594         if self.consume('x') {
595             if self.consume('?') {
596                 spec.flags |= 1 << (FlagDebugLowerHex as u32);
597                 spec.ty = "?";
598             } else {
599                 spec.ty = "x";
600             }
601         } else if self.consume('X') {
602             if self.consume('?') {
603                 spec.flags |= 1 << (FlagDebugUpperHex as u32);
604                 spec.ty = "?";
605             } else {
606                 spec.ty = "X";
607             }
608         } else if self.consume('?') {
609             spec.ty = "?";
610         } else {
611             spec.ty = self.word();
612             let ty_span_end = self.cur.peek().map(|(pos, _)| *pos);
613             if !spec.ty.is_empty() {
614                 spec.ty_span = ty_span_start
615                     .and_then(|s| ty_span_end.map(|e| (s, e)))
616                     .map(|(start, end)| self.to_span_index(start).to(self.to_span_index(end)));
617             }
618         }
619         spec
620     }
621
622     /// Parses an inline assembly template modifier at the current position, returning the modifier
623     /// in the `ty` field of the `FormatSpec` struct.
624     fn inline_asm(&mut self) -> FormatSpec<'a> {
625         let mut spec = FormatSpec {
626             fill: None,
627             align: AlignUnknown,
628             flags: 0,
629             precision: CountImplied,
630             precision_span: None,
631             width: CountImplied,
632             width_span: None,
633             ty: &self.input[..0],
634             ty_span: None,
635         };
636         if !self.consume(':') {
637             return spec;
638         }
639
640         let ty_span_start = self.cur.peek().map(|(pos, _)| *pos);
641         spec.ty = self.word();
642         let ty_span_end = self.cur.peek().map(|(pos, _)| *pos);
643         if !spec.ty.is_empty() {
644             spec.ty_span = ty_span_start
645                 .and_then(|s| ty_span_end.map(|e| (s, e)))
646                 .map(|(start, end)| self.to_span_index(start).to(self.to_span_index(end)));
647         }
648
649         spec
650     }
651
652     /// Parses a `Count` parameter at the current position. This does not check
653     /// for 'CountIsNextParam' because that is only used in precision, not
654     /// width.
655     fn count(&mut self, start: usize) -> (Count, Option<InnerSpan>) {
656         if let Some(i) = self.integer() {
657             if let Some(end) = self.consume_pos('$') {
658                 let span = self.to_span_index(start).to(self.to_span_index(end + 1));
659                 (CountIsParam(i), Some(span))
660             } else {
661                 (CountIs(i), None)
662             }
663         } else {
664             let tmp = self.cur.clone();
665             let word = self.word();
666             if word.is_empty() {
667                 self.cur = tmp;
668                 (CountImplied, None)
669             } else if self.consume('$') {
670                 (CountIsName(Symbol::intern(word)), 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,
739         _ => return (vec![], false),
740     };
741
742     fn find_skips(snippet: &str, is_raw: bool) -> Vec<usize> {
743         let mut eat_ws = false;
744         let mut s = snippet.chars().enumerate().peekable();
745         let mut skips = vec![];
746         while let Some((pos, c)) = s.next() {
747             match (c, s.peek()) {
748                 // skip whitespace and empty lines ending in '\\'
749                 ('\\', Some((next_pos, '\n'))) if !is_raw => {
750                     eat_ws = true;
751                     skips.push(pos);
752                     skips.push(*next_pos);
753                     let _ = s.next();
754                 }
755                 ('\\', Some((next_pos, '\n' | 'n' | 't'))) if eat_ws => {
756                     skips.push(pos);
757                     skips.push(*next_pos);
758                     let _ = s.next();
759                 }
760                 (' ' | '\n' | '\t', _) if eat_ws => {
761                     skips.push(pos);
762                 }
763                 ('\\', Some((next_pos, 'n' | 't' | '0' | '\\' | '\'' | '\"'))) => {
764                     skips.push(*next_pos);
765                     let _ = s.next();
766                 }
767                 ('\\', Some((_, 'x'))) if !is_raw => {
768                     for _ in 0..3 {
769                         // consume `\xAB` literal
770                         if let Some((pos, _)) = s.next() {
771                             skips.push(pos);
772                         } else {
773                             break;
774                         }
775                     }
776                 }
777                 ('\\', Some((_, 'u'))) if !is_raw => {
778                     if let Some((pos, _)) = s.next() {
779                         skips.push(pos);
780                     }
781                     if let Some((next_pos, next_c)) = s.next() {
782                         if next_c == '{' {
783                             skips.push(next_pos);
784                             let mut i = 0; // consume up to 6 hexanumeric chars + closing `}`
785                             while let (Some((next_pos, c)), true) = (s.next(), i < 7) {
786                                 if c.is_digit(16) {
787                                     skips.push(next_pos);
788                                 } else if c == '}' {
789                                     skips.push(next_pos);
790                                     break;
791                                 } else {
792                                     break;
793                                 }
794                                 i += 1;
795                             }
796                         } else if next_c.is_digit(16) {
797                             skips.push(next_pos);
798                             // We suggest adding `{` and `}` when appropriate, accept it here as if
799                             // it were correct
800                             let mut i = 0; // consume up to 6 hexanumeric chars
801                             while let (Some((next_pos, c)), _) = (s.next(), i < 6) {
802                                 if c.is_digit(16) {
803                                     skips.push(next_pos);
804                                 } else {
805                                     break;
806                                 }
807                                 i += 1;
808                             }
809                         }
810                     }
811                 }
812                 _ if eat_ws => {
813                     // `take_while(|c| c.is_whitespace())`
814                     eat_ws = false;
815                 }
816                 _ => {}
817             }
818         }
819         skips
820     }
821
822     let r_start = str_style.map(|r| r + 1).unwrap_or(0);
823     let r_end = str_style.map(|r| r).unwrap_or(0);
824     let s = &snippet[r_start + 1..snippet.len() - r_end - 1];
825     (find_skips(s, str_style.is_some()), true)
826 }
827
828 #[cfg(test)]
829 mod tests;