ruchy 4.1.2

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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
// SPRINT3-002: Complexity analysis implementation
// PMAT Complexity: <10 per function
use crate::notebook::testing::types::{Cell, CellType, Notebook};
#[derive(Debug, Clone)]
pub struct ComplexityConfig {
    pub cyclomatic_threshold: usize,
    pub cognitive_threshold: usize,
    pub enable_suggestions: bool,
}
impl Default for ComplexityConfig {
    fn default() -> Self {
        Self {
            cyclomatic_threshold: 10,
            cognitive_threshold: 15,
            enable_suggestions: true,
        }
    }
}
#[derive(Debug, Clone, PartialEq)]
pub enum TimeComplexity {
    O1,     // Constant
    OLogN,  // Logarithmic
    ON,     // Linear
    ONLogN, // Linearithmic
    ON2,    // Quadratic
    ON3,    // Cubic
    OExp,   // Exponential
}
#[derive(Debug, Clone, PartialEq)]
pub enum SpaceComplexity {
    O1,    // Constant
    OLogN, // Logarithmic
    ON,    // Linear
    ON2,   // Quadratic
}
#[derive(Debug, Clone)]
pub struct ComplexityResult {
    pub time_complexity: TimeComplexity,
    pub space_complexity: SpaceComplexity,
    pub cyclomatic_complexity: usize,
    pub cognitive_complexity: usize,
    pub halstead_metrics: HalsteadMetrics,
}
#[derive(Debug, Clone)]
pub struct HalsteadMetrics {
    pub volume: f64,
    pub difficulty: f64,
    pub effort: f64,
}
#[derive(Debug, Clone)]
pub struct Hotspot {
    pub cell_id: String,
    pub complexity: TimeComplexity,
    pub impact: f64,
    pub location: String,
}

/// Complexity analyzer for notebook code
pub struct ComplexityAnalyzer {
    config: ComplexityConfig,
}

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

impl ComplexityAnalyzer {
    /// # Examples
    ///
    /// ```
    /// use ruchy::notebook::testing::complexity::ComplexityAnalyzer;
    ///
    /// let instance = ComplexityAnalyzer::new();
    /// // Verify behavior
    /// ```
    pub fn new() -> Self {
        Self {
            config: ComplexityConfig::default(),
        }
    }
    /// # Examples
    ///
    /// ```
    /// use ruchy::notebook::testing::complexity::ComplexityAnalyzer;
    ///
    /// let mut instance = ComplexityAnalyzer::new();
    /// let result = instance.with_config();
    /// // Verify behavior
    /// ```
    pub fn with_config(config: ComplexityConfig) -> Self {
        Self { config }
    }
    /// # Examples
    ///
    /// ```
    /// use ruchy::notebook::testing::complexity::ComplexityAnalyzer;
    ///
    /// let mut instance = ComplexityAnalyzer::new();
    /// let result = instance.get_default_threshold();
    /// // Verify behavior
    /// ```
    pub fn get_default_threshold(&self) -> usize {
        self.config.cyclomatic_threshold
    }
    /// Analyze complexity of a cell
    /// # Examples
    ///
    /// ```
    /// use ruchy::notebook::testing::complexity::ComplexityAnalyzer;
    ///
    /// let mut instance = ComplexityAnalyzer::new();
    /// let result = instance.analyze();
    /// // Verify behavior
    /// ```
    pub fn analyze(&self, cell: &Cell) -> ComplexityResult {
        let source = &cell.source;
        // Analyze time complexity
        let time_complexity = self.analyze_time_complexity(source);
        // Analyze space complexity
        let space_complexity = self.analyze_space_complexity(source);
        // Calculate cyclomatic complexity
        let cyclomatic = self.calculate_cyclomatic(source);
        // Calculate cognitive complexity
        let cognitive = self.calculate_cognitive(source);
        // Calculate Halstead metrics
        let halstead = self.calculate_halstead(source);
        ComplexityResult {
            time_complexity,
            space_complexity,
            cyclomatic_complexity: cyclomatic,
            cognitive_complexity: cognitive,
            halstead_metrics: halstead,
        }
    }
    fn analyze_time_complexity(&self, source: &str) -> TimeComplexity {
        // ISSUE-142 FIX: Check for recursion FIRST before loop analysis
        let recursive_calls = self.count_recursive_calls(source);
        let loop_depth = self.count_loop_depth(source);

        // Recursion detection (Issue #142)
        if recursive_calls >= 2 {
            // Multiple recursive calls = exponential (fibonacci, tribonacci, etc.)
            TimeComplexity::OExp
        } else if recursive_calls == 1 && loop_depth >= 1 {
            // Single recursion + loop = exponential or worse
            TimeComplexity::OExp
        } else if recursive_calls == 1 {
            // Single recursive call = linear (factorial, sum, etc.)
            TimeComplexity::ON
        } else {
            // No recursion - analyze loops only
            self.analyze_loop_complexity(source, loop_depth)
        }
    }

    /// Analyze complexity based on loop depth only (no recursion)
    /// Extracted from `analyze_time_complexity` to reduce complexity
    /// Complexity: 6 (≤10 ✓)
    fn analyze_loop_complexity(&self, source: &str, loop_depth: usize) -> TimeComplexity {
        match loop_depth {
            0 => {
                if source.contains("sort") {
                    TimeComplexity::ONLogN
                } else if source.contains("binary_search") {
                    TimeComplexity::OLogN
                } else {
                    TimeComplexity::O1
                }
            }
            1 => TimeComplexity::ON,
            2 => TimeComplexity::ON2,
            3 => TimeComplexity::ON3,
            _ => TimeComplexity::OExp,
        }
    }
    fn analyze_space_complexity(&self, source: &str) -> SpaceComplexity {
        if source.contains("Array(n).fill(0).map(() => Array(n)") {
            SpaceComplexity::ON2
        } else if source.contains("Array(n)") || source.contains("vec![") {
            SpaceComplexity::ON
        } else if source.contains("recursive") || source.contains("fn ") {
            SpaceComplexity::OLogN // Stack space for recursion
        } else {
            SpaceComplexity::O1
        }
    }
    fn calculate_cyclomatic(&self, source: &str) -> usize {
        let mut complexity = 1; // Base complexity
                                // Decision points
        complexity += source.matches("if ").count();
        complexity += source.matches("else if").count();
        complexity += source.matches("for ").count();
        complexity += source.matches("while ").count();
        complexity += source.matches("match ").count();
        complexity += source.matches("&&").count();
        complexity += source.matches("||").count();
        complexity
    }
    fn calculate_cognitive(&self, source: &str) -> usize {
        let mut complexity = 0;
        let mut nesting_level = 0;
        for line in source.lines() {
            let trimmed = line.trim();
            // Increase nesting for blocks
            if trimmed.contains('{') {
                nesting_level += 1;
            }
            // Add complexity for control flow at current nesting
            if trimmed.starts_with("if ") || trimmed.starts_with("else if") {
                complexity += 1 + nesting_level;
            }
            if trimmed.starts_with("for ") || trimmed.starts_with("while ") {
                complexity += 1 + nesting_level;
            }
            // Decrease nesting
            if trimmed.contains('}') && nesting_level > 0 {
                nesting_level -= 1;
            }
        }
        if complexity == 0 {
            complexity = 1;
        }
        complexity
    }
    fn calculate_halstead(&self, source: &str) -> HalsteadMetrics {
        // Simplified Halstead metrics
        let operators = source.matches(|c: char| "+-*/%=<>!&|".contains(c)).count();
        let operands = source
            .split_whitespace()
            .filter(|w| w.parse::<f64>().is_ok() || w.starts_with('"'))
            .count();
        let n1 = operators.max(1) as f64;
        let n2 = operands.max(1) as f64;
        let n = n1 + n2;
        let volume = n * n.log2();
        let difficulty = (n1 / 2.0) * (n2 / n2.max(1.0));
        let effort = volume * difficulty;
        HalsteadMetrics {
            volume,
            difficulty,
            effort,
        }
    }
    fn count_loop_depth(&self, source: &str) -> usize {
        let mut max_depth: usize = 0;
        let mut current_depth: usize = 0;
        for line in source.lines() {
            if line.trim().starts_with("for ") || line.trim().starts_with("while ") {
                current_depth += 1;
                max_depth = max_depth.max(current_depth);
            }
            if line.contains('}') {
                current_depth = current_depth.saturating_sub(1);
            }
        }
        max_depth
    }

    /// Count recursive function calls (Issue #142)
    /// Detects branching recursion like fibonacci(n-1) + fibonacci(n-2)
    /// Complexity: 6 (simple string analysis with helper)
    fn count_recursive_calls(&self, source: &str) -> usize {
        // Extract function name from source
        let func_name = self.extract_function_name(source);

        if func_name.is_empty() {
            return 0; // No function found
        }

        // Count how many times function calls itself
        // Look for patterns like: func_name( or func_name (
        let pattern1 = format!("{func_name}(");
        let pattern2 = format!("{func_name} (");

        let count =
            source.matches(pattern1.as_str()).count() + source.matches(pattern2.as_str()).count();

        // Subtract 1 for the function definition itself
        count.saturating_sub(1)
    }

    /// Extract function name from source code (helper for recursion detection)
    /// Looks for patterns: "fun name(" or "fn name("
    /// Complexity: 4 (simple string parsing)
    fn extract_function_name(&self, source: &str) -> String {
        for line in source.lines() {
            let trimmed = line.trim();
            // Match Ruchy syntax: "fun function_name(" or "pub fun function_name("
            if let Some(start) = trimmed.find("fun ") {
                let after_fun = &trimmed[start + 4..];
                if let Some(paren) = after_fun.find('(') {
                    return after_fun[..paren].trim().to_string();
                }
            }
            // Match Rust syntax: "fn function_name("
            if let Some(start) = trimmed.find("fn ") {
                let after_fn = &trimmed[start + 3..];
                if let Some(paren) = after_fn.find('(') {
                    return after_fn[..paren].trim().to_string();
                }
            }
        }
        String::new() // No function found
    }

    /// Find performance hotspots in a notebook
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::notebook::testing::complexity::find_hotspots;
    ///
    /// let result = find_hotspots(());
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn find_hotspots(&self, notebook: &Notebook) -> Vec<Hotspot> {
        let mut hotspots = Vec::new();
        for cell in &notebook.cells {
            if matches!(cell.cell_type, CellType::Code) {
                let result = self.analyze(cell);
                // Check if it's a hotspot
                let is_hotspot = matches!(
                    result.time_complexity,
                    TimeComplexity::ON2 | TimeComplexity::ON3 | TimeComplexity::OExp
                ) || result.cyclomatic_complexity
                    > self.config.cyclomatic_threshold;
                if is_hotspot {
                    let impact = self.calculate_impact(&result);
                    hotspots.push(Hotspot {
                        cell_id: cell.id.clone(),
                        complexity: result.time_complexity,
                        impact,
                        location: format!("Cell {}", cell.id),
                    });
                }
            }
        }
        // Sort by impact
        hotspots.sort_by(|a, b| {
            b.impact
                .partial_cmp(&a.impact)
                .expect("Impact values must be valid f64 (not NaN) for sorting")
        });
        hotspots
    }
    fn calculate_impact(&self, result: &ComplexityResult) -> f64 {
        let time_weight = match result.time_complexity {
            TimeComplexity::O1 => 0.1,
            TimeComplexity::OLogN => 0.2,
            TimeComplexity::ON => 0.3,
            TimeComplexity::ONLogN => 0.5,
            TimeComplexity::ON2 => 0.7,
            TimeComplexity::ON3 => 0.9,
            TimeComplexity::OExp => 1.0,
        };
        let cyclo_weight = (result.cyclomatic_complexity as f64 / 20.0).min(1.0);
        time_weight * 0.7 + cyclo_weight * 0.3
    }
    /// Suggest optimizations for a cell
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::notebook::testing::complexity::suggest_optimizations;
    ///
    /// let result = suggest_optimizations(());
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn suggest_optimizations(&self, cell: &Cell) -> Vec<String> {
        let mut suggestions = Vec::new();
        if !self.config.enable_suggestions {
            return suggestions;
        }
        let result = self.analyze(cell);
        // Time complexity suggestions
        match result.time_complexity {
            TimeComplexity::ON2 | TimeComplexity::ON3 => {
                if cell.source.contains("for") && cell.source.contains("==") {
                    suggestions.push(
                        "Consider using a hash map or index for O(1) lookups instead of nested loops".to_string(),
                    );
                }
                if cell.source.contains("sort") {
                    suggestions.push(
                        "If data is partially sorted, consider using insertion sort or TimSort"
                            .to_string(),
                    );
                }
            }
            TimeComplexity::OExp => {
                suggestions.push(
                    "Exponential complexity detected - consider dynamic programming or memoization"
                        .to_string(),
                );
            }
            _ => {}
        }
        // Cyclomatic complexity suggestions
        if result.cyclomatic_complexity > self.config.cyclomatic_threshold {
            suggestions.push(format!(
                "High cyclomatic complexity ({}) - consider breaking into smaller functions",
                result.cyclomatic_complexity
            ));
        }
        // Cognitive complexity suggestions
        if result.cognitive_complexity > self.config.cognitive_threshold {
            suggestions.push(
                "High cognitive complexity - reduce nesting and simplify control flow".to_string(),
            );
        }
        suggestions
    }
}

#[cfg(test)]
mod test_issue_142_bigo_recursion {
    use crate::notebook::testing::complexity::{
        ComplexityAnalyzer, ComplexityConfig, ComplexityResult, HalsteadMetrics, Hotspot,
        SpaceComplexity, TimeComplexity,
    };
    use crate::notebook::testing::types::{Cell, CellMetadata, CellType};

    fn make_test_cell(id: &str, code: &str) -> Cell {
        Cell {
            id: id.to_string(),
            source: code.to_string(),
            cell_type: CellType::Code,
            metadata: CellMetadata { test: None },
        }
    }

    #[test]
    fn test_issue_142_recursive_fibonacci_should_be_exponential() {
        // Issue #142: fibonacci(n-1) + fibonacci(n-2) is O(2^n)
        let analyzer = ComplexityAnalyzer::new();
        let cell = make_test_cell(
            "fib",
            r"
pub fun fibonacci(n: i32) -> i32 {
    if n <= 1 {
        n
    } else {
        fibonacci(n - 1) + fibonacci(n - 2)
    }
}
",
        );

        let result = analyzer.analyze(&cell);
        assert_eq!(
            result.time_complexity,
            TimeComplexity::OExp,
            "Fibonacci with 2 recursive calls should be O(2^n) exponential"
        );
    }

    #[test]
    fn test_single_recursion_factorial_should_be_linear() {
        // Single recursive call is O(n)
        let analyzer = ComplexityAnalyzer::new();
        let cell = make_test_cell(
            "fact",
            r"
pub fun factorial(n: i32) -> i32 {
    if n <= 1 { 1 } else { n * factorial(n - 1) }
}
",
        );

        let result = analyzer.analyze(&cell);
        assert_eq!(
            result.time_complexity,
            TimeComplexity::ON,
            "Factorial with 1 recursive call should be O(n) linear"
        );
    }

    #[test]
    fn test_triple_recursion_should_be_exponential() {
        // Triple recursion is O(3^n)
        let analyzer = ComplexityAnalyzer::new();
        let cell = make_test_cell(
            "trib",
            r"
pub fun tribonacci(n: i32) -> i32 {
    if n <= 1 { n } 
    else { tribonacci(n-1) + tribonacci(n-2) + tribonacci(n-3) }
}
",
        );

        let result = analyzer.analyze(&cell);
        assert_eq!(
            result.time_complexity,
            TimeComplexity::OExp,
            "Tribonacci with 3 recursive calls should be O(3^n) exponential"
        );
    }

    #[test]
    fn test_non_recursive_linear_search() {
        // Simple loop, no recursion
        let analyzer = ComplexityAnalyzer::new();
        let cell = make_test_cell(
            "search",
            r"
pub fun search(arr: Vec<i32>, target: i32) -> bool {
    for x in arr {
        if x == target { return true; }
    }
    false
}
",
        );

        let result = analyzer.analyze(&cell);
        assert_eq!(
            result.time_complexity,
            TimeComplexity::ON,
            "Single loop should be O(n) linear"
        );
    }

    #[test]
    fn test_no_recursion_no_loops_should_be_constant() {
        let analyzer = ComplexityAnalyzer::new();
        let cell = make_test_cell(
            "add",
            r"
pub fun add(a: i32, b: i32) -> i32 {
    a + b
}
",
        );

        let result = analyzer.analyze(&cell);
        assert_eq!(
            result.time_complexity,
            TimeComplexity::O1,
            "Simple arithmetic should be O(1) constant"
        );
    }

    #[test]
    fn test_recursion_with_loop_should_be_exponential_or_worse() {
        // Recursion + loop combination
        let analyzer = ComplexityAnalyzer::new();
        let cell = make_test_cell(
            "weird",
            r"
pub fun weird_recursion(n: i32) -> i32 {
    if n <= 0 { return 0; }
    let mut sum = 0;
    for i in 0..n {
        sum += weird_recursion(n - 1);
    }
    sum
}
",
        );

        let result = analyzer.analyze(&cell);
        // Should be at least exponential (recursion in a loop)
        assert!(
            matches!(result.time_complexity, TimeComplexity::OExp),
            "Recursion inside loop should be exponential or worse"
        );
    }

    #[test]
    fn test_complexity_config_default() {
        let config = ComplexityConfig::default();
        assert_eq!(config.cyclomatic_threshold, 10);
        assert_eq!(config.cognitive_threshold, 15);
        assert!(config.enable_suggestions);
    }

    #[test]
    fn test_time_complexity_enum() {
        let tc = TimeComplexity::ON;
        assert_eq!(tc, TimeComplexity::ON);
        assert_ne!(tc, TimeComplexity::O1);
    }

    #[test]
    fn test_space_complexity_enum() {
        let sc = SpaceComplexity::ON;
        assert_eq!(sc, SpaceComplexity::ON);
        assert_ne!(sc, SpaceComplexity::O1);
    }

    #[test]
    fn test_complexity_analyzer_default() {
        let analyzer = ComplexityAnalyzer::default();
        assert_eq!(analyzer.get_default_threshold(), 10);
    }

    #[test]
    fn test_complexity_analyzer_with_config() {
        let config = ComplexityConfig {
            cyclomatic_threshold: 5,
            cognitive_threshold: 8,
            enable_suggestions: false,
        };
        let analyzer = ComplexityAnalyzer::with_config(config);
        assert_eq!(analyzer.get_default_threshold(), 5);
    }

    #[test]
    fn test_analyze_space_complexity_on2() {
        let analyzer = ComplexityAnalyzer::new();
        let cell = make_test_cell("matrix", "let m = Array(n).fill(0).map(() => Array(n))");
        let result = analyzer.analyze(&cell);
        assert_eq!(result.space_complexity, SpaceComplexity::ON2);
    }

    #[test]
    fn test_analyze_space_complexity_on() {
        let analyzer = ComplexityAnalyzer::new();
        let cell = make_test_cell("vec", "let v = vec![0; n];");
        let result = analyzer.analyze(&cell);
        assert_eq!(result.space_complexity, SpaceComplexity::ON);
    }

    #[test]
    fn test_calculate_cyclomatic_simple() {
        let analyzer = ComplexityAnalyzer::new();
        let cell = make_test_cell("simple", "let x = 1 + 2;");
        let result = analyzer.analyze(&cell);
        assert_eq!(result.cyclomatic_complexity, 1); // Base complexity only
    }

    #[test]
    fn test_calculate_cyclomatic_with_if() {
        let analyzer = ComplexityAnalyzer::new();
        let cell = make_test_cell("ifelse", "if x > 0 { y } else if x < 0 { z } else { w }");
        let result = analyzer.analyze(&cell);
        assert!(result.cyclomatic_complexity >= 3); // if + else if + base
    }

    #[test]
    fn test_calculate_cognitive_nested() {
        let analyzer = ComplexityAnalyzer::new();
        let cell = make_test_cell(
            "nested",
            r"
if a {
    if b {
        if c {
            x
        }
    }
}
",
        );
        let result = analyzer.analyze(&cell);
        assert!(result.cognitive_complexity > 1);
    }

    #[test]
    fn test_count_loop_depth_nested() {
        let analyzer = ComplexityAnalyzer::new();
        let cell = make_test_cell(
            "nested_loops",
            r"
for i in 0..n {
    for j in 0..m {
        x
    }
}
",
        );
        let result = analyzer.analyze(&cell);
        assert_eq!(result.time_complexity, TimeComplexity::ON2);
    }

    #[test]
    fn test_extract_function_name_fun() {
        let analyzer = ComplexityAnalyzer::new();
        let source = "fun myfunction(x: i32) -> i32 { x }";
        let name = analyzer.extract_function_name(source);
        assert_eq!(name, "myfunction");
    }

    #[test]
    fn test_extract_function_name_fn() {
        let analyzer = ComplexityAnalyzer::new();
        let source = "fn myfunction(x: i32) -> i32 { x }";
        let name = analyzer.extract_function_name(source);
        assert_eq!(name, "myfunction");
    }

    #[test]
    fn test_extract_function_name_none() {
        let analyzer = ComplexityAnalyzer::new();
        let source = "let x = 42;";
        let name = analyzer.extract_function_name(source);
        assert!(name.is_empty());
    }

    #[test]
    fn test_halstead_metrics() {
        let analyzer = ComplexityAnalyzer::new();
        let cell = make_test_cell("math", "let x = 1 + 2 * 3 - 4 / 5;");
        let result = analyzer.analyze(&cell);
        assert!(result.halstead_metrics.volume > 0.0);
        assert!(result.halstead_metrics.effort >= 0.0);
    }

    #[test]
    fn test_hotspot_struct() {
        let hotspot = Hotspot {
            cell_id: "cell1".to_string(),
            complexity: TimeComplexity::ON2,
            impact: 0.7,
            location: "Cell cell1".to_string(),
        };
        assert_eq!(hotspot.cell_id, "cell1");
        assert_eq!(hotspot.complexity, TimeComplexity::ON2);
    }

    #[test]
    fn test_complexity_result_fields() {
        let result = ComplexityResult {
            time_complexity: TimeComplexity::ON,
            space_complexity: SpaceComplexity::O1,
            cyclomatic_complexity: 5,
            cognitive_complexity: 3,
            halstead_metrics: HalsteadMetrics {
                volume: 10.0,
                difficulty: 2.0,
                effort: 20.0,
            },
        };
        assert_eq!(result.cyclomatic_complexity, 5);
        assert_eq!(result.cognitive_complexity, 3);
    }

    #[test]
    fn test_suggest_optimizations_disabled() {
        let config = ComplexityConfig {
            cyclomatic_threshold: 10,
            cognitive_threshold: 15,
            enable_suggestions: false,
        };
        let analyzer = ComplexityAnalyzer::with_config(config);
        let cell = make_test_cell("complex", "for i in arr { for j in arr { x } }");
        let suggestions = analyzer.suggest_optimizations(&cell);
        assert!(suggestions.is_empty());
    }

    #[test]
    fn test_analyze_loop_complexity_binary_search() {
        let analyzer = ComplexityAnalyzer::new();
        let cell = make_test_cell("bsearch", "binary_search(arr, target)");
        let result = analyzer.analyze(&cell);
        assert_eq!(result.time_complexity, TimeComplexity::OLogN);
    }

    #[test]
    fn test_analyze_loop_complexity_sort() {
        let analyzer = ComplexityAnalyzer::new();
        let cell = make_test_cell("sorting", "arr.sort()");
        let result = analyzer.analyze(&cell);
        assert_eq!(result.time_complexity, TimeComplexity::ONLogN);
    }
}