Skip to content

Commit 20ca54b

Browse files
authored
Rollup merge of #123769 - dtolnay:literal, r=fee1-dead
Improve escaping of byte, byte str, and c str proc-macro literals This PR changes the behavior of `proc_macro::Literal::byte_character` (#115268), `byte_string`, and `c_string` (#119750) to improve their choice of escape sequences. 3 categories of changes are made: 1. Never use `\x00`. Always prefer `\0`, which is supported in all the same places. 2. Never escape `\'` inside double quotes and `\"` inside single quotes. 3. Never use `\x` for valid UTF-8 in literals that permit `\u`. The second commit adds tests covering these cases, asserting the **old** behavior. The third commit implements the behavior change and simultaneously updates the tests to assert the **new** behavior.
2 parents d2ad293 + 7ddc89e commit 20ca54b

File tree

5 files changed

+179
-74
lines changed

5 files changed

+179
-74
lines changed

library/proc_macro/src/escape.rs

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#[derive(Copy, Clone)]
2+
pub(crate) struct EscapeOptions {
3+
/// Produce \'.
4+
pub escape_single_quote: bool,
5+
/// Produce \".
6+
pub escape_double_quote: bool,
7+
/// Produce \x escapes for non-ASCII, and use \x rather than \u for ASCII
8+
/// control characters.
9+
pub escape_nonascii: bool,
10+
}
11+
12+
pub(crate) fn escape_bytes(bytes: &[u8], opt: EscapeOptions) -> String {
13+
let mut repr = String::new();
14+
15+
if opt.escape_nonascii {
16+
for &byte in bytes {
17+
escape_single_byte(byte, opt, &mut repr);
18+
}
19+
} else {
20+
let mut chunks = bytes.utf8_chunks();
21+
while let Some(chunk) = chunks.next() {
22+
for ch in chunk.valid().chars() {
23+
escape_single_char(ch, opt, &mut repr);
24+
}
25+
for &byte in chunk.invalid() {
26+
escape_single_byte(byte, opt, &mut repr);
27+
}
28+
}
29+
}
30+
31+
repr
32+
}
33+
34+
fn escape_single_byte(byte: u8, opt: EscapeOptions, repr: &mut String) {
35+
if byte == b'\0' {
36+
repr.push_str("\\0");
37+
} else if (byte == b'\'' && !opt.escape_single_quote)
38+
|| (byte == b'"' && !opt.escape_double_quote)
39+
{
40+
repr.push(byte as char);
41+
} else {
42+
// Escapes \t, \r, \n, \\, \', \", and uses \x## for non-ASCII and
43+
// for ASCII control characters.
44+
repr.extend(byte.escape_ascii().map(char::from));
45+
}
46+
}
47+
48+
fn escape_single_char(ch: char, opt: EscapeOptions, repr: &mut String) {
49+
if (ch == '\'' && !opt.escape_single_quote) || (ch == '"' && !opt.escape_double_quote) {
50+
repr.push(ch);
51+
} else {
52+
// Escapes \0, \t, \r, \n, \\, \', \", and uses \u{...} for
53+
// non-printable characters and for Grapheme_Extend characters, which
54+
// includes things like U+0300 "Combining Grave Accent".
55+
repr.extend(ch.escape_debug());
56+
}
57+
}

library/proc_macro/src/lib.rs

+37-14
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,12 @@
4343
pub mod bridge;
4444

4545
mod diagnostic;
46+
mod escape;
4647

4748
#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
4849
pub use diagnostic::{Diagnostic, Level, MultiSpan};
4950

51+
use crate::escape::{escape_bytes, EscapeOptions};
5052
use std::ffi::CStr;
5153
use std::ops::{Range, RangeBounds};
5254
use std::path::PathBuf;
@@ -1356,40 +1358,61 @@ impl Literal {
13561358
/// String literal.
13571359
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
13581360
pub fn string(string: &str) -> Literal {
1359-
let quoted = format!("{:?}", string);
1360-
assert!(quoted.starts_with('"') && quoted.ends_with('"'));
1361-
let symbol = &quoted[1..quoted.len() - 1];
1362-
Literal::new(bridge::LitKind::Str, symbol, None)
1361+
let escape = EscapeOptions {
1362+
escape_single_quote: false,
1363+
escape_double_quote: true,
1364+
escape_nonascii: false,
1365+
};
1366+
let repr = escape_bytes(string.as_bytes(), escape);
1367+
Literal::new(bridge::LitKind::Str, &repr, None)
13631368
}
13641369

13651370
/// Character literal.
13661371
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
13671372
pub fn character(ch: char) -> Literal {
1368-
let quoted = format!("{:?}", ch);
1369-
assert!(quoted.starts_with('\'') && quoted.ends_with('\''));
1370-
let symbol = &quoted[1..quoted.len() - 1];
1371-
Literal::new(bridge::LitKind::Char, symbol, None)
1373+
let escape = EscapeOptions {
1374+
escape_single_quote: true,
1375+
escape_double_quote: false,
1376+
escape_nonascii: false,
1377+
};
1378+
let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1379+
Literal::new(bridge::LitKind::Char, &repr, None)
13721380
}
13731381

13741382
/// Byte character literal.
13751383
#[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
13761384
pub fn byte_character(byte: u8) -> Literal {
1377-
let string = [byte].escape_ascii().to_string();
1378-
Literal::new(bridge::LitKind::Byte, &string, None)
1385+
let escape = EscapeOptions {
1386+
escape_single_quote: true,
1387+
escape_double_quote: false,
1388+
escape_nonascii: true,
1389+
};
1390+
let repr = escape_bytes(&[byte], escape);
1391+
Literal::new(bridge::LitKind::Byte, &repr, None)
13791392
}
13801393

13811394
/// Byte string literal.
13821395
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
13831396
pub fn byte_string(bytes: &[u8]) -> Literal {
1384-
let string = bytes.escape_ascii().to_string();
1385-
Literal::new(bridge::LitKind::ByteStr, &string, None)
1397+
let escape = EscapeOptions {
1398+
escape_single_quote: false,
1399+
escape_double_quote: true,
1400+
escape_nonascii: true,
1401+
};
1402+
let repr = escape_bytes(bytes, escape);
1403+
Literal::new(bridge::LitKind::ByteStr, &repr, None)
13861404
}
13871405

13881406
/// C string literal.
13891407
#[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
13901408
pub fn c_string(string: &CStr) -> Literal {
1391-
let string = string.to_bytes().escape_ascii().to_string();
1392-
Literal::new(bridge::LitKind::CStr, &string, None)
1409+
let escape = EscapeOptions {
1410+
escape_single_quote: false,
1411+
escape_double_quote: true,
1412+
escape_nonascii: false,
1413+
};
1414+
let repr = escape_bytes(string.to_bytes(), escape);
1415+
Literal::new(bridge::LitKind::CStr, &repr, None)
13931416
}
13941417

13951418
/// Returns the span encompassing this literal.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
// ignore-tidy-linelength
2+
3+
use proc_macro::Literal;
4+
5+
pub fn test() {
6+
test_display_literal();
7+
test_parse_literal();
8+
}
9+
10+
fn test_display_literal() {
11+
assert_eq!(Literal::isize_unsuffixed(-10).to_string(), "-10");
12+
assert_eq!(Literal::isize_suffixed(-10).to_string(), "-10isize");
13+
assert_eq!(Literal::f32_unsuffixed(-10.0).to_string(), "-10.0");
14+
assert_eq!(Literal::f32_suffixed(-10.0).to_string(), "-10f32");
15+
assert_eq!(Literal::f64_unsuffixed(-10.0).to_string(), "-10.0");
16+
assert_eq!(Literal::f64_suffixed(-10.0).to_string(), "-10f64");
17+
assert_eq!(
18+
Literal::f64_unsuffixed(1e100).to_string(),
19+
"10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0",
20+
);
21+
22+
assert_eq!(Literal::string("aA").to_string(), r#" "aA" "#.trim());
23+
assert_eq!(Literal::string("\t").to_string(), r#" "\t" "#.trim());
24+
assert_eq!(Literal::string("❤").to_string(), r#" "❤" "#.trim());
25+
assert_eq!(Literal::string("'").to_string(), r#" "'" "#.trim());
26+
assert_eq!(Literal::string("\"").to_string(), r#" "\"" "#.trim());
27+
assert_eq!(Literal::string("\0").to_string(), r#" "\0" "#.trim());
28+
assert_eq!(Literal::string("\u{1}").to_string(), r#" "\u{1}" "#.trim());
29+
30+
assert_eq!(Literal::byte_string(b"aA").to_string(), r#" b"aA" "#.trim());
31+
assert_eq!(Literal::byte_string(b"\t").to_string(), r#" b"\t" "#.trim());
32+
assert_eq!(Literal::byte_string(b"'").to_string(), r#" b"'" "#.trim());
33+
assert_eq!(Literal::byte_string(b"\"").to_string(), r#" b"\"" "#.trim());
34+
assert_eq!(Literal::byte_string(b"\0").to_string(), r#" b"\0" "#.trim());
35+
assert_eq!(Literal::byte_string(b"\x01").to_string(), r#" b"\x01" "#.trim());
36+
37+
assert_eq!(Literal::c_string(c"aA").to_string(), r#" c"aA" "#.trim());
38+
assert_eq!(Literal::c_string(c"\t").to_string(), r#" c"\t" "#.trim());
39+
assert_eq!(Literal::c_string(c"❤").to_string(), r#" c"❤" "#.trim());
40+
assert_eq!(Literal::c_string(c"\'").to_string(), r#" c"'" "#.trim());
41+
assert_eq!(Literal::c_string(c"\"").to_string(), r#" c"\"" "#.trim());
42+
assert_eq!(Literal::c_string(c"\x7f\xff\xfe\u{333}").to_string(), r#" c"\u{7f}\xff\xfe\u{333}" "#.trim());
43+
44+
assert_eq!(Literal::character('a').to_string(), r#" 'a' "#.trim());
45+
assert_eq!(Literal::character('\t').to_string(), r#" '\t' "#.trim());
46+
assert_eq!(Literal::character('❤').to_string(), r#" '❤' "#.trim());
47+
assert_eq!(Literal::character('\'').to_string(), r#" '\'' "#.trim());
48+
assert_eq!(Literal::character('"').to_string(), r#" '"' "#.trim());
49+
assert_eq!(Literal::character('\0').to_string(), r#" '\0' "#.trim());
50+
assert_eq!(Literal::character('\u{1}').to_string(), r#" '\u{1}' "#.trim());
51+
52+
assert_eq!(Literal::byte_character(b'a').to_string(), r#" b'a' "#.trim());
53+
assert_eq!(Literal::byte_character(b'\t').to_string(), r#" b'\t' "#.trim());
54+
assert_eq!(Literal::byte_character(b'\'').to_string(), r#" b'\'' "#.trim());
55+
assert_eq!(Literal::byte_character(b'"').to_string(), r#" b'"' "#.trim());
56+
assert_eq!(Literal::byte_character(0).to_string(), r#" b'\0' "#.trim());
57+
assert_eq!(Literal::byte_character(1).to_string(), r#" b'\x01' "#.trim());
58+
}
59+
60+
fn test_parse_literal() {
61+
assert_eq!("1".parse::<Literal>().unwrap().to_string(), "1");
62+
assert_eq!("1.0".parse::<Literal>().unwrap().to_string(), "1.0");
63+
assert_eq!("'a'".parse::<Literal>().unwrap().to_string(), "'a'");
64+
assert_eq!("b'a'".parse::<Literal>().unwrap().to_string(), "b'a'");
65+
assert_eq!("\"\n\"".parse::<Literal>().unwrap().to_string(), "\"\n\"");
66+
assert_eq!("b\"\"".parse::<Literal>().unwrap().to_string(), "b\"\"");
67+
assert_eq!("c\"\"".parse::<Literal>().unwrap().to_string(), "c\"\"");
68+
assert_eq!("r##\"\"##".parse::<Literal>().unwrap().to_string(), "r##\"\"##");
69+
assert_eq!("10ulong".parse::<Literal>().unwrap().to_string(), "10ulong");
70+
assert_eq!("-10ulong".parse::<Literal>().unwrap().to_string(), "-10ulong");
71+
72+
assert!("true".parse::<Literal>().is_err());
73+
assert!(".8".parse::<Literal>().is_err());
74+
assert!("0 1".parse::<Literal>().is_err());
75+
assert!("'a".parse::<Literal>().is_err());
76+
assert!(" 0".parse::<Literal>().is_err());
77+
assert!("0 ".parse::<Literal>().is_err());
78+
assert!("/* comment */0".parse::<Literal>().is_err());
79+
assert!("0/* comment */".parse::<Literal>().is_err());
80+
assert!("0// comment".parse::<Literal>().is_err());
81+
assert!("- 10".parse::<Literal>().is_err());
82+
assert!("-'x'".parse::<Literal>().is_err());
83+
}

tests/ui/proc-macro/auxiliary/api/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
extern crate proc_macro;
1111

1212
mod cmp;
13-
mod parse;
13+
mod literal;
1414

1515
use proc_macro::TokenStream;
1616

@@ -19,7 +19,7 @@ pub fn run(input: TokenStream) -> TokenStream {
1919
assert!(input.is_empty());
2020

2121
cmp::test();
22-
parse::test();
22+
literal::test();
2323

2424
TokenStream::new()
2525
}

tests/ui/proc-macro/auxiliary/api/parse.rs

-58
This file was deleted.

0 commit comments

Comments
 (0)