uiua 0.18.1

A stack-based array programming language
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
//! The Uiua interpreter/runtime

use std::{
    cell::RefCell,
    cmp::Ordering,
    collections::HashMap,
    hash::Hash,
    mem::{size_of, take},
    panic::{AssertUnwindSafe, catch_unwind},
    path::{Path, PathBuf},
    str::FromStr,
    sync::Arc,
    time::Duration,
};

use crossbeam_channel::{Receiver, Sender, TryRecvError};
use ecow::EcoVec;
use parking_lot::Mutex;
use thread_local::ThreadLocal;
use threadpool::ThreadPool;

use crate::{
    Array, Assembly, BindingKind, BindingMeta, Boxed, CodeSpan, Compiler, Function, FunctionId,
    Ident, Inputs, IntoSysBackend, LocalIndex, Node, Primitive, Report, SafeSys, SigNode,
    Signature, Span, SysBackend, TraceFrame, UiuaError, UiuaErrorKind, UiuaResult, VERSION, Value,
    algorithm::{self, validate_size_impl},
    fill::{Fill, FillFrame, FillValue},
    invert::match_format_pattern,
    run_prim_func, run_prim_mod,
};

/// The Uiua interpreter
#[derive(Clone)]
pub struct Uiua {
    pub(crate) rt: Runtime,
    /// The compiled assembly
    pub asm: Assembly,
}

/// Runtime-only data
#[derive(Clone)]
pub(crate) struct Runtime {
    /// The thread's stack
    pub(crate) stack: Vec<Value>,
    /// The thread's under stack
    pub(crate) under_stack: Vec<Value>,
    /// The call stack
    pub(crate) call_stack: Vec<StackFrame>,
    /// The local stack
    pub(crate) local_stack: EcoVec<(usize, Value)>,
    /// The stack for tracking recursion points
    recur_stack: Vec<usize>,
    /// The fill stack
    fill_stack: Vec<FillFrame>,
    /// The unfill stack
    unfill_stack: Vec<FillFrame>,
    /// The fill boundary stack
    fill_boundary_stack: Vec<(usize, usize)>,
    /// A limit on the execution duration in milliseconds
    pub(crate) execution_limit: Option<f64>,
    /// The time at which execution started
    pub(crate) execution_start: f64,
    /// The recursion limit
    recursion_limit: usize,
    /// Whether the program was interrupted
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) interrupted: Option<Arc<dyn Fn() -> bool + Send + Sync>>,
    #[cfg(target_arch = "wasm32")]
    pub(crate) interrupted: Option<Arc<dyn Fn() -> bool>>,
    /// Whether to print the time taken to execute each instruction
    time_instrs: bool,
    /// The time at which the last instruction was executed
    last_time: f64,
    /// Arguments passed from the command line
    cli_arguments: Vec<String>,
    /// File that was passed to the interpreter for execution
    cli_file_path: PathBuf,
    /// Code for unevaluated pure constants, in case they are needed for macros
    ///
    /// This should only be used in the compile-time environment
    pub(crate) unevaluated_constants: HashMap<usize, Node>,
    /// The system backend
    pub(crate) backend: Arc<dyn SysBackend>,
    /// The thread pool
    thread_pool: Arc<Mutex<Option<ThreadPool>>>,
    /// The thread interface
    thread: ThisThread,
    /// Values for output comments
    pub(crate) output_comments: HashMap<usize, Vec<Vec<Value>>>,
    /// Memoized values
    pub(crate) memo: Arc<ThreadLocal<RefCell<MemoMap>>>,
    /// The results of tests
    pub(crate) test_results: Vec<UiuaResult>,
    /// Reports to print
    pub(crate) reports: Vec<Report>,
}

type MemoMap = HashMap<Node, HashMap<Vec<Value>, Vec<Value>>>;

impl AsRef<Assembly> for Uiua {
    fn as_ref(&self) -> &Assembly {
        &self.asm
    }
}

impl AsMut<Assembly> for Uiua {
    fn as_mut(&mut self) -> &mut Assembly {
        &mut self.asm
    }
}

#[derive(Debug, Clone, Default)]
pub(crate) struct StackFrame {
    pub(crate) sig: Signature,
    pub(crate) id: Option<FunctionId>,
    track_caller: bool,
    /// The span at which the function was called
    pub(crate) call_span: usize,
    /// Additional spans for error reporting
    spans: Vec<(usize, Option<Primitive>)>,
    /// The stack height at the start of the function
    pub(crate) start_height: usize,
}

#[derive(Debug, Clone)]
struct Channel {
    pub send: Sender<Value>,
    pub recv: Receiver<Value>,
}

#[derive(Debug, Clone)]
struct ThisThread {
    pub parent: Option<Channel>,
    pub children: HashMap<usize, Thread>,
    pub next_child_id: usize,
}

impl Default for ThisThread {
    fn default() -> Self {
        Self {
            parent: Default::default(),
            children: Default::default(),
            next_child_id: 1,
        }
    }
}

#[derive(Debug, Clone)]
struct Thread {
    #[cfg(not(target_arch = "wasm32"))]
    pub recv: Receiver<UiuaResult<Vec<Value>>>,
    #[cfg(target_arch = "wasm32")]
    pub result: UiuaResult<Vec<Value>>,
    pub channel: Channel,
}

impl Default for Uiua {
    fn default() -> Self {
        Self::with_safe_sys()
    }
}

/// A mode that affects how non-binding lines are run
///
/// Regardless of the mode, lines with a call to `import` will always be run
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum RunMode {
    /// Only run lines outside of test blocks
    #[default]
    Normal,
    /// Only run non-binding lines inside of test blocks
    Test,
    /// Run everything
    All,
}

impl FromStr for RunMode {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "normal" => Ok(RunMode::Normal),
            "test" => Ok(RunMode::Test),
            "all" => Ok(RunMode::All),
            _ => Err(format!("unknown run mode `{s}`")),
        }
    }
}

impl Default for Runtime {
    fn default() -> Self {
        Runtime {
            stack: Vec::new(),
            under_stack: Vec::new(),
            call_stack: vec![StackFrame {
                id: Some(FunctionId::Main),
                ..Default::default()
            }],
            local_stack: EcoVec::new(),
            recur_stack: Vec::new(),
            fill_stack: Vec::new(),
            fill_boundary_stack: Vec::new(),
            unfill_stack: Vec::new(),
            backend: Arc::new(SafeSys::default()),
            time_instrs: false,
            last_time: 0.0,
            cli_arguments: Vec::new(),
            cli_file_path: PathBuf::new(),
            execution_limit: None,
            execution_start: 0.0,
            #[cfg(debug_assertions)]
            recursion_limit: 20,
            #[cfg(not(debug_assertions))]
            recursion_limit: std::env::var("UIUA_RECURSION_LIMIT")
                .ok()
                .and_then(|s| s.parse().ok())
                .unwrap_or(100),
            interrupted: None,
            thread_pool: Arc::new(Mutex::new(None)),
            thread: ThisThread::default(),
            output_comments: HashMap::new(),
            memo: Arc::new(ThreadLocal::new()),
            unevaluated_constants: HashMap::new(),
            test_results: Vec::new(),
            reports: Vec::new(),
        }
    }
}

impl Uiua {
    /// Create a new Uiua runtime with the standard IO backend
    #[cfg(feature = "native_sys")]
    pub fn with_native_sys() -> Self {
        Self::with_backend(crate::NativeSys)
    }
    /// Create a new Uiua runtime with no IO capabilities
    pub fn with_safe_sys() -> Self {
        Self::with_backend(SafeSys::default())
    }
    /// Create a new Uiua runtime with a custom IO backend
    pub fn with_backend(backend: impl IntoSysBackend) -> Self {
        Uiua {
            rt: Runtime {
                backend: backend.into_sys_backend(),
                ..Runtime::default()
            },
            asm: Assembly::default(),
        }
    }
    /// Build an assembly
    pub fn build(self) -> Assembly {
        self.asm
    }
    /// Get a reference to the system backend
    pub fn backend(&self) -> &dyn SysBackend {
        &*self.rt.backend
    }
    /// Attempt to downcast the system backend to a concrete reference type
    pub fn downcast_backend<T: SysBackend>(&self) -> Option<&T> {
        self.rt.backend.any().downcast_ref()
    }
    /// Attempt to downcast the system backend to a concrete mutable type
    pub fn downcast_backend_mut<T: SysBackend>(&mut self) -> Option<&mut T> {
        Arc::get_mut(&mut self.rt.backend).and_then(|b| b.any_mut().downcast_mut())
    }
    /// Take the system backend
    pub fn take_backend<T: SysBackend + Default>(&mut self) -> Option<T> {
        self.downcast_backend_mut::<T>().map(take)
    }
    /// Take all pending reports
    pub fn take_reports(&mut self) -> Vec<Report> {
        take(&mut self.rt.reports)
    }
    /// Print all pending reports
    #[allow(clippy::print_stdout)]
    pub fn print_reports(&mut self) {
        for report in self.take_reports() {
            eprintln!("{report}");
        }
    }
    /// Take the assembly
    pub fn take_asm(&mut self) -> Assembly {
        take(&mut self.asm)
    }
    /// Set whether to emit the time taken to execute each instruction
    pub fn time_instrs(mut self, time_instrs: bool) -> Self {
        self.rt.time_instrs = time_instrs;
        self
    }
    /// Limit the execution duration
    pub fn with_execution_limit(mut self, limit: Duration) -> Self {
        self.rt.execution_limit = Some(limit.as_secs_f64());
        self
    }
    /// Limit the execution duration
    pub fn maybe_with_execution_limit(mut self, limit: Option<Duration>) -> Self {
        self.rt.execution_limit = limit.map(|limit| limit.as_secs_f64());
        self
    }
    /// Set the recursion limit
    ///
    /// Default is 100 for release builds and 20 for debug builds
    pub fn with_recursion_limit(mut self, limit: usize) -> Self {
        self.rt.recursion_limit = limit;
        self
    }
    /// Set the interrupted hook
    #[cfg(not(target_arch = "wasm32"))]
    pub fn with_interrupt_hook(mut self, hook: impl Fn() -> bool + Send + Sync + 'static) -> Self {
        self.rt.interrupted = Some(Arc::new(hook));
        self
    }
    #[cfg(target_arch = "wasm32")]
    /// Set the interrupted hook
    pub fn with_interrupt_hook(mut self, hook: impl Fn() -> bool + 'static) -> Self {
        self.rt.interrupted = Some(Arc::new(hook));
        self
    }
    /// Set the command line arguments
    pub fn with_args(mut self, args: Vec<String>) -> Self {
        self.rt.cli_arguments = args;
        self
    }
    /// Get the command line arguments
    pub fn args(&self) -> &[String] {
        self.rt.cli_arguments.as_slice()
    }
    /// Set the path of the file that is being executed
    pub fn with_file_path(mut self, file_path: impl Into<PathBuf>) -> Self {
        self.rt.cli_file_path = file_path.into();
        self
    }
    /// Get the path of the file that is being executed
    pub fn file_path(&self) -> &Path {
        self.rt.cli_file_path.as_path()
    }
    /// Get the input code
    pub fn inputs(&self) -> &Inputs {
        &self.asm.inputs
    }
    /// Configure the compiler, compile, and run
    pub fn compile_run(
        &mut self,
        compile: impl FnOnce(&mut Compiler) -> UiuaResult<&mut Compiler>,
    ) -> UiuaResult<Compiler> {
        let mut comp = Compiler::with_backend(self.rt.backend.clone());
        let asm = compile(&mut comp)?.finish();
        self.run_asm(asm)?;
        comp.set_backend(SafeSys::default());
        Ok(comp)
    }
    /// Run a string as Uiua code
    pub fn run_str(&mut self, input: &str) -> UiuaResult<Compiler> {
        self.compile_run(|comp| comp.load_str(input))
    }
    /// Run a file as Uiua code
    pub fn run_file<P: AsRef<Path>>(&mut self, path: P) -> UiuaResult<Compiler> {
        self.compile_run(|comp| comp.load_file(path))
    }
    /// Run from a compiler
    ///
    /// The runtime will inherit the system backend from the compiler
    pub fn run_compiler(&mut self, compiler: &mut Compiler) -> UiuaResult {
        let backup = compiler.clone();
        self.rt.backend = compiler.backend();
        let res = self.run_asm(compiler.finish());
        let asm = self.take_asm();
        self.asm.line_sigs = asm.line_sigs.clone();
        match res {
            Ok(()) => {
                *compiler.assembly_mut() = asm;
                Ok(())
            }
            Err(e) => {
                *compiler = backup;
                Err(e)
            }
        }
    }
    /// Run a Uiua assembly
    pub fn run_asm(&mut self, asm: Assembly) -> UiuaResult {
        self.asm = asm;
        self.rt.execution_start = self.rt.backend.now();
        let mut res = self
            .catching_crash(|env| env.exec(env.asm.root.clone()))
            .unwrap_or_else(Err);
        let mut push_error = |te: UiuaError| match &mut res {
            Ok(()) => res = Err(te),
            Err(e) => e.meta.multi.push(te),
        };
        if self.asm.test_assert_count > 0 {
            let total_run = self.rt.test_results.len();
            let not_run = self.asm.test_assert_count.saturating_sub(total_run);
            let mut successes = 0;
            for res in self.rt.test_results.drain(..) {
                match res {
                    Ok(()) => successes += 1,
                    Err(e) => push_error(e),
                }
            }
            (self.rt.reports).push(Report::tests(successes, total_run - successes, not_run));
        }
        #[cfg(debug_assertions)]
        if res.is_ok() && !self.rt.under_stack.is_empty() {
            res = Err(self.error(format!(
                "Execution ended with {} values left on the under stack. \
                This is a bug in the interpreter.",
                self.rt.under_stack.len()
            )))
        }
        if res.is_err() {
            self.rt = Runtime {
                backend: self.rt.backend.clone(),
                execution_limit: self.rt.execution_limit,
                time_instrs: self.rt.time_instrs,
                output_comments: take(&mut self.rt.output_comments),
                reports: take(&mut self.rt.reports),
                stack: take(&mut self.rt.stack),
                cli_arguments: take(&mut self.rt.cli_arguments),
                ..Runtime::default()
            };
        }
        res
    }
    fn catching_crash<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> UiuaResult<T> {
        match catch_unwind(AssertUnwindSafe(|| f(self))) {
            Ok(res) => Ok(res),
            Err(_) => Err(self.error(format!(
                "\
The interpreter has crashed!
Hooray! You found a bug!
Please report this at http://github.com/uiua-lang/uiua/issues/new \
or on Discord at https://discord.gg/9CU2ME4kmn.

Uiua version {VERSION}

at {}",
                self.span()
            ))),
        }
    }
}

/// Things that can be executed
pub trait Exec {
    /// Execute
    fn exec(self, uiua: &mut Uiua) -> UiuaResult;
}

impl Exec for Node {
    fn exec(self, uiua: &mut Uiua) -> UiuaResult {
        uiua.exec_impl(self)
    }
}

impl Exec for SigNode {
    fn exec(self, uiua: &mut Uiua) -> UiuaResult {
        uiua.exec_with_span(self, 0)
    }
}

impl<T: Exec + Clone> Exec for Arc<T> {
    fn exec(self, uiua: &mut Uiua) -> UiuaResult {
        Arc::unwrap_or_clone(self).exec(uiua)
    }
}

impl Uiua {
    /// Execute an [`Exec`]
    pub fn exec(&mut self, node: impl Exec) -> UiuaResult {
        node.exec(self)
    }
    fn exec_impl(&mut self, node: Node) -> UiuaResult {
        let mut formatted_node = String::new();

        // Uncomment to debug
        // for val in self.rt.stack.iter().rev() {
        //     print!("{:?} ", val);
        // }
        // if self.rt.stack.is_empty() {
        //     print!("(empty) ");
        // }
        // println!();
        // if !self.rt.under_stack.is_empty() {
        //     print!("under: ");
        //     for val in self.rt.under_stack.iter().rev() {
        //         print!("{:?} ", val);
        //     }
        //     println!();
        // }
        // println!("\n    {node:?}");

        if self.rt.time_instrs {
            formatted_node = format!("{node:?}");
            self.rt.last_time = self.rt.backend.now();
        }
        let res = match node {
            Node::Run(nodes) => nodes.into_iter().try_for_each(|node| self.exec(node)),
            Node::Prim(prim, span) => {
                self.with_prim_span(span, Some(prim), |env| run_prim_func(&prim, env))
            }
            Node::ImplPrim(prim, span) => self.with_span(span, |env| prim.run(env)),
            Node::Mod(prim, args, span) => {
                self.with_prim_span(span, Some(prim), |env| run_prim_mod(&prim, args, env))
            }
            Node::ImplMod(prim, args, span) => self.with_span(span, |env| prim.run_mod(args, env)),
            Node::Push(val) => {
                self.rt.stack.push(val);
                Ok(())
            }
            Node::CallGlobal(index, _) => {
                let binding = self.asm.bindings.get(index).ok_or_else(|| {
                    self.error(
                        "Called out-of-bounds binding. \
                        This is a bug in the interpreter.",
                    )
                })?;
                match binding.kind.clone() {
                    BindingKind::Const(Some(val)) => {
                        self.rt.stack.push(val);
                        Ok(())
                    }
                    BindingKind::Const(None) => {
                        if let Some(node) = self.rt.unevaluated_constants.remove(&index) {
                            (|| -> UiuaResult {
                                self.exec(node)?;
                                let val = self.pop("constant")?;
                                self.push(val.clone());
                                self.asm.bindings.make_mut()[index].kind =
                                    BindingKind::Const(Some(val));
                                Ok(())
                            })()
                        } else {
                            Err(self.error(
                                "Called unbound constant. \
                                This is a bug in the interpreter.",
                            ))
                        }
                    }
                    BindingKind::Func(f) => {
                        self.respect_recursion_limit().and_then(|_| self.call(&f))
                    }
                    BindingKind::Module(_) | BindingKind::Scope(_) => Err(self.error(
                        "Called module global. \
                        This is a bug in the interpreter.",
                    )),
                    BindingKind::IndexMacro(_) => Err(self.error(
                        "Called index macro global. \
                        This is a bug in the interpreter.",
                    )),
                    BindingKind::CodeMacro(_) => Err(self.error(
                        "Called code macro global. \
                        This is a bug in the interpreter.",
                    )),
                    BindingKind::Error => Ok(()),
                }
            }
            Node::CallMacro { index, span, .. } => self.with_span(span, |env| {
                let binding = env.asm.bindings.get(index).ok_or_else(|| {
                    env.error(
                        "Called out-of-bounds binding. \
                        This is a bug in the interpreter.",
                    )
                })?;
                let func = match &binding.kind {
                    BindingKind::Func(f) => f.clone(),
                    _ => {
                        return Err(env.error(
                            "Recursive macro is not bound as a function. \
                            This is a bug in the interpreter.",
                        ));
                    }
                };
                env.call(&func)
            }),
            Node::BindGlobal { span, index } => {
                let local = LocalIndex {
                    index,
                    public: false,
                };
                let Some(mut value) = self.rt.stack.pop() else {
                    return Err(self.error_with_span(
                        self.get_span(span),
                        "No values on the stack for binding. \
                        This is a bug in the interpreter",
                    ));
                };
                value.try_shrink();
                // Binding is a constant
                self.asm
                    .bind_const(local, Some(value), span, BindingMeta::default());
                Ok(())
            }
            Node::Array {
                len,
                inner,
                boxed,
                allow_ext,
                span,
                ..
            } => self.with_span(span, |env| {
                env.make_array(len, inner.into(), boxed, allow_ext)
            }),
            Node::Call(f, span) => self.call_with_span(&f, span),
            Node::CustomInverse(cust, span) => match &cust.normal {
                Ok(normal) => self.exec_with_span(normal.clone(), span),
                Err(e) => self.with_span(span, |env| Err(env.error(e))),
            },
            Node::Switch {
                branches,
                sig,
                span,
                under_cond,
            } => self.with_span(span, |env| {
                algorithm::switch(branches, sig, under_cond, env)
            }),
            Node::Format(parts, span) => self.with_span(span, |env| algorithm::format(&parts, env)),
            Node::MatchFormatPattern(parts, span) => {
                self.with_span(span, |env| match_format_pattern(parts, env))
            }
            Node::Label(label, span) => self.with_span(span, |env| {
                env.monadic_mut(|val| {
                    val.meta
                        .set_label(if label.is_empty() { None } else { Some(label) });
                })
            }),
            Node::RemoveLabel(_, span) => {
                self.with_span(span, |env| env.monadic_mut(|val| val.meta.set_label(None)))
            }
            Node::Dynamic(df) => (|| {
                self.asm
                    .dynamic_functions
                    .get(df.index)
                    .ok_or_else(|| {
                        self.error(format!("Dynamic function index {} out of range", df.index))
                    })?
                    .clone()(self)
            })(),
            Node::Unpack {
                count,
                span,
                prim,
                unbox,
                ..
            } => self.with_span(span, |env| {
                let arr = env.pop(1)?;
                if arr.row_count() != count || arr.shape.is_empty() {
                    let prim_text;
                    let prim_text = if let Some(prim) = prim {
                        prim_text = prim.to_string();
                        prim_text.as_str()
                    } else if unbox {
                        "{}"
                    } else {
                        "[]"
                    };
                    return Err(env.error(if arr.shape.is_empty() {
                        format!(
                            "This °{prim_text} expects an array with {count} rows, \
                            but the array is a scalar"
                        )
                    } else {
                        format!(
                            "This °{prim_text} expects an array with {count} rows, \
                            but the array has {}",
                            arr.row_count()
                        )
                    }));
                }
                if unbox {
                    for val in arr.into_rows().rev() {
                        env.push(val.unboxed());
                    }
                } else {
                    for val in arr.into_rows().rev() {
                        env.push(val);
                    }
                }
                Ok(())
            }),
            Node::SetOutputComment { i, n } => {
                let values = self.stack()[self.stack().len().saturating_sub(n)..].to_vec();
                let stack_values = self.rt.output_comments.entry(i).or_default();
                if stack_values.is_empty() {
                    *stack_values = values.into_iter().map(|v| vec![v]).collect();
                } else {
                    for (stack_values, value) in stack_values.iter_mut().zip(values) {
                        stack_values.push(value);
                    }
                }
                Ok(())
            }
            Node::PushUnder(n, span) => self.with_span(span, |env| {
                env.require_height(n)?;
                let start = env.rt.stack.len() - n;
                env.rt.under_stack.extend(env.rt.stack.drain(start..).rev());
                Ok(())
            }),
            Node::CopyToUnder(n, span) => self.with_span(span, |env| {
                env.require_height(n)?;
                env.rt
                    .under_stack
                    .extend(env.rt.stack.iter().rev().take(n).cloned());
                Ok(())
            }),
            Node::PopUnder(n, span) => self.with_span(span, |env| {
                if env.under_stack_height() < n {
                    return Err(env.error(
                        "Stack was empty when getting context value. \
                        This is a bug in the interpreter.",
                    ));
                }
                let start = env.under_stack_height() - n;
                env.rt.stack.extend(env.rt.under_stack.drain(start..).rev());
                Ok(())
            }),
            Node::NoInline(inner) => self.exec(inner),
            Node::TrackCaller(inner) => self.require_height(inner.sig.args()).and_then(|_| {
                self.rt.call_stack.last_mut().unwrap().track_caller = true;
                self.exec(inner)
            }),
        };
        #[allow(clippy::print_stdout)]
        if self.rt.time_instrs {
            let end_time = self.rt.backend.now();
            let padding = self.rt.call_stack.len().saturating_sub(1) * 2;
            eprintln!(
                "  ⏲{:padding$}{:.2}ms - {}",
                "",
                end_time - self.rt.last_time,
                formatted_node
            );
            self.rt.last_time = self.rt.backend.now();
        }
        self.respect_execution_limit()?;
        res
    }
    /// Timeout if an execution limit is set and has been exceeded
    pub fn respect_execution_limit(&self) -> UiuaResult {
        if let Some(limit) = self.rt.execution_limit {
            let elapsed = self.rt.backend.now() - self.rt.execution_start;
            if elapsed > limit {
                return Err(
                    UiuaErrorKind::Timeout(self.span(), self.inputs().clone().into()).into(),
                );
            }
        }
        if let Some(hook) = &self.rt.interrupted
            && hook()
        {
            return Err(UiuaErrorKind::Interrupted.into());
        }
        Ok(())
    }
    pub(crate) fn with_span<T>(
        &mut self,
        span: usize,
        f: impl FnOnce(&mut Self) -> UiuaResult<T>,
    ) -> UiuaResult<T> {
        self.with_prim_span(span, None, f)
    }
    fn with_prim_span<T>(
        &mut self,
        span: usize,
        prim: Option<Primitive>,
        f: impl FnOnce(&mut Self) -> T,
    ) -> T {
        self.rt
            .call_stack
            .last_mut()
            .unwrap()
            .spans
            .push((span, prim));
        let res = f(self);
        self.rt.call_stack.last_mut().unwrap().spans.pop();
        res
    }
    /// Call a function
    #[inline]
    pub fn call(&mut self, f: &Function) -> UiuaResult {
        let call_span = self.span_index();
        self.call_with_span(f, call_span)
    }
    /// Call and truncate the stack to before the args were pushed if the call fails
    pub(crate) fn exec_clean_stack(&mut self, sn: SigNode) -> UiuaResult {
        let sig = sn.sig;
        let bottom = self.stack_height().saturating_sub(sig.args());
        let under_bottom = self
            .rt
            .under_stack
            .len()
            .saturating_sub(sn.sig.under_args());
        let res = self.exec(sn.node);
        if res.is_err() {
            self.truncate_stack(bottom);
            self.rt.under_stack.truncate(under_bottom);
        }
        res
    }
    /// Call and maintain the stack delta if the call fails
    pub(crate) fn exec_maintain_sig(&mut self, sn: SigNode) -> UiuaResult {
        if !sn.node.is_pure(&self.asm) {
            for i in 0..sn.sig.args() {
                self.pop(i + 1)?;
            }
            for _ in 0..sn.sig.outputs() {
                self.push(Value::default());
            }
            return Ok(());
        }

        let mut args = self.stack()[self.stack().len().saturating_sub(sn.sig.args())..].to_vec();
        args.reverse();
        let target_height = (self.stack_height() + sn.sig.outputs()).saturating_sub(sn.sig.args());
        let under_target_height = (self.rt.under_stack.len() + sn.sig.under_outputs())
            .saturating_sub(sn.sig.under_args());
        let res = self.exec(sn);
        match self.stack_height().cmp(&target_height) {
            Ordering::Equal => {}
            Ordering::Greater => {
                self.truncate_stack(target_height);
            }
            Ordering::Less => {
                let diff = target_height - self.stack_height();
                for _ in 0..diff {
                    self.push(args.pop().unwrap_or_default());
                }
            }
        }
        match self.rt.under_stack.len().cmp(&under_target_height) {
            Ordering::Equal => {}
            Ordering::Greater => self.truncate_under_stack(under_target_height),
            Ordering::Less => {
                let diff = under_target_height - self.rt.under_stack.len();
                for _ in 0..diff {
                    self.push_under(args.pop().unwrap_or_default());
                }
            }
        }
        res
    }
    fn call_with_span(&mut self, f: &Function, call_span: usize) -> UiuaResult {
        self.without_fill(|env| {
            env.exec_with_frame_span(
                env.asm[f].clone(),
                StackFrame {
                    sig: f.sig,
                    id: Some(f.id.clone()),
                    call_span,
                    start_height: env.stack_height(),
                    ..Default::default()
                },
                call_span,
            )
        })
    }
    fn exec_with_span(&mut self, sn: SigNode, call_span: usize) -> UiuaResult {
        self.exec_with_frame_span(
            sn.node,
            StackFrame {
                sig: sn.sig,
                call_span,
                start_height: self.stack_height(),
                ..Default::default()
            },
            call_span,
        )
    }
    fn exec_with_frame_span(
        &mut self,
        node: Node,
        frame: StackFrame,
        _call_span: usize,
    ) -> UiuaResult {
        let start_height = self.rt.stack.len();
        let sig = frame.sig;
        self.rt.call_stack.push(frame);
        let res = self.exec(node.clone());
        let frame = self.rt.call_stack.pop().unwrap();
        if let Err(mut err) = res {
            // Trace errors
            let span = self.asm.spans[frame.call_span].clone();
            if frame.track_caller {
                err.track_caller(span);
            } else {
                err.meta.trace.push(TraceFrame { id: frame.id, span });
            }
            return Err(err);
        }
        let height_diff = self.rt.stack.len() as isize - start_height as isize;
        let sig_diff = sig.outputs() as isize - sig.args() as isize;
        if height_diff != sig_diff {
            let message = if let Some(id) = &frame.id {
                format!(
                    "{id} modified the stack by {height_diff} values, but its \
                    signature of {sig} implies a change of {sig_diff}"
                )
            } else {
                format!(
                    "Function ({node:?}) modified the stack by {height_diff} values, but its \
                    signature of {sig} implies a change of {sig_diff}"
                )
            };
            #[cfg(debug_assertions)]
            panic!("{message}");
            #[cfg(not(debug_assertions))]
            return Err(self.error_with_span(self.asm.spans[_call_span].clone(), message));
        }
        Ok(())
    }
    pub(crate) fn span_index(&self) -> usize {
        self.rt.call_stack.last().map_or(0, |frame| {
            (frame.spans.last())
                .map(|(i, _)| *i)
                .unwrap_or(frame.call_span)
        })
    }
    /// Get the span of the current function call
    #[track_caller]
    pub fn span(&self) -> Span {
        self.get_span(self.span_index())
    }
    /// Get a span by its index
    #[track_caller]
    pub fn get_span(&self, span: usize) -> Span {
        self.asm.spans[span].clone()
    }
    /// Register a span
    pub fn add_span(&mut self, span: Span) -> usize {
        let idx = self.asm.spans.len();
        self.asm.spans.push(span);
        idx
    }
    /// Construct an error with the current span
    pub fn error(&self, message: impl ToString) -> UiuaError {
        UiuaErrorKind::Run {
            message: self.span().clone().sp(message.to_string()),
            info: Vec::new(),
            inputs: self.inputs().clone().into(),
        }
        .into()
    }
    /// Construct an error with a custom span
    pub fn error_with_span(&self, span: Span, message: impl ToString) -> UiuaError {
        UiuaErrorKind::Run {
            message: span.sp(message.to_string()),
            info: Vec::new(),
            inputs: self.inputs().clone().into(),
        }
        .into()
    }
    #[allow(dead_code)]
    pub(crate) fn error_maybe_span(
        &self,
        span: Option<&CodeSpan>,
        message: impl ToString,
    ) -> UiuaError {
        if let Some(span) = span {
            self.error_with_span(span.clone().into(), message)
        } else {
            self.error(message)
        }
    }
    /// Pop a value from the stack
    pub fn pop(&mut self, arg: impl StackArg) -> UiuaResult<Value> {
        (self.rt.stack.pop()).ok_or_else(|| self.error(format!("Missing {}", arg.arg_name())))
    }
    /// Pop a value and try to convert it
    pub fn pop_convert<T>(
        &mut self,
        f: impl FnOnce(&Value, &Uiua, &'static str) -> UiuaResult<T>,
    ) -> UiuaResult<T> {
        f(&self.pop(())?, self, "")
    }
    /// Attempt to pop a value and convert it to a boolean
    pub fn pop_bool(&mut self) -> UiuaResult<bool> {
        self.pop_convert(Value::as_bool)
    }
    /// Attempt to pop a value and convert it to an integer
    pub fn pop_int(&mut self) -> UiuaResult<isize> {
        self.pop_convert(Value::as_int)
    }
    /// Attempt to pop a value and convert it to a natural number
    pub fn pop_nat(&mut self) -> UiuaResult<usize> {
        self.pop_convert(Value::as_nat)
    }
    /// Attempt to pop a value and convert it to a number
    pub fn pop_num(&mut self) -> UiuaResult<f64> {
        self.pop_convert(Value::as_num)
    }
    /// Attempt to pop a value and convert it to a list of natural numbers
    pub fn pop_nats(&mut self) -> UiuaResult<Vec<usize>> {
        self.pop_convert(Value::as_nats)
    }
    /// Attempt to pop a value and convert it to a list of integers
    pub fn pop_ints(&mut self) -> UiuaResult<Vec<isize>> {
        self.pop_convert(Value::as_ints)
    }
    /// Attempt to pop a value and convert it to a list of numbers
    pub fn pop_nums(&mut self) -> UiuaResult<Vec<f64>> {
        Ok(self.pop(())?.as_nums(self, "")?.into_owned())
    }
    /// Attempt to pop a value and convert it to a string
    pub fn pop_string(&mut self) -> UiuaResult<String> {
        self.pop_convert(Value::as_string)
    }
    pub(crate) fn make_array(
        &mut self,
        len: usize,
        inner: Node,
        boxed: bool,
        allow_ext: bool,
    ) -> UiuaResult {
        self.without_fill(|env| env.exec(inner))?;
        let start = self.require_height(len)?;
        let values = self.rt.stack.drain(start..).rev();
        let values: Vec<Value> = if boxed {
            values.map(Boxed).map(Value::from).collect()
        } else {
            values.collect()
        };
        let val = if values.is_empty() && boxed {
            Array::<Boxed>::default().into()
        } else {
            let elems: usize = values.iter().map(|v| v.shape.elements()).sum();
            let elem_size = values.first().map_or(size_of::<f64>(), Value::elem_size);
            validate_size_impl(elem_size, [elems]).map_err(|e| self.error(e))?;
            Value::from_row_values_impl(values, self, allow_ext)?
        };
        self.push(val);
        Ok(())
    }
    /// Push a value onto the stack
    pub fn push<V: Into<Value>>(&mut self, val: V) {
        self.rt.stack.push(val.into());
    }
    pub(crate) fn push_under(&mut self, val: Value) {
        self.rt.under_stack.push(val);
    }
    /// Push several values onto the stack
    pub fn push_all<V: Into<Value>>(&mut self, vals: impl IntoIterator<Item = V>) {
        self.rt.stack.extend(vals.into_iter().map(Into::into));
    }
    /// Take the entire stack
    pub fn take_stack(&mut self) -> Vec<Value> {
        self.rt.under_stack.clear();
        take(&mut self.rt.stack)
    }
    /// Take the entire stack split up into lines
    pub fn take_stack_lines(&mut self) -> Vec<Vec<Value>> {
        let mut stack = self.take_stack();
        let mut sigs = self.asm.line_sigs.clone();
        let Some((_, mut curr)) = sigs.pop_last() else {
            return stack.into_iter().map(|v| vec![v]).collect();
        };
        let mut lines = Vec::new();
        if curr.outputs() > 0 {
            lines.push(stack.split_off(stack.len().saturating_sub(curr.outputs())));
        }
        while let Some((_, prev)) = sigs.pop_last() {
            if prev.outputs() > curr.args() {
                let n = prev.outputs() - curr.args();
                lines.push(stack.split_off(stack.len().saturating_sub(n)));
                curr = prev;
            } else {
                curr = curr.compose(prev)
            }
        }
        lines.reverse();
        for line in &mut lines {
            line.reverse();
        }
        lines
    }
    /// Take the main stack and under stack
    pub fn take_stacks(&mut self) -> (Vec<Value>, Vec<Value>) {
        let stack = take(&mut self.rt.stack);
        let under = take(&mut self.rt.under_stack);
        (stack, under)
    }
    /// Copy some values from the stack
    pub fn copy_n(&self, n: usize) -> UiuaResult<Vec<Value>> {
        let height = self.require_height(n)?;
        Ok(self.rt.stack[height..].to_vec())
    }
    /// Copy some values down the stack
    ///
    /// `depth` must be greater than or equal to `n`
    pub fn copy_n_down(&self, n: usize, depth: usize) -> UiuaResult<Vec<Value>> {
        debug_assert!(depth >= n);
        let height = self.require_height(depth)?;
        Ok(self.rt.stack[height..][..n].to_vec())
    }
    /// Prepare to fork and return the arguments to f
    pub fn prepare_fork(&mut self, f_args: usize, g_args: usize) -> UiuaResult<Vec<Value>> {
        if f_args > g_args {
            self.require_height(f_args)?;
            let mut vals = Vec::with_capacity(f_args);
            let len = self.rt.stack.len();
            vals.extend(self.rt.stack.drain(len - f_args..(len - g_args)));
            vals.extend(
                self.rt.stack[self.rt.stack.len() - g_args..]
                    .iter()
                    .cloned(),
            );
            debug_assert_eq!(vals.len(), f_args);
            Ok(vals)
        } else {
            self.copy_n(f_args)
        }
    }
    /// Get a value some amount from the top of the stack
    pub fn copy_nth(&self, n: usize) -> UiuaResult<Value> {
        let height = self.require_height(n + 1)?;
        Ok(self.rt.stack[height].clone())
    }
    /// Duplicate some values down the stack
    ///
    /// `depth` must be greater than or equal to `n`
    pub fn dup_values(&mut self, n: usize, depth: usize) -> UiuaResult {
        debug_assert!(depth >= n);
        let start = self.require_height(depth)?;
        for i in 0..n {
            self.rt.stack.push(self.rt.stack[start + i].clone());
        }
        if n != depth {
            self.rt.stack[start..].rotate_right(n);
        }
        Ok(())
    }
    /// Insert some values into the stack
    pub fn insert_stack(
        &mut self,
        depth: usize,
        values: impl IntoIterator<Item = Value>,
    ) -> UiuaResult {
        let start = self.require_height(depth)?;
        self.rt.stack.extend(values);
        self.rt.stack[start..].rotate_left(depth);
        Ok(())
    }
    /// Remove some values from the stack
    ///
    /// `depth` must be greater than or equal to `n`
    pub fn remove_n(
        &mut self,
        n: usize,
        depth: usize,
    ) -> UiuaResult<impl DoubleEndedIterator<Item = Value> + '_> {
        debug_assert!(depth >= n);
        let start = self.require_height(depth)?;
        Ok(self.rt.stack.drain(start..start + n).rev())
    }
    /// Rotate the stack up at some depth
    pub fn rotate_up(&mut self, n: usize, depth: usize) -> UiuaResult {
        let start = self.require_height(depth)?;
        self.rt.stack[start..].rotate_right(n);
        Ok(())
    }
    /// Rotate the stack down at some depth
    pub fn rotate_down(&mut self, n: usize, depth: usize) -> UiuaResult {
        let start = self.require_height(depth)?;
        self.rt.stack[start..].rotate_left(n);
        Ok(())
    }
    /// Access n stack values mutably
    pub fn n_mut(&mut self, n: usize) -> UiuaResult<&mut [Value]> {
        let start = self.require_height(n)?;
        Ok(&mut self.rt.stack[start..])
    }
    pub(crate) fn require_height(&self, n: usize) -> UiuaResult<usize> {
        if self.rt.stack.len() < n {
            return Err(self.error(format!("Missing argument {}", self.rt.stack.len() + 1)));
        }
        Ok(self.rt.stack.len() - n)
    }
    /// Get a reference to the stack
    pub fn stack(&self) -> &[Value] {
        &self.rt.stack
    }
    /// Get a mutable reference to the stack data
    pub fn stack_mut(&mut self) -> &mut [Value] {
        &mut self.rt.stack
    }
    /// Get all bound values in the assembly
    ///
    /// Bindings are only given values once the assembly has been run successfully
    pub fn bound_values(&self) -> HashMap<Ident, Value> {
        let mut bindings = HashMap::new();
        for binding in &self.asm.bindings {
            if let BindingKind::Const(Some(val)) = &binding.kind {
                let name = binding.span.as_str(self.inputs(), |s| s.into());
                bindings.insert(name, val.clone());
            }
        }
        bindings
    }
    /// Get all bound functions in the assembly
    pub fn bound_functions(&self) -> HashMap<Ident, Function> {
        let mut bindings = HashMap::new();
        for binding in &self.asm.bindings {
            if let BindingKind::Func(f) = &binding.kind {
                let name = binding.span.as_str(self.inputs(), |s| s.into());
                bindings.insert(name, f.clone());
            }
        }
        bindings
    }
    /// Clone `n` values from the top of the stack
    ///
    /// Values are cloned in the order they were pushed
    pub fn clone_stack_top(&self, n: usize) -> UiuaResult<Vec<Value>> {
        if self.rt.stack.len() < n {
            return Err(self.error(format!("Missing argument {}", n - self.rt.stack.len())));
        }
        Ok(self.rt.stack.iter().rev().take(n).rev().cloned().collect())
    }
    pub(crate) fn monadic_ref<V: Into<Value>>(&mut self, f: fn(&Value) -> V) -> UiuaResult {
        let value = self.pop(1)?;
        self.push(f(&value));
        Ok(())
    }
    pub(crate) fn monadic_env<V: Into<Value>>(
        &mut self,
        f: fn(Value, &Self) -> UiuaResult<V>,
    ) -> UiuaResult {
        let value = self.pop(1)?;
        self.push(f(value, self)?);
        Ok(())
    }
    pub(crate) fn monadic_env_with<T, V: Into<Value>>(
        &mut self,
        with: T,
        f: fn(T, Value, &Self) -> UiuaResult<V>,
    ) -> UiuaResult {
        let value = self.pop(1)?;
        self.push(f(with, value, self)?);
        Ok(())
    }
    pub(crate) fn monadic_ref_env<V: Into<Value>>(
        &mut self,
        f: fn(&Value, &Self) -> UiuaResult<V>,
    ) -> UiuaResult {
        let value = self.pop(1)?;
        self.push(f(&value, self)?);
        Ok(())
    }
    pub(crate) fn monadic_mut(&mut self, f: impl FnOnce(&mut Value)) -> UiuaResult {
        let mut a = self.pop(1)?;
        f(&mut a);
        self.push(a);
        Ok(())
    }
    pub(crate) fn monadic_mut_env(
        &mut self,
        f: impl FnOnce(&mut Value, &Self) -> UiuaResult,
    ) -> UiuaResult {
        let mut a = self.pop(1)?;
        f(&mut a, self)?;
        self.push(a);
        Ok(())
    }
    pub(crate) fn dyadic_rr<V: Into<Value>>(&mut self, f: fn(&Value, &Value) -> V) -> UiuaResult {
        let a = self.pop(1)?;
        let b = self.pop(2)?;
        self.push(f(&a, &b));
        Ok(())
    }
    pub(crate) fn dyadic_oo_env<V: Into<Value>>(
        &mut self,
        f: fn(Value, Value, &Self) -> UiuaResult<V>,
    ) -> UiuaResult {
        let a = self.pop(1)?;
        let b = self.pop(2)?;
        self.push(f(a, b, self)?);
        Ok(())
    }
    pub(crate) fn dyadic_oo_env_with<V: Into<Value>, T>(
        &mut self,
        with: T,
        f: fn(T, Value, Value, &Self) -> UiuaResult<V>,
    ) -> UiuaResult {
        let a = self.pop(1)?;
        let b = self.pop(2)?;
        self.push(f(with, a, b, self)?);
        Ok(())
    }
    pub(crate) fn dyadic_rr_env<V: Into<Value>>(
        &mut self,
        f: fn(&Value, &Value, &Self) -> UiuaResult<V>,
    ) -> UiuaResult {
        let a = self.pop(1)?;
        let b = self.pop(2)?;
        self.push(f(&a, &b, self)?);
        Ok(())
    }
    pub(crate) fn dyadic_ro_env<V: Into<Value>>(
        &mut self,
        f: fn(&Value, Value, &Self) -> UiuaResult<V>,
    ) -> UiuaResult {
        let a = self.pop(1)?;
        let b = self.pop(2)?;
        self.push(f(&a, b, self)?);
        Ok(())
    }
    #[inline]
    pub(crate) fn stack_height(&self) -> usize {
        self.rt.stack.len()
    }
    #[inline]
    pub(crate) fn under_stack_height(&self) -> usize {
        self.rt.under_stack.len()
    }
    #[inline]
    pub(crate) fn truncate_stack(&mut self, size: usize) -> Vec<Value> {
        self.rt.stack.split_off(size.min(self.rt.stack.len()))
    }
    #[inline]
    pub(crate) fn truncate_under_stack(&mut self, size: usize) {
        self.rt.under_stack.truncate(size);
    }
    /// Pop `n` values from the stack
    pub fn pop_n(&mut self, n: usize) -> UiuaResult<Vec<Value>> {
        let height = self.require_height(n)?;
        Ok(self.rt.stack.split_off(height))
    }
    /// Get a slice of the top `n` stack values
    pub fn top_n(&self, n: usize) -> UiuaResult<&[Value]> {
        let height = self.require_height(n)?;
        Ok(&self.rt.stack[height..])
    }
    /// Get a mutable slice of the top `n` stack values
    pub fn top_n_mut(&mut self, n: usize) -> UiuaResult<&mut [Value]> {
        let height = self.require_height(n)?;
        Ok(&mut self.rt.stack[height..])
    }
    pub(crate) fn fill_frame(&self) -> Option<&FillFrame> {
        if (self.rt.fill_boundary_stack.last()).is_some_and(|&(i, _)| i >= self.rt.fill_stack.len())
        {
            None
        } else {
            self.last_fill()
        }
    }
    pub(crate) fn unfill_frame(&self) -> Option<&FillFrame> {
        if (self.rt.fill_boundary_stack.last())
            .is_some_and(|&(_, i)| i >= self.rt.unfill_stack.len())
        {
            None
        } else {
            self.last_unfill()
        }
    }
    pub(crate) fn value_fill(&self) -> Option<FillValue<&Value>> {
        self.fill_frame().and_then(|frame| {
            frame.values.first().map(|value| FillValue {
                value,
                side: frame.side,
            })
        })
    }
    pub(crate) fn _value_unfill(&self) -> Option<FillValue<&Value>> {
        self.unfill_frame().and_then(|frame| {
            frame.values.first().map(|value| FillValue {
                value,
                side: frame.side,
            })
        })
    }
    pub(crate) fn last_fill(&self) -> Option<&FillFrame> {
        self.rt.fill_stack.last()
    }
    pub(crate) fn last_unfill(&self) -> Option<&FillFrame> {
        self.rt.unfill_stack.last()
    }
    pub(crate) fn fill(&self) -> Fill {
        Fill::new(self)
    }
    pub(crate) fn unfill(&self) -> Fill {
        Fill::new_un(self)
    }
    /// Do something with the fill context set
    pub(crate) fn with_fill<T>(
        &mut self,
        vals: impl Into<FillFrame>,
        in_ctx: impl FnOnce(&mut Self) -> UiuaResult<T>,
    ) -> UiuaResult<T> {
        self.rt.fill_stack.push(vals.into());
        let res = in_ctx(self);
        self.rt.fill_stack.pop();
        res
    }
    /// Do something with the unfill context set
    pub(crate) fn with_unfill<T>(
        &mut self,
        vals: impl Into<FillFrame>,
        in_ctx: impl FnOnce(&mut Self) -> UiuaResult<T>,
    ) -> UiuaResult<T> {
        self.rt.unfill_stack.push(vals.into());
        let res = in_ctx(self);
        self.rt.unfill_stack.pop();
        res
    }
    /// Do something with the top fill context unset
    pub(crate) fn without_fill<T>(&mut self, in_ctx: impl FnOnce(&mut Self) -> T) -> T {
        let fill_boundary = self.rt.fill_stack.len();
        let unfill_boundary = self.rt.unfill_stack.len();
        (self.rt.fill_boundary_stack).push((fill_boundary, unfill_boundary));
        let res = in_ctx(self);
        self.rt.fill_boundary_stack.pop();
        res
    }
    pub(crate) fn without_fill_but(
        &mut self,
        n: usize,
        but: impl FnOnce(&mut Self) -> UiuaResult,
        in_ctx: impl FnOnce(&mut Self) -> UiuaResult,
    ) -> UiuaResult {
        let fills = self.rt.fill_stack[self.rt.fill_stack.len().max(n) - n..].to_vec();
        if fills.len() < n {
            for _ in 0..n - fills.len() {
                self.push(Value::default());
            }
        }
        for frame in fills.into_iter().rev() {
            for val in frame.values {
                self.push(val);
            }
        }
        but(self)?;
        self.without_fill(|env| in_ctx(env))
    }
    pub(crate) fn without_unfill_but(
        &mut self,
        n: usize,
        but: impl FnOnce(&mut Self) -> UiuaResult,
        in_ctx: impl FnOnce(&mut Self) -> UiuaResult,
    ) -> UiuaResult {
        let fills = self.rt.unfill_stack[self.rt.unfill_stack.len().max(n) - n..].to_vec();
        if fills.len() < n {
            for _ in 0..n - fills.len() {
                self.push(Value::default());
            }
        }
        for frame in fills.into_iter().rev() {
            for val in frame.values {
                self.push(val);
            }
        }
        but(self)?;
        self.without_fill(|env| in_ctx(env))
    }
    pub(crate) fn call_frames(&self) -> impl DoubleEndedIterator<Item = &StackFrame> {
        self.rt.call_stack.iter()
    }
    pub(crate) fn respect_recursion_limit(&mut self) -> UiuaResult {
        if self.rt.call_stack.len() > self.rt.recursion_limit {
            Err(
                self.error(if cfg!(target_arch = "wasm32") || cfg!(debug_assertions) {
                    "Recursion limit reached".into()
                } else {
                    format!(
                        "Recursion limit reached. \
                        You can try setting UIUA_RECURSION_LIMIT to a higher value. \
                        The current limit is {}.",
                        self.rt.recursion_limit
                    )
                }),
            )
        } else {
            Ok(())
        }
    }
    /// Spawn a thread
    pub(crate) fn spawn(&mut self, _pool: bool, f: SigNode) -> UiuaResult {
        if !self.rt.backend.allow_thread_spawning() {
            return Err(self.error("Thread spawning is not allowed in this environment"));
        }
        if self.rt.stack.len() < f.sig.args() {
            return Err(self.error(format!(
                "Expected at least {} value(s) on the stack, but there are {}",
                f.sig.args(),
                self.rt.stack.len()
            )))?;
        }
        let (this_send, child_recv) = crossbeam_channel::unbounded();
        let (child_send, this_recv) = crossbeam_channel::unbounded();
        let thread = ThisThread {
            parent: Some(Channel {
                send: child_send,
                recv: child_recv,
            }),
            ..ThisThread::default()
        };
        let make_env = || Uiua {
            asm: self.asm.clone(),
            rt: Runtime {
                stack: (self.rt.stack)
                    .drain(self.rt.stack.len() - f.sig.args()..)
                    .collect(),
                under_stack: Vec::new(),
                local_stack: self.rt.local_stack.clone(),
                fill_stack: Vec::new(),
                fill_boundary_stack: Vec::new(),
                unfill_stack: Vec::new(),
                recur_stack: self.rt.recur_stack.clone(),
                call_stack: Vec::from_iter(self.rt.call_stack.last().cloned()),
                time_instrs: self.rt.time_instrs,
                last_time: self.rt.last_time,
                cli_arguments: self.rt.cli_arguments.clone(),
                cli_file_path: self.rt.cli_file_path.clone(),
                backend: self.rt.backend.clone(),
                execution_limit: self.rt.execution_limit,
                execution_start: self.rt.execution_start,
                recursion_limit: self.rt.recursion_limit,
                interrupted: self.rt.interrupted.clone(),
                output_comments: HashMap::new(),
                memo: self.rt.memo.clone(),
                unevaluated_constants: HashMap::new(),
                test_results: Vec::new(),
                reports: Vec::new(),
                thread_pool: self.rt.thread_pool.clone(),
                thread,
            },
        };
        #[cfg(not(target_arch = "wasm32"))]
        let recv = {
            let (send, recv) = crossbeam_channel::unbounded();
            if _pool {
                use std::sync::LazyLock;
                static MAX_THREADS: LazyLock<usize> = LazyLock::new(|| {
                    std::thread::available_parallelism()
                        .map(|p| p.get())
                        .unwrap_or(1)
                });
                let mut pool = self.rt.thread_pool.lock();
                if pool.is_none() {
                    *pool = Some(ThreadPool::new(*MAX_THREADS));
                }
                let pool = pool.as_mut().unwrap();
                while pool.active_count() >= *MAX_THREADS {
                    std::thread::yield_now();
                }
                let mut env = make_env();
                pool.execute(move || _ = send.send(env.exec(f).map(|_| env.take_stack())));
            } else {
                let mut env = make_env();
                std::thread::Builder::new()
                    .spawn(move || _ = send.send(env.exec(f).map(|_| env.take_stack())))
                    .map_err(|e| self.error(format!("Error spawning thread: {e}")))?;
            }
            recv
        };
        #[cfg(target_arch = "wasm32")]
        let result = {
            let mut env = make_env();
            env.exec(f).map(|_| env.take_stack())
        };

        let id = self.rt.thread.next_child_id;
        self.rt.thread.next_child_id += 1;
        self.rt.thread.children.insert(
            id,
            Thread {
                #[cfg(not(target_arch = "wasm32"))]
                recv,
                #[cfg(target_arch = "wasm32")]
                result,
                channel: Channel {
                    send: this_send,
                    recv: this_recv,
                },
            },
        );
        self.push(id);
        Ok(())
    }
    /// Wait for a thread to finish
    pub(crate) fn wait(&mut self, id: Value) -> UiuaResult {
        let ids = id.as_natural_array(self, "Thread id must be an array of natural numbers")?;
        if ids.shape.is_empty() {
            let handle = ids.data[0];
            #[cfg(not(target_arch = "wasm32"))]
            let mut thread_stack = self
                .rt
                .thread
                .children
                .remove(&handle)
                .ok_or_else(|| self.error("Invalid thread id"))?
                .recv
                .recv()
                .unwrap()?;
            #[cfg(target_arch = "wasm32")]
            let mut thread_stack = self
                .rt
                .thread
                .children
                .remove(&handle)
                .ok_or_else(|| self.error("Invalid thread id"))?
                .result?;
            match thread_stack.len() {
                0 => self.push(Value::default()),
                1 => self.push(thread_stack.into_iter().next().unwrap()),
                _ => {
                    thread_stack.reverse();
                    self.push(Value::from_row_values(thread_stack, self)?)
                }
            }
        } else {
            let mut rows = Vec::new();
            for handle in ids.data {
                #[cfg(not(target_arch = "wasm32"))]
                let mut thread_stack = self
                    .rt
                    .thread
                    .children
                    .remove(&handle)
                    .ok_or_else(|| self.error("Invalid thread id"))?
                    .recv
                    .recv()
                    .unwrap()?;
                #[cfg(target_arch = "wasm32")]
                let mut thread_stack = self
                    .rt
                    .thread
                    .children
                    .remove(&handle)
                    .ok_or_else(|| self.error("Invalid thread id"))?
                    .result?;
                let row = if thread_stack.len() == 1 {
                    thread_stack.into_iter().next().unwrap()
                } else {
                    thread_stack.reverse();
                    Value::from_row_values(thread_stack, self)?
                };
                rows.push(row);
            }
            let mut val = Value::from_row_values(rows, self)?;
            let mut shape = ids.shape;
            shape.extend_from_slice(&val.shape[1..]);
            val.shape = shape;
            self.push(val);
        }
        Ok(())
    }
    pub(crate) fn send(&self, id: Value, value: Value) -> UiuaResult {
        if cfg!(target_arch = "wasm32") {
            return Err(self.error("send is not supported in this environment"));
        }
        let ids = id.as_natural_array(self, "Thread id must be an array of natural numbers")?;
        for id in ids.data {
            self.channel(id)?
                .send
                .send(value.clone())
                .map_err(|_| self.error("Thread channel closed"))?;
        }
        Ok(())
    }
    pub(crate) fn recv(&mut self, id: Value) -> UiuaResult {
        if cfg!(target_arch = "wasm32") {
            return Err(self.error("recv is not supported in this environment"));
        }
        let ids = id.as_natural_array(self, "Thread id must be an array of natural numbers")?;
        let mut values = Vec::with_capacity(ids.data.len());
        for id in ids.data {
            values.push(self.channel(id)?.recv.recv().map_err(|_| {
                if let Err(e) = self.wait(id.into()) {
                    e
                } else {
                    self.error("Thread channel closed")
                }
            })?);
        }
        let mut val = Value::from_row_values(values, self)?;
        let mut shape = ids.shape;
        shape.extend_from_slice(&val.shape[1..]);
        val.shape = shape;
        self.push(val);
        Ok(())
    }
    pub(crate) fn try_recv(&mut self, id: Value) -> UiuaResult {
        if cfg!(target_arch = "wasm32") {
            return Err(self.error("try_recv is not supported in this environment"));
        }
        let id = id.as_nat(self, "Thread id must be a natural number")?;
        let value = match self.channel(id)?.recv.try_recv() {
            Ok(value) => value,
            Err(TryRecvError::Empty) => return Err(self.error("No value available")),
            Err(_) => {
                return Err(if let Err(e) = self.wait(id.into()) {
                    e
                } else {
                    self.error("Thread channel closed")
                });
            }
        };
        self.push(value);
        Ok(())
    }
    fn channel(&self, id: usize) -> UiuaResult<&Channel> {
        Ok(if id == 0 {
            self.rt
                .thread
                .parent
                .as_ref()
                .ok_or_else(|| self.error("Thread has no parent"))?
        } else {
            &self
                .rt
                .thread
                .children
                .get(&id)
                .ok_or_else(|| self.error("Invalid thread id"))?
                .channel
        })
    }
}

/// A trait for types that can be used as argument specifiers for [`Uiua::pop`]
///
/// If the stack is empty, the error message will be "Missing {arg_name}"
pub trait StackArg {
    /// Get the name of the argument
    fn arg_name(self) -> String;
}

impl StackArg for () {
    fn arg_name(self) -> String {
        "value".to_string()
    }
}

impl StackArg for usize {
    fn arg_name(self) -> String {
        format!("argument {self}")
    }
}
impl StackArg for u8 {
    fn arg_name(self) -> String {
        format!("argument {self}")
    }
}
impl StackArg for i32 {
    fn arg_name(self) -> String {
        format!("argument {self}")
    }
}
impl StackArg for &str {
    fn arg_name(self) -> String {
        self.to_string()
    }
}

impl StackArg for String {
    fn arg_name(self) -> String {
        self
    }
}

impl StackArg for (&'static str, usize) {
    fn arg_name(self) -> String {
        format!("{} {}", self.0, self.1)
    }
}

impl<F, T> StackArg for F
where
    F: FnOnce() -> T,
    T: StackArg,
{
    fn arg_name(self) -> String {
        self().arg_name()
    }
}