perl-tdd-support 0.13.1

Test-driven development helpers and test generation for the Perl LSP ecosystem
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
//! Basic TDD workflow support for LSP
//!
//! Simplified TDD implementation focused on core red-green-refactor cycle

use crate::ast::{Node, NodeKind};

/// Diagnostic produced during a TDD cycle (independent of `lsp_types`).
///
/// Used internally to track uncovered lines and code quality issues without
/// pulling in the full LSP dependency.
#[derive(Debug, Clone)]
pub struct Diagnostic {
    /// Byte offset range (start line, end line) - 0-indexed
    pub range: (usize, usize),
    /// Severity level
    pub severity: DiagnosticSeverity,
    /// Optional diagnostic code
    pub code: Option<String>,
    /// Human-readable message
    pub message: String,
    /// Related diagnostic information
    pub related_information: Vec<String>,
    /// Diagnostic tags
    pub tags: Vec<String>,
}

/// Severity level for a TDD-cycle [`Diagnostic`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiagnosticSeverity {
    /// A hard failure that must be resolved before the cycle can proceed.
    Error,
    /// A potential problem that should be addressed.
    Warning,
    /// Informational note, no action required.
    Information,
    /// Low-priority suggestion.
    Hint,
}

/// Basic test generator
pub struct TestGenerator {
    framework: String,
}

impl TestGenerator {
    /// Create a generator targeting `framework` (e.g. `"Test::More"` or `"Test2::V0"`).
    pub fn new(framework: &str) -> Self {
        Self { framework: framework.to_string() }
    }

    /// Generate basic test for a subroutine
    pub fn generate_test(&self, name: &str, params: usize) -> String {
        let args = (0..params).map(|i| format!("'arg{}'", i + 1)).collect::<Vec<_>>().join(", ");

        match self.framework.as_str() {
            "Test2::V0" => {
                format!(
                    "use Test2::V0;\n\n\
                     subtest '{}' => sub {{\n    \
                     my $result = {}({});\n    \
                     ok($result, 'Function returns value');\n\
                     }};\n\n\
                     done_testing();\n",
                    name, name, args
                )
            }
            _ => {
                // Default to Test::More
                format!(
                    "use Test::More;\n\n\
                     subtest '{}' => sub {{\n    \
                     my $result = {}({});\n    \
                     ok(defined $result, 'Function returns defined value');\n\
                     }};\n\n\
                     done_testing();\n",
                    name, name, args
                )
            }
        }
    }

    /// Find all subroutines in AST
    pub fn find_subroutines(&self, node: &Node) -> Vec<SubroutineInfo> {
        let mut subs = Vec::new();
        self.find_subroutines_recursive(node, &mut subs);
        subs
    }

    fn find_subroutines_recursive(&self, node: &Node, subs: &mut Vec<SubroutineInfo>) {
        match &node.kind {
            NodeKind::Subroutine { name, signature, .. } => {
                subs.push(SubroutineInfo {
                    name: name.clone().unwrap_or_else(|| "anonymous".to_string()),
                    param_count: signature
                        .as_ref()
                        .map(|s| {
                            if let NodeKind::Signature { parameters } = &s.kind {
                                parameters.len()
                            } else {
                                0
                            }
                        })
                        .unwrap_or(0),
                });
            }
            NodeKind::Program { statements } => {
                for stmt in statements {
                    self.find_subroutines_recursive(stmt, subs);
                }
            }
            NodeKind::Block { statements } => {
                for stmt in statements {
                    self.find_subroutines_recursive(stmt, subs);
                }
            }
            NodeKind::If { then_branch, elsif_branches, else_branch, .. } => {
                self.find_subroutines_recursive(then_branch, subs);
                for (_, branch) in elsif_branches {
                    self.find_subroutines_recursive(branch, subs);
                }
                if let Some(branch) = else_branch {
                    self.find_subroutines_recursive(branch, subs);
                }
            }
            NodeKind::While { body, continue_block, .. }
            | NodeKind::For { body, continue_block, .. } => {
                self.find_subroutines_recursive(body, subs);
                if let Some(cont) = continue_block {
                    self.find_subroutines_recursive(cont, subs);
                }
            }
            NodeKind::Foreach { body, .. }
            | NodeKind::Given { body, .. }
            | NodeKind::When { body, .. }
            | NodeKind::Default { body } => {
                self.find_subroutines_recursive(body, subs);
            }
            NodeKind::Package { block, .. } => {
                if let Some(blk) = block {
                    self.find_subroutines_recursive(blk, subs);
                }
            }
            NodeKind::Class { body, .. } => {
                self.find_subroutines_recursive(body, subs);
            }
            _ => {
                // Other node types don't contain subroutines
            }
        }
    }
}

/// Metadata about a subroutine discovered in an AST.
#[derive(Debug, Clone)]
pub struct SubroutineInfo {
    /// The subroutine name (`"anonymous"` for unnamed subs).
    pub name: String,
    /// Number of declared parameters in the signature.
    pub param_count: usize,
}

/// Basic refactoring analyzer
pub struct RefactoringAnalyzer {
    max_complexity: usize,
    max_lines: usize,
    max_params: usize,
}

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

impl RefactoringAnalyzer {
    /// Create an analyzer with default thresholds (complexity ≤ 10, lines ≤ 50, params ≤ 5).
    pub fn new() -> Self {
        Self { max_complexity: 10, max_lines: 50, max_params: 5 }
    }

    /// Analyze code and suggest refactorings
    pub fn analyze(&self, node: &Node, source: &str) -> Vec<RefactoringSuggestion> {
        let mut suggestions = Vec::new();
        self.analyze_recursive(node, source, &mut suggestions);
        suggestions
    }

    fn analyze_recursive(
        &self,
        node: &Node,
        source: &str,
        suggestions: &mut Vec<RefactoringSuggestion>,
    ) {
        match &node.kind {
            NodeKind::Subroutine { name, signature, body, .. } => {
                let sub_name = name.clone().unwrap_or_else(|| "anonymous".to_string());

                // Check parameter count
                let param_count = signature
                    .as_ref()
                    .map(|s| {
                        if let NodeKind::Signature { parameters } = &s.kind {
                            parameters.len()
                        } else {
                            0
                        }
                    })
                    .unwrap_or(0);
                if param_count > self.max_params {
                    suggestions.push(RefactoringSuggestion {
                        title: format!("Too many parameters in {}", sub_name),
                        description: format!(
                            "Function has {} parameters, consider using a hash",
                            param_count
                        ),
                        category: RefactoringCategory::TooManyParameters,
                    });
                }

                // Check complexity
                let complexity = self.calculate_complexity(body);
                if complexity > self.max_complexity {
                    suggestions.push(RefactoringSuggestion {
                        title: format!("High complexity in {}", sub_name),
                        description: format!(
                            "Cyclomatic complexity is {}, consider breaking into smaller functions",
                            complexity
                        ),
                        category: RefactoringCategory::HighComplexity,
                    });
                }

                // Check length
                let lines = self.count_lines(body, source);
                if lines > self.max_lines {
                    suggestions.push(RefactoringSuggestion {
                        title: format!("Long method: {}", sub_name),
                        description: format!(
                            "Method has {} lines, consider breaking into smaller functions",
                            lines
                        ),
                        category: RefactoringCategory::LongMethod,
                    });
                }

                // Recurse into body
                self.analyze_recursive(body, source, suggestions);
            }
            NodeKind::Program { statements } | NodeKind::Block { statements } => {
                for stmt in statements {
                    self.analyze_recursive(stmt, source, suggestions);
                }
            }
            NodeKind::If { then_branch, elsif_branches, else_branch, .. } => {
                self.analyze_recursive(then_branch, source, suggestions);
                for (_, branch) in elsif_branches {
                    self.analyze_recursive(branch, source, suggestions);
                }
                if let Some(branch) = else_branch {
                    self.analyze_recursive(branch, source, suggestions);
                }
            }
            NodeKind::While { body, .. }
            | NodeKind::For { body, .. }
            | NodeKind::Foreach { body, .. }
            | NodeKind::Given { body, .. }
            | NodeKind::When { body, .. }
            | NodeKind::Default { body }
            | NodeKind::Class { body, .. } => {
                self.analyze_recursive(body, source, suggestions);
            }
            NodeKind::Package { block, .. } => {
                if let Some(blk) = block {
                    self.analyze_recursive(blk, source, suggestions);
                }
            }
            _ => {
                // Other node types don't need analysis
            }
        }
    }

    fn calculate_complexity(&self, node: &Node) -> usize {
        let mut complexity = 1;
        self.count_decision_points(node, &mut complexity);
        complexity
    }

    fn count_decision_points(&self, node: &Node, complexity: &mut usize) {
        match &node.kind {
            NodeKind::If { elsif_branches, .. } => {
                *complexity += 1 + elsif_branches.len();
            }
            NodeKind::While { .. } | NodeKind::For { .. } | NodeKind::Foreach { .. } => {
                *complexity += 1;
            }
            NodeKind::Binary { op, left, right } => {
                if op == "&&" || op == "||" || op == "and" || op == "or" {
                    *complexity += 1;
                }
                self.count_decision_points(left, complexity);
                self.count_decision_points(right, complexity);
                return;
            }
            _ => {}
        }

        // Recurse into children
        match &node.kind {
            NodeKind::Program { statements } | NodeKind::Block { statements } => {
                for stmt in statements {
                    self.count_decision_points(stmt, complexity);
                }
            }
            NodeKind::If { then_branch, elsif_branches, else_branch, .. } => {
                self.count_decision_points(then_branch, complexity);
                for (_, branch) in elsif_branches {
                    self.count_decision_points(branch, complexity);
                }
                if let Some(branch) = else_branch {
                    self.count_decision_points(branch, complexity);
                }
            }
            NodeKind::While { body, .. }
            | NodeKind::For { body, .. }
            | NodeKind::Foreach { body, .. }
            | NodeKind::Given { body, .. }
            | NodeKind::When { body, .. }
            | NodeKind::Default { body }
            | NodeKind::Class { body, .. } => {
                self.count_decision_points(body, complexity);
            }
            _ => {}
        }
    }

    fn count_lines(&self, node: &Node, source: &str) -> usize {
        let start = node.location.start;
        let end = node.location.end.min(source.len());

        if start >= end {
            return 0;
        }

        source[start..end].lines().count()
    }
}

/// A single refactoring suggestion produced by [`RefactoringAnalyzer`].
#[derive(Debug, Clone)]
pub struct RefactoringSuggestion {
    /// Short one-line title suitable for a menu item or notification.
    pub title: String,
    /// Longer explanation of why the refactoring is recommended.
    pub description: String,
    /// The kind of refactoring this suggestion belongs to.
    pub category: RefactoringCategory,
}

/// Category of refactoring opportunity identified by [`RefactoringAnalyzer`].
#[derive(Debug, Clone, PartialEq)]
pub enum RefactoringCategory {
    /// Subroutine has more parameters than the configured maximum.
    TooManyParameters,
    /// Cyclomatic complexity exceeds the configured threshold.
    HighComplexity,
    /// Subroutine body is longer than the configured line limit.
    LongMethod,
}

/// Simple TDD workflow state
#[derive(Debug, Clone, PartialEq)]
pub enum TddState {
    Red,
    Green,
    Refactor,
    Idle,
}

/// TDD workflow manager
pub struct TddWorkflow {
    state: TddState,
    generator: TestGenerator,
    analyzer: RefactoringAnalyzer,
}

impl TddWorkflow {
    /// Create a workflow manager using `framework` for test generation (e.g. `"Test::More"`).
    pub fn new(framework: &str) -> Self {
        Self {
            state: TddState::Idle,
            generator: TestGenerator::new(framework),
            analyzer: RefactoringAnalyzer::new(),
        }
    }

    /// Start TDD cycle
    pub fn start_cycle(&mut self, test_name: &str) -> TddResult {
        self.state = TddState::Red;
        TddResult {
            state: self.state.clone(),
            message: format!("Starting TDD cycle for '{}'", test_name),
        }
    }

    /// Run tests and update state
    pub fn run_tests(&mut self, success: bool) -> TddResult {
        self.state = if success { TddState::Green } else { TddState::Red };

        TddResult {
            state: self.state.clone(),
            message: if success {
                "Tests passing, ready to refactor".to_string()
            } else {
                "Tests failing, fix implementation".to_string()
            },
        }
    }

    /// Move to refactor phase
    pub fn start_refactor(&mut self) -> TddResult {
        self.state = TddState::Refactor;
        TddResult {
            state: self.state.clone(),
            message: "Refactoring phase - improve code while keeping tests green".to_string(),
        }
    }

    /// Complete cycle
    pub fn complete_cycle(&mut self) -> TddResult {
        self.state = TddState::Idle;
        TddResult { state: self.state.clone(), message: "TDD cycle complete".to_string() }
    }

    /// Generate test for function
    pub fn generate_test(&self, name: &str, params: usize) -> String {
        self.generator.generate_test(name, params)
    }

    /// Analyze code for refactoring
    pub fn analyze_for_refactoring(&self, ast: &Node, source: &str) -> Vec<RefactoringSuggestion> {
        self.analyzer.analyze(ast, source)
    }

    /// Get coverage diagnostics
    pub fn get_coverage_diagnostics(&self, uncovered_lines: &[usize]) -> Vec<Diagnostic> {
        uncovered_lines
            .iter()
            .map(|&line| Diagnostic {
                range: (line, line),
                severity: DiagnosticSeverity::Warning,
                code: Some("tdd.uncovered".to_string()),
                message: "Line not covered by tests".to_string(),
                related_information: vec![],
                tags: vec![],
            })
            .collect()
    }
}

/// Result returned from each [`TddWorkflow`] transition method.
#[derive(Debug, Clone)]
pub struct TddResult {
    /// The new TDD state after the transition.
    pub state: TddState,
    /// Human-readable description of what happened and what to do next.
    pub message: String,
}

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

    #[test]
    fn test_test_generation() {
        let generator = TestGenerator::new("Test::More");
        let test = generator.generate_test("add", 2);
        assert!(test.contains("Test::More"));
        assert!(test.contains("add"));
        assert!(test.contains("arg1"));
        assert!(test.contains("arg2"));
    }

    #[test]
    fn test_find_subroutines() {
        let ast = Node::new(
            NodeKind::Program {
                statements: vec![Node::new(
                    NodeKind::Subroutine {
                        name: Some("test_func".to_string()),
                        name_span: None,
                        prototype: None,
                        signature: None,
                        attributes: vec![],
                        body: Box::new(Node::new(
                            NodeKind::Block { statements: vec![] },
                            SourceLocation { start: 0, end: 0 },
                        )),
                    },
                    SourceLocation { start: 0, end: 0 },
                )],
            },
            SourceLocation { start: 0, end: 0 },
        );

        let generator = TestGenerator::new("Test::More");
        let subs = generator.find_subroutines(&ast);
        assert_eq!(subs.len(), 1);
        assert_eq!(subs[0].name, "test_func");
    }

    #[test]
    fn test_refactoring_suggestions() {
        let analyzer = RefactoringAnalyzer::new();

        // Create a subroutine with too many parameters
        let ast = Node::new(
            NodeKind::Subroutine {
                name: Some("complex".to_string()),
                name_span: None,
                prototype: None,
                signature: Some(Box::new(Node::new(
                    NodeKind::Signature {
                        parameters: vec![
                            Node::new(
                                NodeKind::MandatoryParameter {
                                    variable: Box::new(Node::new(
                                        NodeKind::Variable {
                                            sigil: "$".to_string(),
                                            name: "a".to_string(),
                                        },
                                        SourceLocation { start: 0, end: 0 },
                                    )),
                                },
                                SourceLocation { start: 0, end: 0 },
                            ),
                            Node::new(
                                NodeKind::MandatoryParameter {
                                    variable: Box::new(Node::new(
                                        NodeKind::Variable {
                                            sigil: "$".to_string(),
                                            name: "b".to_string(),
                                        },
                                        SourceLocation { start: 0, end: 0 },
                                    )),
                                },
                                SourceLocation { start: 0, end: 0 },
                            ),
                            Node::new(
                                NodeKind::MandatoryParameter {
                                    variable: Box::new(Node::new(
                                        NodeKind::Variable {
                                            sigil: "$".to_string(),
                                            name: "c".to_string(),
                                        },
                                        SourceLocation { start: 0, end: 0 },
                                    )),
                                },
                                SourceLocation { start: 0, end: 0 },
                            ),
                            Node::new(
                                NodeKind::MandatoryParameter {
                                    variable: Box::new(Node::new(
                                        NodeKind::Variable {
                                            sigil: "$".to_string(),
                                            name: "d".to_string(),
                                        },
                                        SourceLocation { start: 0, end: 0 },
                                    )),
                                },
                                SourceLocation { start: 0, end: 0 },
                            ),
                            Node::new(
                                NodeKind::MandatoryParameter {
                                    variable: Box::new(Node::new(
                                        NodeKind::Variable {
                                            sigil: "$".to_string(),
                                            name: "e".to_string(),
                                        },
                                        SourceLocation { start: 0, end: 0 },
                                    )),
                                },
                                SourceLocation { start: 0, end: 0 },
                            ),
                            Node::new(
                                NodeKind::MandatoryParameter {
                                    variable: Box::new(Node::new(
                                        NodeKind::Variable {
                                            sigil: "$".to_string(),
                                            name: "f".to_string(),
                                        },
                                        SourceLocation { start: 0, end: 0 },
                                    )),
                                },
                                SourceLocation { start: 0, end: 0 },
                            ),
                            // 6 parameters - more than max_params (5)
                        ],
                    },
                    SourceLocation { start: 0, end: 0 },
                ))),
                attributes: vec![],
                body: Box::new(Node::new(
                    NodeKind::Block { statements: vec![] },
                    SourceLocation { start: 0, end: 0 },
                )),
            },
            SourceLocation { start: 0, end: 0 },
        );

        let suggestions = analyzer.analyze(&ast, "sub complex($a, $b, $c, $d, $e, $f) { }");
        assert!(!suggestions.is_empty());
        assert!(suggestions.iter().any(|s| s.category == RefactoringCategory::TooManyParameters));
    }

    #[test]
    fn test_tdd_workflow() {
        let mut workflow = TddWorkflow::new("Test::More");

        // Start cycle
        let _result = workflow.start_cycle("add");
        assert_eq!(workflow.state, TddState::Red);

        // Run failing tests
        let _result = workflow.run_tests(false);
        assert_eq!(workflow.state, TddState::Red);

        // Run passing tests
        let _result = workflow.run_tests(true);
        assert_eq!(workflow.state, TddState::Green);

        // Start refactoring
        let _result = workflow.start_refactor();
        assert_eq!(workflow.state, TddState::Refactor);

        // Complete cycle
        let _result = workflow.complete_cycle();
        assert_eq!(workflow.state, TddState::Idle);
    }
}