Skip to main content

kaish_kernel/ast/
types.rs

1//! AST type definitions.
2
3use std::fmt;
4
5/// A complete kaish program is a sequence of statements.
6#[derive(Debug, Clone, PartialEq)]
7pub struct Program {
8    pub statements: Vec<Stmt>,
9}
10
11/// A single statement in kaish.
12#[derive(Debug, Clone, PartialEq)]
13pub enum Stmt {
14    /// Variable assignment: `NAME=value` or `local NAME = value`
15    Assignment(Assignment),
16    /// Simple command: `tool arg1 arg2`
17    Command(Command),
18    /// Pipeline: `a | b | c`
19    Pipeline(Pipeline),
20    /// Conditional: `if cond; then ...; fi`
21    If(IfStmt),
22    /// Loop: `for X in items; do ...; done`
23    For(ForLoop),
24    /// While loop: `while cond; do ...; done`
25    While(WhileLoop),
26    /// Case statement: `case expr in pattern) ... ;; esac`
27    Case(CaseStmt),
28    /// Break out of loop: `break` or `break N`
29    Break(Option<usize>),
30    /// Continue to next iteration: `continue` or `continue N`
31    Continue(Option<usize>),
32    /// Return from tool: `return` or `return expr`
33    Return(Option<Box<Expr>>),
34    /// Exit the script: `exit` or `exit code`
35    Exit(Option<Box<Expr>>),
36    /// Tool definition: `tool name(params) { body }`
37    ToolDef(ToolDef),
38    /// Test expression: `[[ -f path ]]` or `[[ $X == "value" ]]`
39    Test(TestExpr),
40    /// Statement chain with `&&`: run right only if left succeeds
41    AndChain { left: Box<Stmt>, right: Box<Stmt> },
42    /// Statement chain with `||`: run right only if left fails
43    OrChain { left: Box<Stmt>, right: Box<Stmt> },
44    /// Empty statement (newline or semicolon only)
45    Empty,
46}
47
48impl Stmt {
49    /// Human-readable variant name for tracing spans.
50    pub fn kind_name(&self) -> &'static str {
51        match self {
52            Stmt::Assignment(_) => "assignment",
53            Stmt::Command(_) => "command",
54            Stmt::Pipeline(_) => "pipeline",
55            Stmt::If(_) => "if",
56            Stmt::For(_) => "for",
57            Stmt::While(_) => "while",
58            Stmt::Case(_) => "case",
59            Stmt::Break(_) => "break",
60            Stmt::Continue(_) => "continue",
61            Stmt::Return(_) => "return",
62            Stmt::Exit(_) => "exit",
63            Stmt::ToolDef(_) => "tooldef",
64            Stmt::Test(_) => "test",
65            Stmt::AndChain { .. } => "and_chain",
66            Stmt::OrChain { .. } => "or_chain",
67            Stmt::Empty => "empty",
68        }
69    }
70}
71
72/// Variable assignment: `NAME=value` (bash-style) or `local NAME = value` (scoped)
73#[derive(Debug, Clone, PartialEq)]
74pub struct Assignment {
75    pub name: String,
76    pub value: Expr,
77    /// True if declared with `local` keyword (explicit local scope)
78    pub local: bool,
79}
80
81/// A command invocation with arguments and redirections.
82#[derive(Debug, Clone, PartialEq)]
83pub struct Command {
84    pub name: String,
85    pub args: Vec<Arg>,
86    pub redirects: Vec<Redirect>,
87}
88
89/// A pipeline of commands connected by pipes.
90#[derive(Debug, Clone, PartialEq)]
91pub struct Pipeline {
92    pub commands: Vec<Command>,
93    pub background: bool,
94}
95
96/// Conditional statement.
97#[derive(Debug, Clone, PartialEq)]
98pub struct IfStmt {
99    pub condition: Box<Expr>,
100    pub then_branch: Vec<Stmt>,
101    pub else_branch: Option<Vec<Stmt>>,
102}
103
104/// For loop over items.
105#[derive(Debug, Clone, PartialEq)]
106pub struct ForLoop {
107    pub variable: String,
108    /// Items to iterate over. Each is evaluated, then word-split for iteration.
109    pub items: Vec<Expr>,
110    pub body: Vec<Stmt>,
111}
112
113/// While loop with condition.
114#[derive(Debug, Clone, PartialEq)]
115pub struct WhileLoop {
116    pub condition: Box<Expr>,
117    pub body: Vec<Stmt>,
118}
119
120/// Case statement for pattern matching.
121///
122/// ```kaish
123/// case $VAR in
124///     pattern1) commands ;;
125///     pattern2|pattern3) commands ;;
126///     *) default ;;
127/// esac
128/// ```
129#[derive(Debug, Clone, PartialEq)]
130pub struct CaseStmt {
131    /// The expression to match against
132    pub expr: Expr,
133    /// The pattern branches
134    pub branches: Vec<CaseBranch>,
135}
136
137/// A single branch in a case statement.
138#[derive(Debug, Clone, PartialEq)]
139pub struct CaseBranch {
140    /// Glob patterns to match (separated by `|`)
141    pub patterns: Vec<String>,
142    /// Commands to execute if matched
143    pub body: Vec<Stmt>,
144}
145
146/// User-defined tool.
147#[derive(Debug, Clone, PartialEq)]
148pub struct ToolDef {
149    pub name: String,
150    pub params: Vec<ParamDef>,
151    pub body: Vec<Stmt>,
152}
153
154/// Parameter definition for a tool.
155#[derive(Debug, Clone, PartialEq)]
156pub struct ParamDef {
157    pub name: String,
158    pub param_type: Option<ParamType>,
159    pub default: Option<Expr>,
160}
161
162/// Parameter type annotation.
163#[derive(Debug, Clone, PartialEq)]
164pub enum ParamType {
165    String,
166    Int,
167    Float,
168    Bool,
169}
170
171/// A command argument (positional or named).
172#[derive(Debug, Clone, PartialEq)]
173pub enum Arg {
174    /// Positional argument: `value`
175    Positional(Expr),
176    /// Named argument: `key=value`
177    Named { key: String, value: Expr },
178    /// Short flag: `-l`, `-v` (boolean flag)
179    ShortFlag(String),
180    /// Long flag: `--force`, `--verbose` (boolean flag)
181    LongFlag(String),
182    /// Double-dash marker: `--` - signals end of flags
183    DoubleDash,
184}
185
186/// I/O redirection.
187#[derive(Debug, Clone, PartialEq)]
188pub struct Redirect {
189    pub kind: RedirectKind,
190    pub target: Expr,
191}
192
193/// Type of redirection.
194#[derive(Debug, Clone, PartialEq)]
195pub enum RedirectKind {
196    /// `>` stdout to file (overwrite)
197    StdoutOverwrite,
198    /// `>>` stdout to file (append)
199    StdoutAppend,
200    /// `<` stdin from file
201    Stdin,
202    /// `<<EOF ... EOF` stdin from here-doc
203    HereDoc,
204    /// `2>` stderr to file
205    Stderr,
206    /// `&>` both stdout and stderr to file
207    Both,
208    /// `2>&1` merge stderr into stdout
209    MergeStderr,
210    /// `1>&2` or `>&2` merge stdout into stderr
211    MergeStdout,
212}
213
214/// An expression that evaluates to a value.
215#[derive(Debug, Clone, PartialEq)]
216pub enum Expr {
217    /// Literal value
218    Literal(Value),
219    /// Variable reference: `${VAR}` or `${VAR.field}` or `$VAR`
220    VarRef(VarPath),
221    /// String with interpolation: `"hello ${NAME}"` or `"hello $NAME"`
222    Interpolated(Vec<StringPart>),
223    /// Binary operation: `a && b`, `a || b`
224    BinaryOp {
225        left: Box<Expr>,
226        op: BinaryOp,
227        right: Box<Expr>,
228    },
229    /// Command substitution: `$(pipeline)` - runs a pipeline and returns its result
230    CommandSubst(Box<Pipeline>),
231    /// Test expression: `[[ -f path ]]` or `[[ $X == "value" ]]`
232    Test(Box<TestExpr>),
233    /// Positional parameter: `$0` through `$9`
234    Positional(usize),
235    /// All positional arguments: `$@`
236    AllArgs,
237    /// Argument count: `$#`
238    ArgCount,
239    /// Variable string length: `${#VAR}`
240    VarLength(String),
241    /// Variable with default: `${VAR:-default}` - use default if VAR is unset or empty
242    /// The default can contain nested variable expansions and command substitutions
243    VarWithDefault { name: String, default: Vec<StringPart> },
244    /// Arithmetic expansion: `$((expr))` - evaluates to integer
245    Arithmetic(String),
246    /// Command as condition: `if grep -q pattern file; then` - exit code determines truthiness
247    Command(Command),
248    /// Last exit code: `$?`
249    LastExitCode,
250    /// Current shell PID: `$$`
251    CurrentPid,
252    /// Bare glob pattern: `*.txt`, `src/**/*.rs` — expanded during arg building
253    GlobPattern(String),
254}
255
256/// Test expression for `[[ ... ]]` conditionals.
257#[derive(Debug, Clone, PartialEq)]
258pub enum TestExpr {
259    /// File test: `[[ -f path ]]`, `[[ -d path ]]`, etc.
260    FileTest { op: FileTestOp, path: Box<Expr> },
261    /// String test: `[[ -z str ]]`, `[[ -n str ]]`
262    StringTest { op: StringTestOp, value: Box<Expr> },
263    /// Comparison: `[[ $X == "value" ]]`, `[[ $NUM -gt 5 ]]`
264    Comparison { left: Box<Expr>, op: TestCmpOp, right: Box<Expr> },
265    /// Logical AND: `[[ -f a && -d b ]]` (short-circuit evaluation)
266    And { left: Box<TestExpr>, right: Box<TestExpr> },
267    /// Logical OR: `[[ -f a || -d b ]]` (short-circuit evaluation)
268    Or { left: Box<TestExpr>, right: Box<TestExpr> },
269    /// Logical NOT: `[[ ! -f file ]]`
270    Not { expr: Box<TestExpr> },
271}
272
273/// File test operators for `[[ ]]`.
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275pub enum FileTestOp {
276    /// `-e` - exists
277    Exists,
278    /// `-f` - is regular file
279    IsFile,
280    /// `-d` - is directory
281    IsDir,
282    /// `-r` - is readable
283    Readable,
284    /// `-w` - is writable
285    Writable,
286    /// `-x` - is executable
287    Executable,
288}
289
290/// String test operators for `[[ ]]`.
291#[derive(Debug, Clone, Copy, PartialEq, Eq)]
292pub enum StringTestOp {
293    /// `-z` - string is empty
294    IsEmpty,
295    /// `-n` - string is non-empty
296    IsNonEmpty,
297}
298
299/// Comparison operators for `[[ ]]` tests.
300#[derive(Debug, Clone, Copy, PartialEq, Eq)]
301pub enum TestCmpOp {
302    /// `==` - string equality
303    Eq,
304    /// `!=` - string inequality
305    NotEq,
306    /// `=~` - regex match
307    Match,
308    /// `!~` - regex not match
309    NotMatch,
310    /// `-gt` - greater than (numeric)
311    Gt,
312    /// `-lt` - less than (numeric)
313    Lt,
314    /// `-ge` - greater than or equal (numeric)
315    GtEq,
316    /// `-le` - less than or equal (numeric)
317    LtEq,
318}
319
320// Value and BlobRef live in kaish-types.
321pub use kaish_types::{BlobRef, Value};
322
323/// Variable reference path: `${VAR}` or `${?.field}` for special variables.
324///
325/// Simple variable references support only field access for special variables
326/// like `$?`. Array indexing is not supported - use `jq` for JSON processing.
327#[derive(Debug, Clone, PartialEq)]
328pub struct VarPath {
329    pub segments: Vec<VarSegment>,
330}
331
332impl VarPath {
333    /// Create a simple variable reference with just a name.
334    pub fn simple(name: impl Into<String>) -> Self {
335        Self {
336            segments: vec![VarSegment::Field(name.into())],
337        }
338    }
339}
340
341/// A segment in a variable path.
342#[derive(Debug, Clone, PartialEq)]
343pub enum VarSegment {
344    /// Field access: `.field` or initial name
345    /// Only supported for special variables like `$?`
346    Field(String),
347}
348
349/// Part of an interpolated string.
350#[derive(Debug, Clone, PartialEq)]
351pub enum StringPart {
352    /// Literal text
353    Literal(String),
354    /// Variable interpolation: `${VAR}` or `$VAR`
355    Var(VarPath),
356    /// Variable with default: `${VAR:-default}` where default can contain nested expansions
357    VarWithDefault { name: String, default: Vec<StringPart> },
358    /// Variable string length: `${#VAR}`
359    VarLength(String),
360    /// Positional parameter: `$0`, `$1`, ..., `$9`
361    Positional(usize),
362    /// All arguments: `$@`
363    AllArgs,
364    /// Argument count: `$#`
365    ArgCount,
366    /// Arithmetic expansion: `$((expr))`
367    Arithmetic(String),
368    /// Command substitution: `$(pipeline)` embedded in a string
369    CommandSubst(Pipeline),
370    /// Last exit code: `$?`
371    LastExitCode,
372    /// Current shell PID: `$$`
373    CurrentPid,
374}
375
376/// Binary operators.
377#[derive(Debug, Clone, Copy, PartialEq, Eq)]
378pub enum BinaryOp {
379    /// `&&` - logical and (short-circuit)
380    And,
381    /// `||` - logical or (short-circuit)
382    Or,
383    /// `==` - equality
384    Eq,
385    /// `!=` - inequality
386    NotEq,
387    /// `=~` - regex match
388    Match,
389    /// `!~` - regex not match
390    NotMatch,
391    /// `<` - less than
392    Lt,
393    /// `>` - greater than
394    Gt,
395    /// `<=` - less than or equal
396    LtEq,
397    /// `>=` - greater than or equal
398    GtEq,
399}
400
401impl fmt::Display for BinaryOp {
402    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
403        match self {
404            BinaryOp::And => write!(f, "&&"),
405            BinaryOp::Or => write!(f, "||"),
406            BinaryOp::Eq => write!(f, "=="),
407            BinaryOp::NotEq => write!(f, "!="),
408            BinaryOp::Match => write!(f, "=~"),
409            BinaryOp::NotMatch => write!(f, "!~"),
410            BinaryOp::Lt => write!(f, "<"),
411            BinaryOp::Gt => write!(f, ">"),
412            BinaryOp::LtEq => write!(f, "<="),
413            BinaryOp::GtEq => write!(f, ">="),
414        }
415    }
416}
417
418impl fmt::Display for RedirectKind {
419    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
420        match self {
421            RedirectKind::StdoutOverwrite => write!(f, ">"),
422            RedirectKind::StdoutAppend => write!(f, ">>"),
423            RedirectKind::Stdin => write!(f, "<"),
424            RedirectKind::HereDoc => write!(f, "<<"),
425            RedirectKind::Stderr => write!(f, "2>"),
426            RedirectKind::Both => write!(f, "&>"),
427            RedirectKind::MergeStderr => write!(f, "2>&1"),
428            RedirectKind::MergeStdout => write!(f, "1>&2"),
429        }
430    }
431}
432
433impl fmt::Display for FileTestOp {
434    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
435        match self {
436            FileTestOp::Exists => write!(f, "-e"),
437            FileTestOp::IsFile => write!(f, "-f"),
438            FileTestOp::IsDir => write!(f, "-d"),
439            FileTestOp::Readable => write!(f, "-r"),
440            FileTestOp::Writable => write!(f, "-w"),
441            FileTestOp::Executable => write!(f, "-x"),
442        }
443    }
444}
445
446impl fmt::Display for StringTestOp {
447    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
448        match self {
449            StringTestOp::IsEmpty => write!(f, "-z"),
450            StringTestOp::IsNonEmpty => write!(f, "-n"),
451        }
452    }
453}
454
455impl fmt::Display for TestCmpOp {
456    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
457        match self {
458            TestCmpOp::Eq => write!(f, "=="),
459            TestCmpOp::NotEq => write!(f, "!="),
460            TestCmpOp::Match => write!(f, "=~"),
461            TestCmpOp::NotMatch => write!(f, "!~"),
462            TestCmpOp::Gt => write!(f, "-gt"),
463            TestCmpOp::Lt => write!(f, "-lt"),
464            TestCmpOp::GtEq => write!(f, "-ge"),
465            TestCmpOp::LtEq => write!(f, "-le"),
466        }
467    }
468}