Skip to content

Commit b9045fa

Browse files
authored
Rollup merge of rust-lang#81828 - davidhewitt:capture-raw-format-strings, r=estebank
parse_format: treat r" as a literal This PR changes `format_args!` internal parsing machinery to treat raw strings starting `r"` as a literal. Currently `"` and `r#` are recognised as valid starting combinations for string literals, but `r"` is not. This was noticed when debugging rust-lang#67984 (comment) As well as fixing the behavior observed in that comment, this improves diagnostic spans for `r"` formatting strings.
2 parents 480865d + 04a19b9 commit b9045fa

File tree

3 files changed

+14
-3
lines changed

3 files changed

+14
-3
lines changed

compiler/rustc_parse_format/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -730,7 +730,7 @@ fn find_skips_from_snippet(
730730
str_style: Option<usize>,
731731
) -> (Vec<usize>, bool) {
732732
let snippet = match snippet {
733-
Some(ref s) if s.starts_with('"') || s.starts_with("r#") => s,
733+
Some(ref s) if s.starts_with('"') || s.starts_with("r\"") || s.starts_with("r#") => s,
734734
_ => return (vec![], false),
735735
};
736736

src/test/ui/fmt/format-args-capture.rs

+11
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
fn main() {
66
named_argument_takes_precedence_to_captured();
77
formatting_parameters_can_be_captured();
8+
capture_raw_strings_and_idents();
89

910
#[cfg(panic = "unwind")]
1011
{
@@ -25,6 +26,16 @@ fn named_argument_takes_precedence_to_captured() {
2526
assert_eq!(&s, "positional-named-captured");
2627
}
2728

29+
fn capture_raw_strings_and_idents() {
30+
let r#type = "apple";
31+
let s = format!(r#"The fruit is an {type}"#);
32+
assert_eq!(&s, "The fruit is an apple");
33+
34+
let r#type = "orange";
35+
let s = format!(r"The fruit is an {type}");
36+
assert_eq!(&s, "The fruit is an orange");
37+
}
38+
2839
#[cfg(panic = "unwind")]
2940
fn panic_with_single_argument_does_not_get_formatted() {
3041
// panic! with a single argument does not perform string formatting.

src/test/ui/issues/issue-75307.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
error: invalid reference to positional arguments 1 and 2 (there is 1 argument)
2-
--> $DIR/issue-75307.rs:2:13
2+
--> $DIR/issue-75307.rs:2:17
33
|
44
LL | format!(r"{}{}{}", named_arg=1);
5-
| ^^^^^^^^^
5+
| ^^^^
66
|
77
= note: positional arguments are zero-based
88

0 commit comments

Comments
 (0)