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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use crate::Reflect;
use bevy_utils::TypeIdMap;
use core::fmt::{Debug, Formatter};
use std::any::TypeId;

/// A collection of custom attributes for a type, field, or variant.
///
/// These attributes can be created with the [`Reflect` derive macro].
///
/// Attributes are stored by their [`TypeId`](std::any::TypeId).
/// Because of this, there can only be one attribute per type.
///
/// # Example
///
/// ```
/// # use bevy_reflect::{Reflect, Typed, TypeInfo};
/// use core::ops::RangeInclusive;
/// #[derive(Reflect)]
/// struct Slider {
///   #[reflect(@RangeInclusive::<f32>::new(0.0, 1.0))]
///   value: f32
/// }
///
/// let TypeInfo::Struct(info) = <Slider as Typed>::type_info() else {
///   panic!("expected struct info");
/// };
///
/// let range = info.field("value").unwrap().get_attribute::<RangeInclusive<f32>>().unwrap();
/// assert_eq!(0.0..=1.0, *range);
/// ```
///
/// [`Reflect` derive macro]: derive@crate::Reflect
#[derive(Default)]
pub struct CustomAttributes {
    attributes: TypeIdMap<CustomAttribute>,
}

impl CustomAttributes {
    /// Inserts a custom attribute into the collection.
    ///
    /// Note that this will overwrite any existing attribute of the same type.
    pub fn with_attribute<T: Reflect>(mut self, value: T) -> Self {
        self.attributes
            .insert(TypeId::of::<T>(), CustomAttribute::new(value));

        self
    }

    /// Returns `true` if this collection contains a custom attribute of the specified type.
    pub fn contains<T: Reflect>(&self) -> bool {
        self.attributes.contains_key(&TypeId::of::<T>())
    }

    /// Returns `true` if this collection contains a custom attribute with the specified [`TypeId`].
    pub fn contains_by_id(&self, id: TypeId) -> bool {
        self.attributes.contains_key(&id)
    }

    /// Gets a custom attribute by type.
    pub fn get<T: Reflect>(&self) -> Option<&T> {
        self.attributes.get(&TypeId::of::<T>())?.value::<T>()
    }

    /// Gets a custom attribute by its [`TypeId`].
    pub fn get_by_id(&self, id: TypeId) -> Option<&dyn Reflect> {
        Some(self.attributes.get(&id)?.reflect_value())
    }

    /// Returns an iterator over all custom attributes.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = (&TypeId, &dyn Reflect)> {
        self.attributes
            .iter()
            .map(|(key, value)| (key, value.reflect_value()))
    }

    /// Returns the number of custom attributes in this collection.
    pub fn len(&self) -> usize {
        self.attributes.len()
    }

    /// Returns `true` if this collection is empty.
    pub fn is_empty(&self) -> bool {
        self.attributes.is_empty()
    }
}

impl Debug for CustomAttributes {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        f.debug_set().entries(self.attributes.values()).finish()
    }
}

struct CustomAttribute {
    value: Box<dyn Reflect>,
}

impl CustomAttribute {
    pub fn new<T: Reflect>(value: T) -> Self {
        Self {
            value: Box::new(value),
        }
    }

    pub fn value<T: Reflect>(&self) -> Option<&T> {
        self.value.downcast_ref()
    }

    pub fn reflect_value(&self) -> &dyn Reflect {
        &*self.value
    }
}

impl Debug for CustomAttribute {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        self.value.debug(f)
    }
}

/// Implements methods for accessing custom attributes.
///
/// Implements the following methods:
///
/// * `fn custom_attributes(&self) -> &CustomAttributes`
/// * `fn get_attribute<T: Reflect>(&self) -> Option<&T>`
/// * `fn get_attribute_by_id(&self, id: TypeId) -> Option<&dyn Reflect>`
/// * `fn has_attribute<T: Reflect>(&self) -> bool`
/// * `fn has_attribute_by_id(&self, id: TypeId) -> bool`
///
/// # Params
///
/// * `$self` - The name of the variable containing the custom attributes (usually `self`).
/// * `$attributes` - The name of the field containing the [`CustomAttributes`].
/// * `$term` - (Optional) The term used to describe the type containing the custom attributes.
///   This is purely used to generate better documentation. Defaults to `"item"`.
///
macro_rules! impl_custom_attribute_methods {
    ($self:ident . $attributes:ident, $term:literal) => {
        $crate::attributes::impl_custom_attribute_methods!($self, &$self.$attributes, "item");
    };
    ($self:ident, $attributes:expr, $term:literal) => {
        #[doc = concat!("Returns the custom attributes for this ", $term, ".")]
        pub fn custom_attributes(&$self) -> &$crate::attributes::CustomAttributes {
            $attributes
        }

        /// Gets a custom attribute by type.
        ///
        /// For dynamically accessing an attribute, see [`get_attribute_by_id`](Self::get_attribute_by_id).
        pub fn get_attribute<T: $crate::Reflect>(&$self) -> Option<&T> {
            $self.custom_attributes().get::<T>()
        }

        /// Gets a custom attribute by its [`TypeId`](std::any::TypeId).
        ///
        /// This is the dynamic equivalent of [`get_attribute`](Self::get_attribute).
        pub fn get_attribute_by_id(&$self, id: ::std::any::TypeId) -> Option<&dyn $crate::Reflect> {
            $self.custom_attributes().get_by_id(id)
        }

        #[doc = concat!("Returns `true` if this ", $term, " has a custom attribute of the specified type.")]
        #[doc = "\n\nFor dynamically checking if an attribute exists, see [`has_attribute_by_id`](Self::has_attribute_by_id)."]
        pub fn has_attribute<T: $crate::Reflect>(&$self) -> bool {
            $self.custom_attributes().contains::<T>()
        }

        #[doc = concat!("Returns `true` if this ", $term, " has a custom attribute with the specified [`TypeId`](::std::any::TypeId).")]
        #[doc = "\n\nThis is the dynamic equivalent of [`has_attribute`](Self::has_attribute)"]
        pub fn has_attribute_by_id(&$self, id: ::std::any::TypeId) -> bool {
            $self.custom_attributes().contains_by_id(id)
        }
    };
}

pub(crate) use impl_custom_attribute_methods;

#[cfg(test)]
mod tests {
    use super::*;
    use crate as bevy_reflect;
    use crate::type_info::Typed;
    use crate::{TypeInfo, VariantInfo};
    use std::ops::RangeInclusive;

    #[derive(Reflect, PartialEq, Debug)]
    struct Tooltip(String);

    impl Tooltip {
        fn new(value: impl Into<String>) -> Self {
            Self(value.into())
        }
    }

    #[test]
    fn should_get_custom_attribute() {
        let attributes = CustomAttributes::default().with_attribute(0.0..=1.0);

        let value = attributes.get::<RangeInclusive<f64>>().unwrap();
        assert_eq!(&(0.0..=1.0), value);
    }

    #[test]
    fn should_get_custom_attribute_dynamically() {
        let attributes = CustomAttributes::default().with_attribute(String::from("Hello, World!"));

        let value = attributes.get_by_id(TypeId::of::<String>()).unwrap();
        assert!(value
            .reflect_partial_eq(&String::from("Hello, World!"))
            .unwrap());
    }

    #[test]
    fn should_debug_custom_attributes() {
        let attributes = CustomAttributes::default().with_attribute("My awesome custom attribute!");

        let debug = format!("{:?}", attributes);

        assert_eq!(r#"{"My awesome custom attribute!"}"#, debug);

        #[derive(Reflect)]
        struct Foo {
            value: i32,
        }

        let attributes = CustomAttributes::default().with_attribute(Foo { value: 42 });

        let debug = format!("{:?}", attributes);

        assert_eq!(
            r#"{bevy_reflect::attributes::tests::Foo { value: 42 }}"#,
            debug
        );
    }

    #[test]
    fn should_derive_custom_attributes_on_struct_container() {
        #[derive(Reflect)]
        #[reflect(@Tooltip::new("My awesome custom attribute!"))]
        struct Slider {
            value: f32,
        }

        let TypeInfo::Struct(info) = Slider::type_info() else {
            panic!("expected struct info");
        };

        let tooltip = info.get_attribute::<Tooltip>().unwrap();
        assert_eq!(&Tooltip::new("My awesome custom attribute!"), tooltip);
    }

    #[test]
    fn should_derive_custom_attributes_on_struct_fields() {
        #[derive(Reflect)]
        struct Slider {
            #[reflect(@0.0..=1.0)]
            #[reflect(@Tooltip::new("Range: 0.0 to 1.0"))]
            value: f32,
        }

        let TypeInfo::Struct(info) = Slider::type_info() else {
            panic!("expected struct info");
        };

        let field = info.field("value").unwrap();

        let range = field.get_attribute::<RangeInclusive<f64>>().unwrap();
        assert_eq!(&(0.0..=1.0), range);

        let tooltip = field.get_attribute::<Tooltip>().unwrap();
        assert_eq!(&Tooltip::new("Range: 0.0 to 1.0"), tooltip);
    }

    #[test]
    fn should_derive_custom_attributes_on_tuple_container() {
        #[derive(Reflect)]
        #[reflect(@Tooltip::new("My awesome custom attribute!"))]
        struct Slider(f32);

        let TypeInfo::TupleStruct(info) = Slider::type_info() else {
            panic!("expected tuple struct info");
        };

        let tooltip = info.get_attribute::<Tooltip>().unwrap();
        assert_eq!(&Tooltip::new("My awesome custom attribute!"), tooltip);
    }

    #[test]
    fn should_derive_custom_attributes_on_tuple_struct_fields() {
        #[derive(Reflect)]
        struct Slider(
            #[reflect(@0.0..=1.0)]
            #[reflect(@Tooltip::new("Range: 0.0 to 1.0"))]
            f32,
        );

        let TypeInfo::TupleStruct(info) = Slider::type_info() else {
            panic!("expected tuple struct info");
        };

        let field = info.field_at(0).unwrap();

        let range = field.get_attribute::<RangeInclusive<f64>>().unwrap();
        assert_eq!(&(0.0..=1.0), range);

        let tooltip = field.get_attribute::<Tooltip>().unwrap();
        assert_eq!(&Tooltip::new("Range: 0.0 to 1.0"), tooltip);
    }

    #[test]
    fn should_derive_custom_attributes_on_enum_container() {
        #[derive(Reflect)]
        #[reflect(@Tooltip::new("My awesome custom attribute!"))]
        enum Color {
            Transparent,
            Grayscale(f32),
            Rgb { r: u8, g: u8, b: u8 },
        }

        let TypeInfo::Enum(info) = Color::type_info() else {
            panic!("expected enum info");
        };

        let tooltip = info.get_attribute::<Tooltip>().unwrap();
        assert_eq!(&Tooltip::new("My awesome custom attribute!"), tooltip);
    }

    #[test]
    fn should_derive_custom_attributes_on_enum_variants() {
        #[derive(Reflect, Debug, PartialEq)]
        enum Display {
            Toggle,
            Slider,
            Picker,
        }

        #[derive(Reflect)]
        enum Color {
            #[reflect(@Display::Toggle)]
            Transparent,
            #[reflect(@Display::Slider)]
            Grayscale(f32),
            #[reflect(@Display::Picker)]
            Rgb { r: u8, g: u8, b: u8 },
        }

        let TypeInfo::Enum(info) = Color::type_info() else {
            panic!("expected enum info");
        };

        let VariantInfo::Unit(transparent_variant) = info.variant("Transparent").unwrap() else {
            panic!("expected unit variant");
        };

        let display = transparent_variant.get_attribute::<Display>().unwrap();
        assert_eq!(&Display::Toggle, display);

        let VariantInfo::Tuple(grayscale_variant) = info.variant("Grayscale").unwrap() else {
            panic!("expected tuple variant");
        };

        let display = grayscale_variant.get_attribute::<Display>().unwrap();
        assert_eq!(&Display::Slider, display);

        let VariantInfo::Struct(rgb_variant) = info.variant("Rgb").unwrap() else {
            panic!("expected struct variant");
        };

        let display = rgb_variant.get_attribute::<Display>().unwrap();
        assert_eq!(&Display::Picker, display);
    }

    #[test]
    fn should_derive_custom_attributes_on_enum_variant_fields() {
        #[derive(Reflect)]
        enum Color {
            Transparent,
            Grayscale(#[reflect(@0.0..=1.0_f32)] f32),
            Rgb {
                #[reflect(@0..=255u8)]
                r: u8,
                #[reflect(@0..=255u8)]
                g: u8,
                #[reflect(@0..=255u8)]
                b: u8,
            },
        }

        let TypeInfo::Enum(info) = Color::type_info() else {
            panic!("expected enum info");
        };

        let VariantInfo::Tuple(grayscale_variant) = info.variant("Grayscale").unwrap() else {
            panic!("expected tuple variant");
        };

        let field = grayscale_variant.field_at(0).unwrap();

        let range = field.get_attribute::<RangeInclusive<f32>>().unwrap();
        assert_eq!(&(0.0..=1.0), range);

        let VariantInfo::Struct(rgb_variant) = info.variant("Rgb").unwrap() else {
            panic!("expected struct variant");
        };

        let field = rgb_variant.field("g").unwrap();

        let range = field.get_attribute::<RangeInclusive<u8>>().unwrap();
        assert_eq!(&(0..=255), range);
    }

    #[test]
    fn should_allow_unit_struct_attribute_values() {
        #[derive(Reflect)]
        struct Required;

        #[derive(Reflect)]
        struct Foo {
            #[reflect(@Required)]
            value: i32,
        }

        let TypeInfo::Struct(info) = Foo::type_info() else {
            panic!("expected struct info");
        };

        let field = info.field("value").unwrap();
        assert!(field.has_attribute::<Required>());
    }

    #[test]
    fn should_accept_last_attribute() {
        #[derive(Reflect)]
        struct Foo {
            #[reflect(@false)]
            #[reflect(@true)]
            value: i32,
        }

        let TypeInfo::Struct(info) = Foo::type_info() else {
            panic!("expected struct info");
        };

        let field = info.field("value").unwrap();
        assert!(field.get_attribute::<bool>().unwrap());
    }
}