ruchy 4.2.0

A systems scripting language that transpiles to idiomatic Rust with extreme quality engineering
Documentation
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
500
501
502
503
504
505
506
507
508
//! Code instrumentation for coverage tracking
//!
//! [RUCHY-206] Instrument Ruchy code for runtime coverage collection
use anyhow::Result;
use std::collections::{HashMap, HashSet};
/// Runtime coverage collector
pub struct CoverageInstrumentation {
    /// Map of file -> set of executed line numbers
    pub executed_lines: HashMap<String, HashSet<usize>>,
    /// Map of file -> set of executed function names
    pub executed_functions: HashMap<String, HashSet<String>>,
    /// Map of file -> branch execution counts
    pub executed_branches: HashMap<String, HashMap<String, usize>>,
}
impl CoverageInstrumentation {
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::instrumentation::CoverageInstrumentation;
    /// let instance = CoverageInstrumentation::new();
    /// ```
    pub fn new() -> Self {
        Self {
            executed_lines: HashMap::new(),
            executed_functions: HashMap::new(),
            executed_branches: HashMap::new(),
        }
    }
    /// Mark a line as executed
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::instrumentation::CoverageInstrumentation;
    /// let mut instance = CoverageInstrumentation::new();
    /// instance.mark_line_executed("test.rs", 42);
    /// ```
    pub fn mark_line_executed(&mut self, file: &str, line: usize) {
        self.executed_lines
            .entry(file.to_string())
            .or_default()
            .insert(line);
    }
    /// Mark a function as executed
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::instrumentation::CoverageInstrumentation;
    /// let mut instance = CoverageInstrumentation::new();
    /// instance.mark_function_executed("test.rs", "main");
    /// ```
    pub fn mark_function_executed(&mut self, file: &str, function: &str) {
        self.executed_functions
            .entry(file.to_string())
            .or_default()
            .insert(function.to_string());
    }
    /// Mark a branch as executed
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::instrumentation::CoverageInstrumentation;
    /// let mut instance = CoverageInstrumentation::new();
    /// instance.mark_branch_executed("test.rs", "branch_1");
    /// ```
    pub fn mark_branch_executed(&mut self, file: &str, branch_id: &str) {
        *self
            .executed_branches
            .entry(file.to_string())
            .or_default()
            .entry(branch_id.to_string())
            .or_default() += 1;
    }
    /// Get executed lines for a file
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::instrumentation::CoverageInstrumentation;
    /// let mut instance = CoverageInstrumentation::new();
    /// let lines = instance.get_executed_lines("test.rs");
    /// ```
    pub fn get_executed_lines(&self, file: &str) -> Option<&HashSet<usize>> {
        self.executed_lines.get(file)
    }
    /// Get executed functions for a file
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::instrumentation::get_executed_functions;
    ///
    /// let functions = instance.get_executed_functions("test.rs");
    /// assert!(functions.is_some());
    /// ```
    pub fn get_executed_functions(&self, file: &str) -> Option<&HashSet<String>> {
        self.executed_functions.get(file)
    }
    /// Get branch execution counts for a file
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::instrumentation::CoverageInstrumentation;
    /// let mut instance = CoverageInstrumentation::new();
    /// let branches = instance.get_executed_branches("test.rs");
    /// ```
    pub fn get_executed_branches(&self, file: &str) -> Option<&HashMap<String, usize>> {
        self.executed_branches.get(file)
    }
    /// Merge coverage data from another instrumentation instance
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::instrumentation::merge;
    ///
    /// let mut instance = CoverageInstrumentation::new();
    /// let other = CoverageInstrumentation::new();
    /// instance.merge(&other);
    /// ```
    pub fn merge(&mut self, other: &CoverageInstrumentation) {
        // Merge executed lines
        for (file, lines) in &other.executed_lines {
            let entry = self.executed_lines.entry(file.clone()).or_default();
            for line in lines {
                entry.insert(*line);
            }
        }
        // Merge executed functions
        for (file, functions) in &other.executed_functions {
            let entry = self.executed_functions.entry(file.clone()).or_default();
            for function in functions {
                entry.insert(function.clone());
            }
        }
        // Merge branch counts
        for (file, branches) in &other.executed_branches {
            let entry = self.executed_branches.entry(file.clone()).or_default();
            for (branch_id, count) in branches {
                *entry.entry(branch_id.clone()).or_default() += count;
            }
        }
    }
}
impl Default for CoverageInstrumentation {
    fn default() -> Self {
        Self::new()
    }
}
/// Add instrumentation to Ruchy source code
/// # Examples
///
/// ```ignore
/// use ruchy::quality::instrumentation::instrument_source;
///
/// let result = instrument_source("println(\"hello\")", "test.rs");
/// assert!(result.is_ok());
/// ```
pub fn instrument_source(source: &str, file_path: &str) -> Result<String> {
    let lines: Vec<&str> = source.lines().collect();
    let mut instrumented = String::new();
    // Add coverage initialization at the top
    instrumented.push_str(&format!("// Coverage instrumentation for {file_path}\n"));
    instrumented.push_str("let __coverage = CoverageInstrumentation::new();\n\n");
    for (line_num, line) in lines.iter().enumerate() {
        let actual_line_num = line_num + 1;
        let trimmed = line.trim();
        // Skip empty lines and comments
        if trimmed.is_empty() || trimmed.starts_with("//") {
            instrumented.push_str(line);
            instrumented.push('\n');
            continue;
        }
        // Add line execution tracking before executable statements
        if is_executable_line(trimmed) {
            instrumented.push_str(&format!(
                "__coverage.mark_line_executed(\"{file_path}\", {actual_line_num});\n"
            ));
        }
        // Instrument function declarations
        if trimmed.starts_with("fn ") || trimmed.starts_with("fun ") {
            let function_name = extract_function_name(trimmed);
            instrumented.push_str(&format!(
                "__coverage.mark_function_executed(\"{file_path}\", \"{function_name}\");\n"
            ));
        }
        // Add the original line
        instrumented.push_str(line);
        instrumented.push('\n');
    }
    Ok(instrumented)
}
/// Check if a line contains executable code (not just declarations)
fn is_executable_line(line: &str) -> bool {
    let trimmed = line.trim();
    // Check control flow (complexity: 4)
    if is_control_flow_statement(trimmed) {
        return true;
    }
    // Check declarations (complexity: 3)
    if is_declaration_statement(trimmed) {
        return false;
    }
    // Check block starts (complexity: 2)
    if is_block_start(trimmed) {
        return false;
    }
    // Check executable statements (complexity: 1)
    is_executable_statement(trimmed)
}
/// Check if line is a control flow statement (complexity: 4)
fn is_control_flow_statement(trimmed: &str) -> bool {
    trimmed.starts_with("if ")
        || trimmed.starts_with("while ")
        || trimmed.starts_with("for ")
        || trimmed.starts_with("match ")
}
/// Check if line is a declaration (complexity: 7)
fn is_declaration_statement(trimmed: &str) -> bool {
    trimmed.starts_with("fn ")
        || trimmed.starts_with("fun ")
        || trimmed.starts_with("struct ")
        || trimmed.starts_with("enum ")
        || trimmed.starts_with("use ")
        || trimmed.starts_with("mod ")
        || trimmed.starts_with("#[")
}
/// Check if line starts a block (complexity: 2)
fn is_block_start(trimmed: &str) -> bool {
    trimmed.ends_with('{') && !trimmed.contains('=')
}
/// Check if line contains executable statement (complexity: 4)
fn is_executable_statement(trimmed: &str) -> bool {
    trimmed.contains('=')
        || trimmed.contains("println")
        || trimmed.contains("assert")
        || trimmed.contains("return")
}
/// Extract function name from function declaration
fn extract_function_name(line: &str) -> String {
    let parts: Vec<&str> = line.split_whitespace().collect();
    if parts.len() >= 2 {
        parts[1].split('(').next().unwrap_or("unknown").to_string()
    } else {
        "unknown".to_string()
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_coverage_instrumentation() {
        let mut coverage = CoverageInstrumentation::new();
        coverage.mark_line_executed("test.ruchy", 5);
        coverage.mark_function_executed("test.ruchy", "main");
        coverage.mark_branch_executed("test.ruchy", "if_1");
        assert!(coverage
            .get_executed_lines("test.ruchy")
            .expect("operation should succeed in test")
            .contains(&5));
        assert!(coverage
            .get_executed_functions("test.ruchy")
            .expect("operation should succeed in test")
            .contains("main"));
        assert_eq!(
            coverage
                .get_executed_branches("test.ruchy")
                .expect("operation should succeed in test")
                .get("if_1"),
            Some(&1)
        );
    }
    #[test]
    fn test_is_executable_line() {
        assert!(is_executable_line("let x = 5;"));
        assert!(is_executable_line("println(\"hello\");"));
        assert!(is_executable_line("return x + 1;"));
        assert!(is_executable_line("if x > 0 {"));
        assert!(!is_executable_line("fn main() {"));
        assert!(!is_executable_line("struct Point {"));
        assert!(!is_executable_line(
            "use std::collections::HashMap;
#[cfg(test)]
use proptest::prelude::*;
"
        ));
        assert!(!is_executable_line("// comment"));
        assert!(!is_executable_line(""));
    }
    #[test]
    fn test_extract_function_name() {
        assert_eq!(extract_function_name("fn main() {"), "main");
        assert_eq!(
            extract_function_name("fun test_function(x: i32) -> i32 {"),
            "test_function"
        );
        assert_eq!(
            extract_function_name("fn add(a: i32, b: i32) -> i32 {"),
            "add"
        );
    }
    #[test]
    fn test_merge_coverage() {
        let mut coverage1 = CoverageInstrumentation::new();
        coverage1.mark_line_executed("test.ruchy", 1);
        coverage1.mark_function_executed("test.ruchy", "func1");
        let mut coverage2 = CoverageInstrumentation::new();
        coverage2.mark_line_executed("test.ruchy", 2);
        coverage2.mark_function_executed("test.ruchy", "func2");
        coverage1.merge(&coverage2);
        let lines = coverage1
            .get_executed_lines("test.ruchy")
            .expect("operation should succeed in test");
        assert!(lines.contains(&1));
        assert!(lines.contains(&2));
        let functions = coverage1
            .get_executed_functions("test.ruchy")
            .expect("operation should succeed in test");
        assert!(functions.contains("func1"));
        assert!(functions.contains("func2"));
    }
}
#[cfg(test)]
mod property_tests_instrumentation {
    use proptest::proptest;

    proptest! {
        /// Property: Function never panics on any input
        #[test]
        fn test_new_never_panics(input: String) {
            // Limit input size to avoid timeout
            let _input = if input.len() > 100 { &input[..100] } else { &input[..] };
            // Function should not panic on any input
            let _ = std::panic::catch_unwind(|| {
                // Call function with various inputs
                // This is a template - adjust based on actual function signature
            });
        }
    }
}

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

    // COVERAGE-95: Additional tests

    #[test]
    fn test_coverage_instrumentation_default() {
        let coverage = CoverageInstrumentation::default();
        assert!(coverage.executed_lines.is_empty());
        assert!(coverage.executed_functions.is_empty());
        assert!(coverage.executed_branches.is_empty());
    }

    #[test]
    fn test_get_executed_lines_none() {
        let coverage = CoverageInstrumentation::new();
        assert!(coverage.get_executed_lines("nonexistent.rs").is_none());
    }

    #[test]
    fn test_get_executed_functions_none() {
        let coverage = CoverageInstrumentation::new();
        assert!(coverage.get_executed_functions("nonexistent.rs").is_none());
    }

    #[test]
    fn test_get_executed_branches_none() {
        let coverage = CoverageInstrumentation::new();
        assert!(coverage.get_executed_branches("nonexistent.rs").is_none());
    }

    #[test]
    fn test_mark_line_executed_multiple_files() {
        let mut coverage = CoverageInstrumentation::new();
        coverage.mark_line_executed("file1.rs", 1);
        coverage.mark_line_executed("file2.rs", 2);
        coverage.mark_line_executed("file1.rs", 3);

        let file1_lines = coverage.get_executed_lines("file1.rs").unwrap();
        assert!(file1_lines.contains(&1));
        assert!(file1_lines.contains(&3));
        assert_eq!(file1_lines.len(), 2);

        let file2_lines = coverage.get_executed_lines("file2.rs").unwrap();
        assert!(file2_lines.contains(&2));
    }

    #[test]
    fn test_mark_branch_executed_increments() {
        let mut coverage = CoverageInstrumentation::new();
        coverage.mark_branch_executed("test.rs", "branch_1");
        coverage.mark_branch_executed("test.rs", "branch_1");
        coverage.mark_branch_executed("test.rs", "branch_1");

        let branches = coverage.get_executed_branches("test.rs").unwrap();
        assert_eq!(branches.get("branch_1"), Some(&3));
    }

    #[test]
    fn test_merge_branch_counts_accumulate() {
        let mut coverage1 = CoverageInstrumentation::new();
        coverage1.mark_branch_executed("test.rs", "branch_1");
        coverage1.mark_branch_executed("test.rs", "branch_1");

        let mut coverage2 = CoverageInstrumentation::new();
        coverage2.mark_branch_executed("test.rs", "branch_1");
        coverage2.mark_branch_executed("test.rs", "branch_2");

        coverage1.merge(&coverage2);

        let branches = coverage1.get_executed_branches("test.rs").unwrap();
        assert_eq!(branches.get("branch_1"), Some(&3));
        assert_eq!(branches.get("branch_2"), Some(&1));
    }

    #[test]
    fn test_instrument_source_basic() {
        let source = "let x = 5;\nprintln(x);";
        let result = instrument_source(source, "test.ruchy").unwrap();
        assert!(result.contains("Coverage instrumentation"));
        assert!(result.contains("CoverageInstrumentation::new()"));
    }

    #[test]
    fn test_instrument_source_empty_lines() {
        let source = "\n\n// comment\n";
        let result = instrument_source(source, "test.ruchy").unwrap();
        assert!(result.contains("// comment"));
    }

    #[test]
    fn test_instrument_source_function() {
        let source = "fn main() { println(\"hello\"); }";
        let result = instrument_source(source, "test.ruchy").unwrap();
        assert!(result.contains("mark_function_executed"));
    }

    #[test]
    fn test_instrument_source_fun_keyword() {
        let source = "fun add(a, b) { a + b }";
        let result = instrument_source(source, "test.ruchy").unwrap();
        assert!(result.contains("mark_function_executed"));
        assert!(result.contains("\"add\""));
    }

    #[test]
    fn test_is_control_flow_statement_while() {
        assert!(is_control_flow_statement("while x > 0 {"));
    }

    #[test]
    fn test_is_control_flow_statement_for() {
        assert!(is_control_flow_statement("for i in 0..10 {"));
    }

    #[test]
    fn test_is_control_flow_statement_match() {
        assert!(is_control_flow_statement("match x {"));
    }

    #[test]
    fn test_is_declaration_statement_mod() {
        assert!(is_declaration_statement("mod tests;"));
    }

    #[test]
    fn test_is_declaration_statement_attribute() {
        assert!(is_declaration_statement("#[derive(Debug)]"));
    }

    #[test]
    fn test_is_block_start() {
        assert!(is_block_start("impl Foo {"));
        assert!(!is_block_start("let x = Foo {"));
    }

    #[test]
    fn test_is_executable_statement_assert() {
        assert!(is_executable_statement("assert!(x > 0);"));
    }

    #[test]
    fn test_extract_function_name_short() {
        assert_eq!(extract_function_name("fn"), "unknown");
    }

    #[test]
    fn test_merge_empty() {
        let mut coverage1 = CoverageInstrumentation::new();
        let coverage2 = CoverageInstrumentation::new();
        coverage1.merge(&coverage2);
        assert!(coverage1.executed_lines.is_empty());
    }

    #[test]
    fn test_merge_multiple_files() {
        let mut coverage1 = CoverageInstrumentation::new();
        coverage1.mark_line_executed("file1.rs", 1);

        let mut coverage2 = CoverageInstrumentation::new();
        coverage2.mark_line_executed("file2.rs", 1);
        coverage2.mark_function_executed("file2.rs", "test");

        coverage1.merge(&coverage2);

        assert!(coverage1.get_executed_lines("file1.rs").is_some());
        assert!(coverage1.get_executed_lines("file2.rs").is_some());
        assert!(coverage1.get_executed_functions("file2.rs").is_some());
    }
}