prismqueer 0.1.0

The spectral-triple substrate — five operations (focus, project, split, shift, settle), the Prism trait, zero deps. The foundation.
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
//! Named — a labeled Prism.

use crate::oid::{Addressable, Oid};

/// A labeled Prism. The name is for humans. The OID is for the graph.
///
/// Named("focus", optic) — the optic with a name.
/// The OID is derived from both the name and the inner optic.
#[derive(Debug, Clone, PartialEq)]
pub struct Named<P>(pub &'static str, pub P);

impl<P> Named<P> {
    pub fn name(&self) -> &'static str {
        self.0
    }

    pub fn inner(&self) -> &P {
        &self.1
    }

    pub fn into_inner(self) -> P {
        self.1
    }
}

impl<P: Addressable> Addressable for Named<P> {
    fn oid(&self) -> Oid {
        let inner_oid = self.1.oid();
        let combined = format!("named:{}:{}", self.0, inner_oid);
        Oid::hash(combined.as_bytes())
    }
}

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

    #[derive(Debug, Clone, PartialEq)]
    struct FocusOptic(u32);

    impl Addressable for FocusOptic {
        fn oid(&self) -> Oid {
            Oid::hash(&self.0.to_le_bytes())
        }
    }

    #[test]
    fn named_wraps_optic() {
        let named = Named("focus", FocusOptic(1));
        assert_eq!(named.name(), "focus");
        assert_eq!(named.inner(), &FocusOptic(1));
    }

    #[test]
    fn named_oid_includes_name() {
        let a = Named("focus", FocusOptic(1));
        let b = Named("project", FocusOptic(1));
        // Same inner optic, different name → different OID
        assert_ne!(a.oid(), b.oid());
    }

    #[test]
    fn named_same_name_same_optic_same_oid() {
        let a = Named("focus", FocusOptic(1));
        let b = Named("focus", FocusOptic(1));
        assert_eq!(a.oid(), b.oid());
    }

    #[test]
    fn named_different_optic_different_oid() {
        let a = Named("focus", FocusOptic(1));
        let b = Named("focus", FocusOptic(2));
        assert_ne!(a.oid(), b.oid());
    }

    // --- #[derive(Prism)] tests ---

    #[derive(prismqueer_projections::Prism)]
    #[oid("@test")]
    struct TestNamed {
        _value: u32,
    }

    #[test]
    fn derived_named_has_oid() {
        let t = TestNamed { _value: 42 };
        let oid = t.oid();
        assert!(!oid.is_dark());
    }

    #[test]
    fn derived_named_display() {
        let t = TestNamed { _value: 42 };
        assert_eq!(format!("{}", t), "@test");
    }

    #[test]
    fn derived_named_oid_deterministic() {
        let a = TestNamed { _value: 1 };
        let b = TestNamed { _value: 2 };
        // Same @oid string → same Oid (the oid comes from the name, not the value)
        assert_eq!(a.oid(), b.oid());
    }

    #[derive(prismqueer_projections::Prism)]
    #[oid("@wrapper")]
    struct TestWrapper {
        #[prism(inner)]
        _inner: crate::Crystal<u32>,
        _extra: String,
    }

    #[test]
    fn derived_named_with_prism_inner_display() {
        let w = TestWrapper {
            _inner: crate::Crystal(42, crate::Luminosity::Light),
            _extra: "test".into(),
        };
        assert_eq!(format!("{}", w), "@wrapper");
    }

    #[test]
    fn derived_named_with_prism_inner_oid() {
        let w = TestWrapper {
            _inner: crate::Crystal(42, crate::Luminosity::Light),
            _extra: "test".into(),
        };
        assert!(!w.oid().is_dark());
    }

    // --- Cascade tests: three-level derive(Prism) ---

    #[derive(prismqueer_projections::Prism)]
    #[oid("@test/simple")]
    struct Simple;

    #[derive(Clone, prismqueer_projections::Prism)]
    #[oid("@test/with-inner")]
    struct WithInner {
        #[prism(inner)]
        _inner: crate::Crystal<u32>,
        _extra: String,
    }

    #[derive(prismqueer_projections::Prism)]
    #[oid("@test/nested")]
    struct Nested {
        #[prism(inner)]
        _inner: WithInner,
    }

    #[test]
    fn derive_cascade_oids_differ() {
        let s = Simple;
        let w = WithInner {
            _inner: crate::Crystal(42, crate::Luminosity::Light),
            _extra: "x".into(),
        };
        let n = Nested { _inner: w.clone() };

        // Different @oid strings → different Oids
        assert_ne!(s.oid(), w.oid());
        assert_ne!(w.oid(), n.oid());
    }

    #[test]
    fn derive_cascade_display() {
        assert_eq!(format!("{}", Simple), "@test/simple");
        assert_eq!(
            format!(
                "{}",
                WithInner {
                    _inner: crate::Crystal(42, crate::Luminosity::Light),
                    _extra: "x".into(),
                }
            ),
            "@test/with-inner"
        );
        assert_eq!(
            format!(
                "{}",
                Nested {
                    _inner: WithInner {
                        _inner: crate::Crystal(42, crate::Luminosity::Light),
                        _extra: "x".into(),
                    },
                }
            ),
            "@test/nested"
        );
    }

    #[test]
    fn derive_cascade_three_levels() {
        // Three nested derives. Each one is a Prism.
        // The Oid at each level is derived from the @oid string, not the inner value.
        let n = Nested {
            _inner: WithInner {
                _inner: crate::Crystal(42, crate::Luminosity::Light),
                _extra: "x".into(),
            },
        };

        // The Oid is from "@test/nested", not from the inner Crystal
        let oid = n.oid();
        assert!(!oid.is_dark());

        // Same @oid string → same Oid regardless of inner value
        let n2 = Nested {
            _inner: WithInner {
                _inner: crate::Crystal(99, crate::Luminosity::Dark),
                _extra: "y".into(),
            },
        };
        assert_eq!(n.oid(), n2.oid()); // same @oid string
    }

    #[test]
    fn derive_vs_hand_written_same_oid() {
        // Hand-written impl
        struct HandWritten;
        impl Addressable for HandWritten {
            fn oid(&self) -> Oid {
                Oid::hash("@test/simple".as_bytes())
            }
        }
        // Derive-generated
        let derived = Simple;
        let hand = HandWritten;
        assert_eq!(derived.oid(), hand.oid());
    }

    #[test]
    fn derive_vs_hand_written_same_display() {
        assert_eq!(format!("{}", Simple), "@test/simple");
    }

    #[test]
    fn benchmark_derive_prism_hash() {
        // Warm up
        let _ = Simple.oid();

        let start = std::time::Instant::now();
        for _ in 0..1_000 {
            let _ = Simple.oid();
        }
        let elapsed = start.elapsed();
        eprintln!("--- derive(Prism) oid: 1k calls in {:?} ---", elapsed);
        // Each call runs CoincidenceHash<3> (eigenvalue-based).
        // No LazyLock in the derive — each call recomputes the hash.
        // ~1ms per call is expected for the full coincidence detector pipeline.
    }

    // -----------------------------------------------------------------------
    // Optic field annotation tests
    // -----------------------------------------------------------------------

    #[test]
    fn lens_on_plain_field() {
        #[derive(prismqueer_projections::Prism)]
        #[oid("@test/lens")]
        struct Foo {
            #[lens]
            x: u32,
        }
        assert_eq!(Foo::optic_fields()[0].kind, crate::OpticKind::Lens);
        let mut foo = Foo { x: 42 };
        assert_eq!(*XLens::view(&foo), 42);
        XLens::set(&mut foo, 99);
        assert_eq!(foo.x, 99);
    }

    #[test]
    fn prism_on_option_field() {
        #[derive(prismqueer_projections::Prism)]
        #[oid("@test/prism")]
        struct Bar {
            #[prism]
            maybe: Option<String>,
        }
        assert_eq!(Bar::optic_fields()[0].kind, crate::OpticKind::Prism);
        let bar = Bar { maybe: None };
        assert!(MaybePrism::extract(&bar).is_none());

        let mut bar2 = Bar { maybe: None };
        MaybePrism::review(&mut bar2, "hello".to_string());
        assert_eq!(MaybePrism::extract(&bar2), Some(&"hello".to_string()));
    }

    #[test]
    fn traversal_on_vec_field() {
        #[derive(prismqueer_projections::Prism)]
        #[oid("@test/traversal")]
        struct Baz {
            #[traversal]
            items: Vec<i32>,
        }
        assert_eq!(Baz::optic_fields()[0].kind, crate::OpticKind::Traversal);
        let baz = Baz {
            items: vec![1, 2, 3],
        };
        assert_eq!(ItemsTraversal::traverse(&baz).len(), 3);
    }

    #[test]
    fn traversal_mut_access() {
        #[derive(prismqueer_projections::Prism)]
        #[oid("@test/traversal-mut")]
        struct Quux {
            #[traversal]
            vals: Vec<u32>,
        }
        let mut q = Quux { vals: vec![10, 20] };
        ValsTraversal::traverse_mut(&mut q).push(30);
        ValsTraversal::traverse_mut(&mut q).push(40);
        assert_eq!(q.vals.len(), 4);
    }

    #[test]
    fn iso_on_field() {
        #[derive(prismqueer_projections::Prism)]
        #[oid("@test/iso")]
        struct IsoTest {
            #[iso]
            value: f64,
        }
        assert_eq!(IsoTest::optic_fields()[0].kind, crate::OpticKind::Iso);
        let mut t = IsoTest { value: 3.14 };
        assert_eq!(*ValueIso::forward(&t), 3.14);
        ValueIso::backward(&mut t, 2.72);
        assert_eq!(t.value, 2.72);
    }

    #[test]
    fn composition_table() {
        use crate::OpticKind::*;
        assert_eq!(Lens.compose(Lens), Lens);
        assert_eq!(Lens.compose(Prism), Prism);
        assert_eq!(Prism.compose(Traversal), Traversal);
        assert_eq!(Iso.compose(Lens), Lens);
        assert_eq!(Fold.compose(Lens), Fold);
    }

    #[test]
    fn optic_fields_metadata() {
        #[derive(prismqueer_projections::Prism)]
        #[oid("@multi")]
        struct Multi {
            #[lens]
            a: u32,
            #[prism]
            b: Option<u32>,
            #[traversal]
            c: Vec<u32>,
        }
        let fields = Multi::optic_fields();
        assert_eq!(fields.len(), 3);
        assert_eq!(fields[0].name, "a");
        assert_eq!(fields[0].kind, crate::OpticKind::Lens);
        assert_eq!(fields[1].name, "b");
        assert_eq!(fields[1].kind, crate::OpticKind::Prism);
        assert_eq!(fields[2].name, "c");
        assert_eq!(fields[2].kind, crate::OpticKind::Traversal);
    }

    #[test]
    fn mixed_annotated_and_unannotated() {
        #[derive(prismqueer_projections::Prism)]
        #[oid("@test/mixed")]
        struct Mixed {
            #[lens]
            visible: u32,
            _hidden: String,
        }
        let fields = Mixed::optic_fields();
        assert_eq!(fields.len(), 1, "only annotated fields appear");
        assert_eq!(fields[0].name, "visible");
    }

    #[test]
    fn prism_inner_still_works() {
        // #[prism(inner)] should still be accepted without generating optic accessors
        #[derive(prismqueer_projections::Prism)]
        #[oid("@test/inner")]
        struct WithInner {
            #[prism(inner)]
            _inner: crate::Crystal<u32>,
        }
        // No optic_fields generated (no bare #[prism] annotation)
        let w = WithInner {
            _inner: crate::Crystal(42, crate::Luminosity::Light),
        };
        assert_eq!(format!("{}", w), "@test/inner");
    }

    #[test]
    fn lens_view_returns_reference() {
        #[derive(prismqueer_projections::Prism)]
        #[oid("@test/ref")]
        struct RefTest {
            #[lens]
            name: String,
        }
        let t = RefTest {
            name: "hello".to_string(),
        };
        let r: &String = NameLens::view(&t);
        assert_eq!(r, "hello");
    }
}