pmat 3.15.0

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP, HTTP)
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
#![cfg_attr(coverage_nightly, coverage(off))]
use std::collections::HashMap;
use syn::{self, visit::Visit};

/// Complexity analyzer.
pub struct ComplexityAnalyzer {
    _current_complexity: u32,
    _cognitive_complexity: u32,
    _nesting_depth: u32,
    _max_nesting: u32,
}

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

impl ComplexityAnalyzer {
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Create a new instance.
    pub fn new() -> Self {
        Self {
            _current_complexity: 1, // Base complexity
            _cognitive_complexity: 0,
            _nesting_depth: 0,
            _max_nesting: 0,
        }
    }

    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Calculate cyclomatic.
    pub fn calculate_cyclomatic(&self, ast: &syn::File) -> u32 {
        let mut visitor = ComplexityVisitor {
            complexity: 1,
            nesting_depth: 0,
        };
        visitor.visit_file(ast);
        visitor.complexity
    }

    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "score_range")]
    /// Calculate cognitive.
    pub fn calculate_cognitive(&self, ast: &syn::File) -> u32 {
        let mut visitor = CognitiveComplexityVisitor {
            complexity: 0,
            nesting_depth: 0,
        };
        visitor.visit_file(ast);
        visitor.complexity
    }

    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Analyze string.
    pub fn analyze_string(&self, code: &str) -> Result<ComplexityMetrics, syn::Error> {
        let ast = syn::parse_file(code)?;
        Ok(ComplexityMetrics {
            cyclomatic: self.calculate_cyclomatic(&ast),
            cognitive: self.calculate_cognitive(&ast),
        })
    }

    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "score_range")]
    /// Calculate shannon entropy.
    pub fn calculate_shannon_entropy(&self, code: &str) -> f64 {
        let mut char_counts = HashMap::new();
        let total = code.len() as f64;

        for ch in code.chars() {
            *char_counts.entry(ch).or_insert(0) += 1;
        }

        let mut entropy = 0.0;
        for count in char_counts.values() {
            let probability = *count as f64 / total;
            if probability > 0.0 {
                entropy -= probability * probability.log2();
            }
        }

        entropy
    }
}

#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
/// Complexity metrics.
pub struct ComplexityMetrics {
    pub cyclomatic: u32,
    pub cognitive: u32,
}

struct ComplexityVisitor {
    complexity: u32,
    nesting_depth: u32,
}

impl<'ast> Visit<'ast> for ComplexityVisitor {
    fn visit_expr_if(&mut self, node: &'ast syn::ExprIf) {
        self.complexity += 1; // Each if adds a path
        self.nesting_depth += 1;
        syn::visit::visit_expr_if(self, node);
        self.nesting_depth -= 1;
    }

    fn visit_expr_match(&mut self, node: &'ast syn::ExprMatch) {
        // Each arm except the first adds a path
        if node.arms.len() > 1 {
            self.complexity += (node.arms.len() - 1) as u32;
        }
        self.nesting_depth += 1;
        syn::visit::visit_expr_match(self, node);
        self.nesting_depth -= 1;
    }

    fn visit_expr_for_loop(&mut self, node: &'ast syn::ExprForLoop) {
        self.complexity += 1;
        self.nesting_depth += 1;
        syn::visit::visit_expr_for_loop(self, node);
        self.nesting_depth -= 1;
    }

    fn visit_expr_while(&mut self, node: &'ast syn::ExprWhile) {
        self.complexity += 1;
        self.nesting_depth += 1;
        syn::visit::visit_expr_while(self, node);
        self.nesting_depth -= 1;
    }

    fn visit_expr_loop(&mut self, node: &'ast syn::ExprLoop) {
        self.complexity += 1;
        self.nesting_depth += 1;
        syn::visit::visit_expr_loop(self, node);
        self.nesting_depth -= 1;
    }

    fn visit_expr_binary(&mut self, node: &'ast syn::ExprBinary) {
        use syn::BinOp;
        match node.op {
            BinOp::And(_) | BinOp::Or(_) => {
                self.complexity += 1;
            }
            _ => {}
        }
        syn::visit::visit_expr_binary(self, node);
    }
}

struct CognitiveComplexityVisitor {
    complexity: u32,
    nesting_depth: u32,
}

impl<'ast> Visit<'ast> for CognitiveComplexityVisitor {
    fn visit_expr_if(&mut self, node: &'ast syn::ExprIf) {
        self.complexity += 1 + self.nesting_depth; // Nesting adds cognitive load
        self.nesting_depth += 1;
        syn::visit::visit_expr_if(self, node);
        self.nesting_depth -= 1;
    }

    fn visit_expr_match(&mut self, node: &'ast syn::ExprMatch) {
        self.complexity += 1 + self.nesting_depth;
        self.nesting_depth += 1;
        syn::visit::visit_expr_match(self, node);
        self.nesting_depth -= 1;
    }

    fn visit_expr_for_loop(&mut self, node: &'ast syn::ExprForLoop) {
        self.complexity += 1 + self.nesting_depth;
        self.nesting_depth += 1;
        syn::visit::visit_expr_for_loop(self, node);
        self.nesting_depth -= 1;
    }

    fn visit_expr_while(&mut self, node: &'ast syn::ExprWhile) {
        self.complexity += 1 + self.nesting_depth;
        self.nesting_depth += 1;
        syn::visit::visit_expr_while(self, node);
        self.nesting_depth -= 1;
    }

    fn visit_expr_break(&mut self, _node: &'ast syn::ExprBreak) {
        self.complexity += 1; // Breaks add cognitive complexity
    }

    fn visit_expr_continue(&mut self, _node: &'ast syn::ExprContinue) {
        self.complexity += 1; // Continues add cognitive complexity
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod coverage_tests {
    use super::*;

    // ComplexityAnalyzer tests
    #[test]
    fn test_complexity_analyzer_default() {
        let analyzer = ComplexityAnalyzer::default();
        let _ = analyzer;
    }

    #[test]
    fn test_complexity_analyzer_new() {
        let analyzer = ComplexityAnalyzer::new();
        let _ = analyzer;
    }

    #[test]
    fn test_calculate_cyclomatic_simple_function() {
        let analyzer = ComplexityAnalyzer::new();
        let code = "fn simple() { let x = 1; }";
        let ast = syn::parse_file(code).unwrap();
        let complexity = analyzer.calculate_cyclomatic(&ast);
        assert_eq!(complexity, 1); // Base complexity
    }

    #[test]
    fn test_calculate_cyclomatic_with_if() {
        let analyzer = ComplexityAnalyzer::new();
        let code = "fn with_if() { if true { } }";
        let ast = syn::parse_file(code).unwrap();
        let complexity = analyzer.calculate_cyclomatic(&ast);
        assert_eq!(complexity, 2); // Base + 1 for if
    }

    #[test]
    fn test_calculate_cyclomatic_with_match() {
        let analyzer = ComplexityAnalyzer::new();
        let code = r#"
            fn with_match() {
                match x {
                    1 => {},
                    2 => {},
                    _ => {},
                }
            }
        "#;
        let ast = syn::parse_file(code).unwrap();
        let complexity = analyzer.calculate_cyclomatic(&ast);
        assert_eq!(complexity, 3); // Base + 2 for arms (3-1)
    }

    #[test]
    fn test_calculate_cyclomatic_with_for_loop() {
        let analyzer = ComplexityAnalyzer::new();
        let code = "fn with_for() { for i in 0..10 { } }";
        let ast = syn::parse_file(code).unwrap();
        let complexity = analyzer.calculate_cyclomatic(&ast);
        assert_eq!(complexity, 2); // Base + 1 for loop
    }

    #[test]
    fn test_calculate_cyclomatic_with_while() {
        let analyzer = ComplexityAnalyzer::new();
        let code = "fn with_while() { while true { } }";
        let ast = syn::parse_file(code).unwrap();
        let complexity = analyzer.calculate_cyclomatic(&ast);
        assert_eq!(complexity, 2); // Base + 1 for while
    }

    #[test]
    fn test_calculate_cyclomatic_with_loop() {
        let analyzer = ComplexityAnalyzer::new();
        let code = "fn with_loop() { loop { break; } }";
        let ast = syn::parse_file(code).unwrap();
        let complexity = analyzer.calculate_cyclomatic(&ast);
        assert_eq!(complexity, 2); // Base + 1 for loop
    }

    #[test]
    fn test_calculate_cyclomatic_with_and_or() {
        let analyzer = ComplexityAnalyzer::new();
        let code = "fn with_logic() { let x = a && b || c; }";
        let ast = syn::parse_file(code).unwrap();
        let complexity = analyzer.calculate_cyclomatic(&ast);
        assert_eq!(complexity, 3); // Base + 2 for && and ||
    }

    #[test]
    fn test_calculate_cognitive_simple() {
        let analyzer = ComplexityAnalyzer::new();
        let code = "fn simple() { let x = 1; }";
        let ast = syn::parse_file(code).unwrap();
        let cognitive = analyzer.calculate_cognitive(&ast);
        assert_eq!(cognitive, 0); // No control flow
    }

    #[test]
    fn test_calculate_cognitive_with_if() {
        let analyzer = ComplexityAnalyzer::new();
        let code = "fn with_if() { if true { } }";
        let ast = syn::parse_file(code).unwrap();
        let cognitive = analyzer.calculate_cognitive(&ast);
        assert_eq!(cognitive, 1); // +1 for if at nesting 0
    }

    #[test]
    fn test_calculate_cognitive_nested_if() {
        let analyzer = ComplexityAnalyzer::new();
        let code = r#"
            fn nested() {
                if true {
                    if false { }
                }
            }
        "#;
        let ast = syn::parse_file(code).unwrap();
        let cognitive = analyzer.calculate_cognitive(&ast);
        // First if: +1 (nesting 0)
        // Second if: +1 + 1 = +2 (nesting 1)
        assert_eq!(cognitive, 3);
    }

    #[test]
    fn test_calculate_cognitive_with_break() {
        let analyzer = ComplexityAnalyzer::new();
        let code = "fn with_break() { loop { break; } }";
        let ast = syn::parse_file(code).unwrap();
        let cognitive = analyzer.calculate_cognitive(&ast);
        // +1 for break
        assert!(cognitive >= 1);
    }

    #[test]
    fn test_calculate_cognitive_with_continue() {
        let analyzer = ComplexityAnalyzer::new();
        let code = "fn with_continue() { for i in 0..10 { continue; } }";
        let ast = syn::parse_file(code).unwrap();
        let cognitive = analyzer.calculate_cognitive(&ast);
        // +1 for for at nesting 0, +1 for continue
        assert!(cognitive >= 2);
    }

    #[test]
    fn test_analyze_string_success() {
        let analyzer = ComplexityAnalyzer::new();
        let code = "fn test() { if true { } }";
        let result = analyzer.analyze_string(code);
        assert!(result.is_ok());
        let metrics = result.unwrap();
        assert_eq!(metrics.cyclomatic, 2);
        assert_eq!(metrics.cognitive, 1);
    }

    #[test]
    fn test_analyze_string_parse_error() {
        let analyzer = ComplexityAnalyzer::new();
        let code = "this is not valid rust code {{{{";
        let result = analyzer.analyze_string(code);
        assert!(result.is_err());
    }

    #[test]
    fn test_calculate_shannon_entropy_uniform() {
        let analyzer = ComplexityAnalyzer::new();
        let code = "aaaa"; // All same characters
        let entropy = analyzer.calculate_shannon_entropy(code);
        assert_eq!(entropy, 0.0); // Zero entropy for uniform distribution
    }

    #[test]
    fn test_calculate_shannon_entropy_diverse() {
        let analyzer = ComplexityAnalyzer::new();
        let code = "fn calculate_prime(n: u64) -> bool { if n <= 1 { false } else { true } }";
        let entropy = analyzer.calculate_shannon_entropy(code);
        assert!(entropy > 3.0); // High entropy for diverse code
    }

    #[test]
    fn test_calculate_shannon_entropy_empty() {
        let analyzer = ComplexityAnalyzer::new();
        let entropy = analyzer.calculate_shannon_entropy("");
        assert!(entropy.is_nan() || entropy == 0.0); // Handle empty string
    }

    // ComplexityMetrics tests
    #[test]
    fn test_complexity_metrics_default() {
        let metrics = ComplexityMetrics::default();
        assert_eq!(metrics.cyclomatic, 0);
        assert_eq!(metrics.cognitive, 0);
    }

    #[test]
    fn test_complexity_metrics_clone() {
        let metrics = ComplexityMetrics {
            cyclomatic: 5,
            cognitive: 3,
        };
        let cloned = metrics.clone();
        assert_eq!(metrics.cyclomatic, cloned.cyclomatic);
        assert_eq!(metrics.cognitive, cloned.cognitive);
    }

    #[test]
    fn test_complexity_metrics_serialization() {
        let metrics = ComplexityMetrics {
            cyclomatic: 10,
            cognitive: 7,
        };
        let json = serde_json::to_string(&metrics).unwrap();
        let deserialized: ComplexityMetrics = serde_json::from_str(&json).unwrap();
        assert_eq!(metrics.cyclomatic, deserialized.cyclomatic);
        assert_eq!(metrics.cognitive, deserialized.cognitive);
    }

    // Complex code tests
    #[test]
    fn test_complex_nested_loops() {
        let analyzer = ComplexityAnalyzer::new();
        let code = r#"
            fn complex() {
                for i in 0..10 {
                    for j in 0..10 {
                        for k in 0..10 {
                            if i == j && j == k {
                                break;
                            }
                        }
                    }
                }
            }
        "#;
        let ast = syn::parse_file(code).unwrap();
        let cyclomatic = analyzer.calculate_cyclomatic(&ast);
        let cognitive = analyzer.calculate_cognitive(&ast);

        // High cyclomatic: 3 loops + 1 if + 1 && + base = 6
        assert!(cyclomatic >= 5);
        // High cognitive due to nesting
        assert!(cognitive >= 10);
    }

    #[test]
    fn test_match_with_many_arms() {
        let analyzer = ComplexityAnalyzer::new();
        let code = r#"
            fn many_arms(x: i32) {
                match x {
                    0 => {},
                    1 => {},
                    2 => {},
                    3 => {},
                    4 => {},
                    5 => {},
                    _ => {},
                }
            }
        "#;
        let ast = syn::parse_file(code).unwrap();
        let cyclomatic = analyzer.calculate_cyclomatic(&ast);
        // 7 arms - 1 = 6, + base = 7
        assert_eq!(cyclomatic, 7);
    }

    #[test]
    fn test_multiple_functions() {
        let analyzer = ComplexityAnalyzer::new();
        let code = r#"
            fn func1() { if true { } }
            fn func2() { for i in 0..1 { } }
            fn func3() { while false { } }
        "#;
        let ast = syn::parse_file(code).unwrap();
        let cyclomatic = analyzer.calculate_cyclomatic(&ast);
        // Base + if + for + while = 1 + 1 + 1 + 1 = 4
        assert_eq!(cyclomatic, 4);
    }

    #[test]
    fn test_empty_file() {
        let analyzer = ComplexityAnalyzer::new();
        let code = "";
        let ast = syn::parse_file(code).unwrap();
        let cyclomatic = analyzer.calculate_cyclomatic(&ast);
        assert_eq!(cyclomatic, 1); // Base complexity
    }

    #[test]
    fn test_only_struct_definition() {
        let analyzer = ComplexityAnalyzer::new();
        let code = "struct Foo { x: i32, y: String }";
        let ast = syn::parse_file(code).unwrap();
        let cyclomatic = analyzer.calculate_cyclomatic(&ast);
        let cognitive = analyzer.calculate_cognitive(&ast);
        assert_eq!(cyclomatic, 1); // No control flow
        assert_eq!(cognitive, 0);
    }
}