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