bashrs 6.66.0

Rust-to-Shell transpiler for deterministic bootstrap scripts
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
//! Coverage tests for bash_parser/parser_control.rs uncovered branches.
//!
//! Targets: if/elif/else with redirects, while/until with semicolons and
//! redirects, brace group/subshell with redirects, coproc named/unnamed,
//! standalone [ ] and [[ ]] test commands with combinators, for loops
//! (C-style, single/multi item, newline terminator), select statement,
//! case parsing (patterns, alternates, body semicolons, terminators).
#![allow(clippy::unwrap_used)]
#![allow(clippy::expect_used)]

use super::ast::{BashExpr, BashStmt};
use super::parser::BashParser;

/// Helper: parse input and return the AST, panicking on failure.
fn parse_ok(input: &str) -> super::ast::BashAst {
    let mut p = BashParser::new(input).unwrap();
    p.parse().unwrap()
}

/// Helper: parse input, accepting either Ok or Err (no panic).
fn parse_no_panic(input: &str) {
    let _ = BashParser::new(input).and_then(|mut p| p.parse());
}

// ---------------------------------------------------------------------------
// parse_if — elif, else, redirect branches
// ---------------------------------------------------------------------------

#[test]
fn test_if_with_elif_redirect_suppression() {
    let input = "if [ -f /a ]; then\n  echo a\nelif [ -f /b ] 2>/dev/null; then\n  echo b\nfi";
    assert!(BashParser::new(input).and_then(|mut p| p.parse()).is_ok());
}

#[test]
fn test_if_with_else_block() {
    let ast = parse_ok("if [ -f /a ]; then\n  echo yes\nelse\n  echo no\nfi");
    if let BashStmt::If { else_block, .. } = &ast.statements[0] {
        assert!(else_block.is_some());
    }
}

#[test]
fn test_if_trailing_redirect() {
    parse_no_panic("if true; then echo hi; fi > /tmp/log");
}

#[test]
fn test_if_semicolon_before_then() {
    let ast = parse_ok("if [ 1 = 1 ] ; then echo ok ; fi");
    assert!(ast
        .statements
        .iter()
        .any(|s| matches!(s, BashStmt::If { .. })));
}

#[test]
fn test_if_multiple_elif_blocks() {
    let input = "if [ $x = 1 ]; then\n  echo one\nelif [ $x = 2 ]; then\n  echo two\nelif [ $x = 3 ]; then\n  echo three\nelse\n  echo other\nfi";
    let ast = parse_ok(input);
    if let BashStmt::If { elif_blocks, .. } = &ast.statements[0] {
        assert_eq!(elif_blocks.len(), 2);
    }
}

// ---------------------------------------------------------------------------
// parse_while — semicolons, redirects
// ---------------------------------------------------------------------------

#[test]
fn test_while_variants() {
    assert!(BashParser::new("while [ $i -lt 10 ]; do echo $i; done")
        .and_then(|mut p| p.parse())
        .is_ok());
    assert!(BashParser::new("while [ $i -lt 5 ]\ndo\n  echo $i\ndone")
        .and_then(|mut p| p.parse())
        .is_ok());
    parse_no_panic("while read line; do echo $line; done < /tmp/in");
    parse_no_panic("while [ -f /tmp/lock ] 2>/dev/null; do sleep 1; done");
}

// ---------------------------------------------------------------------------
// parse_until — semicolons, redirects
// ---------------------------------------------------------------------------

#[test]
fn test_until_variants() {
    assert!(BashParser::new("until [ $done = yes ]; do echo w; done")
        .and_then(|mut p| p.parse())
        .is_ok());
    assert!(
        BashParser::new("until [ -f /tmp/ready ]\ndo\n  sleep 1\ndone")
            .and_then(|mut p| p.parse())
            .is_ok()
    );
    parse_no_panic("until [ -f /tmp/done ] 2>/dev/null; do sleep 1; done");
}

// ---------------------------------------------------------------------------
// parse_brace_group and parse_subshell — trailing redirects
// ---------------------------------------------------------------------------

#[test]
fn test_brace_group_redirects() {
    parse_no_panic("{ echo a; echo b; } > /tmp/out");
    parse_no_panic("{ echo a; echo b; } 2>/dev/null");
    parse_no_panic("{ echo out; echo err >&2; } > /tmp/out 2>/dev/null");
}

#[test]
fn test_subshell_redirects() {
    parse_no_panic("(echo a; echo b) > /tmp/out");
    parse_no_panic("(echo a; echo b) 2>/dev/null");
    parse_no_panic("(echo l1; echo l2) >> /tmp/log");
}

// ---------------------------------------------------------------------------
// parse_coproc — named and unnamed
// ---------------------------------------------------------------------------

#[test]
fn test_coproc_unnamed() {
    let result = BashParser::new("coproc { cat; }").and_then(|mut p| p.parse());
    if let Ok(ast) = &result {
        if let BashStmt::Coproc { name, .. } = &ast.statements[0] {
            assert!(name.is_none());
        }
    }
}

#[test]
fn test_coproc_named() {
    let result = BashParser::new("coproc mycat { cat; }").and_then(|mut p| p.parse());
    if let Ok(ast) = &result {
        if let BashStmt::Coproc { name, .. } = &ast.statements[0] {
            assert_eq!(name.as_deref(), Some("mycat"));
        }
    }
}

#[test]
fn test_coproc_with_newlines() {
    parse_no_panic("coproc\n{\n  cat\n}");
}

// ---------------------------------------------------------------------------
// Standalone [ ] and [[ ]] test commands with combinators
// ---------------------------------------------------------------------------

#[test]
fn test_standalone_test_commands() {
    parse_no_panic("[ -f /tmp/test ] && echo exists");
    parse_no_panic("[ -f /a -a -d /b ] && echo both");
    parse_no_panic("[ -f /a -o -f /b ] && echo one");
}

#[test]
fn test_standalone_extended_test_commands() {
    parse_no_panic("[[ -d /tmp ]] && echo dir");
    parse_no_panic("[[ -f /a && -d /b ]] && echo both");
    parse_no_panic("[[ -f /a || -d /b ]] && echo one");
}

// ---------------------------------------------------------------------------
// parse_for — single/multi items, newline, C-style
// ---------------------------------------------------------------------------

#[test]
fn test_for_single_item() {
    let ast = parse_ok("for x in items; do echo $x; done");
    if let BashStmt::For { items, .. } = &ast.statements[0] {
        assert!(!matches!(items, BashExpr::Array(_)));
    }
}

#[test]
fn test_for_multiple_items() {
    let ast = parse_ok("for x in a b c d; do echo $x; done");
    if let BashStmt::For { items, .. } = &ast.statements[0] {
        assert!(matches!(items, BashExpr::Array(_)));
    }
}

#[test]
fn test_for_items_newline_terminated() {
    assert!(BashParser::new("for x in a b c\ndo\n  echo $x\ndone")
        .and_then(|mut p| p.parse())
        .is_ok());
}

#[test]
fn test_for_with_variable_and_cmd_subst() {
    assert!(BashParser::new("for f in $FILES; do echo $f; done")
        .and_then(|mut p| p.parse())
        .is_ok());
    parse_no_panic("for f in $(ls); do echo $f; done");
}

#[test]
fn test_for_c_style_from_arithmetic_token() {
    parse_no_panic("for ((i=0; i<10; i++)); do echo $i; done");
}

#[test]
fn test_for_c_style_parts_parsing() {
    let result =
        BashParser::new("for ((x=1; x<=5; x++)); do echo $x; done").and_then(|mut p| p.parse());
    if let Ok(ast) = &result {
        if let BashStmt::ForCStyle {
            init,
            condition,
            increment,
            ..
        } = &ast.statements[0]
        {
            assert!(!init.is_empty());
            assert!(!condition.is_empty());
            assert!(!increment.is_empty());
        }
    }
}

#[test]
fn test_for_c_style_operators() {
    // Various operator tokens inside (( )): <=, >=, ==, !=, $var
    parse_no_panic("for ((i=0; i<=10; i++)); do echo $i; done");
    parse_no_panic("for ((i=10; i>=0; i--)); do echo $i; done");
    parse_no_panic("for ((i=0; i==0; i++)); do echo once; done");
    parse_no_panic("for ((i=0; i!=5; i++)); do echo $i; done");
    parse_no_panic("for ((i=0; i<$MAX; i++)); do echo $i; done");
}

#[test]
fn test_for_c_style_malformed() {
    parse_no_panic("for ((i=0)); do echo $i; done");
}

#[test]
fn test_for_error_missing_variable() {
    parse_no_panic("for in a b; do echo nope; done");
}

// ---------------------------------------------------------------------------
// parse_select — interactive menu
// ---------------------------------------------------------------------------

#[test]
fn test_select_single_item() {
    assert!(BashParser::new("select opt in options; do echo $opt; done")
        .and_then(|mut p| p.parse())
        .is_ok());
}

#[test]
fn test_select_multiple_items() {
    let ast = parse_ok("select opt in a b c d; do echo $opt; break; done");
    if let BashStmt::Select {
        variable, items, ..
    } = &ast.statements[0]
    {
        assert_eq!(variable, "opt");
        assert!(matches!(items, BashExpr::Array(_)));
    }
}

#[test]
fn test_select_newline_and_semicolon() {
    assert!(
        BashParser::new("select x in a b c\ndo\n  echo $x\n  break\ndone")
            .and_then(|mut p| p.parse())
            .is_ok()
    );
    assert!(
        BashParser::new("select color in red green blue; do echo $color; break; done")
            .and_then(|mut p| p.parse())
            .is_ok()
    );
}

#[test]
fn test_select_error_missing_variable() {
    parse_no_panic("select in a b; do echo nope; done");
}

// ---------------------------------------------------------------------------
// parse_case — patterns, alternates, body, terminators
// ---------------------------------------------------------------------------

#[test]
fn test_case_basic() {
    let ast = parse_ok("case $x in\n  a) echo a ;;\n  b) echo b ;;\nesac");
    if let BashStmt::Case { arms, .. } = &ast.statements[0] {
        assert_eq!(arms.len(), 2);
    }
}

#[test]
fn test_case_with_pipe_alternatives() {
    let ast = parse_ok("case $x in\n  a|b|c) echo abc ;;\n  *) echo other ;;\nesac");
    if let BashStmt::Case { arms, .. } = &ast.statements[0] {
        assert!(arms[0].patterns.len() >= 2);
    }
}

#[test]
fn test_case_pattern_types() {
    // Variable, number, glob, string patterns
    assert!(BashParser::new("case $x in\n  $E) echo m ;;\nesac")
        .and_then(|mut p| p.parse())
        .is_ok());
    assert!(
        BashParser::new("case $x in\n  1) echo one ;;\n  2) echo two ;;\nesac")
            .and_then(|mut p| p.parse())
            .is_ok()
    );
    assert!(
        BashParser::new("case $f in\n  *.txt) echo t ;;\n  *) echo o ;;\nesac")
            .and_then(|mut p| p.parse())
            .is_ok()
    );
    parse_no_panic("case $x in\n  \"hello\") echo g ;;\nesac");
}

#[test]
fn test_case_bracket_class_pattern() {
    parse_no_panic("case $x in\n  [0-9]*) echo d ;;\n  [a-z]*) echo a ;;\nesac");
}

#[test]
fn test_case_arm_body_variants() {
    // Multiple stmts, empty body, semicolon-separated stmts
    assert!(
        BashParser::new("case $x in\n  a) echo a; echo again ;;\nesac")
            .and_then(|mut p| p.parse())
            .is_ok()
    );
    assert!(
        BashParser::new("case $x in\n  skip) ;;\n  *) echo d ;;\nesac")
            .and_then(|mut p| p.parse())
            .is_ok()
    );
    assert!(
        BashParser::new("case $x in\n  a) echo one; echo two ;;\nesac")
            .and_then(|mut p| p.parse())
            .is_ok()
    );
}

#[test]
fn test_case_terminators() {
    // ;& and ;;& terminators
    parse_no_panic("case $x in\n  a) echo a ;& \n  b) echo b ;;\nesac");
    parse_no_panic("case $x in\n  a) echo a ;;& \n  b) echo b ;;\nesac");
}

#[test]
fn test_case_double_semicolon_tokens() {
    // Two consecutive Semicolon tokens as ;; (vs single identifier)
    assert!(
        BashParser::new("case $x in\na) echo a\n;;\nb) echo b\n;;\nesac")
            .and_then(|mut p| p.parse())
            .is_ok()
    );
}

#[test]
fn test_case_missing_esac_error() {
    let result = BashParser::new("case $x in\n  a) echo a ;;\n").and_then(|mut p| p.parse());
    assert!(result.is_err());
}

#[test]
fn test_case_no_terminator_before_esac() {
    parse_no_panic("case $x in\n  *) echo default\nesac");
}

#[test]
fn test_case_word_is_variable() {
    let ast = parse_ok("case $CMD in\n  start) echo s ;;\n  stop) echo t ;;\nesac");
    if let BashStmt::Case { word, .. } = &ast.statements[0] {
        assert!(matches!(word, BashExpr::Variable(_)));
    }
}

// ---------------------------------------------------------------------------
// Compound command nesting
// ---------------------------------------------------------------------------

#[test]
fn test_nested_control_flow() {
    parse_no_panic("while true; do\n  if [ $x = 5 ]; then break; fi\n  continue\ndone");
    assert!(BashParser::new(
        "for x in 1 2 3; do\n  if [ $x = 2 ]; then\n    echo found\n  fi\ndone"
    )
    .and_then(|mut p| p.parse())
    .is_ok());
    parse_no_panic(
        "while read cmd; do\n  case $cmd in\n    quit) break ;;\n    *) echo u ;;\n  esac\ndone",
    );
}

// ---------------------------------------------------------------------------
// parser_control_methods.rs — parse_select edge cases
// ---------------------------------------------------------------------------

#[test]
fn test_select_semicolon_before_do() {
    // Tests the optional semicolon before do in select
    let ast = parse_ok("select opt in x y z ;\n do echo $opt; break; done");
    assert!(ast
        .statements
        .iter()
        .any(|s| matches!(s, BashStmt::Select { .. })));
}

#[test]
fn test_select_single_item_no_array() {
    // When item_list has exactly 1 item, it should not be wrapped in Array
    let ast = parse_ok("select opt in onlyone; do echo $opt; break; done");
    if let BashStmt::Select { items, .. } = &ast.statements[0] {
        assert!(
            !matches!(items, BashExpr::Array(_)),
            "Single item should not be Array"
        );
    }
}

#[test]
fn test_select_error_missing_variable_returns_err() {
    // Token after 'select' is not an identifier
    let result = BashParser::new("select 42 in a b; do echo x; done").and_then(|mut p| p.parse());
    assert!(result.is_err());
}

// ---------------------------------------------------------------------------
// parser_control_methods.rs — parse_for_c_style token varieties
// ---------------------------------------------------------------------------

#[test]
fn test_for_c_style_with_lt_gt_operators() {
    // Tests the Lt and Gt token branches inside (( ))
    parse_no_panic("for ((i=0; i<10; i=i+1)); do echo $i; done");
    parse_no_panic("for ((i=10; i>0; i=i-1)); do echo $i; done");
}

#[test]
fn test_for_c_style_with_nested_parens() {
    // Tests paren_depth tracking for nested parens inside (( ))
    parse_no_panic("for ((i=(1+2); i<10; i=i+1)); do echo $i; done");
}

#[test]
fn test_for_c_style_with_variables() {
    // Tests the Variable token branch inside (( ))
    parse_no_panic("for (($start; $i<$end; $i++)); do echo $i; done");
}

#[test]
fn test_for_c_style_with_eq_ne() {
    // Tests Eq and Ne token branches inside (( ))
    parse_no_panic("for ((i=0; i!=5; i=i+1)); do echo $i; done");
    parse_no_panic("for ((i=0; i==0; i=i+1)); do echo once; done");
}

#[test]
fn test_for_c_style_with_le_ge() {
    // Tests Le and Ge token branches inside (( ))
    parse_no_panic("for ((i=0; i<=10; i=i+1)); do echo $i; done");
    parse_no_panic("for ((i=10; i>=0; i=i-1)); do echo $i; done");
}

#[test]
fn test_for_c_style_with_assign() {
    // Tests the Assign token branch inside (( ))
    parse_no_panic("for ((i=0; i<5; i=i+1)); do echo $i; done");
}

#[test]
fn test_for_c_style_semicolon_before_do() {
    // Tests optional semicolon consumption after ))
    parse_no_panic("for ((i=0; i<5; i=i+1)) ; do echo $i; done");
}

#[test]
fn test_for_c_style_from_content_malformed_parts() {
    // When content has fewer than 3 parts, should use empty strings
    // This path is tested indirectly via the ArithmeticExpansion token
    parse_no_panic("for ((i=0)); do echo $i; done");
}

// ---------------------------------------------------------------------------
// parser_control_methods.rs — parse_case edge cases
// ---------------------------------------------------------------------------

#[test]
fn test_case_empty_pattern_skipped() {
    // When a pattern is empty, it should be skipped in the patterns vec
    parse_no_panic("case $x in\n  ) echo empty ;;\n  *) echo d ;;\nesac");
}

#[test]
fn test_case_multiple_statements_in_arm() {
    // Multiple statements separated by semicolons within arm body
    let ast = parse_ok("case $x in\n  a) echo one; echo two; echo three ;;\nesac");
    if let BashStmt::Case { arms, .. } = &ast.statements[0] {
        assert!(arms[0].body.len() >= 2);
    }
}

#[test]
fn test_case_fall_through_terminator() {
    // ;& fall-through terminator
    parse_no_panic("case $x in\n  a) echo a ;& \n  b) echo b ;;\nesac");
}

#[test]
fn test_case_resume_pattern_terminator() {
    // ;;& resume pattern matching terminator
    parse_no_panic("case $x in\n  a) echo a ;;& \n  b) echo b ;;\nesac");
}

#[test]
fn test_case_semicolon_semicolon_as_two_tokens() {
    // consume_case_terminator handling two consecutive Semicolon tokens
    parse_no_panic("case $x in\na) echo a\n;;\nesac");
}

#[test]
fn test_case_single_semicolon_in_terminator() {
    // consume_case_terminator with single Semicolon (not ;;)
    parse_no_panic("case $x in\na) echo a; \nesac");
}

#[test]
fn test_case_posix_class_in_pattern() {
    // parse_case_posix_class for [[:alpha:]] style patterns
    parse_no_panic("case $x in\n  [[:alpha:]]*) echo letter ;;\n  *) echo other ;;\nesac");
}

#[test]
fn test_case_bracket_class_with_negation() {
    // parse_case_bracket_class with ! for negation [!abc]
    parse_no_panic("case $x in\n  [!0-9]*) echo nodigit ;;\n  *) echo d ;;\nesac");
}

#[test]
fn test_case_string_pattern() {
    // parse_case_single_pattern with String token
    parse_no_panic("case $x in\n  \"hello\") echo hi ;;\n  *) echo d ;;\nesac");
}

#[test]
fn test_case_no_right_paren_after_pattern() {
    // When pattern is not followed by ), parser should handle gracefully
    parse_no_panic("case $x in\n  a echo a ;;\nesac");
}

#[test]
fn test_case_arm_body_with_if_inside() {
    // Case arm body containing an if statement
    let input = "case $x in\n  a) if [ 1 = 1 ]; then echo y; fi ;;\nesac";
    let ast = parse_ok(input);
    if let BashStmt::Case { arms, .. } = &ast.statements[0] {
        assert!(!arms[0].body.is_empty());
    }
}

#[test]
fn test_case_dot_pattern_concatenation() {
    // Tests concatenation of identifier.identifier patterns like server.host
    parse_no_panic("case $key in\n  server) echo s ;;\n  *) echo o ;;\nesac");
}