Skip to content

Commit ed2a482

Browse files
committed
rustc_parse_format: improve diagnostics for unsupported python numeric grouping
Detect Python-style numeric grouping syntax in format strings (e.g. `{x:,}`) and emit a clear diagnostic explaining that it is not supported in Rust. This helps users coming from Python understand the error without exposing the full set of valid Rust format specifiers. Signed-off-by: Usman Akinyemi <usmanakinyemi202@gmail.com>
1 parent cf027a1 commit ed2a482

3 files changed

Lines changed: 30 additions & 1 deletion

File tree

compiler/rustc_parse_format/src/lib.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -461,6 +461,7 @@ impl<'input> Parser<'input> {
461461
('?', '}') => self.missing_colon_before_debug_formatter(),
462462
('?', _) => self.suggest_format_debug(),
463463
('<' | '^' | '>', _) => self.suggest_format_align(c),
464+
(',', _) => self.suggest_unsupported_python_numeric_grouping(),
464465
_ => self.suggest_positional_arg_instead_of_captured_arg(arg),
465466
}
466467
}
@@ -934,6 +935,24 @@ impl<'input> Parser<'input> {
934935
}
935936
}
936937
}
938+
939+
fn suggest_unsupported_python_numeric_grouping(&mut self) {
940+
if let Some((range, _)) = self.consume_pos(',') {
941+
self.errors.insert(
942+
0,
943+
ParseError {
944+
description: "expected `}`, found `,`".to_owned(),
945+
note: Some(format!("to print `{{`, you can escape it using `{{{{`",)),
946+
label:
947+
" python-style numeric grouping `,` is not supported in rust format strings"
948+
.to_owned(),
949+
span: range,
950+
secondary_label: None,
951+
suggestion: Suggestion::None,
952+
},
953+
);
954+
}
955+
}
937956
}
938957

939958
// Assert a reasonable size for `Piece`

tests/ui/fmt/format-string-error-2.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,4 +86,6 @@ raw { \n
8686

8787
println!("{x?}, world!",);
8888
//~^ ERROR invalid format string: expected `}`, found `?`
89+
println!("{x,}, world!",);
90+
//~^ ERROR invalid format string: expected `}`, found `,`
8991
}

tests/ui/fmt/format-string-error-2.stderr

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,5 +188,13 @@ LL | println!("{x?}, world!",);
188188
|
189189
= note: to print `{`, you can escape it using `{{`
190190

191-
error: aborting due to 19 previous errors
191+
error: invalid format string: expected `}`, found `,`
192+
--> $DIR/format-string-error-2.rs:89:17
193+
|
194+
LL | println!("{x,}, world!",);
195+
| ^ python-style numeric grouping `,` is not supported in rust format strings in format string
196+
|
197+
= note: to print `{`, you can escape it using `{{`
198+
199+
error: aborting due to 20 previous errors
192200

0 commit comments

Comments
 (0)