yash-semantics 0.16.0

Yash shell language semantics
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
// This file is part of yash, an extended POSIX shell.
// Copyright (C) 2021 WATANABE Yuki
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! Redirection semantics.
//!
//! # Effect of redirections
//!
//! A [redirection](Redir) modifies its [target file
//! descriptor](Redir::fd_or_default) on the basis of its [body](RedirBody).
//!
//! If the body is `Normal`, the operand word is [expanded](crate::expansion)
//! first. Then, the [operator](RedirOp) defines the next behavior:
//!
//! - `FileIn`: Opens a file for reading, regarding the expanded field as a
//!   pathname.
//! - `FileInOut`: Likewise, opens a file for reading and writing.
//! - `FileOut`, `FileClobber`: Likewise, opens a file for writing and clears
//!   the file content.  Creates an empty regular file if the file does not
//!   exist.
//! - `FileAppend`: Likewise, opens a file for appending.
//!   Creates an empty regular file if the file does not exist.
//! - `FdIn`: Copies a file descriptor, regarding the expanded field as a
//!   non-negative decimal integer denoting a readable file descriptor to copy
//!   from. Closes the target file descriptor if the field is a single hyphen
//!   (`-`) instead.
//! - `FdOut`: Likewise, copies or closes a file descriptor, but the source file
//!   descriptor must be writable instead of readable.
//! - `Pipe`: Opens a pipe, regarding the expanded field as a
//!   non-negative decimal integer denoting a file descriptor to become the
//!   reading end of the pipe. The target file descriptor will be the writing
//!   end. (TODO: `Pipe` is not yet implemented.)
//! - `String`: Opens a readable file descriptor from which you can read the
//!   expanded field followed by a newline character. (TODO: `String` is not yet
//!   implemented.)
//!
//! If the `Clobber` [shell option](yash_env::option::Option) is off and a
//! regular file exists at the target pathname, then `FileOut` will fail.
//!
//! If the body is `HereDoc`, the redirection opens a readable file descriptor
//! that yields [expansion](crate::expansion) of the content. The current
//! implementation uses an unnamed temporary file for the file descriptor, but
//! we may change the behavior in the future.
//!
//! # Performing redirections
//!
//! To perform redirections, you need to wrap an [`Env`] in a [`RedirGuard`]
//! first. Then, you call [`RedirGuard::perform_redir`] to affect the target
//! file descriptor. When you drop the `RedirGuard`, it undoes the effect to the
//! file descriptor. See the documentation for [`RedirGuard`] for details.
//!
//! # The CLOEXEC flag
//!
//! The shell may open file descriptors to accomplish its tasks. For example,
//! the dot built-in opens an FD to read a script file. Such FDs should be
//! invisible to the user, so the shell should set the CLOEXEC flag on the FDs.
//!
//! When the user tries to redirect an FD with the CLOEXEC flag, it fails with a
//! [`ReservedFd`](ErrorCause::ReservedFd) error to protect the FD from being
//! overwritten.
//!
//! Note that POSIX requires FDs between 0 and 9 (inclusive) to be available for
//! the user. The shell should move an FD to 10 or above before setting its
//! CLOEXEC flag. Also note that the above described behavior about the CLOEXEC
//! flag is specific to this implementation.

use crate::Runtime;
use crate::expansion::expand_text;
use crate::expansion::expand_word;
use crate::xtrace::XTrace;
use enumset::EnumSet;
use enumset::enum_set;
use std::borrow::Cow;
use std::ffi::CString;
use std::ffi::NulError;
use std::fmt::Write as _;
use std::num::ParseIntError;
use std::ops::Deref;
use std::ops::DerefMut;
use thiserror::Error;
use yash_env::Env;
use yash_env::io::Fd;
use yash_env::io::MIN_INTERNAL_FD;
use yash_env::option::Option::Clobber;
use yash_env::option::State::Off;
use yash_env::semantics::ExitStatus;
use yash_env::semantics::Field;
use yash_env::system::Stat as _;
use yash_env::system::{Close, Dup, Errno, Fcntl, FdFlag, Fstat, Mode, OfdAccess, Open, OpenFlag};
use yash_quote::quoted;
use yash_syntax::source::Location;
use yash_syntax::source::pretty::{Report, ReportType, Snippet};
use yash_syntax::syntax::HereDoc;
use yash_syntax::syntax::Redir;
use yash_syntax::syntax::RedirBody;
use yash_syntax::syntax::RedirOp;
use yash_syntax::syntax::Unquote as _;

/// Record of saving an open file description in another file descriptor.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct SavedFd {
    /// File descriptor by which the original open file description was
    /// previously accessible.
    original: Fd,
    /// Temporary file descriptor that remembers the original open file
    /// description.
    save: Option<Fd>,
}

/// Types of errors that may occur in the redirection.
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ErrorCause {
    /// Expansion error.
    #[error(transparent)]
    Expansion(#[from] crate::expansion::ErrorCause),

    /// Pathname containing a nul byte.
    #[error(transparent)]
    NulByte(#[from] NulError),

    /// The target file descriptor could not be modified for the redirection.
    #[error("{1}")]
    FdNotOverwritten(Fd, Errno),

    /// Use of an FD reserved by the shell
    ///
    /// This error occurs when a redirection tries to modify an existing FD with
    /// the CLOEXEC flag set. See the [module documentation](self) for details.
    #[error("file descriptor {0} is reserved by the shell")]
    ReservedFd(Fd),

    /// Error while opening a file.
    ///
    /// The `CString` is the pathname of the file that could not be opened.
    #[error("cannot open file '{}': {}", .0.to_string_lossy(), .1)]
    OpenFile(CString, Errno),

    /// Operand of `<&` or `>&` that cannot be parsed as an integer.
    #[error("{0} is not a valid file descriptor: {1}")]
    MalformedFd(String, ParseIntError),

    /// `<&` applied to an unreadable file descriptor
    #[error("{0} is not a readable file descriptor")]
    UnreadableFd(Fd),

    /// `>&` applied to an unwritable file descriptor
    #[error("{0} is not a writable file descriptor")]
    UnwritableFd(Fd),

    /// Error preparing a temporary file to save here-document content
    #[error("cannot prepare temporary file for here-document: {0}")]
    TemporaryFileUnavailable(Errno),

    /// Pipe redirection is used, which is not yet implemented.
    #[error("pipe redirection is not yet implemented")]
    UnsupportedPipeRedirection,

    /// Here-string redirection is used, which is not yet implemented.
    #[error("here-string redirection is not yet implemented")]
    UnsupportedHereString,
}

impl ErrorCause {
    /// Returns an error message describing the error.
    #[must_use]
    pub fn message(&self) -> &str {
        // TODO Localize
        use ErrorCause::*;
        match self {
            Expansion(e) => e.message(),
            NulByte(_) => "nul byte found in the pathname",
            FdNotOverwritten(_, _) | ReservedFd(_) => "cannot redirect the file descriptor",
            OpenFile(_, _) => "cannot open the file",
            MalformedFd(_, _) => "not a valid file descriptor",
            UnreadableFd(_) | UnwritableFd(_) => "cannot copy file descriptor",
            TemporaryFileUnavailable(_) => "cannot prepare here-document",
            UnsupportedPipeRedirection | UnsupportedHereString => "unsupported redirection",
        }
    }

    /// Returns a label for annotating the error location.
    #[must_use]
    pub fn label(&self) -> Cow<'_, str> {
        // TODO Localize
        use ErrorCause::*;
        match self {
            Expansion(e) => e.label(),
            NulByte(_) => "pathname should not contain a nul byte".into(),
            FdNotOverwritten(_, errno) => errno.to_string().into(),
            ReservedFd(fd) => format!("file descriptor {fd} reserved by shell").into(),
            OpenFile(path, errno) => format!("{}: {}", path.to_string_lossy(), errno).into(),
            MalformedFd(value, error) => format!("{value}: {error}").into(),
            UnreadableFd(fd) => format!("{fd}: not a readable file descriptor").into(),
            UnwritableFd(fd) => format!("{fd}: not a writable file descriptor").into(),
            TemporaryFileUnavailable(errno) => errno.to_string().into(),
            UnsupportedPipeRedirection => "pipe redirection is not yet implemented".into(),
            UnsupportedHereString => "here-string redirection is not yet implemented".into(),
        }
    }
}

/// Explanation of a redirection error.
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[error("{cause}")]
pub struct Error {
    pub cause: ErrorCause,
    pub location: Location,
}

impl From<crate::expansion::Error> for Error {
    fn from(e: crate::expansion::Error) -> Self {
        Error {
            cause: e.cause.into(),
            location: e.location,
        }
    }
}

impl Error {
    /// Returns a report for the error.
    #[must_use]
    pub fn to_report(&self) -> Report<'_> {
        let mut report = Report::new();
        report.r#type = ReportType::Error;
        report.title = self.cause.message().into();
        report.snippets = Snippet::with_primary_span(&self.location, self.cause.label());
        report
    }
}

/// Converts the error into a report by calling [`Error::to_report`].
impl<'a> From<&'a Error> for Report<'a> {
    #[inline(always)]
    fn from(error: &'a Error) -> Self {
        error.to_report()
    }
}

/// Intermediate state of a redirected file descriptor
#[derive(Debug)]
enum FdSpec {
    /// File descriptor specifically opened for redirection
    Owned(Fd),
    /// Existing file descriptor
    Borrowed(Fd),
    /// Closed file descriptor
    Closed,
}

impl FdSpec {
    fn as_fd(&self) -> Option<Fd> {
        match self {
            &FdSpec::Owned(fd) | &FdSpec::Borrowed(fd) => Some(fd),
            &FdSpec::Closed => None,
        }
    }

    fn close<S: Close>(self, system: &S) {
        match self {
            FdSpec::Owned(fd) => {
                let _ = system.close(fd);
            }
            FdSpec::Borrowed(_) | FdSpec::Closed => (),
        }
    }
}

const MODE: Mode = Mode::ALL_READ.union(Mode::ALL_WRITE);

fn is_cloexec<S: Fcntl>(env: &Env<S>, fd: Fd) -> bool {
    matches!(env.system.fcntl_getfd(fd), Ok(flags) if flags.contains(FdFlag::CloseOnExec))
}

fn into_c_string_value_and_origin(field: Field) -> Result<(CString, Location), Error> {
    match CString::new(field.value) {
        Ok(value) => Ok((value, field.origin)),
        Err(e) => Err(Error {
            cause: ErrorCause::NulByte(e),
            location: field.origin,
        }),
    }
}

/// Opens a file for redirection.
async fn open_file<S: Open>(
    env: &mut Env<S>,
    access: OfdAccess,
    flags: EnumSet<OpenFlag>,
    path: Field,
) -> Result<(FdSpec, Location), Error> {
    let system = &mut env.system;
    let (path, origin) = into_c_string_value_and_origin(path)?;
    match system.open(&path, access, flags, MODE).await {
        Ok(fd) => Ok((FdSpec::Owned(fd), origin)),
        Err(errno) => Err(Error {
            cause: ErrorCause::OpenFile(path, errno),
            location: origin,
        }),
    }
}

/// Opens a file for writing with the `noclobber` option.
async fn open_file_noclobber<S>(env: &mut Env<S>, path: Field) -> Result<(FdSpec, Location), Error>
where
    S: Open + Fstat + Close,
{
    let system = &mut env.system;
    let (path, origin) = into_c_string_value_and_origin(path)?;

    const FLAGS_EXCL: EnumSet<OpenFlag> = enum_set!(OpenFlag::Create | OpenFlag::Exclusive);
    match system
        .open(&path, OfdAccess::WriteOnly, FLAGS_EXCL, MODE)
        .await
    {
        Ok(fd) => return Ok((FdSpec::Owned(fd), origin)),
        Err(Errno::EEXIST) => (),
        Err(errno) => {
            return Err(Error {
                cause: ErrorCause::OpenFile(path, errno),
                location: origin,
            });
        }
    }

    // Okay, it seems there is an existing file. Try opening it.
    match system
        .open(&path, OfdAccess::WriteOnly, EnumSet::empty(), MODE)
        .await
    {
        Ok(fd) => {
            let is_regular = system.fstat(fd).is_ok_and(|stat| stat.is_regular_file());
            if is_regular {
                // We opened the FD without the O_CREAT flag, so somebody else
                // must have created this file. Failure.
                let _: Result<_, _> = system.close(fd);
                Err(Error {
                    cause: ErrorCause::OpenFile(path, Errno::EEXIST),
                    location: origin,
                })
            } else {
                Ok((FdSpec::Owned(fd), origin))
            }
        }
        Err(Errno::ENOENT) => {
            // A file existed on the first open but not on the second. There are
            // two possibilities: One is that a file existed on the first open
            // call and had been removed before the second. In this case, we
            // might be able to create another if we start over. The other is
            // that there is a symbolic link pointing to nothing, in which case
            // retrying would only lead to the same result. Since there is no
            // reliable way to tell the situations apart atomically, we give up
            // and return the initial error.
            Err(Error {
                cause: ErrorCause::OpenFile(path, Errno::EEXIST),
                location: origin,
            })
        }
        Err(errno) => Err(Error {
            cause: ErrorCause::OpenFile(path, errno),
            location: origin,
        }),
    }
}

/// Parses the target of `<&` and `>&`.
fn copy_fd<S: Fcntl>(
    env: &mut Env<S>,
    target: Field,
    expected_access: OfdAccess,
) -> Result<(FdSpec, Location), Error> {
    if target.value == "-" {
        return Ok((FdSpec::Closed, target.origin));
    }

    // Parse the string as an integer
    let fd = match target.value.parse() {
        Ok(number) => Fd(number),
        Err(error) => {
            return Err(Error {
                cause: ErrorCause::MalformedFd(target.value, error),
                location: target.origin,
            });
        }
    };

    // Check if the FD is really readable or writable
    fn is_fd_valid<S: Fcntl>(system: &S, fd: Fd, expected_access: OfdAccess) -> bool {
        system
            .ofd_access(fd)
            .is_ok_and(|access| access == expected_access || access == OfdAccess::ReadWrite)
    }
    fn fd_mode_error(
        fd: Fd,
        expected_access: OfdAccess,
        target: Field,
    ) -> Result<(FdSpec, Location), Error> {
        let cause = match expected_access {
            OfdAccess::ReadOnly => ErrorCause::UnreadableFd(fd),
            OfdAccess::WriteOnly => ErrorCause::UnwritableFd(fd),
            _ => unreachable!("unexpected expected access {expected_access:?}"),
        };
        let location = target.origin;
        Err(Error { cause, location })
    }
    if !is_fd_valid(&env.system, fd, expected_access) {
        return fd_mode_error(fd, expected_access, target);
    }

    // Ensure the FD has no CLOEXEC flag
    if is_cloexec(env, fd) {
        return Err(Error {
            cause: ErrorCause::ReservedFd(fd),
            location: target.origin,
        });
    }

    Ok((FdSpec::Borrowed(fd), target.origin))
}

/// Opens the file for a normal redirection.
async fn open_normal<S>(
    env: &mut Env<S>,
    operator: RedirOp,
    operand: Field,
) -> Result<(FdSpec, Location), Error>
where
    S: Close + Fstat + Fcntl + Open,
{
    use RedirOp::*;
    match operator {
        FileIn => open_file(env, OfdAccess::ReadOnly, EnumSet::empty(), operand).await,
        FileOut if env.options.get(Clobber) == Off => open_file_noclobber(env, operand).await,
        FileOut | FileClobber => {
            open_file(
                env,
                OfdAccess::WriteOnly,
                OpenFlag::Create | OpenFlag::Truncate,
                operand,
            )
            .await
        }
        FileAppend => {
            open_file(
                env,
                OfdAccess::WriteOnly,
                OpenFlag::Create | OpenFlag::Append,
                operand,
            )
            .await
        }
        FileInOut => open_file(env, OfdAccess::ReadWrite, OpenFlag::Create.into(), operand).await,
        FdIn => copy_fd(env, operand, OfdAccess::ReadOnly),
        FdOut => copy_fd(env, operand, OfdAccess::WriteOnly),
        Pipe => Err(Error {
            cause: ErrorCause::UnsupportedPipeRedirection,
            location: operand.origin,
        }),
        String => Err(Error {
            cause: ErrorCause::UnsupportedHereString,
            location: operand.origin,
        }),
    }
}

/// Prepares xtrace for a normal redirection.
fn trace_normal(xtrace: Option<&mut XTrace>, target_fd: Fd, operator: RedirOp, operand: &Field) {
    if let Some(xtrace) = xtrace {
        write!(
            xtrace.redirs(),
            "{}{}{} ",
            target_fd,
            operator,
            quoted(&operand.value)
        )
        .unwrap();
    }
}

/// Prepares xtrace for a here-document.
fn trace_here_doc(xtrace: Option<&mut XTrace>, target_fd: Fd, here_doc: &HereDoc, content: &str) {
    if let Some(xtrace) = xtrace {
        write!(xtrace.redirs(), "{target_fd}{here_doc} ").unwrap();
        let (delimiter, _is_quoted) = here_doc.delimiter.unquote();
        writeln!(xtrace.here_doc_contents(), "{content}{delimiter}").unwrap();
    }
}

mod here_doc;

/// Performs a redirection.
async fn perform<S>(
    env: &mut Env<S>,
    redir: &Redir,
    xtrace: Option<&mut XTrace>,
) -> Result<(SavedFd, Option<ExitStatus>), Error>
where
    S: Runtime + 'static,
{
    let target_fd = redir.fd_or_default();

    // Make sure target_fd doesn't have the CLOEXEC flag
    if is_cloexec(env, target_fd) {
        return Err(Error {
            cause: ErrorCause::ReservedFd(target_fd),
            location: redir.body.operand().location.clone(),
        });
    }

    // Save the current open file description at target_fd to a new FD
    let save = match env
        .system
        .dup(target_fd, MIN_INTERNAL_FD, FdFlag::CloseOnExec.into())
    {
        Ok(save_fd) => Some(save_fd),
        Err(Errno::EBADF) => None,
        Err(errno) => {
            return Err(Error {
                cause: ErrorCause::FdNotOverwritten(target_fd, errno),
                location: redir.body.operand().location.clone(),
            });
        }
    };

    // Prepare an FD from the redirection body
    let (fd_spec, location, exit_status) = match &redir.body {
        RedirBody::Normal { operator, operand } => {
            // TODO perform pathname expansion if applicable
            let (expansion, exit_status) = expand_word(env, operand).await?;
            trace_normal(xtrace, target_fd, *operator, &expansion);
            let (fd, location) = open_normal(env, *operator, expansion).await?;
            (fd, location, exit_status)
        }
        RedirBody::HereDoc(here_doc) => {
            let content_ref = here_doc.content.get();
            let content = content_ref.map(Cow::Borrowed).unwrap_or_default();
            let (content, exit_status) = expand_text(env, &content).await?;
            trace_here_doc(xtrace, target_fd, here_doc, &content);
            let location = here_doc.delimiter.location.clone();
            match here_doc::open_fd(env, content).await {
                Ok(fd) => (FdSpec::Owned(fd), location, exit_status),
                Err(cause) => return Err(Error { cause, location }),
            }
        }
    };

    if let Some(fd) = fd_spec.as_fd() {
        if fd != target_fd {
            let dup_result = env.system.dup2(fd, target_fd);
            fd_spec.close(&env.system);
            match dup_result {
                Ok(new_fd) => assert_eq!(new_fd, target_fd),
                Err(errno) => {
                    return Err(Error {
                        cause: ErrorCause::FdNotOverwritten(target_fd, errno),
                        location,
                    });
                }
            }
        }
    } else {
        let _: Result<(), Errno> = env.system.close(target_fd);
    }

    let original = target_fd;
    Ok((SavedFd { original, save }, exit_status))
}

/// `Env` wrapper for performing redirections.
///
/// This is an RAII-style wrapper of [`Env`] in which redirections are
/// performed. A `RedirGuard` keeps track of file descriptors affected by
/// redirections so that we can restore the file descriptors to the state before
/// performing the redirections.
///
/// There are two ways to clear file descriptors saved in the `RedirGuard`.  One
/// is [`undo_redirs`](Self::undo_redirs), which restores the file descriptors
/// to the original state, and the other is
/// [`preserve_redirs`](Self::preserve_redirs), which removes the saved file
/// descriptors without restoring the state and thus makes the effect of the
/// redirections permanent.
///
/// When an instance of `RedirGuard` is dropped, `undo_redirs` is implicitly
/// called. That means you need to call `preserve_redirs` explicitly to preserve
/// the redirections' effect.
#[derive(Debug)]
pub struct RedirGuard<'e, S: Close + Dup> {
    /// Environment in which redirections are performed.
    env: &'e mut yash_env::Env<S>,
    /// Records of file descriptors that have been modified by redirections.
    saved_fds: Vec<SavedFd>,
}

impl<S: Close + Dup> Deref for RedirGuard<'_, S> {
    type Target = yash_env::Env<S>;
    fn deref(&self) -> &yash_env::Env<S> {
        self.env
    }
}

impl<S: Close + Dup> DerefMut for RedirGuard<'_, S> {
    fn deref_mut(&mut self) -> &mut yash_env::Env<S> {
        self.env
    }
}

impl<S: Close + Dup> std::ops::Drop for RedirGuard<'_, S> {
    fn drop(&mut self) {
        self.undo_redirs()
    }
}

impl<'e, S: Close + Dup> RedirGuard<'e, S> {
    /// Creates a new `RedirGuard`.
    pub fn new(env: &'e mut yash_env::Env<S>) -> Self {
        let saved_fds = Vec::new();
        RedirGuard { env, saved_fds }
    }

    /// Performs a redirection.
    ///
    /// If successful, this function saves internally a backing copy of the file
    /// descriptor affected by the redirection, and returns the exit status of
    /// the last command substitution performed during the redirection, if any.
    ///
    /// If `xtrace` is `Some` instance of `XTrace`, the redirection operators
    /// and the expanded operands are written to it.
    pub async fn perform_redir(
        &mut self,
        redir: &Redir,
        xtrace: Option<&mut XTrace>,
    ) -> Result<Option<ExitStatus>, Error>
    where
        S: Runtime + 'static,
    {
        let (saved_fd, exit_status) = perform(self, redir, xtrace).await?;
        self.saved_fds.push(saved_fd);
        Ok(exit_status)
    }

    /// Performs redirections.
    ///
    /// This is a convenience function for [performing
    /// redirection](Self::perform_redir) for each iterator item.
    ///
    /// If the redirection fails for an item, the remainders are ignored, but
    /// the effects of the preceding items are not canceled.
    ///
    /// If `xtrace` is `Some` instance of `XTrace`, the redirection operators
    /// and the expanded operands are written to it.
    pub async fn perform_redirs<'a, I>(
        &mut self,
        redirs: I,
        mut xtrace: Option<&mut XTrace>,
    ) -> Result<Option<ExitStatus>, Error>
    where
        S: Runtime + 'static,
        I: IntoIterator<Item = &'a Redir>,
    {
        let mut exit_status = None;
        for redir in redirs {
            let new_exit_status = self.perform_redir(redir, xtrace.as_deref_mut()).await?;
            exit_status = new_exit_status.or(exit_status);
        }
        Ok(exit_status)
    }

    /// Undoes the effect of the redirections.
    ///
    /// This function restores the file descriptors affected by redirections to
    /// the original state and closes internal backing file descriptors, which
    /// were used for restoration and are no longer needed.
    pub fn undo_redirs(&mut self) {
        for SavedFd { original, save } in self.saved_fds.drain(..).rev() {
            if let Some(save) = save {
                assert_ne!(save, original);
                let _: Result<_, _> = self.env.system.dup2(save, original);
                let _: Result<_, _> = self.env.system.close(save);
            } else {
                let _: Result<_, _> = self.env.system.close(original);
            }
        }
    }

    /// Makes the redirections permanent.
    ///
    /// This function closes internal backing file descriptors without restoring
    /// the original file descriptor state.
    pub fn preserve_redirs(&mut self) {
        for SavedFd { original: _, save } in self.saved_fds.drain(..) {
            if let Some(save) = save {
                let _: Result<_, _> = self.env.system.close(save);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tests::echo_builtin;
    use crate::tests::return_builtin;
    use assert_matches::assert_matches;
    use futures_util::FutureExt as _;
    use std::cell::RefCell;
    use std::rc::Rc;
    use yash_env::Env;
    use yash_env::VirtualSystem;
    use yash_env::system::Concurrent;
    use yash_env::system::Read as _;
    use yash_env::system::Write as _;
    use yash_env::system::resource::LimitPair;
    use yash_env::system::resource::Resource;
    use yash_env::system::resource::SetRlimit as _;
    use yash_env::system::r#virtual::FileBody;
    use yash_env::system::r#virtual::Inode;
    use yash_env::system::r#virtual::SystemState;
    use yash_env::test_helper::in_virtual_system;
    use yash_env::waker::WakerSet;
    use yash_syntax::syntax::Text;

    /// Returns an environment with a virtual system with a file descriptor limit.
    fn env_with_nofile_limit() -> (Env<Rc<Concurrent<VirtualSystem>>>, Rc<RefCell<SystemState>>) {
        let system = VirtualSystem::new();
        system
            .setrlimit(
                Resource::NOFILE,
                LimitPair {
                    soft: 1024,
                    hard: 1024,
                },
            )
            .unwrap();
        let state = Rc::clone(&system.state);
        let env = Env::with_system(Rc::new(Concurrent::new(system)));
        (env, state)
    }

    #[test]
    fn basic_file_in_redirection() {
        let (mut env, state) = env_with_nofile_limit();
        let file = Rc::new(RefCell::new(Inode::new([42, 123, 254])));
        let mut state = state.borrow_mut();
        state.file_system.save("foo", file).unwrap();
        drop(state);
        let mut env = RedirGuard::new(&mut env);
        let redir = "3< foo".parse().unwrap();
        let result = env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap();
        assert_eq!(result, None);

        let mut buffer = [0; 4];
        let read_count = env
            .system
            .read(Fd(3), &mut buffer)
            .now_or_never()
            .unwrap()
            .unwrap();
        assert_eq!(read_count, 3);
        assert_eq!(buffer, [42, 123, 254, 0]);
    }

    #[test]
    fn moving_fd() {
        let (mut env, state) = env_with_nofile_limit();
        let file = Rc::new(RefCell::new(Inode::new([42, 123, 254])));
        let mut state = state.borrow_mut();
        state.file_system.save("foo", file).unwrap();
        drop(state);
        let mut env = RedirGuard::new(&mut env);
        let redir = "< foo".parse().unwrap();
        env.perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap();

        let mut buffer = [0; 4];
        let read_count = env
            .system
            .read(Fd::STDIN, &mut buffer)
            .now_or_never()
            .unwrap()
            .unwrap();
        assert_eq!(read_count, 3);
        assert_eq!(buffer, [42, 123, 254, 0]);

        let e = env
            .system
            .read(Fd(3), &mut buffer)
            .now_or_never()
            .unwrap()
            .unwrap_err();
        assert_eq!(e, Errno::EBADF);
    }

    #[test]
    fn saving_and_undoing_fd() {
        let (mut env, state) = env_with_nofile_limit();
        let mut state = state.borrow_mut();
        state.file_system.save("file", Rc::default()).unwrap();
        state
            .file_system
            .get("/dev/stdin")
            .unwrap()
            .borrow_mut()
            .body = FileBody::new([17]);
        drop(state);
        let mut redir_env = RedirGuard::new(&mut env);
        let redir = "< file".parse().unwrap();
        redir_env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap();
        redir_env.undo_redirs();
        drop(redir_env);

        let mut buffer = [0; 2];
        let read_count = env
            .system
            .read(Fd::STDIN, &mut buffer)
            .now_or_never()
            .unwrap()
            .unwrap();
        assert_eq!(read_count, 1);
        assert_eq!(buffer[0], 17);
    }

    #[test]
    fn preserving_fd() {
        let (mut env, state) = env_with_nofile_limit();
        let mut state = state.borrow_mut();
        state.file_system.save("file", Rc::default()).unwrap();
        state
            .file_system
            .get("/dev/stdin")
            .unwrap()
            .borrow_mut()
            .body = FileBody::new([17]);
        drop(state);
        let mut redir_env = RedirGuard::new(&mut env);
        let redir = "< file".parse().unwrap();
        redir_env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap();
        redir_env.preserve_redirs();
        drop(redir_env);

        let mut buffer = [0; 2];
        let read_count = env
            .system
            .read(Fd::STDIN, &mut buffer)
            .now_or_never()
            .unwrap()
            .unwrap();
        assert_eq!(read_count, 0);
        let e = env
            .system
            .read(MIN_INTERNAL_FD, &mut buffer)
            .now_or_never()
            .unwrap()
            .unwrap_err();
        assert_eq!(e, Errno::EBADF);
    }

    #[test]
    fn undoing_without_initial_fd() {
        let (mut env, state) = env_with_nofile_limit();
        let mut state = state.borrow_mut();
        state.file_system.save("input", Rc::default()).unwrap();
        drop(state);
        let mut redir_env = RedirGuard::new(&mut env);
        let redir = "4< input".parse().unwrap();
        redir_env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap();
        redir_env.undo_redirs();
        drop(redir_env);

        let mut buffer = [0; 1];
        let e = env
            .system
            .read(Fd(4), &mut buffer)
            .now_or_never()
            .unwrap()
            .unwrap_err();
        assert_eq!(e, Errno::EBADF);
    }

    #[test]
    fn unreadable_file() {
        let mut env = env_with_nofile_limit().0;
        let mut env = RedirGuard::new(&mut env);
        let redir = "< no_such_file".parse().unwrap();
        let e = env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap_err();
        assert_eq!(
            e.cause,
            ErrorCause::OpenFile(c"no_such_file".to_owned(), Errno::ENOENT)
        );
        assert_eq!(e.location, redir.body.operand().location);
    }

    #[test]
    fn multiple_redirections() {
        let (mut env, state) = env_with_nofile_limit();
        let mut state = state.borrow_mut();
        let file = Rc::new(RefCell::new(Inode::new([100])));
        state.file_system.save("foo", file).unwrap();
        let file = Rc::new(RefCell::new(Inode::new([200])));
        state.file_system.save("bar", file).unwrap();
        drop(state);
        let mut env = RedirGuard::new(&mut env);
        env.perform_redir(&"< foo".parse().unwrap(), None)
            .now_or_never()
            .unwrap()
            .unwrap();
        env.perform_redir(&"3< bar".parse().unwrap(), None)
            .now_or_never()
            .unwrap()
            .unwrap();

        let mut buffer = [0; 1];
        let read_count = env
            .system
            .read(Fd::STDIN, &mut buffer)
            .now_or_never()
            .unwrap()
            .unwrap();
        assert_eq!(read_count, 1);
        assert_eq!(buffer, [100]);
        let read_count = env
            .system
            .read(Fd(3), &mut buffer)
            .now_or_never()
            .unwrap()
            .unwrap();
        assert_eq!(read_count, 1);
        assert_eq!(buffer, [200]);
    }

    #[test]
    fn later_redirection_wins() {
        let (mut env, state) = env_with_nofile_limit();
        let mut state = state.borrow_mut();
        let file = Rc::new(RefCell::new(Inode::new([100])));
        state.file_system.save("foo", file).unwrap();
        let file = Rc::new(RefCell::new(Inode::new([200])));
        state.file_system.save("bar", file).unwrap();
        drop(state);

        let mut env = RedirGuard::new(&mut env);
        env.perform_redir(&"< foo".parse().unwrap(), None)
            .now_or_never()
            .unwrap()
            .unwrap();
        env.perform_redir(&"< bar".parse().unwrap(), None)
            .now_or_never()
            .unwrap()
            .unwrap();

        let mut buffer = [0; 1];
        let read_count = env
            .system
            .read(Fd::STDIN, &mut buffer)
            .now_or_never()
            .unwrap()
            .unwrap();
        assert_eq!(read_count, 1);
        assert_eq!(buffer, [200]);
    }

    #[test]
    fn target_with_cloexec() {
        let mut env = env_with_nofile_limit().0;
        let fd = env
            .system
            .open(
                c"foo",
                OfdAccess::WriteOnly,
                OpenFlag::Create.into(),
                Mode::ALL_9,
            )
            .now_or_never()
            .unwrap()
            .unwrap();
        env.system
            .fcntl_setfd(fd, FdFlag::CloseOnExec.into())
            .unwrap();

        let mut env = RedirGuard::new(&mut env);
        let redir = format!("{fd}> bar").parse().unwrap();
        let e = env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap_err();
        assert_eq!(e.cause, ErrorCause::ReservedFd(fd));
        assert_eq!(e.location, redir.body.operand().location);
    }

    #[test]
    fn exit_status_of_command_substitution_in_normal() {
        in_virtual_system(|mut env, state| async move {
            env.builtins.insert("echo", echo_builtin());
            env.builtins.insert("return", return_builtin());
            let mut env = RedirGuard::new(&mut env);
            let redir = "3> $(echo foo; return -n 79)".parse().unwrap();
            let result = env.perform_redir(&redir, None).await.unwrap();
            assert_eq!(result, Some(ExitStatus(79)));
            let file = state.borrow().file_system.get("foo");
            assert!(file.is_ok(), "{file:?}");
        })
    }

    #[test]
    fn exit_status_of_command_substitution_in_here_doc() {
        in_virtual_system(|mut env, _state| async move {
            env.builtins.insert("echo", echo_builtin());
            env.builtins.insert("return", return_builtin());
            let mut env = RedirGuard::new(&mut env);
            let redir = Redir {
                fd: Some(Fd(4)),
                body: RedirBody::HereDoc(Rc::new(HereDoc {
                    delimiter: "-END".parse().unwrap(),
                    remove_tabs: false,
                    content: "$(echo foo)$(echo bar; return -n 42)\n"
                        .parse::<Text>()
                        .unwrap()
                        .into(),
                })),
            };
            let result = env.perform_redir(&redir, None).await.unwrap();
            assert_eq!(result, Some(ExitStatus(42)));

            let mut buffer = [0; 10];
            let count = env
                .system
                .read(Fd(4), &mut buffer)
                .now_or_never()
                .unwrap()
                .unwrap();
            assert_eq!(count, 7);
            assert_eq!(&buffer[..7], b"foobar\n");
        })
    }

    #[test]
    fn xtrace_normal() {
        let mut xtrace = XTrace::new();
        let mut env = env_with_nofile_limit().0;
        let mut env = RedirGuard::new(&mut env);
        env.perform_redir(&"> foo${unset-&}".parse().unwrap(), Some(&mut xtrace))
            .now_or_never()
            .unwrap()
            .unwrap();
        env.perform_redir(&"3>> bar".parse().unwrap(), Some(&mut xtrace))
            .now_or_never()
            .unwrap()
            .unwrap();
        let result = xtrace.finish(&mut env).now_or_never().unwrap();
        assert_eq!(result, "1>'foo&' 3>>bar\n");
    }

    #[test]
    fn xtrace_here_doc() {
        let mut xtrace = XTrace::new();
        let mut env = env_with_nofile_limit().0;
        let mut env = RedirGuard::new(&mut env);

        let redir = Redir {
            fd: Some(Fd(4)),
            body: RedirBody::HereDoc(Rc::new(HereDoc {
                delimiter: r"-\END".parse().unwrap(),
                remove_tabs: false,
                content: "foo\n".parse::<Text>().unwrap().into(),
            })),
        };
        env.perform_redir(&redir, Some(&mut xtrace))
            .now_or_never()
            .unwrap()
            .unwrap();

        let redir = Redir {
            fd: Some(Fd(5)),
            body: RedirBody::HereDoc(Rc::new(HereDoc {
                delimiter: r"EOF".parse().unwrap(),
                remove_tabs: false,
                content: "bar${unset-}\n".parse::<Text>().unwrap().into(),
            })),
        };
        env.perform_redir(&redir, Some(&mut xtrace))
            .now_or_never()
            .unwrap()
            .unwrap();

        let result = xtrace.finish(&mut env).now_or_never().unwrap();
        assert_eq!(result, "4<< -\\END 5<<EOF\nfoo\n-END\nbar\nEOF\n");
    }

    #[test]
    fn file_in_closes_opened_file_on_error() {
        let mut env = env_with_nofile_limit().0;
        let mut env = RedirGuard::new(&mut env);
        let redir = "999999999</dev/stdin".parse().unwrap();
        let e = env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap_err();

        assert_eq!(
            e.cause,
            ErrorCause::FdNotOverwritten(Fd(999999999), Errno::EBADF)
        );
        assert_eq!(e.location, redir.body.operand().location);
        let mut buffer = [0; 1];
        let e = env
            .system
            .read(Fd(3), &mut buffer)
            .now_or_never()
            .unwrap()
            .unwrap_err();
        assert_eq!(e, Errno::EBADF);
    }

    #[test]
    fn file_out_creates_empty_file() {
        let (mut env, state) = env_with_nofile_limit();
        let mut env = RedirGuard::new(&mut env);
        let redir = "3> foo".parse().unwrap();
        env.perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap();
        env.system
            .write(Fd(3), &[42, 123, 57])
            .now_or_never()
            .unwrap()
            .unwrap();

        let file = state.borrow().file_system.get("foo").unwrap();
        let file = file.borrow();
        assert_matches!(&file.body, FileBody::Regular { content, .. } => {
            assert_eq!(content[..], [42, 123, 57]);
        });
    }

    #[test]
    fn file_out_truncates_existing_file() {
        let file = Rc::new(RefCell::new(Inode::new([42, 123, 254])));
        let (mut env, state) = env_with_nofile_limit();
        let mut state = state.borrow_mut();
        state.file_system.save("foo", Rc::clone(&file)).unwrap();
        drop(state);
        let mut env = RedirGuard::new(&mut env);

        let redir = "3> foo".parse().unwrap();
        env.perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap();

        let file = file.borrow();
        assert_matches!(&file.body, FileBody::Regular { content, .. } => {
            assert_eq!(content[..], []);
        });
    }

    #[test]
    fn file_out_noclobber_with_regular_file() {
        let file = Rc::new(RefCell::new(Inode::new([42, 123, 254])));
        let (mut env, state) = env_with_nofile_limit();
        let mut state = state.borrow_mut();
        state.file_system.save("foo", Rc::clone(&file)).unwrap();
        drop(state);
        env.options.set(Clobber, Off);
        let mut env = RedirGuard::new(&mut env);

        let redir = "3> foo".parse().unwrap();
        let e = env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap_err();

        assert_eq!(
            e.cause,
            ErrorCause::OpenFile(c"foo".to_owned(), Errno::EEXIST)
        );
        assert_eq!(e.location, redir.body.operand().location);
        let file = file.borrow();
        assert_matches!(&file.body, FileBody::Regular { content, .. } => {
            assert_eq!(content[..], [42, 123, 254]);
        });
    }

    #[test]
    fn file_out_noclobber_with_non_regular_file() {
        let inode = Inode {
            body: FileBody::Fifo {
                content: Default::default(),
                readers: 1,
                writers: 0,
                pending_open_wakers: WakerSet::new(),
                pending_read_wakers: WakerSet::new(),
                pending_write_wakers: WakerSet::new(),
            },
            permissions: Default::default(),
        };
        let file = Rc::new(RefCell::new(inode));
        let (mut env, state) = env_with_nofile_limit();
        let mut state = state.borrow_mut();
        state.file_system.save("foo", Rc::clone(&file)).unwrap();
        drop(state);
        env.options.set(Clobber, Off);
        let mut env = RedirGuard::new(&mut env);

        let redir = "3> foo".parse().unwrap();
        let result = env.perform_redir(&redir, None).now_or_never().unwrap();
        assert_eq!(result, Ok(None));
    }

    #[test]
    fn file_out_closes_opened_file_on_error() {
        let mut env = env_with_nofile_limit().0;
        let mut env = RedirGuard::new(&mut env);
        let redir = "999999999>foo".parse().unwrap();
        let e = env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap_err();

        assert_eq!(
            e.cause,
            ErrorCause::FdNotOverwritten(Fd(999999999), Errno::EBADF)
        );
        assert_eq!(e.location, redir.body.operand().location);
        let e = env
            .system
            .write(Fd(3), &[0x20])
            .now_or_never()
            .unwrap()
            .unwrap_err();
        assert_eq!(e, Errno::EBADF);
    }

    #[test]
    fn file_clobber_creates_empty_file() {
        let (mut env, state) = env_with_nofile_limit();
        let mut env = RedirGuard::new(&mut env);

        let redir = "3>| foo".parse().unwrap();
        env.perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap();
        env.system
            .write(Fd(3), &[42, 123, 57])
            .now_or_never()
            .unwrap()
            .unwrap();

        let file = state.borrow().file_system.get("foo").unwrap();
        let file = file.borrow();
        assert_matches!(&file.body, FileBody::Regular { content, .. } => {
            assert_eq!(content[..], [42, 123, 57]);
        });
    }

    #[test]
    fn file_clobber_by_default_truncates_existing_file() {
        let file = Rc::new(RefCell::new(Inode::new([42, 123, 254])));
        let (mut env, state) = env_with_nofile_limit();
        let mut state = state.borrow_mut();
        state.file_system.save("foo", Rc::clone(&file)).unwrap();
        drop(state);
        let mut env = RedirGuard::new(&mut env);

        let redir = "3>| foo".parse().unwrap();
        env.perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap();

        let file = file.borrow();
        assert_matches!(&file.body, FileBody::Regular { content, .. } => {
            assert_eq!(content[..], []);
        });
    }

    // TODO file_clobber_with_noclobber_fails_with_existing_file

    #[test]
    fn file_clobber_closes_opened_file_on_error() {
        let mut env = env_with_nofile_limit().0;
        let mut env = RedirGuard::new(&mut env);
        let redir = "999999999>|foo".parse().unwrap();
        let e = env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap_err();

        assert_eq!(
            e.cause,
            ErrorCause::FdNotOverwritten(Fd(999999999), Errno::EBADF)
        );
        assert_eq!(e.location, redir.body.operand().location);
        let e = env
            .system
            .write(Fd(3), &[0x20])
            .now_or_never()
            .unwrap()
            .unwrap_err();
        assert_eq!(e, Errno::EBADF);
    }

    #[test]
    fn file_append_creates_empty_file() {
        let (mut env, state) = env_with_nofile_limit();
        let mut env = RedirGuard::new(&mut env);

        let redir = "3>> foo".parse().unwrap();
        env.perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap();
        env.system
            .write(Fd(3), &[42, 123, 57])
            .now_or_never()
            .unwrap()
            .unwrap();

        let file = state.borrow().file_system.get("foo").unwrap();
        let file = file.borrow();
        assert_matches!(&file.body, FileBody::Regular { content, .. } => {
            assert_eq!(content[..], [42, 123, 57]);
        });
    }

    #[test]
    fn file_append_appends_to_existing_file() {
        let file = Rc::new(RefCell::new(Inode::new(*b"one\n")));
        let (mut env, state) = env_with_nofile_limit();
        let mut state = state.borrow_mut();
        state.file_system.save("foo", Rc::clone(&file)).unwrap();
        drop(state);
        let mut env = RedirGuard::new(&mut env);

        let redir = ">> foo".parse().unwrap();
        env.perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap();
        env.system
            .write(Fd::STDOUT, "two\n".as_bytes())
            .now_or_never()
            .unwrap()
            .unwrap();

        let file = file.borrow();
        assert_matches!(&file.body, FileBody::Regular { content, .. } => {
            assert_eq!(std::str::from_utf8(content), Ok("one\ntwo\n"));
        });
    }

    #[test]
    fn file_append_closes_opened_file_on_error() {
        let mut env = env_with_nofile_limit().0;
        let mut env = RedirGuard::new(&mut env);
        let redir = "999999999>>foo".parse().unwrap();
        let e = env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap_err();

        assert_eq!(
            e.cause,
            ErrorCause::FdNotOverwritten(Fd(999999999), Errno::EBADF)
        );
        assert_eq!(e.location, redir.body.operand().location);
        let e = env
            .system
            .write(Fd(3), &[0x20])
            .now_or_never()
            .unwrap()
            .unwrap_err();
        assert_eq!(e, Errno::EBADF);
    }

    #[test]
    fn file_in_out_creates_empty_file() {
        let (mut env, state) = env_with_nofile_limit();
        let mut env = RedirGuard::new(&mut env);
        let redir = "3<> foo".parse().unwrap();
        env.perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap();
        env.system
            .write(Fd(3), &[230, 175, 26])
            .now_or_never()
            .unwrap()
            .unwrap();

        let file = state.borrow().file_system.get("foo").unwrap();
        let file = file.borrow();
        assert_matches!(&file.body, FileBody::Regular { content, .. } => {
            assert_eq!(content[..], [230, 175, 26]);
        });
    }

    #[test]
    fn file_in_out_leaves_existing_file_content() {
        let (mut env, state) = env_with_nofile_limit();
        let file = Rc::new(RefCell::new(Inode::new([132, 79, 210])));
        let mut state = state.borrow_mut();
        state.file_system.save("foo", file).unwrap();
        drop(state);
        let mut env = RedirGuard::new(&mut env);
        let redir = "3<> foo".parse().unwrap();
        env.perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap();

        let mut buffer = [0; 4];
        let read_count = env
            .system
            .read(Fd(3), &mut buffer)
            .now_or_never()
            .unwrap()
            .unwrap();
        assert_eq!(read_count, 3);
        assert_eq!(buffer, [132, 79, 210, 0]);
    }

    #[test]
    fn file_in_out_closes_opened_file_on_error() {
        let mut env = env_with_nofile_limit().0;
        let mut env = RedirGuard::new(&mut env);
        let redir = "999999999<>foo".parse().unwrap();
        let e = env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap_err();

        assert_eq!(
            e.cause,
            ErrorCause::FdNotOverwritten(Fd(999999999), Errno::EBADF)
        );
        assert_eq!(e.location, redir.body.operand().location);
        let e = env
            .system
            .write(Fd(3), &[0x20])
            .now_or_never()
            .unwrap()
            .unwrap_err();
        assert_eq!(e, Errno::EBADF);
    }

    #[test]
    fn fd_in_copies_fd() {
        for fd in [Fd(0), Fd(3)] {
            let (mut env, state) = env_with_nofile_limit();
            state
                .borrow_mut()
                .file_system
                .get("/dev/stdin")
                .unwrap()
                .borrow_mut()
                .body = FileBody::new([1, 2, 42]);
            let mut env = RedirGuard::new(&mut env);
            let redir = "3<& 0".parse().unwrap();
            env.perform_redir(&redir, None)
                .now_or_never()
                .unwrap()
                .unwrap();

            let mut buffer = [0; 4];
            let read_count = env
                .system
                .read(fd, &mut buffer)
                .now_or_never()
                .unwrap()
                .unwrap();
            assert_eq!(read_count, 3);
            assert_eq!(buffer, [1, 2, 42, 0]);
        }
    }

    #[test]
    fn fd_in_closes_fd() {
        let mut env = env_with_nofile_limit().0;
        let mut env = RedirGuard::new(&mut env);
        let redir = "<& -".parse().unwrap();
        env.perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap();

        let mut buffer = [0; 1];
        let e = env
            .system
            .read(Fd::STDIN, &mut buffer)
            .now_or_never()
            .unwrap()
            .unwrap_err();
        assert_eq!(e, Errno::EBADF);
    }

    #[test]
    fn fd_in_rejects_unreadable_fd() {
        let mut env = env_with_nofile_limit().0;
        let mut env = RedirGuard::new(&mut env);
        let redir = "3>foo".parse().unwrap();
        env.perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap();

        let redir = "<&3".parse().unwrap();
        let e = env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap_err();
        assert_eq!(e.cause, ErrorCause::UnreadableFd(Fd(3)));
        assert_eq!(e.location, redir.body.operand().location);
    }

    #[test]
    fn fd_in_rejects_unopened_fd() {
        let mut env = env_with_nofile_limit().0;
        let mut env = RedirGuard::new(&mut env);

        let redir = "3<&3".parse().unwrap();
        let e = env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap_err();
        assert_eq!(e.cause, ErrorCause::UnreadableFd(Fd(3)));
        assert_eq!(e.location, redir.body.operand().location);
    }

    #[test]
    fn fd_in_rejects_fd_with_cloexec() {
        let mut env = env_with_nofile_limit().0;
        env.system
            .fcntl_setfd(Fd(0), FdFlag::CloseOnExec.into())
            .unwrap();

        let mut env = RedirGuard::new(&mut env);
        let redir = "3<& 0".parse().unwrap();
        let e = env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap_err();
        assert_eq!(e.cause, ErrorCause::ReservedFd(Fd(0)));
        assert_eq!(e.location, redir.body.operand().location);
    }

    #[test]
    fn keep_target_fd_open_on_error_in_fd_in() {
        let mut env = env_with_nofile_limit().0;
        let mut env = RedirGuard::new(&mut env);
        let redir = "999999999<&0".parse().unwrap();
        let e = env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap_err();

        assert_eq!(
            e.cause,
            ErrorCause::FdNotOverwritten(Fd(999999999), Errno::EBADF)
        );
        assert_eq!(e.location, redir.body.operand().location);
        let mut buffer = [0; 1];
        let read_count = env
            .system
            .read(Fd(0), &mut buffer)
            .now_or_never()
            .unwrap()
            .unwrap();
        assert_eq!(read_count, 0);
    }

    #[test]
    fn fd_out_copies_fd() {
        for fd in [Fd(1), Fd(4)] {
            let (mut env, state) = env_with_nofile_limit();
            let mut env = RedirGuard::new(&mut env);
            let redir = "4>& 1".parse().unwrap();
            env.perform_redir(&redir, None)
                .now_or_never()
                .unwrap()
                .unwrap();

            env.system
                .write(fd, &[7, 6, 91])
                .now_or_never()
                .unwrap()
                .unwrap();
            let file = state.borrow().file_system.get("/dev/stdout").unwrap();
            let file = file.borrow();
            assert_matches!(&file.body, FileBody::Regular { content, .. } => {
                assert_eq!(content[..], [7, 6, 91]);
            });
        }
    }

    #[test]
    fn fd_out_closes_fd() {
        let mut env = env_with_nofile_limit().0;
        let mut env = RedirGuard::new(&mut env);
        let redir = ">& -".parse().unwrap();
        env.perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap();

        let mut buffer = [0; 1];
        let e = env
            .system
            .read(Fd::STDOUT, &mut buffer)
            .now_or_never()
            .unwrap()
            .unwrap_err();
        assert_eq!(e, Errno::EBADF);
    }

    #[test]
    fn fd_out_rejects_unwritable_fd() {
        let mut env = env_with_nofile_limit().0;
        let mut env = RedirGuard::new(&mut env);
        let redir = "3</dev/stdin".parse().unwrap();
        env.perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap();

        let redir = ">&3".parse().unwrap();
        let e = env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap_err();
        assert_eq!(e.cause, ErrorCause::UnwritableFd(Fd(3)));
        assert_eq!(e.location, redir.body.operand().location);
    }

    #[test]
    fn fd_out_rejects_unopened_fd() {
        let mut env = env_with_nofile_limit().0;
        let mut env = RedirGuard::new(&mut env);

        let redir = "3>&3".parse().unwrap();
        let e = env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap_err();
        assert_eq!(e.cause, ErrorCause::UnwritableFd(Fd(3)));
        assert_eq!(e.location, redir.body.operand().location);
    }

    #[test]
    fn fd_out_rejects_fd_with_cloexec() {
        let mut env = env_with_nofile_limit().0;
        env.system
            .fcntl_setfd(Fd(1), FdFlag::CloseOnExec.into())
            .unwrap();

        let mut env = RedirGuard::new(&mut env);
        let redir = "4>& 1".parse().unwrap();
        let e = env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap_err();
        assert_eq!(e.cause, ErrorCause::ReservedFd(Fd(1)));
        assert_eq!(e.location, redir.body.operand().location);
    }

    #[test]
    fn keep_target_fd_open_on_error_in_fd_out() {
        let mut env = env_with_nofile_limit().0;
        let mut env = RedirGuard::new(&mut env);
        let redir = "999999999>&1".parse().unwrap();
        let e = env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap_err();

        assert_eq!(
            e.cause,
            ErrorCause::FdNotOverwritten(Fd(999999999), Errno::EBADF)
        );
        assert_eq!(e.location, redir.body.operand().location);
        let write_count = env
            .system
            .write(Fd(1), &[0x20])
            .now_or_never()
            .unwrap()
            .unwrap();
        assert_eq!(write_count, 1);
    }

    #[test]
    fn pipe_redirection_not_yet_implemented() {
        let mut env = env_with_nofile_limit().0;
        let mut env = RedirGuard::new(&mut env);
        let redir = "3>>|4".parse().unwrap();
        let e = env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap_err();

        assert_eq!(e.cause, ErrorCause::UnsupportedPipeRedirection);
        assert_eq!(e.location, redir.body.operand().location);
    }

    #[test]
    fn here_string_not_yet_implemented() {
        let mut env = env_with_nofile_limit().0;
        let mut env = RedirGuard::new(&mut env);
        let redir = "3<<< here".parse().unwrap();
        let e = env
            .perform_redir(&redir, None)
            .now_or_never()
            .unwrap()
            .unwrap_err();

        assert_eq!(e.cause, ErrorCause::UnsupportedHereString);
        assert_eq!(e.location, redir.body.operand().location);
    }
}