runmat-runtime 0.5.0

Core runtime for RunMat with builtins, BLAS/LAPACK integration, and execution APIs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
//! MATLAB-compatible `setfield` builtin with struct array and object support.
//!
//! Mirrors MATLAB's `setfield` semantics, including nested field creation, struct
//! array indexing via cell arguments, and property assignment on MATLAB-style
//! objects. The builtin performs all updates on host data; GPU-resident values are
//! gathered automatically before mutation. Updated tensors remain on the host.

use crate::builtins::common::spec::{
    BroadcastSemantics, BuiltinFusionSpec, BuiltinGpuSpec, ConstantStrategy, GpuOpKind,
    ReductionNaN, ResidencyPolicy, ShapeRequirements,
};
use crate::builtins::structs::type_resolvers::setfield_type;
use crate::{
    build_runtime_error, call_builtin_async, gather_if_needed_async, object_property_getter_name,
    object_property_setter_name, BuiltinResult, RuntimeError,
};
use runmat_builtins::{
    Access, BuiltinCompletionPolicy, BuiltinDescriptor, BuiltinErrorDescriptor, BuiltinOutputMode,
    BuiltinParamArity, BuiltinParamDescriptor, BuiltinParamType, BuiltinSignatureDescriptor,
    CellArray, CharArray, ComplexTensor, HandleRef, LogicalArray, ObjectInstance, StructValue,
    Tensor, Value,
};
use runmat_gc_api::GcPtr;
use runmat_macros::runtime_builtin;
use std::convert::TryFrom;

#[runmat_macros::register_gpu_spec(builtin_path = "crate::builtins::structs::core::setfield")]
pub const GPU_SPEC: BuiltinGpuSpec = BuiltinGpuSpec {
    name: "setfield",
    op_kind: GpuOpKind::Custom("setfield"),
    supported_precisions: &[],
    broadcast: BroadcastSemantics::None,
    provider_hooks: &[],
    constant_strategy: ConstantStrategy::InlineLiteral,
    residency: ResidencyPolicy::InheritInputs,
    nan_mode: ReductionNaN::Include,
    two_pass_threshold: None,
    workgroup_size: None,
    accepts_nan_mode: false,
    notes: "Host-only metadata mutation; GPU tensors are gathered before assignment.",
};

#[runmat_macros::register_fusion_spec(builtin_path = "crate::builtins::structs::core::setfield")]
pub const FUSION_SPEC: BuiltinFusionSpec = BuiltinFusionSpec {
    name: "setfield",
    shape: ShapeRequirements::Any,
    constant_strategy: ConstantStrategy::InlineLiteral,
    elementwise: None,
    reduction: None,
    emits_nan: false,
    notes: "Assignments terminate fusion and gather device data back to the host.",
};

const BUILTIN_NAME: &str = "setfield";
const SETFIELD_OUTPUT: [BuiltinParamDescriptor; 1] = [BuiltinParamDescriptor {
    name: "S",
    ty: BuiltinParamType::Any,
    arity: BuiltinParamArity::Required,
    default: None,
    description: "Updated struct/object/array value.",
}];

const SETFIELD_INPUTS_SCALAR: [BuiltinParamDescriptor; 3] = [
    BuiltinParamDescriptor {
        name: "S",
        ty: BuiltinParamType::Any,
        arity: BuiltinParamArity::Required,
        default: None,
        description: "Input struct/object/struct-array target.",
    },
    BuiltinParamDescriptor {
        name: "field",
        ty: BuiltinParamType::PropertyName,
        arity: BuiltinParamArity::Required,
        default: None,
        description: "Field/property name to assign.",
    },
    BuiltinParamDescriptor {
        name: "value",
        ty: BuiltinParamType::Any,
        arity: BuiltinParamArity::Required,
        default: None,
        description: "Assigned value.",
    },
];

const SETFIELD_INPUTS_NESTED: [BuiltinParamDescriptor; 3] = [
    BuiltinParamDescriptor {
        name: "S",
        ty: BuiltinParamType::Any,
        arity: BuiltinParamArity::Required,
        default: None,
        description: "Input struct/object/struct-array target.",
    },
    BuiltinParamDescriptor {
        name: "path",
        ty: BuiltinParamType::Any,
        arity: BuiltinParamArity::Variadic,
        default: None,
        description:
            "Alternating field names and optional index-selector cells `{...}` for nested assignment.",
    },
    BuiltinParamDescriptor {
        name: "value",
        ty: BuiltinParamType::Any,
        arity: BuiltinParamArity::Required,
        default: None,
        description: "Assigned value.",
    },
];

const SETFIELD_INPUTS_LEADING_INDEX: [BuiltinParamDescriptor; 4] = [
    BuiltinParamDescriptor {
        name: "S",
        ty: BuiltinParamType::Any,
        arity: BuiltinParamArity::Required,
        default: None,
        description: "Input struct-array target.",
    },
    BuiltinParamDescriptor {
        name: "index_selector",
        ty: BuiltinParamType::Any,
        arity: BuiltinParamArity::Required,
        default: None,
        description: "Leading index selector in a cell array, e.g. `{2}` or `{end}`.",
    },
    BuiltinParamDescriptor {
        name: "path",
        ty: BuiltinParamType::Any,
        arity: BuiltinParamArity::Variadic,
        default: None,
        description:
            "Alternating field names and optional index-selector cells `{...}` for nested assignment.",
    },
    BuiltinParamDescriptor {
        name: "value",
        ty: BuiltinParamType::Any,
        arity: BuiltinParamArity::Required,
        default: None,
        description: "Assigned value.",
    },
];

const SETFIELD_SIGNATURES: [BuiltinSignatureDescriptor; 3] = [
    BuiltinSignatureDescriptor {
        label: "S = setfield(S, field, value)",
        inputs: &SETFIELD_INPUTS_SCALAR,
        outputs: &SETFIELD_OUTPUT,
    },
    BuiltinSignatureDescriptor {
        label: "S = setfield(S, field_or_index, ..., value)",
        inputs: &SETFIELD_INPUTS_NESTED,
        outputs: &SETFIELD_OUTPUT,
    },
    BuiltinSignatureDescriptor {
        label: "S = setfield(S, {idx0}, field_or_index, ..., value)",
        inputs: &SETFIELD_INPUTS_LEADING_INDEX,
        outputs: &SETFIELD_OUTPUT,
    },
];

const SETFIELD_ERROR_NOT_ENOUGH_INPUTS: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.SETFIELD.NOT_ENOUGH_INPUTS",
    identifier: Some("RunMat:setfield:NotEnoughInputs"),
    when: "Input does not provide at least one path component plus assigned value.",
    message: "setfield: expected at least one field name and a value",
};

const SETFIELD_ERROR_FIELD_EXPECTED: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.SETFIELD.FIELD_EXPECTED",
    identifier: Some("RunMat:setfield:FieldExpected"),
    when: "Field/path arguments are missing after parsing selectors.",
    message: "setfield: expected field name arguments",
};

const SETFIELD_ERROR_INDEX_SELECTOR_TYPE: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.SETFIELD.INDEX_SELECTOR_TYPE",
    identifier: Some("RunMat:setfield:IndexSelectorType"),
    when: "Index selector is not provided as a cell array.",
    message: "setfield: indices must be provided in a cell array",
};

const SETFIELD_ERROR_INDEX_INVALID: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.SETFIELD.INDEX_INVALID",
    identifier: Some("RunMat:setfield:InvalidIndex"),
    when: "Index component is malformed, empty, unsupported, or not a positive integer.",
    message: "setfield: invalid index element",
};

const SETFIELD_ERROR_FIELD_NAME_TYPE: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.SETFIELD.FIELD_NAME_TYPE",
    identifier: Some("RunMat:setfield:FieldNameType"),
    when: "Field name is not a scalar string or 1-by-N char vector.",
    message: "setfield: expected field name",
};

const SETFIELD_ERROR_INDEX_SHAPE: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.SETFIELD.INDEX_SHAPE",
    identifier: Some("RunMat:setfield:IndexShape"),
    when: "Indexing rank/shape is unsupported for the targeted value.",
    message: "setfield: unsupported index shape for target value",
};

const SETFIELD_ERROR_NON_STRUCT_ASSIGNMENT: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.SETFIELD.NON_STRUCT_ASSIGNMENT",
    identifier: Some("RunMat:setfield:NonStructAssignment"),
    when: "Assignment target does not support struct-like field updates.",
    message: "Struct contents assignment to a non-struct object is not supported.",
};

const SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.SETFIELD.INDEX_OUT_OF_BOUNDS",
    identifier: Some("RunMat:setfield:IndexOutOfBounds"),
    when: "Resolved index is outside bounds for target value.",
    message: "Index exceeds the number of array elements.",
};

const SETFIELD_ERROR_MISSING_FIELD: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.SETFIELD.MISSING_FIELD",
    identifier: Some("RunMat:setfield:MissingField"),
    when: "Indexed assignment path references a missing field.",
    message: "Reference to non-existent field",
};

const SETFIELD_ERROR_PROPERTY_PRIVATE_ACCESS: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.SETFIELD.PROPERTY_PRIVATE_ACCESS",
    identifier: Some("RunMat:PropertyPrivateAccess"),
    when: "Property exists but get/set access is private.",
    message: "setfield: private property access denied",
};

const SETFIELD_ERROR_PROPERTY_STATIC_ACCESS: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.SETFIELD.PROPERTY_STATIC_ACCESS",
    identifier: Some("RunMat:PropertyStaticAccess"),
    when: "Property exists but is static and cannot be assigned through an instance.",
    message: "setfield: static property access denied",
};

const SETFIELD_ERROR_OBJECT_PROPERTY: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.SETFIELD.OBJECT_PROPERTY",
    identifier: Some("RunMat:setfield:ObjectProperty"),
    when: "Object property operation is invalid (static, non-public, or malformed setter result).",
    message: "setfield: invalid object property operation",
};

const SETFIELD_ERROR_INVALID_HANDLE: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.SETFIELD.INVALID_HANDLE",
    identifier: Some("RunMat:setfield:InvalidHandle"),
    when: "Handle target is invalid/deleted/null.",
    message: "setfield: invalid or deleted handle object",
};

const SETFIELD_ERROR_INTERNAL: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.SETFIELD.INTERNAL",
    identifier: Some("RunMat:setfield:InternalError"),
    when: "Internal conversion/allocation failed while assigning values.",
    message: "setfield: internal error",
};

const SETFIELD_ERRORS: [BuiltinErrorDescriptor; 14] = [
    SETFIELD_ERROR_NOT_ENOUGH_INPUTS,
    SETFIELD_ERROR_FIELD_EXPECTED,
    SETFIELD_ERROR_INDEX_SELECTOR_TYPE,
    SETFIELD_ERROR_INDEX_INVALID,
    SETFIELD_ERROR_FIELD_NAME_TYPE,
    SETFIELD_ERROR_INDEX_SHAPE,
    SETFIELD_ERROR_NON_STRUCT_ASSIGNMENT,
    SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS,
    SETFIELD_ERROR_MISSING_FIELD,
    SETFIELD_ERROR_PROPERTY_PRIVATE_ACCESS,
    SETFIELD_ERROR_PROPERTY_STATIC_ACCESS,
    SETFIELD_ERROR_OBJECT_PROPERTY,
    SETFIELD_ERROR_INVALID_HANDLE,
    SETFIELD_ERROR_INTERNAL,
];

pub const SETFIELD_DESCRIPTOR: BuiltinDescriptor = BuiltinDescriptor {
    signatures: &SETFIELD_SIGNATURES,
    output_mode: BuiltinOutputMode::Fixed,
    completion_policy: BuiltinCompletionPolicy::Public,
    errors: &SETFIELD_ERRORS,
};

fn setfield_flow(message: impl Into<String>) -> RuntimeError {
    setfield_error_with_message(
        format!("{}: {}", SETFIELD_ERROR_INTERNAL.message, message.into()),
        &SETFIELD_ERROR_INTERNAL,
    )
}

fn setfield_error_with_message(
    message: impl Into<String>,
    error: &'static BuiltinErrorDescriptor,
) -> RuntimeError {
    let mut builder = build_runtime_error(message).with_builtin(BUILTIN_NAME);
    if let Some(identifier) = error.identifier {
        builder = builder.with_identifier(identifier);
    }
    builder.build()
}

fn setfield_private_access(message: impl Into<String>) -> RuntimeError {
    setfield_error_with_message(message, &SETFIELD_ERROR_PROPERTY_PRIVATE_ACCESS)
}

fn setfield_static_access(message: impl Into<String>) -> RuntimeError {
    setfield_error_with_message(message, &SETFIELD_ERROR_PROPERTY_STATIC_ACCESS)
}

fn remap_setfield_flow(err: RuntimeError, prefix: Option<&str>) -> RuntimeError {
    let mut message = err.message().to_string();
    if let Some(prefix) = prefix {
        if !message.starts_with(prefix) {
            message = format!("{prefix}{message}");
        }
    }
    let mut builder = build_runtime_error(message).with_builtin(BUILTIN_NAME);
    if let Some(identifier) = err.identifier() {
        builder = builder.with_identifier(identifier);
    }
    builder.with_source(err).build()
}

fn is_undefined_function(err: &RuntimeError) -> bool {
    err.identifier() == Some(crate::IDENT_UNDEFINED_FUNCTION)
}

#[runtime_builtin(
    name = "setfield",
    category = "structs/core",
    summary = "Assign values into struct fields, nested fields, or struct-array elements.",
    keywords = "setfield,struct,assignment,object property",
    type_resolver(setfield_type),
    descriptor(crate::builtins::structs::core::setfield::SETFIELD_DESCRIPTOR),
    builtin_path = "crate::builtins::structs::core::setfield"
)]
async fn setfield_builtin(base: Value, rest: Vec<Value>) -> BuiltinResult<Value> {
    let parsed = parse_arguments(rest)?;
    let ParsedArguments {
        leading_index,
        steps,
        value,
    } = parsed;
    assign_value(base, leading_index, steps, value).await
}

struct ParsedArguments {
    leading_index: Option<IndexSelector>,
    steps: Vec<FieldStep>,
    value: Value,
}

struct FieldStep {
    name: String,
    index: Option<IndexSelector>,
}

#[derive(Clone)]
struct IndexSelector {
    components: Vec<IndexComponent>,
}

#[derive(Clone)]
enum IndexComponent {
    Scalar(usize),
    End,
}

fn parse_arguments(mut rest: Vec<Value>) -> BuiltinResult<ParsedArguments> {
    if rest.len() < 2 {
        return Err(setfield_flow(SETFIELD_ERROR_NOT_ENOUGH_INPUTS.message));
    }

    let value = rest
        .pop()
        .expect("rest contains at least two elements after early return");

    let mut parsed = ParsedArguments {
        leading_index: None,
        steps: Vec::new(),
        value,
    };

    if let Some(first) = rest.first() {
        if is_index_selector(first) {
            let selector = rest.remove(0);
            parsed.leading_index = Some(parse_index_selector(selector)?);
        }
    }

    if rest.is_empty() {
        return Err(setfield_flow(SETFIELD_ERROR_FIELD_EXPECTED.message));
    }

    let mut iter = rest.into_iter().peekable();
    while let Some(arg) = iter.next() {
        let name = parse_field_name(arg)?;
        let mut step = FieldStep { name, index: None };
        if let Some(next) = iter.peek() {
            if is_index_selector(next) {
                let selector = iter.next().unwrap();
                step.index = Some(parse_index_selector(selector)?);
            }
        }
        parsed.steps.push(step);
    }

    if parsed.steps.is_empty() {
        return Err(setfield_flow(SETFIELD_ERROR_FIELD_EXPECTED.message));
    }

    Ok(parsed)
}

async fn assign_value(
    base: Value,
    leading_index: Option<IndexSelector>,
    steps: Vec<FieldStep>,
    rhs: Value,
) -> BuiltinResult<Value> {
    if steps.is_empty() {
        return Err(setfield_flow(SETFIELD_ERROR_FIELD_EXPECTED.message));
    }
    if let Some(selector) = leading_index {
        assign_with_leading_index(base, &selector, &steps, rhs).await
    } else {
        assign_without_leading_index(base, &steps, rhs).await
    }
}

async fn assign_with_leading_index(
    base: Value,
    selector: &IndexSelector,
    steps: &[FieldStep],
    rhs: Value,
) -> BuiltinResult<Value> {
    match base {
        Value::Cell(cell) => assign_into_struct_array(cell, selector, steps, rhs).await,
        other => Err(setfield_flow(format!(
            "setfield: leading indices require a struct array, got {other:?}"
        ))),
    }
}

async fn assign_without_leading_index(
    base: Value,
    steps: &[FieldStep],
    rhs: Value,
) -> BuiltinResult<Value> {
    match base {
        Value::Struct(struct_value) => assign_into_struct(struct_value, steps, rhs).await,
        Value::Object(object) => assign_into_object(object, steps, rhs).await,
        Value::Cell(cell) if is_struct_array(&cell) => {
            if cell.data.is_empty() {
                Err(setfield_flow(
                    "setfield: struct array is empty; supply indices in a cell array",
                ))
            } else {
                let selector = IndexSelector {
                    components: vec![IndexComponent::Scalar(1)],
                };
                assign_into_struct_array(cell, &selector, steps, rhs).await
            }
        }
        Value::HandleObject(handle) => assign_into_handle(handle, steps, rhs).await,
        Value::Listener(_) => Err(setfield_flow(
            "setfield: listeners do not support direct field assignment",
        )),
        other => Err(setfield_flow(format!(
            "setfield unsupported on this value for field '{}': {other:?}",
            steps.first().map(|s| s.name.as_str()).unwrap_or_default()
        ))),
    }
}

async fn assign_into_struct_array(
    mut cell: CellArray,
    selector: &IndexSelector,
    steps: &[FieldStep],
    rhs: Value,
) -> BuiltinResult<Value> {
    if selector.components.is_empty() {
        return Err(setfield_flow(
            "setfield: index cell must contain at least one element",
        ));
    }

    let resolved = resolve_indices(&Value::Cell(cell.clone()), selector)?;

    let position = match resolved.len() {
        1 => {
            let idx = resolved[0];
            if idx == 0 || idx > cell.data.len() {
                return Err(setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message));
            }
            idx - 1
        }
        2 => {
            let row = resolved[0];
            let col = resolved[1];
            if row == 0 || row > cell.rows || col == 0 || col > cell.cols {
                return Err(setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message));
            }
            (row - 1) * cell.cols + (col - 1)
        }
        _ => {
            return Err(setfield_flow(
                "setfield: indexing with more than two indices is not supported yet",
            ));
        }
    };

    let handle = cell
        .data
        .get(position)
        .ok_or_else(|| setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message))?
        .clone();

    let current = unsafe { &*handle.as_raw() }.clone();
    let updated = assign_into_value(current, steps, rhs).await?;
    cell.data[position] = allocate_cell_handle(updated)?;
    Ok(Value::Cell(cell))
}

#[async_recursion::async_recursion(?Send)]
async fn assign_into_value(value: Value, steps: &[FieldStep], rhs: Value) -> BuiltinResult<Value> {
    if steps.is_empty() {
        return Ok(rhs);
    }
    match value {
        Value::Struct(struct_value) => assign_into_struct(struct_value, steps, rhs).await,
        Value::Object(object) => assign_into_object(object, steps, rhs).await,
        Value::Cell(cell) => assign_into_cell(cell, steps, rhs).await,
        Value::HandleObject(handle) => assign_into_handle(handle, steps, rhs).await,
        Value::Listener(_) => Err(setfield_flow(
            "setfield: listeners do not support nested field assignment",
        )),
        other => Err(setfield_flow(format!(
            "Struct contents assignment to a {other:?} object is not supported."
        ))),
    }
}

#[async_recursion::async_recursion(?Send)]
async fn assign_into_struct(
    mut struct_value: StructValue,
    steps: &[FieldStep],
    rhs: Value,
) -> BuiltinResult<Value> {
    let (first, rest) = steps
        .split_first()
        .expect("steps is non-empty when assign_into_struct is called");

    if rest.is_empty() {
        if let Some(selector) = &first.index {
            let current = struct_value
                .fields
                .get(&first.name)
                .cloned()
                .ok_or_else(|| format!("Reference to non-existent field '{}'.", first.name))?;
            let updated = assign_with_selector(current, selector, &[], rhs).await?;
            struct_value.fields.insert(first.name.clone(), updated);
        } else {
            struct_value.fields.insert(first.name.clone(), rhs);
        }
        return Ok(Value::Struct(struct_value));
    }

    if let Some(selector) = &first.index {
        let current = struct_value
            .fields
            .get(&first.name)
            .cloned()
            .ok_or_else(|| format!("Reference to non-existent field '{}'.", first.name))?;
        let updated = assign_with_selector(current, selector, rest, rhs).await?;
        struct_value.fields.insert(first.name.clone(), updated);
        return Ok(Value::Struct(struct_value));
    }

    let current = struct_value
        .fields
        .get(&first.name)
        .cloned()
        .unwrap_or_else(|| Value::Struct(StructValue::new()));
    let updated = assign_into_value(current, rest, rhs).await?;
    struct_value.fields.insert(first.name.clone(), updated);
    Ok(Value::Struct(struct_value))
}

async fn assign_into_object(
    mut object: ObjectInstance,
    steps: &[FieldStep],
    rhs: Value,
) -> BuiltinResult<Value> {
    let (first, rest) = steps
        .split_first()
        .expect("steps is non-empty when assign_into_object is called");

    if first.index.is_some() {
        return Err(setfield_flow(
            "setfield: indexing into object properties is not currently supported",
        ));
    }

    if rest.is_empty() {
        write_object_property(&mut object, &first.name, rhs).await?;
        return Ok(Value::Object(object));
    }

    let current = read_object_property(&object, &first.name).await?;
    let updated = assign_into_value(current, rest, rhs).await?;
    write_object_property(&mut object, &first.name, updated).await?;
    Ok(Value::Object(object))
}

async fn assign_into_cell(
    cell: CellArray,
    steps: &[FieldStep],
    rhs: Value,
) -> BuiltinResult<Value> {
    let (first, rest) = steps
        .split_first()
        .expect("steps is non-empty when assign_into_cell is called");

    let selector = first.index.as_ref().ok_or_else(|| {
        setfield_flow("setfield: cell array assignments require indices in a cell array")
    })?;
    if rest.is_empty() {
        assign_with_selector(Value::Cell(cell), selector, &[], rhs).await
    } else {
        assign_with_selector(Value::Cell(cell), selector, rest, rhs).await
    }
}

#[async_recursion::async_recursion(?Send)]
async fn assign_with_selector(
    value: Value,
    selector: &IndexSelector,
    rest: &[FieldStep],
    rhs: Value,
) -> BuiltinResult<Value> {
    let host_value = gather_if_needed_async(&value)
        .await
        .map_err(|flow| remap_setfield_flow(flow, Some("setfield: ")))?;
    match host_value {
        Value::Cell(mut cell) => {
            let resolved = resolve_indices(&Value::Cell(cell.clone()), selector)?;
            let position = match resolved.len() {
                1 => {
                    let idx = resolved[0];
                    if idx == 0 || idx > cell.data.len() {
                        return Err(setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message));
                    }
                    idx - 1
                }
                2 => {
                    let row = resolved[0];
                    let col = resolved[1];
                    if row == 0 || row > cell.rows || col == 0 || col > cell.cols {
                        return Err(setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message));
                    }
                    (row - 1) * cell.cols + (col - 1)
                }
                _ => {
                    return Err(setfield_flow(
                        "setfield: indexing with more than two indices is not supported yet",
                    ));
                }
            };

            let handle = cell
                .data
                .get(position)
                .ok_or_else(|| setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message))?
                .clone();
            let existing = unsafe { &*handle.as_raw() }.clone();
            let new_value = if rest.is_empty() {
                rhs
            } else {
                assign_into_value(existing, rest, rhs).await?
            };
            cell.data[position] = allocate_cell_handle(new_value)?;
            Ok(Value::Cell(cell))
        }
        Value::Tensor(mut tensor) => {
            if !rest.is_empty() {
                return Err(setfield_flow(
                    "setfield: cannot traverse deeper fields after indexing into a numeric tensor",
                ));
            }
            assign_tensor_element(&mut tensor, selector, rhs)?;
            Ok(Value::Tensor(tensor))
        }
        Value::LogicalArray(mut logical) => {
            if !rest.is_empty() {
                return Err(setfield_flow(
                    "setfield: cannot traverse deeper fields after indexing into a logical array",
                ));
            }
            assign_logical_element(&mut logical, selector, rhs)?;
            Ok(Value::LogicalArray(logical))
        }
        Value::StringArray(mut sa) => {
            if !rest.is_empty() {
                return Err(setfield_flow(
                    "setfield: cannot traverse deeper fields after indexing into a string array",
                ));
            }
            assign_string_array_element(&mut sa, selector, rhs)?;
            Ok(Value::StringArray(sa))
        }
        Value::CharArray(mut ca) => {
            if !rest.is_empty() {
                return Err(setfield_flow(
                    "setfield: cannot traverse deeper fields after indexing into a char array",
                ));
            }
            assign_char_array_element(&mut ca, selector, rhs)?;
            Ok(Value::CharArray(ca))
        }
        Value::ComplexTensor(mut tensor) => {
            if !rest.is_empty() {
                return Err(setfield_flow(
                    "setfield: cannot traverse deeper fields after indexing into a complex tensor",
                ));
            }
            assign_complex_tensor_element(&mut tensor, selector, rhs)?;
            Ok(Value::ComplexTensor(tensor))
        }
        other => Err(setfield_flow(format!(
            "Struct contents assignment to a {other:?} object is not supported."
        ))),
    }
}

fn assign_tensor_element(
    tensor: &mut Tensor,
    selector: &IndexSelector,
    rhs: Value,
) -> BuiltinResult<()> {
    let resolved = resolve_indices(&Value::Tensor(tensor.clone()), selector)?;
    let value = value_to_scalar(rhs)?;
    match resolved.len() {
        1 => {
            let idx = resolved[0];
            if idx == 0 || idx > tensor.data.len() {
                return Err(setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message));
            }
            tensor.data[idx - 1] = value;
            Ok(())
        }
        2 => {
            let row = resolved[0];
            let col = resolved[1];
            if row == 0 || row > tensor.rows() || col == 0 || col > tensor.cols() {
                return Err(setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message));
            }
            let pos = (row - 1) + (col - 1) * tensor.rows();
            tensor
                .data
                .get_mut(pos)
                .map(|slot| *slot = value)
                .ok_or_else(|| setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message))
        }
        _ => Err(setfield_flow(
            "setfield: indexing with more than two indices is not supported yet",
        )),
    }
}

fn assign_logical_element(
    logical: &mut LogicalArray,
    selector: &IndexSelector,
    rhs: Value,
) -> BuiltinResult<()> {
    let resolved = resolve_indices(&Value::LogicalArray(logical.clone()), selector)?;
    let value = value_to_bool(rhs)?;
    match resolved.len() {
        1 => {
            let idx = resolved[0];
            if idx == 0 || idx > logical.data.len() {
                return Err(setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message));
            }
            logical.data[idx - 1] = if value { 1 } else { 0 };
            Ok(())
        }
        2 => {
            if logical.shape.len() < 2 {
                return Err(setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message));
            }
            let row = resolved[0];
            let col = resolved[1];
            let rows = logical.shape[0];
            let cols = logical.shape[1];
            if row == 0 || row > rows || col == 0 || col > cols {
                return Err(setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message));
            }
            let pos = (row - 1) + (col - 1) * rows;
            if pos >= logical.data.len() {
                return Err(setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message));
            }
            logical.data[pos] = if value { 1 } else { 0 };
            Ok(())
        }
        _ => Err(setfield_flow(
            "setfield: indexing with more than two indices is not supported yet",
        )),
    }
}

fn assign_string_array_element(
    array: &mut runmat_builtins::StringArray,
    selector: &IndexSelector,
    rhs: Value,
) -> BuiltinResult<()> {
    let resolved = resolve_indices(&Value::StringArray(array.clone()), selector)?;
    let text = String::try_from(&rhs).map_err(|_| {
        setfield_flow("setfield: string assignments require text-compatible values")
    })?;
    match resolved.len() {
        1 => {
            let idx = resolved[0];
            if idx == 0 || idx > array.data.len() {
                return Err(setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message));
            }
            array.data[idx - 1] = text;
            Ok(())
        }
        2 => {
            let row = resolved[0];
            let col = resolved[1];
            if row == 0 || row > array.rows || col == 0 || col > array.cols {
                return Err(setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message));
            }
            let pos = (row - 1) + (col - 1) * array.rows;
            if pos >= array.data.len() {
                return Err(setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message));
            }
            array.data[pos] = text;
            Ok(())
        }
        _ => Err(setfield_flow(
            "setfield: indexing with more than two indices is not supported yet",
        )),
    }
}

fn assign_char_array_element(
    array: &mut CharArray,
    selector: &IndexSelector,
    rhs: Value,
) -> BuiltinResult<()> {
    let resolved = resolve_indices(&Value::CharArray(array.clone()), selector)?;
    let text = String::try_from(&rhs)
        .map_err(|_| setfield_flow("setfield: char assignments require text-compatible values"))?;
    if text.chars().count() != 1 {
        return Err(setfield_flow(
            "setfield: char array assignments require single characters",
        ));
    }
    let ch = text.chars().next().unwrap();
    match resolved.len() {
        1 => {
            let idx = resolved[0];
            if idx == 0 || idx > array.data.len() {
                return Err(setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message));
            }
            array.data[idx - 1] = ch;
            Ok(())
        }
        2 => {
            let row = resolved[0];
            let col = resolved[1];
            if row == 0 || row > array.rows || col == 0 || col > array.cols {
                return Err(setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message));
            }
            let pos = (row - 1) * array.cols + (col - 1);
            if pos >= array.data.len() {
                return Err(setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message));
            }
            array.data[pos] = ch;
            Ok(())
        }
        _ => Err(setfield_flow(
            "setfield: indexing with more than two indices is not supported yet",
        )),
    }
}

fn assign_complex_tensor_element(
    tensor: &mut ComplexTensor,
    selector: &IndexSelector,
    rhs: Value,
) -> BuiltinResult<()> {
    let resolved = resolve_indices(&Value::ComplexTensor(tensor.clone()), selector)?;
    let (re, im) = match rhs {
        Value::Complex(r, i) => (r, i),
        Value::Num(n) => (n, 0.0),
        Value::Int(i) => (i.to_f64(), 0.0),
        other => {
            return Err(setfield_flow(format!(
                "setfield: cannot assign {other:?} into a complex tensor element"
            )));
        }
    };
    match resolved.len() {
        1 => {
            let idx = resolved[0];
            if idx == 0 || idx > tensor.data.len() {
                return Err(setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message));
            }
            tensor.data[idx - 1] = (re, im);
            Ok(())
        }
        2 => {
            let row = resolved[0];
            let col = resolved[1];
            if row == 0 || row > tensor.rows || col == 0 || col > tensor.cols {
                return Err(setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message));
            }
            let pos = (row - 1) + (col - 1) * tensor.rows;
            if pos >= tensor.data.len() {
                return Err(setfield_flow(SETFIELD_ERROR_INDEX_OUT_OF_BOUNDS.message));
            }
            tensor.data[pos] = (re, im);
            Ok(())
        }
        _ => Err(setfield_flow(
            "setfield: indexing with more than two indices is not supported yet",
        )),
    }
}

async fn read_object_property(obj: &ObjectInstance, name: &str) -> BuiltinResult<Value> {
    if let Some((prop, _owner)) = runmat_builtins::lookup_property(&obj.class_name, name) {
        if prop.is_static {
            return Err(setfield_flow(format!(
                "You cannot access the static property '{}' through an instance of class '{}'.",
                name, obj.class_name
            )));
        }
        if prop.get_access == Access::Private {
            return Err(setfield_private_access(format!(
                "You cannot get the '{}' property of '{}' class.",
                name, obj.class_name
            )));
        }
        if prop.is_dependent {
            let getter = object_property_getter_name(name);
            match call_builtin_async(&getter, &[Value::Object(obj.clone())]).await {
                Ok(value) => return Ok(value),
                Err(err) => {
                    if !is_undefined_function(&err) {
                        return Err(remap_setfield_flow(err, None));
                    }
                }
            }
            if let Some(value) = obj.properties.get(&format!("{name}_backing")) {
                return Ok(value.clone());
            }
        }
    }

    if let Some(value) = obj.properties.get(name) {
        return Ok(value.clone());
    }

    if let Some((prop, _owner)) = runmat_builtins::lookup_property(&obj.class_name, name) {
        if prop.get_access == Access::Private {
            return Err(setfield_private_access(format!(
                "You cannot get the '{}' property of '{}' class.",
                name, obj.class_name
            )));
        }
        return Err(setfield_flow(format!(
            "No public property '{}' for class '{}'.",
            name, obj.class_name
        )));
    }

    Err(setfield_flow(format!(
        "Undefined property '{}' for class {}",
        name, obj.class_name
    )))
}

async fn write_object_property(
    obj: &mut ObjectInstance,
    name: &str,
    rhs: Value,
) -> BuiltinResult<()> {
    if let Some((prop, _owner)) = runmat_builtins::lookup_property(&obj.class_name, name) {
        if prop.is_static {
            return Err(setfield_static_access(format!(
                "Property '{}' is static; use classref('{}').{}",
                name, obj.class_name, name
            )));
        }
        if prop.set_access == Access::Private {
            return Err(setfield_private_access(format!(
                "Property '{name}' is private"
            )));
        }
        if prop.is_dependent {
            let setter = object_property_setter_name(name);
            match call_builtin_async(&setter, &[Value::Object(obj.clone()), rhs.clone()]).await {
                Ok(value) => {
                    if let Value::Object(updated) = value {
                        *obj = updated;
                        return Ok(());
                    }
                    return Err(setfield_flow(format!(
                        "Dependent property setter for '{}' must return the updated object",
                        name
                    )));
                }
                Err(err) => {
                    if !is_undefined_function(&err) {
                        return Err(remap_setfield_flow(err, None));
                    }
                }
            }
            obj.properties.insert(format!("{name}_backing"), rhs);
            return Ok(());
        }
    }

    obj.properties.insert(name.to_string(), rhs);
    Ok(())
}

async fn assign_into_handle(
    handle: HandleRef,
    steps: &[FieldStep],
    rhs: Value,
) -> BuiltinResult<Value> {
    if steps.is_empty() {
        return Err(setfield_flow(
            "setfield: expected at least one field name when assigning into a handle",
        ));
    }
    if !runmat_builtins::is_handle_valid(&handle) {
        return Err(setfield_flow(format!(
            "Invalid or deleted handle object '{}'.",
            handle.class_name
        )));
    }
    let current = unsafe { &*handle.target.as_raw() }.clone();
    let updated = assign_into_value(current, steps, rhs).await?;
    let raw = unsafe { handle.target.as_raw_mut() };
    if raw.is_null() {
        return Err(setfield_flow("setfield: handle target is null"));
    }
    unsafe {
        *raw = updated;
    }
    Ok(Value::HandleObject(handle))
}

fn is_index_selector(value: &Value) -> bool {
    matches!(value, Value::Cell(_))
}

fn parse_index_selector(value: Value) -> BuiltinResult<IndexSelector> {
    let Value::Cell(cell) = value else {
        return Err(setfield_flow(SETFIELD_ERROR_INDEX_SELECTOR_TYPE.message));
    };
    let mut components = Vec::with_capacity(cell.data.len());
    for handle in &cell.data {
        let entry = unsafe { &*handle.as_raw() };
        components.push(parse_index_component(entry)?);
    }
    Ok(IndexSelector { components })
}

fn parse_index_component(value: &Value) -> BuiltinResult<IndexComponent> {
    match value {
        Value::CharArray(ca) => {
            let text: String = ca.data.iter().collect();
            parse_index_text(text.trim())
        }
        Value::String(s) => parse_index_text(s.trim()),
        Value::StringArray(sa) if sa.data.len() == 1 => parse_index_text(sa.data[0].trim()),
        _ => {
            let idx = parse_positive_scalar(value).map_err(|err| {
                setfield_flow(format!(
                    "setfield: invalid index element ({})",
                    err.message()
                ))
            })?;
            Ok(IndexComponent::Scalar(idx))
        }
    }
}

fn parse_index_text(text: &str) -> BuiltinResult<IndexComponent> {
    if text.eq_ignore_ascii_case("end") {
        return Ok(IndexComponent::End);
    }
    if text == ":" {
        return Err(setfield_flow(
            "setfield: ':' indexing is not currently supported",
        ));
    }
    if text.is_empty() {
        return Err(setfield_flow("setfield: index elements must not be empty"));
    }
    if let Ok(value) = text.parse::<usize>() {
        if value == 0 {
            return Err(setfield_flow("setfield: index must be >= 1"));
        }
        return Ok(IndexComponent::Scalar(value));
    }
    Err(setfield_flow(format!(
        "setfield: invalid index element '{}'",
        text
    )))
}

fn parse_positive_scalar(value: &Value) -> BuiltinResult<usize> {
    let number = match value {
        Value::Int(i) => i.to_i64() as f64,
        Value::Num(n) => *n,
        Value::Tensor(t) if t.data.len() == 1 => t.data[0],
        _ => {
            let repr = format!("{value:?}");
            return Err(setfield_flow(format!(
                "expected positive integer index, got {repr}"
            )));
        }
    };

    if !number.is_finite() {
        return Err(setfield_flow("index must be a finite number"));
    }
    if number.fract() != 0.0 {
        return Err(setfield_flow("index must be an integer"));
    }
    if number <= 0.0 {
        return Err(setfield_flow("index must be >= 1"));
    }
    if number > usize::MAX as f64 {
        return Err(setfield_flow("index exceeds platform limits"));
    }
    Ok(number as usize)
}

fn parse_field_name(value: Value) -> BuiltinResult<String> {
    match value {
        Value::String(s) => Ok(s),
        Value::StringArray(sa) => {
            if sa.data.len() == 1 {
                Ok(sa.data[0].clone())
            } else {
                Err(setfield_flow(
                    "setfield: field names must be scalar string arrays or character vectors",
                ))
            }
        }
        Value::CharArray(ca) => {
            if ca.rows == 1 {
                Ok(ca.data.iter().collect())
            } else {
                Err(setfield_flow(
                    "setfield: field names must be 1-by-N character vectors",
                ))
            }
        }
        other => Err(setfield_flow(format!(
            "setfield: expected field name, got {other:?}"
        ))),
    }
}

fn resolve_indices(value: &Value, selector: &IndexSelector) -> BuiltinResult<Vec<usize>> {
    let dims = selector.components.len();
    let mut resolved = Vec::with_capacity(dims);
    for (dim_idx, component) in selector.components.iter().enumerate() {
        let index = match component {
            IndexComponent::Scalar(idx) => *idx,
            IndexComponent::End => dimension_length(value, dims, dim_idx)?,
        };
        resolved.push(index);
    }
    Ok(resolved)
}

fn dimension_length(value: &Value, dims: usize, dim_idx: usize) -> BuiltinResult<usize> {
    match value {
        Value::Tensor(tensor) => tensor_dimension_length(tensor, dims, dim_idx),
        Value::Cell(cell) => cell_dimension_length(cell, dims, dim_idx),
        Value::StringArray(array) => string_array_dimension_length(array, dims, dim_idx),
        Value::LogicalArray(logical) => logical_array_dimension_length(logical, dims, dim_idx),
        Value::CharArray(array) => char_array_dimension_length(array, dims, dim_idx),
        Value::ComplexTensor(tensor) => complex_tensor_dimension_length(tensor, dims, dim_idx),
        Value::Num(_) | Value::Int(_) | Value::Bool(_) => {
            if dims == 1 {
                Ok(1)
            } else {
                Err(setfield_flow(
                    "setfield: indexing with more than one dimension is not supported for scalars",
                ))
            }
        }
        other => Err(setfield_flow(format!(
            "Struct contents assignment to a {other:?} object is not supported."
        ))),
    }
}

fn tensor_dimension_length(tensor: &Tensor, dims: usize, dim_idx: usize) -> BuiltinResult<usize> {
    if dims == 1 {
        let total = tensor.data.len();
        if total == 0 {
            return Err(setfield_flow(
                "Index exceeds the number of array elements (0).",
            ));
        }
        return Ok(total);
    }
    if dims > 2 {
        return Err(setfield_flow(
            "setfield: indexing with more than two indices is not supported yet",
        ));
    }
    let len = if dim_idx == 0 {
        tensor.rows()
    } else {
        tensor.cols()
    };
    if len == 0 {
        return Err(setfield_flow(
            "Index exceeds the number of array elements (0).",
        ));
    }
    Ok(len)
}

fn cell_dimension_length(cell: &CellArray, dims: usize, dim_idx: usize) -> BuiltinResult<usize> {
    if dims == 1 {
        let total = cell.data.len();
        if total == 0 {
            return Err(setfield_flow(
                "Index exceeds the number of array elements (0).",
            ));
        }
        return Ok(total);
    }
    if dims > 2 {
        return Err(setfield_flow(
            "setfield: indexing with more than two indices is not supported yet",
        ));
    }
    let len = if dim_idx == 0 { cell.rows } else { cell.cols };
    if len == 0 {
        return Err(setfield_flow(
            "Index exceeds the number of array elements (0).",
        ));
    }
    Ok(len)
}

fn string_array_dimension_length(
    array: &runmat_builtins::StringArray,
    dims: usize,
    dim_idx: usize,
) -> BuiltinResult<usize> {
    if dims == 1 {
        let total = array.data.len();
        if total == 0 {
            return Err(setfield_flow(
                "Index exceeds the number of array elements (0).",
            ));
        }
        return Ok(total);
    }
    if dims > 2 {
        return Err(setfield_flow(
            "setfield: indexing with more than two indices is not supported yet",
        ));
    }
    let len = if dim_idx == 0 { array.rows } else { array.cols };
    if len == 0 {
        return Err(setfield_flow(
            "Index exceeds the number of array elements (0).",
        ));
    }
    Ok(len)
}

fn logical_array_dimension_length(
    array: &LogicalArray,
    dims: usize,
    dim_idx: usize,
) -> BuiltinResult<usize> {
    if dims == 1 {
        let total = array.data.len();
        if total == 0 {
            return Err(setfield_flow(
                "Index exceeds the number of array elements (0).",
            ));
        }
        return Ok(total);
    }
    if dims > 2 {
        return Err(setfield_flow(
            "setfield: indexing with more than two indices is not supported yet",
        ));
    }
    if array.shape.len() < dims {
        return Err(setfield_flow(
            "Index exceeds the number of array elements (0).",
        ));
    }
    let len = array.shape[dim_idx];
    if len == 0 {
        return Err(setfield_flow(
            "Index exceeds the number of array elements (0).",
        ));
    }
    Ok(len)
}

fn char_array_dimension_length(
    array: &CharArray,
    dims: usize,
    dim_idx: usize,
) -> BuiltinResult<usize> {
    if dims == 1 {
        let total = array.data.len();
        if total == 0 {
            return Err(setfield_flow(
                "Index exceeds the number of array elements (0).",
            ));
        }
        return Ok(total);
    }
    if dims > 2 {
        return Err(setfield_flow(
            "setfield: indexing with more than two indices is not supported yet",
        ));
    }
    let len = if dim_idx == 0 { array.rows } else { array.cols };
    if len == 0 {
        return Err(setfield_flow(
            "Index exceeds the number of array elements (0).",
        ));
    }
    Ok(len)
}

fn complex_tensor_dimension_length(
    tensor: &ComplexTensor,
    dims: usize,
    dim_idx: usize,
) -> BuiltinResult<usize> {
    if dims == 1 {
        let total = tensor.data.len();
        if total == 0 {
            return Err(setfield_flow(
                "Index exceeds the number of array elements (0).",
            ));
        }
        return Ok(total);
    }
    if dims > 2 {
        return Err(setfield_flow(
            "setfield: indexing with more than two indices is not supported yet",
        ));
    }
    let len = if dim_idx == 0 {
        tensor.rows
    } else {
        tensor.cols
    };
    if len == 0 {
        return Err(setfield_flow(
            "Index exceeds the number of array elements (0).",
        ));
    }
    Ok(len)
}

fn value_to_scalar(value: Value) -> BuiltinResult<f64> {
    match value {
        Value::Num(n) => Ok(n),
        Value::Int(i) => Ok(i.to_f64()),
        Value::Bool(b) => Ok(if b { 1.0 } else { 0.0 }),
        Value::Tensor(t) if t.data.len() == 1 => Ok(t.data[0]),
        other => Err(setfield_flow(format!(
            "setfield: cannot assign {other:?} into a numeric tensor element"
        ))),
    }
}

fn value_to_bool(value: Value) -> BuiltinResult<bool> {
    match value {
        Value::Bool(b) => Ok(b),
        Value::Num(n) => Ok(n != 0.0),
        Value::Int(i) => Ok(i.to_i64() != 0),
        Value::Tensor(t) if t.data.len() == 1 => Ok(t.data[0] != 0.0),
        other => Err(setfield_flow(format!(
            "setfield: cannot assign {other:?} into a logical array element"
        ))),
    }
}

fn allocate_cell_handle(value: Value) -> BuiltinResult<GcPtr<Value>> {
    runmat_gc::gc_allocate(value).map_err(|e| {
        setfield_flow(format!(
            "setfield: failed to allocate cell element in GC: {e}"
        ))
    })
}

fn is_struct_array(cell: &CellArray) -> bool {
    cell.data
        .iter()
        .all(|handle| matches!(unsafe { &*handle.as_raw() }, Value::Struct(_)))
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use runmat_builtins::{
        Access, CellArray, ClassDef, HandleRef, IntValue, ObjectInstance, PropertyDef, StructValue,
    };
    use runmat_gc::gc_allocate;

    fn error_message(err: crate::RuntimeError) -> String {
        err.message().to_string()
    }

    fn run_setfield(base: Value, rest: Vec<Value>) -> BuiltinResult<Value> {
        futures::executor::block_on(setfield_builtin(base, rest))
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn setfield_creates_scalar_field() {
        let struct_value = StructValue::new();
        let updated = run_setfield(
            Value::Struct(struct_value),
            vec![Value::from("answer"), Value::Num(42.0)],
        )
        .expect("setfield");
        match updated {
            Value::Struct(st) => {
                assert_eq!(
                    st.fields.get("answer"),
                    Some(&Value::Num(42.0)),
                    "field should be inserted"
                );
            }
            other => panic!("expected struct result, got {other:?}"),
        }
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn setfield_creates_nested_structs() {
        let struct_value = StructValue::new();
        let updated = run_setfield(
            Value::Struct(struct_value),
            vec![
                Value::from("solver"),
                Value::from("name"),
                Value::from("cg"),
            ],
        )
        .expect("setfield");
        match updated {
            Value::Struct(st) => {
                let solver = st.fields.get("solver").expect("solver field");
                match solver {
                    Value::Struct(inner) => {
                        assert_eq!(
                            inner.fields.get("name"),
                            Some(&Value::from("cg")),
                            "inner field should exist"
                        );
                    }
                    other => panic!("expected inner struct, got {other:?}"),
                }
            }
            other => panic!("expected struct result, got {other:?}"),
        }
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn setfield_updates_struct_array_element() {
        let mut a = StructValue::new();
        a.fields
            .insert("id".to_string(), Value::Int(IntValue::I32(1)));
        let mut b = StructValue::new();
        b.fields
            .insert("id".to_string(), Value::Int(IntValue::I32(2)));
        let array = CellArray::new_with_shape(vec![Value::Struct(a), Value::Struct(b)], vec![1, 2])
            .unwrap();
        let indices =
            CellArray::new_with_shape(vec![Value::Int(IntValue::I32(2))], vec![1, 1]).unwrap();
        let updated = run_setfield(
            Value::Cell(array),
            vec![
                Value::Cell(indices),
                Value::from("id"),
                Value::Int(IntValue::I32(42)),
            ],
        )
        .expect("setfield");
        match updated {
            Value::Cell(cell) => {
                let second = unsafe { &*cell.data[1].as_raw() }.clone();
                match second {
                    Value::Struct(st) => {
                        assert_eq!(st.fields.get("id"), Some(&Value::Int(IntValue::I32(42))));
                    }
                    other => panic!("expected struct element, got {other:?}"),
                }
            }
            other => panic!("expected cell array, got {other:?}"),
        }
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn setfield_assigns_into_cell_then_struct() {
        let mut inner1 = StructValue::new();
        inner1.fields.insert("value".to_string(), Value::Num(1.0));
        let mut inner2 = StructValue::new();
        inner2.fields.insert("value".to_string(), Value::Num(2.0));
        let cell = CellArray::new_with_shape(
            vec![Value::Struct(inner1), Value::Struct(inner2)],
            vec![1, 2],
        )
        .unwrap();
        let mut root = StructValue::new();
        root.fields.insert("samples".to_string(), Value::Cell(cell));

        let index_cell =
            CellArray::new_with_shape(vec![Value::Int(IntValue::I32(2))], vec![1, 1]).unwrap();
        let updated = run_setfield(
            Value::Struct(root),
            vec![
                Value::from("samples"),
                Value::Cell(index_cell),
                Value::from("value"),
                Value::Num(10.0),
            ],
        )
        .expect("setfield");

        match updated {
            Value::Struct(st) => {
                let samples = st.fields.get("samples").expect("samples field");
                match samples {
                    Value::Cell(cell) => {
                        let value = unsafe { &*cell.data[1].as_raw() }.clone();
                        match value {
                            Value::Struct(inner) => {
                                assert_eq!(inner.fields.get("value"), Some(&Value::Num(10.0)));
                            }
                            other => panic!("expected struct, got {other:?}"),
                        }
                    }
                    other => panic!("expected cell array, got {other:?}"),
                }
            }
            other => panic!("expected struct, got {other:?}"),
        }
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn setfield_struct_array_with_end_index() {
        let mut first = StructValue::new();
        first
            .fields
            .insert("id".to_string(), Value::Int(IntValue::I32(1)));
        let mut second = StructValue::new();
        second
            .fields
            .insert("id".to_string(), Value::Int(IntValue::I32(2)));
        let array = CellArray::new_with_shape(
            vec![Value::Struct(first), Value::Struct(second)],
            vec![1, 2],
        )
        .unwrap();
        let index_cell = CellArray::new_with_shape(vec![Value::from("end")], vec![1, 1]).unwrap();
        let updated = run_setfield(
            Value::Cell(array),
            vec![
                Value::Cell(index_cell),
                Value::from("id"),
                Value::Int(IntValue::I32(99)),
            ],
        )
        .expect("setfield");
        match updated {
            Value::Cell(cell) => {
                let second = unsafe { &*cell.data[1].as_raw() }.clone();
                match second {
                    Value::Struct(st) => {
                        assert_eq!(st.fields.get("id"), Some(&Value::Int(IntValue::I32(99))));
                    }
                    other => panic!("expected struct element, got {other:?}"),
                }
            }
            other => panic!("expected cell array result, got {other:?}"),
        }
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn setfield_assigns_object_property() {
        let mut class_def = ClassDef {
            name: "Simple".to_string(),
            parent: None,
            properties: Default::default(),
            methods: Default::default(),
        };
        class_def.properties.insert(
            "x".to_string(),
            PropertyDef {
                name: "x".to_string(),
                is_static: false,
                is_constant: false,
                is_dependent: false,
                get_access: Access::Public,
                set_access: Access::Public,
                default_value: None,
            },
        );
        runmat_builtins::register_class(class_def);

        let mut obj = ObjectInstance::new("Simple".to_string());
        obj.properties.insert("x".to_string(), Value::Num(0.0));

        let updated = run_setfield(Value::Object(obj), vec![Value::from("x"), Value::Num(5.0)])
            .expect("setfield");

        match updated {
            Value::Object(o) => {
                assert_eq!(o.properties.get("x"), Some(&Value::Num(5.0)));
            }
            other => panic!("expected object result, got {other:?}"),
        }
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn setfield_errors_when_indexing_missing_field() {
        let struct_value = StructValue::new();
        let index_cell =
            CellArray::new_with_shape(vec![Value::Int(IntValue::I32(1))], vec![1, 1]).unwrap();
        let err = error_message(
            run_setfield(
                Value::Struct(struct_value),
                vec![
                    Value::from("missing"),
                    Value::Cell(index_cell),
                    Value::Num(1.0),
                ],
            )
            .expect_err("setfield should fail when field is missing"),
        );
        assert!(
            err.contains("Reference to non-existent field 'missing'."),
            "unexpected error message: {err}"
        );
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn setfield_errors_on_static_property_assignment() {
        let mut class_def = ClassDef {
            name: "StaticSetfield".to_string(),
            parent: None,
            properties: Default::default(),
            methods: Default::default(),
        };
        class_def.properties.insert(
            "version".to_string(),
            PropertyDef {
                name: "version".to_string(),
                is_static: true,
                is_constant: false,
                is_dependent: false,
                get_access: Access::Public,
                set_access: Access::Public,
                default_value: None,
            },
        );
        runmat_builtins::register_class(class_def);

        let obj = ObjectInstance::new("StaticSetfield".to_string());
        let err = error_message(
            run_setfield(
                Value::Object(obj),
                vec![Value::from("version"), Value::Num(2.0)],
            )
            .expect_err("setfield should reject static property writes"),
        );
        assert!(
            err.contains("Property 'version' is static"),
            "unexpected error message: {err}"
        );
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn setfield_rejects_inherited_static_property_assignment() {
        let parent_name = "runmat.unittest.StaticSetfieldParent";
        let child_name = "runmat.unittest.StaticSetfieldChild";

        let mut parent = ClassDef {
            name: parent_name.to_string(),
            parent: None,
            properties: Default::default(),
            methods: Default::default(),
        };
        parent.properties.insert(
            "version".to_string(),
            PropertyDef {
                name: "version".to_string(),
                is_static: true,
                is_constant: false,
                is_dependent: false,
                get_access: Access::Public,
                set_access: Access::Public,
                default_value: None,
            },
        );
        runmat_builtins::register_class(parent);
        runmat_builtins::register_class(ClassDef {
            name: child_name.to_string(),
            parent: Some(parent_name.to_string()),
            properties: Default::default(),
            methods: Default::default(),
        });

        let obj = ObjectInstance::new(child_name.to_string());
        let err = error_message(
            run_setfield(
                Value::Object(obj),
                vec![Value::from("version"), Value::Num(2.0)],
            )
            .expect_err("setfield should reject inherited static property writes"),
        );
        assert!(
            err.contains("Property 'version' is static"),
            "unexpected error message: {err}"
        );
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn setfield_updates_handle_target() {
        let mut inner = StructValue::new();
        inner.fields.insert("x".to_string(), Value::Num(0.0));
        let gc_ptr = gc_allocate(Value::Struct(inner)).expect("gc allocation");
        let handle_ptr = gc_ptr.clone();
        let handle = HandleRef {
            class_name: "PointHandle".to_string(),
            target: handle_ptr,
            valid: true,
        };

        let updated = run_setfield(
            Value::HandleObject(handle.clone()),
            vec![Value::from("x"), Value::Num(7.0)],
        )
        .expect("setfield handle update");

        match updated {
            Value::HandleObject(h) => assert!(runmat_builtins::is_handle_valid(&h)),
            other => panic!("expected handle, got {other:?}"),
        }

        let pointee = unsafe { &*gc_ptr.as_raw() };
        match pointee {
            Value::Struct(st) => {
                assert_eq!(st.fields.get("x"), Some(&Value::Num(7.0)));
            }
            other => panic!("expected struct pointee, got {other:?}"),
        }
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    #[cfg(feature = "wgpu")]
    fn setfield_gpu_tensor_indexing_gathers_to_host() {
        use runmat_accelerate::backend::wgpu::provider::{
            register_wgpu_provider, WgpuProviderOptions,
        };
        use runmat_accelerate_api::HostTensorView;

        if runmat_accelerate_api::provider().is_none()
            && register_wgpu_provider(WgpuProviderOptions::default()).is_err()
        {
            runmat_accelerate::simple_provider::register_inprocess_provider();
        }

        let provider = runmat_accelerate_api::provider().expect("accel provider");
        let data = [1.0, 2.0, 3.0, 4.0];
        let shape = [2usize, 2usize];
        let view = HostTensorView {
            data: &data,
            shape: &shape,
        };
        let handle = provider.upload(&view).expect("upload");

        let mut root = StructValue::new();
        root.fields
            .insert("values".to_string(), Value::GpuTensor(handle));

        let index_cell = CellArray::new_with_shape(
            vec![Value::Int(IntValue::I32(2)), Value::Int(IntValue::I32(2))],
            vec![1, 2],
        )
        .unwrap();

        let updated = run_setfield(
            Value::Struct(root),
            vec![
                Value::from("values"),
                Value::Cell(index_cell),
                Value::Num(99.0),
            ],
        )
        .expect("setfield gpu value");

        match updated {
            Value::Struct(st) => {
                let values = st.fields.get("values").expect("values field");
                match values {
                    Value::Tensor(tensor) => {
                        assert_eq!(tensor.shape, vec![2, 2]);
                        assert_eq!(tensor.data[3], 99.0);
                    }
                    other => panic!("expected tensor after gather, got {other:?}"),
                }
            }
            other => panic!("expected struct result, got {other:?}"),
        }
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn setfield_undefined_detection_requires_identifier() {
        let with_identifier = build_runtime_error("missing")
            .with_identifier(crate::IDENT_UNDEFINED_FUNCTION)
            .build();
        assert!(is_undefined_function(&with_identifier));

        let message_only =
            build_runtime_error(format!("{} message only", crate::IDENT_UNDEFINED_FUNCTION))
                .build();
        assert!(
            !is_undefined_function(&message_only),
            "message-only undefined markers should not trigger setter fallback"
        );
    }
}