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
//! Property Test Generation (Sprint 2)
//!
//! Generates property tests using proptest for:
//! - Determinism (same input → same output)
//! - Idempotency (f(f(x)) == f(x))
//! - Bounds checking
//! - Type preservation

use super::core::TestGenResult;
use crate::bash_parser::ast::*;
use std::collections::HashSet;

pub struct PropertyTestGenerator {
    /// Maximum test cases per property
    max_test_cases: usize,
}

impl Default for PropertyTestGenerator {
    fn default() -> Self {
        Self::new()
    }
}

impl PropertyTestGenerator {
    pub fn new() -> Self {
        Self {
            max_test_cases: 100,
        }
    }

    /// Generate property tests for AST
    pub fn generate_properties(&self, ast: &BashAst) -> TestGenResult<Vec<PropertyTest>> {
        let mut tests = Vec::new();

        for stmt in &ast.statements {
            if let BashStmt::Function { name, body, .. } = stmt {
                // Generate determinism tests
                if let Some(test) = self.generate_determinism_test(name, body)? {
                    tests.push(test);
                }

                // Generate idempotency tests
                if let Some(test) = self.generate_idempotency_test(name, body)? {
                    tests.push(test);
                }

                // Generate bounds tests
                tests.extend(self.generate_bounds_tests(name, body)?);

                // Generate type preservation tests
                if let Some(test) = self.generate_type_preservation_test(name, body)? {
                    tests.push(test);
                }
            }
        }

        Ok(tests)
    }

    /// Generate determinism property test (same input → same output)
    fn generate_determinism_test(
        &self,
        name: &str,
        body: &[BashStmt],
    ) -> TestGenResult<Option<PropertyTest>> {
        // Check if function is deterministic (no random operations, no file I/O)
        if self.has_nondeterministic_operations(body) {
            return Ok(None);
        }

        let generators = self.infer_generators_from_function(name, body)?;

        Ok(Some(PropertyTest {
            name: format!("prop_{}_determinism", name),
            property: Property::Determinism,
            generators,
            test_cases: self.max_test_cases,
        }))
    }

    /// Generate idempotency property test (f(f(x)) == f(x))
    fn generate_idempotency_test(
        &self,
        name: &str,
        body: &[BashStmt],
    ) -> TestGenResult<Option<PropertyTest>> {
        // Check if function is likely idempotent (normalization, formatting, etc.)
        if !self.is_potentially_idempotent(body) {
            return Ok(None);
        }

        let generators = self.infer_generators_from_function(name, body)?;

        Ok(Some(PropertyTest {
            name: format!("prop_{}_idempotency", name),
            property: Property::Idempotency,
            generators,
            test_cases: self.max_test_cases,
        }))
    }

    /// Generate bounds checking property tests
    fn generate_bounds_tests(
        &self,
        name: &str,
        body: &[BashStmt],
    ) -> TestGenResult<Vec<PropertyTest>> {
        let mut tests = Vec::new();

        // Look for arithmetic operations that suggest bounds
        for stmt in body {
            if let Some(bounds) = self.extract_bounds(stmt) {
                let generators = vec![Generator::Integer {
                    min: bounds.min - 10,
                    max: bounds.max + 10,
                }];

                tests.push(PropertyTest {
                    name: format!("prop_{}_bounds_{}_{}", name, bounds.min, bounds.max),
                    property: Property::Bounds {
                        min: bounds.min,
                        max: bounds.max,
                    },
                    generators,
                    test_cases: self.max_test_cases,
                });
            }
        }

        Ok(tests)
    }

    /// Generate type preservation property test
    fn generate_type_preservation_test(
        &self,
        name: &str,
        body: &[BashStmt],
    ) -> TestGenResult<Option<PropertyTest>> {
        // Check if function preserves types (string → string, int → int)
        let generators = self.infer_generators_from_function(name, body)?;

        Ok(Some(PropertyTest {
            name: format!("prop_{}_type_preservation", name),
            property: Property::TypePreservation,
            generators,
            test_cases: self.max_test_cases,
        }))
    }

    /// Check if a command name is non-deterministic
    fn is_nondeterministic_command(name: &str) -> bool {
        matches!(name, "random" | "date" | "time" | "rand" | "uuid")
    }

    /// Check if an If statement's blocks contain non-deterministic operations
    fn if_stmt_has_nondeterminism(
        &self,
        then_block: &[BashStmt],
        elif_blocks: &[(BashExpr, Vec<BashStmt>)],
        else_block: &Option<Vec<BashStmt>>,
    ) -> bool {
        if self.has_nondeterministic_operations(then_block) {
            return true;
        }
        if elif_blocks
            .iter()
            .any(|(_, block)| self.has_nondeterministic_operations(block))
        {
            return true;
        }
        else_block
            .as_deref()
            .is_some_and(|block| self.has_nondeterministic_operations(block))
    }

    /// Check if function has non-deterministic operations
    fn has_nondeterministic_operations(&self, body: &[BashStmt]) -> bool {
        body.iter().any(|stmt| match stmt {
            BashStmt::Command { name, .. } => Self::is_nondeterministic_command(name.as_str()),
            BashStmt::If {
                then_block,
                elif_blocks,
                else_block,
                ..
            } => self.if_stmt_has_nondeterminism(then_block, elif_blocks, else_block),
            BashStmt::While { body, .. } | BashStmt::For { body, .. } => {
                self.has_nondeterministic_operations(body)
            }
            _ => false,
        })
    }

    /// Check if function is potentially idempotent
    fn is_potentially_idempotent(&self, body: &[BashStmt]) -> bool {
        // Look for patterns that suggest idempotency:
        // - String normalization (trim, lowercase, etc.)
        // - Sorting operations
        // - Deduplication
        // - Path normalization

        for stmt in body {
            if let BashStmt::Command { name, .. } = stmt {
                if matches!(
                    name.as_str(),
                    "sort" | "uniq" | "tr" | "sed" | "awk" | "normalize" | "trim"
                ) {
                    return true;
                }
            }
        }

        false
    }

    /// Default string generator pattern
    fn default_string_generator() -> Generator {
        Generator::String {
            pattern: "[a-zA-Z0-9]{1,20}".to_string(),
        }
    }

    /// Default integer generator
    fn default_integer_generator() -> Generator {
        Generator::Integer {
            min: -1000,
            max: 1000,
        }
    }

    /// Add a generator inferred from a literal assignment value, if not already seen
    fn add_generator_for_literal(
        lit: &str,
        generators: &mut Vec<Generator>,
        seen_types: &mut HashSet<&'static str>,
    ) {
        if lit.parse::<i64>().is_ok() {
            if !seen_types.contains("integer") {
                generators.push(Self::default_integer_generator());
                seen_types.insert("integer");
            }
        } else if !seen_types.contains("string") {
            generators.push(Self::default_string_generator());
            seen_types.insert("string");
        }
    }

    /// Add an integer generator for an arithmetic assignment value, if not already seen
    fn add_generator_for_arithmetic(
        generators: &mut Vec<Generator>,
        seen_types: &mut HashSet<&'static str>,
    ) {
        if !seen_types.contains("integer") {
            generators.push(Self::default_integer_generator());
            seen_types.insert("integer");
        }
    }

    /// Infer proptest generators from function signature and body
    fn infer_generators_from_function(
        &self,
        _name: &str,
        body: &[BashStmt],
    ) -> TestGenResult<Vec<Generator>> {
        let mut generators = Vec::new();
        let mut seen_types = HashSet::new();

        for stmt in body {
            if let BashStmt::Assignment { value, .. } = stmt {
                match value {
                    BashExpr::Literal(lit) => {
                        Self::add_generator_for_literal(lit, &mut generators, &mut seen_types);
                    }
                    BashExpr::Arithmetic(_) => {
                        Self::add_generator_for_arithmetic(&mut generators, &mut seen_types);
                    }
                    _ => {}
                }
            }
        }

        // Default to string generator if nothing else was found
        if generators.is_empty() {
            generators.push(Self::default_string_generator());
        }

        Ok(generators)
    }

    /// Extract bounds from conditional statements
    fn extract_bounds(&self, stmt: &BashStmt) -> Option<BoundsInfo> {
        if let BashStmt::If {
            condition: BashExpr::Test { .. },
            ..
        } = stmt
        {
            // Try to extract bounds from conditions like [ $x -gt 0 ] && [ $x -lt 100 ]
            // Simplified: assume reasonable bounds
            return Some(BoundsInfo { min: 0, max: 100 });
        }
        None
    }
}

struct BoundsInfo {
    min: i64,
    max: i64,
}

#[derive(Debug, Clone)]
pub struct PropertyTest {
    pub name: String,
    pub property: Property,
    pub generators: Vec<Generator>,
    pub test_cases: usize,
}

impl PropertyTest {
    // Generate Rust code for this property test
    pub fn to_rust_code(&self) -> String {
        let mut code = String::new();

        // Generate the proptest macro invocation
        code.push_str("proptest! {\n");
        code.push_str("    #[test]\n");
        code.push_str(&format!("    fn {}(\n", self.name));

        // Generate parameter list from generators
        for (i, gen) in self.generators.iter().enumerate() {
            let param_name = format!("arg{}", i);
            let generator_code = gen.to_proptest_strategy();
            code.push_str(&format!("        {} in {},\n", param_name, generator_code));
        }

        code.push_str("    ) {\n");

        // Generate property assertion based on property type
        match &self.property {
            Property::Determinism => {
                code.push_str("        // Test determinism: same input → same output\n");
                let args = (0..self.generators.len())
                    .map(|i| format!("arg{}", i))
                    .collect::<Vec<_>>()
                    .join(", ");
                code.push_str(&format!(
                    "        let result1 = function_under_test({});\n",
                    args
                ));
                code.push_str(&format!(
                    "        let result2 = function_under_test({});\n",
                    args
                ));
                code.push_str("        prop_assert_eq!(result1, result2);\n");
            }
            Property::Idempotency => {
                code.push_str("        // Test idempotency: f(f(x)) == f(x)\n");
                let args = (0..self.generators.len())
                    .map(|i| format!("arg{}", i))
                    .collect::<Vec<_>>()
                    .join(", ");
                code.push_str(&format!(
                    "        let result1 = function_under_test({});\n",
                    args
                ));
                code.push_str("        let result2 = function_under_test(&result1);\n");
                code.push_str("        prop_assert_eq!(result1, result2);\n");
            }
            Property::Commutativity => {
                code.push_str("        // Test commutativity: f(a, b) == f(b, a)\n");
                if self.generators.len() >= 2 {
                    code.push_str("        let result1 = function_under_test(arg0, arg1);\n");
                    code.push_str("        let result2 = function_under_test(arg1, arg0);\n");
                    code.push_str("        prop_assert_eq!(result1, result2);\n");
                }
            }
            Property::Bounds { min, max } => {
                code.push_str(&format!(
                    "        // Test bounds: result in range [{}, {}]\n",
                    min, max
                ));
                let args = (0..self.generators.len())
                    .map(|i| format!("arg{}", i))
                    .collect::<Vec<_>>()
                    .join(", ");
                code.push_str(&format!(
                    "        let result = function_under_test({});\n",
                    args
                ));
                code.push_str(&format!("        prop_assert!(result >= {});\n", min));
                code.push_str(&format!("        prop_assert!(result <= {});\n", max));
            }
            Property::TypePreservation => {
                code.push_str("        // Test type preservation\n");
                let args = (0..self.generators.len())
                    .map(|i| format!("arg{}", i))
                    .collect::<Vec<_>>()
                    .join(", ");
                code.push_str(&format!(
                    "        let result = function_under_test({});\n",
                    args
                ));
                code.push_str("        // Verify result has expected type\n");
                code.push_str("        prop_assert!(std::mem::size_of_val(&result) > 0);\n");
            }
            Property::NoSideEffects => {
                code.push_str(
                    "        // Test no side effects: function doesn't modify external state\n",
                );
                let args = (0..self.generators.len())
                    .map(|i| format!("arg{}", i))
                    .collect::<Vec<_>>()
                    .join(", ");
                code.push_str(&format!(
                    "        let _result = function_under_test({});\n",
                    args
                ));
                code.push_str("        // Verify no side effects occurred\n");
            }
        }

        code.push_str("    }\n");
        code.push_str("}\n");

        code
    }
}

#[derive(Debug, Clone)]
pub enum Property {
    Determinism,
    Idempotency,
    Commutativity,
    Bounds { min: i64, max: i64 },
    TypePreservation,
    NoSideEffects,
}

#[derive(Debug, Clone)]
pub enum Generator {
    Integer { min: i64, max: i64 },
    String { pattern: String },
    Path { valid: bool },
}

impl Generator {
    /// Convert to proptest strategy code
    pub fn to_proptest_strategy(&self) -> String {
        match self {
            Generator::Integer { min, max } => {
                format!("{}..={}", min, max)
            }
            Generator::String { pattern } => {
                // For simple patterns, use proptest string generators
                if pattern == "[a-zA-Z0-9]{1,20}" {
                    "\"[a-zA-Z0-9]{1,20}\"".to_string()
                } else {
                    format!("\"{}\"", pattern)
                }
            }
            Generator::Path { valid } => {
                if *valid {
                    "\"/[a-z]{1,10}/[a-z]{1,10}\"".to_string()
                } else {
                    "\"/[^/]{0,5}\"".to_string()
                }
            }
        }
    }
}