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
#[cfg(feature = "native_sys")]
pub(crate) mod native;

use std::{
    any::Any,
    borrow::Cow,
    fmt,
    io::stdin,
    mem::take,
    net::SocketAddr,
    path::{Path, PathBuf},
    sync::{Arc, LazyLock},
    time::Duration,
};

#[cfg(feature = "image")]
use image::DynamicImage;
use parking_lot::Mutex;
use time::UtcOffset;

#[cfg(feature = "native_sys")]
pub use self::native::*;
use crate::{
    Array, BigConstant, Boxed, FfiArg, FfiType, MetaPtr, Ops, Primitive, SysOp, Uiua,
    UiuaErrorKind, UiuaResult, Value,
    algorithm::{multi_output, validate_size},
    cowslice::cowslice,
    get_ops,
};

/// The text of Uiua's example module
pub const EXAMPLE_UA: &str = "\
# Uiua's example module

Square ← ˙×
Double ← ˙+
Increment ← +1
RangeDiff ↚ ⇡-
Span ← +⟜RangeDiff
Mac! ← /^0 [1 2 3 4 5]
Foo ← 5
Bar ← \"bar\"";

/// The text of Uiua's example text file
pub const EXAMPLE_TXT: &str = "\
This is a simple text file for 
use in example Uiua code ✨";

/// Access the built-in `example.ua` file
pub fn example_ua<T>(f: impl FnOnce(&mut String) -> T) -> T {
    static S: LazyLock<Mutex<String>> = LazyLock::new(|| Mutex::new(EXAMPLE_UA.to_string()));
    f(&mut S.lock())
}

/// Access the built-in `example.txt` file
pub fn example_txt<T>(f: impl FnOnce(&mut String) -> T) -> T {
    static S: LazyLock<Mutex<String>> = LazyLock::new(|| Mutex::new(EXAMPLE_TXT.to_string()));
    f(&mut S.lock())
}

/// A handle to an IO stream
///
/// 0 is stdin, 1 is stdout, 2 is stderr.
///
/// Other handles can be used by files or sockets.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Handle(pub u64);

impl Handle {
    const STDIN: Self = Self(0);
    const STDOUT: Self = Self(1);
    const STDERR: Self = Self(2);
    /// The first handle that can be used by the user
    pub const FIRST_UNRESERVED: Self = Self(3);
}

impl From<usize> for Handle {
    fn from(n: usize) -> Self {
        Self(n as u64)
    }
}

impl Handle {
    pub(crate) fn value(self, kind: HandleKind) -> Value {
        let mut arr = Array::from(self.0 as f64);
        arr.meta.handle_kind = Some(kind);
        Boxed(arr.into()).into()
    }
}

impl Value {
    /// Attempt to convert the array to system handle
    ///
    /// The `requirement` parameter is used in error messages.
    pub fn as_handle(
        &self,
        env: &Uiua,
        requirement: impl Into<Option<&'static str>>,
    ) -> UiuaResult<Handle> {
        let requirement = requirement
            .into()
            .unwrap_or("Expected value to be a stream handle");
        match self {
            Value::Box(b) => {
                if let Some(b) = b.as_scalar() {
                    b.0.as_nat(env, requirement).map(|h| Handle(h as u64))
                } else {
                    Err(env.error(format!("{requirement}, but it is rank {}", b.rank())))
                }
            }
            value => value.as_nat(env, requirement).map(|h| Handle(h as u64)),
        }
    }
}

/// The function type passed to `&rl`'s returned function
#[cfg(not(target_arch = "wasm32"))]
pub type ReadLinesFn<'a> = Box<dyn FnMut(String, &mut Uiua) -> UiuaResult + Send + 'a>;
/// The function type passed to `&rl`'s returned function
#[cfg(target_arch = "wasm32")]
pub type ReadLinesFn<'a> = Box<dyn FnMut(String, &mut Uiua) -> UiuaResult + 'a>;

/// The function type returned by `&rl`
#[cfg(not(target_arch = "wasm32"))]
pub type ReadLinesReturnFn<'a> = Box<dyn FnMut(&mut Uiua, ReadLinesFn) -> UiuaResult + Send + 'a>;
/// The function type returned by `&rl`
#[cfg(target_arch = "wasm32")]
pub type ReadLinesReturnFn<'a> = Box<dyn FnMut(&mut Uiua, ReadLinesFn) -> UiuaResult + 'a>;

/// The function type passed to `&ast`
#[cfg(not(target_arch = "wasm32"))]
pub type AudioStreamFn = Box<dyn FnMut(&[f64]) -> UiuaResult<Vec<[f64; 2]>> + Send>;
/// The function type passed to `&ast`
#[cfg(target_arch = "wasm32")]
pub type AudioStreamFn = Box<dyn FnMut(&[f64]) -> UiuaResult<Vec<[f64; 2]>>>;

/// The kind of a handle
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[allow(missing_docs)]
pub enum HandleKind {
    File(PathBuf),
    TcpListener(SocketAddr),
    TlsListener(SocketAddr),
    TcpSocket(SocketAddr),
    TlsSocket(SocketAddr),
    UdpSocket(String),
    ChildStdin(String),
    ChildStdout(String),
    ChildStderr(String),
}

impl fmt::Display for HandleKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::File(path) => write!(f, "file {}", path.display()),
            Self::TcpListener(addr) => write!(f, "tcp listener {addr}"),
            Self::TlsListener(addr) => write!(f, "tls listener {addr}"),
            Self::TcpSocket(addr) => write!(f, "tcp socket {addr}"),
            Self::TlsSocket(addr) => write!(f, "tls socket {addr}"),
            Self::UdpSocket(addr) => write!(f, "udp socket {addr}"),
            Self::ChildStdin(com) => write!(f, "stdin {com}"),
            Self::ChildStdout(com) => write!(f, "stdout {com}"),
            Self::ChildStderr(com) => write!(f, "stderr {com}"),
        }
    }
}

/// Reference point and offset to seek a position in a stream with
/// This is used instead of `std::io::SeekFrom` because the latter is more general than what Uiua uses, so using a more specific enum reduces checks elsewhere in the code.
pub enum StreamSeek {
    /// Seek a position forward from the start of the stream
    Start(usize),
    /// Seek a position backward from the end of the stream
    End(usize),
}

impl From<StreamSeek> for std::io::SeekFrom {
    fn from(value: StreamSeek) -> Self {
        match value {
            StreamSeek::Start(off) => std::io::SeekFrom::Start(off as u64),
            StreamSeek::End(off) => std::io::SeekFrom::End(-(off as i64)),
        }
    }
}

#[cfg(feature = "image")]
pub(crate) type WebcamImage = image::RgbImage;
#[cfg(not(feature = "image"))]
pub(crate) type WebcamImage = ();

/// Trait for defining a system backend
#[allow(unused_variables)]
pub trait SysBackend: Any + Send + Sync + 'static {
    /// Cast the backend to `&dyn Any`
    fn any(&self) -> &dyn Any;
    /// Cast the backend to `&mut dyn Any`
    fn any_mut(&mut self) -> &mut dyn Any;
    /// Save a color-formatted version of an error message for later printing
    fn save_error_color(&self, message: String, colored: String) {}
    /// Check whether output is enabled
    fn output_enabled(&self) -> bool {
        true
    }
    /// Set whether output should be enabled
    ///
    /// Returns the previous value.
    ///
    /// It is the trait implementor's responsibility to ensure that this value is respected.
    fn set_output_enabled(&self, enabled: bool) -> bool {
        true
    }
    /// Print a string (without a newline) to stdout
    fn print_str_stdout(&self, s: &str) -> Result<(), String> {
        Err("Printing to stdout is not supported in this environment".into())
    }
    /// Print a string (without a newline) to stderr
    fn print_str_stderr(&self, s: &str) -> Result<(), String> {
        Err("Printing to stderr is not supported in this environment".into())
    }
    /// Print a string that was create by `trace`
    fn print_str_trace(&self, s: &str) {}
    /// Show a value
    fn show(&self, value: Value) -> Result<(), String> {
        self.print_str_stdout(&format!("{}\n", value.show()))
    }
    /// Read a line from stdin
    ///
    /// Should return `Ok(None)` if EOF is reached.
    fn scan_line_stdin(&self) -> Result<Option<String>, String> {
        Err("Reading from stdin is not supported in this environment".into())
    }
    /// Read a number of bytes from stdin
    ///
    /// If `count` is `None`, read until EOF.
    fn scan_stdin(&self, count: Option<usize>) -> Result<Vec<u8>, String> {
        Err("Reading from stdin is not supported in this environment".into())
    }
    /// Read from stdin until a delimiter is reached
    fn scan_until_stdin(&self, delim: &[u8]) -> Result<Vec<u8>, String> {
        let mut buffer = Vec::new();
        loop {
            let bytes = self.scan_stdin(Some(1))?;
            if bytes.is_empty() {
                break;
            }
            buffer.extend_from_slice(&bytes);
            if buffer.ends_with(delim) {
                break;
            }
        }
        Ok(buffer)
    }
    /// Set the terminal to raw mode
    fn set_raw_mode(&self, raw_mode: bool) -> Result<(), String> {
        Err("Setting raw mode is not supported in this environment".into())
    }
    /// Get the terminal raw mode
    fn get_raw_mode(&self) -> Result<bool, String> {
        Err("Getting raw mode is not supported in this environment".into())
    }
    /// Get an environment variable
    fn var(&self, name: &str) -> Option<String> {
        None
    }
    /// Get the size of the terminal
    fn term_size(&self) -> Result<(usize, usize), String> {
        Err("Getting the terminal size is not supported in this environment".into())
    }
    /// Exit the program with a status code
    fn exit(&self, status: i32) -> Result<(), String> {
        Err("Exiting is not supported in this environment".into())
    }
    /// Check if a file or directory exists
    fn file_exists(&self, path: &str) -> bool {
        false
    }
    /// List the contents of a directory
    fn list_dir(&self, path: &str) -> Result<Vec<String>, String> {
        Err("Listing directories is not supported in this environment".into())
    }
    /// Check if a path is a file
    fn is_file(&self, path: &str) -> Result<bool, String> {
        Err("Checking if a path is a file is not supported in this environment".into())
    }
    /// Delete a file or directory
    fn delete(&self, path: &str) -> Result<(), String> {
        Err("Deleting files is not supported in this environment".into())
    }
    /// Move a file or directory to the trash
    fn trash(&self, path: &str) -> Result<(), String> {
        Err("Trashing files is not supported in this environment".into())
    }
    /// Read at most `count` bytes from a stream
    fn read(&self, handle: Handle, count: usize) -> Result<Vec<u8>, String> {
        Err("Reading from streams is not supported in this environment".into())
    }
    /// Read from a stream until the end
    fn read_all(&self, handle: Handle) -> Result<Vec<u8>, String> {
        Err("Reading from streams is not supported in this environment".into())
    }
    /// Read from a stream until a delimiter is reached
    fn read_until(&self, handle: Handle, delim: &[u8]) -> Result<Vec<u8>, String> {
        let mut buffer = Vec::new();
        loop {
            let bytes = self.read(handle, 1)?;
            if bytes.is_empty() {
                break;
            }
            buffer.extend_from_slice(&bytes);
            if buffer.ends_with(delim) {
                break;
            }
        }
        Ok(buffer)
    }
    /// Read lines from a stream
    fn read_lines<'a>(&self, handle: Handle) -> Result<ReadLinesReturnFn<'a>, String> {
        Err("Reading from streams is not supported in this environment".into())
    }
    /// Write bytes to a stream
    fn write(&self, handle: Handle, contents: &[u8]) -> Result<(), String> {
        Err("Writing to streams is not supported in this environment".into())
    }
    /// Go to an absolute file position
    fn seek(&self, handle: Handle, offset: StreamSeek) -> Result<(), String> {
        Err("Seeking streams is not supported in this environment".into())
    }
    /// Create a file
    fn create_file(&self, path: &Path) -> Result<Handle, String> {
        Err("Creating files is not supported in this environment".into())
    }
    /// Open a file
    fn open_file(&self, path: &Path, write: bool) -> Result<Handle, String> {
        Err("Opening files is not supported in this environment".into())
    }
    /// Create a directory
    fn make_dir(&self, path: &Path) -> Result<(), String> {
        Err("Creating directories is not supported in this environment".into())
    }
    /// Read all bytes from a file
    fn file_read_all(&self, path: &Path) -> Result<Vec<u8>, String> {
        let handle = self.open_file(path, false)?;
        let bytes = self.read(handle, usize::MAX)?;
        self.close(handle)?;
        Ok(bytes)
    }
    /// Write all bytes to a file
    fn file_write_all(&self, path: &Path, contents: &[u8]) -> Result<(), String> {
        let handle = self.create_file(path)?;
        self.write(handle, contents)?;
        self.close(handle)?;
        Ok(())
    }
    /// Get the clipboard contents
    fn clipboard(&self) -> Result<String, String> {
        Err("Getting the clipboard is not supported in this environment".into())
    }
    /// Set the clipboard contents
    fn set_clipboard(&self, contents: &str) -> Result<(), String> {
        Err("Setting the clipboard is not supported in this environment".into())
    }
    /// Sleep the current thread for `seconds` seconds
    fn sleep(&self, seconds: f64) -> Result<(), String> {
        Err("Sleeping is not supported in this environment".into())
    }
    /// Whether thread spawning is allowed
    fn allow_thread_spawning(&self) -> bool {
        false
    }
    /// Show an image
    #[cfg(feature = "image")]
    fn show_image(&self, image: DynamicImage, label: Option<&str>) -> Result<(), String> {
        Err("Showing images is not supported in this environment".into())
    }
    /// Show a GIF
    fn show_gif(&self, gif_bytes: Vec<u8>, label: Option<&str>) -> Result<(), String> {
        Err("Showing gifs is not supported in this environment".into())
    }
    /// Show an APNG
    fn show_apng(&self, apng_bytes: Vec<u8>, label: Option<&str>) -> Result<(), String> {
        Err("Showing APNGs is not supported in this environment".into())
    }
    /// Play audio from WAV bytes
    fn play_audio(&self, wave_bytes: Vec<u8>, label: Option<&str>) -> Result<(), String> {
        Err("Playing audio is not supported in this environment".into())
    }
    /// Get the audio sample rate
    fn audio_sample_rate(&self) -> u32 {
        44100
    }
    /// Stream audio
    fn stream_audio(&self, f: AudioStreamFn) -> Result<(), String> {
        Err("Streaming audio is not supported in this environment".into())
    }
    /// The result of the `now` function
    ///
    /// Should be in seconds
    fn now(&self) -> f64 {
        now()
    }
    /// Create a TCP listener and bind it to an address
    fn tcp_listen(&self, addr: &str) -> Result<Handle, String> {
        Err("TCP listeners are not supported in this environment".into())
    }
    /// Create a TLS listener and bind it to an address
    fn tls_listen(&self, addr: &str, cert: &[u8], key: &[u8]) -> Result<Handle, String> {
        Err("TLS listeners are not supported in this environment".into())
    }
    /// Accept a connection with a TCP listener
    fn tcp_accept(&self, handle: Handle) -> Result<Handle, String> {
        Err("TCP listeners are not supported in this environment".into())
    }
    /// Create a TCP socket and connect it to an address
    fn tcp_connect(&self, addr: &str) -> Result<Handle, String> {
        Err("TCP sockets are not supported in this environment".into())
    }
    /// Create a TCP socket with TLS support and connect it to an address
    fn tls_connect(&self, addr: &str) -> Result<Handle, String> {
        Err("TLS sockets are not supported in this environment".into())
    }
    /// Get the connection address of a TCP socket or listener
    fn tcp_addr(&self, handle: Handle) -> Result<SocketAddr, String> {
        Err("TCP sockets are not supported in this environment".into())
    }
    /// Set a TCP socket to non-blocking mode
    fn tcp_set_non_blocking(&self, handle: Handle, non_blocking: bool) -> Result<(), String> {
        Err("TCP sockets are not supported in this environment".into())
    }
    /// Set the read timeout of a TCP socket
    fn tcp_set_read_timeout(
        &self,
        handle: Handle,
        timeout: Option<Duration>,
    ) -> Result<(), String> {
        Err("TCP sockets are not supported in this environment".into())
    }
    /// Set the write timeout of a TCP socket
    fn tcp_set_write_timeout(
        &self,
        handle: Handle,
        timeout: Option<Duration>,
    ) -> Result<(), String> {
        Err("TCP sockets are not supported in this environment".into())
    }
    /// Fetch a URL, respecting protocol and port (defaults to https and 443)
    fn fetch(&self, url: &str) -> Result<Vec<u8>, String> {
        let is_https = url.starts_with("https://");
        let is_http = url.starts_with("http://");
        let no_protocol = url
            .trim_start_matches("https://")
            .trim_start_matches("http://");
        let (host, route) = match no_protocol.find('/') {
            Some(i) => no_protocol.split_at(i),
            None => (no_protocol, "/"),
        };
        let (host_only, port, use_tls) = match host.rsplit_once(':') {
            Some((h, p)) if p.parse::<u16>().is_ok() => (h, p, is_https || !is_http),
            _ => {
                let tls = is_https || !is_http;
                let port = if tls { "443" } else { "80" };
                (host, port, tls)
            }
        };
        let addr = format!("{host_only}:{port}");
        let default_port = if use_tls { "443" } else { "80" };
        let host_header = if port == default_port {
            host_only.to_owned()
        } else {
            format!("{host_only}:{port}")
        };
        let req = format!(
            "\
            GET {route} HTTP/1.1\r\n\
            Host: {host_header}\r\n\
            Connection: close\r\n\
            User-Agent: Uiua/{}\r\n\
            \r\n",
            crate::VERSION
        );
        let handle = if use_tls {
            self.tls_connect(&addr)?
        } else {
            self.tcp_connect(&addr)?
        };
        self.write(handle, req.as_bytes())?;

        let mut bytes = match self.read_all(handle) {
            Ok(b) => b,
            Err(e) => {
                if e.contains("close_notify") || e.contains("UnexpectedEof") {
                    return Err("Connection closed without close_notify".into());
                } else {
                    return Err(e);
                }
            }
        };

        let _ = self.close(handle);

        if bytes.is_empty() {
            return Err("Empty HTTP response".into());
        }
        let status_line = bytes.split(|&b| b == b'\n').next().unwrap();
        let status = status_line
            .split(|&b| b == b' ')
            .nth(1)
            .ok_or("Invalid HTTP response: missing status code")?;
        let status_str = String::from_utf8_lossy(status);
        if !status_str.starts_with('2') && !status_str.starts_with('3') {
            return Err(format!("HTTP {status_str}"));
        }
        let body_start = bytes
            .windows(4)
            .position(|w| w == b"\r\n\r\n")
            .map(|i| i + 4)
            .or(bytes.windows(2).position(|w| w == b"\n\n").map(|i| i + 2))
            .ok_or("Invalid HTTP response: missing header separator")?;
        bytes.rotate_left(body_start);
        bytes.truncate(bytes.len() - body_start);
        Ok(bytes)
    }
    /// Create a UDP socket and bind it to an address
    fn udp_bind(&self, addr: &str) -> Result<Handle, String> {
        Err("UDP sockets are not supported in this environment".into())
    }
    /// Receive a single datagram on a UDP socket
    fn udp_recv(&self, handle: Handle) -> Result<(Vec<u8>, SocketAddr), String> {
        Err("UDP sockets are not supported in this environment".into())
    }
    /// Send a datagram to an address over a UDP socket
    fn udp_send(&self, handle: Handle, packet: &[u8], addr: &str) -> Result<(), String> {
        Err("UDP sockets are not supported in this environment".into())
    }
    /// Set the maximum message length for a UDP socket
    fn udp_set_max_msg_length(&self, handle: Handle, max_len: usize) -> Result<(), String> {
        Err("UDP sockets are not supported in this environment".into())
    }
    /// Close a stream
    fn close(&self, handle: Handle) -> Result<(), String> {
        Ok(())
    }
    /// Invoke a path with the system's default program
    fn invoke(&self, path: &str) -> Result<(), String> {
        Err("Invoking paths is not supported in this environment".into())
    }
    /// Run a command, inheriting standard IO
    fn run_command_inherit(&self, command: &str, args: &[&str]) -> Result<i32, String> {
        Err("Running inheritting commands is not supported in this environment".into())
    }
    /// Run a command, capturing standard IO
    fn run_command_capture(
        &self,
        command: &str,
        args: &[&str],
    ) -> Result<(i32, String, String), String> {
        Err("Running capturing commands is not supported in this environment".into())
    }
    /// Run a command and return an IO stream handle
    fn run_command_stream(&self, command: &str, args: &[&str]) -> Result<[Handle; 3], String> {
        Err("Running streamed commands is not supported in this environment".into())
    }
    /// Change the current directory
    fn change_directory(&self, path: &str) -> Result<(), String> {
        Err("Changing directories is not supported in this environment".into())
    }
    /// Get the current directory
    fn get_current_directory(&self) -> Result<String, String> {
        Err("Getting the current directory is not supported in this environment".into())
    }
    /// Capture an image from the webcam
    fn webcam_capture(&self, index: usize) -> Result<WebcamImage, String> {
        Err("Capturing from webcam is not supported in this environment".into())
    }
    /// List available webcams
    fn webcam_list(&self) -> Result<Vec<String>, String> {
        Err("Listing webcams is not supported in this environment".into())
    }
    /// Call a foreign function interface
    fn ffi(
        &self,
        file: &str,
        result_ty: FfiType,
        name: &str,
        arg_tys: &[FfiArg],
        args: Vec<Value>,
    ) -> Result<Value, String> {
        Err("FFI is not supported in this environment".into())
    }
    /// Copy the data from a pointer into an array
    fn mem_copy(&self, ptr: MetaPtr, len: usize) -> Result<Value, String> {
        Err("Pointer copying is not supported in this environment".into())
    }
    /// Write data from an array into a pointer
    fn mem_set(&self, ptr: MetaPtr, idx: usize, value: Value) -> Result<(), String> {
        Err("Pointer writing is not supported in this environment".into())
    }
    /// Free a pointer
    fn mem_free(&self, ptr: &MetaPtr) -> Result<(), String> {
        Err("Pointer freeing is not supported in this environment".into())
    }
    /// Allocate memory and return a pointer to it
    fn mem_allocate(&self, size: usize) -> Result<Value, String> {
        Err("Memory allocation is not supported in this environment".into())
    }
    /// Load a git repo as a module and return the path to its `lib.ua` file
    ///
    /// The returned path should be loadable via [`SysBackend::file_read_all`]
    fn load_git_module(&self, url: &str, target: GitTarget) -> Result<PathBuf, String> {
        Err("Loading git modules is not supported in this environment".into())
    }
    /// Get the local timezone offset in hours
    fn timezone(&self) -> Result<f64, String> {
        if cfg!(target_arch = "wasm32") {
            return Err("Getting the timezone is not supported in this environment".into());
        }
        let offset = UtcOffset::current_local_offset().map_err(|e| e.to_string())?;
        let (h, m, s) = offset.as_hms();
        let mut o = h as f64;
        o += m as f64 / 60.0;
        o += s as f64 / 3600.0;
        Ok(o)
    }
    /// Hit a breakpoint
    ///
    /// Returns whether to continue the program
    fn breakpoint(&self, env: &Uiua) -> Result<bool, String> {
        Err("Breakpoints are not supported in this environment".into())
    }
    /// Resolve a big constant
    fn big_constant(&self, key: BigConstant) -> Result<Cow<'static, [u8]>, String> {
        Err("Retrieval of big constants is not supported in this environment".into())
    }
}

/// A target for a git repository
#[derive(Debug, Clone, Default)]
pub enum GitTarget {
    /// The latest commit on the default branch
    #[default]
    Default,
    /// The latest commit on a specific branch
    Branch(String),
    /// A specific commit
    Commit(String),
}

impl fmt::Debug for dyn SysBackend {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "<sys backend>")
    }
}

/// A safe backend with no IO other than captured stdout and stderr
#[derive(Default)]
pub struct SafeSys {
    stdout: Arc<Mutex<Vec<u8>>>,
    stderr: Arc<Mutex<Vec<u8>>>,
    /// Whether to allow thread spawning
    pub allow_thread_spawning: bool,
}
impl SysBackend for SafeSys {
    fn any(&self) -> &dyn Any {
        self
    }
    fn any_mut(&mut self) -> &mut dyn Any {
        self
    }
    fn print_str_stdout(&self, s: &str) -> Result<(), String> {
        self.stdout.lock().extend_from_slice(s.as_bytes());
        Ok(())
    }
    fn print_str_stderr(&self, s: &str) -> Result<(), String> {
        self.stderr.lock().extend_from_slice(s.as_bytes());
        Ok(())
    }
    fn allow_thread_spawning(&self) -> bool {
        self.allow_thread_spawning
    }
    #[cfg(feature = "native_sys")]
    fn big_constant(&self, key: BigConstant) -> Result<Cow<'static, [u8]>, String> {
        NativeSys.big_constant(key)
    }
}

impl SafeSys {
    /// Create a new safe system backend
    pub fn new() -> Self {
        Self::default()
    }
    /// Create a new safe system backend that allows thread spawning
    pub fn with_thread_spawning() -> Self {
        Self {
            allow_thread_spawning: true,
            ..Self::default()
        }
    }
    /// Take the captured stdout
    pub fn take_stdout(&self) -> Vec<u8> {
        take(&mut *self.stdout.lock())
    }
    /// Take the captured stderr
    pub fn take_stderr(&self) -> Vec<u8> {
        take(&mut *self.stderr.lock())
    }
}

/// Trait for converting to a system backend
pub trait IntoSysBackend {
    /// Convert to a reference counted system backend
    fn into_sys_backend(self) -> Arc<dyn SysBackend>;
}

impl<T> IntoSysBackend for T
where
    T: SysBackend + Send + Sync + 'static,
{
    fn into_sys_backend(self) -> Arc<dyn SysBackend> {
        Arc::new(self)
    }
}

impl IntoSysBackend for Arc<dyn SysBackend> {
    fn into_sys_backend(self) -> Arc<dyn SysBackend> {
        self
    }
}

pub(crate) fn run_sys_op(op: &SysOp, env: &mut Uiua) -> UiuaResult {
    match op {
        SysOp::Show => {
            let val = env.pop(1)?;
            env.rt.backend.show(val).map_err(|e| env.error(e))?;
        }
        SysOp::Prin => {
            let s = env.pop(1)?.format();
            (env.rt.backend)
                .print_str_stdout(&s)
                .map_err(|e| env.error(e))?;
        }
        SysOp::Print => {
            let s = env.pop(1)?.format();
            (env.rt.backend)
                .print_str_stdout(&format!("{s}\n"))
                .map_err(|e| env.error(e))?;
        }
        SysOp::PrinErr => {
            let s = env.pop(1)?.format();
            (env.rt.backend)
                .print_str_stderr(&s)
                .map_err(|e| env.error(e))?;
        }
        SysOp::PrintErr => {
            let s = env.pop(1)?.format();
            (env.rt.backend)
                .print_str_stderr(&format!("{s}\n"))
                .map_err(|e| env.error(e))?;
        }
        SysOp::ScanLine => {
            let start = env.rt.backend.now();
            let res = env.rt.backend.scan_line_stdin().map_err(|e| env.error(e));
            env.rt.execution_start += env.rt.backend.now() - start;
            if let Some(line) = res? {
                env.push(line);
            } else {
                env.push(0u8);
            }
        }
        SysOp::TermSize => {
            let (width, height) = env.rt.backend.term_size().map_err(|e| env.error(e))?;
            env.push(cowslice![height as f64, width as f64])
        }
        SysOp::Exit => {
            let status = env.pop(1)?.as_int(env, "Status must be an integer")? as i32;
            (env.rt.backend).exit(status).map_err(|e| env.error(e))?;
        }
        SysOp::RawMode => {
            let raw_mode = env.pop(1)?.as_bool(env, "Raw mode must be a boolean")?;
            (env.rt.backend)
                .set_raw_mode(raw_mode)
                .map_err(|e| env.error(e))?;
        }
        SysOp::EnvArgs => {
            let mut args = Vec::new();
            args.push(env.file_path().to_string_lossy().into_owned());
            args.extend(env.args().to_owned());
            env.push(Array::<Boxed>::from_iter(args));
        }
        SysOp::Var => {
            let key = env
                .pop(1)?
                .as_string(env, "Augument to var must be a string")?;
            let var = env
                .rt
                .backend
                .var(&key)
                .ok_or_else(|| env.error(format!("Environment variable `{key}` is not set")))?;
            env.push(var);
        }
        SysOp::FOpen => {
            let path = env.pop(1)?.as_string(env, "Path must be a string")?;
            let handle = (env.rt.backend)
                .open_file(path.as_ref(), true)
                .map_err(|e| env.error(e))?
                .value(HandleKind::File(path.into()));
            env.push(handle);
        }
        SysOp::FCreate => {
            let path = env.pop(1)?.as_string(env, "Path must be a string")?;
            let handle: Value = (env.rt.backend)
                .create_file(path.as_ref())
                .map_err(|e| env.error(e))?
                .value(HandleKind::File(path.into()));
            env.push(handle);
        }
        SysOp::FMakeDir => {
            let path = env.pop(1)?.as_string(env, "Path must be a string")?;
            (env.rt.backend)
                .make_dir(path.as_ref())
                .map_err(|e| env.error(e))?;
        }
        SysOp::FDelete => {
            let path = env.pop(1)?.as_string(env, "Path must be a string")?;
            env.rt.backend.delete(&path).map_err(|e| env.error(e))?;
        }
        SysOp::FTrash => {
            let path = env.pop(1)?.as_string(env, "Path must be a string")?;
            env.rt.backend.trash(&path).map_err(|e| env.error(e))?;
        }
        SysOp::ReadStr => {
            let count = env
                .pop(1)?
                .as_nat_or_inf(env, "Count must be an integer or infinity")?;
            if let Some(count) = count {
                validate_size::<char>([count], env)?;
            }
            let handle = env.pop(2)?.as_handle(env, None)?;
            let s = match handle {
                Handle::STDOUT => return Err(env.error("Cannot read from stdout")),
                Handle::STDERR => return Err(env.error("Cannot read from stderr")),
                Handle::STDIN => {
                    let buf = env.rt.backend.scan_stdin(count).map_err(|e| env.error(e))?;
                    match String::from_utf8(buf) {
                        Ok(s) => s,
                        Err(e) => {
                            let valid_to = e.utf8_error().valid_up_to();
                            let mut buf = e.into_bytes();
                            let mut rest = buf.split_off(valid_to);
                            for _ in 0..3 {
                                rest.extend(
                                    env.rt
                                        .backend
                                        .scan_stdin(Some(1))
                                        .map_err(|e| env.error(e))?,
                                );
                                if let Ok(s) = std::str::from_utf8(&rest) {
                                    buf.extend_from_slice(s.as_bytes());
                                    break;
                                }
                            }
                            String::from_utf8(buf).map_err(|e| env.error(e))?
                        }
                    }
                }
                _ => {
                    if let Some(count) = count {
                        let buf = env
                            .rt
                            .backend
                            .read(handle, count)
                            .map_err(|e| env.error(e))?;
                        match String::from_utf8(buf) {
                            Ok(s) => s,
                            Err(e) => {
                                let valid_to = e.utf8_error().valid_up_to();
                                let mut buf = e.into_bytes();
                                let mut rest = buf.split_off(valid_to);
                                for _ in 0..3 {
                                    rest.extend(
                                        env.rt.backend.read(handle, 1).map_err(|e| env.error(e))?,
                                    );
                                    if let Ok(s) = std::str::from_utf8(&rest) {
                                        buf.extend_from_slice(s.as_bytes());
                                        break;
                                    }
                                }
                                String::from_utf8(buf).map_err(|e| env.error(e))?
                            }
                        }
                    } else {
                        let bytes = env.rt.backend.read_all(handle).map_err(|e| env.error(e))?;
                        String::from_utf8(bytes).map_err(|e| env.error(e))?
                    }
                }
            };
            env.push(s);
        }
        SysOp::ReadBytes => {
            let count = env
                .pop(1)?
                .as_nat_or_inf(env, "Count must be an integer or infinity")?;
            if let Some(count) = count {
                validate_size::<u8>([count], env)?;
            }
            let handle = env.pop(2)?.as_handle(env, None)?;
            let bytes = match handle {
                Handle::STDOUT => return Err(env.error("Cannot read from stdout")),
                Handle::STDERR => return Err(env.error("Cannot read from stderr")),
                Handle::STDIN => env.rt.backend.scan_stdin(count).map_err(|e| env.error(e))?,
                _ => {
                    if let Some(count) = count {
                        env.rt
                            .backend
                            .read(handle, count)
                            .map_err(|e| env.error(e))?
                    } else {
                        env.rt.backend.read_all(handle).map_err(|e| env.error(e))?
                    }
                }
            };
            env.push(Array::from(bytes.as_slice()));
        }
        SysOp::ReadUntil => {
            let delim = env.pop(1)?;
            let handle = env.pop(2)?.as_handle(env, None)?;
            if delim.rank() > 1 {
                return Err(env.error("Delimiter must be a rank 0 or 1 string or byte array"));
            }
            match handle {
                Handle::STDOUT => return Err(env.error("Cannot read from stdout")),
                Handle::STDERR => return Err(env.error("Cannot read from stderr")),
                Handle::STDIN => {
                    let mut is_string = false;
                    let delim_bytes: Vec<u8> = match delim {
                        Value::Num(arr) => arr.data.iter().map(|&x| x as u8).collect(),
                        Value::Byte(arr) => arr.data.into(),
                        Value::Char(arr) => {
                            is_string = true;
                            arr.data.iter().collect::<String>().into()
                        }
                        _ => return Err(env.error("Delimiter must be a string or byte array")),
                    };
                    let buffer = env
                        .rt
                        .backend
                        .scan_until_stdin(&delim_bytes)
                        .map_err(|e| env.error(e))?;
                    if is_string {
                        let s = String::from_utf8_lossy(&buffer).into_owned();
                        env.push(s);
                    } else {
                        env.push(Array::from(buffer.as_slice()));
                    }
                }
                _ => match delim {
                    Value::Num(arr) => {
                        let delim: Vec<u8> = arr.data.iter().map(|&x| x as u8).collect();
                        let bytes = env
                            .rt
                            .backend
                            .read_until(handle, &delim)
                            .map_err(|e| env.error(e))?;
                        env.push(Array::from(bytes.as_slice()));
                    }
                    Value::Byte(arr) => {
                        let delim: Vec<u8> = arr.data.into();
                        let bytes = env
                            .rt
                            .backend
                            .read_until(handle, &delim)
                            .map_err(|e| env.error(e))?;
                        env.push(Array::from(bytes.as_slice()));
                    }
                    Value::Char(arr) => {
                        let delim: Vec<u8> = arr.data.iter().collect::<String>().into();
                        let bytes = env
                            .rt
                            .backend
                            .read_until(handle, &delim)
                            .map_err(|e| env.error(e))?;
                        let s = String::from_utf8(bytes).map_err(|e| env.error(e))?;
                        env.push(s);
                    }
                    _ => return Err(env.error("Delimiter must be a string or byte array")),
                },
            }
        }
        SysOp::Write => {
            let data = env.pop(1)?;
            let handle = env.pop(2)?.as_handle(env, None)?;
            let bytes: Vec<u8> = match data {
                Value::Num(arr) => arr.data.iter().map(|&x| x as u8).collect(),
                Value::Byte(arr) => arr.data.into(),
                Value::Char(arr) => arr.data.iter().collect::<String>().into(),
                val => return Err(env.error(format!("Cannot write {} array", val.type_name()))),
            };
            match handle {
                Handle::STDOUT => (env.rt.backend)
                    .print_str_stdout(&String::from_utf8_lossy(&bytes))
                    .map_err(|e| env.error(e))?,
                Handle::STDERR => (env.rt.backend)
                    .print_str_stderr(&String::from_utf8_lossy(&bytes))
                    .map_err(|e| env.error(e))?,
                Handle::STDIN => return Err(env.error("Cannot write to stdin")),
                _ => (env.rt.backend.write(handle, &bytes)).map_err(|e| env.error(e))?,
            }
        }
        SysOp::Seek => {
            let pos = env.pop(1)?.as_int_or_inf(env, None)?;
            let pos = match pos {
                Ok(pos @ ..0) => StreamSeek::End(pos.unsigned_abs()),
                Ok(pos @ 0..) => StreamSeek::Start(pos.unsigned_abs()),
                Err(false) => StreamSeek::End(0),
                Err(true) => StreamSeek::Start(0),
            };
            let handle = env.pop(2)?.as_handle(env, None)?;
            env.rt.backend.seek(handle, pos).map_err(|e| env.error(e))?;
        }
        SysOp::FReadAllStr => {
            let path = env.pop(1)?.as_string(env, "Path must be a string")?;
            let bytes = (env.rt.backend)
                .file_read_all(path.as_ref())
                .or_else(|e| match path.as_str() {
                    "example.ua" => Ok(EXAMPLE_UA.as_bytes().to_vec()),
                    "example.txt" => Ok(EXAMPLE_TXT.as_bytes().to_vec()),
                    _ => Err(e),
                })
                .map_err(|e| env.error(e))?;
            let s = String::from_utf8(bytes).map_err(|e| env.error(e))?;
            env.push(s);
        }
        SysOp::FReadAllBytes => {
            let path = env.pop(1)?.as_string(env, "Path must be a string")?;
            let bytes = (env.rt.backend)
                .file_read_all(path.as_ref())
                .or_else(|e| match path.as_str() {
                    "example.ua" => Ok(EXAMPLE_UA.as_bytes().to_vec()),
                    "example.txt" => Ok(EXAMPLE_TXT.as_bytes().to_vec()),
                    _ => Err(e),
                })
                .map_err(|e| env.error(e))?;
            env.push(Array::<u8>::from_iter(bytes));
        }
        SysOp::FWriteAll => {
            let path = env.pop(1)?.as_string(env, "Path must be a string")?;
            let data = env.pop(2)?;
            let bytes: Vec<u8> = match data {
                Value::Num(arr) => arr.data.iter().map(|&x| x as u8).collect(),
                Value::Byte(arr) => arr.data.into(),
                Value::Char(arr) => arr.data.iter().collect::<String>().into(),
                val => {
                    return Err(
                        env.error(format!("Cannot write {} array to file", val.type_name()))
                    );
                }
            };
            (env.rt.backend)
                .file_write_all(path.as_ref(), &bytes)
                .or_else(|e| {
                    if path == "example.ua" {
                        let new_ex = String::from_utf8(bytes).map_err(|e| e.to_string())?;
                        example_ua(move |ex| *ex = new_ex);
                        Ok(())
                    } else {
                        Err(e)
                    }
                })
                .map_err(|e| env.error(e))?;
        }
        SysOp::FExists => {
            let path = env.pop(1)?.as_string(env, "Path must be a string")?;
            let exists = env.rt.backend.file_exists(&path);
            env.push(exists);
        }
        SysOp::FListDir => {
            let path = env.pop(1)?.as_string(env, "Path must be a string")?;
            let paths = env.rt.backend.list_dir(&path).map_err(|e| env.error(e))?;
            env.push(Array::<Boxed>::from_iter(paths));
        }
        SysOp::FIsFile => {
            let path = env.pop(1)?.as_string(env, "Path must be a string")?;
            let is_file = env.rt.backend.is_file(&path).map_err(|e| env.error(e))?;
            env.push(is_file);
        }
        SysOp::Invoke => {
            let path = env.pop(1)?.as_string(env, "Invoke path must be a string")?;
            env.rt.backend.invoke(&path).map_err(|e| env.error(e))?;
        }
        SysOp::ImShow => {
            #[cfg(feature = "image")]
            {
                let value = env.pop(1)?;
                let image = crate::media::value_to_image(&value).map_err(|e| env.error(e))?;
                (env.rt.backend)
                    .show_image(image, value.meta.label.as_deref())
                    .map_err(|e| env.error(e))?;
            }
            #[cfg(not(feature = "image"))]
            return Err(env.error("Image encoding is not supported in this environment"));
        }
        SysOp::GifShow => {
            #[cfg(feature = "gif")]
            {
                let delay = env.pop(1)?.as_num(env, "Framerate must be a number")?;
                let value = env.pop(2)?;
                let start = env.rt.backend.now();
                let bytes =
                    crate::media::value_to_gif_bytes(&value, delay).map_err(|e| env.error(e))?;
                env.rt.execution_start += env.rt.backend.now() - start;
                (env.rt.backend)
                    .show_gif(bytes, value.meta.label.as_deref())
                    .map_err(|e| env.error(e))?;
            }
            #[cfg(not(feature = "gif"))]
            return Err(env.error("GIF showing is not supported in this environment"));
        }
        SysOp::ApngShow => {
            #[cfg(feature = "apng")]
            {
                let delay = env.pop(1)?.as_num(env, "Framerate must be a number")?;
                let value = env.pop(2)?;
                let start = env.rt.backend.now();
                let bytes =
                    crate::media::value_to_apng_bytes(&value, delay).map_err(|e| env.error(e))?;
                env.rt.execution_start += env.rt.backend.now() - start;
                (env.rt.backend)
                    .show_apng(bytes.into_iter().collect(), value.meta.label.as_deref())
                    .map_err(|e| env.error(e))?;
            }
            #[cfg(not(feature = "apng"))]
            return Err(env.error("APNG showing is not supported in this environment"));
        }
        SysOp::AudioPlay => {
            #[cfg(feature = "audio_encode")]
            {
                let value = env.pop(1)?;
                let bytes =
                    crate::media::value_to_wav_bytes(&value, env.rt.backend.audio_sample_rate())
                        .map_err(|e| env.error(e))?;
                (env.rt.backend)
                    .play_audio(bytes, value.meta.label.as_deref())
                    .map_err(|e| env.error(e))?;
            }
            #[cfg(not(feature = "audio_encode"))]
            return Err(env.error("Audio encoding is not supported in this environment"));
        }
        SysOp::AudioSampleRate => {
            let sample_rate = env.rt.backend.audio_sample_rate();
            env.push(f64::from(sample_rate));
        }
        SysOp::Clip => {
            let contents = env.rt.backend.clipboard().map_err(|e| env.error(e))?;
            env.push(contents);
        }
        SysOp::Sleep => {
            let mut seconds = env.pop(1)?.as_num(env, "Sleep time must be a number")?;
            if seconds < 0.0 {
                return Err(env.error("Sleep time must be positive"));
            }
            if seconds.is_infinite() {
                return Err(env.error("Sleep time cannot be infinite"));
            }
            if let Some(limit) = env.rt.execution_limit {
                let elapsed = env.rt.backend.now() - env.rt.execution_start;
                let max = limit - elapsed;
                seconds = seconds.min(max);
            }
            env.rt.backend.sleep(seconds).map_err(|e| env.error(e))?;
        }
        SysOp::TcpListen => {
            let addr = env.pop(1)?.as_string(env, "Address must be a string")?;
            let handle = (env.rt.backend)
                .tcp_listen(&addr)
                .map_err(|e| env.error(e))?;
            let sock_addr = env.rt.backend.tcp_addr(handle).map_err(|e| env.error(e))?;
            let handle = handle.value(HandleKind::TcpListener(sock_addr));
            env.push(handle);
        }
        SysOp::TlsListen => {
            let addr = env.pop(1)?.as_string(env, "Address must be a string")?;
            let cert = env
                .pop(2)?
                .into_bytes(env, "Cert must be a byte or character array")?;
            let key = env
                .pop(3)?
                .into_bytes(env, "Key must be a byte or character array")?;
            let handle = (env.rt.backend)
                .tls_listen(&addr, &cert, &key)
                .map_err(|e| env.error(e))?;
            let sock_addr = env.rt.backend.tcp_addr(handle).map_err(|e| env.error(e))?;
            let handle = handle.value(HandleKind::TlsListener(sock_addr));
            env.push(handle);
        }
        SysOp::TcpAccept => {
            let handle = env.pop(1)?.as_handle(env, None)?;
            let handle = (env.rt.backend)
                .tcp_accept(handle)
                .map_err(|e| env.error(e))?;
            let addr = (env.rt.backend)
                .tcp_addr(handle)
                .map_err(|e| env.error(e))?;
            let handle = handle.value(HandleKind::TcpSocket(addr));
            env.push(handle);
        }
        SysOp::TcpConnect => {
            let addr = env.pop(1)?.as_string(env, "Address must be a string")?;
            let handle = (env.rt.backend)
                .tcp_connect(&addr)
                .map_err(|e| env.error(e))?;
            let sock_addr = env.rt.backend.tcp_addr(handle).map_err(|e| env.error(e))?;
            let handle = handle.value(HandleKind::TcpSocket(sock_addr));
            env.push(handle);
        }
        SysOp::TlsConnect => {
            let addr = env.pop(1)?.as_string(env, "Address must be a string")?;
            let handle = (env.rt.backend)
                .tls_connect(&addr)
                .map_err(|e| env.error(e))?;
            let sock_addr = env.rt.backend.tcp_addr(handle).map_err(|e| env.error(e))?;
            let handle = handle.value(HandleKind::TlsSocket(sock_addr));
            env.push(handle);
        }
        SysOp::TcpAddr => {
            let handle = env.pop(1)?.as_handle(env, None)?;
            let addr = env.rt.backend.tcp_addr(handle).map_err(|e| env.error(e))?;
            env.push(addr.to_string());
        }
        SysOp::TcpSetNonBlocking => {
            let handle = env.pop(1)?.as_handle(env, None)?;
            (env.rt.backend)
                .tcp_set_non_blocking(handle, true)
                .map_err(|e| env.error(e))?;
        }
        SysOp::TcpSetReadTimeout => {
            let timeout = env.pop(1)?.as_num(env, "Timeout must be a number")?.abs();
            let timeout = if timeout.is_infinite() {
                None
            } else {
                Some(Duration::from_secs_f64(timeout))
            };
            let handle = env.pop(2)?.as_handle(env, None)?;
            (env.rt.backend)
                .tcp_set_read_timeout(handle, timeout)
                .map_err(|e| env.error(e))?;
        }
        SysOp::TcpSetWriteTimeout => {
            let timeout = env.pop(1)?.as_num(env, "Timeout must be a number")?.abs();
            let timeout = if timeout.is_infinite() {
                None
            } else {
                Some(Duration::from_secs_f64(timeout))
            };
            let handle = env.pop(2)?.as_handle(env, None)?;
            (env.rt.backend)
                .tcp_set_write_timeout(handle, timeout)
                .map_err(|e| env.error(e))?;
        }
        SysOp::Fetch => {
            let url = env.pop(1)?.as_string(env, "Url must be a string")?;
            let bytes = env.rt.backend.fetch(&url).map_err(|e| env.error(e))?;
            env.push(bytes);
        }
        SysOp::UdpBind => {
            let addr = env.pop(1)?.as_string(env, "Address must be a string")?;
            let handle = (env.rt.backend).udp_bind(&addr).map_err(|e| env.error(e))?;
            let handle = handle.value(HandleKind::UdpSocket(addr));
            env.push(handle)
        }
        SysOp::UdpReceive => {
            let handle = env.pop(1)?.as_handle(env, None)?;
            let (bytes, addr) = (env.rt.backend)
                .udp_recv(handle)
                .map_err(|e| env.error(e))?;
            env.push(addr.to_string());
            env.push(Array::from(bytes.as_slice()));
        }
        SysOp::UdpSend => {
            let bytes = env.pop(1)?;
            let bytes = bytes.as_bytes(env, "Datagram must be bytes")?;
            let addr = env.pop(2)?.as_string(env, "Address must be a string")?;
            let handle = env.pop(3)?.as_handle(env, None)?;
            (env.rt.backend)
                .udp_send(handle, &bytes, &addr)
                .map_err(|e| env.error(e))?;
        }
        SysOp::UdpSetMaxMsgLength => {
            let length = env
                .pop(1)?
                .as_nat(env, "Message length must be a natural number")?;
            let handle = env.pop(2)?.as_handle(env, None)?;
            (env.rt.backend)
                .udp_set_max_msg_length(handle, length)
                .map_err(|e| env.error(e))?;
        }
        SysOp::Close => {
            let handle = env.pop(1)?.as_handle(env, None)?;
            env.rt.backend.close(handle).map_err(|e| env.error(e))?;
        }
        SysOp::RunInherit => {
            let (command, args) = value_to_command(&env.pop(1)?, env)?;
            let args: Vec<_> = args.iter().map(|s| s.as_str()).collect();
            let code = (env.rt.backend)
                .run_command_inherit(&command, &args)
                .map_err(|e| env.error(e))?;
            env.push(code);
        }
        SysOp::RunCapture => {
            let (command, args) = value_to_command(&env.pop(1)?, env)?;
            let args: Vec<_> = args.iter().map(|s| s.as_str()).collect();
            let (code, stdout, stderr) = (env.rt.backend)
                .run_command_capture(&command, &args)
                .map_err(|e| env.error(e))?;
            env.push(stderr);
            env.push(stdout);
            env.push(code);
        }
        SysOp::RunStream => {
            let (command, args) = value_to_command(&env.pop(1)?, env)?;
            let args: Vec<_> = args.iter().map(|s| s.as_str()).collect();
            let handles = (env.rt.backend)
                .run_command_stream(&command, &args)
                .map_err(|e| env.error(e))?;
            for (handle, kind) in handles
                .into_iter()
                .zip([
                    HandleKind::ChildStdin,
                    HandleKind::ChildStdout,
                    HandleKind::ChildStderr,
                ])
                .rev()
            {
                env.push(handle.value(kind(command.clone())));
            }
        }
        SysOp::ChangeDirectory => {
            let path = env.pop(1)?.as_string(env, "Path must be a string")?;
            (env.rt.backend)
                .change_directory(&path)
                .map_err(|e| env.error(e))?;
        }
        SysOp::WebcamCapture => {
            let index = env.pop(1)?;
            let index = match index.as_nat(env, "Webcam selector must be an integer or string") {
                Ok(index) => index,
                Err(e) => {
                    let name = index.as_string(env, "").map_err(|_| e)?;
                    let names = env.rt.backend.webcam_list().map_err(|e| env.error(e))?;
                    (names.iter().position(|n| n == &name))
                        .ok_or_else(|| env.error(format!("Webcam {name:?} is not available")))?
                }
            };
            let _image = (env.rt.backend)
                .webcam_capture(index)
                .map_err(|e| env.error(e))?;
            #[cfg(feature = "image")]
            env.push(crate::media::rgb_image_to_array(_image));
            #[cfg(not(feature = "image"))]
            return Err(env.error("Webcam capture is not supported in this environment"));
        }
        SysOp::WebcamList => {
            let names = env.rt.backend.webcam_list().map_err(|e| env.error(e))?;
            let arr = Array::from_iter(names.into_iter().map(Into::into).map(Boxed));
            env.push(arr);
        }
        SysOp::Ffi => {
            let sig_def = env.pop(1)?;
            let sig_def = match sig_def {
                Value::Box(arr) => arr,
                val => {
                    return Err(env.error(format!(
                        "FFI signature must be a box array, but it is {}",
                        val.type_name_plural()
                    )));
                }
            };
            if sig_def.rank() != 1 {
                return Err(env.error(format!(
                    "FFI signature must be a rank 1 array, but it is rank {}",
                    sig_def.rank()
                )));
            }
            if sig_def.row_count() < 3 {
                return Err(env.error("FFI signature array must have at least two elements"));
            }
            let mut sig_frags = sig_def.data.into_iter().map(|b| b.0);
            let file_name =
                (sig_frags.next().unwrap()).as_string(env, "FFI file name must be a string")?;
            let result_ty = (sig_frags.next().unwrap())
                .as_string(env, "FFI result type must be a string")?
                .parse::<FfiType>()
                .map_err(|e| env.error(e))?;
            let name = (sig_frags.next().unwrap()).as_string(env, "FFI name must be a string")?;
            let arg_tys = sig_frags
                .map(|frag| {
                    frag.as_string(env, "FFI argument type must be a string")
                        .and_then(|ty| ty.parse::<FfiArg>().map_err(|e| env.error(e)))
                })
                .collect::<UiuaResult<Vec<_>>>()?;
            let args = env.pop(2)?;
            let args: Vec<Value> = args.into_rows().map(Value::unpacked).collect();
            let result = (env.rt.backend)
                .ffi(&file_name, result_ty, &name, &arg_tys, args)
                .map_err(|e| env.error(e))?;
            env.push(result);
        }
        SysOp::MemCopy => {
            let ptr = env
                .pop("pointer")?
                .meta
                .pointer
                .as_ref()
                .ok_or_else(|| env.error("Copied pointer must be a pointer value"))?
                .clone();
            let len = env
                .pop("length")?
                .as_nat(env, "Copied length must be a non-negative integer")?;
            let value = (env.rt.backend)
                .mem_copy(ptr, len)
                .map_err(|e| env.error(e))?;
            env.push(value);
        }
        SysOp::MemSet => {
            let ptr = env
                .pop("pointer")?
                .meta
                .pointer
                .as_ref()
                .ok_or_else(|| env.error("Target pointer must be a pointer value"))?
                .clone();
            let idx = env
                .pop("index")?
                .as_nat(env, "Target index must be a non-negative integer")?;
            let value = env.pop(3)?;
            (env.rt.backend)
                .mem_set(ptr, idx, value)
                .map_err(|e| env.error(e))?;
        }
        SysOp::MemFree => {
            let val = env.pop(1)?;
            let ptr = val
                .meta
                .pointer
                .as_ref()
                .ok_or_else(|| env.error("Freed pointer must be a pointer value"))?;

            (env.rt.backend).mem_free(ptr).map_err(|e| env.error(e))?;
        }
        SysOp::Malloc => {
            let size = env
                .pop("size")?
                .as_nat(env, "Allocated size must be a non-negative integer")?;
            let val = (env.rt.backend)
                .mem_allocate(size)
                .map_err(|e| env.error(e))?;
            env.push(val);
        }
        SysOp::Breakpoint => {
            if !env.rt.backend.breakpoint(env).map_err(|e| env.error(e))? {
                return Err(UiuaErrorKind::Interrupted.into());
            }
        }
        prim => {
            return Err(env.error(if prim.modifier_args().is_some() {
                format!(
                    "{} was not handled as a modifier. \
                        This is a bug in the interpreter",
                    Primitive::Sys(*prim)
                )
            } else {
                format!(
                    "{} was not handled as a function. \
                        This is a bug in the interpreter",
                    Primitive::Sys(*prim)
                )
            }));
        }
    }
    Ok(())
}
pub(crate) fn run_sys_op_mod(op: &SysOp, ops: Ops, env: &mut Uiua) -> UiuaResult {
    match op {
        SysOp::ReadLines => {
            let [f] = get_ops(ops, env)?;
            let handle = env.pop(1)?.as_handle(env, None)?;
            let mut read_lines: ReadLinesReturnFn = match handle {
                Handle::STDIN => Box::new(|env, mut f| {
                    for line in stdin().lines() {
                        let line = line.map_err(|e| env.error(e))?;
                        f(line, env)?;
                    }
                    Ok(())
                }),
                _ => (env.rt.backend)
                    .read_lines(handle)
                    .map_err(|e| env.error(e))?,
            };
            let sig = f.sig;
            if sig.args() == 0 {
                return env.exec(f);
            }
            let acc_count = sig.args().saturating_sub(1);
            let out_count = sig.outputs().saturating_sub(acc_count);
            let mut outputs = multi_output(out_count, Vec::new());
            env.without_fill(|env| {
                read_lines(
                    env,
                    Box::new(|s, env| {
                        let val = Value::from(s);
                        env.push(val);
                        env.exec(f.clone())?;
                        for i in 0..out_count {
                            outputs[i].push(env.pop("read lines output")?);
                        }
                        Ok(())
                    }),
                )
            })?;
            for rows in outputs.into_iter().rev() {
                let val = Value::from_row_values(rows, env)?;
                env.push(val);
            }
        }
        SysOp::AudioStream => {
            let [f] = get_ops(ops, env)?;
            let push_time = f.sig.args() > 0;
            if f.sig != (0, 1) && f.sig.args() != f.sig.outputs() {
                return Err(env.error(format!(
                    "&ast's function must have the same number \
                        of inputs and outputs, but its signature is {}",
                    f.sig
                )));
            }
            if f.sig == (0, 0) {
                return Ok(());
            }
            let mut stream_env = env.clone();
            let res = env.rt.backend.stream_audio(Box::new(move |time_array| {
                if push_time {
                    let time_array = Array::<f64>::from(time_array);
                    stream_env.push(time_array);
                }
                stream_env.exec(f.clone())?;
                let samples = &stream_env.pop(1)?;
                let samples = samples.as_num_array().ok_or_else(|| {
                    stream_env.error("Audio stream function must return a numeric array")
                })?;
                match &*samples.shape {
                    [_] => Ok(samples.data.iter().map(|&x| [x, x]).collect()),
                    &[n, 2] => {
                        let mut samps: Vec<[f64; 2]> = Vec::with_capacity(n);
                        for samp in samples.data.chunks_exact(2) {
                            samps.push([samp[0], samp[1]]);
                        }
                        Ok(samps)
                    }
                    &[2, n] => {
                        let mut samps: Vec<[f64; 2]> = Vec::with_capacity(n);
                        for i in 0..n {
                            samps.push([samples.data[i], samples.data[i + n]]);
                        }
                        Ok(samps)
                    }
                    _ => Err(stream_env.error(format!(
                        "Audio stream function must return either a \
                            rank 1 array or a rank 2 array with 2 rows, \
                            but its shape is {}",
                        samples.shape
                    ))),
                }
            }));
            res.map_err(|e| env.error(e))?;
        }
        prim => {
            return Err(env.error(if prim.modifier_args().is_some() {
                format!(
                    "{} was not handled as a modifier. \
                        This is a bug in the interpreter",
                    Primitive::Sys(*prim)
                )
            } else {
                format!(
                    "{} was handled as a modifier. \
                        This is a bug in the interpreter",
                    Primitive::Sys(*prim)
                )
            }));
        }
    }
    Ok(())
}

fn value_to_command(value: &Value, env: &Uiua) -> UiuaResult<(String, Vec<String>)> {
    let mut strings = Vec::new();
    match value {
        Value::Char(arr) => match arr.rank() {
            0 | 1 => strings.push(arr.data.iter().collect::<String>()),
            2 => {
                for row in arr.rows() {
                    strings.push(row.data.iter().collect::<String>());
                }
            }
            n => {
                return Err(env.error(format!(
                    "Character array as command must be rank 0, 1, \
                    or 2, but its rank is {n}"
                )));
            }
        },
        Value::Box(arr) => match arr.rank() {
            0 | 1 => {
                for Boxed(val) in &arr.data {
                    match val {
                        Value::Char(arr) if arr.rank() <= 1 => {
                            strings.push(arr.data.iter().collect::<String>())
                        }
                        val => {
                            return Err(env.error(format!(
                                "Function array as command must be all boxed strings, \
                                but at least one is a {}",
                                val.type_name()
                            )));
                        }
                    }
                }
            }
            n => {
                return Err(env.error(format!(
                    "Function array as command must be rank 0 or 1, \
                    but its rank is {n}"
                )));
            }
        },
        val => {
            return Err(env.error(format!(
                "Command must be a string or box array, but it is {}",
                val.type_name_plural()
            )));
        }
    }
    if strings.is_empty() {
        return Err(env.error("Command array not be empty"));
    }
    let command = strings.remove(0);
    Ok((command, strings))
}

/// Get the current time in seconds
///
/// This function works on both native and web targets.
pub fn now() -> f64 {
    #[cfg(not(target_arch = "wasm32"))]
    {
        std::time::SystemTime::now()
            .duration_since(std::time::SystemTime::UNIX_EPOCH)
            .expect("System clock was before 1970.")
            .as_secs_f64()
    }
    #[cfg(target_arch = "wasm32")]
    {
        #[cfg(not(feature = "web"))]
        {
            compile_error!("Web target requires the `web` feature")
        }
        #[cfg(feature = "web")]
        {
            use wasm_bindgen::{JsCast, prelude::*};
            js_sys::Reflect::get(&js_sys::global(), &JsValue::from_str("performance"))
                .expect("failed to get performance from global object")
                .unchecked_into::<web_sys::Performance>()
                .now()
                / 1000.0
        }
    }
}

pub(crate) fn terminal_size() -> Option<(usize, usize)> {
    #[cfg(all(not(target_arch = "wasm32"), feature = "terminal_size"))]
    {
        terminal_size::terminal_size().map(|(w, h)| (w.0 as usize, h.0 as usize))
    }

    #[cfg(not(all(not(target_arch = "wasm32"), feature = "terminal_size")))]
    None
}