2014-05-06 16:52:53 +00:00
|
|
|
//! Macro support for format strings
|
2013-10-13 02:02:46 +00:00
|
|
|
//!
|
|
|
|
//! These structures are used when parsing format strings for the compiler.
|
2014-03-16 22:59:04 +00:00
|
|
|
//! Parsing does not happen at runtime: structures of `std::fmt::rt` are
|
|
|
|
//! generated instead.
|
2013-10-13 02:02:46 +00:00
|
|
|
|
Use `tidy` to sort crate attributes for all compiler crates.
We already do this for a number of crates, e.g. `rustc_middle`,
`rustc_span`, `rustc_metadata`, `rustc_span`, `rustc_errors`.
For the ones we don't, in many cases the attributes are a mess.
- There is no consistency about order of attribute kinds (e.g.
`allow`/`deny`/`feature`).
- Within attribute kind groups (e.g. the `feature` attributes),
sometimes the order is alphabetical, and sometimes there is no
particular order.
- Sometimes the attributes of a particular kind aren't even grouped
all together, e.g. there might be a `feature`, then an `allow`, then
another `feature`.
This commit extends the existing sorting to all compiler crates,
increasing consistency. If any new attribute line is added there is now
only one place it can go -- no need for arbitrary decisions.
Exceptions:
- `rustc_log`, `rustc_next_trait_solver` and `rustc_type_ir_macros`,
because they have no crate attributes.
- `rustc_codegen_gcc`, because it's quasi-external to rustc (e.g. it's
ignored in `rustfmt.toml`).
2024-06-12 03:49:36 +00:00
|
|
|
// tidy-alphabetical-start
|
|
|
|
// We want to be able to build this crate with a stable compiler,
|
|
|
|
// so no `#![feature]` attributes should be added.
|
|
|
|
#![deny(unstable_features)]
|
2019-02-05 13:37:15 +00:00
|
|
|
#![doc(
|
2020-09-23 19:51:56 +00:00
|
|
|
html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/",
|
2015-11-03 15:30:14 +00:00
|
|
|
html_playground_url = "https://play.rust-lang.org/",
|
|
|
|
test(attr(deny(warnings)))
|
|
|
|
)]
|
Use `tidy` to sort crate attributes for all compiler crates.
We already do this for a number of crates, e.g. `rustc_middle`,
`rustc_span`, `rustc_metadata`, `rustc_span`, `rustc_errors`.
For the ones we don't, in many cases the attributes are a mess.
- There is no consistency about order of attribute kinds (e.g.
`allow`/`deny`/`feature`).
- Within attribute kind groups (e.g. the `feature` attributes),
sometimes the order is alphabetical, and sometimes there is no
particular order.
- Sometimes the attributes of a particular kind aren't even grouped
all together, e.g. there might be a `feature`, then an `allow`, then
another `feature`.
This commit extends the existing sorting to all compiler crates,
increasing consistency. If any new attribute line is added there is now
only one place it can go -- no need for arbitrary decisions.
Exceptions:
- `rustc_log`, `rustc_next_trait_solver` and `rustc_type_ir_macros`,
because they have no crate attributes.
- `rustc_codegen_gcc`, because it's quasi-external to rustc (e.g. it's
ignored in `rustfmt.toml`).
2024-06-12 03:49:36 +00:00
|
|
|
// tidy-alphabetical-end
|
2018-08-09 10:48:10 +00:00
|
|
|
|
2019-02-02 17:18:39 +00:00
|
|
|
pub use Alignment::*;
|
|
|
|
pub use Count::*;
|
|
|
|
pub use Position::*;
|
2025-03-18 12:28:56 +00:00
|
|
|
use rustc_lexer::unescape;
|
2014-08-13 03:31:30 +00:00
|
|
|
|
2022-04-29 16:48:58 +00:00
|
|
|
// Note: copied from rustc_span
|
|
|
|
/// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
|
|
|
|
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
|
|
|
pub struct InnerSpan {
|
|
|
|
pub start: usize,
|
|
|
|
pub end: usize,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl InnerSpan {
|
|
|
|
pub fn new(start: usize, end: usize) -> InnerSpan {
|
|
|
|
InnerSpan { start, end }
|
|
|
|
}
|
|
|
|
}
|
2019-06-04 15:03:43 +00:00
|
|
|
|
2022-11-22 04:36:11 +00:00
|
|
|
/// The location and before/after width of a character whose width has changed from its source code
|
|
|
|
/// representation
|
|
|
|
#[derive(Copy, Clone, PartialEq, Eq)]
|
|
|
|
pub struct InnerWidthMapping {
|
|
|
|
/// Index of the character in the source
|
|
|
|
pub position: usize,
|
|
|
|
/// The inner width in characters
|
|
|
|
pub before: usize,
|
|
|
|
/// The transformed width in characters
|
|
|
|
pub after: usize,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl InnerWidthMapping {
|
|
|
|
pub fn new(position: usize, before: usize, after: usize) -> InnerWidthMapping {
|
|
|
|
InnerWidthMapping { position, before, after }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-27 22:00:03 +00:00
|
|
|
/// Whether the input string is a literal. If yes, it contains the inner width mappings.
|
|
|
|
#[derive(Clone, PartialEq, Eq)]
|
|
|
|
enum InputStringKind {
|
|
|
|
NotALiteral,
|
|
|
|
Literal { width_mappings: Vec<InnerWidthMapping> },
|
|
|
|
}
|
|
|
|
|
2020-02-12 15:47:43 +00:00
|
|
|
/// The type of format string that we are parsing.
|
|
|
|
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
|
|
|
|
pub enum ParseMode {
|
|
|
|
/// A normal format string as per `format_args!`.
|
|
|
|
Format,
|
|
|
|
/// An inline assembly template string for `asm!`.
|
|
|
|
InlineAsm,
|
|
|
|
}
|
|
|
|
|
2019-06-04 15:03:43 +00:00
|
|
|
#[derive(Copy, Clone)]
|
|
|
|
struct InnerOffset(usize);
|
|
|
|
|
|
|
|
impl InnerOffset {
|
|
|
|
fn to(self, end: InnerOffset) -> InnerSpan {
|
|
|
|
InnerSpan::new(self.0, end.0)
|
|
|
|
}
|
|
|
|
}
|
2019-06-04 02:47:42 +00:00
|
|
|
|
2014-03-16 22:59:04 +00:00
|
|
|
/// A piece is a portion of the format string which represents the next part
|
|
|
|
/// to emit. These are emitted as a stream by the `Parser` class.
|
2022-12-06 12:02:56 +00:00
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
2013-12-10 07:16:18 +00:00
|
|
|
pub enum Piece<'a> {
|
2013-07-29 08:12:41 +00:00
|
|
|
/// A literal string which should directly be emitted
|
2025-01-23 09:16:08 +00:00
|
|
|
Lit(&'a str),
|
2013-07-29 08:12:41 +00:00
|
|
|
/// This describes that formatting should process the next argument (as
|
|
|
|
/// specified inside) for emission.
|
2022-12-06 12:02:56 +00:00
|
|
|
NextArgument(Box<Argument<'a>>),
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Representation of an argument specification.
|
2019-11-06 00:02:12 +00:00
|
|
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
2013-12-10 07:16:18 +00:00
|
|
|
pub struct Argument<'a> {
|
2013-07-29 08:12:41 +00:00
|
|
|
/// Where to find this argument
|
2022-04-29 16:48:58 +00:00
|
|
|
pub position: Position<'a>,
|
2022-07-31 15:11:00 +00:00
|
|
|
/// The span of the position indicator. Includes any whitespace in implicit
|
|
|
|
/// positions (`{ }`).
|
|
|
|
pub position_span: InnerSpan,
|
2013-07-29 08:12:41 +00:00
|
|
|
/// How to format the argument
|
2014-03-27 22:09:47 +00:00
|
|
|
pub format: FormatSpec<'a>,
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Specification for the formatting of an argument in the format string.
|
2019-11-06 00:02:12 +00:00
|
|
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
2013-12-10 07:16:18 +00:00
|
|
|
pub struct FormatSpec<'a> {
|
On `format!()` arg count mismatch provide extra info
When positional width and precision formatting flags are present in a
formatting string that has an argument count mismatch, provide extra
information pointing at them making it easiser to understand where the
problem may lay:
```
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:78:15
|
LL | println!("{} {:.*} {}", 1, 3.2, 4);
| ^^ ^^--^ ^^ --- this parameter corresponds to the precision flag
| |
| this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:81:15
|
LL | println!("{} {:07$.*} {}", 1, 3.2, 4);
| ^^ ^^-----^ ^^ --- this parameter corresponds to the precision flag
| | |
| | this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 3 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:84:15
|
LL | println!("{} {:07$} {}", 1, 3.2, 4);
| ^^ ^^---^ ^^
| |
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
```
2019-07-30 01:19:21 +00:00
|
|
|
/// Optionally specified character to fill alignment with.
|
2014-03-27 22:09:47 +00:00
|
|
|
pub fill: Option<char>,
|
2023-07-17 00:36:00 +00:00
|
|
|
/// Span of the optionally specified fill character.
|
|
|
|
pub fill_span: Option<InnerSpan>,
|
On `format!()` arg count mismatch provide extra info
When positional width and precision formatting flags are present in a
formatting string that has an argument count mismatch, provide extra
information pointing at them making it easiser to understand where the
problem may lay:
```
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:78:15
|
LL | println!("{} {:.*} {}", 1, 3.2, 4);
| ^^ ^^--^ ^^ --- this parameter corresponds to the precision flag
| |
| this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:81:15
|
LL | println!("{} {:07$.*} {}", 1, 3.2, 4);
| ^^ ^^-----^ ^^ --- this parameter corresponds to the precision flag
| | |
| | this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 3 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:84:15
|
LL | println!("{} {:07$} {}", 1, 3.2, 4);
| ^^ ^^---^ ^^
| |
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
```
2019-07-30 01:19:21 +00:00
|
|
|
/// Optionally specified alignment.
|
2014-03-27 22:09:47 +00:00
|
|
|
pub align: Alignment,
|
2023-01-13 12:32:49 +00:00
|
|
|
/// The `+` or `-` flag.
|
|
|
|
pub sign: Option<Sign>,
|
|
|
|
/// The `#` flag.
|
|
|
|
pub alternate: bool,
|
|
|
|
/// The `0` flag.
|
|
|
|
pub zero_pad: bool,
|
|
|
|
/// The `x` or `X` flag. (Only for `Debug`.)
|
|
|
|
pub debug_hex: Option<DebugHex>,
|
On `format!()` arg count mismatch provide extra info
When positional width and precision formatting flags are present in a
formatting string that has an argument count mismatch, provide extra
information pointing at them making it easiser to understand where the
problem may lay:
```
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:78:15
|
LL | println!("{} {:.*} {}", 1, 3.2, 4);
| ^^ ^^--^ ^^ --- this parameter corresponds to the precision flag
| |
| this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:81:15
|
LL | println!("{} {:07$.*} {}", 1, 3.2, 4);
| ^^ ^^-----^ ^^ --- this parameter corresponds to the precision flag
| | |
| | this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 3 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:84:15
|
LL | println!("{} {:07$} {}", 1, 3.2, 4);
| ^^ ^^---^ ^^
| |
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
```
2019-07-30 01:19:21 +00:00
|
|
|
/// The integer precision to use.
|
2022-04-29 16:48:58 +00:00
|
|
|
pub precision: Count<'a>,
|
On `format!()` arg count mismatch provide extra info
When positional width and precision formatting flags are present in a
formatting string that has an argument count mismatch, provide extra
information pointing at them making it easiser to understand where the
problem may lay:
```
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:78:15
|
LL | println!("{} {:.*} {}", 1, 3.2, 4);
| ^^ ^^--^ ^^ --- this parameter corresponds to the precision flag
| |
| this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:81:15
|
LL | println!("{} {:07$.*} {}", 1, 3.2, 4);
| ^^ ^^-----^ ^^ --- this parameter corresponds to the precision flag
| | |
| | this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 3 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:84:15
|
LL | println!("{} {:07$} {}", 1, 3.2, 4);
| ^^ ^^---^ ^^
| |
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
```
2019-07-30 01:19:21 +00:00
|
|
|
/// The span of the precision formatting flag (for diagnostics).
|
|
|
|
pub precision_span: Option<InnerSpan>,
|
|
|
|
/// The string width requested for the resulting format.
|
2022-04-29 16:48:58 +00:00
|
|
|
pub width: Count<'a>,
|
On `format!()` arg count mismatch provide extra info
When positional width and precision formatting flags are present in a
formatting string that has an argument count mismatch, provide extra
information pointing at them making it easiser to understand where the
problem may lay:
```
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:78:15
|
LL | println!("{} {:.*} {}", 1, 3.2, 4);
| ^^ ^^--^ ^^ --- this parameter corresponds to the precision flag
| |
| this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:81:15
|
LL | println!("{} {:07$.*} {}", 1, 3.2, 4);
| ^^ ^^-----^ ^^ --- this parameter corresponds to the precision flag
| | |
| | this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 3 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:84:15
|
LL | println!("{} {:07$} {}", 1, 3.2, 4);
| ^^ ^^---^ ^^
| |
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
```
2019-07-30 01:19:21 +00:00
|
|
|
/// The span of the width formatting flag (for diagnostics).
|
|
|
|
pub width_span: Option<InnerSpan>,
|
2013-10-13 03:00:58 +00:00
|
|
|
/// The descriptor string representing the name of the format desired for
|
|
|
|
/// this argument, this can be empty or any number of characters, although
|
|
|
|
/// it is required to be one word.
|
2015-10-13 14:10:51 +00:00
|
|
|
pub ty: &'a str,
|
Point at formatting descriptor string when it is invalid
When a formatting string contains an invalid descriptor, point at it
instead of the argument:
```
error: unknown format trait `foo`
--> $DIR/ifmt-bad-arg.rs:86:17
|
LL | println!("{:foo}", 1);
| ^^^
|
= note: the only appropriate formatting traits are:
- ``, which uses the `Display` trait
- `?`, which uses the `Debug` trait
- `e`, which uses the `LowerExp` trait
- `E`, which uses the `UpperExp` trait
- `o`, which uses the `Octal` trait
- `p`, which uses the `Pointer` trait
- `b`, which uses the `Binary` trait
- `x`, which uses the `LowerHex` trait
- `X`, which uses the `UpperHex` trait
```
2019-11-05 19:55:00 +00:00
|
|
|
/// The span of the descriptor string (for diagnostics).
|
|
|
|
pub ty_span: Option<InnerSpan>,
|
2013-10-13 03:00:58 +00:00
|
|
|
}
|
|
|
|
|
2013-07-29 08:12:41 +00:00
|
|
|
/// Enum describing where an argument for a format can be located.
|
2019-11-06 00:02:12 +00:00
|
|
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
2022-04-29 16:48:58 +00:00
|
|
|
pub enum Position<'a> {
|
2018-02-10 11:22:57 +00:00
|
|
|
/// The argument is implied to be located at an index
|
2017-11-09 17:16:25 +00:00
|
|
|
ArgumentImplicitlyIs(usize),
|
2022-07-16 21:13:14 +00:00
|
|
|
/// The argument is located at a specific index given in the format,
|
2022-07-31 15:11:00 +00:00
|
|
|
ArgumentIs(usize),
|
2014-03-16 22:59:04 +00:00
|
|
|
/// The argument has a name.
|
2022-07-31 15:11:00 +00:00
|
|
|
ArgumentNamed(&'a str),
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
|
2022-04-29 16:48:58 +00:00
|
|
|
impl Position<'_> {
|
Fix simple formatting optimization
name old2 ns/iter new2 ns/iter diff ns/iter diff % speedup
fmt::write_str_macro1 12,295 12,308 13 0.11% x 1.00
fmt::write_str_macro2 24,079 21,451 -2,628 -10.91% x 1.12
fmt::write_str_macro_debug 238,363 230,807 -7,556 -3.17% x 1.03
fmt::write_str_ref 6,203 6,064 -139 -2.24% x 1.02
fmt::write_str_value 6,225 6,075 -150 -2.41% x 1.02
fmt::write_vec_macro1 17,144 17,121 -23 -0.13% x 1.00
fmt::write_vec_macro2 29,845 26,703 -3,142 -10.53% x 1.12
fmt::write_vec_macro_debug 248,840 242,117 -6,723 -2.70% x 1.03
fmt::write_vec_ref 5,954 6,438 484 8.13% x 0.92
fmt::write_vec_value 5,959 6,439 480 8.06% x 0.93
2019-01-12 04:30:03 +00:00
|
|
|
pub fn index(&self) -> Option<usize> {
|
|
|
|
match self {
|
2022-07-16 21:13:14 +00:00
|
|
|
ArgumentIs(i, ..) | ArgumentImplicitlyIs(i) => Some(*i),
|
Fix simple formatting optimization
name old2 ns/iter new2 ns/iter diff ns/iter diff % speedup
fmt::write_str_macro1 12,295 12,308 13 0.11% x 1.00
fmt::write_str_macro2 24,079 21,451 -2,628 -10.91% x 1.12
fmt::write_str_macro_debug 238,363 230,807 -7,556 -3.17% x 1.03
fmt::write_str_ref 6,203 6,064 -139 -2.24% x 1.02
fmt::write_str_value 6,225 6,075 -150 -2.41% x 1.02
fmt::write_vec_macro1 17,144 17,121 -23 -0.13% x 1.00
fmt::write_vec_macro2 29,845 26,703 -3,142 -10.53% x 1.12
fmt::write_vec_macro_debug 248,840 242,117 -6,723 -2.70% x 1.03
fmt::write_vec_ref 5,954 6,438 484 8.13% x 0.92
fmt::write_vec_value 5,959 6,439 480 8.06% x 0.93
2019-01-12 04:30:03 +00:00
|
|
|
_ => None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-08-16 05:41:28 +00:00
|
|
|
/// Enum of alignments which are supported.
|
2019-11-06 00:02:12 +00:00
|
|
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
2014-03-16 22:59:04 +00:00
|
|
|
pub enum Alignment {
|
|
|
|
/// The value will be aligned to the left.
|
|
|
|
AlignLeft,
|
|
|
|
/// The value will be aligned to the right.
|
|
|
|
AlignRight,
|
2014-08-30 18:27:02 +00:00
|
|
|
/// The value will be aligned in the center.
|
|
|
|
AlignCenter,
|
2014-03-16 22:59:04 +00:00
|
|
|
/// The value will take on a default alignment.
|
|
|
|
AlignUnknown,
|
|
|
|
}
|
2013-07-29 08:12:41 +00:00
|
|
|
|
2023-01-13 12:32:49 +00:00
|
|
|
/// Enum for the sign flags.
|
2019-11-06 00:02:12 +00:00
|
|
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
2023-01-13 12:32:49 +00:00
|
|
|
pub enum Sign {
|
|
|
|
/// The `+` flag.
|
|
|
|
Plus,
|
|
|
|
/// The `-` flag.
|
|
|
|
Minus,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Enum for the debug hex flags.
|
|
|
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
|
|
|
pub enum DebugHex {
|
|
|
|
/// The `x` flag in `{:x?}`.
|
|
|
|
Lower,
|
|
|
|
/// The `X` flag in `{:X?}`.
|
|
|
|
Upper,
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// A count is used for the precision and width parameters of an integer, and
|
|
|
|
/// can reference either an argument or a literal integer.
|
2019-11-06 00:02:12 +00:00
|
|
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
2022-04-29 16:48:58 +00:00
|
|
|
pub enum Count<'a> {
|
2014-03-16 22:59:04 +00:00
|
|
|
/// The count is specified explicitly.
|
2025-02-12 15:59:13 +00:00
|
|
|
CountIs(u16),
|
2014-03-16 22:59:04 +00:00
|
|
|
/// The count is specified by the argument with the given name.
|
2022-04-29 16:48:58 +00:00
|
|
|
CountIsName(&'a str, InnerSpan),
|
2014-03-16 22:59:04 +00:00
|
|
|
/// The count is specified by the argument at the given index.
|
2015-02-23 03:07:38 +00:00
|
|
|
CountIsParam(usize),
|
2022-08-25 12:49:09 +00:00
|
|
|
/// The count is specified by a star (like in `{:.*}`) that refers to the argument at the given index.
|
|
|
|
CountIsStar(usize),
|
2014-03-16 22:59:04 +00:00
|
|
|
/// The count is implied and cannot be explicitly specified.
|
2013-07-29 08:12:41 +00:00
|
|
|
CountImplied,
|
|
|
|
}
|
|
|
|
|
2018-05-10 16:09:58 +00:00
|
|
|
pub struct ParseError {
|
2025-01-23 09:16:08 +00:00
|
|
|
pub description: String,
|
|
|
|
pub note: Option<String>,
|
|
|
|
pub label: String,
|
2019-06-04 15:03:43 +00:00
|
|
|
pub span: InnerSpan,
|
2025-01-23 09:16:08 +00:00
|
|
|
pub secondary_label: Option<(String, InnerSpan)>,
|
2023-09-06 14:32:06 +00:00
|
|
|
pub suggestion: Suggestion,
|
|
|
|
}
|
|
|
|
|
|
|
|
pub enum Suggestion {
|
|
|
|
None,
|
|
|
|
/// Replace inline argument with positional argument:
|
|
|
|
/// `format!("{foo.bar}")` -> `format!("{}", foo.bar)`
|
|
|
|
UsePositional,
|
|
|
|
/// Remove `r#` from identifier:
|
|
|
|
/// `format!("{r#foo}")` -> `format!("{foo}")`
|
|
|
|
RemoveRawIdent(InnerSpan),
|
2024-12-29 04:47:07 +00:00
|
|
|
/// Reorder format parameter:
|
|
|
|
/// `format!("{foo:?#}")` -> `format!("{foo:#?}")`
|
|
|
|
/// `format!("{foo:?x}")` -> `format!("{foo:x?}")`
|
|
|
|
/// `format!("{foo:?X}")` -> `format!("{foo:X?}")`
|
2025-01-23 09:16:08 +00:00
|
|
|
ReorderFormatParameter(InnerSpan, String),
|
2018-05-10 16:09:58 +00:00
|
|
|
}
|
|
|
|
|
2013-07-29 08:12:41 +00:00
|
|
|
/// The parser structure for interpreting the input format string. This is
|
2015-10-13 13:44:11 +00:00
|
|
|
/// modeled as an iterator over `Piece` structures to form a stream of tokens
|
2013-07-29 08:12:41 +00:00
|
|
|
/// being output.
|
|
|
|
///
|
|
|
|
/// This is a recursive-descent parser for the sake of simplicity, and if
|
|
|
|
/// necessary there's probably lots of room for improvement performance-wise.
|
2013-12-10 07:16:18 +00:00
|
|
|
pub struct Parser<'a> {
|
2020-02-12 15:47:43 +00:00
|
|
|
mode: ParseMode,
|
2014-03-27 22:09:47 +00:00
|
|
|
input: &'a str,
|
2025-01-23 09:16:08 +00:00
|
|
|
cur: std::iter::Peekable<std::str::CharIndices<'a>>,
|
Remove std::condition
This has been a long time coming. Conditions in rust were initially envisioned
as being a good alternative to error code return pattern. The idea is that all
errors are fatal-by-default, and you can opt-in to handling the error by
registering an error handler.
While sounding nice, conditions ended up having some unforseen shortcomings:
* Actually handling an error has some very awkward syntax:
let mut result = None;
let mut answer = None;
io::io_error::cond.trap(|e| { result = Some(e) }).inside(|| {
answer = Some(some_io_operation());
});
match result {
Some(err) => { /* hit an I/O error */ }
None => {
let answer = answer.unwrap();
/* deal with the result of I/O */
}
}
This pattern can certainly use functions like io::result, but at its core
actually handling conditions is fairly difficult
* The "zero value" of a function is often confusing. One of the main ideas
behind using conditions was to change the signature of I/O functions. Instead
of read_be_u32() returning a result, it returned a u32. Errors were notified
via a condition, and if you caught the condition you understood that the "zero
value" returned is actually a garbage value. These zero values are often
difficult to understand, however.
One case of this is the read_bytes() function. The function takes an integer
length of the amount of bytes to read, and returns an array of that size. The
array may actually be shorter, however, if an error occurred.
Another case is fs::stat(). The theoretical "zero value" is a blank stat
struct, but it's a little awkward to create and return a zero'd out stat
struct on a call to stat().
In general, the return value of functions that can raise error are much more
natural when using a Result as opposed to an always-usable zero-value.
* Conditions impose a necessary runtime requirement on *all* I/O. In theory I/O
is as simple as calling read() and write(), but using conditions imposed the
restriction that a rust local task was required if you wanted to catch errors
with I/O. While certainly an surmountable difficulty, this was always a bit of
a thorn in the side of conditions.
* Functions raising conditions are not always clear that they are raising
conditions. This suffers a similar problem to exceptions where you don't
actually know whether a function raises a condition or not. The documentation
likely explains, but if someone retroactively adds a condition to a function
there's nothing forcing upstream users to acknowledge a new point of task
failure.
* Libaries using I/O are not guaranteed to correctly raise on conditions when an
error occurs. In developing various I/O libraries, it's much easier to just
return `None` from a read rather than raising an error. The silent contract of
"don't raise on EOF" was a little difficult to understand and threw a wrench
into the answer of the question "when do I raise a condition?"
Many of these difficulties can be overcome through documentation, examples, and
general practice. In the end, all of these difficulties added together ended up
being too overwhelming and improving various aspects didn't end up helping that
much.
A result-based I/O error handling strategy also has shortcomings, but the
cognitive burden is much smaller. The tooling necessary to make this strategy as
usable as conditions were is much smaller than the tooling necessary for
conditions.
Perhaps conditions may manifest themselves as a future entity, but for now
we're going to remove them from the standard library.
Closes #9795
Closes #8968
2014-02-05 03:02:10 +00:00
|
|
|
/// Error messages accumulated during parsing
|
2018-05-10 16:09:58 +00:00
|
|
|
pub errors: Vec<ParseError>,
|
2016-05-16 06:10:54 +00:00
|
|
|
/// Current position of implicit positional argument pointer
|
asm: Allow multiple template strings; interpret them as newline-separated
Allow the `asm!` macro to accept a series of template arguments, and
interpret them as if they were concatenated with a '\n' between them.
This allows writing an `asm!` where each line of assembly appears in a
separate template string argument.
This syntax makes it possible for rustfmt to reliably format and indent
each line of assembly, without risking changes to the inside of a
template string. It also avoids the complexity of having the user
carefully format and indent a multi-line string (including where to put
the surrounding quotes), and avoids the extra indentation and lines of a
call to `concat!`.
For example, rewriting the second example from the [blog post on the new
inline assembly
syntax](https://blog.rust-lang.org/inside-rust/2020/06/08/new-inline-asm.html)
using multiple template strings:
```rust
fn main() {
let mut bits = [0u8; 64];
for value in 0..=1024u64 {
let popcnt;
unsafe {
asm!(
" popcnt {popcnt}, {v}",
"2:",
" blsi rax, {v}",
" jz 1f",
" xor {v}, rax",
" tzcnt rax, rax",
" stosb",
" jmp 2b",
"1:",
v = inout(reg) value => _,
popcnt = out(reg) popcnt,
out("rax") _, // scratch
inout("rdi") bits.as_mut_ptr() => _,
);
}
println!("bits of {}: {:?}", value, &bits[0..popcnt]);
}
}
```
Note that all the template strings must appear before all other
arguments; you cannot, for instance, provide a series of template
strings intermixed with the corresponding operands.
In order to get srcloc mappings right for macros that generate
multi-line string literals, create one line_span for each
line in the string literal, each pointing to the macro.
Make `rustc_parse_format::Parser::curarg` `pub`, so that we can
propagate it from one template string argument to the next.
2020-06-15 06:33:55 +00:00
|
|
|
pub curarg: usize,
|
2018-07-21 23:18:06 +00:00
|
|
|
/// `Some(raw count)` when the string is "raw", used to position spans correctly
|
|
|
|
style: Option<usize>,
|
2018-08-19 13:30:23 +00:00
|
|
|
/// Start and end byte offset of every successfully parsed argument
|
2019-06-04 15:03:43 +00:00
|
|
|
pub arg_places: Vec<InnerSpan>,
|
2022-11-22 04:36:11 +00:00
|
|
|
/// Characters whose length has been changed from their in-code representation
|
|
|
|
width_map: Vec<InnerWidthMapping>,
|
2019-06-04 15:03:43 +00:00
|
|
|
/// Span of the last opening brace seen, used for error reporting
|
|
|
|
last_opening_brace: Option<InnerSpan>,
|
2020-03-06 11:13:55 +00:00
|
|
|
/// Whether the source string is comes from `println!` as opposed to `format!` or `print!`
|
2018-12-21 06:33:16 +00:00
|
|
|
append_newline: bool,
|
2023-01-05 19:17:30 +00:00
|
|
|
/// Whether this formatting string was written directly in the source. This controls whether we
|
|
|
|
/// can use spans to refer into it and give better error messages.
|
|
|
|
/// N.B: This does _not_ control whether implicit argument captures can be used.
|
|
|
|
pub is_source_literal: bool,
|
2020-05-26 19:07:59 +00:00
|
|
|
/// Start position of the current line.
|
|
|
|
cur_line_start: usize,
|
|
|
|
/// Start and end byte offset of every line of the format string. Excludes
|
|
|
|
/// newline characters and leading whitespace.
|
|
|
|
pub line_spans: Vec<InnerSpan>,
|
2018-12-21 06:33:16 +00:00
|
|
|
}
|
|
|
|
|
2015-01-02 03:36:34 +00:00
|
|
|
impl<'a> Iterator for Parser<'a> {
|
|
|
|
type Item = Piece<'a>;
|
|
|
|
|
2013-12-10 07:16:18 +00:00
|
|
|
fn next(&mut self) -> Option<Piece<'a>> {
|
2015-09-10 13:48:11 +00:00
|
|
|
if let Some(&(pos, c)) = self.cur.peek() {
|
|
|
|
match c {
|
|
|
|
'{' => {
|
2019-06-04 15:03:43 +00:00
|
|
|
let curr_last_brace = self.last_opening_brace;
|
|
|
|
let byte_pos = self.to_span_index(pos);
|
2022-11-22 04:36:11 +00:00
|
|
|
let lbrace_end = InnerOffset(byte_pos.0 + self.to_span_width(pos));
|
2022-07-31 15:11:00 +00:00
|
|
|
self.last_opening_brace = Some(byte_pos.to(lbrace_end));
|
2015-09-10 13:48:11 +00:00
|
|
|
self.cur.next();
|
|
|
|
if self.consume('{') {
|
2019-06-04 15:03:43 +00:00
|
|
|
self.last_opening_brace = curr_last_brace;
|
2018-12-21 06:33:16 +00:00
|
|
|
|
2025-01-23 09:16:08 +00:00
|
|
|
Some(Piece::Lit(self.string(pos + 1)))
|
2015-09-10 13:48:11 +00:00
|
|
|
} else {
|
2022-07-31 15:11:00 +00:00
|
|
|
let arg = self.argument(lbrace_end);
|
2023-07-17 00:36:00 +00:00
|
|
|
if let Some(rbrace_pos) = self.consume_closing_brace(&arg) {
|
2023-01-05 19:17:30 +00:00
|
|
|
if self.is_source_literal {
|
2022-11-22 04:36:11 +00:00
|
|
|
let lbrace_byte_pos = self.to_span_index(pos);
|
|
|
|
let rbrace_byte_pos = self.to_span_index(rbrace_pos);
|
|
|
|
|
|
|
|
let width = self.to_span_width(rbrace_pos);
|
|
|
|
|
2022-08-04 02:51:25 +00:00
|
|
|
self.arg_places.push(
|
2022-11-22 04:36:11 +00:00
|
|
|
lbrace_byte_pos.to(InnerOffset(rbrace_byte_pos.0 + width)),
|
2022-08-04 02:51:25 +00:00
|
|
|
);
|
2020-02-12 15:47:43 +00:00
|
|
|
}
|
2024-05-30 01:51:27 +00:00
|
|
|
} else if let Some(&(_, maybe)) = self.cur.peek() {
|
|
|
|
match maybe {
|
|
|
|
'?' => self.suggest_format_debug(),
|
|
|
|
'<' | '^' | '>' => self.suggest_format_align(maybe),
|
|
|
|
_ => self.suggest_positional_arg_instead_of_captured_arg(arg),
|
2023-01-08 22:48:41 +00:00
|
|
|
}
|
2018-07-23 05:40:24 +00:00
|
|
|
}
|
2025-01-23 09:16:08 +00:00
|
|
|
Some(Piece::NextArgument(Box::new(arg)))
|
2015-09-10 13:48:11 +00:00
|
|
|
}
|
2014-05-28 16:24:28 +00:00
|
|
|
}
|
2015-09-10 13:48:11 +00:00
|
|
|
'}' => {
|
|
|
|
self.cur.next();
|
|
|
|
if self.consume('}') {
|
2025-01-23 09:16:08 +00:00
|
|
|
Some(Piece::Lit(self.string(pos + 1)))
|
2015-09-10 13:48:11 +00:00
|
|
|
} else {
|
2018-12-21 06:33:16 +00:00
|
|
|
let err_pos = self.to_span_index(pos);
|
2018-05-10 16:09:58 +00:00
|
|
|
self.err_with_note(
|
|
|
|
"unmatched `}` found",
|
|
|
|
"unmatched `}`",
|
|
|
|
"if you intended to print `}`, you can escape it using `}}`",
|
2019-06-04 15:03:43 +00:00
|
|
|
err_pos.to(err_pos),
|
2018-05-10 16:09:58 +00:00
|
|
|
);
|
2015-09-10 13:48:11 +00:00
|
|
|
None
|
|
|
|
}
|
2014-05-28 16:24:28 +00:00
|
|
|
}
|
2025-01-23 09:16:08 +00:00
|
|
|
_ => Some(Piece::Lit(self.string(pos))),
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
2015-09-10 13:48:11 +00:00
|
|
|
} else {
|
2023-01-05 19:17:30 +00:00
|
|
|
if self.is_source_literal {
|
2022-08-21 16:19:48 +00:00
|
|
|
let span = self.span(self.cur_line_start, self.input.len());
|
asm: Allow multiple template strings; interpret them as newline-separated
Allow the `asm!` macro to accept a series of template arguments, and
interpret them as if they were concatenated with a '\n' between them.
This allows writing an `asm!` where each line of assembly appears in a
separate template string argument.
This syntax makes it possible for rustfmt to reliably format and indent
each line of assembly, without risking changes to the inside of a
template string. It also avoids the complexity of having the user
carefully format and indent a multi-line string (including where to put
the surrounding quotes), and avoids the extra indentation and lines of a
call to `concat!`.
For example, rewriting the second example from the [blog post on the new
inline assembly
syntax](https://blog.rust-lang.org/inside-rust/2020/06/08/new-inline-asm.html)
using multiple template strings:
```rust
fn main() {
let mut bits = [0u8; 64];
for value in 0..=1024u64 {
let popcnt;
unsafe {
asm!(
" popcnt {popcnt}, {v}",
"2:",
" blsi rax, {v}",
" jz 1f",
" xor {v}, rax",
" tzcnt rax, rax",
" stosb",
" jmp 2b",
"1:",
v = inout(reg) value => _,
popcnt = out(reg) popcnt,
out("rax") _, // scratch
inout("rdi") bits.as_mut_ptr() => _,
);
}
println!("bits of {}: {:?}", value, &bits[0..popcnt]);
}
}
```
Note that all the template strings must appear before all other
arguments; you cannot, for instance, provide a series of template
strings intermixed with the corresponding operands.
In order to get srcloc mappings right for macros that generate
multi-line string literals, create one line_span for each
line in the string literal, each pointing to the macro.
Make `rustc_parse_format::Parser::curarg` `pub`, so that we can
propagate it from one template string argument to the next.
2020-06-15 06:33:55 +00:00
|
|
|
if self.line_spans.last() != Some(&span) {
|
|
|
|
self.line_spans.push(span);
|
|
|
|
}
|
2020-05-26 19:07:59 +00:00
|
|
|
}
|
2015-09-10 13:48:11 +00:00
|
|
|
None
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-12-10 07:16:18 +00:00
|
|
|
impl<'a> Parser<'a> {
|
2013-07-29 08:12:41 +00:00
|
|
|
/// Creates a new parser for the given format string
|
2018-12-21 06:33:16 +00:00
|
|
|
pub fn new(
|
|
|
|
s: &'a str,
|
|
|
|
style: Option<usize>,
|
2025-01-23 09:16:08 +00:00
|
|
|
snippet: Option<String>,
|
2018-12-21 06:33:16 +00:00
|
|
|
append_newline: bool,
|
2020-02-12 15:47:43 +00:00
|
|
|
mode: ParseMode,
|
2018-12-21 06:33:16 +00:00
|
|
|
) -> Parser<'a> {
|
2023-03-13 18:52:41 +00:00
|
|
|
let input_string_kind = find_width_map_from_snippet(s, snippet, style);
|
2023-01-05 19:17:30 +00:00
|
|
|
let (width_map, is_source_literal) = match input_string_kind {
|
2022-12-27 22:00:03 +00:00
|
|
|
InputStringKind::Literal { width_mappings } => (width_mappings, true),
|
|
|
|
InputStringKind::NotALiteral => (Vec::new(), false),
|
|
|
|
};
|
2023-01-18 18:47:22 +00:00
|
|
|
|
2013-07-29 08:12:41 +00:00
|
|
|
Parser {
|
2020-02-12 15:47:43 +00:00
|
|
|
mode,
|
2013-07-29 08:12:41 +00:00
|
|
|
input: s,
|
2015-09-10 12:03:22 +00:00
|
|
|
cur: s.char_indices().peekable(),
|
2015-11-23 23:11:20 +00:00
|
|
|
errors: vec![],
|
2016-05-16 06:10:54 +00:00
|
|
|
curarg: 0,
|
2018-07-20 06:14:00 +00:00
|
|
|
style,
|
2018-07-23 05:40:24 +00:00
|
|
|
arg_places: vec![],
|
2022-11-22 04:36:11 +00:00
|
|
|
width_map,
|
2019-06-04 15:03:43 +00:00
|
|
|
last_opening_brace: None,
|
2018-12-21 06:33:16 +00:00
|
|
|
append_newline,
|
2023-01-05 19:17:30 +00:00
|
|
|
is_source_literal,
|
2020-05-26 19:07:59 +00:00
|
|
|
cur_line_start: 0,
|
|
|
|
line_spans: vec![],
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Notifies of an error. The message doesn't actually need to be of type
|
2014-05-22 23:57:53 +00:00
|
|
|
/// String, but I think it does when this eventually uses conditions so it
|
2013-07-29 08:12:41 +00:00
|
|
|
/// might as well start using it now.
|
2025-01-23 09:16:08 +00:00
|
|
|
fn err(&mut self, description: impl Into<String>, label: impl Into<String>, span: InnerSpan) {
|
2018-05-10 16:09:58 +00:00
|
|
|
self.errors.push(ParseError {
|
|
|
|
description: description.into(),
|
|
|
|
note: None,
|
|
|
|
label: label.into(),
|
2019-06-04 15:03:43 +00:00
|
|
|
span,
|
2018-12-21 06:33:16 +00:00
|
|
|
secondary_label: None,
|
2023-09-06 14:32:06 +00:00
|
|
|
suggestion: Suggestion::None,
|
2018-05-10 16:09:58 +00:00
|
|
|
});
|
2016-11-10 20:48:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Notifies of an error. The message doesn't actually need to be of type
|
|
|
|
/// String, but I think it does when this eventually uses conditions so it
|
|
|
|
/// might as well start using it now.
|
2025-01-23 09:16:08 +00:00
|
|
|
fn err_with_note(
|
2018-05-10 16:09:58 +00:00
|
|
|
&mut self,
|
2025-01-23 09:16:08 +00:00
|
|
|
description: impl Into<String>,
|
|
|
|
label: impl Into<String>,
|
|
|
|
note: impl Into<String>,
|
2019-06-04 15:03:43 +00:00
|
|
|
span: InnerSpan,
|
2018-05-10 16:09:58 +00:00
|
|
|
) {
|
|
|
|
self.errors.push(ParseError {
|
|
|
|
description: description.into(),
|
|
|
|
note: Some(note.into()),
|
|
|
|
label: label.into(),
|
2019-06-04 15:03:43 +00:00
|
|
|
span,
|
2018-12-21 06:33:16 +00:00
|
|
|
secondary_label: None,
|
2023-09-06 14:32:06 +00:00
|
|
|
suggestion: Suggestion::None,
|
2018-05-10 16:09:58 +00:00
|
|
|
});
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Optionally consumes the specified character. If the character is not at
|
On `format!()` arg count mismatch provide extra info
When positional width and precision formatting flags are present in a
formatting string that has an argument count mismatch, provide extra
information pointing at them making it easiser to understand where the
problem may lay:
```
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:78:15
|
LL | println!("{} {:.*} {}", 1, 3.2, 4);
| ^^ ^^--^ ^^ --- this parameter corresponds to the precision flag
| |
| this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:81:15
|
LL | println!("{} {:07$.*} {}", 1, 3.2, 4);
| ^^ ^^-----^ ^^ --- this parameter corresponds to the precision flag
| | |
| | this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 3 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:84:15
|
LL | println!("{} {:07$} {}", 1, 3.2, 4);
| ^^ ^^---^ ^^
| |
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
```
2019-07-30 01:19:21 +00:00
|
|
|
/// the current position, then the current iterator isn't moved and `false` is
|
|
|
|
/// returned, otherwise the character is consumed and `true` is returned.
|
2013-07-29 08:12:41 +00:00
|
|
|
fn consume(&mut self, c: char) -> bool {
|
On `format!()` arg count mismatch provide extra info
When positional width and precision formatting flags are present in a
formatting string that has an argument count mismatch, provide extra
information pointing at them making it easiser to understand where the
problem may lay:
```
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:78:15
|
LL | println!("{} {:.*} {}", 1, 3.2, 4);
| ^^ ^^--^ ^^ --- this parameter corresponds to the precision flag
| |
| this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:81:15
|
LL | println!("{} {:07$.*} {}", 1, 3.2, 4);
| ^^ ^^-----^ ^^ --- this parameter corresponds to the precision flag
| | |
| | this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 3 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:84:15
|
LL | println!("{} {:07$} {}", 1, 3.2, 4);
| ^^ ^^---^ ^^
| |
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
```
2019-07-30 01:19:21 +00:00
|
|
|
self.consume_pos(c).is_some()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Optionally consumes the specified character. If the character is not at
|
|
|
|
/// the current position, then the current iterator isn't moved and `None` is
|
|
|
|
/// returned, otherwise the character is consumed and the current position is
|
|
|
|
/// returned.
|
|
|
|
fn consume_pos(&mut self, c: char) -> Option<usize> {
|
|
|
|
if let Some(&(pos, maybe)) = self.cur.peek() {
|
2015-10-13 14:10:51 +00:00
|
|
|
if c == maybe {
|
|
|
|
self.cur.next();
|
On `format!()` arg count mismatch provide extra info
When positional width and precision formatting flags are present in a
formatting string that has an argument count mismatch, provide extra
information pointing at them making it easiser to understand where the
problem may lay:
```
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:78:15
|
LL | println!("{} {:.*} {}", 1, 3.2, 4);
| ^^ ^^--^ ^^ --- this parameter corresponds to the precision flag
| |
| this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:81:15
|
LL | println!("{} {:07$.*} {}", 1, 3.2, 4);
| ^^ ^^-----^ ^^ --- this parameter corresponds to the precision flag
| | |
| | this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 3 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:84:15
|
LL | println!("{} {:07$} {}", 1, 3.2, 4);
| ^^ ^^---^ ^^
| |
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
```
2019-07-30 01:19:21 +00:00
|
|
|
return Some(pos);
|
2015-10-13 14:10:51 +00:00
|
|
|
}
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
On `format!()` arg count mismatch provide extra info
When positional width and precision formatting flags are present in a
formatting string that has an argument count mismatch, provide extra
information pointing at them making it easiser to understand where the
problem may lay:
```
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:78:15
|
LL | println!("{} {:.*} {}", 1, 3.2, 4);
| ^^ ^^--^ ^^ --- this parameter corresponds to the precision flag
| |
| this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:81:15
|
LL | println!("{} {:07$.*} {}", 1, 3.2, 4);
| ^^ ^^-----^ ^^ --- this parameter corresponds to the precision flag
| | |
| | this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 3 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:84:15
|
LL | println!("{} {:07$} {}", 1, 3.2, 4);
| ^^ ^^---^ ^^
| |
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
```
2019-07-30 01:19:21 +00:00
|
|
|
None
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
|
2022-11-22 04:36:11 +00:00
|
|
|
fn remap_pos(&self, mut pos: usize) -> InnerOffset {
|
|
|
|
for width in &self.width_map {
|
|
|
|
if pos > width.position {
|
|
|
|
pos += width.before - width.after;
|
|
|
|
} else if pos == width.position && width.after == 0 {
|
|
|
|
pos += width.before;
|
|
|
|
} else {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
InnerOffset(pos)
|
|
|
|
}
|
|
|
|
|
2019-06-04 15:03:43 +00:00
|
|
|
fn to_span_index(&self, pos: usize) -> InnerOffset {
|
2019-06-07 00:38:34 +00:00
|
|
|
// This handles the raw string case, the raw argument is the number of #
|
|
|
|
// in r###"..."### (we need to add one because of the `r`).
|
2021-01-11 19:45:33 +00:00
|
|
|
let raw = self.style.map_or(0, |raw| raw + 1);
|
2022-11-22 04:36:11 +00:00
|
|
|
let pos = self.remap_pos(pos);
|
|
|
|
InnerOffset(raw + pos.0 + 1)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn to_span_width(&self, pos: usize) -> usize {
|
|
|
|
let pos = self.remap_pos(pos);
|
|
|
|
match self.width_map.iter().find(|w| w.position == pos.0) {
|
|
|
|
Some(w) => w.before,
|
|
|
|
None => 1,
|
2018-12-21 06:33:16 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-21 16:19:48 +00:00
|
|
|
fn span(&self, start_pos: usize, end_pos: usize) -> InnerSpan {
|
|
|
|
let start = self.to_span_index(start_pos);
|
|
|
|
let end = self.to_span_index(end_pos);
|
|
|
|
start.to(end)
|
|
|
|
}
|
|
|
|
|
2013-10-18 17:30:40 +00:00
|
|
|
/// Forces consumption of the specified character. If the character is not
|
|
|
|
/// found, an error is emitted.
|
2023-07-17 00:36:00 +00:00
|
|
|
fn consume_closing_brace(&mut self, arg: &Argument<'_>) -> Option<usize> {
|
2013-10-18 17:30:40 +00:00
|
|
|
self.ws();
|
2018-07-20 16:15:22 +00:00
|
|
|
|
2023-07-17 00:36:00 +00:00
|
|
|
let pos;
|
|
|
|
let description;
|
|
|
|
|
|
|
|
if let Some(&(peek_pos, maybe)) = self.cur.peek() {
|
|
|
|
if maybe == '}' {
|
2013-10-18 17:30:40 +00:00
|
|
|
self.cur.next();
|
2023-07-17 00:36:00 +00:00
|
|
|
return Some(peek_pos);
|
2013-10-18 17:30:40 +00:00
|
|
|
}
|
2023-07-17 00:36:00 +00:00
|
|
|
|
|
|
|
pos = peek_pos;
|
2024-10-14 21:22:51 +00:00
|
|
|
description = format!("expected `}}`, found `{}`", maybe.escape_debug());
|
2015-09-10 13:48:11 +00:00
|
|
|
} else {
|
2024-10-14 21:22:51 +00:00
|
|
|
description = "expected `}` but string was terminated".to_owned();
|
2018-12-21 06:33:16 +00:00
|
|
|
// point at closing `"`
|
2023-07-17 00:36:00 +00:00
|
|
|
pos = self.input.len() - if self.append_newline { 1 } else { 0 };
|
2013-10-18 17:30:40 +00:00
|
|
|
}
|
2023-07-17 00:36:00 +00:00
|
|
|
|
|
|
|
let pos = self.to_span_index(pos);
|
|
|
|
|
2024-10-14 21:22:51 +00:00
|
|
|
let label = "expected `}`".to_owned();
|
2023-07-17 00:36:00 +00:00
|
|
|
let (note, secondary_label) = if arg.format.fill == Some('}') {
|
|
|
|
(
|
2024-10-14 21:22:51 +00:00
|
|
|
Some("the character `}` is interpreted as a fill character because of the `:` that precedes it".to_owned()),
|
2023-07-17 00:36:00 +00:00
|
|
|
arg.format.fill_span.map(|sp| ("this is not interpreted as a formatting closing brace".to_owned(), sp)),
|
|
|
|
)
|
|
|
|
} else {
|
|
|
|
(
|
|
|
|
Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
|
|
|
|
self.last_opening_brace.map(|sp| ("because of this opening brace".to_owned(), sp)),
|
|
|
|
)
|
|
|
|
};
|
|
|
|
|
|
|
|
self.errors.push(ParseError {
|
|
|
|
description,
|
|
|
|
note,
|
|
|
|
label,
|
|
|
|
span: pos.to(pos),
|
|
|
|
secondary_label,
|
2023-09-06 14:32:06 +00:00
|
|
|
suggestion: Suggestion::None,
|
2023-07-17 00:36:00 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
None
|
2013-10-18 17:30:40 +00:00
|
|
|
}
|
|
|
|
|
2018-12-21 06:33:16 +00:00
|
|
|
/// Consumes all whitespace characters until the first non-whitespace character
|
2013-07-29 08:12:41 +00:00
|
|
|
fn ws(&mut self) {
|
2025-01-23 08:44:23 +00:00
|
|
|
while let Some(_) = self.cur.next_if(|&(_, c)| c.is_whitespace()) {}
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Parses all of a string which is to be considered a "raw literal" in a
|
|
|
|
/// format string. This is everything outside of the braces.
|
2015-02-23 03:07:38 +00:00
|
|
|
fn string(&mut self, start: usize) -> &'a str {
|
2015-09-10 13:48:11 +00:00
|
|
|
// we may not consume the character, peek the iterator
|
|
|
|
while let Some(&(pos, c)) = self.cur.peek() {
|
|
|
|
match c {
|
2015-10-13 14:10:51 +00:00
|
|
|
'{' | '}' => {
|
|
|
|
return &self.input[start..pos];
|
|
|
|
}
|
2023-01-05 19:17:30 +00:00
|
|
|
'\n' if self.is_source_literal => {
|
2022-08-21 16:19:48 +00:00
|
|
|
self.line_spans.push(self.span(self.cur_line_start, pos));
|
2020-05-26 19:07:59 +00:00
|
|
|
self.cur_line_start = pos + 1;
|
|
|
|
self.cur.next();
|
|
|
|
}
|
2015-10-13 14:10:51 +00:00
|
|
|
_ => {
|
2023-01-05 19:17:30 +00:00
|
|
|
if self.is_source_literal && pos == self.cur_line_start && c.is_whitespace() {
|
2020-05-26 19:07:59 +00:00
|
|
|
self.cur_line_start = pos + c.len_utf8();
|
|
|
|
}
|
2015-10-13 14:10:51 +00:00
|
|
|
self.cur.next();
|
|
|
|
}
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
}
|
2025-01-22 15:46:40 +00:00
|
|
|
&self.input[start..]
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
|
2019-09-30 00:08:15 +00:00
|
|
|
/// Parses an `Argument` structure, or what's contained within braces inside the format string.
|
2022-07-31 15:11:00 +00:00
|
|
|
fn argument(&mut self, start: InnerOffset) -> Argument<'a> {
|
2016-05-16 17:02:42 +00:00
|
|
|
let pos = self.position();
|
2022-07-31 15:11:00 +00:00
|
|
|
|
|
|
|
let end = self
|
|
|
|
.cur
|
|
|
|
.clone()
|
|
|
|
.find(|(_, ch)| !ch.is_whitespace())
|
|
|
|
.map_or(start, |(end, _)| self.to_span_index(end));
|
|
|
|
let position_span = start.to(end);
|
|
|
|
|
2020-02-12 15:47:43 +00:00
|
|
|
let format = match self.mode {
|
|
|
|
ParseMode::Format => self.format(),
|
|
|
|
ParseMode::InlineAsm => self.inline_asm(),
|
|
|
|
};
|
2016-05-16 06:10:54 +00:00
|
|
|
|
2016-05-16 17:02:42 +00:00
|
|
|
// Resolve position after parsing format spec.
|
|
|
|
let pos = match pos {
|
|
|
|
Some(position) => position,
|
|
|
|
None => {
|
2016-05-16 06:10:54 +00:00
|
|
|
let i = self.curarg;
|
|
|
|
self.curarg += 1;
|
2017-11-09 17:16:25 +00:00
|
|
|
ArgumentImplicitlyIs(i)
|
2016-05-16 06:10:54 +00:00
|
|
|
}
|
2016-05-16 17:02:42 +00:00
|
|
|
};
|
2016-05-16 06:10:54 +00:00
|
|
|
|
2022-07-31 15:11:00 +00:00
|
|
|
Argument { position: pos, position_span, format }
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Parses a positional argument for a format. This could either be an
|
|
|
|
/// integer index of an argument, a named argument, or a blank string.
|
2016-05-16 17:02:42 +00:00
|
|
|
/// Returns `Some(parsed_position)` if the position is not implicitly
|
|
|
|
/// consuming a macro argument, `None` if it's the case.
|
2022-04-29 16:48:58 +00:00
|
|
|
fn position(&mut self) -> Option<Position<'a>> {
|
2015-09-10 13:48:11 +00:00
|
|
|
if let Some(i) = self.integer() {
|
2025-02-12 15:59:13 +00:00
|
|
|
Some(ArgumentIs(i.into()))
|
2015-09-10 13:48:11 +00:00
|
|
|
} else {
|
|
|
|
match self.cur.peek() {
|
2023-09-06 14:32:06 +00:00
|
|
|
Some(&(lo, c)) if rustc_lexer::is_id_start(c) => {
|
|
|
|
let word = self.word();
|
|
|
|
|
|
|
|
// Recover from `r#ident` in format strings.
|
|
|
|
// FIXME: use a let chain
|
|
|
|
if word == "r" {
|
|
|
|
if let Some((pos, '#')) = self.cur.peek() {
|
|
|
|
if self.input[pos + 1..]
|
|
|
|
.chars()
|
|
|
|
.next()
|
|
|
|
.is_some_and(rustc_lexer::is_id_start)
|
|
|
|
{
|
|
|
|
self.cur.next();
|
|
|
|
let word = self.word();
|
|
|
|
let prefix_span = self.span(lo, lo + 2);
|
|
|
|
let full_span = self.span(lo, lo + 2 + word.len());
|
|
|
|
self.errors.insert(0, ParseError {
|
|
|
|
description: "raw identifiers are not supported".to_owned(),
|
|
|
|
note: Some("identifiers in format strings can be keywords and don't need to be prefixed with `r#`".to_string()),
|
|
|
|
label: "raw identifier used here".to_owned(),
|
|
|
|
span: full_span,
|
|
|
|
secondary_label: None,
|
|
|
|
suggestion: Suggestion::RemoveRawIdent(prefix_span),
|
|
|
|
});
|
|
|
|
return Some(ArgumentNamed(word));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Some(ArgumentNamed(word))
|
|
|
|
}
|
2016-05-16 17:02:42 +00:00
|
|
|
|
|
|
|
// This is an `ArgumentNext`.
|
|
|
|
// Record the fact and do the resolution after parsing the
|
|
|
|
// format spec, to make things like `{:.*}` work.
|
|
|
|
_ => None,
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-21 16:19:48 +00:00
|
|
|
fn current_pos(&mut self) -> usize {
|
|
|
|
if let Some(&(pos, _)) = self.cur.peek() { pos } else { self.input.len() }
|
|
|
|
}
|
|
|
|
|
2013-07-29 08:12:41 +00:00
|
|
|
/// Parses a format specifier at the current position, returning all of the
|
2019-09-30 00:08:15 +00:00
|
|
|
/// relevant information in the `FormatSpec` struct.
|
2013-12-10 07:16:18 +00:00
|
|
|
fn format(&mut self) -> FormatSpec<'a> {
|
2013-07-29 08:12:41 +00:00
|
|
|
let mut spec = FormatSpec {
|
|
|
|
fill: None,
|
2023-07-17 00:36:00 +00:00
|
|
|
fill_span: None,
|
2013-08-10 23:50:42 +00:00
|
|
|
align: AlignUnknown,
|
2023-01-13 12:32:49 +00:00
|
|
|
sign: None,
|
|
|
|
alternate: false,
|
|
|
|
zero_pad: false,
|
|
|
|
debug_hex: None,
|
2013-07-29 08:12:41 +00:00
|
|
|
precision: CountImplied,
|
On `format!()` arg count mismatch provide extra info
When positional width and precision formatting flags are present in a
formatting string that has an argument count mismatch, provide extra
information pointing at them making it easiser to understand where the
problem may lay:
```
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:78:15
|
LL | println!("{} {:.*} {}", 1, 3.2, 4);
| ^^ ^^--^ ^^ --- this parameter corresponds to the precision flag
| |
| this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:81:15
|
LL | println!("{} {:07$.*} {}", 1, 3.2, 4);
| ^^ ^^-----^ ^^ --- this parameter corresponds to the precision flag
| | |
| | this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 3 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:84:15
|
LL | println!("{} {:07$} {}", 1, 3.2, 4);
| ^^ ^^---^ ^^
| |
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
```
2019-07-30 01:19:21 +00:00
|
|
|
precision_span: None,
|
2013-07-29 08:12:41 +00:00
|
|
|
width: CountImplied,
|
On `format!()` arg count mismatch provide extra info
When positional width and precision formatting flags are present in a
formatting string that has an argument count mismatch, provide extra
information pointing at them making it easiser to understand where the
problem may lay:
```
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:78:15
|
LL | println!("{} {:.*} {}", 1, 3.2, 4);
| ^^ ^^--^ ^^ --- this parameter corresponds to the precision flag
| |
| this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:81:15
|
LL | println!("{} {:07$.*} {}", 1, 3.2, 4);
| ^^ ^^-----^ ^^ --- this parameter corresponds to the precision flag
| | |
| | this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 3 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:84:15
|
LL | println!("{} {:07$} {}", 1, 3.2, 4);
| ^^ ^^---^ ^^
| |
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
```
2019-07-30 01:19:21 +00:00
|
|
|
width_span: None,
|
2015-01-12 21:59:18 +00:00
|
|
|
ty: &self.input[..0],
|
Point at formatting descriptor string when it is invalid
When a formatting string contains an invalid descriptor, point at it
instead of the argument:
```
error: unknown format trait `foo`
--> $DIR/ifmt-bad-arg.rs:86:17
|
LL | println!("{:foo}", 1);
| ^^^
|
= note: the only appropriate formatting traits are:
- ``, which uses the `Display` trait
- `?`, which uses the `Debug` trait
- `e`, which uses the `LowerExp` trait
- `E`, which uses the `UpperExp` trait
- `o`, which uses the `Octal` trait
- `p`, which uses the `Pointer` trait
- `b`, which uses the `Binary` trait
- `x`, which uses the `LowerHex` trait
- `X`, which uses the `UpperHex` trait
```
2019-11-05 19:55:00 +00:00
|
|
|
ty_span: None,
|
2013-07-29 08:12:41 +00:00
|
|
|
};
|
2015-10-13 14:10:51 +00:00
|
|
|
if !self.consume(':') {
|
2015-11-23 23:11:20 +00:00
|
|
|
return spec;
|
2015-10-13 14:10:51 +00:00
|
|
|
}
|
2013-07-29 08:12:41 +00:00
|
|
|
|
|
|
|
// fill character
|
2023-07-17 00:36:00 +00:00
|
|
|
if let Some(&(idx, c)) = self.cur.peek() {
|
2020-09-18 16:33:37 +00:00
|
|
|
if let Some((_, '>' | '<' | '^')) = self.cur.clone().nth(1) {
|
|
|
|
spec.fill = Some(c);
|
2023-07-17 00:36:00 +00:00
|
|
|
spec.fill_span = Some(self.span(idx, idx + 1));
|
2020-09-18 16:33:37 +00:00
|
|
|
self.cur.next();
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
// Alignment
|
|
|
|
if self.consume('<') {
|
2013-08-10 23:50:42 +00:00
|
|
|
spec.align = AlignLeft;
|
2013-07-29 08:12:41 +00:00
|
|
|
} else if self.consume('>') {
|
2013-08-10 23:50:42 +00:00
|
|
|
spec.align = AlignRight;
|
2014-08-30 18:27:02 +00:00
|
|
|
} else if self.consume('^') {
|
|
|
|
spec.align = AlignCenter;
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
// Sign flags
|
|
|
|
if self.consume('+') {
|
2023-01-13 12:32:49 +00:00
|
|
|
spec.sign = Some(Sign::Plus);
|
2013-07-29 08:12:41 +00:00
|
|
|
} else if self.consume('-') {
|
2023-01-13 12:32:49 +00:00
|
|
|
spec.sign = Some(Sign::Minus);
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
// Alternate marker
|
|
|
|
if self.consume('#') {
|
2023-01-13 12:32:49 +00:00
|
|
|
spec.alternate = true;
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
// Width and precision
|
2013-10-13 03:00:58 +00:00
|
|
|
let mut havewidth = false;
|
On `format!()` arg count mismatch provide extra info
When positional width and precision formatting flags are present in a
formatting string that has an argument count mismatch, provide extra
information pointing at them making it easiser to understand where the
problem may lay:
```
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:78:15
|
LL | println!("{} {:.*} {}", 1, 3.2, 4);
| ^^ ^^--^ ^^ --- this parameter corresponds to the precision flag
| |
| this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:81:15
|
LL | println!("{} {:07$.*} {}", 1, 3.2, 4);
| ^^ ^^-----^ ^^ --- this parameter corresponds to the precision flag
| | |
| | this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 3 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:84:15
|
LL | println!("{} {:07$} {}", 1, 3.2, 4);
| ^^ ^^---^ ^^
| |
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
```
2019-07-30 01:19:21 +00:00
|
|
|
|
2013-08-10 23:50:42 +00:00
|
|
|
if self.consume('0') {
|
2013-10-13 03:00:58 +00:00
|
|
|
// small ambiguity with '0$' as a format string. In theory this is a
|
|
|
|
// '0' flag and then an ill-formatted format string with just a '$'
|
|
|
|
// and no count, but this is better if we instead interpret this as
|
|
|
|
// no '0' flag and '0$' as the width instead.
|
2022-07-19 21:25:26 +00:00
|
|
|
if let Some(end) = self.consume_pos('$') {
|
2013-10-13 03:00:58 +00:00
|
|
|
spec.width = CountIsParam(0);
|
2022-08-21 16:19:48 +00:00
|
|
|
spec.width_span = Some(self.span(end - 1, end + 1));
|
2013-10-13 03:00:58 +00:00
|
|
|
havewidth = true;
|
|
|
|
} else {
|
2023-01-13 12:32:49 +00:00
|
|
|
spec.zero_pad = true;
|
2013-10-13 03:00:58 +00:00
|
|
|
}
|
|
|
|
}
|
2022-08-21 16:19:48 +00:00
|
|
|
|
2013-10-13 03:00:58 +00:00
|
|
|
if !havewidth {
|
2022-08-21 16:19:48 +00:00
|
|
|
let start = self.current_pos();
|
|
|
|
spec.width = self.count(start);
|
|
|
|
if spec.width != CountImplied {
|
|
|
|
let end = self.current_pos();
|
|
|
|
spec.width_span = Some(self.span(start, end));
|
|
|
|
}
|
2013-08-10 23:50:42 +00:00
|
|
|
}
|
2022-07-16 21:13:14 +00:00
|
|
|
|
On `format!()` arg count mismatch provide extra info
When positional width and precision formatting flags are present in a
formatting string that has an argument count mismatch, provide extra
information pointing at them making it easiser to understand where the
problem may lay:
```
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:78:15
|
LL | println!("{} {:.*} {}", 1, 3.2, 4);
| ^^ ^^--^ ^^ --- this parameter corresponds to the precision flag
| |
| this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 4 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:81:15
|
LL | println!("{} {:07$.*} {}", 1, 3.2, 4);
| ^^ ^^-----^ ^^ --- this parameter corresponds to the precision flag
| | |
| | this precision flag adds an extra required argument at position 1, which is why there are 4 arguments expected
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
error: 3 positional arguments in format string, but there are 3 arguments
--> $DIR/ifmt-bad-arg.rs:84:15
|
LL | println!("{} {:07$} {}", 1, 3.2, 4);
| ^^ ^^---^ ^^
| |
| this width flag expects an `usize` argument at position 7, but there are 3 arguments
|
= note: positional arguments are zero-based
= note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html
```
2019-07-30 01:19:21 +00:00
|
|
|
if let Some(start) = self.consume_pos('.') {
|
2022-08-21 16:19:48 +00:00
|
|
|
if self.consume('*') {
|
2016-05-16 17:02:42 +00:00
|
|
|
// Resolve `CountIsNextParam`.
|
|
|
|
// We can do this immediately as `position` is resolved later.
|
|
|
|
let i = self.curarg;
|
|
|
|
self.curarg += 1;
|
2022-08-25 12:49:09 +00:00
|
|
|
spec.precision = CountIsStar(i);
|
2013-07-29 08:12:41 +00:00
|
|
|
} else {
|
2022-08-21 16:19:48 +00:00
|
|
|
spec.precision = self.count(start + 1);
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
2022-08-21 16:19:48 +00:00
|
|
|
let end = self.current_pos();
|
|
|
|
spec.precision_span = Some(self.span(start, end));
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
2022-08-21 16:19:48 +00:00
|
|
|
|
|
|
|
let ty_span_start = self.current_pos();
|
2018-03-13 13:08:15 +00:00
|
|
|
// Optional radix followed by the actual format specifier
|
|
|
|
if self.consume('x') {
|
|
|
|
if self.consume('?') {
|
2023-01-13 12:32:49 +00:00
|
|
|
spec.debug_hex = Some(DebugHex::Lower);
|
2018-03-13 13:08:15 +00:00
|
|
|
spec.ty = "?";
|
|
|
|
} else {
|
|
|
|
spec.ty = "x";
|
|
|
|
}
|
|
|
|
} else if self.consume('X') {
|
|
|
|
if self.consume('?') {
|
2023-01-13 12:32:49 +00:00
|
|
|
spec.debug_hex = Some(DebugHex::Upper);
|
2018-03-13 13:08:15 +00:00
|
|
|
spec.ty = "?";
|
|
|
|
} else {
|
|
|
|
spec.ty = "X";
|
|
|
|
}
|
|
|
|
} else if self.consume('?') {
|
2013-08-15 03:40:15 +00:00
|
|
|
spec.ty = "?";
|
2024-12-29 04:47:07 +00:00
|
|
|
if let Some(&(_, maybe)) = self.cur.peek() {
|
|
|
|
match maybe {
|
|
|
|
'#' | 'x' | 'X' => self.suggest_format_parameter(maybe),
|
|
|
|
_ => (),
|
|
|
|
}
|
|
|
|
}
|
2013-08-15 03:40:15 +00:00
|
|
|
} else {
|
|
|
|
spec.ty = self.word();
|
2019-11-06 00:02:12 +00:00
|
|
|
if !spec.ty.is_empty() {
|
2022-08-21 16:19:48 +00:00
|
|
|
let ty_span_end = self.current_pos();
|
|
|
|
spec.ty_span = Some(self.span(ty_span_start, ty_span_end));
|
2019-11-06 00:02:12 +00:00
|
|
|
}
|
2013-08-15 03:40:15 +00:00
|
|
|
}
|
2015-09-02 10:13:10 +00:00
|
|
|
spec
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
|
2020-02-12 15:47:43 +00:00
|
|
|
/// Parses an inline assembly template modifier at the current position, returning the modifier
|
|
|
|
/// in the `ty` field of the `FormatSpec` struct.
|
|
|
|
fn inline_asm(&mut self) -> FormatSpec<'a> {
|
|
|
|
let mut spec = FormatSpec {
|
|
|
|
fill: None,
|
2023-07-17 00:36:00 +00:00
|
|
|
fill_span: None,
|
2020-02-12 15:47:43 +00:00
|
|
|
align: AlignUnknown,
|
2023-01-13 12:32:49 +00:00
|
|
|
sign: None,
|
|
|
|
alternate: false,
|
|
|
|
zero_pad: false,
|
|
|
|
debug_hex: None,
|
2020-02-12 15:47:43 +00:00
|
|
|
precision: CountImplied,
|
|
|
|
precision_span: None,
|
|
|
|
width: CountImplied,
|
|
|
|
width_span: None,
|
|
|
|
ty: &self.input[..0],
|
|
|
|
ty_span: None,
|
|
|
|
};
|
|
|
|
if !self.consume(':') {
|
|
|
|
return spec;
|
|
|
|
}
|
|
|
|
|
2022-08-21 16:19:48 +00:00
|
|
|
let ty_span_start = self.current_pos();
|
2020-02-12 15:47:43 +00:00
|
|
|
spec.ty = self.word();
|
|
|
|
if !spec.ty.is_empty() {
|
2022-08-21 16:19:48 +00:00
|
|
|
let ty_span_end = self.current_pos();
|
|
|
|
spec.ty_span = Some(self.span(ty_span_start, ty_span_end));
|
2020-02-12 15:47:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
spec
|
|
|
|
}
|
|
|
|
|
2019-09-30 00:08:15 +00:00
|
|
|
/// Parses a `Count` parameter at the current position. This does not check
|
2013-07-29 08:12:41 +00:00
|
|
|
/// for 'CountIsNextParam' because that is only used in precision, not
|
|
|
|
/// width.
|
2022-08-21 16:19:48 +00:00
|
|
|
fn count(&mut self, start: usize) -> Count<'a> {
|
2015-09-10 13:48:11 +00:00
|
|
|
if let Some(i) = self.integer() {
|
2025-02-12 15:59:13 +00:00
|
|
|
if self.consume('$') { CountIsParam(i.into()) } else { CountIs(i) }
|
2015-09-10 13:48:11 +00:00
|
|
|
} else {
|
|
|
|
let tmp = self.cur.clone();
|
|
|
|
let word = self.word();
|
|
|
|
if word.is_empty() {
|
|
|
|
self.cur = tmp;
|
2022-08-21 16:19:48 +00:00
|
|
|
CountImplied
|
2022-02-16 00:38:04 +00:00
|
|
|
} else if let Some(end) = self.consume_pos('$') {
|
2022-08-21 16:19:48 +00:00
|
|
|
let name_span = self.span(start, end);
|
|
|
|
CountIsName(word, name_span)
|
2015-09-10 13:48:11 +00:00
|
|
|
} else {
|
2018-08-10 11:13:50 +00:00
|
|
|
self.cur = tmp;
|
2022-08-21 16:19:48 +00:00
|
|
|
CountImplied
|
2013-10-13 03:00:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2013-07-29 08:12:41 +00:00
|
|
|
|
2019-07-21 11:50:39 +00:00
|
|
|
/// Parses a word starting at the current position. A word is the same as
|
|
|
|
/// Rust identifier, except that it can't start with `_` character.
|
2013-12-10 07:16:18 +00:00
|
|
|
fn word(&mut self) -> &'a str {
|
2015-09-10 12:03:22 +00:00
|
|
|
let start = match self.cur.peek() {
|
2019-11-28 18:49:13 +00:00
|
|
|
Some(&(pos, c)) if rustc_lexer::is_id_start(c) => {
|
2015-10-13 14:10:51 +00:00
|
|
|
self.cur.next();
|
|
|
|
pos
|
|
|
|
}
|
|
|
|
_ => {
|
2019-11-28 18:49:13 +00:00
|
|
|
return "";
|
2015-10-13 14:10:51 +00:00
|
|
|
}
|
2013-07-29 08:12:41 +00:00
|
|
|
};
|
2019-11-28 18:49:13 +00:00
|
|
|
let mut end = None;
|
2015-09-10 13:48:11 +00:00
|
|
|
while let Some(&(pos, c)) = self.cur.peek() {
|
2019-09-04 10:16:36 +00:00
|
|
|
if rustc_lexer::is_id_continue(c) {
|
2015-09-10 13:48:11 +00:00
|
|
|
self.cur.next();
|
|
|
|
} else {
|
2019-11-28 18:49:13 +00:00
|
|
|
end = Some(pos);
|
|
|
|
break;
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
}
|
2019-11-28 18:49:13 +00:00
|
|
|
let end = end.unwrap_or(self.input.len());
|
|
|
|
let word = &self.input[start..end];
|
|
|
|
if word == "_" {
|
|
|
|
self.err_with_note(
|
|
|
|
"invalid argument name `_`",
|
|
|
|
"invalid argument name",
|
|
|
|
"argument name cannot be a single underscore",
|
2022-08-21 16:19:48 +00:00
|
|
|
self.span(start, end),
|
2019-11-28 18:49:13 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
word
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
|
2025-02-12 15:59:13 +00:00
|
|
|
fn integer(&mut self) -> Option<u16> {
|
|
|
|
let mut cur: u16 = 0;
|
2013-07-29 08:12:41 +00:00
|
|
|
let mut found = false;
|
2022-09-30 22:40:59 +00:00
|
|
|
let mut overflow = false;
|
|
|
|
let start = self.current_pos();
|
2015-09-10 12:03:22 +00:00
|
|
|
while let Some(&(_, c)) = self.cur.peek() {
|
2015-09-02 10:13:10 +00:00
|
|
|
if let Some(i) = c.to_digit(10) {
|
2022-09-30 22:40:59 +00:00
|
|
|
let (tmp, mul_overflow) = cur.overflowing_mul(10);
|
2025-02-12 15:59:13 +00:00
|
|
|
let (tmp, add_overflow) = tmp.overflowing_add(i as u16);
|
2022-09-30 22:40:59 +00:00
|
|
|
if mul_overflow || add_overflow {
|
|
|
|
overflow = true;
|
|
|
|
}
|
|
|
|
cur = tmp;
|
2015-09-02 10:13:10 +00:00
|
|
|
found = true;
|
|
|
|
self.cur.next();
|
|
|
|
} else {
|
2015-11-23 23:11:20 +00:00
|
|
|
break;
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
}
|
2022-09-30 22:40:59 +00:00
|
|
|
|
|
|
|
if overflow {
|
|
|
|
let end = self.current_pos();
|
|
|
|
let overflowed_int = &self.input[start..end];
|
|
|
|
self.err(
|
|
|
|
format!(
|
2025-02-12 15:59:13 +00:00
|
|
|
"integer `{}` does not fit into the type `u16` whose range is `0..={}`",
|
2022-09-30 22:40:59 +00:00
|
|
|
overflowed_int,
|
2025-02-12 15:59:13 +00:00
|
|
|
u16::MAX
|
2022-09-30 22:40:59 +00:00
|
|
|
),
|
2025-02-12 15:59:13 +00:00
|
|
|
"integer out of range for `u16`",
|
2022-09-30 22:40:59 +00:00
|
|
|
self.span(start, end),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2023-02-15 17:39:43 +00:00
|
|
|
found.then_some(cur)
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
2022-08-02 11:33:40 +00:00
|
|
|
|
2024-01-07 19:39:46 +00:00
|
|
|
fn suggest_format_debug(&mut self) {
|
2023-01-08 22:48:41 +00:00
|
|
|
if let (Some(pos), Some(_)) = (self.consume_pos('?'), self.consume_pos(':')) {
|
|
|
|
let word = self.word();
|
|
|
|
let pos = self.to_span_index(pos);
|
|
|
|
self.errors.insert(
|
|
|
|
0,
|
|
|
|
ParseError {
|
|
|
|
description: "expected format parameter to occur after `:`".to_owned(),
|
2023-02-10 17:08:25 +00:00
|
|
|
note: Some(format!("`?` comes after `:`, try `{}:{}` instead", word, "?")),
|
2023-01-08 22:48:41 +00:00
|
|
|
label: "expected `?` to occur after `:`".to_owned(),
|
|
|
|
span: pos.to(pos),
|
|
|
|
secondary_label: None,
|
2023-09-06 14:32:06 +00:00
|
|
|
suggestion: Suggestion::None,
|
2023-01-08 22:48:41 +00:00
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-07 19:39:46 +00:00
|
|
|
fn suggest_format_align(&mut self, alignment: char) {
|
|
|
|
if let Some(pos) = self.consume_pos(alignment) {
|
|
|
|
let pos = self.to_span_index(pos);
|
|
|
|
self.errors.insert(
|
|
|
|
0,
|
|
|
|
ParseError {
|
|
|
|
description: "expected format parameter to occur after `:`".to_owned(),
|
2024-01-08 18:41:01 +00:00
|
|
|
note: None,
|
2024-02-17 11:46:18 +00:00
|
|
|
label: format!("expected `{}` to occur after `:`", alignment),
|
2024-01-07 19:39:46 +00:00
|
|
|
span: pos.to(pos),
|
|
|
|
secondary_label: None,
|
|
|
|
suggestion: Suggestion::None,
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-02 11:33:40 +00:00
|
|
|
fn suggest_positional_arg_instead_of_captured_arg(&mut self, arg: Argument<'a>) {
|
|
|
|
if let Some(end) = self.consume_pos('.') {
|
|
|
|
let byte_pos = self.to_span_index(end);
|
|
|
|
let start = InnerOffset(byte_pos.0 + 1);
|
|
|
|
let field = self.argument(start);
|
2024-03-15 16:23:17 +00:00
|
|
|
// We can only parse simple `foo.bar` field access or `foo.0` tuple index access, any
|
|
|
|
// deeper nesting, or another type of expression, like method calls, are not supported
|
2022-08-04 02:51:25 +00:00
|
|
|
if !self.consume('}') {
|
|
|
|
return;
|
|
|
|
}
|
2022-08-02 11:33:40 +00:00
|
|
|
if let ArgumentNamed(_) = arg.position {
|
2024-03-15 16:23:17 +00:00
|
|
|
match field.position {
|
|
|
|
ArgumentNamed(_) => {
|
|
|
|
self.errors.insert(
|
|
|
|
0,
|
|
|
|
ParseError {
|
|
|
|
description: "field access isn't supported".to_string(),
|
|
|
|
note: None,
|
|
|
|
label: "not supported".to_string(),
|
|
|
|
span: InnerSpan::new(
|
|
|
|
arg.position_span.start,
|
|
|
|
field.position_span.end,
|
|
|
|
),
|
|
|
|
secondary_label: None,
|
|
|
|
suggestion: Suggestion::UsePositional,
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
ArgumentIs(_) => {
|
|
|
|
self.errors.insert(
|
|
|
|
0,
|
|
|
|
ParseError {
|
|
|
|
description: "tuple index access isn't supported".to_string(),
|
|
|
|
note: None,
|
|
|
|
label: "not supported".to_string(),
|
|
|
|
span: InnerSpan::new(
|
|
|
|
arg.position_span.start,
|
|
|
|
field.position_span.end,
|
|
|
|
),
|
|
|
|
secondary_label: None,
|
|
|
|
suggestion: Suggestion::UsePositional,
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
_ => {}
|
|
|
|
};
|
2022-08-02 11:33:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-12-29 04:47:07 +00:00
|
|
|
|
|
|
|
fn suggest_format_parameter(&mut self, c: char) {
|
|
|
|
let replacement = match c {
|
|
|
|
'#' => "#?",
|
|
|
|
'x' => "x?",
|
|
|
|
'X' => "X?",
|
|
|
|
_ => return,
|
|
|
|
};
|
|
|
|
let Some(pos) = self.consume_pos(c) else {
|
|
|
|
return;
|
|
|
|
};
|
|
|
|
|
|
|
|
let span = self.span(pos - 1, pos + 1);
|
|
|
|
let pos = self.to_span_index(pos);
|
|
|
|
|
|
|
|
self.errors.insert(
|
|
|
|
0,
|
|
|
|
ParseError {
|
|
|
|
description: format!("expected `}}`, found `{c}`"),
|
|
|
|
note: None,
|
|
|
|
label: "expected `'}'`".into(),
|
|
|
|
span: pos.to(pos),
|
|
|
|
secondary_label: None,
|
|
|
|
suggestion: Suggestion::ReorderFormatParameter(span, format!("{replacement}")),
|
|
|
|
},
|
|
|
|
)
|
|
|
|
}
|
2013-07-29 08:12:41 +00:00
|
|
|
}
|
|
|
|
|
2020-02-12 15:47:43 +00:00
|
|
|
/// Finds the indices of all characters that have been processed and differ between the actual
|
|
|
|
/// written code (code snippet) and the `InternedString` that gets processed in the `Parser`
|
2022-03-30 19:14:15 +00:00
|
|
|
/// in order to properly synthesise the intra-string `Span`s for error diagnostics.
|
2022-11-22 04:36:11 +00:00
|
|
|
fn find_width_map_from_snippet(
|
2023-03-13 18:52:41 +00:00
|
|
|
input: &str,
|
2025-01-23 09:16:08 +00:00
|
|
|
snippet: Option<String>,
|
2020-02-12 15:47:43 +00:00
|
|
|
str_style: Option<usize>,
|
2022-12-27 22:00:03 +00:00
|
|
|
) -> InputStringKind {
|
2020-02-12 15:47:43 +00:00
|
|
|
let snippet = match snippet {
|
2021-02-06 15:01:07 +00:00
|
|
|
Some(ref s) if s.starts_with('"') || s.starts_with("r\"") || s.starts_with("r#") => s,
|
2022-12-27 22:00:03 +00:00
|
|
|
_ => return InputStringKind::NotALiteral,
|
2020-02-12 15:47:43 +00:00
|
|
|
};
|
|
|
|
|
2022-11-09 13:40:51 +00:00
|
|
|
if str_style.is_some() {
|
2022-12-27 22:00:03 +00:00
|
|
|
return InputStringKind::Literal { width_mappings: Vec::new() };
|
2022-11-09 13:40:51 +00:00
|
|
|
}
|
2021-03-21 11:27:22 +00:00
|
|
|
|
2023-03-13 18:52:41 +00:00
|
|
|
// Strip quotes.
|
2022-11-09 13:40:51 +00:00
|
|
|
let snippet = &snippet[1..snippet.len() - 1];
|
|
|
|
|
2023-04-10 20:02:52 +00:00
|
|
|
// Macros like `println` add a newline at the end. That technically doesn't make them "literals" anymore, but it's fine
|
2023-03-13 18:52:41 +00:00
|
|
|
// since we will never need to point our spans there, so we lie about it here by ignoring it.
|
|
|
|
// Since there might actually be newlines in the source code, we need to normalize away all trailing newlines.
|
|
|
|
// If we only trimmed it off the input, `format!("\n")` would cause a mismatch as here we they actually match up.
|
|
|
|
// Alternatively, we could just count the trailing newlines and only trim one from the input if they don't match up.
|
|
|
|
let input_no_nl = input.trim_end_matches('\n');
|
|
|
|
let Some(unescaped) = unescape_string(snippet) else {
|
|
|
|
return InputStringKind::NotALiteral;
|
|
|
|
};
|
|
|
|
|
|
|
|
let unescaped_no_nl = unescaped.trim_end_matches('\n');
|
|
|
|
|
|
|
|
if unescaped_no_nl != input_no_nl {
|
|
|
|
// The source string that we're pointing at isn't our input, so spans pointing at it will be incorrect.
|
|
|
|
// This can for example happen with proc macros that respan generated literals.
|
|
|
|
return InputStringKind::NotALiteral;
|
|
|
|
}
|
|
|
|
|
2022-11-09 13:40:51 +00:00
|
|
|
let mut s = snippet.char_indices();
|
2022-11-22 04:36:11 +00:00
|
|
|
let mut width_mappings = vec![];
|
2022-11-09 13:40:51 +00:00
|
|
|
while let Some((pos, c)) = s.next() {
|
|
|
|
match (c, s.clone().next()) {
|
|
|
|
// skip whitespace and empty lines ending in '\\'
|
2022-11-22 04:36:11 +00:00
|
|
|
('\\', Some((_, '\n'))) => {
|
2022-11-09 13:40:51 +00:00
|
|
|
let _ = s.next();
|
2022-11-22 04:36:11 +00:00
|
|
|
let mut width = 2;
|
2022-11-09 13:40:51 +00:00
|
|
|
|
2022-11-22 04:36:11 +00:00
|
|
|
while let Some((_, c)) = s.clone().next() {
|
2022-11-09 13:40:51 +00:00
|
|
|
if matches!(c, ' ' | '\n' | '\t') {
|
2022-11-22 04:36:11 +00:00
|
|
|
width += 1;
|
2022-11-09 13:40:51 +00:00
|
|
|
let _ = s.next();
|
|
|
|
} else {
|
|
|
|
break;
|
2020-02-12 15:47:43 +00:00
|
|
|
}
|
|
|
|
}
|
2022-11-22 04:36:11 +00:00
|
|
|
|
|
|
|
width_mappings.push(InnerWidthMapping::new(pos, width, 0));
|
2022-11-09 13:40:51 +00:00
|
|
|
}
|
2022-11-22 04:36:11 +00:00
|
|
|
('\\', Some((_, 'n' | 't' | 'r' | '0' | '\\' | '\'' | '\"'))) => {
|
|
|
|
width_mappings.push(InnerWidthMapping::new(pos, 2, 1));
|
2022-11-09 13:40:51 +00:00
|
|
|
let _ = s.next();
|
|
|
|
}
|
|
|
|
('\\', Some((_, 'x'))) => {
|
2022-11-22 04:36:11 +00:00
|
|
|
// consume `\xAB` literal
|
|
|
|
s.nth(2);
|
|
|
|
width_mappings.push(InnerWidthMapping::new(pos, 4, 1));
|
2022-11-09 13:40:51 +00:00
|
|
|
}
|
|
|
|
('\\', Some((_, 'u'))) => {
|
2022-11-22 04:36:11 +00:00
|
|
|
let mut width = 2;
|
|
|
|
let _ = s.next();
|
|
|
|
|
|
|
|
if let Some((_, next_c)) = s.next() {
|
2022-11-09 13:40:51 +00:00
|
|
|
if next_c == '{' {
|
|
|
|
// consume up to 6 hexanumeric chars
|
|
|
|
let digits_len =
|
2024-05-30 01:51:27 +00:00
|
|
|
s.clone().take(6).take_while(|(_, c)| c.is_ascii_hexdigit()).count();
|
2022-11-09 13:40:51 +00:00
|
|
|
|
|
|
|
let len_utf8 = s
|
|
|
|
.as_str()
|
|
|
|
.get(..digits_len)
|
|
|
|
.and_then(|digits| u32::from_str_radix(digits, 16).ok())
|
|
|
|
.and_then(char::from_u32)
|
|
|
|
.map_or(1, char::len_utf8);
|
|
|
|
|
|
|
|
// Skip the digits, for chars that encode to more than 1 utf-8 byte
|
|
|
|
// exclude as many digits as it is greater than 1 byte
|
|
|
|
//
|
|
|
|
// So for a 3 byte character, exclude 2 digits
|
|
|
|
let required_skips = digits_len.saturating_sub(len_utf8.saturating_sub(1));
|
|
|
|
|
|
|
|
// skip '{' and '}' also
|
2022-11-22 04:36:11 +00:00
|
|
|
width += required_skips + 2;
|
2022-10-27 18:20:56 +00:00
|
|
|
|
2022-11-09 13:40:51 +00:00
|
|
|
s.nth(digits_len);
|
2024-05-30 01:51:27 +00:00
|
|
|
} else if next_c.is_ascii_hexdigit() {
|
2022-11-22 04:36:11 +00:00
|
|
|
width += 1;
|
|
|
|
|
2022-11-09 13:40:51 +00:00
|
|
|
// We suggest adding `{` and `}` when appropriate, accept it here as if
|
|
|
|
// it were correct
|
|
|
|
let mut i = 0; // consume up to 6 hexanumeric chars
|
2022-11-22 04:36:11 +00:00
|
|
|
while let (Some((_, c)), _) = (s.next(), i < 6) {
|
2024-05-30 01:51:27 +00:00
|
|
|
if c.is_ascii_hexdigit() {
|
2022-11-22 04:36:11 +00:00
|
|
|
width += 1;
|
2022-11-09 13:40:51 +00:00
|
|
|
} else {
|
|
|
|
break;
|
2020-02-12 15:47:43 +00:00
|
|
|
}
|
2022-11-09 13:40:51 +00:00
|
|
|
i += 1;
|
2020-02-12 15:47:43 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-11-22 04:36:11 +00:00
|
|
|
|
|
|
|
width_mappings.push(InnerWidthMapping::new(pos, width, 1));
|
2020-02-12 15:47:43 +00:00
|
|
|
}
|
2022-11-09 13:40:51 +00:00
|
|
|
_ => {}
|
2020-02-12 15:47:43 +00:00
|
|
|
}
|
|
|
|
}
|
2022-12-27 21:15:25 +00:00
|
|
|
|
2022-12-27 22:00:03 +00:00
|
|
|
InputStringKind::Literal { width_mappings }
|
2020-02-12 15:47:43 +00:00
|
|
|
}
|
|
|
|
|
2025-01-23 09:16:08 +00:00
|
|
|
fn unescape_string(string: &str) -> Option<String> {
|
|
|
|
let mut buf = String::new();
|
2023-03-13 18:52:41 +00:00
|
|
|
let mut ok = true;
|
2025-03-18 12:28:56 +00:00
|
|
|
unescape::unescape_unicode(string, unescape::Mode::Str, &mut |_, unescaped_char| {
|
|
|
|
match unescaped_char {
|
2023-03-13 18:52:41 +00:00
|
|
|
Ok(c) => buf.push(c),
|
|
|
|
Err(_) => ok = false,
|
2025-03-18 12:28:56 +00:00
|
|
|
}
|
|
|
|
});
|
2023-03-13 18:52:41 +00:00
|
|
|
|
|
|
|
ok.then_some(buf)
|
|
|
|
}
|
|
|
|
|
2022-12-08 11:20:01 +00:00
|
|
|
// Assert a reasonable size for `Piece`
|
2025-03-17 12:06:34 +00:00
|
|
|
#[cfg(all(test, target_pointer_width = "64"))]
|
2023-09-05 17:11:50 +00:00
|
|
|
rustc_index::static_assert_size!(Piece<'_>, 16);
|
2022-12-08 11:20:01 +00:00
|
|
|
|
2013-07-29 08:12:41 +00:00
|
|
|
#[cfg(test)]
|
2019-06-15 19:54:46 +00:00
|
|
|
mod tests;
|