connections 0.1.0

Galois connections as first-class values: lawful numeric casts, Q-format / IEEE / time ladders
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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
//! Galois-connection core: the [`Conn<A, B, K>`] type, the kind
//! markers [`L`] and [`R`], the [`ConnL`] / [`ConnR`] / [`ConnK`]
//! capability traits for adjoint connections, and the operations on
//! a `Conn` (kind-gated accessors and lifters, plus two-sided
//! rounding helpers on [`ConnK`]).
//!
//! ## Representation
//!
//! A Galois connection is a pair of monotone functions `f: A → B`
//! and `g: B → A`, such that `f(a) ≤ b ⟺  a ≤ g(b)` for all pairs
//! of inputs `(a, b)`. A picture is worth 1000 words:
//!
//! ```text
//! A  ←  B
//!    g
//!
//! 3  ↔  3
//!
//!
//! 2  ←  2
//!//!//! 1  →  1
//!
//!    f
//! A  →  B
//! ```
//!
//! Each row is a `(a, b)` pair; arrows show the action of `f` (A → B,
//! bottom legend) and `g` (B → A, top legend). Lone arrows mark
//! single function mappings (`f(1) = 1`, `g(2) = 2`); the `↔` marks a
//! matched pair where both functions agree (`f(3) = 3`, `g(3) = 3`); the
//! adjacent `↰ ↳` glyphs depict the *lens* `f(2) ↔ g(1)` — two
//! non-crossing arrows `↰ ↳` between rows 2 and 1 are the 'geometric
//! signature' of adjointness.
//!
//! [`Conn<A, B, K>`] holds *exactly two* fn-pointer fields, and the
//! kind tag `K` (defaulting to [`L`]) determines which adjoint role
//! each field plays. Kind-specific inherent methods enforce the
//! discipline at the type level: calling `.floor(...)` on an
//! `Conn<_, _, L>` is a compile error (the method only exists on
//! `Conn<_, _, R>`); same for `.ceil(...)` on `R`.
//!
//! An **adjoint triple** `f ⊣ g ⊣ h` is two adjunctions sharing the
//! middle function `g`: an L-Galois pair `(f, g)` and an R-Galois pair
//! `(g, h)` over the same `(A, B)`. Triples are *not* a third kind of
//! `Conn`; they are zero-sized marker types implementing both the
//! [`ConnL`] and [`ConnR`] capability traits (and so [`ConnK`], the
//! super-trait `ConnL + ConnR`). The "third function" — the adjoint
//! that distinguishes a triple from a one-sided Conn — lives as a
//! free function in module scope, referenced from the marker's
//! projections; no struct in the crate stores three fns.
//!
//! Each capability trait carries exactly one method: the polarity
//! **swap**. `ConnL::swap_l` reads the marker's L-pair over the
//! reversed `(B, A)` as an R-Galois value; `ConnR::swap_r` is the
//! dual. `Conn` *values* do not implement the traits — a value already
//! is its own view, and its swap is the inherent `const fn`
//! ([`Conn::swap_l`] / [`Conn::swap_r`]). One name, disjoint
//! receivers, no duplication. Markers also expose the swaps as
//! inherent `const fn`s (emitted by [`conn_k!`](crate::conn_k) and
//! friends), which is what `const` composition uses:
//! `compose!(U032BE04.swap_r(), ...)`. The direct views are the
//! [`ConnL::view_l`] / [`ConnR::view_r`] trait methods — each the
//! marker's swap methods composed into a round trip, law-guaranteed
//! equal to the raw double swap (see `prop::conn::swap_involutive_l`).
//!
//! Two-sided operations ([`round`], [`truncate`], [`interval`],
//! [`median`], plus the `1` / `2` lifters) bind on [`ConnK`]
//! (`= ConnL + ConnR`), so they are callable only on triple markers,
//! not on one-sided Conns. One-sided accessors (`ceil` / `upper` /
//! `floor` / `lower` and their lifters) are kind-gated inherent
//! methods on the value type.

use core::cmp::Ordering;
use core::marker::PhantomData;
use core::ops::Sub;

use crate::interval::Interval;

// ── Kind markers ─────────────────────────────────────────────────────

mod kind {
    mod sealed {
        pub trait Sealed {}
    }

    /// Sealed marker trait: the kind universe is exactly `{L, R}`.
    pub trait Kind: sealed::Sealed + Copy + 'static {}

    /// Left-Galois kind tag.
    #[derive(Copy, Clone, Debug)]
    pub struct L;
    /// Right-Galois kind tag.
    #[derive(Copy, Clone, Debug)]
    pub struct R;

    impl sealed::Sealed for L {}
    impl Kind for L {}
    impl sealed::Sealed for R {}
    impl Kind for R {}
}

pub use kind::{Kind, L, R};

// ── Conn struct ──────────────────────────────────────────────────────

/// A Galois connection between preordered sets `A` and `B`, kind-tagged
/// by `K` (defaults to [`L`]).
///
/// Holds two `fn`-pointer fields whose adjoint roles depend on the kind:
///
/// | Kind  | `f`              | `g`              | Galois law                |
/// |-------|------------------|------------------|---------------------------|
/// | [`L`] | lower (`ceil`)   | upper (`upper`)  | `f(a) ≤ b ⟺ a ≤ g(b)`     |
/// | [`R`] | upper (`floor`)  | lower (`lower`)  | `g(b) ≤ a ⟺ b ≤ f(a)`     |
pub struct Conn<A, B, K: Kind = L> {
    f: fn(A) -> B,
    g: fn(B) -> A,
    _k: PhantomData<fn() -> K>,
}

impl<A, B, K: Kind> Copy for Conn<A, B, K> {}
impl<A, B, K: Kind> Clone for Conn<A, B, K> {
    #[inline]
    fn clone(&self) -> Self {
        *self
    }
}

// `PhantomData<fn() -> K>` is invariant in `K` but is universally
// `Eq` / `Hash`; the only state distinguishing two `Conn` values is the
// `(f, g)` fn-pointer pair. Fn-pointer equality is reference-identity
// on the same monomorphisation.
impl<A, B, K: Kind> PartialEq for Conn<A, B, K> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        core::ptr::fn_addr_eq(self.f, other.f) && core::ptr::fn_addr_eq(self.g, other.g)
    }
}
impl<A, B, K: Kind> Eq for Conn<A, B, K> {}

impl<A, B, K: Kind> core::fmt::Debug for Conn<A, B, K> {
    fn fmt(&self, fmtr: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            fmtr,
            "Conn<{}{}, {}>",
            core::any::type_name::<A>(),
            core::any::type_name::<B>(),
            core::any::type_name::<K>(),
        )
    }
}

// ── Constructors and inherent ops on L-Conns ─────────────────────────

impl<A, B> Conn<A, B, L> {
    /// Construct a left-Galois connection `ceil ⊣ inner`.
    #[inline]
    pub const fn new_l(ceil: fn(A) -> B, inner: fn(B) -> A) -> Self {
        Conn {
            f: ceil,
            g: inner,
            _k: PhantomData,
        }
    }

    /// Slot-swap: `Conn<A, B, L> → Conn<B, A, R>`.
    ///
    /// The same `(f, g)` pair satisfies the R-Galois law over the
    /// swapped pair `(B, A)`. Zero-cost type-level relabel.
    #[inline]
    pub const fn swap_l(self) -> Conn<B, A, R> {
        Conn {
            f: self.g,
            g: self.f,
            _k: PhantomData,
        }
    }
}

impl<A: Copy, B: Copy> Conn<A, B, L> {
    /// Apply the lower adjoint (round-up): `a ↦ f(a)`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use connections::conn::ConnL;
    /// use connections::float::N5;
    /// use connections::core::f064::F064F032;
    ///
    /// let pi64 = N5::new(std::f64::consts::PI);
    /// let pi32 = N5::new(std::f32::consts::PI as f64);
    /// let pi32_err = pi32 - pi64;
    ///
    /// // The f32 ceiling of π is std::f32::consts::PI itself —
    /// // π's nearest f32 representation rounds up.
    /// assert_eq!(F064F032.ceil(pi64), N5::new(std::f32::consts::PI));
    /// // Widening the result back to f64 lands at pi32, which sits
    /// // exactly pi32_err above true π:
    /// assert_eq!(F064F032.upper(F064F032.ceil(pi64)) - pi64, pi32_err);
    /// ```
    #[inline]
    #[must_use]
    pub fn ceil(self, a: A) -> B {
        (self.f)(a)
    }

    /// Lift a unary endofunction over `A` into one over `B` through
    /// the L-pair: `b ↦ f(h(g(b)))`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use connections::conn::ConnL;
    /// use connections::float::N5;
    /// use connections::core::f064::F064F032;
    ///
    /// // ceil1 / floor1 / truncate1 share this closure shape: `2π − x`
    /// // in f64-precision lands strictly between two f32 grid points.
    /// // ceil1 unconditionally narrows up — to std::f32::consts::PI.
    /// let pi32 = N5::new(std::f32::consts::PI);
    /// let probe = |a| N5::new(2.0_f64) * N5::new(std::f64::consts::PI) - a;
    /// assert_eq!(
    ///     F064F032.ceil1(probe, pi32),
    ///     N5::new(std::f32::consts::PI),
    /// );
    /// ```
    #[inline]
    #[must_use]
    pub fn ceil1<H>(self, h: H, b: B) -> B
    where
        H: FnOnce(A) -> A,
    {
        (self.f)(h((self.g)(b)))
    }

    /// Lift a binary function over `A` through the L-pair.
    #[inline]
    #[must_use]
    pub fn ceil2<H>(self, h: H, b1: B, b2: B) -> B
    where
        H: FnOnce(A, A) -> A,
    {
        (self.f)(h((self.g)(b1), (self.g)(b2)))
    }

    /// Apply the upper adjoint (embedding): `b ↦ g(b)`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use connections::conn::ConnL;
    /// use connections::float::N5;
    /// use connections::core::f064::F064F032;
    ///
    /// let pi64 = N5::new(std::f64::consts::PI);
    /// // f32's nearest representation of π widened losslessly to f64.
    /// // Lossless ≠ precise: the value is still the f32 approximation.
    /// let pi32 = N5::new(std::f32::consts::PI as f64);
    /// // f32's rounding error for π — about +8.74e-8 (f32 rounds π up).
    /// // The same constant carries through every π-widening doctest below.
    /// let pi32_err = pi32 - pi64;
    ///
    /// // upper just widens; for F064F032 that's the f32 → f64 cast.
    /// assert_eq!(F064F032.upper(N5::new(std::f32::consts::PI)), pi32);
    /// // Equivalently, "f64 π plus f32's rounding error":
    /// assert_eq!(F064F032.upper(N5::new(std::f32::consts::PI)) - pi64, pi32_err);
    /// ```
    #[inline]
    #[must_use]
    pub fn upper(self, b: B) -> A {
        (self.g)(b)
    }

    /// Lift a unary endofunction over `B` into one over `A` through
    /// the L-pair: `a ↦ g(h(f(a)))`.
    #[inline]
    #[must_use]
    pub fn upper1<H>(self, h: H, a: A) -> A
    where
        H: FnOnce(B) -> B,
    {
        (self.g)(h((self.f)(a)))
    }

    /// Lift a binary function over `B` through the L-pair.
    #[inline]
    #[must_use]
    pub fn upper2<H>(self, h: H, a1: A, a2: A) -> A
    where
        H: FnOnce(B, B) -> B,
    {
        (self.g)(h((self.f)(a1), (self.f)(a2)))
    }

    /// Membership in the principal filter generated by `a`:
    /// `b ∈ filter_l(a) ⟺ ceil(a) ≤ b`.
    ///
    /// The principal filter generated by `a ∈ A` is the upward-closed
    /// set `{ b ∈ B : ceil(a) ≤ b }`. Since `ceil` is monotonic and
    /// every B-value above `ceil(a)` satisfies the L-Galois law for
    /// some A-value above `a`, this characterises the
    /// upward-closure on the B side.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use connections::float::N5;
    /// use connections::core::f064::F064F032;
    ///
    /// let l = F064F032.view_l();
    /// let pi64 = N5::new(std::f64::consts::PI);
    /// // The f32 ceiling of pi64 is std::f32::consts::PI; equality
    /// // witnesses the lower edge of the filter.
    /// assert!(l.filter_l(pi64, N5::new(std::f32::consts::PI)));
    /// // Anything strictly larger is also in the filter
    /// // (upward-closed):
    /// assert!(l.filter_l(pi64, N5::new(4.0_f32)));
    /// // Strictly smaller f32s are not.
    /// assert!(!l.filter_l(pi64, N5::new(3.0_f32)));
    /// ```
    #[inline]
    #[must_use]
    pub fn filter_l(self, a: A, b: B) -> bool
    where
        B: PartialOrd,
    {
        self.ceil(a) <= b
    }
}

// ── Constructors and inherent ops on R-Conns ─────────────────────────

impl<A, B> Conn<A, B, R> {
    /// Construct a right-Galois connection `inner ⊣ floor`.
    ///
    /// Argument order mirrors Haskell's `CastR`: `inner` (the lower
    /// adjoint `g: B → A`) first, `floor` (the upper adjoint
    /// `f: A → B`) second.
    #[inline]
    pub const fn new_r(inner: fn(B) -> A, floor: fn(A) -> B) -> Self {
        Conn {
            f: floor,
            g: inner,
            _k: PhantomData,
        }
    }

    /// Slot-swap: `Conn<A, B, R> → Conn<B, A, L>`.
    #[inline]
    pub const fn swap_r(self) -> Conn<B, A, L> {
        Conn {
            f: self.g,
            g: self.f,
            _k: PhantomData,
        }
    }
}

impl<A: Copy, B: Copy> Conn<A, B, R> {
    /// Apply the upper adjoint (round-down): `a ↦ f(a)`.
    #[inline]
    #[must_use]
    pub fn floor(self, a: A) -> B {
        (self.f)(a)
    }

    /// Lift a unary endofunction over `A` into one over `B` through
    /// the R-pair: `b ↦ f(h(g(b)))`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use connections::conn::ConnR;
    /// use connections::float::N5;
    /// use connections::core::f064::F064F032;
    ///
    /// // Same shared probe as ceil1 / truncate1: `2π − x` in f64
    /// // lands strictly between two f32 grid points. floor1
    /// // unconditionally narrows down — to one f32 ULP below
    /// // std::f32::consts::PI.
    /// let pi32 = N5::new(std::f32::consts::PI);
    /// let probe = |a| N5::new(2.0_f64) * N5::new(std::f64::consts::PI) - a;
    /// assert_eq!(
    ///     F064F032.floor1(probe, pi32),
    ///     N5::new(3.1415925_f32),
    /// );
    /// ```
    #[inline]
    #[must_use]
    pub fn floor1<H>(self, h: H, b: B) -> B
    where
        H: FnOnce(A) -> A,
    {
        (self.f)(h((self.g)(b)))
    }

    /// Lift a binary function over `A` through the R-pair.
    #[inline]
    #[must_use]
    pub fn floor2<H>(self, h: H, b1: B, b2: B) -> B
    where
        H: FnOnce(A, A) -> A,
    {
        (self.f)(h((self.g)(b1), (self.g)(b2)))
    }

    /// Apply the lower adjoint (embedding): `b ↦ g(b)`.
    #[inline]
    #[must_use]
    pub fn lower(self, b: B) -> A {
        (self.g)(b)
    }

    /// Lift a unary endofunction over `B` into one over `A` through
    /// the R-pair.
    #[inline]
    #[must_use]
    pub fn lower1<H>(self, h: H, a: A) -> A
    where
        H: FnOnce(B) -> B,
    {
        (self.g)(h((self.f)(a)))
    }

    /// Lift a binary function over `B` through the R-pair.
    #[inline]
    #[must_use]
    pub fn lower2<H>(self, h: H, a1: A, a2: A) -> A
    where
        H: FnOnce(B, B) -> B,
    {
        (self.g)(h((self.f)(a1), (self.f)(a2)))
    }

    /// Membership in the principal ideal generated by `a`:
    /// `b ∈ filter_r(a) ⟺ b ≤ floor(a)`.
    ///
    /// The principal ideal generated by `a ∈ A` is the
    /// downward-closed set `{ b ∈ B : b ≤ floor(a) }` — the dual
    /// of [`Conn::filter_l`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use connections::float::N5;
    /// use connections::core::f064::F064F032;
    ///
    /// let r = F064F032.view_r();
    /// let pi64 = N5::new(std::f64::consts::PI);
    /// // The f32 floor of pi64 is 3.1415925; that's the upper edge
    /// // of the ideal.
    /// assert!(r.filter_r(pi64, N5::new(3.1415925_f32)));
    /// // Anything smaller is also in the ideal (downward-closed):
    /// assert!(r.filter_r(pi64, N5::new(3.0_f32)));
    /// // The f32 ceiling (next f32 above) is not.
    /// assert!(!r.filter_r(pi64, N5::new(std::f32::consts::PI)));
    /// ```
    #[inline]
    #[must_use]
    pub fn filter_r(self, a: A, b: B) -> bool
    where
        B: PartialOrd,
    {
        b <= self.floor(a)
    }
}

// ── Identity ─────────────────────────────────────────────────────────

impl<X, K: Kind> Conn<X, X, K> {
    /// The identity connection: `f = g = id`. Kind-generic — the same
    /// body satisfies both Galois laws, so the identity exists directly
    /// at either polarity (`Conn::<X, X, R>::identity()` needs no swap
    /// workaround). `Conn<X, X>` infers `K = L` by the type default.
    #[inline]
    pub const fn identity() -> Self {
        const fn id_<X>(x: X) -> X {
            x
        }
        Conn {
            f: id_::<X>,
            g: id_::<X>,
            _k: PhantomData,
        }
    }
}

// ── ConnL / ConnR / ConnK capability traits ──────────────────────────

/// Capability trait: types carrying an `L`-Galois connection between
/// `A` and `B`, exposed through its polarity swap and a uniform
/// accessor API.
///
/// Implementors are the adjoint-triple markers (zero-sized unit
/// structs from [`conn_k!`](crate::conn_k) / [`iso!`](crate::iso) /
/// [`compose_k!`](crate::compose_k)) *and* one-sided `Conn<A, B, L>`
/// values (through the blanket impl below). The one required method,
/// [`swap_l`](ConnL::swap_l), is the categorical content: the marker's
/// L-pair `(f, g)` read over the swapped pair `(B, A)`, where it
/// satisfies the R-Galois law. Everything else —
/// [`view_l`](ConnL::view_l), [`ceil`](ConnL::ceil),
/// [`upper`](ConnL::upper), and the `*1`/`*2` lifters — is a provided
/// method routed through the L-view, so a marker answers `M.ceil(a)`
/// directly with no projection step.
///
/// The provided methods are **not** `const` (trait methods can't be on
/// stable Rust). In `const` position spell the view as the public
/// double swap `t.swap_l().swap_r()`, or call a marker's inherent
/// `const fn view_l()` / a value's inherent `const fn ceil()` — those
/// stay `const` and shadow the trait defaults on concrete receivers.
///
/// `Conn` *values* also implement this trait, but a value receiver
/// resolves `.ceil(a)` / `.swap_l()` to the inherent `const fn`
/// ([`Conn::swap_l`]) rather than the trait default — inherent methods
/// win method resolution — so const composition is unaffected.
///
/// Laws (`prop::conn`): the swaps are involutive up to fn-pointer
/// identity — `t.view_l()` agrees with a marker's inherent `const fn
/// view_l()`, and `c.swap_l().swap_r() == c` on values.
pub trait ConnL {
    /// The connection's source type.
    type A: Copy;
    /// The connection's target type.
    type B: Copy;

    /// The swapped L-view: the same pair over `(B, A)` in R polarity.
    /// The single required method; every other method defaults through
    /// it.
    fn swap_l(&self) -> Conn<Self::B, Self::A, R>;

    /// The direct L-view as a `Conn<A, B, L>` value. Fn-pointer-identical
    /// to a marker's inherent `const fn view_l()` by the swap-involution
    /// law (`prop::conn::swap_involutive_l`).
    #[inline]
    #[must_use]
    fn view_l(&self) -> Conn<Self::A, Self::B, L> {
        self.swap_l().swap_r()
    }

    /// Apply the lower adjoint (round-up) through the L-view: `a ↦ f(a)`.
    #[inline]
    #[must_use]
    fn ceil(&self, a: Self::A) -> Self::B {
        self.view_l().ceil(a)
    }

    /// Lift a unary endofunction over `A` through the L-pair:
    /// `b ↦ f(h(g(b)))`.
    #[inline]
    #[must_use]
    fn ceil1<H>(&self, h: H, b: Self::B) -> Self::B
    where
        H: FnOnce(Self::A) -> Self::A,
    {
        self.view_l().ceil1(h, b)
    }

    /// Lift a binary function over `A` through the L-pair.
    #[inline]
    #[must_use]
    fn ceil2<H>(&self, h: H, b1: Self::B, b2: Self::B) -> Self::B
    where
        H: FnOnce(Self::A, Self::A) -> Self::A,
    {
        self.view_l().ceil2(h, b1, b2)
    }

    /// Apply the upper adjoint (embedding) through the L-view: `b ↦ g(b)`.
    #[inline]
    #[must_use]
    fn upper(&self, b: Self::B) -> Self::A {
        self.view_l().upper(b)
    }

    /// Lift a unary endofunction over `B` through the L-pair:
    /// `a ↦ g(h(f(a)))`.
    #[inline]
    #[must_use]
    fn upper1<H>(&self, h: H, a: Self::A) -> Self::A
    where
        H: FnOnce(Self::B) -> Self::B,
    {
        self.view_l().upper1(h, a)
    }

    /// Lift a binary function over `B` through the L-pair.
    #[inline]
    #[must_use]
    fn upper2<H>(&self, h: H, a1: Self::A, a2: Self::A) -> Self::A
    where
        H: FnOnce(Self::B, Self::B) -> Self::B,
    {
        self.view_l().upper2(h, a1, a2)
    }
}

// One-sided `Conn` values join the capability traits so the same
// method surface works on values and markers alike. A value is only
// *one* of `ConnL` / `ConnR` (never both), so it never becomes `ConnK`
// — the two-sided helpers stay triple-only, which is correct. Value
// receivers still resolve `.ceil` / `.swap_l` to the inherent `const
// fn` (inherent wins method resolution), so const composition is
// untouched.
impl<A: Copy, B: Copy> ConnL for Conn<A, B, L> {
    type A = A;
    type B = B;
    #[inline]
    fn swap_l(&self) -> Conn<B, A, R> {
        Conn::swap_l(*self)
    }
}

/// Capability trait: types carrying an `R`-Galois connection between
/// `A` and `B`, exposed through its polarity swap and a uniform
/// accessor API. Counterpart to [`ConnL`]; the direct R-view is
/// [`view_r`](ConnR::view_r), and [`floor`](ConnR::floor) /
/// [`lower`](ConnR::lower) / the `*1`/`*2` lifters route through it, so
/// a marker answers `M.floor(a)` directly. In `const` position spell
/// the view as the public double swap `t.swap_r().swap_l()`, or call a
/// marker's inherent `const fn view_r()`.
pub trait ConnR {
    /// The connection's source type.
    type A: Copy;
    /// The connection's target type.
    type B: Copy;

    /// The swapped R-view: the same pair over `(B, A)` in L polarity.
    /// The single required method; every other method defaults through
    /// it.
    fn swap_r(&self) -> Conn<Self::B, Self::A, L>;

    /// The direct R-view as a `Conn<A, B, R>` value. Fn-pointer-identical
    /// to a marker's inherent `const fn view_r()` by the swap-involution
    /// law (`prop::conn::swap_involutive_r`).
    #[inline]
    #[must_use]
    fn view_r(&self) -> Conn<Self::A, Self::B, R> {
        self.swap_r().swap_l()
    }

    /// Apply the upper adjoint (round-down) through the R-view: `a ↦ f(a)`.
    #[inline]
    #[must_use]
    fn floor(&self, a: Self::A) -> Self::B {
        self.view_r().floor(a)
    }

    /// Lift a unary endofunction over `A` through the R-pair:
    /// `b ↦ f(h(g(b)))`.
    #[inline]
    #[must_use]
    fn floor1<H>(&self, h: H, b: Self::B) -> Self::B
    where
        H: FnOnce(Self::A) -> Self::A,
    {
        self.view_r().floor1(h, b)
    }

    /// Lift a binary function over `A` through the R-pair.
    #[inline]
    #[must_use]
    fn floor2<H>(&self, h: H, b1: Self::B, b2: Self::B) -> Self::B
    where
        H: FnOnce(Self::A, Self::A) -> Self::A,
    {
        self.view_r().floor2(h, b1, b2)
    }

    /// Apply the lower adjoint (embedding) through the R-view: `b ↦ g(b)`.
    #[inline]
    #[must_use]
    fn lower(&self, b: Self::B) -> Self::A {
        self.view_r().lower(b)
    }

    /// Lift a unary endofunction over `B` through the R-pair.
    #[inline]
    #[must_use]
    fn lower1<H>(&self, h: H, a: Self::A) -> Self::A
    where
        H: FnOnce(Self::B) -> Self::B,
    {
        self.view_r().lower1(h, a)
    }

    /// Lift a binary function over `B` through the R-pair.
    #[inline]
    #[must_use]
    fn lower2<H>(&self, h: H, a1: Self::A, a2: Self::A) -> Self::A
    where
        H: FnOnce(Self::B, Self::B) -> Self::B,
    {
        self.view_r().lower2(h, a1, a2)
    }
}

impl<A: Copy, B: Copy> ConnR for Conn<A, B, R> {
    type A = A;
    type B = B;
    #[inline]
    fn swap_r(&self) -> Conn<B, A, L> {
        Conn::swap_r(*self)
    }
}

/// Convenience super-trait: a type is a [`ConnK`] iff it implements
/// *both* [`ConnL`] and [`ConnR`] over the same `(A, B)`. Adjoint-
/// triple markers (and triple-shaped composed markers) implement
/// `ConnK` automatically via the blanket below; one-sided values
/// (`Conn<A, B, L>` and `Conn<A, B, R>`) do **not** — which is
/// correct, since a one-sided Conn isn't a triple.
///
/// The cross-trait equality `ConnR<A = <Self as ConnL>::A,
/// B = <Self as ConnL>::B>` is what makes the `(A, B)` pair *the
/// same* on both sides — without it, a `T: ConnL + ConnR` could
/// pair an `L`-side over `(i32, i64)` with an `R`-side over
/// `(i32, u32)` and still satisfy `ConnL + ConnR` separately. The
/// equality bound forbids that and is the type-level statement of
/// the functional dependency `T → (A, B)`.
pub trait ConnK: ConnL + ConnR<A = <Self as ConnL>::A, B = <Self as ConnL>::B> {
    /// Bracket of `x`: the closed interval `[lo, hi] ⊆ A` whose members
    /// share `x`'s B-cell. Method form of the free [`interval`] fn; see
    /// it for the `Empty`/`Closed` contract.
    #[inline]
    #[must_use]
    fn interval(&self, x: <Self as ConnL>::A) -> Interval<<Self as ConnL>::A>
    where
        <Self as ConnL>::A: PartialOrd,
    {
        interval(self, x)
    }

    /// Birkhoff median over a diagonal triple `A = (B, B)`. Method form
    /// of the free [`median`] fn; only callable on the diagonal markers
    /// (`N5Float`-shaped) it already required.
    #[inline]
    #[must_use]
    fn median(
        &self,
        x: <Self as ConnL>::B,
        y: <Self as ConnL>::B,
        z: <Self as ConnL>::B,
    ) -> <Self as ConnL>::B
    where
        Self: ConnL<A = (<Self as ConnL>::B, <Self as ConnL>::B)>,
    {
        median(self, x, y, z)
    }

    /// Round `x` to nearest, ties toward zero. Method form of [`round`].
    #[inline]
    #[must_use]
    fn round(&self, x: <Self as ConnL>::A) -> <Self as ConnL>::B
    where
        <Self as ConnL>::A: PartialOrd + Sub<Output = <Self as ConnL>::A> + From<u8>,
    {
        round(self, x)
    }

    /// Lift a unary `h: A → A`, rounded to nearest. Method form of
    /// [`round1`].
    #[inline]
    #[must_use]
    fn round1<H>(&self, h: H, x: <Self as ConnL>::B) -> <Self as ConnL>::B
    where
        <Self as ConnL>::A: PartialOrd + Sub<Output = <Self as ConnL>::A> + From<u8>,
        H: FnOnce(<Self as ConnL>::A) -> <Self as ConnL>::A,
    {
        round1(self, h, x)
    }

    /// Lift a binary `h: (A, A) → A`, rounded to nearest. Method form of
    /// [`round2`].
    #[inline]
    #[must_use]
    fn round2<H>(&self, h: H, x: <Self as ConnL>::B, y: <Self as ConnL>::B) -> <Self as ConnL>::B
    where
        <Self as ConnL>::A: PartialOrd + Sub<Output = <Self as ConnL>::A> + From<u8>,
        H: FnOnce(<Self as ConnL>::A, <Self as ConnL>::A) -> <Self as ConnL>::A,
    {
        round2(self, h, x, y)
    }

    /// Truncate `x` toward zero through the triple. Method form of
    /// [`truncate`].
    #[inline]
    #[must_use]
    fn truncate(&self, x: <Self as ConnL>::A) -> <Self as ConnL>::B
    where
        <Self as ConnL>::A: PartialOrd + From<u8>,
    {
        truncate(self, x)
    }

    /// Lift a unary `h: A → A`, truncated toward zero. Method form of
    /// [`truncate1`].
    #[inline]
    #[must_use]
    fn truncate1<H>(&self, h: H, x: <Self as ConnL>::B) -> <Self as ConnL>::B
    where
        <Self as ConnL>::A: PartialOrd + From<u8>,
        H: FnOnce(<Self as ConnL>::A) -> <Self as ConnL>::A,
    {
        truncate1(self, h, x)
    }

    /// Lift a binary `h: (A, A) → A`, truncated toward zero. Method form
    /// of [`truncate2`].
    #[inline]
    #[must_use]
    fn truncate2<H>(&self, h: H, x: <Self as ConnL>::B, y: <Self as ConnL>::B) -> <Self as ConnL>::B
    where
        <Self as ConnL>::A: PartialOrd + From<u8>,
        H: FnOnce(<Self as ConnL>::A, <Self as ConnL>::A) -> <Self as ConnL>::A,
    {
        truncate2(self, h, x, y)
    }
}
impl<T> ConnK for T where T: ConnL + ConnR<A = <T as ConnL>::A, B = <T as ConnL>::B> {}

// ── Two-sided helpers (bound on ConnK) ────────────────────────────────

/// Bracket of `x` under conn `t`: the closed interval `[lo, hi] ⊆ A`
/// of values sharing `x`'s B-cell.
///
/// Returns [`Interval::Empty`] when the **`ConnK` sandwich
/// inequality** `lo ≤ x ≤ hi` fails. The Galois laws give
/// `floor(x) ≤ ceil(x)` on the B-side, but lifting that back to
/// `A` requires the middle adjoint to be shared between the L-
/// and R-views, which the type system does not enforce: a user
/// can implement `ConnL` and `ConnR` independently with
/// incompatible widening functions. Genuinely partially-ordered
/// `A` (e.g. antichain pairs) can also produce incomparable
/// `lo` / `hi`. In either case the bracket cannot meaningfully
/// represent `x`'s `B`-cell, so we surface it as `Empty` rather
/// than fabricate a misleading `Closed`.
///
/// **Postcondition for `Closed` results**: `lo ≤ x ≤ hi`.
/// Downstream consumers (`round`, `bracket_contains_x`, etc.) may
/// rely on this without an extra runtime check.
///
/// # Examples
///
/// ```rust
/// use connections::interval::Interval;
/// use connections::conn::interval;
/// use connections::float::N5;
/// use connections::core::f064::F064F032;
///
/// // True π_f64 is bracketed by two adjacent f64 grid values that
/// // share an f32 cell; the bracket contains pi64.
/// let pi64 = N5::new(std::f64::consts::PI);
/// assert!(interval(&F064F032, pi64).contains(&pi64));
///
/// // An exact f32 grid value (pi32 widened back to f64) has a
/// // degenerate (singleton) bracket.
/// let pi32 = N5::new(std::f32::consts::PI as f64);
/// assert_eq!(
///     interval(&F064F032, pi32),
///     Interval::Closed { lo: pi32, hi: pi32 }
/// );
/// ```
#[inline]
#[must_use]
pub fn interval<T, A, B>(t: &T, x: A) -> Interval<A>
where
    T: ?Sized + ConnL<A = A, B = B> + ConnR<A = A, B = B>,
    A: Copy + PartialOrd,
    B: Copy,
{
    let lo = t.view_r().lower1(|b| b, x);
    let hi = t.view_l().upper1(|b| b, x);
    // Route through `Interval::new` defensively: a contract-broken
    // `PartialOrd` (non-transitive) could in principle satisfy
    // `lo ≤ x ∧ x ≤ hi` while `lo > hi`. The extra `partial_cmp`
    // is cheap and keeps `Interval::Closed`'s `lo ≤ hi` invariant
    // intact regardless of caller PartialOrd hygiene.
    if lo <= x && x <= hi {
        Interval::new(lo, hi)
    } else {
        Interval::Empty
    }
}

/// Round `x` to the nearest representable value across the triple,
/// with ties broken toward zero.
///
/// # Examples
///
/// ```rust
/// use connections::conn::ConnL;
/// use connections::conn::round;
/// use connections::float::N5;
/// use connections::core::f064::F064F032;
///
/// let pi64 = N5::new(std::f64::consts::PI);
/// let pi32 = N5::new(std::f32::consts::PI as f64);
/// let pi32_err = pi32 - pi64;
///
/// // Round-to-nearest f32 of π is std::f32::consts::PI — the f32
/// // value `(pi as f32)` would also produce.
/// assert_eq!(round(&F064F032, pi64), N5::new(std::f32::consts::PI));
/// // Widening the result back to f64 lands pi32_err above true π:
/// assert_eq!(F064F032.upper(round(&F064F032, pi64)) - pi64, pi32_err);
/// ```
#[inline]
#[must_use]
pub fn round<T, A, B>(t: &T, x: A) -> B
where
    T: ?Sized + ConnL<A = A, B = B> + ConnR<A = A, B = B>,
    A: Copy + PartialOrd + Sub<Output = A> + From<u8>,
    B: Copy,
{
    // `Closed` carries `lo ≤ x ≤ hi` as a postcondition (see
    // [`interval`]); `x - lo` and `hi - x` are non-negative for
    // any sensible `A: Sub`. `Empty` signals a malformed triple
    // or antichain endpoints — fall back to truncate.
    match interval(t, x) {
        Interval::Closed { lo, hi } => match (x - lo).partial_cmp(&(hi - x)) {
            Some(Ordering::Greater) => t.view_l().ceil(x),
            Some(Ordering::Less) => t.view_r().floor(x),
            _ => truncate(t, x),
        },
        Interval::Empty => truncate(t, x),
    }
}

/// Birkhoff median over a diagonal triple `T: ConnK` with `A = (B, B)`,
/// using the triple's L-view ceil as join and R-view floor as meet.
/// Also available as the [`ConnK::median`] method (`t.median(x, y, z)`).
///
/// # Examples
///
/// On a totally-ordered i32 lattice (`max`/`min`/diag), `median`
/// reduces to the standard 3-element numeric median:
///
/// ```rust
/// use connections::{conn_k, conn::median};
///
/// fn ceil_max(p: (i32, i32)) -> i32 { p.0.max(p.1) }
/// fn dup(x: i32) -> (i32, i32) { (x, x) }
/// fn floor_min(p: (i32, i32)) -> i32 { p.0.min(p.1) }
/// conn_k! {
///     OrdI32 : (i32, i32) => i32 {
///         ceil:  ceil_max,
///         inner: dup,
///         floor: floor_min,
///     }
/// }
///
/// fn main() {
///     assert_eq!(median(&OrdI32, 1, 2, 3), 2);
/// }
/// ```
///
/// On the partially-ordered N5 lattice over `N5<f32>`, an
/// incomparable pair (NaN vs finite) escalates `lub` to `+∞` and
/// `glb` to `-∞`; the formula then collapses to the median of the two
/// finite values:
///
/// ```rust
/// use connections::{conn_k, conn::median};
/// use connections::float::N5;
/// use core::cmp::Ordering;
///
/// fn lub(p: (N5<f32>, N5<f32>)) -> N5<f32> {
///     match p.0.partial_cmp(&p.1) {
///         Some(Ordering::Less | Ordering::Equal) => p.1,
///         Some(Ordering::Greater) => p.0,
///         None => N5::new(f32::INFINITY),
///     }
/// }
/// fn glb(p: (N5<f32>, N5<f32>)) -> N5<f32> {
///     match p.0.partial_cmp(&p.1) {
///         Some(Ordering::Less | Ordering::Equal) => p.0,
///         Some(Ordering::Greater) => p.1,
///         None => N5::new(f32::NEG_INFINITY),
///     }
/// }
/// fn diag(x: N5<f32>) -> (N5<f32>, N5<f32>) {
///     (x, x)
/// }
/// conn_k! {
///     N5Float : (N5<f32>, N5<f32>) => N5<f32> {
///         ceil:  lub,
///         inner: diag,
///         floor: glb,
///     }
/// }
///
/// fn main() {
///     let nan = N5::new(0.0_f32 / 0.0_f32);
///
///     // All finite — matches the standard numeric median.
///     assert_eq!(
///         median(&N5Float, N5::new(1.0_f32), N5::new(9.0_f32), N5::new(7.0_f32)),
///         N5::new(7.0_f32),
///     );
///
///     // NaN argument: incomparable, so the formula collapses to the
///     // median of the two finite values.
///     assert_eq!(
///         median(&N5Float, N5::new(1.0_f32), N5::new(9.0_f32), nan),
///         N5::new(9.0_f32),
///     );
/// }
/// ```
#[inline]
#[must_use]
pub fn median<T, A>(t: &T, x: A, y: A, z: A) -> A
where
    T: ?Sized + ConnL<A = (A, A), B = A> + ConnR<A = (A, A), B = A>,
    A: Copy,
{
    let join = |p: A, q: A| t.view_l().ceil((p, q));
    let meet = |p: A, q: A| t.view_r().floor((p, q));
    meet(meet(join(x, y), join(y, z)), join(z, x))
}

/// Lift a unary function `h: A → A` through the triple, rounded to
/// nearest with ties toward zero.
///
/// # Examples
///
/// ```rust
/// use connections::conn::round1;
/// use connections::float::N5;
/// use connections::core::f064::F064F032;
///
/// // One Newton step on sin's zero near π. std::f32::consts::PI is
/// // ~8.7e-8 above true π; a Newton step `x − tan(x)` in
/// // f64-precision converges to true π_f64. round1 then picks the
/// // closer f32 endpoint — std::f32::consts::PI itself.
/// let pi32 = N5::new(std::f32::consts::PI);
/// assert_eq!(
///     round1(&F064F032, |a| a - a.tan(), pi32),
///     N5::new(std::f32::consts::PI),
/// );
/// ```
#[inline]
#[must_use]
pub fn round1<T, A, B, H>(t: &T, h: H, x: B) -> B
where
    T: ?Sized + ConnL<A = A, B = B> + ConnR<A = A, B = B>,
    A: Copy + PartialOrd + Sub<Output = A> + From<u8>,
    B: Copy,
    H: FnOnce(A) -> A,
{
    round(t, h(t.view_l().upper(x)))
}

/// Lift a binary function `h: (A, A) → A` through the triple,
/// rounded to nearest with ties toward zero.
///
/// # Examples
///
/// ```rust
/// use connections::conn::round2;
/// use connections::float::N5;
/// use connections::core::f064::F064F032;
///
/// // Catastrophic cancellation example: `(x + y) − x` should be y, but
/// // at the largest odd-integer f32 (2^24 - 1) the sum already rounds
/// // away the small operand, and the answer collapses to 1.0 instead
/// // of 2.0. round2 lifts to f64, computes exactly, narrows once.
/// let max_odd = N5::new(16777215.0_f32);   // = 2^24 - 1
/// let two = N5::new(2.0_f32);
/// assert_eq!((16777215.0_f32 + 2.0_f32) - 16777215.0_f32, 1.0); // raw f32
/// assert_eq!(
///     round2(&F064F032, |a, b| (a + b) - a, max_odd, two),
///     N5::new(2.0_f32),
/// );
/// ```
#[inline]
#[must_use]
pub fn round2<T, A, B, H>(t: &T, h: H, x: B, y: B) -> B
where
    T: ?Sized + ConnL<A = A, B = B> + ConnR<A = A, B = B>,
    A: Copy + PartialOrd + Sub<Output = A> + From<u8>,
    B: Copy,
    H: FnOnce(A, A) -> A,
{
    let l = t.view_l();
    round(t, h(l.upper(x), l.upper(y)))
}

/// Truncate `x` toward zero through the triple: returns
/// `t.view_r().floor(x)` when `x ≥ 0`, otherwise
/// `t.view_l().ceil(x)`.
///
/// # Examples
///
/// ```rust
/// use connections::conn::truncate;
/// use connections::float::N5;
/// use connections::core::f064::F064F032;
///
/// // π > 0 → truncate-toward-zero takes the f32 floor; one f32 ULP
/// // below std::f32::consts::PI.
/// let pi = N5::new(std::f64::consts::PI);
/// assert_eq!(truncate(&F064F032, pi), N5::new(3.1415925_f32));
/// ```
#[inline]
#[must_use]
pub fn truncate<T, A, B>(t: &T, x: A) -> B
where
    T: ?Sized + ConnL<A = A, B = B> + ConnR<A = A, B = B>,
    A: Copy + PartialOrd + From<u8>,
    B: Copy,
{
    if x >= A::from(0) {
        t.view_r().floor(x)
    } else {
        t.view_l().ceil(x)
    }
}

/// Lift a unary function `h: A → A` through the triple, with the
/// result truncated toward zero.
///
/// We widen `x: B → A` via the L-view's `upper`, but `truncate` then
/// routes the positive branch through the R-view's `floor` and the
/// negative through the L-view's `ceil`. Choosing the L-view's
/// `upper` here is canonical: in any lawful triple, the L-view's
/// `g` field and the R-view's `g` field are both the same shared
/// middle adjoint, so widening through either view yields the same
/// value. We pick L by convention.
///
/// # Examples
///
/// ```rust
/// use connections::conn::truncate1;
/// use connections::float::N5;
/// use connections::core::f064::F064F032;
///
/// // truncate1 / floor1 / ceil1 share this closure shape: `2π − x`
/// // in f64-precision lands strictly between the f32 floor of π
/// // (3.1415925_f32) and the f32 ceiling (std::f32::consts::PI), so
/// // the three lifters narrow it to two distinct f32 values.
/// // truncate-toward-zero of a positive result == floor:
/// let pi32 = N5::new(std::f32::consts::PI);
/// let probe = |a| N5::new(2.0_f64) * N5::new(std::f64::consts::PI) - a;
/// assert_eq!(truncate1(&F064F032, probe, pi32), N5::new(3.1415925_f32));
/// ```
#[inline]
#[must_use]
pub fn truncate1<T, A, B, H>(t: &T, h: H, x: B) -> B
where
    T: ?Sized + ConnL<A = A, B = B> + ConnR<A = A, B = B>,
    A: Copy + PartialOrd + From<u8>,
    B: Copy,
    H: FnOnce(A) -> A,
{
    truncate(t, h(t.view_l().upper(x)))
}

/// Lift a binary function `h: (A, A) → A` through the triple, with
/// the result truncated toward zero.
///
/// # Examples
///
/// ```rust
/// use connections::conn::truncate2;
/// use connections::float::N5;
/// use connections::core::f064::F064F032;
///
/// // 2 · std::f32::consts::PI in f64 space, narrowed back to f32.
/// // 2π32 > 0, so truncate-toward-zero takes the f32 floor.
/// let pi32 = N5::new(std::f32::consts::PI);
/// assert_eq!(
///     truncate2(&F064F032, |a, b| a + b, pi32, pi32),
///     N5::new(6.2831855_f32),
/// );
/// ```
#[inline]
#[must_use]
pub fn truncate2<T, A, B, H>(t: &T, h: H, x: B, y: B) -> B
where
    T: ?Sized + ConnL<A = A, B = B> + ConnR<A = A, B = B>,
    A: Copy + PartialOrd + From<u8>,
    B: Copy,
    H: FnOnce(A, A) -> A,
{
    let l = t.view_l();
    truncate(t, h(l.upper(x), l.upper(y)))
}

// ── Composition macros ───────────────────────────────────────────────

/// Compose a chain of L-Conn paths into a single fresh `Conn<Src, Dst>`.
///
/// Variadic over two or more parents. The expansion uses non-capturing
/// closures referencing the parent paths so each closure coerces to
/// an `fn(_) -> _` pointer at the `Conn::new_l` call site.
#[macro_export]
macro_rules! compose_l {
    ($first:expr, $($rest:expr),+ $(,)?) => {
        $crate::conn::Conn::new_l(
            |a| $crate::compose_l!(@nest_f a; $first $(, $rest)+),
            |z| $crate::compose_l!(@nest_g z; $first $(, $rest)+),
        )
    };

    (@nest_f $x:expr; $last:expr) => { $last.ceil($x) };
    (@nest_f $x:expr; $first:expr $(, $rest:expr)+) => {
        $crate::compose_l!(@nest_f $first.ceil($x); $($rest),+)
    };

    (@nest_g $z:expr; $last:expr) => { $last.upper($z) };
    (@nest_g $z:expr; $first:expr $(, $rest:expr)+) => {
        $first.upper($crate::compose_l!(@nest_g $z; $($rest),+))
    };
}

/// Compose a chain of R-Conn expressions into a single fresh `Conn<Src, Dst, R>`.
#[macro_export]
macro_rules! compose_r {
    ($first:expr, $($rest:expr),+ $(,)?) => {
        $crate::conn::Conn::new_r(
            |z| $crate::compose_r!(@nest_g z; $first $(, $rest)+),
            |a| $crate::compose_r!(@nest_f a; $first $(, $rest)+),
        )
    };

    (@nest_f $x:expr; $last:expr) => { $last.floor($x) };
    (@nest_f $x:expr; $first:expr $(, $rest:expr)+) => {
        $crate::compose_r!(@nest_f $first.floor($x); $($rest),+)
    };

    (@nest_g $z:expr; $last:expr) => { $last.lower($z) };
    (@nest_g $z:expr; $first:expr $(, $rest:expr)+) => {
        $first.lower($crate::compose_r!(@nest_g $z; $($rest),+))
    };
}

/// Forwarding alias for [`compose_l!`](crate::compose_l) — mirrors the `K = L` default
/// of [`Conn`]. Use when composing L-side conns and you'd rather not
/// spell the side explicitly. Error spans may point at this
/// forwarder rather than [`compose_l!`](crate::compose_l) directly.
///
/// # Examples
///
/// ```rust,no_run
/// use connections::compose;
/// use connections::conn::Conn;
///
/// // Three-step compose: id ∘ id ∘ id = id (any Conn type works).
/// const ID_I32: Conn<i32, i32> = Conn::identity();
/// const COMPOSED: Conn<i32, i32> = compose!(ID_I32, ID_I32, ID_I32);
/// ```
#[macro_export]
macro_rules! compose {
    ($($t:tt)*) => { $crate::compose_l!($($t)*) };
}

/// Declaration-form macro: compose two adjoint-triple markers into a
/// fresh triple marker. The composed marker is a unit struct with
/// freshly-built `ConnL` and `ConnR` impls whose `conn_l` / `conn_r`
/// methods build the projection via [`compose_l!`](crate::compose_l) / [`compose_r!`](crate::compose_r)
/// over the parents' views.
///
/// ```
/// # use connections::compose_k;
/// # use connections::core::f032::F032U008;
/// # use connections::core::f064::F064F032;
/// # use connections::extended::Extended;
/// # use connections::float::{F032, F064};
/// // Compose `F064F032 : F064 ⇒ F032` with `F032U008 : F032 ⇒ Extended<u8>`
/// // into one fresh triple marker for the whole `F064 ⇒ Extended<u8>` chain.
/// compose_k!(Chain : F064 => F032 => Extended<u8> = F064F032, F032U008);
/// # let _ = Chain;
/// ```
#[macro_export]
macro_rules! compose_k {
    (
        $(#[$meta:meta])*
        $vis:vis $name:ident : $A:ty => $B:ty => $C:ty = $t1:path, $t2:path $(,)?
    ) => {
        $(#[$meta])*
        #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Default)]
        $vis struct $name;
        impl $name {
            /// The composed L-view. `const`-projectable: the closure
            /// coercion happens in a `const` item, the supported
            /// composition position.
            #[allow(dead_code)]
            #[inline]
            #[must_use]
            $vis const fn view_l(self) -> $crate::conn::Conn<$A, $C, $crate::conn::L> {
                const COMPOSED: $crate::conn::Conn<$A, $C, $crate::conn::L> =
                    $crate::compose_l!($t1.swap_l().swap_r(), $t2.swap_l().swap_r());
                COMPOSED
            }
            /// The composed R-view. `const`-projectable.
            #[allow(dead_code)]
            #[inline]
            #[must_use]
            $vis const fn view_r(self) -> $crate::conn::Conn<$A, $C, $crate::conn::R> {
                const COMPOSED: $crate::conn::Conn<$A, $C, $crate::conn::R> =
                    $crate::compose_r!($t1.swap_r().swap_l(), $t2.swap_r().swap_l());
                COMPOSED
            }
            /// The swapped composed L-view. `const`-projectable.
            #[allow(dead_code)]
            #[inline]
            #[must_use]
            $vis const fn swap_l(self) -> $crate::conn::Conn<$C, $A, $crate::conn::R> {
                self.view_l().swap_l()
            }
            /// The swapped composed R-view. `const`-projectable.
            #[allow(dead_code)]
            #[inline]
            #[must_use]
            $vis const fn swap_r(self) -> $crate::conn::Conn<$C, $A, $crate::conn::L> {
                self.view_r().swap_r()
            }
        }
        impl $crate::conn::ConnL for $name {
            type A = $A;
            type B = $C;
            #[inline]
            fn swap_l(&self) -> $crate::conn::Conn<$C, $A, $crate::conn::R> {
                // Path call binds the inherent `const fn swap_l` (inherent
                // wins over the trait default), avoiding infinite recursion
                // through the `&self`-receiver trait `view_l`.
                $name::swap_l(*self)
            }
        }
        impl $crate::conn::ConnR for $name {
            type A = $A;
            type B = $C;
            #[inline]
            fn swap_r(&self) -> $crate::conn::Conn<$C, $A, $crate::conn::L> {
                $name::swap_r(*self)
            }
        }
    };
}

/// Declaration-form macro: ship a new adjoint-triple marker from
/// three free-function paths `(ceil, inner, floor)`.
///
/// ```
/// # use connections::conn_k;
/// # use std::num::NonZeroI8;
/// # fn ceil(v: i8)  -> NonZeroI8 { NonZeroI8::new(if v == 0 { 1 } else { v }).unwrap() }
/// # fn floor(v: i8) -> NonZeroI8 { NonZeroI8::new(if v == 0 { -1 } else { v }).unwrap() }
/// # fn inner(nz: NonZeroI8) -> i8 { nz.get() }
/// // A lawful adjoint triple: `ceil` / `floor` sandwich 0 between
/// // `NonZero(+1)` and `NonZero(-1)`, and `inner` is the total
/// // embedding — exactly how `core::i008::I008N008` is built.
/// conn_k! {
///     pub I008N008 : i8 => NonZeroI8 {
///         ceil:  ceil,
///         inner: inner,
///         floor: floor,
///     }
/// }
/// # let _ = I008N008;
/// ```
#[macro_export]
macro_rules! conn_k {
    (
        $(#[$meta:meta])*
        $vis:vis $name:ident : $A:ty => $B:ty {
            ceil:  $ceil:expr,
            inner: $inner:expr,
            floor: $floor:expr $(,)?
        }
    ) => {
        $(#[$meta])*
        #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Default)]
        $vis struct $name;
        impl $name {
            /// The L-view `(ceil, inner)`. `const`-projectable, so the
            /// marker composes in `const` position.
            #[allow(dead_code)]
            #[inline]
            #[must_use]
            $vis const fn view_l(self) -> $crate::conn::Conn<$A, $B, $crate::conn::L> {
                $crate::conn::Conn::new_l($ceil, $inner)
            }
            /// The R-view `(inner, floor)`. `const`-projectable.
            #[allow(dead_code)]
            #[inline]
            #[must_use]
            $vis const fn view_r(self) -> $crate::conn::Conn<$A, $B, $crate::conn::R> {
                $crate::conn::Conn::new_r($inner, $floor)
            }
            /// The swapped L-view over the reversed pair.
            /// `const`-projectable.
            #[allow(dead_code)]
            #[inline]
            #[must_use]
            $vis const fn swap_l(self) -> $crate::conn::Conn<$B, $A, $crate::conn::R> {
                self.view_l().swap_l()
            }
            /// The swapped R-view over the reversed pair.
            /// `const`-projectable.
            #[allow(dead_code)]
            #[inline]
            #[must_use]
            $vis const fn swap_r(self) -> $crate::conn::Conn<$B, $A, $crate::conn::L> {
                self.view_r().swap_r()
            }
        }
        impl $crate::conn::ConnL for $name {
            type A = $A;
            type B = $B;
            #[inline]
            fn swap_l(&self) -> $crate::conn::Conn<$B, $A, $crate::conn::R> {
                // Inherent `const fn swap_l` (path call), not the trait
                // `view_l` default — see the compose_k! note above.
                $name::swap_l(*self)
            }
        }
        impl $crate::conn::ConnR for $name {
            type A = $A;
            type B = $B;
            #[inline]
            fn swap_r(&self) -> $crate::conn::Conn<$B, $A, $crate::conn::L> {
                $name::swap_r(*self)
            }
        }
    };
}

/// Declaration-form macro: ship a degenerate-Galois iso (lossless
/// bijection) from a single `(forward, back)` function pair.
///
/// Equivalent to [`conn_k!`](crate::conn_k) with `ceil = floor = forward`; the macro
/// name itself flags the bijection so the body fields read as
/// `forward` / `back` rather than `ceil` / `inner` / `floor`. Both
/// [`ConnL`] and [`ConnR`] are implemented; every iso law
/// (`galois_l`, `galois_r`, `floor_le_ceil`, `idempotent`, …) holds
/// trivially.
///
/// ```
/// # use connections::iso;
/// # use std::net::Ipv4Addr;
/// # fn u32_to_v4(x: u32) -> Ipv4Addr { Ipv4Addr::from(x) }
/// # fn v4_to_u32(a: Ipv4Addr) -> u32 { u32::from(a) }
/// iso! {
///     pub U032IPV4 : u32 => Ipv4Addr {
///         forward: u32_to_v4,
///         back:    v4_to_u32,
///     }
/// }
/// # let _ = U032IPV4;
/// ```
#[macro_export]
macro_rules! iso {
    (
        $(#[$meta:meta])*
        $vis:vis $name:ident : $A:ty => $B:ty {
            forward: $fwd:expr,
            back:    $bk:expr $(,)?
        }
    ) => {
        $crate::conn_k! {
            $(#[$meta])*
            $vis $name : $A => $B {
                ceil:  $fwd,
                inner: $bk,
                floor: $fwd,
            }
        }
    };
}

/// Declaration-form macro: ship a one-sided left-Galois `Conn`
/// (`ceil ⊣ inner`) as a `pub const` of type [`Conn<A, B>`].
///
/// Named-field syntax mirrors [`conn_k!`](crate::conn_k) / [`iso!`](crate::iso) and removes the
/// argument-order footgun on [`Conn::new_l`]: the field labels make
/// it impossible to swap `ceil` and `inner` accidentally (and the
/// `_l` / `_r` macro-name split prevents picking the wrong kind).
///
/// Unlike [`conn_k!`](crate::conn_k), this macro emits the `Conn` value directly —
/// not a marker struct with [`ConnL`] / [`ConnR`] impls — because no
/// adjoint triple exists for one-sided connections. Use [`conn_k!`](crate::conn_k)
/// when both `ceil` and `floor` are available and the inner
/// embedding is order-reflecting; use this macro when only the
/// left half of the adjunction holds.
///
/// ```
/// # use connections::conn_l;
/// # fn ceil(x: i16) -> i8 {
/// #     if x > i8::MAX as i16 { i8::MAX } else if x < i8::MIN as i16 { i8::MIN } else { x as i8 }
/// # }
/// # fn inner(x: i8) -> i16 { if x == i8::MAX { i16::MAX } else { x as i16 } }
/// // A lawful left-Galois narrowing: `ceil` saturates `i16` into `i8`
/// // and `inner` widens back with the source-side `MAX` fixup —
/// // exactly how `core::i016::I016I008` is built.
/// conn_l! {
///     pub I016I008 : i16 => i8 {
///         ceil:  ceil,
///         inner: inner,
///     }
/// }
/// # let _ = I016I008;
/// ```
#[macro_export]
macro_rules! conn_l {
    (
        $(#[$meta:meta])*
        $vis:vis $name:ident : $A:ty => $B:ty {
            ceil:  $ceil:expr,
            inner: $inner:expr $(,)?
        }
    ) => {
        $(#[$meta])*
        $vis const $name: $crate::conn::Conn<$A, $B> =
            $crate::conn::Conn::new_l($ceil, $inner);
    };
}

/// Declaration-form macro: ship a one-sided right-Galois `Conn`
/// (`inner ⊣ floor`) as a `pub const` of type [`Conn<A, B, R>`].
///
/// Named-field syntax mirrors [`conn_k!`](crate::conn_k) / [`iso!`](crate::iso) and removes the
/// argument-order footgun on [`Conn::new_r`] — whose positional
/// shape `(inner, floor)` (mirroring Haskell's `CastR`) is the
/// reverse of [`Conn::new_l`]'s `(ceil, inner)`. Field labels make
/// the order self-documenting.
///
/// ```
/// # use connections::conn_r;
/// # fn inner(x: i8) -> u8 { if x < 0 { 0 } else { x as u8 } }
/// # fn floor(x: u8) -> i8 { if x > i8::MAX as u8 { i8::MAX } else { x as i8 } }
/// // A lawful right-Galois cross-sign cast: `inner` clips `i8`'s
/// // negative half to `0`, and `floor` saturates `u8` above `i8::MAX`
/// // — exactly how `core::u008::U008I008` is built.
/// conn_r! {
///     pub U008I008 : u8 => i8 {
///         inner: inner,
///         floor: floor,
///     }
/// }
/// # let _ = U008I008;
/// ```
#[macro_export]
macro_rules! conn_r {
    (
        $(#[$meta:meta])*
        $vis:vis $name:ident : $A:ty => $B:ty {
            inner: $inner:expr,
            floor: $floor:expr $(,)?
        }
    ) => {
        $(#[$meta])*
        $vis const $name: $crate::conn::Conn<$A, $B, $crate::conn::R> =
            $crate::conn::Conn::new_r($inner, $floor);
    };
}

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

    // ── Conn type smoke test ─────────────────────────────────────────

    #[test]
    fn kind_default_l() {
        // K = L is the default, so `Conn<A,B>` ≡ `Conn<A,B,L>`.
        const _L: Conn<i64, i32> = Conn::new_l(|x| x as i32, |x| x as i64);
        const _R: Conn<i64, i32, R> = Conn::new_r(|x| x as i64, |x| x as i32);
    }

    // ── conn_k! macro instantiation ──────────────────────────────────

    const fn _id_i32_ceil(x: i32) -> i32 {
        x
    }
    const fn _id_i32_inner(x: i32) -> i32 {
        x
    }
    const fn _id_i32_floor(x: i32) -> i32 {
        x
    }

    crate::conn_k! {
        TripleIdI32 : i32 => i32 {
            ceil:  _id_i32_ceil,
            inner: _id_i32_inner,
            floor: _id_i32_floor,
        }
    }

    #[test]
    fn triple_marker_zero_sized() {
        assert_eq!(core::mem::size_of::<TripleIdI32>(), 0);
    }

    #[test]
    fn triple_uses_both_views() {
        // Reach for both views and confirm they round-trip through
        // the shared inner.
        assert_eq!(TripleIdI32.view_l().ceil(7_i32), 7_i32);
        assert_eq!(TripleIdI32.view_r().floor(7_i32), 7_i32);
        assert_eq!(TripleIdI32.view_l().upper(7_i32), 7_i32);
        assert_eq!(TripleIdI32.view_r().lower(7_i32), 7_i32);
    }

    // ── compose_k! macro instantiation ───────────────────────────────

    crate::conn_k! {
        TripleAdd1 : i32 => i32 {
            ceil:  _add1,
            inner: _sub1,
            floor: _add1,
        }
    }
    const fn _add1(x: i32) -> i32 {
        x.wrapping_add(1)
    }
    const fn _sub1(x: i32) -> i32 {
        x.wrapping_sub(1)
    }

    crate::compose_k! {
        ComposedI32 : i32 => i32 => i32 = TripleIdI32, TripleAdd1
    }

    // ── iso! macro instantiation ─────────────────────────────────────

    const fn _i32_to_u32(x: i32) -> u32 {
        x as u32
    }
    const fn _u32_to_i32(x: u32) -> i32 {
        x as i32
    }

    crate::iso! {
        IsoI32U32 : i32 => u32 {
            forward: _i32_to_u32,
            back:    _u32_to_i32,
        }
    }

    #[test]
    fn iso_marker_zero_sized() {
        assert_eq!(core::mem::size_of::<IsoI32U32>(), 0);
    }

    #[test]
    fn iso_floor_eq_ceil() {
        // iso! sets floor = ceil = forward, so both adjoints agree on
        // every input (the defining property of a degenerate Galois
        // iso).
        for x in [i32::MIN, -1, 0, 1, 42, i32::MAX] {
            assert_eq!(IsoI32U32.view_l().ceil(x), IsoI32U32.view_r().floor(x));
        }
    }

    #[test]
    fn iso_round_trip_both_directions() {
        for x in [i32::MIN, -1, 0, 1, 42, i32::MAX] {
            let y = IsoI32U32.view_l().ceil(x);
            assert_eq!(IsoI32U32.view_l().upper(y), x);
        }
        for y in [0_u32, 1, 42, u32::MAX] {
            let x = IsoI32U32.view_l().upper(y);
            assert_eq!(IsoI32U32.view_l().ceil(x), y);
        }
    }

    #[test]
    fn compose_triple_marker() {
        // Composed triple's L-view: ceil(x) = TripleAdd1.ceil(TripleIdI32.ceil(x)) = x + 1
        assert_eq!(ComposedI32.view_l().ceil(0_i32), 1_i32);
        // Composed triple's R-view: floor(x) = TripleAdd1.floor(TripleIdI32.floor(x)) = x + 1
        assert_eq!(ComposedI32.view_r().floor(0_i32), 1_i32);
    }

    // ── Variadic compose_l! chain (3 operands, const-context) ────────

    const ID_L: Conn<i32, i32> = Conn::identity();
    const COMPOSED_3WAY: Conn<i32, i32> = crate::compose_l!(ID_L, ID_L, ID_L);

    #[test]
    fn compose_l_three_arg_chain() {
        // id ∘ id ∘ id over the L-side stays identity. Proves the
        // variadic `:expr` arm parses with 3 operands and produces a
        // valid `const` expression.
        assert_eq!(COMPOSED_3WAY.ceil(42_i32), 42_i32);
        assert_eq!(COMPOSED_3WAY.upper(7_i32), 7_i32);
    }

    #[test]
    fn compose_alias_matches_compose_l() {
        // The bare `compose!` is a forwarder to `compose_l!`; both
        // shapes must produce the same const value.
        const VIA_ALIAS: Conn<i32, i32> = crate::compose!(ID_L, ID_L);
        const VIA_LEFT: Conn<i32, i32> = crate::compose_l!(ID_L, ID_L);
        assert_eq!(VIA_ALIAS.ceil(42_i32), VIA_LEFT.ceil(42_i32));
        assert_eq!(VIA_ALIAS.upper(7_i32), VIA_LEFT.upper(7_i32));
    }

    #[test]
    fn compose_alias_matches_compose_l_three_operands() {
        // Variadic forward — three operands through the alias must
        // match three operands through `compose_l!` directly.
        const VIA_ALIAS: Conn<i32, i32> = crate::compose!(ID_L, ID_L, ID_L);
        const VIA_LEFT: Conn<i32, i32> = crate::compose_l!(ID_L, ID_L, ID_L);
        assert_eq!(VIA_ALIAS.ceil(42_i32), VIA_LEFT.ceil(42_i32));
        assert_eq!(VIA_ALIAS.upper(7_i32), VIA_LEFT.upper(7_i32));
    }

    // ── conn_l! / conn_r! macro instantiation ────────────────────────

    const fn _i64_to_i32(x: i64) -> i32 {
        x as i32
    }
    const fn _i32_to_i64(x: i32) -> i64 {
        x as i64
    }

    crate::conn_l! {
        CONNLI64I32 : i64 => i32 {
            ceil:  _i64_to_i32,
            inner: _i32_to_i64,
        }
    }

    crate::conn_r! {
        CONNRI64I32 : i64 => i32 {
            inner: _i32_to_i64,
            floor: _i64_to_i32,
        }
    }

    #[test]
    fn conn_l_macro_expands_to_new_l() {
        // Hand-written reference and the macro-built const must agree
        // on both adjoint slots for representative inputs.
        const REF: Conn<i64, i32> = Conn::new_l(_i64_to_i32, _i32_to_i64);
        for a in [i64::MIN, -1, 0, 1, 42, i64::MAX] {
            assert_eq!(CONNLI64I32.ceil(a), REF.ceil(a));
        }
        for b in [i32::MIN, -1, 0, 1, 42, i32::MAX] {
            assert_eq!(CONNLI64I32.upper(b), REF.upper(b));
        }
    }

    #[test]
    fn conn_r_macro_expands_to_new_r() {
        // `Conn::new_r` argument order is `(inner, floor)` — the
        // mirror of `new_l`'s `(ceil, inner)`. The macro reorders for
        // the constructor; this test confirms slots match a hand-
        // written reference.
        const REF: Conn<i64, i32, R> = Conn::new_r(_i32_to_i64, _i64_to_i32);
        for a in [i64::MIN, -1, 0, 1, 42, i64::MAX] {
            assert_eq!(CONNRI64I32.floor(a), REF.floor(a));
        }
        for b in [i32::MIN, -1, 0, 1, 42, i32::MAX] {
            assert_eq!(CONNRI64I32.lower(b), REF.lower(b));
        }
    }

    // ── Trait smoke test: markers dispatch generically via swap ──────

    #[test]
    fn marker_traits_dispatch_via_swap() {
        // The traits carry exactly the swap; a generic consumer derives
        // the direct views via `view_l` / `view_r` (the law-guaranteed
        // double swap).
        conn_k! {
            SmokeI64I32 : i64 => i32 {
                ceil:  _i64_to_i32,
                inner: _i32_to_i64,
                floor: _i64_to_i32,
            }
        }
        fn use_as_conn_l<T: ConnL<A = i64, B = i32>>(t: &T, a: i64) -> i32 {
            t.view_l().ceil(a)
        }
        fn use_as_conn_r<T: ConnR<A = i64, B = i32>>(t: &T, a: i64) -> i32 {
            t.view_r().floor(a)
        }
        assert_eq!(use_as_conn_l(&SmokeI64I32, 42_i64), 42_i32);
        assert_eq!(use_as_conn_r(&SmokeI64I32, 42_i64), 42_i32);
    }

    // ── swap_l / swap_r involution proptests ─────────────────────────

    use proptest::prelude::*;

    const fn _double(x: i32) -> i64 {
        (x as i64).wrapping_mul(2)
    }
    const fn _halve(x: i64) -> i32 {
        (x / 2) as i32
    }
    const ROUND_TRIP_L: Conn<i32, i64> = Conn::new_l(_double, _halve);
    const ROUND_TRIP_R: Conn<i32, i64, R> = Conn::new_r(_halve, _double);

    proptest! {
        #[test]
        fn swap_round_trip_l(a: i32, b: i64) {
            // (swap_r ∘ swap_l)(c) preserves the fn pair on every input.
            let c = ROUND_TRIP_L;
            let c2: Conn<i32, i64> = c.swap_l().swap_r();
            prop_assert_eq!(c.ceil(a), c2.ceil(a));
            prop_assert_eq!(c.upper(b), c2.upper(b));
        }

        #[test]
        fn swap_round_trip_r(a: i32, b: i64) {
            let c = ROUND_TRIP_R;
            let c2: Conn<i32, i64, R> = c.swap_r().swap_l();
            prop_assert_eq!(c.floor(a), c2.floor(a));
            prop_assert_eq!(c.lower(b), c2.lower(b));
        }
    }
}