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