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
//! Common types for event macros.

use std::fmt;

use proc_macro2::{Span, TokenStream};
use quote::{ToTokens, format_ident, quote};
use syn::parse::{Parse, ParseStream};

use crate::util::{RumaEvents, m_prefix_name_to_type_name};

/// All the common event kinds.
#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub(super) enum CommonEventKind {
    /// Global account data.
    ///
    /// This is user data for the whole account.
    GlobalAccountData,

    /// Room account data.
    ///
    /// This is user data specific to a room.
    RoomAccountData,

    /// Ephemeral room data.
    ///
    /// This is data associated to a room and that is not persisted.
    EphemeralRoom,

    /// Message-like event.
    ///
    /// This is an event that can occur in the timeline and that doesn't have a state key.
    MessageLike,

    /// State event.
    ///
    /// This is an event that can occur in the timeline and that has a state key.
    State,

    /// A to-device event.
    ///
    /// This is an event that is sent directly to another device.
    ToDevice,
}

impl CommonEventKind {
    /// Get the list of variations for an event type (struct or enum) for this kind.
    pub(super) fn event_variations(self) -> &'static [EventVariation] {
        match self {
            Self::GlobalAccountData | Self::RoomAccountData | Self::ToDevice => {
                &[EventVariation::None]
            }
            Self::EphemeralRoom => &[EventVariation::None, EventVariation::Sync],
            Self::MessageLike => &[
                EventVariation::None,
                EventVariation::Original,
                EventVariation::Redacted,
                EventVariation::Sync,
                EventVariation::OriginalSync,
                EventVariation::RedactedSync,
            ],
            Self::State => &[
                EventVariation::None,
                EventVariation::Original,
                EventVariation::Redacted,
                EventVariation::Sync,
                EventVariation::OriginalSync,
                EventVariation::RedactedSync,
                EventVariation::Stripped,
                EventVariation::Initial,
            ],
        }
    }

    /// Get the name of the `*EventType` enum for this kind.
    pub(super) fn to_event_type_enum(self) -> syn::Ident {
        format_ident!("{self}Type")
    }
}

impl fmt::Display for CommonEventKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::GlobalAccountData => write!(f, "GlobalAccountDataEvent"),
            Self::RoomAccountData => write!(f, "RoomAccountDataEvent"),
            Self::EphemeralRoom => write!(f, "EphemeralRoomEvent"),
            Self::MessageLike => write!(f, "MessageLikeEvent"),
            Self::State => write!(f, "StateEvent"),
            Self::ToDevice => write!(f, "ToDeviceEvent"),
        }
    }
}

impl Parse for CommonEventKind {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let ident: syn::Ident = input.parse()?;
        Ok(match ident.to_string().as_str() {
            "GlobalAccountData" => Self::GlobalAccountData,
            "RoomAccountData" => Self::RoomAccountData,
            "EphemeralRoom" => Self::EphemeralRoom,
            "MessageLike" => Self::MessageLike,
            "State" => Self::State,
            "ToDevice" => Self::ToDevice,
            id => {
                return Err(syn::Error::new_spanned(
                    ident,
                    format!(
                        "valid event kinds are GlobalAccountData, RoomAccountData, EphemeralRoom, \
                         MessageLike, State, ToDevice; found `{id}`",
                    ),
                ));
            }
        })
    }
}

/// All the possible event variations.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum EventVariation {
    /// The full format of an event.
    ///
    /// Either the event cannot be redacted, or the type contains variants for the original and
    /// redacted variations.
    None,

    /// The sync format of an event.
    ///
    /// Either the event cannot be redacted, or the type contains variants for the original and
    /// redacted variations.
    Sync,

    /// The full format of an event that can be redacted.
    Original,

    /// The sync format of an event that can be redacted.
    OriginalSync,

    /// The stripped format of an event.
    Stripped,

    /// The format of an event passed during room creation.
    Initial,

    /// The full format of an event that was redacted.
    Redacted,

    /// The sync format of an event that was redacted.
    RedactedSync,
}

impl EventVariation {
    /// Whether this variation was redacted.
    pub(super) fn is_redacted(self) -> bool {
        matches!(self, Self::Redacted | Self::RedactedSync)
    }

    /// Whether this variation was received via the `/sync` endpoint.
    pub(super) fn is_sync(self) -> bool {
        matches!(self, Self::Sync | Self::OriginalSync | Self::RedactedSync)
    }

    /// Convert this "sync" variation to one which contains a `room_id`, if possible.
    ///
    /// Returns `None` if this is not a "sync" variation.
    pub(super) fn to_full(self) -> Option<Self> {
        Some(match self {
            Self::Sync => Self::None,
            Self::OriginalSync => Self::Original,
            Self::RedactedSync => Self::Redacted,
            _ => return None,
        })
    }

    /// Whether this variation can implement `JsonCastable` for the other variation, if both are
    /// available for a kind.
    ///
    /// A variation can be cast to another variation when that other variation includes the same
    /// fields or less.
    pub(super) fn is_json_castable_to(self, other: Self) -> bool {
        match self {
            Self::None | Self::OriginalSync | Self::RedactedSync => {
                matches!(other, Self::Sync | Self::Stripped)
            }
            Self::Original => {
                matches!(other, Self::None | Self::Sync | Self::OriginalSync | Self::Stripped)
            }
            Self::Redacted => {
                matches!(other, Self::None | Self::Sync | Self::RedactedSync | Self::Stripped)
            }
            Self::Sync | Self::Stripped | Self::Initial => false,
        }
    }
}

impl fmt::Display for EventVariation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::None => write!(f, ""),
            Self::Sync => write!(f, "Sync"),
            Self::Original => write!(f, "Original"),
            Self::OriginalSync => write!(f, "OriginalSync"),
            Self::Stripped => write!(f, "Stripped"),
            Self::Initial => write!(f, "Initial"),
            Self::Redacted => write!(f, "Redacted"),
            Self::RedactedSync => write!(f, "RedactedSync"),
        }
    }
}

/// The possible variations of an event content trait.
#[derive(Clone, Copy, PartialEq)]
pub(super) enum EventContentTraitVariation {
    /// An event content that wasn't redacted.
    Original,

    /// An event content that was redacted.
    Redacted,

    /// An event content that might have been redacted.
    PossiblyRedacted,

    /// Static data about an event content that wasn't redacted.
    Static,
}

impl fmt::Display for EventContentTraitVariation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Original => Ok(()),
            Self::Redacted => write!(f, "Redacted"),
            Self::PossiblyRedacted => write!(f, "PossiblyRedacted"),
            Self::Static => write!(f, "Static"),
        }
    }
}

/// An event type.
#[derive(Debug, Clone)]
pub(super) struct EventType {
    /// The source of the event type.
    source: syn::LitStr,

    /// Whether this event type is a prefix.
    is_prefix: bool,

    /// The value of the event type.
    value: String,
}

impl EventType {
    /// Whether this event type is a prefix.
    pub(super) fn is_prefix(&self) -> bool {
        self.is_prefix
    }

    /// Access the inner string of this event type.
    pub(super) fn as_str(&self) -> &str {
        &self.value
    }

    /// Access the inner string of this event type and remove the final `*` if this is a prefix.
    pub(super) fn without_wildcard(&self) -> &str {
        if self.is_prefix { self.value.trim_end_matches('*') } else { &self.value }
    }

    /// Whether this event type is stable.
    ///
    /// A stable event type starts with `m.`.
    pub(super) fn is_stable(&self) -> bool {
        self.value.starts_with("m.")
    }

    /// Get the `match` arm representation of this event type.
    pub(super) fn as_match_arm(&self) -> TokenStream {
        let ev_type = self.without_wildcard();

        if self.is_prefix() {
            quote! { t if t.starts_with(#ev_type) }
        } else {
            quote! { #ev_type }
        }
    }
}

impl PartialEq for EventType {
    fn eq(&self, other: &Self) -> bool {
        self.is_prefix == other.is_prefix && self.value == other.value
    }
}

impl Eq for EventType {}

impl From<syn::LitStr> for EventType {
    fn from(source: syn::LitStr) -> Self {
        let value = source.value();
        Self { source, is_prefix: value.ends_with(".*"), value }
    }
}

impl Parse for EventType {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        Ok(input.parse::<syn::LitStr>()?.into())
    }
}

impl fmt::Display for EventType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl ToTokens for EventType {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        self.source.to_tokens(tokens);
    }
}

/// All the event types supported by an event.
#[derive(Clone)]
pub(super) struct EventTypes {
    /// The main event type.
    pub(super) ev_type: EventType,

    /// The alternate event types.
    pub(super) aliases: Vec<EventType>,
}

impl EventTypes {
    /// Try to construct an `EventTypes` from the given default event type and aliases.
    ///
    /// This performs the following validation on the event types:
    ///
    /// - `*` cannot be used anywhere in the event type but as a wildcard at the end.
    /// - If one event type ends with `.*`, all event types must end with it.
    pub(super) fn try_from_parts(ev_type: EventType, aliases: Vec<EventType>) -> syn::Result<Self> {
        if ev_type.without_wildcard().contains('*') {
            return Err(syn::Error::new_spanned(
                ev_type,
                "event type may only contain `*` as part of a `.*` suffix",
            ));
        }

        let is_prefix = ev_type.is_prefix();

        for alias in &aliases {
            if alias.without_wildcard().contains('*') {
                return Err(syn::Error::new_spanned(
                    alias,
                    "alias may only contain `*` as part of a `.*` suffix",
                ));
            }

            if alias.is_prefix() != is_prefix {
                return Err(syn::Error::new_spanned(
                    alias,
                    "aliases should have the same `.*` suffix, or lack thereof, as the main event type",
                ));
            }
        }

        Ok(Self { ev_type, aliases })
    }

    /// Get an iterator over all the event types.
    pub(super) fn iter(&self) -> impl Iterator<Item = &EventType> {
        std::iter::once(&self.ev_type).chain(&self.aliases)
    }

    /// Whether the default event type is a prefix.
    ///
    /// If one event type is a prefix, all event types are prefixes.
    pub(super) fn is_prefix(&self) -> bool {
        self.ev_type.is_prefix
    }

    /// Get the stable event type, if any.
    ///
    /// A stable type is a type beginning with `m.`.
    pub(super) fn stable_type(&self) -> Option<&EventType> {
        self.iter().find(|ev_type| ev_type.is_stable())
    }

    /// Get the main event type.
    ///
    /// It is the stable event type or the default event type as a fallback.
    pub(super) fn main_type(&self) -> &EventType {
        self.stable_type().unwrap_or(&self.ev_type)
    }

    /// Get the type name for these event types.
    ///
    /// Returns an error if none of these types are the stable type.
    pub(super) fn as_event_ident(&self) -> syn::Result<syn::Ident> {
        let stable_type = self.stable_type().ok_or_else(|| {
            syn::Error::new(
                Span::call_site(),
                format!(
                    "A matrix event must declare a well-known type that starts with `m.` \
                     either as the main type or as an alias, or must declare the ident that \
                     should be used if it is only an unstable type, found main type `{}`",
                    self.ev_type
                ),
            )
        })?;

        Ok(m_prefix_name_to_type_name(&stable_type.source)
            .expect("we already checked that the event type is stable"))
    }
}

/// Common fields in event types.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum CommonEventField {
    /// `origin_server_ts`.
    OriginServerTs,

    /// `room_id`.
    RoomId,

    /// `event_id`.
    EventId,

    /// `sender`.
    Sender,
}

impl CommonEventField {
    /// All the variants of this enum
    pub(super) const ALL: &[Self] =
        &[Self::OriginServerTs, Self::RoomId, Self::EventId, Self::Sender];

    /// Get the string representation of this field.
    pub(super) fn as_str(self) -> &'static str {
        match self {
            Self::OriginServerTs => "origin_server_ts",
            Self::RoomId => "room_id",
            Self::EventId => "event_id",
            Self::Sender => "sender",
        }
    }

    /// This field as a [`syn::Ident`].
    pub(super) fn ident(self) -> syn::Ident {
        format_ident!("{}", self.as_str())
    }

    /// Get the type of this field.
    ///
    /// Returns a `(type, is_reference)` tuple.
    pub(super) fn ty(self, ruma_events: &RumaEvents) -> (TokenStream, bool) {
        let ruma_common = ruma_events.ruma_common();

        match self {
            Self::OriginServerTs => (quote! { #ruma_common::MilliSecondsSinceUnixEpoch }, false),
            Self::RoomId => (quote! { &#ruma_common::RoomId }, true),
            Self::EventId => (quote! { &#ruma_common::EventId }, true),
            Self::Sender => (quote! { &#ruma_common::UserId }, true),
        }
    }
}

impl fmt::Display for CommonEventField {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}