panproto-inst 0.51.0

Instance representation for panproto
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
//! Internal hom schema construction.
//!
//! The internal hom `[S, T]` constructs a schema whose instances represent
//! lenses (structure-preserving maps) from schema `S` to schema `T`.
//!
//! This module provides three operations:
//!
//! 1. `hom_schema(S, T)`: build the schema `[S, T]`
//! 2. `curry_migration(m, S, [S,T])`: encode a compiled migration as an instance of `[S, T]`
//! 3. `eval_hom(h, x, S, T)`: given an instance `h` of `[S, T]` and an instance `x` of `S`,
//!    produce an instance of `T`

use std::collections::{HashMap, HashSet};

use panproto_gat::Name;
use panproto_schema::{Edge, Schema, Vertex};
use smallvec::SmallVec;

use crate::error::InstError;
use crate::metadata::Node;
use crate::value::Value;
use crate::wtype::{CompiledMigration, WInstance, wtype_restrict};

/// Construct the internal hom schema `[S, T]`.
///
/// For each source vertex `v` in `S`, the hom schema contains:
///
/// - A `choice_v` vertex (kind `"hom_choice"`) representing which target
///   vertex `v` maps to.
/// - A `maps_to` edge from `choice_v` to each compatible target vertex
///   (same kind).
/// - A `backward_v_e` vertex (kind `"hom_backward"`) for each outgoing
///   edge from `v`, representing the backward (edge-level) component of
///   the lens.
/// - A `backward_for` edge from `choice_v` to each of its backward
///   vertices.
#[must_use]
pub fn hom_schema(source: &Schema, target: &Schema) -> Schema {
    let mut vertices: HashMap<Name, Vertex> = HashMap::new();
    let mut edges: HashMap<Edge, Name> = HashMap::new();
    let mut outgoing: HashMap<Name, SmallVec<Edge, 4>> = HashMap::new();
    let mut incoming: HashMap<Name, SmallVec<Edge, 4>> = HashMap::new();
    let mut between: HashMap<(Name, Name), SmallVec<Edge, 2>> = HashMap::new();

    // Collect target vertices grouped by kind for compatibility matching.
    let mut target_by_kind: HashMap<Name, Vec<Name>> = HashMap::new();
    for (tid, tv) in &target.vertices {
        target_by_kind
            .entry(tv.kind.clone())
            .or_default()
            .push(tid.clone());
    }

    for (vid, sv) in &source.vertices {
        let choice_id: Name = format!("choice_{vid}").into();
        vertices.insert(
            choice_id.clone(),
            Vertex {
                id: choice_id.clone(),
                kind: Name::from("hom_choice"),
                nsid: None,
            },
        );

        add_maps_to_edges(
            &choice_id,
            &sv.kind,
            &target_by_kind,
            target,
            &mut vertices,
            &mut edges,
            &mut outgoing,
            &mut incoming,
            &mut between,
        );

        add_backward_vertices(
            vid,
            &choice_id,
            source,
            &mut vertices,
            &mut edges,
            &mut outgoing,
            &mut incoming,
            &mut between,
        );
    }

    Schema {
        protocol: "hom".into(),
        vertices,
        edges,
        hyper_edges: HashMap::new(),
        constraints: HashMap::new(),
        required: HashMap::new(),
        nsids: HashMap::new(),
        entries: Vec::new(),
        variants: HashMap::new(),
        orderings: HashMap::new(),
        recursion_points: HashMap::new(),
        spans: HashMap::new(),
        usage_modes: HashMap::new(),
        nominal: HashMap::new(),
        coercions: HashMap::new(),
        mergers: HashMap::new(),
        defaults: HashMap::new(),
        policies: HashMap::new(),
        outgoing,
        incoming,
        between,
    }
}

/// Add `maps_to` edges from a choice vertex to all compatible target vertices.
#[allow(clippy::too_many_arguments)]
fn add_maps_to_edges(
    choice_id: &Name,
    source_kind: &Name,
    target_by_kind: &HashMap<Name, Vec<Name>>,
    target: &Schema,
    vertices: &mut HashMap<Name, Vertex>,
    edges: &mut HashMap<Edge, Name>,
    outgoing: &mut HashMap<Name, SmallVec<Edge, 4>>,
    incoming: &mut HashMap<Name, SmallVec<Edge, 4>>,
    between: &mut HashMap<(Name, Name), SmallVec<Edge, 2>>,
) {
    let Some(compatible) = target_by_kind.get(source_kind) else {
        return;
    };
    for tid in compatible {
        let edge = Edge {
            src: choice_id.clone(),
            tgt: tid.clone(),
            kind: Name::from("maps_to"),
            name: Some(tid.clone()),
        };

        if !vertices.contains_key(tid) {
            let tv = &target.vertices[tid];
            vertices.insert(
                tid.clone(),
                Vertex {
                    id: tid.clone(),
                    kind: tv.kind.clone(),
                    nsid: tv.nsid.clone(),
                },
            );
        }

        outgoing
            .entry(choice_id.clone())
            .or_default()
            .push(edge.clone());
        incoming.entry(tid.clone()).or_default().push(edge.clone());
        between
            .entry((choice_id.clone(), tid.clone()))
            .or_default()
            .push(edge.clone());
        edges.insert(edge, Name::from("maps_to"));
    }
}

/// Add backward vertices for each outgoing edge from a source vertex.
#[allow(clippy::too_many_arguments)]
fn add_backward_vertices(
    vid: &Name,
    choice_id: &Name,
    source: &Schema,
    vertices: &mut HashMap<Name, Vertex>,
    edges: &mut HashMap<Edge, Name>,
    outgoing: &mut HashMap<Name, SmallVec<Edge, 4>>,
    incoming: &mut HashMap<Name, SmallVec<Edge, 4>>,
    between: &mut HashMap<(Name, Name), SmallVec<Edge, 2>>,
) {
    let Some(src_edges) = source.outgoing.get(vid) else {
        return;
    };
    for src_edge in src_edges {
        let backward_id: Name = format!("backward_{vid}_{}", edge_label(src_edge)).into();
        vertices.insert(
            backward_id.clone(),
            Vertex {
                id: backward_id.clone(),
                kind: Name::from("hom_backward"),
                nsid: None,
            },
        );

        let bf_edge = Edge {
            src: choice_id.clone(),
            tgt: backward_id.clone(),
            kind: Name::from("backward_for"),
            name: Some(backward_id.clone()),
        };
        outgoing
            .entry(choice_id.clone())
            .or_default()
            .push(bf_edge.clone());
        incoming
            .entry(backward_id.clone())
            .or_default()
            .push(bf_edge.clone());
        between
            .entry((choice_id.clone(), backward_id.clone()))
            .or_default()
            .push(bf_edge.clone());
        edges.insert(bf_edge, Name::from("backward_for"));
    }
}

/// Derive a stable label for an edge, used when constructing backward vertex
/// names. Prefers the edge's `name` field; falls back to the target vertex id.
fn edge_label(e: &Edge) -> &str {
    e.name.as_deref().unwrap_or(&e.tgt)
}

/// Evaluate an instance of `[S, T]` (a lens encoding) against an instance
/// of `S` to produce an instance of `T`.
///
/// The evaluation proceeds in three steps:
///
/// 1. Extract the forward map from `hom_instance`: for each `choice_v`
///    node, read its `maps_to` target to determine the vertex remapping.
/// 2. Extract backward maps from `hom_instance`: for each `backward_v_e`
///    node, read the stored edge mapping.
/// 3. Build a `CompiledMigration` from the extracted maps and apply
///    `wtype_restrict` to the source instance.
///
/// # Errors
///
/// Returns `InstError::NodeNotFound` if a `maps_to` arc references a missing node,
/// or `InstError::EvalHom` if the underlying `wtype_restrict` fails.
pub fn eval_hom(
    hom_instance: &WInstance,
    source_instance: &WInstance,
    source_schema: &Schema,
    target_schema: &Schema,
) -> Result<WInstance, InstError> {
    // Step 1: extract vertex remap from choice nodes.
    let mut vertex_remap: HashMap<Name, Name> = HashMap::new();
    let mut surviving_verts: HashSet<Name> = HashSet::new();

    for (node_id, node) in &hom_instance.nodes {
        let anchor: &str = &node.anchor;
        let Some(source_vertex_str) = anchor.strip_prefix("choice_") else {
            continue;
        };
        let source_vertex: Name = source_vertex_str.into();

        // Find the maps_to arc from this choice node.
        for &(parent, child, ref edge) in &hom_instance.arcs {
            if parent == *node_id && &*edge.kind == "maps_to" {
                let target_node = hom_instance
                    .nodes
                    .get(&child)
                    .ok_or(InstError::NodeNotFound(child))?;
                surviving_verts.insert(target_node.anchor.clone());
                vertex_remap.insert(source_vertex.clone(), target_node.anchor.clone());
                break;
            }
        }
    }

    // Step 2: extract edge remap from backward nodes.
    let mut edge_remap: HashMap<Edge, Edge> = HashMap::new();
    let mut surviving_edges: HashSet<Edge> = HashSet::new();

    for node in hom_instance.nodes.values() {
        let anchor: &str = &node.anchor;
        if !anchor.starts_with("backward_") {
            continue;
        }
        if let (Some(Value::Str(src_src)), Some(Value::Str(src_tgt)), Some(Value::Str(src_kind))) = (
            node.extra_fields.get("src_src"),
            node.extra_fields.get("src_tgt"),
            node.extra_fields.get("src_kind"),
        ) {
            let src_edge = Edge {
                src: Name::from(src_src.as_str()),
                tgt: Name::from(src_tgt.as_str()),
                kind: Name::from(src_kind.as_str()),
                name: node.extra_fields.get("src_name").and_then(|v| match v {
                    Value::Str(s) => Some(Name::from(s.as_str())),
                    _ => None,
                }),
            };

            let tgt_edge = Edge {
                src: vertex_remap
                    .get(&src_edge.src)
                    .cloned()
                    .unwrap_or_else(|| src_edge.src.clone()),
                tgt: vertex_remap
                    .get(&src_edge.tgt)
                    .cloned()
                    .unwrap_or_else(|| src_edge.tgt.clone()),
                kind: node
                    .extra_fields
                    .get("tgt_kind")
                    .and_then(|v| match v {
                        Value::Str(s) => Some(Name::from(s.as_str())),
                        _ => None,
                    })
                    .unwrap_or_else(|| src_edge.kind.clone()),
                name: node
                    .extra_fields
                    .get("tgt_name")
                    .and_then(|v| match v {
                        Value::Str(s) => Some(Name::from(s.as_str())),
                        _ => None,
                    })
                    .or_else(|| src_edge.name.clone()),
            };

            surviving_edges.insert(src_edge.clone());
            edge_remap.insert(src_edge, tgt_edge);
        }
    }

    // Step 3: build compiled migration and apply wtype_restrict.
    let compiled = CompiledMigration {
        surviving_verts,
        surviving_edges,
        vertex_remap,
        edge_remap,
        resolver: HashMap::new(),
        hyper_resolver: HashMap::new(),
        field_transforms: HashMap::new(),
        conditional_survival: HashMap::new(),
        expansion_path: HashMap::new(),
    };

    wtype_restrict(source_instance, source_schema, target_schema, &compiled)
        .map_err(|e| InstError::EvalHom(e.to_string()))
}

/// Curry a compiled migration into an instance of `[S, T]`.
///
/// Given `vertex_remap` and `edge_remap` from a `CompiledMigration`,
/// construct a `WInstance` of the hom schema encoding those mappings.
/// This is the inverse of `eval_hom`: currying a migration and then
/// evaluating should produce the same result as applying the migration
/// directly.
#[must_use]
pub fn curry_migration(
    compiled: &CompiledMigration,
    source_schema: &Schema,
    _hom_schema: &Schema,
) -> WInstance {
    let mut nodes: HashMap<u32, Node> = HashMap::new();
    let mut arcs: Vec<(u32, u32, Edge)> = Vec::new();
    let mut next_id: u32 = 0;

    // Create root node anchored to a synthetic hom root.
    let root_id = next_id;
    let root_anchor: Name = "hom_root".into();
    nodes.insert(root_id, Node::new(root_id, root_anchor.clone()));
    next_id += 1;

    for (src_v, tgt_v) in &compiled.vertex_remap {
        let choice_anchor: Name = format!("choice_{src_v}").into();
        let choice_node_id = next_id;
        next_id += 1;
        nodes.insert(
            choice_node_id,
            Node::new(choice_node_id, choice_anchor.clone()),
        );

        // Arc from root to choice node.
        arcs.push((
            root_id,
            choice_node_id,
            Edge {
                src: root_anchor.clone(),
                tgt: choice_anchor.clone(),
                kind: Name::from("has_choice"),
                name: Some(choice_anchor.clone()),
            },
        ));

        // Create target vertex node.
        let target_node_id = next_id;
        next_id += 1;
        nodes.insert(target_node_id, Node::new(target_node_id, tgt_v.clone()));

        // maps_to arc from choice to target.
        arcs.push((
            choice_node_id,
            target_node_id,
            Edge {
                src: choice_anchor.clone(),
                tgt: tgt_v.clone(),
                kind: Name::from("maps_to"),
                name: Some(tgt_v.clone()),
            },
        ));

        // Create backward nodes for each outgoing edge from this source vertex.
        if let Some(src_edges) = source_schema.outgoing.get(src_v) {
            for src_edge in src_edges {
                let backward_anchor: Name =
                    format!("backward_{src_v}_{}", edge_label(src_edge)).into();
                let backward_node_id = next_id;
                next_id += 1;

                let mut backward_node = Node::new(backward_node_id, backward_anchor.clone());
                backward_node
                    .extra_fields
                    .insert("src_src".into(), Value::Str(src_edge.src.to_string()));
                backward_node
                    .extra_fields
                    .insert("src_tgt".into(), Value::Str(src_edge.tgt.to_string()));
                backward_node
                    .extra_fields
                    .insert("src_kind".into(), Value::Str(src_edge.kind.to_string()));
                if let Some(ref n) = src_edge.name {
                    backward_node
                        .extra_fields
                        .insert("src_name".into(), Value::Str(n.to_string()));
                }

                if let Some(tgt_edge) = compiled.edge_remap.get(src_edge) {
                    backward_node
                        .extra_fields
                        .insert("tgt_kind".into(), Value::Str(tgt_edge.kind.to_string()));
                    if let Some(ref n) = tgt_edge.name {
                        backward_node
                            .extra_fields
                            .insert("tgt_name".into(), Value::Str(n.to_string()));
                    }
                }

                nodes.insert(backward_node_id, backward_node);

                arcs.push((
                    choice_node_id,
                    backward_node_id,
                    Edge {
                        src: choice_anchor.clone(),
                        tgt: backward_anchor.clone(),
                        kind: Name::from("backward_for"),
                        name: Some(backward_anchor.clone()),
                    },
                ));
            }
        }
    }

    WInstance::new(nodes, arcs, Vec::new(), root_id, root_anchor)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::value::FieldPresence;

    /// Helper: build a minimal test schema with the given vertices (all kind
    /// "object") and edges, populating the precomputed indices.
    fn make_schema(verts: &[&str], edge_list: &[(&str, &str, &str)]) -> Schema {
        let mut vertices: HashMap<Name, Vertex> = HashMap::new();
        let mut edges: HashMap<Edge, Name> = HashMap::new();
        let mut outgoing: HashMap<Name, SmallVec<Edge, 4>> = HashMap::new();
        let mut incoming: HashMap<Name, SmallVec<Edge, 4>> = HashMap::new();
        let mut between: HashMap<(Name, Name), SmallVec<Edge, 2>> = HashMap::new();

        for &v in verts {
            vertices.insert(
                Name::from(v),
                Vertex {
                    id: Name::from(v),
                    kind: Name::from("object"),
                    nsid: None,
                },
            );
        }

        for &(src, tgt, label) in edge_list {
            let edge = Edge {
                src: Name::from(src),
                tgt: Name::from(tgt),
                kind: Name::from("prop"),
                name: Some(Name::from(label)),
            };
            outgoing
                .entry(Name::from(src))
                .or_default()
                .push(edge.clone());
            incoming
                .entry(Name::from(tgt))
                .or_default()
                .push(edge.clone());
            between
                .entry((Name::from(src), Name::from(tgt)))
                .or_default()
                .push(edge.clone());
            edges.insert(edge, Name::from("prop"));
        }

        Schema {
            protocol: "test".into(),
            vertices,
            edges,
            hyper_edges: HashMap::new(),
            constraints: HashMap::new(),
            required: HashMap::new(),
            nsids: HashMap::new(),
            entries: Vec::new(),
            variants: HashMap::new(),
            orderings: HashMap::new(),
            recursion_points: HashMap::new(),
            spans: HashMap::new(),
            usage_modes: HashMap::new(),
            nominal: HashMap::new(),
            coercions: HashMap::new(),
            mergers: HashMap::new(),
            defaults: HashMap::new(),
            policies: HashMap::new(),
            outgoing,
            incoming,
            between,
        }
    }

    #[test]
    fn hom_schema_empty_schemas() {
        let s = make_schema(&[], &[]);
        let t = make_schema(&[], &[]);
        let h = hom_schema(&s, &t);

        assert!(
            h.vertices.is_empty(),
            "empty schemas yield empty hom schema"
        );
        assert!(h.edges.is_empty());
    }

    #[test]
    #[allow(clippy::unwrap_used)]
    fn hom_schema_two_vertex() {
        let source = make_schema(&["a", "b"], &[("a", "b", "edge_ab")]);
        let target = make_schema(&["x", "y"], &[("x", "y", "edge_xy")]);
        let h = hom_schema(&source, &target);

        assert!(
            h.vertices.contains_key(&Name::from("choice_a")),
            "choice_a vertex must exist"
        );
        assert!(
            h.vertices.contains_key(&Name::from("choice_b")),
            "choice_b vertex must exist"
        );
        assert!(
            h.vertices.contains_key(&Name::from("backward_a_edge_ab")),
            "backward vertex for edge_ab must exist"
        );

        assert_eq!(h.vertices[&Name::from("choice_a")].kind, "hom_choice");
        assert_eq!(
            h.vertices[&Name::from("backward_a_edge_ab")].kind,
            "hom_backward"
        );

        let choice_a_out = h.outgoing.get(&Name::from("choice_a")).unwrap();
        let maps_to_count = choice_a_out
            .iter()
            .filter(|e| &*e.kind == "maps_to")
            .count();
        assert_eq!(maps_to_count, 2, "choice_a maps_to x and y");

        let backward_for_count = choice_a_out
            .iter()
            .filter(|e| &*e.kind == "backward_for")
            .count();
        assert_eq!(backward_for_count, 1, "choice_a has one backward_for edge");
    }

    #[test]
    #[allow(clippy::unwrap_used)]
    fn curry_roundtrip() {
        let source = make_schema(&["a", "b"], &[("a", "b", "child")]);
        let target = make_schema(&["x", "y"], &[("x", "y", "child")]);

        let src_edge = Edge {
            src: Name::from("a"),
            tgt: Name::from("b"),
            kind: Name::from("prop"),
            name: Some(Name::from("child")),
        };
        let tgt_edge = Edge {
            src: Name::from("x"),
            tgt: Name::from("y"),
            kind: Name::from("prop"),
            name: Some(Name::from("child")),
        };

        let compiled = CompiledMigration {
            surviving_verts: HashSet::from([Name::from("x"), Name::from("y")]),
            surviving_edges: HashSet::from([src_edge.clone()]),
            vertex_remap: HashMap::from([
                (Name::from("a"), Name::from("x")),
                (Name::from("b"), Name::from("y")),
            ]),
            edge_remap: HashMap::from([(src_edge.clone(), tgt_edge)]),
            resolver: HashMap::new(),
            hyper_resolver: HashMap::new(),
            field_transforms: HashMap::new(),
            conditional_survival: HashMap::new(),
            expansion_path: HashMap::new(),
        };

        let h = hom_schema(&source, &target);
        let curried = curry_migration(&compiled, &source, &h);

        let choice_count = curried
            .nodes
            .values()
            .filter(|n| n.anchor.starts_with("choice_"))
            .count();
        assert_eq!(choice_count, 2, "two choice nodes (one per source vertex)");

        // Build a source instance: root "a" with child "b".
        let src_nodes = HashMap::from([
            (0, Node::new(0, "a")),
            (
                1,
                Node::new(1, "b").with_value(FieldPresence::Present(Value::Str("hello".into()))),
            ),
        ]);
        let src_arcs = vec![(0, 1, src_edge)];
        let src_instance = WInstance::new(src_nodes, src_arcs, Vec::new(), 0, Name::from("a"));

        let result = eval_hom(&curried, &src_instance, &source, &target).unwrap();

        let root_node = result.nodes.get(&result.root).unwrap();
        assert_eq!(root_node.anchor, "x", "root remapped to x");

        let child_ids = result.children(result.root);
        assert_eq!(child_ids.len(), 1, "one child");
        let child_node = result.nodes.get(&child_ids[0]).unwrap();
        assert_eq!(child_node.anchor, "y", "child remapped to y");

        assert_eq!(
            child_node.value,
            Some(FieldPresence::Present(Value::Str("hello".into())))
        );

        // Compare with direct wtype_restrict.
        let direct = wtype_restrict(&src_instance, &source, &target, &compiled).unwrap();
        assert_eq!(result.node_count(), direct.node_count());
        assert_eq!(result.arc_count(), direct.arc_count());

        let direct_root = direct.nodes.get(&direct.root).unwrap();
        assert_eq!(direct_root.anchor, root_node.anchor);
    }
}