1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

use super::*;

macro_rules! literal {
    ($($type:ty,)*) => {
        $(
            impl Bake for $type {
                fn bake(&self, _: &CrateEnv) -> TokenStream {
                    quote! {
                        #self
                    }
                }
            }
        )*
    }
}

literal!(
    u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64, &str, char, bool,
);

#[test]
fn literal() {
    test_bake!(
        u16,
        const: 3849u16
    );
}

impl<'a, T: ?Sized> Bake for &'a T
where
    T: Bake,
{
    fn bake(&self, ctx: &CrateEnv) -> TokenStream {
        if core::mem::size_of::<Self>() == core::mem::size_of::<&[u8]>()
            && core::any::type_name::<Self>() == core::any::type_name::<&[u8]>()
        {
            // Safety: `&T` and `&[u8]` have the same size. Note that `self: &&T`, so this copies
            // `&T`, not `T` itself.
            // There are no types smaller than `u8`, so there won't be an alignment or allocation-length
            // issue even if T is not actually `[u8]`.
            return byte_string(unsafe { core::mem::transmute_copy(self) });
        }
        let t = <T as Bake>::bake(*self, ctx);
        quote! {
            &#t
        }
    }
}

#[test]
fn r#ref() {
    test_bake!(
        &f32,
        const: &934.34f32
    );
}

impl<T> Bake for [T]
where
    T: Bake,
{
    fn bake(&self, ctx: &CrateEnv) -> TokenStream {
        if core::mem::size_of::<T>() == core::mem::size_of::<u8>()
            && core::any::type_name::<T>() == core::any::type_name::<u8>()
        {
            // Safety: self.as_ptr()'s allocation is at least self.len() bytes long,
            // initialised, and well-alligned.
            return byte_string(unsafe {
                core::slice::from_raw_parts(self.as_ptr() as *const u8, self.len())
            });
        }
        let data = self.iter().map(|d| d.bake(ctx));
        quote! {
            [#(#data),*]
        }
    }
}

fn byte_string(bytes: &[u8]) -> TokenStream {
    let byte_string = proc_macro2::Literal::byte_string(bytes);
    // Before clippy 1.70 there's a bug (https://github.com/rust-lang/rust-clippy/pull/10603) where a byte
    // string like b"\0\\01" would incorrectly trigger this lint. This was due to it swallowing the slash's
    // escape slash when trying to match the first "\0" with another digit, and then seeing b"\01".
    // This workaround is conservative as it doesn't actually check for swallowing, only whether an escaped
    // slash appears before 0[0-7].
    let suppress_octal_false_positive = if bytes
        .windows(3)
        .any(|b| matches!(b, &[b'\\', b'0', b'0'..=b'7']))
    {
        quote!(#[allow(clippy::octal_escapes)])
    } else {
        quote!()
    };
    quote!(#suppress_octal_false_positive #byte_string)
}

#[test]
fn slice() {
    // Cannot use test_bake! as it's not possible to write a closed slice expression (&[1] has type &[usize; 1])
    let slice: &[bool] = &[];
    assert_eq!(Bake::bake(&slice, &Default::default()).to_string(), "& []");
    let slice: &[bool] = &[true];
    assert_eq!(
        Bake::bake(&slice, &Default::default()).to_string(),
        "& [true]",
    );
    let slice: &[bool] = &[true, false];
    assert_eq!(
        Bake::bake(&slice, &Default::default()).to_string(),
        "& [true , false]",
    );
}

impl<T, const N: usize> Bake for [T; N]
where
    T: Bake,
{
    fn bake(&self, ctx: &CrateEnv) -> TokenStream {
        self.as_slice().bake(ctx)
    }
}

#[test]
fn array() {
    test_bake!(
        &[bool; 0],
        const: &[]
    );
    test_bake!(
        &[bool; 1],
        const: &[true]
    );
    test_bake!(
        &[bool; 2],
        const: &[true, false]
    );
}

impl<T> Bake for Option<T>
where
    T: Bake,
{
    fn bake(&self, ctx: &CrateEnv) -> TokenStream {
        match self {
            None => quote! { None },
            Some(t) => {
                let t = t.bake(ctx);
                quote! {
                    Some(#t)
                }
            }
        }
    }
}

#[test]
fn option() {
    test_bake!(
        Option<&'static str>,
        const: Some("hello")
    );
    test_bake!(
        Option<&'static str>,
        const: None
    );
}

impl<T, E> Bake for Result<T, E>
where
    T: Bake,
    E: Bake,
{
    fn bake(&self, ctx: &CrateEnv) -> TokenStream {
        match self {
            Ok(ok) => {
                let ok = ok.bake(ctx);
                quote! { Ok(#ok) }
            }
            Err(e) => {
                let e = e.bake(ctx);
                quote! {
                    Err(#e)
                }
            }
        }
    }
}

#[test]
fn result() {
    test_bake!(
        Result<&'static str, ()>,
        const: Ok("hello")
    );
    test_bake!(
        Result<&'static str, ()>,
        const: Err(())
    );
}

macro_rules! tuple {
    ($ty:ident, $ident:ident) => {
        impl<$ty> Bake for ($ty,) where $ty: Bake {
            fn bake(&self, ctx: &CrateEnv) -> TokenStream {
                let $ident = self.0.bake(ctx);
                quote! {
                    (#$ident,)
                }
            }
        }
    };
    ($($ty:ident, $ident:ident),*) => {
        impl<$($ty),*> Bake for ($($ty,)*) where $($ty: Bake),* {
            fn bake(&self, _ctx: &CrateEnv) -> TokenStream {
                let ($($ident,)*) = self;
                $(
                    let $ident = $ident.bake(_ctx);
                )*
                quote! {
                    ($(#$ident),*)
                }
            }
        }
    }
}

tuple!();
tuple!(A, a);
tuple!(A, a, B, b);
tuple!(A, a, B, b, C, c);
tuple!(A, a, B, b, C, c, D, d);
tuple!(A, a, B, b, C, c, D, d, E, e);
tuple!(A, a, B, b, C, c, D, d, E, e, F, f);
tuple!(A, a, B, b, C, c, D, d, E, e, F, f, G, g);
tuple!(A, a, B, b, C, c, D, d, E, e, F, f, G, g, H, h);
tuple!(A, a, B, b, C, c, D, d, E, e, F, f, G, g, H, h, I, i);
tuple!(A, a, B, b, C, c, D, d, E, e, F, f, G, g, H, h, I, i, J, j);

#[test]
fn tuple() {
    test_bake!(
        (),
        const: ()
    );
    test_bake!(
        (u8,),
        const: (0u8,)
    );
    test_bake!(
        (u8, i8),
        const: (0u8, 0i8)
    );
}