apis 0.5.13

Reactive, session-oriented, asynchronous process-calculus framework
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//
//  def_session!
//
/// Macro to define all parts of a session.
///
/// Defines an instance of `session:Context` with the given name and the
/// following associated types:
///
/// - `type MID = MessageId`
/// - `type CID = ChannelId`
/// - `type PID = ProcessId`
/// - `type GMSG = GlobalMessage`
/// - `type GPROC = GlobalProcess`
/// - `type GPRES = GlobalPresult`
///
/// Process and message types with the given names and specifications are
/// defined with implementations of relevant traits.
///
/// Process `handle_message` and `update` behavior is provided as a block of
/// code which is to be run inside of the actual trait methods where `self` is
/// bound to the provided identifier in both cases, and the `message_in`
/// (global message) argument of `handle_message` is bound to the provided
/// identifier.

/// # Examples
///
/// From `examples/simplex.rs`-- defines two processes (`Chargen` and `Upcase`)
/// connected by a channel sending `Charstreammessage`s:
///
/// ```
/// extern crate apis;
///
/// use apis::{channel, message, process, session};
///
/// apis::def_session! {
///   context Mycontext {
///     PROCESSES where
///       let process    = self,
///       let message_in = message_in
///     [
///       process Chargen (update_count : u64) {
///         kind { process::Kind::Isochronous {
///           tick_ms: 20,
///           ticks_per_update: 1 } }
///         sourcepoints [Charstream]
///         endpoints    []
///         handle_message { apis::process::ControlFlow::Break }
///         update         { apis::process::ControlFlow::Break }
///       }
///       process Upcase (history : String) {
///         kind { process::Kind::asynchronous_default() }
///         sourcepoints []
///         endpoints    [Charstream]
///         handle_message { apis::process::ControlFlow::Break }
///         update         { apis::process::ControlFlow::Break }
///       }
///     ]
///     CHANNELS  [
///       channel Charstream <Charstreammessage> (Simplex) {
///         producers [Chargen]
///         consumers [Upcase]
///       }
///     ]
///     MESSAGES [
///       message Charstreammessage {
///         Achar (char),
///         Quit
///       }
///     ]
///   }
/// }
///
/// # fn main() {}
/// ```
///
/// The `handle_message` and `update` definitions have been ommitted for
/// brevity, but in general any block of code can be substituted that
/// references the `self` and `message_in` bindings.

#[macro_export]
macro_rules! def_session {

  ( context $context:ident {
      PROCESSES where
        let $process_self:ident = self,
        let $message_in:ident   = message_in
      [
        $(process $process:ident (
          $($field_name:ident : $field_type:ty $(= $field_default:expr)*),*
        ) $(-> ($presult_type:ty $(= $presult_default:expr)*))* {
          kind { $process_kind:expr }
          sourcepoints [ $($sourcepoint:ident),* ]
          endpoints    [ $($endpoint:ident),* ]
          $(initialize   $initialize:block)*
          $(terminate    $terminate:block)*
          handle_message $handle_message:block
          update         $update:block
        })+
      ]
      CHANNELS [
        $(channel $channel:ident <$local_type:ident> ($kind:ident) {
          producers [ $($producer:ident),+ ]
          consumers [ $($consumer:ident),+ ]
        })*
      ]
      MESSAGES [
        $(message $message_type:ident $message_variants:tt)*
      ]
      $(main: $main_process:ident)*
    }

  ) => {

    ////////////////////////////////////////////////////////////////////////////
    //  structs
    ////////////////////////////////////////////////////////////////////////////

    //
    //  session context
    //
    #[derive(Clone, Debug, Eq, PartialEq)]
    pub struct $context;

    //
    //  processes
    //
    $(
    pub struct $process {
      inner  : $crate::process::Inner <$context>,
      result : ($($presult_type)*),
      $(
      pub $field_name : $field_type
      ),*
    }
    )+

    //
    //  messages
    //
    $(
    #[derive(Debug, $crate::strum::Display)]
    pub enum $message_type $message_variants
    )*

    ////////////////////////////////////////////////////////////////////////////
    //  enums
    ////////////////////////////////////////////////////////////////////////////

    //
    //  ids
    //
    #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd,
      $crate::strum::EnumCount, $crate::strum::EnumIter,
      $crate::strum::FromRepr)]
    #[repr(u16)]
    pub enum ProcessId {
      $($process),+
    }
    $crate::def_session!(@channel_id { $($channel),* });
    $crate::def_session!(@message_id { $($message_type),* });

    impl TryFrom <$crate::process::IdReprType> for ProcessId {
      type Error = $crate::process::IdReprType;
      fn try_from (id : $crate::process::IdReprType)
        -> Result <Self, Self::Error>
      {
        Self::from_repr (id).ok_or (id)
      }
    }

    impl From <ProcessId> for usize {
      fn from (pid : ProcessId) -> usize {
        pid as usize
      }
    }

    impl From <ChannelId> for usize {
      fn from (cid : ChannelId) -> usize {
        cid as usize
      }
    }

    impl From <MessageId> for usize {
      fn from (mid : MessageId) -> usize {
        mid as usize
      }
    }

    //
    //  global process type
    //
    pub enum GlobalProcess {
      $(
      $process ($process)
      ),+
    }

    //
    //  global process result type
    //
    #[derive(Debug)]
    pub enum GlobalPresult {
      $(
      $process (($($presult_type)*))
      ),+
    }

    //
    //  global message type
    //
    #[derive(Debug)]
    pub enum GlobalMessage {
      $(
      $message_type ($message_type)
      ),*
    }

    ////////////////////////////////////////////////////////////////////////////
    //  impls
    ////////////////////////////////////////////////////////////////////////////

    impl $crate::session::Context for $context {
      type MID   = MessageId;
      type CID   = ChannelId;
      type PID   = ProcessId;
      type GMSG  = GlobalMessage;
      type GPROC = GlobalProcess;
      type GPRES = GlobalPresult;

      fn name() -> &'static str {
        stringify!($context)
      }

      fn maybe_main() -> Option <Self::PID> {
        $(use self::ProcessId::$main_process;)*
        $crate::def_session!(@expr_option $($main_process)*)
      }

      fn process_field_names() -> Vec <Vec <&'static str>> {
        let mut v = Vec::new();
        $({
          let mut _w = Vec::new();
          $(_w.push (stringify!($field_name));)*
          v.push (_w);
        })+
        v
      }
      fn process_field_types() -> Vec <Vec <&'static str>> {
        let mut v = Vec::new();
        $({
          let mut _w = Vec::new();
          $(_w.push (stringify!($field_type));)*
          v.push (_w);
        })+
        v
      }
      fn process_field_defaults() -> Vec <Vec <&'static str>> {
        let mut v = Vec::new();
        $({
          let mut _w = Vec::new();
          $(
          _w.push ({
            let default_expr = stringify!($($field_default)*);
            if !default_expr.is_empty() {
              default_expr
            } else {
              concat!(stringify!($field_type), "::default()")
            }
          });
          )*
          v.push (_w);
        })+
        v
      }
      fn process_result_types() -> Vec <&'static str> {
        vec![$(stringify!($($presult_type)*)),+]
      }
      fn process_result_defaults() -> Vec <&'static str> {
        let mut v = Vec::new();
        $(
        v.push ({
          let default_expr = stringify!($($($presult_default)*)*);
          if !default_expr.is_empty() {
            default_expr
          } else {
            concat!(stringify!($($presult_type)*), "::default()")
          }
        });
        )+
        v
      }
      fn channel_local_types() -> Vec <&'static str> {
        vec![$(stringify!($local_type)),*]
      }
    }

    //
    //  processes
    //
    $(
    impl $crate::Process <$context, ($($presult_type)*)> for $process {
      fn new (inner : $crate::process::Inner <$context>) -> Self {
        $process {
          inner,
          result:        $crate::def_session!(@expr_default $($($presult_default)*)*),
          $($field_name: $crate::def_session!(@expr_default $($field_default)*)),*
        }
      }
      fn extract_result (session_results : &mut $crate::vec_map::VecMap <GlobalPresult>)
        -> Result <($($presult_type)*), String>
      {
        let pid = ProcessId::$process as usize;
        let global_presult = session_results.remove (pid)
          .ok_or ("process result not present".to_string())?;
        #[allow(unreachable_patterns)]
        match global_presult {
          GlobalPresult::$process (presult) => Ok (presult),
          _ => Err ("global process result does not match process".to_string())
        }
      }
      fn inner_ref (&self) -> &$crate::process::Inner <$context> {
        &self.inner
      }
      fn inner_mut (&mut self) -> &mut $crate::process::Inner <$context> {
        &mut self.inner
      }
      fn result_ref (&self) -> &($($presult_type)*) {
        &self.result
      }
      fn result_mut (&mut self) -> &mut ($($presult_type)*) {
        &mut self.result
      }
      fn global_result (&mut self) -> GlobalPresult {
        GlobalPresult::$process (self.result.clone())
      }
      $(
      fn initialize (&mut self) {
        #[allow(unused_variables)]
        let $process_self = self;
        $initialize
      }
      )*
      $(
      fn terminate (&mut self) {
        #[allow(unused_variables)]
        let $process_self = self;
        $terminate
      }
      )*
      fn handle_message (&mut self, message : GlobalMessage)
        -> $crate::process::ControlFlow
      {
        #[allow(unused_variables)]
        let $process_self = self;
        #[allow(unused_variables)]
        let $message_in   = message;
        $handle_message
      }
      fn update (&mut self) -> $crate::process::ControlFlow {
        #[allow(unused_variables)]
        let $process_self = self;
        $update
      }
    }
    impl std::convert::TryFrom <GlobalProcess> for $process {
      type Error = String;
      fn try_from (global_process : GlobalProcess) -> Result <Self, Self::Error> {
        #[allow(unreachable_patterns)]
        match global_process {
          GlobalProcess::$process (process) => Ok (process),
          _ => Err (format!("not a {} process", stringify!($process)))
        }
      }
    }
    impl From <$process> for GlobalProcess {
      fn from (process : $process) -> Self {
        GlobalProcess::$process (process)
      }
    }

    impl $crate::process::Presult <$context, $process> for ($($presult_type)*) { }
    )+

    //
    //  global process
    //
    impl $crate::process::Global <$context> for GlobalProcess {
      fn id (&self) -> ProcessId {
        match *self {
          $(GlobalProcess::$process (..) => ProcessId::$process),+
        }
      }
      fn run (&mut self) {
        use $crate::Process;
        match *self {
          $(GlobalProcess::$process (ref mut process) => process.run()),+
        }
      }
    }

    //
    //  global presult
    //
    impl $crate::process::presult::Global <$context> for GlobalPresult { }

    //
    //  process id
    //
    impl $crate::process::Id <$context> for ProcessId {
      fn def (&self) -> $crate::process::Def <$context> {
        match *self {
          $(
          ProcessId::$process => $crate::process::Def::define (
            self.clone(),
            $process_kind,
            vec![$(ChannelId::$sourcepoint),*],
            vec![$(ChannelId::$endpoint),*]
          ).unwrap()
          ),+
        }
      }

      fn spawn (inner : $crate::process::Inner <$context>)
        -> std::thread::JoinHandle <Option <()>>
      {
        use $crate::Process;
        match *inner.as_ref().def.id() {
          $(ProcessId::$process => {
            std::thread::Builder::new()
              .name (stringify!($process).to_string())
              .spawn (||{
                let process = $process::new (inner);
                process.run_continue()
              }).unwrap()
          }),+
        }
      }

      fn gproc (inner : $crate::process::Inner <$context>) -> GlobalProcess {
        use $crate::Process;
        match *inner.as_ref().def.id() {
          $(ProcessId::$process =>
            GlobalProcess::$process ($process::new (inner))
          ),+
        }
      }
    }

    //
    //  channel id
    //
    impl $crate::channel::Id <$context> for ChannelId {
      fn def (&self) -> $crate::channel::Def <$context> {
        #[allow(unreachable_patterns)]
        match *self {
          $(
          ChannelId::$channel => {
            $crate::channel::Def::define (
              self.clone(),
              $crate::channel::Kind::$kind,
              vec![$(ProcessId::$producer),+],
              vec![$(ProcessId::$consumer),+]
            ).unwrap()
          }
          )*
          _ => unreachable!("no defs for nullary channel ids")
        }
      }

      fn message_type_id (&self) -> MessageId {
        #[allow(unreachable_patterns)]
        match *self {
          $(ChannelId::$channel => MessageId::$local_type,)*
          _ => unreachable!("no message type for nullary channel ids")
        }
      }

      fn create (def : $crate::channel::Def <$context>)
        -> $crate::Channel <$context>
      {
        #[allow(unreachable_patterns)]
        match *def.id() {
          $(ChannelId::$channel => def.to_channel::<$local_type>(),)*
          _ => unreachable!("can't create channel for nullary channel id")
        }
      }
    }

    //
    //  global messages
    //
    impl $crate::message::Id for MessageId {}
    impl $crate::message::Global <$context> for GlobalMessage {
      fn id (&self) -> MessageId {
        #[allow(unreachable_patterns)]
        #[allow(clippy::uninhabited_references)]
        match *self {
          $(GlobalMessage::$message_type (..) => MessageId::$message_type),*
        }
      }
      /// Get the message name of the inner message type
      fn inner_name (&self) -> String {
        use $crate::message::Message;
        #[allow(clippy::uninhabited_references)]
        match *self {
          $(GlobalMessage::$message_type (ref msg) => msg.name()),*
        }
      }
    }

    //
    //  local messages
    //
    $(
    impl $crate::Message <$context> for $message_type {
      /// Name of message variant
      fn name (&self) -> String {
        self.to_string()
      }
    }
    impl std::convert::TryFrom <GlobalMessage> for $message_type {
      type Error = String;
      fn try_from (global_message : GlobalMessage) -> Result <Self, Self::Error> {
        #[allow(unreachable_patterns)]
        match global_message {
          GlobalMessage::$message_type (local_message) => Ok (local_message),
          _ => Err (format!("not a {} message", stringify!($message_type)))
        }
      }
    }
    impl From <$message_type> for GlobalMessage {
      fn from (local_message : $message_type) -> Self {
        GlobalMessage::$message_type (local_message)
      }
    }
    )*

  };
  // NOTE: need to special case empty enums because they don't allow repr
  // attriute
  (@channel_id { }) => {
    #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd,
      $crate::strum::EnumIter, $crate::strum::FromRepr)]
    pub enum ChannelId { }
    impl TryFrom <$crate::channel::IdReprType> for ChannelId {
      type Error = $crate::channel::IdReprType;
      fn try_from (id : $crate::channel::IdReprType)
        -> Result <Self, Self::Error>
      {
        Err (id)
      }
    }
  };
  (@channel_id { $($channel:ident),+ }) => {
    #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd,
      $crate::strum::EnumIter, $crate::strum::FromRepr)]
    #[repr(u16)]
    pub enum ChannelId {
      $($channel),+
    }
    impl TryFrom <$crate::channel::IdReprType> for ChannelId {
      type Error = $crate::channel::IdReprType;
      fn try_from (id : $crate::channel::IdReprType)
        -> Result <Self, Self::Error>
      {
        Self::from_repr (id).ok_or (id)
      }
    }
  };
  (@message_id { }) => {
    #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd,
      $crate::strum::EnumIter, $crate::strum::FromRepr)]
    pub enum MessageId { }
    impl TryFrom <$crate::message::IdReprType> for MessageId {
      type Error = $crate::message::IdReprType;
      fn try_from (id : $crate::message::IdReprType)
        -> Result <Self, Self::Error>
      {
        Err (id)
      }
    }
  };
  (@message_id { $($message_type:ident),+ }) => {
    #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd,
      $crate::strum::EnumIter, $crate::strum::FromRepr)]
    #[repr(u16)]
    pub enum MessageId {
      $($message_type),+
    }
    impl TryFrom <$crate::message::IdReprType> for MessageId {
      type Error = $crate::message::IdReprType;
      fn try_from (id : $crate::message::IdReprType)
        -> Result <Self, Self::Error>
      {
        Self::from_repr (id).ok_or (id)
      }
    }
  };

  //
  //  @expr_option: Some (expr)
  //
  ( @expr_option $expr:expr ) => { Some($expr) };

  //
  //  @expr_option: None
  //
  ( @expr_option ) => { None };

  //
  //  @expr_default: override default
  //
  ( @expr_default $default:expr ) => { $default };

  //
  //  @expr_default: use default
  //
  ( @expr_default ) => { Default::default() };

} // end def_session!