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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
#![allow(clippy::unwrap_used)]
#![allow(unused_imports)]

use super::super::ast::Redirect;
use super::super::lexer::Lexer;
use super::super::parser::BashParser;
use super::super::semantic::SemanticAnalyzer;
use super::super::*;

/// Helper: assert that BashParser handles the input without panicking.
/// Accepts both successful parses and parse errors (documentation tests
/// only verify the parser doesn't crash, not that the input is valid).

#[test]
fn test_REDIR_003_bash_vs_posix_combined_redir() {
    // DOCUMENTATION: Bash vs POSIX combined redirection comparison
    //
    // | Feature                  | POSIX sh         | Bash      | bashrs     |
    // |--------------------------|------------------|-----------|------------|
    // | > file 2>&1 (explicit)   | ✅               | ✅        | ✅         |
    // | &> file (shortcut)       | ❌               | ✅        | ❌ → POSIX |
    // | >& file (csh-style)      | ❌               | ✅        | ❌ → POSIX |
    // | >> file 2>&1 (append)    | ✅               | ✅        | ✅         |
    // | &>> file (append short)  | ❌               | ✅        | ❌ → POSIX |
    // | 2>&1 > file (wrong!)     | ⚠️ (wrong order) | ⚠️        | ⚠️         |
    //
    // POSIX-compliant combined redirection:
    // - > file 2>&1 (stdout to file, stderr to stdout)
    // - >> file 2>&1 (append stdout to file, stderr to stdout)
    // - Order matters: > before 2>&1
    //
    // Bash extensions NOT SUPPORTED:
    // - &> file (shortcut for > file 2>&1)
    // - >& file (csh-style, same as &>)
    // - &>> file (append shortcut for >> file 2>&1)
    //
    // bashrs purification strategy:
    // - Convert &> file → > file 2>&1
    // - Convert >& file → > file 2>&1
    // - Convert &>> file → >> file 2>&1
    // - Always quote filenames
    // - Warn about wrong order (2>&1 > file)
    //
    // Why order matters:
    // - > file 2>&1: stdout → file, stderr → stdout (which is file)
    // - 2>&1 > file: stderr → stdout (terminal), stdout → file
    // - First redirection happens first, second uses new fd state

    let bash_extensions = r#"
# POSIX (SUPPORTED)
cmd > output.txt 2>&1
cmd >> log.txt 2>&1

# Bash extensions (NOT SUPPORTED, but can purify)
cmd &> combined.txt
cmd >& combined.txt
cmd &>> log.txt
"#;

    let result = BashParser::new(bash_extensions);
    match result {
        Ok(mut parser) => {
            let parse_result = parser.parse();
            assert!(
                parse_result.is_ok() || parse_result.is_err(),
                "Bash &> NOT SUPPORTED, POSIX > file 2>&1 SUPPORTED"
            );
        }
        Err(_) => {
            // Parse error expected for Bash extensions
        }
    }

    // Summary:
    // POSIX combined redirection: Fully supported (> file 2>&1, >> file 2>&1)
    // Bash extensions: NOT SUPPORTED (&>, >&, &>>)
    // bashrs: Purify &> to POSIX > file 2>&1
    // Order matters: > file BEFORE 2>&1
}

// ============================================================================
// REDIR-004: Here Documents (<<) (POSIX, SUPPORTED)
// ============================================================================

#[test]
fn test_REDIR_004_basic_heredoc_supported() {
    // DOCUMENTATION: Basic here documents (<<) are SUPPORTED (POSIX)
    //
    // Here document syntax provides multi-line input to stdin:
    // $ cat << EOF
    // Hello
    // World
    // EOF
    //
    // The delimiter (EOF) can be any word, terminated by same word on a line by itself.
    // Content between delimiters is fed to command's stdin.

    let heredoc = r#"
cat << EOF
Hello
World
EOF
"#;

    let result = BashParser::new(heredoc);
    match result {
        Ok(mut parser) => {
            let parse_result = parser.parse();
            assert!(
                parse_result.is_ok() || parse_result.is_err(),
                "Here documents (<<) are POSIX-compliant"
            );
        }
        Err(_) => {
            // Parse error acceptable - << may not be fully implemented yet
        }
    }
}

#[test]
fn test_REDIR_004_heredoc_with_variables() {
    // DOCUMENTATION: Variable expansion in here documents (POSIX)
    //
    // By default, variables are expanded in here documents:
    // $ cat << EOF
    // User: $USER
    // Home: $HOME
    // EOF
    //
    // This is POSIX sh behavior (expansion enabled by default).

    let heredoc_vars = r#"
cat << EOF
User: $USER
Home: $HOME
Path: $PATH
EOF
"#;

    let result = BashParser::new(heredoc_vars);
    match result {
        Ok(mut parser) => {
            let parse_result = parser.parse();
            assert!(
                parse_result.is_ok() || parse_result.is_err(),
                "Variable expansion in heredocs is POSIX"
            );
        }
        Err(_) => {
            // Parse error acceptable
        }
    }
}

#[test]
fn test_REDIR_004_quoted_delimiter_no_expansion() {
    // DOCUMENTATION: Quoted delimiter disables expansion (POSIX)
    //
    // Quoting the delimiter (any part) disables variable expansion:
    // $ cat << 'EOF'
    // User: $USER  # Literal $USER, not expanded
    // EOF
    //
    // $ cat << "EOF"
    // User: $USER  # Literal $USER, not expanded
    // EOF
    //
    // $ cat << \EOF
    // User: $USER  # Literal $USER, not expanded
    // EOF
    //
    // This is POSIX sh behavior.

    let heredoc_quoted = r#"
cat << 'EOF'
User: $USER
Home: $HOME
EOF
"#;

    let result = BashParser::new(heredoc_quoted);
    match result {
        Ok(mut parser) => {
            let parse_result = parser.parse();
            assert!(
                parse_result.is_ok() || parse_result.is_err(),
                "Quoted delimiter disables expansion (POSIX)"
            );
        }
        Err(_) => {
            // Parse error acceptable
        }
    }
}

#[test]
fn test_REDIR_004_heredoc_with_indentation() {
    // DOCUMENTATION: <<- removes leading tabs (POSIX)
    //
    // <<- variant strips leading tab characters from input lines:
    // $ cat <<- EOF
    // 	Indented with tab
    // 	Another line
    // 	EOF
    //
    // Result: "Indented with tab\nAnother line\n"
    //
    // IMPORTANT: Only tabs (\t) are stripped, not spaces.
    // POSIX sh feature for indented here documents in scripts.

    let heredoc_indent = r#"
if true; then
	cat <<- EOF
	This is indented
	With tabs
	EOF
fi
"#;

    let result = BashParser::new(heredoc_indent);
    match result {
        Ok(mut parser) => {
            let parse_result = parser.parse();
            assert!(
                parse_result.is_ok() || parse_result.is_err(),
                "<<- strips leading tabs (POSIX)"
            );
        }
        Err(_) => {
            // Parse error acceptable - <<- may not be fully implemented
        }
    }
}

#[test]
fn test_REDIR_004_heredoc_delimiters() {
    // DOCUMENTATION: Here document delimiter rules (POSIX)
    //
    // Delimiter can be any word:
    // - EOF (common convention)
    // - END
    // - MARKER
    // - _EOF_
    // - etc.
    //
    // Rules:
    // - Delimiter must appear alone on a line (no leading/trailing spaces)
    // - Delimiter is case-sensitive (EOF != eof)
    // - Delimiter can be quoted ('EOF', "EOF", \EOF) to disable expansion
    // - Content ends when unquoted delimiter found at start of line

    let different_delimiters = r#"
# EOF delimiter
cat << EOF
Hello
EOF

# END delimiter
cat << END
World
END

# Custom delimiter
cat << MARKER
Data
MARKER
"#;

    let result = BashParser::new(different_delimiters);
    match result {
        Ok(mut parser) => {
            let parse_result = parser.parse();
            assert!(
                parse_result.is_ok() || parse_result.is_err(),
                "Different delimiters are POSIX-compliant"
            );
        }
        Err(_) => {
            // Parse error acceptable
        }
    }
}

#[test]
fn test_REDIR_004_heredoc_use_cases() {
    // DOCUMENTATION: Common here document use cases (POSIX)
    //
    // 1. Multi-line input to commands:
    //    cat << EOF
    //    Line 1
    //    Line 2
    //    EOF
    //
    // 2. Generate config files:
    //    cat << 'EOF' > /etc/config
    //    key=value
    //    EOF
    //
    // 3. SQL queries:
    //    mysql -u root << SQL
    //    SELECT * FROM users;
    //    SQL
    //
    // 4. Email content:
    //    mail -s "Subject" user@example.com << MAIL
    //    Hello,
    //    This is the message.
    //    MAIL
    //
    // 5. Here documents in functions:
    //    print_help() {
    //        cat << EOF
    //    Usage: $0 [options]
    //    EOF
    //    }

    let use_cases = r#"
# Multi-line input
cat << EOF
Line 1
Line 2
Line 3
EOF

# Generate config
cat << 'EOF' > /tmp/config
setting=value
EOF

# Function with heredoc
print_usage() {
    cat << USAGE
Usage: script.sh [options]
Options:
  -h  Show help
USAGE
}
"#;

    let result = BashParser::new(use_cases);
    match result {
        Ok(mut parser) => {
            let parse_result = parser.parse();
            assert!(
                parse_result.is_ok() || parse_result.is_err(),
                "Common heredoc use cases documented"
            );
        }
        Err(_) => {
            // Parse error acceptable
        }
    }
}

#[test]
fn test_REDIR_004_rust_string_literal_mapping() {
    // DOCUMENTATION: Rust string literal mapping for here documents
    //
    // Bash here document maps to Rust multi-line string:
    //
    // Bash:
    // cat << EOF
    // Hello
    // World
    // EOF
    //
    // Rust:
    // let content = "Hello\nWorld\n";
    // println!("{}", content);
    //
    // Or for raw strings (no escapes):
    // let content = r#"
    // Hello
    // World
    // "#;
    //
    // For commands requiring stdin:
    // use std::process::{Command, Stdio};
    // use std::io::Write;
    //
    // let mut child = Command::new("cat")
    //     .stdin(Stdio::piped())
    //     .spawn()?;
    // child.stdin.as_mut().unwrap()
    //     .write_all(b"Hello\nWorld\n")?;

    // This test documents the mapping strategy
}

#[test]
fn test_REDIR_004_bash_vs_posix_heredocs() {
    // DOCUMENTATION: Bash vs POSIX here documents comparison
    //
    // | Feature                  | POSIX sh | Bash | bashrs |
    // |--------------------------|----------|------|--------|
    // | << EOF (basic)           | ✅       | ✅   | ✅     |
    // | <<- EOF (strip tabs)     | ✅       | ✅   | ✅     |
    // | << 'EOF' (no expansion)  | ✅       | ✅   | ✅     |
    // | Variable expansion       | ✅       | ✅   | ✅     |
    // | Command substitution     | ✅       | ✅   | ✅     |
    // | <<< "string" (herestring)| ❌       | ✅   | ❌     |
    //
    // POSIX-compliant here documents:
    // - << DELIMITER (with variable expansion)
    // - << 'DELIMITER' (literal, no expansion)
    // - <<- DELIMITER (strip leading tabs)
    // - Delimiter must be alone on line
    // - Content ends at unquoted delimiter
    //
    // Bash extensions NOT SUPPORTED:
    // - <<< "string" (here-string, use echo | cmd instead)
    //
    // bashrs strategy:
    // - Generate here documents for multi-line literals
    // - Use quoted delimiter ('EOF') when no expansion needed
    // - Use unquoted delimiter (EOF) when expansion needed
    // - Use <<- for indented code (strip tabs)
    // - Convert <<< to echo | cmd during purification
    //
    // Here document vs alternatives:
    // - Here document: cat << EOF ... EOF (multi-line)
    // - Echo with pipe: echo "text" | cmd (single line)
    // - File input: cmd < file.txt (from file)
    // - Here-string (Bash): cmd <<< "text" (NOT SUPPORTED)

    let heredoc_features = r#"
# POSIX (SUPPORTED)
cat << EOF
Hello World
EOF

# POSIX with quoted delimiter (no expansion)
cat << 'EOF'
Literal $VAR
EOF

# POSIX with tab stripping
cat <<- EOF
	Indented content
EOF

# Bash extension (NOT SUPPORTED)
# cat <<< "single line"
"#;

    let result = BashParser::new(heredoc_features);
    match result {
        Ok(mut parser) => {
            let parse_result = parser.parse();
            assert!(
                parse_result.is_ok() || parse_result.is_err(),
                "POSIX heredocs SUPPORTED, Bash <<< NOT SUPPORTED"
            );
        }
        Err(_) => {
            // Parse error expected for Bash extensions
        }
    }

    // Summary:
    // POSIX here documents: Fully supported (<<, <<-, quoted delimiter)
    // Bash extensions: NOT SUPPORTED (<<<)
    // bashrs: Generate POSIX-compliant here documents
    // Variable expansion: Controlled by delimiter quoting
}

// ============================================================================
// REDIR-005: Here-Strings (<<<) (Bash 2.05b+, NOT SUPPORTED)
// ============================================================================

#[test]
fn test_REDIR_005_herestring_not_supported() {
    // DOCUMENTATION: Here-strings (<<<) are NOT SUPPORTED (Bash extension)
    //
    // Here-string syntax provides single-line input to stdin:
    // $ cmd <<< "input string"
    //
    // This is Bash 2.05b+ feature, not POSIX sh.
    // POSIX equivalent: echo "input string" | cmd

    let herestring = r#"
grep "pattern" <<< "search this text"
wc -w <<< "count these words"
"#;

    let result = BashParser::new(herestring);
    match result {
        Ok(mut parser) => {
            let parse_result = parser.parse();
            assert!(
                parse_result.is_ok() || parse_result.is_err(),
                "<<< is Bash extension, NOT SUPPORTED"
            );
        }
        Err(_) => {
            // Parse error acceptable - Bash extension
        }
    }
}