[feature request] format to raw

fn main() {
    let str = r#"raw"str"#;
    println!("{:?}", str);
}

will get "raw\"str". Is there a way to generate r#"raw"str"#

If this is a feature request, no, because at runtime the information that the original string token was a raw string is erased.

If you just want to do that in this case, sure, but I don't know something built in/some crate that does that. You need to use display view, not debug (as it escapes character) and figure out the number of needed hashes from the string.

And BTW, naming a variable str is not a good idea.

It's even worse: IIRC after tokenization the compiler pretty much forgets that the string is raw (besides a few bits of diagnostic-related metadata that we've added over time), because it doesn't need to :grimacing:

Oh, I was thinking that maybe a procedural macro could distinguish macro!("a") from macro!(r#"a"#) but I guess it wouldn't?

It can, it must be somewhere a little later than the tokens the proc-macro sees that forgets it.

EDIT: Actually, no, it can't directly. There's just a bug in Literal::subspan that doesn't take it into account when emitting diagnostics.

EDIT2: Nope, I was right the first time, I just messed up my test case

[macros/src/lib.rs:168] format_lit.token().to_string() = "r#\"{b:a$}\"#"
1 Like