Skip to main content

rustc_parse_format/
lib.rs

1//! Macro support for format strings
2//!
3//! These structures are used when parsing format strings for the compiler.
4//! Parsing does not happen at runtime: structures of `std::fmt::rt` are
5//! generated instead.
6
7// tidy-alphabetical-start
8// We want to be able to build this crate with a stable compiler,
9// so no `#![feature]` attributes should be added.
10#![deny(unstable_features)]
11#![doc(test(attr(deny(warnings), allow(internal_features))))]
12// tidy-alphabetical-end
13
14use std::ops::Range;
15
16pub use Alignment::*;
17pub use Count::*;
18pub use Position::*;
19
20/// The type of format string that we are parsing.
21#[derive(#[automatically_derived]
impl ::core::marker::Copy for ParseMode { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ParseMode {
    #[inline]
    fn clone(&self) -> ParseMode { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ParseMode {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ParseMode::Format => "Format",
                ParseMode::InlineAsm => "InlineAsm",
                ParseMode::Diagnostic => "Diagnostic",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for ParseMode {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for ParseMode {
    #[inline]
    fn eq(&self, other: &ParseMode) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
22pub enum ParseMode {
23    /// A normal format string as per `format_args!`.
24    Format,
25    /// An inline assembly template string for `asm!`.
26    InlineAsm,
27    /// A format string for use in diagnostic attributes.
28    ///
29    /// Similar to `format_args!`, however only named ("captured") arguments
30    /// are allowed, and no format modifiers are permitted.
31    Diagnostic,
32}
33
34/// A piece is a portion of the format string which represents the next part
35/// to emit. These are emitted as a stream by the `Parser` class.
36#[derive(#[automatically_derived]
impl<'input> ::core::clone::Clone for Piece<'input> {
    #[inline]
    fn clone(&self) -> Piece<'input> {
        match self {
            Piece::Lit(__self_0) =>
                Piece::Lit(::core::clone::Clone::clone(__self_0)),
            Piece::NextArgument(__self_0) =>
                Piece::NextArgument(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]
impl<'input> ::core::fmt::Debug for Piece<'input> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Piece::Lit(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Lit",
                    &__self_0),
            Piece::NextArgument(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "NextArgument", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<'input> ::core::cmp::PartialEq for Piece<'input> {
    #[inline]
    fn eq(&self, other: &Piece<'input>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (Piece::Lit(__self_0), Piece::Lit(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Piece::NextArgument(__self_0), Piece::NextArgument(__arg1_0))
                    => __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq)]
37pub enum Piece<'input> {
38    /// A literal string which should directly be emitted
39    Lit(&'input str),
40    /// This describes that formatting should process the next argument (as
41    /// specified inside) for emission.
42    NextArgument(Box<Argument<'input>>),
43}
44
45/// Representation of an argument specification.
46#[derive(#[automatically_derived]
impl<'input> ::core::clone::Clone for Argument<'input> {
    #[inline]
    fn clone(&self) -> Argument<'input> {
        Argument {
            position: ::core::clone::Clone::clone(&self.position),
            position_span: ::core::clone::Clone::clone(&self.position_span),
            format: ::core::clone::Clone::clone(&self.format),
        }
    }
}Clone, #[automatically_derived]
impl<'input> ::core::fmt::Debug for Argument<'input> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "Argument",
            "position", &self.position, "position_span", &self.position_span,
            "format", &&self.format)
    }
}Debug, #[automatically_derived]
impl<'input> ::core::cmp::PartialEq for Argument<'input> {
    #[inline]
    fn eq(&self, other: &Argument<'input>) -> bool {
        self.position == other.position &&
                self.position_span == other.position_span &&
            self.format == other.format
    }
}PartialEq)]
47pub struct Argument<'input> {
48    /// Where to find this argument
49    pub position: Position<'input>,
50    /// The span of the position indicator. Includes any whitespace in implicit
51    /// positions (`{  }`).
52    pub position_span: Range<usize>,
53    /// How to format the argument
54    pub format: FormatSpec<'input>,
55}
56
57impl<'input> Argument<'input> {
58    pub fn is_identifier(&self) -> bool {
59        #[allow(non_exhaustive_omitted_patterns)] match self.position {
    Position::ArgumentNamed(_) => true,
    _ => false,
}matches!(self.position, Position::ArgumentNamed(_)) && self.format == FormatSpec::default()
60    }
61}
62
63/// Specification for the formatting of an argument in the format string.
64#[derive(#[automatically_derived]
impl<'input> ::core::clone::Clone for FormatSpec<'input> {
    #[inline]
    fn clone(&self) -> FormatSpec<'input> {
        FormatSpec {
            fill: ::core::clone::Clone::clone(&self.fill),
            fill_span: ::core::clone::Clone::clone(&self.fill_span),
            align: ::core::clone::Clone::clone(&self.align),
            sign: ::core::clone::Clone::clone(&self.sign),
            alternate: ::core::clone::Clone::clone(&self.alternate),
            zero_pad: ::core::clone::Clone::clone(&self.zero_pad),
            debug_hex: ::core::clone::Clone::clone(&self.debug_hex),
            precision: ::core::clone::Clone::clone(&self.precision),
            precision_span: ::core::clone::Clone::clone(&self.precision_span),
            width: ::core::clone::Clone::clone(&self.width),
            width_span: ::core::clone::Clone::clone(&self.width_span),
            ty: ::core::clone::Clone::clone(&self.ty),
            ty_span: ::core::clone::Clone::clone(&self.ty_span),
        }
    }
}Clone, #[automatically_derived]
impl<'input> ::core::fmt::Debug for FormatSpec<'input> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["fill", "fill_span", "align", "sign", "alternate", "zero_pad",
                        "debug_hex", "precision", "precision_span", "width",
                        "width_span", "ty", "ty_span"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.fill, &self.fill_span, &self.align, &self.sign,
                        &self.alternate, &self.zero_pad, &self.debug_hex,
                        &self.precision, &self.precision_span, &self.width,
                        &self.width_span, &self.ty, &&self.ty_span];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "FormatSpec",
            names, values)
    }
}Debug, #[automatically_derived]
impl<'input> ::core::cmp::PartialEq for FormatSpec<'input> {
    #[inline]
    fn eq(&self, other: &FormatSpec<'input>) -> bool {
        self.alternate == other.alternate && self.zero_pad == other.zero_pad
                                                    && self.fill == other.fill &&
                                                self.fill_span == other.fill_span &&
                                            self.align == other.align && self.sign == other.sign &&
                                    self.debug_hex == other.debug_hex &&
                                self.precision == other.precision &&
                            self.precision_span == other.precision_span &&
                        self.width == other.width &&
                    self.width_span == other.width_span && self.ty == other.ty
            && self.ty_span == other.ty_span
    }
}PartialEq, #[automatically_derived]
impl<'input> ::core::default::Default for FormatSpec<'input> {
    #[inline]
    fn default() -> FormatSpec<'input> {
        FormatSpec {
            fill: ::core::default::Default::default(),
            fill_span: ::core::default::Default::default(),
            align: ::core::default::Default::default(),
            sign: ::core::default::Default::default(),
            alternate: ::core::default::Default::default(),
            zero_pad: ::core::default::Default::default(),
            debug_hex: ::core::default::Default::default(),
            precision: ::core::default::Default::default(),
            precision_span: ::core::default::Default::default(),
            width: ::core::default::Default::default(),
            width_span: ::core::default::Default::default(),
            ty: ::core::default::Default::default(),
            ty_span: ::core::default::Default::default(),
        }
    }
}Default)]
65pub struct FormatSpec<'input> {
66    /// Optionally specified character to fill alignment with.
67    pub fill: Option<char>,
68    /// Span of the optionally specified fill character.
69    pub fill_span: Option<Range<usize>>,
70    /// Optionally specified alignment.
71    pub align: Alignment,
72    /// The `+` or `-` flag.
73    pub sign: Option<Sign>,
74    /// The `#` flag.
75    pub alternate: bool,
76    /// The `0` flag.
77    pub zero_pad: bool,
78    /// The `x` or `X` flag. (Only for `Debug`.)
79    pub debug_hex: Option<DebugHex>,
80    /// The integer precision to use.
81    pub precision: Count<'input>,
82    /// The span of the precision formatting flag (for diagnostics).
83    pub precision_span: Option<Range<usize>>,
84    /// The string width requested for the resulting format.
85    pub width: Count<'input>,
86    /// The span of the width formatting flag (for diagnostics).
87    pub width_span: Option<Range<usize>>,
88    /// The descriptor string representing the name of the format desired for
89    /// this argument, this can be empty or any number of characters, although
90    /// it is required to be one word.
91    pub ty: &'input str,
92    /// The span of the descriptor string (for diagnostics).
93    pub ty_span: Option<Range<usize>>,
94}
95
96/// Enum describing where an argument for a format can be located.
97#[derive(#[automatically_derived]
impl<'input> ::core::clone::Clone for Position<'input> {
    #[inline]
    fn clone(&self) -> Position<'input> {
        match self {
            Position::ArgumentImplicitlyIs(__self_0) =>
                Position::ArgumentImplicitlyIs(::core::clone::Clone::clone(__self_0)),
            Position::ArgumentIs(__self_0) =>
                Position::ArgumentIs(::core::clone::Clone::clone(__self_0)),
            Position::ArgumentNamed(__self_0) =>
                Position::ArgumentNamed(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]
impl<'input> ::core::fmt::Debug for Position<'input> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Position::ArgumentImplicitlyIs(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ArgumentImplicitlyIs", &__self_0),
            Position::ArgumentIs(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ArgumentIs", &__self_0),
            Position::ArgumentNamed(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ArgumentNamed", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<'input> ::core::cmp::PartialEq for Position<'input> {
    #[inline]
    fn eq(&self, other: &Position<'input>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (Position::ArgumentImplicitlyIs(__self_0),
                    Position::ArgumentImplicitlyIs(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Position::ArgumentIs(__self_0),
                    Position::ArgumentIs(__arg1_0)) => __self_0 == __arg1_0,
                (Position::ArgumentNamed(__self_0),
                    Position::ArgumentNamed(__arg1_0)) => __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq)]
98pub enum Position<'input> {
99    /// The argument is implied to be located at an index
100    ArgumentImplicitlyIs(usize),
101    /// The argument is located at a specific index given in the format,
102    ArgumentIs(usize),
103    /// The argument has a name.
104    ArgumentNamed(&'input str),
105}
106
107impl Position<'_> {
108    pub fn index(&self) -> Option<usize> {
109        match self {
110            ArgumentIs(i, ..) | ArgumentImplicitlyIs(i) => Some(*i),
111            _ => None,
112        }
113    }
114}
115
116/// Enum of alignments which are supported.
117#[derive(#[automatically_derived]
impl ::core::marker::Copy for Alignment { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Alignment {
    #[inline]
    fn clone(&self) -> Alignment { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Alignment {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                Alignment::AlignLeft => "AlignLeft",
                Alignment::AlignRight => "AlignRight",
                Alignment::AlignCenter => "AlignCenter",
                Alignment::AlignUnknown => "AlignUnknown",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for Alignment {
    #[inline]
    fn eq(&self, other: &Alignment) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::default::Default for Alignment {
    #[inline]
    fn default() -> Alignment { Self::AlignUnknown }
}Default)]
118pub enum Alignment {
119    /// The value will be aligned to the left.
120    AlignLeft,
121    /// The value will be aligned to the right.
122    AlignRight,
123    /// The value will be aligned in the center.
124    AlignCenter,
125    /// The value will take on a default alignment.
126    #[default]
127    AlignUnknown,
128}
129
130/// Enum for the sign flags.
131#[derive(#[automatically_derived]
impl ::core::marker::Copy for Sign { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Sign {
    #[inline]
    fn clone(&self) -> Sign { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Sign {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self { Sign::Plus => "Plus", Sign::Minus => "Minus", })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for Sign {
    #[inline]
    fn eq(&self, other: &Sign) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
132pub enum Sign {
133    /// The `+` flag.
134    Plus,
135    /// The `-` flag.
136    Minus,
137}
138
139/// Enum for the debug hex flags.
140#[derive(#[automatically_derived]
impl ::core::marker::Copy for DebugHex { }Copy, #[automatically_derived]
impl ::core::clone::Clone for DebugHex {
    #[inline]
    fn clone(&self) -> DebugHex { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for DebugHex {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                DebugHex::Lower => "Lower",
                DebugHex::Upper => "Upper",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for DebugHex {
    #[inline]
    fn eq(&self, other: &DebugHex) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
141pub enum DebugHex {
142    /// The `x` flag in `{:x?}`.
143    Lower,
144    /// The `X` flag in `{:X?}`.
145    Upper,
146}
147
148/// A count is used for the precision and width parameters of an integer, and
149/// can reference either an argument or a literal integer.
150#[derive(#[automatically_derived]
impl<'input> ::core::clone::Clone for Count<'input> {
    #[inline]
    fn clone(&self) -> Count<'input> {
        match self {
            Count::CountIs(__self_0) =>
                Count::CountIs(::core::clone::Clone::clone(__self_0)),
            Count::CountIsName(__self_0, __self_1) =>
                Count::CountIsName(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            Count::CountIsParam(__self_0) =>
                Count::CountIsParam(::core::clone::Clone::clone(__self_0)),
            Count::CountIsStar(__self_0) =>
                Count::CountIsStar(::core::clone::Clone::clone(__self_0)),
            Count::CountImplied => Count::CountImplied,
        }
    }
}Clone, #[automatically_derived]
impl<'input> ::core::fmt::Debug for Count<'input> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Count::CountIs(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "CountIs", &__self_0),
            Count::CountIsName(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "CountIsName", __self_0, &__self_1),
            Count::CountIsParam(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "CountIsParam", &__self_0),
            Count::CountIsStar(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "CountIsStar", &__self_0),
            Count::CountImplied =>
                ::core::fmt::Formatter::write_str(f, "CountImplied"),
        }
    }
}Debug, #[automatically_derived]
impl<'input> ::core::cmp::PartialEq for Count<'input> {
    #[inline]
    fn eq(&self, other: &Count<'input>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (Count::CountIs(__self_0), Count::CountIs(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Count::CountIsName(__self_0, __self_1),
                    Count::CountIsName(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (Count::CountIsParam(__self_0), Count::CountIsParam(__arg1_0))
                    => __self_0 == __arg1_0,
                (Count::CountIsStar(__self_0), Count::CountIsStar(__arg1_0))
                    => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl<'input> ::core::default::Default for Count<'input> {
    #[inline]
    fn default() -> Count<'input> { Self::CountImplied }
}Default)]
151pub enum Count<'input> {
152    /// The count is specified explicitly.
153    CountIs(u16),
154    /// The count is specified by the argument with the given name.
155    CountIsName(&'input str, Range<usize>),
156    /// The count is specified by the argument at the given index.
157    CountIsParam(usize),
158    /// The count is specified by a star (like in `{:.*}`) that refers to the argument at the given index.
159    CountIsStar(usize),
160    /// The count is implied and cannot be explicitly specified.
161    #[default]
162    CountImplied,
163}
164
165pub struct ParseError {
166    pub description: String,
167    pub note: Option<String>,
168    pub label: String,
169    pub span: Range<usize>,
170    pub secondary_label: Option<(String, Range<usize>)>,
171    pub suggestion: Suggestion,
172}
173
174pub enum Suggestion {
175    None,
176    /// Replace inline argument with positional argument:
177    /// `format!("{foo.bar}")` -> `format!("{}", foo.bar)`
178    UsePositional,
179    /// Remove `r#` from identifier:
180    /// `format!("{r#foo}")` -> `format!("{foo}")`
181    RemoveRawIdent(Range<usize>),
182    /// Reorder format parameter:
183    /// `format!("{foo:?#}")` -> `format!("{foo:#?}")`
184    /// `format!("{foo:?x}")` -> `format!("{foo:x?}")`
185    /// `format!("{foo:?X}")` -> `format!("{foo:X?}")`
186    ReorderFormatParameter(Range<usize>, String),
187    /// Add missing colon:
188    /// `format!("{foo?}")` -> `format!("{foo:?}")`
189    AddMissingColon(Range<usize>),
190    /// Use Rust format string:
191    /// `format!("{x=}")` -> `dbg!(x)`
192    UseRustDebugPrintingMacro,
193}
194
195/// The parser structure for interpreting the input format string. This is
196/// modeled as an iterator over `Piece` structures to form a stream of tokens
197/// being output.
198///
199/// This is a recursive-descent parser for the sake of simplicity, and if
200/// necessary there's probably lots of room for improvement performance-wise.
201pub struct Parser<'input> {
202    mode: ParseMode,
203    /// Input to be parsed
204    input: &'input str,
205    /// Tuples of the span in the code snippet (input as written before being unescaped), the pos in input, and the char in input
206    input_vec: Vec<(Range<usize>, usize, char)>,
207    /// Index into input_vec
208    input_vec_index: usize,
209    /// Error messages accumulated during parsing
210    pub errors: Vec<ParseError>,
211    /// Current position of implicit positional argument pointer
212    pub curarg: usize,
213    /// Start and end byte offset of every successfully parsed argument
214    pub arg_places: Vec<Range<usize>>,
215    /// Span of the last opening brace seen, used for error reporting
216    last_open_brace: Option<Range<usize>>,
217    /// Whether this formatting string was written directly in the source. This controls whether we
218    /// can use spans to refer into it and give better error messages.
219    /// N.B: This does _not_ control whether implicit argument captures can be used.
220    pub is_source_literal: bool,
221    /// Index to the end of the literal snippet
222    end_of_snippet: usize,
223    /// Start position of the current line.
224    cur_line_start: usize,
225    /// Start and end byte offset of every line of the format string. Excludes
226    /// newline characters and leading whitespace.
227    pub line_spans: Vec<Range<usize>>,
228}
229
230impl<'input> Iterator for Parser<'input> {
231    type Item = Piece<'input>;
232
233    fn next(&mut self) -> Option<Piece<'input>> {
234        if let Some((Range { start, end }, idx, ch)) = self.peek() {
235            match ch {
236                '{' => {
237                    self.input_vec_index += 1;
238                    if let Some((_, i, '{')) = self.peek() {
239                        self.input_vec_index += 1;
240                        // double open brace escape: "{{"
241                        // next state after this is either end-of-input or seen-a-brace
242                        Some(Piece::Lit(self.string(i)))
243                    } else {
244                        // single open brace
245                        self.last_open_brace = Some(start..end);
246                        let arg = self.argument();
247                        self.ws();
248                        if let Some((close_brace_range, _)) = self.consume_pos('}') {
249                            if self.is_source_literal {
250                                self.arg_places.push(start..close_brace_range.end);
251                            }
252                        } else {
253                            self.missing_closing_brace(&arg);
254                        }
255
256                        Some(Piece::NextArgument(Box::new(arg)))
257                    }
258                }
259                '}' => {
260                    self.input_vec_index += 1;
261                    if let Some((_, i, '}')) = self.peek() {
262                        self.input_vec_index += 1;
263                        // double close brace escape: "}}"
264                        // next state after this is either end-of-input or start
265                        Some(Piece::Lit(self.string(i)))
266                    } else {
267                        // error: single close brace without corresponding open brace
268                        self.errors.push(ParseError {
269                            description: "unmatched `}` found".into(),
270                            note: Some(
271                                "if you intended to print `}`, you can escape it using `}}`".into(),
272                            ),
273                            label: "unmatched `}`".into(),
274                            span: start..end,
275                            secondary_label: None,
276                            suggestion: Suggestion::None,
277                        });
278                        None
279                    }
280                }
281                _ => Some(Piece::Lit(self.string(idx))),
282            }
283        } else {
284            // end of input
285            if self.is_source_literal {
286                let span = self.cur_line_start..self.end_of_snippet;
287                if self.line_spans.last() != Some(&span) {
288                    self.line_spans.push(span);
289                }
290            }
291            None
292        }
293    }
294}
295
296impl<'input> Parser<'input> {
297    /// Creates a new parser for the given unescaped input string and
298    /// optional code snippet (the input as written before being unescaped),
299    /// where `style` is `Some(nr_hashes)` when the snippet is a raw string with that many hashes.
300    /// If the input comes via `println` or `panic`, then it has a newline already appended,
301    /// which is reflected in the `appended_newline` parameter.
302    pub fn new(
303        input: &'input str,
304        style: Option<usize>,
305        snippet: Option<String>,
306        appended_newline: bool,
307        mode: ParseMode,
308    ) -> Self {
309        let quote_offset = style.map_or(1, |nr_hashes| nr_hashes + 2);
310
311        let (is_source_literal, end_of_snippet, pre_input_vec) = if let Some(snippet) = snippet {
312            if let Some(nr_hashes) = style {
313                // snippet is a raw string
314
315                // validate snippet because a proc macro may have
316                // respanned it to something completely different (fixes #114865)
317                let prefix_len = nr_hashes + 2; // r + hashes + opening "
318                let suffix_len = nr_hashes + 1; // closing " + hashes
319                let snippet_bytes = snippet.as_bytes();
320                let content_end = snippet.len() - suffix_len;
321                if snippet.len() >= prefix_len + suffix_len // is sufficiently long
322                    && snippet_bytes[0] == b'r'
323                    && snippet_bytes[1..1 + nr_hashes].iter().all(|&c| c == b'#')
324                    && snippet_bytes[1 + nr_hashes] == b'"'
325                    && snippet_bytes[content_end] == b'"'
326                    && snippet_bytes[content_end + 1..].iter().all(|&c| c == b'#')
327                {
328                    let snippet_without_quotes = &snippet[prefix_len..content_end];
329                    let input_without_newline =
330                        if appended_newline { &input[..input.len() - 1] } else { input };
331                    if snippet_without_quotes == input_without_newline {
332                        (true, snippet.len() - suffix_len, ::alloc::vec::Vec::new()vec![])
333                    } else {
334                        (false, snippet.len(), ::alloc::vec::Vec::new()vec![])
335                    }
336                } else {
337                    (false, snippet.len(), ::alloc::vec::Vec::new()vec![])
338                }
339            } else {
340                // snippet is not a raw string
341                if snippet.starts_with('"') {
342                    // snippet looks like an ordinary string literal
343                    // check whether it is the escaped version of input
344                    let snippet_without_quotes = &snippet[1..snippet.len() - 1];
345                    let (mut ok, mut vec) = (true, ::alloc::vec::Vec::new()vec![]);
346                    let mut chars = input.chars();
347                    rustc_literal_escaper::unescape_str(snippet_without_quotes, |range, res| {
348                        match res {
349                            Ok(ch) if ok && chars.next().is_some_and(|c| ch == c) => {
350                                vec.push((range, ch));
351                            }
352                            _ => {
353                                ok = false;
354                                vec = ::alloc::vec::Vec::new()vec![];
355                            }
356                        }
357                    });
358                    let end = vec.last().map(|(r, _)| r.end).unwrap_or(0);
359                    if ok {
360                        if appended_newline {
361                            if chars.as_str() == "\n" {
362                                vec.push((end..end + 1, '\n'));
363                                (true, 1 + end, vec)
364                            } else {
365                                (false, snippet.len(), ::alloc::vec::Vec::new()vec![])
366                            }
367                        } else if chars.as_str() == "" {
368                            (true, 1 + end, vec)
369                        } else {
370                            (false, snippet.len(), ::alloc::vec::Vec::new()vec![])
371                        }
372                    } else {
373                        (false, snippet.len(), ::alloc::vec::Vec::new()vec![])
374                    }
375                } else {
376                    // snippet is not a raw string and does not start with '"'
377                    (false, snippet.len(), ::alloc::vec::Vec::new()vec![])
378                }
379            }
380        } else {
381            // snippet is None
382            (false, input.len() - if appended_newline { 1 } else { 0 }, ::alloc::vec::Vec::new()vec![])
383        };
384
385        let input_vec: Vec<(Range<usize>, usize, char)> = if pre_input_vec.is_empty() {
386            // Snippet is *not* input before unescaping, so spans pointing at it will be incorrect.
387            // This can happen with proc macros that respan generated literals.
388            input
389                .char_indices()
390                .map(|(idx, c)| {
391                    let i = idx + quote_offset;
392                    (i..i + c.len_utf8(), idx, c)
393                })
394                .collect()
395        } else {
396            // Snippet is input before unescaping
397            input
398                .char_indices()
399                .zip(pre_input_vec)
400                .map(|((i, c), (r, _))| (r.start + quote_offset..r.end + quote_offset, i, c))
401                .collect()
402        };
403
404        Parser {
405            mode,
406            input,
407            input_vec,
408            input_vec_index: 0,
409            errors: ::alloc::vec::Vec::new()vec![],
410            curarg: 0,
411            arg_places: ::alloc::vec::Vec::new()vec![],
412            last_open_brace: None,
413            is_source_literal,
414            end_of_snippet,
415            cur_line_start: quote_offset,
416            line_spans: ::alloc::vec::Vec::new()vec![],
417        }
418    }
419
420    /// Peeks at the current position, without incrementing the pointer.
421    pub fn peek(&self) -> Option<(Range<usize>, usize, char)> {
422        self.input_vec.get(self.input_vec_index).cloned()
423    }
424
425    /// Peeks at the current position + 1, without incrementing the pointer.
426    pub fn peek_ahead(&self) -> Option<(Range<usize>, usize, char)> {
427        self.input_vec.get(self.input_vec_index + 1).cloned()
428    }
429
430    /// Optionally consumes the specified character. If the character is not at
431    /// the current position, then the current iterator isn't moved and `false` is
432    /// returned, otherwise the character is consumed and `true` is returned.
433    fn consume(&mut self, c: char) -> bool {
434        self.consume_pos(c).is_some()
435    }
436
437    /// Optionally consumes the specified character. If the character is not at
438    /// the current position, then the current iterator isn't moved and `None` is
439    /// returned, otherwise the character is consumed and the current position is
440    /// returned.
441    fn consume_pos(&mut self, ch: char) -> Option<(Range<usize>, usize)> {
442        if let Some((r, i, c)) = self.peek()
443            && ch == c
444        {
445            self.input_vec_index += 1;
446            return Some((r, i));
447        }
448
449        None
450    }
451
452    /// Called if a closing brace was not found.
453    fn missing_closing_brace(&mut self, arg: &Argument<'_>) {
454        let (range, description) = if let Some((r, _, c)) = self.peek() {
455            (r.start..r.start, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `}}`, found `{0}`",
                c.escape_debug()))
    })format!("expected `}}`, found `{}`", c.escape_debug()))
456        } else {
457            (
458                // point at closing `"`
459                self.end_of_snippet..self.end_of_snippet,
460                "expected `}` but string was terminated".to_owned(),
461            )
462        };
463
464        let (note, secondary_label) = if arg.format.fill == Some('}') {
465            (
466                Some("the character `}` is interpreted as a fill character because of the `:` that precedes it".to_owned()),
467                arg.format.fill_span.clone().map(|sp| ("this is not interpreted as a formatting closing brace".to_owned(), sp)),
468            )
469        } else {
470            (
471                Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
472                self.last_open_brace
473                    .clone()
474                    .map(|sp| ("because of this opening brace".to_owned(), sp)),
475            )
476        };
477
478        self.errors.push(ParseError {
479            description,
480            note,
481            label: "expected `}`".to_owned(),
482            span: range.start..range.start,
483            secondary_label,
484            suggestion: Suggestion::None,
485        });
486
487        if let (Some((_, _, c)), Some((_, _, nc))) = (self.peek(), self.peek_ahead()) {
488            match (c, nc) {
489                ('?', '}') => self.missing_colon_before_debug_formatter(),
490                ('?', _) => self.suggest_format_debug(),
491                ('<' | '^' | '>', _) => self.suggest_format_align(c),
492                (',', _) => self.suggest_unsupported_python_numeric_grouping(),
493                ('=', '}') => self.suggest_rust_debug_printing_macro(),
494                _ => self.suggest_positional_arg_instead_of_captured_arg(arg),
495            }
496        }
497    }
498
499    /// Consumes all whitespace characters until the first non-whitespace character
500    fn ws(&mut self) {
501        let rest = &self.input_vec[self.input_vec_index..];
502        let step = rest.iter().position(|&(_, _, c)| !c.is_whitespace()).unwrap_or(rest.len());
503        self.input_vec_index += step;
504    }
505
506    /// Parses all of a string which is to be considered a "raw literal" in a
507    /// format string. This is everything outside of the braces.
508    fn string(&mut self, start: usize) -> &'input str {
509        while let Some((r, i, c)) = self.peek() {
510            match c {
511                '{' | '}' => {
512                    return &self.input[start..i];
513                }
514                '\n' if self.is_source_literal => {
515                    self.input_vec_index += 1;
516                    self.line_spans.push(self.cur_line_start..r.start);
517                    self.cur_line_start = r.end;
518                }
519                _ => {
520                    self.input_vec_index += 1;
521                    if self.is_source_literal && r.start == self.cur_line_start && c.is_whitespace()
522                    {
523                        self.cur_line_start = r.end;
524                    }
525                }
526            }
527        }
528        &self.input[start..]
529    }
530
531    /// Parses an `Argument` structure, or what's contained within braces inside the format string.
532    fn argument(&mut self) -> Argument<'input> {
533        let start_idx = self.input_vec_index;
534
535        let position = self.position();
536        self.ws();
537
538        let end_idx = self.input_vec_index;
539
540        let format = match self.mode {
541            ParseMode::Format => self.format(),
542            ParseMode::InlineAsm => self.inline_asm(),
543            ParseMode::Diagnostic => self.diagnostic(),
544        };
545
546        // Resolve position after parsing format spec.
547        let position = position.unwrap_or_else(|| {
548            let i = self.curarg;
549            self.curarg += 1;
550            ArgumentImplicitlyIs(i)
551        });
552
553        let position_span =
554            self.input_vec_index2range(start_idx).start..self.input_vec_index2range(end_idx).start;
555        Argument { position, position_span, format }
556    }
557
558    /// Parses a positional argument for a format. This could either be an
559    /// integer index of an argument, a named argument, or a blank string.
560    /// Returns `Some(parsed_position)` if the position is not implicitly
561    /// consuming a macro argument, `None` if it's the case.
562    fn position(&mut self) -> Option<Position<'input>> {
563        if let Some(i) = self.integer() {
564            Some(ArgumentIs(i.into()))
565        } else {
566            match self.peek() {
567                Some((range, _, c)) if rustc_lexer::is_id_start(c) => {
568                    let start = range.start;
569                    let word = self.word();
570
571                    // Recover from `r#ident` in format strings.
572                    if word == "r"
573                        && let Some((r, _, '#')) = self.peek()
574                        && self.peek_ahead().is_some_and(|(_, _, c)| rustc_lexer::is_id_start(c))
575                    {
576                        self.input_vec_index += 1;
577                        let prefix_end = r.end;
578                        let word = self.word();
579                        let prefix_span = start..prefix_end;
580                        let full_span =
581                            start..self.input_vec_index2range(self.input_vec_index).start;
582                        self.errors.insert(0, ParseError {
583                                    description: "raw identifiers are not supported".to_owned(),
584                                    note: Some("identifiers in format strings can be keywords and don't need to be prefixed with `r#`".to_string()),
585                                    label: "raw identifier used here".to_owned(),
586                                    span: full_span,
587                                    secondary_label: None,
588                                    suggestion: Suggestion::RemoveRawIdent(prefix_span),
589                                });
590                        return Some(ArgumentNamed(word));
591                    }
592
593                    Some(ArgumentNamed(word))
594                }
595                // This is an `ArgumentNext`.
596                // Record the fact and do the resolution after parsing the
597                // format spec, to make things like `{:.*}` work.
598                _ => None,
599            }
600        }
601    }
602
603    fn input_vec_index2pos(&self, index: usize) -> usize {
604        if let Some((_, pos, _)) = self.input_vec.get(index) { *pos } else { self.input.len() }
605    }
606
607    fn input_vec_index2range(&self, index: usize) -> Range<usize> {
608        if let Some((r, _, _)) = self.input_vec.get(index) {
609            r.clone()
610        } else {
611            self.end_of_snippet..self.end_of_snippet
612        }
613    }
614
615    /// Parses a format specifier at the current position, returning all of the
616    /// relevant information in the `FormatSpec` struct.
617    fn format(&mut self) -> FormatSpec<'input> {
618        let mut spec = FormatSpec::default();
619
620        if !self.consume(':') {
621            return spec;
622        }
623
624        // fill character
625        if let (Some((r, _, c)), Some((_, _, '>' | '<' | '^'))) = (self.peek(), self.peek_ahead()) {
626            self.input_vec_index += 1;
627            spec.fill = Some(c);
628            spec.fill_span = Some(r);
629        }
630        // Alignment
631        if self.consume('<') {
632            spec.align = AlignLeft;
633        } else if self.consume('>') {
634            spec.align = AlignRight;
635        } else if self.consume('^') {
636            spec.align = AlignCenter;
637        }
638        // Sign flags
639        if self.consume('+') {
640            spec.sign = Some(Sign::Plus);
641        } else if self.consume('-') {
642            spec.sign = Some(Sign::Minus);
643        }
644        // Alternate marker
645        if self.consume('#') {
646            spec.alternate = true;
647        }
648        // Width and precision
649        let mut havewidth = false;
650
651        if let Some((range, _)) = self.consume_pos('0') {
652            // small ambiguity with '0$' as a format string. In theory this is a
653            // '0' flag and then an ill-formatted format string with just a '$'
654            // and no count, but this is better if we instead interpret this as
655            // no '0' flag and '0$' as the width instead.
656            if let Some((r, _)) = self.consume_pos('$') {
657                spec.width = CountIsParam(0);
658                spec.width_span = Some(range.start..r.end);
659                havewidth = true;
660            } else {
661                spec.zero_pad = true;
662            }
663        }
664
665        if !havewidth {
666            let start_idx = self.input_vec_index;
667            spec.width = self.count();
668            if spec.width != CountImplied {
669                let end = self.input_vec_index2range(self.input_vec_index).start;
670                spec.width_span = Some(self.input_vec_index2range(start_idx).start..end);
671            }
672        }
673
674        if let Some((range, _)) = self.consume_pos('.') {
675            if self.consume('*') {
676                // Resolve `CountIsNextParam`.
677                // We can do this immediately as `position` is resolved later.
678                let i = self.curarg;
679                self.curarg += 1;
680                spec.precision = CountIsStar(i);
681            } else {
682                spec.precision = self.count();
683            }
684            spec.precision_span =
685                Some(range.start..self.input_vec_index2range(self.input_vec_index).start);
686        }
687
688        let start_idx = self.input_vec_index;
689        // Optional radix followed by the actual format specifier
690        if self.consume('x') {
691            if self.consume('?') {
692                spec.debug_hex = Some(DebugHex::Lower);
693                spec.ty = "?";
694            } else {
695                spec.ty = "x";
696            }
697        } else if self.consume('X') {
698            if self.consume('?') {
699                spec.debug_hex = Some(DebugHex::Upper);
700                spec.ty = "?";
701            } else {
702                spec.ty = "X";
703            }
704        } else if let Some((range, _)) = self.consume_pos('?') {
705            spec.ty = "?";
706            if let Some((r, _, c @ ('#' | 'x' | 'X'))) = self.peek() {
707                self.errors.insert(
708                    0,
709                    ParseError {
710                        description: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `}}`, found `{0}`", c))
    })format!("expected `}}`, found `{c}`"),
711                        note: None,
712                        label: "expected `'}'`".into(),
713                        span: r.clone(),
714                        secondary_label: None,
715                        suggestion: Suggestion::ReorderFormatParameter(
716                            range.start..r.end,
717                            ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("{0}?", c)) })format!("{c}?"),
718                        ),
719                    },
720                );
721            }
722        } else {
723            spec.ty = self.word();
724            if !spec.ty.is_empty() {
725                let start = self.input_vec_index2range(start_idx).start;
726                let end = self.input_vec_index2range(self.input_vec_index).start;
727                spec.ty_span = Some(start..end);
728            }
729        }
730        spec
731    }
732
733    /// Parses an inline assembly template modifier at the current position, returning the modifier
734    /// in the `ty` field of the `FormatSpec` struct.
735    fn inline_asm(&mut self) -> FormatSpec<'input> {
736        let mut spec = FormatSpec::default();
737
738        if !self.consume(':') {
739            return spec;
740        }
741
742        let start_idx = self.input_vec_index;
743        spec.ty = self.word();
744        if !spec.ty.is_empty() {
745            let start = self.input_vec_index2range(start_idx).start;
746            let end = self.input_vec_index2range(self.input_vec_index).start;
747            spec.ty_span = Some(start..end);
748        }
749
750        spec
751    }
752
753    /// Always returns an empty `FormatSpec`
754    fn diagnostic(&mut self) -> FormatSpec<'input> {
755        let mut spec = FormatSpec::default();
756
757        let Some((Range { start, .. }, start_idx)) = self.consume_pos(':') else {
758            return spec;
759        };
760
761        spec.ty = self.string(start_idx);
762        spec.ty_span = {
763            let end = self.input_vec_index2range(self.input_vec_index).start;
764            Some(start..end)
765        };
766        spec
767    }
768
769    /// Parses a `Count` parameter at the current position. This does not check
770    /// for 'CountIsNextParam' because that is only used in precision, not
771    /// width.
772    fn count(&mut self) -> Count<'input> {
773        if let Some(i) = self.integer() {
774            if self.consume('$') { CountIsParam(i.into()) } else { CountIs(i) }
775        } else {
776            let start_idx = self.input_vec_index;
777            let word = self.word();
778            if word.is_empty() {
779                CountImplied
780            } else if let Some((r, _)) = self.consume_pos('$') {
781                CountIsName(word, self.input_vec_index2range(start_idx).start..r.start)
782            } else {
783                self.input_vec_index = start_idx;
784                CountImplied
785            }
786        }
787    }
788
789    /// Parses a word starting at the current position. A word is the same as a
790    /// Rust identifier or keyword, except that it can't be a bare `_` character.
791    fn word(&mut self) -> &'input str {
792        let index = self.input_vec_index;
793        match self.peek() {
794            Some((ref r, i, c)) if rustc_lexer::is_id_start(c) => {
795                self.input_vec_index += 1;
796                (r.start, i)
797            }
798            _ => {
799                return "";
800            }
801        };
802        let (err_end, end): (usize, usize) = loop {
803            if let Some((ref r, i, c)) = self.peek() {
804                if rustc_lexer::is_id_continue(c) {
805                    self.input_vec_index += 1;
806                } else {
807                    break (r.start, i);
808                }
809            } else {
810                break (self.end_of_snippet, self.input.len());
811            }
812        };
813
814        let word = &self.input[self.input_vec_index2pos(index)..end];
815        if word == "_" {
816            self.errors.push(ParseError {
817                description: "invalid argument name `_`".into(),
818                note: Some("argument name cannot be a single underscore".into()),
819                label: "invalid argument name".into(),
820                span: self.input_vec_index2range(index).start..err_end,
821                secondary_label: None,
822                suggestion: Suggestion::None,
823            });
824        }
825        word
826    }
827
828    fn integer(&mut self) -> Option<u16> {
829        let mut cur: u16 = 0;
830        let mut found = false;
831        let mut overflow = false;
832        let start_index = self.input_vec_index;
833        while let Some((_, _, c)) = self.peek() {
834            if let Some(i) = c.to_digit(10) {
835                self.input_vec_index += 1;
836                let (tmp, mul_overflow) = cur.overflowing_mul(10);
837                let (tmp, add_overflow) = tmp.overflowing_add(i as u16);
838                if mul_overflow || add_overflow {
839                    overflow = true;
840                }
841                cur = tmp;
842                found = true;
843            } else {
844                break;
845            }
846        }
847
848        if overflow {
849            let overflowed_int = &self.input[self.input_vec_index2pos(start_index)
850                ..self.input_vec_index2pos(self.input_vec_index)];
851            self.errors.push(ParseError {
852                description: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("integer `{0}` does not fit into the type `u16` whose range is `0..={1}`",
                overflowed_int, u16::MAX))
    })format!(
853                    "integer `{}` does not fit into the type `u16` whose range is `0..={}`",
854                    overflowed_int,
855                    u16::MAX
856                ),
857                note: None,
858                label: "integer out of range for `u16`".into(),
859                span: self.input_vec_index2range(start_index).start
860                    ..self.input_vec_index2range(self.input_vec_index).end,
861                secondary_label: None,
862                suggestion: Suggestion::None,
863            });
864        }
865
866        found.then_some(cur)
867    }
868
869    fn suggest_format_debug(&mut self) {
870        if let (Some((range, _)), Some(_)) = (self.consume_pos('?'), self.consume_pos(':')) {
871            let word = self.word();
872            self.errors.insert(
873                0,
874                ParseError {
875                    description: "expected format parameter to occur after `:`".to_owned(),
876                    note: Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`?` comes after `:`, try `{0}:{1}` instead",
                word, "?"))
    })format!("`?` comes after `:`, try `{}:{}` instead", word, "?")),
877                    label: "expected `?` to occur after `:`".to_owned(),
878                    span: range,
879                    secondary_label: None,
880                    suggestion: Suggestion::None,
881                },
882            );
883        }
884    }
885
886    fn missing_colon_before_debug_formatter(&mut self) {
887        if let Some((range, _)) = self.consume_pos('?') {
888            let span = range.clone();
889            self.errors.insert(
890                0,
891                ParseError {
892                    description: "expected `}`, found `?`".to_owned(),
893                    note: Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("to print `{{`, you can escape it using `{{{{`"))
    })format!("to print `{{`, you can escape it using `{{{{`",)),
894                    label: "expected `:` before `?` to format with `Debug`".to_owned(),
895                    span: range,
896                    secondary_label: None,
897                    suggestion: Suggestion::AddMissingColon(span),
898                },
899            );
900        }
901    }
902
903    fn suggest_rust_debug_printing_macro(&mut self) {
904        if let Some((range, _)) = self.consume_pos('=') {
905            self.errors.insert(
906                0,
907                ParseError {
908                    description:
909                        "python's f-string debug `=` is not supported in rust, use `dbg(x)` instead"
910                            .to_owned(),
911                    note: Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("to print `{{`, you can escape it using `{{{{`"))
    })format!("to print `{{`, you can escape it using `{{{{`",)),
912                    label: "expected `}`".to_owned(),
913                    span: range,
914                    secondary_label: self
915                        .last_open_brace
916                        .clone()
917                        .map(|sp| ("because of this opening brace".to_owned(), sp)),
918                    suggestion: Suggestion::UseRustDebugPrintingMacro,
919                },
920            );
921        }
922    }
923
924    fn suggest_format_align(&mut self, alignment: char) {
925        if let Some((range, _)) = self.consume_pos(alignment) {
926            self.errors.insert(
927                0,
928                ParseError {
929                    description:
930                        "expected alignment specifier after `:` in format string; example: `{:>?}`"
931                            .to_owned(),
932                    note: None,
933                    label: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{0}` to occur after `:`",
                alignment))
    })format!("expected `{}` to occur after `:`", alignment),
934                    span: range,
935                    secondary_label: None,
936                    suggestion: Suggestion::None,
937                },
938            );
939        }
940    }
941
942    fn suggest_positional_arg_instead_of_captured_arg(&mut self, arg: &Argument<'_>) {
943        // If the argument is not an identifier, it is not a field access.
944        if !arg.is_identifier() {
945            return;
946        }
947
948        if let Some((_range, _pos)) = self.consume_pos('.') {
949            let field = self.argument();
950            // We can only parse simple `foo.bar` field access or `foo.0` tuple index access, any
951            // deeper nesting, or another type of expression, like method calls, are not supported
952            if !self.consume('}') {
953                return;
954            }
955            if let ArgumentNamed(_) = arg.position {
956                match field.position {
957                    ArgumentNamed(_) => {
958                        self.errors.insert(
959                            0,
960                            ParseError {
961                                description: "field access isn't supported".to_string(),
962                                note: Some(
963                                    "consider moving this expression to a local variable and then \
964                                     using the local here instead"
965                                        .to_owned(),
966                                ),
967                                label: "not supported".to_string(),
968                                span: arg.position_span.start..field.position_span.end,
969                                secondary_label: None,
970                                suggestion: Suggestion::UsePositional,
971                            },
972                        );
973                    }
974                    ArgumentIs(_) => {
975                        self.errors.insert(
976                            0,
977                            ParseError {
978                                description: "tuple index access isn't supported".to_string(),
979                                note: Some(
980                                    "consider moving this expression to a local variable and then \
981                                     using the local here instead"
982                                        .to_owned(),
983                                ),
984                                label: "not supported".to_string(),
985                                span: arg.position_span.start..field.position_span.end,
986                                secondary_label: None,
987                                suggestion: Suggestion::UsePositional,
988                            },
989                        );
990                    }
991                    _ => {}
992                };
993            }
994        }
995    }
996
997    fn suggest_unsupported_python_numeric_grouping(&mut self) {
998        if let Some((range, _)) = self.consume_pos(',') {
999            self.errors.insert(
1000                0,
1001                ParseError {
1002                    description:
1003                        "python's numeric grouping `,` is not supported in rust format strings"
1004                            .to_owned(),
1005                    note: Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("to print `{{`, you can escape it using `{{{{`"))
    })format!("to print `{{`, you can escape it using `{{{{`",)),
1006                    label: "expected `}`".to_owned(),
1007                    span: range,
1008                    secondary_label: self
1009                        .last_open_brace
1010                        .clone()
1011                        .map(|sp| ("because of this opening brace".to_owned(), sp)),
1012                    suggestion: Suggestion::None,
1013                },
1014            );
1015        }
1016    }
1017}
1018
1019// Assert a reasonable size for `Piece`
1020#[cfg(all(test, target_pointer_width = "64"))]
1021rustc_index::static_assert_size!(Piece<'_>, 16);
1022
1023#[cfg(test)]
1024mod tests;