nano-coder 0.7.0

A 6MB coding agent for the terminal and for agent fleets: multi-provider, ACP, resumable sessions, plans.
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
//! A small bash parser for permission checks.
//!
//! It splits a command line into simple commands (on `;`, `&`, `&&`, `||`,
//! `|`, newlines and parentheses), unquotes words, records redirections and
//! here-document bodies, and parses command substitutions (`$(...)`,
//! backticks, `<(...)`) as further commands. It does not expand anything:
//! words that contain `$...` or command substitutions are marked dynamic, and
//! unquoted glob characters are recorded.
//!
//! Anything it cannot parse (an unterminated quote, an unmatched `)`) is an
//! error, so callers can fail closed.

/// One word of a simple command, unquoted but not expanded.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Word {
    /// Literal text; expansions are kept as written (`$HOME`, `${X:?}`, `$(...)`).
    pub text: String,
    /// Contains a parameter expansion or command substitution.
    pub dynamic: bool,
    /// Contains an unquoted `*`, `?` or `[`.
    pub glob: bool,
    /// Some part of the word was quoted or escaped.
    pub quoted: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Redirect {
    pub op: String,
    pub target: Word,
}

/// A here-document body fed to a command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Heredoc {
    /// The raw body text between the operator line and the delimiter.
    pub body: String,
    /// The parent shell expands the body (so command substitutions and
    /// parameter expansions in it run) unless the delimiter was quoted
    /// (`<<'EOF'` / `<<"EOF"` / `<<\EOF`).
    pub expand: bool,
}

/// A simple command: words, redirections and here-document bodies.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Simple {
    pub words: Vec<Word>,
    pub redirects: Vec<Redirect>,
    pub heredocs: Vec<Heredoc>,
}

const MAX_DEPTH: usize = 16;

/// Parse a command line into its simple commands, including those inside
/// command substitutions.
pub fn parse(source: &str) -> Result<Vec<Simple>, String> {
    parse_nested(source, 0)
}

pub fn parse_nested(source: &str, depth: usize) -> Result<Vec<Simple>, String> {
    if depth > MAX_DEPTH {
        return Err("command nests too deeply to inspect".into());
    }
    let mut parser = Parser { chars: source.chars().collect(), pos: 0, depth, out: Vec::new(), case_depth: 0 };
    parser.script(false)?;
    Ok(parser.out)
}

struct PendingHeredoc {
    command: usize,
    delimiter: String,
    strip_tabs: bool,
    expand: bool,
}

struct Parser {
    chars: Vec<char>,
    pos: usize,
    depth: usize,
    out: Vec<Simple>,
    case_depth: usize,
}

fn is_operator(c: char) -> bool {
    matches!(c, ';' | '&' | '|' | '(' | ')' | '<' | '>' | '\n')
}

impl Parser {
    fn peek(&self) -> Option<char> {
        self.chars.get(self.pos).copied()
    }

    fn peek_at(&self, offset: usize) -> Option<char> {
        self.chars.get(self.pos + offset).copied()
    }

    /// Decode one ANSI-C (`$'...'`) backslash escape, `self.pos` positioned just
    /// past the backslash. Bash interprets these escapes, so `\x72` means `r`:
    /// leaving it as the literal text `x72` would make the guard inspect the
    /// wrong command (`bash -c $'\x72m -rf /'` would look like the harmless
    /// `x72m`, hiding the real `rm`). Decode every well-defined escape so the
    /// true bytes are inspected, and fail closed on anything unrecognized by
    /// marking the word dynamic (untrusted) instead of trusting it as a literal.
    fn ansi_c_escape(&mut self, word: &mut Word) -> Result<(), String> {
        let next = self.peek().ok_or("unterminated $'...' string")?;
        self.pos += 1;
        let push_code = |word: &mut Word, val: u32| match char::from_u32(val) {
            Some(c) => word.text.push(c),
            None => word.dynamic = true,
        };
        match next {
            'a' => word.text.push('\u{07}'),
            'b' => word.text.push('\u{08}'),
            'e' | 'E' => word.text.push('\u{1b}'),
            'f' => word.text.push('\u{0c}'),
            'n' => word.text.push('\n'),
            'r' => word.text.push('\r'),
            't' => word.text.push('\t'),
            'v' => word.text.push('\u{0b}'),
            '\\' => word.text.push('\\'),
            '\'' => word.text.push('\''),
            '"' => word.text.push('"'),
            '?' => word.text.push('?'),
            'x' => {
                // `\xHH` — one or two hex digits.
                let mut val = 0u32;
                let mut n = 0;
                while n < 2 {
                    match self.peek().and_then(|c| c.to_digit(16)) {
                        Some(d) => {
                            val = val * 16 + d;
                            self.pos += 1;
                            n += 1;
                        }
                        None => break,
                    }
                }
                if n == 0 { word.text.push('x') } else { push_code(word, val) }
            }
            '0'..='7' => {
                // `\NNN` — up to three octal digits (the first already consumed).
                let mut val = next.to_digit(8).unwrap_or(0);
                let mut n = 1;
                while n < 3 {
                    match self.peek().and_then(|c| c.to_digit(8)) {
                        Some(d) => {
                            val = val * 8 + d;
                            self.pos += 1;
                            n += 1;
                        }
                        None => break,
                    }
                }
                push_code(word, val)
            }
            'u' | 'U' => {
                // `\uHHHH` / `\UHHHHHHHH` — up to 4 / 8 hex digits.
                let width = if next == 'u' { 4 } else { 8 };
                let mut val = 0u32;
                let mut n = 0;
                while n < width {
                    match self.peek().and_then(|c| c.to_digit(16)) {
                        Some(d) => {
                            val = val * 16 + d;
                            self.pos += 1;
                            n += 1;
                        }
                        None => break,
                    }
                }
                if n == 0 { word.text.push(next) } else { push_code(word, val) }
            }
            'c' => {
                // `\cX` — control character.
                match self.peek() {
                    Some(c) => {
                        self.pos += 1;
                        word.text.push(((c.to_ascii_uppercase() as u8) ^ 0x40) as char);
                    }
                    None => word.dynamic = true,
                }
            }
            other => {
                // Unrecognized escape: distrust the token so an unmodelled
                // encoding cannot masquerade as a benign literal.
                word.text.push(other);
                word.dynamic = true;
            }
        }
        Ok(())
    }

    fn eat(&mut self, c: char) -> bool {
        if self.peek() == Some(c) {
            self.pos += 1;
            true
        } else {
            false
        }
    }

    /// Parse commands until the end of input or, when `until_paren`, the
    /// `)` that closes a command substitution.
    fn script(&mut self, until_paren: bool) -> Result<(), String> {
        let mut current = Simple::default();
        let mut parens = 0usize;
        let mut pending: Vec<PendingHeredoc> = Vec::new();
        loop {
            self.skip_blanks();
            let Some(c) = self.peek() else {
                if until_paren {
                    return Err("unterminated command substitution".into());
                }
                if parens > 0 {
                    return Err("unmatched (".into());
                }
                self.flush(&mut current, &mut pending);
                return Ok(());
            };
            match c {
                '#' => {
                    while self.peek().is_some_and(|c| c != '\n') {
                        self.pos += 1;
                    }
                }
                '\n' => {
                    self.pos += 1;
                    self.flush(&mut current, &mut pending);
                    for heredoc in pending.drain(..) {
                        let body = self.heredoc_body(&heredoc.delimiter, heredoc.strip_tabs);
                        if let Some(command) = self.out.get_mut(heredoc.command) {
                            command.heredocs.push(Heredoc { body, expand: heredoc.expand });
                        }
                    }
                }
                ';' | '&' | '|' => {
                    if c == '&' && self.peek_at(1) == Some('>') {
                        self.redirect(&mut current, &mut pending)?;
                        continue;
                    }
                    self.pos += 1;
                    // `&&`, `||`, `|&`, `;;`, `;&`, `;;&`
                    while self.peek().is_some_and(|n| matches!(n, '&' | '|' | ';')) {
                        self.pos += 1;
                    }
                    self.flush(&mut current, &mut pending);
                }
                '(' => {
                    self.pos += 1;
                    parens += 1;
                    self.flush(&mut current, &mut pending);
                }
                ')' => {
                    self.pos += 1;
                    if parens > 0 {
                        parens -= 1;
                        self.flush(&mut current, &mut pending);
                    } else if self.case_depth > 0 {
                        // A `case` pattern such as `a|b)`.
                        current = Simple::default();
                    } else if until_paren {
                        self.flush(&mut current, &mut pending);
                        if !pending.is_empty() {
                            return Err("here-document inside a command substitution".into());
                        }
                        return Ok(());
                    } else {
                        return Err("unmatched )".into());
                    }
                }
                '<' | '>' => {
                    if self.peek_at(1) == Some('(') {
                        // Process substitution <(...) / >(...).
                        self.pos += 2;
                        self.substitution()?;
                        current.words.push(Word { text: "/dev/fd/63".into(), dynamic: true, ..Default::default() });
                    } else {
                        self.redirect(&mut current, &mut pending)?;
                    }
                }
                _ => {
                    if c.is_ascii_digit() && self.is_fd_redirect() {
                        while self.peek().is_some_and(|c| c.is_ascii_digit()) {
                            self.pos += 1;
                        }
                        self.redirect(&mut current, &mut pending)?;
                        continue;
                    }
                    let word = self.word()?;
                    if current.words.is_empty() && !word.quoted {
                        match word.text.as_str() {
                            "case" => self.case_depth += 1,
                            "esac" => self.case_depth = self.case_depth.saturating_sub(1),
                            _ => {}
                        }
                    }
                    current.words.push(word);
                }
            }
        }
    }

    fn is_fd_redirect(&self) -> bool {
        let mut i = self.pos;
        while self.chars.get(i).is_some_and(|c| c.is_ascii_digit()) {
            i += 1;
        }
        matches!(self.chars.get(i), Some('<' | '>'))
    }

    /// End the current simple command; here-documents it opened now know
    /// which command their body belongs to.
    fn flush(&mut self, current: &mut Simple, pending: &mut [PendingHeredoc]) {
        let simple = std::mem::take(current);
        // The pattern list of `case WORD in PATTERN|...` is not a command.
        let case_head = simple.words.first().is_some_and(|w| !w.quoted && w.text == "case");
        if !case_head && (!simple.words.is_empty() || !simple.redirects.is_empty()) {
            self.out.push(simple);
            let index = self.out.len() - 1;
            for heredoc in pending.iter_mut().filter(|h| h.command == usize::MAX) {
                heredoc.command = index;
            }
        }
    }

    fn skip_blanks(&mut self) {
        loop {
            match self.peek() {
                Some(' ' | '\t' | '\r') => self.pos += 1,
                Some('\\') if self.peek_at(1) == Some('\n') => self.pos += 2,
                _ => return,
            }
        }
    }

    fn redirect(&mut self, current: &mut Simple, pending: &mut Vec<PendingHeredoc>) -> Result<(), String> {
        let start = self.pos;
        if self.eat('&') {
            self.eat('>');
            self.eat('>');
        } else if self.eat('<') {
            if self.eat('<') {
                if self.eat('<') {
                    // here-string
                } else {
                    self.eat('-');
                }
            } else {
                let _ = self.eat('&') || self.eat('>');
            }
        } else if self.eat('>') {
            let _ = self.eat('>') || self.eat('|') || self.eat('&');
        }
        let op: String = self.chars[start..self.pos].iter().collect();
        self.skip_blanks();
        if self.peek().is_none_or(|c| is_operator(c) && c != '<' && c != '>') {
            return Err(format!("redirection {op} has no target"));
        }
        let target = self.word()?;
        if op == "<<" || op == "<<-" {
            // The body belongs to the current command, which gets its index when flushed.
            // A quoted delimiter (`<<'EOF'`) disables expansion of the body.
            pending.push(PendingHeredoc {
                command: usize::MAX,
                delimiter: target.text.clone(),
                strip_tabs: op == "<<-",
                expand: !target.quoted,
            });
        }
        current.redirects.push(Redirect { op, target });
        Ok(())
    }

    fn heredoc_body(&mut self, delimiter: &str, strip_tabs: bool) -> String {
        let mut body = String::new();
        while self.pos < self.chars.len() {
            let start = self.pos;
            while self.peek().is_some_and(|c| c != '\n') {
                self.pos += 1;
            }
            let line: String = self.chars[start..self.pos].iter().collect();
            self.eat('\n');
            let candidate = if strip_tabs { line.trim_start_matches('\t') } else { line.as_str() };
            if candidate == delimiter {
                break;
            }
            body.push_str(&line);
            body.push('\n');
        }
        body
    }

    /// Parse a `$(...)` body (the opening `$(` already consumed) as commands.
    fn substitution(&mut self) -> Result<(), String> {
        if self.depth >= MAX_DEPTH {
            return Err("command nests too deeply to inspect".into());
        }
        let mut inner = Parser {
            chars: std::mem::take(&mut self.chars),
            pos: self.pos,
            depth: self.depth + 1,
            out: Vec::new(),
            case_depth: 0,
        };
        let result = inner.script(true);
        self.chars = std::mem::take(&mut inner.chars);
        self.pos = inner.pos;
        result?;
        self.out.extend(inner.out);
        Ok(())
    }

    fn backtick(&mut self) -> Result<(), String> {
        let mut inner = String::new();
        loop {
            match self.peek() {
                None => return Err("unterminated backtick".into()),
                Some('`') => {
                    self.pos += 1;
                    break;
                }
                Some('\\') if matches!(self.peek_at(1), Some('`' | '\\' | '$')) => {
                    inner.push(self.chars[self.pos + 1]);
                    self.pos += 2;
                }
                Some(c) => {
                    inner.push(c);
                    self.pos += 1;
                }
            }
        }
        let commands = parse_nested(&inner, self.depth + 1)?;
        self.out.extend(commands);
        Ok(())
    }

    /// Skip a balanced `${...}` or `$((...))` body, returning its text. Command
    /// substitutions (`$(...)`, backticks) nested in the body are still parsed,
    /// since bash evaluates them; otherwise a destructive command hidden inside
    /// an expansion (`${X:-$(rm -rf /)}`, `$(( $(rm -rf /) ))`) would go unseen.
    fn balanced(&mut self, open: char, close: char) -> Result<String, String> {
        let start = self.pos;
        let mut level = 1;
        while let Some(c) = self.peek() {
            match c {
                '\\' => self.pos += 2,
                '\'' if open == '{' => {
                    self.pos += 1;
                    while self.peek().is_some_and(|c| c != '\'') {
                        self.pos += 1;
                    }
                    self.pos += 1;
                }
                '`' => {
                    self.pos += 1;
                    self.backtick()?;
                }
                '$' if self.peek_at(1) == Some('(') && self.peek_at(2) == Some('(') => {
                    self.pos += 3;
                    self.balanced('(', ')')?;
                    self.eat(')');
                }
                '$' if self.peek_at(1) == Some('(') => {
                    self.pos += 2;
                    self.substitution()?;
                }
                c if c == open => {
                    self.pos += 1;
                    level += 1;
                }
                c if c == close => {
                    self.pos += 1;
                    level -= 1;
                    if level == 0 {
                        return Ok(self.chars[start..self.pos - 1].iter().collect());
                    }
                }
                _ => self.pos += 1,
            }
        }
        Err(format!("unterminated {open}"))
    }

    /// `$...` at the current position (the `$` not yet consumed).
    fn dollar(&mut self, word: &mut Word) -> Result<(), String> {
        self.pos += 1;
        match self.peek() {
            Some('(') if self.peek_at(1) == Some('(') => {
                self.pos += 2;
                let body = self.balanced('(', ')')?;
                self.eat(')');
                word.text.push_str(&format!("$(({body}))"));
                word.dynamic = true;
            }
            Some('(') => {
                self.pos += 1;
                self.substitution()?;
                word.text.push_str("$(...)");
                word.dynamic = true;
            }
            Some('{') => {
                self.pos += 1;
                let body = self.balanced('{', '}')?;
                word.text.push_str(&format!("${{{body}}}"));
                word.dynamic = true;
            }
            Some(c) if c.is_ascii_alphanumeric() || c == '_' => {
                word.text.push('$');
                while self.peek().is_some_and(|c| c.is_ascii_alphanumeric() || c == '_') {
                    word.text.push(self.chars[self.pos]);
                    self.pos += 1;
                }
                word.dynamic = true;
            }
            Some(c) if "@*#?$!-".contains(c) => {
                word.text.push('$');
                word.text.push(c);
                self.pos += 1;
                word.dynamic = true;
            }
            _ => word.text.push('$'),
        }
        Ok(())
    }

    fn word(&mut self) -> Result<Word, String> {
        let mut word = Word::default();
        while let Some(c) = self.peek() {
            match c {
                ' ' | '\t' | '\r' => break,
                c if is_operator(c) => break,
                '\\' => {
                    self.pos += 1;
                    match self.peek() {
                        Some('\n') => self.pos += 1,
                        Some(next) => {
                            word.text.push(next);
                            word.quoted = true;
                            self.pos += 1;
                        }
                        None => word.text.push('\\'),
                    }
                }
                '\'' => {
                    self.pos += 1;
                    word.quoted = true;
                    loop {
                        match self.peek() {
                            None => return Err("unterminated single quote".into()),
                            Some('\'') => {
                                self.pos += 1;
                                break;
                            }
                            Some(c) => {
                                word.text.push(c);
                                self.pos += 1;
                            }
                        }
                    }
                }
                '"' => {
                    self.pos += 1;
                    word.quoted = true;
                    loop {
                        match self.peek() {
                            None => return Err("unterminated double quote".into()),
                            Some('"') => {
                                self.pos += 1;
                                break;
                            }
                            Some('\\') if matches!(self.peek_at(1), Some('"' | '\\' | '$' | '`' | '\n')) => {
                                let next = self.chars[self.pos + 1];
                                if next != '\n' {
                                    word.text.push(next);
                                }
                                self.pos += 2;
                            }
                            Some('$') => self.dollar(&mut word)?,
                            Some('`') => {
                                self.pos += 1;
                                self.backtick()?;
                                word.text.push_str("$(...)");
                                word.dynamic = true;
                            }
                            Some(c) => {
                                word.text.push(c);
                                self.pos += 1;
                            }
                        }
                    }
                }
                '$' if self.peek_at(1) == Some('\'') => {
                    self.pos += 2;
                    word.quoted = true;
                    loop {
                        match self.peek() {
                            None => return Err("unterminated $'...' string".into()),
                            Some('\'') => {
                                self.pos += 1;
                                break;
                            }
                            Some('\\') => {
                                self.pos += 1;
                                self.ansi_c_escape(&mut word)?;
                            }
                            Some(c) => {
                                word.text.push(c);
                                self.pos += 1;
                            }
                        }
                    }
                }
                '$' => self.dollar(&mut word)?,
                '`' => {
                    self.pos += 1;
                    self.backtick()?;
                    word.text.push_str("$(...)");
                    word.dynamic = true;
                }
                '*' | '?' | '[' => {
                    word.glob = true;
                    word.text.push(c);
                    self.pos += 1;
                }
                _ => {
                    word.text.push(c);
                    self.pos += 1;
                }
            }
        }
        Ok(word)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn words(source: &str) -> Vec<Vec<String>> {
        parse(source)
            .unwrap()
            .into_iter()
            .map(|s| s.words.into_iter().map(|w| w.text).collect())
            .collect()
    }

    #[test]
    fn splits_on_operators() {
        assert_eq!(
            words("ls -la && rm -rf / ; echo 'a b' | wc -l || true & sleep 1\ngit status"),
            vec![
                vec!["ls", "-la"],
                vec!["rm", "-rf", "/"],
                vec!["echo", "a b"],
                vec!["wc", "-l"],
                vec!["true"],
                vec!["sleep", "1"],
                vec!["git", "status"],
            ]
        );
    }

    #[test]
    fn unquotes_and_marks_dynamic_and_glob() {
        let parsed = parse(r#"rm -rf "$HOME"/x \* '*' * ${D:?}/y"#).unwrap();
        let w = &parsed[0].words;
        assert_eq!(w[2].text, "$HOME/x");
        assert!(w[2].dynamic && w[2].quoted);
        assert!(!w[3].glob && w[3].text == "*");
        assert!(!w[4].glob);
        assert!(w[5].glob && !w[5].quoted);
        assert_eq!(w[6].text, "${D:?}/y");
    }

    #[test]
    fn parses_substitutions_as_commands() {
        assert_eq!(
            words(r#"echo "$(rm -rf / )" `mkfs /dev/sda` $(( 1 + 2 )) <(dd of=/dev/sda)"#),
            vec![
                vec!["rm", "-rf", "/"],
                vec!["mkfs", "/dev/sda"],
                vec!["dd", "of=/dev/sda"],
                vec!["echo", "$(...)", "$(...)", "$(( 1 + 2 ))", "/dev/fd/63"],
            ]
        );
    }

    #[test]
    fn nested_command_substitutions_are_inspected() {
        // Command substitutions hidden inside arithmetic or parameter expansions
        // are parsed, so the destructive command is seen rather than skipped.
        assert_eq!(
            words(r#"echo $(( $(rm -rf /) ))"#),
            vec![vec!["rm", "-rf", "/"], vec!["echo", "$(( $(rm -rf /) ))"]]
        );
        assert_eq!(
            words(r#"echo "${X:-$(rm -rf /)}""#),
            vec![vec!["rm", "-rf", "/"], vec!["echo", "${X:-$(rm -rf /)}"]]
        );
        assert_eq!(
            words(r#"echo "${X:-`mkfs /dev/sda`}""#),
            vec![vec!["mkfs", "/dev/sda"], vec!["echo", "${X:-`mkfs /dev/sda`}"]]
        );
    }

    #[test]
    fn records_redirects_and_heredocs() {
        let parsed = parse("cat > /dev/sda 2>&1 <<EOF\nDROP DATABASE x;\nEOF\necho done").unwrap();
        assert_eq!(parsed[0].redirects[0].op, ">");
        assert_eq!(parsed[0].redirects[0].target.text, "/dev/sda");
        assert_eq!(parsed[0].redirects[1].op, ">&");
        assert_eq!(parsed[0].heredocs, vec![Heredoc { body: "DROP DATABASE x;\n".into(), expand: true }]);
        assert_eq!(parsed[1].words[0].text, "echo");
        let parsed = parse("psql <<-'SQL' && echo ok\n\tDROP TABLE t;\n\tSQL\n").unwrap();
        assert_eq!(parsed[0].heredocs, vec![Heredoc { body: "\tDROP TABLE t;\n".into(), expand: false }]);
        assert_eq!(parsed[1].words[0].text, "echo");
    }

    #[test]
    fn handles_subshells_groups_and_case() {
        assert_eq!(words("(cd x && rm -rf y)"), vec![vec!["cd", "x"], vec!["rm", "-rf", "y"]]);
        assert_eq!(words("{ rm a; }"), vec![vec!["{", "rm", "a"], vec!["}"]]);
        assert_eq!(
            words("case $x in a|b) rm a ;; *) echo no ;; esac"),
            vec![vec!["rm", "a"], vec!["echo", "no"], vec!["esac"]]
        );
    }

    #[test]
    fn fails_closed_on_malformed_input() {
        for bad in ["echo 'x", "echo \"x", "echo $(ls", "echo `ls", "ls )", "(ls", "echo ${x"] {
            assert!(parse(bad).is_err(), "{bad}");
        }
        let deep = "$(".repeat(40) + &")".repeat(40);
        assert!(parse(&format!("echo {deep}")).is_err());
    }
}