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