bashrs 6.66.0

Rust-to-Shell transpiler for deterministic bootstrap scripts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! Bash Abstract Syntax Tree
//!
//! Represents parsed bash scripts in a type-safe AST structure.
//! Designed to capture semantics needed for transpilation to Rash.

use serde::{Deserialize, Serialize};
use std::fmt;

/// Root AST node representing a complete bash script
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BashAst {
    pub statements: Vec<BashStmt>,
    pub metadata: AstMetadata,
}

/// Metadata about the parsed script
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AstMetadata {
    pub source_file: Option<String>,
    pub line_count: usize,
    pub parse_time_ms: u64,
}

/// Statement-level AST node
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BashStmt {
    /// Variable assignment: VAR=value or VAR[index]=value (F019: array element)
    Assignment {
        name: String,
        /// F019: Optional array index for element assignments like `hash[key]=value`
        index: Option<String>,
        value: BashExpr,
        exported: bool,
        span: Span,
    },

    /// Command execution: echo "hello"
    Command {
        name: String,
        args: Vec<BashExpr>,
        redirects: Vec<Redirect>,
        span: Span,
    },

    /// Function definition
    Function {
        name: String,
        body: Vec<BashStmt>,
        span: Span,
    },

    /// If statement
    If {
        condition: BashExpr,
        then_block: Vec<BashStmt>,
        elif_blocks: Vec<(BashExpr, Vec<BashStmt>)>,
        else_block: Option<Vec<BashStmt>>,
        span: Span,
    },

    /// While loop
    While {
        condition: BashExpr,
        body: Vec<BashStmt>,
        span: Span,
    },

    /// Until loop: until CONDITION; do BODY; done
    /// Note: Purified to `while ! CONDITION` for POSIX compatibility
    Until {
        condition: BashExpr,
        body: Vec<BashStmt>,
        span: Span,
    },

    /// For loop: for VAR in LIST; do BODY; done
    For {
        variable: String,
        items: BashExpr,
        body: Vec<BashStmt>,
        span: Span,
    },

    /// C-style for loop: for ((init; cond; incr)); do BODY; done
    /// Issue #68: Bash-specific construct, purified to POSIX while loop
    ForCStyle {
        /// Initialization expression (e.g., "i=0")
        init: String,
        /// Condition expression (e.g., "i<10")
        condition: String,
        /// Increment expression (e.g., "i++")
        increment: String,
        body: Vec<BashStmt>,
        span: Span,
    },

    /// Return statement
    Return { code: Option<BashExpr>, span: Span },

    /// Case statement: case WORD in PATTERN) BODY;; esac
    Case {
        word: BashExpr,
        arms: Vec<CaseArm>,
        span: Span,
    },

    /// Comment (preserved for documentation)
    Comment { text: String, span: Span },

    /// Pipeline: cmd1 | cmd2 | cmd3
    /// Chains multiple commands with stdout→stdin data flow
    Pipeline { commands: Vec<BashStmt>, span: Span },

    /// Logical AND list: cmd1 && cmd2
    /// Execute cmd2 only if cmd1 succeeds (exit code 0)
    /// Issue #59: Support for && operator after commands
    AndList {
        left: Box<BashStmt>,
        right: Box<BashStmt>,
        span: Span,
    },

    /// Logical OR list: cmd1 || cmd2
    /// Execute cmd2 only if cmd1 fails (non-zero exit code)
    /// Issue #59: Support for || operator after commands
    OrList {
        left: Box<BashStmt>,
        right: Box<BashStmt>,
        span: Span,
    },

    /// Brace group: { cmd1; cmd2; } or subshell: ( cmd1; cmd2 )
    /// Groups commands together as a compound command
    /// Issue #60: Support for brace groups in || and && contexts
    BraceGroup {
        body: Vec<BashStmt>,
        subshell: bool,
        span: Span,
    },

    /// Coprocess: coproc NAME { COMMAND; } or coproc { COMMAND; }
    /// Runs command asynchronously in a subprocess with bidirectional pipes
    /// BUG-018: Added coproc keyword support
    Coproc {
        name: Option<String>,
        body: Vec<BashStmt>,
        span: Span,
    },

    /// Select statement: select VAR in WORDS; do COMMANDS; done
    /// F017: Interactive menu selection loop (bash-specific)
    /// Presents numbered menu from WORDS, user selects, VAR is set, COMMANDS run
    Select {
        variable: String,
        items: BashExpr,
        body: Vec<BashStmt>,
        span: Span,
    },

    /// Negated command/pipeline: ! command
    /// Inverts the exit status of the command or pipeline
    /// Issue #133: Support for `if ! cmd1 | cmd2; then` patterns
    Negated { command: Box<BashStmt>, span: Span },
}

/// Case statement arm
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CaseArm {
    pub patterns: Vec<String>,
    pub body: Vec<BashStmt>,
}

/// Expression-level AST node
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BashExpr {
    /// String literal
    Literal(String),

    /// Variable reference: $VAR or ${VAR}
    Variable(String),

    /// Command substitution: $(cmd) or `cmd`
    CommandSubst(Box<BashStmt>),

    /// Arithmetic expansion: $((expr))
    Arithmetic(Box<ArithExpr>),

    /// Array/list: (item1 item2 item3)
    Array(Vec<BashExpr>),

    /// String concatenation
    Concat(Vec<BashExpr>),

    /// Test expression: [ expr ]
    Test(Box<TestExpr>),

    /// Glob pattern: *.txt
    Glob(String),

    /// Command condition: a command used as a condition in if/while
    /// The exit code of the command determines the condition result (0=true, non-zero=false)
    /// Example: `if grep -q pattern file; then ...`
    CommandCondition(Box<BashStmt>),

    /// Default value expansion: ${VAR:-default}
    /// If variable is unset or null, use default value
    DefaultValue {
        variable: String,
        default: Box<BashExpr>,
    },

    /// Assign default value expansion: ${VAR:=default}
    /// If variable is unset or null, assign default value to variable and use it
    AssignDefault {
        variable: String,
        default: Box<BashExpr>,
    },

    /// Error if unset expansion: ${VAR:?message}
    /// If variable is unset or null, exit with error message
    ErrorIfUnset {
        variable: String,
        message: Box<BashExpr>,
    },

    /// Alternative value expansion: ${VAR:+alt_value}
    /// If variable is set and non-null, use alt_value, otherwise empty string
    AlternativeValue {
        variable: String,
        alternative: Box<BashExpr>,
    },

    /// String length expansion: ${#VAR}
    /// Get the length of the string value of variable
    StringLength { variable: String },

    /// Remove suffix expansion: ${VAR%pattern}
    /// Remove shortest matching suffix pattern from variable
    RemoveSuffix {
        variable: String,
        pattern: Box<BashExpr>,
    },

    /// Remove prefix expansion: ${VAR#pattern}
    /// Remove shortest matching prefix pattern from variable
    RemovePrefix {
        variable: String,
        pattern: Box<BashExpr>,
    },

    /// Remove longest prefix expansion: ${VAR##pattern}
    /// Remove longest matching prefix pattern from variable (greedy)
    RemoveLongestPrefix {
        variable: String,
        pattern: Box<BashExpr>,
    },

    /// Remove longest suffix expansion: ${VAR%%pattern}
    /// Remove longest matching suffix pattern from variable (greedy)
    RemoveLongestSuffix {
        variable: String,
        pattern: Box<BashExpr>,
    },
}

/// Redirection operator
/// Represents I/O redirection for commands (>, >>, <, etc.)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Redirect {
    /// Output redirection: > file
    /// Redirects stdout to file (creates or truncates)
    Output { target: BashExpr },

    /// Append redirection: >> file
    /// Redirects stdout to file (creates or appends)
    Append { target: BashExpr },

    /// Input redirection: < file
    /// Redirects file contents to stdin
    Input { target: BashExpr },

    /// Error redirection: 2> file
    /// Redirects stderr to file
    Error { target: BashExpr },

    /// Append error redirection: 2>> file
    /// Appends stderr to file (creates or appends)
    AppendError { target: BashExpr },

    /// Combined redirection: &> file (bash-specific)
    /// Redirects both stdout and stderr to file
    /// Note: Purified to POSIX as: >file 2>&1
    Combined { target: BashExpr },

    /// File descriptor duplication: 2>&1
    /// Duplicates from_fd to to_fd
    Duplicate { from_fd: i32, to_fd: i32 },

    /// Here-string: <<< "string" (Issue #61)
    /// Provides a string to stdin without needing a heredoc
    /// Note: This is a bash-specific feature, not POSIX
    HereString { content: String },
}

/// Arithmetic expression
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ArithExpr {
    Number(i64),
    Variable(String),
    Add(Box<ArithExpr>, Box<ArithExpr>),
    Sub(Box<ArithExpr>, Box<ArithExpr>),
    Mul(Box<ArithExpr>, Box<ArithExpr>),
    Div(Box<ArithExpr>, Box<ArithExpr>),
    Mod(Box<ArithExpr>, Box<ArithExpr>),
}

/// Test expression (conditional)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TestExpr {
    /// String comparison
    StringEq(BashExpr, BashExpr),
    StringNe(BashExpr, BashExpr),

    /// Integer comparison
    IntEq(BashExpr, BashExpr),
    IntNe(BashExpr, BashExpr),
    IntLt(BashExpr, BashExpr),
    IntLe(BashExpr, BashExpr),
    IntGt(BashExpr, BashExpr),
    IntGe(BashExpr, BashExpr),

    /// File tests
    FileExists(BashExpr),
    FileReadable(BashExpr),
    FileWritable(BashExpr),
    FileExecutable(BashExpr),
    FileDirectory(BashExpr),

    /// String tests
    StringEmpty(BashExpr),
    StringNonEmpty(BashExpr),

    /// Logical operations
    And(Box<TestExpr>, Box<TestExpr>),
    Or(Box<TestExpr>, Box<TestExpr>),
    Not(Box<TestExpr>),
}

/// Source code span for error reporting
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Span {
    pub start_line: usize,
    pub start_col: usize,
    pub end_line: usize,
    pub end_col: usize,
}

impl Span {
    pub fn new(start_line: usize, start_col: usize, end_line: usize, end_col: usize) -> Self {
        Self {
            start_line,
            start_col,
            end_line,
            end_col,
        }
    }

    pub fn dummy() -> Self {
        Self::new(0, 0, 0, 0)
    }
}

impl BashStmt {
    /// Get the node type as a string (for tracing/debugging)
    pub fn node_type(&self) -> &str {
        match self {
            BashStmt::Assignment { .. } => "Assignment",
            BashStmt::Command { .. } => "Command",
            BashStmt::Function { .. } => "Function",
            BashStmt::If { .. } => "If",
            BashStmt::While { .. } => "While",
            BashStmt::Until { .. } => "Until",
            BashStmt::For { .. } => "For",
            BashStmt::ForCStyle { .. } => "ForCStyle",
            BashStmt::Case { .. } => "Case",
            BashStmt::Return { .. } => "Return",
            BashStmt::Comment { .. } => "Comment",
            BashStmt::Pipeline { .. } => "Pipeline",
            BashStmt::AndList { .. } => "AndList",
            BashStmt::OrList { .. } => "OrList",
            BashStmt::BraceGroup { .. } => "BraceGroup",
            BashStmt::Coproc { .. } => "Coproc",
            BashStmt::Select { .. } => "Select",
            BashStmt::Negated { .. } => "Negated",
        }
    }

    /// Get the source span for this statement
    pub fn span(&self) -> crate::tracing::Span {
        let ast_span = match self {
            BashStmt::Assignment { span, .. }
            | BashStmt::Command { span, .. }
            | BashStmt::Function { span, .. }
            | BashStmt::If { span, .. }
            | BashStmt::While { span, .. }
            | BashStmt::Until { span, .. }
            | BashStmt::For { span, .. }
            | BashStmt::ForCStyle { span, .. }
            | BashStmt::Case { span, .. }
            | BashStmt::Return { span, .. }
            | BashStmt::Comment { span, .. }
            | BashStmt::Pipeline { span, .. }
            | BashStmt::AndList { span, .. }
            | BashStmt::OrList { span, .. }
            | BashStmt::BraceGroup { span, .. }
            | BashStmt::Coproc { span, .. }
            | BashStmt::Select { span, .. }
            | BashStmt::Negated { span, .. } => *span,
        };

        // Convert bash_parser::Span to tracing::Span
        crate::tracing::Span::new(
            ast_span.start_line,
            ast_span.start_col,
            ast_span.end_line,
            ast_span.end_col,
        )
    }
}

impl fmt::Display for BashStmt {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BashStmt::Assignment { name, .. } => write!(f, "Assignment({})", name),
            BashStmt::Command { name, .. } => write!(f, "Command({})", name),
            BashStmt::Function { name, .. } => write!(f, "Function({})", name),
            BashStmt::If { .. } => write!(f, "If"),
            BashStmt::While { .. } => write!(f, "While"),
            BashStmt::Until { .. } => write!(f, "Until"),
            BashStmt::For { variable, .. } => write!(f, "For({})", variable),
            BashStmt::ForCStyle { .. } => write!(f, "ForCStyle"),
            BashStmt::Case { .. } => write!(f, "Case"),
            BashStmt::Return { .. } => write!(f, "Return"),
            BashStmt::Comment { .. } => write!(f, "Comment"),
            BashStmt::Pipeline { commands, .. } => write!(f, "Pipeline({} cmds)", commands.len()),
            BashStmt::AndList { .. } => write!(f, "AndList"),
            BashStmt::OrList { .. } => write!(f, "OrList"),
            BashStmt::BraceGroup { body, .. } => write!(f, "BraceGroup({} stmts)", body.len()),
            BashStmt::Coproc { name, body, .. } => {
                if let Some(n) = name {
                    write!(f, "Coproc({}, {} stmts)", n, body.len())
                } else {
                    write!(f, "Coproc({} stmts)", body.len())
                }
            }
            BashStmt::Select { variable, .. } => write!(f, "Select({})", variable),
            BashStmt::Negated { command, .. } => write!(f, "Negated({})", command),
        }
    }
}

/// Wrapper type for AST nodes
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BashNode<T> {
    pub node: T,
    pub span: Span,
}

impl<T> BashNode<T> {
    pub fn new(node: T, span: Span) -> Self {
        Self { node, span }
    }
}

#[cfg(test)]
mod tests {
    use super::*;


    include!("ast_part2_incl2.rs");
}