yash-builtin 0.1.0

Implementation of the built-in utilities of yash
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
// 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/>.

//! Implementation of the shell built-in utilities.
//!
//! Each built-in utility is implemented in the submodule named after the
//! utility. The submodule contains the `main` function that implements the
//! built-in utility. The submodule many also export other items that are used
//! by the `main` function. The module documentation for each submodule
//! describes the specification of the built-in utility.
//!
//! The [`common`] module provides common functions that are used for
//! implementing built-in utilities.
//!
//! # Stack
//!
//! Many built-ins in this crate use [`Stack::current_builtin`] to obtain the
//! command word that invoked the built-in. It is used to report the command
//! location in error messages, switch the behavior of the built-in depending on
//! the command, etc. For the built-ins to work correctly, the
//! [stack](Env::stack) should contain a [built-in frame](Frame::Builtin) so
//! that `Stack::current_builtin` provides the correct command word.
//!
//! # Optional dependency
//!
//! The `yash-builtin` crate has an optional dependency on the `yash-semantics`
//! crate, which is enabled by default. If you disable the `yash-semantics`
//! feature, the following built-ins will be unavailable:
//!
//! - `command`
//! - `eval`
//! - `exec`
//! - `read`
//! - `source`
//! - `type`
//! - `wait`

pub mod alias;
pub mod bg;
pub mod r#break;
pub mod cd;
pub mod colon;
#[cfg(feature = "yash-semantics")]
pub mod command;
pub mod common;
pub mod r#continue;
#[cfg(feature = "yash-semantics")]
pub mod eval;
#[cfg(feature = "yash-semantics")]
pub mod exec;
pub mod exit;
pub mod export;
pub mod r#false;
pub mod fg;
pub mod getopts;
pub mod jobs;
pub mod kill;
pub mod pwd;
#[cfg(feature = "yash-semantics")]
pub mod read;
pub mod readonly;
pub mod r#return;
pub mod set;
pub mod shift;
#[cfg(feature = "yash-semantics")]
pub mod source;
pub mod times;
pub mod trap;
pub mod r#true;
#[cfg(feature = "yash-semantics")]
pub mod r#type;
pub mod typeset;
pub mod ulimit;
pub mod umask;
pub mod unalias;
pub mod unset;
#[cfg(feature = "yash-semantics")]
pub mod wait;

#[doc(no_inline)]
pub use yash_env::builtin::*;
#[cfg(doc)]
use yash_env::stack::{Frame, Stack};
#[cfg(doc)]
use yash_env::Env;

use std::future::ready;
use Type::{Elective, Mandatory, Special};

/// Array of all the implemented built-in utilities.
///
/// The array items are ordered alphabetically.
pub const BUILTINS: &[(&str, Builtin)] = &[
    #[cfg(feature = "yash-semantics")]
    (
        ".",
        Builtin {
            r#type: Special,
            execute: |env, args| Box::pin(source::main(env, args)),
        },
    ),
    (
        ":",
        Builtin {
            r#type: Special,
            execute: |env, args| Box::pin(ready(colon::main(env, args))),
        },
    ),
    (
        "alias",
        Builtin {
            r#type: Mandatory,
            execute: |env, args| Box::pin(alias::main(env, args)),
        },
    ),
    (
        "bg",
        Builtin {
            r#type: Mandatory,
            execute: |env, args| Box::pin(bg::main(env, args)),
        },
    ),
    (
        "break",
        Builtin {
            r#type: Special,
            execute: |env, args| Box::pin(r#break::main(env, args)),
        },
    ),
    (
        "cd",
        Builtin {
            r#type: Mandatory,
            execute: |env, args| Box::pin(cd::main(env, args)),
        },
    ),
    #[cfg(feature = "yash-semantics")]
    (
        "command",
        Builtin {
            r#type: Mandatory,
            execute: |env, args| Box::pin(command::main(env, args)),
        },
    ),
    (
        "continue",
        Builtin {
            r#type: Special,
            execute: |env, args| Box::pin(r#continue::main(env, args)),
        },
    ),
    #[cfg(feature = "yash-semantics")]
    (
        "eval",
        Builtin {
            r#type: Special,
            execute: |env, args| Box::pin(eval::main(env, args)),
        },
    ),
    #[cfg(feature = "yash-semantics")]
    (
        "exec",
        Builtin {
            r#type: Special,
            execute: |env, args| Box::pin(exec::main(env, args)),
        },
    ),
    (
        "exit",
        Builtin {
            r#type: Special,
            execute: |env, args| Box::pin(exit::main(env, args)),
        },
    ),
    (
        "export",
        Builtin {
            r#type: Special,
            execute: |env, args| Box::pin(export::main(env, args)),
        },
    ),
    (
        "false",
        Builtin {
            r#type: Mandatory,
            execute: |env, args| Box::pin(r#false::main(env, args)),
        },
    ),
    (
        "fg",
        Builtin {
            r#type: Mandatory,
            execute: |env, args| Box::pin(fg::main(env, args)),
        },
    ),
    (
        "getopts",
        Builtin {
            r#type: Mandatory,
            execute: |env, args| Box::pin(getopts::main(env, args)),
        },
    ),
    (
        "jobs",
        Builtin {
            r#type: Mandatory,
            execute: |env, args| Box::pin(jobs::main(env, args)),
        },
    ),
    (
        "kill",
        Builtin {
            r#type: Mandatory,
            execute: |env, args| Box::pin(kill::main(env, args)),
        },
    ),
    (
        "pwd",
        Builtin {
            r#type: Mandatory,
            execute: |env, args| Box::pin(pwd::main(env, args)),
        },
    ),
    #[cfg(feature = "yash-semantics")]
    (
        "read",
        Builtin {
            r#type: Mandatory,
            execute: |env, args| Box::pin(read::main(env, args)),
        },
    ),
    (
        "readonly",
        Builtin {
            r#type: Special,
            execute: |env, args| Box::pin(readonly::main(env, args)),
        },
    ),
    (
        "return",
        Builtin {
            r#type: Special,
            execute: |env, args| Box::pin(r#return::main(env, args)),
        },
    ),
    (
        "set",
        Builtin {
            r#type: Special,
            execute: |env, args| Box::pin(set::main(env, args)),
        },
    ),
    (
        "shift",
        Builtin {
            r#type: Special,
            execute: |env, args| Box::pin(shift::main(env, args)),
        },
    ),
    #[cfg(feature = "yash-semantics")]
    (
        "source",
        Builtin {
            r#type: Special,
            execute: |env, args| Box::pin(source::main(env, args)),
        },
    ),
    (
        "times",
        Builtin {
            r#type: Special,
            execute: |env, args| Box::pin(times::main(env, args)),
        },
    ),
    (
        "trap",
        Builtin {
            r#type: Special,
            execute: |env, args| Box::pin(trap::main(env, args)),
        },
    ),
    (
        "true",
        Builtin {
            r#type: Mandatory,
            execute: |env, args| Box::pin(r#true::main(env, args)),
        },
    ),
    #[cfg(feature = "yash-semantics")]
    (
        "type",
        Builtin {
            r#type: Mandatory,
            execute: |env, args| Box::pin(r#type::main(env, args)),
        },
    ),
    (
        "typeset",
        Builtin {
            r#type: Elective,
            execute: |env, args| Box::pin(typeset::main(env, args)),
        },
    ),
    (
        "ulimit",
        Builtin {
            r#type: Mandatory,
            execute: |env, args| Box::pin(ulimit::main(env, args)),
        },
    ),
    (
        "umask",
        Builtin {
            r#type: Mandatory,
            execute: |env, args| Box::pin(umask::main(env, args)),
        },
    ),
    (
        "unalias",
        Builtin {
            r#type: Mandatory,
            execute: |env, args| Box::pin(unalias::main(env, args)),
        },
    ),
    (
        "unset",
        Builtin {
            r#type: Special,
            execute: |env, args| Box::pin(unset::main(env, args)),
        },
    ),
    #[cfg(feature = "yash-semantics")]
    (
        "wait",
        Builtin {
            r#type: Mandatory,
            execute: |env, args| Box::pin(wait::main(env, args)),
        },
    ),
];

#[cfg(test)]
pub(crate) mod tests {
    use assert_matches::assert_matches;
    use futures_executor::LocalSpawner;
    use futures_util::task::LocalSpawnExt as _;
    use futures_util::FutureExt as _;
    use std::cell::RefCell;
    use std::future::Future;
    use std::pin::Pin;
    use std::rc::Rc;
    use std::str::from_utf8;
    use yash_env::system::r#virtual::FileBody;
    use yash_env::system::r#virtual::INode;
    use yash_env::system::r#virtual::SystemState;
    use yash_env::Env;
    use yash_env::VirtualSystem;

    #[derive(Clone, Debug)]
    pub struct LocalExecutor(pub LocalSpawner);

    impl yash_env::system::r#virtual::Executor for LocalExecutor {
        fn spawn(
            &self,
            task: Pin<Box<dyn Future<Output = ()>>>,
        ) -> Result<(), Box<dyn std::error::Error>> {
            self.0
                .spawn_local(task)
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
        }
    }

    /// Helper function to perform a test in a virtual system with an executor.
    pub fn in_virtual_system<F, Fut, T>(f: F) -> T
    where
        F: FnOnce(Env, Rc<RefCell<SystemState>>) -> Fut,
        Fut: Future<Output = T> + 'static,
        T: 'static,
    {
        let system = VirtualSystem::new();
        let state = Rc::clone(&system.state);
        let mut executor = futures_executor::LocalPool::new();
        state.borrow_mut().executor = Some(Rc::new(LocalExecutor(executor.spawner())));

        let env = Env::with_system(Box::new(system));
        let shared_system = env.system.clone();
        let task = f(env, Rc::clone(&state));
        let mut task = executor.spawner().spawn_local_with_handle(task).unwrap();
        loop {
            if let Some(result) = (&mut task).now_or_never() {
                return result;
            }
            executor.run_until_stalled();
            shared_system.select(false).unwrap();
            SystemState::select_all(&state);
        }
    }

    pub fn stub_tty(state: &RefCell<SystemState>) {
        state
            .borrow_mut()
            .file_system
            .save("/dev/tty", Rc::new(RefCell::new(INode::new([]))))
            .unwrap();
    }

    /// Helper function for asserting on the content of /dev/stdout.
    pub fn assert_stdout<F, T>(state: &RefCell<SystemState>, f: F) -> T
    where
        F: FnOnce(&str) -> T,
    {
        let stdout = state.borrow().file_system.get("/dev/stdout").unwrap();
        let stdout = stdout.borrow();
        assert_matches!(&stdout.body, FileBody::Regular { content, .. } => {
            f(from_utf8(content).unwrap())
        })
    }

    /// Helper function for asserting on the content of /dev/stderr.
    pub fn assert_stderr<F, T>(state: &RefCell<SystemState>, f: F) -> T
    where
        F: FnOnce(&str) -> T,
    {
        let stderr = state.borrow().file_system.get("/dev/stderr").unwrap();
        let stderr = stderr.borrow();
        assert_matches!(&stderr.body, FileBody::Regular { content, .. } => {
            f(from_utf8(content).unwrap())
        })
    }

    #[test]
    fn builtins_are_sorted() {
        super::BUILTINS
            .windows(2)
            .for_each(|pair| assert!(pair[0].0 < pair[1].0, "disordered pair: {pair:?}"))
    }
}