grabapl 0.0.4

A library for graph-based programming languages, with pluggable type systems and a focus on visible intermediate states.
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! A 'canonical' example semantics implementation. Mostly used for testing purposes.
//!
//! Defined here for easy reusability elsewhere without running into cyclic crate dependency issues.

use crate::operation::ConcreteData;
use crate::operation::query::ConcreteQueryOutput;
use crate::operation::signature::parameter::{AbstractOperationOutput, OperationOutput};
use crate::prelude::*;
use crate::semantics::*;
use derive_more::From;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::ops::Deref;

pub struct ExampleSemantics;

pub struct NodeMatcher;
impl AbstractMatcher for NodeMatcher {
    type Abstract = NodeType;

    fn matches(argument: &Self::Abstract, parameter: &Self::Abstract) -> bool {
        if argument == &NodeType::Separate || parameter == &NodeType::Separate {
            // if either is Separate, they can only match themselves.
            return argument == parameter;
        }
        match (argument, parameter) {
            (_, NodeType::Object) => true,
            _ => argument == parameter,
        }
    }
}

pub struct EdgeMatcher;
impl AbstractMatcher for EdgeMatcher {
    type Abstract = EdgeType;

    fn matches(argument: &Self::Abstract, parameter: &Self::Abstract) -> bool {
        match (argument, parameter) {
            (_, EdgeType::Wildcard) => true,
            (EdgeType::Exact(a), EdgeType::Exact(b)) => a == b,
            _ => false,
        }
    }
}

pub struct NodeJoiner;
impl AbstractJoin for NodeJoiner {
    type Abstract = NodeType;

    fn join(a: &Self::Abstract, b: &Self::Abstract) -> Option<Self::Abstract> {
        if a == b {
            Some(a.clone())
        } else if a != &NodeType::Separate && b != &NodeType::Separate {
            Some(NodeType::Object)
        } else {
            // Separate have no join.
            None
        }
    }
}

pub struct EdgeJoiner;
impl AbstractJoin for EdgeJoiner {
    type Abstract = EdgeType;

    fn join(a: &Self::Abstract, b: &Self::Abstract) -> Option<Self::Abstract> {
        match (a, b) {
            (EdgeType::Exact(a), EdgeType::Exact(b)) if a == b => Some(EdgeType::Exact(a.clone())),
            _ => Some(EdgeType::Wildcard),
        }
    }
}

pub struct NodeConcreteToAbstract;
impl ConcreteToAbstract for NodeConcreteToAbstract {
    type Concrete = NodeValue;
    type Abstract = NodeType;

    fn concrete_to_abstract(c: &Self::Concrete) -> Self::Abstract {
        match c {
            NodeValue::String(_) => NodeType::String,
            NodeValue::Integer(_) => NodeType::Integer,
        }
    }
}

pub struct EdgeConcreteToAbstract;
impl ConcreteToAbstract for EdgeConcreteToAbstract {
    type Concrete = String;
    type Abstract = EdgeType;

    fn concrete_to_abstract(c: &Self::Concrete) -> Self::Abstract {
        EdgeType::Exact(c.clone())
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum NodeType {
    String,
    Integer,
    /// Top type.
    #[default]
    Object,
    /// Not joinable with any of the other.
    Separate,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum NodeValue {
    String(String),
    Integer(i32),
}

impl NodeValue {
    pub fn must_string(&self) -> &str {
        match self {
            NodeValue::String(s) => s,
            NodeValue::Integer(_) => {
                panic!("type unsoundness: expected a string node value, found integer")
            }
        }
    }

    pub fn must_integer(&self) -> i32 {
        match self {
            NodeValue::String(_) => {
                panic!("type unsoundness: expected an integer node value, found string")
            }
            NodeValue::Integer(i) => *i,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum EdgeType {
    Wildcard,
    Exact(String),
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ExampleOperation {
    NoOp,
    SetTo {
        op_typ: NodeType,
        target_typ: NodeType,
        value: NodeValue,
    },
    SetEdgeTo {
        node_typ: NodeType,
        param_typ: EdgeType,
        target_typ: EdgeType,
        value: String,
    },
    AddEdge {
        node_typ: NodeType,
        // TODO: remove. unused.
        param_typ: EdgeType,
        target_typ: EdgeType,
        value: String,
    },
    AddNode {
        node_type: NodeType,
        value: NodeValue,
    },
    CopyValueFromTo,
    SwapValues,
    DeleteNode,
    DeleteEdge,
    AddInteger(i32),
    AModBToC,
}

impl BuiltinOperation for ExampleOperation {
    type S = ExampleSemantics;

    fn parameter(&self) -> OperationParameter<Self::S> {
        let mut param_builder = OperationParameterBuilder::new();
        match self {
            ExampleOperation::NoOp => {
                param_builder
                    .expect_explicit_input_node("input", NodeType::Object)
                    .unwrap();
            }
            ExampleOperation::SetTo {
                op_typ,
                target_typ,
                value,
            } => {
                param_builder
                    .expect_explicit_input_node("target", *op_typ)
                    .unwrap();
            }
            ExampleOperation::SetEdgeTo {
                node_typ,
                param_typ: op_typ,
                target_typ,
                value,
            } => {
                param_builder
                    .expect_explicit_input_node("src", *node_typ)
                    .unwrap();
                param_builder
                    .expect_explicit_input_node("dst", *node_typ)
                    .unwrap();
                param_builder
                    .expect_edge(
                        SubstMarker::from("src"),
                        SubstMarker::from("dst"),
                        op_typ.clone(),
                    )
                    .unwrap();
            }
            ExampleOperation::AddEdge {
                node_typ,
                param_typ: op_typ,
                target_typ,
                value,
            } => {
                param_builder
                    .expect_explicit_input_node("src", *node_typ)
                    .unwrap();
                param_builder
                    .expect_explicit_input_node("dst", *node_typ)
                    .unwrap();
            }
            ExampleOperation::AddNode { node_type, value } => {}
            ExampleOperation::CopyValueFromTo => {
                param_builder
                    .expect_explicit_input_node("source", NodeType::Object)
                    .unwrap();
                param_builder
                    .expect_explicit_input_node("destination", NodeType::Object)
                    .unwrap();
            }
            ExampleOperation::SwapValues => {
                param_builder
                    .expect_explicit_input_node("source", NodeType::Object)
                    .unwrap();
                param_builder
                    .expect_explicit_input_node("destination", NodeType::Object)
                    .unwrap();
            }
            ExampleOperation::DeleteNode => {
                param_builder
                    .expect_explicit_input_node("target", NodeType::Object)
                    .unwrap();
            }
            ExampleOperation::DeleteEdge => {
                param_builder
                    .expect_explicit_input_node("src", NodeType::Object)
                    .unwrap();
                param_builder
                    .expect_explicit_input_node("dst", NodeType::Object)
                    .unwrap();
                param_builder
                    .expect_edge(
                        SubstMarker::from("src"),
                        SubstMarker::from("dst"),
                        EdgeType::Wildcard,
                    )
                    .unwrap();
            }
            ExampleOperation::AddInteger(i) => {
                param_builder
                    .expect_explicit_input_node("target", NodeType::Integer)
                    .unwrap();
            }
            ExampleOperation::AModBToC => {
                param_builder
                    .expect_explicit_input_node("a", NodeType::Integer)
                    .unwrap();
                param_builder
                    .expect_explicit_input_node("b", NodeType::Integer)
                    .unwrap();
                param_builder
                    .expect_explicit_input_node("c", NodeType::Integer)
                    .unwrap();
            }
        }
        param_builder.build().unwrap()
    }

    fn apply_abstract(
        &self,
        g: &mut GraphWithSubstitution<AbstractGraph<Self::S>>,
    ) -> AbstractOperationOutput<Self::S> {
        let mut new_node_names = HashMap::new();
        match self {
            ExampleOperation::NoOp => {
                // No operation, so no changes to the abstract graph.
            }
            ExampleOperation::SetTo {
                op_typ,
                target_typ,
                value,
            } => {
                // Set the abstract value of the node to the specified type.
                g.set_node_value(SubstMarker::from("target"), *target_typ)
                    .unwrap();
            }
            ExampleOperation::SetEdgeTo {
                node_typ,
                param_typ: op_typ,
                target_typ,
                value,
            } => {
                // Set the edge from source to destination with the specified type.
                g.set_edge_value(
                    SubstMarker::from("src"),
                    SubstMarker::from("dst"),
                    target_typ.clone(),
                )
                .unwrap();
            }
            ExampleOperation::AddEdge {
                node_typ,
                param_typ: op_typ,
                target_typ,
                value,
            } => {
                // Add an edge from source to destination with the specified type.
                g.add_edge(
                    SubstMarker::from("src"),
                    SubstMarker::from("dst"),
                    target_typ.clone(),
                );
            }
            ExampleOperation::AddNode { node_type, value } => {
                // Add a new node with the specified type and value.
                g.add_node("new", node_type.clone());
                new_node_names.insert("new".into(), "new".into());
            }
            ExampleOperation::CopyValueFromTo => {
                // Copy the value from one node to another.
                let value = g.get_node_value(SubstMarker::from("source")).unwrap();
                g.set_node_value(SubstMarker::from("destination"), value.clone())
                    .unwrap();
            }
            ExampleOperation::SwapValues => {
                // Swap the values of two nodes.
                let value1 = g.get_node_value(SubstMarker::from("source")).unwrap();
                let value2 = g.get_node_value(SubstMarker::from("destination")).unwrap();
                let v1 = value1.clone();
                let v2 = value2.clone();
                g.set_node_value(SubstMarker::from("source"), v2).unwrap();
                g.set_node_value(SubstMarker::from("destination"), v1)
                    .unwrap();
                // TODO: talk about above problem in user defined op.
                //  Specifically: We take two objects as input, and swap them. Nothing guarantees that the most precise
                //  types of the two nodes are the same, hence the valid inferred signature (if this were an user defined op) would be
                //  that both nodes end up as type Object. However, because this is builtin, it can actually in a sense
                //  "look at" the real, most precise values of the nodes, and just say that it swaps those.
                //  If we didn't have this, we'd need monomorphized swapvaluesInt etc operations, or support for generics.
            }
            ExampleOperation::DeleteNode => {
                // Delete the node.
                g.delete_node(SubstMarker::from("target")).unwrap();
            }
            ExampleOperation::DeleteEdge => {
                // Delete the edge from source to destination.
                g.delete_edge(SubstMarker::from("src"), SubstMarker::from("dst"))
                    .unwrap();
            }
            ExampleOperation::AddInteger(i) => {
                // no abstract changes
            }
            ExampleOperation::AModBToC => {
                // no abstract changes
            }
        }
        g.get_abstract_output(new_node_names)
    }

    fn apply(
        &self,
        g: &mut GraphWithSubstitution<ConcreteGraph<Self::S>>,
        _: &mut ConcreteData,
    ) -> OperationOutput {
        let mut new_node_names = HashMap::new();
        match self {
            ExampleOperation::NoOp => {
                // No operation, so no changes to the concrete graph.
            }
            ExampleOperation::SetTo {
                op_typ,
                target_typ,
                value,
            } => {
                // Set the concrete value of the node to the specified value.
                g.set_node_value(SubstMarker::from("target"), value.clone())
                    .unwrap();
            }
            ExampleOperation::SetEdgeTo {
                node_typ,
                param_typ: op_typ,
                target_typ,
                value,
            } => {
                // Set the edge from source to destination with the specified value.
                g.set_edge_value(
                    SubstMarker::from("src"),
                    SubstMarker::from("dst"),
                    value.clone(),
                )
                .unwrap();
            }
            ExampleOperation::AddEdge {
                node_typ,
                param_typ: op_typ,
                target_typ,
                value,
            } => {
                // Add an edge from source to destination with the specified value.
                g.add_edge(
                    SubstMarker::from("src"),
                    SubstMarker::from("dst"),
                    value.clone(),
                );
            }
            ExampleOperation::AddNode { node_type, value } => {
                // Add a new node with the specified type and value.
                g.add_node("new", value.clone());
                new_node_names.insert("new".into(), "new".into());
            }
            ExampleOperation::CopyValueFromTo => {
                // Copy the value from one node to another.
                let value = g.get_node_value(SubstMarker::from("source")).unwrap();
                g.set_node_value(SubstMarker::from("destination"), value.clone())
                    .unwrap();
            }
            ExampleOperation::SwapValues => {
                // Swap the values of two nodes.
                let value1 = g.get_node_value(SubstMarker::from("source")).unwrap();
                let value2 = g.get_node_value(SubstMarker::from("destination")).unwrap();
                let v1 = value1.clone();
                let v2 = value2.clone();
                g.set_node_value(SubstMarker::from("source"), v2).unwrap();
                g.set_node_value(SubstMarker::from("destination"), v1)
                    .unwrap();
            }
            ExampleOperation::DeleteNode => {
                // Delete the node.
                g.delete_node(SubstMarker::from("target")).unwrap();
            }
            ExampleOperation::DeleteEdge => {
                // Delete the edge from source to destination.
                g.delete_edge(SubstMarker::from("src"), SubstMarker::from("dst"))
                    .unwrap();
            }
            ExampleOperation::AddInteger(i) => {
                // Add an integer to the node.
                let NodeValue::Integer(old_value) =
                    g.get_node_value(SubstMarker::from("target")).unwrap()
                else {
                    panic!(
                        "expected an integer node value for AddInteger operation - type unsoundness"
                    );
                };
                let value = NodeValue::Integer(*i + *old_value);
                g.set_node_value(SubstMarker::from("target"), value)
                    .unwrap();
            }
            ExampleOperation::AModBToC => {
                // Compute a % b and store it in c.
                let a = g.get_node_value(SubstMarker::from("a")).unwrap();
                let b = g.get_node_value(SubstMarker::from("b")).unwrap();
                let c = g.get_node_value(SubstMarker::from("c")).unwrap();
                let NodeValue::Integer(a_val) = a else {
                    panic!(
                        "expected an integer node value for AModBToC operation - type unsoundness"
                    );
                };
                let NodeValue::Integer(b_val) = b else {
                    panic!(
                        "expected an integer node value for AModBToC operation - type unsoundness"
                    );
                };
                let NodeValue::Integer(c_val) = c else {
                    panic!(
                        "expected an integer node value for AModBToC operation - type unsoundness"
                    );
                };
                let result = a_val % b_val;
                g.set_node_value(SubstMarker::from("c"), NodeValue::Integer(result))
                    .unwrap();
            }
        }
        g.get_concrete_output(new_node_names)
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Copy, From)]
pub struct MyOrdering(std::cmp::Ordering);

impl Deref for MyOrdering {
    type Target = std::cmp::Ordering;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ExampleQuery {
    ValuesEqual,
    ValueEqualTo(NodeValue),
    CmpFstSnd(MyOrdering),
}

impl BuiltinQuery for ExampleQuery {
    type S = ExampleSemantics;

    fn parameter(&self) -> OperationParameter<Self::S> {
        let mut param_builder = OperationParameterBuilder::new();
        match self {
            ExampleQuery::ValuesEqual => {
                param_builder
                    .expect_explicit_input_node("a", NodeType::Object)
                    .unwrap();
                param_builder
                    .expect_explicit_input_node("b", NodeType::Object)
                    .unwrap();
            }
            ExampleQuery::ValueEqualTo(_) => {
                param_builder
                    .expect_explicit_input_node("a", NodeType::Object)
                    .unwrap();
            }
            ExampleQuery::CmpFstSnd(_) => {
                param_builder
                    .expect_explicit_input_node("a", NodeType::Object)
                    .unwrap();
                param_builder
                    .expect_explicit_input_node("b", NodeType::Object)
                    .unwrap();
            }
        }
        param_builder.build().unwrap()
    }

    fn apply_abstract(&self, g: &mut GraphWithSubstitution<AbstractGraph<Self::S>>) {
        // does nothing, not testing side-effect-ful queries here
    }

    fn query(&self, g: &mut GraphWithSubstitution<ConcreteGraph<Self::S>>) -> ConcreteQueryOutput {
        match self {
            ExampleQuery::ValuesEqual => {
                let value1 = g.get_node_value(SubstMarker::from("a")).unwrap();
                let value2 = g.get_node_value(SubstMarker::from("b")).unwrap();
                ConcreteQueryOutput {
                    taken: value1 == value2,
                }
            }
            ExampleQuery::ValueEqualTo(value) => {
                let node_value = g.get_node_value(SubstMarker::from("a")).unwrap();
                ConcreteQueryOutput {
                    taken: node_value == value,
                }
            }
            ExampleQuery::CmpFstSnd(ordering) => {
                let value1 = g.get_node_value(SubstMarker::from("a")).unwrap();
                let value2 = g.get_node_value(SubstMarker::from("b")).unwrap();
                let cmp_result = match (value1, value2) {
                    (NodeValue::Integer(a), NodeValue::Integer(b)) => a.cmp(&b),
                    _ => {
                        panic!("type unsoundness: expected integers for comparison");
                    }
                };
                ConcreteQueryOutput {
                    taken: &cmp_result == ordering.deref(),
                }
            }
        }
    }
}

impl Semantics for ExampleSemantics {
    type NodeConcrete = NodeValue;
    type NodeAbstract = NodeType;
    type EdgeConcrete = String;
    type EdgeAbstract = EdgeType;
    type NodeMatcher = NodeMatcher;
    type EdgeMatcher = EdgeMatcher;
    type NodeJoin = NodeJoiner;
    type EdgeJoin = EdgeJoiner;
    type NodeConcreteToAbstract = NodeConcreteToAbstract;
    type EdgeConcreteToAbstract = EdgeConcreteToAbstract;
    type BuiltinOperation = ExampleOperation;
    type BuiltinQuery = ExampleQuery;

    fn top_node_abstract() -> Option<Self::NodeAbstract> {
        // despite us not having a top node due to `Separate`, we can still return Object as the default.
        // TODO: we should really document whether or not the library makes any assumptions about the top node wrt soundness. Right now it doesnt.
        Some(NodeType::Object)
    }
}

// additions for serde support
#[cfg(feature = "serde")]
impl Serialize for MyOrdering {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        // serialize as -1, 0, or 1 for Less, Equal, Greater
        let value = match self.0 {
            std::cmp::Ordering::Less => -1,
            std::cmp::Ordering::Equal => 0,
            std::cmp::Ordering::Greater => 1,
        };
        value.serialize(serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for MyOrdering {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = i32::deserialize(deserializer)?;
        let ordering = match value {
            -1 => std::cmp::Ordering::Less,
            0 => std::cmp::Ordering::Equal,
            1 => std::cmp::Ordering::Greater,
            _ => return Err(serde::de::Error::custom("invalid ordering value")),
        };
        Ok(MyOrdering(ordering))
    }
}