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