redjs 0.4.0

Full-control Rust embedding layer over Bun's JavaScriptCore prebuilt. C ABI designed for zero-alloc C# (NativeAOT) codegen bindings.
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
//! Native `DOMPointReadOnly` / `DOMPoint` / `DOMRectReadOnly` / `DOMRect` / `DOMMatrixReadOnly` /
//! `DOMMatrix` (Geometry Interfaces Module Level 1).
//!
//! All the arithmetic is Rust ([`Mat`], unit-tested without a JS context); the
//! JS half is only the prototype chain, the accessors and `instanceof`.
//! `DOMMatrix` extends `DOMMatrixReadOnly` for real (spec §DOMMatrix), so the
//! read-only surface is inherited rather than duplicated and
//! `m instanceof DOMMatrixReadOnly` is true for both.
//!
//! Storage is the spec's own order — `m11, m12, m13, m14, m21, …, m44`, which
//! is column-major — so `toFloat64Array` is a straight copy and the transform
//! is `x' = m11·x + m21·y + m31·z + m41·w` (spec §"transform a point").
//!
//! ## Deliberate narrowing
//!
//! `new DOMMatrix(string)` and `setMatrixValue(string)` parse a **CSS transform
//! list** (spec §"create a DOMMatrix from a DOMString"). That is a CSS value
//! grammar, and this runtime has no CSS front end (the embedder owns CSS).
//! Rather than grow a CSS parser here for one constructor, both REFUSE with a
//! named error. Nothing silently returns identity: a caller that passes a
//! string finds out immediately.

use core::ffi::c_void;
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};

use super::util::*;
use crate::capi;
use crate::glue;

// ---------------------------------------------------------------------------
// The math (no JS)
// ---------------------------------------------------------------------------

/// A 4×4 transform in the spec's `mIJ` order: `a[(I-1)*4 + (J-1)] == mIJ`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Mat {
    pub a: [f64; 16],
    /// Spec `is2D` flag. Sticky-false: once an operation makes the matrix 3D it
    /// never returns to 2D, even if the 3D components later cancel
    /// (spec §"DOMMatrixReadOnly.is2D" — the flag tracks provenance, not values).
    pub is2d: bool,
}

pub const IDENTITY: Mat = Mat {
    a: [1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1.],
    is2d: true,
};

impl Mat {
    #[inline]
    pub fn get(&self, i: usize, j: usize) -> f64 {
        self.a[(i - 1) * 4 + (j - 1)]
    }
    #[inline]
    pub fn set(&mut self, i: usize, j: usize, v: f64) {
        self.a[(i - 1) * 4 + (j - 1)] = v;
    }

    /// 2D interop: `[a, b, c, d, e, f]` == `[m11, m12, m21, m22, m41, m42]`.
    pub fn from_2d(v: [f64; 6]) -> Mat {
        let mut m = IDENTITY;
        m.a[0] = v[0];
        m.a[1] = v[1];
        m.a[4] = v[2];
        m.a[5] = v[3];
        m.a[12] = v[4];
        m.a[13] = v[5];
        m
    }

    /// Spec §"create a DOMMatrix from a sequence": the 16-number form sets
    /// `is2D` to false regardless of the values.
    pub fn from_16(v: [f64; 16]) -> Mat {
        Mat { a: v, is2d: false }
    }

    /// `self · other` — post-multiplication, the direction every DOMMatrix
    /// method uses (spec §"multiply a matrix"): the result applies `other`
    /// first and `self` second.
    pub fn multiply(&self, other: &Mat) -> Mat {
        let mut r = [0.0f64; 16];
        for i in 0..4 {
            for j in 0..4 {
                let mut s = 0.0;
                for k in 0..4 {
                    s += self.a[k * 4 + j] * other.a[i * 4 + k];
                }
                r[i * 4 + j] = s;
            }
        }
        Mat { a: r, is2d: self.is2d && other.is2d }
    }

    pub fn translate(tx: f64, ty: f64, tz: f64) -> Mat {
        let mut m = IDENTITY;
        m.a[12] = tx;
        m.a[13] = ty;
        m.a[14] = tz;
        m.is2d = tz == 0.0;
        m
    }

    pub fn scale(sx: f64, sy: f64, sz: f64) -> Mat {
        let mut m = IDENTITY;
        m.a[0] = sx;
        m.a[5] = sy;
        m.a[10] = sz;
        m.is2d = sz == 1.0;
        m
    }

    pub fn rotate_z(deg: f64) -> Mat {
        let (s, c) = deg.to_radians().sin_cos();
        let mut m = IDENTITY;
        m.a[0] = c;
        m.a[1] = s;
        m.a[4] = -s;
        m.a[5] = c;
        m
    }

    pub fn rotate_y(deg: f64) -> Mat {
        let (s, c) = deg.to_radians().sin_cos();
        let mut m = IDENTITY;
        m.a[0] = c;
        m.a[2] = -s;
        m.a[8] = s;
        m.a[10] = c;
        m.is2d = false;
        m
    }

    pub fn rotate_x(deg: f64) -> Mat {
        let (s, c) = deg.to_radians().sin_cos();
        let mut m = IDENTITY;
        m.a[5] = c;
        m.a[6] = s;
        m.a[9] = -s;
        m.a[10] = c;
        m.is2d = false;
        m
    }

    /// Rodrigues rotation about an arbitrary axis (spec §"rotateAxisAngle").
    /// A zero-length axis yields identity, the spec's degenerate case.
    pub fn rotate_axis_angle(x: f64, y: f64, z: f64, deg: f64) -> Mat {
        let len = (x * x + y * y + z * z).sqrt();
        if len == 0.0 {
            return IDENTITY;
        }
        let (x, y, z) = (x / len, y / len, z / len);
        let (s, c) = deg.to_radians().sin_cos();
        let t = 1.0 - c;
        let mut m = IDENTITY;
        m.set(1, 1, t * x * x + c);
        m.set(1, 2, t * x * y + s * z);
        m.set(1, 3, t * x * z - s * y);
        m.set(2, 1, t * x * y - s * z);
        m.set(2, 2, t * y * y + c);
        m.set(2, 3, t * y * z + s * x);
        m.set(3, 1, t * x * z + s * y);
        m.set(3, 2, t * y * z - s * x);
        m.set(3, 3, t * z * z + c);
        // Rotation about z alone stays 2D; any other axis does not.
        m.is2d = x == 0.0 && y == 0.0;
        m
    }

    pub fn skew_x(deg: f64) -> Mat {
        let mut m = IDENTITY;
        m.a[4] = deg.to_radians().tan();
        m
    }

    pub fn skew_y(deg: f64) -> Mat {
        let mut m = IDENTITY;
        m.a[1] = deg.to_radians().tan();
        m
    }

    /// Spec §"transform a point": `p' = M · p`, column-vector convention.
    pub fn transform_point(&self, p: [f64; 4]) -> [f64; 4] {
        let mut out = [0.0f64; 4];
        for j in 0..4 {
            out[j] =
                self.a[j] * p[0] + self.a[4 + j] * p[1] + self.a[8 + j] * p[2] + self.a[12 + j] * p[3];
        }
        out
    }

    pub fn is_identity(&self) -> bool {
        self.a == IDENTITY.a
    }

    /// Full 4×4 inverse. `None` when the matrix is singular — the caller then
    /// sets every component to NaN and `is2D` to false (spec §"invert self"),
    /// which is what makes a non-invertible matrix impossible to mistake for a
    /// working one.
    pub fn inverse(&self) -> Option<Mat> {
        let m = &self.a;
        let mut inv = [0.0f64; 16];
        inv[0] = m[5] * m[10] * m[15] - m[5] * m[11] * m[14] - m[9] * m[6] * m[15]
            + m[9] * m[7] * m[14] + m[13] * m[6] * m[11] - m[13] * m[7] * m[10];
        inv[4] = -m[4] * m[10] * m[15] + m[4] * m[11] * m[14] + m[8] * m[6] * m[15]
            - m[8] * m[7] * m[14] - m[12] * m[6] * m[11] + m[12] * m[7] * m[10];
        inv[8] = m[4] * m[9] * m[15] - m[4] * m[11] * m[13] - m[8] * m[5] * m[15]
            + m[8] * m[7] * m[13] + m[12] * m[5] * m[11] - m[12] * m[7] * m[9];
        inv[12] = -m[4] * m[9] * m[14] + m[4] * m[10] * m[13] + m[8] * m[5] * m[14]
            - m[8] * m[6] * m[13] - m[12] * m[5] * m[10] + m[12] * m[6] * m[9];
        inv[1] = -m[1] * m[10] * m[15] + m[1] * m[11] * m[14] + m[9] * m[2] * m[15]
            - m[9] * m[3] * m[14] - m[13] * m[2] * m[11] + m[13] * m[3] * m[10];
        inv[5] = m[0] * m[10] * m[15] - m[0] * m[11] * m[14] - m[8] * m[2] * m[15]
            + m[8] * m[3] * m[14] + m[12] * m[2] * m[11] - m[12] * m[3] * m[10];
        inv[9] = -m[0] * m[9] * m[15] + m[0] * m[11] * m[13] + m[8] * m[1] * m[15]
            - m[8] * m[3] * m[13] - m[12] * m[1] * m[11] + m[12] * m[3] * m[9];
        inv[13] = m[0] * m[9] * m[14] - m[0] * m[10] * m[13] - m[8] * m[1] * m[14]
            + m[8] * m[2] * m[13] + m[12] * m[1] * m[10] - m[12] * m[2] * m[9];
        inv[2] = m[1] * m[6] * m[15] - m[1] * m[7] * m[14] - m[5] * m[2] * m[15]
            + m[5] * m[3] * m[14] + m[13] * m[2] * m[7] - m[13] * m[3] * m[6];
        inv[6] = -m[0] * m[6] * m[15] + m[0] * m[7] * m[14] + m[4] * m[2] * m[15]
            - m[4] * m[3] * m[14] - m[12] * m[2] * m[7] + m[12] * m[3] * m[6];
        inv[10] = m[0] * m[5] * m[15] - m[0] * m[7] * m[13] - m[4] * m[1] * m[15]
            + m[4] * m[3] * m[13] + m[12] * m[1] * m[7] - m[12] * m[3] * m[5];
        inv[14] = -m[0] * m[5] * m[14] + m[0] * m[6] * m[13] + m[4] * m[1] * m[14]
            - m[4] * m[2] * m[13] - m[12] * m[1] * m[6] + m[12] * m[2] * m[5];
        inv[3] = -m[1] * m[6] * m[11] + m[1] * m[7] * m[10] + m[5] * m[2] * m[11]
            - m[5] * m[3] * m[10] - m[9] * m[2] * m[7] + m[9] * m[3] * m[6];
        inv[7] = m[0] * m[6] * m[11] - m[0] * m[7] * m[10] - m[4] * m[2] * m[11]
            + m[4] * m[3] * m[10] + m[8] * m[2] * m[7] - m[8] * m[3] * m[6];
        inv[11] = -m[0] * m[5] * m[11] + m[0] * m[7] * m[9] + m[4] * m[1] * m[11]
            - m[4] * m[3] * m[9] - m[8] * m[1] * m[7] + m[8] * m[3] * m[5];
        inv[15] = m[0] * m[5] * m[10] - m[0] * m[6] * m[9] - m[4] * m[1] * m[10]
            + m[4] * m[2] * m[9] + m[8] * m[1] * m[6] - m[8] * m[2] * m[5];

        let det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];
        if det == 0.0 || !det.is_finite() {
            return None;
        }
        for v in inv.iter_mut() {
            *v /= det;
        }
        Some(Mat { a: inv, is2d: self.is2d })
    }

    /// Spec §"stringification behavior": `matrix(a, b, c, d, e, f)` when 2D,
    /// `matrix3d(…16…)` otherwise. `None` when a component is non-finite —
    /// the caller's InvalidStateError case.
    pub fn to_css(&self) -> Option<String> {
        if self.a.iter().any(|v| !v.is_finite()) {
            return None;
        }
        let n = |v: f64| {
            let s = format!("{v}");
            if s == "-0" { "0".to_string() } else { s }
        };
        if self.is2d {
            Some(format!(
                "matrix({}, {}, {}, {}, {}, {})",
                n(self.a[0]), n(self.a[1]), n(self.a[4]), n(self.a[5]), n(self.a[12]), n(self.a[13])
            ))
        } else {
            let parts: Vec<String> = self.a.iter().map(|&v| n(v)).collect();
            Some(format!("matrix3d({})", parts.join(", ")))
        }
    }
}

pub struct MatrixData {
    pub m: Mat,
}

pub struct PointData {
    pub p: [f64; 4],
}

pub struct RectData {
    pub r: [f64; 4],
}

// ---------------------------------------------------------------------------
// Per-context classes
// ---------------------------------------------------------------------------

struct GeomClasses {
    matrix_class: capi::JSClassRef,
    ro: Class,
    rw: Class,
    point_class: capi::JSClassRef,
    point_ro: Class,
    point_rw: Class,
    rect_class: capi::JSClassRef,
    rect_ro: Class,
    rect_rw: Class,
}

unsafe impl Send for GeomClasses {}
unsafe impl Sync for GeomClasses {}

fn registry() -> &'static Mutex<HashMap<usize, &'static GeomClasses>> {
    static R: OnceLock<Mutex<HashMap<usize, &'static GeomClasses>>> = OnceLock::new();
    R.get_or_init(|| Mutex::new(HashMap::new()))
}

fn classes(g: *mut c_void) -> &'static GeomClasses {
    registry().lock().unwrap().get(&(g as usize)).copied().expect("webapi::geometry not installed")
}

pub(crate) fn forget(gone: crate::context::Gone) {
    registry().lock().unwrap().remove(&gone.key);
}

unsafe fn this_mat<'a>(g: *mut c_void, cf: *mut c_void) -> Option<&'a mut MatrixData> {
    host_data::<MatrixData>(g, classes(g).matrix_class, cf_this(cf))
}

unsafe fn this_point<'a>(g: *mut c_void, cf: *mut c_void) -> Option<&'a mut PointData> {
    host_data::<PointData>(g, classes(g).point_class, cf_this(cf))
}

/// Build a `DOMMatrix` (the mutable flavour) around `m`.
pub unsafe fn new_matrix(g: *mut c_void, m: Mat) -> u64 {
    let c = classes(g);
    host_create(g, c.matrix_class, c.rw.proto, MatrixData { m })
}

pub unsafe fn new_point(g: *mut c_void, p: [f64; 4]) -> u64 {
    let c = classes(g);
    host_create(g, c.point_class, c.point_rw.proto, PointData { p })
}

// ---- structured serialization (webapi::serialize) ----------------------------

use super::util::proto_chain_has as has_in_chain;

fn classes_opt(g: *mut c_void) -> Option<&'static GeomClasses> {
    registry().lock().unwrap().get(&(g as usize)).copied()
}

/// `(x, y, z, w, read_only)` of a DOMPoint / DOMPointReadOnly — read-only
/// unless `DOMPoint.prototype` is on its chain (a subclass serializes as the
/// interface it extends, as in a browser).
pub(crate) unsafe fn point_parts(g: *mut c_void, v: u64) -> Option<([f64; 4], bool)> {
    let c = classes_opt(g)?;
    let d = host_data::<PointData>(g, c.point_class, v)?;
    Some((d.p, !has_in_chain(g, v, c.point_rw.proto)))
}

pub(crate) unsafe fn create_point(g: *mut c_void, p: [f64; 4], read_only: bool) -> Option<u64> {
    let c = classes_opt(g)?;
    let proto = if read_only { c.point_ro.proto } else { c.point_rw.proto };
    Some(host_create(g, c.point_class, proto, PointData { p }))
}

/// The matrix and whether it is a DOMMatrixReadOnly (see [`point_parts`]).
pub(crate) unsafe fn matrix_parts(g: *mut c_void, v: u64) -> Option<(Mat, bool)> {
    let c = classes_opt(g)?;
    let d = host_data::<MatrixData>(g, c.matrix_class, v)?;
    Some((d.m, !has_in_chain(g, v, c.rw.proto)))
}

pub(crate) unsafe fn create_matrix(g: *mut c_void, m: Mat, read_only: bool) -> Option<u64> {
    let c = classes_opt(g)?;
    let proto = if read_only { c.ro.proto } else { c.rw.proto };
    Some(host_create(g, c.matrix_class, proto, MatrixData { m }))
}

/// True when `v` is one of this module's matrix objects.
pub unsafe fn is_matrix(g: *mut c_void, v: u64) -> bool {
    host_data::<MatrixData>(g, classes(g).matrix_class, v).is_some()
}

/// Reads a DOMMatrix-ish argument: a real matrix object, or any object carrying
/// `m11…m44` / `a…f` (spec §"create a DOMMatrix from a dictionary").
pub unsafe fn mat_of(g: *mut c_void, v: u64) -> Option<Mat> {
    let c = classes(g);
    if let Some(d) = host_data::<MatrixData>(g, c.matrix_class, v) {
        return Some(d.m);
    }
    if !is_cell(v) {
        return None;
    }
    if get(g, v, "m11") != UNDEF {
        let mut m = IDENTITY;
        for i in 1..=4usize {
            for j in 1..=4usize {
                let got = get(g, v, &format!("m{i}{j}"));
                if got != UNDEF {
                    m.set(i, j, read_number(g, got));
                }
            }
        }
        m.is2d = truthy_flag(get(g, v, "is2D"));
        return Some(m);
    }
    if get(g, v, "a") != UNDEF {
        let f = |k: &str, d: f64| {
            let got = get(g, v, k);
            if got == UNDEF { d } else { read_number(g, got) }
        };
        return Some(Mat::from_2d([
            f("a", 1.), f("b", 0.), f("c", 0.), f("d", 1.), f("e", 0.), f("f", 0.),
        ]));
    }
    None
}

/// Prototype for an instance under construction: new.target's, else the class
/// default (spec OrdinaryCreateFromConstructor — subclassing works).
unsafe fn ordinary_proto(g: *mut c_void, new_target: u64, fallback: u64) -> u64 {
    let p = if is_cell(new_target) { get(g, new_target, "prototype") } else { UNDEF };
    if is_cell(p) { p } else { fallback }
}

// ---------------------------------------------------------------------------
// DOMPoint
// ---------------------------------------------------------------------------

macro_rules! point_accessors {
    ($get:ident, $set:ident, $idx:expr) => {
        #[crate::host_fn]
        unsafe fn $get(g: *mut c_void, cf: *mut c_void) -> u64 {
            match this_point(g, cf) {
                Some(p) => enc_f64(p.p[$idx]),
                None => throw_type_error(g, "DOMPoint getter called on a non-DOMPoint"),
            }
        }
        #[crate::host_fn]
        unsafe fn $set(g: *mut c_void, cf: *mut c_void) -> u64 {
            let v = arg_num(g, cf, 0, 0.0);
            match this_point(g, cf) {
                Some(p) => {
                    p.p[$idx] = v;
                    UNDEF
                }
                None => throw_type_error(g, "DOMPoint setter called on a non-DOMPoint"),
            }
        }
    };
}
point_accessors!(pt_get_x, pt_set_x, 0);
point_accessors!(pt_get_y, pt_set_y, 1);
point_accessors!(pt_get_z, pt_set_z, 2);
point_accessors!(pt_get_w, pt_set_w, 3);

#[crate::host_fn]
unsafe fn point_construct(g: *mut c_void, cf: *mut c_void) -> u64 {
    let c = classes(g);
    let p = [
        arg_num(g, cf, 0, 0.0),
        arg_num(g, cf, 1, 0.0),
        arg_num(g, cf, 2, 0.0),
        arg_num(g, cf, 3, 1.0),
    ];
    let proto = ordinary_proto(g, cf_new_target(cf), c.point_rw.proto);
    host_create(g, c.point_class, proto, PointData { p })
}

#[crate::host_fn]
unsafe fn point_matrix_transform(g: *mut c_void, cf: *mut c_void) -> u64 {
    let Some(pt) = this_point(g, cf) else {
        return throw_type_error(g, "DOMPoint.matrixTransform called on a non-DOMPoint");
    };
    let src = pt.p;
    match mat_of(g, cf_arg(cf, 0)) {
        Some(m) => new_point(g, m.transform_point(src)),
        None => throw_type_error(g, "DOMPoint.matrixTransform: argument is not a matrix"),
    }
}

#[crate::host_fn]
unsafe fn point_to_json(g: *mut c_void, cf: *mut c_void) -> u64 {
    let Some(pt) = this_point(g, cf) else {
        return throw_type_error(g, "DOMPoint.toJSON called on a non-DOMPoint");
    };
    let v = pt.p;
    let o = new_object(g, UNDEF);
    for (k, i) in [("x", 0usize), ("y", 1), ("z", 2), ("w", 3)] {
        define(g, o, k, enc_f64(v[i]), 0);
    }
    o
}

// ---------------------------------------------------------------------------
// DOMRect
// ---------------------------------------------------------------------------

unsafe fn this_rect<'a>(g: *mut c_void, cf: *mut c_void) -> Option<&'a mut RectData> {
    host_data::<RectData>(g, classes(g).rect_class, cf_this(cf))
}

/// A `DOMRect` (the mutable flavour).
pub unsafe fn new_rect(g: *mut c_void, x: f64, y: f64, width: f64, height: f64) -> u64 {
    let c = classes(g);
    host_create(g, c.rect_class, c.rect_rw.proto, RectData { r: [x, y, width, height] })
}

pub(crate) unsafe fn rect_parts(g: *mut c_void, v: u64) -> Option<([f64; 4], bool)> {
    let c = classes_opt(g)?;
    let d = host_data::<RectData>(g, c.rect_class, v)?;
    Some((d.r, !has_in_chain(g, v, c.rect_rw.proto)))
}

pub(crate) unsafe fn create_rect(g: *mut c_void, r: [f64; 4], read_only: bool) -> Option<u64> {
    let c = classes_opt(g)?;
    let proto = if read_only { c.rect_ro.proto } else { c.rect_rw.proto };
    Some(host_create(g, c.rect_class, proto, RectData { r }))
}

/// `top`, `right`, `bottom`, `left`: a negative width or height flips its edges (spec §DOMRectReadOnly).
fn edges(r: [f64; 4]) -> [f64; 4] {
    let [x, y, w, h] = r;
    [y.min(y + h), x.max(x + w), y.max(y + h), x.min(x + w)]
}

macro_rules! rect_accessors {
    ($get:ident, $set:ident, $idx:expr) => {
        #[crate::host_fn]
        unsafe fn $get(g: *mut c_void, cf: *mut c_void) -> u64 {
            match this_rect(g, cf) {
                Some(r) => enc_f64(r.r[$idx]),
                None => throw_type_error(g, "Illegal invocation"),
            }
        }
        #[crate::host_fn]
        unsafe fn $set(g: *mut c_void, cf: *mut c_void) -> u64 {
            let v = arg_num(g, cf, 0, f64::NAN);
            match this_rect(g, cf) {
                Some(r) => {
                    r.r[$idx] = v;
                    UNDEF
                }
                None => throw_type_error(g, "Illegal invocation"),
            }
        }
    };
}
rect_accessors!(rc_get_x, rc_set_x, 0);
rect_accessors!(rc_get_y, rc_set_y, 1);
rect_accessors!(rc_get_width, rc_set_width, 2);
rect_accessors!(rc_get_height, rc_set_height, 3);

macro_rules! rect_edge {
    ($get:ident, $idx:expr) => {
        #[crate::host_fn]
        unsafe fn $get(g: *mut c_void, cf: *mut c_void) -> u64 {
            match this_rect(g, cf) {
                Some(r) => enc_f64(edges(r.r)[$idx]),
                None => throw_type_error(g, "Illegal invocation"),
            }
        }
    };
}
rect_edge!(rc_top, 0);
rect_edge!(rc_right, 1);
rect_edge!(rc_bottom, 2);
rect_edge!(rc_left, 3);

#[crate::host_fn]
unsafe fn rect_construct(g: *mut c_void, cf: *mut c_void) -> u64 {
    let c = classes(g);
    let r = [arg_num(g, cf, 0, 0.0), arg_num(g, cf, 1, 0.0), arg_num(g, cf, 2, 0.0), arg_num(g, cf, 3, 0.0)];
    let proto = ordinary_proto(g, cf_new_target(cf), c.rect_rw.proto);
    host_create(g, c.rect_class, proto, RectData { r })
}

#[crate::host_fn]
unsafe fn rect_to_json(g: *mut c_void, cf: *mut c_void) -> u64 {
    let Some(rc) = this_rect(g, cf) else {
        return throw_type_error(g, "Illegal invocation");
    };
    let [x, y, w, h] = rc.r;
    let [top, right, bottom, left] = edges(rc.r);
    let o = new_object(g, UNDEF);
    for (k, v) in [("x", x), ("y", y), ("width", w), ("height", h), ("top", top), ("right", right), ("bottom", bottom), ("left", left)] {
        define(g, o, k, enc_f64(v), 0);
    }
    o
}

unsafe fn rect_from(g: *mut c_void, cf: *mut c_void, read_only: bool) -> u64 {
    let d = cf_arg(cf, 0);
    let mut r = [0.0; 4];
    if is_cell(d) {
        for (i, k) in ["x", "y", "width", "height"].into_iter().enumerate() {
            let Ok(v) = try_get(g, d, k) else { return UNDEF };
            if v != UNDEF {
                let Ok(n) = to_number(g, v) else { return UNDEF };
                r[i] = n;
            }
        }
    }
    create_rect(g, r, read_only).unwrap_or(UNDEF)
}

#[crate::host_fn]
unsafe fn rect_from_ro(g: *mut c_void, cf: *mut c_void) -> u64 {
    rect_from(g, cf, true)
}

#[crate::host_fn]
unsafe fn rect_from_rw(g: *mut c_void, cf: *mut c_void) -> u64 {
    rect_from(g, cf, false)
}

// ---------------------------------------------------------------------------
// DOMMatrix — component accessors
// ---------------------------------------------------------------------------

/// Writing a component outside the 2D subset makes the matrix 3D — but only
/// when the value differs from that component's identity value, so
/// `m.m33 = 1` on a 2D matrix leaves it 2D (spec §"DOMMatrix attributes").
const TWO_D_INDICES: [usize; 6] = [0, 1, 4, 5, 12, 13];

unsafe fn comp_get_impl(g: *mut c_void, cf: *mut c_void, idx: usize) -> u64 {
    match this_mat(g, cf) {
        Some(d) => enc_f64(d.m.a[idx]),
        None => throw_type_error(g, "DOMMatrix component getter called on a non-DOMMatrix"),
    }
}

unsafe fn comp_set_impl(g: *mut c_void, cf: *mut c_void, idx: usize) -> u64 {
    let value = arg_num(g, cf, 0, 0.0);
    let Some(d) = this_mat(g, cf) else {
        return throw_type_error(g, "DOMMatrix component setter called on a non-DOMMatrix");
    };
    d.m.a[idx] = value;
    if !TWO_D_INDICES.contains(&idx) {
        let identity_value = if idx == 10 || idx == 15 { 1.0 } else { 0.0 };
        if value != identity_value {
            d.m.is2d = false;
        }
    }
    UNDEF
}

/// One host function per accessor. Deliberately NOT a single shared function
/// carrying the index in a bound argument: `Function.prototype.bind` also pins
/// `this`, which would sever every accessor from its instance.
macro_rules! matrix_accessors {
    ($($get:ident, $set:ident, $idx:expr;)*) => {
        $(
            #[crate::host_fn]
            unsafe fn $get(g: *mut c_void, cf: *mut c_void) -> u64 {
                comp_get_impl(g, cf, $idx)
            }
            #[crate::host_fn]
            unsafe fn $set(g: *mut c_void, cf: *mut c_void) -> u64 {
                comp_set_impl(g, cf, $idx)
            }
        )*
    };
}

matrix_accessors! {
    g_m11, s_m11, 0;  g_m12, s_m12, 1;  g_m13, s_m13, 2;  g_m14, s_m14, 3;
    g_m21, s_m21, 4;  g_m22, s_m22, 5;  g_m23, s_m23, 6;  g_m24, s_m24, 7;
    g_m31, s_m31, 8;  g_m32, s_m32, 9;  g_m33, s_m33, 10; g_m34, s_m34, 11;
    g_m41, s_m41, 12; g_m42, s_m42, 13; g_m43, s_m43, 14; g_m44, s_m44, 15;
    g_a, s_a, 0; g_b, s_b, 1; g_c, s_c, 4; g_d, s_d, 5; g_e, s_e, 12; g_f, s_f, 13;
}

/// `(name, index, getter, setter)`. The index is carried alongside so the
/// accessor table and the storage layout are asserted against each other by
/// `the_accessor_table_matches_the_storage_layout` instead of by inspection.
const COMPONENTS: &[(&str, usize, HostFn, HostFn)] = &[
    ("m11", 0, g_m11, s_m11), ("m12", 1, g_m12, s_m12), ("m13", 2, g_m13, s_m13), ("m14", 3, g_m14, s_m14),
    ("m21", 4, g_m21, s_m21), ("m22", 5, g_m22, s_m22), ("m23", 6, g_m23, s_m23), ("m24", 7, g_m24, s_m24),
    ("m31", 8, g_m31, s_m31), ("m32", 9, g_m32, s_m32), ("m33", 10, g_m33, s_m33), ("m34", 11, g_m34, s_m34),
    ("m41", 12, g_m41, s_m41), ("m42", 13, g_m42, s_m42), ("m43", 14, g_m43, s_m43), ("m44", 15, g_m44, s_m44),
    ("a", 0, g_a, s_a), ("b", 1, g_b, s_b), ("c", 4, g_c, s_c),
    ("d", 5, g_d, s_d), ("e", 12, g_e, s_e), ("f", 13, g_f, s_f),
];

unsafe fn define_components(g: *mut c_void, proto: u64, writable: bool) {
    for (name, _, getf, setf) in COMPONENTS {
        let getter = make_fn(g, &format!("get {name}"), 0, *getf);
        let setter = if writable { make_fn(g, &format!("set {name}"), 1, *setf) } else { UNDEF };
        let a = atom(g, name);
        glue::rjs_define_accessor(g, proto, a, getter, setter, 2);
        glue::rjs_atom_free(g, a);
    }
}

// ---------------------------------------------------------------------------
// DOMMatrix — transforms
// ---------------------------------------------------------------------------

#[crate::host_fn]
unsafe fn mat_get_is_2d(g: *mut c_void, cf: *mut c_void) -> u64 {
    match this_mat(g, cf) {
        Some(d) => enc_bool(d.m.is2d),
        None => throw_type_error(g, "DOMMatrixReadOnly.is2D called on a non-DOMMatrix"),
    }
}

#[crate::host_fn]
unsafe fn mat_get_is_identity(g: *mut c_void, cf: *mut c_void) -> u64 {
    match this_mat(g, cf) {
        Some(d) => enc_bool(d.m.is_identity()),
        None => throw_type_error(g, "DOMMatrixReadOnly.isIdentity called on a non-DOMMatrix"),
    }
}

/// Post-multiply `rhs` and either mutate `this` (the `*Self` methods on
/// DOMMatrix) or return a fresh DOMMatrix (the read-only methods).
unsafe fn finish(g: *mut c_void, cf: *mut c_void, mutate: bool, rhs: Option<Mat>, name: &str) -> u64 {
    let Some(rhs) = rhs else {
        return throw_type_error(g, &format!("DOMMatrix.{name}: invalid argument"));
    };
    let Some(d) = this_mat(g, cf) else {
        return throw_type_error(g, &format!("DOMMatrix.{name} called on a non-DOMMatrix"));
    };
    let result = d.m.multiply(&rhs);
    if mutate {
        d.m = result;
        cf_this(cf)
    } else {
        new_matrix(g, result)
    }
}

unsafe fn build_translate(g: *mut c_void, cf: *mut c_void) -> Option<Mat> {
    Some(Mat::translate(arg_num(g, cf, 0, 0.), arg_num(g, cf, 1, 0.), arg_num(g, cf, 2, 0.)))
}

unsafe fn build_scale(g: *mut c_void, cf: *mut c_void) -> Option<Mat> {
    // scale(sx, sy?, sz?, ox?, oy?, oz?) — sy defaults to sx (spec §"scale()").
    let sx = arg_num(g, cf, 0, 1.);
    let sy = if cf_arg(cf, 1) == UNDEF { sx } else { read_number(g, cf_arg(cf, 1)) };
    let sz = arg_num(g, cf, 2, 1.);
    let (ox, oy, oz) = (arg_num(g, cf, 3, 0.), arg_num(g, cf, 4, 0.), arg_num(g, cf, 5, 0.));
    Some(
        Mat::translate(ox, oy, oz)
            .multiply(&Mat::scale(sx, sy, sz))
            .multiply(&Mat::translate(-ox, -oy, -oz)),
    )
}

unsafe fn build_scale3d(g: *mut c_void, cf: *mut c_void) -> Option<Mat> {
    let s = arg_num(g, cf, 0, 1.);
    let (ox, oy, oz) = (arg_num(g, cf, 1, 0.), arg_num(g, cf, 2, 0.), arg_num(g, cf, 3, 0.));
    let mut sc = Mat::scale(s, s, s);
    sc.is2d = false; // scale3d is a 3D operation by definition
    Some(Mat::translate(ox, oy, oz).multiply(&sc).multiply(&Mat::translate(-ox, -oy, -oz)))
}

unsafe fn build_rotate(g: *mut c_void, cf: *mut c_void) -> Option<Mat> {
    // Spec §"rotate()": "If rotY and rotZ are both missing, set rotZ to rotX,
    // then set rotX and rotY to 0" — one argument is a Z rotation.
    let a0 = arg_num(g, cf, 0, 0.);
    let (rx, ry, rz) = if cf_arg(cf, 1) == UNDEF && cf_arg(cf, 2) == UNDEF {
        (0., 0., a0)
    } else {
        (a0, arg_num(g, cf, 1, 0.), arg_num(g, cf, 2, 0.))
    };
    Some(Mat::rotate_z(rz).multiply(&Mat::rotate_y(ry)).multiply(&Mat::rotate_x(rx)))
}

unsafe fn build_rotate_from_vector(g: *mut c_void, cf: *mut c_void) -> Option<Mat> {
    let (x, y) = (arg_num(g, cf, 0, 0.), arg_num(g, cf, 1, 0.));
    // Spec: the angle is 0 when x and y are both 0.
    let deg = if x == 0.0 && y == 0.0 { 0.0 } else { y.atan2(x).to_degrees() };
    Some(Mat::rotate_z(deg))
}

unsafe fn build_rotate_axis_angle(g: *mut c_void, cf: *mut c_void) -> Option<Mat> {
    Some(Mat::rotate_axis_angle(
        arg_num(g, cf, 0, 0.),
        arg_num(g, cf, 1, 0.),
        arg_num(g, cf, 2, 0.),
        arg_num(g, cf, 3, 0.),
    ))
}

unsafe fn build_skew_x(g: *mut c_void, cf: *mut c_void) -> Option<Mat> {
    Some(Mat::skew_x(arg_num(g, cf, 0, 0.)))
}

unsafe fn build_skew_y(g: *mut c_void, cf: *mut c_void) -> Option<Mat> {
    Some(Mat::skew_y(arg_num(g, cf, 0, 0.)))
}

unsafe fn build_multiply(g: *mut c_void, cf: *mut c_void) -> Option<Mat> {
    mat_of(g, cf_arg(cf, 0))
}

unsafe fn build_flip_x(_g: *mut c_void, _cf: *mut c_void) -> Option<Mat> {
    Some(Mat::from_2d([-1., 0., 0., 1., 0., 0.]))
}

unsafe fn build_flip_y(_g: *mut c_void, _cf: *mut c_void) -> Option<Mat> {
    Some(Mat::from_2d([1., 0., 0., -1., 0., 0.]))
}

/// Read-only and mutating flavours from ONE builder, so the pair cannot drift.
macro_rules! transform_pair {
    ($($ro:ident, $rw:ident, $build:path, $name:literal;)*) => {
        $(
            #[crate::host_fn]
            unsafe fn $ro(g: *mut c_void, cf: *mut c_void) -> u64 {
                let r = $build(g, cf);
                finish(g, cf, false, r, $name)
            }
            #[crate::host_fn]
            unsafe fn $rw(g: *mut c_void, cf: *mut c_void) -> u64 {
                let r = $build(g, cf);
                finish(g, cf, true, r, $name)
            }
        )*
    };
}

transform_pair! {
    x_translate, x_translate_self, build_translate, "translate";
    x_scale, x_scale_self, build_scale, "scale";
    x_scale3d, x_scale3d_self, build_scale3d, "scale3d";
    x_rotate, x_rotate_self, build_rotate, "rotate";
    x_rot_vec, x_rot_vec_self, build_rotate_from_vector, "rotateFromVector";
    x_rot_axis, x_rot_axis_self, build_rotate_axis_angle, "rotateAxisAngle";
    x_skew_x, x_skew_x_self, build_skew_x, "skewX";
    x_skew_y, x_skew_y_self, build_skew_y, "skewY";
    x_multiply, x_multiply_self, build_multiply, "multiply";
    x_flip_x, x_flip_x_self, build_flip_x, "flipX";
    x_flip_y, x_flip_y_self, build_flip_y, "flipY";
}

/// `(read-only name, mutating name, arity, ro fn, self fn)`.
const TRANSFORMS: &[(&str, &str, u32, HostFn, HostFn)] = &[
    ("translate", "translateSelf", 3, x_translate, x_translate_self),
    ("scale", "scaleSelf", 6, x_scale, x_scale_self),
    ("scale3d", "scale3dSelf", 4, x_scale3d, x_scale3d_self),
    ("rotate", "rotateSelf", 3, x_rotate, x_rotate_self),
    ("rotateFromVector", "rotateFromVectorSelf", 2, x_rot_vec, x_rot_vec_self),
    ("rotateAxisAngle", "rotateAxisAngleSelf", 4, x_rot_axis, x_rot_axis_self),
    ("skewX", "skewXSelf", 1, x_skew_x, x_skew_x_self),
    ("skewY", "skewYSelf", 1, x_skew_y, x_skew_y_self),
    ("multiply", "multiplySelf", 1, x_multiply, x_multiply_self),
    ("flipX", "flipXSelf", 0, x_flip_x, x_flip_x_self),
    ("flipY", "flipYSelf", 0, x_flip_y, x_flip_y_self),
];

#[crate::host_fn]
unsafe fn op_pre_multiply_self(g: *mut c_void, cf: *mut c_void) -> u64 {
    let Some(other) = mat_of(g, cf_arg(cf, 0)) else {
        return throw_type_error(g, "DOMMatrix.preMultiplySelf: argument is not a matrix");
    };
    let Some(d) = this_mat(g, cf) else {
        return throw_type_error(g, "DOMMatrix.preMultiplySelf called on a non-DOMMatrix");
    };
    d.m = other.multiply(&d.m);
    cf_this(cf)
}

/// Spec §"invert self": a non-invertible matrix becomes all-NaN with `is2D`
/// false. NOT an exception, and NOT the original matrix — the point is that
/// every subsequent read is visibly poison rather than plausibly fine.
unsafe fn invert_impl(g: *mut c_void, cf: *mut c_void, mutate: bool) -> u64 {
    let Some(d) = this_mat(g, cf) else {
        return throw_type_error(g, "DOMMatrix.inverse called on a non-DOMMatrix");
    };
    let result = d.m.inverse().unwrap_or(Mat { a: [f64::NAN; 16], is2d: false });
    if mutate {
        d.m = result;
        cf_this(cf)
    } else {
        new_matrix(g, result)
    }
}

#[crate::host_fn]
unsafe fn op_inverse(g: *mut c_void, cf: *mut c_void) -> u64 {
    invert_impl(g, cf, false)
}

#[crate::host_fn]
unsafe fn op_invert_self(g: *mut c_void, cf: *mut c_void) -> u64 {
    invert_impl(g, cf, true)
}

#[crate::host_fn]
unsafe fn op_transform_point(g: *mut c_void, cf: *mut c_void) -> u64 {
    let arg = cf_arg(cf, 0);
    let p = if is_cell(arg) {
        match host_data::<PointData>(g, classes(g).point_class, arg) {
            Some(pt) => pt.p,
            None => {
                let f = |k: &str, d: f64| {
                    let v = get(g, arg, k);
                    if v == UNDEF { d } else { read_number(g, v) }
                };
                [f("x", 0.), f("y", 0.), f("z", 0.), f("w", 1.)]
            }
        }
    } else {
        [0., 0., 0., 1.]
    };
    let Some(d) = this_mat(g, cf) else {
        return throw_type_error(g, "DOMMatrixReadOnly.transformPoint called on a non-DOMMatrix");
    };
    let out = d.m.transform_point(p);
    new_point(g, out)
}

unsafe fn to_typed(g: *mut c_void, cf: *mut c_void, kind: u32) -> u64 {
    let Some(d) = this_mat(g, cf) else {
        return throw_type_error(g, "DOMMatrixReadOnly.toFloatNArray called on a non-DOMMatrix");
    };
    let vals = d.m.a;
    let mut out = UNDEF;
    if crate::ffi::redjs_typedarray_create(g, kind, 16, &mut out) != 0 {
        return UNDEF;
    }
    let mut ta = crate::ffi::RjsTaInfo::default();
    if glue::rjs_typedarray_info(g, out, &mut ta) == 0 && !ta.data.is_null() {
        if kind == 8 {
            let p = ta.data as *mut f32;
            for (i, v) in vals.iter().enumerate() {
                *p.add(i) = *v as f32;
            }
        } else {
            let p = ta.data as *mut f64;
            for (i, v) in vals.iter().enumerate() {
                *p.add(i) = *v;
            }
        }
    }
    out
}

#[crate::host_fn]
unsafe fn op_to_f32(g: *mut c_void, cf: *mut c_void) -> u64 {
    to_typed(g, cf, 8)
}

#[crate::host_fn]
unsafe fn op_to_f64(g: *mut c_void, cf: *mut c_void) -> u64 {
    to_typed(g, cf, 9)
}

#[crate::host_fn]
unsafe fn op_to_string(g: *mut c_void, cf: *mut c_void) -> u64 {
    let Some(d) = this_mat(g, cf) else {
        return throw_type_error(g, "DOMMatrixReadOnly.toString called on a non-DOMMatrix");
    };
    match d.m.to_css() {
        Some(s) => js_string(g, &s),
        // Spec: "If one or more of m11 … m44 are a non-finite number, then
        // throw an InvalidStateError DOMException".
        None => super::domexception::throw(
            g,
            "InvalidStateError",
            "DOMMatrix.toString on a matrix with non-finite components",
        ),
    }
}

const CSS_REFUSAL: &str = "parses a CSS <transform-list>, which this runtime does not implement: \
    the runtime has no CSS front end (the embedder owns CSS). Build the matrix from components or a 6/16-number sequence instead.";

#[crate::host_fn]
unsafe fn op_set_matrix_value(g: *mut c_void, _cf: *mut c_void) -> u64 {
    throw_type_error(g, &format!("DOMMatrix.setMatrixValue {CSS_REFUSAL}"))
}

#[crate::host_fn]
unsafe fn op_to_json(g: *mut c_void, cf: *mut c_void) -> u64 {
    let Some(d) = this_mat(g, cf) else {
        return throw_type_error(g, "DOMMatrixReadOnly.toJSON called on a non-DOMMatrix");
    };
    let m = d.m;
    let o = new_object(g, UNDEF);
    for (name, idx, _, _) in COMPONENTS {
        define(g, o, name, enc_f64(m.a[*idx]), 0);
    }
    define(g, o, "is2D", enc_bool(m.is2d), 0);
    define(g, o, "isIdentity", enc_bool(m.is_identity()), 0);
    o
}

// ---------------------------------------------------------------------------
// Constructors and statics
// ---------------------------------------------------------------------------

unsafe fn matrix_from_init(g: *mut c_void, init: u64) -> Result<Mat, String> {
    if init == UNDEF || init == NULL {
        return Ok(IDENTITY);
    }
    if glue::rjs_kind(g, init) == 5 {
        return Err(format!("DOMMatrix(string) {CSS_REFUSAL}"));
    }
    // Sequence form: 6 or 16 numbers (spec §"create a DOMMatrix from a sequence").
    if is_cell(init) && get(g, init, "length") != UNDEF && !is_matrix(g, init) {
        let n = array_len(g, init);
        let mut v: Vec<f64> = Vec::with_capacity(n as usize);
        for i in 0..n {
            v.push(read_number(g, get_i(g, init, i)));
        }
        return match v.len() {
            6 => Ok(Mat::from_2d([v[0], v[1], v[2], v[3], v[4], v[5]])),
            16 => {
                let mut a = [0.0f64; 16];
                a.copy_from_slice(&v);
                Ok(Mat::from_16(a))
            }
            other => Err(format!(
                "DOMMatrix: a sequence initializer must have 6 or 16 numbers, got {other}"
            )),
        };
    }
    match mat_of(g, init) {
        Some(m) => Ok(m),
        None => Err("DOMMatrix: unsupported initializer".into()),
    }
}

macro_rules! matrix_ctor {
    ($name:ident, $proto:ident) => {
        #[crate::host_fn]
        unsafe fn $name(g: *mut c_void, cf: *mut c_void) -> u64 {
            let c = classes(g);
            match matrix_from_init(g, cf_arg(cf, 0)) {
                Ok(m) => {
                    let proto = ordinary_proto(g, cf_new_target(cf), c.$proto.proto);
                    host_create(g, c.matrix_class, proto, MatrixData { m })
                }
                Err(e) => throw_type_error(g, &e),
            }
        }
    };
}
matrix_ctor!(matrix_construct_rw, rw);
matrix_ctor!(matrix_construct_ro, ro);

#[crate::host_fn]
unsafe fn static_from_matrix(g: *mut c_void, cf: *mut c_void) -> u64 {
    match mat_of(g, cf_arg(cf, 0)) {
        Some(m) => new_matrix(g, m),
        None => new_matrix(g, IDENTITY),
    }
}

#[crate::host_fn]
unsafe fn static_from_array(g: *mut c_void, cf: *mut c_void) -> u64 {
    let arg = cf_arg(cf, 0);
    let mut ta = crate::ffi::RjsTaInfo::default();
    let mut v: Vec<f64> = Vec::new();
    if glue::rjs_typedarray_info(g, arg, &mut ta) == 0 && !ta.data.is_null() && ta.detached == 0 {
        let n = ta.length as usize;
        if ta.kind == 8 {
            let p = ta.data as *const f32;
            for i in 0..n {
                v.push(*p.add(i) as f64);
            }
        } else {
            let p = ta.data as *const f64;
            for i in 0..n {
                v.push(*p.add(i));
            }
        }
    } else if is_cell(arg) {
        let n = array_len(g, arg);
        for i in 0..n {
            v.push(read_number(g, get_i(g, arg, i)));
        }
    }
    match v.len() {
        6 => new_matrix(g, Mat::from_2d([v[0], v[1], v[2], v[3], v[4], v[5]])),
        16 => {
            let mut a = [0.0f64; 16];
            a.copy_from_slice(&v);
            new_matrix(g, Mat::from_16(a))
        }
        other => throw_type_error(
            g,
            &format!("DOMMatrix.fromFloat32Array/fromFloat64Array: expected 6 or 16 elements, got {other}"),
        ),
    }
}

pub unsafe fn install(g: *mut c_void) {
    let point_class = make_host_class::<PointData>("DOMPoint");
    let point_ro = define_class(g, &ClassSpec {
        name: "DOMPointReadOnly",
        arity: 4,
        construct: Some(point_construct),
        parent_proto: 0,
        methods: &[("matrixTransform", 1, point_matrix_transform), ("toJSON", 0, point_to_json)],
        getters: &[("x", pt_get_x), ("y", pt_get_y), ("z", pt_get_z), ("w", pt_get_w)],
        accessors: &[],
    });
    let point_rw = define_class(g, &ClassSpec {
        name: "DOMPoint",
        arity: 4,
        construct: Some(point_construct),
        parent_proto: point_ro.proto,
        methods: &[],
        getters: &[],
        accessors: &[
            ("x", pt_get_x, pt_set_x),
            ("y", pt_get_y, pt_set_y),
            ("z", pt_get_z, pt_set_z),
            ("w", pt_get_w, pt_set_w),
        ],
    });

    let rect_class = make_host_class::<RectData>("DOMRect");
    let rect_ro = define_class(g, &ClassSpec {
        name: "DOMRectReadOnly",
        arity: 0,
        construct: Some(rect_construct),
        parent_proto: 0,
        methods: &[("toJSON", 0, rect_to_json)],
        getters: &[
            ("x", rc_get_x),
            ("y", rc_get_y),
            ("width", rc_get_width),
            ("height", rc_get_height),
            ("top", rc_top),
            ("right", rc_right),
            ("bottom", rc_bottom),
            ("left", rc_left),
        ],
        accessors: &[],
    });
    let rect_rw = define_class(g, &ClassSpec {
        name: "DOMRect",
        arity: 0,
        construct: Some(rect_construct),
        parent_proto: rect_ro.proto,
        methods: &[],
        getters: &[],
        accessors: &[
            ("x", rc_get_x, rc_set_x),
            ("y", rc_get_y, rc_set_y),
            ("width", rc_get_width, rc_set_width),
            ("height", rc_get_height, rc_set_height),
        ],
    });
    define(g, rect_ro.ctor, "fromRect", make_fn(g, "fromRect", 0, rect_from_ro), 2);
    define(g, rect_rw.ctor, "fromRect", make_fn(g, "fromRect", 0, rect_from_rw), 2);

    let matrix_class = make_host_class::<MatrixData>("DOMMatrix");
    let ro = define_class(g, &ClassSpec {
        name: "DOMMatrixReadOnly",
        arity: 1,
        construct: Some(matrix_construct_ro),
        parent_proto: 0,
        methods: &[
            ("transformPoint", 1, op_transform_point),
            ("inverse", 0, op_inverse),
            ("toFloat32Array", 0, op_to_f32),
            ("toFloat64Array", 0, op_to_f64),
            ("toString", 0, op_to_string),
            ("toJSON", 0, op_to_json),
        ],
        getters: &[("is2D", mat_get_is_2d), ("isIdentity", mat_get_is_identity)],
        accessors: &[],
    });
    define_components(g, ro.proto, false);
    for (name, _, arity, f, _) in TRANSFORMS {
        define(g, ro.proto, name, make_fn(g, name, *arity, *f), 2);
    }

    let rw = define_class(g, &ClassSpec {
        name: "DOMMatrix",
        arity: 1,
        construct: Some(matrix_construct_rw),
        parent_proto: ro.proto,
        methods: &[
            ("preMultiplySelf", 1, op_pre_multiply_self),
            ("invertSelf", 0, op_invert_self),
            ("setMatrixValue", 1, op_set_matrix_value),
        ],
        getters: &[],
        accessors: &[],
    });
    // The mutable component accessors shadow the read-only ones inherited from
    // DOMMatrixReadOnly.prototype; the transform methods do NOT — `multiply`
    // still returns a new matrix on a DOMMatrix, which is why the chain is real
    // rather than two flat copies.
    define_components(g, rw.proto, true);
    for (_, self_name, arity, _, f) in TRANSFORMS {
        define(g, rw.proto, self_name, make_fn(g, self_name, *arity, *f), 2);
    }

    for ctor in [ro.ctor, rw.ctor] {
        define(g, ctor, "fromMatrix", make_fn(g, "fromMatrix", 1, static_from_matrix), 2);
        define(g, ctor, "fromFloat32Array", make_fn(g, "fromFloat32Array", 1, static_from_array), 2);
        define(g, ctor, "fromFloat64Array", make_fn(g, "fromFloat64Array", 1, static_from_array), 2);
    }

    let boxed: &'static GeomClasses =
        Box::leak(Box::new(GeomClasses { matrix_class, ro, rw, point_class, point_ro, point_rw, rect_class, rect_ro, rect_rw }));
    registry().lock().unwrap().insert(g as usize, boxed);
}

// ---------------------------------------------------------------------------
// Tests — the arithmetic, no JS context needed
// ---------------------------------------------------------------------------

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

    fn close(a: f64, b: f64) -> bool {
        (a - b).abs() < 1e-9
    }

    #[test]
    fn multiply_is_post_multiplication_so_the_argument_applies_first() {
        // The direction is easy to get backwards, and backwards still produces a
        // plausible-looking matrix. Pin it with a case whose two orders DISAGREE.
        let t = Mat::translate(10.0, 0.0, 0.0);
        let s = Mat::scale(2.0, 2.0, 1.0);

        // t.multiply(s) applies s first, then t: (1,0) → (2,0) → (12,0).
        let p = t.multiply(&s).transform_point([1.0, 0.0, 0.0, 1.0]);
        assert!(close(p[0], 12.0), "{p:?}");

        // s.multiply(t) applies t first, then s: (1,0) → (11,0) → (22,0).
        let q = s.multiply(&t).transform_point([1.0, 0.0, 0.0, 1.0]);
        assert!(close(q[0], 22.0), "{q:?}");
    }

    #[test]
    fn rotate_z_ninety_degrees_maps_x_onto_y() {
        let p = Mat::rotate_z(90.0).transform_point([1.0, 0.0, 0.0, 1.0]);
        assert!(close(p[0], 0.0) && close(p[1], 1.0), "{p:?}");
    }

    #[test]
    fn rotate_x_and_y_leave_the_two_d_flag_behind() {
        assert!(Mat::rotate_z(30.0).is2d);
        assert!(!Mat::rotate_x(30.0).is2d);
        assert!(!Mat::rotate_y(30.0).is2d);
        assert!(!Mat::rotate_z(30.0).multiply(&Mat::rotate_x(30.0)).is2d);
    }

    #[test]
    fn inverse_round_trips_a_nontrivial_transform() {
        let m = Mat::translate(3.0, -7.0, 2.0)
            .multiply(&Mat::rotate_axis_angle(1.0, 2.0, 3.0, 37.0))
            .multiply(&Mat::scale(2.0, 0.5, 4.0));
        let inv = m.inverse().expect("invertible");
        for (i, v) in m.multiply(&inv).a.iter().enumerate() {
            assert!(close(*v, IDENTITY.a[i]), "component {i} was {v}");
        }
    }

    #[test]
    fn a_singular_matrix_has_no_inverse() {
        assert!(Mat::scale(0.0, 1.0, 1.0).inverse().is_none());
    }

    #[test]
    fn rotate_axis_angle_about_z_matches_rotate_z() {
        let a = Mat::rotate_axis_angle(0.0, 0.0, 1.0, 42.0);
        let b = Mat::rotate_z(42.0);
        for i in 0..16 {
            assert!(close(a.a[i], b.a[i]), "component {i}: {} vs {}", a.a[i], b.a[i]);
        }
    }

    #[test]
    fn skew_x_shears_y_into_x() {
        let p = Mat::skew_x(45.0).transform_point([0.0, 1.0, 0.0, 1.0]);
        assert!(close(p[0], 1.0) && close(p[1], 1.0), "{p:?}");
    }

    #[test]
    fn the_two_d_serialization_is_the_css_matrix_function() {
        assert_eq!(Mat::from_2d([1., 2., 3., 4., 5., 6.]).to_css().unwrap(), "matrix(1, 2, 3, 4, 5, 6)");
    }

    #[test]
    fn a_three_d_matrix_serializes_as_matrix3d_with_sixteen_components() {
        let s = Mat::rotate_x(90.0).to_css().unwrap();
        assert!(s.starts_with("matrix3d("), "{s}");
        assert_eq!(s.matches(',').count(), 15, "{s}");
    }

    #[test]
    fn a_non_finite_component_has_no_serialization() {
        let mut m = IDENTITY;
        m.a[0] = f64::INFINITY;
        assert!(m.to_css().is_none());
    }

    #[test]
    fn the_accessor_table_matches_the_storage_layout() {
        // 22 hand-written accessor entries is 22 chances to transpose an index,
        // and a transposed index is a wrong picture rather than a crash. Check
        // every entry against `Mat::get`, which the layout test below pins.
        let mut m = IDENTITY;
        for (i, v) in m.a.iter_mut().enumerate() {
            *v = 100.0 + i as f64;
        }
        let expect = |name: &str| -> f64 {
            match name {
                "a" => m.get(1, 1), "b" => m.get(1, 2), "c" => m.get(2, 1),
                "d" => m.get(2, 2), "e" => m.get(4, 1), "f" => m.get(4, 2),
                _ => {
                    let b = name.as_bytes();
                    m.get((b[1] - b'0') as usize, (b[2] - b'0') as usize)
                }
            }
        };
        for (name, idx, _, _) in COMPONENTS {
            assert_eq!(m.a[*idx], expect(name), "accessor {name} points at index {idx}");
        }
    }

    #[test]
    fn the_2d_alias_layout_matches_the_spec_component_names() {
        // a,b,c,d,e,f == m11,m12,m21,m22,m41,m42.
        let m = Mat::from_2d([1., 2., 3., 4., 5., 6.]);
        assert_eq!((m.get(1, 1), m.get(1, 2)), (1.0, 2.0));
        assert_eq!((m.get(2, 1), m.get(2, 2)), (3.0, 4.0));
        assert_eq!((m.get(4, 1), m.get(4, 2)), (5.0, 6.0));
    }
}

/// Through a real JSC context — the half the arithmetic tests above cannot see.
#[cfg(test)]
mod jsc_tests {
    use crate::webapi::testing::*;

    #[test]
    fn to_string_of_a_non_finite_matrix_is_an_invalid_state_error() {
        let c = ctx();
        ok(
            &c,
            "(() => { try { String(new DOMMatrix([NaN, 0, 0, 1, 0, 0])); return false; } \
              catch (e) { return e instanceof DOMException && e.name === 'InvalidStateError'; } })()",
        );
    }

    #[test]
    fn the_prototype_chain_is_real() {
        let c = ctx();
        ok(&c, "new DOMMatrix() instanceof DOMMatrix");
        ok(&c, "new DOMMatrix() instanceof DOMMatrixReadOnly");
        ok(&c, "!(new DOMMatrixReadOnly() instanceof DOMMatrix)");
        ok(&c, "new DOMPoint() instanceof DOMPointReadOnly");
        // Inheritance, not two flat copies: the read-only method is found on the
        // parent prototype and still returns a NEW matrix from a DOMMatrix.
        ok(&c, "!Object.getOwnPropertyNames(DOMMatrix.prototype).includes('translate')");
        ok(&c, "(m => m.translate(1,2) !== m)(new DOMMatrix())");
    }

    #[test]
    fn the_component_accessors_reach_the_right_storage() {
        let c = ctx();
        ok(&c, "(m => m.a===1&&m.b===2&&m.c===3&&m.d===4&&m.e===5&&m.f===6)(new DOMMatrix([1,2,3,4,5,6]))");
        ok(&c, "(m => m.m11===1&&m.m12===2&&m.m21===3&&m.m22===4&&m.m41===5&&m.m42===6)(new DOMMatrix([1,2,3,4,5,6]))");
        // The alias and the canonical name are ONE storage slot.
        ok(&c, "(m => { m.a = 9; return m.m11 === 9; })(new DOMMatrix())");
    }

    #[test]
    fn read_only_components_do_not_write() {
        let c = ctx();
        // No setter on DOMMatrixReadOnly: a sloppy-mode assignment is silently
        // dropped, so assert the VALUE rather than expecting a throw.
        ok(&c, "(m => { try { m.a = 5; } catch (e) {} return m.a === 1; })(new DOMMatrixReadOnly())");
    }

    #[test]
    fn self_methods_mutate_and_return_this_while_plain_ones_do_not() {
        let c = ctx();
        ok(&c, "(m => m.translateSelf(10, 0) === m && m.e === 10)(new DOMMatrix())");
        ok(&c, "(m => { m.translate(10, 0); return m.e === 0; })(new DOMMatrix())");
    }

    #[test]
    fn transform_point_returns_a_dompoint_with_the_transformed_coordinates() {
        let c = ctx();
        ok(&c, "(p => p instanceof DOMPoint && p.x === 12 && p.y === 0)(new DOMMatrix().translateSelf(10,0).scaleSelf(2).transformPoint({x:1,y:0}))");
    }

    #[test]
    fn to_float64_array_is_sixteen_components_in_spec_order() {
        let c = ctx();
        ok(&c, "(a => a instanceof Float64Array && a.length === 16 && a[0] === 1 && a[1] === 2)(new DOMMatrix([1,2,3,4,5,6]).toFloat64Array())");
    }

    #[test]
    fn a_string_initializer_refuses_by_name_instead_of_returning_identity() {
        // The failure this guards against is the plausible one: silently
        // yielding identity, which draws everything at the origin unrotated and
        // looks like a bug anywhere but here.
        let c = ctx();
        let msg = throws(&c, "new DOMMatrix('translate(10px, 20px)')");
        assert!(msg.contains("transform-list"), "{msg}");
        assert!(msg.contains("no CSS front end"), "{msg}");
        let msg2 = throws(&c, "new DOMMatrix().setMatrixValue('scale(2)')");
        assert!(msg2.contains("transform-list"), "{msg2}");
    }

    #[test]
    fn a_bad_sequence_length_says_what_it_got() {
        let c = ctx();
        let msg = throws(&c, "new DOMMatrix([1,2,3])");
        assert!(msg.contains("6 or 16"), "{msg}");
        assert!(msg.contains('3'), "{msg}");
    }

    #[test]
    fn an_accessor_on_a_foreign_object_is_a_type_error() {
        let c = ctx();
        let msg = throws(&c, "Object.getOwnPropertyDescriptor(DOMMatrix.prototype,'a').get.call({})");
        assert!(msg.contains("non-DOMMatrix"), "{msg}");
    }

    #[test]
    fn a_singular_matrix_inverts_to_nan_rather_than_to_itself() {
        let c = ctx();
        ok(&c, "Number.isNaN(new DOMMatrix().scaleSelf(0).inverse().m11)");
        ok(&c, "new DOMMatrix().scaleSelf(0).inverse().is2D === false");
    }

    #[test]
    fn rects_have_flipped_edges_mutable_sides_and_clone() {
        let c = ctx();
        assert_eq!(
            s(&c, "(() => { const r = new DOMRect(10, 20, -4, 6); return [r.left, r.right, r.top, r.bottom].join(); })()"),
            "6,10,20,26"
        );
        ok(&c, "(() => { const r = new DOMRect(); r.width = 5; return r.right === 5 && r instanceof DOMRectReadOnly; })()");
        ok(&c, "(() => { const r = new DOMRectReadOnly(1, 2, 3, 4); r.x = 9; return r.x === 1 && !(r instanceof DOMRect); })()");
        assert_eq!(s(&c, "JSON.stringify(DOMRect.fromRect({ x: 1, width: 2 }))"), r#"{"x":1,"y":0,"width":2,"height":0,"top":0,"right":3,"bottom":0,"left":1}"#);
        ok(&c, "DOMRectReadOnly.fromRect() instanceof DOMRectReadOnly && !(DOMRectReadOnly.fromRect() instanceof DOMRect)");
        ok(&c, "(() => { const r = structuredClone(new DOMRect(1, 2, 3, 4)); return r instanceof DOMRect && r.bottom === 6; })()");
        ok(&c, "!(structuredClone(new DOMRectReadOnly()) instanceof DOMRect)");
        ok(&c, "NodeFilter.SHOW_ELEMENT === 1 && NodeFilter.FILTER_SKIP === 3 && NodeFilter.SHOW_ALL === 4294967295");
    }
}