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