yash-semantics 0.15.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
// This file is part of yash, an extended POSIX shell.
// Copyright (C) 2022 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/>.

//! Execution of the case command

use crate::Handle;
use crate::Runtime;
use crate::command::Command;
use crate::expansion::attr_fnmatch::apply_escapes;
use crate::expansion::attr_fnmatch::to_pattern_chars;
use crate::expansion::expand_word;
use crate::expansion::expand_word_attr;
use crate::xtrace::XTrace;
use crate::xtrace::print;
use std::fmt::Write;
use std::ops::ControlFlow::Continue;
use yash_env::Env;
use yash_env::semantics::ExitStatus;
use yash_env::semantics::Result;
use yash_fnmatch::Config;
use yash_fnmatch::Pattern;
use yash_quote::quoted;
use yash_syntax::syntax::CaseItem;
use yash_syntax::syntax::Word;

async fn trace_subject<S: Runtime + 'static>(env: &mut Env<S>, value: &str) {
    if let Some(mut xtrace) = XTrace::from_options(&env.options) {
        write!(xtrace.words(), "case {} in ", quoted(value)).unwrap();
        print(env, xtrace).await;
    }
}
// We don't trace expanded patterns since they need a quoting method different
// from yash_quote::quote.

fn config() -> Config {
    let mut config = Config::default();
    config.anchor_begin = true;
    config.anchor_end = true;
    config
}

/// Executes the case command.
pub async fn execute<S: Runtime + 'static>(
    env: &mut Env<S>,
    subject: &Word,
    items: &[CaseItem],
) -> Result {
    let subject = match expand_word(env, subject).await {
        Ok((expansion, _exit_status)) => expansion,
        Err(error) => return error.handle(env).await,
    };
    trace_subject(env, &subject.value).await;

    let mut falling_through = false;
    let mut exit_status_updated = false;
    for item in items {
        if !falling_through {
            match matches(env, &subject.value, &item.patterns).await {
                Ok(true) => (),
                Ok(false) => continue,
                Err(error) => return error.handle(env).await,
            }
        }

        item.body.execute(env).await?;
        exit_status_updated = !item.body.0.is_empty();

        use yash_syntax::syntax::CaseContinuation::*;
        falling_through = match item.continuation {
            Break => break,
            FallThrough => true,
            Continue => false,
        };
    }

    if !exit_status_updated {
        env.exit_status = ExitStatus::SUCCESS;
    }
    Continue(())
}

/// Returns whether the subject matches any of the patterns.
///
/// Each pattern is expanded and matched against the subject.
/// Returns the error if any expansion fails.
async fn matches<S: Runtime + 'static>(
    env: &mut Env<S>,
    subject: &str,
    patterns: &[Word],
) -> crate::expansion::Result<bool> {
    for pattern in patterns {
        let mut pattern = expand_word_attr(env, pattern).await?.0.chars;

        // Unquoted backslashes should act as quoting, as required by POSIX XCU 2.13.1
        apply_escapes(&mut pattern);

        let Ok(pattern) = Pattern::parse_with_config(to_pattern_chars(&pattern), config()) else {
            // Treat the broken pattern as a valid pattern that does not match anything
            continue;
        };

        if pattern.is_match(subject) {
            return Ok(true);
        }
    }

    Ok(false)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tests::echo_builtin;
    use crate::tests::return_builtin;
    use futures_util::FutureExt;
    use std::cell::RefCell;
    use std::ops::ControlFlow::Break;
    use std::rc::Rc;
    use yash_env::VirtualSystem;
    use yash_env::option::Option::ErrExit;
    use yash_env::option::State::On;
    use yash_env::semantics::Divert;
    use yash_env::system::r#virtual::SystemState;
    use yash_env::test_helper::assert_stderr;
    use yash_env::test_helper::assert_stdout;
    use yash_env::test_helper::in_virtual_system;
    use yash_env::variable::Scope;
    use yash_syntax::syntax::CompoundCommand;

    fn fixture() -> (Env<VirtualSystem>, Rc<RefCell<SystemState>>) {
        let system = VirtualSystem::new();
        let state = Rc::clone(&system.state);
        let mut env = Env::with_system(system);
        env.builtins.insert("echo", echo_builtin());
        env.builtins.insert("return", return_builtin());
        (env, state)
    }

    #[test]
    fn no_items() {
        let mut env = Env::new_virtual();
        env.exit_status = ExitStatus(57);
        let command: CompoundCommand = "case foo in esac".parse().unwrap();

        let result = command.execute(&mut env).now_or_never().unwrap();
        assert_eq!(result, Continue(()));
        assert_eq!(env.exit_status, ExitStatus::SUCCESS);
    }

    #[test]
    fn one_unmatched_item() {
        let (mut env, state) = fixture();
        env.exit_status = ExitStatus(17);
        let command: CompoundCommand = "case foo in (bar) echo X;; esac".parse().unwrap();

        let result = command.execute(&mut env).now_or_never().unwrap();
        assert_eq!(result, Continue(()));
        assert_eq!(env.exit_status, ExitStatus::SUCCESS);
        assert_stdout(&state, |stdout| assert_eq!(stdout, ""));
    }

    #[test]
    fn many_unmatched_items() {
        let (mut env, state) = fixture();
        env.exit_status = ExitStatus::FAILURE;
        let command: CompoundCommand = "case word in
        (foo) echo foo;;
        (bar|baz) echo bar baz;;
        (1|2|3) echo 1 2 3;;
        esac"
            .parse()
            .unwrap();

        let result = command.execute(&mut env).now_or_never().unwrap();
        assert_eq!(result, Continue(()));
        assert_eq!(env.exit_status, ExitStatus::SUCCESS);
        assert_stdout(&state, |stdout| assert_eq!(stdout, ""));
    }

    #[test]
    fn first_item_matched() {
        in_virtual_system(|mut env, state| async move {
            env.builtins.insert("echo", echo_builtin());
            env.builtins.insert("return", return_builtin());
            env.exit_status = ExitStatus(100);
            let command: CompoundCommand = "case foo in
            ($(echo foo)) echo A; return -n 42;;
            ($(echo 1 >&2)|$(echo 2 >&2)|$(echo 3 >&2)) echo B;;
            ($(echo 4 >&2)|$(echo 5 >&2)) echo C;;
            esac"
                .parse()
                .unwrap();

            let result = command.execute(&mut env).await;
            assert_eq!(result, Continue(()));
            assert_eq!(env.exit_status, ExitStatus(42));
            assert_stdout(&state, |stdout| assert_eq!(stdout, "A\n"));
            assert_stderr(&state, |stderr| assert_eq!(stderr, ""));
        })
    }

    #[test]
    fn first_pattern_of_second_item_matched() {
        in_virtual_system(|mut env, state| async move {
            env.builtins.insert("echo", echo_builtin());
            env.exit_status = ExitStatus(100);
            let command: CompoundCommand = "case 1 in
            ($(echo foo)) echo A;;
            ($(echo 1)|$(echo 2)|$(echo 3 >&2)) echo B;;
            ($(echo 4 >&2)|$(echo 5 >&2)) echo C;;
            esac"
                .parse()
                .unwrap();

            let result = command.execute(&mut env).await;
            assert_eq!(result, Continue(()));
            assert_eq!(env.exit_status, ExitStatus::SUCCESS);
            assert_stdout(&state, |stdout| assert_eq!(stdout, "B\n"));
            assert_stderr(&state, |stderr| assert_eq!(stderr, ""));
        })
    }

    #[test]
    fn second_pattern_of_second_item_matched() {
        in_virtual_system(|mut env, state| async move {
            env.builtins.insert("echo", echo_builtin());
            env.exit_status = ExitStatus(100);
            let command: CompoundCommand = "case 2 in
            ($(echo foo)) echo A;;
            ($(echo 1)|$(echo 2)|$(echo 3 >&2)) echo B;;
            ($(echo 4 >&2)|$(echo 5 >&2)) echo C;;
            esac"
                .parse()
                .unwrap();

            let result = command.execute(&mut env).await;
            assert_eq!(result, Continue(()));
            assert_eq!(env.exit_status, ExitStatus::SUCCESS);
            assert_stdout(&state, |stdout| assert_eq!(stdout, "B\n"));
            assert_stderr(&state, |stderr| assert_eq!(stderr, ""));
        })
    }

    #[test]
    fn third_item_matched() {
        in_virtual_system(|mut env, state| async move {
            env.builtins.insert("echo", echo_builtin());
            env.exit_status = ExitStatus(100);
            let command: CompoundCommand = "case 4 in
            ($(echo foo)) echo A; return -n 42;;
            ($(echo 1)|$(echo 2)|$(echo 3)) echo B;;
            ($(echo 4)|$(echo 5 >&2)) echo C;;
            esac"
                .parse()
                .unwrap();

            let result = command.execute(&mut env).await;
            assert_eq!(result, Continue(()));
            assert_eq!(env.exit_status, ExitStatus::SUCCESS);
            assert_stdout(&state, |stdout| assert_eq!(stdout, "C\n"));
            assert_stderr(&state, |stderr| assert_eq!(stderr, ""));
        })
    }

    #[test]
    fn pattern_must_match_whole_word() {
        let (mut env, state) = fixture();
        let command: CompoundCommand = "case 123 in
        (2) echo 2;;
        (2*) echo '2*';;
        (*2) echo '*2';;
        (1*3) echo '1*3';;
        esac"
            .parse()
            .unwrap();

        let result = command.execute(&mut env).now_or_never().unwrap();
        assert_eq!(result, Continue(()));
        assert_eq!(env.exit_status, ExitStatus::SUCCESS);
        assert_stdout(&state, |stdout| assert_eq!(stdout, "1*3\n"));
    }

    #[test]
    fn quoted_pattern() {
        let (mut env, state) = fixture();
        let command: CompoundCommand = "case X in
        ('*') echo quoted;;
        (*) echo literal;;
        esac"
            .parse()
            .unwrap();

        let _ = command.execute(&mut env).now_or_never().unwrap();
        assert_stdout(&state, |stdout| assert_eq!(stdout, "literal\n"));
        assert_stderr(&state, |stderr| assert_eq!(stderr, ""));
    }

    #[test]
    fn unquoted_backslash_escapes_next_char_in_pattern() {
        let (mut env, state) = fixture();
        let var = &mut env.variables.get_or_new("empty", Scope::Global);
        var.assign("", None).unwrap();
        let var = &mut env.variables.get_or_new("one", Scope::Global);
        var.assign(r"\", None).unwrap();
        let var = &mut env.variables.get_or_new("v", Scope::Global);
        var.assign(r"\\\a", None).unwrap();
        let command: CompoundCommand = r#"case '\a' in
        ($empty) echo unquoted empty;;
        ("$empty") echo quoted empty;;
        ($one) echo unquoted one;;
        ("$one") echo quoted one;;
        ("$v") echo wrong quote;;
        ($v) echo ok;;
        esac"#
            .parse()
            .unwrap();

        let _ = command.execute(&mut env).now_or_never().unwrap();
        assert_stdout(&state, |stdout| assert_eq!(stdout, "ok\n"));
        assert_stderr(&state, |stderr| assert_eq!(stderr, ""));
    }

    #[test]
    fn broken_pattern_is_ignored() {
        let (mut env, state) = fixture();
        let command: CompoundCommand = "case [[..]] in ([[..]]) echo X; esac".parse().unwrap();

        let result = command.execute(&mut env).now_or_never().unwrap();
        assert_eq!(result, Continue(()));
        assert_eq!(env.exit_status, ExitStatus::SUCCESS);
        assert_stdout(&state, |stdout| assert_eq!(stdout, ""));
        assert_stderr(&state, |stderr| assert_eq!(stderr, ""));
    }

    #[test]
    fn item_with_empty_body() {
        let (mut env, state) = fixture();
        env.exit_status = ExitStatus::ERROR;
        let command: CompoundCommand = "case success in
        (success) ;;
        (success) echo X;;
        esac"
            .parse()
            .unwrap();

        let result = command.execute(&mut env).now_or_never().unwrap();
        assert_eq!(result, Continue(()));
        assert_eq!(env.exit_status, ExitStatus::SUCCESS);
        assert_stdout(&state, |stdout| assert_eq!(stdout, ""));
    }

    #[test]
    fn breaking_terminator() {
        let (mut env, state) = fixture();
        let command: CompoundCommand = "case 1 in
        (1) echo 1;;
        (1) echo 2;;
        (1) echo 3;;
        esac"
            .parse()
            .unwrap();

        let result = command.execute(&mut env).now_or_never().unwrap();
        assert_eq!(result, Continue(()));
        assert_stdout(&state, |stdout| assert_eq!(stdout, "1\n"));
    }

    #[test]
    fn falling_through_terminator() {
        let (mut env, state) = fixture();
        let command: CompoundCommand = "case foo in
        (x)   echo x;&
        (foo) echo 1;&
        (bar) echo 2; return -n 1;&
        (y)   ;;
        (foo) echo not reached;;
        esac"
            .parse()
            .unwrap();

        let result = command.execute(&mut env).now_or_never().unwrap();
        assert_eq!(result, Continue(()));
        assert_eq!(env.exit_status, ExitStatus::SUCCESS);
        assert_stdout(&state, |stdout| assert_eq!(stdout, "1\n2\n"));
    }

    #[test]
    fn continuing_terminator() {
        let (mut env, state) = fixture();
        let command: CompoundCommand = "case foo in
        (x)   echo x;|
        (foo) echo 1;|
        (boo) echo not reached 1;|
        (foo) ;|
        (foo) echo 2; return -n 42;|
        (boo) echo not reached 2;|
        esac"
            .parse()
            .unwrap();

        let result = command.execute(&mut env).now_or_never().unwrap();
        assert_eq!(result, Continue(()));
        assert_eq!(env.exit_status, ExitStatus(42));
        assert_stdout(&state, |stdout| assert_eq!(stdout, "1\n2\n"));
    }

    #[test]
    fn return_from_body() {
        let (mut env, state) = fixture();
        env.exit_status = ExitStatus::ERROR;
        let command: CompoundCommand = "case success in
        (success) return 73;;
        (success) echo X;;
        esac"
            .parse()
            .unwrap();

        let result = command.execute(&mut env).now_or_never().unwrap();
        assert_eq!(result, Break(Divert::Return(Some(ExitStatus(73)))));
        assert_eq!(env.exit_status, ExitStatus::ERROR);
        assert_stdout(&state, |stdout| assert_eq!(stdout, ""));
    }

    #[test]
    fn xtrace_of_case() {
        let (mut env, state) = fixture();
        env.options.set(yash_env::option::Option::XTrace, On);
        let command: CompoundCommand =
            "case ${unset-X} in (foo);; (bar | ${unset-X} | not_reached) esac"
                .parse()
                .unwrap();
        _ = command.execute(&mut env).now_or_never().unwrap();
        assert_stderr(&state, |stderr| assert_eq!(stderr, "case X in\n"));
    }

    #[test]
    fn error_expanding_subject() {
        let (mut env, state) = fixture();
        let command: CompoundCommand = "case $(echo X) in (X) echo X; esac".parse().unwrap();

        let result = command.execute(&mut env).now_or_never().unwrap();
        assert_eq!(result, Break(Divert::Interrupt(Some(ExitStatus::ERROR))));
        assert_stdout(&state, |stdout| assert_eq!(stdout, ""));
        assert_stderr(&state, |stderr| assert_ne!(stderr, ""));
    }

    #[test]
    fn errexit_with_error_expanding_subject() {
        let (mut env, state) = fixture();
        env.options.set(ErrExit, On);
        let command: CompoundCommand = "case $(echo X) in (X) echo X; esac".parse().unwrap();

        let result = command.execute(&mut env).now_or_never().unwrap();
        assert_eq!(result, Break(Divert::Exit(Some(ExitStatus::ERROR))));
        assert_stdout(&state, |stdout| assert_eq!(stdout, ""));
        assert_stderr(&state, |stderr| assert_ne!(stderr, ""));
    }

    #[test]
    fn error_expanding_pattern() {
        let (mut env, state) = fixture();
        let command: CompoundCommand = "case X in ($(echo X)) echo X; esac".parse().unwrap();

        let result = command.execute(&mut env).now_or_never().unwrap();
        assert_eq!(result, Break(Divert::Interrupt(Some(ExitStatus::ERROR))));
        assert_stdout(&state, |stdout| assert_eq!(stdout, ""));
        assert_stderr(&state, |stderr| assert_ne!(stderr, ""));
    }

    #[test]
    fn errexit_with_error_expanding_pattern() {
        let (mut env, state) = fixture();
        env.options.set(ErrExit, On);
        let command: CompoundCommand = "case X in ($(echo X)) echo X; esac".parse().unwrap();

        let result = command.execute(&mut env).now_or_never().unwrap();
        assert_eq!(result, Break(Divert::Exit(Some(ExitStatus::ERROR))));
        assert_stdout(&state, |stdout| assert_eq!(stdout, ""));
        assert_stderr(&state, |stderr| assert_ne!(stderr, ""));
    }
}