yarp-cli 0.1.0

Prune Pi command output and archive tool calls locally
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
use std::collections::BTreeSet;

use tree_sitter::{Node, Parser};

const MAX_SOURCE_BYTES: usize = 256 * 1024;
const MAX_AST_NODES: usize = 16_384;
const MAX_NESTING_DEPTH: usize = 64;
const MAX_STAGES: usize = 256;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Connector {
    Sequence,
    And,
    Or,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct ShellProgram {
    pub(crate) items: Vec<ShellItem>,
    pub(crate) connectors: Vec<Connector>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum ShellItem {
    Simple(SimpleCommand),
    Pipeline(Vec<SimpleCommand>),
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct SimpleCommand {
    pub(crate) words: Vec<String>,
    pub(crate) stream_merges: Vec<StreamMerge>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum StreamMerge {
    StderrToStdout,
    StdoutToStderr,
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum SyntaxFeature {
    Pipeline,
    AndChain,
    OtherRedirection,
    StreamMerge,
    Semicolon,
    Multiline,
    ParameterExpansion,
    OrChain,
    CommandSubstitution,
    PathInvocation,
    ControlStructure,
    UnsupportedWrapper,
    Comment,
    Background,
    NestedShell,
    SubshellGroup,
    ShellFunction,
    ParserFailure,
}

impl SyntaxFeature {
    const fn label(self) -> &'static str {
        match self {
            Self::Pipeline => "pipeline",
            Self::AndChain => "and_chain",
            Self::OtherRedirection => "other_redirection",
            Self::StreamMerge => "stream_merge",
            Self::Semicolon => "semicolon",
            Self::Multiline => "multiline",
            Self::ParameterExpansion => "parameter_expansion",
            Self::OrChain => "or_chain",
            Self::CommandSubstitution => "command_substitution",
            Self::PathInvocation => "path_invocation",
            Self::ControlStructure => "control_structure",
            Self::UnsupportedWrapper => "unsupported_wrapper",
            Self::Comment => "comment",
            Self::Background => "background",
            Self::NestedShell => "nested_shell",
            Self::SubshellGroup => "subshell_group",
            Self::ShellFunction => "shell_function",
            Self::ParserFailure => "parser_failure",
        }
    }
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct SyntaxFeatures {
    values: BTreeSet<SyntaxFeature>,
}

impl SyntaxFeatures {
    #[must_use]
    pub fn contains(&self, feature: SyntaxFeature) -> bool {
        self.values.contains(&feature)
    }

    pub fn labels(&self) -> impl Iterator<Item = &'static str> + '_ {
        self.values.iter().map(|feature| feature.label())
    }

    fn insert(&mut self, feature: SyntaxFeature) {
        self.values.insert(feature);
    }
}

/// Inspect fixed public shell syntax features without retaining source values.
#[must_use]
pub fn inspect_syntax(source: &str) -> SyntaxFeatures {
    let mut features = inspect_lexical_syntax(source);
    if source.len() > MAX_SOURCE_BYTES {
        features.insert(SyntaxFeature::ParserFailure);
        return features;
    }
    let mut parser = Parser::new();
    if parser
        .set_language(&tree_sitter_bash::LANGUAGE.into())
        .is_err()
    {
        features.insert(SyntaxFeature::ParserFailure);
        return features;
    }
    let Some(tree) = parser.parse(source, None) else {
        features.insert(SyntaxFeature::ParserFailure);
        return features;
    };
    let root = tree.root_node();
    if root.has_error() {
        features.insert(SyntaxFeature::ParserFailure);
    }
    let mut node_count = 0_usize;
    inspect_syntax_tree(root, source, &mut features, 0, &mut node_count);
    features
}

/// Parse one conservatively supported Bash command without executing or expanding it.
///
/// # Errors
///
/// Returns an error for unsupported syntax, dynamic words, unsafe redirects, or resource limits.
pub(crate) fn parse(source: &str) -> Result<ShellProgram, String> {
    if source.trim().is_empty() {
        return Err("empty shell source".to_owned());
    }
    if source.len() > MAX_SOURCE_BYTES {
        return Err("shell source exceeds the parser byte limit".to_owned());
    }
    let mut parser = Parser::new();
    parser
        .set_language(&tree_sitter_bash::LANGUAGE.into())
        .map_err(|error| format!("could not load Bash grammar: {error}"))?;
    let tree = parser
        .parse(source, None)
        .ok_or_else(|| "Bash parser returned no syntax tree".to_owned())?;
    let root = tree.root_node();
    if root.start_byte() != 0 || root.end_byte() != source.len() {
        return Err("Bash syntax tree does not cover the full source".to_owned());
    }
    validate_tree_limits(root)?;
    if root.has_error() {
        return Err("Bash syntax tree contains an error or missing node".to_owned());
    }
    if root.kind() != "program" {
        return Err("Bash syntax tree has an unsupported root".to_owned());
    }

    let mut program = ShellProgram {
        items: Vec::new(),
        connectors: Vec::new(),
    };
    let mut cursor = root.walk();
    for child in root.named_children(&mut cursor) {
        if child.kind() == "comment" {
            return Err("shell comments are unsupported".to_owned());
        }
        let connector = (!program.items.is_empty()).then_some(Connector::Sequence);
        append_statement(child, source, connector, &mut program)?;
    }
    if program.items.is_empty() || program.items.len() > MAX_STAGES {
        return Err("shell command count is outside the supported range".to_owned());
    }
    if program.connectors.len().saturating_add(1) != program.items.len() {
        return Err("shell connector count is inconsistent".to_owned());
    }
    Ok(program)
}

/// Parse exactly one simple command for pre-execution rewriting.
///
/// # Errors
///
/// Returns an error when the source is compound or contains stream redirects.
pub(crate) fn parse_simple_words(source: &str) -> Result<Vec<String>, String> {
    let program = parse(source)?;
    let [ShellItem::Simple(command)] = program.items.as_slice() else {
        return Err("shell source is not one simple command".to_owned());
    };
    if !program.connectors.is_empty() || !command.stream_merges.is_empty() {
        return Err("simple command contains unsupported stream syntax".to_owned());
    }
    Ok(command.words.clone())
}

fn validate_tree_limits(root: Node<'_>) -> Result<(), String> {
    let mut count = 0_usize;
    let mut stack = vec![(root, 1_usize)];
    while let Some((node, depth)) = stack.pop() {
        count = count.saturating_add(1);
        if count > MAX_AST_NODES {
            return Err("Bash syntax tree exceeds the node limit".to_owned());
        }
        if depth > MAX_NESTING_DEPTH {
            return Err("Bash syntax tree exceeds the nesting limit".to_owned());
        }
        if node.is_error() || node.is_missing() {
            return Err("Bash syntax tree contains an error or missing node".to_owned());
        }
        if !node.is_named() && node.kind() == "&" {
            return Err("background shell jobs are unsupported".to_owned());
        }
        let mut cursor = node.walk();
        stack.extend(
            node.children(&mut cursor)
                .map(|child| (child, depth.saturating_add(1))),
        );
    }
    Ok(())
}

fn append_statement(
    node: Node<'_>,
    source: &str,
    preceding: Option<Connector>,
    output: &mut ShellProgram,
) -> Result<(), String> {
    if node.kind() == "list" {
        let mut cursor = node.walk();
        let children = node.named_children(&mut cursor).collect::<Vec<_>>();
        if children.len() != 2 {
            return Err("shell list has an unsupported shape".to_owned());
        }
        let connector = list_connector(node)?;
        append_statement(children[0], source, preceding, output)?;
        append_statement(children[1], source, Some(connector), output)?;
        return Ok(());
    }

    let item = parse_item(node, source)?;
    if let Some(connector) = preceding {
        if output.items.is_empty() {
            return Err("shell connector has no left command".to_owned());
        }
        output.connectors.push(connector);
    } else if !output.items.is_empty() {
        return Err("shell command is missing a connector".to_owned());
    }
    output.items.push(item);
    Ok(())
}

fn list_connector(node: Node<'_>) -> Result<Connector, String> {
    let mut cursor = node.walk();
    let operators = node
        .children(&mut cursor)
        .filter(|child| !child.is_named())
        .filter_map(|child| match child.kind() {
            "&&" => Some(Connector::And),
            "||" => Some(Connector::Or),
            _ => None,
        })
        .collect::<Vec<_>>();
    let [connector] = operators.as_slice() else {
        return Err("shell list has an unsupported connector".to_owned());
    };
    Ok(*connector)
}

fn parse_item(node: Node<'_>, source: &str) -> Result<ShellItem, String> {
    match node.kind() {
        "command" | "declaration_command" | "variable_assignment" | "variable_assignments" => {
            Ok(ShellItem::Simple(parse_simple(node, source)?))
        }
        "redirected_statement" => parse_redirected(node, source),
        "pipeline" => parse_pipeline(node, source),
        kind => Err(format!("unsupported shell statement: {kind}")),
    }
}

fn parse_pipeline(node: Node<'_>, source: &str) -> Result<ShellItem, String> {
    let mut stage_cursor = node.walk();
    let stage_nodes = node.named_children(&mut stage_cursor).collect::<Vec<_>>();
    if stage_nodes.len() < 2 || stage_nodes.len() > MAX_STAGES {
        return Err("pipeline stage count is outside the supported range".to_owned());
    }
    let mut token_cursor = node.walk();
    if node
        .children(&mut token_cursor)
        .any(|child| !child.is_named() && child.kind() != "|")
    {
        return Err("pipeline uses an unsupported operator or prefix".to_owned());
    }
    let mut stages = Vec::with_capacity(stage_nodes.len());
    for stage in stage_nodes {
        let simple = match parse_item(stage, source)? {
            ShellItem::Simple(simple) => simple,
            ShellItem::Pipeline(_) => return Err("nested pipelines are unsupported".to_owned()),
        };
        stages.push(simple);
    }
    Ok(ShellItem::Pipeline(stages))
}

fn parse_redirected(node: Node<'_>, source: &str) -> Result<ShellItem, String> {
    let body = node
        .child_by_field_name("body")
        .ok_or_else(|| "redirected shell statement has no body".to_owned())?;
    let ShellItem::Simple(mut command) = parse_item(body, source)? else {
        return Err("redirects around compound statements are unsupported".to_owned());
    };
    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        if child.id() == body.id() {
            continue;
        }
        command
            .stream_merges
            .push(parse_stream_merge(child, source)?);
    }
    Ok(ShellItem::Simple(command))
}

fn parse_simple(node: Node<'_>, source: &str) -> Result<SimpleCommand, String> {
    if matches!(
        node.kind(),
        "declaration_command" | "variable_assignment" | "variable_assignments"
    ) {
        return Ok(SimpleCommand {
            words: decode_fragment_words(node_text(node, source)?)?,
            stream_merges: Vec::new(),
        });
    }
    if node.kind() != "command" {
        return Err("unsupported simple command node".to_owned());
    }
    let mut words = Vec::new();
    let mut stream_merges = Vec::new();
    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        match child.kind() {
            "file_redirect" => stream_merges.push(parse_stream_merge(child, source)?),
            "herestring_redirect" | "subshell" => {
                return Err("dynamic command input is unsupported".to_owned());
            }
            _ => words.push(decode_one_word(node_text(child, source)?)?),
        }
    }
    if words.is_empty() {
        return Err("simple command has no literal words".to_owned());
    }
    Ok(SimpleCommand {
        words,
        stream_merges,
    })
}

fn parse_stream_merge(node: Node<'_>, source: &str) -> Result<StreamMerge, String> {
    if node.kind() != "file_redirect" {
        return Err("unsupported shell redirection".to_owned());
    }
    let compact = node_text(node, source)?
        .bytes()
        .filter(|byte| !byte.is_ascii_whitespace())
        .collect::<Vec<_>>();
    match compact.as_slice() {
        b"2>&1" => Ok(StreamMerge::StderrToStdout),
        b"1>&2" => Ok(StreamMerge::StdoutToStderr),
        _ => Err("unsupported shell redirection".to_owned()),
    }
}

fn node_text<'a>(node: Node<'_>, source: &'a str) -> Result<&'a str, String> {
    source
        .get(node.byte_range())
        .ok_or_else(|| "Bash syntax node is outside the source".to_owned())
}

fn decode_one_word(source: &str) -> Result<String, String> {
    let words = decode_fragment_words(source)?;
    let [word] = words.as_slice() else {
        return Err("shell word did not decode to one literal argument".to_owned());
    };
    Ok(word.clone())
}

fn decode_fragment_words(source: &str) -> Result<Vec<String>, String> {
    #[derive(Clone, Copy, Eq, PartialEq)]
    enum Quote {
        None,
        Single,
        Double,
    }

    let mut words = Vec::new();
    let mut word = String::new();
    let mut started = false;
    let mut quote = Quote::None;
    let mut characters = source.chars();
    while let Some(character) = characters.next() {
        match quote {
            Quote::None => match character {
                '\'' => {
                    quote = Quote::Single;
                    started = true;
                }
                '"' => {
                    quote = Quote::Double;
                    started = true;
                }
                '\\' => {
                    let escaped = characters
                        .next()
                        .ok_or_else(|| "shell word has a trailing escape".to_owned())?;
                    if matches!(escaped, '\n' | '\r') {
                        return Err("escaped newlines are unsupported".to_owned());
                    }
                    word.push(escaped);
                    started = true;
                }
                '*' | '?' | '[' if word.is_empty() || word.starts_with('-') => {
                    return Err("shell word contains unsafe pathname expansion".to_owned());
                }
                '{' | '}' => return Err("shell brace expansion is unsupported".to_owned()),
                '\n' | '\r' | '|' | '&' | ';' | '<' | '>' | '(' | ')' | '`' | '$' | '#' => {
                    return Err("shell word contains dynamic or control syntax".to_owned());
                }
                value if value.is_whitespace() => finish_word(&mut words, &mut word, &mut started),
                _ => {
                    word.push(character);
                    started = true;
                }
            },
            Quote::Single => {
                if character == '\'' {
                    quote = Quote::None;
                } else {
                    word.push(character);
                }
            }
            Quote::Double => match character {
                '"' => quote = Quote::None,
                '\\' => {
                    let escaped = characters
                        .next()
                        .ok_or_else(|| "shell word has a trailing escape".to_owned())?;
                    if matches!(escaped, '\n' | '\r') {
                        return Err("escaped newlines are unsupported".to_owned());
                    }
                    word.push(escaped);
                }
                '`' | '$' => return Err("shell expansion is unsupported".to_owned()),
                _ => word.push(character),
            },
        }
    }
    if quote != Quote::None {
        return Err("shell word has an unterminated quote".to_owned());
    }
    finish_word(&mut words, &mut word, &mut started);
    if words.is_empty() {
        return Err("shell fragment has no literal words".to_owned());
    }
    Ok(words)
}

fn finish_word(words: &mut Vec<String>, word: &mut String, started: &mut bool) {
    if *started {
        words.push(std::mem::take(word));
        *started = false;
    }
}

fn inspect_syntax_tree(
    node: Node<'_>,
    source: &str,
    features: &mut SyntaxFeatures,
    depth: usize,
    node_count: &mut usize,
) {
    *node_count = node_count.saturating_add(1);
    if depth > MAX_NESTING_DEPTH || *node_count > MAX_AST_NODES {
        features.insert(SyntaxFeature::ParserFailure);
        return;
    }
    match node.kind() {
        "for_statement"
        | "c_style_for_statement"
        | "while_statement"
        | "if_statement"
        | "case_statement" => features.insert(SyntaxFeature::ControlStructure),
        "function_definition" => features.insert(SyntaxFeature::ShellFunction),
        "subshell" => features.insert(SyntaxFeature::SubshellGroup),
        "comment" => features.insert(SyntaxFeature::Comment),
        "file_redirect" => {
            if parse_stream_merge(node, source).is_ok() {
                features.insert(SyntaxFeature::StreamMerge);
            } else {
                features.insert(SyntaxFeature::OtherRedirection);
            }
        }
        "herestring_redirect" | "heredoc_redirect" | "process_substitution" => {
            features.insert(SyntaxFeature::OtherRedirection);
        }
        "simple_expansion" | "expansion" => features.insert(SyntaxFeature::ParameterExpansion),
        "command_substitution" | "arithmetic_expansion" => {
            features.insert(SyntaxFeature::CommandSubstitution);
        }
        "command" => inspect_command_name(node, source, features),
        _ => {}
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        inspect_syntax_tree(child, source, features, depth + 1, node_count);
    }
}

fn inspect_command_name(node: Node<'_>, source: &str, features: &mut SyntaxFeatures) {
    let Some(name) = node.child_by_field_name("name") else {
        return;
    };
    let Ok(name) = node_text(name, source).and_then(decode_one_word) else {
        return;
    };
    if name.contains('/') {
        features.insert(SyntaxFeature::PathInvocation);
    }
    let base = name.rsplit('/').next().unwrap_or(&name);
    if matches!(
        base,
        "sudo" | "doas" | "nice" | "nohup" | "stdbuf" | "unbuffer" | "xargs" | "parallel" | "watch"
    ) {
        features.insert(SyntaxFeature::UnsupportedWrapper);
    }
    if matches!(base, "bash" | "sh" | "zsh" | "fish") {
        features.insert(SyntaxFeature::NestedShell);
    }
}

#[derive(Clone, Copy, Eq, PartialEq)]
enum LexicalQuote {
    None,
    Single,
    Double,
}

struct LexicalScanner<'a> {
    bytes: &'a [u8],
    features: SyntaxFeatures,
    index: usize,
    quote: LexicalQuote,
    escaped: bool,
    comment: bool,
    boundary: bool,
}

impl<'a> LexicalScanner<'a> {
    fn new(source: &'a str) -> Self {
        Self {
            bytes: source.as_bytes(),
            features: SyntaxFeatures::default(),
            index: 0,
            quote: LexicalQuote::None,
            escaped: false,
            comment: false,
            boundary: true,
        }
    }

    fn finish(mut self) -> SyntaxFeatures {
        while self.index < self.bytes.len() {
            self.advance();
        }
        self.features
    }

    fn advance(&mut self) {
        let byte = self.bytes[self.index];
        if self.comment {
            if matches!(byte, b'\n' | b'\r') {
                self.comment = false;
                self.features.insert(SyntaxFeature::Multiline);
                self.boundary = true;
            }
            self.index += 1;
            return;
        }
        if self.escaped {
            self.escaped = false;
            self.boundary = false;
            self.index += 1;
            return;
        }
        match self.quote {
            LexicalQuote::Single => {
                if byte == b'\'' {
                    self.quote = LexicalQuote::None;
                }
            }
            LexicalQuote::Double => self.observe_double_quoted(byte),
            LexicalQuote::None => self.observe_unquoted(byte),
        }
        self.index += 1;
    }

    fn observe_double_quoted(&mut self, byte: u8) {
        match byte {
            b'\\' => self.escaped = true,
            b'"' => self.quote = LexicalQuote::None,
            b'`' => self.features.insert(SyntaxFeature::CommandSubstitution),
            b'$' if self.bytes.get(self.index + 1) == Some(&b'(') => {
                self.features.insert(SyntaxFeature::CommandSubstitution);
            }
            b'$' => self.features.insert(SyntaxFeature::ParameterExpansion),
            b'\n' | b'\r' => self.features.insert(SyntaxFeature::Multiline),
            _ => {}
        }
    }

    fn observe_unquoted(&mut self, byte: u8) {
        match byte {
            b'\\' => self.escaped = true,
            b'\'' => self.quote = LexicalQuote::Single,
            b'"' => self.quote = LexicalQuote::Double,
            b'#' if self.boundary => {
                self.features.insert(SyntaxFeature::Comment);
                self.comment = true;
            }
            b'\n' | b'\r' => self.features.insert(SyntaxFeature::Multiline),
            b'`' => self.features.insert(SyntaxFeature::CommandSubstitution),
            b'$' if self.bytes.get(self.index + 1) == Some(&b'(') => {
                self.features.insert(SyntaxFeature::CommandSubstitution);
            }
            b'$' => self.features.insert(SyntaxFeature::ParameterExpansion),
            b'|' if self.bytes.get(self.index + 1) == Some(&b'|') => {
                self.features.insert(SyntaxFeature::OrChain);
                self.index += 1;
            }
            b'|' => {
                self.features.insert(SyntaxFeature::Pipeline);
                if self.bytes.get(self.index + 1) == Some(&b'&') {
                    self.index += 1;
                }
            }
            b'&' if self.is_redirect_ampersand() => {}
            b'&' if self.bytes.get(self.index + 1) == Some(&b'&') => {
                self.features.insert(SyntaxFeature::AndChain);
                self.index += 1;
            }
            b'&' => self.features.insert(SyntaxFeature::Background),
            b';' => self.features.insert(SyntaxFeature::Semicolon),
            b'<' | b'>' if !self.is_safe_stream_merge() => {
                self.features.insert(SyntaxFeature::OtherRedirection);
            }
            _ => {}
        }
        self.boundary = byte.is_ascii_whitespace()
            || matches!(byte, b';' | b'&' | b'|' | b'(' | b')' | b'<' | b'>');
    }

    fn is_redirect_ampersand(&self) -> bool {
        self.bytes.get(self.index.saturating_sub(1)) == Some(&b'>')
            || self.bytes.get(self.index + 1) == Some(&b'>')
    }

    fn is_safe_stream_merge(&self) -> bool {
        let start = self.index.saturating_sub(1);
        let end = self.index.saturating_add(3).min(self.bytes.len());
        matches!(&self.bytes[start..end], b"2>&1" | b"1>&2")
    }
}

fn inspect_lexical_syntax(source: &str) -> SyntaxFeatures {
    LexicalScanner::new(source).finish()
}

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

    #[test]
    fn parses_simple_commands_and_literal_quotes() {
        assert_eq!(
            parse_simple_words("git diff -- 'file name'").expect("simple"),
            ["git", "diff", "--", "file name"]
        );
        assert_eq!(
            parse_simple_words("GOWORK=off go test ./...").expect("assignment"),
            ["GOWORK=off", "go", "test", "./..."]
        );
        assert_eq!(
            parse_simple_words(r"printf escaped\|operator").expect("escaped operator"),
            ["printf", "escaped|operator"]
        );
        assert_eq!(
            parse_simple_words("echo src/*.rs ~/private").expect("safe path expansion"),
            ["echo", "src/*.rs", "~/private"]
        );
    }

    #[test]
    fn parses_lists_and_pipelines_without_expanding_them() {
        let program = parse("cd repo && rg TODO . | sort | head -50; true").expect("program");
        assert_eq!(program.items.len(), 3);
        assert_eq!(program.connectors, [Connector::And, Connector::Sequence]);
        let ShellItem::Pipeline(stages) = &program.items[1] else {
            panic!("pipeline");
        };
        assert_eq!(stages.len(), 3);
        assert_eq!(stages[0].words, ["rg", "TODO", "."]);
        assert_eq!(stages[2].words, ["head", "-50"]);
    }

    #[test]
    fn accepts_only_reviewed_stream_merges() {
        let program = parse("cargo test 2>&1 || true").expect("stream merge");
        let ShellItem::Simple(command) = &program.items[0] else {
            panic!("simple");
        };
        assert_eq!(command.stream_merges, [StreamMerge::StderrToStdout]);
        let features = inspect_syntax("cargo test 2>&1");
        assert!(!features.contains(SyntaxFeature::Background));
        assert!(!features.contains(SyntaxFeature::OtherRedirection));
        assert!(features.contains(SyntaxFeature::StreamMerge));
        assert!(parse("cargo test > result.log").is_err());
        assert!(parse("cargo test |& head").is_err());
    }

    #[test]
    fn reports_fixed_syntax_features_without_source_values() {
        let features = inspect_syntax(
            "cd /repo && /usr/bin/rg $TERM . | head -50; printf '%s' \"$(pwd)\" > result &",
        );
        assert!(features.contains(SyntaxFeature::Pipeline));
        assert!(features.contains(SyntaxFeature::AndChain));
        assert!(features.contains(SyntaxFeature::Semicolon));
        assert!(features.contains(SyntaxFeature::ParameterExpansion));
        assert!(features.contains(SyntaxFeature::CommandSubstitution));
        assert!(features.contains(SyntaxFeature::OtherRedirection));
        assert!(features.contains(SyntaxFeature::Background));
        assert!(features.contains(SyntaxFeature::PathInvocation));
        assert!(!features.labels().any(|label| label.contains("repo")));
    }

    #[test]
    fn rejects_dynamic_or_unbounded_shell_forms() {
        for source in [
            "echo $HOME",
            "echo $(pwd)",
            "echo `pwd`",
            "echo *.rs",
            "echo --j*",
            "echo {one,two}",
            "echo value # comment",
            "cargo test &",
            "cargo test | head &",
            "(cargo test)",
            "for x in a; do echo $x; done",
            "cat <<EOF\nvalue\nEOF",
            "cargo test |",
            "cargo test &&",
            "! cargo test | head -100",
            "((((((((((((((((((((cargo test))))))))))))))))))))",
        ] {
            assert!(parse(source).is_err(), "accepted {source:?}");
        }
        let oversized = "x".repeat(MAX_SOURCE_BYTES + 1);
        assert!(parse(&oversized).is_err());
        assert!(inspect_syntax(&oversized).contains(SyntaxFeature::ParserFailure));
        let too_many_stages = std::iter::repeat_n("cat", MAX_STAGES + 1)
            .collect::<Vec<_>>()
            .join(" | ");
        assert!(parse(&too_many_stages).is_err());
    }

    #[test]
    fn arbitrary_parse_failures_are_pure_and_fail_open_without_mutation() {
        let alphabet = b"abc $'\"\\|&;()<>#\n`";
        let mut state = 0x6a09_e667_f3bc_c909_u64;
        for length in 0..128 {
            let mut source = String::with_capacity(length);
            for _ in 0..length {
                state ^= state << 13;
                state ^= state >> 7;
                state ^= state << 17;
                let modulus = u64::try_from(alphabet.len()).expect("alphabet length");
                let index = usize::try_from(state % modulus).expect("alphabet index");
                source.push(char::from(alphabet[index]));
            }
            let before = source.clone();
            let _ = parse(&source);
            assert_eq!(source, before);
        }
    }
}