ruma_macros/events/
event_parse.rs

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
//! Implementation of event enum and event content enum macros.

use std::fmt;

use proc_macro2::Span;
use quote::{format_ident, IdentFragment};
use syn::{
    braced,
    parse::{self, Parse, ParseStream},
    punctuated::Punctuated,
    Attribute, Ident, LitStr, Path, Token,
};

/// Custom keywords for the `event_enum!` macro
mod kw {
    syn::custom_keyword!(kind);
    syn::custom_keyword!(events);
    syn::custom_keyword!(alias);
    syn::custom_keyword!(ident);
}

// If the variants of this enum change `to_event_path` needs to be updated as well.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EventKindVariation {
    None,
    Sync,
    Original,
    OriginalSync,
    Stripped,
    Initial,
    Redacted,
    RedactedSync,
}

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

impl EventKindVariation {
    pub fn is_redacted(self) -> bool {
        matches!(self, Self::Redacted | Self::RedactedSync)
    }

    pub fn is_sync(self) -> bool {
        matches!(self, Self::OriginalSync | Self::RedactedSync)
    }

    pub fn to_full(self) -> Self {
        match self {
            EventKindVariation::OriginalSync => EventKindVariation::Original,
            EventKindVariation::RedactedSync => EventKindVariation::Redacted,
            _ => panic!("No original (unredacted) form of {self:?}"),
        }
    }
}

// If the variants of this enum change `to_event_path` needs to be updated as well.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EventKind {
    GlobalAccountData,
    RoomAccountData,
    Ephemeral,
    MessageLike,
    State,
    ToDevice,
    RoomRedaction,
    Presence,
    HierarchySpaceChild,
    Decrypted,
}

impl fmt::Display for EventKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            EventKind::GlobalAccountData => write!(f, "GlobalAccountDataEvent"),
            EventKind::RoomAccountData => write!(f, "RoomAccountDataEvent"),
            EventKind::Ephemeral => write!(f, "EphemeralRoomEvent"),
            EventKind::MessageLike => write!(f, "MessageLikeEvent"),
            EventKind::State => write!(f, "StateEvent"),
            EventKind::ToDevice => write!(f, "ToDeviceEvent"),
            EventKind::RoomRedaction => write!(f, "RoomRedactionEvent"),
            EventKind::Presence => write!(f, "PresenceEvent"),
            EventKind::HierarchySpaceChild => write!(f, "HierarchySpaceChildEvent"),
            EventKind::Decrypted => unreachable!(),
        }
    }
}

impl IdentFragment for EventKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl IdentFragment for EventKindVariation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl EventKind {
    pub fn is_account_data(self) -> bool {
        matches!(self, Self::GlobalAccountData | Self::RoomAccountData)
    }

    pub fn is_timeline(self) -> bool {
        matches!(self, Self::MessageLike | Self::RoomRedaction | Self::State)
    }

    pub fn to_event_ident(self, var: EventKindVariation) -> syn::Result<Ident> {
        use EventKindVariation as V;

        match (self, var) {
            (_, V::None)
            | (Self::Ephemeral | Self::MessageLike | Self::State, V::Sync)
            | (
                Self::MessageLike | Self::RoomRedaction | Self::State,
                V::Original | V::OriginalSync | V::Redacted | V::RedactedSync,
            )
            | (Self::State, V::Stripped | V::Initial) => Ok(format_ident!("{var}{self}")),
            _ => Err(syn::Error::new(
                Span::call_site(),
                format!("({self:?}, {var:?}) is not a valid event kind / variation combination"),
            )),
        }
    }

    pub fn to_event_enum_ident(self, var: EventKindVariation) -> syn::Result<Ident> {
        Ok(format_ident!("Any{}", self.to_event_ident(var)?))
    }

    pub fn to_event_type_enum(self) -> Ident {
        format_ident!("{}Type", self)
    }

    /// `Any[kind]EventContent`
    pub fn to_content_enum(self) -> Ident {
        format_ident!("Any{}Content", self)
    }

    /// `AnyFull[kind]EventContent`
    pub fn to_full_content_enum(self) -> Ident {
        format_ident!("AnyFull{}Content", self)
    }
}

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

// This function is only used in the `Event` derive macro expansion code.
/// Validates the given `ident` is a valid event struct name and returns a tuple of enums
/// representing the name.
pub fn to_kind_variation(ident: &Ident) -> Option<(EventKind, EventKindVariation)> {
    let ident_str = ident.to_string();
    match ident_str.as_str() {
        "GlobalAccountDataEvent" => Some((EventKind::GlobalAccountData, EventKindVariation::None)),
        "RoomAccountDataEvent" => Some((EventKind::RoomAccountData, EventKindVariation::None)),
        "EphemeralRoomEvent" => Some((EventKind::Ephemeral, EventKindVariation::None)),
        "SyncEphemeralRoomEvent" => Some((EventKind::Ephemeral, EventKindVariation::Sync)),
        "OriginalMessageLikeEvent" => Some((EventKind::MessageLike, EventKindVariation::Original)),
        "OriginalSyncMessageLikeEvent" => {
            Some((EventKind::MessageLike, EventKindVariation::OriginalSync))
        }
        "RedactedMessageLikeEvent" => Some((EventKind::MessageLike, EventKindVariation::Redacted)),
        "RedactedSyncMessageLikeEvent" => {
            Some((EventKind::MessageLike, EventKindVariation::RedactedSync))
        }
        "OriginalStateEvent" => Some((EventKind::State, EventKindVariation::Original)),
        "OriginalSyncStateEvent" => Some((EventKind::State, EventKindVariation::OriginalSync)),
        "StrippedStateEvent" => Some((EventKind::State, EventKindVariation::Stripped)),
        "InitialStateEvent" => Some((EventKind::State, EventKindVariation::Initial)),
        "RedactedStateEvent" => Some((EventKind::State, EventKindVariation::Redacted)),
        "RedactedSyncStateEvent" => Some((EventKind::State, EventKindVariation::RedactedSync)),
        "ToDeviceEvent" => Some((EventKind::ToDevice, EventKindVariation::None)),
        "PresenceEvent" => Some((EventKind::Presence, EventKindVariation::None)),
        "HierarchySpaceChildEvent" => {
            Some((EventKind::HierarchySpaceChild, EventKindVariation::Stripped))
        }
        "OriginalRoomRedactionEvent" => Some((EventKind::RoomRedaction, EventKindVariation::None)),
        "OriginalSyncRoomRedactionEvent" => {
            Some((EventKind::RoomRedaction, EventKindVariation::OriginalSync))
        }
        "RedactedRoomRedactionEvent" => {
            Some((EventKind::RoomRedaction, EventKindVariation::Redacted))
        }
        "RedactedSyncRoomRedactionEvent" => {
            Some((EventKind::RoomRedaction, EventKindVariation::RedactedSync))
        }
        "DecryptedOlmV1Event" | "DecryptedMegolmV1Event" => {
            Some((EventKind::Decrypted, EventKindVariation::None))
        }
        _ => None,
    }
}

pub struct EventEnumEntry {
    pub attrs: Vec<Attribute>,
    pub aliases: Vec<LitStr>,
    pub ev_type: LitStr,
    pub ev_path: Path,
    pub ident: Option<Ident>,
}

impl Parse for EventEnumEntry {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let (ruma_enum_attrs, attrs) = input
            .call(Attribute::parse_outer)?
            .into_iter()
            .partition::<Vec<_>, _>(|attr| attr.path().is_ident("ruma_enum"));
        let ev_type: LitStr = input.parse()?;
        let _: Token![=>] = input.parse()?;
        let ev_path = input.call(Path::parse_mod_style)?;
        let has_suffix = ev_type.value().ends_with(".*");

        let mut aliases = Vec::with_capacity(ruma_enum_attrs.len());
        let mut ident = None;

        for attr_list in ruma_enum_attrs {
            for attr in attr_list
                .parse_args_with(Punctuated::<EventEnumAttr, Token![,]>::parse_terminated)?
            {
                match attr {
                    EventEnumAttr::Alias(alias) => {
                        if alias.value().ends_with(".*") == has_suffix {
                            aliases.push(alias);
                        } else {
                            return Err(syn::Error::new_spanned(
                                &attr_list,
                                "aliases should have the same `.*` suffix, or lack thereof, as the main event type",
                            ));
                        }
                    }
                    EventEnumAttr::Ident(i) => {
                        if ident.is_some() {
                            return Err(syn::Error::new_spanned(
                                &attr_list,
                                "multiple `ident` attributes found, there can be only one",
                            ));
                        }

                        ident = Some(i);
                    }
                }
            }
        }

        Ok(Self { attrs, aliases, ev_type, ev_path, ident })
    }
}

/// The entire `event_enum!` macro structure directly as it appears in the source code.
pub struct EventEnumDecl {
    /// Outer attributes on the field, such as a docstring.
    pub attrs: Vec<Attribute>,

    /// The event kind.
    pub kind: EventKind,

    /// An array of valid matrix event types.
    ///
    /// This will generate the variants of the event type "kind". There needs to be a corresponding
    /// variant in the `*EventType` enum for this event kind (converted to a valid Rust-style type
    /// name by stripping `m.`, replacing the remaining dots by underscores and then converting
    /// from snake_case to CamelCase).
    pub events: Vec<EventEnumEntry>,
}

/// The entire `event_enum!` macro structure directly as it appears in the source code.
pub struct EventEnumInput {
    pub(crate) enums: Vec<EventEnumDecl>,
}

impl Parse for EventEnumInput {
    fn parse(input: ParseStream<'_>) -> parse::Result<Self> {
        let mut enums = vec![];
        while !input.is_empty() {
            let attrs = input.call(Attribute::parse_outer)?;

            let _: Token![enum] = input.parse()?;
            let kind: EventKind = input.parse()?;

            let content;
            braced!(content in input);
            let events = content.parse_terminated(EventEnumEntry::parse, Token![,])?;
            let events = events.into_iter().collect();
            enums.push(EventEnumDecl { attrs, kind, events });
        }
        Ok(EventEnumInput { enums })
    }
}

pub enum EventEnumAttr {
    Alias(LitStr),
    Ident(Ident),
}

impl Parse for EventEnumAttr {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let lookahead = input.lookahead1();

        if lookahead.peek(kw::alias) {
            let _: kw::alias = input.parse()?;
            let _: Token![=] = input.parse()?;
            let s: LitStr = input.parse()?;
            Ok(Self::Alias(s))
        } else if lookahead.peek(kw::ident) {
            let _: kw::ident = input.parse()?;
            let _: Token![=] = input.parse()?;
            let i: Ident = input.parse()?;
            Ok(Self::Ident(i))
        } else {
            Err(lookahead.error())
        }
    }
}