rable 0.1.3

A Rust implementation of the Parable bash parser — complete GNU Bash 5.3-compatible parsing with Python bindings
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
pub(crate) mod ansi_c;
pub(crate) mod word;

use std::fmt;

use crate::ast::{CasePattern, Node};

/// Dispatch formatting to type-specific helpers, keeping the match arms short.
#[allow(clippy::too_many_lines, clippy::match_same_arms)]
impl fmt::Display for Node {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Word { value, .. } => {
                write!(f, "(word \"")?;
                word::write_word_value(f, value)?;
                write!(f, "\")")
            }
            Self::Command { words, redirects } => write_spaced(f, "(command", words, redirects),
            Self::Pipeline { commands } => write_pipeline(f, commands),
            Self::List { parts } => write_list(f, parts),
            Self::Operator { op } => write!(f, "{}", operator_name(op)),
            Self::Empty | Self::PipeBoth => Ok(()),
            Self::Comment { text } => write!(f, "(comment \"{text}\")"),

            // Compound commands
            Self::If {
                condition,
                then_body,
                else_body,
                redirects,
            } => {
                write!(f, "(if {condition} {then_body}")?;
                write_optional(f, else_body.as_deref())?;
                write!(f, ")")?;
                write_redirects(f, redirects)
            }
            Self::While {
                condition,
                body,
                redirects,
            } => {
                write!(f, "(while {condition} {body})")?;
                write_redirects(f, redirects)
            }
            Self::Until {
                condition,
                body,
                redirects,
            } => {
                write!(f, "(until {condition} {body})")?;
                write_redirects(f, redirects)
            }
            Self::For {
                var,
                words,
                body,
                redirects,
            } => {
                write!(f, "(for (word \"{var}\")")?;
                write_in_list(f, words.as_deref())?;
                write!(f, " {body})")?;
                write_redirects(f, redirects)
            }
            Self::ForArith {
                init,
                cond,
                incr,
                body,
                redirects,
            } => {
                write!(f, "(arith-for")?;
                write!(f, " (init (word \"{init}\"))")?;
                write!(f, " (test (word \"{cond}\"))")?;
                write!(f, " (step (word \"{incr}\"))")?;
                write!(f, " {body})")?;
                write_redirects(f, redirects)
            }
            Self::Select {
                var,
                words,
                body,
                redirects,
            } => {
                write!(f, "(select (word \"{var}\")")?;
                write_in_list(f, words.as_deref())?;
                write!(f, " {body})")?;
                write_redirects(f, redirects)
            }
            Self::Case {
                word,
                patterns,
                redirects,
            } => {
                write!(f, "(case {word}")?;
                for p in patterns {
                    write!(f, " {p}")?;
                }
                write!(f, ")")?;
                write_redirects(f, redirects)
            }
            Self::Function { name, body } => write!(f, "(function \"{name}\" {body})"),
            Self::Subshell { body, redirects } => {
                write!(f, "(subshell {body})")?;
                write_redirects(f, redirects)
            }
            Self::BraceGroup { body, redirects } => {
                write!(f, "(brace-group {body})")?;
                write_redirects(f, redirects)
            }
            Self::Coproc { name, command } => {
                let n = name.as_deref().unwrap_or("COPROC");
                write!(f, "(coproc \"{n}\" {command})")
            }

            // Redirections
            Self::Redirect { op, target, fd } => write_redirect(f, op, target, *fd),
            Self::HereDoc {
                content,
                strip_tabs,
                ..
            } => {
                let op = if *strip_tabs { "<<-" } else { "<<" };
                // Here-doc content uses literal newlines, not \\n
                write!(f, "(redirect \"{op}\" \"{content}\")")
            }

            // Expansions
            Self::ParamExpansion { param, op, arg } => {
                write_param(f, "${{", param, op.as_deref(), arg.as_deref())
            }
            Self::ParamLength { param } => write!(f, "${{#{param}}}"),
            Self::ParamIndirect { param, op, arg } => {
                write_param(f, "${{!", param, op.as_deref(), arg.as_deref())
            }
            Self::CommandSubstitution { command, brace } => {
                let tag = if *brace { "cmdsub-brace" } else { "cmdsub" };
                write!(f, "({tag} {command})")
            }
            Self::ProcessSubstitution { direction, command } => {
                write!(f, "(procsub {direction} {command})")
            }
            Self::AnsiCQuote { content } => write!(f, "$'{content}'"),
            Self::LocaleString { content } => write!(f, "$\"{content}\""),
            Self::ArithmeticExpansion { expression } => {
                write_arith_wrapper(f, "arith", expression.as_deref())
            }
            Self::ArithmeticCommand {
                redirects,
                raw_content,
                ..
            } => {
                if raw_content.is_empty() {
                    write!(f, "(arith (word \"\"))")?;
                } else {
                    write!(f, "(arith (word \"{raw_content}\"))")?;
                }
                write_redirects(f, redirects)
            }

            // Arithmetic nodes
            Self::ArithNumber { value } => write!(f, "{value}"),
            Self::ArithVar { name } => write!(f, "{name}"),
            Self::ArithBinaryOp { op, left, right } => write!(f, "({op} {left} {right})"),
            Self::ArithUnaryOp { op, operand } => write!(f, "({op} {operand})"),
            Self::ArithPreIncr { operand } => write!(f, "(pre++ {operand})"),
            Self::ArithPostIncr { operand } => write!(f, "(post++ {operand})"),
            Self::ArithPreDecr { operand } => write!(f, "(pre-- {operand})"),
            Self::ArithPostDecr { operand } => write!(f, "(post-- {operand})"),
            Self::ArithAssign { op, target, value } => write!(f, "({op} {target} {value})"),
            Self::ArithTernary {
                condition,
                if_true,
                if_false,
            } => {
                write!(f, "(? {condition}")?;
                write_optional(f, if_true.as_deref())?;
                write_optional(f, if_false.as_deref())?;
                write!(f, ")")
            }
            Self::ArithComma { left, right } => write!(f, "(, {left} {right})"),
            Self::ArithSubscript { array, index } => write!(f, "(subscript {array} {index})"),
            Self::ArithEmpty => write!(f, "(empty)"),
            Self::ArithEscape { ch } => write!(f, "(escape {ch})"),
            Self::ArithDeprecated { expression } => write!(f, "(arith-deprecated {expression})"),
            Self::ArithConcat { parts } => write_tagged_list(f, "concat", parts),

            // Conditional expressions
            Self::ConditionalExpr { body, redirects } => {
                write!(f, "(cond {body})")?;
                write_redirects(f, redirects)
            }
            Self::CondTerm { value } => {
                // Strip $" locale prefix
                let val = if value.starts_with("$\"") {
                    &value[1..]
                } else {
                    value
                };
                // Process cmdsubs within the value (for redirect normalization)
                // but write other content raw (no escaping — cond-terms use raw values)
                if val.contains("$(") {
                    write!(f, "(cond-term \"")?;
                    let segments = word::parse_word_segments(val);
                    for seg in &segments {
                        match seg {
                            word::WordSegment::Literal(text) => write!(f, "{text}")?,
                            word::WordSegment::CommandSubstitution(content) => {
                                write!(f, "$(")?;
                                if let Some(reformatted) = crate::format::reformat_bash(content) {
                                    write!(f, "{reformatted}")?;
                                } else {
                                    let normalized = normalize_cmdsub_content(content);
                                    write!(f, "{normalized}")?;
                                }
                                write!(f, ")")?;
                            }
                            _ => write!(f, "{seg:?}")?,
                        }
                    }
                    write!(f, "\")")
                } else {
                    write!(f, "(cond-term \"{val}\")")
                }
            }
            Self::UnaryTest { op, operand } => {
                write!(f, "(cond-unary \"{op}\" {operand})")
            }
            Self::BinaryTest { op, left, right } => {
                write!(f, "(cond-binary \"{op}\" {left} {right})")
            }
            Self::CondAnd { left, right } => write!(f, "(cond-and {left} {right})"),
            Self::CondOr { left, right } => write!(f, "(cond-or {left} {right})"),
            // Parable drops negation in S-expression output — unwrap CondNot
            Self::CondNot { operand } => write!(f, "{operand}"),
            Self::CondParen { inner } => write!(f, "(cond-expr {inner})"),

            // Other
            Self::Negation { pipeline } => write!(f, "(negation {pipeline})"),
            Self::Time { pipeline, posix } => {
                if *posix {
                    write!(f, "(time -p {pipeline})")
                } else {
                    write!(f, "(time {pipeline})")
                }
            }
            Self::Array { elements } => write_tagged_list(f, "array", elements),
        }
    }
}

impl fmt::Display for CasePattern {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "(pattern (")?;
        for (i, p) in self.patterns.iter().enumerate() {
            if i > 0 {
                write!(f, " ")?;
            }
            write!(f, "{p}")?;
        }
        write!(f, ")")?;
        match &self.body {
            Some(body) => write!(f, " {body}")?,
            None => write!(f, " ()")?,
        }
        write!(f, ")")
    }
}

// --- helpers ---

// Old write_word_value replaced by word::write_word_value (segment-based)

/// Extracts content from matched parentheses (for command substitution).
/// Case-aware: `)` in case patterns doesn't close the substitution.
#[allow(clippy::too_many_lines)]
pub(super) fn extract_paren_content(chars: &[char], pos: &mut usize) -> String {
    let mut content = String::new();
    let mut depth = 1;
    let mut case_depth = 0usize;
    let mut in_case_pattern = false;
    let mut word_buf = String::new();

    while *pos < chars.len() {
        let c = chars[*pos];
        // Handle backslash-escaped characters
        if c == '\\' && *pos + 1 < chars.len() {
            word_buf.clear();
            content.push(c);
            *pos += 1;
            content.push(chars[*pos]);
            *pos += 1;
            continue;
        }
        if c == '(' {
            check_case_kw(&word_buf, &mut case_depth, &mut in_case_pattern);
            word_buf.clear();
            // In case pattern mode, `(` is optional pattern prefix — don't increment depth
            if !(case_depth > 0 && in_case_pattern) {
                depth += 1;
            }
            content.push(c);
        } else if c == ')' {
            check_case_kw(&word_buf, &mut case_depth, &mut in_case_pattern);
            word_buf.clear();
            if case_depth > 0 && in_case_pattern {
                // Case pattern terminator — don't close
                content.push(c);
                in_case_pattern = false;
            } else {
                depth -= 1;
                if depth == 0 {
                    *pos += 1;
                    return content;
                }
                content.push(c);
            }
        } else if c == '\'' {
            check_case_kw(&word_buf, &mut case_depth, &mut in_case_pattern);
            word_buf.clear();
            content.push(c);
            *pos += 1;
            while *pos < chars.len() && chars[*pos] != '\'' {
                content.push(chars[*pos]);
                *pos += 1;
            }
            if *pos < chars.len() {
                content.push(chars[*pos]); // closing '
            }
        } else if c == '"' {
            check_case_kw(&word_buf, &mut case_depth, &mut in_case_pattern);
            word_buf.clear();
            content.push(c);
            *pos += 1;
            while *pos < chars.len() && chars[*pos] != '"' {
                content.push(chars[*pos]);
                if chars[*pos] == '\\' && *pos + 1 < chars.len() {
                    *pos += 1;
                    content.push(chars[*pos]);
                }
                *pos += 1;
            }
            if *pos < chars.len() {
                content.push(chars[*pos]); // closing "
            }
        } else if c == ';' {
            check_case_kw(&word_buf, &mut case_depth, &mut in_case_pattern);
            word_buf.clear();
            content.push(c);
            // Check for ;; ;& ;;& which resume case pattern mode
            if case_depth > 0 && *pos + 1 < chars.len() {
                if chars[*pos + 1] == ';' {
                    *pos += 1;
                    content.push(chars[*pos]);
                    if *pos + 1 < chars.len() && chars[*pos + 1] == '&' {
                        *pos += 1;
                        content.push(chars[*pos]);
                    }
                    in_case_pattern = true;
                } else if chars[*pos + 1] == '&' {
                    *pos += 1;
                    content.push(chars[*pos]);
                    in_case_pattern = true;
                }
            }
        } else if c == ' ' || c == '\t' || c == '\n' || c == '|' {
            check_case_kw(&word_buf, &mut case_depth, &mut in_case_pattern);
            word_buf.clear();
            content.push(c);
        } else {
            word_buf.push(c);
            content.push(c);
        }
        *pos += 1;
    }
    content
}

/// Checks case-related keywords for `extract_paren_content`.
fn check_case_kw(word: &str, case_depth: &mut usize, in_pattern: &mut bool) {
    match word {
        "case" => *case_depth += 1,
        "in" if *case_depth > 0 => *in_pattern = true,
        "esac" if *case_depth > 0 => {
            *case_depth -= 1;
            if *case_depth == 0 {
                *in_pattern = false;
            }
        }
        _ => {}
    }
}

/// Normalizes command substitution content:
/// - Strips leading/trailing whitespace and newlines
/// - Strips trailing semicolons
/// - Adds space after `<` for file reading shortcuts
pub(super) fn normalize_cmdsub_content(content: &str) -> String {
    let trimmed = content.trim();
    let stripped = trimmed.strip_suffix(';').unwrap_or(trimmed).trim_end();
    // Normalize $(<file) to $(< file)
    if let Some(rest) = stripped.strip_prefix('<')
        && !rest.starts_with(['<', ' '])
    {
        return format!("< {rest}");
    }
    stripped.to_string()
}

/// Process ANSI-C escape sequences inside `$'...'`.
/// `chars` is the full character array, `pos` points to the first char after `$'`.
/// Returns the processed content (without surrounding quotes).
/// Advances `pos` past the closing `'`.
#[allow(clippy::too_many_lines)]
pub(crate) fn process_ansi_c_content(chars: &[char], pos: &mut usize) -> String {
    let mut out = String::new();
    while *pos < chars.len() {
        let c = chars[*pos];
        if c == '\'' {
            *pos += 1; // skip closing '
            return out;
        }
        if c == '\\' && *pos + 1 < chars.len() {
            *pos += 1;
            let esc = chars[*pos];
            *pos += 1;
            match esc {
                'n' => out.push('\n'),
                't' => out.push('\t'),
                'r' => out.push('\r'),
                'a' => out.push('\x07'),
                'b' => out.push('\x08'),
                'f' => out.push('\x0C'),
                'v' => out.push('\x0B'),
                'e' | 'E' => out.push('\x1B'),
                '\\' => out.push('\\'),
                'c' => {
                    // Control character: \cX → chr(X & 0x1F)
                    if *pos < chars.len() {
                        let ctrl = chars[*pos];
                        *pos += 1;
                        let val = (ctrl as u32) & 0x1F;
                        if val > 0
                            && let Some(ch) = char::from_u32(val)
                        {
                            out.push(ch);
                        }
                        // \c@ or val==0 → NUL, which is dropped
                    }
                }
                '\'' => {
                    // Escaped single quote: output as '\\''
                    out.push('\'');
                    out.push('\\');
                    out.push('\'');
                    out.push('\'');
                    return process_ansi_c_continue(chars, pos, out);
                }
                '"' => out.push('"'),
                'x' => {
                    // Hex escape: \xNN — NUL is dropped
                    let hex = read_hex(chars, pos, 2);
                    if hex > 0
                        && let Some(ch) = char::from_u32(hex)
                    {
                        out.push(ch);
                    }
                }
                'u' => {
                    // Unicode: \uNNNN
                    let val = read_hex(chars, pos, 4);
                    if let Some(ch) = char::from_u32(val) {
                        out.push(ch);
                    }
                }
                'U' => {
                    // Unicode long: \UNNNNNNNN
                    let val = read_hex(chars, pos, 8);
                    if let Some(ch) = char::from_u32(val) {
                        out.push(ch);
                    }
                }
                '0'..='7' => {
                    // Octal escape — NUL is dropped
                    let mut val = u32::from(esc as u8 - b'0');
                    for _ in 0..2 {
                        if *pos < chars.len() && chars[*pos] >= '0' && chars[*pos] <= '7' {
                            val = val * 8 + u32::from(chars[*pos] as u8 - b'0');
                            *pos += 1;
                        }
                    }
                    if val > 0
                        && let Some(ch) = char::from_u32(val)
                    {
                        out.push(ch);
                    }
                }
                _ => {
                    out.push('\\');
                    out.push(esc);
                }
            }
        } else {
            out.push(c);
            *pos += 1;
        }
    }
    out
}

/// Continue processing after an escaped quote split.
fn process_ansi_c_continue(chars: &[char], pos: &mut usize, mut out: String) -> String {
    // After \' we output '\\'' and need to continue in a new quote context
    out.push_str(&process_ansi_c_content(chars, pos));
    out
}

/// Read up to `max` hex digits from chars at pos.
fn read_hex(chars: &[char], pos: &mut usize, max: usize) -> u32 {
    let mut val = 0u32;
    for _ in 0..max {
        if *pos < chars.len() && chars[*pos].is_ascii_hexdigit() {
            val = val * 16 + chars[*pos].to_digit(16).unwrap_or(0);
            *pos += 1;
        } else {
            break;
        }
    }
    val
}

fn operator_name(op: &str) -> &str {
    match op {
        "&&" => "and",
        "||" => "or",
        ";" | "\n" => "semi",
        "&" => "background",
        "|" => "pipe",
        other => other,
    }
}

/// Writes a single character with S-expression escaping.
pub(super) fn write_escaped_char(f: &mut fmt::Formatter<'_>, ch: char) -> fmt::Result {
    match ch {
        '"' => write!(f, "\\\""),
        '\\' => write!(f, "\\\\"),
        '\n' => write!(f, "\\n"),
        '\t' => write!(f, "\\t"),
        _ => write!(f, "{ch}"),
    }
}

/// Writes a word value with proper escaping for S-expression output.
pub(super) fn write_escaped_word(f: &mut fmt::Formatter<'_>, value: &str) -> fmt::Result {
    for ch in value.chars() {
        match ch {
            '"' => write!(f, "\\\"")?,
            '\\' => write!(f, "\\\\")?,
            '\n' => write!(f, "\\n")?,
            '\t' => write!(f, "\\t")?,
            _ => write!(f, "{ch}")?,
        }
    }
    Ok(())
}

fn write_optional(f: &mut fmt::Formatter<'_>, node: Option<&Node>) -> fmt::Result {
    if let Some(n) = node {
        write!(f, " {n}")?;
    }
    Ok(())
}

fn write_redirects(f: &mut fmt::Formatter<'_>, redirects: &[Node]) -> fmt::Result {
    for r in redirects {
        write!(f, " {r}")?;
    }
    Ok(())
}

fn write_spaced(
    f: &mut fmt::Formatter<'_>,
    tag: &str,
    first: &[Node],
    second: &[Node],
) -> fmt::Result {
    write!(f, "{tag}")?;
    for n in first {
        write!(f, " {n}")?;
    }
    for n in second {
        write!(f, " {n}")?;
    }
    write!(f, ")")
}

fn write_tagged_list(f: &mut fmt::Formatter<'_>, tag: &str, items: &[Node]) -> fmt::Result {
    write!(f, "({tag}")?;
    for n in items {
        write!(f, " {n}")?;
    }
    write!(f, ")")
}

/// Pipelines are right-nested: `(pipe a (pipe b c))`.
fn write_pipeline(f: &mut fmt::Formatter<'_>, commands: &[Node]) -> fmt::Result {
    let filtered: Vec<_> = commands
        .iter()
        .filter(|c| !matches!(c, Node::PipeBoth))
        .collect();
    if filtered.len() == 1 {
        return write!(f, "{}", filtered[0]);
    }
    // Group commands with their trailing redirects
    let mut groups: Vec<Vec<&Node>> = Vec::new();
    for cmd in &filtered {
        if matches!(cmd, Node::Redirect { .. }) {
            // Attach redirect to the previous group
            if let Some(last) = groups.last_mut() {
                last.push(cmd);
            } else {
                groups.push(vec![cmd]);
            }
        } else {
            groups.push(vec![cmd]);
        }
    }
    write_pipeline_groups(f, &groups, 0)
}

fn write_pipeline_groups(
    f: &mut fmt::Formatter<'_>,
    groups: &[Vec<&Node>],
    idx: usize,
) -> fmt::Result {
    if idx >= groups.len() {
        return Ok(());
    }
    if idx == groups.len() - 1 {
        // Last group: write all elements
        for (j, node) in groups[idx].iter().enumerate() {
            if j > 0 {
                write!(f, " ")?;
            }
            write!(f, "{node}")?;
        }
        return Ok(());
    }
    write!(f, "(pipe ")?;
    for (j, node) in groups[idx].iter().enumerate() {
        if j > 0 {
            write!(f, " ")?;
        }
        write!(f, "{node}")?;
    }
    write!(f, " ")?;
    write_pipeline_groups(f, groups, idx + 1)?;
    write!(f, ")")
}

/// Lists use left-associative nesting: `(and (and a b) c)`.
fn write_list(f: &mut fmt::Formatter<'_>, parts: &[Node]) -> fmt::Result {
    if parts.len() == 1 {
        return write!(f, "{}", parts[0]);
    }
    let mut items: Vec<&Node> = Vec::new();
    let mut ops: Vec<&str> = Vec::new();
    for part in parts {
        if let Node::Operator { op } = part {
            ops.push(op);
        } else {
            items.push(part);
        }
    }
    if items.len() == 1 && ops.is_empty() {
        return write!(f, "{}", items[0]);
    }
    // Left-associative: build from left to right
    write_list_left_assoc(f, &items, &ops)
}

fn write_list_left_assoc(f: &mut fmt::Formatter<'_>, items: &[&Node], ops: &[&str]) -> fmt::Result {
    // Handle trailing unary operator (e.g., "cmd &" → "(background cmd)")
    if items.len() == 1 && ops.len() == 1 {
        let sexp_op = operator_name(ops[0]);
        return write!(f, "({sexp_op} {})", items[0]);
    }
    if items.len() <= 1 && ops.is_empty() {
        if let Some(item) = items.first() {
            return write!(f, "{item}");
        }
        return Ok(());
    }

    // For a trailing background operator with no RHS
    if items.len() == ops.len() {
        // Last op is trailing (e.g., "cmd &")
        let sexp_op = operator_name(ops[ops.len() - 1]);
        write!(f, "({sexp_op} ")?;
        write_list_left_assoc(f, &items[..items.len()], &ops[..ops.len() - 1])?;
        return write!(f, ")");
    }

    // Write left-associatively: ((op1 a b) op2 c) op3 d) ...
    // Open all the parens first, then close them
    for i in (1..ops.len()).rev() {
        write!(f, "({} ", operator_name(ops[i]))?;
    }
    write!(f, "({} {} {})", operator_name(ops[0]), items[0], items[1])?;
    for i in 1..ops.len() {
        write!(f, " {})", items[i + 1])?;
    }
    Ok(())
}

/// Writes a word list wrapped in `(in ...)` for `for`/`select` statements.
fn write_in_list(f: &mut fmt::Formatter<'_>, words: Option<&[Node]>) -> fmt::Result {
    if let Some(ws) = words {
        write!(f, " (in")?;
        for w in ws {
            write!(f, " {w}")?;
        }
        write!(f, ")")?;
    }
    Ok(())
}

fn write_redirect(f: &mut fmt::Formatter<'_>, op: &str, target: &Node, _fd: i32) -> fmt::Result {
    write!(f, "(redirect \"{op}\" ")?;
    if let Node::Word { value, .. } = target {
        // For fd operations (>&, <&, >&-, <&-), output bare number
        let is_fd_op =
            op.starts_with(">&") || op.starts_with("<&") || op.ends_with("&-") || op.ends_with('&');
        if is_fd_op && value.chars().all(|c| c.is_ascii_digit() || c == '-') {
            write!(f, "{value})")
        } else if value.starts_with("$\"") {
            // Locale string in redirect: strip $ prefix, preserve literal quotes
            write!(f, "\"{}\")", &value[1..])
        } else if value.starts_with("$'") {
            // ANSI-C in redirect: process escapes, output with literal newlines
            let chars: Vec<char> = value.chars().collect();
            let mut pos = 2; // skip $'
            let processed = process_ansi_c_content(&chars, &mut pos);
            write!(f, "\"'{processed}'\")")
        } else if value.starts_with("<(") || value.starts_with(">(") {
            // Process substitution in redirect target: use word value processing
            write!(f, "\"")?;
            word::write_word_value(f, value)?;
            write!(f, "\")")
        } else {
            write!(f, "\"{value}\")")
        }
    } else {
        write!(f, "{target})")
    }
}

fn write_param(
    f: &mut fmt::Formatter<'_>,
    prefix: &str,
    param: &str,
    op: Option<&str>,
    arg: Option<&str>,
) -> fmt::Result {
    if op.is_some() || arg.is_some() {
        write!(f, "{prefix}{param}")?;
        if let Some(o) = op {
            write!(f, "{o}")?;
        }
        if let Some(a) = arg {
            write!(f, "{a}")?;
        }
        write!(f, "}}")
    } else {
        write!(f, "${param}")
    }
}

fn write_arith_wrapper(
    f: &mut fmt::Formatter<'_>,
    tag: &str,
    expression: Option<&Node>,
) -> fmt::Result {
    write!(f, "({tag}")?;
    if let Some(expr) = expression {
        write!(f, " {expr}")?;
    }
    write!(f, ")")
}