| 1 |
commit 618d64c2e0c3faa1acc5bf2cd2c7b7fa73b479e9 |
| 2 |
Author: Nicholas Nethercote <[email protected]> |
| 3 |
Date: Fri Jan 26 10:49:17 2024 +1100 |
| 4 |
|
| 5 |
Fix `proc macro panicked` with `Invalid type` in `const_random!` in Rust 1.77. |
| 6 |
|
| 7 |
With Rust nightly 1.77, any invocation of `const_random!` with a `u8` |
| 8 |
array causes a compile-time panic. This can be seen when running `cargo |
| 9 |
test`: |
| 10 |
``` |
| 11 |
error: proc macro panicked |
| 12 |
--> tests/tests.rs:52:28 |
| 13 |
| |
| 14 |
52 | const VALUE1: &[u8] = &const_random!([u8; 30]); |
| 15 |
| ^^^^^^^^^^^^^^^^^^^^^^^ |
| 16 |
| |
| 17 |
= help: message: Invalid type |
| 18 |
``` |
| 19 |
This is because the proc macro starts by calling `to_string` on the |
| 20 |
input token stream, and then uses substring matching to "parse" it. In |
| 21 |
Rust 1.77 the `Display` impl for `TokenStream` has changed, and what |
| 22 |
used to be converted to the string `"[u8 ; 30]"` is now `"[u8; 30]"`. As |
| 23 |
a result, the `byte_array.starts_with("[u8 ; ")` call fails. |
| 24 |
|
| 25 |
Note that substring matching is inherently flawed because the whitespace |
| 26 |
in the output of `to_string` is not guaranteed. |
| 27 |
|
| 28 |
This commit rewrites the proc macro to be robust in the face of |
| 29 |
`to_string` whitespace changes, by iterating over the individual |
| 30 |
`TokenTrees`s. |
| 31 |
|
| 32 |
The commit also adds a comment explaining why `usize` and `isize` are |
| 33 |
handled differently, because it's subtle. |
| 34 |
|
| 35 |
Note: I ran `cargo fmt` within `macro/` to format the changes to |
| 36 |
`macro/src/lib.rs` and it made some minor changes to `macro/src/span.rs` |
| 37 |
as well. |
| 38 |
|
| 39 |
diff --git macro/src/lib.rs macro/src/lib.rs |
| 40 |
index f65695631..732028394 100644 |
| 41 |
--- macro/src/lib.rs |
| 42 |
+++ macro/src/lib.rs |
| 43 |
@@ -1,11 +1,9 @@ |
| 44 |
-#[allow(unused_extern_crates)] |
| 45 |
extern crate proc_macro; |
| 46 |
|
| 47 |
use proc_macro::*; |
| 48 |
use std::iter::once; |
| 49 |
mod span; |
| 50 |
-use crate::span::{gen_random_bytes, gen_random}; |
| 51 |
- |
| 52 |
+use crate::span::{gen_random, gen_random_bytes}; |
| 53 |
|
| 54 |
/// Create a TokenStream of an identifier out of a string |
| 55 |
fn ident(ident: &str) -> TokenStream { |
| 56 |
@@ -14,44 +12,89 @@ fn ident(ident: &str) -> TokenStream { |
| 57 |
|
| 58 |
#[proc_macro] |
| 59 |
pub fn const_random(input: TokenStream) -> TokenStream { |
| 60 |
- match &input.to_string()[..] { |
| 61 |
- "u8" => TokenTree::from(Literal::u8_suffixed(gen_random())).into(), |
| 62 |
- "u16" => TokenTree::from(Literal::u16_suffixed(gen_random())).into(), |
| 63 |
- "u32" => TokenTree::from(Literal::u32_suffixed(gen_random())).into(), |
| 64 |
- "u64" => TokenTree::from(Literal::u64_suffixed(gen_random())).into(), |
| 65 |
- "u128" => TokenTree::from(Literal::u128_suffixed(gen_random())).into(), |
| 66 |
- "i8" => TokenTree::from(Literal::i8_suffixed(gen_random())).into(), |
| 67 |
- "i16" => TokenTree::from(Literal::i16_suffixed(gen_random())).into(), |
| 68 |
- "i32" => TokenTree::from(Literal::i32_suffixed(gen_random())).into(), |
| 69 |
- "i64" => TokenTree::from(Literal::i64_suffixed(gen_random())).into(), |
| 70 |
- "i128" => TokenTree::from(Literal::i128_suffixed(gen_random())).into(), |
| 71 |
- "usize" => { |
| 72 |
- let value: TokenStream = TokenTree::from(Literal::u128_suffixed(gen_random())).into(); |
| 73 |
- let type_cast: TokenStream = [value, ident("as"), ident("usize")] |
| 74 |
- .iter() |
| 75 |
- .cloned() |
| 76 |
- .collect(); |
| 77 |
- TokenTree::from(Group::new(Delimiter::Parenthesis, type_cast)).into() |
| 78 |
+ let mut iter = input.into_iter(); |
| 79 |
+ let Some(tt) = iter.next() else { |
| 80 |
+ panic!("missing type arg"); |
| 81 |
+ }; |
| 82 |
+ |
| 83 |
+ let result = match &tt { |
| 84 |
+ TokenTree::Ident(id) => { |
| 85 |
+ let s = id.to_string(); |
| 86 |
+ match s.as_str() { |
| 87 |
+ "u8" => TokenTree::from(Literal::u8_suffixed(gen_random())).into(), |
| 88 |
+ "u16" => TokenTree::from(Literal::u16_suffixed(gen_random())).into(), |
| 89 |
+ "u32" => TokenTree::from(Literal::u32_suffixed(gen_random())).into(), |
| 90 |
+ "u64" => TokenTree::from(Literal::u64_suffixed(gen_random())).into(), |
| 91 |
+ "u128" => TokenTree::from(Literal::u128_suffixed(gen_random())).into(), |
| 92 |
+ "i8" => TokenTree::from(Literal::i8_suffixed(gen_random())).into(), |
| 93 |
+ "i16" => TokenTree::from(Literal::i16_suffixed(gen_random())).into(), |
| 94 |
+ "i32" => TokenTree::from(Literal::i32_suffixed(gen_random())).into(), |
| 95 |
+ "i64" => TokenTree::from(Literal::i64_suffixed(gen_random())).into(), |
| 96 |
+ "i128" => TokenTree::from(Literal::i128_suffixed(gen_random())).into(), |
| 97 |
+ "usize" => { |
| 98 |
+ // Note: usize does not implement `Random` and follow the pattern above. If it |
| 99 |
+ // did, when cross-compiling from a 32-bit host to a 64-bit target, |
| 100 |
+ // `usize::random()` would produce a 32-bit random usize which would then be |
| 101 |
+ // turned into a suffixed literal (e.g. `0x1234_5678usize`). On the 64-bit |
| 102 |
+ // target that literal would always have the upper 32 bits as zero, which would |
| 103 |
+ // be bad. Instead we produce code that will generate a 128-bit integer literal |
| 104 |
+ // (on the host) and then truncate it to usize (on the target). |
| 105 |
+ let value: TokenStream = |
| 106 |
+ TokenTree::from(Literal::u128_suffixed(gen_random())).into(); |
| 107 |
+ let type_cast: TokenStream = [value, ident("as"), ident("usize")] |
| 108 |
+ .iter() |
| 109 |
+ .cloned() |
| 110 |
+ .collect(); |
| 111 |
+ TokenTree::from(Group::new(Delimiter::Parenthesis, type_cast)).into() |
| 112 |
+ } |
| 113 |
+ "isize" => { |
| 114 |
+ // The same reasoning as `usize` applies for `isize`. |
| 115 |
+ let value: TokenStream = |
| 116 |
+ TokenTree::from(Literal::i128_suffixed(gen_random())).into(); |
| 117 |
+ let type_cast: TokenStream = [value, ident("as"), ident("isize")] |
| 118 |
+ .iter() |
| 119 |
+ .cloned() |
| 120 |
+ .collect(); |
| 121 |
+ TokenTree::from(Group::new(Delimiter::Parenthesis, type_cast)).into() |
| 122 |
+ } |
| 123 |
+ _ => panic!("invalid integer type arg: `{}`", s), |
| 124 |
+ } |
| 125 |
} |
| 126 |
- "isize" => { |
| 127 |
- let value: TokenStream = TokenTree::from(Literal::i128_suffixed(gen_random())).into(); |
| 128 |
- let type_cast: TokenStream = [value, ident("as"), ident("isize")] |
| 129 |
- .iter() |
| 130 |
- .cloned() |
| 131 |
- .collect(); |
| 132 |
- TokenTree::from(Group::new(Delimiter::Parenthesis, type_cast)).into() |
| 133 |
+ TokenTree::Group(group) if group.delimiter() == Delimiter::Bracket => { |
| 134 |
+ let mut iter = group.stream().into_iter(); |
| 135 |
+ match (&iter.next(), &iter.next(), &iter.next(), &iter.next()) { |
| 136 |
+ ( |
| 137 |
+ Some(TokenTree::Ident(ident)), |
| 138 |
+ Some(TokenTree::Punct(punct)), |
| 139 |
+ Some(TokenTree::Literal(literal)), |
| 140 |
+ None, |
| 141 |
+ ) if ident.to_string().as_str() == "u8" && punct.as_char() == ';' => { |
| 142 |
+ let Ok(len) = literal.to_string().parse() else { |
| 143 |
+ panic!("invalid array length: `{}`", literal); |
| 144 |
+ }; |
| 145 |
+ let mut random_bytes = vec![0; len]; |
| 146 |
+ gen_random_bytes(&mut random_bytes); |
| 147 |
+ let array_parts: TokenStream = random_bytes |
| 148 |
+ .into_iter() |
| 149 |
+ .flat_map(|byte| { |
| 150 |
+ let val = TokenTree::from(Literal::u8_suffixed(byte)); |
| 151 |
+ let comma = TokenTree::from(Punct::new(',', Spacing::Alone)); |
| 152 |
+ once(val).chain(once(comma)) |
| 153 |
+ }) |
| 154 |
+ .collect(); |
| 155 |
+ TokenTree::from(Group::new(Delimiter::Bracket, array_parts)).into() |
| 156 |
+ } |
| 157 |
+ _ => panic!("invalid array type arg: `{}`", tt), |
| 158 |
+ } |
| 159 |
} |
| 160 |
- byte_array if byte_array.starts_with("[u8 ; ") && byte_array.ends_with(']')=> { |
| 161 |
- let len = byte_array[6..byte_array.len()-1].parse().unwrap(); |
| 162 |
- let mut random_bytes = vec![0; len]; |
| 163 |
- gen_random_bytes(&mut random_bytes); |
| 164 |
- let array_parts: TokenStream = random_bytes.into_iter().flat_map(|byte| { |
| 165 |
- let val = TokenTree::from(Literal::u8_suffixed(byte)); |
| 166 |
- let comma = TokenTree::from(Punct::new(',', Spacing::Alone)); |
| 167 |
- once(val).chain(once(comma)) |
| 168 |
- }).collect(); |
| 169 |
- TokenTree::from(Group::new(Delimiter::Bracket, array_parts)).into() |
| 170 |
+ _ => { |
| 171 |
+ panic!("invalid type arg: `{}`", tt); |
| 172 |
} |
| 173 |
- _ => panic!("Invalid type"), |
| 174 |
- } |
| 175 |
+ }; |
| 176 |
+ |
| 177 |
+ if let Some(tt) = iter.next() { |
| 178 |
+ panic!("invalid trailing token tree: `{}`", tt); |
| 179 |
+ }; |
| 180 |
+ |
| 181 |
+ result |
| 182 |
} |
| 183 |
diff --git macro/src/span.rs macro/src/span.rs |
| 184 |
index ab72bb08e..e9bda8d69 100644 |
| 185 |
--- macro/src/span.rs |
| 186 |
+++ macro/src/span.rs |
| 187 |
@@ -2,16 +2,15 @@ use proc_macro::Span; |
| 188 |
use std::option_env; |
| 189 |
|
| 190 |
use once_cell::race::OnceBox; |
| 191 |
-use tiny_keccak::{Xof, Hasher, Shake}; |
| 192 |
- |
| 193 |
+use tiny_keccak::{Hasher, Shake, Xof}; |
| 194 |
|
| 195 |
static SEED: OnceBox<Vec<u8>> = OnceBox::new(); |
| 196 |
|
| 197 |
fn get_seed() -> &'static [u8] { |
| 198 |
&SEED.get_or_init(|| { |
| 199 |
if let Some(value) = option_env!("CONST_RANDOM_SEED") { |
| 200 |
- Box::new(value.as_bytes().to_vec()) |
| 201 |
- } else { |
| 202 |
+ Box::new(value.as_bytes().to_vec()) |
| 203 |
+ } else { |
| 204 |
let mut value = [0u8; 32]; |
| 205 |
getrandom::getrandom(&mut value).unwrap(); |
| 206 |
Box::new(value.to_vec()) |