Skip to main content

kaish_kernel/
parser.rs

1//! Parser for kaish source code.
2//!
3//! Transforms a token stream from the lexer into an Abstract Syntax Tree.
4//! Uses chumsky for parser combinators with good error recovery.
5
6use crate::ast::{
7    Arg, Assignment, BinaryOp, CaseBranch, CaseStmt, Command, Expr, FileTestOp, ForLoop, IfStmt,
8    ListElem, Pipeline, Program, RecordEntry, RecordKey, Redirect, RedirectKind, SpannedPart, Stmt,
9    StringPart, StringTestOp, TestCmpOp, TestExpr, ToolDef, Value, VarPath, VarSegment, WhileLoop,
10};
11use crate::lexer::{self, HereDocData, Token};
12use chumsky::{input::ValueInput, prelude::*};
13
14/// Span type used throughout the parser.
15pub type Span = SimpleSpan;
16
17/// Parse a raw `${...}` string into an Expr.
18///
19/// Handles:
20/// - Special variables: `${?}` → LastExitCode, `${$}` → CurrentPid
21/// - Simple paths: `${VAR}`, `${VAR.field}`, `${VAR[0]}` → VarRef
22/// - Default values: `${VAR:-default}` → VarWithDefault (with nested expansion support)
23fn parse_var_expr(raw: &str) -> Expr {
24    // Special case: ${?} is the last exit code (same as $?)
25    if raw == "${?}" {
26        return Expr::LastExitCode;
27    }
28
29    // Special case: ${$} is the current PID (same as $$)
30    if raw == "${$}" {
31        return Expr::CurrentPid;
32    }
33
34    // Check for default value syntax: ${VAR:-default}
35    // Need to find :- that's not inside a nested ${...}
36    if let Some(colon_idx) = find_default_separator(raw) {
37        // Extract the variable path (between ${ and :-) — may carry subscripts.
38        let path = parse_varpath(&format!("${{{}}}", &raw[2..colon_idx]));
39        // Extract default value (between :- and }) and recursively parse it,
40        // after stripping shell quoting from the word (quotes are syntax).
41        let default_str = &raw[colon_idx + 2..raw.len() - 1];
42        // This `${VAR:-WORD}` expr path is infallible; a malformed `$()` inside
43        // the default word stays literal here (rare edge). The common quoted
44        // `"$(…)"` path is the loud one (see `parse_interpolated_string`).
45        let default_word = unquote_default_word(default_str);
46        let default = parse_interpolated_string(&default_word)
47            .unwrap_or_else(|_| vec![StringPart::Literal(default_word.clone())]);
48        return Expr::VarWithDefault { path, default };
49    }
50
51    // Regular variable path
52    Expr::VarRef(parse_varpath(raw))
53}
54
55/// Remove shell quoting from a `${VAR:-WORD}` default word, bash-style, before
56/// the word is parsed for interpolation.
57///
58/// The quotes around a default word are syntax, not data: `${X:-"default"}`
59/// yields `default`, not `"default"`. Double quotes are stripped but `$`-style
60/// interpolation inside them stays active; single quotes are stripped and
61/// suppress interpolation (their `$` becomes a literal, via the lexer's
62/// `__KAISH_ESCAPED_DOLLAR__` marker that `parse_interpolated_string` turns
63/// back into a bare `$`). Unquoted text passes through unchanged.
64///
65/// A backslash-escaped quote unescapes to a bare quote character without
66/// toggling the quote-tracking state, but *which* quote is escapable depends on
67/// context, matching bash (GH #93 item 5): OUTSIDE any quotes both `\"` and
68/// `\'` escape (this is what makes the `'it'\''s'` → `it's` embedding idiom
69/// resolve); INSIDE double quotes only `\"` escapes, since `'` is an ordinary
70/// character there — a backslash before it stays literal (`"a\'b"` → `a\'b`). A
71/// run of backslashes immediately before an escapable quote is judged by parity
72/// (bash pairs them left-to-right): an odd run escapes the quote, an even run
73/// doesn't, and either way the run collapses to half as many literal
74/// backslashes. Backslashes not immediately followed by an escapable quote are
75/// untouched — general backslash-escape processing (`\\`, `\n`, ...) outside
76/// quote-adjacency is out of scope for this function.
77///
78/// Inside a single-quoted region shell rules apply verbatim: it is a LITERAL
79/// span with zero escape processing and zero interpolation. A backslash is a
80/// literal character and a `'` always closes the region (it is never escaped);
81/// only `$` is marked (`__KAISH_ESCAPED_DOLLAR__`) so it can't interpolate
82/// downstream. Only the delimiter quotes themselves are stripped — they are
83/// syntax, not data.
84fn unquote_default_word(word: &str) -> String {
85    let mut out = String::with_capacity(word.len());
86    let mut in_single = false;
87    let mut in_double = false;
88    let chars: Vec<char> = word.chars().collect();
89    let mut i = 0;
90    while i < chars.len() {
91        let ch = chars[i];
92        // Backslash-escape processing applies only OUTSIDE single quotes. In a
93        // single-quoted region a backslash is a literal character (handled by
94        // the `_` arm below) and a `'` always closes the span, per shell rules.
95        if ch == '\\' && !in_single {
96            let run_start = i;
97            while i < chars.len() && chars[i] == '\\' {
98                i += 1;
99            }
100            let run_len = i - run_start;
101            // Inside double quotes only `\"` escapes; `'` is an ordinary
102            // character there, so a preceding backslash stays literal.
103            let next_is_quote =
104                chars.get(i).is_some_and(|c| *c == '"' || (*c == '\'' && !in_double));
105            if next_is_quote {
106                if run_len / 2 > 0 {
107                    out.push_str(&"\\".repeat(run_len / 2));
108                }
109                if run_len % 2 == 1 {
110                    // Odd run: the quote is escaped — literal quote, no
111                    // toggle. Consume it here; the main loop below never
112                    // sees it.
113                    out.push(chars[i]);
114                    i += 1;
115                }
116                // Even run: the quote at chars[i] is unescaped and falls
117                // through to the normal toggle logic on the next iteration.
118            } else {
119                out.push_str(&"\\".repeat(run_len));
120            }
121            continue;
122        }
123        i += 1;
124        match ch {
125            // A quote delimiter toggles its mode and is itself dropped; the
126            // other quote kind is literal data while inside one.
127            '\'' if !in_double => in_single = !in_single,
128            '"' if !in_single => in_double = !in_double,
129            // `$` inside single quotes must not interpolate downstream.
130            '$' if in_single => out.push_str("__KAISH_ESCAPED_DOLLAR__"),
131            _ => out.push(ch),
132        }
133    }
134    out
135}
136
137/// Find the position of :- in a ${VAR:-default} expression, accounting for nested ${...}.
138fn find_default_separator(raw: &str) -> Option<usize> {
139    let bytes = raw.as_bytes();
140    let mut depth = 0;
141    let mut bracket_depth = 0;
142    let mut i = 0;
143
144    while i < bytes.len() {
145        if i + 1 < bytes.len() && bytes[i] == b'$' && bytes[i + 1] == b'{' {
146            depth += 1;
147            i += 2;
148            continue;
149        }
150        if bytes[i] == b'}' && depth > 0 {
151            depth -= 1;
152            i += 1;
153            continue;
154        }
155        // Track `[...]` so a `:-` inside a subscript (e.g. the negative slice end
156        // in `${xs[0:-1]}`) is NOT mistaken for a default separator.
157        if bytes[i] == b'[' {
158            bracket_depth += 1;
159        } else if bytes[i] == b']' && bracket_depth > 0 {
160            bracket_depth -= 1;
161        }
162        // Only find :- at the top level (depth == 1 means we're inside the outer
163        // ${...}) and outside any subscript.
164        if depth == 1
165            && bracket_depth == 0
166            && i + 1 < bytes.len()
167            && bytes[i] == b':'
168            && bytes[i + 1] == b'-'
169        {
170            return Some(i);
171        }
172        i += 1;
173    }
174    None
175}
176
177/// Find the position of :- in variable content (without outer braces), accounting for nested ${...}.
178fn find_default_separator_in_content(content: &str) -> Option<usize> {
179    let bytes = content.as_bytes();
180    let mut depth = 0;
181    let mut bracket_depth = 0;
182    let mut i = 0;
183
184    while i < bytes.len() {
185        if i + 1 < bytes.len() && bytes[i] == b'$' && bytes[i + 1] == b'{' {
186            depth += 1;
187            i += 2;
188            continue;
189        }
190        if bytes[i] == b'}' && depth > 0 {
191            depth -= 1;
192            i += 1;
193            continue;
194        }
195        // Track `[...]` so a `:-` inside a subscript (e.g. the negative slice end
196        // in `${xs[0:-1]}`) is NOT mistaken for a default separator.
197        if bytes[i] == b'[' {
198            bracket_depth += 1;
199        } else if bytes[i] == b']' && bracket_depth > 0 {
200            bracket_depth -= 1;
201        }
202        // Find :- at the top level (depth == 0) and outside any subscript.
203        if depth == 0
204            && bracket_depth == 0
205            && i + 1 < bytes.len()
206            && bytes[i] == b':'
207            && bytes[i + 1] == b'-'
208        {
209            return Some(i);
210        }
211        i += 1;
212    }
213    None
214}
215
216/// Parse a raw `${...}` string into a VarPath.
217///
218/// The first segment is the root variable name; each `[...]` segment the lexer
219/// produced becomes the corresponding subscript (`Index`/`Key`/`Dynamic`/
220/// `Slice`). A dotted segment (`${a.b}`) is kept as a non-root `Field` so
221/// resolution can emit the brackets-only error — the lexer already split it out.
222pub(crate) fn parse_varpath(raw: &str) -> VarPath {
223    let segment_strs = lexer::parse_var_ref(raw).unwrap_or_default();
224    let segments = segment_strs
225        .into_iter()
226        .enumerate()
227        .map(|(i, s)| {
228            if i == 0 {
229                // The root name (or the special `?`).
230                VarSegment::Field(s)
231            } else if let Some(inner) = s.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
232                parse_subscript(inner)
233            } else {
234                // A dotted `.field` — carried through as a Field so resolution
235                // produces the "use ${name[field]}" error (brackets only).
236                VarSegment::Field(s)
237            }
238        })
239        .collect();
240    VarPath { segments }
241}
242
243/// Parse the interior of a `[...]` subscript into a `VarSegment`.
244///
245/// Classification is syntactic (the container's runtime type decides list-vs-
246/// record at resolution): `$var` → dynamic; a quoted string → literal key;
247/// `int:int` (either side optional) → slice; a bare integer → index; anything
248/// else → a literal bareword key.
249fn parse_subscript(inner: &str) -> VarSegment {
250    // Dynamic: `[$var]`.
251    if let Some(var) = inner.strip_prefix('$') {
252        return VarSegment::Dynamic(var.to_string());
253    }
254    // Quoted key: `["weird key"]` or `['weird key']`.
255    if inner.len() >= 2
256        && ((inner.starts_with('"') && inner.ends_with('"'))
257            || (inner.starts_with('\'') && inner.ends_with('\'')))
258    {
259        return VarSegment::Key(inner[1..inner.len() - 1].to_string());
260    }
261    // Slice: `a:b` where each side is empty or a valid integer. A colon that
262    // isn't a numeric slice falls through to a bareword key (`["a:b"]` covers
263    // colon-bearing keys explicitly).
264    if let Some((lhs, rhs)) = inner.split_once(':') {
265        let bound = |s: &str| -> Option<Option<i64>> {
266            if s.is_empty() {
267                Some(None)
268            } else {
269                s.parse::<i64>().ok().map(Some)
270            }
271        };
272        if let (Some(start), Some(end)) = (bound(lhs), bound(rhs)) {
273            return VarSegment::Slice(start, end);
274        }
275    }
276    // Integer index: `[0]`, `[-1]`.
277    if let Ok(i) = inner.parse::<i64>() {
278        return VarSegment::Index(i);
279    }
280    // Bareword literal key: `[name]`, `[content-type]`.
281    VarSegment::Key(inner.to_string())
282}
283
284/// Drop `Stmt::Empty` (bare newlines/semicolons) from a parsed `$()` body so an
285/// empty or whitespace-only substitution collapses to nothing runnable.
286fn strip_empty_stmts(statements: Vec<Stmt>) -> Vec<Stmt> {
287    statements
288        .into_iter()
289        .filter(|s| !matches!(s, Stmt::Empty))
290        .collect()
291}
292
293/// Parse an unquoted heredoc body's interpolation while tracking each part's
294/// byte offset in the source.
295///
296/// `base_offset` is added to every part's offset so callers can attribute
297/// positions to a larger source (e.g., heredoc body inside the original
298/// script). Returns parts in source order with offset+len populated.
299///
300/// **Heredoc-specific behaviour**: per POSIX, unquoted heredoc bodies process
301/// three backslash escapes — `\$` (suppress expansion), `\\` (literal
302/// backslash), and `\<newline>` (line continuation). All other backslashes
303/// are kept verbatim. This differs from [`parse_interpolated_string`], which
304/// is called on double-quoted string content where the lexer has already
305/// processed escapes via `__KAISH_ESCAPED_DOLLAR__`.
306///
307/// This sibling of [`parse_interpolated_string`] duplicates parsing logic
308/// for now; unifying them behind a position-tracking core is a follow-up
309/// cleanup. Behaviour MUST stay aligned for the non-escape paths — bug fixes
310/// for the shared interpolation logic here should land there as well.
311fn parse_interpolated_string_spanned(s: &str, base_offset: usize) -> Vec<SpannedPart> {
312    let s = s.replace("__KAISH_ESCAPED_DOLLAR__", "\x00DOLLAR\x00");
313
314    let chars_vec: Vec<char> = s.chars().collect();
315    let mut i = 0;
316    let mut pos: usize = 0;
317
318    let mut parts: Vec<SpannedPart> = Vec::new();
319    let mut current_text = String::new();
320    let mut current_text_start: usize = pos;
321
322    let push_literal =
323        |current_text: &mut String, start: &mut usize, end: usize, parts: &mut Vec<SpannedPart>| {
324            if !current_text.is_empty() {
325                parts.push(SpannedPart {
326                    part: StringPart::Literal(std::mem::take(current_text)),
327                    offset: base_offset + *start,
328                    len: end - *start,
329                });
330                *start = end;
331            }
332        };
333
334    while i < chars_vec.len() {
335        let ch = chars_vec[i];
336
337        if ch == '\x00' {
338            // Escaped-dollar marker: \x00 DOLLAR \x00 → literal '$'
339            let start = pos;
340            i += 1;
341            pos += 1;
342            let mut marker = String::new();
343            while let Some(&c) = chars_vec.get(i) {
344                if c == '\x00' {
345                    i += 1;
346                    pos += 1;
347                    break;
348                }
349                marker.push(c);
350                i += 1;
351                pos += c.len_utf8();
352            }
353            if marker == "DOLLAR" {
354                if current_text.is_empty() {
355                    current_text_start = start;
356                }
357                current_text.push('$');
358            }
359        } else if ch == '\\' {
360            // POSIX heredoc-body escape processing for unquoted heredocs.
361            // Only `\$`, `\\`, and `\<newline>` are escapes; everything else
362            // keeps the backslash verbatim. Each case advances `pos` by the
363            // bytes consumed from the source so subsequent part offsets stay
364            // anchored to original-source coordinates.
365            let next = chars_vec.get(i + 1).copied();
366            match next {
367                Some('$') => {
368                    if current_text.is_empty() {
369                        current_text_start = pos;
370                    }
371                    current_text.push('$');
372                    i += 2;
373                    pos += 2;
374                }
375                Some('\\') => {
376                    if current_text.is_empty() {
377                        current_text_start = pos;
378                    }
379                    current_text.push('\\');
380                    i += 2;
381                    pos += 2;
382                }
383                Some('\n') => {
384                    // Line continuation: consume both bytes, emit nothing.
385                    // The literal run resumes on the next line.
386                    i += 2;
387                    pos += 2;
388                    if current_text.is_empty() {
389                        current_text_start = pos;
390                    }
391                }
392                Some('\r') => {
393                    // \<CR> or \<CR><LF>: line continuation
394                    i += 2;
395                    pos += 2;
396                    if chars_vec.get(i) == Some(&'\n') {
397                        i += 1;
398                        pos += 1;
399                    }
400                    if current_text.is_empty() {
401                        current_text_start = pos;
402                    }
403                }
404                _ => {
405                    // Other backslash sequences: keep `\` literally,
406                    // consume only the backslash. The next iteration will
407                    // process the following char on its own merits.
408                    if current_text.is_empty() {
409                        current_text_start = pos;
410                    }
411                    current_text.push('\\');
412                    i += 1;
413                    pos += 1;
414                }
415            }
416        } else if ch == '$' {
417            // Possible expansion. Save current run before peeking ahead.
418            let part_start = pos;
419            let next = chars_vec.get(i + 1).copied();
420
421            if next == Some('(') && chars_vec.get(i + 2) != Some(&'(') {
422                // $(...) command substitution
423                push_literal(&mut current_text, &mut current_text_start, pos, &mut parts);
424                i += 2; // consume "$("
425                pos += 2;
426                let mut cmd_content = String::new();
427                let mut depth = 1;
428                while let Some(&c) = chars_vec.get(i) {
429                    i += 1;
430                    pos += c.len_utf8();
431                    if c == '(' {
432                        depth += 1;
433                        cmd_content.push(c);
434                    } else if c == ')' {
435                        depth -= 1;
436                        if depth == 0 {
437                            break;
438                        }
439                        cmd_content.push(c);
440                    } else {
441                        cmd_content.push(c);
442                    }
443                }
444                let inserted = if let Ok(program) = parse(&cmd_content) {
445                    // The full statement block runs as the substitution body
446                    // (pipelines, `&&`/`||`, `;`/newline sequences, comments).
447                    let stmts = strip_empty_stmts(program.statements);
448                    if stmts.is_empty() {
449                        false
450                    } else {
451                        parts.push(SpannedPart {
452                            part: StringPart::CommandSubst(stmts),
453                            offset: base_offset + part_start,
454                            len: pos - part_start,
455                        });
456                        true
457                    }
458                } else {
459                    false
460                };
461                if inserted {
462                    // Successfully pushed a CommandSubst; the next literal
463                    // run will start after the closing ')'.
464                    current_text_start = pos;
465                } else {
466                    // Fall back to literal text. The literal run starts at
467                    // the leading '$' (set above only if current_text was
468                    // empty); leave current_text_start alone otherwise so we
469                    // don't lose an in-progress run.
470                    if current_text.is_empty() {
471                        current_text_start = part_start;
472                    }
473                    current_text.push_str("$(");
474                    current_text.push_str(&cmd_content);
475                    current_text.push(')');
476                }
477            } else if next == Some('{') {
478                push_literal(&mut current_text, &mut current_text_start, pos, &mut parts);
479                i += 2; // consume "${"
480                pos += 2;
481                let mut var_content = String::new();
482                let mut depth = 1;
483                while let Some(&c) = chars_vec.get(i) {
484                    i += 1;
485                    pos += c.len_utf8();
486                    if c == '{' && var_content.ends_with('$') {
487                        depth += 1;
488                        var_content.push(c);
489                    } else if c == '}' {
490                        depth -= 1;
491                        if depth == 0 {
492                            break;
493                        }
494                        var_content.push(c);
495                    } else {
496                        var_content.push(c);
497                    }
498                }
499                let part = if let Some(name) = var_content.strip_prefix('#') {
500                    StringPart::VarLength(parse_varpath(&format!("${{{name}}}")))
501                } else if var_content.starts_with("__ARITH:") && var_content.ends_with("__") {
502                    let expr = var_content
503                        .strip_prefix("__ARITH:")
504                        .and_then(|s| s.strip_suffix("__"))
505                        .unwrap_or("");
506                    StringPart::Arithmetic(expr.to_string())
507                } else if let Some(colon_idx) = find_default_separator_in_content(&var_content) {
508                    let path = parse_varpath(&format!("${{{}}}", &var_content[..colon_idx]));
509                    let default_str = &var_content[colon_idx + 2..];
510                    // Default value spans recursively kept relative to the
511                    // outer body — the inner parts get their own offsets via
512                    // the recursive call when needed. For now, the default's
513                    // parts are stored without spans (default is a Vec<StringPart>).
514                    let default_word = unquote_default_word(default_str);
515                    let default = parse_interpolated_string(&default_word)
516                        .unwrap_or_else(|_| vec![StringPart::Literal(default_word.clone())]);
517                    StringPart::VarWithDefault { path, default }
518                } else {
519                    StringPart::Var(parse_varpath(&format!("${{{}}}", var_content)))
520                };
521                parts.push(SpannedPart {
522                    part,
523                    offset: base_offset + part_start,
524                    len: pos - part_start,
525                });
526                current_text_start = pos;
527            } else if next.map(|c| c.is_ascii_digit()).unwrap_or(false) {
528                push_literal(&mut current_text, &mut current_text_start, pos, &mut parts);
529                i += 1; // consume '$'
530                pos += 1;
531                if let Some(&digit) = chars_vec.get(i) {
532                    let n = digit.to_digit(10).unwrap_or(0) as usize;
533                    i += 1;
534                    pos += digit.len_utf8();
535                    parts.push(SpannedPart {
536                        part: StringPart::Positional(n),
537                        offset: base_offset + part_start,
538                        len: pos - part_start,
539                    });
540                }
541                current_text_start = pos;
542            } else if next == Some('@') {
543                push_literal(&mut current_text, &mut current_text_start, pos, &mut parts);
544                i += 2; // consume "$@"
545                pos += 2;
546                parts.push(SpannedPart {
547                    part: StringPart::AllArgs,
548                    offset: base_offset + part_start,
549                    len: pos - part_start,
550                });
551                current_text_start = pos;
552            } else if next == Some('#') {
553                push_literal(&mut current_text, &mut current_text_start, pos, &mut parts);
554                i += 2; // consume "$#"
555                pos += 2;
556                parts.push(SpannedPart {
557                    part: StringPart::ArgCount,
558                    offset: base_offset + part_start,
559                    len: pos - part_start,
560                });
561                current_text_start = pos;
562            } else if next == Some('?') {
563                push_literal(&mut current_text, &mut current_text_start, pos, &mut parts);
564                i += 2; // consume "$?"
565                pos += 2;
566                parts.push(SpannedPart {
567                    part: StringPart::LastExitCode,
568                    offset: base_offset + part_start,
569                    len: pos - part_start,
570                });
571                current_text_start = pos;
572            } else if next == Some('$') {
573                push_literal(&mut current_text, &mut current_text_start, pos, &mut parts);
574                i += 2; // consume "$$"
575                pos += 2;
576                parts.push(SpannedPart {
577                    part: StringPart::CurrentPid,
578                    offset: base_offset + part_start,
579                    len: pos - part_start,
580                });
581                current_text_start = pos;
582            } else if next.map(|c| c.is_ascii_alphabetic() || c == '_').unwrap_or(false) {
583                push_literal(&mut current_text, &mut current_text_start, pos, &mut parts);
584                i += 1; // consume '$'
585                pos += 1;
586                let mut var_name = String::new();
587                while let Some(&c) = chars_vec.get(i) {
588                    if c.is_ascii_alphanumeric() || c == '_' {
589                        var_name.push(c);
590                        i += 1;
591                        pos += c.len_utf8();
592                    } else {
593                        break;
594                    }
595                }
596                parts.push(SpannedPart {
597                    part: StringPart::Var(VarPath::simple(var_name)),
598                    offset: base_offset + part_start,
599                    len: pos - part_start,
600                });
601                current_text_start = pos;
602            } else {
603                // Bare $ — treat as literal
604                if current_text.is_empty() {
605                    current_text_start = pos;
606                }
607                current_text.push(ch);
608                i += 1;
609                pos += 1;
610            }
611        } else {
612            if current_text.is_empty() {
613                current_text_start = pos;
614            }
615            current_text.push(ch);
616            i += 1;
617            pos += ch.len_utf8();
618        }
619    }
620
621    push_literal(&mut current_text, &mut current_text_start, pos, &mut parts);
622
623    parts
624}
625
626fn parse_interpolated_string(s: &str) -> Result<Vec<StringPart>, String> {
627    // First, replace escaped dollar markers with a temporary placeholder
628    // The lexer uses __KAISH_ESCAPED_DOLLAR__ for \$ to prevent re-interpretation
629    let s = s.replace("__KAISH_ESCAPED_DOLLAR__", "\x00DOLLAR\x00");
630
631    let mut parts = Vec::new();
632    let mut current_text = String::new();
633    let mut chars = s.chars().peekable();
634
635    while let Some(ch) = chars.next() {
636        if ch == '\x00' {
637            // This is our escaped dollar marker - skip "DOLLAR" and the closing \x00
638            let mut marker = String::new();
639            while let Some(&c) = chars.peek() {
640                if c == '\x00' {
641                    chars.next(); // consume closing marker
642                    break;
643                }
644                if let Some(c) = chars.next() {
645                    marker.push(c);
646                }
647            }
648            if marker == "DOLLAR" {
649                current_text.push('$');
650            }
651        } else if ch == '$' {
652            // Check for command substitution $(...)
653            if chars.peek() == Some(&'(') {
654                // Command substitution $(...)
655                if !current_text.is_empty() {
656                    parts.push(StringPart::Literal(std::mem::take(&mut current_text)));
657                }
658
659                // Consume the '('
660                chars.next();
661
662                // Collect until matching ')' accounting for nested parens
663                let mut cmd_content = String::new();
664                let mut paren_depth = 1;
665                for c in chars.by_ref() {
666                    if c == '(' {
667                        paren_depth += 1;
668                        cmd_content.push(c);
669                    } else if c == ')' {
670                        paren_depth -= 1;
671                        if paren_depth == 0 {
672                            break;
673                        }
674                        cmd_content.push(c);
675                    } else {
676                        cmd_content.push(c);
677                    }
678                }
679
680                // Parse the command content as a full statement block
681                // (pipelines, `&&`/`||` chains, `;`/newline sequences, comments).
682                match parse(&cmd_content) {
683                    Ok(program) => {
684                        let stmts = strip_empty_stmts(program.statements);
685                        if stmts.is_empty() {
686                            // Nothing runnable (e.g. `$()` or only a comment) —
687                            // bash treats this as the empty string. Keep literal.
688                            current_text.push_str("$(");
689                            current_text.push_str(&cmd_content);
690                            current_text.push(')');
691                        } else {
692                            parts.push(StringPart::CommandSubst(stmts));
693                        }
694                    }
695                    Err(_) => {
696                        // A syntax error inside the substitution is loud, exactly
697                        // like the unquoted `$(...)` form — never silently demoted
698                        // to literal text.
699                        return Err(format!(
700                            "syntax error in command substitution: $({cmd_content})"
701                        ));
702                    }
703                }
704            } else if chars.peek() == Some(&'{') {
705                // Braced variable reference ${...}
706                if !current_text.is_empty() {
707                    parts.push(StringPart::Literal(std::mem::take(&mut current_text)));
708                }
709
710                // Consume the '{'
711                chars.next();
712
713                // Collect until matching '}', tracking nesting depth
714                let mut var_content = String::new();
715                let mut depth = 1;
716                for c in chars.by_ref() {
717                    if c == '{' && var_content.ends_with('$') {
718                        depth += 1;
719                        var_content.push(c);
720                    } else if c == '}' {
721                        depth -= 1;
722                        if depth == 0 {
723                            break;
724                        }
725                        var_content.push(c);
726                    } else {
727                        var_content.push(c);
728                    }
729                }
730
731                // Parse the content for special syntax
732                let part = if let Some(name) = var_content.strip_prefix('#') {
733                    // Variable length: ${#VAR} / ${#path[sub]}
734                    StringPart::VarLength(parse_varpath(&format!("${{{name}}}")))
735                } else if var_content.starts_with("__ARITH:") && var_content.ends_with("__") {
736                    // Arithmetic expression: ${__ARITH:expr__}
737                    let expr = var_content
738                        .strip_prefix("__ARITH:")
739                        .and_then(|s| s.strip_suffix("__"))
740                        .unwrap_or("");
741                    StringPart::Arithmetic(expr.to_string())
742                } else if let Some(colon_idx) = find_default_separator_in_content(&var_content) {
743                    // Variable with default: ${VAR:-default} - recursively parse the default
744                    let path = parse_varpath(&format!("${{{}}}", &var_content[..colon_idx]));
745                    let default_str = &var_content[colon_idx + 2..];
746                    let default = parse_interpolated_string(&unquote_default_word(default_str))?;
747                    StringPart::VarWithDefault { path, default }
748                } else {
749                    // Regular variable: ${VAR} or ${VAR.field}
750                    StringPart::Var(parse_varpath(&format!("${{{}}}", var_content)))
751                };
752                parts.push(part);
753            } else if chars.peek().map(|c| c.is_ascii_digit()).unwrap_or(false) {
754                // Positional parameter $0-$9
755                if !current_text.is_empty() {
756                    parts.push(StringPart::Literal(std::mem::take(&mut current_text)));
757                }
758                if let Some(digit) = chars.next() {
759                    let n = digit.to_digit(10).unwrap_or(0) as usize;
760                    parts.push(StringPart::Positional(n));
761                }
762            } else if chars.peek() == Some(&'@') {
763                // All arguments $@
764                if !current_text.is_empty() {
765                    parts.push(StringPart::Literal(std::mem::take(&mut current_text)));
766                }
767                chars.next(); // consume '@'
768                parts.push(StringPart::AllArgs);
769            } else if chars.peek() == Some(&'#') {
770                // Argument count $#
771                if !current_text.is_empty() {
772                    parts.push(StringPart::Literal(std::mem::take(&mut current_text)));
773                }
774                chars.next(); // consume '#'
775                parts.push(StringPart::ArgCount);
776            } else if chars.peek() == Some(&'?') {
777                // Last exit code $?
778                if !current_text.is_empty() {
779                    parts.push(StringPart::Literal(std::mem::take(&mut current_text)));
780                }
781                chars.next(); // consume '?'
782                parts.push(StringPart::LastExitCode);
783            } else if chars.peek() == Some(&'$') {
784                // Current PID $$
785                if !current_text.is_empty() {
786                    parts.push(StringPart::Literal(std::mem::take(&mut current_text)));
787                }
788                chars.next(); // consume second '$'
789                parts.push(StringPart::CurrentPid);
790            } else if chars.peek().map(|c| c.is_ascii_alphabetic() || *c == '_').unwrap_or(false) {
791                // Simple variable reference $NAME
792                if !current_text.is_empty() {
793                    parts.push(StringPart::Literal(std::mem::take(&mut current_text)));
794                }
795
796                // Collect identifier characters
797                let mut var_name = String::new();
798                while let Some(&c) = chars.peek() {
799                    if c.is_ascii_alphanumeric() || c == '_' {
800                        if let Some(c) = chars.next() {
801                            var_name.push(c);
802                        }
803                    } else {
804                        break;
805                    }
806                }
807
808                parts.push(StringPart::Var(VarPath::simple(var_name)));
809            } else {
810                // Literal $ (not followed by { or identifier start)
811                current_text.push(ch);
812            }
813        } else {
814            current_text.push(ch);
815        }
816    }
817
818    if !current_text.is_empty() {
819        parts.push(StringPart::Literal(current_text));
820    }
821
822    Ok(parts)
823}
824
825/// Parse error with location and context.
826#[derive(Debug, Clone)]
827pub struct ParseError {
828    pub span: Span,
829    pub message: String,
830}
831
832impl ParseError {
833    /// Format the error against the original source, emitting a 1-indexed
834    /// `line:col [parse]: <message>` prefix and a snippet of the offending
835    /// line. Mirrors `ValidationIssue::format` so error reporting feels
836    /// consistent across pipeline phases.
837    pub fn format(&self, source: &str) -> String {
838        let start = self.span.start;
839        let mut line = 1usize;
840        let mut col = 1usize;
841        for (i, ch) in source.char_indices() {
842            if i >= start {
843                break;
844            }
845            if ch == '\n' {
846                line += 1;
847                col = 1;
848            } else {
849                col += 1;
850            }
851        }
852        let line_content = {
853            let line_start = source[..start.min(source.len())]
854                .rfind('\n')
855                .map_or(0, |i| i + 1);
856            let line_end = source[start.min(source.len())..]
857                .find('\n')
858                .map_or(source.len(), |i| start + i);
859            source.get(line_start..line_end).unwrap_or("")
860        };
861        if line_content.is_empty() {
862            format!("{}:{} [parse]: {}", line, col, self.message)
863        } else {
864            format!(
865                "{}:{} [parse]: {}\n  | {}",
866                line, col, self.message, line_content
867            )
868        }
869    }
870}
871
872impl std::fmt::Display for ParseError {
873    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
874        write!(f, "{} at {:?}", self.message, self.span)
875    }
876}
877
878impl std::error::Error for ParseError {}
879
880/// Parse kaish source code into a Program AST.
881pub fn parse(source: &str) -> Result<Program, Vec<ParseError>> {
882    // Tokenize with logos
883    let tokens = lexer::tokenize(source).map_err(|errs| {
884        errs.into_iter()
885            .map(|e| ParseError {
886                span: (e.span.start..e.span.end).into(),
887                message: format!("lexer error: {}", e.token),
888            })
889            .collect::<Vec<_>>()
890    })?;
891
892    // Convert tokens to (Token, SimpleSpan) pairs
893    let tokens: Vec<(Token, Span)> = tokens
894        .into_iter()
895        .map(|spanned| (spanned.token, (spanned.span.start..spanned.span.end).into()))
896        .collect();
897
898    // End-of-input span
899    let end_span: Span = (source.len()..source.len()).into();
900
901    // Parse using slice-based input (like nano_rust example)
902    let parser = program_parser();
903    let result = parser.parse(tokens.as_slice().map(end_span, |(t, s)| (t, s)));
904
905    let program = result.into_result().map_err(|errs| {
906        errs.into_iter()
907            .map(|e| ParseError {
908                span: *e.span(),
909                message: e.to_string(),
910            })
911            .collect::<Vec<_>>()
912    })?;
913
914    // Structural well-formedness checks that chumsky's grammar can't surface a
915    // clean message for. A command with two stdin sources (`<`/`<<`/`<<<`)
916    // would silently depend on redirect ordering at execution time, so reject
917    // it here — at parse time, which (unlike validation) can never be skipped.
918    if first_ambiguous_stdin(&program.statements) {
919        return Err(vec![ParseError {
920            // Redirects carry no AST span, so anchor at the start of the
921            // source; the message is the actionable part. Precise columns
922            // would require spanning `Redirect` (deferred — see docs/issues.md).
923            span: (0..0).into(),
924            message: "multiple stdin redirects on one command are ambiguous; \
925                      use exactly one of `<`, `<<`, or `<<<`"
926                .to_string(),
927        }]);
928    }
929
930    Ok(program)
931}
932
933/// Parse a single statement (useful for REPL).
934pub fn parse_statement(source: &str) -> Result<Stmt, Vec<ParseError>> {
935    let program = parse(source)?;
936    program
937        .statements
938        .into_iter()
939        .find(|s| !matches!(s, Stmt::Empty))
940        .ok_or_else(|| {
941            vec![ParseError {
942                span: (0..source.len()).into(),
943                message: "empty input".to_string(),
944            }]
945        })
946}
947
948// ═══════════════════════════════════════════════════════════════════════════
949// Parser Combinators - generic over input type
950// ═══════════════════════════════════════════════════════════════════════════
951
952/// Top-level program parser.
953fn program_parser<'tokens, 'src: 'tokens, I>(
954) -> impl Parser<'tokens, I, Program, extra::Err<Rich<'tokens, Token, Span>>>
955where
956    I: ValueInput<'tokens, Token = Token, Span = Span>,
957{
958    statement_parser()
959        .repeated()
960        .collect::<Vec<_>>()
961        .map(|statements| Program { statements })
962}
963
964/// Statement parser - dispatches based on leading token.
965/// Supports statement-level chaining with && and ||.
966fn statement_parser<'tokens, I>(
967) -> impl Parser<'tokens, I, Stmt, extra::Err<Rich<'tokens, Token, Span>>> + Clone
968where
969    I: ValueInput<'tokens, Token = Token, Span = Span>,
970{
971    recursive(|stmt| {
972        let terminator = choice((just(Token::Newline), just(Token::Semi))).repeated();
973
974        // break [N] - break out of N levels of loops (default 1)
975        let break_stmt = just(Token::Break)
976            .ignore_then(
977                select! { Token::Int(n) => n as usize }.or_not()
978            )
979            .map(Stmt::Break);
980
981        // continue [N] - continue to next iteration, skipping N levels (default 1)
982        let continue_stmt = just(Token::Continue)
983            .ignore_then(
984                select! { Token::Int(n) => n as usize }.or_not()
985            )
986            .map(Stmt::Continue);
987
988        // return [expr] - return from a tool
989        let return_stmt = just(Token::Return)
990            .ignore_then(primary_expr_parser().or_not())
991            .map(|e| Stmt::Return(e.map(Box::new)));
992
993        // exit [code] - exit the script
994        let exit_stmt = just(Token::Exit)
995            .ignore_then(primary_expr_parser().or_not())
996            .map(|e| Stmt::Exit(e.map(Box::new)));
997
998        // set command: `set -e`, `set +e`, `set` (no args), `set -o pipefail`
999        // This must come BEFORE assignment_parser to handle `set -e` vs `X=value`
1000        //
1001        // Strategy: Use lookahead to check what follows `set`:
1002        // - If followed by a flag (-e, --long, +e): parse as set command
1003        // - If followed by identifier NOT followed by =: parse as set command (e.g., `set pipefail`)
1004        // - If followed by nothing (end/newline/semi): parse as set command
1005        // - If followed by identifier then =: let assignment_parser handle it
1006        let set_flag_arg = choice((
1007            select! { Token::ShortFlag(f) => Arg::ShortFlag(f) },
1008            select! { Token::LongFlag(f) => Arg::LongFlag(f) },
1009            // PlusFlag for +e, +x etc. - convert to positional arg with + prefix
1010            select! { Token::PlusFlag(f) => Arg::Positional(Expr::Literal(Value::String(format!("+{}", f)))) },
1011        ));
1012
1013        // Option value after `-o`/`+o`: a size literal (`8K`, `1M`) or raw
1014        // byte count. Stringified so `set.rs` can `parse_size` the
1015        // `output-limit=<value>` it reconstructs.
1016        let option_value_str = select! {
1017            Token::NumberIdent(s) => s,
1018            Token::Int(n) => n.to_string(),
1019            Token::Ident(s) => s,
1020        };
1021
1022        // `-o output-limit=8K`: `name`, `=`, `value` are three tokens; fold
1023        // them back into a single `name=value` positional (the form `set.rs`
1024        // and bash both expect). Without this the `=` is a parse error.
1025        let set_option_assign = ident_parser()
1026            .then_ignore(just(Token::Eq))
1027            .then(option_value_str)
1028            .map(|(name, value)| {
1029                Arg::Positional(Expr::Literal(Value::String(format!("{name}={value}"))))
1030            });
1031
1032        // Quoted option such as `set -o "output-limit=8K"`: the whole thing is
1033        // one string token. Accept it as a positional so the quoted form works
1034        // too (agents reach for it after the unquoted form trips a shell lint).
1035        let set_quoted_arg = select! {
1036            Token::String(s) => Arg::Positional(Expr::Literal(Value::String(s))),
1037            Token::SingleString(s) => Arg::Positional(Expr::Literal(Value::String(s))),
1038        };
1039
1040        // set with flags: `set -e`, `set -e -u -o pipefail`
1041        let set_with_flags = just(Token::Set)
1042            .then(set_flag_arg)
1043            .then(
1044                choice((
1045                    set_flag_arg,
1046                    // `-o name=value` (try before the bare-ident arm).
1047                    set_option_assign,
1048                    set_quoted_arg,
1049                    // Identifiers like 'pipefail' after -o
1050                    ident_parser().map(|name| Arg::Positional(Expr::Literal(Value::String(name)))),
1051                ))
1052                .repeated()
1053                .collect::<Vec<_>>(),
1054            )
1055            .map(|((_, first_arg), mut rest_args)| {
1056                let mut args = vec![first_arg];
1057                args.append(&mut rest_args);
1058                Stmt::Command(Command {
1059                    name: "set".to_string(),
1060                    args,
1061                    redirects: vec![],
1062                })
1063            });
1064
1065        // set with no args: `set` alone (shows settings)
1066        // Must be followed by newline, semicolon, end of input, or a chaining operator (&&, ||)
1067        let set_no_args = just(Token::Set)
1068            .then(
1069                choice((
1070                    just(Token::Newline).to(()),
1071                    just(Token::Semi).to(()),
1072                    just(Token::And).to(()),
1073                    just(Token::Or).to(()),
1074                    end(),
1075                ))
1076                .rewind(),
1077            )
1078            .map(|_| Stmt::Command(Command {
1079                name: "set".to_string(),
1080                args: vec![],
1081                redirects: vec![],
1082            }));
1083
1084        // Try set_with_flags first (requires at least one flag)
1085        // Then try set_no_args (no args, followed by terminator)
1086        // If neither matches, fall through to assignment_parser
1087        let set_command = set_with_flags.or(set_no_args);
1088
1089        // Inline env prefix: `NAME=value ... command`. One or more bash-style
1090        // assignments immediately followed by a command/pipeline scopes those
1091        // assignments to that command only (Stmt::EnvScoped). With no command
1092        // following, this alternative fails and we fall through to a plain,
1093        // persistent assignment. Must precede `assignment_parser` so the
1094        // prefixed-command form wins when a command follows.
1095        // Env-prefix assignment stays BARE-IDENT ONLY — a subscripted target
1096        // (`user[email]=x cmd`) is illegal here, not just unsupported:
1097        // structured values can't cross the process boundary anyway (see
1098        // docs/arrays-and-hashes.md, "Assignment lvalues"). Using
1099        // `ident_parser()` directly (not `lvalue_path_parser()`) means a
1100        // bracket run before `=` in this position never gets a chance to
1101        // parse as a path — it either isn't there (plain ident) or the
1102        // lexer's lvalue suppression fires and the stray `LBracket` fails
1103        // this parser, falling through to a real parse error instead of
1104        // silently being accepted.
1105        let env_prefix_assign = ident_parser()
1106            .then_ignore(just(Token::Eq))
1107            .then(value_expr_parser())
1108            .map(|(name, value)| Assignment { path: VarPath::simple(name), value, local: false });
1109        let env_scoped = env_prefix_assign
1110            .repeated()
1111            .at_least(1)
1112            .collect::<Vec<_>>()
1113            .then(pipeline_parser().map(pipeline_into_stmt))
1114            .map(|(assignments, body)| Stmt::EnvScoped {
1115                assignments,
1116                body: Box::new(body),
1117            });
1118
1119        // Base statement (without chaining)
1120        let base_statement = choice((
1121            just(Token::Newline).to(Stmt::Empty),
1122            set_command,
1123            env_scoped,
1124            assignment_parser().map(Stmt::Assignment),
1125            // Shell-style functions (use $1, $2 positional params)
1126            posix_function_parser(stmt.clone()).map(Stmt::ToolDef),  // name() { }
1127            bash_function_parser(stmt.clone()).map(Stmt::ToolDef),   // function name { }
1128            if_parser(stmt.clone()).map(Stmt::If),
1129            for_parser(stmt.clone()).map(Stmt::For),
1130            while_parser(stmt.clone()).map(Stmt::While),
1131            case_parser(stmt.clone()).map(Stmt::Case),
1132            break_stmt,
1133            continue_stmt,
1134            return_stmt,
1135            exit_stmt,
1136            test_expr_stmt_parser().map(Stmt::Test),
1137            // Note: 'true' and 'false' are handled by command_parser/pipeline_parser
1138            pipeline_parser().map(pipeline_into_stmt),
1139        ))
1140        .boxed();
1141
1142        // Statement chaining: `&&` and `||` have EQUAL precedence and associate
1143        // left-to-right (POSIX), so `true || echo A && echo B` parses as
1144        // `((true || echo A) && echo B)` and prints B — NOT `&&`-binds-tighter.
1145        // A single left fold over a stream of (operator, statement) pairs gives
1146        // that: each operator wraps the accumulated left side with the next stmt.
1147        base_statement
1148            .clone()
1149            .foldl(
1150                choice((
1151                    just(Token::And).to(true), // true = &&
1152                    just(Token::Or).to(false), // false = ||
1153                ))
1154                .then(base_statement)
1155                .repeated(),
1156                |left, (is_and, right): (bool, Stmt)| {
1157                    if is_and {
1158                        Stmt::AndChain {
1159                            left: Box::new(left),
1160                            right: Box::new(right),
1161                        }
1162                    } else {
1163                        Stmt::OrChain {
1164                            left: Box::new(left),
1165                            right: Box::new(right),
1166                        }
1167                    }
1168                },
1169            )
1170            .then_ignore(terminator)
1171    })
1172}
1173
1174/// One bracket subscript in an assignment LHS: `[0]`, `[email]`, `["a b"]`,
1175/// `[$k]`, `[0:2]`. Reached only via the lexer's lvalue suppression (see
1176/// `lexer::flush_glob_run`), which keeps a bracket run immediately followed by
1177/// `=` from fusing into a `GlobWord` — so this always sees primitive
1178/// `LBracket`/`RBracket` tokens around one of a handful of interior shapes.
1179/// Interior classification reuses [`parse_subscript`] (string-based) for the
1180/// `Ident` case (bareword key or colon-fused slice like `0:2`/`0:-1` — colon
1181/// merge already ran ahead of this parser) so read and write share one
1182/// subscript grammar; the other interior kinds map straight to their segment.
1183fn lvalue_subscript_parser<'tokens, I>(
1184) -> impl Parser<'tokens, I, VarSegment, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1185where
1186    I: ValueInput<'tokens, Token = Token, Span = Span>,
1187{
1188    let interior = choice((
1189        select! { Token::SimpleVarRef(name) => VarSegment::Dynamic(name) },
1190        select! { Token::String(s) => VarSegment::Key(s) },
1191        select! { Token::SingleString(s) => VarSegment::Key(s) },
1192        select! { Token::Int(n) => VarSegment::Index(n) },
1193        select! { Token::Ident(s) => parse_subscript(&s) },
1194    ));
1195
1196    just(Token::LBracket)
1197        .ignore_then(interior)
1198        .then_ignore(just(Token::RBracket))
1199        .labelled("subscript")
1200}
1201
1202/// An lvalue path: `NAME`, `NAME[sub]`, `NAME[sub][sub]…`. The root is a
1203/// plain identifier; zero or more bracket subscripts follow with no
1204/// whitespace expected between them (the lexer only suppresses fusion for a
1205/// bracket run immediately followed by `=`, so this is the only shape that
1206/// reaches here already split into primitive tokens).
1207fn lvalue_path_parser<'tokens, I>(
1208) -> impl Parser<'tokens, I, VarPath, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1209where
1210    I: ValueInput<'tokens, Token = Token, Span = Span>,
1211{
1212    ident_parser()
1213        .then(lvalue_subscript_parser().repeated().collect::<Vec<_>>())
1214        .map(|(name, subscripts)| {
1215            let mut segments = vec![VarSegment::Field(name)];
1216            segments.extend(subscripts);
1217            VarPath { segments }
1218        })
1219        .labelled("lvalue path")
1220}
1221
1222/// Assignment: `NAME=value` / `NAME[sub]=value` (bash-style), or
1223/// `local NAME = value` (scoped). Bracket paths are lvalues here — see
1224/// `docs/arrays-and-hashes.md` ("Assignment lvalues") — and are resolved at
1225/// runtime by `Scope::walk_write`, sharing the read resolver's per-hop
1226/// classification.
1227fn assignment_parser<'tokens, I>(
1228) -> impl Parser<'tokens, I, Assignment, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1229where
1230    I: ValueInput<'tokens, Token = Token, Span = Span>,
1231{
1232    // local NAME = value (with spaces around =)
1233    let local_assignment = just(Token::Local)
1234        .ignore_then(lvalue_path_parser())
1235        .then_ignore(just(Token::Eq))
1236        .then(value_expr_parser())
1237        .map(|(path, value)| Assignment {
1238            path,
1239            value,
1240            local: true,
1241        });
1242
1243    // Bash-style: NAME=value / NAME[sub]=value (no spaces around =)
1244    // The lexer produces IDENT (LBRACKET ... RBRACKET)* EQ EXPR, so we parse it here
1245    let bash_assignment = lvalue_path_parser()
1246        .then_ignore(just(Token::Eq))
1247        .then(value_expr_parser())
1248        .map(|(path, value)| Assignment {
1249            path,
1250            value,
1251            local: false,
1252        });
1253
1254    choice((local_assignment, bash_assignment))
1255        .labelled("assignment")
1256        .boxed()
1257}
1258
1259/// POSIX-style function: `name() { body }`
1260///
1261/// Produces a ToolDef with empty params - uses positional params ($1, $2, etc.)
1262fn posix_function_parser<'tokens, I, S>(
1263    stmt: S,
1264) -> impl Parser<'tokens, I, ToolDef, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1265where
1266    I: ValueInput<'tokens, Token = Token, Span = Span>,
1267    S: Parser<'tokens, I, Stmt, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
1268{
1269    ident_parser()
1270        .then_ignore(just(Token::LParen))
1271        .then_ignore(just(Token::RParen))
1272        .then_ignore(just(Token::LBrace))
1273        .then_ignore(just(Token::Newline).repeated())
1274        .then(
1275            stmt.repeated()
1276                .collect::<Vec<_>>()
1277                .map(|stmts| stmts.into_iter().filter(|s| !matches!(s, Stmt::Empty)).collect()),
1278        )
1279        .then_ignore(just(Token::Newline).repeated())
1280        .then_ignore(just(Token::RBrace))
1281        .map(|(name, body)| ToolDef { name, params: vec![], body })
1282        .labelled("POSIX function")
1283        .boxed()
1284}
1285
1286/// Bash-style function: `function name { body }` (without parens)
1287///
1288/// Produces a ToolDef with empty params - uses positional params ($1, $2, etc.)
1289fn bash_function_parser<'tokens, I, S>(
1290    stmt: S,
1291) -> impl Parser<'tokens, I, ToolDef, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1292where
1293    I: ValueInput<'tokens, Token = Token, Span = Span>,
1294    S: Parser<'tokens, I, Stmt, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
1295{
1296    just(Token::Function)
1297        .ignore_then(ident_parser())
1298        .then_ignore(just(Token::LBrace))
1299        .then_ignore(just(Token::Newline).repeated())
1300        .then(
1301            stmt.repeated()
1302                .collect::<Vec<_>>()
1303                .map(|stmts| stmts.into_iter().filter(|s| !matches!(s, Stmt::Empty)).collect()),
1304        )
1305        .then_ignore(just(Token::Newline).repeated())
1306        .then_ignore(just(Token::RBrace))
1307        .map(|(name, body)| ToolDef { name, params: vec![], body })
1308        .labelled("bash function")
1309        .boxed()
1310}
1311
1312/// If statement: `if COND; then STMTS [elif COND; then STMTS]* [else STMTS] fi`
1313///
1314/// elif clauses are desugared to nested if/else:
1315///   `if A; then X elif B; then Y else Z fi`
1316/// becomes:
1317///   `if A; then X else { if B; then Y else Z fi } fi`
1318fn if_parser<'tokens, I, S>(
1319    stmt: S,
1320) -> impl Parser<'tokens, I, IfStmt, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1321where
1322    I: ValueInput<'tokens, Token = Token, Span = Span>,
1323    S: Parser<'tokens, I, Stmt, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
1324{
1325    // Parse a single branch: condition + then statements
1326    let branch = condition_parser()
1327        .then_ignore(just(Token::Semi).or_not())
1328        .then_ignore(just(Token::Newline).repeated())
1329        .then_ignore(just(Token::Then))
1330        .then_ignore(just(Token::Newline).repeated())
1331        .then(
1332            stmt.clone()
1333                .repeated()
1334                .collect::<Vec<_>>()
1335                .map(|stmts: Vec<Stmt>| {
1336                    stmts
1337                        .into_iter()
1338                        .filter(|s| !matches!(s, Stmt::Empty))
1339                        .collect::<Vec<_>>()
1340                }),
1341        );
1342
1343    // Parse elif branches: `elif COND; then STMTS`
1344    let elif_branch = just(Token::Elif)
1345        .ignore_then(condition_parser())
1346        .then_ignore(just(Token::Semi).or_not())
1347        .then_ignore(just(Token::Newline).repeated())
1348        .then_ignore(just(Token::Then))
1349        .then_ignore(just(Token::Newline).repeated())
1350        .then(
1351            stmt.clone()
1352                .repeated()
1353                .collect::<Vec<_>>()
1354                .map(|stmts: Vec<Stmt>| {
1355                    stmts
1356                        .into_iter()
1357                        .filter(|s| !matches!(s, Stmt::Empty))
1358                        .collect::<Vec<_>>()
1359                }),
1360        );
1361
1362    // Parse else branch: `else STMTS`
1363    let else_branch = just(Token::Else)
1364        .ignore_then(just(Token::Newline).repeated())
1365        .ignore_then(stmt.repeated().collect::<Vec<_>>())
1366        .map(|stmts: Vec<Stmt>| {
1367            stmts
1368                .into_iter()
1369                .filter(|s| !matches!(s, Stmt::Empty))
1370                .collect::<Vec<_>>()
1371        });
1372
1373    just(Token::If)
1374        .ignore_then(branch)
1375        .then(elif_branch.repeated().collect::<Vec<_>>())
1376        .then(else_branch.or_not())
1377        .then_ignore(just(Token::Fi))
1378        .map(|(((condition, then_branch), elif_branches), else_branch)| {
1379            // Build nested if/else structure from elif branches
1380            build_if_chain(condition, then_branch, elif_branches, else_branch)
1381        })
1382        .labelled("if statement")
1383        .boxed()
1384}
1385
1386/// Build a nested IfStmt chain from elif branches.
1387///
1388/// Transforms:
1389///   if A then X elif B then Y elif C then Z else W fi
1390/// Into:
1391///   IfStmt { cond: A, then: X, else: Some([IfStmt { cond: B, then: Y, else: Some([IfStmt { cond: C, then: Z, else: Some(W) }]) }]) }
1392fn build_if_chain(
1393    condition: Expr,
1394    then_branch: Vec<Stmt>,
1395    mut elif_branches: Vec<(Expr, Vec<Stmt>)>,
1396    else_branch: Option<Vec<Stmt>>,
1397) -> IfStmt {
1398    if elif_branches.is_empty() {
1399        // No elif, just if/else
1400        IfStmt {
1401            condition: Box::new(condition),
1402            then_branch,
1403            else_branch,
1404        }
1405    } else {
1406        // Pop the first elif and recursively build the rest
1407        let (elif_cond, elif_then) = elif_branches.remove(0);
1408        let nested_if = build_if_chain(elif_cond, elif_then, elif_branches, else_branch);
1409        IfStmt {
1410            condition: Box::new(condition),
1411            then_branch,
1412            else_branch: Some(vec![Stmt::If(nested_if)]),
1413        }
1414    }
1415}
1416
1417/// For loop: `for VAR in ITEMS; do STMTS done`
1418fn for_parser<'tokens, I, S>(
1419    stmt: S,
1420) -> impl Parser<'tokens, I, ForLoop, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1421where
1422    I: ValueInput<'tokens, Token = Token, Span = Span>,
1423    S: Parser<'tokens, I, Stmt, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
1424{
1425    just(Token::For)
1426        .ignore_then(ident_parser())
1427        .then_ignore(just(Token::In))
1428        .then(expr_parser().repeated().at_least(1).collect::<Vec<_>>())
1429        .then_ignore(just(Token::Semi).or_not())
1430        .then_ignore(just(Token::Newline).repeated())
1431        .then_ignore(just(Token::Do))
1432        .then_ignore(just(Token::Newline).repeated())
1433        .then(
1434            stmt.repeated()
1435                .collect::<Vec<_>>()
1436                .map(|stmts| stmts.into_iter().filter(|s| !matches!(s, Stmt::Empty)).collect()),
1437        )
1438        .then_ignore(just(Token::Done))
1439        .map(|((variable, items), body)| ForLoop {
1440            variable,
1441            items,
1442            body,
1443        })
1444        .labelled("for loop")
1445        .boxed()
1446}
1447
1448/// While loop: `while condition; do ...; done`
1449fn while_parser<'tokens, I, S>(
1450    stmt: S,
1451) -> impl Parser<'tokens, I, WhileLoop, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1452where
1453    I: ValueInput<'tokens, Token = Token, Span = Span>,
1454    S: Parser<'tokens, I, Stmt, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
1455{
1456    just(Token::While)
1457        .ignore_then(condition_parser())
1458        .then_ignore(just(Token::Semi).or_not())
1459        .then_ignore(just(Token::Newline).repeated())
1460        .then_ignore(just(Token::Do))
1461        .then_ignore(just(Token::Newline).repeated())
1462        .then(
1463            stmt.repeated()
1464                .collect::<Vec<_>>()
1465                .map(|stmts| stmts.into_iter().filter(|s| !matches!(s, Stmt::Empty)).collect()),
1466        )
1467        .then_ignore(just(Token::Done))
1468        .map(|(condition, body)| WhileLoop {
1469            condition: Box::new(condition),
1470            body,
1471        })
1472        .labelled("while loop")
1473        .boxed()
1474}
1475
1476/// Case statement: `case expr in pattern) commands ;; esac`
1477///
1478/// Supports:
1479/// - Single patterns: `pattern) commands ;;`
1480/// - Multiple patterns: `pattern1|pattern2) commands ;;`
1481/// - Optional leading `(` before patterns: `(pattern) commands ;;`
1482fn case_parser<'tokens, I, S>(
1483    stmt: S,
1484) -> impl Parser<'tokens, I, CaseStmt, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1485where
1486    I: ValueInput<'tokens, Token = Token, Span = Span>,
1487    S: Parser<'tokens, I, Stmt, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
1488{
1489    // Pattern part: individual tokens that make up a glob pattern
1490    // e.g., "*.rs" is Star + Dot + Ident("rs")
1491    let pattern_part = choice((
1492        select! { Token::GlobWord(s) => s },
1493        select! { Token::Ident(s) => s },
1494        select! { Token::NumberIdent(s) => s },
1495        select! { Token::DashNumWord(s) => s },
1496        select! { Token::AtWord(s) => s },
1497        select! { Token::DottedIdent(s) => s },
1498        select! { Token::String(s) => s },
1499        select! { Token::SingleString(s) => s },
1500        select! { Token::Int(n) => n.to_string() },
1501        select! { Token::Star => "*".to_string() },
1502        select! { Token::Question => "?".to_string() },
1503        select! { Token::Dot => ".".to_string() },
1504        select! { Token::DotDot => "..".to_string() },
1505        select! { Token::Tilde => "~".to_string() },
1506        select! { Token::TildePath(s) => s },
1507        select! { Token::RelativePath(s) => s },
1508        select! { Token::DotSlashPath(s) => s },
1509        select! { Token::Path(p) => p },
1510        select! { Token::VarRef(v) => v },
1511        select! { Token::SimpleVarRef(v) => format!("${}", v) },
1512        // Character class: [a-z], [!abc], [^abc], etc.
1513        just(Token::LBracket)
1514            .ignore_then(
1515                choice((
1516                    select! { Token::Ident(s) => s },
1517                    select! { Token::Int(n) => n.to_string() },
1518                    just(Token::Colon).to(":".to_string()),
1519                    // Negation: ! or ^ at start of char class
1520                    just(Token::Bang).to("!".to_string()),
1521                    // Range like a-z
1522                    select! { Token::ShortFlag(s) => format!("-{}", s) },
1523                ))
1524                .repeated()
1525                .at_least(1)
1526                .collect::<Vec<String>>()
1527            )
1528            .then_ignore(just(Token::RBracket))
1529            .map(|parts| format!("[{}]", parts.join(""))),
1530        // Brace expansion: {a,b,c} or {js,ts}
1531        just(Token::LBrace)
1532            .ignore_then(
1533                choice((
1534                    select! { Token::Ident(s) => s },
1535                    select! { Token::Int(n) => n.to_string() },
1536                ))
1537                .separated_by(just(Token::Comma))
1538                .at_least(1)
1539                .collect::<Vec<String>>()
1540            )
1541            .then_ignore(just(Token::RBrace))
1542            .map(|parts| format!("{{{}}}", parts.join(","))),
1543    ));
1544
1545    // A complete pattern is one or more pattern parts joined together
1546    // e.g., "*.rs" = Star + Dot + Ident
1547    let pattern = pattern_part
1548        .repeated()
1549        .at_least(1)
1550        .collect::<Vec<String>>()
1551        .map(|parts| parts.join(""))
1552        .labelled("case pattern");
1553
1554    // Multiple patterns separated by pipe: `pattern1 | pattern2`
1555    let patterns = pattern
1556        .separated_by(just(Token::Pipe))
1557        .at_least(1)
1558        .collect::<Vec<String>>()
1559        .labelled("case patterns");
1560
1561    // Branch: `[( ] patterns ) commands ;;`
1562    let branch = just(Token::LParen)
1563        .or_not()
1564        .ignore_then(just(Token::Newline).repeated())
1565        .ignore_then(patterns)
1566        .then_ignore(just(Token::RParen))
1567        .then_ignore(just(Token::Newline).repeated())
1568        .then(
1569            stmt.clone()
1570                .repeated()
1571                .collect::<Vec<_>>()
1572                .map(|stmts| stmts.into_iter().filter(|s| !matches!(s, Stmt::Empty)).collect()),
1573        )
1574        .then_ignore(just(Token::DoubleSemi))
1575        .then_ignore(just(Token::Newline).repeated())
1576        .map(|(patterns, body)| CaseBranch { patterns, body })
1577        .labelled("case branch");
1578
1579    just(Token::Case)
1580        .ignore_then(expr_parser())
1581        .then_ignore(just(Token::In))
1582        .then_ignore(just(Token::Newline).repeated())
1583        .then(branch.repeated().collect::<Vec<_>>())
1584        .then_ignore(just(Token::Esac))
1585        .map(|(expr, branches)| CaseStmt { expr, branches })
1586        .labelled("case statement")
1587        .boxed()
1588}
1589
1590/// Pipeline: `cmd | cmd | cmd [&]`
1591fn pipeline_parser<'tokens, I>(
1592) -> impl Parser<'tokens, I, Pipeline, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1593where
1594    I: ValueInput<'tokens, Token = Token, Span = Span>,
1595{
1596    command_parser()
1597        .separated_by(just(Token::Pipe))
1598        .at_least(1)
1599        .collect::<Vec<_>>()
1600        .then(just(Token::Amp).or_not())
1601        .map(|(commands, bg)| Pipeline {
1602            commands,
1603            background: bg.is_some(),
1604        })
1605        .labelled("pipeline")
1606        .boxed()
1607}
1608
1609/// Command: `name args... [redirects...]`
1610/// Command names can be identifiers, 'true', 'false', or '.' (source alias).
1611fn command_parser<'tokens, I>(
1612) -> impl Parser<'tokens, I, Command, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1613where
1614    I: ValueInput<'tokens, Token = Token, Span = Span>,
1615{
1616    // Command name can be an identifier, path, 'true', 'false', '.' (source alias), or ./path
1617    let command_name = choice((
1618        ident_parser(),
1619        path_parser(),
1620        select! { Token::DotSlashPath(s) => s },
1621        just(Token::True).to("true".to_string()),
1622        just(Token::False).to("false".to_string()),
1623        just(Token::Dot).to(".".to_string()),
1624    ));
1625
1626    // NB: the "at most one stdin source per command" rule is enforced by a
1627    // post-parse scan in `parse()` (see `first_ambiguous_stdin`), NOT here.
1628    // A `try_map` rejection at this level cannot surface its own message: a
1629    // command like `cat <<< a <<< b` also fails the competing statement-level
1630    // assignment/function alternative ("expected '=', or '('"), and chumsky's
1631    // `choice` merge keeps that alternative's error regardless of which span
1632    // our custom error carries. So we accept the command here and reject it
1633    // structurally after parsing, where the message is fully under our control
1634    // (verified empirically 2026-06-07; see docs/issues.md).
1635    command_name
1636        .then(args_list_parser())
1637        .then(redirect_parser(primary_expr_parser()).repeated().collect::<Vec<_>>())
1638        .map(|((name, args), redirects)| Command {
1639            name,
1640            args,
1641            redirects,
1642        })
1643        .labelled("command")
1644        .boxed()
1645}
1646
1647/// Map a parsed `Pipeline` to a statement, unwrapping a single redirect-free
1648/// foreground command to `Stmt::Command` (the canonical shape used throughout
1649/// the parser). Shared by the top-level statement parser, `$()` bodies, and
1650/// inline env-prefix bodies so the unwrap rule lives in one place.
1651fn pipeline_into_stmt(p: Pipeline) -> Stmt {
1652    if p.commands.len() == 1 && !p.background && p.commands[0].redirects.is_empty() {
1653        match p.commands.into_iter().next() {
1654            Some(cmd) => Stmt::Command(cmd),
1655            None => Stmt::Empty, // unreachable (len checked) but safe
1656        }
1657    } else {
1658        Stmt::Pipeline(p)
1659    }
1660}
1661
1662/// True if `cmd` has more than one stdin source (`<`, `<<`, `<<<`). Such a
1663/// command would silently depend on redirect ordering at execution time
1664/// (`setup_stdin_redirects` is last-wins), so `parse()` rejects it loudly.
1665fn command_has_ambiguous_stdin(cmd: &Command) -> bool {
1666    cmd.redirects
1667        .iter()
1668        .filter(|r| {
1669            matches!(
1670                r.kind,
1671                RedirectKind::Stdin | RedirectKind::HereDoc | RedirectKind::HereString
1672            )
1673        })
1674        .count()
1675        > 1
1676}
1677
1678/// Find the first command anywhere in `stmts` (recursing into pipelines,
1679/// control-flow bodies, chains, and tool definitions) that has more than one
1680/// stdin source. Used by `parse()` to reject the ambiguity after parsing.
1681fn first_ambiguous_stdin(stmts: &[Stmt]) -> bool {
1682    stmts.iter().any(stmt_has_ambiguous_stdin)
1683}
1684
1685fn stmt_has_ambiguous_stdin(stmt: &Stmt) -> bool {
1686    match stmt {
1687        Stmt::Command(c) => command_has_ambiguous_stdin(c),
1688        Stmt::Pipeline(p) => p.commands.iter().any(command_has_ambiguous_stdin),
1689        Stmt::If(i) => {
1690            first_ambiguous_stdin(&i.then_branch)
1691                || i.else_branch
1692                    .as_deref()
1693                    .is_some_and(first_ambiguous_stdin)
1694        }
1695        Stmt::For(f) => first_ambiguous_stdin(&f.body),
1696        Stmt::While(w) => first_ambiguous_stdin(&w.body),
1697        Stmt::Case(c) => c.branches.iter().any(|b| first_ambiguous_stdin(&b.body)),
1698        Stmt::ToolDef(t) => first_ambiguous_stdin(&t.body),
1699        Stmt::AndChain { left, right } | Stmt::OrChain { left, right } => {
1700            stmt_has_ambiguous_stdin(left) || stmt_has_ambiguous_stdin(right)
1701        }
1702        Stmt::EnvScoped { body, .. } => stmt_has_ambiguous_stdin(body),
1703        Stmt::Assignment(_)
1704        | Stmt::Break(_)
1705        | Stmt::Continue(_)
1706        | Stmt::Return(_)
1707        | Stmt::Exit(_)
1708        | Stmt::Test(_)
1709        | Stmt::Empty => false,
1710    }
1711}
1712
1713/// True when `arg` is the bare-comma literal positional (`Expr::Literal(",")`),
1714/// produced by a lone `,` token in argument position.
1715fn is_comma_literal_arg(arg: &Arg) -> bool {
1716    matches!(arg, Arg::Positional(Expr::Literal(Value::String(s))) if s == ",")
1717}
1718
1719/// Arguments list parser that handles `--` flag terminator.
1720///
1721/// After `--`, all subsequent flags are converted to positional string arguments.
1722fn args_list_parser<'tokens, I>(
1723) -> impl Parser<'tokens, I, Vec<Arg>, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1724where
1725    I: ValueInput<'tokens, Token = Token, Span = Span>,
1726{
1727    // Arguments before `--` (normal parsing). Each arg is captured with its
1728    // source span so we can reject the silent argv-splat: two positional words
1729    // with no whitespace between them (`/tmp/$(echo x).txt` → 3 args). kaish does
1730    // no token pasting, so an unquoted interpolated word fragments into separate
1731    // args; the fix is to quote the whole word. Single-token words (`file.txt`,
1732    // `v1.2.3`) are one arg and never trigger this. See docs/issues.md #2.
1733    let pre_dash = arg_before_double_dash_parser()
1734        .map_with(|arg, e| -> (Arg, Span) { (arg, e.span()) })
1735        .repeated()
1736        .collect::<Vec<(Arg, Span)>>()
1737        .try_map(|args, _span| {
1738            for pair in args.windows(2) {
1739                let (prev, prev_span) = &pair[0];
1740                let (next, next_span) = &pair[1];
1741                if matches!(prev, Arg::Positional(_))
1742                    && matches!(next, Arg::Positional(_))
1743                    && prev_span.end == next_span.start
1744                {
1745                    // A bare `,` lexes as its own token, so a comma-bearing word
1746                    // (`cut -f1,3`, `sort -k2,2n`, `echo a,b`) trips this guard.
1747                    // It isn't token pasting — `,` is reserved (brace expansion,
1748                    // lists) — so give a comma-specific hint that teaches quoting.
1749                    let msg = if is_comma_literal_arg(prev) || is_comma_literal_arg(next) {
1750                        "an unquoted comma splits this into separate words — kaish reserves \
1751                         `,` (brace expansion, lists); quote a comma-bearing argument to keep \
1752                         it one word, e.g. cut -f \"1,3\", sort -k \"2,2n\", or echo \"a,b\""
1753                    } else {
1754                        "adjacent words with no space between them are not joined into one \
1755                         argument (kaish does no token pasting); quote the whole word, e.g. \
1756                         \"/tmp/$(echo x).txt\" or \"$dir/out.txt\""
1757                    };
1758                    return Err(Rich::custom(*next_span, msg));
1759                }
1760            }
1761            Ok(args.into_iter().map(|(arg, _)| arg).collect::<Vec<Arg>>())
1762        });
1763
1764    // The `--` marker itself
1765    let double_dash = select! {
1766        Token::DoubleDash => Arg::DoubleDash,
1767    };
1768
1769    // Arguments after `--` (flags become positional strings)
1770    let post_dash_arg = choice((
1771        // Flags become positional strings
1772        select! {
1773            Token::ShortFlag(name) => Arg::Positional(Expr::Literal(Value::String(format!("-{}", name)))),
1774            Token::LongFlag(name) => Arg::Positional(Expr::Literal(Value::String(format!("--{}", name)))),
1775        },
1776        // `name=value` — same WordAssign production used before `--`. Nothing
1777        // is special after `--` (standard shell behavior), but the
1778        // WordAssign→positional collapse already yields the literal
1779        // `"name=value"` string for commands that don't consume shell
1780        // assignments (like `echo`), so no separate literal-folding rule is
1781        // needed here.
1782        word_assign_arg_parser(),
1783        // `test`/`[` operators stay literal after `--` too (`test -- a = b`).
1784        test_operator_arg_parser(),
1785        // Everything else stays the same
1786        primary_expr_parser().map(Arg::Positional),
1787    ));
1788
1789    let post_dash = post_dash_arg.repeated().collect::<Vec<_>>();
1790
1791    // Combine: args_before ++ [--] ++ args_after
1792    pre_dash
1793        .then(double_dash.then(post_dash).or_not())
1794        .map(|(mut args, maybe_dd)| {
1795            if let Some((dd, post)) = maybe_dd {
1796                args.push(dd);
1797                args.extend(post);
1798            }
1799            args
1800        })
1801}
1802
1803/// A statement keyword used as a plain word — its source spelling.
1804///
1805/// Lets keywords serve as the *key* of a `key=value` argv assignment, so
1806/// `dd if=/dev/urandom` works (`if` is `Token::If`, not an `Ident`). Safe
1807/// because: statement-level `if`/`for`/… are decided before arg parsing (their
1808/// productions precede `pipeline_parser`), `command_name` never accepts these
1809/// tokens, and the `key=value` rule requires the key span-adjacent to `=` — a
1810/// real `if <cond>` has a space and never matches. See docs/binary-data.md.
1811fn keyword_word<'tokens, I>(
1812) -> impl Parser<'tokens, I, String, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1813where
1814    I: ValueInput<'tokens, Token = Token, Span = Span>,
1815{
1816    select! {
1817        Token::Set => "set",
1818        Token::Local => "local",
1819        Token::If => "if",
1820        Token::Then => "then",
1821        Token::Else => "else",
1822        Token::Elif => "elif",
1823        Token::Fi => "fi",
1824        Token::For => "for",
1825        Token::While => "while",
1826        Token::In => "in",
1827        Token::Do => "do",
1828        Token::Done => "done",
1829        Token::Case => "case",
1830        Token::Esac => "esac",
1831        Token::Function => "function",
1832        Token::Break => "break",
1833        Token::Continue => "continue",
1834        Token::Return => "return",
1835        Token::Exit => "exit",
1836    }
1837    .map(|s| s.to_string())
1838}
1839
1840/// Shell assignment in argv position: `name=value` (must not have spaces
1841/// around `=`). Produces `Arg::WordAssign`; the kernel routes it through
1842/// `tool_args.named` only for shell-assignment-accepting builtins (export,
1843/// alias). For every other command it materialises as a `"name=value"`
1844/// positional, matching bash semantics (`cat foo=bar` opens a file named
1845/// `foo=bar`). Shared by the pre-`--` and post-`--` argument grammars — the
1846/// `WordAssign`/positional collapse already gives `--`-following `a=b` the
1847/// literal-string behavior shell users expect, so it needs no special casing
1848/// after `--`.
1849fn word_assign_arg_parser<'tokens, I>(
1850) -> impl Parser<'tokens, I, Arg, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1851where
1852    I: ValueInput<'tokens, Token = Token, Span = Span>,
1853{
1854    choice((
1855        select! { Token::Ident(s) => s },
1856        keyword_word(),
1857    ))
1858    .map_with(|s, e| -> (String, Span) { (s, e.span()) })
1859    .then(just(Token::Eq).map_with(|_, e| -> Span { e.span() }))
1860    .then(primary_expr_parser().map_with(|expr, e| -> (Expr, Span) { (expr, e.span()) }))
1861    .try_map(|(((key, key_span), eq_span), (value, value_span)): (((String, Span), Span), (Expr, Span)), span| {
1862        // Check that key ends where = starts and = ends where value starts
1863        if key_span.end != eq_span.start || eq_span.end != value_span.start {
1864            Err(Rich::custom(
1865                span,
1866                "shell assignment must not have spaces around '=' (use 'key=value' not 'key = value')",
1867            ))
1868        } else {
1869            Ok(Arg::WordAssign { key, value })
1870        }
1871    })
1872}
1873
1874/// The `test`/`[` comparison and negation operators (`=`, `==`, `!=`, `!`) as
1875/// ordinary positional argv words.
1876///
1877/// POSIX `test` is a *command*, so its operators must reach it flat as argv —
1878/// but kaish lexes `=`/`==`/`!=`/`!` as shell-significant tokens, so at
1879/// command-argument position they used to parse-error before ever reaching a
1880/// command (`test a = b`). This production makes each a literal-string
1881/// positional. It is name-agnostic: like bash, `echo a = b` prints `a = b` —
1882/// no command name is special-cased (that would be fragile under aliases).
1883///
1884/// Deliberately EXCLUDES the angle brackets `<` `>` `<=` `>=`: those stay
1885/// redirection (making them argv would shadow redirects) and remain
1886/// `[[ ]]`-only. Ordered after the flag/`word_assign` productions so a glued
1887/// `name=value` still binds as a `WordAssign` — this bare-operator rule only
1888/// fires once the current token IS the standalone operator (a spaced `a = b`,
1889/// where `word_assign`'s span-adjacency check has already declined).
1890fn test_operator_arg_parser<'tokens, I>(
1891) -> impl Parser<'tokens, I, Arg, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1892where
1893    I: ValueInput<'tokens, Token = Token, Span = Span>,
1894{
1895    select! {
1896        Token::Eq => "=",
1897        Token::EqEq => "==",
1898        Token::NotEq => "!=",
1899        Token::Bang => "!",
1900    }
1901    .map(|s| Arg::Positional(Expr::Literal(Value::String(s.to_string()))))
1902}
1903
1904/// Argument parser for arguments before `--` (normal flag handling).
1905fn arg_before_double_dash_parser<'tokens, I>(
1906) -> impl Parser<'tokens, I, Arg, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1907where
1908    I: ValueInput<'tokens, Token = Token, Span = Span>,
1909{
1910    // Long flag with value: --name=value
1911    let long_flag_with_value = select! {
1912        Token::LongFlag(name) => name,
1913    }
1914    .then_ignore(just(Token::Eq))
1915    .then(primary_expr_parser())
1916    .map(|(key, value)| Arg::Named { key, value });
1917
1918    // Boolean long flag: --name
1919    let long_flag = select! {
1920        Token::LongFlag(name) => Arg::LongFlag(name),
1921    };
1922
1923    // Boolean short flag: -x
1924    let short_flag = select! {
1925        Token::ShortFlag(name) => Arg::ShortFlag(name),
1926    };
1927
1928    // Shell assignment in argv position: name=value (must not have spaces around =).
1929    let named = word_assign_arg_parser();
1930
1931    // Positional argument
1932    let positional = primary_expr_parser().map(Arg::Positional);
1933
1934    // The `test`/`[` operators (`=` `==` `!=` `!`) as literal positionals.
1935    // After the flag/`named` productions (so glued `name=value` stays a
1936    // WordAssign), before `positional` (which can't parse these tokens).
1937    let test_operator = test_operator_arg_parser();
1938
1939    // Order matters: try more specific patterns first
1940    // Note: DoubleDash is NOT included here - it's handled by args_list_parser
1941    choice((
1942        long_flag_with_value,
1943        long_flag,
1944        short_flag,
1945        named,
1946        test_operator,
1947        positional,
1948    ))
1949    .boxed()
1950}
1951
1952/// Redirect: `> file`, `>> file`, `< file`, `<< heredoc`, `2> file`, `&> file`, `2>&1`
1953///
1954/// `target` parses the file word (and here-string body). Callers pass the
1955/// expression parser appropriate to their context: the top-level command
1956/// grammar passes a fresh `primary_expr_parser()`, while `cmd_subst_parser`
1957/// passes its *already-recursive* `expr` handle. Threading it in (rather than
1958/// building `primary_expr_parser()` internally) is what lets `$(cmd > file)`
1959/// parse without an unbounded `cmd_subst → redirect → primary_expr → cmd_subst`
1960/// construction cycle.
1961fn redirect_parser<'tokens, I, T>(
1962    target: T,
1963) -> impl Parser<'tokens, I, Redirect, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1964where
1965    I: ValueInput<'tokens, Token = Token, Span = Span>,
1966    T: Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
1967{
1968    // Regular redirects: >, >>, <, 2>, &>
1969    let regular_redirect = select! {
1970        Token::GtGt => RedirectKind::StdoutAppend,
1971        Token::Gt => RedirectKind::StdoutOverwrite,
1972        Token::Lt => RedirectKind::Stdin,
1973        Token::Stderr => RedirectKind::Stderr,
1974        Token::Both => RedirectKind::Both,
1975    }
1976    .then(target.clone())
1977    .map(|(kind, target)| Redirect { kind, target });
1978
1979    // Here-doc redirect: << content
1980    // Quoted delimiters (<<'EOF' or <<"EOF") produce literal heredocs (no expansion).
1981    // Unquoted delimiters produce interpolated heredocs (variables are expanded).
1982    // For literal heredocs the `<<-EOF` tab stripping is applied here at parse
1983    // time (the body is fully known); for interpolated heredocs the stripping
1984    // is deferred to the interpreter so source byte offsets in `parts` stay
1985    // aligned with the original source for span reporting.
1986    let heredoc_redirect = just(Token::HereDocStart)
1987        .ignore_then(select! { Token::HereDoc(data) => data })
1988        .map(|data: HereDocData| {
1989            let target = if data.literal {
1990                let body = if data.strip_tabs {
1991                    crate::interpreter::strip_leading_tabs(&data.content)
1992                } else {
1993                    data.content
1994                };
1995                Expr::Literal(Value::String(body))
1996            } else {
1997                let parts = parse_interpolated_string_spanned(
1998                    &data.content,
1999                    data.body_start_offset,
2000                );
2001                // If there's only one literal part and no tab stripping is
2002                // needed, simplify to Expr::Literal — keeps the AST shape
2003                // identical to the pre-spans path for trivial bodies.
2004                if parts.len() == 1 && !data.strip_tabs {
2005                    if let StringPart::Literal(text) = &parts[0].part {
2006                        return Redirect {
2007                            kind: RedirectKind::HereDoc,
2008                            target: Expr::Literal(Value::String(text.clone())),
2009                        };
2010                    }
2011                }
2012                Expr::HereDocBody {
2013                    parts,
2014                    strip_tabs: data.strip_tabs,
2015                }
2016            };
2017            Redirect {
2018                kind: RedirectKind::HereDoc,
2019                target,
2020            }
2021        });
2022
2023    // Here-string redirect: <<< word
2024    // The target is any single expression; kaish's existing Expr machinery
2025    // handles interpolation, single-quoted literals, and command substitution.
2026    let herestring_redirect = just(Token::HereString)
2027        .ignore_then(target.clone())
2028        .map(|target| Redirect {
2029            kind: RedirectKind::HereString,
2030            target,
2031        });
2032
2033    // Merge stderr to stdout: 2>&1 (no target needed - implicit)
2034    let merge_stderr_redirect = just(Token::StderrToStdout)
2035        .map(|_| Redirect {
2036            kind: RedirectKind::MergeStderr,
2037            // Target is unused for MergeStderr, but we need something
2038            target: Expr::Literal(Value::Null),
2039        });
2040
2041    // Merge stdout to stderr: 1>&2 or >&2 (no target needed - implicit)
2042    let merge_stdout_redirect = choice((
2043        just(Token::StdoutToStderr),
2044        just(Token::StdoutToStderr2),
2045    ))
2046    .map(|_| Redirect {
2047        kind: RedirectKind::MergeStdout,
2048        // Target is unused for MergeStdout, but we need something
2049        target: Expr::Literal(Value::Null),
2050    });
2051
2052    choice((
2053        heredoc_redirect,
2054        herestring_redirect,
2055        merge_stderr_redirect,
2056        merge_stdout_redirect,
2057        regular_redirect,
2058    ))
2059    .labelled("redirect")
2060    .boxed()
2061}
2062
2063/// Test expression parser for `[[ ... ]]` syntax.
2064///
2065/// Supports:
2066/// - File tests: `[[ -f path ]]`, `[[ -d path ]]`, etc.
2067/// - String tests: `[[ -z str ]]`, `[[ -n str ]]`
2068/// - Shape-guard tests: `[[ -list x ]]`, `[[ -record x ]]` (see
2069///   `docs/arrays-and-hashes.md`, decision F)
2070/// - Comparisons: `[[ $X == "value" ]]`, `[[ $NUM -gt 5 ]]`
2071/// - Compound: `[[ -f a && -d b ]]`, `[[ -z x || -n y ]]`, `[[ ! -f file ]]`
2072///
2073/// Precedence (highest to lowest): `!` > `&&` > `||`
2074fn test_expr_stmt_parser<'tokens, I>(
2075) -> impl Parser<'tokens, I, TestExpr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2076where
2077    I: ValueInput<'tokens, Token = Token, Span = Span>,
2078{
2079    // File test operators: -e, -f, -d, -r, -w, -x
2080    let file_test_op = select! {
2081        Token::ShortFlag(s) if s == "e" => FileTestOp::Exists,
2082        Token::ShortFlag(s) if s == "f" => FileTestOp::IsFile,
2083        Token::ShortFlag(s) if s == "d" => FileTestOp::IsDir,
2084        Token::ShortFlag(s) if s == "r" => FileTestOp::Readable,
2085        Token::ShortFlag(s) if s == "w" => FileTestOp::Writable,
2086        Token::ShortFlag(s) if s == "x" => FileTestOp::Executable,
2087    };
2088
2089    // String test operators: -z, -n, plus the shape-guard operators -list /
2090    // -record (value-typed tests, not path stats — same operand-evaluation
2091    // path as -z/-n, unlike the file_test_op family above).
2092    let string_test_op = select! {
2093        Token::ShortFlag(s) if s == "z" => StringTestOp::IsEmpty,
2094        Token::ShortFlag(s) if s == "n" => StringTestOp::IsNonEmpty,
2095        Token::ShortFlag(s) if s == "list" => StringTestOp::IsList,
2096        Token::ShortFlag(s) if s == "record" => StringTestOp::IsRecord,
2097    };
2098
2099    // Comparison operators: =, ==, !=, =~, !~, >, <, >=, <=, -gt, -lt, -ge, -le, -eq, -ne
2100    // Note: = and == are equivalent inside [[ ]] (matching bash behavior)
2101    let cmp_op = choice((
2102        just(Token::EqEq).to(TestCmpOp::Eq),
2103        just(Token::Eq).to(TestCmpOp::Eq),
2104        just(Token::NotEq).to(TestCmpOp::NotEq),
2105        just(Token::Match).to(TestCmpOp::Match),
2106        just(Token::NotMatch).to(TestCmpOp::NotMatch),
2107        just(Token::Gt).to(TestCmpOp::Gt),
2108        just(Token::Lt).to(TestCmpOp::Lt),
2109        just(Token::GtEq).to(TestCmpOp::GtEq),
2110        just(Token::LtEq).to(TestCmpOp::LtEq),
2111        select! { Token::ShortFlag(s) if s == "eq" => TestCmpOp::NumEq },
2112        select! { Token::ShortFlag(s) if s == "ne" => TestCmpOp::NumNotEq },
2113        select! { Token::ShortFlag(s) if s == "gt" => TestCmpOp::NumGt },
2114        select! { Token::ShortFlag(s) if s == "lt" => TestCmpOp::NumLt },
2115        select! { Token::ShortFlag(s) if s == "ge" => TestCmpOp::NumGtEq },
2116        select! { Token::ShortFlag(s) if s == "le" => TestCmpOp::NumLtEq },
2117    ));
2118
2119    // File test: -f path
2120    let file_test = file_test_op
2121        .then(primary_expr_parser())
2122        .map(|(op, path)| TestExpr::FileTest {
2123            op,
2124            path: Box::new(path),
2125        });
2126
2127    // String test: -z str
2128    let string_test = string_test_op
2129        .then(primary_expr_parser())
2130        .map(|(op, value)| TestExpr::StringTest {
2131            op,
2132            value: Box::new(value),
2133        });
2134
2135    // Comparison: $X == "value" or $NUM -gt 5
2136    let comparison = primary_expr_parser()
2137        .then(cmp_op)
2138        .then(primary_expr_parser())
2139        .map(|((left, op), right)| TestExpr::Comparison {
2140            left: Box::new(left),
2141            op,
2142            right: Box::new(right),
2143        });
2144
2145    // Collection membership: `e in $coll` / `e not in $coll` (element-in-list,
2146    // key-in-record; see docs/arrays-and-hashes.md). There is no dedicated
2147    // `not` token — it lexes as a plain identifier, so `not_in` is matched as
2148    // the two-word sequence `Ident("not") In`. `not_in` must be tried before
2149    // `in` in the choice below so `e not in c` doesn't get parsed as `e` `in`
2150    // failing on the stray `not` bareword.
2151    let not_in = primary_expr_parser()
2152        .then_ignore(select! { Token::Ident(s) if s == "not" => () })
2153        .then_ignore(just(Token::In))
2154        .then(value_primary_parser())
2155        .map(|(left, right)| TestExpr::NotIn {
2156            left: Box::new(left),
2157            right: Box::new(right),
2158        });
2159
2160    let in_ = primary_expr_parser()
2161        .then_ignore(just(Token::In))
2162        .then(value_primary_parser())
2163        .map(|(left, right)| TestExpr::In {
2164            left: Box::new(left),
2165            right: Box::new(right),
2166        });
2167
2168    // Primary test expression (atomic - no compound operators)
2169    let primary_test = choice((file_test, string_test, not_in, in_, comparison));
2170
2171    // Build compound expressions with proper precedence:
2172    // Grammar:
2173    //   test_expr = or_expr
2174    //   or_expr   = and_expr { "||" and_expr }
2175    //   and_expr  = unary_expr { "&&" unary_expr }
2176    //   unary_expr = "!" unary_expr | primary_test
2177    //
2178    // Precedence: ! (highest) > && > ||
2179
2180    // Unary NOT binds tighter than `&&`/`||`, so it must recurse at the
2181    // unary level — `! A || B` is `(!A) || B`, NOT `!(A || B)`. The inner
2182    // `recursive` lets `!` chain (`! ! expr`) while bottoming out at a
2183    // primary test, so the bang never swallows a following `&&`/`||` operand.
2184    let unary = recursive(|unary| {
2185        let not_expr = just(Token::Bang)
2186            .ignore_then(unary)
2187            .map(|expr| TestExpr::Not { expr: Box::new(expr) });
2188        choice((not_expr, primary_test.clone()))
2189    });
2190
2191    // AND level: unary && unary && ...
2192    let and_expr = unary.clone().foldl(
2193        just(Token::And).ignore_then(unary).repeated(),
2194        |left, right| TestExpr::And {
2195            left: Box::new(left),
2196            right: Box::new(right),
2197        },
2198    );
2199
2200    // OR level: and_expr || and_expr || ...
2201    let compound_test = and_expr.clone().foldl(
2202        just(Token::Or).ignore_then(and_expr).repeated(),
2203        |left, right| TestExpr::Or {
2204            left: Box::new(left),
2205            right: Box::new(right),
2206        },
2207    );
2208
2209    // [[ ]] is two consecutive bracket tokens (not a single TestStart token)
2210    // to avoid conflicts with nested array syntax like [[1, 2], [3, 4]]
2211    just(Token::LBracket)
2212        .then(just(Token::LBracket))
2213        .ignore_then(compound_test)
2214        .then_ignore(just(Token::RBracket).then(just(Token::RBracket)))
2215        .labelled("test expression")
2216        .boxed()
2217}
2218
2219/// Condition parser: supports [[ ]] test expressions and commands with && / || chaining.
2220///
2221/// Shell semantics: conditions are commands whose exit codes determine truthiness.
2222/// - `if true; then` → runs `true` builtin, exit code 0 = truthy
2223/// - `if grep -q pattern file; then` → runs command, checks exit code
2224/// - `if a && b; then` → runs `a`, if exit 0, runs `b`
2225///
2226/// Use `[[ ]]` for comparisons: `if [[ $X -gt 5 ]]; then`
2227///
2228/// Grammar (with precedence - && binds tighter than ||):
2229///   condition = or_expr
2230///   or_expr   = and_expr { "||" and_expr }
2231///   and_expr  = base { "&&" base }
2232///   base      = test_expr | command
2233fn condition_parser<'tokens, I>(
2234) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2235where
2236    I: ValueInput<'tokens, Token = Token, Span = Span>,
2237{
2238    // [[ ]] test expression - wrap as Expr::Test
2239    let test_expr_condition = test_expr_stmt_parser().map(|test| Expr::Test(Box::new(test)));
2240
2241    // Command as condition (includes true/false as command names)
2242    // The command's exit code determines truthiness (0 = true, non-zero = false)
2243    let command_condition = command_parser().map(Expr::Command);
2244
2245    // Base: test expr OR command
2246    let base = choice((test_expr_condition, command_condition));
2247
2248    // && has higher precedence than ||
2249    // First chain with && (higher precedence)
2250    let and_expr = base.clone().foldl(
2251        just(Token::And).ignore_then(base).repeated(),
2252        |left, right| Expr::BinaryOp {
2253            left: Box::new(left),
2254            op: BinaryOp::And,
2255            right: Box::new(right),
2256        },
2257    );
2258
2259    // Then chain with || (lower precedence)
2260    and_expr
2261        .clone()
2262        .foldl(
2263            just(Token::Or).ignore_then(and_expr).repeated(),
2264            |left, right| Expr::BinaryOp {
2265                left: Box::new(left),
2266                op: BinaryOp::Or,
2267                right: Box::new(right),
2268            },
2269        )
2270        .labelled("condition")
2271        .boxed()
2272}
2273
2274/// Expression parser - supports && and || binary operators.
2275///
2276/// Used by `for`-head items (among others), which must stay `$()`-only
2277/// (bare `$VAR` splice is rejected upstream by validator E012 — see
2278/// docs/LANGUAGE.md) and must NOT gain collection literals later. Do not
2279/// reroute this to the value seam.
2280fn expr_parser<'tokens, I>(
2281) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2282where
2283    I: ValueInput<'tokens, Token = Token, Span = Span>,
2284{
2285    // For now, just primary expressions. Can extend for && / || later if needed.
2286    primary_expr_parser()
2287}
2288
2289/// Value-position expression parser (assignment RHS: bash-style, `local`,
2290/// and env-prefix). Adds collection literals on top of everything
2291/// `primary_expr_parser` covers, so they appear on assignment RHS but never
2292/// in argv or `for`-head items (`expr_parser`, above, stays untouched).
2293fn value_expr_parser<'tokens, I>(
2294) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2295where
2296    I: ValueInput<'tokens, Token = Token, Span = Span>,
2297{
2298    value_literal_parser()
2299}
2300
2301/// Value-position primary parser (`in`/`not in` RHS operand only — the
2302/// collection being tested for membership; the left needle stays on
2303/// `primary_expr_parser`). Same grammar as `value_expr_parser`; kept as a
2304/// separate name because the two seams are conceptually distinct call sites
2305/// (see PR-A) even though they currently share an implementation.
2306fn value_primary_parser<'tokens, I>(
2307) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2308where
2309    I: ValueInput<'tokens, Token = Token, Span = Span>,
2310{
2311    value_literal_parser()
2312}
2313
2314/// The value-position grammar: list/record literals (tried first, so a
2315/// `[`/`{` at value position is always a literal — never a bareword/glob),
2316/// falling back to everything `primary_expr_parser` covers ($(), `$VAR`,
2317/// scalars, …). `recursive` lets literal interiors reference this same
2318/// grammar, so nesting (`{tags: [a b], meta: {active: true}}`) and spread
2319/// (`[...$xs date]`) both parse.
2320///
2321/// The lexer guarantees a `[`/`{` reaching here at value position was never
2322/// fused into a `GlobWord`/colon-joined `Ident` (see
2323/// `lexer::compute_value_context`), so this choice never needs to "unfuse"
2324/// anything — it just sees primitive bracket/brace tokens.
2325fn value_literal_parser<'tokens, I>(
2326) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2327where
2328    I: ValueInput<'tokens, Token = Token, Span = Span>,
2329{
2330    recursive(|value| {
2331        choice((
2332            list_literal_parser(value.clone()),
2333            record_literal_parser(value.clone()),
2334            primary_expr_parser(),
2335        ))
2336    })
2337    .boxed()
2338}
2339
2340/// List literal: `[a b c]`, `[]`, `[...$xs date]`. Elements may be separated
2341/// by whitespace alone, commas, newlines, or any mix — all optional and
2342/// interchangeable (see docs/arrays-and-hashes.md, "Commas optional in BOTH
2343/// lists and records") — and newlines are consumed rather than treated as
2344/// statement terminators, so a multi-line literal doesn't end the assignment
2345/// early. A bare element nests as ONE item; `...` flattens a list operand's
2346/// elements into this one (spread).
2347fn list_literal_parser<'tokens, I, V>(
2348    value: V,
2349) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2350where
2351    I: ValueInput<'tokens, Token = Token, Span = Span>,
2352    V: Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
2353{
2354    let spread_elem = just(Token::DotDotDot)
2355        .ignore_then(value.clone())
2356        .map(ListElem::Spread);
2357    let item_elem = value.map(ListElem::Item);
2358    let elem = choice((spread_elem, item_elem));
2359
2360    let sep = choice((just(Token::Comma).to(()), just(Token::Newline).to(()))).repeated();
2361
2362    just(Token::LBracket)
2363        .ignore_then(just(Token::Newline).repeated())
2364        .ignore_then(elem.then_ignore(sep).repeated().collect::<Vec<_>>())
2365        .then_ignore(just(Token::RBracket))
2366        .map(Expr::ListLiteral)
2367        .labelled("list literal")
2368}
2369
2370/// Record literal: `{name: amy, role: maintainer}`, `{port:8080}` (the
2371/// colon-fusion exemption in the lexer means both spellings reach here as
2372/// the same three tokens). Keys are a bareword (`Ident`) or a quoted string
2373/// (for anything that isn't a bareword, e.g. `{"content-type": x}`); values
2374/// are the full recursive value grammar, so nested literals work. Entries
2375/// separate the same way list elements do (comma/newline/whitespace, all
2376/// optional) — including multi-line literals with a trailing comma.
2377fn record_literal_parser<'tokens, I, V>(
2378    value: V,
2379) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2380where
2381    I: ValueInput<'tokens, Token = Token, Span = Span>,
2382    V: Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
2383{
2384    let bare_key = select! { Token::Ident(s) => RecordKey::Bare(s) };
2385    // A double-quoted key interpolates like any double-quoted string ({"$k": v}
2386    // resolves $k at eval time — it used to silently create a literal "$k"
2387    // key); a pure-literal result folds back to Quoted so the common case
2388    // carries no eval overhead. Single quotes stay verbatim — the escape hatch
2389    // for a literal `$` in a key.
2390    let double_key = select! { Token::String(s) => s }.try_map(|s, span| {
2391        let parts = parse_interpolated_string(&s)
2392            .map_err(|e| Rich::custom(span, format!("record key: {e}")))?;
2393        Ok(match parts.as_slice() {
2394            [] => RecordKey::Quoted(String::new()),
2395            [StringPart::Literal(lit)] => RecordKey::Quoted(lit.clone()),
2396            _ => RecordKey::Interpolated(parts),
2397        })
2398    });
2399    let single_key = select! { Token::SingleString(s) => RecordKey::Quoted(s) };
2400    let key = choice((double_key, single_key, bare_key)).labelled("record key");
2401
2402    let entry = key
2403        .then_ignore(just(Token::Colon))
2404        .then(value)
2405        .map(|(key, value)| RecordEntry { key, value });
2406
2407    let sep = choice((just(Token::Comma).to(()), just(Token::Newline).to(()))).repeated();
2408
2409    just(Token::LBrace)
2410        .ignore_then(just(Token::Newline).repeated())
2411        .ignore_then(entry.then_ignore(sep).repeated().collect::<Vec<_>>())
2412        .then_ignore(just(Token::RBrace))
2413        .map(Expr::RecordLiteral)
2414        .labelled("record literal")
2415}
2416
2417/// Primary expression: literal, variable reference, command substitution, or bare identifier.
2418///
2419/// Uses `recursive` to support nested command substitution like `$(echo $(date))`.
2420fn primary_expr_parser<'tokens, I>(
2421) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2422where
2423    I: ValueInput<'tokens, Token = Token, Span = Span>,
2424{
2425    // Positional parameters: $0-$9, $@, $#, ${#VAR}, $?, $$
2426    let positional = select! {
2427        Token::Positional(n) => Expr::Positional(n),
2428        Token::AllArgs => Expr::AllArgs,
2429        Token::ArgCount => Expr::ArgCount,
2430        Token::VarLength(name) => Expr::VarLength(parse_varpath(&format!("${{{name}}}"))),
2431        Token::LastExitCode => Expr::LastExitCode,
2432        Token::CurrentPid => Expr::CurrentPid,
2433    };
2434
2435    // Arithmetic expression: $((expr)) - preprocessed into Arithmetic token
2436    let arithmetic = select! {
2437        Token::Arithmetic(expr_str) => Expr::Arithmetic(expr_str),
2438    };
2439
2440    // Keywords that can also be used as barewords in argument position
2441    // (e.g., `echo done` should work even though `done` is a keyword)
2442    let keyword_as_bareword = select! {
2443        Token::Done => "done",
2444        Token::Fi => "fi",
2445        Token::Then => "then",
2446        Token::Else => "else",
2447        Token::Elif => "elif",
2448        Token::In => "in",
2449        Token::Do => "do",
2450        Token::Esac => "esac",
2451        // `set` in argument position is the literal word (`echo set`,
2452        // `kaish-output-limit set 1K`); the `set` *builtin* is only matched
2453        // when `Token::Set` leads a statement (see `set_command`), so this
2454        // arm never shadows it.
2455        Token::Set => "set",
2456    }
2457    .map(|s| Expr::Literal(Value::String(s.to_string())));
2458
2459    // Bare words starting with + or - (e.g., date +%s, cat -), and a
2460    // `--`-prefixed word that isn't a valid long flag (`echo ---`,
2461    // `echo --=x`, GH #137).
2462    let plus_minus_bare = select! {
2463        Token::PlusBare(s) => Expr::Literal(Value::String(s)),
2464        Token::MinusBare(s) => Expr::Literal(Value::String(s)),
2465        Token::MinusAlone => Expr::Literal(Value::String("-".to_string())),
2466        Token::DoubleDashBare(s) => Expr::Literal(Value::String(s)),
2467    };
2468
2469    // Glob patterns: merged GlobWord tokens and bare Star/Question
2470    let glob_pattern = select! {
2471        Token::GlobWord(s) => Expr::GlobPattern(s),
2472        Token::Star => Expr::GlobPattern("*".to_string()),
2473        Token::Question => Expr::GlobPattern("?".to_string()),
2474    };
2475
2476    recursive(|expr| {
2477        choice((
2478            positional,
2479            arithmetic,
2480            cmd_subst_parser(expr.clone()),
2481            var_expr_parser(),
2482            interpolated_string_parser(),
2483            literal_parser().map(Expr::Literal),
2484            // Glob patterns before ident (GlobWord is more specific)
2485            glob_pattern,
2486            // Bare identifiers become string literals (shell barewords)
2487            ident_parser().map(|s| Expr::Literal(Value::String(s))),
2488            // Absolute paths become string literals
2489            path_parser().map(|s| Expr::Literal(Value::String(s))),
2490            // Bare words starting with + or - (date +%s, cat -)
2491            // Shell navigation tokens
2492            select! {
2493                // Bare `.` in argument/expression position is the literal
2494                // current-directory path (`find .`, `ls .`, `echo .`). The
2495                // `source` alias is unaffected: `command_parser` consumes a
2496                // *leading* `.` as the command name before args are parsed,
2497                // so only a `.` that follows a command reaches here.
2498                Token::Dot => Expr::Literal(Value::String(".".into())),
2499                Token::DotDot => Expr::Literal(Value::String("..".into())),
2500                // Bare comma in argument position is the literal "," — the
2501                // `cut -d, -f2` / `tr -d ,` delimiter idiom. Brace expansion
2502                // consumes its separator commas inside `{…}` before reaching
2503                // here, and a run of comma-touching positionals (`echo 1,2,3`)
2504                // is still caught by the no-token-pasting guard in
2505                // `args_list_parser`. See docs/issues.md.
2506                Token::Comma => Expr::Literal(Value::String(",".into())),
2507                // Bare colon in argument position is the literal ":" — the
2508                // `awk -F: '{print $1}'` / `--field-separator=:` idiom and
2509                // the bash no-op `:` alias. In statement position the colon is
2510                // the no-op command (handled by `command_parser`); here it is
2511                // only reached after a command name has been parsed, so there
2512                // is no ambiguity with the statement form.
2513                Token::Colon => Expr::Literal(Value::String(":".into())),
2514                Token::Tilde => Expr::Literal(Value::String("~".into())),
2515                Token::TildePath(s) => Expr::Literal(Value::String(s)),
2516                Token::RelativePath(s) => Expr::Literal(Value::String(s)),
2517                Token::DotSlashPath(s) => Expr::Literal(Value::String(s)),
2518                // Digit-leading bareword (SHA prefix `019dda1c`, UUIDs).
2519                Token::NumberIdent(s) => Expr::Literal(Value::String(s)),
2520                // Hyphenated/minus-led numeric word (`2024-01-02`, `10-20`,
2521                // `1.5-2`, `cut -f 1-3`, `find -size -1k`) — one contiguous word.
2522                Token::DashNumWord(s) => Expr::Literal(Value::String(s)),
2523                // Leading-`@` bareword (`@scope/pkg`, `@0`, bare `@`).
2524                Token::AtWord(s) => Expr::Literal(Value::String(s)),
2525                // Dot-prefixed bareword (`.gitignore`, `.parent`, `.parent.parent`).
2526                // Distinct from `Token::Dot` (the source alias), which only
2527                // matches a bare `.` and requires whitespace before its file
2528                // argument.
2529                Token::DottedIdent(s) => Expr::Literal(Value::String(s)),
2530                // Job specifier `%1` for wait/kill — flows as the literal
2531                // string "%1"; the builtins interpret the leading `%`.
2532                Token::JobSpec(s) => Expr::Literal(Value::String(s)),
2533            },
2534            plus_minus_bare,
2535            // Keywords can be used as barewords in argument position
2536            keyword_as_bareword,
2537        ))
2538        .labelled("expression")
2539    })
2540    .boxed()
2541}
2542
2543/// Variable reference: `${VAR}`, `${VAR.field}`, `${VAR:-default}`, or `$VAR` (simple form).
2544/// Returns Expr directly to support both VarRef and VarWithDefault.
2545fn var_expr_parser<'tokens, I>(
2546) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2547where
2548    I: ValueInput<'tokens, Token = Token, Span = Span>,
2549{
2550    select! {
2551        Token::VarRef(raw) => parse_var_expr(&raw),
2552        Token::SimpleVarRef(name) => Expr::VarRef(VarPath::simple(name)),
2553    }
2554    .labelled("variable reference")
2555}
2556
2557/// Command substitution: `$(pipeline)` - runs a pipeline and returns its result.
2558///
2559/// Accepts a recursive expression parser to support nested command substitution.
2560fn cmd_subst_parser<'tokens, I, E>(
2561    expr: E,
2562) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2563where
2564    I: ValueInput<'tokens, Token = Token, Span = Span>,
2565    E: Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
2566{
2567    // Argument parser using the recursive expression parser
2568    // Long flag with value: --name=value
2569    let long_flag_with_value = select! {
2570        Token::LongFlag(name) => name,
2571    }
2572    .then_ignore(just(Token::Eq))
2573    .then(expr.clone())
2574    .map(|(key, value)| Arg::Named { key, value });
2575
2576    // Boolean long flag: --name
2577    let long_flag = select! {
2578        Token::LongFlag(name) => Arg::LongFlag(name),
2579    };
2580
2581    // Boolean short flag: -x
2582    let short_flag = select! {
2583        Token::ShortFlag(name) => Arg::ShortFlag(name),
2584    };
2585
2586    // Shell assignment in argv position: name=value (see arg_before_double_dash_parser).
2587    // Keyword keys (`if=`, `in=`, …) are accepted so `$(dd if=x)` parses.
2588    let named = choice((ident_parser(), keyword_word()))
2589        .then_ignore(just(Token::Eq))
2590        .then(expr.clone())
2591        .map(|(key, value)| Arg::WordAssign { key, value });
2592
2593    // Positional argument
2594    let positional = expr.clone().map(Arg::Positional);
2595
2596    let arg = choice((
2597        long_flag_with_value,
2598        long_flag,
2599        short_flag,
2600        named,
2601        positional,
2602    ));
2603
2604    // Command name parser - accepts identifiers and boolean keywords (true/false are builtins)
2605    let command_name = choice((
2606        ident_parser(),
2607        just(Token::True).to("true".to_string()),
2608        just(Token::False).to("false".to_string()),
2609    ));
2610
2611    // Command parser. Trailing redirects (`> file`, `2> file`, `>> file`, …)
2612    // reuse the same `redirect_parser` combinator the top-level
2613    // `command_parser` uses, so `$(cmd > file)` parses like any other command.
2614    // The redirect *target* threads the recursive `expr` handle (not a fresh
2615    // `primary_expr_parser()`) so the target may itself contain `$(...)` while
2616    // avoiding an unbounded parser-construction cycle.
2617    let command = command_name
2618        .then(arg.repeated().collect::<Vec<_>>())
2619        .then(
2620            redirect_parser(expr.clone())
2621                .repeated()
2622                .collect::<Vec<_>>(),
2623        )
2624        .map(|((name, args), redirects)| Command {
2625            name,
2626            args,
2627            redirects,
2628        });
2629
2630    // Pipeline parser
2631    let pipeline = command
2632        .separated_by(just(Token::Pipe))
2633        .at_least(1)
2634        .collect::<Vec<_>>()
2635        .map(|commands| Pipeline {
2636            commands,
2637            background: false,
2638        });
2639
2640    // A single pipeline becomes one statement (`$(echo x)` → one `Stmt::Command`),
2641    // keeping the AST shape uniform with the rest of the parser.
2642    let pipeline_stmt = pipeline.map(pipeline_into_stmt);
2643
2644    // Statement chaining inside `$()`. `&&` and `||` have EQUAL precedence and
2645    // associate left-to-right (POSIX) — the same single left fold as the top
2646    // level (`statement_parser`), NOT `&&`-binds-tighter. This is the full
2647    // statement grammar a command substitution body accepts — pipelines,
2648    // `&&`/`||` chains, and (via the sequence below) `;`/newline separators and
2649    // `#` comments. Control structures (`if`/`for`/`while`/`case`) are
2650    // intentionally out of scope here (see docs/issues.md).
2651    let chained = pipeline_stmt.clone().foldl(
2652        choice((
2653            just(Token::And).to(true), // true = &&
2654            just(Token::Or).to(false), // false = ||
2655        ))
2656        .then(pipeline_stmt.clone())
2657        .repeated(),
2658        |left, (is_and, right): (bool, Stmt)| {
2659            if is_and {
2660                Stmt::AndChain {
2661                    left: Box::new(left),
2662                    right: Box::new(right),
2663                }
2664            } else {
2665                Stmt::OrChain {
2666                    left: Box::new(left),
2667                    right: Box::new(right),
2668                }
2669            }
2670        },
2671    );
2672
2673    // `;` / newline separated sequence of chained statements, with optional
2674    // leading/trailing/interior separators (so multi-line bodies and a trailing
2675    // `;` or comment-induced newline parse cleanly). `#` comments lex to
2676    // newlines, so they are consumed here as ordinary separators.
2677    let separator = choice((just(Token::Newline), just(Token::Semi)));
2678    let body = separator
2679        .clone()
2680        .repeated()
2681        .ignore_then(
2682            chained
2683                .separated_by(separator.clone().repeated().at_least(1))
2684                .allow_trailing()
2685                .collect::<Vec<_>>(),
2686        )
2687        .then_ignore(separator.repeated());
2688
2689    just(Token::CmdSubstStart)
2690        .ignore_then(body)
2691        .then_ignore(just(Token::RParen))
2692        .map(Expr::CommandSubst)
2693        .labelled("command substitution")
2694}
2695
2696/// String parser - handles double-quoted strings (with interpolation) and single-quoted (literal).
2697fn interpolated_string_parser<'tokens, I>(
2698) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2699where
2700    I: ValueInput<'tokens, Token = Token, Span = Span>,
2701{
2702    // Double-quoted string: may contain $VAR or ${VAR} interpolation
2703    let double_quoted = select! {
2704        Token::String(s) => s,
2705    }
2706    .try_map(|s, span| {
2707        // Check if string contains interpolation markers (${} or $NAME) or escaped dollars
2708        if s.contains('$') || s.contains("__KAISH_ESCAPED_DOLLAR__") {
2709            // Parse interpolated parts. A syntax error inside a `$(…)` is loud
2710            // (Rich error at this string's span), not silently demoted to text.
2711            let parts = parse_interpolated_string(&s)
2712                .map_err(|msg| Rich::custom(span, msg))?;
2713            if parts.len() == 1
2714                && let StringPart::Literal(text) = &parts[0] {
2715                    return Ok(Expr::Literal(Value::String(text.clone())));
2716                }
2717            Ok(Expr::Interpolated(parts))
2718        } else {
2719            Ok(Expr::Literal(Value::String(s)))
2720        }
2721    });
2722
2723    // Single-quoted string: literal, no interpolation
2724    let single_quoted = select! {
2725        Token::SingleString(s) => Expr::Literal(Value::String(s)),
2726    };
2727
2728    choice((single_quoted, double_quoted)).labelled("string")
2729}
2730
2731/// Literal value parser (excluding strings, which are handled by interpolated_string_parser).
2732fn literal_parser<'tokens, I>(
2733) -> impl Parser<'tokens, I, Value, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2734where
2735    I: ValueInput<'tokens, Token = Token, Span = Span>,
2736{
2737    choice((
2738        select! {
2739            Token::True => Value::Bool(true),
2740            Token::False => Value::Bool(false),
2741        },
2742        select! {
2743            Token::Int(n) => Value::Int(n),
2744            Token::Float(f) => Value::Float(f),
2745        },
2746    ))
2747    .labelled("literal")
2748    .boxed()
2749}
2750
2751/// Identifier parser.
2752fn ident_parser<'tokens, I>(
2753) -> impl Parser<'tokens, I, String, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2754where
2755    I: ValueInput<'tokens, Token = Token, Span = Span>,
2756{
2757    select! {
2758        Token::Ident(s) => s,
2759    }
2760    .labelled("identifier")
2761}
2762
2763/// Path parser: matches absolute paths like `/tmp/out`, `/etc/hosts`.
2764fn path_parser<'tokens, I>(
2765) -> impl Parser<'tokens, I, String, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2766where
2767    I: ValueInput<'tokens, Token = Token, Span = Span>,
2768{
2769    select! {
2770        Token::Path(s) => s,
2771    }
2772    .labelled("path")
2773}
2774
2775#[cfg(test)]
2776#[allow(clippy::approx_constant)]
2777mod tests {
2778    use super::*;
2779
2780    /// Extract the single `Command` from a one-statement `$(cmd)` body.
2781    fn subst_cmd(expr: &Expr) -> &Command {
2782        match expr {
2783            Expr::CommandSubst(stmts) => match stmts.as_slice() {
2784                [Stmt::Command(cmd)] => cmd,
2785                other => panic!("expected a single command in $(), got {other:?}"),
2786            },
2787            other => panic!("expected command subst, got {other:?}"),
2788        }
2789    }
2790
2791    /// Extract the single `Pipeline` from a one-statement `$(a | b)` body.
2792    fn subst_pipeline(expr: &Expr) -> &Pipeline {
2793        match expr {
2794            Expr::CommandSubst(stmts) => match stmts.as_slice() {
2795                [Stmt::Pipeline(p)] => p,
2796                other => panic!("expected a single pipeline in $(), got {other:?}"),
2797            },
2798            other => panic!("expected command subst, got {other:?}"),
2799        }
2800    }
2801
2802    #[test]
2803    fn parse_empty() {
2804        let result = parse("");
2805        assert!(result.is_ok());
2806        assert_eq!(result.expect("ok").statements.len(), 0);
2807    }
2808
2809    #[test]
2810    fn parse_newlines_only() {
2811        let result = parse("\n\n\n");
2812        assert!(result.is_ok());
2813    }
2814
2815    #[test]
2816    fn parse_simple_command() {
2817        let result = parse("echo");
2818        assert!(result.is_ok());
2819        let program = result.expect("ok");
2820        assert_eq!(program.statements.len(), 1);
2821        assert!(matches!(&program.statements[0], Stmt::Command(_)));
2822    }
2823
2824    #[test]
2825    fn parse_command_with_string_arg() {
2826        let result = parse(r#"echo "hello""#);
2827        assert!(result.is_ok());
2828        let program = result.expect("ok");
2829        match &program.statements[0] {
2830            Stmt::Command(cmd) => assert_eq!(cmd.args.len(), 1),
2831            _ => panic!("expected Command"),
2832        }
2833    }
2834
2835    #[test]
2836    fn parse_assignment() {
2837        let result = parse("X=5");
2838        assert!(result.is_ok());
2839        let program = result.expect("ok");
2840        assert!(matches!(&program.statements[0], Stmt::Assignment(_)));
2841    }
2842
2843    #[test]
2844    fn parse_pipeline() {
2845        let result = parse("a | b | c");
2846        assert!(result.is_ok());
2847        let program = result.expect("ok");
2848        match &program.statements[0] {
2849            Stmt::Pipeline(p) => assert_eq!(p.commands.len(), 3),
2850            _ => panic!("expected Pipeline"),
2851        }
2852    }
2853
2854    #[test]
2855    fn parse_background_job() {
2856        let result = parse("cmd &");
2857        assert!(result.is_ok());
2858        let program = result.expect("ok");
2859        match &program.statements[0] {
2860            Stmt::Pipeline(p) => assert!(p.background),
2861            _ => panic!("expected Pipeline with background"),
2862        }
2863    }
2864
2865    #[test]
2866    fn parse_if_simple() {
2867        let result = parse("if true; then echo; fi");
2868        assert!(result.is_ok());
2869        let program = result.expect("ok");
2870        assert!(matches!(&program.statements[0], Stmt::If(_)));
2871    }
2872
2873    #[test]
2874    fn parse_if_else() {
2875        let result = parse("if true; then echo; else echo; fi");
2876        assert!(result.is_ok());
2877        let program = result.expect("ok");
2878        match &program.statements[0] {
2879            Stmt::If(if_stmt) => assert!(if_stmt.else_branch.is_some()),
2880            _ => panic!("expected If"),
2881        }
2882    }
2883
2884    #[test]
2885    fn parse_elif_simple() {
2886        let result = parse("if true; then echo a; elif false; then echo b; fi");
2887        assert!(result.is_ok(), "parse failed: {:?}", result);
2888        let program = result.expect("ok");
2889        match &program.statements[0] {
2890            Stmt::If(if_stmt) => {
2891                // elif is desugared to nested if in else
2892                assert!(if_stmt.else_branch.is_some());
2893                let else_branch = if_stmt.else_branch.as_ref().unwrap();
2894                assert_eq!(else_branch.len(), 1);
2895                assert!(matches!(&else_branch[0], Stmt::If(_)));
2896            }
2897            _ => panic!("expected If"),
2898        }
2899    }
2900
2901    #[test]
2902    fn parse_elif_with_else() {
2903        let result = parse("if true; then echo a; elif false; then echo b; else echo c; fi");
2904        assert!(result.is_ok(), "parse failed: {:?}", result);
2905        let program = result.expect("ok");
2906        match &program.statements[0] {
2907            Stmt::If(outer_if) => {
2908                // Check nested structure: if -> elif -> else
2909                let else_branch = outer_if.else_branch.as_ref().expect("outer else");
2910                assert_eq!(else_branch.len(), 1);
2911                match &else_branch[0] {
2912                    Stmt::If(inner_if) => {
2913                        // The inner if (from elif) should have the final else
2914                        assert!(inner_if.else_branch.is_some());
2915                    }
2916                    _ => panic!("expected nested If from elif"),
2917                }
2918            }
2919            _ => panic!("expected If"),
2920        }
2921    }
2922
2923    #[test]
2924    fn parse_multiple_elif() {
2925        // Shell-compatible: use [[ ]] for comparisons
2926        let result = parse(
2927            "if [[ ${X} == 1 ]]; then echo one; elif [[ ${X} == 2 ]]; then echo two; elif [[ ${X} == 3 ]]; then echo three; else echo other; fi",
2928        );
2929        assert!(result.is_ok(), "parse failed: {:?}", result);
2930    }
2931
2932    #[test]
2933    fn parse_for_loop() {
2934        let result = parse("for X in items; do echo; done");
2935        assert!(result.is_ok());
2936        let program = result.expect("ok");
2937        assert!(matches!(&program.statements[0], Stmt::For(_)));
2938    }
2939
2940    #[test]
2941    fn parse_brackets_not_array_literal() {
2942        // Array literals are no longer supported, [ is just a regular char
2943        let result = parse("cmd [1");
2944        // This should fail or parse unexpectedly - arrays are removed
2945        // Just verify we don't crash
2946        let _ = result;
2947    }
2948
2949    #[test]
2950    fn parse_named_arg() {
2951        // Bareword key=value parses as WordAssign — the kernel decides per
2952        // command whether to route it to tool_args.named (export/alias) or
2953        // stringify to a positional (every other builtin).
2954        let result = parse("cmd foo=5");
2955        assert!(result.is_ok());
2956        let program = result.expect("ok");
2957        match &program.statements[0] {
2958            Stmt::Command(cmd) => {
2959                assert_eq!(cmd.args.len(), 1);
2960                assert!(matches!(&cmd.args[0], Arg::WordAssign { .. }));
2961            }
2962            _ => panic!("expected Command"),
2963        }
2964    }
2965
2966    #[test]
2967    fn parse_short_flag() {
2968        let result = parse("ls -l");
2969        assert!(result.is_ok());
2970        let program = result.expect("ok");
2971        match &program.statements[0] {
2972            Stmt::Command(cmd) => {
2973                assert_eq!(cmd.name, "ls");
2974                assert_eq!(cmd.args.len(), 1);
2975                match &cmd.args[0] {
2976                    Arg::ShortFlag(name) => assert_eq!(name, "l"),
2977                    _ => panic!("expected ShortFlag"),
2978                }
2979            }
2980            _ => panic!("expected Command"),
2981        }
2982    }
2983
2984    #[test]
2985    fn parse_long_flag() {
2986        let result = parse("git push --force");
2987        assert!(result.is_ok());
2988        let program = result.expect("ok");
2989        match &program.statements[0] {
2990            Stmt::Command(cmd) => {
2991                assert_eq!(cmd.name, "git");
2992                assert_eq!(cmd.args.len(), 2);
2993                match &cmd.args[0] {
2994                    Arg::Positional(Expr::Literal(Value::String(s))) => assert_eq!(s, "push"),
2995                    _ => panic!("expected Positional push"),
2996                }
2997                match &cmd.args[1] {
2998                    Arg::LongFlag(name) => assert_eq!(name, "force"),
2999                    _ => panic!("expected LongFlag"),
3000                }
3001            }
3002            _ => panic!("expected Command"),
3003        }
3004    }
3005
3006    #[test]
3007    fn parse_long_flag_with_value() {
3008        let result = parse(r#"git commit --message="hello""#);
3009        assert!(result.is_ok());
3010        let program = result.expect("ok");
3011        match &program.statements[0] {
3012            Stmt::Command(cmd) => {
3013                assert_eq!(cmd.name, "git");
3014                assert_eq!(cmd.args.len(), 2);
3015                match &cmd.args[1] {
3016                    Arg::Named { key, value } => {
3017                        assert_eq!(key, "message");
3018                        match value {
3019                            Expr::Literal(Value::String(s)) => assert_eq!(s, "hello"),
3020                            _ => panic!("expected String value"),
3021                        }
3022                    }
3023                    _ => panic!("expected Named from --flag=value"),
3024                }
3025            }
3026            _ => panic!("expected Command"),
3027        }
3028    }
3029
3030    #[test]
3031    fn parse_mixed_flags_and_args() {
3032        let result = parse(r#"git commit -m "message" --amend"#);
3033        assert!(result.is_ok());
3034        let program = result.expect("ok");
3035        match &program.statements[0] {
3036            Stmt::Command(cmd) => {
3037                assert_eq!(cmd.name, "git");
3038                assert_eq!(cmd.args.len(), 4);
3039                // commit (positional)
3040                assert!(matches!(&cmd.args[0], Arg::Positional(_)));
3041                // -m (short flag)
3042                match &cmd.args[1] {
3043                    Arg::ShortFlag(name) => assert_eq!(name, "m"),
3044                    _ => panic!("expected ShortFlag -m"),
3045                }
3046                // "message" (positional)
3047                assert!(matches!(&cmd.args[2], Arg::Positional(_)));
3048                // --amend (long flag)
3049                match &cmd.args[3] {
3050                    Arg::LongFlag(name) => assert_eq!(name, "amend"),
3051                    _ => panic!("expected LongFlag --amend"),
3052                }
3053            }
3054            _ => panic!("expected Command"),
3055        }
3056    }
3057
3058    #[test]
3059    fn parse_redirect_stdout() {
3060        let result = parse("cmd > file");
3061        assert!(result.is_ok());
3062        let program = result.expect("ok");
3063        // Commands with redirects stay as Pipeline, not Command
3064        match &program.statements[0] {
3065            Stmt::Pipeline(p) => {
3066                assert_eq!(p.commands.len(), 1);
3067                let cmd = &p.commands[0];
3068                assert_eq!(cmd.redirects.len(), 1);
3069                assert!(matches!(cmd.redirects[0].kind, RedirectKind::StdoutOverwrite));
3070            }
3071            _ => panic!("expected Pipeline"),
3072        }
3073    }
3074
3075    #[test]
3076    fn parse_var_ref() {
3077        let result = parse("echo ${VAR}");
3078        assert!(result.is_ok());
3079        let program = result.expect("ok");
3080        match &program.statements[0] {
3081            Stmt::Command(cmd) => {
3082                assert_eq!(cmd.args.len(), 1);
3083                assert!(matches!(&cmd.args[0], Arg::Positional(Expr::VarRef(_))));
3084            }
3085            _ => panic!("expected Command"),
3086        }
3087    }
3088
3089    #[test]
3090    fn parse_multiple_statements() {
3091        let result = parse("a\nb\nc");
3092        assert!(result.is_ok());
3093        let program = result.expect("ok");
3094        let non_empty: Vec<_> = program.statements.iter().filter(|s| !matches!(s, Stmt::Empty)).collect();
3095        assert_eq!(non_empty.len(), 3);
3096    }
3097
3098    #[test]
3099    fn parse_semicolon_separated() {
3100        let result = parse("a; b; c");
3101        assert!(result.is_ok());
3102        let program = result.expect("ok");
3103        let non_empty: Vec<_> = program.statements.iter().filter(|s| !matches!(s, Stmt::Empty)).collect();
3104        assert_eq!(non_empty.len(), 3);
3105    }
3106
3107    #[test]
3108    fn parse_complex_pipeline() {
3109        let result = parse(r#"cat file | grep pattern="foo" | head count=10"#);
3110        assert!(result.is_ok());
3111        let program = result.expect("ok");
3112        match &program.statements[0] {
3113            Stmt::Pipeline(p) => assert_eq!(p.commands.len(), 3),
3114            _ => panic!("expected Pipeline"),
3115        }
3116    }
3117
3118    #[test]
3119    fn parse_json_as_string_arg() {
3120        // JSON arrays/objects should be passed as string arguments
3121        let result = parse(r#"cmd '[[1, 2], [3, 4]]'"#);
3122        assert!(result.is_ok());
3123    }
3124
3125    #[test]
3126    fn parse_mixed_args() {
3127        let result = parse(r#"cmd pos1 key="val" pos2 num=42"#);
3128        assert!(result.is_ok());
3129        let program = result.expect("ok");
3130        match &program.statements[0] {
3131            Stmt::Command(cmd) => assert_eq!(cmd.args.len(), 4),
3132            _ => panic!("expected Command"),
3133        }
3134    }
3135
3136    #[test]
3137    fn error_unterminated_string() {
3138        let result = parse(r#"echo "hello"#);
3139        assert!(result.is_err());
3140    }
3141
3142    #[test]
3143    fn error_unterminated_var_ref() {
3144        let result = parse("echo ${VAR");
3145        assert!(result.is_err());
3146    }
3147
3148    #[test]
3149    fn error_missing_fi() {
3150        let result = parse("if true; then echo");
3151        assert!(result.is_err());
3152    }
3153
3154    #[test]
3155    fn error_missing_done() {
3156        let result = parse("for X in items; do echo");
3157        assert!(result.is_err());
3158    }
3159
3160    #[test]
3161    fn parse_lvalue_single_index() {
3162        let result = parse("xs[0]=9").unwrap();
3163        match &result.statements[0] {
3164            Stmt::Assignment(a) => {
3165                assert_eq!(a.name(), "xs");
3166                assert_eq!(
3167                    a.path.segments,
3168                    vec![VarSegment::Field("xs".into()), VarSegment::Index(0)]
3169                );
3170                assert!(!a.local);
3171            }
3172            other => panic!("expected assignment, got {:?}", other),
3173        }
3174    }
3175
3176    #[test]
3177    fn parse_lvalue_negative_index() {
3178        let result = parse("xs[-1]=7").unwrap();
3179        match &result.statements[0] {
3180            Stmt::Assignment(a) => assert_eq!(
3181                a.path.segments,
3182                vec![VarSegment::Field("xs".into()), VarSegment::Index(-1)]
3183            ),
3184            other => panic!("expected assignment, got {:?}", other),
3185        }
3186    }
3187
3188    #[test]
3189    fn parse_lvalue_bareword_key() {
3190        let result = parse("user[email]=x").unwrap();
3191        match &result.statements[0] {
3192            Stmt::Assignment(a) => assert_eq!(
3193                a.path.segments,
3194                vec![
3195                    VarSegment::Field("user".into()),
3196                    VarSegment::Key("email".into())
3197                ]
3198            ),
3199            other => panic!("expected assignment, got {:?}", other),
3200        }
3201    }
3202
3203    #[test]
3204    fn parse_lvalue_chained_keys() {
3205        let result = parse("s[web][port]=9000").unwrap();
3206        match &result.statements[0] {
3207            Stmt::Assignment(a) => assert_eq!(
3208                a.path.segments,
3209                vec![
3210                    VarSegment::Field("s".into()),
3211                    VarSegment::Key("web".into()),
3212                    VarSegment::Key("port".into())
3213                ]
3214            ),
3215            other => panic!("expected assignment, got {:?}", other),
3216        }
3217    }
3218
3219    #[test]
3220    fn parse_lvalue_dynamic_key() {
3221        let result = parse("r[$k]=v").unwrap();
3222        match &result.statements[0] {
3223            Stmt::Assignment(a) => assert_eq!(
3224                a.path.segments,
3225                vec![
3226                    VarSegment::Field("r".into()),
3227                    VarSegment::Dynamic("k".into())
3228                ]
3229            ),
3230            other => panic!("expected assignment, got {:?}", other),
3231        }
3232    }
3233
3234    #[test]
3235    fn parse_local_lvalue_spaced() {
3236        let result = parse("local xs[0] = 9").unwrap();
3237        match &result.statements[0] {
3238            Stmt::Assignment(a) => {
3239                assert!(a.local);
3240                assert_eq!(
3241                    a.path.segments,
3242                    vec![VarSegment::Field("xs".into()), VarSegment::Index(0)]
3243                );
3244            }
3245            other => panic!("expected assignment, got {:?}", other),
3246        }
3247    }
3248
3249    #[test]
3250    fn env_prefix_subscripted_target_is_not_captured_as_env_scoped() {
3251        // A subscripted target before a following command (`user[email]=x
3252        // echo hi`) must NOT become `Stmt::EnvScoped` — structured values
3253        // can't cross the process boundary, so env-prefix stays bare-ident
3254        // only. The lexer suppression + `env_prefix_assign` using
3255        // `ident_parser()` (not `lvalue_path_parser()`) means this falls
3256        // through to an ordinary subscripted assignment followed by an
3257        // independent statement — the SAME back-to-back-without-a-terminator
3258        // shape `X=1 Y=2` already has (kaish's `terminator` is
3259        // `.repeated()`, not `.at_least(1)`), not a new hazard.
3260        let result = parse("user={}\nuser[email]=x echo hi").unwrap();
3261        for stmt in &result.statements {
3262            assert!(
3263                !matches!(stmt, Stmt::EnvScoped { .. }),
3264                "a subscripted assignment must never be captured into EnvScoped: {stmt:?}"
3265            );
3266        }
3267        // Sanity: it really did parse as two independent statements.
3268        assert!(matches!(&result.statements[1], Stmt::Assignment(a) if a.name() == "user"));
3269        assert!(matches!(&result.statements[2], Stmt::Command(c) if c.name == "echo"));
3270    }
3271
3272    #[test]
3273    fn parse_nested_cmd_subst() {
3274        // Nested command substitution is supported
3275        let result = parse("X=$(echo $(date))").unwrap();
3276        match &result.statements[0] {
3277            Stmt::Assignment(a) => {
3278                assert_eq!(a.name(), "X");
3279                let outer = subst_cmd(&a.value);
3280                assert_eq!(outer.name, "echo");
3281                // The argument should be another command substitution
3282                match &outer.args[0] {
3283                    Arg::Positional(inner_expr) => {
3284                        assert_eq!(subst_cmd(inner_expr).name, "date");
3285                    }
3286                    other => panic!("expected nested cmd subst arg, got {:?}", other),
3287                }
3288            }
3289            other => panic!("expected assignment, got {:?}", other),
3290        }
3291    }
3292
3293    #[test]
3294    fn parse_deeply_nested_cmd_subst() {
3295        // Three levels deep
3296        let result = parse("X=$(a $(b $(c)))").unwrap();
3297        match &result.statements[0] {
3298            Stmt::Assignment(a) => {
3299                let level1 = subst_cmd(&a.value);
3300                assert_eq!(level1.name, "a");
3301                match &level1.args[0] {
3302                    Arg::Positional(level2_expr) => {
3303                        let level2 = subst_cmd(level2_expr);
3304                        assert_eq!(level2.name, "b");
3305                        match &level2.args[0] {
3306                            Arg::Positional(level3_expr) => {
3307                                assert_eq!(subst_cmd(level3_expr).name, "c");
3308                            }
3309                            other => panic!("expected level3 cmd subst, got {:?}", other),
3310                        }
3311                    }
3312                    other => panic!("expected level2 cmd subst, got {:?}", other),
3313                }
3314            }
3315            other => panic!("expected assignment, got {:?}", other),
3316        }
3317    }
3318
3319    // ═══════════════════════════════════════════════════════════════════════════
3320    // Value Preservation Tests - These test that actual values are captured
3321    // ═══════════════════════════════════════════════════════════════════════════
3322
3323    #[test]
3324    fn value_int_preserved() {
3325        let result = parse("X=42").unwrap();
3326        match &result.statements[0] {
3327            Stmt::Assignment(a) => {
3328                assert_eq!(a.name(), "X");
3329                match &a.value {
3330                    Expr::Literal(Value::Int(n)) => assert_eq!(*n, 42),
3331                    other => panic!("expected int literal, got {:?}", other),
3332                }
3333            }
3334            other => panic!("expected assignment, got {:?}", other),
3335        }
3336    }
3337
3338    #[test]
3339    fn value_negative_int_preserved() {
3340        let result = parse("X=-99").unwrap();
3341        match &result.statements[0] {
3342            Stmt::Assignment(a) => match &a.value {
3343                Expr::Literal(Value::Int(n)) => assert_eq!(*n, -99),
3344                other => panic!("expected int, got {:?}", other),
3345            },
3346            other => panic!("expected assignment, got {:?}", other),
3347        }
3348    }
3349
3350    #[test]
3351    fn value_float_preserved() {
3352        let result = parse("PI=3.14").unwrap();
3353        match &result.statements[0] {
3354            Stmt::Assignment(a) => match &a.value {
3355                Expr::Literal(Value::Float(f)) => assert!((*f - 3.14).abs() < 0.001),
3356                other => panic!("expected float, got {:?}", other),
3357            },
3358            other => panic!("expected assignment, got {:?}", other),
3359        }
3360    }
3361
3362    #[test]
3363    fn value_string_preserved() {
3364        let result = parse(r#"echo "hello world""#).unwrap();
3365        match &result.statements[0] {
3366            Stmt::Command(cmd) => {
3367                assert_eq!(cmd.name, "echo");
3368                match &cmd.args[0] {
3369                    Arg::Positional(Expr::Literal(Value::String(s))) => {
3370                        assert_eq!(s, "hello world");
3371                    }
3372                    other => panic!("expected string arg, got {:?}", other),
3373                }
3374            }
3375            other => panic!("expected command, got {:?}", other),
3376        }
3377    }
3378
3379    #[test]
3380    fn value_string_with_escapes_preserved() {
3381        let result = parse(r#"echo "line1\nline2""#).unwrap();
3382        match &result.statements[0] {
3383            Stmt::Command(cmd) => match &cmd.args[0] {
3384                Arg::Positional(Expr::Literal(Value::String(s))) => {
3385                    assert_eq!(s, "line1\nline2");
3386                }
3387                other => panic!("expected string, got {:?}", other),
3388            },
3389            other => panic!("expected command, got {:?}", other),
3390        }
3391    }
3392
3393    #[test]
3394    fn value_command_name_preserved() {
3395        let result = parse("my-command").unwrap();
3396        match &result.statements[0] {
3397            Stmt::Command(cmd) => assert_eq!(cmd.name, "my-command"),
3398            other => panic!("expected command, got {:?}", other),
3399        }
3400    }
3401
3402    #[test]
3403    fn value_assignment_name_preserved() {
3404        let result = parse("MY_VAR=1").unwrap();
3405        match &result.statements[0] {
3406            Stmt::Assignment(a) => assert_eq!(a.name(), "MY_VAR"),
3407            other => panic!("expected assignment, got {:?}", other),
3408        }
3409    }
3410
3411    #[test]
3412    fn value_for_variable_preserved() {
3413        let result = parse("for ITEM in items; do echo; done").unwrap();
3414        match &result.statements[0] {
3415            Stmt::For(f) => assert_eq!(f.variable, "ITEM"),
3416            other => panic!("expected for, got {:?}", other),
3417        }
3418    }
3419
3420    #[test]
3421    fn value_varref_name_preserved() {
3422        let result = parse("echo ${MESSAGE}").unwrap();
3423        match &result.statements[0] {
3424            Stmt::Command(cmd) => match &cmd.args[0] {
3425                Arg::Positional(Expr::VarRef(path)) => {
3426                    assert_eq!(path.segments.len(), 1);
3427                    let VarSegment::Field(name) = &path.segments[0] else {
3428                        panic!("expected root field, got {:?}", path.segments[0]);
3429                    };
3430                    assert_eq!(name, "MESSAGE");
3431                }
3432                other => panic!("expected varref, got {:?}", other),
3433            },
3434            other => panic!("expected command, got {:?}", other),
3435        }
3436    }
3437
3438    #[test]
3439    fn value_varref_field_access_preserved() {
3440        let result = parse("echo ${RESULT.data}").unwrap();
3441        match &result.statements[0] {
3442            Stmt::Command(cmd) => match &cmd.args[0] {
3443                Arg::Positional(Expr::VarRef(path)) => {
3444                    // A dotted `${RESULT.data}` keeps both as Field — the root
3445                    // and a dotted segment (resolution turns the latter into the
3446                    // brackets-only error).
3447                    assert_eq!(path.segments.len(), 2);
3448                    let VarSegment::Field(a) = &path.segments[0] else {
3449                        panic!("expected field, got {:?}", path.segments[0]);
3450                    };
3451                    let VarSegment::Field(b) = &path.segments[1] else {
3452                        panic!("expected field, got {:?}", path.segments[1]);
3453                    };
3454                    assert_eq!(a, "RESULT");
3455                    assert_eq!(b, "data");
3456                }
3457                other => panic!("expected varref, got {:?}", other),
3458            },
3459            other => panic!("expected command, got {:?}", other),
3460        }
3461    }
3462
3463    #[test]
3464    fn value_varref_index_parsed() {
3465        // Bracket subscripts are now parsed into typed segments (native
3466        // collection access), not filtered out.
3467        let result = parse("echo ${ITEMS[0]}").unwrap();
3468        match &result.statements[0] {
3469            Stmt::Command(cmd) => match &cmd.args[0] {
3470                Arg::Positional(Expr::VarRef(path)) => {
3471                    assert_eq!(path.segments.len(), 2);
3472                    let VarSegment::Field(name) = &path.segments[0] else {
3473                        panic!("expected root field, got {:?}", path.segments[0]);
3474                    };
3475                    assert_eq!(name, "ITEMS");
3476                    assert_eq!(path.segments[1], VarSegment::Index(0));
3477                }
3478                other => panic!("expected varref, got {:?}", other),
3479            },
3480            other => panic!("expected command, got {:?}", other),
3481        }
3482    }
3483
3484    #[test]
3485    fn value_named_arg_preserved() {
3486        // Bareword key=value parses as WordAssign — the kernel decides per
3487        // command whether to route into args.named (export/alias) or
3488        // stringify as a positional.
3489        let result = parse("cmd count=42").unwrap();
3490        match &result.statements[0] {
3491            Stmt::Command(cmd) => {
3492                assert_eq!(cmd.name, "cmd");
3493                match &cmd.args[0] {
3494                    Arg::WordAssign { key, value } => {
3495                        assert_eq!(key, "count");
3496                        match value {
3497                            Expr::Literal(Value::Int(n)) => assert_eq!(*n, 42),
3498                            other => panic!("expected int, got {:?}", other),
3499                        }
3500                    }
3501                    other => panic!("expected WordAssign arg, got {:?}", other),
3502                }
3503            }
3504            other => panic!("expected command, got {:?}", other),
3505        }
3506    }
3507
3508    #[test]
3509    fn value_function_def_name_preserved() {
3510        let result = parse("greet() { echo }").unwrap();
3511        match &result.statements[0] {
3512            Stmt::ToolDef(t) => {
3513                assert_eq!(t.name, "greet");
3514                assert!(t.params.is_empty());
3515            }
3516            other => panic!("expected function def, got {:?}", other),
3517        }
3518    }
3519
3520    // ═══════════════════════════════════════════════════════════════════════════
3521    // New Feature Tests - Comparisons, Interpolation, Nested Structures
3522    // ═══════════════════════════════════════════════════════════════════════════
3523
3524    #[test]
3525    fn parse_comparison_equals() {
3526        // Shell-compatible: use [[ ]] for comparisons
3527        let result = parse("if [[ ${X} == 5 ]]; then echo; fi").unwrap();
3528        match &result.statements[0] {
3529            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3530                Expr::Test(test) => match test.as_ref() {
3531                    TestExpr::Comparison { left, op, right } => {
3532                        assert!(matches!(left.as_ref(), Expr::VarRef(_)));
3533                        assert_eq!(*op, TestCmpOp::Eq);
3534                        match right.as_ref() {
3535                            Expr::Literal(Value::Int(n)) => assert_eq!(*n, 5),
3536                            other => panic!("expected int, got {:?}", other),
3537                        }
3538                    }
3539                    other => panic!("expected comparison, got {:?}", other),
3540                },
3541                other => panic!("expected test expr, got {:?}", other),
3542            },
3543            other => panic!("expected if, got {:?}", other),
3544        }
3545    }
3546
3547    #[test]
3548    fn parse_comparison_not_equals() {
3549        let result = parse("if [[ ${X} != 0 ]]; then echo; fi").unwrap();
3550        match &result.statements[0] {
3551            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3552                Expr::Test(test) => match test.as_ref() {
3553                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::NotEq),
3554                    other => panic!("expected comparison, got {:?}", other),
3555                },
3556                other => panic!("expected test expr, got {:?}", other),
3557            },
3558            other => panic!("expected if, got {:?}", other),
3559        }
3560    }
3561
3562    #[test]
3563    fn parse_comparison_less_than() {
3564        let result = parse("if [[ ${COUNT} -lt 10 ]]; then echo; fi").unwrap();
3565        match &result.statements[0] {
3566            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3567                Expr::Test(test) => match test.as_ref() {
3568                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::NumLt),
3569                    other => panic!("expected comparison, got {:?}", other),
3570                },
3571                other => panic!("expected test expr, got {:?}", other),
3572            },
3573            other => panic!("expected if, got {:?}", other),
3574        }
3575    }
3576
3577    #[test]
3578    fn parse_comparison_greater_than() {
3579        let result = parse("if [[ ${COUNT} -gt 0 ]]; then echo; fi").unwrap();
3580        match &result.statements[0] {
3581            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3582                Expr::Test(test) => match test.as_ref() {
3583                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::NumGt),
3584                    other => panic!("expected comparison, got {:?}", other),
3585                },
3586                other => panic!("expected test expr, got {:?}", other),
3587            },
3588            other => panic!("expected if, got {:?}", other),
3589        }
3590    }
3591
3592    #[test]
3593    fn parse_comparison_less_equal() {
3594        let result = parse("if [[ ${X} -le 100 ]]; then echo; fi").unwrap();
3595        match &result.statements[0] {
3596            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3597                Expr::Test(test) => match test.as_ref() {
3598                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::NumLtEq),
3599                    other => panic!("expected comparison, got {:?}", other),
3600                },
3601                other => panic!("expected test expr, got {:?}", other),
3602            },
3603            other => panic!("expected if, got {:?}", other),
3604        }
3605    }
3606
3607    #[test]
3608    fn parse_comparison_greater_equal() {
3609        let result = parse("if [[ ${X} -ge 1 ]]; then echo; fi").unwrap();
3610        match &result.statements[0] {
3611            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3612                Expr::Test(test) => match test.as_ref() {
3613                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::NumGtEq),
3614                    other => panic!("expected comparison, got {:?}", other),
3615                },
3616                other => panic!("expected test expr, got {:?}", other),
3617            },
3618            other => panic!("expected if, got {:?}", other),
3619        }
3620    }
3621
3622    #[test]
3623    fn parse_regex_match() {
3624        let result = parse(r#"if [[ ${NAME} =~ "^test" ]]; then echo; fi"#).unwrap();
3625        match &result.statements[0] {
3626            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3627                Expr::Test(test) => match test.as_ref() {
3628                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::Match),
3629                    other => panic!("expected comparison, got {:?}", other),
3630                },
3631                other => panic!("expected test expr, got {:?}", other),
3632            },
3633            other => panic!("expected if, got {:?}", other),
3634        }
3635    }
3636
3637    #[test]
3638    fn parse_regex_not_match() {
3639        let result = parse(r#"if [[ ${NAME} !~ "^test" ]]; then echo; fi"#).unwrap();
3640        match &result.statements[0] {
3641            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3642                Expr::Test(test) => match test.as_ref() {
3643                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::NotMatch),
3644                    other => panic!("expected comparison, got {:?}", other),
3645                },
3646                other => panic!("expected test expr, got {:?}", other),
3647            },
3648            other => panic!("expected if, got {:?}", other),
3649        }
3650    }
3651
3652    #[test]
3653    fn parse_string_interpolation() {
3654        let result = parse(r#"echo "Hello ${NAME}!""#).unwrap();
3655        match &result.statements[0] {
3656            Stmt::Command(cmd) => match &cmd.args[0] {
3657                Arg::Positional(Expr::Interpolated(parts)) => {
3658                    assert_eq!(parts.len(), 3);
3659                    match &parts[0] {
3660                        StringPart::Literal(s) => assert_eq!(s, "Hello "),
3661                        other => panic!("expected literal, got {:?}", other),
3662                    }
3663                    match &parts[1] {
3664                        StringPart::Var(path) => {
3665                            assert_eq!(path.segments.len(), 1);
3666                            let VarSegment::Field(name) = &path.segments[0] else {
3667                                panic!("expected root field, got {:?}", path.segments[0]);
3668                            };
3669                            assert_eq!(name, "NAME");
3670                        }
3671                        other => panic!("expected var, got {:?}", other),
3672                    }
3673                    match &parts[2] {
3674                        StringPart::Literal(s) => assert_eq!(s, "!"),
3675                        other => panic!("expected literal, got {:?}", other),
3676                    }
3677                }
3678                other => panic!("expected interpolated, got {:?}", other),
3679            },
3680            other => panic!("expected command, got {:?}", other),
3681        }
3682    }
3683
3684    #[test]
3685    fn parse_string_interpolation_multiple_vars() {
3686        let result = parse(r#"echo "${FIRST} and ${SECOND}""#).unwrap();
3687        match &result.statements[0] {
3688            Stmt::Command(cmd) => match &cmd.args[0] {
3689                Arg::Positional(Expr::Interpolated(parts)) => {
3690                    // ${FIRST} + " and " + ${SECOND} = 3 parts
3691                    assert_eq!(parts.len(), 3);
3692                    assert!(matches!(&parts[0], StringPart::Var(_)));
3693                    assert!(matches!(&parts[1], StringPart::Literal(_)));
3694                    assert!(matches!(&parts[2], StringPart::Var(_)));
3695                }
3696                other => panic!("expected interpolated, got {:?}", other),
3697            },
3698            other => panic!("expected command, got {:?}", other),
3699        }
3700    }
3701
3702    #[test]
3703    fn parse_empty_function_body() {
3704        let result = parse("empty() { }").unwrap();
3705        match &result.statements[0] {
3706            Stmt::ToolDef(t) => {
3707                assert_eq!(t.name, "empty");
3708                assert!(t.params.is_empty());
3709                assert!(t.body.is_empty());
3710            }
3711            other => panic!("expected function def, got {:?}", other),
3712        }
3713    }
3714
3715    #[test]
3716    fn parse_bash_style_function() {
3717        let result = parse("function greet { echo hello }").unwrap();
3718        match &result.statements[0] {
3719            Stmt::ToolDef(t) => {
3720                assert_eq!(t.name, "greet");
3721                assert!(t.params.is_empty());
3722                assert_eq!(t.body.len(), 1);
3723            }
3724            other => panic!("expected function def, got {:?}", other),
3725        }
3726    }
3727
3728    #[test]
3729    fn parse_comparison_string_values() {
3730        let result = parse(r#"if [[ ${STATUS} == "ok" ]]; then echo; fi"#).unwrap();
3731        match &result.statements[0] {
3732            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3733                Expr::Test(test) => match test.as_ref() {
3734                    TestExpr::Comparison { left, op, right } => {
3735                        assert!(matches!(left.as_ref(), Expr::VarRef(_)));
3736                        assert_eq!(*op, TestCmpOp::Eq);
3737                        match right.as_ref() {
3738                            Expr::Literal(Value::String(s)) => assert_eq!(s, "ok"),
3739                            other => panic!("expected string, got {:?}", other),
3740                        }
3741                    }
3742                    other => panic!("expected comparison, got {:?}", other),
3743                },
3744                other => panic!("expected test expr, got {:?}", other),
3745            },
3746            other => panic!("expected if, got {:?}", other),
3747        }
3748    }
3749
3750    // ═══════════════════════════════════════════════════════════════════════════
3751    // Command Substitution Tests
3752    // ═══════════════════════════════════════════════════════════════════════════
3753
3754    #[test]
3755    fn parse_cmd_subst_simple() {
3756        let result = parse("X=$(echo)").unwrap();
3757        match &result.statements[0] {
3758            Stmt::Assignment(a) => {
3759                assert_eq!(a.name(), "X");
3760                assert_eq!(subst_cmd(&a.value).name, "echo");
3761            }
3762            other => panic!("expected assignment, got {:?}", other),
3763        }
3764    }
3765
3766    #[test]
3767    fn parse_cmd_subst_with_args() {
3768        let result = parse(r#"X=$(fetch url="http://example.com")"#).unwrap();
3769        match &result.statements[0] {
3770            Stmt::Assignment(a) => {
3771                let cmd = subst_cmd(&a.value);
3772                assert_eq!(cmd.name, "fetch");
3773                assert_eq!(cmd.args.len(), 1);
3774                match &cmd.args[0] {
3775                    Arg::WordAssign { key, .. } => assert_eq!(key, "url"),
3776                    other => panic!("expected WordAssign arg, got {:?}", other),
3777                }
3778            }
3779            other => panic!("expected assignment, got {:?}", other),
3780        }
3781    }
3782
3783    #[test]
3784    fn parse_cmd_subst_pipeline() {
3785        let result = parse("X=$(cat file | grep pattern)").unwrap();
3786        match &result.statements[0] {
3787            Stmt::Assignment(a) => {
3788                let pipeline = subst_pipeline(&a.value);
3789                assert_eq!(pipeline.commands.len(), 2);
3790                assert_eq!(pipeline.commands[0].name, "cat");
3791                assert_eq!(pipeline.commands[1].name, "grep");
3792            }
3793            other => panic!("expected assignment, got {:?}", other),
3794        }
3795    }
3796
3797    #[test]
3798    fn parse_cmd_subst_with_redirect() {
3799        // Regression: `cmd_subst_parser` used to hardcode `redirects: vec![]`,
3800        // so a redirect inside `$()` was a parse error. A command carrying a
3801        // redirect stays a `Stmt::Pipeline` (`pipeline_into_stmt` only unwraps
3802        // redirect-free commands), so read it back through `subst_pipeline`.
3803        let result = parse("X=$(echo hi > out.txt)").unwrap();
3804        match &result.statements[0] {
3805            Stmt::Assignment(a) => {
3806                let pipeline = subst_pipeline(&a.value);
3807                assert_eq!(pipeline.commands.len(), 1);
3808                let cmd = &pipeline.commands[0];
3809                assert_eq!(cmd.name, "echo");
3810                assert_eq!(cmd.redirects.len(), 1);
3811                assert!(matches!(
3812                    cmd.redirects[0].kind,
3813                    RedirectKind::StdoutOverwrite
3814                ));
3815            }
3816            other => panic!("expected assignment, got {:?}", other),
3817        }
3818    }
3819
3820    #[test]
3821    fn parse_cmd_subst_redirect_target_with_nested_subst() {
3822        // The cycle-break's sharpest case: a `$(...)` in the redirect *target*,
3823        // inside a `$(...)`. This exercises cmd_subst → redirect → (recursive
3824        // expr) → cmd_subst, the path that used to recurse unboundedly during
3825        // parser construction (stack overflow). It must parse; the target is a
3826        // nested `CommandSubst`.
3827        let result = parse("X=$(echo hi > $(echo f))").unwrap();
3828        match &result.statements[0] {
3829            Stmt::Assignment(a) => {
3830                let pipeline = subst_pipeline(&a.value);
3831                assert_eq!(pipeline.commands.len(), 1);
3832                let cmd = &pipeline.commands[0];
3833                assert_eq!(cmd.name, "echo");
3834                assert_eq!(cmd.redirects.len(), 1);
3835                assert!(
3836                    matches!(cmd.redirects[0].target, Expr::CommandSubst(_)),
3837                    "redirect target should be a nested command substitution, got {:?}",
3838                    cmd.redirects[0].target
3839                );
3840            }
3841            other => panic!("expected assignment, got {:?}", other),
3842        }
3843    }
3844
3845    #[test]
3846    fn parse_cmd_subst_chain_with_redirect() {
3847        // A redirect in a chained `$()` body binds to its own command, not to
3848        // the chain: `$(a && b > f)` → AndChain{ left: a, right: (b > f) }, with
3849        // the redirect on `b` only.
3850        let result = parse("X=$(echo a && echo b > out.txt)").unwrap();
3851        let stmts = match &result.statements[0] {
3852            Stmt::Assignment(a) => match &a.value {
3853                Expr::CommandSubst(s) => s,
3854                other => panic!("expected command subst, got {:?}", other),
3855            },
3856            other => panic!("expected assignment, got {:?}", other),
3857        };
3858        match stmts.as_slice() {
3859            [Stmt::AndChain { left, right }] => {
3860                // `echo a` is redirect-free → unwrapped to Stmt::Command.
3861                assert!(
3862                    matches!(**left, Stmt::Command(_)),
3863                    "left of && should be a bare command, got {:?}",
3864                    left
3865                );
3866                // `echo b > out.txt` carries a redirect → stays Stmt::Pipeline.
3867                match &**right {
3868                    Stmt::Pipeline(p) => {
3869                        assert_eq!(p.commands.len(), 1);
3870                        assert_eq!(p.commands[0].name, "echo");
3871                        assert_eq!(p.commands[0].redirects.len(), 1);
3872                    }
3873                    other => panic!("right should be a redirect-bearing pipeline, got {:?}", other),
3874                }
3875            }
3876            other => panic!("expected a single AndChain, got {:?}", other),
3877        }
3878    }
3879
3880    #[test]
3881    fn parse_cmd_subst_in_condition() {
3882        // Shell-compatible: conditions are commands, not command substitutions
3883        let result = parse("if kaish-validate; then echo; fi").unwrap();
3884        match &result.statements[0] {
3885            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3886                Expr::Command(cmd) => {
3887                    assert_eq!(cmd.name, "kaish-validate");
3888                }
3889                other => panic!("expected command, got {:?}", other),
3890            },
3891            other => panic!("expected if, got {:?}", other),
3892        }
3893    }
3894
3895    // ═══════════════════════════════════════════════════════════════════════════
3896    // Inline env-prefix (`NAME=value command`) Tests
3897    // ═══════════════════════════════════════════════════════════════════════════
3898
3899    #[test]
3900    fn parse_env_prefix_single() {
3901        let result = parse("FOO=bar echo hi").unwrap();
3902        match &result.statements[0] {
3903            Stmt::EnvScoped { assignments, body } => {
3904                assert_eq!(assignments.len(), 1);
3905                assert_eq!(assignments[0].name(), "FOO");
3906                assert!(!assignments[0].local);
3907                match body.as_ref() {
3908                    Stmt::Command(cmd) => assert_eq!(cmd.name, "echo"),
3909                    other => panic!("expected command body, got {other:?}"),
3910                }
3911            }
3912            other => panic!("expected env-scoped, got {other:?}"),
3913        }
3914    }
3915
3916    #[test]
3917    fn parse_env_prefix_multiple() {
3918        let result = parse("A=1 B=2 run").unwrap();
3919        match &result.statements[0] {
3920            Stmt::EnvScoped { assignments, body } => {
3921                assert_eq!(assignments.len(), 2);
3922                assert_eq!(assignments[0].name(), "A");
3923                assert_eq!(assignments[1].name(), "B");
3924                assert!(matches!(body.as_ref(), Stmt::Command(c) if c.name == "run"));
3925            }
3926            other => panic!("expected env-scoped, got {other:?}"),
3927        }
3928    }
3929
3930    #[test]
3931    fn parse_bare_assignment_is_not_env_scoped() {
3932        // No command follows — stays a plain (persistent) assignment.
3933        let result = parse("FOO=bar").unwrap();
3934        assert!(
3935            matches!(&result.statements[0], Stmt::Assignment(a) if a.name() == "FOO"),
3936            "got {:?}",
3937            result.statements[0]
3938        );
3939    }
3940
3941    #[test]
3942    fn parse_assignment_then_and_chain_does_not_over_capture() {
3943        // `FOO=bar && echo` is a (persistent) assignment chained with `&&`, NOT
3944        // an env-prefixed command — the `&&` is not a command for the prefix.
3945        let result = parse("FOO=bar && echo hi").unwrap();
3946        match &result.statements[0] {
3947            Stmt::AndChain { left, right } => {
3948                assert!(matches!(left.as_ref(), Stmt::Assignment(a) if a.name() == "FOO"));
3949                assert!(matches!(right.as_ref(), Stmt::Command(c) if c.name == "echo"));
3950            }
3951            other => panic!("expected and-chain, got {other:?}"),
3952        }
3953    }
3954
3955    #[test]
3956    fn parse_env_prefix_pipeline_body() {
3957        let result = parse("FOO=bar cat | grep x").unwrap();
3958        match &result.statements[0] {
3959            Stmt::EnvScoped { assignments, body } => {
3960                assert_eq!(assignments[0].name(), "FOO");
3961                match body.as_ref() {
3962                    Stmt::Pipeline(p) => assert_eq!(p.commands.len(), 2),
3963                    other => panic!("expected pipeline body, got {other:?}"),
3964                }
3965            }
3966            other => panic!("expected env-scoped, got {other:?}"),
3967        }
3968    }
3969
3970    // ═══════════════════════════════════════════════════════════════════════════
3971    // Argv-splat rejection (adjacent unquoted words — docs/issues.md #2)
3972    // ═══════════════════════════════════════════════════════════════════════════
3973
3974    fn parse_err_message(source: &str) -> String {
3975        parse(source)
3976            .expect_err("expected a parse error")
3977            .iter()
3978            .map(|e| e.message.clone())
3979            .collect::<Vec<_>>()
3980            .join(" ")
3981    }
3982
3983    #[test]
3984    fn argv_splat_cmdsubst_glued_to_path_is_rejected() {
3985        // `/tmp/$(echo x).txt` lexes as 3 adjacent tokens; unquoted it would
3986        // silently splat into 3 args. Reject with a quote-it hint.
3987        let msg = parse_err_message("echo /tmp/$(echo x).txt");
3988        assert!(msg.contains("quote"), "expected quote hint, got: {msg}");
3989    }
3990
3991    #[test]
3992    fn argv_splat_var_glued_to_path_is_rejected() {
3993        assert!(parse("echo $dir/out.txt").is_err());
3994    }
3995
3996    #[test]
3997    fn argv_splat_three_way_glue_is_rejected() {
3998        assert!(parse("echo foo$(echo bar)baz").is_err());
3999    }
4000
4001    #[test]
4002    fn argv_splat_quoted_word_is_accepted() {
4003        // The supported idiom: quote the whole interpolated word.
4004        assert!(parse(r#"echo "/tmp/$(echo x).txt""#).is_ok());
4005        assert!(parse(r#"echo "$dir/out.txt""#).is_ok());
4006    }
4007
4008    #[test]
4009    fn argv_single_token_words_are_not_splat() {
4010        // These lex as a single token each — no adjacency, must still parse.
4011        assert!(parse("echo file.txt").is_ok(), "file.txt");
4012        assert!(parse("echo a.b.c").is_ok(), "a.b.c");
4013        assert!(parse("echo v1.2.3").is_ok(), "v1.2.3");
4014    }
4015
4016    #[test]
4017    fn argv_spaced_words_are_not_splat() {
4018        assert!(parse("echo a b c").is_ok());
4019        assert!(parse("echo /tmp/x $(echo y)").is_ok());
4020    }
4021
4022    #[test]
4023    fn parse_cmd_subst_in_command_arg() {
4024        let result = parse("echo $(whoami)").unwrap();
4025        match &result.statements[0] {
4026            Stmt::Command(cmd) => {
4027                assert_eq!(cmd.name, "echo");
4028                match &cmd.args[0] {
4029                    Arg::Positional(expr) => {
4030                        assert_eq!(subst_cmd(expr).name, "whoami");
4031                    }
4032                    other => panic!("expected command subst, got {:?}", other),
4033                }
4034            }
4035            other => panic!("expected command, got {:?}", other),
4036        }
4037    }
4038
4039    // ═══════════════════════════════════════════════════════════════════════════
4040    // Logical Operator Tests (&&, ||)
4041    // ═══════════════════════════════════════════════════════════════════════════
4042
4043    #[test]
4044    fn parse_condition_and() {
4045        // Shell-compatible: commands chained with &&
4046        let result = parse("if check-a && check-b; then echo; fi").unwrap();
4047        match &result.statements[0] {
4048            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
4049                Expr::BinaryOp { left, op, right } => {
4050                    assert_eq!(*op, BinaryOp::And);
4051                    assert!(matches!(left.as_ref(), Expr::Command(_)));
4052                    assert!(matches!(right.as_ref(), Expr::Command(_)));
4053                }
4054                other => panic!("expected binary op, got {:?}", other),
4055            },
4056            other => panic!("expected if, got {:?}", other),
4057        }
4058    }
4059
4060    #[test]
4061    fn parse_condition_or() {
4062        let result = parse("if try-a || try-b; then echo; fi").unwrap();
4063        match &result.statements[0] {
4064            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
4065                Expr::BinaryOp { left, op, right } => {
4066                    assert_eq!(*op, BinaryOp::Or);
4067                    assert!(matches!(left.as_ref(), Expr::Command(_)));
4068                    assert!(matches!(right.as_ref(), Expr::Command(_)));
4069                }
4070                other => panic!("expected binary op, got {:?}", other),
4071            },
4072            other => panic!("expected if, got {:?}", other),
4073        }
4074    }
4075
4076    #[test]
4077    fn parse_condition_and_or_precedence() {
4078        // a && b || c should parse as (a && b) || c
4079        let result = parse("if cmd-a && cmd-b || cmd-c; then echo; fi").unwrap();
4080        match &result.statements[0] {
4081            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
4082                Expr::BinaryOp { left, op, right } => {
4083                    // Top level should be ||
4084                    assert_eq!(*op, BinaryOp::Or);
4085                    // Left side should be && expression
4086                    match left.as_ref() {
4087                        Expr::BinaryOp { op: inner_op, .. } => {
4088                            assert_eq!(*inner_op, BinaryOp::And);
4089                        }
4090                        other => panic!("expected binary op (&&), got {:?}", other),
4091                    }
4092                    // Right side should be command
4093                    assert!(matches!(right.as_ref(), Expr::Command(_)));
4094                }
4095                other => panic!("expected binary op, got {:?}", other),
4096            },
4097            other => panic!("expected if, got {:?}", other),
4098        }
4099    }
4100
4101    #[test]
4102    fn parse_condition_multiple_and() {
4103        let result = parse("if cmd-a && cmd-b && cmd-c; then echo; fi").unwrap();
4104        match &result.statements[0] {
4105            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
4106                Expr::BinaryOp { left, op, .. } => {
4107                    assert_eq!(*op, BinaryOp::And);
4108                    // Left side should also be &&
4109                    match left.as_ref() {
4110                        Expr::BinaryOp { op: inner_op, .. } => {
4111                            assert_eq!(*inner_op, BinaryOp::And);
4112                        }
4113                        other => panic!("expected binary op, got {:?}", other),
4114                    }
4115                }
4116                other => panic!("expected binary op, got {:?}", other),
4117            },
4118            other => panic!("expected if, got {:?}", other),
4119        }
4120    }
4121
4122    #[test]
4123    fn parse_condition_mixed_comparison_and_logical() {
4124        // Shell-compatible: use [[ ]] for comparisons, && to chain them
4125        let result = parse("if [[ ${X} == 5 ]] && [[ ${Y} -gt 0 ]]; then echo; fi").unwrap();
4126        match &result.statements[0] {
4127            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
4128                Expr::BinaryOp { left, op, right } => {
4129                    assert_eq!(*op, BinaryOp::And);
4130                    // Left: [[ ${X} == 5 ]]
4131                    match left.as_ref() {
4132                        Expr::Test(test) => match test.as_ref() {
4133                            TestExpr::Comparison { op: left_op, .. } => {
4134                                assert_eq!(*left_op, TestCmpOp::Eq);
4135                            }
4136                            other => panic!("expected comparison, got {:?}", other),
4137                        },
4138                        other => panic!("expected test, got {:?}", other),
4139                    }
4140                    // Right: [[ ${Y} -gt 0 ]]
4141                    match right.as_ref() {
4142                        Expr::Test(test) => match test.as_ref() {
4143                            TestExpr::Comparison { op: right_op, .. } => {
4144                                assert_eq!(*right_op, TestCmpOp::NumGt);
4145                            }
4146                            other => panic!("expected comparison, got {:?}", other),
4147                        },
4148                        other => panic!("expected test, got {:?}", other),
4149                    }
4150                }
4151                other => panic!("expected binary op, got {:?}", other),
4152            },
4153            other => panic!("expected if, got {:?}", other),
4154        }
4155    }
4156
4157    // ═══════════════════════════════════════════════════════════════════════════
4158    // Integration Tests - Complete Scripts
4159    // ═══════════════════════════════════════════════════════════════════════════
4160
4161    /// Level 1: Linear script using core features
4162    #[test]
4163    fn script_level1_linear() {
4164        let script = r#"
4165NAME="kaish"
4166VERSION=1
4167TIMEOUT=30
4168ITEMS="alpha beta gamma"
4169
4170echo "Starting ${NAME} v${VERSION}"
4171cat "README.md" | grep pattern="install" | head count=5
4172fetch url="https://api.example.com/status" timeout=${TIMEOUT} > "/tmp/status.json"
4173echo "Items: ${ITEMS}"
4174"#;
4175        let result = parse(script).unwrap();
4176        let stmts: Vec<_> = result.statements.iter()
4177            .filter(|s| !matches!(s, Stmt::Empty))
4178            .collect();
4179
4180        assert_eq!(stmts.len(), 8);
4181        assert!(matches!(stmts[0], Stmt::Assignment(_)));  // set NAME
4182        assert!(matches!(stmts[1], Stmt::Assignment(_)));  // set VERSION
4183        assert!(matches!(stmts[2], Stmt::Assignment(_)));  // set TIMEOUT
4184        assert!(matches!(stmts[3], Stmt::Assignment(_)));  // set ITEMS
4185        assert!(matches!(stmts[4], Stmt::Command(_)));     // echo "Starting..."
4186        assert!(matches!(stmts[5], Stmt::Pipeline(_)));    // cat | grep | head
4187        assert!(matches!(stmts[6], Stmt::Pipeline(_)));    // fetch (with redirect - Pipeline since it has redirects)
4188        assert!(matches!(stmts[7], Stmt::Command(_)));     // echo "Items: ${ITEMS}"
4189    }
4190
4191    /// Level 2: Script with conditionals (shell-compatible syntax)
4192    #[test]
4193    fn script_level2_branching() {
4194        let script = r#"
4195RESULT=$(kaish-validate "input.json")
4196
4197if [[ ${RESULT.ok} == true ]]; then
4198    echo "Validation passed"
4199    process "input.json" > "output.json"
4200else
4201    echo "Validation failed: ${RESULT.err}"
4202fi
4203
4204if [[ ${COUNT} -gt 0 ]] && [[ ${COUNT} -le 100 ]]; then
4205    echo "Count in valid range"
4206fi
4207
4208if check-network || check-cache; then
4209    fetch url=${URL}
4210fi
4211"#;
4212        let result = parse(script).unwrap();
4213        let stmts: Vec<_> = result.statements.iter()
4214            .filter(|s| !matches!(s, Stmt::Empty))
4215            .collect();
4216
4217        assert_eq!(stmts.len(), 4);
4218
4219        // First: assignment with command substitution
4220        match stmts[0] {
4221            Stmt::Assignment(a) => {
4222                assert_eq!(a.name(), "RESULT");
4223                assert!(matches!(&a.value, Expr::CommandSubst(_)));
4224            }
4225            other => panic!("expected assignment, got {:?}", other),
4226        }
4227
4228        // Second: if/else
4229        match stmts[1] {
4230            Stmt::If(if_stmt) => {
4231                assert_eq!(if_stmt.then_branch.len(), 2);
4232                assert!(if_stmt.else_branch.is_some());
4233                assert_eq!(if_stmt.else_branch.as_ref().unwrap().len(), 1);
4234            }
4235            other => panic!("expected if, got {:?}", other),
4236        }
4237
4238        // Third: if with && condition
4239        match stmts[2] {
4240            Stmt::If(if_stmt) => {
4241                match if_stmt.condition.as_ref() {
4242                    Expr::BinaryOp { op, .. } => assert_eq!(*op, BinaryOp::And),
4243                    other => panic!("expected && condition, got {:?}", other),
4244                }
4245            }
4246            other => panic!("expected if, got {:?}", other),
4247        }
4248
4249        // Fourth: if with || of commands
4250        match stmts[3] {
4251            Stmt::If(if_stmt) => {
4252                match if_stmt.condition.as_ref() {
4253                    Expr::BinaryOp { op, left, right } => {
4254                        assert_eq!(*op, BinaryOp::Or);
4255                        assert!(matches!(left.as_ref(), Expr::Command(_)));
4256                        assert!(matches!(right.as_ref(), Expr::Command(_)));
4257                    }
4258                    other => panic!("expected || condition, got {:?}", other),
4259                }
4260            }
4261            other => panic!("expected if, got {:?}", other),
4262        }
4263    }
4264
4265    /// Level 3: Script with loops and function definitions
4266    #[test]
4267    fn script_level3_loops_and_functions() {
4268        let script = r#"
4269greet() {
4270    echo "Hello, $1!"
4271}
4272
4273fetch_all() {
4274    for URL in $@; do
4275        fetch url=${URL}
4276    done
4277}
4278
4279USERS="alice bob charlie"
4280
4281for USER in ${USERS}; do
4282    greet ${USER}
4283    if [[ ${USER} == "bob" ]]; then
4284        echo "Found Bob!"
4285    fi
4286done
4287
4288long-running-task &
4289"#;
4290        let result = parse(script).unwrap();
4291        let stmts: Vec<_> = result.statements.iter()
4292            .filter(|s| !matches!(s, Stmt::Empty))
4293            .collect();
4294
4295        assert_eq!(stmts.len(), 5);
4296
4297        // First function def
4298        match stmts[0] {
4299            Stmt::ToolDef(t) => {
4300                assert_eq!(t.name, "greet");
4301                assert!(t.params.is_empty());
4302            }
4303            other => panic!("expected function def, got {:?}", other),
4304        }
4305
4306        // Second function def with nested for loop
4307        match stmts[1] {
4308            Stmt::ToolDef(t) => {
4309                assert_eq!(t.name, "fetch_all");
4310                assert_eq!(t.body.len(), 1);
4311                assert!(matches!(&t.body[0], Stmt::For(_)));
4312            }
4313            other => panic!("expected function def, got {:?}", other),
4314        }
4315
4316        // Assignment
4317        assert!(matches!(stmts[2], Stmt::Assignment(_)));
4318
4319        // For loop with nested if
4320        match stmts[3] {
4321            Stmt::For(f) => {
4322                assert_eq!(f.variable, "USER");
4323                assert_eq!(f.body.len(), 2);
4324                assert!(matches!(&f.body[0], Stmt::Command(_)));
4325                assert!(matches!(&f.body[1], Stmt::If(_)));
4326            }
4327            other => panic!("expected for loop, got {:?}", other),
4328        }
4329
4330        // Background job
4331        match stmts[4] {
4332            Stmt::Pipeline(p) => {
4333                assert!(p.background);
4334                assert_eq!(p.commands[0].name, "long-running-task");
4335            }
4336            other => panic!("expected pipeline (background), got {:?}", other),
4337        }
4338    }
4339
4340    /// Level 4: Complex nested control flow (shell-compatible syntax)
4341    #[test]
4342    fn script_level4_complex_nesting() {
4343        let script = r#"
4344RESULT=$(cat "config.json" | jq query=".servers" | kaish-validate schema="server-schema.json")
4345
4346if ping host=${HOST} && [[ ${RESULT} == true ]]; then
4347    for SERVER in "prod-1 prod-2"; do
4348        deploy target=${SERVER} port=8080
4349        if [[ $? -ne 0 ]]; then
4350            notify channel="ops" message="Deploy failed"
4351        fi
4352    done
4353fi
4354"#;
4355        let result = parse(script).unwrap();
4356        let stmts: Vec<_> = result.statements.iter()
4357            .filter(|s| !matches!(s, Stmt::Empty))
4358            .collect();
4359
4360        assert_eq!(stmts.len(), 2);
4361
4362        // Command substitution with pipeline
4363        match stmts[0] {
4364            Stmt::Assignment(a) => {
4365                assert_eq!(a.name(), "RESULT");
4366                assert_eq!(subst_pipeline(&a.value).commands.len(), 3);
4367            }
4368            other => panic!("expected assignment, got {:?}", other),
4369        }
4370
4371        // If with && condition, containing for loop with nested if
4372        match stmts[1] {
4373            Stmt::If(if_stmt) => {
4374                match if_stmt.condition.as_ref() {
4375                    Expr::BinaryOp { op, .. } => assert_eq!(*op, BinaryOp::And),
4376                    other => panic!("expected && condition, got {:?}", other),
4377                }
4378                assert_eq!(if_stmt.then_branch.len(), 1);
4379                match &if_stmt.then_branch[0] {
4380                    Stmt::For(f) => {
4381                        assert_eq!(f.body.len(), 2);
4382                        assert!(matches!(&f.body[1], Stmt::If(_)));
4383                    }
4384                    other => panic!("expected for in if body, got {:?}", other),
4385                }
4386            }
4387            other => panic!("expected if, got {:?}", other),
4388        }
4389    }
4390
4391    /// Level 5: Edge cases and parser stress test
4392    #[test]
4393    fn script_level5_edge_cases() {
4394        let script = r#"
4395echo ""
4396echo "quotes: \"nested\" here"
4397echo "escapes: \n\t\r\\"
4398echo "unicode: \u2764"
4399
4400X=-99999
4401Y=3.14159265358979
4402Z=-0.001
4403
4404cmd a=1 b="two" c=true d=false e=null
4405
4406if true; then
4407    if false; then
4408        echo "inner"
4409    else
4410        echo "else"
4411    fi
4412fi
4413
4414for I in "a b c"; do
4415    echo ${I}
4416done
4417
4418no_params() {
4419    echo "no params"
4420}
4421
4422function all_args {
4423    echo "args: $@"
4424}
4425
4426a | b | c | d | e &
4427cmd 2> "errors.log"
4428cmd &> "all.log"
4429cmd >> "append.log"
4430cmd < "input.txt"
4431"#;
4432        let result = parse(script).unwrap();
4433        let stmts: Vec<_> = result.statements.iter()
4434            .filter(|s| !matches!(s, Stmt::Empty))
4435            .collect();
4436
4437        // Verify it parses without error
4438        assert!(stmts.len() >= 10, "expected many statements, got {}", stmts.len());
4439
4440        // Background pipeline
4441        let bg_stmt = stmts.iter().find(|s| matches!(s, Stmt::Pipeline(p) if p.background));
4442        assert!(bg_stmt.is_some(), "expected background pipeline");
4443
4444        match bg_stmt.unwrap() {
4445            Stmt::Pipeline(p) => {
4446                assert_eq!(p.commands.len(), 5);
4447                assert!(p.background);
4448            }
4449            _ => unreachable!(),
4450        }
4451    }
4452
4453    // ═══════════════════════════════════════════════════════════════════════════
4454    // Edge Case Tests: Ambiguity Resolution
4455    // ═══════════════════════════════════════════════════════════════════════════
4456
4457    #[test]
4458    fn parse_keyword_as_variable_rejected() {
4459        // Keywords CANNOT be used as variable names - this is intentional
4460        // to avoid ambiguity. Use different names instead.
4461        let result = parse(r#"if="value""#);
4462        assert!(result.is_err(), "if= should fail - 'if' is a keyword");
4463
4464        let result = parse("while=true");
4465        assert!(result.is_err(), "while= should fail - 'while' is a keyword");
4466
4467        let result = parse(r#"then="next""#);
4468        assert!(result.is_err(), "then= should fail - 'then' is a keyword");
4469    }
4470
4471    #[test]
4472    fn parse_set_command_with_flag() {
4473        let result = parse("set -e");
4474        assert!(result.is_ok(), "failed to parse set -e: {:?}", result);
4475        let program = result.unwrap();
4476        match &program.statements[0] {
4477            Stmt::Command(cmd) => {
4478                assert_eq!(cmd.name, "set");
4479                assert_eq!(cmd.args.len(), 1);
4480                match &cmd.args[0] {
4481                    Arg::ShortFlag(f) => assert_eq!(f, "e"),
4482                    other => panic!("expected ShortFlag, got {:?}", other),
4483                }
4484            }
4485            other => panic!("expected Command, got {:?}", other),
4486        }
4487    }
4488
4489    #[test]
4490    fn parse_set_command_no_args() {
4491        let result = parse("set");
4492        assert!(result.is_ok(), "failed to parse set: {:?}", result);
4493        let program = result.unwrap();
4494        match &program.statements[0] {
4495            Stmt::Command(cmd) => {
4496                assert_eq!(cmd.name, "set");
4497                assert_eq!(cmd.args.len(), 0);
4498            }
4499            other => panic!("expected Command, got {:?}", other),
4500        }
4501    }
4502
4503    #[test]
4504    fn parse_set_assignment_vs_command() {
4505        // X=5 should be assignment
4506        let result = parse("X=5");
4507        assert!(result.is_ok());
4508        let program = result.unwrap();
4509        assert!(matches!(&program.statements[0], Stmt::Assignment(_)));
4510
4511        // set -e should be command
4512        let result = parse("set -e");
4513        assert!(result.is_ok());
4514        let program = result.unwrap();
4515        assert!(matches!(&program.statements[0], Stmt::Command(_)));
4516    }
4517
4518    #[test]
4519    fn parse_true_as_command() {
4520        let result = parse("true");
4521        assert!(result.is_ok());
4522        let program = result.unwrap();
4523        match &program.statements[0] {
4524            Stmt::Command(cmd) => assert_eq!(cmd.name, "true"),
4525            other => panic!("expected Command(true), got {:?}", other),
4526        }
4527    }
4528
4529    #[test]
4530    fn parse_false_as_command() {
4531        let result = parse("false");
4532        assert!(result.is_ok());
4533        let program = result.unwrap();
4534        match &program.statements[0] {
4535            Stmt::Command(cmd) => assert_eq!(cmd.name, "false"),
4536            other => panic!("expected Command(false), got {:?}", other),
4537        }
4538    }
4539
4540    #[test]
4541    fn parse_dot_as_source_alias() {
4542        let result = parse(". script.kai");
4543        assert!(result.is_ok(), "failed to parse . script.kai: {:?}", result);
4544        let program = result.unwrap();
4545        match &program.statements[0] {
4546            Stmt::Command(cmd) => {
4547                assert_eq!(cmd.name, ".");
4548                assert_eq!(cmd.args.len(), 1);
4549            }
4550            other => panic!("expected Command(.), got {:?}", other),
4551        }
4552    }
4553
4554    #[test]
4555    fn parse_source_command() {
4556        let result = parse("source utils.kai");
4557        assert!(result.is_ok(), "failed to parse source: {:?}", result);
4558        let program = result.unwrap();
4559        match &program.statements[0] {
4560            Stmt::Command(cmd) => {
4561                assert_eq!(cmd.name, "source");
4562                assert_eq!(cmd.args.len(), 1);
4563            }
4564            other => panic!("expected Command(source), got {:?}", other),
4565        }
4566    }
4567
4568    #[test]
4569    fn parse_test_expr_file_test() {
4570        // Paths must be quoted strings in test expressions
4571        let result = parse(r#"[[ -f "/path/file" ]]"#);
4572        assert!(result.is_ok(), "failed to parse file test: {:?}", result);
4573    }
4574
4575    #[test]
4576    fn parse_test_expr_comparison() {
4577        let result = parse(r#"[[ $X == "value" ]]"#);
4578        assert!(result.is_ok(), "failed to parse comparison test: {:?}", result);
4579    }
4580
4581    #[test]
4582    fn parse_test_expr_single_eq() {
4583        // = and == are equivalent inside [[ ]] (matching bash behavior)
4584        let result = parse(r#"[[ $X = "value" ]]"#);
4585        assert!(result.is_ok(), "failed to parse single-= comparison: {:?}", result);
4586        let program = result.unwrap();
4587        match &program.statements[0] {
4588            Stmt::Test(TestExpr::Comparison { op, .. }) => {
4589                assert_eq!(op, &TestCmpOp::Eq);
4590            }
4591            other => panic!("expected Test(Comparison), got {:?}", other),
4592        }
4593    }
4594
4595    #[test]
4596    fn parse_while_loop() {
4597        let result = parse("while true; do echo; done");
4598        assert!(result.is_ok(), "failed to parse while loop: {:?}", result);
4599        let program = result.unwrap();
4600        assert!(matches!(&program.statements[0], Stmt::While(_)));
4601    }
4602
4603    #[test]
4604    fn parse_break_with_level() {
4605        let result = parse("break 2");
4606        assert!(result.is_ok());
4607        let program = result.unwrap();
4608        match &program.statements[0] {
4609            Stmt::Break(Some(n)) => assert_eq!(*n, 2),
4610            other => panic!("expected Break(2), got {:?}", other),
4611        }
4612    }
4613
4614    #[test]
4615    fn parse_continue_with_level() {
4616        let result = parse("continue 3");
4617        assert!(result.is_ok());
4618        let program = result.unwrap();
4619        match &program.statements[0] {
4620            Stmt::Continue(Some(n)) => assert_eq!(*n, 3),
4621            other => panic!("expected Continue(3), got {:?}", other),
4622        }
4623    }
4624
4625    #[test]
4626    fn parse_exit_with_code() {
4627        let result = parse("exit 1");
4628        assert!(result.is_ok());
4629        let program = result.unwrap();
4630        match &program.statements[0] {
4631            Stmt::Exit(Some(expr)) => {
4632                match expr.as_ref() {
4633                    Expr::Literal(Value::Int(n)) => assert_eq!(*n, 1),
4634                    other => panic!("expected Int(1), got {:?}", other),
4635                }
4636            }
4637            other => panic!("expected Exit(1), got {:?}", other),
4638        }
4639    }
4640
4641    // ========================================================================
4642    // parse_interpolated_string_spanned — body-internal span tracking for
4643    // heredoc bodies. The byte offsets these tests pin become validator
4644    // issue spans via the HereDocBody → SpannedPart flow.
4645    // ========================================================================
4646
4647    #[test]
4648    fn spanned_literal_only_records_byte_range() {
4649        let parts = parse_interpolated_string_spanned("hello world", 100);
4650        assert_eq!(parts.len(), 1);
4651        assert!(matches!(&parts[0].part, StringPart::Literal(s) if s == "hello world"));
4652        assert_eq!(parts[0].offset, 100, "base_offset must propagate to literals");
4653        assert_eq!(parts[0].len, 11);
4654    }
4655
4656    #[test]
4657    fn spanned_braced_var_at_zero() {
4658        let parts = parse_interpolated_string_spanned("${X}", 50);
4659        assert_eq!(parts.len(), 1);
4660        assert!(matches!(&parts[0].part, StringPart::Var(_)));
4661        assert_eq!(parts[0].offset, 50);
4662        assert_eq!(parts[0].len, 4); // "${X}"
4663    }
4664
4665    #[test]
4666    fn spanned_simple_var_then_literal() {
4667        let parts = parse_interpolated_string_spanned("$X end", 10);
4668        assert_eq!(parts.len(), 2);
4669        assert!(matches!(&parts[0].part, StringPart::Var(_)));
4670        assert_eq!(parts[0].offset, 10);
4671        assert_eq!(parts[0].len, 2); // "$X"
4672        assert!(matches!(&parts[1].part, StringPart::Literal(s) if s == " end"));
4673        assert_eq!(parts[1].offset, 12);
4674        assert_eq!(parts[1].len, 4);
4675    }
4676
4677    #[test]
4678    fn spanned_mixed_literal_var_literal() {
4679        let parts = parse_interpolated_string_spanned("hi ${X} bye", 0);
4680        assert_eq!(parts.len(), 3);
4681        // "hi "
4682        assert!(matches!(&parts[0].part, StringPart::Literal(s) if s == "hi "));
4683        assert_eq!(parts[0].offset, 0);
4684        assert_eq!(parts[0].len, 3);
4685        // ${X}
4686        assert!(matches!(&parts[1].part, StringPart::Var(_)));
4687        assert_eq!(parts[1].offset, 3);
4688        assert_eq!(parts[1].len, 4);
4689        // " bye"
4690        assert!(matches!(&parts[2].part, StringPart::Literal(s) if s == " bye"));
4691        assert_eq!(parts[2].offset, 7);
4692        assert_eq!(parts[2].len, 4);
4693    }
4694
4695    #[test]
4696    fn spanned_positional_param() {
4697        let parts = parse_interpolated_string_spanned("$1 done", 0);
4698        assert_eq!(parts.len(), 2);
4699        assert!(matches!(&parts[0].part, StringPart::Positional(1)));
4700        assert_eq!(parts[0].offset, 0);
4701        assert_eq!(parts[0].len, 2); // "$1"
4702    }
4703
4704    #[test]
4705    fn spanned_special_dollar_dollar() {
4706        let parts = parse_interpolated_string_spanned("$$", 5);
4707        assert_eq!(parts.len(), 1);
4708        assert!(matches!(&parts[0].part, StringPart::CurrentPid));
4709        assert_eq!(parts[0].offset, 5);
4710        assert_eq!(parts[0].len, 2);
4711    }
4712
4713    #[test]
4714    fn spanned_arithmetic_marker_recognised() {
4715        // The lexer wraps arithmetic markers as ${__ARITH:expr__} for
4716        // interpolated heredocs; the spanned parser must produce
4717        // StringPart::Arithmetic for that shape.
4718        let parts = parse_interpolated_string_spanned("${__ARITH:1+2__}", 0);
4719        assert_eq!(parts.len(), 1);
4720        assert!(matches!(&parts[0].part, StringPart::Arithmetic(e) if e == "1+2"));
4721    }
4722
4723    #[test]
4724    fn spanned_default_separator_yields_var_with_default() {
4725        let parts = parse_interpolated_string_spanned("${X:-fallback}", 0);
4726        assert_eq!(parts.len(), 1);
4727        assert!(matches!(&parts[0].part, StringPart::VarWithDefault { .. }));
4728        assert_eq!(parts[0].offset, 0);
4729        assert_eq!(parts[0].len, 14); // "${X:-fallback}"
4730    }
4731
4732    #[test]
4733    fn spanned_no_dollar_runs_one_literal() {
4734        let parts = parse_interpolated_string_spanned("plain text only", 7);
4735        assert_eq!(parts.len(), 1);
4736        assert!(matches!(&parts[0].part, StringPart::Literal(s) if s == "plain text only"));
4737        assert_eq!(parts[0].offset, 7);
4738        assert_eq!(parts[0].len, 15);
4739    }
4740
4741    #[test]
4742    fn spanned_matches_unspanned_part_count() {
4743        // Spanned and spanless variants must agree on the part decomposition.
4744        // Bug fixes in one should land in the other.
4745        let cases = [
4746            "hello",
4747            "$X",
4748            "${X}",
4749            "${X:-d}",
4750            "hi $A and $B",
4751            "$0 $1 $2",
4752            "$$ $? $#",
4753        ];
4754        for s in &cases {
4755            let unspanned = parse_interpolated_string(s).expect("test input parses");
4756            let spanned = parse_interpolated_string_spanned(s, 0);
4757            assert_eq!(
4758                unspanned.len(),
4759                spanned.len(),
4760                "part count differs for {:?}",
4761                s
4762            );
4763        }
4764    }
4765
4766    #[test]
4767    fn spanned_multibyte_utf8_before_var_uses_byte_offsets() {
4768        // 🚀 is 4 bytes in UTF-8 and a space is 1 byte, so the literal
4769        // prefix is 5 bytes total. `${X}` then sits at byte offset 5.
4770        // Right-by-luck for char-vs-byte indexing is precisely what this
4771        // test catches: if someone swaps .len_utf8() for 1, offset becomes 2.
4772        let parts = parse_interpolated_string_spanned("🚀 ${X}", 0);
4773        assert_eq!(parts.len(), 2);
4774
4775        assert!(matches!(&parts[0].part, StringPart::Literal(s) if s == "🚀 "));
4776        assert_eq!(parts[0].offset, 0);
4777        assert_eq!(parts[0].len, 5, "literal len must be bytes, not chars");
4778
4779        assert!(matches!(&parts[1].part, StringPart::Var(_)));
4780        assert_eq!(parts[1].offset, 5, "var offset must be bytes, not chars");
4781        assert_eq!(parts[1].len, 4);
4782    }
4783
4784    #[test]
4785    fn spanned_multibyte_utf8_pure_literal_is_byte_length() {
4786        // "hello 世界 world": 5 + 1 + 6 (3 per CJK char) + 1 + 5 = 18 bytes,
4787        // 13 chars. The `len` field must report 18, not 13.
4788        let parts = parse_interpolated_string_spanned("hello 世界 world", 0);
4789        assert_eq!(parts.len(), 1);
4790        assert!(matches!(&parts[0].part, StringPart::Literal(s) if s == "hello 世界 world"));
4791        assert_eq!(parts[0].offset, 0);
4792        assert_eq!(parts[0].len, 18);
4793    }
4794
4795    #[test]
4796    fn spanned_escape_dollar_consumes_two_bytes_emits_one_char() {
4797        // `\$` is 2 source bytes and resolves to a single literal `$`.
4798        // The literal part's `len` should reflect the SOURCE length (2).
4799        let parts = parse_interpolated_string_spanned("\\$", 0);
4800        assert_eq!(parts.len(), 1);
4801        assert!(matches!(&parts[0].part, StringPart::Literal(s) if s == "$"));
4802        assert_eq!(parts[0].offset, 0);
4803        assert_eq!(parts[0].len, 2, "len is source byte length, not rendered length");
4804    }
4805
4806    #[test]
4807    fn spanned_escape_backslash_collapses_pair_to_one() {
4808        let parts = parse_interpolated_string_spanned("\\\\", 0);
4809        assert_eq!(parts.len(), 1);
4810        assert!(matches!(&parts[0].part, StringPart::Literal(s) if s == "\\"));
4811        assert_eq!(parts[0].len, 2);
4812    }
4813
4814    #[test]
4815    fn spanned_standalone_cr_continuation_realigns_span_start() {
4816        // `\` + bare `\r` (old Mac line ending, no trailing `\n`) is a line
4817        // continuation: 2 source bytes, consumed with no output. Pins the
4818        // `current_text_start` update on that branch (parser.rs's `Some('\r')`
4819        // arm in `parse_interpolated_string_spanned`) — if it failed to
4820        // advance past the consumed `\`+`\r`, the following literal run would
4821        // be misreported starting at byte 0 instead of byte 2, corrupting
4822        // every subsequent span in the string (here, the `${x}` var's offset).
4823        let parts = parse_interpolated_string_spanned("\\\rCD${x}", 0);
4824        assert_eq!(parts.len(), 2);
4825        assert!(matches!(&parts[0].part, StringPart::Literal(s) if s == "CD"));
4826        assert_eq!(parts[0].offset, 2, "literal run must start after the consumed \\+CR");
4827        assert_eq!(parts[0].len, 2);
4828        assert!(matches!(&parts[1].part, StringPart::Var(_)));
4829        assert_eq!(parts[1].offset, 4);
4830        assert_eq!(parts[1].len, 4); // "${x}"
4831    }
4832
4833    #[test]
4834    fn spanned_standalone_cr_continuation_mid_run_keeps_span_start() {
4835        // Same continuation, but hit mid-run (current_text already holds
4836        // "AB") — current_text_start must stay anchored to the run's true
4837        // start (0), not jump to the post-continuation position, so "AB"
4838        // and "CD" merge into one literal spanning the whole source run.
4839        let parts = parse_interpolated_string_spanned("AB\\\rCD${x}", 0);
4840        assert_eq!(parts.len(), 2);
4841        assert!(matches!(&parts[0].part, StringPart::Literal(s) if s == "ABCD"));
4842        assert_eq!(parts[0].offset, 0);
4843        assert_eq!(parts[0].len, 6); // "AB" + "\" + "\r" + "CD" = 6 source bytes
4844        assert!(matches!(&parts[1].part, StringPart::Var(_)));
4845        assert_eq!(parts[1].offset, 6);
4846        assert_eq!(parts[1].len, 4); // "${x}"
4847    }
4848
4849    // ── Collection literals ─────────────────────────────────────────────
4850
4851    /// Extract the RHS `Expr` from a one-statement `NAME=value` assignment.
4852    fn assignment_value(source: &str) -> Expr {
4853        let program = parse(source).unwrap_or_else(|e| panic!("parse {source:?}: {e:?}"));
4854        match program.statements.as_slice() {
4855            [Stmt::Assignment(a)] => a.value.clone(),
4856            other => panic!("expected a single assignment, got {other:?}"),
4857        }
4858    }
4859
4860    #[test]
4861    fn list_literal_three_elements() {
4862        let expr = assignment_value("xs=[a b c]");
4863        match expr {
4864            Expr::ListLiteral(elems) => {
4865                assert_eq!(elems.len(), 3);
4866                assert!(elems.iter().all(|e| matches!(e, ListElem::Item(_))));
4867            }
4868            other => panic!("expected ListLiteral, got {other:?}"),
4869        }
4870    }
4871
4872    #[test]
4873    fn list_literal_empty() {
4874        let expr = assignment_value("xs=[]");
4875        assert!(matches!(expr, Expr::ListLiteral(elems) if elems.is_empty()));
4876    }
4877
4878    #[test]
4879    fn list_literal_single_glued_dog() {
4880        // `[dog]` is glued (no spaces) — the value-position glob-merge
4881        // suppression must still hand it to the parser as a one-element list,
4882        // not a fused GlobWord.
4883        let expr = assignment_value("xs=[dog]");
4884        match expr {
4885            Expr::ListLiteral(elems) => assert_eq!(elems.len(), 1),
4886            other => panic!("expected ListLiteral, got {other:?}"),
4887        }
4888    }
4889
4890    #[test]
4891    fn list_literal_single_int() {
4892        let expr = assignment_value("xs=[1]");
4893        match expr {
4894            Expr::ListLiteral(elems) => match elems.as_slice() {
4895                [ListElem::Item(Expr::Literal(Value::Int(1)))] => {}
4896                other => panic!("expected one Int(1) item, got {other:?}"),
4897            },
4898            other => panic!("expected ListLiteral, got {other:?}"),
4899        }
4900    }
4901
4902    #[test]
4903    fn record_literal_unspaced_colon_equals_spaced() {
4904        let spaced = assignment_value("x={port: 8080}");
4905        let unspaced = assignment_value("x={port:8080}");
4906        assert_eq!(spaced, unspaced, "{{port:8080}} must parse identically to {{port: 8080}}");
4907        match spaced {
4908            Expr::RecordLiteral(entries) => match entries.as_slice() {
4909                [RecordEntry { key: RecordKey::Bare(k), value: Expr::Literal(Value::Int(8080)) }] => {
4910                    assert_eq!(k, "port");
4911                }
4912                other => panic!("expected one port:8080 entry, got {other:?}"),
4913            },
4914            other => panic!("expected RecordLiteral, got {other:?}"),
4915        }
4916    }
4917
4918    #[test]
4919    fn record_literal_name_role() {
4920        let expr = assignment_value("u={name: amy, role: maintainer}");
4921        match expr {
4922            Expr::RecordLiteral(entries) => assert_eq!(entries.len(), 2),
4923            other => panic!("expected RecordLiteral, got {other:?}"),
4924        }
4925    }
4926
4927    #[test]
4928    fn record_literal_multiline_trailing_comma() {
4929        let source = "services={\n  web:    {port: 8080, replicas: 3, healthy: true},\n  api:    {port: 9000, replicas: 2, healthy: false},\n}";
4930        let expr = assignment_value(source);
4931        match expr {
4932            Expr::RecordLiteral(entries) => assert_eq!(entries.len(), 2, "web + api entries"),
4933            other => panic!("expected RecordLiteral, got {other:?}"),
4934        }
4935    }
4936
4937    #[test]
4938    fn record_literal_quoted_key() {
4939        let expr = assignment_value(r#"r={"content-type": x}"#);
4940        match expr {
4941            Expr::RecordLiteral(entries) => match entries.as_slice() {
4942                [RecordEntry { key: RecordKey::Quoted(k), .. }] => assert_eq!(k, "content-type"),
4943                other => panic!("expected one quoted-key entry, got {other:?}"),
4944            },
4945            other => panic!("expected RecordLiteral, got {other:?}"),
4946        }
4947    }
4948
4949    #[test]
4950    fn nested_list_and_record_in_record() {
4951        let expr = assignment_value("x={tags: [a b], meta: {active: true}}");
4952        match expr {
4953            Expr::RecordLiteral(entries) => {
4954                assert_eq!(entries.len(), 2);
4955                assert!(matches!(entries[0].value, Expr::ListLiteral(_)));
4956                assert!(matches!(entries[1].value, Expr::RecordLiteral(_)));
4957            }
4958            other => panic!("expected RecordLiteral, got {other:?}"),
4959        }
4960    }
4961
4962    #[test]
4963    fn spread_and_item_elements() {
4964        let expr = assignment_value("new=[...$xs date]");
4965        match expr {
4966            Expr::ListLiteral(elems) => match elems.as_slice() {
4967                [ListElem::Spread(Expr::VarRef(_)), ListElem::Item(Expr::Literal(Value::String(s)))] => {
4968                    assert_eq!(s, "date");
4969                }
4970                other => panic!("expected [Spread($xs), Item(date)], got {other:?}"),
4971            },
4972            other => panic!("expected ListLiteral, got {other:?}"),
4973        }
4974    }
4975
4976    #[test]
4977    fn spread_of_two_variables() {
4978        let expr = assignment_value("c=[...$a ...$b]");
4979        match expr {
4980            Expr::ListLiteral(elems) => {
4981                assert_eq!(elems.len(), 2);
4982                assert!(elems.iter().all(|e| matches!(e, ListElem::Spread(_))));
4983            }
4984            other => panic!("expected ListLiteral, got {other:?}"),
4985        }
4986    }
4987
4988    #[test]
4989    fn in_rhs_accepts_a_list_literal() {
4990        let program = parse("if [[ $a not in [dog] ]]; then echo hit; fi")
4991            .unwrap_or_else(|e| panic!("parse: {e:?}"));
4992        assert_eq!(program.statements.len(), 1);
4993    }
4994
4995    #[test]
4996    fn multiword_bareword_record_value_is_a_parse_error() {
4997        // Strict quoting inside literals: a record value must be exactly one
4998        // word or one quoted string — never silently split or joined.
4999        assert!(parse("x={msg: hello world}").is_err());
5000    }
5001
5002    // ── Invariant guards: argv/for-head globs must be unaffected ────────
5003
5004    #[test]
5005    fn argv_bracket_glob_stays_a_glob_pattern() {
5006        // `ls [dog]` is argv position — the glued `[dog]` run must still fuse
5007        // to a GlobWord (the value-position suppression only applies right
5008        // after `Eq`/a genuine membership `In`, not after a command name).
5009        let program = parse("ls [dog]").unwrap_or_else(|e| panic!("parse: {e:?}"));
5010        assert_eq!(program.statements.len(), 1);
5011    }
5012
5013    #[test]
5014    fn brace_expansion_at_argv_position_is_unaffected() {
5015        // `*.{rs,go}` is glob/brace-expansion argv syntax (the glob-merge run
5016        // needs a wildcard char present to fuse at all — a bare `{a,b}` with
5017        // no `*`/`?`/`[...]` never fuses into a GlobWord, independent of this
5018        // PR). Value-position literal parsing must not leak into argv.
5019        let program = parse("cmd *.{rs,go}").unwrap_or_else(|e| panic!("parse: {e:?}"));
5020        assert_eq!(program.statements.len(), 1);
5021    }
5022
5023    #[test]
5024    fn for_head_item_is_not_a_literal() {
5025        // `for x in [a]` stays argv (a GlobPattern word list), never a
5026        // ListLiteral — collection literals are value-position only.
5027        let program = parse("for x in [a]; do echo $x; done")
5028            .unwrap_or_else(|e| panic!("parse: {e:?}"));
5029        match program.statements.as_slice() {
5030            [Stmt::For(for_loop)] => {
5031                assert_eq!(for_loop.items.len(), 1);
5032                assert!(
5033                    !matches!(for_loop.items[0], Expr::ListLiteral(_)),
5034                    "for-head item must not be a ListLiteral: {:?}",
5035                    for_loop.items[0]
5036                );
5037            }
5038            other => panic!("expected a single For statement, got {other:?}"),
5039        }
5040    }
5041}