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.
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: a
1097        // structured value cannot cross the process boundary into a child's
1098        // environment, so there is nothing correct to assign.
1099        //
1100        // Using `ident_parser()` directly, not `lvalue_path_parser()`, means a
1101        // bracket run before `=` never gets a chance to parse as a path here.
1102        // Either it is absent (plain ident), or the lexer's lvalue suppression
1103        // fires and the stray `LBracket` fails this parser. Both fall through
1104        // to a real parse error rather than being accepted silently.
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/LANGUAGE.md`, "Assignment — bracket-path lvalues". They resolve at
1225/// runtime in `Scope::walk_write`, which shares the read resolver's per-hop
1226/// classification so a read and a write disagree about no path.
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        // Dash/plus bare words and flag-shaped tokens (GH #144): a case
1513        // pattern that happens to look like a flag (`-h`, `--help`, `+x`) or
1514        // an unrecognized dash/plus prefix (`---`, `-%`, `+%s`) is still a
1515        // literal glob pattern in case position, not a flag — the lexer
1516        // strips the leading dash/plus off `ShortFlag`/`LongFlag`/`PlusFlag`,
1517        // so put it back. Grouped in a nested `choice()` to stay under
1518        // chumsky's 26-element tuple limit for the outer `choice()`.
1519        choice((
1520            select! { Token::DoubleDashBare(s) => s },
1521            select! { Token::PlusBare(s) => s },
1522            select! { Token::MinusBare(s) => s },
1523            select! { Token::MinusAlone => "-".to_string() },
1524            select! { Token::DoubleDash => "--".to_string() },
1525            select! { Token::ShortFlag(s) => format!("-{}", s) },
1526            select! { Token::LongFlag(s) => format!("--{}", s) },
1527            select! { Token::PlusFlag(s) => format!("+{}", s) },
1528        )),
1529        // Character class: [a-z], [!abc], [^abc], etc.
1530        just(Token::LBracket)
1531            .ignore_then(
1532                choice((
1533                    select! { Token::Ident(s) => s },
1534                    select! { Token::Int(n) => n.to_string() },
1535                    just(Token::Colon).to(":".to_string()),
1536                    // Negation: ! or ^ at start of char class
1537                    just(Token::Bang).to("!".to_string()),
1538                    // Range like a-z
1539                    select! { Token::ShortFlag(s) => format!("-{}", s) },
1540                ))
1541                .repeated()
1542                .at_least(1)
1543                .collect::<Vec<String>>()
1544            )
1545            .then_ignore(just(Token::RBracket))
1546            .map(|parts| format!("[{}]", parts.join(""))),
1547        // Brace expansion: {a,b,c} or {js,ts}
1548        just(Token::LBrace)
1549            .ignore_then(
1550                choice((
1551                    select! { Token::Ident(s) => s },
1552                    select! { Token::Int(n) => n.to_string() },
1553                ))
1554                .separated_by(just(Token::Comma))
1555                .at_least(1)
1556                .collect::<Vec<String>>()
1557            )
1558            .then_ignore(just(Token::RBrace))
1559            .map(|parts| format!("{{{}}}", parts.join(","))),
1560    ));
1561
1562    // A complete pattern is one or more pattern parts joined together
1563    // e.g., "*.rs" = Star + Dot + Ident
1564    let pattern = pattern_part
1565        .repeated()
1566        .at_least(1)
1567        .collect::<Vec<String>>()
1568        .map(|parts| parts.join(""))
1569        .labelled("case pattern");
1570
1571    // Multiple patterns separated by pipe: `pattern1 | pattern2`
1572    let patterns = pattern
1573        .separated_by(just(Token::Pipe))
1574        .at_least(1)
1575        .collect::<Vec<String>>()
1576        .labelled("case patterns");
1577
1578    // Branch: `[( ] patterns ) commands ;;`
1579    let branch = just(Token::LParen)
1580        .or_not()
1581        .ignore_then(just(Token::Newline).repeated())
1582        .ignore_then(patterns)
1583        .then_ignore(just(Token::RParen))
1584        .then_ignore(just(Token::Newline).repeated())
1585        .then(
1586            stmt.clone()
1587                .repeated()
1588                .collect::<Vec<_>>()
1589                .map(|stmts| stmts.into_iter().filter(|s| !matches!(s, Stmt::Empty)).collect()),
1590        )
1591        .then_ignore(just(Token::DoubleSemi))
1592        .then_ignore(just(Token::Newline).repeated())
1593        .map(|(patterns, body)| CaseBranch { patterns, body })
1594        .labelled("case branch");
1595
1596    just(Token::Case)
1597        .ignore_then(expr_parser())
1598        .then_ignore(just(Token::In))
1599        .then_ignore(just(Token::Newline).repeated())
1600        .then(branch.repeated().collect::<Vec<_>>())
1601        .then_ignore(just(Token::Esac))
1602        .map(|(expr, branches)| CaseStmt { expr, branches })
1603        .labelled("case statement")
1604        .boxed()
1605}
1606
1607/// Pipeline: `cmd | cmd | cmd [&]`
1608fn pipeline_parser<'tokens, I>(
1609) -> impl Parser<'tokens, I, Pipeline, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1610where
1611    I: ValueInput<'tokens, Token = Token, Span = Span>,
1612{
1613    command_parser()
1614        .separated_by(just(Token::Pipe))
1615        .at_least(1)
1616        .collect::<Vec<_>>()
1617        .then(just(Token::Amp).or_not())
1618        .map(|(commands, bg)| Pipeline {
1619            commands,
1620            background: bg.is_some(),
1621        })
1622        .labelled("pipeline")
1623        .boxed()
1624}
1625
1626/// Command: `name args... [redirects...]`
1627/// Command names can be identifiers, 'true', 'false', or '.' (source alias).
1628fn command_parser<'tokens, I>(
1629) -> impl Parser<'tokens, I, Command, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1630where
1631    I: ValueInput<'tokens, Token = Token, Span = Span>,
1632{
1633    // Command name can be an identifier, path, 'true', 'false', '.' (source alias), or ./path
1634    let command_name = choice((
1635        ident_parser(),
1636        path_parser(),
1637        select! { Token::DotSlashPath(s) => s },
1638        just(Token::True).to("true".to_string()),
1639        just(Token::False).to("false".to_string()),
1640        just(Token::Dot).to(".".to_string()),
1641    ));
1642
1643    // NB: the "at most one stdin source per command" rule is enforced by a
1644    // post-parse scan in `parse()` (see `first_ambiguous_stdin`), NOT here.
1645    // A `try_map` rejection at this level cannot surface its own message: a
1646    // command like `cat <<< a <<< b` also fails the competing statement-level
1647    // assignment/function alternative ("expected '=', or '('"), and chumsky's
1648    // `choice` merge keeps that alternative's error regardless of which span
1649    // our custom error carries. So we accept the command here and reject it
1650    // structurally after parsing, where the message is fully under our control
1651    // (verified empirically 2026-06-07).
1652    command_name
1653        .then(args_list_parser())
1654        .then(redirect_parser(primary_expr_parser()).repeated().collect::<Vec<_>>())
1655        .map(|((name, args), redirects)| Command {
1656            name,
1657            args,
1658            redirects,
1659        })
1660        .labelled("command")
1661        .boxed()
1662}
1663
1664/// Map a parsed `Pipeline` to a statement, unwrapping a single redirect-free
1665/// foreground command to `Stmt::Command` (the canonical shape used throughout
1666/// the parser). Shared by the top-level statement parser, `$()` bodies, and
1667/// inline env-prefix bodies so the unwrap rule lives in one place.
1668fn pipeline_into_stmt(p: Pipeline) -> Stmt {
1669    if p.commands.len() == 1 && !p.background && p.commands[0].redirects.is_empty() {
1670        match p.commands.into_iter().next() {
1671            Some(cmd) => Stmt::Command(cmd),
1672            None => Stmt::Empty, // unreachable (len checked) but safe
1673        }
1674    } else {
1675        Stmt::Pipeline(p)
1676    }
1677}
1678
1679/// True if `cmd` has more than one stdin source (`<`, `<<`, `<<<`). Such a
1680/// command would silently depend on redirect ordering at execution time
1681/// (`setup_stdin_redirects` is last-wins), so `parse()` rejects it loudly.
1682fn command_has_ambiguous_stdin(cmd: &Command) -> bool {
1683    cmd.redirects
1684        .iter()
1685        .filter(|r| {
1686            matches!(
1687                r.kind,
1688                RedirectKind::Stdin | RedirectKind::HereDoc | RedirectKind::HereString
1689            )
1690        })
1691        .count()
1692        > 1
1693}
1694
1695/// Find the first command anywhere in `stmts` (recursing into pipelines,
1696/// control-flow bodies, chains, and tool definitions) that has more than one
1697/// stdin source. Used by `parse()` to reject the ambiguity after parsing.
1698fn first_ambiguous_stdin(stmts: &[Stmt]) -> bool {
1699    stmts.iter().any(stmt_has_ambiguous_stdin)
1700}
1701
1702fn stmt_has_ambiguous_stdin(stmt: &Stmt) -> bool {
1703    match stmt {
1704        Stmt::Command(c) => command_has_ambiguous_stdin(c),
1705        Stmt::Pipeline(p) => p.commands.iter().any(command_has_ambiguous_stdin),
1706        Stmt::If(i) => {
1707            first_ambiguous_stdin(&i.then_branch)
1708                || i.else_branch
1709                    .as_deref()
1710                    .is_some_and(first_ambiguous_stdin)
1711        }
1712        Stmt::For(f) => first_ambiguous_stdin(&f.body),
1713        Stmt::While(w) => first_ambiguous_stdin(&w.body),
1714        Stmt::Case(c) => c.branches.iter().any(|b| first_ambiguous_stdin(&b.body)),
1715        Stmt::ToolDef(t) => first_ambiguous_stdin(&t.body),
1716        Stmt::AndChain { left, right } | Stmt::OrChain { left, right } => {
1717            stmt_has_ambiguous_stdin(left) || stmt_has_ambiguous_stdin(right)
1718        }
1719        Stmt::EnvScoped { body, .. } => stmt_has_ambiguous_stdin(body),
1720        Stmt::Assignment(_)
1721        | Stmt::Break(_)
1722        | Stmt::Continue(_)
1723        | Stmt::Return(_)
1724        | Stmt::Exit(_)
1725        | Stmt::Test(_)
1726        | Stmt::Empty => false,
1727    }
1728}
1729
1730/// True for the argv-fragment `Arg` shapes eligible for the no-token-pasting
1731/// glue check below: bareword/expr positionals AND long flags.
1732///
1733/// `ShortFlag` is deliberately EXCLUDED: a single-char short flag glued
1734/// straight to its value with no space (`cut -d,`, `grep -A$n`) is the
1735/// getopt-style glued-value idiom the kernel binder (`consume_flag_positionals`
1736/// / `bind_glued_short_value`) already supports and tests rely on — the flag
1737/// char class covers alnum/dash so a purely-textual glued value (`-f1`,
1738/// `-C3`) is already ONE lexer token, but a punctuation/subst value (`-d,`,
1739/// `-d$(cmd)`) genuinely arrives as two adjacent `Arg`s and must NOT be
1740/// rejected here. `--flag` has no such glued-value idiom (only the explicit
1741/// `--flag=value` form, which fuses into `Named` before reaching this list),
1742/// so a `LongFlag` glued to a following fragment is always a pasting
1743/// accident, not a feature.
1744///
1745/// `Named`/`WordAssign` are excluded too — those already fuse a span-adjacent
1746/// `--key=value`/`key=value` pair into ONE `Arg` before reaching this list
1747/// (see `long_flag_with_value`/`word_assign_arg_parser`'s own adjacency
1748/// checks), so back-to-back adjacency there is by design, not a pasting
1749/// accident.
1750fn is_glue_candidate(arg: &Arg) -> bool {
1751    matches!(arg, Arg::Positional(_) | Arg::LongFlag(_))
1752}
1753
1754/// Reject a run of argv fragments produced by glued (zero source-gap)
1755/// tokens — kaish does no token pasting, so an unquoted `/tmp/$(echo
1756/// x).txt` lexes into three fragments (`/tmp/`, the substitution, `.txt`)
1757/// that would otherwise silently bind as THREE separate args, and
1758/// `--flag$(echo x)` glues a flag straight to the next fragment with no
1759/// error at all. Shared by the pre-`--` and post-`--` argument grammars
1760/// (GH #189: the post-`--` half of this used to be unchecked entirely — a
1761/// script relying on `--` to end flag parsing got a silent argv-splat
1762/// instead of this same helpful error).
1763///
1764/// A comma-bearing word (`cut -f1,3`, `sort -k2,2n`, `echo a,b`) used to
1765/// trip this guard and get a comma-specific "kaish reserves `,`" hint —
1766/// that was never true outside a `[...]`/`{...}` literal or pattern, and
1767/// the lexer now folds a bare comma into the surrounding bareword before
1768/// the parser ever sees separate fragments (see `lexer::flush_glob_run`),
1769/// so a comma-bearing word no longer reaches this function as two glued
1770/// `Arg`s at all. Every remaining case is genuine token pasting.
1771fn reject_glued_args<'src>(
1772    args: Vec<(Arg, Span)>,
1773) -> Result<Vec<Arg>, Rich<'src, Token, Span>> {
1774    for pair in args.windows(2) {
1775        let (prev, prev_span) = &pair[0];
1776        let (next, next_span) = &pair[1];
1777        if is_glue_candidate(prev) && is_glue_candidate(next) && prev_span.end == next_span.start {
1778            let msg = "adjacent words with no space between them are not joined into one \
1779                 argument (kaish does no token pasting); quote the whole word, e.g. \
1780                 \"/tmp/$(echo x).txt\" or \"$dir/out.txt\"";
1781            return Err(Rich::custom(*next_span, msg));
1782        }
1783    }
1784    Ok(args.into_iter().map(|(arg, _)| arg).collect())
1785}
1786
1787/// Arguments list parser that handles `--` flag terminator.
1788///
1789/// After `--`, all subsequent flags are converted to positional string arguments.
1790fn args_list_parser<'tokens, I>(
1791) -> impl Parser<'tokens, I, Vec<Arg>, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1792where
1793    I: ValueInput<'tokens, Token = Token, Span = Span>,
1794{
1795    // Arguments before `--` (normal parsing). Each arg is captured with its
1796    // source span so we can reject the silent argv-splat: two argv fragments
1797    // with no whitespace between them (`/tmp/$(echo x).txt` → 3 args,
1798    // `--flag$(echo x)` → a flag glued to one). kaish does no token pasting,
1799    // so an unquoted interpolated word fragments into separate args; the fix
1800    // is to quote the whole word. Single-token words (`file.txt`, `v1.2.3`)
1801    // are one arg and never trigger this. See `reject_glued_args`.
1802    let pre_dash = arg_before_double_dash_parser()
1803        .map_with(|arg, e| -> (Arg, Span) { (arg, e.span()) })
1804        .repeated()
1805        .collect::<Vec<(Arg, Span)>>()
1806        .try_map(|args, _span| reject_glued_args(args));
1807
1808    // The `--` marker itself
1809    let double_dash = select! {
1810        Token::DoubleDash => Arg::DoubleDash,
1811    };
1812
1813    // Arguments after `--` (flags become positional strings)
1814    let post_dash_arg = choice((
1815        // Flags become positional strings
1816        select! {
1817            Token::ShortFlag(name) => Arg::Positional(Expr::Literal(Value::String(format!("-{}", name)))),
1818            Token::LongFlag(name) => Arg::Positional(Expr::Literal(Value::String(format!("--{}", name)))),
1819        },
1820        // `name=value` — same WordAssign production used before `--`. Nothing
1821        // is special after `--` (standard shell behavior), but the
1822        // WordAssign→positional collapse already yields the literal
1823        // `"name=value"` string for commands that don't consume shell
1824        // assignments (like `echo`), so no separate literal-folding rule is
1825        // needed here.
1826        word_assign_arg_parser(),
1827        // `test`/`[` operators stay literal after `--` too (`test -- a = b`).
1828        test_operator_arg_parser(),
1829        // Everything else stays the same
1830        primary_expr_parser().map(Arg::Positional),
1831    ));
1832
1833    // Same glue guard as `pre_dash` (GH #189): before this, a post-`--`
1834    // glued word silently split into separate positionals instead of
1835    // erroring — the pre-`--` guard never ran over these tokens at all.
1836    let post_dash = post_dash_arg
1837        .map_with(|arg, e| -> (Arg, Span) { (arg, e.span()) })
1838        .repeated()
1839        .collect::<Vec<(Arg, Span)>>()
1840        .try_map(|args, _span| reject_glued_args(args));
1841
1842    // Combine: args_before ++ [--] ++ args_after
1843    pre_dash
1844        .then(double_dash.then(post_dash).or_not())
1845        .map(|(mut args, maybe_dd)| {
1846            if let Some((dd, post)) = maybe_dd {
1847                args.push(dd);
1848                args.extend(post);
1849            }
1850            args
1851        })
1852}
1853
1854/// A statement keyword used as a plain word — its source spelling.
1855///
1856/// Lets keywords serve as the *key* of a `key=value` argv assignment, so
1857/// `dd if=/dev/urandom` works (`if` is `Token::If`, not an `Ident`). Safe
1858/// because: statement-level `if`/`for`/… are decided before arg parsing (their
1859/// productions precede `pipeline_parser`), `command_name` never accepts these
1860/// tokens, and the `key=value` rule requires the key span-adjacent to `=` — a
1861/// real `if <cond>` has a space and never matches. See docs/binary-data.md.
1862fn keyword_word<'tokens, I>(
1863) -> impl Parser<'tokens, I, String, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1864where
1865    I: ValueInput<'tokens, Token = Token, Span = Span>,
1866{
1867    select! {
1868        Token::Set => "set",
1869        Token::Local => "local",
1870        Token::If => "if",
1871        Token::Then => "then",
1872        Token::Else => "else",
1873        Token::Elif => "elif",
1874        Token::Fi => "fi",
1875        Token::For => "for",
1876        Token::While => "while",
1877        Token::In => "in",
1878        Token::Do => "do",
1879        Token::Done => "done",
1880        Token::Case => "case",
1881        Token::Esac => "esac",
1882        Token::Function => "function",
1883        Token::Break => "break",
1884        Token::Continue => "continue",
1885        Token::Return => "return",
1886        Token::Exit => "exit",
1887    }
1888    .map(|s| s.to_string())
1889}
1890
1891/// Shell assignment in argv position: `name=value` (must not have spaces
1892/// around `=`). Produces `Arg::WordAssign`; the kernel routes it through
1893/// `tool_args.named` only for shell-assignment-accepting builtins (export,
1894/// alias). For every other command it materialises as a `"name=value"`
1895/// positional, matching bash semantics (`cat foo=bar` opens a file named
1896/// `foo=bar`). Shared by the pre-`--` and post-`--` argument grammars — the
1897/// `WordAssign`/positional collapse already gives `--`-following `a=b` the
1898/// literal-string behavior shell users expect, so it needs no special casing
1899/// after `--`.
1900fn word_assign_arg_parser<'tokens, I>(
1901) -> impl Parser<'tokens, I, Arg, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1902where
1903    I: ValueInput<'tokens, Token = Token, Span = Span>,
1904{
1905    choice((
1906        select! { Token::Ident(s) => s },
1907        keyword_word(),
1908    ))
1909    .map_with(|s, e| -> (String, Span) { (s, e.span()) })
1910    .then(just(Token::Eq).map_with(|_, e| -> Span { e.span() }))
1911    .then(primary_expr_parser().map_with(|expr, e| -> (Expr, Span) { (expr, e.span()) }))
1912    .try_map(|(((key, key_span), eq_span), (value, value_span)): (((String, Span), Span), (Expr, Span)), span| {
1913        // Check that key ends where = starts and = ends where value starts
1914        if key_span.end != eq_span.start || eq_span.end != value_span.start {
1915            Err(Rich::custom(
1916                span,
1917                "shell assignment must not have spaces around '=' (use 'key=value' not 'key = value')",
1918            ))
1919        } else {
1920            Ok(Arg::WordAssign { key, value })
1921        }
1922    })
1923}
1924
1925/// The `test`/`[` comparison and negation operators (`=`, `==`, `!=`, `!`) as
1926/// ordinary positional argv words.
1927///
1928/// POSIX `test` is a *command*, so its operators must reach it flat as argv —
1929/// but kaish lexes `=`/`==`/`!=`/`!` as shell-significant tokens, so at
1930/// command-argument position they used to parse-error before ever reaching a
1931/// command (`test a = b`). This production makes each a literal-string
1932/// positional. It is name-agnostic: like bash, `echo a = b` prints `a = b` —
1933/// no command name is special-cased (that would be fragile under aliases).
1934///
1935/// Deliberately EXCLUDES the angle brackets `<` `>` `<=` `>=`: those stay
1936/// redirection (making them argv would shadow redirects) and remain
1937/// `[[ ]]`-only. Ordered after the flag/`word_assign` productions so a glued
1938/// `name=value` still binds as a `WordAssign` — this bare-operator rule only
1939/// fires once the current token IS the standalone operator (a spaced `a = b`,
1940/// where `word_assign`'s span-adjacency check has already declined).
1941fn test_operator_arg_parser<'tokens, I>(
1942) -> impl Parser<'tokens, I, Arg, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1943where
1944    I: ValueInput<'tokens, Token = Token, Span = Span>,
1945{
1946    select! {
1947        Token::Eq => "=",
1948        Token::EqEq => "==",
1949        Token::NotEq => "!=",
1950        Token::Bang => "!",
1951    }
1952    .map(|s| Arg::Positional(Expr::Literal(Value::String(s.to_string()))))
1953}
1954
1955/// Argument parser for arguments before `--` (normal flag handling).
1956fn arg_before_double_dash_parser<'tokens, I>(
1957) -> impl Parser<'tokens, I, Arg, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1958where
1959    I: ValueInput<'tokens, Token = Token, Span = Span>,
1960{
1961    // Long flag with value: --name=value
1962    let long_flag_with_value = select! {
1963        Token::LongFlag(name) => name,
1964    }
1965    .then_ignore(just(Token::Eq))
1966    .then(primary_expr_parser())
1967    .map(|(key, value)| Arg::Named { key, value });
1968
1969    // Boolean long flag: --name
1970    let long_flag = select! {
1971        Token::LongFlag(name) => Arg::LongFlag(name),
1972    };
1973
1974    // Boolean short flag: -x
1975    let short_flag = select! {
1976        Token::ShortFlag(name) => Arg::ShortFlag(name),
1977    };
1978
1979    // Shell assignment in argv position: name=value (must not have spaces around =).
1980    let named = word_assign_arg_parser();
1981
1982    // Positional argument
1983    let positional = primary_expr_parser().map(Arg::Positional);
1984
1985    // The `test`/`[` operators (`=` `==` `!=` `!`) as literal positionals.
1986    // After the flag/`named` productions (so glued `name=value` stays a
1987    // WordAssign), before `positional` (which can't parse these tokens).
1988    let test_operator = test_operator_arg_parser();
1989
1990    // Order matters: try more specific patterns first
1991    // Note: DoubleDash is NOT included here - it's handled by args_list_parser
1992    choice((
1993        long_flag_with_value,
1994        long_flag,
1995        short_flag,
1996        named,
1997        test_operator,
1998        positional,
1999    ))
2000    .boxed()
2001}
2002
2003/// Redirect: `> file`, `>> file`, `< file`, `<< heredoc`, `2> file`, `&> file`, `2>&1`
2004///
2005/// `target` parses the file word (and here-string body). Callers pass the
2006/// expression parser appropriate to their context: the top-level command
2007/// grammar passes a fresh `primary_expr_parser()`, while `cmd_subst_parser`
2008/// passes its *already-recursive* `expr` handle. Threading it in (rather than
2009/// building `primary_expr_parser()` internally) is what lets `$(cmd > file)`
2010/// parse without an unbounded `cmd_subst → redirect → primary_expr → cmd_subst`
2011/// construction cycle.
2012fn redirect_parser<'tokens, I, T>(
2013    target: T,
2014) -> impl Parser<'tokens, I, Redirect, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2015where
2016    I: ValueInput<'tokens, Token = Token, Span = Span>,
2017    T: Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
2018{
2019    // `target` only ever parses ONE expression. An unquoted target that
2020    // spans multiple lexical fragments with no gap between them
2021    // (`/tmp/$(echo x).txt` lexes as three tokens: "/tmp/", the command
2022    // substitution, ".txt") only binds its first fragment as the target —
2023    // the rest dangle, and the surrounding statement grammar rejects them
2024    // with a generic chumsky "expected ..." message that never mentions
2025    // quoting (GH #189). Peek (`rewind`, consumes nothing) for an
2026    // immediately-adjacent further expr fragment and turn that into the same
2027    // "quote it" hint `reject_glued_args` gives positional args, worded for a
2028    // redirect target. The peek reuses the caller's own `target` clone
2029    // (never a fresh `primary_expr_parser()` built here) — see the
2030    // construction-cycle note in this function's doc comment above.
2031    let target = target
2032        .clone()
2033        .map_with(|expr, e| -> (Expr, Span) { (expr, e.span()) })
2034        .then(target.clone().map_with(|_, e| e.span()).rewind().or_not())
2035        .try_map(|((expr, span), glued), _| match glued {
2036            Some(next_span) if next_span.start == span.end => Err(Rich::custom(
2037                next_span,
2038                "adjacent words with no space between them are not joined into the redirect \
2039                 target (kaish does no token pasting); quote the whole target, e.g. \
2040                 \"/tmp/$(echo x).txt\"",
2041            )),
2042            _ => Ok(expr),
2043        })
2044        .boxed();
2045
2046    // Regular redirects: >, >>, <, 2>, &>
2047    let regular_redirect = select! {
2048        Token::GtGt => RedirectKind::StdoutAppend,
2049        Token::Gt => RedirectKind::StdoutOverwrite,
2050        Token::Lt => RedirectKind::Stdin,
2051        Token::Stderr => RedirectKind::Stderr,
2052        Token::Both => RedirectKind::Both,
2053    }
2054    .then(target.clone())
2055    .map(|(kind, target)| Redirect { kind, target });
2056
2057    // Here-doc redirect: << content
2058    // Quoted delimiters (<<'EOF' or <<"EOF") produce literal heredocs (no expansion).
2059    // Unquoted delimiters produce interpolated heredocs (variables are expanded).
2060    // For literal heredocs the `<<-EOF` tab stripping is applied here at parse
2061    // time (the body is fully known); for interpolated heredocs the stripping
2062    // is deferred to the interpreter so source byte offsets in `parts` stay
2063    // aligned with the original source for span reporting.
2064    let heredoc_redirect = just(Token::HereDocStart)
2065        .ignore_then(select! { Token::HereDoc(data) => data })
2066        .map(|data: HereDocData| {
2067            let target = if data.literal {
2068                let body = if data.strip_tabs {
2069                    crate::interpreter::strip_leading_tabs(&data.content)
2070                } else {
2071                    data.content
2072                };
2073                Expr::Literal(Value::String(body))
2074            } else {
2075                let parts = parse_interpolated_string_spanned(
2076                    &data.content,
2077                    data.body_start_offset,
2078                );
2079                // If there's only one literal part and no tab stripping is
2080                // needed, simplify to Expr::Literal — keeps the AST shape
2081                // identical to the pre-spans path for trivial bodies.
2082                if parts.len() == 1 && !data.strip_tabs {
2083                    if let StringPart::Literal(text) = &parts[0].part {
2084                        return Redirect {
2085                            kind: RedirectKind::HereDoc,
2086                            target: Expr::Literal(Value::String(text.clone())),
2087                        };
2088                    }
2089                }
2090                Expr::HereDocBody {
2091                    parts,
2092                    strip_tabs: data.strip_tabs,
2093                }
2094            };
2095            Redirect {
2096                kind: RedirectKind::HereDoc,
2097                target,
2098            }
2099        });
2100
2101    // Here-string redirect: <<< word
2102    // The target is any single expression; kaish's existing Expr machinery
2103    // handles interpolation, single-quoted literals, and command substitution.
2104    let herestring_redirect = just(Token::HereString)
2105        .ignore_then(target.clone())
2106        .map(|target| Redirect {
2107            kind: RedirectKind::HereString,
2108            target,
2109        });
2110
2111    // Merge stderr to stdout: 2>&1 (no target needed - implicit)
2112    let merge_stderr_redirect = just(Token::StderrToStdout)
2113        .map(|_| Redirect {
2114            kind: RedirectKind::MergeStderr,
2115            // Target is unused for MergeStderr, but we need something
2116            target: Expr::Literal(Value::Null),
2117        });
2118
2119    // Merge stdout to stderr: 1>&2 or >&2 (no target needed - implicit)
2120    let merge_stdout_redirect = choice((
2121        just(Token::StdoutToStderr),
2122        just(Token::StdoutToStderr2),
2123    ))
2124    .map(|_| Redirect {
2125        kind: RedirectKind::MergeStdout,
2126        // Target is unused for MergeStdout, but we need something
2127        target: Expr::Literal(Value::Null),
2128    });
2129
2130    choice((
2131        heredoc_redirect,
2132        herestring_redirect,
2133        merge_stderr_redirect,
2134        merge_stdout_redirect,
2135        regular_redirect,
2136    ))
2137    .labelled("redirect")
2138    .boxed()
2139}
2140
2141/// Test expression parser for `[[ ... ]]` syntax.
2142///
2143/// Supports:
2144/// - File tests: `[[ -f path ]]`, `[[ -d path ]]`, etc.
2145/// - String tests: `[[ -z str ]]`, `[[ -n str ]]`
2146/// - Shape-guard tests: `[[ -list x ]]`, `[[ -record x ]]` (see
2147///   `docs/LANGUAGE.md`, "Shape guards")
2148/// - Comparisons: `[[ $X == "value" ]]`, `[[ $NUM -gt 5 ]]`
2149/// - Compound: `[[ -f a && -d b ]]`, `[[ -z x || -n y ]]`, `[[ ! -f file ]]`
2150///
2151/// Precedence (highest to lowest): `!` > `&&` > `||`
2152fn test_expr_stmt_parser<'tokens, I>(
2153) -> impl Parser<'tokens, I, TestExpr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2154where
2155    I: ValueInput<'tokens, Token = Token, Span = Span>,
2156{
2157    // File test operators: -e, -f, -d, -r, -w, -x
2158    let file_test_op = select! {
2159        Token::ShortFlag(s) if s == "e" => FileTestOp::Exists,
2160        Token::ShortFlag(s) if s == "f" => FileTestOp::IsFile,
2161        Token::ShortFlag(s) if s == "d" => FileTestOp::IsDir,
2162        Token::ShortFlag(s) if s == "r" => FileTestOp::Readable,
2163        Token::ShortFlag(s) if s == "w" => FileTestOp::Writable,
2164        Token::ShortFlag(s) if s == "x" => FileTestOp::Executable,
2165    };
2166
2167    // String test operators: -z, -n, plus the shape-guard operators -list /
2168    // -record (value-typed tests, not path stats — same operand-evaluation
2169    // path as -z/-n, unlike the file_test_op family above).
2170    let string_test_op = select! {
2171        Token::ShortFlag(s) if s == "z" => StringTestOp::IsEmpty,
2172        Token::ShortFlag(s) if s == "n" => StringTestOp::IsNonEmpty,
2173        Token::ShortFlag(s) if s == "list" => StringTestOp::IsList,
2174        Token::ShortFlag(s) if s == "record" => StringTestOp::IsRecord,
2175    };
2176
2177    // Comparison operators: =, ==, !=, =~, !~, >, <, >=, <=, -gt, -lt, -ge, -le, -eq, -ne
2178    // Note: = and == are equivalent inside [[ ]] (matching bash behavior)
2179    let cmp_op = choice((
2180        just(Token::EqEq).to(TestCmpOp::Eq),
2181        just(Token::Eq).to(TestCmpOp::Eq),
2182        just(Token::NotEq).to(TestCmpOp::NotEq),
2183        just(Token::Match).to(TestCmpOp::Match),
2184        just(Token::NotMatch).to(TestCmpOp::NotMatch),
2185        just(Token::Gt).to(TestCmpOp::Gt),
2186        just(Token::Lt).to(TestCmpOp::Lt),
2187        just(Token::GtEq).to(TestCmpOp::GtEq),
2188        just(Token::LtEq).to(TestCmpOp::LtEq),
2189        select! { Token::ShortFlag(s) if s == "eq" => TestCmpOp::NumEq },
2190        select! { Token::ShortFlag(s) if s == "ne" => TestCmpOp::NumNotEq },
2191        select! { Token::ShortFlag(s) if s == "gt" => TestCmpOp::NumGt },
2192        select! { Token::ShortFlag(s) if s == "lt" => TestCmpOp::NumLt },
2193        select! { Token::ShortFlag(s) if s == "ge" => TestCmpOp::NumGtEq },
2194        select! { Token::ShortFlag(s) if s == "le" => TestCmpOp::NumLtEq },
2195    ));
2196
2197    // File test: -f path
2198    let file_test = file_test_op
2199        .then(primary_expr_parser())
2200        .map(|(op, path)| TestExpr::FileTest {
2201            op,
2202            path: Box::new(path),
2203        });
2204
2205    // String test: -z str
2206    let string_test = string_test_op
2207        .then(primary_expr_parser())
2208        .map(|(op, value)| TestExpr::StringTest {
2209            op,
2210            value: Box::new(value),
2211        });
2212
2213    // Comparison: $X == "value" or $NUM -gt 5
2214    let comparison = primary_expr_parser()
2215        .then(cmp_op)
2216        .then(primary_expr_parser())
2217        .map(|((left, op), right)| TestExpr::Comparison {
2218            left: Box::new(left),
2219            op,
2220            right: Box::new(right),
2221        });
2222
2223    // Collection membership: `e in $coll` / `e not in $coll` (element-in-list,
2224    // key-in-record; see docs/LANGUAGE.md, "Membership"). There is no dedicated
2225    // `not` token — it lexes as a plain identifier, so `not_in` matches the
2226    // two-word sequence `Ident("not") In`. Try `not_in` before `in` below, or
2227    // `e not in c` parses as `e in` and then fails on the stray `not` bareword.
2228    let not_in = primary_expr_parser()
2229        .then_ignore(select! { Token::Ident(s) if s == "not" => () })
2230        .then_ignore(just(Token::In))
2231        .then(value_primary_parser())
2232        .map(|(left, right)| TestExpr::NotIn {
2233            left: Box::new(left),
2234            right: Box::new(right),
2235        });
2236
2237    let in_ = primary_expr_parser()
2238        .then_ignore(just(Token::In))
2239        .then(value_primary_parser())
2240        .map(|(left, right)| TestExpr::In {
2241            left: Box::new(left),
2242            right: Box::new(right),
2243        });
2244
2245    // Primary test expression (atomic - no compound operators)
2246    let primary_test = choice((file_test, string_test, not_in, in_, comparison));
2247
2248    // Build compound expressions with proper precedence:
2249    // Grammar:
2250    //   test_expr = or_expr
2251    //   or_expr   = and_expr { "||" and_expr }
2252    //   and_expr  = unary_expr { "&&" unary_expr }
2253    //   unary_expr = "!" unary_expr | primary_test
2254    //
2255    // Precedence: ! (highest) > && > ||
2256
2257    // Unary NOT binds tighter than `&&`/`||`, so it must recurse at the
2258    // unary level — `! A || B` is `(!A) || B`, NOT `!(A || B)`. The inner
2259    // `recursive` lets `!` chain (`! ! expr`) while bottoming out at a
2260    // primary test, so the bang never swallows a following `&&`/`||` operand.
2261    let unary = recursive(|unary| {
2262        let not_expr = just(Token::Bang)
2263            .ignore_then(unary)
2264            .map(|expr| TestExpr::Not { expr: Box::new(expr) });
2265        choice((not_expr, primary_test.clone()))
2266    });
2267
2268    // AND level: unary && unary && ...
2269    let and_expr = unary.clone().foldl(
2270        just(Token::And).ignore_then(unary).repeated(),
2271        |left, right| TestExpr::And {
2272            left: Box::new(left),
2273            right: Box::new(right),
2274        },
2275    );
2276
2277    // OR level: and_expr || and_expr || ...
2278    let compound_test = and_expr.clone().foldl(
2279        just(Token::Or).ignore_then(and_expr).repeated(),
2280        |left, right| TestExpr::Or {
2281            left: Box::new(left),
2282            right: Box::new(right),
2283        },
2284    );
2285
2286    // [[ ]] is two consecutive bracket tokens (not a single TestStart token)
2287    // to avoid conflicts with nested array syntax like [[1, 2], [3, 4]]
2288    just(Token::LBracket)
2289        .then(just(Token::LBracket))
2290        .ignore_then(compound_test)
2291        .then_ignore(just(Token::RBracket).then(just(Token::RBracket)))
2292        .labelled("test expression")
2293        .boxed()
2294}
2295
2296/// Condition parser: supports [[ ]] test expressions and commands with && / || chaining.
2297///
2298/// Shell semantics: conditions are commands whose exit codes determine truthiness.
2299/// - `if true; then` → runs `true` builtin, exit code 0 = truthy
2300/// - `if grep -q pattern file; then` → runs command, checks exit code
2301/// - `if a && b; then` → runs `a`, if exit 0, runs `b`
2302///
2303/// Use `[[ ]]` for comparisons: `if [[ $X -gt 5 ]]; then`
2304///
2305/// Grammar (with precedence - && binds tighter than ||):
2306///   condition = or_expr
2307///   or_expr   = and_expr { "||" and_expr }
2308///   and_expr  = base { "&&" base }
2309///   base      = test_expr | command
2310fn condition_parser<'tokens, I>(
2311) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2312where
2313    I: ValueInput<'tokens, Token = Token, Span = Span>,
2314{
2315    // [[ ]] test expression - wrap as Expr::Test
2316    let test_expr_condition = test_expr_stmt_parser().map(|test| Expr::Test(Box::new(test)));
2317
2318    // Command as condition (includes true/false as command names)
2319    // The command's exit code determines truthiness (0 = true, non-zero = false)
2320    let command_condition = command_parser().map(Expr::Command);
2321
2322    // Base: test expr OR command
2323    let base = choice((test_expr_condition, command_condition));
2324
2325    // && has higher precedence than ||
2326    // First chain with && (higher precedence)
2327    let and_expr = base.clone().foldl(
2328        just(Token::And).ignore_then(base).repeated(),
2329        |left, right| Expr::BinaryOp {
2330            left: Box::new(left),
2331            op: BinaryOp::And,
2332            right: Box::new(right),
2333        },
2334    );
2335
2336    // Then chain with || (lower precedence)
2337    and_expr
2338        .clone()
2339        .foldl(
2340            just(Token::Or).ignore_then(and_expr).repeated(),
2341            |left, right| Expr::BinaryOp {
2342                left: Box::new(left),
2343                op: BinaryOp::Or,
2344                right: Box::new(right),
2345            },
2346        )
2347        .labelled("condition")
2348        .boxed()
2349}
2350
2351/// Expression parser - supports && and || binary operators.
2352///
2353/// Used by `for`-head items (among others), which must stay `$()`-only
2354/// (bare `$VAR` splice is rejected upstream by validator E012 — see
2355/// docs/LANGUAGE.md) and must NOT gain collection literals later. Do not
2356/// reroute this to the value seam.
2357fn expr_parser<'tokens, I>(
2358) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2359where
2360    I: ValueInput<'tokens, Token = Token, Span = Span>,
2361{
2362    // For now, just primary expressions. Can extend for && / || later if needed.
2363    primary_expr_parser()
2364}
2365
2366/// Value-position expression parser (assignment RHS: bash-style, `local`,
2367/// and env-prefix). Adds collection literals on top of everything
2368/// `primary_expr_parser` covers, so they appear on assignment RHS but never
2369/// in argv or `for`-head items (`expr_parser`, above, stays untouched).
2370fn value_expr_parser<'tokens, I>(
2371) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2372where
2373    I: ValueInput<'tokens, Token = Token, Span = Span>,
2374{
2375    value_literal_parser()
2376}
2377
2378/// Value-position primary parser (`in`/`not in` RHS operand only — the
2379/// collection being tested for membership; the left needle stays on
2380/// `primary_expr_parser`). Same grammar as `value_expr_parser`; kept as a
2381/// separate name because the two seams are conceptually distinct call sites
2382/// (see PR-A) even though they currently share an implementation.
2383fn value_primary_parser<'tokens, I>(
2384) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2385where
2386    I: ValueInput<'tokens, Token = Token, Span = Span>,
2387{
2388    value_literal_parser()
2389}
2390
2391/// The value-position grammar: list/record literals (tried first, so a
2392/// `[`/`{` at value position is always a literal — never a bareword/glob),
2393/// falling back to everything `primary_expr_parser` covers ($(), `$VAR`,
2394/// scalars, …). `recursive` lets literal interiors reference this same
2395/// grammar, so nesting (`{tags: [a b], meta: {active: true}}`) and spread
2396/// (`[...$xs date]`) both parse.
2397///
2398/// The lexer guarantees a `[`/`{` reaching here at value position was never
2399/// fused into a `GlobWord`/colon-joined `Ident` (see
2400/// `lexer::compute_value_context`), so this choice never needs to "unfuse"
2401/// anything — it just sees primitive bracket/brace tokens.
2402fn value_literal_parser<'tokens, I>(
2403) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2404where
2405    I: ValueInput<'tokens, Token = Token, Span = Span>,
2406{
2407    recursive(|value| {
2408        choice((
2409            list_literal_parser(value.clone()),
2410            record_literal_parser(value.clone()),
2411            primary_expr_parser(),
2412        ))
2413    })
2414    .boxed()
2415}
2416
2417/// List literal: `[a b c]`, `[]`, `[...$xs date]`. Elements may be separated
2418/// by whitespace alone, commas, newlines, or any mix — all optional and
2419/// interchangeable (see docs/LANGUAGE.md, "Construction — list/record
2420/// literals"). Newlines are consumed rather than treated as statement
2421/// terminators, so a multi-line literal does not end the assignment early.
2422/// A bare element nests as ONE item; `...` flattens a list operand's elements
2423/// into this one (spread).
2424fn list_literal_parser<'tokens, I, V>(
2425    value: V,
2426) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2427where
2428    I: ValueInput<'tokens, Token = Token, Span = Span>,
2429    V: Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
2430{
2431    let spread_elem = just(Token::DotDotDot)
2432        .ignore_then(value.clone())
2433        .map(ListElem::Spread);
2434    let item_elem = value.map(ListElem::Item);
2435    let elem = choice((spread_elem, item_elem));
2436
2437    let sep = choice((just(Token::Comma).to(()), just(Token::Newline).to(()))).repeated();
2438
2439    just(Token::LBracket)
2440        .ignore_then(just(Token::Newline).repeated())
2441        .ignore_then(elem.then_ignore(sep).repeated().collect::<Vec<_>>())
2442        .then_ignore(just(Token::RBracket))
2443        .map(Expr::ListLiteral)
2444        .labelled("list literal")
2445}
2446
2447/// Record literal: `{name: amy, role: maintainer}`, `{port:8080}` (the
2448/// colon-fusion exemption in the lexer means both spellings reach here as
2449/// the same three tokens). Keys are a bareword (`Ident`) or a quoted string
2450/// (for anything that isn't a bareword, e.g. `{"content-type": x}`); values
2451/// are the full recursive value grammar, so nested literals work. Entries
2452/// separate the same way list elements do (comma/newline/whitespace, all
2453/// optional) — including multi-line literals with a trailing comma.
2454fn record_literal_parser<'tokens, I, V>(
2455    value: V,
2456) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2457where
2458    I: ValueInput<'tokens, Token = Token, Span = Span>,
2459    V: Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
2460{
2461    let bare_key = select! { Token::Ident(s) => RecordKey::Bare(s) };
2462    // A double-quoted key interpolates like any double-quoted string ({"$k": v}
2463    // resolves $k at eval time — it used to silently create a literal "$k"
2464    // key); a pure-literal result folds back to Quoted so the common case
2465    // carries no eval overhead. Single quotes stay verbatim — the escape hatch
2466    // for a literal `$` in a key.
2467    let double_key = select! { Token::String(s) => s }.try_map(|s, span| {
2468        let parts = parse_interpolated_string(&s)
2469            .map_err(|e| Rich::custom(span, format!("record key: {e}")))?;
2470        Ok(match parts.as_slice() {
2471            [] => RecordKey::Quoted(String::new()),
2472            [StringPart::Literal(lit)] => RecordKey::Quoted(lit.clone()),
2473            _ => RecordKey::Interpolated(parts),
2474        })
2475    });
2476    let single_key = select! { Token::SingleString(s) => RecordKey::Quoted(s) };
2477    let key = choice((double_key, single_key, bare_key)).labelled("record key");
2478
2479    // Guard against the classic unquoted multi-word value mistake
2480    // (`{msg: hello world}`): without this, "world" is consumed by the
2481    // NEXT `entry` attempt as a candidate key (kaish allows a bare
2482    // space — no comma — between entries, so `{a: 1 b: 2}` is legal), which
2483    // then fails at `}` expecting `:` — chumsky's generic message ("found
2484    // '}' expected ':'") without ever naming the actual mistake. Peeked via
2485    // `.rewind()` (consumes nothing — a legitimate following entry, comma
2486    // or not, is still parsed normally by the outer `repeated()`): an
2487    // `Ident` right after this value that ISN'T itself followed by `:` can
2488    // only be a stray unquoted word, since a real next entry always looks
2489    // like `Ident :` (or a quoted key) at this position.
2490    let stray_bareword_after_value = select! { Token::Ident(s) => s }
2491        .then(just(Token::Colon).or_not())
2492        .rewind()
2493        .or_not()
2494        .try_map(|maybe, span| match maybe {
2495            Some((word, None)) => Err(Rich::custom(
2496                span,
2497                format!(
2498                    "record value: unexpected word \"{word}\" after the value — a multi-word \
2499                     value must be quoted, e.g. {{key: \"hello world\"}}"
2500                ),
2501            )),
2502            _ => Ok(()),
2503        });
2504
2505    let entry = key
2506        .then_ignore(just(Token::Colon))
2507        .then(value)
2508        .then_ignore(stray_bareword_after_value)
2509        .map(|(key, value)| RecordEntry { key, value });
2510
2511    let sep = choice((just(Token::Comma).to(()), just(Token::Newline).to(()))).repeated();
2512
2513    just(Token::LBrace)
2514        .ignore_then(just(Token::Newline).repeated())
2515        .ignore_then(entry.then_ignore(sep).repeated().collect::<Vec<_>>())
2516        .then_ignore(just(Token::RBrace))
2517        .map(Expr::RecordLiteral)
2518        .labelled("record literal")
2519}
2520
2521/// Primary expression: literal, variable reference, command substitution, or bare identifier.
2522///
2523/// Uses `recursive` to support nested command substitution like `$(echo $(date))`.
2524fn primary_expr_parser<'tokens, I>(
2525) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2526where
2527    I: ValueInput<'tokens, Token = Token, Span = Span>,
2528{
2529    // Positional parameters: $0-$9, $@, $#, ${#VAR}, $?, $$
2530    let positional = select! {
2531        Token::Positional(n) => Expr::Positional(n),
2532        Token::AllArgs => Expr::AllArgs,
2533        Token::ArgCount => Expr::ArgCount,
2534        Token::VarLength(name) => Expr::VarLength(parse_varpath(&format!("${{{name}}}"))),
2535        Token::LastExitCode => Expr::LastExitCode,
2536        Token::CurrentPid => Expr::CurrentPid,
2537    };
2538
2539    // Arithmetic expression: $((expr)) - preprocessed into Arithmetic token
2540    let arithmetic = select! {
2541        Token::Arithmetic(expr_str) => Expr::Arithmetic(expr_str),
2542    };
2543
2544    // Keywords that can also be used as barewords in argument position
2545    // (e.g., `echo done` should work even though `done` is a keyword)
2546    let keyword_as_bareword = select! {
2547        Token::Done => "done",
2548        Token::Fi => "fi",
2549        Token::Then => "then",
2550        Token::Else => "else",
2551        Token::Elif => "elif",
2552        Token::In => "in",
2553        Token::Do => "do",
2554        Token::Esac => "esac",
2555        // `set` in argument position is the literal word (`echo set`,
2556        // `kaish-output-limit set 1K`); the `set` *builtin* is only matched
2557        // when `Token::Set` leads a statement (see `set_command`), so this
2558        // arm never shadows it.
2559        Token::Set => "set",
2560    }
2561    .map(|s| Expr::Literal(Value::String(s.to_string())));
2562
2563    // Bare words starting with + or - (e.g., date +%s, cat -), and a
2564    // `--`-prefixed word that isn't a valid long flag (`echo ---`,
2565    // `echo --=x`, GH #137).
2566    let plus_minus_bare = select! {
2567        Token::PlusBare(s) => Expr::Literal(Value::String(s)),
2568        Token::MinusBare(s) => Expr::Literal(Value::String(s)),
2569        Token::MinusAlone => Expr::Literal(Value::String("-".to_string())),
2570        Token::DoubleDashBare(s) => Expr::Literal(Value::String(s)),
2571    };
2572
2573    // Glob patterns: merged GlobWord tokens and bare Star/Question
2574    let glob_pattern = select! {
2575        Token::GlobWord(s) => Expr::GlobPattern(s),
2576        Token::Star => Expr::GlobPattern("*".to_string()),
2577        Token::Question => Expr::GlobPattern("?".to_string()),
2578    };
2579
2580    recursive(|expr| {
2581        choice((
2582            positional,
2583            arithmetic,
2584            cmd_subst_parser(expr.clone()),
2585            var_expr_parser(),
2586            interpolated_string_parser(),
2587            literal_parser().map(Expr::Literal),
2588            // Glob patterns before ident (GlobWord is more specific)
2589            glob_pattern,
2590            // Bare identifiers become string literals (shell barewords)
2591            ident_parser().map(|s| Expr::Literal(Value::String(s))),
2592            // Absolute paths become string literals
2593            path_parser().map(|s| Expr::Literal(Value::String(s))),
2594            // Bare words starting with + or - (date +%s, cat -)
2595            // Shell navigation tokens
2596            select! {
2597                // Bare `.` in argument/expression position is the literal
2598                // current-directory path (`find .`, `ls .`, `echo .`). The
2599                // `source` alias is unaffected: `command_parser` consumes a
2600                // *leading* `.` as the command name before args are parsed,
2601                // so only a `.` that follows a command reaches here.
2602                Token::Dot => Expr::Literal(Value::String(".".into())),
2603                Token::DotDot => Expr::Literal(Value::String("..".into())),
2604                // Bare comma in argument position is the literal "," — the
2605                // `cut -d, -f2` / `tr -d ,` delimiter idiom. This is reached
2606                // only by a comma with no adjacent bareword to fold into
2607                // (whitespace on both sides, e.g. `cut -d , -f2`, or a
2608                // neighbor the lexer doesn't fuse across, e.g. `,$VAR`) — a
2609                // comma glued to a bareword (`echo a,b`, `sort -k 2,2n`) is
2610                // already folded into ONE token before the parser runs (see
2611                // `lexer::flush_glob_run`), and a comma inside a
2612                // `[...]`/`{...}` literal or pattern is consumed there
2613                // instead (list/record literals, brace expansion — see
2614                // `docs/LANGUAGE.md`, "Construction").
2615                Token::Comma => Expr::Literal(Value::String(",".into())),
2616                // Bare colon in argument position is the literal ":" — the
2617                // `awk -F: '{print $1}'` / `--field-separator=:` idiom and
2618                // the bash no-op `:` alias. In statement position the colon is
2619                // the no-op command (handled by `command_parser`); here it is
2620                // only reached after a command name has been parsed, so there
2621                // is no ambiguity with the statement form.
2622                Token::Colon => Expr::Literal(Value::String(":".into())),
2623                Token::Tilde => Expr::Literal(Value::String("~".into())),
2624                Token::TildePath(s) => Expr::Literal(Value::String(s)),
2625                Token::RelativePath(s) => Expr::Literal(Value::String(s)),
2626                Token::DotSlashPath(s) => Expr::Literal(Value::String(s)),
2627                // Digit-leading bareword (SHA prefix `019dda1c`, UUIDs).
2628                Token::NumberIdent(s) => Expr::Literal(Value::String(s)),
2629                // Hyphenated/minus-led numeric word (`2024-01-02`, `10-20`,
2630                // `1.5-2`, `cut -f 1-3`, `find -size -1k`) — one contiguous word.
2631                Token::DashNumWord(s) => Expr::Literal(Value::String(s)),
2632                // Leading-`@` bareword (`@scope/pkg`, `@0`, bare `@`).
2633                Token::AtWord(s) => Expr::Literal(Value::String(s)),
2634                // Dot-prefixed bareword (`.gitignore`, `.parent`, `.parent.parent`).
2635                // Distinct from `Token::Dot` (the source alias), which only
2636                // matches a bare `.` and requires whitespace before its file
2637                // argument.
2638                Token::DottedIdent(s) => Expr::Literal(Value::String(s)),
2639                // Job specifier `%1` for wait/kill — flows as the literal
2640                // string "%1"; the builtins interpret the leading `%`.
2641                Token::JobSpec(s) => Expr::Literal(Value::String(s)),
2642            },
2643            plus_minus_bare,
2644            // Keywords can be used as barewords in argument position
2645            keyword_as_bareword,
2646        ))
2647        .labelled("expression")
2648    })
2649    .boxed()
2650}
2651
2652/// Variable reference: `${VAR}`, `${VAR.field}`, `${VAR:-default}`, or `$VAR` (simple form).
2653/// Returns Expr directly to support both VarRef and VarWithDefault.
2654fn var_expr_parser<'tokens, I>(
2655) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2656where
2657    I: ValueInput<'tokens, Token = Token, Span = Span>,
2658{
2659    select! {
2660        Token::VarRef(raw) => parse_var_expr(&raw),
2661        Token::SimpleVarRef(name) => Expr::VarRef(VarPath::simple(name)),
2662    }
2663    .labelled("variable reference")
2664}
2665
2666/// Command substitution: `$(pipeline)` - runs a pipeline and returns its result.
2667///
2668/// Accepts a recursive expression parser to support nested command substitution.
2669fn cmd_subst_parser<'tokens, I, E>(
2670    expr: E,
2671) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2672where
2673    I: ValueInput<'tokens, Token = Token, Span = Span>,
2674    E: Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
2675{
2676    // Argument parser using the recursive expression parser
2677    // Long flag with value: --name=value
2678    let long_flag_with_value = select! {
2679        Token::LongFlag(name) => name,
2680    }
2681    .then_ignore(just(Token::Eq))
2682    .then(expr.clone())
2683    .map(|(key, value)| Arg::Named { key, value });
2684
2685    // Boolean long flag: --name
2686    let long_flag = select! {
2687        Token::LongFlag(name) => Arg::LongFlag(name),
2688    };
2689
2690    // Boolean short flag: -x
2691    let short_flag = select! {
2692        Token::ShortFlag(name) => Arg::ShortFlag(name),
2693    };
2694
2695    // Shell assignment in argv position: name=value (see arg_before_double_dash_parser).
2696    // Keyword keys (`if=`, `in=`, …) are accepted so `$(dd if=x)` parses.
2697    let named = choice((ident_parser(), keyword_word()))
2698        .then_ignore(just(Token::Eq))
2699        .then(expr.clone())
2700        .map(|(key, value)| Arg::WordAssign { key, value });
2701
2702    // Positional argument
2703    let positional = expr.clone().map(Arg::Positional);
2704
2705    let arg = choice((
2706        long_flag_with_value,
2707        long_flag,
2708        short_flag,
2709        named,
2710        positional,
2711    ));
2712
2713    // Command name parser - accepts identifiers and boolean keywords (true/false are builtins)
2714    let command_name = choice((
2715        ident_parser(),
2716        just(Token::True).to("true".to_string()),
2717        just(Token::False).to("false".to_string()),
2718    ));
2719
2720    // Command parser. Trailing redirects (`> file`, `2> file`, `>> file`, …)
2721    // reuse the same `redirect_parser` combinator the top-level
2722    // `command_parser` uses, so `$(cmd > file)` parses like any other command.
2723    // The redirect *target* threads the recursive `expr` handle (not a fresh
2724    // `primary_expr_parser()`) so the target may itself contain `$(...)` while
2725    // avoiding an unbounded parser-construction cycle.
2726    let command = command_name
2727        .then(arg.repeated().collect::<Vec<_>>())
2728        .then(
2729            redirect_parser(expr.clone())
2730                .repeated()
2731                .collect::<Vec<_>>(),
2732        )
2733        .map(|((name, args), redirects)| Command {
2734            name,
2735            args,
2736            redirects,
2737        });
2738
2739    // Pipeline parser
2740    let pipeline = command
2741        .separated_by(just(Token::Pipe))
2742        .at_least(1)
2743        .collect::<Vec<_>>()
2744        .map(|commands| Pipeline {
2745            commands,
2746            background: false,
2747        });
2748
2749    // A single pipeline becomes one statement (`$(echo x)` → one `Stmt::Command`),
2750    // keeping the AST shape uniform with the rest of the parser.
2751    let pipeline_stmt = pipeline.map(pipeline_into_stmt);
2752
2753    // Statement chaining inside `$()`. `&&` and `||` have EQUAL precedence and
2754    // associate left-to-right (POSIX) — the same single left fold as the top
2755    // level (`statement_parser`), NOT `&&`-binds-tighter. This is the full
2756    // statement grammar a command substitution body accepts — pipelines,
2757    // `&&`/`||` chains, and (via the sequence below) `;`/newline separators and
2758    // `#` comments. Control structures (`if`/`for`/`while`/`case`) are
2759    // intentionally out of scope here.
2760    let chained = pipeline_stmt.clone().foldl(
2761        choice((
2762            just(Token::And).to(true), // true = &&
2763            just(Token::Or).to(false), // false = ||
2764        ))
2765        .then(pipeline_stmt.clone())
2766        .repeated(),
2767        |left, (is_and, right): (bool, Stmt)| {
2768            if is_and {
2769                Stmt::AndChain {
2770                    left: Box::new(left),
2771                    right: Box::new(right),
2772                }
2773            } else {
2774                Stmt::OrChain {
2775                    left: Box::new(left),
2776                    right: Box::new(right),
2777                }
2778            }
2779        },
2780    );
2781
2782    // `;` / newline separated sequence of chained statements, with optional
2783    // leading/trailing/interior separators (so multi-line bodies and a trailing
2784    // `;` or comment-induced newline parse cleanly). `#` comments lex to
2785    // newlines, so they are consumed here as ordinary separators.
2786    let separator = choice((just(Token::Newline), just(Token::Semi)));
2787    let body = separator
2788        .clone()
2789        .repeated()
2790        .ignore_then(
2791            chained
2792                .separated_by(separator.clone().repeated().at_least(1))
2793                .allow_trailing()
2794                .collect::<Vec<_>>(),
2795        )
2796        .then_ignore(separator.repeated());
2797
2798    just(Token::CmdSubstStart)
2799        .ignore_then(body)
2800        .then_ignore(just(Token::RParen))
2801        .map(Expr::CommandSubst)
2802        .labelled("command substitution")
2803}
2804
2805/// String parser - handles double-quoted strings (with interpolation) and single-quoted (literal).
2806fn interpolated_string_parser<'tokens, I>(
2807) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2808where
2809    I: ValueInput<'tokens, Token = Token, Span = Span>,
2810{
2811    // Double-quoted string: may contain $VAR or ${VAR} interpolation
2812    let double_quoted = select! {
2813        Token::String(s) => s,
2814    }
2815    .try_map(|s, span| {
2816        // Check if string contains interpolation markers (${} or $NAME) or escaped dollars
2817        if s.contains('$') || s.contains("__KAISH_ESCAPED_DOLLAR__") {
2818            // Parse interpolated parts. A syntax error inside a `$(…)` is loud
2819            // (Rich error at this string's span), not silently demoted to text.
2820            let parts = parse_interpolated_string(&s)
2821                .map_err(|msg| Rich::custom(span, msg))?;
2822            if parts.len() == 1
2823                && let StringPart::Literal(text) = &parts[0] {
2824                    return Ok(Expr::Literal(Value::String(text.clone())));
2825                }
2826            Ok(Expr::Interpolated(parts))
2827        } else {
2828            Ok(Expr::Literal(Value::String(s)))
2829        }
2830    });
2831
2832    // Single-quoted string: literal, no interpolation
2833    let single_quoted = select! {
2834        Token::SingleString(s) => Expr::Literal(Value::String(s)),
2835    };
2836
2837    choice((single_quoted, double_quoted)).labelled("string")
2838}
2839
2840/// Literal value parser (excluding strings, which are handled by interpolated_string_parser).
2841fn literal_parser<'tokens, I>(
2842) -> impl Parser<'tokens, I, Value, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2843where
2844    I: ValueInput<'tokens, Token = Token, Span = Span>,
2845{
2846    choice((
2847        select! {
2848            Token::True => Value::Bool(true),
2849            Token::False => Value::Bool(false),
2850        },
2851        select! {
2852            Token::Int(n) => Value::Int(n),
2853            Token::Float(f) => Value::Float(f),
2854        },
2855    ))
2856    .labelled("literal")
2857    .boxed()
2858}
2859
2860/// Identifier parser.
2861fn ident_parser<'tokens, I>(
2862) -> impl Parser<'tokens, I, String, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2863where
2864    I: ValueInput<'tokens, Token = Token, Span = Span>,
2865{
2866    select! {
2867        Token::Ident(s) => s,
2868    }
2869    .labelled("identifier")
2870}
2871
2872/// Path parser: matches absolute paths like `/tmp/out`, `/etc/hosts`.
2873fn path_parser<'tokens, I>(
2874) -> impl Parser<'tokens, I, String, extra::Err<Rich<'tokens, Token, Span>>> + Clone
2875where
2876    I: ValueInput<'tokens, Token = Token, Span = Span>,
2877{
2878    select! {
2879        Token::Path(s) => s,
2880    }
2881    .labelled("path")
2882}
2883
2884#[cfg(test)]
2885#[allow(clippy::approx_constant)]
2886mod tests {
2887    use super::*;
2888
2889    /// Extract the single `Command` from a one-statement `$(cmd)` body.
2890    fn subst_cmd(expr: &Expr) -> &Command {
2891        match expr {
2892            Expr::CommandSubst(stmts) => match stmts.as_slice() {
2893                [Stmt::Command(cmd)] => cmd,
2894                other => panic!("expected a single command in $(), got {other:?}"),
2895            },
2896            other => panic!("expected command subst, got {other:?}"),
2897        }
2898    }
2899
2900    /// Extract the single `Pipeline` from a one-statement `$(a | b)` body.
2901    fn subst_pipeline(expr: &Expr) -> &Pipeline {
2902        match expr {
2903            Expr::CommandSubst(stmts) => match stmts.as_slice() {
2904                [Stmt::Pipeline(p)] => p,
2905                other => panic!("expected a single pipeline in $(), got {other:?}"),
2906            },
2907            other => panic!("expected command subst, got {other:?}"),
2908        }
2909    }
2910
2911    #[test]
2912    fn parse_empty() {
2913        let result = parse("");
2914        assert!(result.is_ok());
2915        assert_eq!(result.expect("ok").statements.len(), 0);
2916    }
2917
2918    #[test]
2919    fn parse_newlines_only() {
2920        let result = parse("\n\n\n");
2921        assert!(result.is_ok());
2922    }
2923
2924    #[test]
2925    fn parse_simple_command() {
2926        let result = parse("echo");
2927        assert!(result.is_ok());
2928        let program = result.expect("ok");
2929        assert_eq!(program.statements.len(), 1);
2930        assert!(matches!(&program.statements[0], Stmt::Command(_)));
2931    }
2932
2933    #[test]
2934    fn parse_command_with_string_arg() {
2935        let result = parse(r#"echo "hello""#);
2936        assert!(result.is_ok());
2937        let program = result.expect("ok");
2938        match &program.statements[0] {
2939            Stmt::Command(cmd) => assert_eq!(cmd.args.len(), 1),
2940            _ => panic!("expected Command"),
2941        }
2942    }
2943
2944    #[test]
2945    fn parse_assignment() {
2946        let result = parse("X=5");
2947        assert!(result.is_ok());
2948        let program = result.expect("ok");
2949        assert!(matches!(&program.statements[0], Stmt::Assignment(_)));
2950    }
2951
2952    #[test]
2953    fn parse_pipeline() {
2954        let result = parse("a | b | c");
2955        assert!(result.is_ok());
2956        let program = result.expect("ok");
2957        match &program.statements[0] {
2958            Stmt::Pipeline(p) => assert_eq!(p.commands.len(), 3),
2959            _ => panic!("expected Pipeline"),
2960        }
2961    }
2962
2963    #[test]
2964    fn parse_background_job() {
2965        let result = parse("cmd &");
2966        assert!(result.is_ok());
2967        let program = result.expect("ok");
2968        match &program.statements[0] {
2969            Stmt::Pipeline(p) => assert!(p.background),
2970            _ => panic!("expected Pipeline with background"),
2971        }
2972    }
2973
2974    #[test]
2975    fn parse_if_simple() {
2976        let result = parse("if true; then echo; fi");
2977        assert!(result.is_ok());
2978        let program = result.expect("ok");
2979        assert!(matches!(&program.statements[0], Stmt::If(_)));
2980    }
2981
2982    #[test]
2983    fn parse_if_else() {
2984        let result = parse("if true; then echo; else echo; fi");
2985        assert!(result.is_ok());
2986        let program = result.expect("ok");
2987        match &program.statements[0] {
2988            Stmt::If(if_stmt) => assert!(if_stmt.else_branch.is_some()),
2989            _ => panic!("expected If"),
2990        }
2991    }
2992
2993    #[test]
2994    fn parse_elif_simple() {
2995        let result = parse("if true; then echo a; elif false; then echo b; fi");
2996        assert!(result.is_ok(), "parse failed: {:?}", result);
2997        let program = result.expect("ok");
2998        match &program.statements[0] {
2999            Stmt::If(if_stmt) => {
3000                // elif is desugared to nested if in else
3001                assert!(if_stmt.else_branch.is_some());
3002                let else_branch = if_stmt.else_branch.as_ref().unwrap();
3003                assert_eq!(else_branch.len(), 1);
3004                assert!(matches!(&else_branch[0], Stmt::If(_)));
3005            }
3006            _ => panic!("expected If"),
3007        }
3008    }
3009
3010    #[test]
3011    fn parse_elif_with_else() {
3012        let result = parse("if true; then echo a; elif false; then echo b; else echo c; fi");
3013        assert!(result.is_ok(), "parse failed: {:?}", result);
3014        let program = result.expect("ok");
3015        match &program.statements[0] {
3016            Stmt::If(outer_if) => {
3017                // Check nested structure: if -> elif -> else
3018                let else_branch = outer_if.else_branch.as_ref().expect("outer else");
3019                assert_eq!(else_branch.len(), 1);
3020                match &else_branch[0] {
3021                    Stmt::If(inner_if) => {
3022                        // The inner if (from elif) should have the final else
3023                        assert!(inner_if.else_branch.is_some());
3024                    }
3025                    _ => panic!("expected nested If from elif"),
3026                }
3027            }
3028            _ => panic!("expected If"),
3029        }
3030    }
3031
3032    #[test]
3033    fn parse_multiple_elif() {
3034        // Shell-compatible: use [[ ]] for comparisons
3035        let result = parse(
3036            "if [[ ${X} == 1 ]]; then echo one; elif [[ ${X} == 2 ]]; then echo two; elif [[ ${X} == 3 ]]; then echo three; else echo other; fi",
3037        );
3038        assert!(result.is_ok(), "parse failed: {:?}", result);
3039    }
3040
3041    #[test]
3042    fn parse_for_loop() {
3043        let result = parse("for X in items; do echo; done");
3044        assert!(result.is_ok());
3045        let program = result.expect("ok");
3046        assert!(matches!(&program.statements[0], Stmt::For(_)));
3047    }
3048
3049    #[test]
3050    fn parse_brackets_not_array_literal() {
3051        // Array literals are no longer supported, [ is just a regular char
3052        let result = parse("cmd [1");
3053        // This should fail or parse unexpectedly - arrays are removed
3054        // Just verify we don't crash
3055        let _ = result;
3056    }
3057
3058    #[test]
3059    fn parse_named_arg() {
3060        // Bareword key=value parses as WordAssign — the kernel decides per
3061        // command whether to route it to tool_args.named (export/alias) or
3062        // stringify to a positional (every other builtin).
3063        let result = parse("cmd foo=5");
3064        assert!(result.is_ok());
3065        let program = result.expect("ok");
3066        match &program.statements[0] {
3067            Stmt::Command(cmd) => {
3068                assert_eq!(cmd.args.len(), 1);
3069                assert!(matches!(&cmd.args[0], Arg::WordAssign { .. }));
3070            }
3071            _ => panic!("expected Command"),
3072        }
3073    }
3074
3075    #[test]
3076    fn parse_short_flag() {
3077        let result = parse("ls -l");
3078        assert!(result.is_ok());
3079        let program = result.expect("ok");
3080        match &program.statements[0] {
3081            Stmt::Command(cmd) => {
3082                assert_eq!(cmd.name, "ls");
3083                assert_eq!(cmd.args.len(), 1);
3084                match &cmd.args[0] {
3085                    Arg::ShortFlag(name) => assert_eq!(name, "l"),
3086                    _ => panic!("expected ShortFlag"),
3087                }
3088            }
3089            _ => panic!("expected Command"),
3090        }
3091    }
3092
3093    #[test]
3094    fn parse_long_flag() {
3095        let result = parse("git push --force");
3096        assert!(result.is_ok());
3097        let program = result.expect("ok");
3098        match &program.statements[0] {
3099            Stmt::Command(cmd) => {
3100                assert_eq!(cmd.name, "git");
3101                assert_eq!(cmd.args.len(), 2);
3102                match &cmd.args[0] {
3103                    Arg::Positional(Expr::Literal(Value::String(s))) => assert_eq!(s, "push"),
3104                    _ => panic!("expected Positional push"),
3105                }
3106                match &cmd.args[1] {
3107                    Arg::LongFlag(name) => assert_eq!(name, "force"),
3108                    _ => panic!("expected LongFlag"),
3109                }
3110            }
3111            _ => panic!("expected Command"),
3112        }
3113    }
3114
3115    #[test]
3116    fn parse_long_flag_with_value() {
3117        let result = parse(r#"git commit --message="hello""#);
3118        assert!(result.is_ok());
3119        let program = result.expect("ok");
3120        match &program.statements[0] {
3121            Stmt::Command(cmd) => {
3122                assert_eq!(cmd.name, "git");
3123                assert_eq!(cmd.args.len(), 2);
3124                match &cmd.args[1] {
3125                    Arg::Named { key, value } => {
3126                        assert_eq!(key, "message");
3127                        match value {
3128                            Expr::Literal(Value::String(s)) => assert_eq!(s, "hello"),
3129                            _ => panic!("expected String value"),
3130                        }
3131                    }
3132                    _ => panic!("expected Named from --flag=value"),
3133                }
3134            }
3135            _ => panic!("expected Command"),
3136        }
3137    }
3138
3139    #[test]
3140    fn parse_mixed_flags_and_args() {
3141        let result = parse(r#"git commit -m "message" --amend"#);
3142        assert!(result.is_ok());
3143        let program = result.expect("ok");
3144        match &program.statements[0] {
3145            Stmt::Command(cmd) => {
3146                assert_eq!(cmd.name, "git");
3147                assert_eq!(cmd.args.len(), 4);
3148                // commit (positional)
3149                assert!(matches!(&cmd.args[0], Arg::Positional(_)));
3150                // -m (short flag)
3151                match &cmd.args[1] {
3152                    Arg::ShortFlag(name) => assert_eq!(name, "m"),
3153                    _ => panic!("expected ShortFlag -m"),
3154                }
3155                // "message" (positional)
3156                assert!(matches!(&cmd.args[2], Arg::Positional(_)));
3157                // --amend (long flag)
3158                match &cmd.args[3] {
3159                    Arg::LongFlag(name) => assert_eq!(name, "amend"),
3160                    _ => panic!("expected LongFlag --amend"),
3161                }
3162            }
3163            _ => panic!("expected Command"),
3164        }
3165    }
3166
3167    #[test]
3168    fn parse_redirect_stdout() {
3169        let result = parse("cmd > file");
3170        assert!(result.is_ok());
3171        let program = result.expect("ok");
3172        // Commands with redirects stay as Pipeline, not Command
3173        match &program.statements[0] {
3174            Stmt::Pipeline(p) => {
3175                assert_eq!(p.commands.len(), 1);
3176                let cmd = &p.commands[0];
3177                assert_eq!(cmd.redirects.len(), 1);
3178                assert!(matches!(cmd.redirects[0].kind, RedirectKind::StdoutOverwrite));
3179            }
3180            _ => panic!("expected Pipeline"),
3181        }
3182    }
3183
3184    #[test]
3185    fn parse_var_ref() {
3186        let result = parse("echo ${VAR}");
3187        assert!(result.is_ok());
3188        let program = result.expect("ok");
3189        match &program.statements[0] {
3190            Stmt::Command(cmd) => {
3191                assert_eq!(cmd.args.len(), 1);
3192                assert!(matches!(&cmd.args[0], Arg::Positional(Expr::VarRef(_))));
3193            }
3194            _ => panic!("expected Command"),
3195        }
3196    }
3197
3198    #[test]
3199    fn parse_multiple_statements() {
3200        let result = parse("a\nb\nc");
3201        assert!(result.is_ok());
3202        let program = result.expect("ok");
3203        let non_empty: Vec<_> = program.statements.iter().filter(|s| !matches!(s, Stmt::Empty)).collect();
3204        assert_eq!(non_empty.len(), 3);
3205    }
3206
3207    #[test]
3208    fn parse_semicolon_separated() {
3209        let result = parse("a; b; c");
3210        assert!(result.is_ok());
3211        let program = result.expect("ok");
3212        let non_empty: Vec<_> = program.statements.iter().filter(|s| !matches!(s, Stmt::Empty)).collect();
3213        assert_eq!(non_empty.len(), 3);
3214    }
3215
3216    #[test]
3217    fn parse_complex_pipeline() {
3218        let result = parse(r#"cat file | grep pattern="foo" | head count=10"#);
3219        assert!(result.is_ok());
3220        let program = result.expect("ok");
3221        match &program.statements[0] {
3222            Stmt::Pipeline(p) => assert_eq!(p.commands.len(), 3),
3223            _ => panic!("expected Pipeline"),
3224        }
3225    }
3226
3227    #[test]
3228    fn parse_json_as_string_arg() {
3229        // JSON arrays/objects should be passed as string arguments
3230        let result = parse(r#"cmd '[[1, 2], [3, 4]]'"#);
3231        assert!(result.is_ok());
3232    }
3233
3234    #[test]
3235    fn parse_mixed_args() {
3236        let result = parse(r#"cmd pos1 key="val" pos2 num=42"#);
3237        assert!(result.is_ok());
3238        let program = result.expect("ok");
3239        match &program.statements[0] {
3240            Stmt::Command(cmd) => assert_eq!(cmd.args.len(), 4),
3241            _ => panic!("expected Command"),
3242        }
3243    }
3244
3245    #[test]
3246    fn error_unterminated_string() {
3247        let result = parse(r#"echo "hello"#);
3248        assert!(result.is_err());
3249    }
3250
3251    #[test]
3252    fn error_unterminated_var_ref() {
3253        let result = parse("echo ${VAR");
3254        assert!(result.is_err());
3255    }
3256
3257    #[test]
3258    fn error_missing_fi() {
3259        let result = parse("if true; then echo");
3260        assert!(result.is_err());
3261    }
3262
3263    #[test]
3264    fn error_missing_done() {
3265        let result = parse("for X in items; do echo");
3266        assert!(result.is_err());
3267    }
3268
3269    #[test]
3270    fn parse_lvalue_single_index() {
3271        let result = parse("xs[0]=9").unwrap();
3272        match &result.statements[0] {
3273            Stmt::Assignment(a) => {
3274                assert_eq!(a.name(), "xs");
3275                assert_eq!(
3276                    a.path.segments,
3277                    vec![VarSegment::Field("xs".into()), VarSegment::Index(0)]
3278                );
3279                assert!(!a.local);
3280            }
3281            other => panic!("expected assignment, got {:?}", other),
3282        }
3283    }
3284
3285    #[test]
3286    fn parse_lvalue_negative_index() {
3287        let result = parse("xs[-1]=7").unwrap();
3288        match &result.statements[0] {
3289            Stmt::Assignment(a) => assert_eq!(
3290                a.path.segments,
3291                vec![VarSegment::Field("xs".into()), VarSegment::Index(-1)]
3292            ),
3293            other => panic!("expected assignment, got {:?}", other),
3294        }
3295    }
3296
3297    #[test]
3298    fn parse_lvalue_bareword_key() {
3299        let result = parse("user[email]=x").unwrap();
3300        match &result.statements[0] {
3301            Stmt::Assignment(a) => assert_eq!(
3302                a.path.segments,
3303                vec![
3304                    VarSegment::Field("user".into()),
3305                    VarSegment::Key("email".into())
3306                ]
3307            ),
3308            other => panic!("expected assignment, got {:?}", other),
3309        }
3310    }
3311
3312    #[test]
3313    fn parse_lvalue_chained_keys() {
3314        let result = parse("s[web][port]=9000").unwrap();
3315        match &result.statements[0] {
3316            Stmt::Assignment(a) => assert_eq!(
3317                a.path.segments,
3318                vec![
3319                    VarSegment::Field("s".into()),
3320                    VarSegment::Key("web".into()),
3321                    VarSegment::Key("port".into())
3322                ]
3323            ),
3324            other => panic!("expected assignment, got {:?}", other),
3325        }
3326    }
3327
3328    #[test]
3329    fn parse_lvalue_dynamic_key() {
3330        let result = parse("r[$k]=v").unwrap();
3331        match &result.statements[0] {
3332            Stmt::Assignment(a) => assert_eq!(
3333                a.path.segments,
3334                vec![
3335                    VarSegment::Field("r".into()),
3336                    VarSegment::Dynamic("k".into())
3337                ]
3338            ),
3339            other => panic!("expected assignment, got {:?}", other),
3340        }
3341    }
3342
3343    #[test]
3344    fn parse_local_lvalue_spaced() {
3345        let result = parse("local xs[0] = 9").unwrap();
3346        match &result.statements[0] {
3347            Stmt::Assignment(a) => {
3348                assert!(a.local);
3349                assert_eq!(
3350                    a.path.segments,
3351                    vec![VarSegment::Field("xs".into()), VarSegment::Index(0)]
3352                );
3353            }
3354            other => panic!("expected assignment, got {:?}", other),
3355        }
3356    }
3357
3358    #[test]
3359    fn env_prefix_subscripted_target_is_not_captured_as_env_scoped() {
3360        // A subscripted target before a following command (`user[email]=x
3361        // echo hi`) must NOT become `Stmt::EnvScoped` — structured values
3362        // can't cross the process boundary, so env-prefix stays bare-ident
3363        // only. The lexer suppression + `env_prefix_assign` using
3364        // `ident_parser()` (not `lvalue_path_parser()`) means this falls
3365        // through to an ordinary subscripted assignment followed by an
3366        // independent statement — the SAME back-to-back-without-a-terminator
3367        // shape `X=1 Y=2` already has (kaish's `terminator` is
3368        // `.repeated()`, not `.at_least(1)`), not a new hazard.
3369        let result = parse("user={}\nuser[email]=x echo hi").unwrap();
3370        for stmt in &result.statements {
3371            assert!(
3372                !matches!(stmt, Stmt::EnvScoped { .. }),
3373                "a subscripted assignment must never be captured into EnvScoped: {stmt:?}"
3374            );
3375        }
3376        // Sanity: it really did parse as two independent statements.
3377        assert!(matches!(&result.statements[1], Stmt::Assignment(a) if a.name() == "user"));
3378        assert!(matches!(&result.statements[2], Stmt::Command(c) if c.name == "echo"));
3379    }
3380
3381    #[test]
3382    fn parse_nested_cmd_subst() {
3383        // Nested command substitution is supported
3384        let result = parse("X=$(echo $(date))").unwrap();
3385        match &result.statements[0] {
3386            Stmt::Assignment(a) => {
3387                assert_eq!(a.name(), "X");
3388                let outer = subst_cmd(&a.value);
3389                assert_eq!(outer.name, "echo");
3390                // The argument should be another command substitution
3391                match &outer.args[0] {
3392                    Arg::Positional(inner_expr) => {
3393                        assert_eq!(subst_cmd(inner_expr).name, "date");
3394                    }
3395                    other => panic!("expected nested cmd subst arg, got {:?}", other),
3396                }
3397            }
3398            other => panic!("expected assignment, got {:?}", other),
3399        }
3400    }
3401
3402    #[test]
3403    fn parse_deeply_nested_cmd_subst() {
3404        // Three levels deep
3405        let result = parse("X=$(a $(b $(c)))").unwrap();
3406        match &result.statements[0] {
3407            Stmt::Assignment(a) => {
3408                let level1 = subst_cmd(&a.value);
3409                assert_eq!(level1.name, "a");
3410                match &level1.args[0] {
3411                    Arg::Positional(level2_expr) => {
3412                        let level2 = subst_cmd(level2_expr);
3413                        assert_eq!(level2.name, "b");
3414                        match &level2.args[0] {
3415                            Arg::Positional(level3_expr) => {
3416                                assert_eq!(subst_cmd(level3_expr).name, "c");
3417                            }
3418                            other => panic!("expected level3 cmd subst, got {:?}", other),
3419                        }
3420                    }
3421                    other => panic!("expected level2 cmd subst, got {:?}", other),
3422                }
3423            }
3424            other => panic!("expected assignment, got {:?}", other),
3425        }
3426    }
3427
3428    // ═══════════════════════════════════════════════════════════════════════════
3429    // Value Preservation Tests - These test that actual values are captured
3430    // ═══════════════════════════════════════════════════════════════════════════
3431
3432    #[test]
3433    fn value_int_preserved() {
3434        let result = parse("X=42").unwrap();
3435        match &result.statements[0] {
3436            Stmt::Assignment(a) => {
3437                assert_eq!(a.name(), "X");
3438                match &a.value {
3439                    Expr::Literal(Value::Int(n)) => assert_eq!(*n, 42),
3440                    other => panic!("expected int literal, got {:?}", other),
3441                }
3442            }
3443            other => panic!("expected assignment, got {:?}", other),
3444        }
3445    }
3446
3447    #[test]
3448    fn value_negative_int_preserved() {
3449        let result = parse("X=-99").unwrap();
3450        match &result.statements[0] {
3451            Stmt::Assignment(a) => match &a.value {
3452                Expr::Literal(Value::Int(n)) => assert_eq!(*n, -99),
3453                other => panic!("expected int, got {:?}", other),
3454            },
3455            other => panic!("expected assignment, got {:?}", other),
3456        }
3457    }
3458
3459    #[test]
3460    fn value_float_preserved() {
3461        let result = parse("PI=3.14").unwrap();
3462        match &result.statements[0] {
3463            Stmt::Assignment(a) => match &a.value {
3464                Expr::Literal(Value::Float(f)) => assert!((*f - 3.14).abs() < 0.001),
3465                other => panic!("expected float, got {:?}", other),
3466            },
3467            other => panic!("expected assignment, got {:?}", other),
3468        }
3469    }
3470
3471    #[test]
3472    fn value_string_preserved() {
3473        let result = parse(r#"echo "hello world""#).unwrap();
3474        match &result.statements[0] {
3475            Stmt::Command(cmd) => {
3476                assert_eq!(cmd.name, "echo");
3477                match &cmd.args[0] {
3478                    Arg::Positional(Expr::Literal(Value::String(s))) => {
3479                        assert_eq!(s, "hello world");
3480                    }
3481                    other => panic!("expected string arg, got {:?}", other),
3482                }
3483            }
3484            other => panic!("expected command, got {:?}", other),
3485        }
3486    }
3487
3488    #[test]
3489    fn value_string_with_escapes_preserved() {
3490        let result = parse(r#"echo "line1\nline2""#).unwrap();
3491        match &result.statements[0] {
3492            Stmt::Command(cmd) => match &cmd.args[0] {
3493                Arg::Positional(Expr::Literal(Value::String(s))) => {
3494                    assert_eq!(s, "line1\nline2");
3495                }
3496                other => panic!("expected string, got {:?}", other),
3497            },
3498            other => panic!("expected command, got {:?}", other),
3499        }
3500    }
3501
3502    #[test]
3503    fn value_command_name_preserved() {
3504        let result = parse("my-command").unwrap();
3505        match &result.statements[0] {
3506            Stmt::Command(cmd) => assert_eq!(cmd.name, "my-command"),
3507            other => panic!("expected command, got {:?}", other),
3508        }
3509    }
3510
3511    #[test]
3512    fn value_assignment_name_preserved() {
3513        let result = parse("MY_VAR=1").unwrap();
3514        match &result.statements[0] {
3515            Stmt::Assignment(a) => assert_eq!(a.name(), "MY_VAR"),
3516            other => panic!("expected assignment, got {:?}", other),
3517        }
3518    }
3519
3520    #[test]
3521    fn value_for_variable_preserved() {
3522        let result = parse("for ITEM in items; do echo; done").unwrap();
3523        match &result.statements[0] {
3524            Stmt::For(f) => assert_eq!(f.variable, "ITEM"),
3525            other => panic!("expected for, got {:?}", other),
3526        }
3527    }
3528
3529    #[test]
3530    fn value_varref_name_preserved() {
3531        let result = parse("echo ${MESSAGE}").unwrap();
3532        match &result.statements[0] {
3533            Stmt::Command(cmd) => match &cmd.args[0] {
3534                Arg::Positional(Expr::VarRef(path)) => {
3535                    assert_eq!(path.segments.len(), 1);
3536                    let VarSegment::Field(name) = &path.segments[0] else {
3537                        panic!("expected root field, got {:?}", path.segments[0]);
3538                    };
3539                    assert_eq!(name, "MESSAGE");
3540                }
3541                other => panic!("expected varref, got {:?}", other),
3542            },
3543            other => panic!("expected command, got {:?}", other),
3544        }
3545    }
3546
3547    #[test]
3548    fn value_varref_field_access_preserved() {
3549        let result = parse("echo ${RESULT.data}").unwrap();
3550        match &result.statements[0] {
3551            Stmt::Command(cmd) => match &cmd.args[0] {
3552                Arg::Positional(Expr::VarRef(path)) => {
3553                    // A dotted `${RESULT.data}` keeps both as Field — the root
3554                    // and a dotted segment (resolution turns the latter into the
3555                    // brackets-only error).
3556                    assert_eq!(path.segments.len(), 2);
3557                    let VarSegment::Field(a) = &path.segments[0] else {
3558                        panic!("expected field, got {:?}", path.segments[0]);
3559                    };
3560                    let VarSegment::Field(b) = &path.segments[1] else {
3561                        panic!("expected field, got {:?}", path.segments[1]);
3562                    };
3563                    assert_eq!(a, "RESULT");
3564                    assert_eq!(b, "data");
3565                }
3566                other => panic!("expected varref, got {:?}", other),
3567            },
3568            other => panic!("expected command, got {:?}", other),
3569        }
3570    }
3571
3572    #[test]
3573    fn value_varref_index_parsed() {
3574        // Bracket subscripts are now parsed into typed segments (native
3575        // collection access), not filtered out.
3576        let result = parse("echo ${ITEMS[0]}").unwrap();
3577        match &result.statements[0] {
3578            Stmt::Command(cmd) => match &cmd.args[0] {
3579                Arg::Positional(Expr::VarRef(path)) => {
3580                    assert_eq!(path.segments.len(), 2);
3581                    let VarSegment::Field(name) = &path.segments[0] else {
3582                        panic!("expected root field, got {:?}", path.segments[0]);
3583                    };
3584                    assert_eq!(name, "ITEMS");
3585                    assert_eq!(path.segments[1], VarSegment::Index(0));
3586                }
3587                other => panic!("expected varref, got {:?}", other),
3588            },
3589            other => panic!("expected command, got {:?}", other),
3590        }
3591    }
3592
3593    #[test]
3594    fn value_named_arg_preserved() {
3595        // Bareword key=value parses as WordAssign — the kernel decides per
3596        // command whether to route into args.named (export/alias) or
3597        // stringify as a positional.
3598        let result = parse("cmd count=42").unwrap();
3599        match &result.statements[0] {
3600            Stmt::Command(cmd) => {
3601                assert_eq!(cmd.name, "cmd");
3602                match &cmd.args[0] {
3603                    Arg::WordAssign { key, value } => {
3604                        assert_eq!(key, "count");
3605                        match value {
3606                            Expr::Literal(Value::Int(n)) => assert_eq!(*n, 42),
3607                            other => panic!("expected int, got {:?}", other),
3608                        }
3609                    }
3610                    other => panic!("expected WordAssign arg, got {:?}", other),
3611                }
3612            }
3613            other => panic!("expected command, got {:?}", other),
3614        }
3615    }
3616
3617    #[test]
3618    fn value_function_def_name_preserved() {
3619        let result = parse("greet() { echo }").unwrap();
3620        match &result.statements[0] {
3621            Stmt::ToolDef(t) => {
3622                assert_eq!(t.name, "greet");
3623                assert!(t.params.is_empty());
3624            }
3625            other => panic!("expected function def, got {:?}", other),
3626        }
3627    }
3628
3629    // ═══════════════════════════════════════════════════════════════════════════
3630    // New Feature Tests - Comparisons, Interpolation, Nested Structures
3631    // ═══════════════════════════════════════════════════════════════════════════
3632
3633    #[test]
3634    fn parse_comparison_equals() {
3635        // Shell-compatible: use [[ ]] for comparisons
3636        let result = parse("if [[ ${X} == 5 ]]; then echo; fi").unwrap();
3637        match &result.statements[0] {
3638            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3639                Expr::Test(test) => match test.as_ref() {
3640                    TestExpr::Comparison { left, op, right } => {
3641                        assert!(matches!(left.as_ref(), Expr::VarRef(_)));
3642                        assert_eq!(*op, TestCmpOp::Eq);
3643                        match right.as_ref() {
3644                            Expr::Literal(Value::Int(n)) => assert_eq!(*n, 5),
3645                            other => panic!("expected int, got {:?}", other),
3646                        }
3647                    }
3648                    other => panic!("expected comparison, got {:?}", other),
3649                },
3650                other => panic!("expected test expr, got {:?}", other),
3651            },
3652            other => panic!("expected if, got {:?}", other),
3653        }
3654    }
3655
3656    #[test]
3657    fn parse_comparison_not_equals() {
3658        let result = parse("if [[ ${X} != 0 ]]; then echo; fi").unwrap();
3659        match &result.statements[0] {
3660            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3661                Expr::Test(test) => match test.as_ref() {
3662                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::NotEq),
3663                    other => panic!("expected comparison, got {:?}", other),
3664                },
3665                other => panic!("expected test expr, got {:?}", other),
3666            },
3667            other => panic!("expected if, got {:?}", other),
3668        }
3669    }
3670
3671    #[test]
3672    fn parse_comparison_less_than() {
3673        let result = parse("if [[ ${COUNT} -lt 10 ]]; then echo; fi").unwrap();
3674        match &result.statements[0] {
3675            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3676                Expr::Test(test) => match test.as_ref() {
3677                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::NumLt),
3678                    other => panic!("expected comparison, got {:?}", other),
3679                },
3680                other => panic!("expected test expr, got {:?}", other),
3681            },
3682            other => panic!("expected if, got {:?}", other),
3683        }
3684    }
3685
3686    #[test]
3687    fn parse_comparison_greater_than() {
3688        let result = parse("if [[ ${COUNT} -gt 0 ]]; then echo; fi").unwrap();
3689        match &result.statements[0] {
3690            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3691                Expr::Test(test) => match test.as_ref() {
3692                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::NumGt),
3693                    other => panic!("expected comparison, got {:?}", other),
3694                },
3695                other => panic!("expected test expr, got {:?}", other),
3696            },
3697            other => panic!("expected if, got {:?}", other),
3698        }
3699    }
3700
3701    #[test]
3702    fn parse_comparison_less_equal() {
3703        let result = parse("if [[ ${X} -le 100 ]]; then echo; fi").unwrap();
3704        match &result.statements[0] {
3705            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3706                Expr::Test(test) => match test.as_ref() {
3707                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::NumLtEq),
3708                    other => panic!("expected comparison, got {:?}", other),
3709                },
3710                other => panic!("expected test expr, got {:?}", other),
3711            },
3712            other => panic!("expected if, got {:?}", other),
3713        }
3714    }
3715
3716    #[test]
3717    fn parse_comparison_greater_equal() {
3718        let result = parse("if [[ ${X} -ge 1 ]]; then echo; fi").unwrap();
3719        match &result.statements[0] {
3720            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3721                Expr::Test(test) => match test.as_ref() {
3722                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::NumGtEq),
3723                    other => panic!("expected comparison, got {:?}", other),
3724                },
3725                other => panic!("expected test expr, got {:?}", other),
3726            },
3727            other => panic!("expected if, got {:?}", other),
3728        }
3729    }
3730
3731    #[test]
3732    fn parse_regex_match() {
3733        let result = parse(r#"if [[ ${NAME} =~ "^test" ]]; then echo; fi"#).unwrap();
3734        match &result.statements[0] {
3735            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3736                Expr::Test(test) => match test.as_ref() {
3737                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::Match),
3738                    other => panic!("expected comparison, got {:?}", other),
3739                },
3740                other => panic!("expected test expr, got {:?}", other),
3741            },
3742            other => panic!("expected if, got {:?}", other),
3743        }
3744    }
3745
3746    #[test]
3747    fn parse_regex_not_match() {
3748        let result = parse(r#"if [[ ${NAME} !~ "^test" ]]; then echo; fi"#).unwrap();
3749        match &result.statements[0] {
3750            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3751                Expr::Test(test) => match test.as_ref() {
3752                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::NotMatch),
3753                    other => panic!("expected comparison, got {:?}", other),
3754                },
3755                other => panic!("expected test expr, got {:?}", other),
3756            },
3757            other => panic!("expected if, got {:?}", other),
3758        }
3759    }
3760
3761    #[test]
3762    fn parse_string_interpolation() {
3763        let result = parse(r#"echo "Hello ${NAME}!""#).unwrap();
3764        match &result.statements[0] {
3765            Stmt::Command(cmd) => match &cmd.args[0] {
3766                Arg::Positional(Expr::Interpolated(parts)) => {
3767                    assert_eq!(parts.len(), 3);
3768                    match &parts[0] {
3769                        StringPart::Literal(s) => assert_eq!(s, "Hello "),
3770                        other => panic!("expected literal, got {:?}", other),
3771                    }
3772                    match &parts[1] {
3773                        StringPart::Var(path) => {
3774                            assert_eq!(path.segments.len(), 1);
3775                            let VarSegment::Field(name) = &path.segments[0] else {
3776                                panic!("expected root field, got {:?}", path.segments[0]);
3777                            };
3778                            assert_eq!(name, "NAME");
3779                        }
3780                        other => panic!("expected var, got {:?}", other),
3781                    }
3782                    match &parts[2] {
3783                        StringPart::Literal(s) => assert_eq!(s, "!"),
3784                        other => panic!("expected literal, got {:?}", other),
3785                    }
3786                }
3787                other => panic!("expected interpolated, got {:?}", other),
3788            },
3789            other => panic!("expected command, got {:?}", other),
3790        }
3791    }
3792
3793    #[test]
3794    fn parse_string_interpolation_multiple_vars() {
3795        let result = parse(r#"echo "${FIRST} and ${SECOND}""#).unwrap();
3796        match &result.statements[0] {
3797            Stmt::Command(cmd) => match &cmd.args[0] {
3798                Arg::Positional(Expr::Interpolated(parts)) => {
3799                    // ${FIRST} + " and " + ${SECOND} = 3 parts
3800                    assert_eq!(parts.len(), 3);
3801                    assert!(matches!(&parts[0], StringPart::Var(_)));
3802                    assert!(matches!(&parts[1], StringPart::Literal(_)));
3803                    assert!(matches!(&parts[2], StringPart::Var(_)));
3804                }
3805                other => panic!("expected interpolated, got {:?}", other),
3806            },
3807            other => panic!("expected command, got {:?}", other),
3808        }
3809    }
3810
3811    #[test]
3812    fn parse_empty_function_body() {
3813        let result = parse("empty() { }").unwrap();
3814        match &result.statements[0] {
3815            Stmt::ToolDef(t) => {
3816                assert_eq!(t.name, "empty");
3817                assert!(t.params.is_empty());
3818                assert!(t.body.is_empty());
3819            }
3820            other => panic!("expected function def, got {:?}", other),
3821        }
3822    }
3823
3824    #[test]
3825    fn parse_bash_style_function() {
3826        let result = parse("function greet { echo hello }").unwrap();
3827        match &result.statements[0] {
3828            Stmt::ToolDef(t) => {
3829                assert_eq!(t.name, "greet");
3830                assert!(t.params.is_empty());
3831                assert_eq!(t.body.len(), 1);
3832            }
3833            other => panic!("expected function def, got {:?}", other),
3834        }
3835    }
3836
3837    #[test]
3838    fn parse_comparison_string_values() {
3839        let result = parse(r#"if [[ ${STATUS} == "ok" ]]; then echo; fi"#).unwrap();
3840        match &result.statements[0] {
3841            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3842                Expr::Test(test) => match test.as_ref() {
3843                    TestExpr::Comparison { left, op, right } => {
3844                        assert!(matches!(left.as_ref(), Expr::VarRef(_)));
3845                        assert_eq!(*op, TestCmpOp::Eq);
3846                        match right.as_ref() {
3847                            Expr::Literal(Value::String(s)) => assert_eq!(s, "ok"),
3848                            other => panic!("expected string, got {:?}", other),
3849                        }
3850                    }
3851                    other => panic!("expected comparison, got {:?}", other),
3852                },
3853                other => panic!("expected test expr, got {:?}", other),
3854            },
3855            other => panic!("expected if, got {:?}", other),
3856        }
3857    }
3858
3859    // ═══════════════════════════════════════════════════════════════════════════
3860    // Command Substitution Tests
3861    // ═══════════════════════════════════════════════════════════════════════════
3862
3863    #[test]
3864    fn parse_cmd_subst_simple() {
3865        let result = parse("X=$(echo)").unwrap();
3866        match &result.statements[0] {
3867            Stmt::Assignment(a) => {
3868                assert_eq!(a.name(), "X");
3869                assert_eq!(subst_cmd(&a.value).name, "echo");
3870            }
3871            other => panic!("expected assignment, got {:?}", other),
3872        }
3873    }
3874
3875    #[test]
3876    fn parse_cmd_subst_with_args() {
3877        let result = parse(r#"X=$(fetch url="http://example.com")"#).unwrap();
3878        match &result.statements[0] {
3879            Stmt::Assignment(a) => {
3880                let cmd = subst_cmd(&a.value);
3881                assert_eq!(cmd.name, "fetch");
3882                assert_eq!(cmd.args.len(), 1);
3883                match &cmd.args[0] {
3884                    Arg::WordAssign { key, .. } => assert_eq!(key, "url"),
3885                    other => panic!("expected WordAssign arg, got {:?}", other),
3886                }
3887            }
3888            other => panic!("expected assignment, got {:?}", other),
3889        }
3890    }
3891
3892    #[test]
3893    fn parse_cmd_subst_pipeline() {
3894        let result = parse("X=$(cat file | grep pattern)").unwrap();
3895        match &result.statements[0] {
3896            Stmt::Assignment(a) => {
3897                let pipeline = subst_pipeline(&a.value);
3898                assert_eq!(pipeline.commands.len(), 2);
3899                assert_eq!(pipeline.commands[0].name, "cat");
3900                assert_eq!(pipeline.commands[1].name, "grep");
3901            }
3902            other => panic!("expected assignment, got {:?}", other),
3903        }
3904    }
3905
3906    #[test]
3907    fn parse_cmd_subst_with_redirect() {
3908        // Regression: `cmd_subst_parser` used to hardcode `redirects: vec![]`,
3909        // so a redirect inside `$()` was a parse error. A command carrying a
3910        // redirect stays a `Stmt::Pipeline` (`pipeline_into_stmt` only unwraps
3911        // redirect-free commands), so read it back through `subst_pipeline`.
3912        let result = parse("X=$(echo hi > out.txt)").unwrap();
3913        match &result.statements[0] {
3914            Stmt::Assignment(a) => {
3915                let pipeline = subst_pipeline(&a.value);
3916                assert_eq!(pipeline.commands.len(), 1);
3917                let cmd = &pipeline.commands[0];
3918                assert_eq!(cmd.name, "echo");
3919                assert_eq!(cmd.redirects.len(), 1);
3920                assert!(matches!(
3921                    cmd.redirects[0].kind,
3922                    RedirectKind::StdoutOverwrite
3923                ));
3924            }
3925            other => panic!("expected assignment, got {:?}", other),
3926        }
3927    }
3928
3929    #[test]
3930    fn parse_cmd_subst_redirect_target_with_nested_subst() {
3931        // The cycle-break's sharpest case: a `$(...)` in the redirect *target*,
3932        // inside a `$(...)`. This exercises cmd_subst → redirect → (recursive
3933        // expr) → cmd_subst, the path that used to recurse unboundedly during
3934        // parser construction (stack overflow). It must parse; the target is a
3935        // nested `CommandSubst`.
3936        let result = parse("X=$(echo hi > $(echo f))").unwrap();
3937        match &result.statements[0] {
3938            Stmt::Assignment(a) => {
3939                let pipeline = subst_pipeline(&a.value);
3940                assert_eq!(pipeline.commands.len(), 1);
3941                let cmd = &pipeline.commands[0];
3942                assert_eq!(cmd.name, "echo");
3943                assert_eq!(cmd.redirects.len(), 1);
3944                assert!(
3945                    matches!(cmd.redirects[0].target, Expr::CommandSubst(_)),
3946                    "redirect target should be a nested command substitution, got {:?}",
3947                    cmd.redirects[0].target
3948                );
3949            }
3950            other => panic!("expected assignment, got {:?}", other),
3951        }
3952    }
3953
3954    #[test]
3955    fn parse_cmd_subst_chain_with_redirect() {
3956        // A redirect in a chained `$()` body binds to its own command, not to
3957        // the chain: `$(a && b > f)` → AndChain{ left: a, right: (b > f) }, with
3958        // the redirect on `b` only.
3959        let result = parse("X=$(echo a && echo b > out.txt)").unwrap();
3960        let stmts = match &result.statements[0] {
3961            Stmt::Assignment(a) => match &a.value {
3962                Expr::CommandSubst(s) => s,
3963                other => panic!("expected command subst, got {:?}", other),
3964            },
3965            other => panic!("expected assignment, got {:?}", other),
3966        };
3967        match stmts.as_slice() {
3968            [Stmt::AndChain { left, right }] => {
3969                // `echo a` is redirect-free → unwrapped to Stmt::Command.
3970                assert!(
3971                    matches!(**left, Stmt::Command(_)),
3972                    "left of && should be a bare command, got {:?}",
3973                    left
3974                );
3975                // `echo b > out.txt` carries a redirect → stays Stmt::Pipeline.
3976                match &**right {
3977                    Stmt::Pipeline(p) => {
3978                        assert_eq!(p.commands.len(), 1);
3979                        assert_eq!(p.commands[0].name, "echo");
3980                        assert_eq!(p.commands[0].redirects.len(), 1);
3981                    }
3982                    other => panic!("right should be a redirect-bearing pipeline, got {:?}", other),
3983                }
3984            }
3985            other => panic!("expected a single AndChain, got {:?}", other),
3986        }
3987    }
3988
3989    #[test]
3990    fn parse_cmd_subst_in_condition() {
3991        // Shell-compatible: conditions are commands, not command substitutions
3992        let result = parse("if kaish-validate; then echo; fi").unwrap();
3993        match &result.statements[0] {
3994            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
3995                Expr::Command(cmd) => {
3996                    assert_eq!(cmd.name, "kaish-validate");
3997                }
3998                other => panic!("expected command, got {:?}", other),
3999            },
4000            other => panic!("expected if, got {:?}", other),
4001        }
4002    }
4003
4004    // ═══════════════════════════════════════════════════════════════════════════
4005    // Inline env-prefix (`NAME=value command`) Tests
4006    // ═══════════════════════════════════════════════════════════════════════════
4007
4008    #[test]
4009    fn parse_env_prefix_single() {
4010        let result = parse("FOO=bar echo hi").unwrap();
4011        match &result.statements[0] {
4012            Stmt::EnvScoped { assignments, body } => {
4013                assert_eq!(assignments.len(), 1);
4014                assert_eq!(assignments[0].name(), "FOO");
4015                assert!(!assignments[0].local);
4016                match body.as_ref() {
4017                    Stmt::Command(cmd) => assert_eq!(cmd.name, "echo"),
4018                    other => panic!("expected command body, got {other:?}"),
4019                }
4020            }
4021            other => panic!("expected env-scoped, got {other:?}"),
4022        }
4023    }
4024
4025    #[test]
4026    fn parse_env_prefix_multiple() {
4027        let result = parse("A=1 B=2 run").unwrap();
4028        match &result.statements[0] {
4029            Stmt::EnvScoped { assignments, body } => {
4030                assert_eq!(assignments.len(), 2);
4031                assert_eq!(assignments[0].name(), "A");
4032                assert_eq!(assignments[1].name(), "B");
4033                assert!(matches!(body.as_ref(), Stmt::Command(c) if c.name == "run"));
4034            }
4035            other => panic!("expected env-scoped, got {other:?}"),
4036        }
4037    }
4038
4039    #[test]
4040    fn parse_bare_assignment_is_not_env_scoped() {
4041        // No command follows — stays a plain (persistent) assignment.
4042        let result = parse("FOO=bar").unwrap();
4043        assert!(
4044            matches!(&result.statements[0], Stmt::Assignment(a) if a.name() == "FOO"),
4045            "got {:?}",
4046            result.statements[0]
4047        );
4048    }
4049
4050    #[test]
4051    fn parse_assignment_then_and_chain_does_not_over_capture() {
4052        // `FOO=bar && echo` is a (persistent) assignment chained with `&&`, NOT
4053        // an env-prefixed command — the `&&` is not a command for the prefix.
4054        let result = parse("FOO=bar && echo hi").unwrap();
4055        match &result.statements[0] {
4056            Stmt::AndChain { left, right } => {
4057                assert!(matches!(left.as_ref(), Stmt::Assignment(a) if a.name() == "FOO"));
4058                assert!(matches!(right.as_ref(), Stmt::Command(c) if c.name == "echo"));
4059            }
4060            other => panic!("expected and-chain, got {other:?}"),
4061        }
4062    }
4063
4064    #[test]
4065    fn parse_env_prefix_pipeline_body() {
4066        let result = parse("FOO=bar cat | grep x").unwrap();
4067        match &result.statements[0] {
4068            Stmt::EnvScoped { assignments, body } => {
4069                assert_eq!(assignments[0].name(), "FOO");
4070                match body.as_ref() {
4071                    Stmt::Pipeline(p) => assert_eq!(p.commands.len(), 2),
4072                    other => panic!("expected pipeline body, got {other:?}"),
4073                }
4074            }
4075            other => panic!("expected env-scoped, got {other:?}"),
4076        }
4077    }
4078
4079    // ═══════════════════════════════════════════════════════════════════════════
4080    // Argv-splat rejection (adjacent unquoted words)
4081    // ═══════════════════════════════════════════════════════════════════════════
4082
4083    fn parse_err_message(source: &str) -> String {
4084        parse(source)
4085            .expect_err("expected a parse error")
4086            .iter()
4087            .map(|e| e.message.clone())
4088            .collect::<Vec<_>>()
4089            .join(" ")
4090    }
4091
4092    #[test]
4093    fn argv_splat_cmdsubst_glued_to_path_is_rejected() {
4094        // `/tmp/$(echo x).txt` lexes as 3 adjacent tokens; unquoted it would
4095        // silently splat into 3 args. Reject with a quote-it hint.
4096        let msg = parse_err_message("echo /tmp/$(echo x).txt");
4097        assert!(msg.contains("quote"), "expected quote hint, got: {msg}");
4098    }
4099
4100    #[test]
4101    fn argv_splat_var_glued_to_path_is_rejected() {
4102        assert!(parse("echo $dir/out.txt").is_err());
4103    }
4104
4105    #[test]
4106    fn argv_splat_three_way_glue_is_rejected() {
4107        assert!(parse("echo foo$(echo bar)baz").is_err());
4108    }
4109
4110    #[test]
4111    fn argv_splat_quoted_word_is_accepted() {
4112        // The supported idiom: quote the whole interpolated word.
4113        assert!(parse(r#"echo "/tmp/$(echo x).txt""#).is_ok());
4114        assert!(parse(r#"echo "$dir/out.txt""#).is_ok());
4115    }
4116
4117    #[test]
4118    fn argv_single_token_words_are_not_splat() {
4119        // These lex as a single token each — no adjacency, must still parse.
4120        assert!(parse("echo file.txt").is_ok(), "file.txt");
4121        assert!(parse("echo a.b.c").is_ok(), "a.b.c");
4122        assert!(parse("echo v1.2.3").is_ok(), "v1.2.3");
4123    }
4124
4125    #[test]
4126    fn argv_spaced_words_are_not_splat() {
4127        assert!(parse("echo a b c").is_ok());
4128        assert!(parse("echo /tmp/x $(echo y)").is_ok());
4129    }
4130
4131    #[test]
4132    fn parse_cmd_subst_in_command_arg() {
4133        let result = parse("echo $(whoami)").unwrap();
4134        match &result.statements[0] {
4135            Stmt::Command(cmd) => {
4136                assert_eq!(cmd.name, "echo");
4137                match &cmd.args[0] {
4138                    Arg::Positional(expr) => {
4139                        assert_eq!(subst_cmd(expr).name, "whoami");
4140                    }
4141                    other => panic!("expected command subst, got {:?}", other),
4142                }
4143            }
4144            other => panic!("expected command, got {:?}", other),
4145        }
4146    }
4147
4148    // ═══════════════════════════════════════════════════════════════════════════
4149    // Logical Operator Tests (&&, ||)
4150    // ═══════════════════════════════════════════════════════════════════════════
4151
4152    #[test]
4153    fn parse_condition_and() {
4154        // Shell-compatible: commands chained with &&
4155        let result = parse("if check-a && check-b; then echo; fi").unwrap();
4156        match &result.statements[0] {
4157            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
4158                Expr::BinaryOp { left, op, right } => {
4159                    assert_eq!(*op, BinaryOp::And);
4160                    assert!(matches!(left.as_ref(), Expr::Command(_)));
4161                    assert!(matches!(right.as_ref(), Expr::Command(_)));
4162                }
4163                other => panic!("expected binary op, got {:?}", other),
4164            },
4165            other => panic!("expected if, got {:?}", other),
4166        }
4167    }
4168
4169    #[test]
4170    fn parse_condition_or() {
4171        let result = parse("if try-a || try-b; then echo; fi").unwrap();
4172        match &result.statements[0] {
4173            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
4174                Expr::BinaryOp { left, op, right } => {
4175                    assert_eq!(*op, BinaryOp::Or);
4176                    assert!(matches!(left.as_ref(), Expr::Command(_)));
4177                    assert!(matches!(right.as_ref(), Expr::Command(_)));
4178                }
4179                other => panic!("expected binary op, got {:?}", other),
4180            },
4181            other => panic!("expected if, got {:?}", other),
4182        }
4183    }
4184
4185    #[test]
4186    fn parse_condition_and_or_precedence() {
4187        // a && b || c should parse as (a && b) || c
4188        let result = parse("if cmd-a && cmd-b || cmd-c; then echo; fi").unwrap();
4189        match &result.statements[0] {
4190            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
4191                Expr::BinaryOp { left, op, right } => {
4192                    // Top level should be ||
4193                    assert_eq!(*op, BinaryOp::Or);
4194                    // Left side should be && expression
4195                    match left.as_ref() {
4196                        Expr::BinaryOp { op: inner_op, .. } => {
4197                            assert_eq!(*inner_op, BinaryOp::And);
4198                        }
4199                        other => panic!("expected binary op (&&), got {:?}", other),
4200                    }
4201                    // Right side should be command
4202                    assert!(matches!(right.as_ref(), Expr::Command(_)));
4203                }
4204                other => panic!("expected binary op, got {:?}", other),
4205            },
4206            other => panic!("expected if, got {:?}", other),
4207        }
4208    }
4209
4210    #[test]
4211    fn parse_condition_multiple_and() {
4212        let result = parse("if cmd-a && cmd-b && cmd-c; then echo; fi").unwrap();
4213        match &result.statements[0] {
4214            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
4215                Expr::BinaryOp { left, op, .. } => {
4216                    assert_eq!(*op, BinaryOp::And);
4217                    // Left side should also be &&
4218                    match left.as_ref() {
4219                        Expr::BinaryOp { op: inner_op, .. } => {
4220                            assert_eq!(*inner_op, BinaryOp::And);
4221                        }
4222                        other => panic!("expected binary op, got {:?}", other),
4223                    }
4224                }
4225                other => panic!("expected binary op, got {:?}", other),
4226            },
4227            other => panic!("expected if, got {:?}", other),
4228        }
4229    }
4230
4231    #[test]
4232    fn parse_condition_mixed_comparison_and_logical() {
4233        // Shell-compatible: use [[ ]] for comparisons, && to chain them
4234        let result = parse("if [[ ${X} == 5 ]] && [[ ${Y} -gt 0 ]]; then echo; fi").unwrap();
4235        match &result.statements[0] {
4236            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
4237                Expr::BinaryOp { left, op, right } => {
4238                    assert_eq!(*op, BinaryOp::And);
4239                    // Left: [[ ${X} == 5 ]]
4240                    match left.as_ref() {
4241                        Expr::Test(test) => match test.as_ref() {
4242                            TestExpr::Comparison { op: left_op, .. } => {
4243                                assert_eq!(*left_op, TestCmpOp::Eq);
4244                            }
4245                            other => panic!("expected comparison, got {:?}", other),
4246                        },
4247                        other => panic!("expected test, got {:?}", other),
4248                    }
4249                    // Right: [[ ${Y} -gt 0 ]]
4250                    match right.as_ref() {
4251                        Expr::Test(test) => match test.as_ref() {
4252                            TestExpr::Comparison { op: right_op, .. } => {
4253                                assert_eq!(*right_op, TestCmpOp::NumGt);
4254                            }
4255                            other => panic!("expected comparison, got {:?}", other),
4256                        },
4257                        other => panic!("expected test, got {:?}", other),
4258                    }
4259                }
4260                other => panic!("expected binary op, got {:?}", other),
4261            },
4262            other => panic!("expected if, got {:?}", other),
4263        }
4264    }
4265
4266    // ═══════════════════════════════════════════════════════════════════════════
4267    // Integration Tests - Complete Scripts
4268    // ═══════════════════════════════════════════════════════════════════════════
4269
4270    /// Level 1: Linear script using core features
4271    #[test]
4272    fn script_level1_linear() {
4273        let script = r#"
4274NAME="kaish"
4275VERSION=1
4276TIMEOUT=30
4277ITEMS="alpha beta gamma"
4278
4279echo "Starting ${NAME} v${VERSION}"
4280cat "README.md" | grep pattern="install" | head count=5
4281fetch url="https://api.example.com/status" timeout=${TIMEOUT} > "/tmp/status.json"
4282echo "Items: ${ITEMS}"
4283"#;
4284        let result = parse(script).unwrap();
4285        let stmts: Vec<_> = result.statements.iter()
4286            .filter(|s| !matches!(s, Stmt::Empty))
4287            .collect();
4288
4289        assert_eq!(stmts.len(), 8);
4290        assert!(matches!(stmts[0], Stmt::Assignment(_)));  // set NAME
4291        assert!(matches!(stmts[1], Stmt::Assignment(_)));  // set VERSION
4292        assert!(matches!(stmts[2], Stmt::Assignment(_)));  // set TIMEOUT
4293        assert!(matches!(stmts[3], Stmt::Assignment(_)));  // set ITEMS
4294        assert!(matches!(stmts[4], Stmt::Command(_)));     // echo "Starting..."
4295        assert!(matches!(stmts[5], Stmt::Pipeline(_)));    // cat | grep | head
4296        assert!(matches!(stmts[6], Stmt::Pipeline(_)));    // fetch (with redirect - Pipeline since it has redirects)
4297        assert!(matches!(stmts[7], Stmt::Command(_)));     // echo "Items: ${ITEMS}"
4298    }
4299
4300    /// Level 2: Script with conditionals (shell-compatible syntax)
4301    #[test]
4302    fn script_level2_branching() {
4303        let script = r#"
4304RESULT=$(kaish-validate "input.json")
4305
4306if [[ ${RESULT.ok} == true ]]; then
4307    echo "Validation passed"
4308    process "input.json" > "output.json"
4309else
4310    echo "Validation failed: ${RESULT.err}"
4311fi
4312
4313if [[ ${COUNT} -gt 0 ]] && [[ ${COUNT} -le 100 ]]; then
4314    echo "Count in valid range"
4315fi
4316
4317if check-network || check-cache; then
4318    fetch url=${URL}
4319fi
4320"#;
4321        let result = parse(script).unwrap();
4322        let stmts: Vec<_> = result.statements.iter()
4323            .filter(|s| !matches!(s, Stmt::Empty))
4324            .collect();
4325
4326        assert_eq!(stmts.len(), 4);
4327
4328        // First: assignment with command substitution
4329        match stmts[0] {
4330            Stmt::Assignment(a) => {
4331                assert_eq!(a.name(), "RESULT");
4332                assert!(matches!(&a.value, Expr::CommandSubst(_)));
4333            }
4334            other => panic!("expected assignment, got {:?}", other),
4335        }
4336
4337        // Second: if/else
4338        match stmts[1] {
4339            Stmt::If(if_stmt) => {
4340                assert_eq!(if_stmt.then_branch.len(), 2);
4341                assert!(if_stmt.else_branch.is_some());
4342                assert_eq!(if_stmt.else_branch.as_ref().unwrap().len(), 1);
4343            }
4344            other => panic!("expected if, got {:?}", other),
4345        }
4346
4347        // Third: if with && condition
4348        match stmts[2] {
4349            Stmt::If(if_stmt) => {
4350                match if_stmt.condition.as_ref() {
4351                    Expr::BinaryOp { op, .. } => assert_eq!(*op, BinaryOp::And),
4352                    other => panic!("expected && condition, got {:?}", other),
4353                }
4354            }
4355            other => panic!("expected if, got {:?}", other),
4356        }
4357
4358        // Fourth: if with || of commands
4359        match stmts[3] {
4360            Stmt::If(if_stmt) => {
4361                match if_stmt.condition.as_ref() {
4362                    Expr::BinaryOp { op, left, right } => {
4363                        assert_eq!(*op, BinaryOp::Or);
4364                        assert!(matches!(left.as_ref(), Expr::Command(_)));
4365                        assert!(matches!(right.as_ref(), Expr::Command(_)));
4366                    }
4367                    other => panic!("expected || condition, got {:?}", other),
4368                }
4369            }
4370            other => panic!("expected if, got {:?}", other),
4371        }
4372    }
4373
4374    /// Level 3: Script with loops and function definitions
4375    #[test]
4376    fn script_level3_loops_and_functions() {
4377        let script = r#"
4378greet() {
4379    echo "Hello, $1!"
4380}
4381
4382fetch_all() {
4383    for URL in $@; do
4384        fetch url=${URL}
4385    done
4386}
4387
4388USERS="alice bob charlie"
4389
4390for USER in ${USERS}; do
4391    greet ${USER}
4392    if [[ ${USER} == "bob" ]]; then
4393        echo "Found Bob!"
4394    fi
4395done
4396
4397long-running-task &
4398"#;
4399        let result = parse(script).unwrap();
4400        let stmts: Vec<_> = result.statements.iter()
4401            .filter(|s| !matches!(s, Stmt::Empty))
4402            .collect();
4403
4404        assert_eq!(stmts.len(), 5);
4405
4406        // First function def
4407        match stmts[0] {
4408            Stmt::ToolDef(t) => {
4409                assert_eq!(t.name, "greet");
4410                assert!(t.params.is_empty());
4411            }
4412            other => panic!("expected function def, got {:?}", other),
4413        }
4414
4415        // Second function def with nested for loop
4416        match stmts[1] {
4417            Stmt::ToolDef(t) => {
4418                assert_eq!(t.name, "fetch_all");
4419                assert_eq!(t.body.len(), 1);
4420                assert!(matches!(&t.body[0], Stmt::For(_)));
4421            }
4422            other => panic!("expected function def, got {:?}", other),
4423        }
4424
4425        // Assignment
4426        assert!(matches!(stmts[2], Stmt::Assignment(_)));
4427
4428        // For loop with nested if
4429        match stmts[3] {
4430            Stmt::For(f) => {
4431                assert_eq!(f.variable, "USER");
4432                assert_eq!(f.body.len(), 2);
4433                assert!(matches!(&f.body[0], Stmt::Command(_)));
4434                assert!(matches!(&f.body[1], Stmt::If(_)));
4435            }
4436            other => panic!("expected for loop, got {:?}", other),
4437        }
4438
4439        // Background job
4440        match stmts[4] {
4441            Stmt::Pipeline(p) => {
4442                assert!(p.background);
4443                assert_eq!(p.commands[0].name, "long-running-task");
4444            }
4445            other => panic!("expected pipeline (background), got {:?}", other),
4446        }
4447    }
4448
4449    /// Level 4: Complex nested control flow (shell-compatible syntax)
4450    #[test]
4451    fn script_level4_complex_nesting() {
4452        let script = r#"
4453RESULT=$(cat "config.json" | jq query=".servers" | kaish-validate schema="server-schema.json")
4454
4455if ping host=${HOST} && [[ ${RESULT} == true ]]; then
4456    for SERVER in "prod-1 prod-2"; do
4457        deploy target=${SERVER} port=8080
4458        if [[ $? -ne 0 ]]; then
4459            notify channel="ops" message="Deploy failed"
4460        fi
4461    done
4462fi
4463"#;
4464        let result = parse(script).unwrap();
4465        let stmts: Vec<_> = result.statements.iter()
4466            .filter(|s| !matches!(s, Stmt::Empty))
4467            .collect();
4468
4469        assert_eq!(stmts.len(), 2);
4470
4471        // Command substitution with pipeline
4472        match stmts[0] {
4473            Stmt::Assignment(a) => {
4474                assert_eq!(a.name(), "RESULT");
4475                assert_eq!(subst_pipeline(&a.value).commands.len(), 3);
4476            }
4477            other => panic!("expected assignment, got {:?}", other),
4478        }
4479
4480        // If with && condition, containing for loop with nested if
4481        match stmts[1] {
4482            Stmt::If(if_stmt) => {
4483                match if_stmt.condition.as_ref() {
4484                    Expr::BinaryOp { op, .. } => assert_eq!(*op, BinaryOp::And),
4485                    other => panic!("expected && condition, got {:?}", other),
4486                }
4487                assert_eq!(if_stmt.then_branch.len(), 1);
4488                match &if_stmt.then_branch[0] {
4489                    Stmt::For(f) => {
4490                        assert_eq!(f.body.len(), 2);
4491                        assert!(matches!(&f.body[1], Stmt::If(_)));
4492                    }
4493                    other => panic!("expected for in if body, got {:?}", other),
4494                }
4495            }
4496            other => panic!("expected if, got {:?}", other),
4497        }
4498    }
4499
4500    /// Level 5: Edge cases and parser stress test
4501    #[test]
4502    fn script_level5_edge_cases() {
4503        let script = r#"
4504echo ""
4505echo "quotes: \"nested\" here"
4506echo "escapes: \n\t\r\\"
4507echo "unicode: \u2764"
4508
4509X=-99999
4510Y=3.14159265358979
4511Z=-0.001
4512
4513cmd a=1 b="two" c=true d=false e=null
4514
4515if true; then
4516    if false; then
4517        echo "inner"
4518    else
4519        echo "else"
4520    fi
4521fi
4522
4523for I in "a b c"; do
4524    echo ${I}
4525done
4526
4527no_params() {
4528    echo "no params"
4529}
4530
4531function all_args {
4532    echo "args: $@"
4533}
4534
4535a | b | c | d | e &
4536cmd 2> "errors.log"
4537cmd &> "all.log"
4538cmd >> "append.log"
4539cmd < "input.txt"
4540"#;
4541        let result = parse(script).unwrap();
4542        let stmts: Vec<_> = result.statements.iter()
4543            .filter(|s| !matches!(s, Stmt::Empty))
4544            .collect();
4545
4546        // Verify it parses without error
4547        assert!(stmts.len() >= 10, "expected many statements, got {}", stmts.len());
4548
4549        // Background pipeline
4550        let bg_stmt = stmts.iter().find(|s| matches!(s, Stmt::Pipeline(p) if p.background));
4551        assert!(bg_stmt.is_some(), "expected background pipeline");
4552
4553        match bg_stmt.unwrap() {
4554            Stmt::Pipeline(p) => {
4555                assert_eq!(p.commands.len(), 5);
4556                assert!(p.background);
4557            }
4558            _ => unreachable!(),
4559        }
4560    }
4561
4562    // ═══════════════════════════════════════════════════════════════════════════
4563    // Edge Case Tests: Ambiguity Resolution
4564    // ═══════════════════════════════════════════════════════════════════════════
4565
4566    #[test]
4567    fn parse_keyword_as_variable_rejected() {
4568        // Keywords CANNOT be used as variable names - this is intentional
4569        // to avoid ambiguity. Use different names instead.
4570        let result = parse(r#"if="value""#);
4571        assert!(result.is_err(), "if= should fail - 'if' is a keyword");
4572
4573        let result = parse("while=true");
4574        assert!(result.is_err(), "while= should fail - 'while' is a keyword");
4575
4576        let result = parse(r#"then="next""#);
4577        assert!(result.is_err(), "then= should fail - 'then' is a keyword");
4578    }
4579
4580    #[test]
4581    fn parse_set_command_with_flag() {
4582        let result = parse("set -e");
4583        assert!(result.is_ok(), "failed to parse set -e: {:?}", result);
4584        let program = result.unwrap();
4585        match &program.statements[0] {
4586            Stmt::Command(cmd) => {
4587                assert_eq!(cmd.name, "set");
4588                assert_eq!(cmd.args.len(), 1);
4589                match &cmd.args[0] {
4590                    Arg::ShortFlag(f) => assert_eq!(f, "e"),
4591                    other => panic!("expected ShortFlag, got {:?}", other),
4592                }
4593            }
4594            other => panic!("expected Command, got {:?}", other),
4595        }
4596    }
4597
4598    #[test]
4599    fn parse_set_command_no_args() {
4600        let result = parse("set");
4601        assert!(result.is_ok(), "failed to parse set: {:?}", result);
4602        let program = result.unwrap();
4603        match &program.statements[0] {
4604            Stmt::Command(cmd) => {
4605                assert_eq!(cmd.name, "set");
4606                assert_eq!(cmd.args.len(), 0);
4607            }
4608            other => panic!("expected Command, got {:?}", other),
4609        }
4610    }
4611
4612    #[test]
4613    fn parse_set_assignment_vs_command() {
4614        // X=5 should be assignment
4615        let result = parse("X=5");
4616        assert!(result.is_ok());
4617        let program = result.unwrap();
4618        assert!(matches!(&program.statements[0], Stmt::Assignment(_)));
4619
4620        // set -e should be command
4621        let result = parse("set -e");
4622        assert!(result.is_ok());
4623        let program = result.unwrap();
4624        assert!(matches!(&program.statements[0], Stmt::Command(_)));
4625    }
4626
4627    #[test]
4628    fn parse_true_as_command() {
4629        let result = parse("true");
4630        assert!(result.is_ok());
4631        let program = result.unwrap();
4632        match &program.statements[0] {
4633            Stmt::Command(cmd) => assert_eq!(cmd.name, "true"),
4634            other => panic!("expected Command(true), got {:?}", other),
4635        }
4636    }
4637
4638    #[test]
4639    fn parse_false_as_command() {
4640        let result = parse("false");
4641        assert!(result.is_ok());
4642        let program = result.unwrap();
4643        match &program.statements[0] {
4644            Stmt::Command(cmd) => assert_eq!(cmd.name, "false"),
4645            other => panic!("expected Command(false), got {:?}", other),
4646        }
4647    }
4648
4649    #[test]
4650    fn parse_dot_as_source_alias() {
4651        let result = parse(". script.kai");
4652        assert!(result.is_ok(), "failed to parse . script.kai: {:?}", result);
4653        let program = result.unwrap();
4654        match &program.statements[0] {
4655            Stmt::Command(cmd) => {
4656                assert_eq!(cmd.name, ".");
4657                assert_eq!(cmd.args.len(), 1);
4658            }
4659            other => panic!("expected Command(.), got {:?}", other),
4660        }
4661    }
4662
4663    #[test]
4664    fn parse_source_command() {
4665        let result = parse("source utils.kai");
4666        assert!(result.is_ok(), "failed to parse source: {:?}", result);
4667        let program = result.unwrap();
4668        match &program.statements[0] {
4669            Stmt::Command(cmd) => {
4670                assert_eq!(cmd.name, "source");
4671                assert_eq!(cmd.args.len(), 1);
4672            }
4673            other => panic!("expected Command(source), got {:?}", other),
4674        }
4675    }
4676
4677    #[test]
4678    fn parse_test_expr_file_test() {
4679        // Paths must be quoted strings in test expressions
4680        let result = parse(r#"[[ -f "/path/file" ]]"#);
4681        assert!(result.is_ok(), "failed to parse file test: {:?}", result);
4682    }
4683
4684    #[test]
4685    fn parse_test_expr_comparison() {
4686        let result = parse(r#"[[ $X == "value" ]]"#);
4687        assert!(result.is_ok(), "failed to parse comparison test: {:?}", result);
4688    }
4689
4690    #[test]
4691    fn parse_test_expr_single_eq() {
4692        // = and == are equivalent inside [[ ]] (matching bash behavior)
4693        let result = parse(r#"[[ $X = "value" ]]"#);
4694        assert!(result.is_ok(), "failed to parse single-= comparison: {:?}", result);
4695        let program = result.unwrap();
4696        match &program.statements[0] {
4697            Stmt::Test(TestExpr::Comparison { op, .. }) => {
4698                assert_eq!(op, &TestCmpOp::Eq);
4699            }
4700            other => panic!("expected Test(Comparison), got {:?}", other),
4701        }
4702    }
4703
4704    #[test]
4705    fn parse_while_loop() {
4706        let result = parse("while true; do echo; done");
4707        assert!(result.is_ok(), "failed to parse while loop: {:?}", result);
4708        let program = result.unwrap();
4709        assert!(matches!(&program.statements[0], Stmt::While(_)));
4710    }
4711
4712    #[test]
4713    fn parse_break_with_level() {
4714        let result = parse("break 2");
4715        assert!(result.is_ok());
4716        let program = result.unwrap();
4717        match &program.statements[0] {
4718            Stmt::Break(Some(n)) => assert_eq!(*n, 2),
4719            other => panic!("expected Break(2), got {:?}", other),
4720        }
4721    }
4722
4723    #[test]
4724    fn parse_continue_with_level() {
4725        let result = parse("continue 3");
4726        assert!(result.is_ok());
4727        let program = result.unwrap();
4728        match &program.statements[0] {
4729            Stmt::Continue(Some(n)) => assert_eq!(*n, 3),
4730            other => panic!("expected Continue(3), got {:?}", other),
4731        }
4732    }
4733
4734    #[test]
4735    fn parse_exit_with_code() {
4736        let result = parse("exit 1");
4737        assert!(result.is_ok());
4738        let program = result.unwrap();
4739        match &program.statements[0] {
4740            Stmt::Exit(Some(expr)) => {
4741                match expr.as_ref() {
4742                    Expr::Literal(Value::Int(n)) => assert_eq!(*n, 1),
4743                    other => panic!("expected Int(1), got {:?}", other),
4744                }
4745            }
4746            other => panic!("expected Exit(1), got {:?}", other),
4747        }
4748    }
4749
4750    // ========================================================================
4751    // parse_interpolated_string_spanned — body-internal span tracking for
4752    // heredoc bodies. The byte offsets these tests pin become validator
4753    // issue spans via the HereDocBody → SpannedPart flow.
4754    // ========================================================================
4755
4756    #[test]
4757    fn spanned_literal_only_records_byte_range() {
4758        let parts = parse_interpolated_string_spanned("hello world", 100);
4759        assert_eq!(parts.len(), 1);
4760        assert!(matches!(&parts[0].part, StringPart::Literal(s) if s == "hello world"));
4761        assert_eq!(parts[0].offset, 100, "base_offset must propagate to literals");
4762        assert_eq!(parts[0].len, 11);
4763    }
4764
4765    #[test]
4766    fn spanned_braced_var_at_zero() {
4767        let parts = parse_interpolated_string_spanned("${X}", 50);
4768        assert_eq!(parts.len(), 1);
4769        assert!(matches!(&parts[0].part, StringPart::Var(_)));
4770        assert_eq!(parts[0].offset, 50);
4771        assert_eq!(parts[0].len, 4); // "${X}"
4772    }
4773
4774    #[test]
4775    fn spanned_simple_var_then_literal() {
4776        let parts = parse_interpolated_string_spanned("$X end", 10);
4777        assert_eq!(parts.len(), 2);
4778        assert!(matches!(&parts[0].part, StringPart::Var(_)));
4779        assert_eq!(parts[0].offset, 10);
4780        assert_eq!(parts[0].len, 2); // "$X"
4781        assert!(matches!(&parts[1].part, StringPart::Literal(s) if s == " end"));
4782        assert_eq!(parts[1].offset, 12);
4783        assert_eq!(parts[1].len, 4);
4784    }
4785
4786    #[test]
4787    fn spanned_mixed_literal_var_literal() {
4788        let parts = parse_interpolated_string_spanned("hi ${X} bye", 0);
4789        assert_eq!(parts.len(), 3);
4790        // "hi "
4791        assert!(matches!(&parts[0].part, StringPart::Literal(s) if s == "hi "));
4792        assert_eq!(parts[0].offset, 0);
4793        assert_eq!(parts[0].len, 3);
4794        // ${X}
4795        assert!(matches!(&parts[1].part, StringPart::Var(_)));
4796        assert_eq!(parts[1].offset, 3);
4797        assert_eq!(parts[1].len, 4);
4798        // " bye"
4799        assert!(matches!(&parts[2].part, StringPart::Literal(s) if s == " bye"));
4800        assert_eq!(parts[2].offset, 7);
4801        assert_eq!(parts[2].len, 4);
4802    }
4803
4804    #[test]
4805    fn spanned_positional_param() {
4806        let parts = parse_interpolated_string_spanned("$1 done", 0);
4807        assert_eq!(parts.len(), 2);
4808        assert!(matches!(&parts[0].part, StringPart::Positional(1)));
4809        assert_eq!(parts[0].offset, 0);
4810        assert_eq!(parts[0].len, 2); // "$1"
4811    }
4812
4813    #[test]
4814    fn spanned_special_dollar_dollar() {
4815        let parts = parse_interpolated_string_spanned("$$", 5);
4816        assert_eq!(parts.len(), 1);
4817        assert!(matches!(&parts[0].part, StringPart::CurrentPid));
4818        assert_eq!(parts[0].offset, 5);
4819        assert_eq!(parts[0].len, 2);
4820    }
4821
4822    #[test]
4823    fn spanned_arithmetic_marker_recognised() {
4824        // The lexer wraps arithmetic markers as ${__ARITH:expr__} for
4825        // interpolated heredocs; the spanned parser must produce
4826        // StringPart::Arithmetic for that shape.
4827        let parts = parse_interpolated_string_spanned("${__ARITH:1+2__}", 0);
4828        assert_eq!(parts.len(), 1);
4829        assert!(matches!(&parts[0].part, StringPart::Arithmetic(e) if e == "1+2"));
4830    }
4831
4832    #[test]
4833    fn spanned_default_separator_yields_var_with_default() {
4834        let parts = parse_interpolated_string_spanned("${X:-fallback}", 0);
4835        assert_eq!(parts.len(), 1);
4836        assert!(matches!(&parts[0].part, StringPart::VarWithDefault { .. }));
4837        assert_eq!(parts[0].offset, 0);
4838        assert_eq!(parts[0].len, 14); // "${X:-fallback}"
4839    }
4840
4841    #[test]
4842    fn spanned_no_dollar_runs_one_literal() {
4843        let parts = parse_interpolated_string_spanned("plain text only", 7);
4844        assert_eq!(parts.len(), 1);
4845        assert!(matches!(&parts[0].part, StringPart::Literal(s) if s == "plain text only"));
4846        assert_eq!(parts[0].offset, 7);
4847        assert_eq!(parts[0].len, 15);
4848    }
4849
4850    #[test]
4851    fn spanned_matches_unspanned_part_count() {
4852        // Spanned and spanless variants must agree on the part decomposition.
4853        // Bug fixes in one should land in the other.
4854        let cases = [
4855            "hello",
4856            "$X",
4857            "${X}",
4858            "${X:-d}",
4859            "hi $A and $B",
4860            "$0 $1 $2",
4861            "$$ $? $#",
4862        ];
4863        for s in &cases {
4864            let unspanned = parse_interpolated_string(s).expect("test input parses");
4865            let spanned = parse_interpolated_string_spanned(s, 0);
4866            assert_eq!(
4867                unspanned.len(),
4868                spanned.len(),
4869                "part count differs for {:?}",
4870                s
4871            );
4872        }
4873    }
4874
4875    #[test]
4876    fn spanned_multibyte_utf8_before_var_uses_byte_offsets() {
4877        // 🚀 is 4 bytes in UTF-8 and a space is 1 byte, so the literal
4878        // prefix is 5 bytes total. `${X}` then sits at byte offset 5.
4879        // Right-by-luck for char-vs-byte indexing is precisely what this
4880        // test catches: if someone swaps .len_utf8() for 1, offset becomes 2.
4881        let parts = parse_interpolated_string_spanned("🚀 ${X}", 0);
4882        assert_eq!(parts.len(), 2);
4883
4884        assert!(matches!(&parts[0].part, StringPart::Literal(s) if s == "🚀 "));
4885        assert_eq!(parts[0].offset, 0);
4886        assert_eq!(parts[0].len, 5, "literal len must be bytes, not chars");
4887
4888        assert!(matches!(&parts[1].part, StringPart::Var(_)));
4889        assert_eq!(parts[1].offset, 5, "var offset must be bytes, not chars");
4890        assert_eq!(parts[1].len, 4);
4891    }
4892
4893    #[test]
4894    fn spanned_multibyte_utf8_pure_literal_is_byte_length() {
4895        // "hello 世界 world": 5 + 1 + 6 (3 per CJK char) + 1 + 5 = 18 bytes,
4896        // 13 chars. The `len` field must report 18, not 13.
4897        let parts = parse_interpolated_string_spanned("hello 世界 world", 0);
4898        assert_eq!(parts.len(), 1);
4899        assert!(matches!(&parts[0].part, StringPart::Literal(s) if s == "hello 世界 world"));
4900        assert_eq!(parts[0].offset, 0);
4901        assert_eq!(parts[0].len, 18);
4902    }
4903
4904    #[test]
4905    fn spanned_escape_dollar_consumes_two_bytes_emits_one_char() {
4906        // `\$` is 2 source bytes and resolves to a single literal `$`.
4907        // The literal part's `len` should reflect the SOURCE length (2).
4908        let parts = parse_interpolated_string_spanned("\\$", 0);
4909        assert_eq!(parts.len(), 1);
4910        assert!(matches!(&parts[0].part, StringPart::Literal(s) if s == "$"));
4911        assert_eq!(parts[0].offset, 0);
4912        assert_eq!(parts[0].len, 2, "len is source byte length, not rendered length");
4913    }
4914
4915    #[test]
4916    fn spanned_escape_backslash_collapses_pair_to_one() {
4917        let parts = parse_interpolated_string_spanned("\\\\", 0);
4918        assert_eq!(parts.len(), 1);
4919        assert!(matches!(&parts[0].part, StringPart::Literal(s) if s == "\\"));
4920        assert_eq!(parts[0].len, 2);
4921    }
4922
4923    #[test]
4924    fn spanned_standalone_cr_continuation_realigns_span_start() {
4925        // `\` + bare `\r` (old Mac line ending, no trailing `\n`) is a line
4926        // continuation: 2 source bytes, consumed with no output. Pins the
4927        // `current_text_start` update on that branch (parser.rs's `Some('\r')`
4928        // arm in `parse_interpolated_string_spanned`) — if it failed to
4929        // advance past the consumed `\`+`\r`, the following literal run would
4930        // be misreported starting at byte 0 instead of byte 2, corrupting
4931        // every subsequent span in the string (here, the `${x}` var's offset).
4932        let parts = parse_interpolated_string_spanned("\\\rCD${x}", 0);
4933        assert_eq!(parts.len(), 2);
4934        assert!(matches!(&parts[0].part, StringPart::Literal(s) if s == "CD"));
4935        assert_eq!(parts[0].offset, 2, "literal run must start after the consumed \\+CR");
4936        assert_eq!(parts[0].len, 2);
4937        assert!(matches!(&parts[1].part, StringPart::Var(_)));
4938        assert_eq!(parts[1].offset, 4);
4939        assert_eq!(parts[1].len, 4); // "${x}"
4940    }
4941
4942    #[test]
4943    fn spanned_standalone_cr_continuation_mid_run_keeps_span_start() {
4944        // Same continuation, but hit mid-run (current_text already holds
4945        // "AB") — current_text_start must stay anchored to the run's true
4946        // start (0), not jump to the post-continuation position, so "AB"
4947        // and "CD" merge into one literal spanning the whole source run.
4948        let parts = parse_interpolated_string_spanned("AB\\\rCD${x}", 0);
4949        assert_eq!(parts.len(), 2);
4950        assert!(matches!(&parts[0].part, StringPart::Literal(s) if s == "ABCD"));
4951        assert_eq!(parts[0].offset, 0);
4952        assert_eq!(parts[0].len, 6); // "AB" + "\" + "\r" + "CD" = 6 source bytes
4953        assert!(matches!(&parts[1].part, StringPart::Var(_)));
4954        assert_eq!(parts[1].offset, 6);
4955        assert_eq!(parts[1].len, 4); // "${x}"
4956    }
4957
4958    // ── Collection literals ─────────────────────────────────────────────
4959
4960    /// Extract the RHS `Expr` from a one-statement `NAME=value` assignment.
4961    fn assignment_value(source: &str) -> Expr {
4962        let program = parse(source).unwrap_or_else(|e| panic!("parse {source:?}: {e:?}"));
4963        match program.statements.as_slice() {
4964            [Stmt::Assignment(a)] => a.value.clone(),
4965            other => panic!("expected a single assignment, got {other:?}"),
4966        }
4967    }
4968
4969    #[test]
4970    fn list_literal_three_elements() {
4971        let expr = assignment_value("xs=[a b c]");
4972        match expr {
4973            Expr::ListLiteral(elems) => {
4974                assert_eq!(elems.len(), 3);
4975                assert!(elems.iter().all(|e| matches!(e, ListElem::Item(_))));
4976            }
4977            other => panic!("expected ListLiteral, got {other:?}"),
4978        }
4979    }
4980
4981    #[test]
4982    fn list_literal_empty() {
4983        let expr = assignment_value("xs=[]");
4984        assert!(matches!(expr, Expr::ListLiteral(elems) if elems.is_empty()));
4985    }
4986
4987    #[test]
4988    fn list_literal_single_glued_dog() {
4989        // `[dog]` is glued (no spaces) — the value-position glob-merge
4990        // suppression must still hand it to the parser as a one-element list,
4991        // not a fused GlobWord.
4992        let expr = assignment_value("xs=[dog]");
4993        match expr {
4994            Expr::ListLiteral(elems) => assert_eq!(elems.len(), 1),
4995            other => panic!("expected ListLiteral, got {other:?}"),
4996        }
4997    }
4998
4999    #[test]
5000    fn list_literal_single_int() {
5001        let expr = assignment_value("xs=[1]");
5002        match expr {
5003            Expr::ListLiteral(elems) => match elems.as_slice() {
5004                [ListElem::Item(Expr::Literal(Value::Int(1)))] => {}
5005                other => panic!("expected one Int(1) item, got {other:?}"),
5006            },
5007            other => panic!("expected ListLiteral, got {other:?}"),
5008        }
5009    }
5010
5011    #[test]
5012    fn record_literal_unspaced_colon_equals_spaced() {
5013        let spaced = assignment_value("x={port: 8080}");
5014        let unspaced = assignment_value("x={port:8080}");
5015        assert_eq!(spaced, unspaced, "{{port:8080}} must parse identically to {{port: 8080}}");
5016        match spaced {
5017            Expr::RecordLiteral(entries) => match entries.as_slice() {
5018                [RecordEntry { key: RecordKey::Bare(k), value: Expr::Literal(Value::Int(8080)) }] => {
5019                    assert_eq!(k, "port");
5020                }
5021                other => panic!("expected one port:8080 entry, got {other:?}"),
5022            },
5023            other => panic!("expected RecordLiteral, got {other:?}"),
5024        }
5025    }
5026
5027    #[test]
5028    fn record_literal_name_role() {
5029        let expr = assignment_value("u={name: amy, role: maintainer}");
5030        match expr {
5031            Expr::RecordLiteral(entries) => assert_eq!(entries.len(), 2),
5032            other => panic!("expected RecordLiteral, got {other:?}"),
5033        }
5034    }
5035
5036    #[test]
5037    fn record_literal_multiline_trailing_comma() {
5038        let source = "services={\n  web:    {port: 8080, replicas: 3, healthy: true},\n  api:    {port: 9000, replicas: 2, healthy: false},\n}";
5039        let expr = assignment_value(source);
5040        match expr {
5041            Expr::RecordLiteral(entries) => assert_eq!(entries.len(), 2, "web + api entries"),
5042            other => panic!("expected RecordLiteral, got {other:?}"),
5043        }
5044    }
5045
5046    #[test]
5047    fn record_literal_quoted_key() {
5048        let expr = assignment_value(r#"r={"content-type": x}"#);
5049        match expr {
5050            Expr::RecordLiteral(entries) => match entries.as_slice() {
5051                [RecordEntry { key: RecordKey::Quoted(k), .. }] => assert_eq!(k, "content-type"),
5052                other => panic!("expected one quoted-key entry, got {other:?}"),
5053            },
5054            other => panic!("expected RecordLiteral, got {other:?}"),
5055        }
5056    }
5057
5058    #[test]
5059    fn nested_list_and_record_in_record() {
5060        let expr = assignment_value("x={tags: [a b], meta: {active: true}}");
5061        match expr {
5062            Expr::RecordLiteral(entries) => {
5063                assert_eq!(entries.len(), 2);
5064                assert!(matches!(entries[0].value, Expr::ListLiteral(_)));
5065                assert!(matches!(entries[1].value, Expr::RecordLiteral(_)));
5066            }
5067            other => panic!("expected RecordLiteral, got {other:?}"),
5068        }
5069    }
5070
5071    #[test]
5072    fn spread_and_item_elements() {
5073        let expr = assignment_value("new=[...$xs date]");
5074        match expr {
5075            Expr::ListLiteral(elems) => match elems.as_slice() {
5076                [ListElem::Spread(Expr::VarRef(_)), ListElem::Item(Expr::Literal(Value::String(s)))] => {
5077                    assert_eq!(s, "date");
5078                }
5079                other => panic!("expected [Spread($xs), Item(date)], got {other:?}"),
5080            },
5081            other => panic!("expected ListLiteral, got {other:?}"),
5082        }
5083    }
5084
5085    #[test]
5086    fn spread_of_two_variables() {
5087        let expr = assignment_value("c=[...$a ...$b]");
5088        match expr {
5089            Expr::ListLiteral(elems) => {
5090                assert_eq!(elems.len(), 2);
5091                assert!(elems.iter().all(|e| matches!(e, ListElem::Spread(_))));
5092            }
5093            other => panic!("expected ListLiteral, got {other:?}"),
5094        }
5095    }
5096
5097    #[test]
5098    fn in_rhs_accepts_a_list_literal() {
5099        let program = parse("if [[ $a not in [dog] ]]; then echo hit; fi")
5100            .unwrap_or_else(|e| panic!("parse: {e:?}"));
5101        assert_eq!(program.statements.len(), 1);
5102    }
5103
5104    #[test]
5105    fn multiword_bareword_record_value_is_a_parse_error() {
5106        // Strict quoting inside literals: a record value must be exactly one
5107        // word or one quoted string — never silently split or joined.
5108        assert!(parse("x={msg: hello world}").is_err());
5109    }
5110
5111    // ── Invariant guards: argv/for-head globs must be unaffected ────────
5112
5113    #[test]
5114    fn argv_bracket_glob_stays_a_glob_pattern() {
5115        // `ls [dog]` is argv position — the glued `[dog]` run must still fuse
5116        // to a GlobWord (the value-position suppression only applies right
5117        // after `Eq`/a genuine membership `In`, not after a command name).
5118        let program = parse("ls [dog]").unwrap_or_else(|e| panic!("parse: {e:?}"));
5119        assert_eq!(program.statements.len(), 1);
5120    }
5121
5122    #[test]
5123    fn brace_expansion_at_argv_position_is_unaffected() {
5124        // `*.{rs,go}` is glob/brace-expansion argv syntax (the glob-merge run
5125        // needs a wildcard char present to fuse at all — a bare `{a,b}` with
5126        // no `*`/`?`/`[...]` never fuses into a GlobWord, independent of this
5127        // PR). Value-position literal parsing must not leak into argv.
5128        let program = parse("cmd *.{rs,go}").unwrap_or_else(|e| panic!("parse: {e:?}"));
5129        assert_eq!(program.statements.len(), 1);
5130    }
5131
5132    #[test]
5133    fn for_head_item_is_not_a_literal() {
5134        // `for x in [a]` stays argv (a GlobPattern word list), never a
5135        // ListLiteral — collection literals are value-position only.
5136        let program = parse("for x in [a]; do echo $x; done")
5137            .unwrap_or_else(|e| panic!("parse: {e:?}"));
5138        match program.statements.as_slice() {
5139            [Stmt::For(for_loop)] => {
5140                assert_eq!(for_loop.items.len(), 1);
5141                assert!(
5142                    !matches!(for_loop.items[0], Expr::ListLiteral(_)),
5143                    "for-head item must not be a ListLiteral: {:?}",
5144                    for_loop.items[0]
5145                );
5146            }
5147            other => panic!("expected a single For statement, got {other:?}"),
5148        }
5149    }
5150}