pax-runtime-api 0.39.1

Userland constructs used at the runtime API boundary of Pax Engine
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
// ------------------------------- Coercion rules ----------------------------------
// default coercion only allows a single type: the type expected
// custom coercion rules can be implemented by a type

use std::ops::Range;

use crate::{
    impl_default_coercion_rule,
    math::{Transform2, Vector2},
    Color, ColorChannel, Depth, Duration, Fill, GradientStop, LayoutRole, LightShape,
    LinearGradient, Material, MaterialParams, MeshGradient, MeshPoint, Numeric, Opacity, Paint,
    PathElement, PathSmoothing, PaxValue, Percent, Property, RadialGradient, Rotation, Size,
    Stroke, StrokeCap, StrokeJoin, Transform2D, UnitValue, Vector3,
};

// Default coercion rules:
// call Into::<first param>::into() on contents of second enum variant
impl_default_coercion_rule!(bool, PaxValue::Bool, true);

impl_default_coercion_rule!(u8, PaxValue::Numeric, true);
impl_default_coercion_rule!(u16, PaxValue::Numeric, true);
impl_default_coercion_rule!(u32, PaxValue::Numeric, true);
impl_default_coercion_rule!(u64, PaxValue::Numeric, true);

impl_default_coercion_rule!(i8, PaxValue::Numeric, true);
impl_default_coercion_rule!(i16, PaxValue::Numeric, true);
impl_default_coercion_rule!(i32, PaxValue::Numeric, true);
impl_default_coercion_rule!(i64, PaxValue::Numeric, true);

impl_default_coercion_rule!(f32, PaxValue::Numeric, true);
impl_default_coercion_rule!(f64, PaxValue::Numeric, true);

impl_default_coercion_rule!(isize, PaxValue::Numeric, true);
impl_default_coercion_rule!(usize, PaxValue::Numeric, true);

impl CoercionRules for LayoutRole {
    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        match value {
            PaxValue::Enum(contents) => {
                let (_, variant, args) = *contents;
                if !args.is_empty() {
                    return Err(format!(
                        "failed to coerce LayoutRole: expected no enum args, got {:?}",
                        args
                    ));
                }
                match variant.as_str() {
                    "Default" => Ok(LayoutRole::Default),
                    "Breakout" => Ok(LayoutRole::Breakout),
                    _ => Err(format!(
                        "failed to coerce LayoutRole: unknown enum variant {:?}",
                        variant
                    )),
                }
            }
            PaxValue::Option(o) => {
                if let Some(o) = *o {
                    LayoutRole::try_coerce(o)
                } else {
                    Err("failed to coerce LayoutRole".to_string())
                }
            }
            _ => Err("failed to coerce LayoutRole".to_string()),
        }
    }
}

/// Attempts to coerce a dynamic `PaxValue` into a concrete Rust type.
///
/// Coercion is intentionally broader than exact `ToPaxValue` conversion; for
/// example a `Color` can be coerced into a `Paint`.
pub trait CoercionRules
where
    Self: Sized + 'static,
{
    /// Attempts to coerce `value` into `Self`.
    fn try_coerce(value: PaxValue) -> Result<Self, String>;

    /// Opts appearance layers into scalar-to-singleton stack conversion.
    /// Ordinary vector values remain list-only.
    fn allows_singleton_stack() -> bool {
        false
    }

    /// Whether cloning `Self` preserves the semantics of converting that clone
    /// through `ToPaxValue` and back with `try_coerce`.
    ///
    /// Opt in only for exact, side-effect-free value roundtrips. In particular,
    /// shared mutable handles are not eligible when conversion snapshots their
    /// contents. Custom conversions conservatively use the default fallback.
    /// Composite implementations must check every field with
    /// [`super::is_typed_binding_safe`] so recursive types terminate safely.
    fn is_identity_roundtrip() -> bool {
        false
    }
}

/// Checks the opt-in value-roundtrip contract for typed one-way bindings.
/// Recursive type graphs conservatively fall back to conversion. This tracks
/// only the current capability check, never values or property lifetimes.
pub fn is_typed_binding_safe<T: CoercionRules>() -> bool {
    use std::{any::TypeId, cell::RefCell, collections::HashSet};
    thread_local! {
        static CHECKING: RefCell<HashSet<TypeId>> = RefCell::new(HashSet::new());
    }
    struct Check(TypeId);
    impl Drop for Check {
        fn drop(&mut self) {
            CHECKING.with(|checking| checking.borrow_mut().remove(&self.0));
        }
    }
    let id = TypeId::of::<T>();
    if !CHECKING.with(|checking| checking.borrow_mut().insert(id)) {
        return false;
    }
    let _check = Check(id);
    T::is_identity_roundtrip()
}

// #[allow(non_camel_case_types)]
// #[derive(Default, Clone, Serialize, Deserialize, Debug, PartialEq)]
// pub enum Color {
//     /// Models a color in the RGB space, with an alpha channel of 100%
//     rgb(ColorChannel, ColorChannel, ColorChannel),
//     /// Models a color in the RGBA space
//     rgba(ColorChannel, ColorChannel, ColorChannel, ColorChannel),

//     /// Models a color in the HSL space.
//     hsl(Rotation, ColorChannel, ColorChannel),
//     /// Models a color in the HSLA space.
//     hsla(Rotation, ColorChannel, ColorChannel, ColorChannel),

//     #[default]
//     SLATE,
//     GRAY,
//     ZINC,
//     NEUTRAL,
//     STONE,
//     RED,
//     ORANGE,
//     AMBER,
//     YELLOW,
//     LIME,
//     GREEN,
//     EMERALD,
//     TEAL,
//     CYAN,
//     SKY,
//     BLUE,
//     INDIGO,
//     VIOLET,
//     PURPLE,
//     FUCHSIA,
//     PINK,
//     ROSE,
//     BLACK,
//     WHITE,
//     TRANSPARENT,
//     NONE,
// }

impl CoercionRules for Color {
    fn is_identity_roundtrip() -> bool {
        true
    }

    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        match value {
            PaxValue::Color(color) => Ok(*color),
            PaxValue::Enum(contents) => {
                let (name, variant, mut args) = *contents;
                if name != "Color" {
                    return Err(format!(
                        "{:?} can't be coerced into a Color",
                        PaxValue::Enum(Box::new((name, variant, args)))
                    ));
                }
                match variant.as_str() {
                    "rgb" => Ok(Color::rgb(
                        ColorChannel::try_coerce(args.remove(0))?,
                        ColorChannel::try_coerce(args.remove(0))?,
                        ColorChannel::try_coerce(args.remove(0))?,
                    )),
                    "rgba" => Ok(Color::rgba(
                        ColorChannel::try_coerce(args.remove(0))?,
                        ColorChannel::try_coerce(args.remove(0))?,
                        ColorChannel::try_coerce(args.remove(0))?,
                        ColorChannel::try_coerce(args.remove(0))?,
                    )),
                    "hsl" => Ok(Color::hsl(
                        Rotation::try_coerce(args.remove(0))?,
                        ColorChannel::try_coerce(args.remove(0))?,
                        ColorChannel::try_coerce(args.remove(0))?,
                    )),
                    "hsla" => Ok(Color::hsla(
                        Rotation::try_coerce(args.remove(0))?,
                        ColorChannel::try_coerce(args.remove(0))?,
                        ColorChannel::try_coerce(args.remove(0))?,
                        ColorChannel::try_coerce(args.remove(0))?,
                    )),
                    "SLATE" => Ok(Color::SLATE),
                    "GRAY" => Ok(Color::GRAY),
                    "ZINC" => Ok(Color::ZINC),
                    "NEUTRAL" => Ok(Color::NEUTRAL),
                    "STONE" => Ok(Color::STONE),
                    "RED" => Ok(Color::RED),
                    "ORANGE" => Ok(Color::ORANGE),
                    "AMBER" => Ok(Color::AMBER),
                    "YELLOW" => Ok(Color::YELLOW),
                    "LIME" => Ok(Color::LIME),
                    "GREEN" => Ok(Color::GREEN),
                    "EMERALD" => Ok(Color::EMERALD),
                    "TEAL" => Ok(Color::TEAL),
                    "CYAN" => Ok(Color::CYAN),
                    "SKY" => Ok(Color::SKY),
                    "BLUE" => Ok(Color::BLUE),
                    "INDIGO" => Ok(Color::INDIGO),
                    "VIOLET" => Ok(Color::VIOLET),
                    "PURPLE" => Ok(Color::PURPLE),
                    "FUCHSIA" => Ok(Color::FUCHSIA),
                    "PINK" => Ok(Color::PINK),
                    "ROSE" => Ok(Color::ROSE),
                    "BLACK" => Ok(Color::BLACK),
                    "WHITE" => Ok(Color::WHITE),
                    "TRANSPARENT" => Ok(Color::TRANSPARENT),
                    "NONE" => Ok(Color::NONE),
                    _ => Err(format!(
                        "failed to convert to Color: unknown variant {:?}",
                        variant
                    )),
                }
            }
            PaxValue::Option(o) => {
                if let Some(o) = *o {
                    Color::try_coerce(o)
                } else {
                    Err("failed to convert to Color".to_string())
                }
            }
            _ => return Err(format!("{:?} can't be coerced into a Color", value)),
        }
    }
}

impl CoercionRules for PathElement {
    fn is_identity_roundtrip() -> bool {
        true
    }

    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        match value {
            PaxValue::PathElement(path_elem) => Ok(*path_elem),
            // Why is this needed? should never deserialize a path into this
            PaxValue::Enum(contents) => {
                let (name, variant, values) = *contents;
                if name == "PathElement" {
                    let mut values_itr = values.into_iter();
                    match variant.as_str() {
                        "Line" => Ok(PathElement::Line),
                        "Close" => Ok(PathElement::Close),
                        "Empty" => Ok(PathElement::Empty),
                        "Point" => Ok(PathElement::Point(
                            Size::try_coerce(values_itr.next().unwrap())?,
                            Size::try_coerce(values_itr.next().unwrap())?,
                        )),
                        "Quadratic" => Ok(PathElement::Quadratic(
                            Size::try_coerce(values_itr.next().unwrap())?,
                            Size::try_coerce(values_itr.next().unwrap())?,
                        )),
                        "Cubic" => Ok(PathElement::Cubic(
                            Size::try_coerce(values_itr.next().unwrap())?,
                            Size::try_coerce(values_itr.next().unwrap())?,
                            Size::try_coerce(values_itr.next().unwrap())?,
                            Size::try_coerce(values_itr.next().unwrap())?,
                        )),
                        _ => {
                            return Err(format!(
                                "failed to coerce PathElement: unknown enum variant: {:?}",
                                variant
                            ))
                        }
                    }
                } else {
                    return Err(format!(
                        "failed to coerce PathElement: enum name doesn't match"
                    ));
                }
            }
            _ => return Err(format!("failed to coerce PathElement: PaxValue not a path")),
        }
    }
}

// Paint is a type that other types (Color) can be coerced into, thus the default
// from to pax macro isn't enough (only translates directly back and forth, and returns
// an error if it contains any other type)
impl CoercionRules for Paint {
    fn try_coerce(pax_value: PaxValue) -> Result<Self, String> {
        Ok(match pax_value {
            PaxValue::Color(color) => Paint::Solid(*color),
            PaxValue::Enum(contents) => {
                let (scope, variant, args) = *contents;
                if scope == "Color" {
                    return Color::try_coerce(PaxValue::Enum(Box::new((scope, variant, args))))
                        .map(Paint::Solid);
                }
                if scope == "Fill" {
                    return Err("Fill paint constructors moved to Paint; Fill now describes an appearance layer".into());
                }
                if scope != "Paint" {
                    return Err(format!("expected Paint, received {scope}::{variant}"));
                }
                if matches!(
                    variant.as_str(),
                    "Solid" | "LinearGradient" | "RadialGradient" | "MeshGradient"
                ) && args.len() != 1
                {
                    return Err(format!("Paint::{variant} requires exactly one argument"));
                }
                match variant.as_str() {
                    "Blend" => {
                        if args.len() != 1 {
                            return Err("Paint::Blend requires one list of weighted paints".into());
                        }
                        Paint::blend(Vec::<(Paint, f64)>::try_coerce(
                            args.into_iter().next().unwrap(),
                        )?)
                    }
                    "Solid" => {
                        let color = Color::try_coerce(args.into_iter().next().unwrap())?;
                        Paint::Solid(color)
                    }
                    "MeshGradient" => Paint::MeshGradient(MeshGradient::try_coerce(
                        args.into_iter().next().unwrap(),
                    )?),
                    "LinearGradient" => {
                        let gradient =
                            LinearGradient::try_coerce(args.into_iter().next().unwrap())?;
                        Paint::LinearGradient(gradient)
                    }
                    "linearGradient" => Paint::LinearGradient(parse_linear_gradient_args(args)?),
                    "RadialGradient" => {
                        let gradient =
                            RadialGradient::try_coerce(args.into_iter().next().unwrap())?;
                        Paint::RadialGradient(gradient)
                    }
                    "radialGradient" => Paint::RadialGradient(parse_radial_gradient_args(args)?),
                    _ => {
                        return Err(format!(
                            "failed to coerce Paint: unknown enum variant {:?}",
                            variant
                        ))
                    }
                }
            }
            PaxValue::Option(o) => {
                if let Some(o) = *o {
                    Paint::try_coerce(o)?
                } else {
                    return Err(format!("failed to coerce Paint: can't coerce None"));
                }
            }
            _ => return Err(format!("{:?} can't be coerced into a Paint", pax_value)),
        })
    }
}

impl CoercionRules for MeshPoint {
    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        match value {
            PaxValue::Object(fields) => {
                if fields
                    .iter()
                    .any(|(key, _)| key != "position" && key != "color")
                {
                    return Err("mesh anchors accept only `position` and `color`".into());
                }
                let [position, color] = extract_options(["position", "color"], fields)?;
                let coordinates = Vec::<Size>::try_coerce(position)?;
                let [x, y]: [Size; 2] = coordinates
                    .try_into()
                    .map_err(|_| "mesh anchor position requires exactly two coordinates")?;
                Ok(Self {
                    position: (x, y),
                    color: Color::try_coerce(color)?,
                })
            }
            PaxValue::Option(value) => Self::try_coerce(value.ok_or("mesh anchor cannot be None")?),
            _ => Err("mesh anchor requires {position: [x, y], color: ...}".into()),
        }
    }
}

impl CoercionRules for MeshGradient {
    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        match value {
            PaxValue::Object(fields) => {
                if fields.iter().any(|(key, _)| key != "rows") {
                    return Err("mesh gradients accept only `rows`".into());
                }
                let [rows] = extract_options(["rows"], fields)?;
                Ok(Self {
                    rows: Vec::<Vec<MeshPoint>>::try_coerce(rows)?,
                })
            }
            PaxValue::Option(value) => {
                Self::try_coerce(value.ok_or("mesh gradient cannot be None")?)
            }
            _ => Err("mesh gradient requires {rows: ...}".into()),
        }
    }
}

impl CoercionRules for LinearGradient {
    fn try_coerce(pax_value: PaxValue) -> Result<Self, String> {
        Ok(match pax_value {
            PaxValue::Object(map) => {
                let [start, end, stops] = extract_options(["start", "end", "stops"], map)
                    .map_err(|e| format!("failed to convert to LinearGradient: {e}"))?;
                let (s1, s2) = match start {
                    PaxValue::Vec(vec) => {
                        let mut itr = vec.into_iter();
                        let s1 = Size::try_coerce(itr.next().unwrap())?;
                        let s2 = Size::try_coerce(itr.next().unwrap())?;
                        (s1, s2)
                    }
                    _ => return Err(format!("failed to coerce LinearGradient")),
                };

                let (e1, e2) = match end {
                    PaxValue::Vec(vec) => {
                        let mut itr = vec.into_iter();
                        let e1 = Size::try_coerce(itr.next().unwrap())?;
                        let e2 = Size::try_coerce(itr.next().unwrap())?;
                        (e1, e2)
                    }
                    _ => return Err(format!("failed to coerce LinearGradient")),
                };
                let stops = Vec::<GradientStop>::try_coerce(stops)?;
                LinearGradient {
                    start: (s1, s2),
                    end: (e1, e2),
                    stops,
                }
            }
            PaxValue::Enum(contents) => {
                let (_, variant, args) = *contents;
                match variant.as_str() {
                    "linearGradient" => parse_linear_gradient_args(args)?,
                    _ => return Err(format!("failed to coerce LinearGradient")),
                }
            }
            PaxValue::Option(o) => {
                if let Some(o) = *o {
                    LinearGradient::try_coerce(o)?
                } else {
                    return Err(format!("failed to coerce LinearGradient"));
                }
            }
            _ => {
                return Err(format!(
                    "{:?} can't be coerced into a LinearGradient",
                    pax_value
                ))
            }
        })
    }
}

impl CoercionRules for RadialGradient {
    fn try_coerce(pax_value: PaxValue) -> Result<Self, String> {
        Ok(match pax_value {
            PaxValue::Object(map) => {
                let [start, end, stops, radius] =
                    extract_options(["start", "end", "stops", "radius"], map)
                        .map_err(|e| format!("failed to convert to RadialGradient: {e}"))?;
                let (s1, s2) = match start {
                    PaxValue::Vec(vec) => {
                        let mut itr = vec.into_iter();
                        let s1 = Size::try_coerce(itr.next().unwrap())?;
                        let s2 = Size::try_coerce(itr.next().unwrap())?;
                        (s1, s2)
                    }
                    _ => {
                        return Err(format!("failed to coerce RadialGradient"));
                    }
                };

                let (e1, e2) = match end {
                    PaxValue::Vec(vec) => {
                        let mut itr = vec.into_iter();
                        let e1 = Size::try_coerce(itr.next().unwrap())?;
                        let e2 = Size::try_coerce(itr.next().unwrap())?;
                        (e1, e2)
                    }
                    _ => {
                        return Err(format!("failed to coerce RadialGradient"));
                    }
                };
                let radius = match radius {
                    PaxValue::Numeric(n) => n.to_float(),
                    _ => {
                        return Err(format!("failed to coerce RadialGradient"));
                    }
                };
                let stops = Vec::<GradientStop>::try_coerce(stops)?;
                RadialGradient {
                    start: (s1, s2),
                    end: (e1, e2),
                    radius,
                    stops,
                }
            }
            PaxValue::Enum(contents) => {
                let (_, variant, args) = *contents;
                match variant.as_str() {
                    "radialGradient" => parse_radial_gradient_args(args)?,
                    _ => return Err(format!("failed to coerce RadialGradient")),
                }
            }
            PaxValue::Option(o) => {
                if let Some(o) = *o {
                    RadialGradient::try_coerce(o)?
                } else {
                    return Err(format!("failed to coerce RadialGradient"));
                }
            }
            _ => {
                return Err(format!("failed to coerce RadialGradient"));
            }
        })
    }
}

impl CoercionRules for GradientStop {
    fn try_coerce(pax_value: PaxValue) -> Result<Self, String> {
        Ok(match pax_value {
            PaxValue::Object(map) => {
                let [position, color] = extract_options(["position", "color"], map)
                    .map_err(|e| format!("failed to convert to GradientStop: {e}"))?;
                let position = Size::try_coerce(position)?;
                let color = Color::try_coerce(color)?;
                GradientStop { position, color }
            }
            PaxValue::Enum(contents) => {
                let (_, variant, args) = *contents;
                match variant.as_str() {
                    "get" => {
                        let mut args = args.into_iter();
                        let color = Color::try_coerce(
                            args.next()
                                .ok_or_else(|| "failed to convert to GradientStop".to_string())?,
                        )?;
                        let position = Size::try_coerce(
                            args.next()
                                .ok_or_else(|| "failed to convert to GradientStop".to_string())?,
                        )?;
                        GradientStop { position, color }
                    }
                    _ => return Err(format!("failed to convert to GradientStop")),
                }
            }
            PaxValue::Option(o) => {
                if let Some(o) = *o {
                    GradientStop::try_coerce(o)?
                } else {
                    return Err(format!("failed to convert to GradientStop"));
                }
            }
            _ => {
                return Err(format!("failed to convert to GradientStop"));
            }
        })
    }
}

impl CoercionRules for Depth {
    fn try_coerce(pax_value: PaxValue) -> Result<Self, String> {
        Ok(match pax_value {
            PaxValue::Size(Size::Pixels(value)) => Depth(value),
            PaxValue::Size(Size::Percent(_)) | PaxValue::Percent(_) => {
                return Err("failed to coerce Depth: percent depth is not supported".to_string());
            }
            PaxValue::Size(Size::Combined(_, _)) => {
                return Err("failed to coerce Depth: combined depth is not supported".to_string());
            }
            PaxValue::Numeric(value) => Depth(value),
            PaxValue::Option(o) => {
                if let Some(o) = *o {
                    Depth::try_coerce(o)?
                } else {
                    return Err("failed to coerce Depth".to_string());
                }
            }
            _ => return Err(format!("{:?} can't be coerced into a Depth", pax_value)),
        })
    }
}

impl CoercionRules for Vector3 {
    fn try_coerce(pax_value: PaxValue) -> Result<Self, String> {
        Ok(match pax_value {
            PaxValue::Object(map) => {
                let [x, y, z] = extract_options(["x", "y", "z"], map)
                    .map_err(|e| format!("failed to convert to Vector3: {e}"))?;
                Vector3 {
                    x: f64::try_coerce(x)?,
                    y: f64::try_coerce(y)?,
                    z: f64::try_coerce(z)?,
                }
            }
            PaxValue::Vec(values) => {
                if values.len() != 3 {
                    return Err("failed to coerce Vector3: expected three values".to_string());
                }
                let mut values = values.into_iter();
                Vector3 {
                    x: f64::try_coerce(values.next().unwrap())?,
                    y: f64::try_coerce(values.next().unwrap())?,
                    z: f64::try_coerce(values.next().unwrap())?,
                }
            }
            PaxValue::Enum(contents) => {
                let (_, variant, values) = *contents;
                match variant.as_str() {
                    "new" => {
                        if values.len() != 3 {
                            return Err("failed to coerce Vector3::new".to_string());
                        }
                        let mut values = values.into_iter();
                        Vector3 {
                            x: f64::try_coerce(values.next().unwrap())?,
                            y: f64::try_coerce(values.next().unwrap())?,
                            z: f64::try_coerce(values.next().unwrap())?,
                        }
                    }
                    _ => {
                        return Err(format!(
                            "failed to coerce Vector3: unknown enum variant {:?}",
                            variant
                        ))
                    }
                }
            }
            PaxValue::Option(o) => {
                if let Some(o) = *o {
                    Vector3::try_coerce(o)?
                } else {
                    return Err("failed to coerce Vector3".to_string());
                }
            }
            _ => return Err(format!("{:?} can't be coerced into a Vector3", pax_value)),
        })
    }
}

impl CoercionRules for LightShape {
    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        match value {
            PaxValue::Enum(contents) => {
                let (_, variant, args) = *contents;
                if !args.is_empty() {
                    return Err(format!(
                        "failed to coerce LightShape: expected no enum args, got {:?}",
                        args
                    ));
                }
                match variant.as_str() {
                    "Point" => Ok(LightShape::Point),
                    "Directional" => Ok(LightShape::Directional),
                    _ => Err(format!(
                        "failed to coerce LightShape: unknown enum variant {:?}",
                        variant
                    )),
                }
            }
            PaxValue::Option(o) => {
                if let Some(o) = *o {
                    LightShape::try_coerce(o)
                } else {
                    Err("failed to coerce LightShape".to_string())
                }
            }
            _ => Err("failed to coerce LightShape".to_string()),
        }
    }
}

impl CoercionRules for MaterialParams {
    fn try_coerce(pax_value: PaxValue) -> Result<Self, String> {
        Ok(match pax_value {
            PaxValue::Object(map) => {
                let mut params = MaterialParams::default();
                for (key, value) in map {
                    match key.as_str() {
                        "ambient" => params.ambient = Property::new(f64::try_coerce(value)?),
                        "diffuse" => params.diffuse = Property::new(f64::try_coerce(value)?),
                        "specular" => params.specular = Property::new(f64::try_coerce(value)?),
                        "roughness" => params.roughness = Property::new(f64::try_coerce(value)?),
                        "metallic" => params.metallic = Property::new(f64::try_coerce(value)?),
                        "emissive" => params.emissive = Property::new(Color::try_coerce(value)?),
                        "emissive_intensity" | "emissiveIntensity" => {
                            params.emissive_intensity = Property::new(f64::try_coerce(value)?)
                        }
                        _ => {}
                    }
                }
                params
            }
            PaxValue::Option(o) => {
                if let Some(o) = *o {
                    MaterialParams::try_coerce(o)?
                } else {
                    return Err("failed to coerce MaterialParams".to_string());
                }
            }
            _ => {
                return Err(format!(
                    "{:?} can't be coerced into MaterialParams",
                    pax_value
                ))
            }
        })
    }
}

impl CoercionRules for Material {
    fn try_coerce(pax_value: PaxValue) -> Result<Self, String> {
        Ok(match pax_value {
            PaxValue::Object(map) => {
                Material::Lit(MaterialParams::try_coerce(PaxValue::Object(map))?)
            }
            PaxValue::Enum(contents) => {
                let (_, variant, args) = *contents;
                match variant.as_str() {
                    "Lit" | "custom" => {
                        let params = args
                            .into_iter()
                            .next()
                            .ok_or_else(|| "failed to coerce Material::custom".to_string())?;
                        Material::Lit(MaterialParams::try_coerce(params)?)
                    }
                    "Unlit" | "unlit" => Material::Unlit,
                    "Matte" | "matte" => Material::matte(),
                    "Glossy" | "glossy" => {
                        let specular = args
                            .into_iter()
                            .next()
                            .map(f64::try_coerce)
                            .transpose()?
                            .unwrap_or(0.28);
                        Material::glossy(specular)
                    }
                    "Metallic" | "metallic" => {
                        let metallic = args
                            .into_iter()
                            .next()
                            .map(f64::try_coerce)
                            .transpose()?
                            .unwrap_or(0.72);
                        Material::metallic(metallic)
                    }
                    "Emissive" | "emissive" => {
                        if args.len() != 2 {
                            return Err("failed to coerce Material::emissive".to_string());
                        }
                        let mut args = args.into_iter();
                        let color = Color::try_coerce(args.next().unwrap())?;
                        let intensity = f64::try_coerce(args.next().unwrap())?;
                        Material::emissive(color, intensity)
                    }
                    _ => {
                        return Err(format!(
                            "failed to coerce Material: unknown enum variant {:?}",
                            variant
                        ))
                    }
                }
            }
            PaxValue::Option(o) => {
                if let Some(o) = *o {
                    Material::try_coerce(o)?
                } else {
                    return Err("failed to coerce Material".to_string());
                }
            }
            _ => return Err(format!("{:?} can't be coerced into Material", pax_value)),
        })
    }
}

fn parse_gradient_point(value: PaxValue) -> Result<(Size, Size), String> {
    match value {
        PaxValue::Vec(vec) => {
            let mut itr = vec.into_iter();
            let x = Size::try_coerce(
                itr.next()
                    .ok_or_else(|| "failed to coerce gradient point".to_string())?,
            )?;
            let y = Size::try_coerce(
                itr.next()
                    .ok_or_else(|| "failed to coerce gradient point".to_string())?,
            )?;
            Ok((x, y))
        }
        _ => Err("failed to coerce gradient point".to_string()),
    }
}

fn parse_linear_gradient_args(args: Vec<PaxValue>) -> Result<LinearGradient, String> {
    if args.len() != 3 {
        return Err("failed to coerce Paint::linearGradient".to_string());
    }
    let mut args = args.into_iter();
    let start = parse_gradient_point(args.next().unwrap())?;
    let end = parse_gradient_point(args.next().unwrap())?;
    let stops = Vec::<GradientStop>::try_coerce(args.next().unwrap())?;
    Ok(LinearGradient { start, end, stops })
}

fn parse_radial_gradient_args(args: Vec<PaxValue>) -> Result<RadialGradient, String> {
    if args.len() != 4 {
        return Err("failed to coerce Paint::radialGradient".to_string());
    }
    let mut args = args.into_iter();
    let start = parse_gradient_point(args.next().unwrap())?;
    let end = parse_gradient_point(args.next().unwrap())?;
    let stops = Vec::<GradientStop>::try_coerce(args.next().unwrap())?;
    let radius = Numeric::try_coerce(args.next().unwrap())?.to_float();
    Ok(RadialGradient {
        start,
        end,
        radius,
        stops,
    })
}

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

    fn pct(value: i64) -> PaxValue {
        PaxValue::Percent(Percent(Numeric::I64(value)))
    }

    fn color(hex: &str) -> PaxValue {
        PaxValue::Color(Box::new(Color::from_hex(hex)))
    }

    #[test]
    fn coerces_color_helper_syntax() {
        let pax_value = PaxValue::Enum(Box::new((
            "Color".to_string(),
            "rgba".to_string(),
            vec![
                PaxValue::Numeric(255.into()),
                PaxValue::Numeric(224.into()),
                PaxValue::Numeric(162.into()),
                PaxValue::Numeric(255.into()),
            ],
        )));

        let color = Color::try_coerce(pax_value).expect("rgba helper syntax should coerce");
        assert_eq!(
            color,
            Color::rgba(
                ColorChannel::Integer(255),
                ColorChannel::Integer(224),
                ColorChannel::Integer(162),
                ColorChannel::Integer(255),
            )
        );
    }

    #[test]
    fn coerces_fill_linear_gradient_helper_syntax() {
        let pax_value = PaxValue::Enum(Box::new((
            "Paint".to_string(),
            "linearGradient".to_string(),
            vec![
                PaxValue::Vec(vec![pct(0), pct(50)]),
                PaxValue::Vec(vec![pct(100), pct(50)]),
                PaxValue::Vec(vec![
                    PaxValue::Enum(Box::new((
                        "GradientStop".to_string(),
                        "get".to_string(),
                        vec![color("ff00ffff"), pct(0)],
                    ))),
                    PaxValue::Enum(Box::new((
                        "GradientStop".to_string(),
                        "get".to_string(),
                        vec![color("ffffffff"), pct(100)],
                    ))),
                ]),
            ],
        )));

        let fill = Paint::try_coerce(pax_value).expect("helper syntax should coerce");
        let Paint::LinearGradient(gradient) = fill else {
            panic!("expected linear gradient");
        };

        assert_eq!(gradient.stops.len(), 2);
        assert_eq!(gradient.start.0, Size::Percent(Numeric::I64(0)));
        assert_eq!(gradient.end.0, Size::Percent(Numeric::I64(100)));
    }

    #[test]
    fn coerces_gradient_stop_get_helper_syntax() {
        let pax_value = PaxValue::Enum(Box::new((
            "GradientStop".to_string(),
            "get".to_string(),
            vec![color("11223344"), pct(48)],
        )));

        let stop = GradientStop::try_coerce(pax_value).expect("helper syntax should coerce");
        assert_eq!(stop.position, Size::Percent(Numeric::I64(48)));
        assert_eq!(stop.color, Color::from_hex("11223344"));
    }

    #[test]
    fn coerces_opacity_from_percent_literal() {
        let opacity = Opacity::try_coerce(pct(50)).expect("percent opacity should coerce");
        assert_eq!(opacity, Opacity::Percent(Numeric::I64(50)));
        assert!((opacity.to_float_0_1() - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn coerces_opacity_from_numeric_literal() {
        let opacity = Opacity::try_coerce(PaxValue::Numeric(Numeric::F64(0.5)))
            .expect("numeric opacity should coerce");
        assert_eq!(opacity, Opacity::Alpha(Numeric::F64(0.5)));
        assert!((opacity.to_float_0_1() - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn coerces_depth_from_px_but_rejects_percent() {
        let depth = Depth::try_coerce(PaxValue::Size(Size::Pixels(Numeric::F64(260.0))))
            .expect("px depth should coerce");
        assert_eq!(depth.to_float(), 260.0);

        let err = Depth::try_coerce(pct(50)).expect_err("percent depth should fail");
        assert!(err.contains("percent depth"));
    }

    #[test]
    fn coerces_material_helper_syntax() {
        let pax_value = PaxValue::Enum(Box::new((
            "Material".to_string(),
            "glossy".to_string(),
            vec![PaxValue::Numeric(Numeric::F64(0.44))],
        )));

        let material = Material::try_coerce(pax_value).expect("material helper should coerce");
        let Material::Lit(params) = material else {
            panic!("expected lit material");
        };
        assert_eq!(params.specular.get(), 0.44);
        assert_eq!(params.roughness.get(), 0.28);
    }
}

fn layer_object(value: PaxValue, expected: &str) -> Result<PaxValue, String> {
    match value {
        PaxValue::Enum(contents) if contents.0 == "Fill" || contents.0 == "Stroke" => {
            let (name, variant, mut args) = *contents;
            if name != expected || variant != "__layer" || args.len() != 1 {
                return Err(format!("expected {expected} layer, received {name}::{variant}; paint constructors now use Paint"));
            }
            Ok(args.remove(0))
        }
        PaxValue::Option(value) => match *value {
            Some(value) => layer_object(value, expected),
            None => Err(format!(
                "expected {expected}, received None; use [] for no layers"
            )),
        },
        value => Ok(value),
    }
}

macro_rules! layer_coercion {
    ($ty:ident, $($field:ident: $field_ty:ty),+) => {
        impl CoercionRules for $ty {
            fn allows_singleton_stack() -> bool { true }
            fn try_coerce(value: PaxValue) -> Result<Self, String> {
                match layer_object(value, stringify!($ty))? {
                    PaxValue::Object(fields) => {
                        let mut layer = Self::default();
                        for (name, value) in fields {
                            match name.as_str() {
                                $(stringify!($field) => {
                                    layer.$field = Property::new(<$field_ty>::try_coerce(value)
                                        .map_err(|e| format!("{}.{}: expected {}: {e}", stringify!($ty), name, stringify!($field_ty)))?);
                                },)+
                                "color" => return Err(format!("{}.color was renamed to paint", stringify!($ty))),
                                _ => return Err(format!("unknown {} field `{name}`", stringify!($ty))),
                            }
                        }
                        layer.validate_layer()?;
                        Ok(layer)
                    }
                    value => Paint::try_coerce(value).map(Self::from)
                        .map_err(|e| format!("expected {} layer or Paint: {e}", stringify!($ty))),
                }
            }
        }
    }
}
layer_coercion!(Fill, paint: Paint, material: Material, opacity: Opacity);
layer_coercion!(Stroke, paint: Paint, material: Material, opacity: Opacity, width: Size, cap: StrokeCap, join: StrokeJoin);

impl CoercionRules for StrokeCap {
    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        match value {
            PaxValue::Enum(contents) => {
                let (_, variant, args) = *contents;
                if !args.is_empty() {
                    return Err(format!(
                        "failed to coerce StrokeCap: expected no enum args, got {:?}",
                        args
                    ));
                }
                match variant.as_str() {
                    "Butt" => Ok(StrokeCap::Butt),
                    "Round" => Ok(StrokeCap::Round),
                    "Square" => Ok(StrokeCap::Square),
                    _ => Err(format!(
                        "failed to coerce StrokeCap: unknown enum variant {:?}",
                        variant
                    )),
                }
            }
            PaxValue::Option(o) => {
                if let Some(o) = *o {
                    StrokeCap::try_coerce(o)
                } else {
                    Err("failed to coerce StrokeCap".to_string())
                }
            }
            _ => Err(format!("failed to coerce StrokeCap")),
        }
    }
}

impl CoercionRules for PathSmoothing {
    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        match value {
            PaxValue::Enum(contents) => {
                let (_, variant, args) = *contents;
                if !args.is_empty() {
                    return Err(format!(
                        "failed to coerce PathSmoothing: expected no enum args, got {:?}",
                        args
                    ));
                }
                match variant.as_str() {
                    "None" => Ok(PathSmoothing::None),
                    "Light" => Ok(PathSmoothing::Light),
                    "Strong" => Ok(PathSmoothing::Strong),
                    _ => Err(format!(
                        "failed to coerce PathSmoothing: unknown enum variant {:?}",
                        variant
                    )),
                }
            }
            PaxValue::Option(o) => {
                if let Some(o) = *o {
                    PathSmoothing::try_coerce(o)
                } else {
                    Err("failed to coerce PathSmoothing".to_string())
                }
            }
            _ => Err(format!("failed to coerce PathSmoothing")),
        }
    }
}

impl CoercionRules for StrokeJoin {
    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        match value {
            PaxValue::Enum(contents) => {
                let (_, variant, args) = *contents;
                if !args.is_empty() {
                    return Err(format!(
                        "failed to coerce StrokeJoin: expected no enum args, got {:?}",
                        args
                    ));
                }
                match variant.as_str() {
                    "Miter" => Ok(StrokeJoin::Miter),
                    "Round" => Ok(StrokeJoin::Round),
                    "Bevel" => Ok(StrokeJoin::Bevel),
                    _ => Err(format!(
                        "failed to coerce StrokeJoin: unknown enum variant {:?}",
                        variant
                    )),
                }
            }
            PaxValue::Option(o) => {
                if let Some(o) = *o {
                    StrokeJoin::try_coerce(o)
                } else {
                    Err("failed to coerce StrokeJoin".to_string())
                }
            }
            _ => Err(format!("failed to coerce StrokeJoin")),
        }
    }
}

impl CoercionRules for ColorChannel {
    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        Ok(match value {
            PaxValue::Rotation(rot) => ColorChannel::Rotation(rot),
            PaxValue::Percent(perc) => ColorChannel::Percent(perc.0),
            PaxValue::Numeric(num) => ColorChannel::Integer(num.to_int().clamp(0, 255) as u8),
            PaxValue::Enum(contents) => {
                let (_, variant, args) = *contents;
                match variant.as_str() {
                    "Rotation" => {
                        let rot = Rotation::try_coerce(args.into_iter().next().unwrap())?;
                        ColorChannel::Rotation(rot)
                    }
                    "Integer" => {
                        let num = Numeric::try_coerce(args.into_iter().next().unwrap())?;
                        ColorChannel::Integer(num.to_int().clamp(0, 255) as u8)
                    }
                    "Percent" => {
                        let num = Numeric::try_coerce(args.into_iter().next().unwrap())?;
                        ColorChannel::Percent(num)
                    }
                    _ => {
                        return Err(format!(
                            "failed to convert to ColorChannel: unknown variant {:?}",
                            variant
                        ))
                    }
                }
            }
            PaxValue::Option(o) => {
                if let Some(o) = *o {
                    ColorChannel::try_coerce(o)?
                } else {
                    return Err(format!("failed to convert to ColorChannel"));
                }
            }
            _ => return Err(format!("failed to convert to ColorChannel")),
        })
    }
}

impl CoercionRules for Opacity {
    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        Ok(match value {
            PaxValue::Percent(perc) => Opacity::Percent(perc.0),
            PaxValue::Numeric(num) => Opacity::Alpha(num),
            PaxValue::Enum(contents) => {
                let (_, variant, args) = *contents;
                match variant.as_str() {
                    "Alpha" | "Numeric" => {
                        let num = Numeric::try_coerce(args.into_iter().next().unwrap())?;
                        Opacity::Alpha(num)
                    }
                    "Percent" => {
                        let num = Numeric::try_coerce(args.into_iter().next().unwrap())?;
                        Opacity::Percent(num)
                    }
                    _ => {
                        return Err(format!(
                            "failed to convert to Opacity: unknown variant {:?}",
                            variant
                        ))
                    }
                }
            }
            PaxValue::Option(o) => {
                if let Some(o) = *o {
                    Opacity::try_coerce(o)?
                } else {
                    return Err("failed to convert to Opacity".to_string());
                }
            }
            _ => return Err("failed to convert to Opacity".to_string()),
        })
    }
}

impl CoercionRules for UnitValue {
    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        Ok(match value {
            PaxValue::Percent(percent) => UnitValue::Percent(percent.0),
            PaxValue::Numeric(num) => UnitValue::Unitless(num),
            PaxValue::Enum(contents) => {
                let (_, variant, args) = *contents;
                let mut args = args.into_iter();
                match variant.as_str() {
                    "Unitless" | "Numeric" => {
                        UnitValue::Unitless(Numeric::try_coerce(args.next().unwrap())?)
                    }
                    "Percent" => UnitValue::Percent(Numeric::try_coerce(args.next().unwrap())?),
                    _ => {
                        return Err(format!(
                            "failed to convert to UnitValue: unknown variant {:?}",
                            variant
                        ))
                    }
                }
            }
            PaxValue::Option(mut opt) => {
                if let Some(value) = opt.take() {
                    UnitValue::try_coerce(value)?
                } else {
                    return Err("failed to convert to UnitValue".to_string());
                }
            }
            _ => return Err("failed to convert to UnitValue".to_string()),
        })
    }
}

impl CoercionRules for Percent {
    fn is_identity_roundtrip() -> bool {
        true
    }

    fn try_coerce(pax_value: PaxValue) -> Result<Self, String> {
        Ok(match pax_value {
            PaxValue::Percent(p) => p,
            PaxValue::Numeric(v) => Percent(v),
            PaxValue::Option(mut opt) => {
                if let Some(p) = opt.take() {
                    Percent::try_coerce(p)?
                } else {
                    return Err(format!("None can't be coerced into a Percent"));
                }
            }
            _ => return Err(format!("{:?} can't be coerced into a Percent", pax_value)),
        })
    }
}

impl CoercionRules for Size {
    fn is_identity_roundtrip() -> bool {
        true
    }

    fn try_coerce(pax_value: PaxValue) -> Result<Self, String> {
        Ok(match pax_value {
            PaxValue::Size(size) => size,
            PaxValue::Percent(p) => Size::Percent(p.0),
            PaxValue::Numeric(v) => Size::Pixels(v),
            PaxValue::Option(mut opt) => {
                if let Some(p) = opt.take() {
                    Size::try_coerce(p)?
                } else {
                    return Err(format!("None can't be coerced into a Size"));
                }
            }
            _ => return Err(format!("{:?} can't be coerced into a Size", pax_value)),
        })
    }
}

impl CoercionRules for String {
    fn is_identity_roundtrip() -> bool {
        true
    }

    fn try_coerce(pax_value: PaxValue) -> Result<Self, String> {
        Ok(match pax_value {
            PaxValue::String(s) => s,
            PaxValue::Numeric(n) => {
                if n.is_float() {
                    n.to_float().to_string()
                } else {
                    n.to_int().to_string()
                }
            }
            PaxValue::Option(mut opt) => {
                if let Some(p) = opt.take() {
                    String::try_coerce(p)?
                } else {
                    return Err(format!("None can't be coerced into a String"));
                }
            }
            _ => return Err(format!("{:?} can't be coerced into a String", pax_value)),
        })
    }
}

impl CoercionRules for Rotation {
    fn is_identity_roundtrip() -> bool {
        true
    }

    fn try_coerce(pax_value: PaxValue) -> Result<Self, String> {
        Ok(match pax_value {
            PaxValue::Rotation(r) => r,
            PaxValue::Numeric(n) => Rotation::Degrees(n),
            PaxValue::Percent(p) => Rotation::Percent(p.0),
            PaxValue::Option(mut opt) => {
                if let Some(p) = opt.take() {
                    Rotation::try_coerce(p)?
                } else {
                    return Err(format!("None can't be coerced into a Rotation"));
                }
            }
            _ => return Err(format!("{:?} can't be coerced into a Rotation", pax_value)),
        })
    }
}

impl CoercionRules for Duration {
    fn is_identity_roundtrip() -> bool {
        true
    }

    fn try_coerce(pax_value: PaxValue) -> Result<Self, String> {
        Ok(match pax_value {
            PaxValue::Duration(duration) => duration,
            PaxValue::Numeric(value) => Duration::Frames(value),
            PaxValue::Option(mut opt) => {
                if let Some(p) = opt.take() {
                    Duration::try_coerce(p)?
                } else {
                    return Err(format!("None can't be coerced into a Duration"));
                }
            }
            _ => return Err(format!("{:?} can't be coerced into a Duration", pax_value)),
        })
    }
}

impl CoercionRules for Numeric {
    fn is_identity_roundtrip() -> bool {
        true
    }

    fn try_coerce(pax_value: PaxValue) -> Result<Self, String> {
        Ok(match pax_value {
            PaxValue::Bool(b) => (b as i32).into(),
            PaxValue::Numeric(n) => n.into(),
            PaxValue::Size(n) => n.into(),
            PaxValue::Option(mut opt) => {
                if let Some(p) = opt.take() {
                    Numeric::try_coerce(p)?
                } else {
                    return Err(format!("None can't be coerced into a Numeric"));
                }
            }
            _ => return Err(format!("{:?} can't be coerced into a Numeric", pax_value)),
        })
    }
}

impl<T: CoercionRules> CoercionRules for Vec<T> {
    fn allows_singleton_stack() -> bool {
        T::allows_singleton_stack()
    }
    fn is_identity_roundtrip() -> bool {
        is_typed_binding_safe::<T>()
    }

    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        match value {
            PaxValue::Vec(vec) => {
                let res: Result<Vec<T>, _> = vec
                    .into_iter()
                    .enumerate()
                    .map(|(i, v)| T::try_coerce(v).map_err(|e| format!("entry [{i}]: {e}")))
                    .collect();
                res.map_err(|e| format!("couldn't coerce vec, element {:?}", e))
            }
            PaxValue::Option(mut opt) => {
                if let Some(p) = opt.take() {
                    Vec::<T>::try_coerce(p)
                } else {
                    return Err(format!("None can't be coerced into a Vec"));
                }
            }
            v if T::allows_singleton_stack() => T::try_coerce(v).map(|layer| vec![layer]),
            v => Err(format!(
                "{:?} can't be coerced into {:?}",
                v,
                std::any::type_name::<Vec<T>>(),
            )),
        }
    }
}

impl<T1: CoercionRules, T2: CoercionRules> CoercionRules for (T1, T2) {
    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        match value {
            PaxValue::Vec(vec) => {
                let mut itr = vec.into_iter();
                let res: Result<T1, _> = T1::try_coerce(itr.next().unwrap());
                let res2: Result<T2, _> = T2::try_coerce(itr.next().unwrap());
                res.and_then(|v1| res2.map(|v2| (v1, v2)))
            }
            PaxValue::Option(opt) => {
                if let Some(p) = *opt {
                    <(T1, T2)>::try_coerce(p)
                } else {
                    return Err(format!("None can't be coerced into a Vec"));
                }
            }
            v => Err(format!(
                "{:?} can't be coerced into {:?}",
                v,
                std::any::type_name::<(T1, T2)>(),
            )),
        }
    }
}

impl<T: CoercionRules> CoercionRules for Option<T> {
    fn is_identity_roundtrip() -> bool {
        is_typed_binding_safe::<T>()
    }

    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        match value {
            PaxValue::Option(opt) => {
                let res: Result<Option<T>, _> = opt.map(|v| T::try_coerce(v)).transpose();
                res.map_err(|e| format!("couldn't coerce option, element {:?}", e))
            }
            v => Some(T::try_coerce(v)).transpose(),
        }
    }
}

impl<T: CoercionRules> CoercionRules for Range<T> {
    fn is_identity_roundtrip() -> bool {
        is_typed_binding_safe::<T>()
    }

    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        match value {
            PaxValue::Range(start, end) => {
                let start = T::try_coerce(*start)?;
                let end = T::try_coerce(*end)?;
                Ok(start..end)
            }
            PaxValue::Option(mut opt) => {
                if let Some(p) = opt.take() {
                    Range::<T>::try_coerce(p)
                } else {
                    return Err(format!("None can't be coerced into a Range"));
                }
            }
            v => Err(format!(
                "{:?} can't be coerced into {:?}",
                v,
                std::any::type_name::<Range<T>>(),
            )),
        }
    }
}

impl CoercionRules for PaxValue {
    fn is_identity_roundtrip() -> bool {
        true
    }

    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        Ok(value)
    }
}

impl<T: CoercionRules> CoercionRules for Box<T> {
    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        Ok(Box::new(T::try_coerce(value)?))
    }
}

impl CoercionRules for Transform2D {
    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        Ok(match value {
            PaxValue::Option(opt) => {
                if let Some(t) = *opt {
                    Transform2D::try_coerce(t)?
                } else {
                    return Err(format!("None can't be coerced into a Transform2D"));
                }
            }
            PaxValue::Object(map) => {
                let [previous, rotate, translate, anchor, scale, skew] = extract_options(
                    ["previous", "rotate", "translate", "anchor", "scale", "skew"],
                    map,
                )
                .map_err(|e| format!("failed to convert to Transform2D: {e}"))?;
                let previous = Option::<Box<Transform2D>>::try_coerce(previous)?;
                let rotate = Option::<Rotation>::try_coerce(rotate)?;
                let translate = match translate {
                    PaxValue::Option(opt) => {
                        if let Some(t) = *opt {
                            let t = Vec::<Size>::try_coerce(t)?;
                            if t.len() != 2 {
                                return Err(format!(
                                    "expected 2 elements in translate, got {:?}",
                                    t.len()
                                ));
                            }
                            Some([t[0], t[1]])
                        } else {
                            None
                        }
                    }
                    _ => return Err(format!("translate can't be coerced into a Transform2D",)),
                };
                let anchor = match anchor {
                    PaxValue::Option(opt) => {
                        if let Some(a) = *opt {
                            let a = Vec::<Size>::try_coerce(a)?;
                            if a.len() != 2 {
                                return Err(format!(
                                    "expected 2 elements in anchor, got {:?}",
                                    a.len()
                                ));
                            }
                            Some([a[0], a[1]])
                        } else {
                            None
                        }
                    }
                    _ => return Err(format!("anchor can't be coerced into a Transform2D",)),
                };
                let scale = match scale {
                    PaxValue::Option(opt) => {
                        if let Some(s) = *opt {
                            let s = Vec::<Size>::try_coerce(s)?;
                            if s.len() != 2 {
                                return Err(format!(
                                    "expected 2 elements in scale, got {:?}",
                                    s.len()
                                ));
                            }
                            Some([s[0], s[1]])
                        } else {
                            None
                        }
                    }
                    _ => return Err(format!("scale can't be coerced into a Transform2D",)),
                };
                let skew = match skew {
                    PaxValue::Option(opt) => {
                        if let Some(s) = *opt {
                            let s = Vec::<Rotation>::try_coerce(s)?;
                            if s.len() != 2 {
                                return Err(format!(
                                    "expected 2 elements in skew, got {:?}",
                                    s.len()
                                ));
                            }
                            Some([s[0], s[1]])
                        } else {
                            None
                        }
                    }
                    _ => return Err(format!("skew can't be coerced into a Transform2D",)),
                };
                Transform2D {
                    previous,
                    rotate,
                    translate,
                    anchor,
                    scale,
                    skew,
                }
            }
            _ => return Err(format!("{:?} can't be coerced into a Transform2D", value)),
        })
    }
}

impl CoercionRules for Transform2 {
    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        Ok(match value {
            PaxValue::Option(mut opt) => {
                if let Some(t) = opt.take() {
                    Transform2::try_coerce(t)?
                } else {
                    return Err(format!("None can't be coerced into a Transform2"));
                }
            }
            PaxValue::Object(map) => {
                let m = Vec::<f64>::try_coerce(
                    map.into_iter()
                        .find_map(|(n, v)| (n == "m").then_some(v))
                        .unwrap(),
                )?;
                if m.len() != 6 {
                    return Err(format!("expected 6 elements in coeffs, got {:?}", m.len()));
                }
                Transform2::new([m[0], m[1], m[2], m[3], m[4], m[5]])
            }
            _ => return Err(format!("{:?} can't be coerced into a Transform2", value)),
        })
    }
}

impl CoercionRules for Vector2 {
    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        Ok(match value {
            PaxValue::Option(mut opt) => {
                if let Some(t) = opt.take() {
                    Vector2::try_coerce(t)?
                } else {
                    return Err(format!("None can't be coerced into a Vector2"));
                }
            }
            PaxValue::Object(map) => {
                let [x, y] = extract_options(["x", "y"], map)
                    .map_err(|e| format!("failed to convert to Vector2: {e}"))?;
                let x = f64::try_coerce(x)?;
                let y = f64::try_coerce(y)?;
                Vector2::new(x, y)
            }
            _ => return Err(format!("{:?} can't be coerced into a Vector2", value)),
        })
    }
}

// Pulls named object fields into a fixed-order array for coercion implementations.
pub fn extract_options<T, const N: usize>(
    keys: [&'static str; N],
    vec: Vec<(String, T)>,
) -> Result<[T; N], String> {
    // First create array of Options
    let mut intermediate: [Option<T>; N] = std::array::from_fn(|_| None);

    // Paint in the values we find
    for (k, v) in vec {
        if let Some(pos) = keys.iter().position(|&key| k == key) {
            intermediate[pos] = Some(v);
        }
    }

    // Convert to Result, ensuring all values were found
    let result: Result<[T; N], String> = intermediate
        .into_iter()
        .enumerate()
        .map(|(i, opt)| opt.ok_or_else(|| format!("missing field: {}", keys[i])))
        .collect::<Result<Vec<_>, _>>()?
        .try_into()
        .map_err(|_| "Internal error converting vec to array".to_string());

    result
}