shuck-linter 0.0.38

Lint rule engine and checker for shell scripts
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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
use super::*;
use crate::facts::{
    collect_precise_function_return_guard_suppressions_in_seq,
    stmt_is_non_test_return_status_guard, stmt_is_unary_test_return_status_guard,
};
use shuck_ast::{Command, CompoundCommand};

#[test]
fn assignment_value_facts_ignore_line_continuation_backslashes_for_shell_quoting_literals() {
    let source = "#!/bin/bash\npackages=$foo\\\n$bar\nprintf '%s\\n' \"$packages\"\n";

    with_facts(source, None, |_, facts| {
        let fact = facts
            .expansion_word_facts(ExpansionContext::AssignmentValue)
            .next()
            .expect("assignment value fact should exist");

        assert!(!fact.contains_shell_quoting_literals());
    });
}

#[test]
fn assignment_value_facts_keep_single_quoted_backslash_newlines_for_shell_quoting_literals() {
    let source = "#!/bin/bash\npackages='foo\\\nbar'\nprintf '%s\\n' $packages\n";

    with_facts(source, None, |_, facts| {
        let fact = facts
            .expansion_word_facts(ExpansionContext::AssignmentValue)
            .next()
            .expect("assignment value fact should exist");

        assert!(fact.contains_shell_quoting_literals());
    });
}

#[test]
fn background_semicolon_facts_report_plain_semicolons() {
    let source = "#!/bin/bash\necho x &;\necho y & ;\n";

    with_facts(source, None, |_, facts| {
        let spans = facts.background_semicolon_spans();

        assert_eq!(spans.len(), 2);
        assert_eq!(spans[0].slice(source), ";");
        assert_eq!(spans[0].start.line, 2);
        assert_eq!(spans[1].slice(source), ";");
        assert_eq!(spans[1].start.line, 3);
    });
}

#[test]
fn background_semicolon_facts_ignore_case_item_terminators() {
    let source = "\
#!/bin/bash
case ${1-} in
  break) printf '%s\\n' ok &;;
  spaced) printf '%s\\n' ok & ;;
  fallthrough) printf '%s\\n' ok & ;&
  continue) printf '%s\\n' ok & ;;&
esac
";

    with_facts(source, None, |_, facts| {
        assert!(facts.background_semicolon_spans().is_empty());
    });
}

#[test]
fn redundant_echo_space_facts_capture_diagnostic_and_edit_spans() {
    let source = "#!/bin/bash\necho foo    bar    baz\necho foo  bar\n";

    with_facts(source, None, |_, facts| {
        let facts = facts.redundant_echo_space_facts();

        assert_eq!(facts.len(), 1);
        assert_eq!(
            facts[0].diagnostic_span().slice(source),
            "echo foo    bar    baz"
        );
        assert_eq!(facts[0].space_spans().len(), 2);
        assert_eq!(facts[0].space_spans()[0].slice(source), "    ");
        assert_eq!(facts[0].space_spans()[1].slice(source), "    ");
    });
}

#[test]
fn commented_continuation_facts_ignore_plain_comment_only_lines() {
    let source = "#!/bin/sh\necho hello \\\n  #world\n  foo\n";

    with_facts(source, None, |_, facts| {
        assert!(facts.commented_continuation_comment_spans().is_empty());
    });
}

#[test]
fn commented_continuation_facts_anchor_at_comment_backslash() {
    let source = "#!/bin/sh\necho hello \\\n  #world \\\n  foo\n";

    with_facts(source, None, |_, facts| {
        let spans = facts.commented_continuation_comment_spans();
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0].start.line, 3);
        assert_eq!(spans[0].start.column, 11);
        assert_eq!(spans[0].start, spans[0].end);
        assert_eq!(
            &source[spans[0].start.offset - 1..spans[0].start.offset],
            "\\"
        );
    });
}

#[test]
fn builds_command_facts_for_wrapped_and_nested_commands() {
    let source = "#!/bin/bash\ncommand printf '%s\\n' \"$(echo hi)\"\n";
    let output = Parser::new(source).parse().unwrap();
    let indexer = Indexer::new(source, &output);
    let semantic = LinterSemanticArtifacts::build(&output.file, source, &indexer);
    let facts = LinterFacts::build(&output.file, source, &semantic, &indexer);

    let outer = facts
        .structural_commands()
        .find(|fact| fact.effective_name_is("printf"))
        .expect("expected structural printf fact");

    assert_eq!(facts.commands().len(), 2);
    assert_eq!(outer.literal_name(), Some("command"));
    assert_eq!(outer.effective_name(), Some("printf"));
    assert_eq!(outer.wrappers(), &[WrapperKind::Command]);
    assert!(!outer.is_nested_word_command());
    assert_eq!(
        outer
            .options()
            .printf()
            .and_then(|printf| printf.format_word)
            .map(|word| word.span.slice(source)),
        Some("'%s\\n'")
    );

    let nested = facts
        .commands()
        .iter()
        .find(|fact| fact.effective_name_is("echo"))
        .expect("expected nested echo fact");
    assert!(nested.is_nested_word_command());
    let ids = facts
        .commands()
        .iter()
        .map(|fact| fact.id().index())
        .collect::<Vec<_>>();
    assert_eq!(ids.len(), 2);
    assert_ne!(ids[0], ids[1]);
}

#[test]

fn exposes_structural_commands_and_id_lookups() {
    let source = "#!/bin/bash\necho \"$(printf x)\"\n";
    let output = Parser::new(source).parse().unwrap();
    let indexer = Indexer::new(source, &output);
    let semantic = LinterSemanticArtifacts::build(&output.file, source, &indexer);
    let facts = LinterFacts::build(&output.file, source, &semantic, &indexer);

    let structural = facts
        .structural_commands()
        .map(|fact| fact.effective_or_literal_name().unwrap().to_owned())
        .collect::<Vec<_>>();
    let all = facts
        .commands()
        .iter()
        .map(|fact| fact.effective_or_literal_name().unwrap().to_owned())
        .collect::<Vec<_>>();

    assert_eq!(structural, vec!["echo"]);
    assert_eq!(all, vec!["echo", "printf"]);

    let echo_id = facts
        .command_id_for_stmt(&output.file.body[0])
        .expect("expected command id for top-level stmt");
    assert_eq!(
        facts.command(echo_id).effective_or_literal_name(),
        Some("echo")
    );
    assert_eq!(
        facts.command_id_for_command(&output.file.body[0].command),
        Some(echo_id)
    );
}

#[test]
fn precomputes_innermost_command_ids_for_nested_offsets() {
    let source = "#!/bin/bash\necho \"$(printf '%s' \"$(uname)\")\"\n";
    let output = Parser::new(source).parse().unwrap();
    let indexer = Indexer::new(source, &output);
    let semantic = LinterSemanticArtifacts::build(&output.file, source, &indexer);
    let facts = LinterFacts::build(&output.file, source, &semantic, &indexer);

    let outer_id = facts
        .commands()
        .iter()
        .find(|fact| fact.effective_or_literal_name() == Some("echo"))
        .map(|fact| fact.id())
        .expect("expected outer echo command");
    let middle_id = facts
        .commands()
        .iter()
        .find(|fact| fact.effective_or_literal_name() == Some("printf"))
        .map(|fact| fact.id())
        .expect("expected nested printf command");
    let inner_id = facts
        .commands()
        .iter()
        .find(|fact| fact.effective_or_literal_name() == Some("uname"))
        .map(|fact| fact.id())
        .expect("expected nested uname command");

    let command_ids_by_offset = super::build_innermost_command_ids_by_offset(
        facts.commands().raw(),
        vec![
            source.find("echo").expect("expected echo offset"),
            source.find("printf").expect("expected printf offset"),
            source.find("uname").expect("expected uname offset"),
        ],
    );

    assert_eq!(
        super::precomputed_command_id_for_offset(
            &command_ids_by_offset,
            source.find("echo").expect("expected echo offset"),
        ),
        Some(outer_id)
    );
    assert_eq!(
        super::precomputed_command_id_for_offset(
            &command_ids_by_offset,
            source.find("printf").expect("expected printf offset"),
        ),
        Some(middle_id)
    );
    assert_eq!(
        super::precomputed_command_id_for_offset(
            &command_ids_by_offset,
            source.find("uname").expect("expected uname offset"),
        ),
        Some(inner_id)
    );
}

#[test]
fn tracks_nested_commands_inside_if_and_elif_conditions() {
    let source = "\
#!/bin/bash
if \"$( [[ -f if_path ]] )\"; then
  :
elif \"$( [[ -f elif_path ]] )\"; then
  :
fi
";

    with_facts(source, None, |_, facts| {
        let if_nested = facts
            .commands()
            .iter()
            .find(|fact| fact.span().slice(source) == "[[ -f if_path ]]")
            .expect("expected nested if condition command");
        assert!(if_nested.scope_read_source_words().is_empty());
        assert!(facts.is_if_condition_command(if_nested.id()));
        assert!(!facts.is_elif_condition_command(if_nested.id()));

        let elif_nested = facts
            .commands()
            .iter()
            .find(|fact| fact.span().slice(source) == "[[ -f elif_path ]]")
            .expect("expected nested elif condition command");
        assert!(elif_nested.scope_read_source_words().is_empty());
        assert!(facts.is_elif_condition_command(elif_nested.id()));
    });
}

#[test]
fn recognizes_precise_function_return_guard_shapes() {
    let source = "\
#!/bin/bash
build_config() {
  helper || return $?
  [[ -n \"${flag:-}\" ]] || return $?
  export out=\"$(printf ok)\"
}
pkg_check() {
  [[ -f \"${base}/include/$1\" ]] || return $?
  case \"$mode\" in
    a) ext=a ;;
    *) ext=b ;;
  esac
  file=\"$(find \"${base}\" -name \"$2.$ext\" | head -n 1)\"
  [[ -n \"$file\" ]] || return $?
}
";

    let output = Parser::new(source).parse().unwrap();
    let Command::Function(build_config) = &output.file.body[0].command else {
        panic!("expected function");
    };
    let Command::Compound(CompoundCommand::BraceGroup(build_body)) = &build_config.body.command
    else {
        panic!("expected brace-group function body");
    };
    let Command::Function(pkg_check) = &output.file.body[1].command else {
        panic!("expected second function");
    };
    let Command::Compound(CompoundCommand::BraceGroup(pkg_body)) = &pkg_check.body.command else {
        panic!("expected brace-group function body");
    };

    assert!(stmt_is_non_test_return_status_guard(&build_body[0], source));
    assert!(stmt_is_unary_test_return_status_guard(
        &build_body[1],
        source
    ));
    assert!(stmt_is_unary_test_return_status_guard(&pkg_body[0], source));

    let mut body_spans = Vec::new();
    collect_precise_function_return_guard_suppressions_in_seq(
        build_body,
        source,
        &mut body_spans,
        true,
    );
    collect_precise_function_return_guard_suppressions_in_seq(
        pkg_body,
        source,
        &mut body_spans,
        true,
    );
    assert_eq!(
        body_spans
            .iter()
            .map(|span| span.start.line)
            .collect::<Vec<_>>(),
        vec![4, 8]
    );
}

#[test]
fn includes_nested_jq_file_operands_in_writer_scope_reads() {
    let source = "#!/bin/bash\ncat <<<$(jq '.dns={}' \"$cfg\") >\"$cfg\"\n";

    with_facts(source, None, |_, facts| {
        let jq = facts
            .commands()
            .iter()
            .find(|fact| fact.effective_name_is("jq"))
            .expect("expected nested jq command");
        assert_eq!(
            jq.file_operand_words()
                .iter()
                .map(|word| word.span.slice(source))
                .collect::<Vec<_>>(),
            vec!["\"$cfg\""]
        );

        let cat = facts
            .structural_commands()
            .find(|fact| fact.effective_name_is("cat"))
            .expect("expected structural cat command");
        assert_eq!(
            cat.scope_read_source_words()
                .iter()
                .map(|fact| fact.word().span.slice(source))
                .collect::<Vec<_>>(),
            vec!["$(jq '.dns={}' \"$cfg\")", "\"$cfg\""]
        );
    });
}

#[test]
fn parses_jq_input_modes_into_file_operands() {
    let source = "\
#!/bin/bash
jq --args '$ARGS.positional[0]' \"$cfg\"
jq --jsonargs '$ARGS.positional[0]' \"$cfg\"
jq --indent 2 --args '$ARGS.positional[0]' \"$cfg\"
jq --rawfile cfg \"$cfg\" '.dns=$cfg'
jq --slurpfile cfg \"$cfg\" '.dns=$cfg'
jq --argfile cfg \"$cfg\" '.dns=$cfg'
jq -nc '.x=1' \"$cfg\"
jq -Lnewmods '.x=1' \"$cfg\"
";

    with_facts(source, None, |_, facts| {
        let jq_commands = facts
            .structural_commands()
            .filter(|fact| fact.effective_name_is("jq"))
            .collect::<Vec<_>>();

        assert_eq!(
            jq_commands
                .iter()
                .map(|command| {
                    command
                        .file_operand_words()
                        .iter()
                        .map(|word| word.span.slice(source))
                        .collect::<Vec<_>>()
                })
                .collect::<Vec<_>>(),
            vec![
                Vec::<&str>::new(),
                Vec::<&str>::new(),
                Vec::<&str>::new(),
                vec!["\"$cfg\""],
                vec!["\"$cfg\""],
                vec!["\"$cfg\""],
                Vec::<&str>::new(),
                vec!["\"$cfg\""],
            ]
        );
    });
}

#[test]
fn tracks_nested_if_and_elif_conditions_inside_while_conditions() {
    let source = "\
#!/bin/bash
while if \"$( [[ -f if_path ]] )\"; then
  :
elif \"$( [[ -f elif_path ]] )\"; then
  :
fi; do
  :
done
";

    with_facts(source, None, |_, facts| {
        let if_nested = facts
            .commands()
            .iter()
            .find(|fact| fact.span().slice(source) == "[[ -f if_path ]]")
            .expect("expected nested if condition command");
        assert!(if_nested.scope_read_source_words().is_empty());
        assert!(facts.is_if_condition_command(if_nested.id()));
        assert!(!facts.is_elif_condition_command(if_nested.id()));

        let elif_nested = facts
            .commands()
            .iter()
            .find(|fact| fact.span().slice(source) == "[[ -f elif_path ]]")
            .expect("expected nested elif condition command");
        assert!(elif_nested.scope_read_source_words().is_empty());
        assert!(facts.is_elif_condition_command(elif_nested.id()));
    });
}

#[test]
fn tracks_nested_while_and_until_conditions_inside_if_and_elif_conditions() {
    let source = "\
#!/bin/bash
if while [[ -f if_path ]]; do
  :
done; then
  :
elif until [[ -f elif_path ]]; do
  :
done; then
  :
fi
";

    with_facts(source, None, |_, facts| {
        let if_nested = facts
            .commands()
            .iter()
            .find(|fact| fact.span().slice(source) == "[[ -f if_path ]]")
            .expect("expected nested while condition command");
        assert!(if_nested.scope_read_source_words().is_empty());
        assert!(facts.is_if_condition_command(if_nested.id()));
        assert!(!facts.is_elif_condition_command(if_nested.id()));

        let elif_nested = facts
            .commands()
            .iter()
            .find(|fact| fact.span().slice(source) == "[[ -f elif_path ]]")
            .expect("expected nested until condition command");
        assert!(elif_nested.scope_read_source_words().is_empty());
        assert!(facts.is_if_condition_command(elif_nested.id()));
        assert!(facts.is_elif_condition_command(elif_nested.id()));
    });
}

#[test]
fn preserves_condition_related_span_outputs() {
    let source = "\
#!/bin/bash
if [[ -f foo ]]; then
  echo $?
elif [[ -f bar ]]; then
  echo $?
elif [ $? -eq 1 ]; then
  :
fi
while test -f baz; do
  echo $?
done
if [[ -n $mode ]]; then
  case $mode in
    foo) tend $? ;;
  esac
fi
$(printf top)
! $(printf negated)
$(printf short-circuit) && echo ok
if $(printf one); then
  :
fi
if $(command -v printf) --version >/dev/null 2>&1; then
  :
fi
while $(printf two); do
  :
done
until $(command -v printf) --help >/dev/null 2>&1; do
  break
done
";

    with_facts(source, None, |_, facts| {
        assert_eq!(
            facts
                .command_substitution_command_spans()
                .iter()
                .map(|span| span.slice(source))
                .collect::<Vec<_>>(),
            vec![
                "$(printf top)",
                "$(printf negated)",
                "$(printf short-circuit)",
                "$(printf one)",
                "$(printf two)"
            ]
        );
        assert_eq!(
            facts
                .condition_status_capture_spans()
                .iter()
                .map(|span| span.slice(source))
                .collect::<Vec<_>>(),
            vec!["$?", "$?", "$?", "$?", "$?"]
        );
    });
}

#[test]
fn collects_c107_status_checks_in_reportable_test_contexts() {
    let source = "\
#!/bin/bash
run
if [ $? -ne 0 ]; then :; fi
[ $? -ne 0 ]
run && [ $? -eq 0 ]
run || [ $? -ne 0 ]
if (( $? != 0 )); then :; fi
while [[ $? -ne 0 ]]; do break; done
";

    with_facts(source, None, |_, facts| {
        assert_eq!(
            facts
                .dollar_question_after_command_spans()
                .iter()
                .map(|span| span.slice(source))
                .collect::<Vec<_>>(),
            vec!["$?", "$?", "$?", "$?", "$?", "$?"]
        );
    });
}

#[test]
fn collects_c056_status_reads_after_sequential_test_statements() {
    let source = "\
#!/bin/bash
[[ \"${second_line}\" == \"quz\" ]];
tend $?
[[ ${s0} == \"${s2}\" ]] &&
[[ ${s1} != *f* ]]
tend $?
[[ \"${later}\" == \"ok\" ]]
if [ -f foo ]; then :; fi
saved=$?
while [ -f foo ]; do break; done
again=$?
";

    with_facts(source, None, |_, facts| {
        assert_eq!(
            facts
                .condition_status_capture_spans()
                .iter()
                .map(|span| span.slice(source))
                .collect::<Vec<_>>(),
            vec!["$?", "$?"]
        );
    });
}

#[test]
fn keeps_c056_off_one_off_test_followups_without_later_test_blocks() {
    let source = "\
#!/bin/bash
[[ \"${second_line}\" == \"quz\" ]]
tend $?
nextcmd
";

    with_facts(source, None, |_, facts| {
        assert!(
            facts.condition_status_capture_spans().is_empty(),
            "expected no C056 spans for one-off sequential test followup"
        );
    });
}

#[test]
fn collects_c056_when_later_loop_conditions_continue_testing() {
    let source = "\
#!/bin/bash
[ -f first ]
tend $?
while [ -f loop_one ]; do
  :
done
[ -f second ]
tend $?
until [ -f loop_two ]; do
  break
done
";

    with_facts(source, None, |_, facts| {
        assert_eq!(
            facts
                .condition_status_capture_spans()
                .iter()
                .map(|span| span.slice(source))
                .collect::<Vec<_>>(),
            vec!["$?", "$?"]
        );
    });
}

#[test]
fn collects_c056_when_later_if_conditions_continue_testing() {
    let source = "\
#!/bin/bash
[ -f first ]
tend $?
if [ -f later_if ]; then
  :
elif [ -f later_elif ]; then
  :
fi
";

    with_facts(source, None, |_, facts| {
        assert_eq!(
            facts
                .condition_status_capture_spans()
                .iter()
                .map(|span| span.slice(source))
                .collect::<Vec<_>>(),
            vec!["$?"]
        );
    });
}

#[test]
fn collects_c056_inside_function_body_sequences() {
    let source = "\
#!/bin/bash
helper() {
  [ -f first ]
  tend $?
  [ -f second ]
}
";

    with_facts(source, None, |_, facts| {
        assert_eq!(
            facts
                .condition_status_capture_spans()
                .iter()
                .map(|span| span.slice(source))
                .collect::<Vec<_>>(),
            vec!["$?"]
        );
    });
}

#[test]
fn collects_c056_for_complex_status_blocks_but_skips_late_repeats() {
    let source = "\
#!/bin/bash
tbegin one
A=a B=b C=c
evar_push A B C
pu=$?
A=A B=B C=C
evar_pop 1
po1=$?
[[ ${A}${B}${C} == \"ABc\" ]]
po2=$?
evar_pop 2
po3=$?
var=$(bash -c 'echo ${VAR+set}')
[[ ${pu}${po1}${po2}${po3}${A}${B}${C} == \"0000abc\" ]]
tend $?

tbegin two
VAR=1
evar_push_set VAR 2
pu=$?
[[ ${VAR} == \"2\" ]]
po1=$?
evar_pop
po2=$?
[[ ${pu}${po1}${po2}${VAR} == \"0001\" ]]
tend $?
";

    with_facts(source, None, |_, facts| {
        assert_eq!(
            facts
                .condition_status_capture_spans()
                .iter()
                .map(|span| span.slice(source))
                .collect::<Vec<_>>(),
            vec!["$?"]
        );
    });
}

#[test]
fn collects_c056_for_shellspec_style_followup_chains_when_sibling_groups_continue_testing() {
    let source = "\
#!/bin/bash
(
  [ \"$line\" = ok ]
  [ $? -eq 0 ] && no_problem || affect
)

(
  [ \"$other\" = ok ]
  :
)
";

    with_facts(source, None, |_, facts| {
        assert_eq!(
            facts
                .condition_status_capture_spans()
                .iter()
                .map(|span| span.slice(source))
                .collect::<Vec<_>>(),
            vec!["$?"]
        );
    });
}

#[test]
fn keeps_c107_off_plain_function_entry_checks() {
    let source = "\
#!/bin/bash
check_status() {
  if [ $? -ne 0 ]; then :; fi
  [ $? -ne 0 ]
  run && [ $? -ne 0 ]
}
";

    with_facts(source, None, |_, facts| {
        assert_eq!(
            facts
                .dollar_question_after_command_spans()
                .iter()
                .map(|span| span.slice(source))
                .collect::<Vec<_>>(),
            vec!["$?", "$?"]
        );
    });
}

#[test]
fn keeps_getopts_case_facts_when_loop_body_has_nested_command_content() {
    let source = "\
#!/bin/bash
while getopts 'ab' opt; do
  echo \"$(printf warmup)\"
  case \"$opt\" in
    a)
      ;;
    b)
      echo \"$(printf body)\"
      ;;
  esac
done
";

    with_facts(source, None, |_, facts| {
        let [case] = facts.getopts_cases() else {
            panic!("expected one getopts case fact");
        };

        assert_eq!(
            case.case_span().slice(source),
            "case \"$opt\" in\n    a)\n      ;;\n    b)\n      echo \"$(printf body)\"\n      ;;\n  esac"
        );
        assert_eq!(
            case.handled_case_labels()
                .iter()
                .map(|label| label.label())
                .collect::<Vec<_>>(),
            vec!['a', 'b']
        );
        assert!(case.missing_options().is_empty());
    });
}

#[test]
fn records_invalid_flag_handler_coverage_for_getopts_cases() {
    let source = "\
#!/bin/sh
while getopts 'a' opt; do
  case \"$opt\" in
    a) : ;;
  esac
done

while getopts 'a' opt; do
  case \"$opt\" in
    a) : ;;
    \\?) : ;;
  esac
done

while getopts 'a' opt; do
  case \"$opt\" in
    a) : ;;
    *) : ;;
  esac
done

while getopts 'ab' opt; do
  case \"$opt\" in
    [ab]) : ;;
  esac
done

while getopts ':a' opt; do
  case \"$opt\" in
    a) : ;;
    :) : ;;
  esac
done
";

    with_facts(source, None, |_, facts| {
        let cases = facts.getopts_cases();
        assert_eq!(cases.len(), 5);
        assert!(cases[0].missing_invalid_flag_handler());
        assert!(!cases[1].missing_invalid_flag_handler());
        assert!(!cases[2].missing_invalid_flag_handler());
        assert!(cases[3].has_unknown_coverage());
        assert!(!cases[3].missing_invalid_flag_handler());
        assert!(cases[4].missing_invalid_flag_handler());
    });
}