casper-node-macros 0.1.0

A macro to create reactor implementations for the casper-node.
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
//! Parser for reactor macro.
//!
//! Contains the `Parse` implementations for the intermediate representation of the macro, which is
//! `ReactorDefinition`. Many functions required by the code generator are also included here as
//! methods in this representation.

use std::{
    convert::TryFrom,
    fmt::{self, Debug, Formatter},
};

use indexmap::IndexMap;
use inflector::cases::pascalcase::to_pascal_case;
use syn::{
    braced, bracketed,
    export::quote::quote,
    parenthesized,
    parse::{Parse, ParseStream, Result},
    punctuated::Punctuated,
    Expr, Ident, ItemType, Path, Token,
};

use crate::{rust_type::RustType, util::to_ident};
use proc_macro2::{Span, TokenStream};

#[derive(Debug)]
pub(crate) struct ReactorDefinition {
    /// Identifier of the reactor type.
    ///
    /// Example: `ExampleReactor`.
    reactor_type_ident: Ident,

    /// Reactor's associated configuration type.
    ///
    /// A full type that will later be the `Reactor::Config` associated type.
    config_type: RustType,

    /// Mapping of component attribute names to their types.
    ///
    /// Example: "net" maps to `crate::components::small_net::SmallNet<NodeId>`.
    components: IndexMap<Ident, ComponentDefinition>,

    /// Overrides for events of components.
    ///
    /// Example: "net" may have an event type that differs from
    /// `crate::components::small_net::Event`.
    events: IndexMap<Ident, EventDefinition>,

    /// List of request routing directives.
    requests: Vec<RequestDefinition>,

    /// List of announcement routing directives.
    announcements: Vec<AnnouncementDefinition>,
}

impl ReactorDefinition {
    /// Returns the reactor's type's identifier (e.g. `ExampleReactor`).
    pub fn reactor_ident(&self) -> Ident {
        self.reactor_type_ident.clone()
    }

    /// Returns the reactor's associated event type's identifier (e.g. `ExampleReactorEvent`).
    pub fn event_ident(&self) -> Ident {
        let mut event_str = self.reactor_ident().to_string();
        event_str.push_str("Event");
        to_ident(&event_str)
    }

    /// Returns the reactor's associated error type's identifier (e.g. `ExampleReactorError`).
    pub fn error_ident(&self) -> Ident {
        let mut event_str = self.reactor_ident().to_string();
        event_str.push_str("Error");
        to_ident(&event_str)
    }

    /// Returns an iterator over all announcement mappings.
    pub fn announcements(&self) -> impl Iterator<Item = &AnnouncementDefinition> {
        self.announcements.iter()
    }

    /// Returns an iterator over all component definitions.
    pub fn components(&self) -> impl Iterator<Item = &ComponentDefinition> {
        self.components.values()
    }

    /// Returns the configuration type.
    pub fn config_type(&self) -> &RustType {
        &self.config_type
    }

    /// Returns an iterator over all request mappings.
    pub fn requests(&self) -> impl Iterator<Item = &RequestDefinition> {
        self.requests.iter()
    }

    /// Returns the a full component by ident.
    pub fn component(&self, ident: &Ident) -> &ComponentDefinition {
        &self.components[ident]
    }

    /// Returns the type for the event associated with a specific component.
    pub fn component_event(&self, component: &ComponentDefinition) -> TokenStream {
        let component_type = component.component_type();
        let module_ident = component_type.module_ident();

        let event_ident = if let Some(event_def) = self.events.get(component.field_ident()) {
            let path = event_def.event_type.as_given();
            quote!(#path)
        } else {
            let ident = to_ident("Event");
            quote!(#ident)
        };

        quote!(crate::components::#module_ident::#event_ident)
    }
}

impl Parse for ReactorDefinition {
    fn parse(input: ParseStream) -> Result<Self> {
        let content;
        // formerly `name`
        let reactor_type_ident: Ident = input.parse()?;

        // Outer and config type.
        braced!(content in input);
        let config: ItemType = content.parse()?;

        // Components.
        let component_content;
        let _: kw::components = content.parse()?;
        let _: Token!(:) = content.parse()?;
        braced!(component_content in content);

        let mut components = IndexMap::new();
        for cdef in component_content
            .parse_terminated::<ComponentDefinition, Token!(;)>(ComponentDefinition::parse)?
        {
            components.insert(cdef.name.clone(), cdef);
        }

        // Event (-overrides)
        let event_content;
        let _: kw::events = content.parse()?;
        let _: Token!(:) = content.parse()?;
        braced!(event_content in content);

        let mut events = IndexMap::new();
        for edef in
            event_content.parse_terminated::<EventDefinition, Token!(;)>(EventDefinition::parse)?
        {
            events.insert(edef.name.clone(), edef);
        }

        // Requests.
        let requests_content;
        let _: kw::requests = content.parse()?;
        let _: Token!(:) = content.parse()?;
        braced!(requests_content in content);

        let requests = requests_content
            .parse_terminated::<RequestDefinition, Token!(;)>(RequestDefinition::parse)?
            .into_iter()
            .collect();

        // Announcements.
        let announcements_content;
        let _: kw::announcements = content.parse()?;
        let _: Token!(:) = content.parse()?;
        braced!(announcements_content in content);
        let announcements = announcements_content
            .parse_terminated::<AnnouncementDefinition, Token!(;)>(AnnouncementDefinition::parse)?
            .into_iter()
            .collect();

        Ok(ReactorDefinition {
            reactor_type_ident,
            config_type: RustType::try_from(config.ty.as_ref().clone()).map_err(|err| {
                syn::parse::Error::new(
                    Span::call_site(), // FIXME: Can we get a better span here?
                    err,
                )
            })?,
            components,
            events,
            requests,
            announcements,
        })
    }
}

/// A definition of a component.
pub(crate) struct ComponentDefinition {
    /// The attribute-style name of the component, e.g. `net`.
    name: Ident,
    /// The components type.
    component_type: RustType,
    /// Arguments passed to the components `new` constructor when constructing.
    component_arguments: Vec<Expr>,
    /// Whether or not the component has actual effects when constructed.
    has_effects: bool,
}

impl ComponentDefinition {
    /// Returns the component construction arguments.
    pub(crate) fn component_arguments(&self) -> &[Expr] {
        self.component_arguments.as_slice()
    }

    /// Returns an ident identifying the component that is suitable for a struct field, e.g. `net`.
    pub(crate) fn field_ident(&self) -> &Ident {
        &self.name
    }

    /// Returns an ident identifying the component that is suitable for a variant, e.g. `Net`.
    pub fn variant_ident(&self) -> Ident {
        to_ident(&to_pascal_case(&self.field_ident().to_string()))
    }

    /// Returns the type of the component.
    pub(crate) fn component_type(&self) -> &RustType {
        &self.component_type
    }

    /// Returns the full path for a component by prefixing it with `crate::components::`, e.g.
    /// `crate::components::small_net::SmallNet<NodeId>`
    pub fn full_component_type(&self) -> TokenStream {
        let component_type = self.component_type();
        let module_ident = component_type.module_ident();
        let ty = component_type.ty();
        quote!(crate::components::#module_ident::#ty)
    }

    /// Returns the full path for a component's event e.g. `crate::components::small_net::Error`
    pub fn full_error_type(&self, reactor_event_type: TokenStream) -> TokenStream {
        let comp_type = self.full_component_type();
        quote!(<#comp_type as crate::components::Component<#reactor_event_type>>::ConstructionError)
    }

    /// Returns whether or not the component returns effects upon instantiation.
    pub fn has_effects(&self) -> bool {
        self.has_effects
    }
}

impl Debug for ComponentDefinition {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("ComponentDefinition")
            .field("name", &self.name.to_string())
            .field("component_type", &self.component_type)
            .field("component_arguments", &"TODO: fmtargs")
            .finish()
    }
}

impl Parse for ComponentDefinition {
    fn parse(input: ParseStream) -> Result<Self> {
        // Parse left hand side and type def.
        let name: Ident = input.parse()?;
        let _: Token!(=) = input.parse()?;

        let has_effects = if input.peek(Token!(@)) {
            let _: Token!(@) = input.parse()?;
            true
        } else {
            false
        };

        let ty: Path = input.parse()?;

        // Parse arguments
        let content;
        parenthesized!(content in input);

        let args: Punctuated<Expr, Token!(,)> = content.parse_terminated(Expr::parse)?;
        Ok(ComponentDefinition {
            name,
            component_type: RustType::new(ty),
            component_arguments: args.into_iter().collect(),
            has_effects,
        })
    }
}

/// An event-definition
///
/// Typically only used to override tricky event definitions.
#[derive(Debug)]
pub(crate) struct EventDefinition {
    /// Identifier of the components.
    pub name: Ident,
    /// Event type to use.
    pub event_type: RustType,
}

impl Parse for EventDefinition {
    fn parse(input: ParseStream) -> Result<Self> {
        // Parse left hand side and type def.
        let name: Ident = input.parse()?;
        let _: Token!(=) = input.parse()?;
        let ty: Path = input.parse()?;

        Ok(EventDefinition {
            name,
            event_type: RustType::new(ty),
        })
    }
}

#[derive(Debug)]
/// A definition of a request routing.
pub(crate) struct RequestDefinition {
    pub request_type: RustType,
    pub target: Target,
}

impl RequestDefinition {
    /// Returns an ident identifying the request that is suitable for a variant, e.g.
    /// `NetworkRequest`.
    pub fn variant_ident(&self) -> Ident {
        self.request_type.ident()
    }

    /// Returns the type of the request.
    pub(crate) fn request_type(&self) -> &RustType {
        &self.request_type
    }

    /// Returns the target of the request.
    pub(crate) fn target(&self) -> &Target {
        &self.target
    }

    /// Returns the full path for a request.
    pub fn full_request_type(&self) -> TokenStream {
        let request_type = self.request_type();
        let ty = request_type.ty();
        quote!(crate::effect::requests::#ty)
    }
}

impl Parse for RequestDefinition {
    fn parse(input: ParseStream) -> Result<Self> {
        let request_type = RustType::new(input.parse()?);
        let _: Token!(->) = input.parse()?;

        let target = input.parse()?;

        Ok(RequestDefinition {
            request_type,
            target,
        })
    }
}

#[derive(Debug)]
/// A definition of an announcement.
pub(crate) struct AnnouncementDefinition {
    pub announcement_type: RustType,
    pub targets: Vec<Target>,
}

impl AnnouncementDefinition {
    /// Returns the type of the announcement.
    pub(crate) fn announcement_type(&self) -> &RustType {
        &self.announcement_type
    }

    /// Returns the full path for an announcement.
    pub(crate) fn full_announcement_type(&self) -> TokenStream {
        let announcement_type = self.announcement_type();
        let ty = announcement_type.ty();
        quote!(crate::effect::announcements::#ty)
    }

    /// Returns an iterator over the targets of the announcement.
    pub(crate) fn targets(&self) -> impl Iterator<Item = &Target> {
        self.targets.iter()
    }

    /// Returns an ident identifying the announcement that is suitable for a variant, e.g.
    /// `NetworkAnnouncement`.
    pub fn variant_ident(&self) -> Ident {
        self.announcement_type.ident()
    }
}

impl Parse for AnnouncementDefinition {
    fn parse(input: ParseStream) -> Result<Self> {
        let announcement_type = RustType::new(input.parse()?);
        let _: Token!(->) = input.parse()?;

        let content;
        bracketed!(content in input);
        let targets = content
            .parse_terminated::<Target, Token!(,)>(Target::parse)?
            .into_iter()
            .collect();

        Ok(AnnouncementDefinition {
            announcement_type,
            targets,
        })
    }
}

/// A routing target.
pub(crate) enum Target {
    /// Discard whatever is being routed.
    Discard,
    /// Forward to destination.
    Dest(Ident),
}

impl Debug for Target {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Target::Discard => write!(f, "!"),
            Target::Dest(id) => write!(f, "{}", id.to_string()),
        }
    }
}

impl Parse for Target {
    fn parse(input: ParseStream) -> Result<Self> {
        if input.peek(Token!(!)) {
            let _: Token!(!) = input.parse()?;
            Ok(Target::Discard)
        } else {
            input.parse().map(Target::Dest)
        }
    }
}

/// Custom keywords.
///
/// This module groups custom keywords used by the parser.
mod kw {
    syn::custom_keyword!(components);
    syn::custom_keyword!(events);
    syn::custom_keyword!(requests);
    syn::custom_keyword!(announcements);
}