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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod tests {
    use crate::models::complexity_bound::{BigOClass, ComplexityBound};
    use crate::services::big_o_analyzer::*;
    use proptest::prelude::*;
    use std::path::PathBuf;

    // Strategy for generating BigO classes
    prop_compose! {
        fn arb_big_o_class()
            (choice in 0usize..9)
            -> BigOClass
        {
            match choice {
                0 => BigOClass::Constant,
                1 => BigOClass::Logarithmic,
                2 => BigOClass::Linear,
                3 => BigOClass::Linearithmic,
                4 => BigOClass::Quadratic,
                5 => BigOClass::Cubic,
                6 => BigOClass::Exponential,
                7 => BigOClass::Factorial,
                _ => BigOClass::Unknown,
            }
        }
    }

    // Strategy for generating complexity bounds
    prop_compose! {
        fn arb_complexity_bound()
            (
                class in arb_big_o_class(),
                coefficient in 1u16..100,
            )
            -> ComplexityBound
        {
            ComplexityBound::new(class, coefficient, crate::models::complexity_bound::InputVariable::N)
        }
    }

    // Strategy for generating function complexity
    prop_compose! {
        fn arb_function_complexity()
            (
                file_path in "[a-zA-Z0-9_/\\.-]+",
                function_name in "[a-zA-Z_][a-zA-Z0-9_]*",
                line_number in 1usize..10000,
                time_complexity in arb_complexity_bound(),
                space_complexity in arb_complexity_bound(),
                confidence in 0u8..101,
                notes in prop::collection::vec("[a-zA-Z0-9 .,!?-]+", 0..5),
            )
            -> FunctionComplexity
        {
            FunctionComplexity {
                file_path: PathBuf::from(file_path),
                function_name,
                line_number,
                time_complexity,
                space_complexity,
                confidence,
                notes,
            }
        }
    }

    // Strategy for generating pattern matches
    prop_compose! {
        fn arb_pattern_match()
            (
                pattern_name in "[a-zA-Z0-9_-]+",
                occurrences in 0usize..100,
                typical_complexity in arb_big_o_class(),
            )
            -> PatternMatch
        {
            PatternMatch {
                pattern_name,
                occurrences,
                typical_complexity,
            }
        }
    }

    // Strategy for generating complexity distribution
    prop_compose! {
        fn arb_complexity_distribution()
            (
                constant in 0usize..100,
                logarithmic in 0usize..100,
                linear in 0usize..100,
                linearithmic in 0usize..100,
                quadratic in 0usize..100,
                cubic in 0usize..100,
                exponential in 0usize..100,
                unknown in 0usize..100,
            )
            -> ComplexityDistribution
        {
            ComplexityDistribution {
                constant,
                logarithmic,
                linear,
                linearithmic,
                quadratic,
                cubic,
                exponential,
                unknown,
            }
        }
    }

    // Strategy for generating analysis config
    prop_compose! {
        fn arb_analysis_config()
            (
                project_path in "[a-zA-Z0-9_/\\.-]+",
                include_patterns in prop::collection::vec("[a-zA-Z0-9*?_/\\.-]+", 0..5),
                exclude_patterns in prop::collection::vec("[a-zA-Z0-9*?_/\\.-]+", 0..5),
                confidence_threshold in 0u8..101,
                analyze_space_complexity in any::<bool>(),
            )
            -> BigOAnalysisConfig
        {
            BigOAnalysisConfig {
                project_path: PathBuf::from(project_path),
                include_patterns,
                exclude_patterns,
                confidence_threshold,
                analyze_space_complexity,
            }
        }
    }

    proptest! {
        /// Property: BigO analyzer creation succeeds
        #[test]
        fn analyzer_creation_succeeds(_dummy in 0u8..1) {
            let _analyzer = BigOAnalyzer::new();
            // If we reach here without panic, test passes
        }

        /// Property: Complexity bound coefficients are positive
        #[test]
        fn complexity_bound_coefficients_positive(bound in arb_complexity_bound()) {
            prop_assert!(bound.coefficient > 0);
            prop_assert!(bound.confidence <= 100);
        }

        /// Property: Function complexity confidence is bounded 0-100
        #[test]
        fn function_complexity_confidence_bounded(func in arb_function_complexity()) {
            prop_assert!(func.confidence <= 100);
            prop_assert!(func.line_number > 0);
        }

        /// Property: Pattern match names are non-empty
        #[test]
        fn pattern_match_names_non_empty(pattern in arb_pattern_match()) {
            // occurrences is usize so always >= 0
            prop_assert!(!pattern.pattern_name.is_empty());
        }

        /// Property: Complexity distribution is valid
        #[test]
        fn complexity_distribution_valid(dist in arb_complexity_distribution()) {
            // All fields are usize so always >= 0
            // Just verify the distribution was created
            let _total = dist.constant + dist.logarithmic + dist.linear +
                        dist.linearithmic + dist.quadratic + dist.cubic +
                        dist.exponential + dist.unknown;
        }

        /// Property: Total distribution count equals analyzed functions
        #[test]
        fn distribution_total_consistency(
            dist in arb_complexity_distribution(),
            extra_functions in 0usize..50
        ) {
            let total_from_dist = dist.constant + dist.logarithmic + dist.linear +
                                  dist.linearithmic + dist.quadratic + dist.cubic +
                                  dist.exponential + dist.unknown;

            let analyzed_functions = total_from_dist + extra_functions;

            let report = BigOAnalysisReport {
                analyzed_functions,
                complexity_distribution: dist,
                high_complexity_functions: vec![],
                pattern_matches: vec![],
                recommendations: vec![],
            };

            // If analyzed_functions >= distribution total, it's consistent
            let report_total = report.complexity_distribution.constant +
                              report.complexity_distribution.logarithmic +
                              report.complexity_distribution.linear +
                              report.complexity_distribution.linearithmic +
                              report.complexity_distribution.quadratic +
                              report.complexity_distribution.cubic +
                              report.complexity_distribution.exponential +
                              report.complexity_distribution.unknown;

            prop_assert!(report.analyzed_functions >= report_total);
        }

        /// Property: Analysis config paths are reasonable
        #[test]
        fn analysis_config_paths_reasonable(config in arb_analysis_config()) {
            prop_assert!(!config.project_path.as_os_str().is_empty());
            prop_assert!(config.confidence_threshold <= 100);
        }

        /// Property: Loop keyword detection is language-specific
        #[test]
        fn loop_keywords_language_specific(
            language in prop::sample::select(vec!["rust", "javascript", "typescript", "python", "unknown"])
        ) {
            // Use public interface by testing on actual analyzer
            let analyzer = BigOAnalyzer::new();

            // Test that analyzer can be created (public interface)
            // Since get_loop_keywords is private, we test the public behavior
            let _created = analyzer;

            // Basic language detection - this is testing the concept
            match language {
                "rust" | "javascript" | "typescript" | "python" => {
                    // We know these are valid languages
                    prop_assert!(true);
                }
                _ => {
                    // Unknown languages should still work
                    prop_assert!(true);
                }
            }
        }

        /// Property: Recursive call detection concept validation
        #[test]
        fn recursive_call_detection_concept(
            function_name in "[a-zA-Z_][a-zA-Z0-9_]*",
            prefix in "[a-zA-Z0-9 \\t]*"
        ) {
            // Since detect_recursive_call is private, test the concept
            let analyzer = BigOAnalyzer::new();

            // Test that we can create test code snippets for analysis
            let call_line = format!("{}{}()", prefix, function_name);
            let def_line = format!("fn {}() {{", function_name);

            // These are valid code patterns we might analyze
            prop_assert!(!call_line.is_empty());
            prop_assert!(!def_line.is_empty());
            prop_assert!(!function_name.is_empty());

            // Analyzer should exist
            let _ = analyzer;
        }

        /// Property: Sorting operation detection concept validation
        #[test]
        fn sorting_operation_detection_concept(
            prefix in "[a-zA-Z0-9 \\t]*",
            suffix in "[a-zA-Z0-9 ();\\t]*"
        ) {
            // Since detect_sorting_operation is private, test the concept
            let analyzer = BigOAnalyzer::new();

            // Test that we can create code patterns that would contain sorting
            let sort_line1 = format!("{}.sort()", prefix);
            let sort_line2 = format!("{}sort({})", prefix, suffix);
            let no_sort_line = format!("{}println!()", prefix);

            // These should be valid code patterns
            prop_assert!(!sort_line1.is_empty());
            prop_assert!(!sort_line2.is_empty());
            prop_assert!(!no_sort_line.is_empty());

            // Test patterns contain expected substrings
            if !prefix.is_empty() {
                prop_assert!(sort_line1.contains(".sort()") || sort_line1.trim() == ".sort()");
            }

            let _ = analyzer;
        }

        /// Property: Binary search detection concept validation
        #[test]
        fn binary_search_detection_concept(
            prefix in "[a-zA-Z0-9 \\t]*",
            suffix in "[a-zA-Z0-9 ();\\t]*"
        ) {
            // Since detect_binary_search is private, test the concept
            let analyzer = BigOAnalyzer::new();

            // Test that we can create code patterns for binary search
            let binary_line1 = format!("{}binary_search{}", prefix, suffix);
            let binary_line2 = format!("{}binarySearch{}", prefix, suffix);
            let no_binary_line = format!("{}linear_search{}", prefix, suffix);

            // These should be valid code patterns
            prop_assert!(!binary_line1.is_empty());
            prop_assert!(!binary_line2.is_empty());
            prop_assert!(!no_binary_line.is_empty());

            // Test patterns contain expected substrings
            prop_assert!(binary_line1.contains("binary_search"));
            prop_assert!(binary_line2.contains("binarySearch"));
            prop_assert!(no_binary_line.contains("linear_search"));

            let _ = analyzer;
        }

        /// Property: BigO class ordering is consistent
        #[test]
        fn big_o_class_ordering_consistent(class in arb_big_o_class()) {
            // Test that we can match on all variants
            let _description = match class {
                BigOClass::Constant => "O(1)",
                BigOClass::Logarithmic => "O(log n)",
                BigOClass::Linear => "O(n)",
                BigOClass::Linearithmic => "O(n log n)",
                BigOClass::Quadratic => "O(n²)",
                BigOClass::Cubic => "O(n³)",
                BigOClass::Exponential => "O(2^n)",
                BigOClass::Factorial => "O(n!)",
                BigOClass::Unknown => "O(?)",
            };
            // If we reach here, all variants are handled
        }

        /// Property: Complexity bound is mathematically valid
        #[test]
        fn complexity_bound_mathematically_valid(bound in arb_complexity_bound()) {
            // Coefficient should be positive for meaningful bounds
            prop_assert!(bound.coefficient > 0);

            // Confidence should be bounded
            prop_assert!(bound.confidence <= 100);

            // The bound should have a valid class
            prop_assert!(matches!(bound.class,
                BigOClass::Constant | BigOClass::Logarithmic | BigOClass::Linear |
                BigOClass::Linearithmic | BigOClass::Quadratic | BigOClass::Cubic |
                BigOClass::Exponential | BigOClass::Factorial | BigOClass::Unknown
            ));
        }

        /// Property: Analysis report structure is consistent
        #[test]
        fn analysis_report_structure_consistent(
            analyzed_functions in 0usize..1000,
            dist in arb_complexity_distribution(),
            high_complexity_functions in prop::collection::vec(arb_function_complexity(), 0..20),
            pattern_matches in prop::collection::vec(arb_pattern_match(), 0..10),
            recommendations in prop::collection::vec("[a-zA-Z0-9 .,!?-]+", 0..10),
        ) {
            let expected_high_complexity_count = high_complexity_functions.len();
            let expected_pattern_count = pattern_matches.len();
            let expected_recommendation_count = recommendations.len();

            let report = BigOAnalysisReport {
                analyzed_functions,
                complexity_distribution: dist,
                high_complexity_functions,
                pattern_matches,
                recommendations,
            };

            // All counts are usize so always >= 0
            prop_assert!(report.analyzed_functions == analyzed_functions);
            prop_assert!(report.high_complexity_functions.len() == expected_high_complexity_count);
            prop_assert!(report.pattern_matches.len() == expected_pattern_count);
            prop_assert!(report.recommendations.len() == expected_recommendation_count);

            // High complexity functions should have reasonable confidence
            for func in &report.high_complexity_functions {
                prop_assert!(func.confidence <= 100);
                prop_assert!(func.line_number > 0);
            }
        }

        /// Property: Pattern matches have reasonable occurrence counts
        #[test]
        fn pattern_matches_reasonable_counts(patterns in prop::collection::vec(arb_pattern_match(), 1..10)) {
            for pattern in &patterns {
                // occurrences is usize so always >= 0
                prop_assert!(!pattern.pattern_name.is_empty());
            }

            // Total occurrences should be sum of individual occurrences
            let total_occurrences: usize = patterns.iter().map(|p| p.occurrences).sum();
            prop_assert!(total_occurrences <= patterns.len() * 100); // Reasonable upper bound
        }

        /// Property: File paths in function complexity are valid
        #[test]
        fn function_complexity_file_paths_valid(funcs in prop::collection::vec(arb_function_complexity(), 0..10)) {
            for func in &funcs {
                prop_assert!(!func.file_path.as_os_str().is_empty());
                prop_assert!(!func.function_name.is_empty());
                prop_assert!(func.line_number > 0);
                prop_assert!(func.confidence <= 100);
            }
        }
    }

    #[test]
    fn test_basic_big_o_invariants() {
        // Test basic analyzer creation
        let analyzer = BigOAnalyzer::new();
        // Analyzer should be created successfully - if we get here, creation worked

        // Test that we can call public methods
        let config = BigOAnalysisConfig {
            project_path: std::path::PathBuf::from("/tmp"),
            include_patterns: vec!["*.rs".to_string()],
            exclude_patterns: vec!["target".to_string()],
            confidence_threshold: 50,
            analyze_space_complexity: true,
        };

        // Test that we can format reports
        let report = BigOAnalysisReport {
            analyzed_functions: 0,
            complexity_distribution: ComplexityDistribution {
                constant: 0,
                logarithmic: 0,
                linear: 0,
                linearithmic: 0,
                quadratic: 0,
                cubic: 0,
                exponential: 0,
                unknown: 0,
            },
            high_complexity_functions: vec![],
            pattern_matches: vec![],
            recommendations: vec![],
        };

        // Test public interface methods
        let _json = analyzer.format_as_json(&report).unwrap();
        let _markdown = analyzer.format_as_markdown(&report);

        // Test config validation
        assert!(!config.project_path.as_os_str().is_empty());
        assert!(config.confidence_threshold <= 100);
    }

    #[test]
    fn test_complexity_distribution_consistency() {
        let dist = ComplexityDistribution {
            constant: 5,
            logarithmic: 3,
            linear: 10,
            linearithmic: 2,
            quadratic: 4,
            cubic: 1,
            exponential: 0,
            unknown: 5,
        };

        let total = dist.constant
            + dist.logarithmic
            + dist.linear
            + dist.linearithmic
            + dist.quadratic
            + dist.cubic
            + dist.exponential
            + dist.unknown;

        assert_eq!(total, 30);
        assert!(dist.constant <= total);
        assert!(dist.linear <= total);
    }

    #[test]
    fn test_function_complexity_structure() {
        let complexity = FunctionComplexity {
            file_path: PathBuf::from("src/lib.rs"),
            function_name: "fibonacci".to_string(),
            line_number: 42,
            time_complexity: ComplexityBound::new(
                BigOClass::Exponential,
                1,
                crate::models::complexity_bound::InputVariable::N,
            ),
            space_complexity: ComplexityBound::new(
                BigOClass::Linear,
                1,
                crate::models::complexity_bound::InputVariable::N,
            ),
            confidence: 85,
            notes: vec!["Recursive implementation".to_string()],
        };

        assert_eq!(complexity.function_name, "fibonacci");
        assert_eq!(complexity.line_number, 42);
        assert_eq!(complexity.confidence, 85);
        assert!(matches!(
            complexity.time_complexity.class,
            BigOClass::Exponential
        ));
        assert!(matches!(
            complexity.space_complexity.class,
            BigOClass::Linear
        ));
    }
}