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    Pipeline, Program, Redirect, RedirectKind, Stmt, StringPart, StringTestOp, TestCmpOp, TestExpr,
9    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]}`, `${?.ok}` → 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 variable name (between ${ and :-)
38        let name = raw[2..colon_idx].to_string();
39        // Extract default value (between :- and }) and recursively parse it
40        let default_str = &raw[colon_idx + 2..raw.len() - 1];
41        let default = parse_interpolated_string(default_str);
42        return Expr::VarWithDefault { name, default };
43    }
44
45    // Regular variable path
46    Expr::VarRef(parse_varpath(raw))
47}
48
49/// Find the position of :- in a ${VAR:-default} expression, accounting for nested ${...}.
50fn find_default_separator(raw: &str) -> Option<usize> {
51    let bytes = raw.as_bytes();
52    let mut depth = 0;
53    let mut i = 0;
54
55    while i < bytes.len() {
56        if i + 1 < bytes.len() && bytes[i] == b'$' && bytes[i + 1] == b'{' {
57            depth += 1;
58            i += 2;
59            continue;
60        }
61        if bytes[i] == b'}' && depth > 0 {
62            depth -= 1;
63            i += 1;
64            continue;
65        }
66        // Only find :- at the top level (depth == 1 means we're inside the outer ${...})
67        if depth == 1 && i + 1 < bytes.len() && bytes[i] == b':' && bytes[i + 1] == b'-' {
68            return Some(i);
69        }
70        i += 1;
71    }
72    None
73}
74
75/// Find the position of :- in variable content (without outer braces), accounting for nested ${...}.
76fn find_default_separator_in_content(content: &str) -> Option<usize> {
77    let bytes = content.as_bytes();
78    let mut depth = 0;
79    let mut i = 0;
80
81    while i < bytes.len() {
82        if i + 1 < bytes.len() && bytes[i] == b'$' && bytes[i + 1] == b'{' {
83            depth += 1;
84            i += 2;
85            continue;
86        }
87        if bytes[i] == b'}' && depth > 0 {
88            depth -= 1;
89            i += 1;
90            continue;
91        }
92        // Find :- at the top level (depth == 0)
93        if depth == 0 && i + 1 < bytes.len() && bytes[i] == b':' && bytes[i + 1] == b'-' {
94            return Some(i);
95        }
96        i += 1;
97    }
98    None
99}
100
101/// Parse a raw `${...}` string into a VarPath.
102///
103/// Handles paths like `${VAR}`, `${?.ok}`. Array indexing is not supported.
104fn parse_varpath(raw: &str) -> VarPath {
105    let segments_strs = lexer::parse_var_ref(raw).unwrap_or_default();
106    let segments = segments_strs
107        .into_iter()
108        .filter(|s| !s.starts_with('['))  // Skip index segments
109        .map(VarSegment::Field)
110        .collect();
111    VarPath { segments }
112}
113
114/// Parse an interpolated string like "Hello ${NAME}!" or "Hello $NAME!" into parts.
115/// Extract a pipeline from a statement if possible.
116fn stmt_to_pipeline(stmt: Stmt) -> Option<Pipeline> {
117    match stmt {
118        Stmt::Pipeline(p) => Some(p),
119        Stmt::Command(cmd) => Some(Pipeline {
120            commands: vec![cmd],
121            background: false,
122        }),
123        _ => None,
124    }
125}
126
127fn parse_interpolated_string(s: &str) -> Vec<StringPart> {
128    // First, replace escaped dollar markers with a temporary placeholder
129    // The lexer uses __KAISH_ESCAPED_DOLLAR__ for \$ to prevent re-interpretation
130    let s = s.replace("__KAISH_ESCAPED_DOLLAR__", "\x00DOLLAR\x00");
131
132    let mut parts = Vec::new();
133    let mut current_text = String::new();
134    let mut chars = s.chars().peekable();
135
136    while let Some(ch) = chars.next() {
137        if ch == '\x00' {
138            // This is our escaped dollar marker - skip "DOLLAR" and the closing \x00
139            let mut marker = String::new();
140            while let Some(&c) = chars.peek() {
141                if c == '\x00' {
142                    chars.next(); // consume closing marker
143                    break;
144                }
145                if let Some(c) = chars.next() {
146                    marker.push(c);
147                }
148            }
149            if marker == "DOLLAR" {
150                current_text.push('$');
151            }
152        } else if ch == '$' {
153            // Check for command substitution $(...)
154            if chars.peek() == Some(&'(') {
155                // Command substitution $(...)
156                if !current_text.is_empty() {
157                    parts.push(StringPart::Literal(std::mem::take(&mut current_text)));
158                }
159
160                // Consume the '('
161                chars.next();
162
163                // Collect until matching ')' accounting for nested parens
164                let mut cmd_content = String::new();
165                let mut paren_depth = 1;
166                for c in chars.by_ref() {
167                    if c == '(' {
168                        paren_depth += 1;
169                        cmd_content.push(c);
170                    } else if c == ')' {
171                        paren_depth -= 1;
172                        if paren_depth == 0 {
173                            break;
174                        }
175                        cmd_content.push(c);
176                    } else {
177                        cmd_content.push(c);
178                    }
179                }
180
181                // Parse the command content as a pipeline
182                // We need to use the main parser for this
183                if let Ok(program) = parse(&cmd_content) {
184                    // Extract the pipeline from the parsed result
185                    if let Some(stmt) = program.statements.first() {
186                        if let Some(pipeline) = stmt_to_pipeline(stmt.clone()) {
187                            parts.push(StringPart::CommandSubst(pipeline));
188                        } else {
189                            // If we can't extract a pipeline, treat as literal
190                            current_text.push_str("$(");
191                            current_text.push_str(&cmd_content);
192                            current_text.push(')');
193                        }
194                    }
195                } else {
196                    // Parse failed - treat as literal
197                    current_text.push_str("$(");
198                    current_text.push_str(&cmd_content);
199                    current_text.push(')');
200                }
201            } else if chars.peek() == Some(&'{') {
202                // Braced variable reference ${...}
203                if !current_text.is_empty() {
204                    parts.push(StringPart::Literal(std::mem::take(&mut current_text)));
205                }
206
207                // Consume the '{'
208                chars.next();
209
210                // Collect until matching '}', tracking nesting depth
211                let mut var_content = String::new();
212                let mut depth = 1;
213                for c in chars.by_ref() {
214                    if c == '{' && var_content.ends_with('$') {
215                        depth += 1;
216                        var_content.push(c);
217                    } else if c == '}' {
218                        depth -= 1;
219                        if depth == 0 {
220                            break;
221                        }
222                        var_content.push(c);
223                    } else {
224                        var_content.push(c);
225                    }
226                }
227
228                // Parse the content for special syntax
229                let part = if let Some(name) = var_content.strip_prefix('#') {
230                    // Variable length: ${#VAR}
231                    StringPart::VarLength(name.to_string())
232                } else if var_content.starts_with("__ARITH:") && var_content.ends_with("__") {
233                    // Arithmetic expression: ${__ARITH:expr__}
234                    let expr = var_content
235                        .strip_prefix("__ARITH:")
236                        .and_then(|s| s.strip_suffix("__"))
237                        .unwrap_or("");
238                    StringPart::Arithmetic(expr.to_string())
239                } else if let Some(colon_idx) = find_default_separator_in_content(&var_content) {
240                    // Variable with default: ${VAR:-default} - recursively parse the default
241                    let name = var_content[..colon_idx].to_string();
242                    let default_str = &var_content[colon_idx + 2..];
243                    let default = parse_interpolated_string(default_str);
244                    StringPart::VarWithDefault { name, default }
245                } else {
246                    // Regular variable: ${VAR} or ${VAR.field}
247                    StringPart::Var(parse_varpath(&format!("${{{}}}", var_content)))
248                };
249                parts.push(part);
250            } else if chars.peek().map(|c| c.is_ascii_digit()).unwrap_or(false) {
251                // Positional parameter $0-$9
252                if !current_text.is_empty() {
253                    parts.push(StringPart::Literal(std::mem::take(&mut current_text)));
254                }
255                if let Some(digit) = chars.next() {
256                    let n = digit.to_digit(10).unwrap_or(0) as usize;
257                    parts.push(StringPart::Positional(n));
258                }
259            } else if chars.peek() == Some(&'@') {
260                // All arguments $@
261                if !current_text.is_empty() {
262                    parts.push(StringPart::Literal(std::mem::take(&mut current_text)));
263                }
264                chars.next(); // consume '@'
265                parts.push(StringPart::AllArgs);
266            } else if chars.peek() == Some(&'#') {
267                // Argument count $#
268                if !current_text.is_empty() {
269                    parts.push(StringPart::Literal(std::mem::take(&mut current_text)));
270                }
271                chars.next(); // consume '#'
272                parts.push(StringPart::ArgCount);
273            } else if chars.peek() == Some(&'?') {
274                // Last exit code $?
275                if !current_text.is_empty() {
276                    parts.push(StringPart::Literal(std::mem::take(&mut current_text)));
277                }
278                chars.next(); // consume '?'
279                parts.push(StringPart::LastExitCode);
280            } else if chars.peek() == Some(&'$') {
281                // Current PID $$
282                if !current_text.is_empty() {
283                    parts.push(StringPart::Literal(std::mem::take(&mut current_text)));
284                }
285                chars.next(); // consume second '$'
286                parts.push(StringPart::CurrentPid);
287            } else if chars.peek().map(|c| c.is_ascii_alphabetic() || *c == '_').unwrap_or(false) {
288                // Simple variable reference $NAME
289                if !current_text.is_empty() {
290                    parts.push(StringPart::Literal(std::mem::take(&mut current_text)));
291                }
292
293                // Collect identifier characters
294                let mut var_name = String::new();
295                while let Some(&c) = chars.peek() {
296                    if c.is_ascii_alphanumeric() || c == '_' {
297                        if let Some(c) = chars.next() {
298                            var_name.push(c);
299                        }
300                    } else {
301                        break;
302                    }
303                }
304
305                parts.push(StringPart::Var(VarPath::simple(var_name)));
306            } else {
307                // Literal $ (not followed by { or identifier start)
308                current_text.push(ch);
309            }
310        } else {
311            current_text.push(ch);
312        }
313    }
314
315    if !current_text.is_empty() {
316        parts.push(StringPart::Literal(current_text));
317    }
318
319    parts
320}
321
322/// Parse error with location and context.
323#[derive(Debug, Clone)]
324pub struct ParseError {
325    pub span: Span,
326    pub message: String,
327}
328
329impl std::fmt::Display for ParseError {
330    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
331        write!(f, "{} at {:?}", self.message, self.span)
332    }
333}
334
335impl std::error::Error for ParseError {}
336
337/// Parse kaish source code into a Program AST.
338pub fn parse(source: &str) -> Result<Program, Vec<ParseError>> {
339    // Tokenize with logos
340    let tokens = lexer::tokenize(source).map_err(|errs| {
341        errs.into_iter()
342            .map(|e| ParseError {
343                span: (e.span.start..e.span.end).into(),
344                message: format!("lexer error: {}", e.token),
345            })
346            .collect::<Vec<_>>()
347    })?;
348
349    // Convert tokens to (Token, SimpleSpan) pairs
350    let tokens: Vec<(Token, Span)> = tokens
351        .into_iter()
352        .map(|spanned| (spanned.token, (spanned.span.start..spanned.span.end).into()))
353        .collect();
354
355    // End-of-input span
356    let end_span: Span = (source.len()..source.len()).into();
357
358    // Parse using slice-based input (like nano_rust example)
359    let parser = program_parser();
360    let result = parser.parse(tokens.as_slice().map(end_span, |(t, s)| (t, s)));
361
362    result.into_result().map_err(|errs| {
363        errs.into_iter()
364            .map(|e| ParseError {
365                span: *e.span(),
366                message: e.to_string(),
367            })
368            .collect()
369    })
370}
371
372/// Parse a single statement (useful for REPL).
373pub fn parse_statement(source: &str) -> Result<Stmt, Vec<ParseError>> {
374    let program = parse(source)?;
375    program
376        .statements
377        .into_iter()
378        .find(|s| !matches!(s, Stmt::Empty))
379        .ok_or_else(|| {
380            vec![ParseError {
381                span: (0..source.len()).into(),
382                message: "empty input".to_string(),
383            }]
384        })
385}
386
387// ═══════════════════════════════════════════════════════════════════════════
388// Parser Combinators - generic over input type
389// ═══════════════════════════════════════════════════════════════════════════
390
391/// Top-level program parser.
392fn program_parser<'tokens, 'src: 'tokens, I>(
393) -> impl Parser<'tokens, I, Program, extra::Err<Rich<'tokens, Token, Span>>>
394where
395    I: ValueInput<'tokens, Token = Token, Span = Span>,
396{
397    statement_parser()
398        .repeated()
399        .collect::<Vec<_>>()
400        .map(|statements| Program { statements })
401}
402
403/// Statement parser - dispatches based on leading token.
404/// Supports statement-level chaining with && and ||.
405fn statement_parser<'tokens, I>(
406) -> impl Parser<'tokens, I, Stmt, extra::Err<Rich<'tokens, Token, Span>>> + Clone
407where
408    I: ValueInput<'tokens, Token = Token, Span = Span>,
409{
410    recursive(|stmt| {
411        let terminator = choice((just(Token::Newline), just(Token::Semi))).repeated();
412
413        // break [N] - break out of N levels of loops (default 1)
414        let break_stmt = just(Token::Break)
415            .ignore_then(
416                select! { Token::Int(n) => n as usize }.or_not()
417            )
418            .map(Stmt::Break);
419
420        // continue [N] - continue to next iteration, skipping N levels (default 1)
421        let continue_stmt = just(Token::Continue)
422            .ignore_then(
423                select! { Token::Int(n) => n as usize }.or_not()
424            )
425            .map(Stmt::Continue);
426
427        // return [expr] - return from a tool
428        let return_stmt = just(Token::Return)
429            .ignore_then(primary_expr_parser().or_not())
430            .map(|e| Stmt::Return(e.map(Box::new)));
431
432        // exit [code] - exit the script
433        let exit_stmt = just(Token::Exit)
434            .ignore_then(primary_expr_parser().or_not())
435            .map(|e| Stmt::Exit(e.map(Box::new)));
436
437        // set command: `set -e`, `set +e`, `set` (no args), `set -o pipefail`
438        // This must come BEFORE assignment_parser to handle `set -e` vs `X=value`
439        //
440        // Strategy: Use lookahead to check what follows `set`:
441        // - If followed by a flag (-e, --long, +e): parse as set command
442        // - If followed by identifier NOT followed by =: parse as set command (e.g., `set pipefail`)
443        // - If followed by nothing (end/newline/semi): parse as set command
444        // - If followed by identifier then =: let assignment_parser handle it
445        let set_flag_arg = choice((
446            select! { Token::ShortFlag(f) => Arg::ShortFlag(f) },
447            select! { Token::LongFlag(f) => Arg::LongFlag(f) },
448            // PlusFlag for +e, +x etc. - convert to positional arg with + prefix
449            select! { Token::PlusFlag(f) => Arg::Positional(Expr::Literal(Value::String(format!("+{}", f)))) },
450        ));
451
452        // set with flags: `set -e`, `set -e -u -o pipefail`
453        let set_with_flags = just(Token::Set)
454            .then(set_flag_arg)
455            .then(
456                choice((
457                    set_flag_arg,
458                    // Identifiers like 'pipefail' after -o
459                    ident_parser().map(|name| Arg::Positional(Expr::Literal(Value::String(name)))),
460                ))
461                .repeated()
462                .collect::<Vec<_>>(),
463            )
464            .map(|((_, first_arg), mut rest_args)| {
465                let mut args = vec![first_arg];
466                args.append(&mut rest_args);
467                Stmt::Command(Command {
468                    name: "set".to_string(),
469                    args,
470                    redirects: vec![],
471                })
472            });
473
474        // set with no args: `set` alone (shows settings)
475        // Must be followed by newline, semicolon, end of input, or a chaining operator (&&, ||)
476        let set_no_args = just(Token::Set)
477            .then(
478                choice((
479                    just(Token::Newline).to(()),
480                    just(Token::Semi).to(()),
481                    just(Token::And).to(()),
482                    just(Token::Or).to(()),
483                    end(),
484                ))
485                .rewind(),
486            )
487            .map(|_| Stmt::Command(Command {
488                name: "set".to_string(),
489                args: vec![],
490                redirects: vec![],
491            }));
492
493        // Try set_with_flags first (requires at least one flag)
494        // Then try set_no_args (no args, followed by terminator)
495        // If neither matches, fall through to assignment_parser
496        let set_command = set_with_flags.or(set_no_args);
497
498        // Base statement (without chaining)
499        let base_statement = choice((
500            just(Token::Newline).to(Stmt::Empty),
501            set_command,
502            assignment_parser().map(Stmt::Assignment),
503            // Shell-style functions (use $1, $2 positional params)
504            posix_function_parser(stmt.clone()).map(Stmt::ToolDef),  // name() { }
505            bash_function_parser(stmt.clone()).map(Stmt::ToolDef),   // function name { }
506            if_parser(stmt.clone()).map(Stmt::If),
507            for_parser(stmt.clone()).map(Stmt::For),
508            while_parser(stmt.clone()).map(Stmt::While),
509            case_parser(stmt.clone()).map(Stmt::Case),
510            break_stmt,
511            continue_stmt,
512            return_stmt,
513            exit_stmt,
514            test_expr_stmt_parser().map(Stmt::Test),
515            // Note: 'true' and 'false' are handled by command_parser/pipeline_parser
516            pipeline_parser().map(|p| {
517                // Unwrap single-command pipelines without background and without redirects
518                if p.commands.len() == 1 && !p.background {
519                    // Only unwrap if no redirects - redirects require pipeline processing
520                    if p.commands[0].redirects.is_empty() {
521                        // Safe: we just checked len == 1
522                        match p.commands.into_iter().next() {
523                            Some(cmd) => Stmt::Command(cmd),
524                            None => Stmt::Empty, // unreachable but safe
525                        }
526                    } else {
527                        Stmt::Pipeline(p)
528                    }
529                } else {
530                    Stmt::Pipeline(p)
531                }
532            }),
533        ))
534        .boxed();
535
536        // Statement chaining with precedence: && binds tighter than ||
537        // and_chain = base_stmt { "&&" base_stmt }
538        // or_chain  = and_chain { "||" and_chain }
539        let and_chain = base_statement
540            .clone()
541            .foldl(
542                just(Token::And).ignore_then(base_statement).repeated(),
543                |left, right| Stmt::AndChain {
544                    left: Box::new(left),
545                    right: Box::new(right),
546                },
547            );
548
549        and_chain
550            .clone()
551            .foldl(
552                just(Token::Or).ignore_then(and_chain).repeated(),
553                |left, right| Stmt::OrChain {
554                    left: Box::new(left),
555                    right: Box::new(right),
556                },
557            )
558            .then_ignore(terminator)
559    })
560}
561
562/// Assignment: `NAME=value` (bash-style) or `local NAME = value` (scoped)
563fn assignment_parser<'tokens, I>(
564) -> impl Parser<'tokens, I, Assignment, extra::Err<Rich<'tokens, Token, Span>>> + Clone
565where
566    I: ValueInput<'tokens, Token = Token, Span = Span>,
567{
568    // local NAME = value (with spaces around =)
569    let local_assignment = just(Token::Local)
570        .ignore_then(ident_parser())
571        .then_ignore(just(Token::Eq))
572        .then(expr_parser())
573        .map(|(name, value)| Assignment {
574            name,
575            value,
576            local: true,
577        });
578
579    // Bash-style: NAME=value (no spaces around =)
580    // The lexer produces IDENT EQ EXPR, so we parse it here
581    let bash_assignment = ident_parser()
582        .then_ignore(just(Token::Eq))
583        .then(expr_parser())
584        .map(|(name, value)| Assignment {
585            name,
586            value,
587            local: false,
588        });
589
590    choice((local_assignment, bash_assignment))
591        .labelled("assignment")
592        .boxed()
593}
594
595/// POSIX-style function: `name() { body }`
596///
597/// Produces a ToolDef with empty params - uses positional params ($1, $2, etc.)
598fn posix_function_parser<'tokens, I, S>(
599    stmt: S,
600) -> impl Parser<'tokens, I, ToolDef, extra::Err<Rich<'tokens, Token, Span>>> + Clone
601where
602    I: ValueInput<'tokens, Token = Token, Span = Span>,
603    S: Parser<'tokens, I, Stmt, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
604{
605    ident_parser()
606        .then_ignore(just(Token::LParen))
607        .then_ignore(just(Token::RParen))
608        .then_ignore(just(Token::LBrace))
609        .then_ignore(just(Token::Newline).repeated())
610        .then(
611            stmt.repeated()
612                .collect::<Vec<_>>()
613                .map(|stmts| stmts.into_iter().filter(|s| !matches!(s, Stmt::Empty)).collect()),
614        )
615        .then_ignore(just(Token::Newline).repeated())
616        .then_ignore(just(Token::RBrace))
617        .map(|(name, body)| ToolDef { name, params: vec![], body })
618        .labelled("POSIX function")
619        .boxed()
620}
621
622/// Bash-style function: `function name { body }` (without parens)
623///
624/// Produces a ToolDef with empty params - uses positional params ($1, $2, etc.)
625fn bash_function_parser<'tokens, I, S>(
626    stmt: S,
627) -> impl Parser<'tokens, I, ToolDef, extra::Err<Rich<'tokens, Token, Span>>> + Clone
628where
629    I: ValueInput<'tokens, Token = Token, Span = Span>,
630    S: Parser<'tokens, I, Stmt, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
631{
632    just(Token::Function)
633        .ignore_then(ident_parser())
634        .then_ignore(just(Token::LBrace))
635        .then_ignore(just(Token::Newline).repeated())
636        .then(
637            stmt.repeated()
638                .collect::<Vec<_>>()
639                .map(|stmts| stmts.into_iter().filter(|s| !matches!(s, Stmt::Empty)).collect()),
640        )
641        .then_ignore(just(Token::Newline).repeated())
642        .then_ignore(just(Token::RBrace))
643        .map(|(name, body)| ToolDef { name, params: vec![], body })
644        .labelled("bash function")
645        .boxed()
646}
647
648/// If statement: `if COND; then STMTS [elif COND; then STMTS]* [else STMTS] fi`
649///
650/// elif clauses are desugared to nested if/else:
651///   `if A; then X elif B; then Y else Z fi`
652/// becomes:
653///   `if A; then X else { if B; then Y else Z fi } fi`
654fn if_parser<'tokens, I, S>(
655    stmt: S,
656) -> impl Parser<'tokens, I, IfStmt, extra::Err<Rich<'tokens, Token, Span>>> + Clone
657where
658    I: ValueInput<'tokens, Token = Token, Span = Span>,
659    S: Parser<'tokens, I, Stmt, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
660{
661    // Parse a single branch: condition + then statements
662    let branch = condition_parser()
663        .then_ignore(just(Token::Semi).or_not())
664        .then_ignore(just(Token::Newline).repeated())
665        .then_ignore(just(Token::Then))
666        .then_ignore(just(Token::Newline).repeated())
667        .then(
668            stmt.clone()
669                .repeated()
670                .collect::<Vec<_>>()
671                .map(|stmts: Vec<Stmt>| {
672                    stmts
673                        .into_iter()
674                        .filter(|s| !matches!(s, Stmt::Empty))
675                        .collect::<Vec<_>>()
676                }),
677        );
678
679    // Parse elif branches: `elif COND; then STMTS`
680    let elif_branch = just(Token::Elif)
681        .ignore_then(condition_parser())
682        .then_ignore(just(Token::Semi).or_not())
683        .then_ignore(just(Token::Newline).repeated())
684        .then_ignore(just(Token::Then))
685        .then_ignore(just(Token::Newline).repeated())
686        .then(
687            stmt.clone()
688                .repeated()
689                .collect::<Vec<_>>()
690                .map(|stmts: Vec<Stmt>| {
691                    stmts
692                        .into_iter()
693                        .filter(|s| !matches!(s, Stmt::Empty))
694                        .collect::<Vec<_>>()
695                }),
696        );
697
698    // Parse else branch: `else STMTS`
699    let else_branch = just(Token::Else)
700        .ignore_then(just(Token::Newline).repeated())
701        .ignore_then(stmt.repeated().collect::<Vec<_>>())
702        .map(|stmts: Vec<Stmt>| {
703            stmts
704                .into_iter()
705                .filter(|s| !matches!(s, Stmt::Empty))
706                .collect::<Vec<_>>()
707        });
708
709    just(Token::If)
710        .ignore_then(branch)
711        .then(elif_branch.repeated().collect::<Vec<_>>())
712        .then(else_branch.or_not())
713        .then_ignore(just(Token::Fi))
714        .map(|(((condition, then_branch), elif_branches), else_branch)| {
715            // Build nested if/else structure from elif branches
716            build_if_chain(condition, then_branch, elif_branches, else_branch)
717        })
718        .labelled("if statement")
719        .boxed()
720}
721
722/// Build a nested IfStmt chain from elif branches.
723///
724/// Transforms:
725///   if A then X elif B then Y elif C then Z else W fi
726/// Into:
727///   IfStmt { cond: A, then: X, else: Some([IfStmt { cond: B, then: Y, else: Some([IfStmt { cond: C, then: Z, else: Some(W) }]) }]) }
728fn build_if_chain(
729    condition: Expr,
730    then_branch: Vec<Stmt>,
731    mut elif_branches: Vec<(Expr, Vec<Stmt>)>,
732    else_branch: Option<Vec<Stmt>>,
733) -> IfStmt {
734    if elif_branches.is_empty() {
735        // No elif, just if/else
736        IfStmt {
737            condition: Box::new(condition),
738            then_branch,
739            else_branch,
740        }
741    } else {
742        // Pop the first elif and recursively build the rest
743        let (elif_cond, elif_then) = elif_branches.remove(0);
744        let nested_if = build_if_chain(elif_cond, elif_then, elif_branches, else_branch);
745        IfStmt {
746            condition: Box::new(condition),
747            then_branch,
748            else_branch: Some(vec![Stmt::If(nested_if)]),
749        }
750    }
751}
752
753/// For loop: `for VAR in ITEMS; do STMTS done`
754fn for_parser<'tokens, I, S>(
755    stmt: S,
756) -> impl Parser<'tokens, I, ForLoop, extra::Err<Rich<'tokens, Token, Span>>> + Clone
757where
758    I: ValueInput<'tokens, Token = Token, Span = Span>,
759    S: Parser<'tokens, I, Stmt, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
760{
761    just(Token::For)
762        .ignore_then(ident_parser())
763        .then_ignore(just(Token::In))
764        .then(expr_parser().repeated().at_least(1).collect::<Vec<_>>())
765        .then_ignore(just(Token::Semi).or_not())
766        .then_ignore(just(Token::Newline).repeated())
767        .then_ignore(just(Token::Do))
768        .then_ignore(just(Token::Newline).repeated())
769        .then(
770            stmt.repeated()
771                .collect::<Vec<_>>()
772                .map(|stmts| stmts.into_iter().filter(|s| !matches!(s, Stmt::Empty)).collect()),
773        )
774        .then_ignore(just(Token::Done))
775        .map(|((variable, items), body)| ForLoop {
776            variable,
777            items,
778            body,
779        })
780        .labelled("for loop")
781        .boxed()
782}
783
784/// While loop: `while condition; do ...; done`
785fn while_parser<'tokens, I, S>(
786    stmt: S,
787) -> impl Parser<'tokens, I, WhileLoop, extra::Err<Rich<'tokens, Token, Span>>> + Clone
788where
789    I: ValueInput<'tokens, Token = Token, Span = Span>,
790    S: Parser<'tokens, I, Stmt, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
791{
792    just(Token::While)
793        .ignore_then(condition_parser())
794        .then_ignore(just(Token::Semi).or_not())
795        .then_ignore(just(Token::Newline).repeated())
796        .then_ignore(just(Token::Do))
797        .then_ignore(just(Token::Newline).repeated())
798        .then(
799            stmt.repeated()
800                .collect::<Vec<_>>()
801                .map(|stmts| stmts.into_iter().filter(|s| !matches!(s, Stmt::Empty)).collect()),
802        )
803        .then_ignore(just(Token::Done))
804        .map(|(condition, body)| WhileLoop {
805            condition: Box::new(condition),
806            body,
807        })
808        .labelled("while loop")
809        .boxed()
810}
811
812/// Case statement: `case expr in pattern) commands ;; esac`
813///
814/// Supports:
815/// - Single patterns: `pattern) commands ;;`
816/// - Multiple patterns: `pattern1|pattern2) commands ;;`
817/// - Optional leading `(` before patterns: `(pattern) commands ;;`
818fn case_parser<'tokens, I, S>(
819    stmt: S,
820) -> impl Parser<'tokens, I, CaseStmt, extra::Err<Rich<'tokens, Token, Span>>> + Clone
821where
822    I: ValueInput<'tokens, Token = Token, Span = Span>,
823    S: Parser<'tokens, I, Stmt, extra::Err<Rich<'tokens, Token, Span>>> + Clone + 'tokens,
824{
825    // Pattern part: individual tokens that make up a glob pattern
826    // e.g., "*.rs" is Star + Dot + Ident("rs")
827    let pattern_part = choice((
828        select! { Token::Ident(s) => s },
829        select! { Token::String(s) => s },
830        select! { Token::SingleString(s) => s },
831        select! { Token::Int(n) => n.to_string() },
832        select! { Token::Star => "*".to_string() },
833        select! { Token::Question => "?".to_string() },
834        select! { Token::Dot => ".".to_string() },
835        select! { Token::Path(p) => p },
836        select! { Token::VarRef(v) => v },
837        select! { Token::SimpleVarRef(v) => format!("${}", v) },
838        // Character class: [a-z], [!abc], [^abc], etc.
839        just(Token::LBracket)
840            .ignore_then(
841                choice((
842                    select! { Token::Ident(s) => s },
843                    select! { Token::Int(n) => n.to_string() },
844                    just(Token::Colon).to(":".to_string()),
845                    // Negation: ! or ^ at start of char class
846                    just(Token::Bang).to("!".to_string()),
847                    // Range like a-z
848                    select! { Token::ShortFlag(s) => format!("-{}", s) },
849                ))
850                .repeated()
851                .at_least(1)
852                .collect::<Vec<String>>()
853            )
854            .then_ignore(just(Token::RBracket))
855            .map(|parts| format!("[{}]", parts.join(""))),
856        // Brace expansion: {a,b,c} or {js,ts}
857        just(Token::LBrace)
858            .ignore_then(
859                choice((
860                    select! { Token::Ident(s) => s },
861                    select! { Token::Int(n) => n.to_string() },
862                ))
863                .separated_by(just(Token::Comma))
864                .at_least(1)
865                .collect::<Vec<String>>()
866            )
867            .then_ignore(just(Token::RBrace))
868            .map(|parts| format!("{{{}}}", parts.join(","))),
869    ));
870
871    // A complete pattern is one or more pattern parts joined together
872    // e.g., "*.rs" = Star + Dot + Ident
873    let pattern = pattern_part
874        .repeated()
875        .at_least(1)
876        .collect::<Vec<String>>()
877        .map(|parts| parts.join(""))
878        .labelled("case pattern");
879
880    // Multiple patterns separated by pipe: `pattern1 | pattern2`
881    let patterns = pattern
882        .separated_by(just(Token::Pipe))
883        .at_least(1)
884        .collect::<Vec<String>>()
885        .labelled("case patterns");
886
887    // Branch: `[( ] patterns ) commands ;;`
888    let branch = just(Token::LParen)
889        .or_not()
890        .ignore_then(just(Token::Newline).repeated())
891        .ignore_then(patterns)
892        .then_ignore(just(Token::RParen))
893        .then_ignore(just(Token::Newline).repeated())
894        .then(
895            stmt.clone()
896                .repeated()
897                .collect::<Vec<_>>()
898                .map(|stmts| stmts.into_iter().filter(|s| !matches!(s, Stmt::Empty)).collect()),
899        )
900        .then_ignore(just(Token::DoubleSemi))
901        .then_ignore(just(Token::Newline).repeated())
902        .map(|(patterns, body)| CaseBranch { patterns, body })
903        .labelled("case branch");
904
905    just(Token::Case)
906        .ignore_then(expr_parser())
907        .then_ignore(just(Token::In))
908        .then_ignore(just(Token::Newline).repeated())
909        .then(branch.repeated().collect::<Vec<_>>())
910        .then_ignore(just(Token::Esac))
911        .map(|(expr, branches)| CaseStmt { expr, branches })
912        .labelled("case statement")
913        .boxed()
914}
915
916/// Pipeline: `cmd | cmd | cmd [&]`
917fn pipeline_parser<'tokens, I>(
918) -> impl Parser<'tokens, I, Pipeline, extra::Err<Rich<'tokens, Token, Span>>> + Clone
919where
920    I: ValueInput<'tokens, Token = Token, Span = Span>,
921{
922    command_parser()
923        .separated_by(just(Token::Pipe))
924        .at_least(1)
925        .collect::<Vec<_>>()
926        .then(just(Token::Amp).or_not())
927        .map(|(commands, bg)| Pipeline {
928            commands,
929            background: bg.is_some(),
930        })
931        .labelled("pipeline")
932        .boxed()
933}
934
935/// Command: `name args... [redirects...]`
936/// Command names can be identifiers, 'true', 'false', or '.' (source alias).
937fn command_parser<'tokens, I>(
938) -> impl Parser<'tokens, I, Command, extra::Err<Rich<'tokens, Token, Span>>> + Clone
939where
940    I: ValueInput<'tokens, Token = Token, Span = Span>,
941{
942    // Command name can be an identifier, 'true', 'false', or '.' (source alias)
943    let command_name = choice((
944        ident_parser(),
945        just(Token::True).to("true".to_string()),
946        just(Token::False).to("false".to_string()),
947        just(Token::Dot).to(".".to_string()),
948    ));
949
950    command_name
951        .then(args_list_parser())
952        .then(redirect_parser().repeated().collect::<Vec<_>>())
953        .map(|((name, args), redirects)| Command {
954            name,
955            args,
956            redirects,
957        })
958        .labelled("command")
959        .boxed()
960}
961
962/// Arguments list parser that handles `--` flag terminator.
963///
964/// After `--`, all subsequent flags are converted to positional string arguments.
965fn args_list_parser<'tokens, I>(
966) -> impl Parser<'tokens, I, Vec<Arg>, extra::Err<Rich<'tokens, Token, Span>>> + Clone
967where
968    I: ValueInput<'tokens, Token = Token, Span = Span>,
969{
970    // Arguments before `--` (normal parsing)
971    let pre_dash = arg_before_double_dash_parser()
972        .repeated()
973        .collect::<Vec<_>>();
974
975    // The `--` marker itself
976    let double_dash = select! {
977        Token::DoubleDash => Arg::DoubleDash,
978    };
979
980    // Arguments after `--` (flags become positional strings)
981    let post_dash_arg = choice((
982        // Flags become positional strings
983        select! {
984            Token::ShortFlag(name) => Arg::Positional(Expr::Literal(Value::String(format!("-{}", name)))),
985            Token::LongFlag(name) => Arg::Positional(Expr::Literal(Value::String(format!("--{}", name)))),
986        },
987        // Everything else stays the same
988        primary_expr_parser().map(Arg::Positional),
989    ));
990
991    let post_dash = post_dash_arg.repeated().collect::<Vec<_>>();
992
993    // Combine: args_before ++ [--] ++ args_after
994    pre_dash
995        .then(double_dash.then(post_dash).or_not())
996        .map(|(mut args, maybe_dd)| {
997            if let Some((dd, post)) = maybe_dd {
998                args.push(dd);
999                args.extend(post);
1000            }
1001            args
1002        })
1003}
1004
1005/// Argument parser for arguments before `--` (normal flag handling).
1006fn arg_before_double_dash_parser<'tokens, I>(
1007) -> impl Parser<'tokens, I, Arg, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1008where
1009    I: ValueInput<'tokens, Token = Token, Span = Span>,
1010{
1011    // Long flag with value: --name=value
1012    let long_flag_with_value = select! {
1013        Token::LongFlag(name) => name,
1014    }
1015    .then_ignore(just(Token::Eq))
1016    .then(primary_expr_parser())
1017    .map(|(key, value)| Arg::Named { key, value });
1018
1019    // Boolean long flag: --name
1020    let long_flag = select! {
1021        Token::LongFlag(name) => Arg::LongFlag(name),
1022    };
1023
1024    // Boolean short flag: -x
1025    let short_flag = select! {
1026        Token::ShortFlag(name) => Arg::ShortFlag(name),
1027    };
1028
1029    // Named argument: name=value (must not have spaces around =)
1030    // We use map_with to capture spans and validate adjacency
1031    let named = select! {
1032        Token::Ident(s) => s,
1033    }
1034    .map_with(|s, e| -> (String, Span) { (s, e.span()) })
1035    .then(just(Token::Eq).map_with(|_, e| -> Span { e.span() }))
1036    .then(primary_expr_parser().map_with(|expr, e| -> (Expr, Span) { (expr, e.span()) }))
1037    .try_map(|(((key, key_span), eq_span), (value, value_span)): (((String, Span), Span), (Expr, Span)), span| {
1038        // Check that key ends where = starts and = ends where value starts
1039        if key_span.end != eq_span.start || eq_span.end != value_span.start {
1040            Err(Rich::custom(
1041                span,
1042                "named argument must not have spaces around '=' (use 'key=value' not 'key = value')",
1043            ))
1044        } else {
1045            Ok(Arg::Named { key, value })
1046        }
1047    });
1048
1049    // Positional argument
1050    let positional = primary_expr_parser().map(Arg::Positional);
1051
1052    // Order matters: try more specific patterns first
1053    // Note: DoubleDash is NOT included here - it's handled by args_list_parser
1054    choice((
1055        long_flag_with_value,
1056        long_flag,
1057        short_flag,
1058        named,
1059        positional,
1060    ))
1061    .boxed()
1062}
1063
1064/// Redirect: `> file`, `>> file`, `< file`, `<< heredoc`, `2> file`, `&> file`, `2>&1`
1065fn redirect_parser<'tokens, I>(
1066) -> impl Parser<'tokens, I, Redirect, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1067where
1068    I: ValueInput<'tokens, Token = Token, Span = Span>,
1069{
1070    // Regular redirects: >, >>, <, 2>, &>
1071    let regular_redirect = select! {
1072        Token::GtGt => RedirectKind::StdoutAppend,
1073        Token::Gt => RedirectKind::StdoutOverwrite,
1074        Token::Lt => RedirectKind::Stdin,
1075        Token::Stderr => RedirectKind::Stderr,
1076        Token::Both => RedirectKind::Both,
1077    }
1078    .then(primary_expr_parser())
1079    .map(|(kind, target)| Redirect { kind, target });
1080
1081    // Here-doc redirect: << content
1082    // Quoted delimiters (<<'EOF' or <<"EOF") produce literal heredocs (no expansion).
1083    // Unquoted delimiters produce interpolated heredocs (variables are expanded).
1084    let heredoc_redirect = just(Token::HereDocStart)
1085        .ignore_then(select! { Token::HereDoc(data) => data })
1086        .map(|data: HereDocData| {
1087            let target = if data.literal {
1088                Expr::Literal(Value::String(data.content))
1089            } else {
1090                let parts = parse_interpolated_string(&data.content);
1091                // If there's only one literal part, simplify to Expr::Literal
1092                if parts.len() == 1 {
1093                    if let StringPart::Literal(text) = &parts[0] {
1094                        return Redirect {
1095                            kind: RedirectKind::HereDoc,
1096                            target: Expr::Literal(Value::String(text.clone())),
1097                        };
1098                    }
1099                }
1100                Expr::Interpolated(parts)
1101            };
1102            Redirect {
1103                kind: RedirectKind::HereDoc,
1104                target,
1105            }
1106        });
1107
1108    // Merge stderr to stdout: 2>&1 (no target needed - implicit)
1109    let merge_stderr_redirect = just(Token::StderrToStdout)
1110        .map(|_| Redirect {
1111            kind: RedirectKind::MergeStderr,
1112            // Target is unused for MergeStderr, but we need something
1113            target: Expr::Literal(Value::Null),
1114        });
1115
1116    // Merge stdout to stderr: 1>&2 or >&2 (no target needed - implicit)
1117    let merge_stdout_redirect = choice((
1118        just(Token::StdoutToStderr),
1119        just(Token::StdoutToStderr2),
1120    ))
1121    .map(|_| Redirect {
1122        kind: RedirectKind::MergeStdout,
1123        // Target is unused for MergeStdout, but we need something
1124        target: Expr::Literal(Value::Null),
1125    });
1126
1127    choice((heredoc_redirect, merge_stderr_redirect, merge_stdout_redirect, regular_redirect))
1128        .labelled("redirect")
1129        .boxed()
1130}
1131
1132/// Test expression parser for `[[ ... ]]` syntax.
1133///
1134/// Supports:
1135/// - File tests: `[[ -f path ]]`, `[[ -d path ]]`, etc.
1136/// - String tests: `[[ -z str ]]`, `[[ -n str ]]`
1137/// - Comparisons: `[[ $X == "value" ]]`, `[[ $NUM -gt 5 ]]`
1138/// - Compound: `[[ -f a && -d b ]]`, `[[ -z x || -n y ]]`, `[[ ! -f file ]]`
1139///
1140/// Precedence (highest to lowest): `!` > `&&` > `||`
1141fn test_expr_stmt_parser<'tokens, I>(
1142) -> impl Parser<'tokens, I, TestExpr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1143where
1144    I: ValueInput<'tokens, Token = Token, Span = Span>,
1145{
1146    // File test operators: -e, -f, -d, -r, -w, -x
1147    let file_test_op = select! {
1148        Token::ShortFlag(s) if s == "e" => FileTestOp::Exists,
1149        Token::ShortFlag(s) if s == "f" => FileTestOp::IsFile,
1150        Token::ShortFlag(s) if s == "d" => FileTestOp::IsDir,
1151        Token::ShortFlag(s) if s == "r" => FileTestOp::Readable,
1152        Token::ShortFlag(s) if s == "w" => FileTestOp::Writable,
1153        Token::ShortFlag(s) if s == "x" => FileTestOp::Executable,
1154    };
1155
1156    // String test operators: -z, -n
1157    let string_test_op = select! {
1158        Token::ShortFlag(s) if s == "z" => StringTestOp::IsEmpty,
1159        Token::ShortFlag(s) if s == "n" => StringTestOp::IsNonEmpty,
1160    };
1161
1162    // Comparison operators: =, ==, !=, =~, !~, >, <, >=, <=, -gt, -lt, -ge, -le, -eq, -ne
1163    // Note: = and == are equivalent inside [[ ]] (matching bash behavior)
1164    let cmp_op = choice((
1165        just(Token::EqEq).to(TestCmpOp::Eq),
1166        just(Token::Eq).to(TestCmpOp::Eq),
1167        just(Token::NotEq).to(TestCmpOp::NotEq),
1168        just(Token::Match).to(TestCmpOp::Match),
1169        just(Token::NotMatch).to(TestCmpOp::NotMatch),
1170        just(Token::Gt).to(TestCmpOp::Gt),
1171        just(Token::Lt).to(TestCmpOp::Lt),
1172        just(Token::GtEq).to(TestCmpOp::GtEq),
1173        just(Token::LtEq).to(TestCmpOp::LtEq),
1174        select! { Token::ShortFlag(s) if s == "eq" => TestCmpOp::Eq },
1175        select! { Token::ShortFlag(s) if s == "ne" => TestCmpOp::NotEq },
1176        select! { Token::ShortFlag(s) if s == "gt" => TestCmpOp::Gt },
1177        select! { Token::ShortFlag(s) if s == "lt" => TestCmpOp::Lt },
1178        select! { Token::ShortFlag(s) if s == "ge" => TestCmpOp::GtEq },
1179        select! { Token::ShortFlag(s) if s == "le" => TestCmpOp::LtEq },
1180    ));
1181
1182    // File test: -f path
1183    let file_test = file_test_op
1184        .then(primary_expr_parser())
1185        .map(|(op, path)| TestExpr::FileTest {
1186            op,
1187            path: Box::new(path),
1188        });
1189
1190    // String test: -z str
1191    let string_test = string_test_op
1192        .then(primary_expr_parser())
1193        .map(|(op, value)| TestExpr::StringTest {
1194            op,
1195            value: Box::new(value),
1196        });
1197
1198    // Comparison: $X == "value" or $NUM -gt 5
1199    let comparison = primary_expr_parser()
1200        .then(cmp_op)
1201        .then(primary_expr_parser())
1202        .map(|((left, op), right)| TestExpr::Comparison {
1203            left: Box::new(left),
1204            op,
1205            right: Box::new(right),
1206        });
1207
1208    // Primary test expression (atomic - no compound operators)
1209    let primary_test = choice((file_test, string_test, comparison));
1210
1211    // Build compound expressions with proper precedence:
1212    // Grammar:
1213    //   test_expr = or_expr
1214    //   or_expr   = and_expr { "||" and_expr }
1215    //   and_expr  = unary_expr { "&&" unary_expr }
1216    //   unary_expr = "!" unary_expr | primary_test
1217    //
1218    // Precedence: ! (highest) > && > ||
1219
1220    // Use recursive for the unary NOT operator
1221    let compound_test = recursive(|compound| {
1222        // Unary NOT: ! expr (can be chained: ! ! expr)
1223        let not_expr = just(Token::Bang)
1224            .ignore_then(compound.clone())
1225            .map(|expr| TestExpr::Not { expr: Box::new(expr) });
1226
1227        // Unary level: ! or primary
1228        let unary = choice((not_expr, primary_test.clone()));
1229
1230        // AND level: unary && unary && ...
1231        let and_expr = unary.clone().foldl(
1232            just(Token::And).ignore_then(unary).repeated(),
1233            |left, right| TestExpr::And {
1234                left: Box::new(left),
1235                right: Box::new(right),
1236            },
1237        );
1238
1239        // OR level: and_expr || and_expr || ...
1240        and_expr.clone().foldl(
1241            just(Token::Or).ignore_then(and_expr).repeated(),
1242            |left, right| TestExpr::Or {
1243                left: Box::new(left),
1244                right: Box::new(right),
1245            },
1246        )
1247    });
1248
1249    // [[ ]] is two consecutive bracket tokens (not a single TestStart token)
1250    // to avoid conflicts with nested array syntax like [[1, 2], [3, 4]]
1251    just(Token::LBracket)
1252        .then(just(Token::LBracket))
1253        .ignore_then(compound_test)
1254        .then_ignore(just(Token::RBracket).then(just(Token::RBracket)))
1255        .labelled("test expression")
1256        .boxed()
1257}
1258
1259/// Condition parser: supports [[ ]] test expressions and commands with && / || chaining.
1260///
1261/// Shell semantics: conditions are commands whose exit codes determine truthiness.
1262/// - `if true; then` → runs `true` builtin, exit code 0 = truthy
1263/// - `if grep -q pattern file; then` → runs command, checks exit code
1264/// - `if a && b; then` → runs `a`, if exit 0, runs `b`
1265///
1266/// Use `[[ ]]` for comparisons: `if [[ $X -gt 5 ]]; then`
1267///
1268/// Grammar (with precedence - && binds tighter than ||):
1269///   condition = or_expr
1270///   or_expr   = and_expr { "||" and_expr }
1271///   and_expr  = base { "&&" base }
1272///   base      = test_expr | command
1273fn condition_parser<'tokens, I>(
1274) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1275where
1276    I: ValueInput<'tokens, Token = Token, Span = Span>,
1277{
1278    // [[ ]] test expression - wrap as Expr::Test
1279    let test_expr_condition = test_expr_stmt_parser().map(|test| Expr::Test(Box::new(test)));
1280
1281    // Command as condition (includes true/false as command names)
1282    // The command's exit code determines truthiness (0 = true, non-zero = false)
1283    let command_condition = command_parser().map(Expr::Command);
1284
1285    // Base: test expr OR command
1286    let base = choice((test_expr_condition, command_condition));
1287
1288    // && has higher precedence than ||
1289    // First chain with && (higher precedence)
1290    let and_expr = base.clone().foldl(
1291        just(Token::And).ignore_then(base).repeated(),
1292        |left, right| Expr::BinaryOp {
1293            left: Box::new(left),
1294            op: BinaryOp::And,
1295            right: Box::new(right),
1296        },
1297    );
1298
1299    // Then chain with || (lower precedence)
1300    and_expr
1301        .clone()
1302        .foldl(
1303            just(Token::Or).ignore_then(and_expr).repeated(),
1304            |left, right| Expr::BinaryOp {
1305                left: Box::new(left),
1306                op: BinaryOp::Or,
1307                right: Box::new(right),
1308            },
1309        )
1310        .labelled("condition")
1311        .boxed()
1312}
1313
1314/// Expression parser - supports && and || binary operators.
1315fn expr_parser<'tokens, I>(
1316) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1317where
1318    I: ValueInput<'tokens, Token = Token, Span = Span>,
1319{
1320    // For now, just primary expressions. Can extend for && / || later if needed.
1321    primary_expr_parser()
1322}
1323
1324/// Primary expression: literal, variable reference, command substitution, or bare identifier.
1325///
1326/// Uses `recursive` to support nested command substitution like `$(echo $(date))`.
1327fn primary_expr_parser<'tokens, I>(
1328) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1329where
1330    I: ValueInput<'tokens, Token = Token, Span = Span>,
1331{
1332    // Positional parameters: $0-$9, $@, $#, ${#VAR}, $?, $$
1333    let positional = select! {
1334        Token::Positional(n) => Expr::Positional(n),
1335        Token::AllArgs => Expr::AllArgs,
1336        Token::ArgCount => Expr::ArgCount,
1337        Token::VarLength(name) => Expr::VarLength(name),
1338        Token::LastExitCode => Expr::LastExitCode,
1339        Token::CurrentPid => Expr::CurrentPid,
1340    };
1341
1342    // Arithmetic expression: $((expr)) - preprocessed into Arithmetic token
1343    let arithmetic = select! {
1344        Token::Arithmetic(expr_str) => Expr::Arithmetic(expr_str),
1345    };
1346
1347    // Keywords that can also be used as barewords in argument position
1348    // (e.g., `echo done` should work even though `done` is a keyword)
1349    let keyword_as_bareword = select! {
1350        Token::Done => "done",
1351        Token::Fi => "fi",
1352        Token::Then => "then",
1353        Token::Else => "else",
1354        Token::Elif => "elif",
1355        Token::In => "in",
1356        Token::Do => "do",
1357        Token::Esac => "esac",
1358    }
1359    .map(|s| Expr::Literal(Value::String(s.to_string())));
1360
1361    // Bare words starting with + or - (e.g., date +%s, cat -)
1362    let plus_minus_bare = select! {
1363        Token::PlusBare(s) => Expr::Literal(Value::String(s)),
1364        Token::MinusBare(s) => Expr::Literal(Value::String(s)),
1365        Token::MinusAlone => Expr::Literal(Value::String("-".to_string())),
1366    };
1367
1368    recursive(|expr| {
1369        choice((
1370            positional,
1371            arithmetic,
1372            cmd_subst_parser(expr.clone()),
1373            var_expr_parser(),
1374            interpolated_string_parser(),
1375            literal_parser().map(Expr::Literal),
1376            // Bare identifiers become string literals (shell barewords)
1377            ident_parser().map(|s| Expr::Literal(Value::String(s))),
1378            // Absolute paths become string literals
1379            path_parser().map(|s| Expr::Literal(Value::String(s))),
1380            // Bare words starting with + or - (date +%s, cat -)
1381            plus_minus_bare,
1382            // Keywords can be used as barewords in argument position
1383            keyword_as_bareword,
1384        ))
1385        .labelled("expression")
1386    })
1387    .boxed()
1388}
1389
1390/// Variable reference: `${VAR}`, `${VAR.field}`, `${VAR:-default}`, or `$VAR` (simple form).
1391/// Returns Expr directly to support both VarRef and VarWithDefault.
1392fn var_expr_parser<'tokens, I>(
1393) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1394where
1395    I: ValueInput<'tokens, Token = Token, Span = Span>,
1396{
1397    select! {
1398        Token::VarRef(raw) => parse_var_expr(&raw),
1399        Token::SimpleVarRef(name) => Expr::VarRef(VarPath::simple(name)),
1400    }
1401    .labelled("variable reference")
1402}
1403
1404/// Command substitution: `$(pipeline)` - runs a pipeline and returns its result.
1405///
1406/// Accepts a recursive expression parser to support nested command substitution.
1407fn cmd_subst_parser<'tokens, I, E>(
1408    expr: E,
1409) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1410where
1411    I: ValueInput<'tokens, Token = Token, Span = Span>,
1412    E: Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone,
1413{
1414    // Argument parser using the recursive expression parser
1415    // Long flag with value: --name=value
1416    let long_flag_with_value = select! {
1417        Token::LongFlag(name) => name,
1418    }
1419    .then_ignore(just(Token::Eq))
1420    .then(expr.clone())
1421    .map(|(key, value)| Arg::Named { key, value });
1422
1423    // Boolean long flag: --name
1424    let long_flag = select! {
1425        Token::LongFlag(name) => Arg::LongFlag(name),
1426    };
1427
1428    // Boolean short flag: -x
1429    let short_flag = select! {
1430        Token::ShortFlag(name) => Arg::ShortFlag(name),
1431    };
1432
1433    // Named argument: name=value
1434    let named = ident_parser()
1435        .then_ignore(just(Token::Eq))
1436        .then(expr.clone())
1437        .map(|(key, value)| Arg::Named { key, value });
1438
1439    // Positional argument
1440    let positional = expr.map(Arg::Positional);
1441
1442    let arg = choice((
1443        long_flag_with_value,
1444        long_flag,
1445        short_flag,
1446        named,
1447        positional,
1448    ));
1449
1450    // Command name parser - accepts identifiers and boolean keywords (true/false are builtins)
1451    let command_name = choice((
1452        ident_parser(),
1453        just(Token::True).to("true".to_string()),
1454        just(Token::False).to("false".to_string()),
1455    ));
1456
1457    // Command parser
1458    let command = command_name
1459        .then(arg.repeated().collect::<Vec<_>>())
1460        .map(|(name, args)| Command {
1461            name,
1462            args,
1463            redirects: vec![],
1464        });
1465
1466    // Pipeline parser
1467    let pipeline = command
1468        .separated_by(just(Token::Pipe))
1469        .at_least(1)
1470        .collect::<Vec<_>>()
1471        .map(|commands| Pipeline {
1472            commands,
1473            background: false,
1474        });
1475
1476    just(Token::CmdSubstStart)
1477        .ignore_then(pipeline)
1478        .then_ignore(just(Token::RParen))
1479        .map(|pipeline| Expr::CommandSubst(Box::new(pipeline)))
1480        .labelled("command substitution")
1481}
1482
1483/// String parser - handles double-quoted strings (with interpolation) and single-quoted (literal).
1484fn interpolated_string_parser<'tokens, I>(
1485) -> impl Parser<'tokens, I, Expr, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1486where
1487    I: ValueInput<'tokens, Token = Token, Span = Span>,
1488{
1489    // Double-quoted string: may contain $VAR or ${VAR} interpolation
1490    let double_quoted = select! {
1491        Token::String(s) => s,
1492    }
1493    .map(|s| {
1494        // Check if string contains interpolation markers (${} or $NAME) or escaped dollars
1495        if s.contains('$') || s.contains("__KAISH_ESCAPED_DOLLAR__") {
1496            // Parse interpolated parts
1497            let parts = parse_interpolated_string(&s);
1498            if parts.len() == 1
1499                && let StringPart::Literal(text) = &parts[0] {
1500                    return Expr::Literal(Value::String(text.clone()));
1501                }
1502            Expr::Interpolated(parts)
1503        } else {
1504            Expr::Literal(Value::String(s))
1505        }
1506    });
1507
1508    // Single-quoted string: literal, no interpolation
1509    let single_quoted = select! {
1510        Token::SingleString(s) => Expr::Literal(Value::String(s)),
1511    };
1512
1513    choice((single_quoted, double_quoted)).labelled("string")
1514}
1515
1516/// Literal value parser (excluding strings, which are handled by interpolated_string_parser).
1517fn literal_parser<'tokens, I>(
1518) -> impl Parser<'tokens, I, Value, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1519where
1520    I: ValueInput<'tokens, Token = Token, Span = Span>,
1521{
1522    choice((
1523        select! {
1524            Token::True => Value::Bool(true),
1525            Token::False => Value::Bool(false),
1526        },
1527        select! {
1528            Token::Int(n) => Value::Int(n),
1529            Token::Float(f) => Value::Float(f),
1530        },
1531    ))
1532    .labelled("literal")
1533    .boxed()
1534}
1535
1536/// Identifier parser.
1537fn ident_parser<'tokens, I>(
1538) -> impl Parser<'tokens, I, String, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1539where
1540    I: ValueInput<'tokens, Token = Token, Span = Span>,
1541{
1542    select! {
1543        Token::Ident(s) => s,
1544    }
1545    .labelled("identifier")
1546}
1547
1548/// Path parser: matches absolute paths like `/tmp/out`, `/etc/hosts`.
1549fn path_parser<'tokens, I>(
1550) -> impl Parser<'tokens, I, String, extra::Err<Rich<'tokens, Token, Span>>> + Clone
1551where
1552    I: ValueInput<'tokens, Token = Token, Span = Span>,
1553{
1554    select! {
1555        Token::Path(s) => s,
1556    }
1557    .labelled("path")
1558}
1559
1560#[cfg(test)]
1561mod tests {
1562    use super::*;
1563
1564    #[test]
1565    fn parse_empty() {
1566        let result = parse("");
1567        assert!(result.is_ok());
1568        assert_eq!(result.expect("ok").statements.len(), 0);
1569    }
1570
1571    #[test]
1572    fn parse_newlines_only() {
1573        let result = parse("\n\n\n");
1574        assert!(result.is_ok());
1575    }
1576
1577    #[test]
1578    fn parse_simple_command() {
1579        let result = parse("echo");
1580        assert!(result.is_ok());
1581        let program = result.expect("ok");
1582        assert_eq!(program.statements.len(), 1);
1583        assert!(matches!(&program.statements[0], Stmt::Command(_)));
1584    }
1585
1586    #[test]
1587    fn parse_command_with_string_arg() {
1588        let result = parse(r#"echo "hello""#);
1589        assert!(result.is_ok());
1590        let program = result.expect("ok");
1591        match &program.statements[0] {
1592            Stmt::Command(cmd) => assert_eq!(cmd.args.len(), 1),
1593            _ => panic!("expected Command"),
1594        }
1595    }
1596
1597    #[test]
1598    fn parse_assignment() {
1599        let result = parse("X=5");
1600        assert!(result.is_ok());
1601        let program = result.expect("ok");
1602        assert!(matches!(&program.statements[0], Stmt::Assignment(_)));
1603    }
1604
1605    #[test]
1606    fn parse_pipeline() {
1607        let result = parse("a | b | c");
1608        assert!(result.is_ok());
1609        let program = result.expect("ok");
1610        match &program.statements[0] {
1611            Stmt::Pipeline(p) => assert_eq!(p.commands.len(), 3),
1612            _ => panic!("expected Pipeline"),
1613        }
1614    }
1615
1616    #[test]
1617    fn parse_background_job() {
1618        let result = parse("cmd &");
1619        assert!(result.is_ok());
1620        let program = result.expect("ok");
1621        match &program.statements[0] {
1622            Stmt::Pipeline(p) => assert!(p.background),
1623            _ => panic!("expected Pipeline with background"),
1624        }
1625    }
1626
1627    #[test]
1628    fn parse_if_simple() {
1629        let result = parse("if true; then echo; fi");
1630        assert!(result.is_ok());
1631        let program = result.expect("ok");
1632        assert!(matches!(&program.statements[0], Stmt::If(_)));
1633    }
1634
1635    #[test]
1636    fn parse_if_else() {
1637        let result = parse("if true; then echo; else echo; fi");
1638        assert!(result.is_ok());
1639        let program = result.expect("ok");
1640        match &program.statements[0] {
1641            Stmt::If(if_stmt) => assert!(if_stmt.else_branch.is_some()),
1642            _ => panic!("expected If"),
1643        }
1644    }
1645
1646    #[test]
1647    fn parse_elif_simple() {
1648        let result = parse("if true; then echo a; elif false; then echo b; fi");
1649        assert!(result.is_ok(), "parse failed: {:?}", result);
1650        let program = result.expect("ok");
1651        match &program.statements[0] {
1652            Stmt::If(if_stmt) => {
1653                // elif is desugared to nested if in else
1654                assert!(if_stmt.else_branch.is_some());
1655                let else_branch = if_stmt.else_branch.as_ref().unwrap();
1656                assert_eq!(else_branch.len(), 1);
1657                assert!(matches!(&else_branch[0], Stmt::If(_)));
1658            }
1659            _ => panic!("expected If"),
1660        }
1661    }
1662
1663    #[test]
1664    fn parse_elif_with_else() {
1665        let result = parse("if true; then echo a; elif false; then echo b; else echo c; fi");
1666        assert!(result.is_ok(), "parse failed: {:?}", result);
1667        let program = result.expect("ok");
1668        match &program.statements[0] {
1669            Stmt::If(outer_if) => {
1670                // Check nested structure: if -> elif -> else
1671                let else_branch = outer_if.else_branch.as_ref().expect("outer else");
1672                assert_eq!(else_branch.len(), 1);
1673                match &else_branch[0] {
1674                    Stmt::If(inner_if) => {
1675                        // The inner if (from elif) should have the final else
1676                        assert!(inner_if.else_branch.is_some());
1677                    }
1678                    _ => panic!("expected nested If from elif"),
1679                }
1680            }
1681            _ => panic!("expected If"),
1682        }
1683    }
1684
1685    #[test]
1686    fn parse_multiple_elif() {
1687        // Shell-compatible: use [[ ]] for comparisons
1688        let result = parse(
1689            "if [[ ${X} == 1 ]]; then echo one; elif [[ ${X} == 2 ]]; then echo two; elif [[ ${X} == 3 ]]; then echo three; else echo other; fi",
1690        );
1691        assert!(result.is_ok(), "parse failed: {:?}", result);
1692    }
1693
1694    #[test]
1695    fn parse_for_loop() {
1696        let result = parse("for X in items; do echo; done");
1697        assert!(result.is_ok());
1698        let program = result.expect("ok");
1699        assert!(matches!(&program.statements[0], Stmt::For(_)));
1700    }
1701
1702    #[test]
1703    fn parse_brackets_not_array_literal() {
1704        // Array literals are no longer supported, [ is just a regular char
1705        let result = parse("cmd [1");
1706        // This should fail or parse unexpectedly - arrays are removed
1707        // Just verify we don't crash
1708        let _ = result;
1709    }
1710
1711    #[test]
1712    fn parse_named_arg() {
1713        let result = parse("cmd foo=5");
1714        assert!(result.is_ok());
1715        let program = result.expect("ok");
1716        match &program.statements[0] {
1717            Stmt::Command(cmd) => {
1718                assert_eq!(cmd.args.len(), 1);
1719                assert!(matches!(&cmd.args[0], Arg::Named { .. }));
1720            }
1721            _ => panic!("expected Command"),
1722        }
1723    }
1724
1725    #[test]
1726    fn parse_short_flag() {
1727        let result = parse("ls -l");
1728        assert!(result.is_ok());
1729        let program = result.expect("ok");
1730        match &program.statements[0] {
1731            Stmt::Command(cmd) => {
1732                assert_eq!(cmd.name, "ls");
1733                assert_eq!(cmd.args.len(), 1);
1734                match &cmd.args[0] {
1735                    Arg::ShortFlag(name) => assert_eq!(name, "l"),
1736                    _ => panic!("expected ShortFlag"),
1737                }
1738            }
1739            _ => panic!("expected Command"),
1740        }
1741    }
1742
1743    #[test]
1744    fn parse_long_flag() {
1745        let result = parse("git push --force");
1746        assert!(result.is_ok());
1747        let program = result.expect("ok");
1748        match &program.statements[0] {
1749            Stmt::Command(cmd) => {
1750                assert_eq!(cmd.name, "git");
1751                assert_eq!(cmd.args.len(), 2);
1752                match &cmd.args[0] {
1753                    Arg::Positional(Expr::Literal(Value::String(s))) => assert_eq!(s, "push"),
1754                    _ => panic!("expected Positional push"),
1755                }
1756                match &cmd.args[1] {
1757                    Arg::LongFlag(name) => assert_eq!(name, "force"),
1758                    _ => panic!("expected LongFlag"),
1759                }
1760            }
1761            _ => panic!("expected Command"),
1762        }
1763    }
1764
1765    #[test]
1766    fn parse_long_flag_with_value() {
1767        let result = parse(r#"git commit --message="hello""#);
1768        assert!(result.is_ok());
1769        let program = result.expect("ok");
1770        match &program.statements[0] {
1771            Stmt::Command(cmd) => {
1772                assert_eq!(cmd.name, "git");
1773                assert_eq!(cmd.args.len(), 2);
1774                match &cmd.args[1] {
1775                    Arg::Named { key, value } => {
1776                        assert_eq!(key, "message");
1777                        match value {
1778                            Expr::Literal(Value::String(s)) => assert_eq!(s, "hello"),
1779                            _ => panic!("expected String value"),
1780                        }
1781                    }
1782                    _ => panic!("expected Named from --flag=value"),
1783                }
1784            }
1785            _ => panic!("expected Command"),
1786        }
1787    }
1788
1789    #[test]
1790    fn parse_mixed_flags_and_args() {
1791        let result = parse(r#"git commit -m "message" --amend"#);
1792        assert!(result.is_ok());
1793        let program = result.expect("ok");
1794        match &program.statements[0] {
1795            Stmt::Command(cmd) => {
1796                assert_eq!(cmd.name, "git");
1797                assert_eq!(cmd.args.len(), 4);
1798                // commit (positional)
1799                assert!(matches!(&cmd.args[0], Arg::Positional(_)));
1800                // -m (short flag)
1801                match &cmd.args[1] {
1802                    Arg::ShortFlag(name) => assert_eq!(name, "m"),
1803                    _ => panic!("expected ShortFlag -m"),
1804                }
1805                // "message" (positional)
1806                assert!(matches!(&cmd.args[2], Arg::Positional(_)));
1807                // --amend (long flag)
1808                match &cmd.args[3] {
1809                    Arg::LongFlag(name) => assert_eq!(name, "amend"),
1810                    _ => panic!("expected LongFlag --amend"),
1811                }
1812            }
1813            _ => panic!("expected Command"),
1814        }
1815    }
1816
1817    #[test]
1818    fn parse_redirect_stdout() {
1819        let result = parse("cmd > file");
1820        assert!(result.is_ok());
1821        let program = result.expect("ok");
1822        // Commands with redirects stay as Pipeline, not Command
1823        match &program.statements[0] {
1824            Stmt::Pipeline(p) => {
1825                assert_eq!(p.commands.len(), 1);
1826                let cmd = &p.commands[0];
1827                assert_eq!(cmd.redirects.len(), 1);
1828                assert!(matches!(cmd.redirects[0].kind, RedirectKind::StdoutOverwrite));
1829            }
1830            _ => panic!("expected Pipeline"),
1831        }
1832    }
1833
1834    #[test]
1835    fn parse_var_ref() {
1836        let result = parse("echo ${VAR}");
1837        assert!(result.is_ok());
1838        let program = result.expect("ok");
1839        match &program.statements[0] {
1840            Stmt::Command(cmd) => {
1841                assert_eq!(cmd.args.len(), 1);
1842                assert!(matches!(&cmd.args[0], Arg::Positional(Expr::VarRef(_))));
1843            }
1844            _ => panic!("expected Command"),
1845        }
1846    }
1847
1848    #[test]
1849    fn parse_multiple_statements() {
1850        let result = parse("a\nb\nc");
1851        assert!(result.is_ok());
1852        let program = result.expect("ok");
1853        let non_empty: Vec<_> = program.statements.iter().filter(|s| !matches!(s, Stmt::Empty)).collect();
1854        assert_eq!(non_empty.len(), 3);
1855    }
1856
1857    #[test]
1858    fn parse_semicolon_separated() {
1859        let result = parse("a; b; c");
1860        assert!(result.is_ok());
1861        let program = result.expect("ok");
1862        let non_empty: Vec<_> = program.statements.iter().filter(|s| !matches!(s, Stmt::Empty)).collect();
1863        assert_eq!(non_empty.len(), 3);
1864    }
1865
1866    #[test]
1867    fn parse_complex_pipeline() {
1868        let result = parse(r#"cat file | grep pattern="foo" | head count=10"#);
1869        assert!(result.is_ok());
1870        let program = result.expect("ok");
1871        match &program.statements[0] {
1872            Stmt::Pipeline(p) => assert_eq!(p.commands.len(), 3),
1873            _ => panic!("expected Pipeline"),
1874        }
1875    }
1876
1877    #[test]
1878    fn parse_json_as_string_arg() {
1879        // JSON arrays/objects should be passed as string arguments
1880        let result = parse(r#"cmd '[[1, 2], [3, 4]]'"#);
1881        assert!(result.is_ok());
1882    }
1883
1884    #[test]
1885    fn parse_mixed_args() {
1886        let result = parse(r#"cmd pos1 key="val" pos2 num=42"#);
1887        assert!(result.is_ok());
1888        let program = result.expect("ok");
1889        match &program.statements[0] {
1890            Stmt::Command(cmd) => assert_eq!(cmd.args.len(), 4),
1891            _ => panic!("expected Command"),
1892        }
1893    }
1894
1895    #[test]
1896    fn error_unterminated_string() {
1897        let result = parse(r#"echo "hello"#);
1898        assert!(result.is_err());
1899    }
1900
1901    #[test]
1902    fn error_unterminated_var_ref() {
1903        let result = parse("echo ${VAR");
1904        assert!(result.is_err());
1905    }
1906
1907    #[test]
1908    fn error_missing_fi() {
1909        let result = parse("if true; then echo");
1910        assert!(result.is_err());
1911    }
1912
1913    #[test]
1914    fn error_missing_done() {
1915        let result = parse("for X in items; do echo");
1916        assert!(result.is_err());
1917    }
1918
1919    #[test]
1920    fn parse_nested_cmd_subst() {
1921        // Nested command substitution is supported
1922        let result = parse("X=$(echo $(date))").unwrap();
1923        match &result.statements[0] {
1924            Stmt::Assignment(a) => {
1925                assert_eq!(a.name, "X");
1926                match &a.value {
1927                    Expr::CommandSubst(outer) => {
1928                        assert_eq!(outer.commands[0].name, "echo");
1929                        // The argument should be another command substitution
1930                        match &outer.commands[0].args[0] {
1931                            Arg::Positional(Expr::CommandSubst(inner)) => {
1932                                assert_eq!(inner.commands[0].name, "date");
1933                            }
1934                            other => panic!("expected nested cmd subst, got {:?}", other),
1935                        }
1936                    }
1937                    other => panic!("expected cmd subst, got {:?}", other),
1938                }
1939            }
1940            other => panic!("expected assignment, got {:?}", other),
1941        }
1942    }
1943
1944    #[test]
1945    fn parse_deeply_nested_cmd_subst() {
1946        // Three levels deep
1947        let result = parse("X=$(a $(b $(c)))").unwrap();
1948        match &result.statements[0] {
1949            Stmt::Assignment(a) => match &a.value {
1950                Expr::CommandSubst(level1) => {
1951                    assert_eq!(level1.commands[0].name, "a");
1952                    match &level1.commands[0].args[0] {
1953                        Arg::Positional(Expr::CommandSubst(level2)) => {
1954                            assert_eq!(level2.commands[0].name, "b");
1955                            match &level2.commands[0].args[0] {
1956                                Arg::Positional(Expr::CommandSubst(level3)) => {
1957                                    assert_eq!(level3.commands[0].name, "c");
1958                                }
1959                                other => panic!("expected level3 cmd subst, got {:?}", other),
1960                            }
1961                        }
1962                        other => panic!("expected level2 cmd subst, got {:?}", other),
1963                    }
1964                }
1965                other => panic!("expected cmd subst, got {:?}", other),
1966            },
1967            other => panic!("expected assignment, got {:?}", other),
1968        }
1969    }
1970
1971    // ═══════════════════════════════════════════════════════════════════════════
1972    // Value Preservation Tests - These test that actual values are captured
1973    // ═══════════════════════════════════════════════════════════════════════════
1974
1975    #[test]
1976    fn value_int_preserved() {
1977        let result = parse("X=42").unwrap();
1978        match &result.statements[0] {
1979            Stmt::Assignment(a) => {
1980                assert_eq!(a.name, "X");
1981                match &a.value {
1982                    Expr::Literal(Value::Int(n)) => assert_eq!(*n, 42),
1983                    other => panic!("expected int literal, got {:?}", other),
1984                }
1985            }
1986            other => panic!("expected assignment, got {:?}", other),
1987        }
1988    }
1989
1990    #[test]
1991    fn value_negative_int_preserved() {
1992        let result = parse("X=-99").unwrap();
1993        match &result.statements[0] {
1994            Stmt::Assignment(a) => match &a.value {
1995                Expr::Literal(Value::Int(n)) => assert_eq!(*n, -99),
1996                other => panic!("expected int, got {:?}", other),
1997            },
1998            other => panic!("expected assignment, got {:?}", other),
1999        }
2000    }
2001
2002    #[test]
2003    fn value_float_preserved() {
2004        let result = parse("PI=3.14").unwrap();
2005        match &result.statements[0] {
2006            Stmt::Assignment(a) => match &a.value {
2007                Expr::Literal(Value::Float(f)) => assert!((*f - 3.14).abs() < 0.001),
2008                other => panic!("expected float, got {:?}", other),
2009            },
2010            other => panic!("expected assignment, got {:?}", other),
2011        }
2012    }
2013
2014    #[test]
2015    fn value_string_preserved() {
2016        let result = parse(r#"echo "hello world""#).unwrap();
2017        match &result.statements[0] {
2018            Stmt::Command(cmd) => {
2019                assert_eq!(cmd.name, "echo");
2020                match &cmd.args[0] {
2021                    Arg::Positional(Expr::Literal(Value::String(s))) => {
2022                        assert_eq!(s, "hello world");
2023                    }
2024                    other => panic!("expected string arg, got {:?}", other),
2025                }
2026            }
2027            other => panic!("expected command, got {:?}", other),
2028        }
2029    }
2030
2031    #[test]
2032    fn value_string_with_escapes_preserved() {
2033        let result = parse(r#"echo "line1\nline2""#).unwrap();
2034        match &result.statements[0] {
2035            Stmt::Command(cmd) => match &cmd.args[0] {
2036                Arg::Positional(Expr::Literal(Value::String(s))) => {
2037                    assert_eq!(s, "line1\nline2");
2038                }
2039                other => panic!("expected string, got {:?}", other),
2040            },
2041            other => panic!("expected command, got {:?}", other),
2042        }
2043    }
2044
2045    #[test]
2046    fn value_command_name_preserved() {
2047        let result = parse("my-command").unwrap();
2048        match &result.statements[0] {
2049            Stmt::Command(cmd) => assert_eq!(cmd.name, "my-command"),
2050            other => panic!("expected command, got {:?}", other),
2051        }
2052    }
2053
2054    #[test]
2055    fn value_assignment_name_preserved() {
2056        let result = parse("MY_VAR=1").unwrap();
2057        match &result.statements[0] {
2058            Stmt::Assignment(a) => assert_eq!(a.name, "MY_VAR"),
2059            other => panic!("expected assignment, got {:?}", other),
2060        }
2061    }
2062
2063    #[test]
2064    fn value_for_variable_preserved() {
2065        let result = parse("for ITEM in items; do echo; done").unwrap();
2066        match &result.statements[0] {
2067            Stmt::For(f) => assert_eq!(f.variable, "ITEM"),
2068            other => panic!("expected for, got {:?}", other),
2069        }
2070    }
2071
2072    #[test]
2073    fn value_varref_name_preserved() {
2074        let result = parse("echo ${MESSAGE}").unwrap();
2075        match &result.statements[0] {
2076            Stmt::Command(cmd) => match &cmd.args[0] {
2077                Arg::Positional(Expr::VarRef(path)) => {
2078                    assert_eq!(path.segments.len(), 1);
2079                    let VarSegment::Field(name) = &path.segments[0];
2080                    assert_eq!(name, "MESSAGE");
2081                }
2082                other => panic!("expected varref, got {:?}", other),
2083            },
2084            other => panic!("expected command, got {:?}", other),
2085        }
2086    }
2087
2088    #[test]
2089    fn value_varref_field_access_preserved() {
2090        let result = parse("echo ${RESULT.data}").unwrap();
2091        match &result.statements[0] {
2092            Stmt::Command(cmd) => match &cmd.args[0] {
2093                Arg::Positional(Expr::VarRef(path)) => {
2094                    assert_eq!(path.segments.len(), 2);
2095                    let VarSegment::Field(a) = &path.segments[0];
2096                    let VarSegment::Field(b) = &path.segments[1];
2097                    assert_eq!(a, "RESULT");
2098                    assert_eq!(b, "data");
2099                }
2100                other => panic!("expected varref, got {:?}", other),
2101            },
2102            other => panic!("expected command, got {:?}", other),
2103        }
2104    }
2105
2106    #[test]
2107    fn value_varref_index_ignored() {
2108        // Index segments are no longer supported - they're filtered out by parse_varpath
2109        let result = parse("echo ${ITEMS[0]}").unwrap();
2110        match &result.statements[0] {
2111            Stmt::Command(cmd) => match &cmd.args[0] {
2112                Arg::Positional(Expr::VarRef(path)) => {
2113                    // Index segment [0] is skipped, only ITEMS remains
2114                    assert_eq!(path.segments.len(), 1);
2115                    let VarSegment::Field(name) = &path.segments[0];
2116                    assert_eq!(name, "ITEMS");
2117                }
2118                other => panic!("expected varref, got {:?}", other),
2119            },
2120            other => panic!("expected command, got {:?}", other),
2121        }
2122    }
2123
2124    #[test]
2125    fn value_last_result_ref_preserved() {
2126        let result = parse("echo ${?.ok}").unwrap();
2127        match &result.statements[0] {
2128            Stmt::Command(cmd) => match &cmd.args[0] {
2129                Arg::Positional(Expr::VarRef(path)) => {
2130                    assert_eq!(path.segments.len(), 2);
2131                    let VarSegment::Field(name) = &path.segments[0];
2132                    assert_eq!(name, "?");
2133                }
2134                other => panic!("expected varref, got {:?}", other),
2135            },
2136            other => panic!("expected command, got {:?}", other),
2137        }
2138    }
2139
2140    #[test]
2141    fn value_named_arg_preserved() {
2142        let result = parse("cmd count=42").unwrap();
2143        match &result.statements[0] {
2144            Stmt::Command(cmd) => {
2145                assert_eq!(cmd.name, "cmd");
2146                match &cmd.args[0] {
2147                    Arg::Named { key, value } => {
2148                        assert_eq!(key, "count");
2149                        match value {
2150                            Expr::Literal(Value::Int(n)) => assert_eq!(*n, 42),
2151                            other => panic!("expected int, got {:?}", other),
2152                        }
2153                    }
2154                    other => panic!("expected named arg, got {:?}", other),
2155                }
2156            }
2157            other => panic!("expected command, got {:?}", other),
2158        }
2159    }
2160
2161    #[test]
2162    fn value_function_def_name_preserved() {
2163        let result = parse("greet() { echo }").unwrap();
2164        match &result.statements[0] {
2165            Stmt::ToolDef(t) => {
2166                assert_eq!(t.name, "greet");
2167                assert!(t.params.is_empty());
2168            }
2169            other => panic!("expected function def, got {:?}", other),
2170        }
2171    }
2172
2173    // ═══════════════════════════════════════════════════════════════════════════
2174    // New Feature Tests - Comparisons, Interpolation, Nested Structures
2175    // ═══════════════════════════════════════════════════════════════════════════
2176
2177    #[test]
2178    fn parse_comparison_equals() {
2179        // Shell-compatible: use [[ ]] for comparisons
2180        let result = parse("if [[ ${X} == 5 ]]; then echo; fi").unwrap();
2181        match &result.statements[0] {
2182            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
2183                Expr::Test(test) => match test.as_ref() {
2184                    TestExpr::Comparison { left, op, right } => {
2185                        assert!(matches!(left.as_ref(), Expr::VarRef(_)));
2186                        assert_eq!(*op, TestCmpOp::Eq);
2187                        match right.as_ref() {
2188                            Expr::Literal(Value::Int(n)) => assert_eq!(*n, 5),
2189                            other => panic!("expected int, got {:?}", other),
2190                        }
2191                    }
2192                    other => panic!("expected comparison, got {:?}", other),
2193                },
2194                other => panic!("expected test expr, got {:?}", other),
2195            },
2196            other => panic!("expected if, got {:?}", other),
2197        }
2198    }
2199
2200    #[test]
2201    fn parse_comparison_not_equals() {
2202        let result = parse("if [[ ${X} != 0 ]]; then echo; fi").unwrap();
2203        match &result.statements[0] {
2204            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
2205                Expr::Test(test) => match test.as_ref() {
2206                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::NotEq),
2207                    other => panic!("expected comparison, got {:?}", other),
2208                },
2209                other => panic!("expected test expr, got {:?}", other),
2210            },
2211            other => panic!("expected if, got {:?}", other),
2212        }
2213    }
2214
2215    #[test]
2216    fn parse_comparison_less_than() {
2217        let result = parse("if [[ ${COUNT} -lt 10 ]]; then echo; fi").unwrap();
2218        match &result.statements[0] {
2219            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
2220                Expr::Test(test) => match test.as_ref() {
2221                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::Lt),
2222                    other => panic!("expected comparison, got {:?}", other),
2223                },
2224                other => panic!("expected test expr, got {:?}", other),
2225            },
2226            other => panic!("expected if, got {:?}", other),
2227        }
2228    }
2229
2230    #[test]
2231    fn parse_comparison_greater_than() {
2232        let result = parse("if [[ ${COUNT} -gt 0 ]]; then echo; fi").unwrap();
2233        match &result.statements[0] {
2234            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
2235                Expr::Test(test) => match test.as_ref() {
2236                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::Gt),
2237                    other => panic!("expected comparison, got {:?}", other),
2238                },
2239                other => panic!("expected test expr, got {:?}", other),
2240            },
2241            other => panic!("expected if, got {:?}", other),
2242        }
2243    }
2244
2245    #[test]
2246    fn parse_comparison_less_equal() {
2247        let result = parse("if [[ ${X} -le 100 ]]; then echo; fi").unwrap();
2248        match &result.statements[0] {
2249            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
2250                Expr::Test(test) => match test.as_ref() {
2251                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::LtEq),
2252                    other => panic!("expected comparison, got {:?}", other),
2253                },
2254                other => panic!("expected test expr, got {:?}", other),
2255            },
2256            other => panic!("expected if, got {:?}", other),
2257        }
2258    }
2259
2260    #[test]
2261    fn parse_comparison_greater_equal() {
2262        let result = parse("if [[ ${X} -ge 1 ]]; then echo; fi").unwrap();
2263        match &result.statements[0] {
2264            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
2265                Expr::Test(test) => match test.as_ref() {
2266                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::GtEq),
2267                    other => panic!("expected comparison, got {:?}", other),
2268                },
2269                other => panic!("expected test expr, got {:?}", other),
2270            },
2271            other => panic!("expected if, got {:?}", other),
2272        }
2273    }
2274
2275    #[test]
2276    fn parse_regex_match() {
2277        let result = parse(r#"if [[ ${NAME} =~ "^test" ]]; then echo; fi"#).unwrap();
2278        match &result.statements[0] {
2279            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
2280                Expr::Test(test) => match test.as_ref() {
2281                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::Match),
2282                    other => panic!("expected comparison, got {:?}", other),
2283                },
2284                other => panic!("expected test expr, got {:?}", other),
2285            },
2286            other => panic!("expected if, got {:?}", other),
2287        }
2288    }
2289
2290    #[test]
2291    fn parse_regex_not_match() {
2292        let result = parse(r#"if [[ ${NAME} !~ "^test" ]]; then echo; fi"#).unwrap();
2293        match &result.statements[0] {
2294            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
2295                Expr::Test(test) => match test.as_ref() {
2296                    TestExpr::Comparison { op, .. } => assert_eq!(*op, TestCmpOp::NotMatch),
2297                    other => panic!("expected comparison, got {:?}", other),
2298                },
2299                other => panic!("expected test expr, got {:?}", other),
2300            },
2301            other => panic!("expected if, got {:?}", other),
2302        }
2303    }
2304
2305    #[test]
2306    fn parse_string_interpolation() {
2307        let result = parse(r#"echo "Hello ${NAME}!""#).unwrap();
2308        match &result.statements[0] {
2309            Stmt::Command(cmd) => match &cmd.args[0] {
2310                Arg::Positional(Expr::Interpolated(parts)) => {
2311                    assert_eq!(parts.len(), 3);
2312                    match &parts[0] {
2313                        StringPart::Literal(s) => assert_eq!(s, "Hello "),
2314                        other => panic!("expected literal, got {:?}", other),
2315                    }
2316                    match &parts[1] {
2317                        StringPart::Var(path) => {
2318                            assert_eq!(path.segments.len(), 1);
2319                            let VarSegment::Field(name) = &path.segments[0];
2320                            assert_eq!(name, "NAME");
2321                        }
2322                        other => panic!("expected var, got {:?}", other),
2323                    }
2324                    match &parts[2] {
2325                        StringPart::Literal(s) => assert_eq!(s, "!"),
2326                        other => panic!("expected literal, got {:?}", other),
2327                    }
2328                }
2329                other => panic!("expected interpolated, got {:?}", other),
2330            },
2331            other => panic!("expected command, got {:?}", other),
2332        }
2333    }
2334
2335    #[test]
2336    fn parse_string_interpolation_multiple_vars() {
2337        let result = parse(r#"echo "${FIRST} and ${SECOND}""#).unwrap();
2338        match &result.statements[0] {
2339            Stmt::Command(cmd) => match &cmd.args[0] {
2340                Arg::Positional(Expr::Interpolated(parts)) => {
2341                    // ${FIRST} + " and " + ${SECOND} = 3 parts
2342                    assert_eq!(parts.len(), 3);
2343                    assert!(matches!(&parts[0], StringPart::Var(_)));
2344                    assert!(matches!(&parts[1], StringPart::Literal(_)));
2345                    assert!(matches!(&parts[2], StringPart::Var(_)));
2346                }
2347                other => panic!("expected interpolated, got {:?}", other),
2348            },
2349            other => panic!("expected command, got {:?}", other),
2350        }
2351    }
2352
2353    #[test]
2354    fn parse_empty_function_body() {
2355        let result = parse("empty() { }").unwrap();
2356        match &result.statements[0] {
2357            Stmt::ToolDef(t) => {
2358                assert_eq!(t.name, "empty");
2359                assert!(t.params.is_empty());
2360                assert!(t.body.is_empty());
2361            }
2362            other => panic!("expected function def, got {:?}", other),
2363        }
2364    }
2365
2366    #[test]
2367    fn parse_bash_style_function() {
2368        let result = parse("function greet { echo hello }").unwrap();
2369        match &result.statements[0] {
2370            Stmt::ToolDef(t) => {
2371                assert_eq!(t.name, "greet");
2372                assert!(t.params.is_empty());
2373                assert_eq!(t.body.len(), 1);
2374            }
2375            other => panic!("expected function def, got {:?}", other),
2376        }
2377    }
2378
2379    #[test]
2380    fn parse_comparison_string_values() {
2381        let result = parse(r#"if [[ ${STATUS} == "ok" ]]; then echo; fi"#).unwrap();
2382        match &result.statements[0] {
2383            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
2384                Expr::Test(test) => match test.as_ref() {
2385                    TestExpr::Comparison { left, op, right } => {
2386                        assert!(matches!(left.as_ref(), Expr::VarRef(_)));
2387                        assert_eq!(*op, TestCmpOp::Eq);
2388                        match right.as_ref() {
2389                            Expr::Literal(Value::String(s)) => assert_eq!(s, "ok"),
2390                            other => panic!("expected string, got {:?}", other),
2391                        }
2392                    }
2393                    other => panic!("expected comparison, got {:?}", other),
2394                },
2395                other => panic!("expected test expr, got {:?}", other),
2396            },
2397            other => panic!("expected if, got {:?}", other),
2398        }
2399    }
2400
2401    // ═══════════════════════════════════════════════════════════════════════════
2402    // Command Substitution Tests
2403    // ═══════════════════════════════════════════════════════════════════════════
2404
2405    #[test]
2406    fn parse_cmd_subst_simple() {
2407        let result = parse("X=$(echo)").unwrap();
2408        match &result.statements[0] {
2409            Stmt::Assignment(a) => {
2410                assert_eq!(a.name, "X");
2411                match &a.value {
2412                    Expr::CommandSubst(pipeline) => {
2413                        assert_eq!(pipeline.commands.len(), 1);
2414                        assert_eq!(pipeline.commands[0].name, "echo");
2415                    }
2416                    other => panic!("expected command subst, got {:?}", other),
2417                }
2418            }
2419            other => panic!("expected assignment, got {:?}", other),
2420        }
2421    }
2422
2423    #[test]
2424    fn parse_cmd_subst_with_args() {
2425        let result = parse(r#"X=$(fetch url="http://example.com")"#).unwrap();
2426        match &result.statements[0] {
2427            Stmt::Assignment(a) => match &a.value {
2428                Expr::CommandSubst(pipeline) => {
2429                    assert_eq!(pipeline.commands[0].name, "fetch");
2430                    assert_eq!(pipeline.commands[0].args.len(), 1);
2431                    match &pipeline.commands[0].args[0] {
2432                        Arg::Named { key, .. } => assert_eq!(key, "url"),
2433                        other => panic!("expected named arg, got {:?}", other),
2434                    }
2435                }
2436                other => panic!("expected command subst, got {:?}", other),
2437            },
2438            other => panic!("expected assignment, got {:?}", other),
2439        }
2440    }
2441
2442    #[test]
2443    fn parse_cmd_subst_pipeline() {
2444        let result = parse("X=$(cat file | grep pattern)").unwrap();
2445        match &result.statements[0] {
2446            Stmt::Assignment(a) => match &a.value {
2447                Expr::CommandSubst(pipeline) => {
2448                    assert_eq!(pipeline.commands.len(), 2);
2449                    assert_eq!(pipeline.commands[0].name, "cat");
2450                    assert_eq!(pipeline.commands[1].name, "grep");
2451                }
2452                other => panic!("expected command subst, got {:?}", other),
2453            },
2454            other => panic!("expected assignment, got {:?}", other),
2455        }
2456    }
2457
2458    #[test]
2459    fn parse_cmd_subst_in_condition() {
2460        // Shell-compatible: conditions are commands, not command substitutions
2461        let result = parse("if validate; then echo; fi").unwrap();
2462        match &result.statements[0] {
2463            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
2464                Expr::Command(cmd) => {
2465                    assert_eq!(cmd.name, "validate");
2466                }
2467                other => panic!("expected command, got {:?}", other),
2468            },
2469            other => panic!("expected if, got {:?}", other),
2470        }
2471    }
2472
2473    #[test]
2474    fn parse_cmd_subst_in_command_arg() {
2475        let result = parse("echo $(whoami)").unwrap();
2476        match &result.statements[0] {
2477            Stmt::Command(cmd) => {
2478                assert_eq!(cmd.name, "echo");
2479                match &cmd.args[0] {
2480                    Arg::Positional(Expr::CommandSubst(pipeline)) => {
2481                        assert_eq!(pipeline.commands[0].name, "whoami");
2482                    }
2483                    other => panic!("expected command subst, got {:?}", other),
2484                }
2485            }
2486            other => panic!("expected command, got {:?}", other),
2487        }
2488    }
2489
2490    // ═══════════════════════════════════════════════════════════════════════════
2491    // Logical Operator Tests (&&, ||)
2492    // ═══════════════════════════════════════════════════════════════════════════
2493
2494    #[test]
2495    fn parse_condition_and() {
2496        // Shell-compatible: commands chained with &&
2497        let result = parse("if check-a && check-b; then echo; fi").unwrap();
2498        match &result.statements[0] {
2499            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
2500                Expr::BinaryOp { left, op, right } => {
2501                    assert_eq!(*op, BinaryOp::And);
2502                    assert!(matches!(left.as_ref(), Expr::Command(_)));
2503                    assert!(matches!(right.as_ref(), Expr::Command(_)));
2504                }
2505                other => panic!("expected binary op, got {:?}", other),
2506            },
2507            other => panic!("expected if, got {:?}", other),
2508        }
2509    }
2510
2511    #[test]
2512    fn parse_condition_or() {
2513        let result = parse("if try-a || try-b; then echo; fi").unwrap();
2514        match &result.statements[0] {
2515            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
2516                Expr::BinaryOp { left, op, right } => {
2517                    assert_eq!(*op, BinaryOp::Or);
2518                    assert!(matches!(left.as_ref(), Expr::Command(_)));
2519                    assert!(matches!(right.as_ref(), Expr::Command(_)));
2520                }
2521                other => panic!("expected binary op, got {:?}", other),
2522            },
2523            other => panic!("expected if, got {:?}", other),
2524        }
2525    }
2526
2527    #[test]
2528    fn parse_condition_and_or_precedence() {
2529        // a && b || c should parse as (a && b) || c
2530        let result = parse("if cmd-a && cmd-b || cmd-c; then echo; fi").unwrap();
2531        match &result.statements[0] {
2532            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
2533                Expr::BinaryOp { left, op, right } => {
2534                    // Top level should be ||
2535                    assert_eq!(*op, BinaryOp::Or);
2536                    // Left side should be && expression
2537                    match left.as_ref() {
2538                        Expr::BinaryOp { op: inner_op, .. } => {
2539                            assert_eq!(*inner_op, BinaryOp::And);
2540                        }
2541                        other => panic!("expected binary op (&&), got {:?}", other),
2542                    }
2543                    // Right side should be command
2544                    assert!(matches!(right.as_ref(), Expr::Command(_)));
2545                }
2546                other => panic!("expected binary op, got {:?}", other),
2547            },
2548            other => panic!("expected if, got {:?}", other),
2549        }
2550    }
2551
2552    #[test]
2553    fn parse_condition_multiple_and() {
2554        let result = parse("if cmd-a && cmd-b && cmd-c; then echo; fi").unwrap();
2555        match &result.statements[0] {
2556            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
2557                Expr::BinaryOp { left, op, .. } => {
2558                    assert_eq!(*op, BinaryOp::And);
2559                    // Left side should also be &&
2560                    match left.as_ref() {
2561                        Expr::BinaryOp { op: inner_op, .. } => {
2562                            assert_eq!(*inner_op, BinaryOp::And);
2563                        }
2564                        other => panic!("expected binary op, got {:?}", other),
2565                    }
2566                }
2567                other => panic!("expected binary op, got {:?}", other),
2568            },
2569            other => panic!("expected if, got {:?}", other),
2570        }
2571    }
2572
2573    #[test]
2574    fn parse_condition_mixed_comparison_and_logical() {
2575        // Shell-compatible: use [[ ]] for comparisons, && to chain them
2576        let result = parse("if [[ ${X} == 5 ]] && [[ ${Y} -gt 0 ]]; then echo; fi").unwrap();
2577        match &result.statements[0] {
2578            Stmt::If(if_stmt) => match if_stmt.condition.as_ref() {
2579                Expr::BinaryOp { left, op, right } => {
2580                    assert_eq!(*op, BinaryOp::And);
2581                    // Left: [[ ${X} == 5 ]]
2582                    match left.as_ref() {
2583                        Expr::Test(test) => match test.as_ref() {
2584                            TestExpr::Comparison { op: left_op, .. } => {
2585                                assert_eq!(*left_op, TestCmpOp::Eq);
2586                            }
2587                            other => panic!("expected comparison, got {:?}", other),
2588                        },
2589                        other => panic!("expected test, got {:?}", other),
2590                    }
2591                    // Right: [[ ${Y} -gt 0 ]]
2592                    match right.as_ref() {
2593                        Expr::Test(test) => match test.as_ref() {
2594                            TestExpr::Comparison { op: right_op, .. } => {
2595                                assert_eq!(*right_op, TestCmpOp::Gt);
2596                            }
2597                            other => panic!("expected comparison, got {:?}", other),
2598                        },
2599                        other => panic!("expected test, got {:?}", other),
2600                    }
2601                }
2602                other => panic!("expected binary op, got {:?}", other),
2603            },
2604            other => panic!("expected if, got {:?}", other),
2605        }
2606    }
2607
2608    // ═══════════════════════════════════════════════════════════════════════════
2609    // Integration Tests - Complete Scripts
2610    // ═══════════════════════════════════════════════════════════════════════════
2611
2612    /// Level 1: Linear script using core features
2613    #[test]
2614    fn script_level1_linear() {
2615        let script = r#"
2616NAME="kaish"
2617VERSION=1
2618TIMEOUT=30
2619ITEMS="alpha beta gamma"
2620
2621echo "Starting ${NAME} v${VERSION}"
2622cat "README.md" | grep pattern="install" | head count=5
2623fetch url="https://api.example.com/status" timeout=${TIMEOUT} > "/tmp/status.json"
2624echo "Items: ${ITEMS}"
2625"#;
2626        let result = parse(script).unwrap();
2627        let stmts: Vec<_> = result.statements.iter()
2628            .filter(|s| !matches!(s, Stmt::Empty))
2629            .collect();
2630
2631        assert_eq!(stmts.len(), 8);
2632        assert!(matches!(stmts[0], Stmt::Assignment(_)));  // set NAME
2633        assert!(matches!(stmts[1], Stmt::Assignment(_)));  // set VERSION
2634        assert!(matches!(stmts[2], Stmt::Assignment(_)));  // set TIMEOUT
2635        assert!(matches!(stmts[3], Stmt::Assignment(_)));  // set ITEMS
2636        assert!(matches!(stmts[4], Stmt::Command(_)));     // echo "Starting..."
2637        assert!(matches!(stmts[5], Stmt::Pipeline(_)));    // cat | grep | head
2638        assert!(matches!(stmts[6], Stmt::Pipeline(_)));    // fetch (with redirect - Pipeline since it has redirects)
2639        assert!(matches!(stmts[7], Stmt::Command(_)));     // echo "Items: ${ITEMS}"
2640    }
2641
2642    /// Level 2: Script with conditionals (shell-compatible syntax)
2643    #[test]
2644    fn script_level2_branching() {
2645        let script = r#"
2646RESULT=$(validate "input.json")
2647
2648if [[ ${RESULT.ok} == true ]]; then
2649    echo "Validation passed"
2650    process "input.json" > "output.json"
2651else
2652    echo "Validation failed: ${RESULT.err}"
2653fi
2654
2655if [[ ${COUNT} -gt 0 ]] && [[ ${COUNT} -le 100 ]]; then
2656    echo "Count in valid range"
2657fi
2658
2659if check-network || check-cache; then
2660    fetch url=${URL}
2661fi
2662"#;
2663        let result = parse(script).unwrap();
2664        let stmts: Vec<_> = result.statements.iter()
2665            .filter(|s| !matches!(s, Stmt::Empty))
2666            .collect();
2667
2668        assert_eq!(stmts.len(), 4);
2669
2670        // First: assignment with command substitution
2671        match stmts[0] {
2672            Stmt::Assignment(a) => {
2673                assert_eq!(a.name, "RESULT");
2674                assert!(matches!(&a.value, Expr::CommandSubst(_)));
2675            }
2676            other => panic!("expected assignment, got {:?}", other),
2677        }
2678
2679        // Second: if/else
2680        match stmts[1] {
2681            Stmt::If(if_stmt) => {
2682                assert_eq!(if_stmt.then_branch.len(), 2);
2683                assert!(if_stmt.else_branch.is_some());
2684                assert_eq!(if_stmt.else_branch.as_ref().unwrap().len(), 1);
2685            }
2686            other => panic!("expected if, got {:?}", other),
2687        }
2688
2689        // Third: if with && condition
2690        match stmts[2] {
2691            Stmt::If(if_stmt) => {
2692                match if_stmt.condition.as_ref() {
2693                    Expr::BinaryOp { op, .. } => assert_eq!(*op, BinaryOp::And),
2694                    other => panic!("expected && condition, got {:?}", other),
2695                }
2696            }
2697            other => panic!("expected if, got {:?}", other),
2698        }
2699
2700        // Fourth: if with || of commands
2701        match stmts[3] {
2702            Stmt::If(if_stmt) => {
2703                match if_stmt.condition.as_ref() {
2704                    Expr::BinaryOp { op, left, right } => {
2705                        assert_eq!(*op, BinaryOp::Or);
2706                        assert!(matches!(left.as_ref(), Expr::Command(_)));
2707                        assert!(matches!(right.as_ref(), Expr::Command(_)));
2708                    }
2709                    other => panic!("expected || condition, got {:?}", other),
2710                }
2711            }
2712            other => panic!("expected if, got {:?}", other),
2713        }
2714    }
2715
2716    /// Level 3: Script with loops and function definitions
2717    #[test]
2718    fn script_level3_loops_and_functions() {
2719        let script = r#"
2720greet() {
2721    echo "Hello, $1!"
2722}
2723
2724fetch_all() {
2725    for URL in $@; do
2726        fetch url=${URL}
2727    done
2728}
2729
2730USERS="alice bob charlie"
2731
2732for USER in ${USERS}; do
2733    greet ${USER}
2734    if [[ ${USER} == "bob" ]]; then
2735        echo "Found Bob!"
2736    fi
2737done
2738
2739long-running-task &
2740"#;
2741        let result = parse(script).unwrap();
2742        let stmts: Vec<_> = result.statements.iter()
2743            .filter(|s| !matches!(s, Stmt::Empty))
2744            .collect();
2745
2746        assert_eq!(stmts.len(), 5);
2747
2748        // First function def
2749        match stmts[0] {
2750            Stmt::ToolDef(t) => {
2751                assert_eq!(t.name, "greet");
2752                assert!(t.params.is_empty());
2753            }
2754            other => panic!("expected function def, got {:?}", other),
2755        }
2756
2757        // Second function def with nested for loop
2758        match stmts[1] {
2759            Stmt::ToolDef(t) => {
2760                assert_eq!(t.name, "fetch_all");
2761                assert_eq!(t.body.len(), 1);
2762                assert!(matches!(&t.body[0], Stmt::For(_)));
2763            }
2764            other => panic!("expected function def, got {:?}", other),
2765        }
2766
2767        // Assignment
2768        assert!(matches!(stmts[2], Stmt::Assignment(_)));
2769
2770        // For loop with nested if
2771        match stmts[3] {
2772            Stmt::For(f) => {
2773                assert_eq!(f.variable, "USER");
2774                assert_eq!(f.body.len(), 2);
2775                assert!(matches!(&f.body[0], Stmt::Command(_)));
2776                assert!(matches!(&f.body[1], Stmt::If(_)));
2777            }
2778            other => panic!("expected for loop, got {:?}", other),
2779        }
2780
2781        // Background job
2782        match stmts[4] {
2783            Stmt::Pipeline(p) => {
2784                assert!(p.background);
2785                assert_eq!(p.commands[0].name, "long-running-task");
2786            }
2787            other => panic!("expected pipeline (background), got {:?}", other),
2788        }
2789    }
2790
2791    /// Level 4: Complex nested control flow (shell-compatible syntax)
2792    #[test]
2793    fn script_level4_complex_nesting() {
2794        let script = r#"
2795RESULT=$(cat "config.json" | jq query=".servers" | validate schema="server-schema.json")
2796
2797if ping host=${HOST} && [[ ${RESULT} == true ]]; then
2798    for SERVER in "prod-1 prod-2"; do
2799        deploy target=${SERVER} port=8080
2800        if [[ ${?.code} != 0 ]]; then
2801            notify channel="ops" message="Deploy failed"
2802        fi
2803    done
2804fi
2805"#;
2806        let result = parse(script).unwrap();
2807        let stmts: Vec<_> = result.statements.iter()
2808            .filter(|s| !matches!(s, Stmt::Empty))
2809            .collect();
2810
2811        assert_eq!(stmts.len(), 2);
2812
2813        // Command substitution with pipeline
2814        match stmts[0] {
2815            Stmt::Assignment(a) => {
2816                assert_eq!(a.name, "RESULT");
2817                match &a.value {
2818                    Expr::CommandSubst(pipeline) => {
2819                        assert_eq!(pipeline.commands.len(), 3);
2820                    }
2821                    other => panic!("expected command subst, got {:?}", other),
2822                }
2823            }
2824            other => panic!("expected assignment, got {:?}", other),
2825        }
2826
2827        // If with && condition, containing for loop with nested if
2828        match stmts[1] {
2829            Stmt::If(if_stmt) => {
2830                match if_stmt.condition.as_ref() {
2831                    Expr::BinaryOp { op, .. } => assert_eq!(*op, BinaryOp::And),
2832                    other => panic!("expected && condition, got {:?}", other),
2833                }
2834                assert_eq!(if_stmt.then_branch.len(), 1);
2835                match &if_stmt.then_branch[0] {
2836                    Stmt::For(f) => {
2837                        assert_eq!(f.body.len(), 2);
2838                        assert!(matches!(&f.body[1], Stmt::If(_)));
2839                    }
2840                    other => panic!("expected for in if body, got {:?}", other),
2841                }
2842            }
2843            other => panic!("expected if, got {:?}", other),
2844        }
2845    }
2846
2847    /// Level 5: Edge cases and parser stress test
2848    #[test]
2849    fn script_level5_edge_cases() {
2850        let script = r#"
2851echo ""
2852echo "quotes: \"nested\" here"
2853echo "escapes: \n\t\r\\"
2854echo "unicode: \u2764"
2855
2856X=-99999
2857Y=3.14159265358979
2858Z=-0.001
2859
2860cmd a=1 b="two" c=true d=false e=null
2861
2862if true; then
2863    if false; then
2864        echo "inner"
2865    else
2866        echo "else"
2867    fi
2868fi
2869
2870for I in "a b c"; do
2871    echo ${I}
2872done
2873
2874no_params() {
2875    echo "no params"
2876}
2877
2878function all_args {
2879    echo "args: $@"
2880}
2881
2882a | b | c | d | e &
2883cmd 2> "errors.log"
2884cmd &> "all.log"
2885cmd >> "append.log"
2886cmd < "input.txt"
2887"#;
2888        let result = parse(script).unwrap();
2889        let stmts: Vec<_> = result.statements.iter()
2890            .filter(|s| !matches!(s, Stmt::Empty))
2891            .collect();
2892
2893        // Verify it parses without error
2894        assert!(stmts.len() >= 10, "expected many statements, got {}", stmts.len());
2895
2896        // Background pipeline
2897        let bg_stmt = stmts.iter().find(|s| matches!(s, Stmt::Pipeline(p) if p.background));
2898        assert!(bg_stmt.is_some(), "expected background pipeline");
2899
2900        match bg_stmt.unwrap() {
2901            Stmt::Pipeline(p) => {
2902                assert_eq!(p.commands.len(), 5);
2903                assert!(p.background);
2904            }
2905            _ => unreachable!(),
2906        }
2907    }
2908
2909    // ═══════════════════════════════════════════════════════════════════════════
2910    // Edge Case Tests: Ambiguity Resolution
2911    // ═══════════════════════════════════════════════════════════════════════════
2912
2913    #[test]
2914    fn parse_keyword_as_variable_rejected() {
2915        // Keywords CANNOT be used as variable names - this is intentional
2916        // to avoid ambiguity. Use different names instead.
2917        let result = parse(r#"if="value""#);
2918        assert!(result.is_err(), "if= should fail - 'if' is a keyword");
2919
2920        let result = parse("while=true");
2921        assert!(result.is_err(), "while= should fail - 'while' is a keyword");
2922
2923        let result = parse(r#"then="next""#);
2924        assert!(result.is_err(), "then= should fail - 'then' is a keyword");
2925    }
2926
2927    #[test]
2928    fn parse_set_command_with_flag() {
2929        let result = parse("set -e");
2930        assert!(result.is_ok(), "failed to parse set -e: {:?}", result);
2931        let program = result.unwrap();
2932        match &program.statements[0] {
2933            Stmt::Command(cmd) => {
2934                assert_eq!(cmd.name, "set");
2935                assert_eq!(cmd.args.len(), 1);
2936                match &cmd.args[0] {
2937                    Arg::ShortFlag(f) => assert_eq!(f, "e"),
2938                    other => panic!("expected ShortFlag, got {:?}", other),
2939                }
2940            }
2941            other => panic!("expected Command, got {:?}", other),
2942        }
2943    }
2944
2945    #[test]
2946    fn parse_set_command_no_args() {
2947        let result = parse("set");
2948        assert!(result.is_ok(), "failed to parse set: {:?}", result);
2949        let program = result.unwrap();
2950        match &program.statements[0] {
2951            Stmt::Command(cmd) => {
2952                assert_eq!(cmd.name, "set");
2953                assert_eq!(cmd.args.len(), 0);
2954            }
2955            other => panic!("expected Command, got {:?}", other),
2956        }
2957    }
2958
2959    #[test]
2960    fn parse_set_assignment_vs_command() {
2961        // X=5 should be assignment
2962        let result = parse("X=5");
2963        assert!(result.is_ok());
2964        let program = result.unwrap();
2965        assert!(matches!(&program.statements[0], Stmt::Assignment(_)));
2966
2967        // set -e should be command
2968        let result = parse("set -e");
2969        assert!(result.is_ok());
2970        let program = result.unwrap();
2971        assert!(matches!(&program.statements[0], Stmt::Command(_)));
2972    }
2973
2974    #[test]
2975    fn parse_true_as_command() {
2976        let result = parse("true");
2977        assert!(result.is_ok());
2978        let program = result.unwrap();
2979        match &program.statements[0] {
2980            Stmt::Command(cmd) => assert_eq!(cmd.name, "true"),
2981            other => panic!("expected Command(true), got {:?}", other),
2982        }
2983    }
2984
2985    #[test]
2986    fn parse_false_as_command() {
2987        let result = parse("false");
2988        assert!(result.is_ok());
2989        let program = result.unwrap();
2990        match &program.statements[0] {
2991            Stmt::Command(cmd) => assert_eq!(cmd.name, "false"),
2992            other => panic!("expected Command(false), got {:?}", other),
2993        }
2994    }
2995
2996    #[test]
2997    fn parse_dot_as_source_alias() {
2998        let result = parse(". script.kai");
2999        assert!(result.is_ok(), "failed to parse . script.kai: {:?}", result);
3000        let program = result.unwrap();
3001        match &program.statements[0] {
3002            Stmt::Command(cmd) => {
3003                assert_eq!(cmd.name, ".");
3004                assert_eq!(cmd.args.len(), 1);
3005            }
3006            other => panic!("expected Command(.), got {:?}", other),
3007        }
3008    }
3009
3010    #[test]
3011    fn parse_source_command() {
3012        let result = parse("source utils.kai");
3013        assert!(result.is_ok(), "failed to parse source: {:?}", result);
3014        let program = result.unwrap();
3015        match &program.statements[0] {
3016            Stmt::Command(cmd) => {
3017                assert_eq!(cmd.name, "source");
3018                assert_eq!(cmd.args.len(), 1);
3019            }
3020            other => panic!("expected Command(source), got {:?}", other),
3021        }
3022    }
3023
3024    #[test]
3025    fn parse_test_expr_file_test() {
3026        // Paths must be quoted strings in test expressions
3027        let result = parse(r#"[[ -f "/path/file" ]]"#);
3028        assert!(result.is_ok(), "failed to parse file test: {:?}", result);
3029    }
3030
3031    #[test]
3032    fn parse_test_expr_comparison() {
3033        let result = parse(r#"[[ $X == "value" ]]"#);
3034        assert!(result.is_ok(), "failed to parse comparison test: {:?}", result);
3035    }
3036
3037    #[test]
3038    fn parse_test_expr_single_eq() {
3039        // = and == are equivalent inside [[ ]] (matching bash behavior)
3040        let result = parse(r#"[[ $X = "value" ]]"#);
3041        assert!(result.is_ok(), "failed to parse single-= comparison: {:?}", result);
3042        let program = result.unwrap();
3043        match &program.statements[0] {
3044            Stmt::Test(TestExpr::Comparison { op, .. }) => {
3045                assert_eq!(op, &TestCmpOp::Eq);
3046            }
3047            other => panic!("expected Test(Comparison), got {:?}", other),
3048        }
3049    }
3050
3051    #[test]
3052    fn parse_while_loop() {
3053        let result = parse("while true; do echo; done");
3054        assert!(result.is_ok(), "failed to parse while loop: {:?}", result);
3055        let program = result.unwrap();
3056        assert!(matches!(&program.statements[0], Stmt::While(_)));
3057    }
3058
3059    #[test]
3060    fn parse_break_with_level() {
3061        let result = parse("break 2");
3062        assert!(result.is_ok());
3063        let program = result.unwrap();
3064        match &program.statements[0] {
3065            Stmt::Break(Some(n)) => assert_eq!(*n, 2),
3066            other => panic!("expected Break(2), got {:?}", other),
3067        }
3068    }
3069
3070    #[test]
3071    fn parse_continue_with_level() {
3072        let result = parse("continue 3");
3073        assert!(result.is_ok());
3074        let program = result.unwrap();
3075        match &program.statements[0] {
3076            Stmt::Continue(Some(n)) => assert_eq!(*n, 3),
3077            other => panic!("expected Continue(3), got {:?}", other),
3078        }
3079    }
3080
3081    #[test]
3082    fn parse_exit_with_code() {
3083        let result = parse("exit 1");
3084        assert!(result.is_ok());
3085        let program = result.unwrap();
3086        match &program.statements[0] {
3087            Stmt::Exit(Some(expr)) => {
3088                match expr.as_ref() {
3089                    Expr::Literal(Value::Int(n)) => assert_eq!(*n, 1),
3090                    other => panic!("expected Int(1), got {:?}", other),
3091                }
3092            }
3093            other => panic!("expected Exit(1), got {:?}", other),
3094        }
3095    }
3096}