Skip to content

Commit

Permalink
Rollup merge of #81828 - davidhewitt:capture-raw-format-strings, r=es…
Browse files Browse the repository at this point in the history
…tebank

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 #67984 (comment)

As well as fixing the behavior observed in that comment, this improves diagnostic spans for `r"` formatting strings.
  • Loading branch information
m-ou-se authored Feb 8, 2021
2 parents 480865d + 04a19b9 commit b9045fa
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
2 changes: 1 addition & 1 deletion compiler/rustc_parse_format/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -730,7 +730,7 @@ fn find_skips_from_snippet(
str_style: Option<usize>,
) -> (Vec<usize>, bool) {
let snippet = match snippet {
Some(ref s) if s.starts_with('"') || s.starts_with("r#") => s,
Some(ref s) if s.starts_with('"') || s.starts_with("r\"") || s.starts_with("r#") => s,
_ => return (vec![], false),
};

Expand Down
11 changes: 11 additions & 0 deletions src/test/ui/fmt/format-args-capture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
fn main() {
named_argument_takes_precedence_to_captured();
formatting_parameters_can_be_captured();
capture_raw_strings_and_idents();

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

fn capture_raw_strings_and_idents() {
let r#type = "apple";
let s = format!(r#"The fruit is an {type}"#);
assert_eq!(&s, "The fruit is an apple");

let r#type = "orange";
let s = format!(r"The fruit is an {type}");
assert_eq!(&s, "The fruit is an orange");
}

#[cfg(panic = "unwind")]
fn panic_with_single_argument_does_not_get_formatted() {
// panic! with a single argument does not perform string formatting.
Expand Down
4 changes: 2 additions & 2 deletions src/test/ui/issues/issue-75307.stderr
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
error: invalid reference to positional arguments 1 and 2 (there is 1 argument)
--> $DIR/issue-75307.rs:2:13
--> $DIR/issue-75307.rs:2:17
|
LL | format!(r"{}{}{}", named_arg=1);
| ^^^^^^^^^
| ^^^^
|
= note: positional arguments are zero-based

Expand Down

0 comments on commit b9045fa

Please sign in to comment.