panproto-lens 0.52.0

Bidirectional lens combinators 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
//! Complement type system for protolenses.
//!
//! Given a protolens η and schema S, compute the complement type
//! `ComplementType(η, S)`. This is a dependent type: the complement
//! varies with the schema the protolens is instantiated at.

use panproto_gat::Name;
use panproto_inst::value::Value;
use panproto_schema::{Protocol, Schema};
use serde::{Deserialize, Serialize};

use crate::protolens::{ComplementConstructor, Protolens, ProtolensChain};

/// Static specification of what data a complement will contain.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ComplementSpec {
    /// Overall classification.
    pub kind: ComplementKind,
    /// What the user must supply for forward direction.
    pub forward_defaults: Vec<DefaultRequirement>,
    /// What data is captured in the complement for backward direction.
    pub captured_data: Vec<CapturedField>,
    /// Human-readable summary.
    pub summary: String,
}

/// Classification of a complement's role.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ComplementKind {
    /// No complement needed (isomorphism).
    Empty,
    /// Data captured in complement (lossy forward).
    DataCaptured,
    /// User must provide defaults (lossy backward).
    DefaultsRequired,
    /// Both.
    Mixed,
}

/// A default value that must be supplied for the forward direction.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DefaultRequirement {
    /// Name of the element needing a default.
    pub element_name: Name,
    /// What kind: "sort" or "op" or "equation".
    pub element_kind: String,
    /// Human-readable description.
    pub description: String,
    /// Suggested default if known.
    pub suggested_default: Option<Value>,
}

/// A field captured in the complement during the forward direction.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CapturedField {
    /// Name of the captured element.
    pub element_name: Name,
    /// What kind: "sort" or "op".
    pub element_kind: String,
    /// Human-readable description.
    pub description: String,
}

/// Compute the complement spec for a single protolens at a specific schema.
#[must_use]
pub fn complement_spec_at(protolens: &Protolens, schema: &Schema) -> ComplementSpec {
    spec_from_constructor(&protolens.complement_constructor, schema)
}

/// Compute the complement spec for a protolens chain at a specific schema.
#[must_use]
pub fn chain_complement_spec(
    chain: &ProtolensChain,
    schema: &Schema,
    protocol: &Protocol,
) -> ComplementSpec {
    if chain.steps.is_empty() {
        return ComplementSpec {
            kind: ComplementKind::Empty,
            forward_defaults: vec![],
            captured_data: vec![],
            summary: "Identity transformation, no complement needed.".into(),
        };
    }

    let mut all_defaults = Vec::new();
    let mut all_captured = Vec::new();
    let mut current_schema = schema.clone();

    for step in &chain.steps {
        let spec = complement_spec_at(step, &current_schema);
        all_defaults.extend(spec.forward_defaults);
        all_captured.extend(spec.captured_data);
        if let Ok(next) = step.target_schema(&current_schema, protocol) {
            current_schema = next;
        }
    }

    let kind = classify(&all_defaults, &all_captured);
    let summary = build_summary(&kind, &all_defaults, &all_captured);

    ComplementSpec {
        kind,
        forward_defaults: all_defaults,
        captured_data: all_captured,
        summary,
    }
}

fn spec_from_constructor(constructor: &ComplementConstructor, schema: &Schema) -> ComplementSpec {
    match constructor {
        ComplementConstructor::Empty => ComplementSpec {
            kind: ComplementKind::Empty,
            forward_defaults: vec![],
            captured_data: vec![],
            summary: "Lossless transformation.".into(),
        },
        ComplementConstructor::DroppedSortData { sort } => {
            // Count how many vertices of this sort exist in the schema.
            let count = schema.vertices.values().filter(|v| v.kind == *sort).count();
            ComplementSpec {
                kind: ComplementKind::DataCaptured,
                forward_defaults: vec![],
                captured_data: vec![CapturedField {
                    element_name: sort.clone(),
                    element_kind: "sort".into(),
                    description: format!(
                        "Data for {count} vertices of kind '{sort}' will be captured in the complement."
                    ),
                }],
                summary: format!("Drops sort '{sort}': {count} vertices captured in complement."),
            }
        }
        ComplementConstructor::DroppedOpData { op } => {
            let count = schema.edges.keys().filter(|e| e.kind == *op).count();
            ComplementSpec {
                kind: ComplementKind::DataCaptured,
                forward_defaults: vec![],
                captured_data: vec![CapturedField {
                    element_name: op.clone(),
                    element_kind: "op".into(),
                    description: format!(
                        "{count} edges of kind '{op}' will be captured in the complement.",
                    ),
                }],
                summary: format!("Drops operation '{op}': {count} edges captured."),
            }
        }
        ComplementConstructor::DroppedEdge {
            src,
            tgt,
            edge_name,
            ..
        } => dropped_edge_spec(src, tgt, edge_name.as_ref()),
        ComplementConstructor::AddedElement {
            element_name,
            element_kind,
            default_value,
        } => added_element_spec(element_name, element_kind, default_value.as_ref()),
        ComplementConstructor::NatTransKernel { nat_trans_name } => ComplementSpec {
            kind: ComplementKind::DataCaptured,
            forward_defaults: vec![],
            captured_data: vec![CapturedField {
                element_name: nat_trans_name.clone(),
                element_kind: "nat_trans".into(),
                description: format!(
                    "Kernel of natural transformation '{nat_trans_name}' captured in complement.",
                ),
            }],
            summary: format!("Value conversion via '{nat_trans_name}': kernel captured."),
        },
        ComplementConstructor::CoercedSortData { sort, class } => {
            coerced_sort_spec(sort, *class, schema)
        }
        ComplementConstructor::Composite(parts) => {
            let mut all_defaults = Vec::new();
            let mut all_captured = Vec::new();
            for part in parts {
                let sub = spec_from_constructor(part, schema);
                all_defaults.extend(sub.forward_defaults);
                all_captured.extend(sub.captured_data);
            }
            let kind = classify(&all_defaults, &all_captured);
            let summary = build_summary(&kind, &all_defaults, &all_captured);
            ComplementSpec {
                kind,
                forward_defaults: all_defaults,
                captured_data: all_captured,
                summary,
            }
        }
        ComplementConstructor::Scoped { focus, inner } => {
            let inner_spec = spec_from_constructor(inner, schema);
            let kind = inner_spec.kind;
            ComplementSpec {
                kind,
                forward_defaults: inner_spec.forward_defaults,
                captured_data: inner_spec.captured_data,
                summary: format!("Scoped at '{focus}': {}", inner_spec.summary),
            }
        }
        ComplementConstructor::Enrichment { kind, enricher } => {
            enrichment_spec(*kind, enricher, schema)
        }
    }
}

/// Build a `ComplementSpec` for an enrichment-fibre complement.
fn enrichment_spec(
    kind: panproto_gat::EnrichmentKind,
    enricher: &std::sync::Arc<str>,
    schema: &Schema,
) -> ComplementSpec {
    let count = schema
        .constraints
        .values()
        .filter(|cs| cs.iter().any(|c| kind.is_member_sort(c.sort.as_ref())))
        .count();
    ComplementSpec {
        kind: ComplementKind::DataCaptured,
        forward_defaults: vec![],
        captured_data: vec![CapturedField {
            element_name: Name::from(format!("enrichment/{kind:?}/{enricher}")),
            element_kind: "enrichment".into(),
            description: format!(
                "{count} vertices carry constraints in the {kind:?} \
                 enrichment fibre; the registered driver \
                 '{enricher}' is responsible for materialising \
                 them in the put direction."
            ),
        }],
        summary: format!(
            "{kind:?} enrichment via driver '{enricher}'; \
             per-vertex fibre handled by the driver, not the \
             WInstance complement."
        ),
    }
}

/// Build a `ComplementSpec` for an added element requiring a default.
fn added_element_spec(
    element_name: &Name,
    element_kind: &str,
    default_value: Option<&panproto_inst::value::Value>,
) -> ComplementSpec {
    ComplementSpec {
        kind: ComplementKind::DefaultsRequired,
        forward_defaults: vec![DefaultRequirement {
            element_name: element_name.clone(),
            element_kind: element_kind.to_string(),
            description: format!("Default value needed for added {element_kind} '{element_name}'."),
            suggested_default: default_value.cloned(),
        }],
        captured_data: vec![],
        summary: format!("Adds {element_kind} '{element_name}': default required."),
    }
}

/// Build a `ComplementSpec` for a single dropped edge.
fn dropped_edge_spec(src: &Name, tgt: &Name, edge_name: Option<&Name>) -> ComplementSpec {
    let label = edge_name.map_or_else(|| "unnamed".to_string(), ToString::to_string);
    ComplementSpec {
        kind: ComplementKind::DataCaptured,
        forward_defaults: vec![],
        captured_data: vec![CapturedField {
            element_name: Name::from(format!("{src}--{label}-->{tgt}")),
            element_kind: "edge".into(),
            description: format!(
                "Single edge '{src} --({label})--> {tgt}' captured in complement."
            ),
        }],
        summary: format!("Drops edge '{src} --({label})--> {tgt}': captured in complement."),
    }
}

/// Build a `ComplementSpec` for a coerced sort.
fn coerced_sort_spec(
    sort: &Name,
    class: panproto_gat::CoercionClass,
    schema: &Schema,
) -> ComplementSpec {
    let count = schema.vertices.values().filter(|v| v.kind == *sort).count();
    let (kind, desc) = match class {
        panproto_gat::CoercionClass::Iso => (
            ComplementKind::Empty,
            format!("Isomorphic coercion on sort '{sort}' ({count} vertices)."),
        ),
        panproto_gat::CoercionClass::Retraction => (
            ComplementKind::DataCaptured,
            format!("Retraction coercion on sort '{sort}' ({count} vertices): residual captured."),
        ),
        panproto_gat::CoercionClass::Projection => (
            ComplementKind::Empty,
            format!(
                "Projection coercion on sort '{sort}' ({count} vertices): \
                 derived values re-computed by get, no complement storage needed."
            ),
        ),
        panproto_gat::CoercionClass::Opaque | _ => (
            ComplementKind::DataCaptured,
            format!(
                "Opaque coercion on sort '{sort}' ({count} vertices): original values captured."
            ),
        ),
    };
    ComplementSpec {
        kind,
        forward_defaults: vec![],
        // Only coercions that need complement storage (Retraction, Opaque)
        // produce captured data. Iso stores nothing (lossless). Projection
        // stores nothing (the derived value is re-computed by `get`
        // deterministically from the source fiber; the source data itself
        // survives via the tree structure's complement, not this coercion's).
        captured_data: if class.needs_complement_storage() {
            vec![CapturedField {
                element_name: sort.clone(),
                element_kind: "coerced_sort".into(),
                description: desc.clone(),
            }]
        } else {
            vec![]
        },
        summary: desc,
    }
}

/// Classify the complement kind from defaults and captured fields.
const fn classify(defaults: &[DefaultRequirement], captured: &[CapturedField]) -> ComplementKind {
    match (defaults.is_empty(), captured.is_empty()) {
        (true, true) => ComplementKind::Empty,
        (false, true) => ComplementKind::DefaultsRequired,
        (true, false) => ComplementKind::DataCaptured,
        (false, false) => ComplementKind::Mixed,
    }
}

fn build_summary(
    kind: &ComplementKind,
    defaults: &[DefaultRequirement],
    captured: &[CapturedField],
) -> String {
    match kind {
        ComplementKind::Empty => "Lossless transformation, no complement needed.".into(),
        ComplementKind::DefaultsRequired => format!(
            "{} default(s) required: {}",
            defaults.len(),
            defaults
                .iter()
                .map(|d| d.element_name.to_string())
                .collect::<Vec<_>>()
                .join(", ")
        ),
        ComplementKind::DataCaptured => format!(
            "{} field(s) captured in complement: {}",
            captured.len(),
            captured
                .iter()
                .map(|c| c.element_name.to_string())
                .collect::<Vec<_>>()
                .join(", ")
        ),
        ComplementKind::Mixed => format!(
            "{} default(s) required, {} field(s) captured in complement.",
            defaults.len(),
            captured.len()
        ),
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::protolens::elementary;
    use crate::tests::three_node_schema;
    use panproto_inst::value::Value;

    fn test_protocol() -> Protocol {
        Protocol {
            name: "test".into(),
            schema_theory: "ThGraph".into(),
            instance_theory: "ThWType".into(),
            edge_rules: vec![],
            obj_kinds: vec!["object".into(), "string".into(), "array".into()],
            constraint_sorts: vec![],
            ..Protocol::default()
        }
    }

    /// Pin the JSON wire format. The TypeScript SDK declares this
    /// shape in `bindings/typescript/src/protolens.ts` (`ComplementSpec`,
    /// `ComplementKind`, `DefaultRequirement`, `CapturedField`): enum
    /// variants in `snake_case` (`"empty" | "data_captured" |
    /// "defaults_required" | "mixed"`), struct fields in `camelCase`
    /// (`forwardDefaults`, `capturedData`, `elementName`,
    /// `elementKind`, `suggestedDefault`). Without the
    /// `#[serde(rename_all = ...)]` attributes Rust would emit
    /// `"DataCaptured"` enum variants and `element_name` fields, and
    /// every TS consumer reaching for those fields through the typed
    /// API would see `undefined`.
    #[test]
    fn complement_spec_wire_format_matches_ts_sdk() {
        use serde_json::{Value as JsonValue, json};
        let spec = ComplementSpec {
            kind: ComplementKind::DataCaptured,
            forward_defaults: vec![DefaultRequirement {
                element_name: Name::from("field_a"),
                element_kind: "sort".to_owned(),
                description: "needs a default".to_owned(),
                suggested_default: None,
            }],
            captured_data: vec![CapturedField {
                element_name: Name::from("field_b"),
                element_kind: "op".to_owned(),
                description: "captured".to_owned(),
            }],
            summary: "mixed".to_owned(),
        };
        let value: JsonValue = serde_json::to_value(&spec).unwrap();
        assert_eq!(
            value,
            json!({
                "kind": "data_captured",
                "forwardDefaults": [{
                    "elementName": "field_a",
                    "elementKind": "sort",
                    "description": "needs a default",
                    "suggestedDefault": null,
                }],
                "capturedData": [{
                    "elementName": "field_b",
                    "elementKind": "op",
                    "description": "captured",
                }],
                "summary": "mixed",
            }),
            "ComplementSpec wire format must match the TS SDK"
        );
        // All four ComplementKind variants must wire as snake_case
        // to match the TS union type.
        for (variant, wire) in [
            (ComplementKind::Empty, "empty"),
            (ComplementKind::DataCaptured, "data_captured"),
            (ComplementKind::DefaultsRequired, "defaults_required"),
            (ComplementKind::Mixed, "mixed"),
        ] {
            assert_eq!(
                serde_json::to_value(&variant).unwrap(),
                JsonValue::String(wire.to_owned()),
                "ComplementKind::{variant:?} must serialize as {wire:?}"
            );
        }
    }

    #[test]
    fn rename_sort_has_empty_complement() {
        let schema = three_node_schema();
        let p = elementary::rename_sort("string", "text");
        let spec = complement_spec_at(&p, &schema);
        assert_eq!(spec.kind, ComplementKind::Empty);
        assert!(spec.forward_defaults.is_empty());
        assert!(spec.captured_data.is_empty());
    }

    #[test]
    fn drop_sort_captures_data() {
        let schema = three_node_schema();
        let p = elementary::drop_sort("string");
        let spec = complement_spec_at(&p, &schema);
        assert_eq!(spec.kind, ComplementKind::DataCaptured);
        assert!(spec.captured_data.len() == 1);
        assert_eq!(&*spec.captured_data[0].element_name, "string");
    }

    #[test]
    fn add_sort_has_defaults_required_complement() {
        let schema = three_node_schema();
        let p = elementary::add_sort("tags", "array", Value::Null);
        let spec = complement_spec_at(&p, &schema);
        assert_eq!(spec.kind, ComplementKind::DefaultsRequired);
        assert_eq!(spec.forward_defaults.len(), 1);
        assert_eq!(&*spec.forward_defaults[0].element_name, "tags");
    }

    #[test]
    fn drop_op_captures_data() {
        let schema = three_node_schema();
        let p = elementary::drop_op("prop");
        let spec = complement_spec_at(&p, &schema);
        assert_eq!(spec.kind, ComplementKind::DataCaptured);
        assert!(spec.captured_data.len() == 1);
        assert_eq!(&*spec.captured_data[0].element_name, "prop");
    }

    #[test]
    fn empty_chain_is_empty() {
        let schema = three_node_schema();
        let protocol = test_protocol();
        let chain = crate::protolens::ProtolensChain::new(vec![]);
        let spec = chain_complement_spec(&chain, &schema, &protocol);
        assert_eq!(spec.kind, ComplementKind::Empty);
    }

    #[test]
    fn chain_with_drop_has_data_captured() {
        let schema = three_node_schema();
        let protocol = test_protocol();
        let chain = crate::protolens::ProtolensChain::new(vec![elementary::drop_sort("string")]);
        let spec = chain_complement_spec(&chain, &schema, &protocol);
        assert_eq!(spec.kind, ComplementKind::DataCaptured);
    }

    #[test]
    fn chain_mixed() {
        let schema = three_node_schema();
        let protocol = test_protocol();
        // This chain has both adds (defaults required)
        // and drops (data captured).
        let chain = crate::protolens::ProtolensChain::new(vec![
            elementary::add_sort("tags", "array", Value::Null),
            elementary::drop_sort("string"),
        ]);
        let spec = chain_complement_spec(&chain, &schema, &protocol);
        assert_eq!(spec.kind, ComplementKind::Mixed);
    }

    #[test]
    fn summary_describes_complement() {
        let schema = three_node_schema();
        let p = elementary::drop_sort("string");
        let spec = complement_spec_at(&p, &schema);
        assert!(spec.summary.contains("string"));
    }
}