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
fn test_header_and_footer_structure() {
    let config = Config::default();
    let emitter = PosixEmitter::new();

    let ir = ShellIR::Noop;
    let result = emitter.emit(&ir).unwrap();

    // Check header
    assert!(result.starts_with("#!/bin/sh"));
    assert!(result.contains("# Generated by Rash"));
    assert!(result.contains("set -euf"));
    assert!(result.contains("IFS=' \t\n'"));
    assert!(result.contains("export LC_ALL=C"));

    // With selective runtime, Noop IR emits no runtime functions.
    // Runtime functions are only emitted when the IR references them.
    // This is by design for smaller output scripts.

    // Check footer
    assert!(result.contains("main() {"));
    assert!(result.contains("trap 'rm -rf"));
    assert!(result.contains("main \"$@\""));
}

#[test]
fn test_runtime_functions_included() {
    let config = Config::default();
    let emitter = PosixEmitter::new();

    // Use an IR that references rash_require and rash_download_verified
    // so that selective runtime emission includes them
    let ir = ShellIR::Sequence(vec![
        ShellIR::Exec {
            cmd: Command::new("rash_require").arg(ShellValue::String("curl".to_string())),
            effects: EffectSet::pure(),
        },
        ShellIR::Exec {
            cmd: Command::new("rash_download_verified")
                .arg(ShellValue::String("https://example.com/file".to_string()))
                .arg(ShellValue::String("abc123".to_string())),
            effects: EffectSet::pure(),
        },
    ]);
    let result = emitter.emit(&ir).unwrap();

    // Verify essential runtime functions are present
    assert!(result.contains("rash_require() {"));
    assert!(result.contains("rash_download_verified() {"));

    // Verify they contain expected functionality
    assert!(result.contains("curl -fsSL"));
    assert!(result.contains("sha256sum"));
    assert!(result.contains("wget"));
}

#[test]
fn test_test_expression_emission() {
    let config = Config::default();
    let emitter = PosixEmitter::new();

    // Boolean true
    let result = emitter
        .emit_test_expression(&ShellValue::Bool(true))
        .unwrap();
    assert_eq!(result, "true");

    // Boolean false
    let result = emitter
        .emit_test_expression(&ShellValue::Bool(false))
        .unwrap();
    assert_eq!(result, "false");

    // Variable test
    let result = emitter
        .emit_test_expression(&ShellValue::Variable("var".to_string()))
        .unwrap();
    assert_eq!(result, "test -n \"$var\"");

    // String literal
    let result = emitter
        .emit_test_expression(&ShellValue::String("true".to_string()))
        .unwrap();
    assert_eq!(result, "true");

    let result = emitter
        .emit_test_expression(&ShellValue::String("false".to_string()))
        .unwrap();
    assert_eq!(result, "false");
}

// Test escape module functionality
#[test]
fn test_string_escaping() {
    use super::escape::*;

    // Simple strings don't need escaping
    assert_eq!(escape_shell_string("hello"), "hello");
    assert_eq!(escape_shell_string("simple123"), "simple123");

    // Strings with spaces need quotes
    assert_eq!(escape_shell_string("hello world"), "'hello world'");

    // Empty strings
    assert_eq!(escape_shell_string(""), "''");

    // Strings with single quotes
    assert_eq!(escape_shell_string("don't"), "'don'\"'\"'t'");
}

#[test]
fn test_variable_name_escaping() {
    use super::escape::*;

    // Valid identifiers
    assert_eq!(escape_variable_name("valid_name"), "valid_name");
    assert_eq!(escape_variable_name("_underscore"), "_underscore");
    assert_eq!(escape_variable_name("name123"), "name123");

    // Invalid characters converted to underscores
    assert_eq!(escape_variable_name("invalid-name"), "invalid_name");
    assert_eq!(escape_variable_name("123invalid"), "_23invalid");
    assert_eq!(escape_variable_name("my.var"), "my_var");
}

#[test]
fn test_command_name_escaping() {
    use super::escape::*;

    // Simple commands
    assert_eq!(escape_command_name("ls"), "ls");
    assert_eq!(escape_command_name("/bin/ls"), "/bin/ls");
    assert_eq!(escape_command_name("my-tool"), "my-tool");

    // Commands with spaces need quoting
    assert_eq!(escape_command_name("my command"), "'my command'");
}

// Property-based tests
proptest! {
    #![proptest_config(ProptestConfig::with_cases(1000))]

    #[test]
    fn test_string_escaping_preserves_content(s in ".*") {
        use super::escape::*;

        let escaped = escape_shell_string(&s);

        // Escaped strings should either be the original (if safe) or quoted
        if s.chars().all(|c| c.is_alphanumeric() || "_.-/+=:@".contains(c)) && !s.is_empty() {
            // Safe strings might be unquoted
            assert!(escaped == s || escaped == format!("'{s}'"));
        } else {
            // Unsafe strings should be quoted
            assert!(escaped.starts_with('\'') && escaped.ends_with('\'') || escaped == "''");
        }
    }

    #[test]
    fn test_variable_name_escaping_produces_valid_identifiers(name in "[a-zA-Z_][a-zA-Z0-9_-]*") {
        use super::escape::*;

        let escaped = escape_variable_name(&name);

        // Should start with letter or underscore
        assert!(escaped.chars().next().unwrap().is_alphabetic() || escaped.starts_with('_'));

        // Should only contain valid characters
        assert!(escaped.chars().all(|c| c.is_alphanumeric() || c == '_'));
    }

    /// Property: All shell values should emit valid shell code
    #[test]
    fn prop_shell_values_emit_valid_code(
        s in "[a-zA-Z0-9 _.-]{0,100}",
        b in prop::bool::ANY,
        var_name in "[a-zA-Z_][a-zA-Z0-9_]{0,20}"
    ) {
        let config = Config::default();
        let emitter = PosixEmitter::new();

        let test_values = vec![
            ShellValue::String(s),
            ShellValue::Bool(b),
            ShellValue::Variable(var_name),
        ];

        for value in test_values {
            let result = emitter.emit_shell_value(&value);
            prop_assert!(result.is_ok(), "Failed to emit shell value: {:?}", value);

            if let Ok(code) = result {
                // Generated code should not be empty
                prop_assert!(!code.trim().is_empty());

                // Should not contain unescaped dangerous characters
                prop_assert!(!code.contains("$(rm"), "Potential command injection in: {}", code);
                prop_assert!(!code.contains("; rm"), "Potential command injection in: {}", code);
            }
        }
    }

    /// Property: Commands should emit syntactically valid shell
    #[test]
    fn prop_commands_emit_valid_shell(
        cmd_name in "[a-zA-Z][a-zA-Z0-9_-]{0,20}",
        arg_count in 0usize..5usize
    ) {
        let config = Config::default();
        let emitter = PosixEmitter::new();

        let args: Vec<ShellValue> = (0..arg_count)
            .map(|i| ShellValue::String(format!("arg{i}")))
            .collect();

        let cmd = Command {
            program: cmd_name.clone(),
            args,
        };

        let ir = ShellIR::Exec {
            cmd,
            effects: EffectSet::pure(),
        };

        let result = emitter.emit(&ir);
        prop_assert!(result.is_ok(), "Failed to emit command: {}", cmd_name);

        if let Ok(shell_code) = result {
            // Should contain the command name
            prop_assert!(shell_code.contains(&cmd_name));

            // Should have balanced quotes
            let single_quotes = shell_code.chars().filter(|&c| c == '\'').count();
            prop_assert!(single_quotes % 2 == 0, "Unbalanced single quotes in: {}", shell_code);

            // Should contain proper shell structure
            prop_assert!(shell_code.contains("#!/bin/sh"));
            prop_assert!(shell_code.contains("set -euf"));
        }
    }

    /// Property: Let statements should create valid variable assignments
    #[test]
    fn prop_let_statements_valid(
        var_name in "[a-zA-Z_][a-zA-Z0-9_]{0,30}",
        value in "[a-zA-Z0-9 _.-]{0,100}"
    ) {
        let config = Config::default();
        let emitter = PosixEmitter::new();

        let ir = ShellIR::Let {
            name: var_name.clone(),
            value: ShellValue::String(value),
            effects: EffectSet::pure(),
        };

        let result = emitter.emit(&ir);
        prop_assert!(result.is_ok(), "Failed to emit let statement for: {}", var_name);

        if let Ok(shell_code) = result {
            // Variables are now mutable to support let-shadowing semantics
            // prop_assert!(shell_code.contains("readonly"));

            // Variable name should be properly escaped
            let escaped_name = super::escape::escape_variable_name(&var_name);
            prop_assert!(shell_code.contains(&escaped_name));

            // Should be valid shell syntax (basic check)
            prop_assert!(!shell_code.contains("readonly ="), "Invalid assignment syntax");
        }
    }

    /// Property: If statements should have balanced if/fi
    #[test]
    fn prop_if_statements_balanced(condition in prop::bool::ANY) {
        let config = Config::default();
        let emitter = PosixEmitter::new();

        let ir = ShellIR::If {
            test: ShellValue::Bool(condition),
            then_branch: Box::new(ShellIR::Noop),
            else_branch: Some(Box::new(ShellIR::Noop)),
        };

        let result = emitter.emit(&ir);
        prop_assert!(result.is_ok(), "Failed to emit if statement");

        if let Ok(shell_code) = result {
            // Focus on the main function content only
            if let Some(main_start) = shell_code.find("main() {") {
                if let Some(main_end) = shell_code[main_start..].find("# Cleanup") {
                    let main_content = &shell_code[main_start..main_start + main_end];
                    let if_count = main_content.matches("if ").count();
                    let fi_count = main_content.matches("fi").count();
                    prop_assert_eq!(if_count, fi_count, "Unbalanced if/fi in main function");

                    // Should contain then and else in main function
                    prop_assert!(main_content.contains("then"));
                    prop_assert!(main_content.contains("else"));
                }
            }
        }
    }

    /// Property: Concatenation should preserve order
    #[test]
    fn prop_concatenation_preserves_order(
        parts in prop::collection::vec("[a-zA-Z0-9]{1,10}", 1..5)
    ) {
        let config = Config::default();
        let emitter = PosixEmitter::new();

        let shell_values: Vec<ShellValue> = parts.iter()
            .map(|s| ShellValue::String(s.clone()))
            .collect();

        let concat_value = ShellValue::Concat(shell_values);
        let result = emitter.emit_shell_value(&concat_value);

        prop_assert!(result.is_ok(), "Failed to emit concatenation");

        if let Ok(shell_code) = result {
            // All parts should appear in order
            let mut last_pos = 0;
            for part in &parts {
                if let Some(pos) = shell_code[last_pos..].find(part) {
                    last_pos += pos + part.len();
                } else {
                    prop_assert!(false, "Part '{}' not found in order in: {}", part, shell_code);
                }
            }
        }
    }

    /// Property: Generated shell should be deterministic
    #[test]
    fn prop_emission_deterministic(var_name in "[a-zA-Z_][a-zA-Z0-9_]{0,20}") {
        let config = Config::default();
        let emitter1 = PosixEmitter::new();
        let emitter2 = PosixEmitter::new();

        let ir = ShellIR::Let {
            name: var_name,
            value: ShellValue::String("test".to_string()),
            effects: EffectSet::pure(),
        };

        let result1 = emitter1.emit(&ir);
        let result2 = emitter2.emit(&ir);

        match (&result1, &result2) {
            (Ok(code1), Ok(code2)) => prop_assert_eq!(code1, code2, "Non-deterministic emission detected"),
            (Err(_), Err(_)) => {}, // Both failing is acceptable
            _ => prop_assert!(false, "Inconsistent success/failure between runs"),
        }
    }

    /// Property: Special characters should be properly escaped
    #[test]
    fn prop_special_chars_escaped(s in r#"['"$`\\;&|()<> \t\n]*"#) {
        use super::escape::*;

        let escaped = escape_shell_string(&s);

        // If the string contains special characters, it should be quoted
        if s.chars().any(|c| "'\"$`\\;&|()<> \t\n".contains(c)) && !s.is_empty() {
            prop_assert!(
                escaped.starts_with('\'') || escaped.starts_with('"'),
                "Special characters not properly escaped in: '{}' -> '{}'", s, escaped
            );
        }
    }

    /// Property: Exit codes should be valid
    #[test]
    fn prop_exit_codes_valid(code in 0i32..256i32) {
        let config = Config::default();
        let emitter = PosixEmitter::new();

        let ir = ShellIR::Exit {
            code: code as u8,
            message: Some("test message".to_string()),
        };

        let result = emitter.emit(&ir);
        prop_assert!(result.is_ok(), "Failed to emit exit statement with code: {}", code);

        if let Ok(shell_code) = result {
            let exit_string = format!("exit {code}");
            prop_assert!(shell_code.contains(&exit_string));
        }
    }
}

#[rstest]
#[case(ShellValue::String("test".to_string()), "test")]
#[case(ShellValue::Bool(true), "true")]
#[case(ShellValue::Bool(false), "false")]
#[case(ShellValue::Variable("var".to_string()), "\"$var\"")]
fn test_shell_value_emission_cases(#[case] value: ShellValue, #[case] expected: &str) {
    let config = Config::default();
    let emitter = PosixEmitter::new();

    let result = emitter.emit_shell_value(&value).unwrap();
    assert_eq!(result, expected);
}

#[test]
fn test_complex_nested_emission() {
    let config = Config::default();
    let emitter = PosixEmitter::new();

    let ir = ShellIR::Sequence(vec![
        ShellIR::Let {
            name: "prefix".to_string(),
            value: ShellValue::String("/usr/local".to_string()),
            effects: EffectSet::pure(),
        },
        ShellIR::If {
            test: ShellValue::Variable("install_mode".to_string()),
            then_branch: Box::new(ShellIR::Sequence(vec![
                ShellIR::Exec {
                    cmd: Command {
                        program: "mkdir".to_string(),
                        args: vec![ShellValue::Variable("prefix".to_string())],
                    },
                    effects: EffectSet::default(),
                },
                ShellIR::Exec {
                    cmd: Command {
                        program: "echo".to_string(),
                        args: vec![ShellValue::Concat(vec![
                            ShellValue::String("Installing to ".to_string()),
                            ShellValue::Variable("prefix".to_string()),
                        ])],
                    },
                    effects: EffectSet::pure(),
                },
            ])),
            else_branch: Some(Box::new(ShellIR::Exit {
                code: 1,
                message: Some("Installation cancelled".to_string()),
            })),
        },
    ]);

    let result = emitter.emit(&ir).unwrap();

    // Verify structure
    // Updated: Variables are now mutable to support let-shadowing semantics
    assert!(result.contains("prefix='/usr/local'"));
    assert!(!result.contains("readonly"));
    assert!(result.contains("if test -n \"$install_mode\"; then"));
    assert!(result.contains("mkdir \"$prefix\""));
    assert!(result.contains("echo \"Installing to ${prefix}\""));
    assert!(result.contains("else"));
    assert!(result.contains("echo 'Installation cancelled' >&2"));
    assert!(result.contains("exit 1"));
    assert!(result.contains("fi"));
}