ruma-macros 0.18.0

Procedural macros used by the Ruma crates.
Documentation
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! Functions to generate `Any*EventContent` enums.

use std::{collections::BTreeMap, ops::Deref};

use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote};

use crate::{
    events::{
        common::{EventContentTraitVariation, EventVariation},
        event_enum::{EventContentVariation, EventEnum, EventEnumKind},
    },
    util::RumaEventsReexport,
};

/// A list of `Any*EventContent` enums.
pub(super) struct EventContentEnums<'a> {
    inner: &'a EventEnum<'a>,

    /// Enums matching an `EventContentVariation`.
    enums: BTreeMap<EventContentVariation, EventContentEnumVariation<'a>>,

    /// The special `AnyStateEventContentChange` enum.
    change: Option<EventContentChangeEnum<'a>>,
}

impl<'a> EventContentEnums<'a> {
    /// Construct an `EventContentEnums` with the given event enum data.
    pub(super) fn new(inner: &'a EventEnum<'a>) -> Self {
        Self { inner, enums: BTreeMap::new(), change: None }
    }

    /// Get the `EventContentEnumVariation` matching the given event variation, if possible.
    ///
    /// If the event variation is supported but the corresponding `EventContentEnumVariation`
    /// doesn't exist in this list, it is created.
    pub(super) fn get_or_create(
        &mut self,
        event_variation: EventVariation,
    ) -> Option<&EventContentEnumVariation<'a>> {
        let variation = EventContentVariation::from_event_variation(event_variation)?;

        Some(
            self.enums
                .entry(variation)
                .or_insert_with(|| EventContentEnumVariation::new(self.inner, variation)),
        )
    }

    /// Get the `EventContentChangeEnum`.
    ///
    /// If it doesn't exist in this list, it is created.
    pub(super) fn event_content_change_enum(&mut self) -> &EventContentChangeEnum<'a> {
        self.change.get_or_insert_with(|| EventContentChangeEnum::new(self.inner))
    }

    /// Expand the event content enums in this list.
    pub(super) fn expand(&self) -> TokenStream {
        self.enums
            .values()
            .map(EventContentEnumVariation::expand)
            .chain(self.change.iter().map(EventContentChangeEnum::expand))
            .collect()
    }
}

/// The data for an `Any*EventContent` enum.
pub(super) struct EventContentEnumVariation<'a> {
    /// The event enum data.
    inner: &'a EventEnum<'a>,

    /// The variation of this enum.
    variation: EventContentVariation,

    /// The name of this enum.
    ident: syn::Ident,

    /// The paths to the `*EventContent` types of the entries.
    event_content_types: Vec<syn::Path>,
}

impl<'a> EventContentEnumVariation<'a> {
    fn new(inner: &'a EventEnum<'a>, variation: EventContentVariation) -> Self {
        let kind = inner.kind;
        let event_content_types =
            inner.events.iter().map(|event| event.to_event_content_path(kind, variation)).collect();

        Self {
            inner,
            variation,
            ident: format_ident!("Any{variation}{kind}Content"),
            event_content_types,
        }
    }
}

impl EventContentEnumVariation<'_> {
    /// Generate this `Any*EventContent` enum.
    fn expand(&self) -> TokenStream {
        let ruma_events = self.ruma_events;
        let serde = ruma_events.reexported(RumaEventsReexport::Serde);

        let attrs = &self.attrs;
        let ident = &self.ident;
        let variants = &self.variants;
        let variant_attrs = &self.variant_attrs;
        let variant_docs = &self.variant_docs;
        let event_content_types = &self.event_content_types;
        let custom_content_struct = &self.custom_content_struct;

        let event_content_from_type_impl = self.expand_content_enum_event_content_from_type_impl();
        let event_content_kind_trait_impl =
            self.expand_content_enum_event_content_kind_trait_impl();
        let from_impl = self.expand_from_impl(ident, event_content_types);
        let json_castable_impl = self.expand_content_enum_json_castable_impl();

        // We need this path as a string.
        let serialize_custom_event_error_path =
            quote! { #ruma_events::serialize_custom_event_error }.to_string();

        quote! {
            #( #attrs )*
            #[derive(Clone, Debug, #serde::Serialize)]
            #[serde(untagged)]
            #[allow(clippy::large_enum_variant, unused_qualifications)]
            #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
            pub enum #ident {
                #(
                    #variant_docs
                    #( #variant_attrs )*
                    #variants(#event_content_types),
                )*
                #[doc(hidden)]
                #[serde(serialize_with = #serialize_custom_event_error_path)]
                _Custom(#ruma_events::_custom::#custom_content_struct),
            }

            #event_content_from_type_impl
            #event_content_kind_trait_impl
            #from_impl
            #json_castable_impl
        }
    }

    /// Generate the `ruma_events::EventContentFromType` implementation for the
    /// `Any*EventContent` enum.
    fn expand_content_enum_event_content_from_type_impl(&self) -> TokenStream {
        let ruma_events = self.ruma_events;
        let serde_json = ruma_events.reexported(RumaEventsReexport::SerdeJson);

        let ident = &self.ident;
        let variants = &self.variants;
        let event_attrs = &self.variant_attrs;
        let event_content_types = &self.event_content_types;
        let event_type_string_match_arms = &self.event_type_string_match_arms;
        let custom_content_struct = &self.custom_content_struct;

        let deserialize_event_contents = self.events.iter().zip(event_content_types.iter()).map(
            |(event, event_content_type)| {
                if event.has_type_fragment() {
                    // If the event has a type fragment, then it implements EventContentFromType
                    // itself; see `generate_event_content_impl` which does that. In this case,
                    // forward to its implementation.
                    quote! {
                        #event_content_type::from_parts(event_type, json)?
                    }
                } else {
                    // The event doesn't have a type fragment, so it *should* implement
                    // Deserialize: use that here.
                    quote! {
                        #serde_json::from_str(json.get())?
                    }
                }
            },
        );

        quote! {
            #[automatically_derived]
            impl #ruma_events::EventContentFromType for #ident {
                fn from_parts(event_type: &str, json: &#serde_json::value::RawValue) -> serde_json::Result<Self> {
                    match event_type {
                        #(
                            #( #event_attrs )*
                            #( #event_type_string_match_arms )|* => {
                                let content = #deserialize_event_contents;
                                Ok(Self::#variants(content))
                            },
                        )*
                        _ => {
                            Ok(Self::_Custom(
                                #ruma_events::_custom::#custom_content_struct::from_parts(event_type, json)?
                            ))
                        }
                    }
                }
            }
        }
    }

    /// Generate the `ruma_events::{kind}EventContent` trait implementation for the
    /// `Any*EventContent` enum.
    fn expand_content_enum_event_content_kind_trait_impl(&self) -> TokenStream {
        let ruma_events = self.ruma_events;

        let ident = &self.ident;
        let event_type_enum = &self.event_type_enum;
        let variants = &self.variants;
        let variant_attrs = &self.variant_attrs;

        let event_content_kind_trait =
            self.kind.to_content_kind_trait(self.variation.to_event_content_trait());
        let extra_event_content_impl = (self.kind == EventEnumKind::State).then(|| {
            quote! {
                type StateKey = String;
            }
        });

        quote! {
            #[automatically_derived]
            impl #ruma_events::#event_content_kind_trait for #ident {
                #extra_event_content_impl

                fn event_type(&self) -> #ruma_events::#event_type_enum {
                    match self {
                        #(
                            #( #variant_attrs )*
                            Self::#variants(content) => content.event_type(),
                        )*
                        Self::_Custom(content) => content.event_type(),
                    }
                }
            }
        }
    }

    /// Implement `JsonCastable<{enum}>` for all the variants and `JsonCastable<JsonObject>` for the
    /// given event content enum.
    fn expand_content_enum_json_castable_impl(&self) -> TokenStream {
        let ruma_common = self.ruma_events.ruma_common();
        let ident = &self.ident;

        // All event content types are represented as objects in JSON.
        let mut json_castable_impls = quote! {
            #[automatically_derived]
            impl #ruma_common::serde::JsonCastable<#ruma_common::serde::JsonObject> for #ident {}
        };

        json_castable_impls.extend(
            self.event_content_types.iter().zip(self.variant_attrs.iter()).map(
                |(event_content_type, variant_attrs)| {
                    quote! {
                        #[allow(unused_qualifications)]
                        #[automatically_derived]
                        #( #variant_attrs )*
                        impl #ruma_common::serde::JsonCastable<#ident> for #event_content_type {}
                    }
                },
            ),
        );

        json_castable_impls
    }

    /// Generate the accessors on an event enum to get the event content.
    pub(super) fn expand_content_accessors(
        &self,
        event_variation: EventVariation,
        event_struct: &syn::Ident,
    ) -> TokenStream {
        let ruma_events = self.ruma_events;

        let ident = &self.ident;
        let variants = &self.variants;
        let variant_attrs = &self.variant_attrs;

        match (self.kind, self.variation, event_variation) {
            (
                EventEnumKind::State | EventEnumKind::MessageLike,
                EventContentVariation::Original,
                EventVariation::None | EventVariation::Sync,
            ) => {
                quote! {
                    /// Returns the content for this event if it is not redacted, or `None` if it is.
                    pub fn original_content(&self) -> Option<#ident> {
                        match self {
                            #(
                                #( #variant_attrs )*
                                Self::#variants(event) => {
                                    event.as_original().map(|ev| #ident::#variants(ev.content.clone()))
                                }
                            )*
                            Self::_Custom(event) => event.as_original().map(|ev| {
                                #ident::_Custom(ev.content.clone())
                            }),
                        }
                    }

                    /// Returns whether this event is redacted.
                    pub fn is_redacted(&self) -> bool {
                        match self {
                            #(
                                #( #variant_attrs )*
                                Self::#variants(event) => {
                                    event.as_original().is_none()
                                }
                            )*
                            Self::_Custom(event) => event.as_original().is_none(),
                        }
                    }
                }
            }
            (
                EventEnumKind::State,
                EventContentVariation::PossiblyRedacted,
                EventVariation::None | EventVariation::Sync,
            ) => {
                quote! {
                    /// Returns the content for this event.
                    pub fn content(&self) -> #ident {
                        match self {
                            #(
                                #( #variant_attrs )*
                                Self::#variants(event) => match event {
                                    #ruma_events::#event_struct::Original(ev) => {
                                        #ident::#variants(ev.content.clone().into())
                                    }
                                    #ruma_events::#event_struct::Redacted(ev) => {
                                        #ident::#variants(ev.content.clone().into())
                                    }
                                },
                            )*
                            Self::_Custom(event) => match event {
                                #ruma_events::#event_struct::Original(ev) => {
                                    #ident::_Custom(ev.content.clone())
                                }
                                #ruma_events::#event_struct::Redacted(ev) => {
                                    #ident::_Custom(ev.content.clone())
                                }
                            },
                        }
                    }
                }
            }
            _ => {
                quote! {
                    /// Returns the content for this event.
                    pub fn content(&self) -> #ident {
                        match self {
                            #(
                                #( #variant_attrs )*
                                Self::#variants(event) => #ident::#variants(event.content.clone()),
                            )*
                            Self::_Custom(event) => #ident::_Custom(event.content.clone()),
                        }
                    }
                }
            }
        }
    }
}

impl<'a> Deref for EventContentEnumVariation<'a> {
    type Target = EventEnum<'a>;

    fn deref(&self) -> &Self::Target {
        self.inner
    }
}

/// The data for the `AnyStateEventContentChange` enum.
pub(super) struct EventContentChangeEnum<'a> {
    /// The event enum data.
    inner: &'a EventEnum<'a>,

    /// The name of the enum.
    ident: syn::Ident,

    /// The paths to the `*EventContent` types of the entries.
    event_content_types: Vec<syn::Path>,
}

impl<'a> EventContentChangeEnum<'a> {
    /// Construct an `EventContentChangeEnum` with the given event enum data.
    fn new(inner: &'a EventEnum<'a>) -> Self {
        let ident = syn::Ident::new("AnyStateEventContentChange", Span::call_site());
        let kind = inner.kind;
        let event_content_types = inner
            .events
            .iter()
            .map(|event| event.to_event_content_path(kind, EventContentVariation::Original))
            .collect();

        Self { inner, ident, event_content_types }
    }
}

impl EventContentChangeEnum<'_> {
    /// Generate the `AnyStateEventContentChange` enum.
    fn expand(&self) -> TokenStream {
        let ruma_events = self.ruma_events;

        let attrs = &self.attrs;
        let ident = &self.ident;
        let event_type_enum = &self.event_type_enum;
        let variants = &self.variants;
        let variant_attrs = &self.variant_attrs;
        let variant_docs = &self.variant_docs;
        let event_content_types = &self.event_content_types;
        let custom_content_struct = &self.custom_content_struct;

        let event_content_kind_trait =
            self.kind.to_content_kind_trait(EventContentTraitVariation::Original);

        quote! {
            #( #attrs )*
            #[derive(Clone, Debug)]
            #[allow(clippy::large_enum_variant, unused_qualifications)]
            #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
            pub enum #ident {
                #(
                    #variant_docs
                    #( #variant_attrs )*
                    #variants(#ruma_events::StateEventContentChange<#event_content_types>),
                )*
                #[doc(hidden)]
                _Custom(#ruma_events::_custom::#custom_content_struct),
            }

            impl #ident {
                /// Get the event’s type, like `m.room.create`.
                pub fn event_type(&self) -> #ruma_events::#event_type_enum {
                    match self {
                        #(
                            #( #variant_attrs )*
                            Self::#variants(content) => content.event_type(),
                        )*
                        Self::_Custom(content) => {
                            #ruma_events::#event_content_kind_trait::event_type(content)
                        }
                    }
                }
            }
        }
    }

    /// Generate the accessors on an event enum to get the event content.
    ///
    /// `event_enum` is the name of the `*StateEvent` enum containing the `Original` and `Redacted`
    /// variants, used by each variant of the `Any*StateEvent` enum.
    pub(super) fn expand_content_accessors(&self, event_enum: &syn::Ident) -> TokenStream {
        let ruma_events = self.ruma_events;

        let ident = &self.ident;
        let variants = &self.variants;
        let variant_attrs = &self.variant_attrs;

        quote! {
            /// Returns the content change of this state event.
            pub fn content_change(&self) -> #ident {
                match self {
                    #(
                        #( #variant_attrs )*
                        Self::#variants(event) => match event {
                            #ruma_events::#event_enum::Original(ev) => #ident::#variants(
                                #ruma_events::StateEventContentChange::Original {
                                    content: ev.content.clone(),
                                    prev_content: ev.unsigned.prev_content.clone()
                                }
                            ),
                            #ruma_events::#event_enum::Redacted(ev) => #ident::#variants(
                                #ruma_events::StateEventContentChange::Redacted(
                                    ev.content.clone()
                                )
                            ),
                        },
                    )*
                    Self::_Custom(event) => match event {
                        #ruma_events::#event_enum::Original(ev) => {
                            #ident::_Custom(ev.content.clone())
                        }
                        #ruma_events::#event_enum::Redacted(ev) => {
                            #ident::_Custom(ev.content.clone())
                        }
                    },
                }
            }
        }
    }
}

impl<'a> Deref for EventContentChangeEnum<'a> {
    type Target = EventEnum<'a>;

    fn deref(&self) -> &Self::Target {
        self.inner
    }
}