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
use anyhow::Result;
use std::collections::{HashMap, HashSet};
use tree_sitter::{Node, Tree};
use crate::tdg::{Language, MetricCategory, PenaltyTracker, TdgConfig};
use crate::tdg::language::{LanguageRules, NamingStyle};
use super::{Scorer, walk_tree, get_node_text};

/// Consistency analyzer.
pub struct ConsistencyAnalyzer;

impl ConsistencyAnalyzer {
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Create a new instance.
    pub fn new() -> Self {
        Self
    }
    
    fn check_naming_consistency(&self, root: Node, source: &str, rules: &LanguageRules) -> u32 {
        let mut violations = 0;
        
        walk_tree(root, |node| {
            match node.kind() {
                "identifier" => {
                    if let Some(parent) = node.parent() {
                        let naming_style = match parent.kind() {
                            "function_item" | "function_declaration" | "function_definition" => &rules.function_style,
                            "struct_item" | "class_declaration" | "class_definition" | "type_declaration" => &rules.type_style,
                            "const_item" | "static_item" | "const_declaration" => &rules.constant_style,
                            "parameter" | "variable_declaration" | "let_declaration" => &rules.variable_style,
                            _ => return,
                        };
                        
                        let name = get_node_text(node, source);
                        if !naming_style.matches(name) {
                            violations += 1;
                        }
                    }
                }
                _ => {}
            }
        });
        
        violations
    }
    
    fn check_import_organization(&self, root: Node, source: &str, language: Language) -> u32 {
        let mut issues = 0;
        let mut imports = Vec::new();
        
        walk_tree(root, |node| {
            match node.kind() {
                "use_declaration" | "import_statement" | "import" => {
                    let text = get_node_text(node, source);
                    imports.push((text.to_string(), node.start_byte()));
                }
                _ => {}
            }
        });
        
        if imports.len() < 2 {
            return 0;
        }
        
        match language {
            Language::Rust => {
                issues += self.check_rust_import_order(&imports);
            }
            Language::Python => {
                issues += self.check_python_import_order(&imports);
            }
            Language::JavaScript | Language::TypeScript => {
                issues += self.check_js_import_order(&imports);
            }
            Language::Go => {
                issues += self.check_go_import_order(&imports);
            }
            _ => {}
        }
        
        issues
    }
    
    fn check_rust_import_order(&self, imports: &[(String, usize)]) -> u32 {
        let mut issues = 0;
        let mut prev_category = -1;
        
        for (import, _) in imports {
            let category = if import.starts_with("use std::") {
                0
            } else if import.starts_with("use crate::") {
                2
            } else if import.starts_with("use super::") || import.starts_with("use self::") {
                3
            } else {
                1
            };
            
            if category < prev_category {
                issues += 1;
            }
            prev_category = category;
        }
        
        issues
    }
    
    fn check_python_import_order(&self, imports: &[(String, usize)]) -> u32 {
        let mut issues = 0;
        let mut in_stdlib = true;
        let mut in_third_party = false;
        
        for (import, _) in imports {
            let is_stdlib = self.is_python_stdlib_import(import);
            let is_relative = import.starts_with("from .");
            
            if is_relative && (in_stdlib || in_third_party) {
                issues += 1;
            } else if !is_stdlib && in_stdlib && !in_third_party {
                in_stdlib = false;
                in_third_party = true;
            } else if is_stdlib && (in_third_party || !in_stdlib) {
                issues += 1;
            }
        }
        
        issues
    }
    
    fn is_python_stdlib_import(&self, import: &str) -> bool {
        let stdlib_modules = [
            "os", "sys", "json", "re", "datetime", "collections",
            "itertools", "functools", "math", "random", "urllib",
            "http", "pathlib", "typing", "dataclasses", "enum",
        ];
        
        let module_name = if let Some(from_pos) = import.find("from ") {
            &import[from_pos + 5..].split_whitespace().next().unwrap_or("")
        } else if let Some(import_pos) = import.find("import ") {
            &import[import_pos + 7..].split('.').next().unwrap_or("")
        } else {
            ""
        };
        
        stdlib_modules.contains(&module_name)
    }
    
    fn check_js_import_order(&self, _imports: &[(String, usize)]) -> u32 {
        0
    }
    
    fn check_go_import_order(&self, imports: &[(String, usize)]) -> u32 {
        let mut issues = 0;
        let mut in_stdlib = true;
        
        for (import, _) in imports {
            let is_third_party = import.contains('.') && !import.starts_with("import \"");
            
            if is_third_party && in_stdlib {
                in_stdlib = false;
            } else if !is_third_party && !in_stdlib {
                issues += 1;
            }
        }
        
        issues
    }
    
    fn analyze_pattern_consistency(&self, root: Node, source: &str) -> f32 {
        let patterns = self.extract_patterns(root, source);
        
        let error_consistency = self.error_handling_consistency(&patterns);
        let null_consistency = self.null_check_consistency(&patterns);
        let loop_consistency = self.loop_style_consistency(&patterns);
        let conditional_consistency = self.conditional_style_consistency(&patterns);
        
        let scores = vec![error_consistency, null_consistency, loop_consistency, conditional_consistency];
        scores.iter().sum::<f32>() / scores.len() as f32
    }
    
    fn extract_patterns(&self, root: Node, source: &str) -> CodePatterns {
        let mut patterns = CodePatterns::new();
        
        walk_tree(root, |node| {
            match node.kind() {
                "if_statement" | "if_expression" => {
                    let text = get_node_text(node, source);
                    if text.contains("null") || text.contains("None") || text.contains("nil") {
                        patterns.null_checks.push(text.to_string());
                    }
                    patterns.conditionals.push(text.to_string());
                }
                "match_expression" | "switch_statement" => {
                    patterns.error_handling.push(get_node_text(node, source).to_string());
                }
                "try_expression" | "try_statement" => {
                    patterns.error_handling.push(get_node_text(node, source).to_string());
                }
                "while_statement" | "for_statement" | "while_expression" | "for_expression" => {
                    patterns.loops.push(get_node_text(node, source).to_string());
                }
                "call_expression" => {
                    let text = get_node_text(node, source);
                    if text.contains("unwrap") || text.contains("expect") {
                        patterns.error_handling.push(text.to_string());
                    }
                }
                _ => {}
            }
        });
        
        patterns
    }
    
    fn error_handling_consistency(&self, patterns: &CodePatterns) -> f32 {
        if patterns.error_handling.is_empty() {
            return 1.0;
        }
        
        let unwrap_count = patterns.error_handling.iter()
            .filter(|p| p.contains("unwrap"))
            .count();
        let match_count = patterns.error_handling.iter()
            .filter(|p| p.contains("match") || p.contains("switch"))
            .count();
        let try_count = patterns.error_handling.iter()
            .filter(|p| p.contains("try"))
            .count();
        
        let total = unwrap_count + match_count + try_count;
        if total == 0 {
            return 1.0;
        }
        
        let dominant = unwrap_count.max(match_count).max(try_count);
        dominant as f32 / total as f32
    }
    
    fn null_check_consistency(&self, patterns: &CodePatterns) -> f32 {
        if patterns.null_checks.is_empty() {
            return 1.0;
        }
        
        let explicit_checks = patterns.null_checks.iter()
            .filter(|p| p.contains("== null") || p.contains("is None") || p.contains("== nil"))
            .count();
        let pattern_checks = patterns.null_checks.iter()
            .filter(|p| p.contains("if let") || p.contains("match"))
            .count();
        
        let total = explicit_checks + pattern_checks;
        if total == 0 {
            return 1.0;
        }
        
        let dominant = explicit_checks.max(pattern_checks);
        dominant as f32 / total as f32
    }
    
    fn loop_style_consistency(&self, patterns: &CodePatterns) -> f32 {
        if patterns.loops.is_empty() {
            return 1.0;
        }
        
        let for_loops = patterns.loops.iter()
            .filter(|p| p.starts_with("for"))
            .count();
        let while_loops = patterns.loops.iter()
            .filter(|p| p.starts_with("while"))
            .count();
        let iterator_loops = patterns.loops.iter()
            .filter(|p| p.contains(".iter()") || p.contains(".map(") || p.contains(".filter("))
            .count();
        
        let total = for_loops + while_loops + iterator_loops;
        if total == 0 {
            return 1.0;
        }
        
        let dominant = for_loops.max(while_loops).max(iterator_loops);
        dominant as f32 / total as f32
    }
    
    fn conditional_style_consistency(&self, patterns: &CodePatterns) -> f32 {
        if patterns.conditionals.is_empty() {
            return 1.0;
        }
        
        let if_else = patterns.conditionals.iter()
            .filter(|p| p.contains("if") && p.contains("else"))
            .count();
        let match_patterns = patterns.conditionals.iter()
            .filter(|p| p.contains("match"))
            .count();
        let ternary = patterns.conditionals.iter()
            .filter(|p| p.contains('?') && p.contains(':'))
            .count();
        
        let total = if_else + match_patterns + ternary;
        if total == 0 {
            return 1.0;
        }
        
        let dominant = if_else.max(match_patterns).max(ternary);
        dominant as f32 / total as f32
    }
}

impl Scorer for ConsistencyAnalyzer {
    fn score(&self, tree: &Tree, source: &str, language: Language, config: &TdgConfig, tracker: &mut PenaltyTracker) -> Result<f32> {
        let mut points = config.weights.consistency;
        let root = tree.root_node();
        let rules = LanguageRules::for_language(language);
        
        let naming_violations = self.check_naming_consistency(root, source, &rules);
        let naming_penalty = (naming_violations as f32 * 0.2).min(4.0);
        if naming_penalty > 0.0 {
            if let Some(applied) = tracker.apply(
                format!("naming_violations_{}", naming_violations),
                MetricCategory::Consistency,
                naming_penalty,
                format!("Naming convention violations: {}", naming_violations)
            ) {
                points -= applied;
            }
        }
        
        let import_issues = self.check_import_organization(root, source, language);
        let import_penalty = (import_issues as f32 * 0.3).min(2.0);
        if import_penalty > 0.0 {
            if let Some(applied) = tracker.apply(
                format!("import_issues_{}", import_issues),
                MetricCategory::Consistency,
                import_penalty,
                format!("Import organization issues: {}", import_issues)
            ) {
                points -= applied;
            }
        }
        
        let pattern_score = self.analyze_pattern_consistency(root, source);
        let pattern_penalty = ((1.0 - pattern_score) * 4.0).min(4.0);
        if pattern_penalty > 0.5 {
            if let Some(applied) = tracker.apply(
                format!("pattern_inconsistency_{:.2}", pattern_score),
                MetricCategory::Consistency,
                pattern_penalty,
                format!("Pattern inconsistency: {:.1}% consistent", pattern_score * 100.0)
            ) {
                points -= applied;
            }
        }
        
        Ok(points.max(0.0))
    }
    
    fn category(&self) -> MetricCategory {
        MetricCategory::Consistency
    }
}

#[derive(Debug)]
struct CodePatterns {
    error_handling: Vec<String>,
    null_checks: Vec<String>,
    loops: Vec<String>,
    conditionals: Vec<String>,
}

impl CodePatterns {
    fn new() -> Self {
        Self {
            error_handling: Vec::new(),
            null_checks: Vec::new(),
            loops: Vec::new(),
            conditionals: Vec::new(),
        }
    }
}

impl LanguageRules {
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// For language.
    pub fn for_language(language: Language) -> Self {
        match language {
            Language::Rust => Self::rust_rules(),
            Language::Python => Self::python_rules(),
            Language::JavaScript => Self::javascript_rules(),
            Language::TypeScript => Self::typescript_rules(),
            Language::Go => Self::go_rules(),
            _ => Self::rust_rules(), // Default
        }
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod tests {
    use super::*;
    use tree_sitter::Parser;
    
    fn parse_rust(source: &str) -> Tree {
        let mut parser = Parser::new();
        parser.set_language(&tree_sitter_rust::language()).unwrap();
        parser.parse(source, None).unwrap()
    }
    
    #[test]
    fn test_naming_consistency() {
        let source = r#"
            #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
            /// Snake case function.
            pub fn snake_case_function() {}
            /// Camel case function.
            pub fn CamelCaseFunction() {}  // Violation
            
            /// Pascal case struct.
            pub struct PascalCaseStruct;
            /// Snake case struct.
            pub struct snake_case_struct;  // Violation
            
            const SCREAMING_SNAKE: i32 = 42;
            const lowercase_const: i32 = 24;  // Violation
        "#;
        
        let tree = parse_rust(source);
        let analyzer = ConsistencyAnalyzer::new();
        let rules = LanguageRules::rust_rules();
        
        let violations = analyzer.check_naming_consistency(tree.root_node(), source, &rules);
        assert!(violations > 0);
    }
    
    #[test]
    fn test_import_organization() {
        let source = r#"
            use crate::local::Module;
            use std::collections::HashMap;  // Should come first
            use external::crate::Thing;
        "#;
        
        let tree = parse_rust(source);
        let analyzer = ConsistencyAnalyzer::new();
        
        let issues = analyzer.check_import_organization(tree.root_node(), source, Language::Rust);
        assert!(issues > 0);
    }
    
    #[test]
    fn test_pattern_consistency() {
        let source = r#"
            fn inconsistent_patterns() {
                // Mixed error handling
                let result1 = something().unwrap();
                let result2 = match something_else() {
                    Ok(val) => val,
                    Err(_) => return,
                };
                
                // Mixed null checking
                if value.is_some() {
                    // ...
                }
                if other_value == None {
                    // ...
                }
            }
        "#;
        
        let tree = parse_rust(source);
        let analyzer = ConsistencyAnalyzer::new();
        
        let consistency = analyzer.analyze_pattern_consistency(tree.root_node(), source);
        assert!(consistency < 1.0);
    }
}