vce-shell 0.1.1

VCE Shell layer: command language, builtins, execution coordination
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
//! Word expansion in the session.
//!
//! Expansion runs inside [`crate::core::ShellCore`], because parameter operators and
//! command substitution need the session: `$(...)` and backticks execute
//! the inner command through this shell and capture its output, and
//! `${VAR:=word}` mutates the session environment. Quoting semantics
//! (`'...'`, `"..."`, backslash, tilde) match the sh family.
//!
//! Arithmetic (`$(( ))`, and `(( ))` commands) shares this machinery: the
//! expression text may contain parameter and command substitutions, which
//! expand first; the surviving identifiers are then evaluated as references
//! into the session environment by one evaluator shared with `case`-free
//! compound commands.

use brush_parser::ast::{self};

use crate::core::ShellCore;

impl<'os> ShellCore<'os> {
    /// Expands a word with quoting semantics, discarding the glob marker.
    pub fn expand_word(&mut self, raw: &str) -> String {
        self.expand_word_with_glob(raw).0
    }

    /// Expands a word and splits it into fields on the default IFS
    /// characters (space, tab, newline), as unquoted expansions are in
    /// real shells: `v="a b"; ls $v` passes two arguments. Characters
    /// from quoted sections never split.
    ///
    /// An empty expansion yields no fields; the caller decides whether an
    /// empty argument is meaningful.
    pub fn expand_word_fields(&mut self, raw: &str) -> Vec<String> {
        let (text, splittable, _glob) = self.expand_word_masked(raw);
        split_fields(&text, &splittable)
    }

    /// Expands a word with quoting semantics, reporting whether it contains
    /// unquoted glob characters.
    pub fn expand_word_with_glob(&mut self, raw: &str) -> (String, bool) {
        let mut result = String::new();
        let mut glob = false;
        let mut index = 0;
        let mut at_start = true;
        let chars: Vec<char> = raw.chars().collect();
        while index < chars.len() {
            match chars[index] {
                '\'' => {
                    index += 1;
                    while index < chars.len() && chars[index] != '\'' {
                        result.push(chars[index]);
                        index += 1;
                    }
                    index += 1;
                }
                '"' => {
                    index += 1;
                    while index < chars.len() && chars[index] != '"' {
                        if chars[index] == '\\'
                            && index + 1 < chars.len()
                            && matches!(chars[index + 1], '$' | '`' | '"' | '\\')
                        {
                            result.push(chars[index + 1]);
                            index += 2;
                        } else if chars[index] == '$' {
                            if let Some((value, consumed)) = self.expand_parameter(&chars[index..])
                            {
                                result.push_str(&value);
                                index += consumed;
                            } else {
                                result.push(chars[index]);
                                index += 1;
                            }
                        } else if chars[index] == '`'
                            && let Some((value, consumed)) =
                                self.backtick_substitution(&chars, index)
                        {
                            result.push_str(&value);
                            index += consumed;
                        } else {
                            result.push(chars[index]);
                            index += 1;
                        }
                    }
                    index += 1;
                }
                '\\' if index + 1 < chars.len() => {
                    result.push(chars[index + 1]);
                    index += 2;
                }
                '~' if at_start && (index + 1 == chars.len() || chars[index + 1] == '/') => {
                    result.push_str(self.environment().get("HOME").unwrap_or("/"));
                    index += 1;
                }
                '$' => {
                    if let Some((value, consumed)) = self.expand_parameter(&chars[index..]) {
                        result.push_str(&value);
                        index += consumed;
                    } else {
                        result.push(chars[index]);
                        index += 1;
                    }
                }
                '`' => {
                    if let Some((value, consumed)) = self.backtick_substitution(&chars, index) {
                        result.push_str(&value);
                        index += consumed;
                    } else {
                        result.push(chars[index]);
                        index += 1;
                    }
                }
                '*' | '?' | '[' | ']' => {
                    glob = true;
                    result.push(chars[index]);
                    index += 1;
                }
                ch => {
                    result.push(ch);
                    index += 1;
                }
            }
            at_start = false;
        }
        (result, glob)
    }

    /// The masked expansion behind field splitting: returns the expanded
    /// text, a per-character flag marking which characters came from
    /// *unquoted* parameter or command substitutions (the only positions
    /// where IFS field splitting may occur), and whether the word carries
    /// unquoted glob characters.
    #[allow(clippy::same_item_push)]
    fn expand_word_masked(&mut self, raw: &str) -> (String, Vec<bool>, bool) {
        let mut result = String::new();
        let mut mask: Vec<bool> = Vec::new();
        let mut glob = false;
        let mut index = 0;
        let mut at_start = true;
        let chars: Vec<char> = raw.chars().collect();
        while index < chars.len() {
            match chars[index] {
                '\'' => {
                    index += 1;
                    while index < chars.len() && chars[index] != '\'' {
                        result.push(chars[index]);
                        mask.push(false);
                        index += 1;
                    }
                    index += 1;
                }
                '"' => {
                    index += 1;
                    while index < chars.len() && chars[index] != '"' {
                        if chars[index] == '\\'
                            && index + 1 < chars.len()
                            && matches!(chars[index + 1], '$' | '`' | '"' | '\\')
                        {
                            result.push(chars[index + 1]);
                            mask.push(false);
                            index += 2;
                        } else if chars[index] == '$'
                            && let Some((value, consumed)) = self.expand_parameter(&chars[index..])
                        {
                            result.push_str(&value);
                            for _ in value.chars() {
                                mask.push(false);
                            }
                            index += consumed;
                        } else if chars[index] == '`'
                            && let Some((value, consumed)) =
                                self.backtick_substitution(&chars, index)
                        {
                            result.push_str(&value);
                            for _ in value.chars() {
                                mask.push(false);
                            }
                            index += consumed;
                        } else {
                            result.push(chars[index]);
                            mask.push(false);
                            index += 1;
                        }
                    }
                    index += 1;
                }
                '\\' if index + 1 < chars.len() => {
                    result.push(chars[index + 1]);
                    mask.push(false);
                    index += 2;
                }
                '~' if at_start && (index + 1 == chars.len() || chars[index + 1] == '/') => {
                    let home = self.environment().get("HOME").unwrap_or("/").to_owned();
                    result.push_str(&home);
                    for _ in home.chars() {
                        mask.push(false);
                    }
                    index += 1;
                }
                '$' => {
                    let mut value_text = String::new();
                    if let Some((value, consumed)) = self.expand_parameter(&chars[index..]) {
                        for ch in value.chars() {
                            value_text.push(ch);
                            mask.push(true);
                        }
                        index += consumed;
                    } else {
                        value_text.push(chars[index]);
                        mask.push(false);
                        index += 1;
                    }
                    result.push_str(&value_text);
                }
                '`' => {
                    if let Some((value, consumed)) = self.backtick_substitution(&chars, index) {
                        for ch in value.chars() {
                            result.push(ch);
                            mask.push(true);
                        }
                        index += consumed;
                    } else {
                        result.push(chars[index]);
                        mask.push(false);
                        index += 1;
                    }
                }
                '*' | '?' | '[' | ']' => {
                    glob = true;
                    result.push(chars[index]);
                    index += 1;
                }
                ch => {
                    result.push(ch);
                    mask.push(false);
                    index += 1;
                }
            }
            at_start = false;
        }
        (result, mask, glob)
    }

    /// `$((...))` arithmetic expansion: finds the balanced closing `))`,
    /// expands any parameter/command substitutions inside the expression,
    /// and evaluates it. Returns `None` when the text does not close as
    /// arithmetic or does not parse as an expression, letting the caller
    /// fall back to command substitution (the POSIX ambiguity between
    /// `$((expr))` and `$( (cmd) )`).
    fn arithmetic_expansion(&mut self, chars: &[char]) -> Option<(String, usize)> {
        let mut depth = 0i32;
        let mut end = 2;
        while end < chars.len() {
            match chars[end] {
                '(' => depth += 1,
                ')' => {
                    depth -= 1;
                    if depth == 0 {
                        break;
                    }
                }
                _ => {}
            }
            end += 1;
        }
        if depth != 0 || chars.get(end + 1) != Some(&')') || end < 4 {
            return None;
        }
        let inner: String = chars[3..end].iter().collect();
        // Parameter and command substitutions happen before arithmetic
        // evaluation; bare identifiers survive expansion as references.
        let prepared = if inner.contains('$') || inner.contains('`') {
            self.expand_word(&inner)
        } else {
            inner
        };
        let value = self.evaluate_arithmetic(&prepared)?;
        Some((value.to_string(), end + 2))
    }

    /// Evaluates an arithmetic expression (`$(( ))` expansions and `(( ))`
    /// commands share this one evaluator).
    ///
    /// Identifiers are references into the session environment (unset or
    /// empty evaluates to 0); the assignment operators mutate it. Overflow,
    /// division by zero, and array elements fail the evaluation with `None`
    /// rather than inventing a number.
    pub(crate) fn evaluate_arithmetic(&mut self, raw: &str) -> Option<i64> {
        let expr = brush_parser::arithmetic::parse(raw).ok()?;
        self.arithmetic_value(&expr)
    }

    /// The value of a variable in arithmetic context.
    fn arithmetic_variable(&self, name: &str) -> i64 {
        self.environment()
            .get(name)
            .and_then(|value| value.trim().parse::<i64>().ok())
            .unwrap_or(0)
    }

    /// Reads an assignment target's current value (`None` for array
    /// elements).
    fn arithmetic_target_value(&mut self, target: &ast::ArithmeticTarget) -> Option<i64> {
        match target {
            ast::ArithmeticTarget::Variable(name) => Some(self.arithmetic_variable(name)),
            ast::ArithmeticTarget::ArrayElement(..) => None,
        }
    }

    /// Stores an assignment target's value (`None` for array elements).
    fn arithmetic_assign(&mut self, target: &ast::ArithmeticTarget, value: i64) -> Option<()> {
        match target {
            ast::ArithmeticTarget::Variable(name) => {
                self.environment_mut().set(name, value.to_string());
                Some(())
            }
            ast::ArithmeticTarget::ArrayElement(..) => None,
        }
    }

    /// Applies one binary operator to two evaluated sides.
    fn arithmetic_binary(
        &self,
        operator: ast::BinaryOperator,
        left: i64,
        right: i64,
    ) -> Option<i64> {
        use ast::BinaryOperator as Op;
        match operator {
            Op::Add => left.checked_add(right),
            Op::Subtract => left.checked_sub(right),
            Op::Multiply => left.checked_mul(right),
            Op::Divide if right != 0 => left.checked_div(right),
            Op::Modulo if right != 0 => left.checked_rem(right),
            // Division and remainder by zero fail the evaluation.
            Op::Divide | Op::Modulo => None,
            Op::Power => u32::try_from(right)
                .ok()
                .and_then(|exponent| pow(left, exponent)),
            Op::ShiftLeft => u32::try_from(right)
                .ok()
                .and_then(|shift| left.checked_shl(shift)),
            Op::ShiftRight => u32::try_from(right)
                .ok()
                .and_then(|shift| left.checked_shr(shift)),
            Op::BitwiseAnd => Some(left & right),
            Op::BitwiseOr => Some(left | right),
            Op::BitwiseXor => Some(left ^ right),
            Op::LessThan => Some(i64::from(left < right)),
            Op::LessThanOrEqualTo => Some(i64::from(left <= right)),
            Op::GreaterThan => Some(i64::from(left > right)),
            Op::GreaterThanOrEqualTo => Some(i64::from(left >= right)),
            Op::Equals => Some(i64::from(left == right)),
            Op::NotEquals => Some(i64::from(left != right)),
            // Logical operators short-circuit at their call site; the comma
            // operator's left side is evaluated there too.
            Op::LogicalAnd | Op::LogicalOr | Op::Comma => None,
        }
    }

    /// Recursively evaluates one arithmetic expression node.
    fn arithmetic_value(&mut self, expr: &ast::ArithmeticExpr) -> Option<i64> {
        match expr {
            ast::ArithmeticExpr::Literal(value) => Some(*value),
            ast::ArithmeticExpr::Reference(target) => self.arithmetic_target_value(target),
            ast::ArithmeticExpr::Conditional(condition, then, otherwise) => {
                let choice = self.arithmetic_value(condition)?;
                if choice == 0 {
                    self.arithmetic_value(otherwise)
                } else {
                    self.arithmetic_value(then)
                }
            }
            ast::ArithmeticExpr::UnaryOp(operator, operand) => {
                let value = self.arithmetic_value(operand)?;
                match operator {
                    ast::UnaryOperator::UnaryPlus => Some(value),
                    ast::UnaryOperator::UnaryMinus => value.checked_neg(),
                    ast::UnaryOperator::BitwiseNot => Some(!value),
                    ast::UnaryOperator::LogicalNot => Some(i64::from(value == 0)),
                }
            }
            ast::ArithmeticExpr::BinaryOp(operator, left, right) => {
                use ast::BinaryOperator as Op;
                match operator {
                    // Short-circuit forms must not always evaluate both sides.
                    Op::LogicalAnd => {
                        if self.arithmetic_value(left)? == 0 {
                            return Some(0);
                        }
                        Some(i64::from(self.arithmetic_value(right)? != 0))
                    }
                    Op::LogicalOr => {
                        if self.arithmetic_value(left)? != 0 {
                            return Some(1);
                        }
                        Some(i64::from(self.arithmetic_value(right)? != 0))
                    }
                    Op::Comma => {
                        self.arithmetic_value(left)?;
                        self.arithmetic_value(right)
                    }
                    _ => {
                        let left = self.arithmetic_value(left)?;
                        let right = self.arithmetic_value(right)?;
                        self.arithmetic_binary(*operator, left, right)
                    }
                }
            }
            ast::ArithmeticExpr::Assignment(target, value) => {
                let value = self.arithmetic_value(value)?;
                self.arithmetic_assign(target, value)?;
                Some(value)
            }
            ast::ArithmeticExpr::BinaryAssignment(operator, target, value) => {
                let current = self.arithmetic_target_value(target)?;
                let value = self.arithmetic_value(value)?;
                let updated = self.arithmetic_binary(*operator, current, value)?;
                self.arithmetic_assign(target, updated)?;
                Some(updated)
            }
            ast::ArithmeticExpr::UnaryAssignment(operator, target) => {
                let current = self.arithmetic_target_value(target)?;
                let updated = match operator {
                    ast::UnaryAssignmentOperator::PrefixIncrement
                    | ast::UnaryAssignmentOperator::PostfixIncrement => current.checked_add(1)?,
                    ast::UnaryAssignmentOperator::PrefixDecrement
                    | ast::UnaryAssignmentOperator::PostfixDecrement => current.checked_sub(1)?,
                };
                self.arithmetic_assign(target, updated)?;
                match operator {
                    ast::UnaryAssignmentOperator::PrefixIncrement
                    | ast::UnaryAssignmentOperator::PrefixDecrement => Some(updated),
                    ast::UnaryAssignmentOperator::PostfixIncrement
                    | ast::UnaryAssignmentOperator::PostfixDecrement => Some(current),
                }
            }
        }
    }

    /// Expands `$VAR`, `${VAR}`, the parameter operators (`${VAR:-x}`,
    /// `:=`, `:?`, `:+`, `#`, `##`, `%`, `%%`, `${#VAR}`), and `$(...)`
    /// command substitution at the start of `chars`.
    ///
    /// Returns the value and the number of characters consumed, or `None`
    /// when `chars` does not start with a parameter reference.
    fn expand_parameter(&mut self, chars: &[char]) -> Option<(String, usize)> {
        if chars.first() != Some(&'$') {
            return None;
        }
        // `$(...)` command substitution — unless it is arithmetic:
        // `$((...))` is an arithmetic expansion, recognized by
        // the doubled parenthesis.
        if chars.get(1) == Some(&'(') {
            if chars.get(2) == Some(&'(')
                && let Some(expansion) = self.arithmetic_expansion(chars)
            {
                return Some(expansion);
            }
            return self.command_substitution(chars, 0);
        }
        if chars.get(1) == Some(&'{') {
            let close = chars.iter().position(|ch| *ch == '}')?;
            if close <= 2 {
                return None;
            }
            let body: String = chars[2..close].iter().collect();
            let consumed = close + 1;

            // `${#VAR}`: the length of the value.
            if let Some(name) = body.strip_prefix('#') {
                let length = self.environment().get(name).unwrap_or("").chars().count();
                return Some((length.to_string(), consumed));
            }

            // `${VAR:op word}` with `:-`, `:=`, `:?`, `:+`.
            {
                for operator in [":-", ":=", ":?", ":+"] {
                    if let Some((name, word)) = body.split_once(operator) {
                        let value = self.environment().get(name).unwrap_or("").to_owned();
                        let empty = value.is_empty();
                        let word = word.to_owned();
                        let result = match operator {
                            ":-" => {
                                if empty {
                                    word
                                } else {
                                    value
                                }
                            }
                            ":=" => {
                                if empty {
                                    self.environment_mut().set(name, word.clone());
                                    word
                                } else {
                                    value
                                }
                            }
                            ":?" => {
                                // Real shells print the message and abort;
                                // here the message substitutes into the
                                // word, keeping the failure visible.
                                if empty {
                                    format!("{name}: {word}")
                                } else {
                                    value
                                }
                            }
                            ":+" => {
                                if empty {
                                    String::new()
                                } else {
                                    word
                                }
                            }
                            _ => unreachable!(),
                        };
                        return Some((result, consumed));
                    }
                }
            }

            // `${VAR#pat}`, `${VAR##pat}`, `${VAR%pat}`, `${VAR%%pat}`.
            for operator in ["##", "#", "%%", "%"] {
                if let Some((name, pattern)) = body.split_once(operator) {
                    let value = self.environment().get(name).unwrap_or("").to_owned();
                    let stripped = strip_pattern(
                        &value,
                        pattern,
                        operator == "##" || operator == "%%",
                        operator == "%" || operator == "%%",
                    );
                    return Some((stripped, consumed));
                }
            }
            // `${1}`, `${10}`, … consult the positional frame first.
            let value = self
                .positional_value(&body)
                .unwrap_or_else(|| self.environment().get(&body).unwrap_or("").to_owned());
            return Some((value, consumed));
        }
        // Single-character special parameters like `$?` and `$$`; digits,
        // `0`, `#`, `@`, and `*` consult the positional frame first.
        if let Some(second) = chars.get(1)
            && matches!(second, '?' | '$' | '!' | '#' | '*' | '@' | '-' | '0'..='9')
        {
            if let Some(value) = self.positional_value(&second.to_string()) {
                return Some((value, 2));
            }
            let name = second.to_string();
            let value = self.environment().get(&name).unwrap_or("").to_owned();
            return Some((value, 2));
        }
        let start = 1;
        let mut end = start;
        while end < chars.len() && (chars[end].is_alphanumeric() || chars[end] == '_') {
            end += 1;
        }
        if end == start {
            return None;
        }
        let name: String = chars[start..end].iter().collect();
        let value = self.environment().get(&name).unwrap_or("").to_owned();
        Some((value, end))
    }

    /// `$(...)` command substitution: executes the inner command through
    /// this shell and returns its captured stdout.
    fn command_substitution(&mut self, chars: &[char], start: usize) -> Option<(String, usize)> {
        if chars.get(start) != Some(&'$') || chars.get(start + 1) != Some(&'(') {
            return None;
        }
        let mut depth = 0usize;
        let mut end = start + 2;
        while end < chars.len() {
            match chars[end] {
                '(' => depth += 1,
                ')' if depth == 0 => break,
                ')' => depth -= 1,
                _ => {}
            }
            end += 1;
        }
        if end >= chars.len() {
            return None;
        }
        let inner: String = chars[start + 2..end].iter().collect();
        let output = self.execute_captured(&inner);
        Some((output, end - start + 1))
    }

    /// Backtick command substitution: `` `command` ``.
    fn backtick_substitution(&mut self, chars: &[char], start: usize) -> Option<(String, usize)> {
        let mut end = start + 1;
        while end < chars.len() && chars[end] != '`' {
            end += 1;
        }
        if end >= chars.len() {
            return None;
        }
        let inner: String = chars[start + 1..end].iter().collect();
        let output = self.execute_captured(&inner);
        Some((output, end - start + 1))
    }

    /// Executes a command substitution and captures its stdout, with
    /// trailing newlines stripped like the real shells.
    fn execute_captured(&mut self, source: &str) -> String {
        let mut stdin = engine::BytesInput::new(Vec::new());
        let mut stdout = engine::BytesOutput::new();
        let mut stderr = engine::BytesOutput::new();
        let _ = self.execute(source, &mut stdin, &mut stdout, &mut stderr);
        let text = String::from_utf8_lossy(&stdout.into_bytes()).into_owned();
        text.trim_end_matches('\n').to_owned()
    }
}

/// Raises `base` to a non-negative `exponent`.
///
/// `checked_pow` iterates the exponent — a few billion multiplications for
/// `1 ** 4294967295`, which never overflows and would hang the session.
/// Bases whose powers are closed-form (`-1`, `0`, `1`) resolve
/// immediately; everything else falls back to the checked iteration,
/// which overflows within a handful of multiplications.
fn pow(base: i64, exponent: u32) -> Option<i64> {
    match base {
        0 => Some(if exponent == 0 { 1 } else { 0 }),
        1 => Some(1),
        -1 => Some(if exponent.is_multiple_of(2) { 1 } else { -1 }),
        base => base.checked_pow(exponent),
    }
}

/// Strips the shortest or longest prefix/suffix of `value` that matches a
/// glob pattern (`${VAR#pat}`, `${VAR##pat}`, `${VAR%pat}`, `${VAR%%pat}`).
fn strip_pattern(value: &str, pattern: &str, longest: bool, suffix: bool) -> String {
    let mut matches: Vec<usize> = Vec::new();
    let count = value.chars().count();
    for length in 0..=count {
        // The part being stripped: the prefix (first `length` chars) or
        // the suffix (last `length` chars) must match the pattern.
        let candidate: String = if suffix {
            value.chars().skip(count - length).collect()
        } else {
            value.chars().take(length).collect()
        };
        if glob_match(&candidate, pattern) {
            matches.push(length);
        }
    }
    let chosen = if longest {
        matches.last().copied().unwrap_or(0)
    } else {
        matches.first().copied().unwrap_or(0)
    };
    if suffix {
        value.chars().take(count - chosen).collect()
    } else {
        value.chars().skip(chosen).collect()
    }
}

/// Simple glob matching for `*`, `?`, and `[...]` character classes
/// (shared with the core's filesystem globbing).
///
/// Classes support single characters, inclusive ranges (`a-z`), and
/// negation with a leading `!` or `^` (`[!a-z]`). A `]` directly after the
/// opening `[` (or after the negation mark) is a literal member; an
/// unterminated `[` matches a literal `[`.
pub(crate) fn glob_match(text: &str, pattern: &str) -> bool {
    let text: Vec<char> = text.chars().collect();
    let pattern: Vec<char> = pattern.chars().collect();
    // Classic wildcard DP: `dp[i][j]` is whether `text[..i]` matches
    // `pattern[..j]`. A star is either empty (dp[i][j-1]) or eats one more
    // character (dp[i-1][j]), so every state resolves in constant time:
    // O(text.len() * pattern.len()) total, with no backtracking tree.
    let rows = text.len() + 1;
    let cols = pattern.len() + 1;
    let mut dp = vec![false; rows * cols];
    dp[0] = true;
    // Leading stars match the empty prefix.
    for j in 1..=pattern.len() {
        if pattern[j - 1] == '*' {
            dp[j] = dp[j - 1];
        }
    }
    for i in 1..=text.len() {
        // A character class consumes one text character but several
        // pattern positions; those jumps land at `class.end` and must not
        // be clobbered by the ascending `j` pass, so they are applied
        // after the row is computed.
        let mut jumps: Vec<(usize, bool)> = Vec::new();
        for j in 1..=pattern.len() {
            let at = i * cols + j;
            let ch = pattern[j - 1];
            match ch {
                '*' => dp[at] = dp[at - cols] || dp[at - 1],
                '?' => dp[at] = dp[at - cols - 1],
                '[' => match parse_class(&pattern, j - 1) {
                    Some(class) => {
                        dp[at] = false;
                        let reached = dp[at - cols - 1] && class.matches(text[i - 1]);
                        jumps.push((class.end, reached));
                    }
                    // Unterminated `[`: a literal bracket.
                    None => dp[at] = dp[at - cols - 1] && text[i - 1] == '[',
                },
                c => dp[at] = dp[at - cols - 1] && text[i - 1] == c,
            }
        }
        for (end, reached) in jumps {
            if reached {
                dp[i * cols + end] = true;
            }
        }
    }
    dp[rows * cols - 1]
}

/// A parsed `[...]` character class: its member ranges, whether it negates
/// (`[!a-z]`), and the index just past the closing `]`.
struct CharacterClass {
    /// Inclusive member ranges.
    members: Vec<(char, char)>,
    /// Whether the class negates its members.
    negate: bool,
    /// The pattern index just past the closing `]`.
    end: usize,
}

/// Parses the class whose opening `[` is at `pattern[start]`.
///
/// Returns `None` when the class never closes.
fn parse_class(pattern: &[char], start: usize) -> Option<CharacterClass> {
    let mut index = start + 1;
    let negate = matches!(pattern.get(index), Some('!') | Some('^'));
    if negate {
        index += 1;
    }
    let mut members = Vec::new();
    let mut first = true;
    while index < pattern.len() {
        // A `]` in first position is a literal member.
        if pattern[index] == ']' && !first {
            return Some(CharacterClass {
                members,
                negate,
                end: index + 1,
            });
        }
        first = false;
        if index + 2 < pattern.len() && pattern[index + 1] == '-' && pattern[index + 2] != ']' {
            members.push((pattern[index], pattern[index + 2]));
            index += 3;
        } else {
            members.push((pattern[index], pattern[index]));
            index += 1;
        }
    }
    None
}

impl CharacterClass {
    /// Whether `ch` is inside (or, when negating, outside) the member
    /// ranges.
    fn matches(&self, ch: char) -> bool {
        let contained = self.members.iter().any(|(lo, hi)| ch >= *lo && ch <= *hi);
        contained != self.negate
    }
}

mod tests {
    #[allow(unused_imports)]
    use super::glob_match;

    #[test]
    fn stars_and_questions_match() {
        assert!(glob_match("hello", "h*o"));
        assert!(glob_match("hello", "h?llo"));
        assert!(!glob_match("hello", "h?lo"));
        assert!(glob_match("", "*"));
        assert!(glob_match("anything", "*"));
    }

    #[test]
    fn classes_match_members_ranges_and_negation() {
        assert!(glob_match("a", "[abc]"));
        assert!(!glob_match("d", "[abc]"));
        assert!(glob_match("m", "[a-z]"));
        assert!(glob_match("file1.txt", "file[0-9].txt"));
        assert!(!glob_match("file12.txt", "file[0-9].txt"));
        assert!(glob_match("d", "[!abc]"));
        assert!(glob_match("q", "[^abc]"));
        assert!(!glob_match("a", "[!abc]"));
    }

    #[test]
    fn class_edge_cases_follow_posix() {
        // `]` in first position is a literal member.
        assert!(glob_match("]", "[]]"));
        // `-` at either edge is a literal.
        assert!(glob_match("-", "[a-]"));
        assert!(glob_match("+", "[+-/]"));
        // An unterminated `[` matches a literal `[`.
        assert!(glob_match("[", "["));
        assert!(!glob_match("[x", "["));
        // Classes compose with stars.
        assert!(glob_match("abc", "*[bc]"));
    }
}

/// Splits expanded text into fields at IFS whitespace boundaries
/// (space, tab, newline), but only at positions the expansion marked as
/// splittable — characters from quoted sections never separate fields.
///
/// Runs of splitting whitespace collapse into one boundary, and leading
/// and trailing boundaries are dropped: `a  b` is two fields, ` a` one.
fn split_fields(text: &str, mask: &[bool]) -> Vec<String> {
    let chars: Vec<char> = text.chars().collect();
    let mut fields = Vec::new();
    let mut current = String::new();
    for (index, ch) in chars.iter().enumerate() {
        let splittable = mask.get(index).copied().unwrap_or(false);
        if splittable && matches!(ch, ' ' | '\t' | '\n') {
            if !current.is_empty() {
                fields.push(std::mem::take(&mut current));
            }
        } else {
            current.push(*ch);
        }
    }
    if !current.is_empty() {
        fields.push(current);
    }
    fields
}