debtmap 0.17.0

Code complexity and technical debt analyzer
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
//! Refined types for domain invariants
//!
//! This module implements the "parse, don't validate" pattern using stillwater's
//! refined types. Domain invariants are encoded in the type system, validated once
//! at system boundaries, and guaranteed throughout the codebase.
//!
//! # Philosophy
//!
//! Instead of scattering validation checks like:
//! ```ignore
//! fn set_threshold(value: u32) {
//!     assert!(value >= 1 && value <= 1000, "threshold out of range");
//!     // ...
//! }
//! ```
//!
//! We validate once at construction:
//! ```ignore
//! fn set_threshold(value: ComplexityThreshold) {
//!     // Type guarantees 1 <= value <= 1000
//!     // ...
//! }
//! ```
//!
//! # Available Types
//!
//! ## Threshold Types
//! - [`ComplexityThreshold`]: Cyclomatic complexity threshold (1-1000)
//! - [`CognitiveThreshold`]: Cognitive complexity threshold (1-500)
//! - [`NestingThreshold`]: Max nesting depth threshold (1-50)
//!
//! ## Score Types
//! - [`NormalizedScore`]: Percentage score (0-100)
//! - [`RiskScore`]: Risk factor in unit interval (0.0-1.0)
//!
//! ## Weight Types
//! - [`WeightFactor`]: Scoring weight in unit interval (0.0-1.0)
//! - [`Percentage`]: Integer percentage (0-100)
//!
//! # Example
//!
//! ```ignore
//! use debtmap::core::refined::{ComplexityThreshold, WeightFactor};
//!
//! // Validate at construction - returns Result
//! let threshold = ComplexityThreshold::new(25)?;
//!
//! // Use like the inner type via Deref
//! let doubled = *threshold * 2;
//!
//! // Extract inner value explicitly
//! let raw: u32 = threshold.into_inner();
//! ```

use serde::{Deserialize, Serialize};
use stillwater::refined::{InRange, Predicate, Refined};

// ============================================================================
// Custom Predicates
// ============================================================================

/// Predicate for floating-point values in the unit interval [0.0, 1.0].
///
/// Used for weights, probabilities, and normalized scores.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UnitInterval;

impl Predicate<f64> for UnitInterval {
    type Error = &'static str;

    fn check(value: &f64) -> Result<(), Self::Error> {
        if *value >= 0.0 && *value <= 1.0 {
            Ok(())
        } else {
            Err("value must be in range [0.0, 1.0]")
        }
    }
}

/// Predicate for positive f64 values (> 0.0).
///
/// Used for multipliers and factors that must be positive.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PositiveF64;

impl Predicate<f64> for PositiveF64 {
    type Error = &'static str;

    fn check(value: &f64) -> Result<(), Self::Error> {
        if *value > 0.0 {
            Ok(())
        } else {
            Err("value must be positive (> 0.0)")
        }
    }
}

/// Predicate for non-negative f64 values (>= 0.0).
///
/// Used for scores and metrics that cannot be negative.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NonNegativeF64;

impl Predicate<f64> for NonNegativeF64 {
    type Error = &'static str;

    fn check(value: &f64) -> Result<(), Self::Error> {
        if *value >= 0.0 {
            Ok(())
        } else {
            Err("value must be non-negative (>= 0.0)")
        }
    }
}

// ============================================================================
// Threshold Types
// ============================================================================

/// Cyclomatic complexity threshold.
///
/// Valid range: 1-1000. Cyclomatic complexity measures the number of
/// linearly independent paths through a function. Values above this
/// threshold indicate functions that may be difficult to test.
pub type ComplexityThreshold = Refined<u32, InRange<1, 1000>>;

/// Cognitive complexity threshold.
///
/// Valid range: 1-500. Cognitive complexity measures how difficult
/// code is to understand. Values above this threshold suggest the
/// code should be refactored for readability.
pub type CognitiveThreshold = Refined<u32, InRange<1, 500>>;

/// Maximum nesting depth threshold.
///
/// Valid range: 1-50. Deeply nested code is harder to understand
/// and maintain. This threshold flags excessive nesting.
pub type NestingThreshold = Refined<u32, InRange<1, 50>>;

/// Maximum function length threshold in lines.
///
/// Valid range: 1-1000. Long functions are harder to understand
/// and test. This threshold flags oversized functions.
pub type FunctionLengthThreshold = Refined<usize, InRange<1, 1000>>;

/// Maximum file length threshold in lines.
///
/// Valid range: 1-10000. Large files can indicate poor module
/// organization. This threshold flags oversized files.
pub type FileLengthThreshold = Refined<usize, InRange<1, 10000>>;

// ============================================================================
// Score Types
// ============================================================================

/// Normalized score as percentage (0-100).
///
/// Used for coverage percentages, quality scores, and other
/// metrics that are expressed as whole percentages.
pub type NormalizedScore = Refined<u32, InRange<0, 100>>;

/// Risk score in the unit interval [0.0, 1.0].
///
/// A floating-point score representing risk level where:
/// - 0.0 = no risk
/// - 1.0 = maximum risk
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RiskScore(f64);

impl RiskScore {
    /// Create a new risk score, validating it's in [0.0, 1.0].
    pub fn new(value: f64) -> Result<Self, &'static str> {
        UnitInterval::check(&value)?;
        Ok(Self(value))
    }

    /// Create a risk score without validation (for trusted sources).
    ///
    /// # Safety
    /// Caller must ensure value is in [0.0, 1.0].
    #[allow(dead_code)]
    pub fn new_unchecked(value: f64) -> Self {
        Self(value)
    }

    /// Get the inner value.
    pub fn into_inner(self) -> f64 {
        self.0
    }

    /// Get the inner value by reference.
    pub fn get(&self) -> f64 {
        self.0
    }
}

impl std::ops::Deref for RiskScore {
    type Target = f64;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Default for RiskScore {
    fn default() -> Self {
        Self(0.0)
    }
}

// ============================================================================
// Weight and Configuration Types
// ============================================================================

/// Weight factor for scoring calculations.
///
/// Valid range: [0.0, 1.0]. Used for configuring the relative
/// importance of different factors in scoring algorithms.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct WeightFactor(f64);

impl WeightFactor {
    /// Create a new weight factor, validating it's in [0.0, 1.0].
    pub fn new(value: f64) -> Result<Self, &'static str> {
        UnitInterval::check(&value)?;
        Ok(Self(value))
    }

    /// Create a weight factor without validation (for trusted sources).
    ///
    /// # Safety
    /// Caller must ensure value is in [0.0, 1.0].
    #[allow(dead_code)]
    pub fn new_unchecked(value: f64) -> Self {
        Self(value)
    }

    /// Get the inner value.
    pub fn into_inner(self) -> f64 {
        self.0
    }

    /// Get the inner value by reference.
    pub fn get(&self) -> f64 {
        self.0
    }
}

impl std::ops::Deref for WeightFactor {
    type Target = f64;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Default for WeightFactor {
    fn default() -> Self {
        Self(0.0)
    }
}

/// Integer percentage (0-100).
///
/// Used for configuration values that represent percentages
/// as whole numbers.
pub type Percentage = Refined<u32, InRange<0, 100>>;

/// Multiplier factor for scoring adjustments.
///
/// Valid range: (0.0, +inf). Must be positive. Used for role
/// multipliers and other scaling factors.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct MultiplierFactor(f64);

impl MultiplierFactor {
    /// Create a new multiplier, validating it's positive.
    pub fn new(value: f64) -> Result<Self, &'static str> {
        PositiveF64::check(&value)?;
        Ok(Self(value))
    }

    /// Create a multiplier without validation (for trusted sources).
    ///
    /// # Safety
    /// Caller must ensure value is positive.
    #[allow(dead_code)]
    pub fn new_unchecked(value: f64) -> Self {
        Self(value)
    }

    /// Get the inner value.
    pub fn into_inner(self) -> f64 {
        self.0
    }

    /// Get the inner value by reference.
    pub fn get(&self) -> f64 {
        self.0
    }
}

impl std::ops::Deref for MultiplierFactor {
    type Target = f64;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Default for MultiplierFactor {
    fn default() -> Self {
        Self(1.0)
    }
}

// ============================================================================
// Metric Types
// ============================================================================

/// Predicate for positive line counts (>= 1).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PositiveLineCount;

impl Predicate<usize> for PositiveLineCount {
    type Error = &'static str;

    fn check(value: &usize) -> Result<(), Self::Error> {
        if *value >= 1 && *value <= 1_000_000 {
            Ok(())
        } else {
            Err("line count must be in range [1, 1000000]")
        }
    }
}

/// Predicate for valid function counts (0-10000).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ValidFunctionCount;

impl Predicate<usize> for ValidFunctionCount {
    type Error = &'static str;

    fn check(value: &usize) -> Result<(), Self::Error> {
        if *value <= 10_000 {
            Ok(())
        } else {
            Err("function count must be <= 10000")
        }
    }
}

/// Line count for files and functions.
///
/// Valid range: 1-1000000. Represents the number of lines in a
/// code unit. Must be at least 1 (empty files are not analyzed).
pub type LineCount = Refined<usize, PositiveLineCount>;

/// Nesting depth of code blocks.
///
/// Valid range: 0-100. Represents how deeply nested the code is.
pub type NestingDepth = Refined<u32, InRange<0, 100>>;

/// Function count in a module or file.
///
/// Valid range: 0-10000. Represents the number of functions
/// in a code unit.
pub type FunctionCount = Refined<usize, ValidFunctionCount>;

/// Debt density per 1000 lines of code.
///
/// Valid range: [0.0, +inf). Used for scale-independent
/// quality metrics.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct DebtDensity(f64);

impl DebtDensity {
    /// Create a new debt density, validating it's non-negative.
    pub fn new(value: f64) -> Result<Self, &'static str> {
        NonNegativeF64::check(&value)?;
        Ok(Self(value))
    }

    /// Create a debt density without validation (for trusted sources).
    ///
    /// # Safety
    /// Caller must ensure value is non-negative.
    #[allow(dead_code)]
    pub fn new_unchecked(value: f64) -> Self {
        Self(value)
    }

    /// Get the inner value.
    pub fn into_inner(self) -> f64 {
        self.0
    }

    /// Get the inner value by reference.
    pub fn get(&self) -> f64 {
        self.0
    }
}

impl std::ops::Deref for DebtDensity {
    type Target = f64;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Default for DebtDensity {
    fn default() -> Self {
        Self(0.0)
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    mod threshold_types {
        use super::*;

        #[test]
        fn complexity_threshold_valid_range() {
            // Valid values
            assert!(ComplexityThreshold::new(1).is_ok());
            assert!(ComplexityThreshold::new(500).is_ok());
            assert!(ComplexityThreshold::new(1000).is_ok());
        }

        #[test]
        fn complexity_threshold_invalid_range() {
            // Invalid values
            assert!(ComplexityThreshold::new(0).is_err());
            assert!(ComplexityThreshold::new(1001).is_err());
        }

        #[test]
        fn cognitive_threshold_valid_range() {
            assert!(CognitiveThreshold::new(1).is_ok());
            assert!(CognitiveThreshold::new(250).is_ok());
            assert!(CognitiveThreshold::new(500).is_ok());
        }

        #[test]
        fn cognitive_threshold_invalid_range() {
            assert!(CognitiveThreshold::new(0).is_err());
            assert!(CognitiveThreshold::new(501).is_err());
        }

        #[test]
        fn nesting_threshold_valid_range() {
            assert!(NestingThreshold::new(1).is_ok());
            assert!(NestingThreshold::new(25).is_ok());
            assert!(NestingThreshold::new(50).is_ok());
        }

        #[test]
        fn nesting_threshold_invalid_range() {
            assert!(NestingThreshold::new(0).is_err());
            assert!(NestingThreshold::new(51).is_err());
        }

        #[test]
        fn threshold_deref_access() {
            let threshold = ComplexityThreshold::new(25).unwrap();
            // Deref allows transparent access
            assert_eq!(*threshold, 25);
        }

        #[test]
        fn threshold_into_inner() {
            let threshold = ComplexityThreshold::new(30).unwrap();
            let raw: u32 = threshold.into_inner();
            assert_eq!(raw, 30);
        }
    }

    mod score_types {
        use super::*;

        #[test]
        fn normalized_score_valid_range() {
            assert!(NormalizedScore::new(0).is_ok());
            assert!(NormalizedScore::new(50).is_ok());
            assert!(NormalizedScore::new(100).is_ok());
        }

        #[test]
        fn normalized_score_invalid_range() {
            assert!(NormalizedScore::new(101).is_err());
        }

        #[test]
        fn risk_score_valid_range() {
            assert!(RiskScore::new(0.0).is_ok());
            assert!(RiskScore::new(0.5).is_ok());
            assert!(RiskScore::new(1.0).is_ok());
        }

        #[test]
        fn risk_score_invalid_range() {
            assert!(RiskScore::new(-0.1).is_err());
            assert!(RiskScore::new(1.1).is_err());
        }

        #[test]
        fn risk_score_deref() {
            let score = RiskScore::new(0.75).unwrap();
            assert_eq!(*score, 0.75);
        }
    }

    mod weight_types {
        use super::*;

        #[test]
        fn weight_factor_valid_range() {
            assert!(WeightFactor::new(0.0).is_ok());
            assert!(WeightFactor::new(0.5).is_ok());
            assert!(WeightFactor::new(1.0).is_ok());
        }

        #[test]
        fn weight_factor_invalid_range() {
            assert!(WeightFactor::new(-0.1).is_err());
            assert!(WeightFactor::new(1.1).is_err());
        }

        #[test]
        fn percentage_valid_range() {
            assert!(Percentage::new(0).is_ok());
            assert!(Percentage::new(50).is_ok());
            assert!(Percentage::new(100).is_ok());
        }

        #[test]
        fn percentage_invalid_range() {
            assert!(Percentage::new(101).is_err());
        }

        #[test]
        fn multiplier_valid_range() {
            assert!(MultiplierFactor::new(0.1).is_ok());
            assert!(MultiplierFactor::new(1.0).is_ok());
            assert!(MultiplierFactor::new(2.5).is_ok());
        }

        #[test]
        fn multiplier_invalid_range() {
            assert!(MultiplierFactor::new(0.0).is_err());
            assert!(MultiplierFactor::new(-0.5).is_err());
        }
    }

    mod metric_types {
        use super::*;

        #[test]
        fn line_count_valid_range() {
            assert!(LineCount::new(1).is_ok());
            assert!(LineCount::new(1000).is_ok());
            assert!(LineCount::new(1000000).is_ok());
        }

        #[test]
        fn line_count_invalid_range() {
            assert!(LineCount::new(0).is_err());
        }

        #[test]
        fn nesting_depth_valid_range() {
            assert!(NestingDepth::new(0).is_ok());
            assert!(NestingDepth::new(50).is_ok());
            assert!(NestingDepth::new(100).is_ok());
        }

        #[test]
        fn nesting_depth_invalid_range() {
            assert!(NestingDepth::new(101).is_err());
        }

        #[test]
        fn function_count_valid_range() {
            assert!(FunctionCount::new(0).is_ok());
            assert!(FunctionCount::new(500).is_ok());
            assert!(FunctionCount::new(10000).is_ok());
        }

        #[test]
        fn function_count_invalid_range() {
            assert!(FunctionCount::new(10001).is_err());
        }

        #[test]
        fn debt_density_valid_range() {
            assert!(DebtDensity::new(0.0).is_ok());
            assert!(DebtDensity::new(50.0).is_ok());
            assert!(DebtDensity::new(1000.0).is_ok());
        }

        #[test]
        fn debt_density_invalid_range() {
            assert!(DebtDensity::new(-0.1).is_err());
        }
    }

    mod custom_predicates {
        use super::*;

        #[test]
        fn unit_interval_boundaries() {
            assert!(UnitInterval::check(&0.0).is_ok());
            assert!(UnitInterval::check(&0.5).is_ok());
            assert!(UnitInterval::check(&1.0).is_ok());
            assert!(UnitInterval::check(&-0.001).is_err());
            assert!(UnitInterval::check(&1.001).is_err());
        }

        #[test]
        fn positive_f64_boundaries() {
            assert!(PositiveF64::check(&0.001).is_ok());
            assert!(PositiveF64::check(&1.0).is_ok());
            assert!(PositiveF64::check(&f64::MAX).is_ok());
            assert!(PositiveF64::check(&0.0).is_err());
            assert!(PositiveF64::check(&-0.001).is_err());
        }

        #[test]
        fn non_negative_f64_boundaries() {
            assert!(NonNegativeF64::check(&0.0).is_ok());
            assert!(NonNegativeF64::check(&0.001).is_ok());
            assert!(NonNegativeF64::check(&f64::MAX).is_ok());
            assert!(NonNegativeF64::check(&-0.001).is_err());
        }

        #[test]
        fn positive_line_count_boundaries() {
            assert!(PositiveLineCount::check(&1).is_ok());
            assert!(PositiveLineCount::check(&1000).is_ok());
            assert!(PositiveLineCount::check(&1_000_000).is_ok());
            assert!(PositiveLineCount::check(&0).is_err());
            assert!(PositiveLineCount::check(&1_000_001).is_err());
        }

        #[test]
        fn valid_function_count_boundaries() {
            assert!(ValidFunctionCount::check(&0).is_ok());
            assert!(ValidFunctionCount::check(&5000).is_ok());
            assert!(ValidFunctionCount::check(&10_000).is_ok());
            assert!(ValidFunctionCount::check(&10_001).is_err());
        }
    }

    mod serde_roundtrip {
        use super::*;

        #[test]
        fn risk_score_serde() {
            let score = RiskScore::new(0.75).unwrap();
            let json = serde_json::to_string(&score).unwrap();
            let restored: RiskScore = serde_json::from_str(&json).unwrap();
            assert_eq!(*score, *restored);
        }

        #[test]
        fn weight_factor_serde() {
            let weight = WeightFactor::new(0.35).unwrap();
            let json = serde_json::to_string(&weight).unwrap();
            let restored: WeightFactor = serde_json::from_str(&json).unwrap();
            assert_eq!(*weight, *restored);
        }

        #[test]
        fn multiplier_factor_serde() {
            let mult = MultiplierFactor::new(1.5).unwrap();
            let json = serde_json::to_string(&mult).unwrap();
            let restored: MultiplierFactor = serde_json::from_str(&json).unwrap();
            assert_eq!(*mult, *restored);
        }

        #[test]
        fn debt_density_serde() {
            let density = DebtDensity::new(45.5).unwrap();
            let json = serde_json::to_string(&density).unwrap();
            let restored: DebtDensity = serde_json::from_str(&json).unwrap();
            assert_eq!(*density, *restored);
        }
    }
}