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
//! Doctest Generation (Sprint 3)
//!
//! Extracts doctests from bash comments and usage examples

use super::core::TestGenResult;
use crate::bash_parser::ast::*;

pub struct DoctestGenerator;

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

impl DoctestGenerator {
    pub fn new() -> Self {
        Self
    }

    /// Generate doctests from bash comments
    pub fn generate_doctests(&self, ast: &BashAst) -> TestGenResult<Vec<Doctest>> {
        let mut doctests = Vec::new();

        for stmt in &ast.statements {
            if let BashStmt::Function { name, body, .. } = stmt {
                // Extract doctests from function comments
                doctests.extend(self.extract_from_function(name, body)?);
            }
        }

        Ok(doctests)
    }

    /// Parse an "Example: ..." comment, returning either a complete Doctest or a pending example.
    /// Returns `Ok(Some(doctest))` for inline `=>` patterns, `Ok(None)` with side-effect on
    /// `current_example` for deferred patterns, and `Err` is never produced (kept for symmetry).
    fn parse_example_comment(&self, text: &str) -> Option<Result<(String, String), String>> {
        let after = text
            .split_once("example:")
            .or_else(|| text.split_once("Example:"))?;
        let content = after.1.trim();
        if let Some((example, output)) = content.split_once("=>") {
            Some(Ok((example.trim().to_string(), output.trim().to_string())))
        } else {
            Some(Err(content.to_string()))
        }
    }

    /// Parse a "Usage: ..." comment, returning the usage string if present.
    fn parse_usage_comment(&self, text: &str) -> Option<String> {
        let after = text
            .split_once("usage:")
            .or_else(|| text.split_once("Usage:"))?;
        Some(after.1.trim().to_string())
    }

    /// Parse an "Output: ..." comment, returning the output string if present.
    fn parse_output_comment(&self, text: &str) -> Option<String> {
        let after = text
            .split_once("output:")
            .or_else(|| text.split_once("Output:"))?;
        Some(after.1.trim().to_string())
    }

    /// Process a single comment statement, updating state and pushing complete doctests.
    fn process_comment(
        &self,
        text: &str,
        function_name: &str,
        doctests: &mut Vec<Doctest>,
        current_example: &mut Option<String>,
        current_output: &mut Option<String>,
    ) {
        let text_lower = text.to_lowercase();

        if text_lower.contains("example:") {
            match self.parse_example_comment(text) {
                Some(Ok((example, output))) => doctests.push(Doctest {
                    function_name: function_name.to_string(),
                    example,
                    expected_output: output,
                    description: None,
                }),
                Some(Err(pending)) => *current_example = Some(pending),
                None => {}
            }
        }

        if text_lower.contains("usage:") {
            if let Some(usage) = self.parse_usage_comment(text) {
                *current_example = Some(usage);
            }
        }

        if text_lower.contains("output:") {
            if let Some(output) = self.parse_output_comment(text) {
                *current_output = Some(output);
            }
        }
    }

    /// Extract doctests from a function's comments
    fn extract_from_function(
        &self,
        function_name: &str,
        body: &[BashStmt],
    ) -> TestGenResult<Vec<Doctest>> {
        let mut doctests = Vec::new();
        let mut current_example: Option<String> = None;
        let mut current_output: Option<String> = None;

        for stmt in body {
            if let BashStmt::Comment { text, .. } = stmt {
                self.process_comment(
                    text,
                    function_name,
                    &mut doctests,
                    &mut current_example,
                    &mut current_output,
                );
            }

            // Check after each statement if we have both example and output
            if let (Some(ex), Some(out)) = (&current_example, &current_output) {
                doctests.push(Doctest {
                    function_name: function_name.to_string(),
                    example: ex.clone(),
                    expected_output: out.clone(),
                    description: None,
                });
                current_example = None;
                current_output = None;
            }
        }

        // Generate default examples if no examples found
        if doctests.is_empty() {
            doctests.extend(self.generate_default_examples(function_name, body)?);
        }

        Ok(doctests)
    }

    /// Generate default examples based on function structure
    fn generate_default_examples(
        &self,
        function_name: &str,
        body: &[BashStmt],
    ) -> TestGenResult<Vec<Doctest>> {
        let mut examples = Vec::new();

        // Analyze function to create meaningful examples
        let has_return = body
            .iter()
            .any(|stmt| matches!(stmt, BashStmt::Return { .. }));

        // Create a basic example
        examples.push(Doctest {
            function_name: function_name.to_string(),
            example: format!("{}()", function_name),
            expected_output: if has_return {
                "// Returns result".to_string()
            } else {
                "// Executes successfully".to_string()
            },
            description: Some(format!("Basic usage of {}", function_name)),
        });

        Ok(examples)
    }

    /// Extract examples from inline comments
    pub fn extract_inline_examples(&self, ast: &BashAst) -> TestGenResult<Vec<Doctest>> {
        let mut doctests = Vec::new();

        // Look for standalone comment blocks before functions
        let mut pending_examples: Vec<(String, String)> = Vec::new();

        for stmt in &ast.statements {
            match stmt {
                BashStmt::Comment { text, .. } => {
                    let text_lower = text.to_lowercase();

                    // Check if this comment has an example with => separator
                    if text_lower.contains("example:") {
                        if let Some(after_example) = text
                            .split_once("example:")
                            .or_else(|| text.split_once("Example:"))
                        {
                            let content = after_example.1.trim();

                            if let Some((example, output)) = content.split_once("=>") {
                                pending_examples
                                    .push((example.trim().to_string(), output.trim().to_string()));
                            }
                        }
                    }
                }
                BashStmt::Function { name, .. } => {
                    // Associate pending examples with this function
                    for (example, output) in pending_examples.drain(..) {
                        doctests.push(Doctest {
                            function_name: name.clone(),
                            example,
                            expected_output: output,
                            description: None,
                        });
                    }
                }
                _ => {}
            }
        }

        Ok(doctests)
    }
}

#[derive(Debug, Clone)]
pub struct Doctest {
    pub function_name: String,
    pub example: String,
    pub expected_output: String,
    pub description: Option<String>,
}

impl Doctest {
    /// Convert to Rust doctest code
    pub fn to_rust_code(&self) -> String {
        let mut code = String::new();

        // Add description if present
        if let Some(desc) = &self.description {
            code.push_str(&format!("/// {}\n///\n", desc));
        }

        code.push_str("/// # Examples\n");
        code.push_str("///\n");
        code.push_str("/// ```\n");

        // Add the example
        code.push_str(&format!("/// use crate::{};\n", self.function_name));
        code.push_str(&format!("/// {}\n", self.example));

        // Add assertion for expected output if meaningful
        if !self.expected_output.starts_with("//") {
            code.push_str(&format!(
                "/// assert_eq!(result, {});\n",
                self.expected_output
            ));
        } else {
            code.push_str(&format!("/// {}\n", self.expected_output));
        }

        code.push_str("/// ```\n");

        code
    }
}

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

    #[test]
    fn test_doctest_generator_creation() {
        let gen = DoctestGenerator::new();
        let empty_ast = BashAst {
            statements: vec![],
            metadata: AstMetadata {
                source_file: None,
                line_count: 0,
                parse_time_ms: 0,
            },
        };

        let doctests = gen.generate_doctests(&empty_ast).unwrap();
        assert!(doctests.is_empty());
    }

    #[test]
    fn test_extract_example_with_arrow() {
        let gen = DoctestGenerator::new();
        let ast = BashAst {
            statements: vec![BashStmt::Function {
                name: "factorial".to_string(),
                body: vec![BashStmt::Comment {
                    text: " Example: factorial(5) => 120".to_string(),
                    span: Span::dummy(),
                }],
                span: Span::dummy(),
            }],
            metadata: AstMetadata {
                source_file: None,
                line_count: 1,
                parse_time_ms: 0,
            },
        };

        let doctests = gen.generate_doctests(&ast).unwrap();
        assert_eq!(doctests.len(), 1);
        assert_eq!(doctests[0].function_name, "factorial");
        assert_eq!(doctests[0].example, "factorial(5)");
        assert_eq!(doctests[0].expected_output, "120");
    }

    #[test]
    fn test_extract_usage_and_output() {
        let gen = DoctestGenerator::new();
        let ast = BashAst {
            statements: vec![BashStmt::Function {
                name: "greet".to_string(),
                body: vec![
                    BashStmt::Comment {
                        text: " Usage: greet(\"Alice\")".to_string(),
                        span: Span::dummy(),
                    },
                    BashStmt::Comment {
                        text: " Output: Hello, Alice!".to_string(),
                        span: Span::dummy(),
                    },
                ],
                span: Span::dummy(),
            }],
            metadata: AstMetadata {
                source_file: None,
                line_count: 1,
                parse_time_ms: 0,
            },
        };

        let doctests = gen.generate_doctests(&ast).unwrap();
        assert_eq!(doctests.len(), 1);
        assert_eq!(doctests[0].function_name, "greet");
        assert_eq!(doctests[0].example, "greet(\"Alice\")");
        assert_eq!(doctests[0].expected_output, "Hello, Alice!");
    }

    #[test]
    fn test_generate_default_example() {
        let gen = DoctestGenerator::new();
        let ast = BashAst {
            statements: vec![BashStmt::Function {
                name: "test_func".to_string(),
                body: vec![BashStmt::Return {
                    code: Some(BashExpr::Literal("0".to_string())),
                    span: Span::dummy(),
                }],
                span: Span::dummy(),
            }],
            metadata: AstMetadata {
                source_file: None,
                line_count: 1,
                parse_time_ms: 0,
            },
        };

        let doctests = gen.generate_doctests(&ast).unwrap();
        assert_eq!(doctests.len(), 1);
        assert_eq!(doctests[0].function_name, "test_func");
        assert!(doctests[0].example.contains("test_func"));
        assert!(doctests[0].expected_output.contains("Returns result"));
    }

    #[test]
    fn test_doctest_to_rust_code() {
        let doctest = Doctest {
            function_name: "factorial".to_string(),
            example: "let result = factorial(5);".to_string(),
            expected_output: "120".to_string(),
            description: Some("Calculate factorial".to_string()),
        };

        let code = doctest.to_rust_code();
        assert!(code.contains("/// # Examples"));
        assert!(code.contains("/// ```"));
        assert!(code.contains("use crate::factorial"));
        assert!(code.contains("let result = factorial(5);"));
        assert!(code.contains("assert_eq!(result, 120);"));
        assert!(code.contains("Calculate factorial"));
    }

    #[test]
    fn test_doctest_to_rust_code_comment_output() {
        let doctest = Doctest {
            function_name: "test_func".to_string(),
            example: "test_func()".to_string(),
            expected_output: "// Executes successfully".to_string(),
            description: None,
        };

        let code = doctest.to_rust_code();
        assert!(code.contains("/// # Examples"));
        assert!(code.contains("test_func()"));
        assert!(code.contains("// Executes successfully"));
        assert!(!code.contains("assert_eq!"));
    }

    #[test]
    fn test_extract_multiple_examples() {
        let gen = DoctestGenerator::new();
        let ast = BashAst {
            statements: vec![BashStmt::Function {
                name: "math".to_string(),
                body: vec![
                    BashStmt::Comment {
                        text: " Example: math(1, 2) => 3".to_string(),
                        span: Span::dummy(),
                    },
                    BashStmt::Comment {
                        text: " Example: math(10, 5) => 15".to_string(),
                        span: Span::dummy(),
                    },
                ],
                span: Span::dummy(),
            }],
            metadata: AstMetadata {
                source_file: None,
                line_count: 1,
                parse_time_ms: 0,
            },
        };

        let doctests = gen.generate_doctests(&ast).unwrap();
        assert_eq!(doctests.len(), 2);
        assert_eq!(doctests[0].example, "math(1, 2)");
        assert_eq!(doctests[0].expected_output, "3");
        assert_eq!(doctests[1].example, "math(10, 5)");
        assert_eq!(doctests[1].expected_output, "15");
    }

    #[test]
    fn test_extract_inline_examples() {
        let gen = DoctestGenerator::new();
        let ast = BashAst {
            statements: vec![
                BashStmt::Comment {
                    text: " Example: process(data) => result".to_string(),
                    span: Span::dummy(),
                },
                BashStmt::Function {
                    name: "process".to_string(),
                    body: vec![],
                    span: Span::dummy(),
                },
            ],
            metadata: AstMetadata {
                source_file: None,
                line_count: 2,
                parse_time_ms: 0,
            },
        };

        let doctests = gen.extract_inline_examples(&ast).unwrap();
        assert_eq!(doctests.len(), 1);
        assert_eq!(doctests[0].function_name, "process");
        assert_eq!(doctests[0].example, "process(data)");
        assert_eq!(doctests[0].expected_output, "result");
    }
}