Files @ daf15df0f8ca
Branch filter:

Location: CSY/reowolf/src/protocol/mod.rs

daf15df0f8ca 23.8 KiB application/rls-services+xml Show Annotation Show as Raw Download as Raw
MH
scaffolding in place for scheduler/runtime
  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
mod arena;
pub(crate) mod eval;
pub(crate) mod input_source;
mod parser;
#[cfg(test)] mod tests;

pub(crate) mod ast;
pub(crate) mod ast_printer;

use std::sync::Mutex;

use crate::collections::{StringPool, StringRef};
use crate::common::*;
use crate::protocol::ast::*;
use crate::protocol::eval::*;
use crate::protocol::input_source::*;
use crate::protocol::parser::*;
use crate::protocol::type_table::*;

/// A protocol description module
pub struct Module {
    pub(crate) source: InputSource,
    pub(crate) root_id: RootId,
    pub(crate) name: Option<StringRef<'static>>,
}
/// Description of a protocol object, used to configure new connectors.
#[repr(C)]
pub struct ProtocolDescription {
    pub(crate) modules: Vec<Module>,
    pub(crate) heap: Heap,
    pub(crate) types: TypeTable,
    pub(crate) pool: Mutex<StringPool>,
}
#[derive(Debug, Clone)]
pub(crate) struct ComponentState {
    pub(crate) prompt: Prompt,
}

#[allow(dead_code)]
pub(crate) enum EvalContext<'a> {
    Nonsync(&'a mut NonsyncProtoContext<'a>),
    Sync(&'a mut SyncProtoContext<'a>),
    None,
}
//////////////////////////////////////////////

#[derive(Debug)]
pub enum ComponentCreationError {
    ModuleDoesntExist,
    DefinitionDoesntExist,
    DefinitionNotComponent,
    InvalidNumArguments,
    InvalidArgumentType(usize),
}

impl std::fmt::Debug for ProtocolDescription {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "(An opaque protocol description)")
    }
}
impl ProtocolDescription {
    // TODO: Allow for multi-file compilation
    pub fn parse(buffer: &[u8]) -> Result<Self, String> {
        // TODO: @fixme, keep code compilable, but needs support for multiple
        //  input files.
        let source = InputSource::new(String::new(), Vec::from(buffer));
        let mut parser = Parser::new();
        parser.feed(source).expect("failed to feed source");
        
        if let Err(err) = parser.parse() {
            println!("ERROR:\n{}", err);
            return Err(format!("{}", err))
        }

        debug_assert_eq!(parser.modules.len(), 1, "only supporting one module here for now");
        let modules: Vec<Module> = parser.modules.into_iter()
            .map(|module| Module{
                source: module.source,
                root_id: module.root_id,
                name: module.name.map(|(_, name)| name)
            })
            .collect();

        return Ok(ProtocolDescription {
            modules,
            heap: parser.heap,
            types: parser.type_table,
            pool: Mutex::new(parser.string_pool),
        });
    }

    #[deprecated]
    pub(crate) fn component_polarities(
        &self,
        module_name: &[u8],
        identifier: &[u8],
    ) -> Result<Vec<Polarity>, AddComponentError> {
        use AddComponentError::*;

        let module_root = self.lookup_module_root(module_name);
        if module_root.is_none() {
            return Err(AddComponentError::NoSuchModule);
        }
        let module_root = module_root.unwrap();

        let root = &self.heap[module_root];
        let def = root.get_definition_ident(&self.heap, identifier);
        if def.is_none() {
            return Err(NoSuchComponent);
        }

        let def = &self.heap[def.unwrap()];
        if !def.is_component() {
            return Err(NoSuchComponent);
        }

        for &param in def.parameters().iter() {
            let param = &self.heap[param];
            let first_element = &param.parser_type.elements[0];

            match first_element.variant {
                ParserTypeVariant::Input | ParserTypeVariant::Output => continue,
                _ => {
                    return Err(NonPortTypeParameters);
                }
            }
        }

        let mut result = Vec::new();
        for &param in def.parameters().iter() {
            let param = &self.heap[param];
            let first_element = &param.parser_type.elements[0];

            if first_element.variant == ParserTypeVariant::Input {
                result.push(Polarity::Getter)
            } else if first_element.variant == ParserTypeVariant::Output {
                result.push(Polarity::Putter)
            } else {
                unreachable!()
            }
        }
        Ok(result)
    }

    // expects port polarities to be correct
    #[deprecated]
    pub(crate) fn new_component(&self, module_name: &[u8], identifier: &[u8], ports: &[PortId]) -> ComponentState {
        let mut args = Vec::new();
        for (&x, y) in ports.iter().zip(self.component_polarities(module_name, identifier).unwrap()) {
            match y {
                Polarity::Getter => args.push(Value::Input(x)),
                Polarity::Putter => args.push(Value::Output(x)),
            }
        }

        let module_root = self.lookup_module_root(module_name).unwrap();
        let root = &self.heap[module_root];
        let def = root.get_definition_ident(&self.heap, identifier).unwrap();
        // TODO: Check for polymorph
        ComponentState { prompt: Prompt::new(&self.types, &self.heap, def, 0, ValueGroup::new_stack(args)) }
    }

    // TODO: Ofcourse, rename this at some point, perhaps even remove it in its
    //  entirety. Find some way to interface with the parameter's types.
    pub(crate) fn new_component_v2(
        &self, module_name: &[u8], identifier: &[u8], arguments: ValueGroup
    ) -> Result<ComponentState, ComponentCreationError> {
        // Find the module in which the definition can be found
        let module_root = self.lookup_module_root(module_name);
        if module_root.is_none() {
            return Err(ComponentCreationError::ModuleDoesntExist);
        }
        let module_root = module_root.unwrap();

        let root = &self.heap[module_root];
        let definition_id = root.get_definition_ident(&heap, identifier);
        if definition_id.is_none() {
            return Err(ComponentCreationError::DefinitionDoesntExist);
        }
        let definition_id = definition_id.unwrap();

        let definition = &self.heap[definition_id];
        if !definition.is_component() {
            return Err(ComponentCreationError::DefinitionNotComponent);
        }

        // Make sure that the types of the provided value group matches that of
        // the expected types.
        let definition = definition.as_component();
        if !definition.poly_vars.is_empty() {
            return Err(ComponentCreationError::DefinitionNotComponent);
        }

        // - check number of arguments
        let expr_data = self.types.get_procedure_expression_data(&definition_id, 0);
        if expr_data.arg_types.len() != arguments.values.len() {
            return Err(ComponentCreationError::InvalidNumArguments);
        }

        // - for each argument try to make sure the types match
        for arg_idx in 0..arguments.values.len() {
            let expected_type = &expr_data.arg_types[arg_idx];
            let provided_value = &arguments.values[arg_idx];
            if !self.verify_same_type(expected_type, 0, &arguments, provided_value) {
                return Err(ComponentCreationError::InvalidArgumentType(arg_idx));
            }
        }

        // By now we're sure that all of the arguments are correct. So create
        // the connector.
        return Ok(ComponentState{
            prompt: Prompt::new(&self.types, &self.heap, def, 0, arguments),
        });
    }

    fn lookup_module_root(&self, module_name: &[u8]) -> Option<RootId> {
        for module in self.modules.iter() {
            match &module.name {
                Some(name) => if name.as_bytes() == module_name {
                    return Some(module.root_id);
                },
                None => if module_name.is_empty() {
                    return Some(module.root_id);
                }
            }
        }

        return None;
    }

    fn verify_same_type(&self, expected: &ConcreteType, expected_idx: usize, arguments: &ValueGroup, argument: &Value) -> bool {
        use ConcreteTypePart as CTP;

        macro_rules! match_variant {
            ($value:expr, $variant:expr) => {
                if let $variant(_) = $value { true } else { false }
            };
        }

        match &expected.parts[expected_idx] {
            CTP::Void | CTP::Message | CTP::Slice | CTP::Function(_, _) | CTP::Component(_, _) => unreachable!(),
            CTP::Bool => match_variant!(argument, Value::Bool),
            CTP::UInt8 => match_variant!(argument, Value::UInt8),
            CTP::UInt16 => match_variant!(argument, Value::UInt16),
            CTP::UInt32 => match_variant!(argument, Value::UInt32),
            CTP::UInt64 => match_variant!(argument, Value::UInt64),
            CTP::SInt8 => match_variant!(argument, Value::SInt8),
            CTP::SInt16 => match_variant!(argument, Value::SInt16),
            CTP::SInt32 => match_variant!(argument, Value::SInt32),
            CTP::SInt64 => match_variant!(argument, Value::SInt64),
            CTP::Character => match_variant!(argument, Value::Char),
            CTP::String => {
                // Match outer string type and embedded character types
                if let Value::String(heap_pos) = argument {
                    for element in &arguments.regions[*heap_pos as usize] {
                        if let Value::Char(_) = element {} else {
                            return false;
                        }
                    }
                } else {
                    return false;
                }

                return true;
            },
            CTP::Array => {
                if let Value::Array(heap_pos) = argument {
                    let heap_pos = *heap_pos;
                    for element in &arguments.regions[heap_pos as usize] {
                        if !self.verify_same_type(expected, expected_idx + 1, arguments, element) {
                            return false;
                        }
                    }
                    return true;
                } else {
                    return false;
                }
            },
            CTP::Input => match_variant!(argument, Value::Input),
            CTP::Output => match_variant!(argument, Value::Output),
            CTP::Instance(_definition_id, _num_embedded) => {
                todo!("implement full type checking on user-supplied arguments");
                return false;
            },
        }
    }
}

// TODO: @temp Should just become a concrete thing that is passed in
pub trait RunContext {
    fn did_put(&mut self, port: PortId) -> bool;
    fn get(&mut self, port: PortId) -> Option<ValueGroup>; // None if still waiting on message
    fn fires(&mut self, port: PortId) -> Option<Value>; // None if not yet branched
    fn get_channel(&mut self) -> Option<(Value, Value)>; // None if not yet prepared
}

#[derive(Debug)]
pub enum RunResult {
    // Can only occur outside sync blocks
    ComponentTerminated, // component has exited its procedure
    ComponentAtSyncStart,
    NewComponent(DefinitionId, i32, ValueGroup), // should also be possible inside sync
    NewChannel, // should also be possible inside sync
    // Can only occur inside sync blocks
    BranchInconsistent, // branch has inconsistent behaviour
    BranchMissingPortState(PortId), // branch doesn't know about port firing
    BranchMissingPortValue(PortId), // branch hasn't received message on input port yet
    BranchAtSyncEnd,
    BranchPut(PortId, ValueGroup),
}

impl ComponentState {
    pub(crate) fn run(&mut self, ctx: &mut impl RunContext, pd: &ProtocolDescription) -> RunResult {
        use EvalContinuation as EC;
        use RunResult as RR;

        loop {
            let step_result = self.prompt.step(&pd.types, &pd.heap, &pd.modules, ctx);
            match step_result {
                Err(reason) => {
                    // TODO: @temp
                    println!("Evaluation error:\n{}", reason);
                    todo!("proper error handling/bubbling up");
                },
                Ok(continuation) => match continuation {
                    // TODO: Probably want to remove this translation
                    EC::Stepping => continue,
                    EC::Inconsistent => return RR::BranchInconsistent,
                    EC::Terminal => return RR::ComponentTerminated,
                    EC::SyncBlockStart => return RR::ComponentAtSyncStart,
                    EC::SyncBlockEnd => return RR::BranchAtSyncEnd,
                    EC::NewComponent(definition_id, monomorph_idx, args) =>
                        return RR::NewComponent(definition_id, monomorph_idx, args),
                    EC::NewChannel =>
                        return RR::NewChannel,
                    EC::BlockFires(port_id) => return RR::BranchMissingPortState(port_id),
                    EC::BlockGet(port_id) => return RR::BranchMissingPortValue(port_id),
                    EC::Put(port_id, value) => {
                        let value_group = ValueGroup::from_store(&self.prompt.store, &[value]);
                        return RR::BranchPut(port_id, value_group);
                    },
                }
            }
        }
    }
}

// TODO: @remove the old stuff
impl ComponentState {
    pub(crate) fn nonsync_run<'a: 'b, 'b>(
        &'a mut self,
        context: &'b mut NonsyncProtoContext<'b>,
        pd: &'a ProtocolDescription,
    ) -> NonsyncBlocker {
        let mut context = EvalContext::Nonsync(context);
        loop {
            let result = self.prompt.step(&pd.types, &pd.heap, &pd.modules, &mut context);
            match result {
                Err(err) => {
                    println!("Evaluation error:\n{}", err);
                    panic!("proper error handling when component fails");
                },
                Ok(cont) => match cont {
                    EvalContinuation::Stepping => continue,
                    EvalContinuation::Inconsistent => return NonsyncBlocker::Inconsistent,
                    EvalContinuation::Terminal => return NonsyncBlocker::ComponentExit,
                    EvalContinuation::SyncBlockStart => return NonsyncBlocker::SyncBlockStart,
                    // Not possible to end sync block if never entered one
                    EvalContinuation::SyncBlockEnd => unreachable!(),
                    EvalContinuation::NewComponent(definition_id, monomorph_idx, args) => {
                        // Look up definition (TODO for now, assume it is a definition)
                        let mut moved_ports = HashSet::new();
                        for arg in args.values.iter() {
                            match arg {
                                Value::Output(port) => {
                                    moved_ports.insert(*port);
                                }
                                Value::Input(port) => {
                                    moved_ports.insert(*port);
                                }
                                _ => {}
                            }
                        }
                        for region in args.regions.iter() {
                            for arg in region {
                                match arg {
                                    Value::Output(port) => { moved_ports.insert(*port); },
                                    Value::Input(port) => { moved_ports.insert(*port); },
                                    _ => {},
                                }
                            }
                        }
                        let init_state = ComponentState { prompt: Prompt::new(&pd.types, &pd.heap, definition_id, monomorph_idx, args) };
                        context.new_component(moved_ports, init_state);
                        // Continue stepping
                        continue;
                    },
                    EvalContinuation::NewChannel => {
                        // Because of the way we emulate the old context for now, we can safely
                        // assume that this will never happen. The old context thingamajig always
                        // creates a channel, it never bubbles a "need to create a channel" message
                        // to the runtime
                        unreachable!();
                    },
                    // Outside synchronous blocks, no fires/get/put happens
                    EvalContinuation::BlockFires(_) => unreachable!(),
                    EvalContinuation::BlockGet(_) => unreachable!(),
                    EvalContinuation::Put(_, _) => unreachable!(),
                },
            }
        }
    }

    pub(crate) fn sync_run<'a: 'b, 'b>(
        &'a mut self,
        context: &'b mut SyncProtoContext<'b>,
        pd: &'a ProtocolDescription,
    ) -> SyncBlocker {
        let mut context = EvalContext::Sync(context);
        loop {
            let result = self.prompt.step(&pd.types, &pd.heap, &pd.modules, &mut context);
            match result {
                Err(err) => {
                    println!("Evaluation error:\n{}", err);
                    panic!("proper error handling when component fails");
                },
                Ok(cont) => match cont {
                    EvalContinuation::Stepping => continue,
                    EvalContinuation::Inconsistent => return SyncBlocker::Inconsistent,
                    // First need to exit synchronous block before definition may end
                    EvalContinuation::Terminal => unreachable!(),
                    // No nested synchronous blocks
                    EvalContinuation::SyncBlockStart => unreachable!(),
                    EvalContinuation::SyncBlockEnd => return SyncBlocker::SyncBlockEnd,
                    // Not possible to create component in sync block
                    EvalContinuation::NewComponent(_, _, _) => unreachable!(),
                    EvalContinuation::NewChannel => unreachable!(),
                    EvalContinuation::BlockFires(port) => {
                        return SyncBlocker::CouldntCheckFiring(port);
                    },
                    EvalContinuation::BlockGet(port) => {
                        return SyncBlocker::CouldntReadMsg(port);
                    },
                    EvalContinuation::Put(port, message) => {
                        let payload;
                        match message {
                            Value::Null => {
                                return SyncBlocker::Inconsistent;
                            },
                            Value::Message(heap_pos) => {
                                // Create a copy of the payload
                                let values = &self.prompt.store.heap_regions[heap_pos as usize].values;
                                let mut bytes = Vec::with_capacity(values.len());
                                for value in values {
                                    bytes.push(value.as_uint8());
                                }
                                payload = Payload(Arc::new(bytes));
                            }
                            _ => unreachable!(),
                        }
                        return SyncBlocker::PutMsg(port, payload);
                    }
                },
            }
        }
    }
}

impl RunContext for EvalContext<'_> {
    fn did_put(&mut self, port: PortId) -> bool {
        match self {
            EvalContext::None => unreachable!(),
            EvalContext::Nonsync(_) => unreachable!(),
            EvalContext::Sync(ctx) => {
                ctx.did_put_or_get(port)
            }
        }
    }

    fn get(&mut self, port: PortId) -> Option<ValueGroup> {
        match self {
            EvalContext::None => unreachable!(),
            EvalContext::Nonsync(_) => unreachable!(),
            EvalContext::Sync(ctx) => {
                let payload = ctx.read_msg(port);
                if payload.is_none() {
                    return None;
                }

                let payload = payload.unwrap();
                let mut transformed = Vec::with_capacity(payload.len());
                for byte in payload.0.iter() {
                    transformed.push(Value::UInt8(*byte));
                }

                let value_group = ValueGroup{
                    values: vec![Value::Message(0)],
                    regions: vec![transformed],
                };

                return Some(value_group);
            }
        }
    }

    fn fires(&mut self, port: PortId) -> Option<Value> {
        match self {
            EvalContext::None => unreachable!(),
            EvalContext::Nonsync(_) => unreachable!(),
            EvalContext::Sync(context) => {
                match context.is_firing(port) {
                    Some(did_fire) => Some(Value::Bool(did_fire)),
                    None => None,
                }
            }
        }
    }

    fn get_channel(&mut self) -> Option<(Value, Value)> {
        match self {
            EvalContext::None => unreachable!(),
            EvalContext::Nonsync(context) => {
                let [from, to] = context.new_port_pair();
                let from = Value::Output(from);
                let to = Value::Input(to);
                return Some((from, to));
            },
            EvalContext::Sync(_) => unreachable!(),
        }
    }
}

// TODO: @remove once old runtime has disappeared
impl EvalContext<'_> {
    // fn random(&mut self) -> LongValue {
    //     match self {
    //         // EvalContext::None => unreachable!(),
    //         EvalContext::Nonsync(_context) => todo!(),
    //         EvalContext::Sync(_) => unreachable!(),
    //     }
    // }
    fn new_component(&mut self, moved_ports: HashSet<PortId>, init_state: ComponentState) -> () {
        match self {
            EvalContext::None => unreachable!(),
            EvalContext::Nonsync(context) => {
                context.new_component(moved_ports, init_state)
            }
            EvalContext::Sync(_) => unreachable!(),
        }
    }
    fn new_channel(&mut self) -> [Value; 2] {
        match self {
            EvalContext::None => unreachable!(),
            EvalContext::Nonsync(context) => {
                let [from, to] = context.new_port_pair();
                let from = Value::Output(from);
                let to = Value::Input(to);
                return [from, to];
            }
            EvalContext::Sync(_) => unreachable!(),
        }
    }
    fn fires(&mut self, port: Value) -> Option<Value> {
        match self {
            EvalContext::None => unreachable!(),
            EvalContext::Nonsync(_) => unreachable!(),
            EvalContext::Sync(context) => match port {
                Value::Output(port) => context.is_firing(port).map(Value::Bool),
                Value::Input(port) => context.is_firing(port).map(Value::Bool),
                _ => unreachable!(),
            },
        }
    }
    fn get(&mut self, port: Value, store: &mut Store) -> Option<Value> {
        match self {
            EvalContext::None => unreachable!(),
            EvalContext::Nonsync(_) => unreachable!(),
            EvalContext::Sync(context) => match port {
                Value::Input(port) => {
                    let payload = context.read_msg(port);
                    if payload.is_none() { return None; }

                    let heap_pos = store.alloc_heap();
                    let heap_pos_usize = heap_pos as usize;
                    let payload = payload.unwrap();
                    store.heap_regions[heap_pos_usize].values.reserve(payload.0.len());
                    for value in payload.0.iter() {
                        store.heap_regions[heap_pos_usize].values.push(Value::UInt8(*value));
                    }

                    return Some(Value::Message(heap_pos));
                }
                _ => unreachable!(),
            },
        }
    }
    fn did_put(&mut self, port: Value) -> bool {
        match self {
            EvalContext::None => unreachable!("did_put in None context"),
            EvalContext::Nonsync(_) => unreachable!("did_put in nonsync context"),
            EvalContext::Sync(context) => match port {
                Value::Output(port) => {
                    context.did_put_or_get(port)
                },
                _ => unreachable!("did_put on non-output port value")
            }
        }
    }
}