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
#![cfg_attr(coverage_nightly, coverage(off))]
//! CB-500 Series: Runtime behavior checks.
//!
//! - CB-507: Panic Macros
//! - CB-510: include!() Macro Hygiene
//! - CB-511: Flaky Timing Tests
//! - CB-512: Error Propagation Gap
//! - CB-513: Silent Error Swallowing
//! - CB-514: Debug Eprintln Leaks

use super::utilities::{
    is_macro_in_string_literal, DOT_UNWRAP, EPRINTLN_DBG, EPRINTLN_DEBUG, EPRINTLN_TRACE,
    MAP_ERR_DISCARD, UNWRAP_OR_ELSE_DISCARD,
};
use crate::cli::handlers::comply_cb_detect::types::*;
use std::fs;
use std::path::Path;

/// CB-507: Panic Macros - todo!(), unimplemented!() in production code
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub fn detect_cb507_panic_macros(project_path: &Path) -> Vec<CbPatternViolation> {
    let src_dir = project_path.join("src");
    let entries = match walkdir_rs_files(&src_dir) {
        Ok(e) => e,
        Err(_) => return Vec::new(),
    };

    let panic_macros = ["todo!(", "unimplemented!("];
    let mut violations = Vec::new();

    for entry in &entries {
        if is_test_file(entry) {
            continue;
        }
        let content = match fs::read_to_string(entry) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let lines: Vec<&str> = content.lines().collect();
        let test_lines = compute_test_code_lines(&lines);
        let file = entry
            .strip_prefix(project_path)
            .unwrap_or(entry)
            .display()
            .to_string();

        for (i, line) in lines.iter().enumerate() {
            if test_lines.contains(&i) {
                continue;
            }
            let trimmed = line.trim();
            if trimmed.starts_with("//") || trimmed.starts_with("*") {
                continue;
            }
            if is_macro_in_string_literal(trimmed, &panic_macros) {
                continue;
            }
            for mac in &panic_macros {
                if trimmed.contains(mac) {
                    violations.push(CbPatternViolation {
                        pattern_id: "CB-507".to_string(),
                        file: file.clone(),
                        line: i + 1,
                        description: format!(
                            "Panic macro `{}` in production code",
                            mac.trim_end_matches('(')
                        ),
                        severity: Severity::Warning,
                    });
                    break;
                }
            }
        }
    }

    violations
}

/// CB-510: include!() Macro Hygiene - non-standalone files included via include!()
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub fn detect_cb510_include_macro_hygiene(project_path: &Path) -> Vec<CbPatternViolation> {
    let src_dir = project_path.join("src");
    let entries = match walkdir_rs_files(&src_dir) {
        Ok(e) => e,
        Err(_) => return Vec::new(),
    };

    let mut violations = Vec::new();

    for entry in &entries {
        let content = match fs::read_to_string(entry) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let file = entry
            .strip_prefix(project_path)
            .unwrap_or(entry)
            .display()
            .to_string();

        for (i, line) in content.lines().enumerate() {
            let trimmed = line.trim();
            if trimmed.starts_with("//") {
                continue;
            }
            if trimmed.contains("include!(") && !trimmed.contains("include_str!") {
                violations.push(CbPatternViolation {
                    pattern_id: "CB-510".to_string(),
                    file: file.clone(),
                    line: i + 1,
                    description: "include!() macro - included files are not standalone compilable"
                        .to_string(),
                    severity: Severity::Info,
                });
            }
        }
    }

    violations
}

/// CB-511: Flaky Timing Tests - tests with Instant::now() and tight duration assertions
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub fn detect_cb511_flaky_timing_tests(project_path: &Path) -> Vec<CbPatternViolation> {
    let src_dir = project_path.join("src");
    let test_dir = project_path.join("tests");

    let mut all_files = walkdir_rs_files(&src_dir).unwrap_or_default();
    all_files.extend(walkdir_rs_files(&test_dir).unwrap_or_default());

    let mut violations = Vec::new();

    for entry in &all_files {
        let content = match fs::read_to_string(entry) {
            Ok(c) => c,
            Err(_) => continue,
        };

        // Only check files with test attributes
        if !content.contains("#[test]") && !content.contains("#[tokio::test]") {
            continue;
        }

        let file = entry
            .strip_prefix(project_path)
            .unwrap_or(entry)
            .display()
            .to_string();

        // Per-test-function analysis: only flag when Instant::now(), .elapsed(),
        // and a duration assertion all appear in the SAME test function
        let lines: Vec<&str> = content.lines().collect();
        let mut in_test_fn = false;
        let mut test_fn_start: usize = 0;
        let mut brace_depth: u32 = 0;
        let mut fn_has_instant = false;
        let mut fn_has_elapsed = false;
        let mut fn_has_duration_assert = false;

        for (i, line) in lines.iter().enumerate() {
            let trimmed = line.trim();

            // Detect test function start (look for #[test] or #[tokio::test] preceding fn)
            if !in_test_fn
                && (trimmed.starts_with("fn ") || trimmed.starts_with("async fn "))
                && i > 0
            {
                // Look back for #[test] or #[tokio::test] attribute
                let has_test_attr = (1..=3).any(|back| {
                    i >= back && {
                        let prev = lines[i - back].trim();
                        prev == "#[test]" || prev == "#[tokio::test]"
                    }
                });
                if has_test_attr {
                    in_test_fn = true;
                    test_fn_start = i + 1;
                    brace_depth = 0;
                    fn_has_instant = false;
                    fn_has_elapsed = false;
                    fn_has_duration_assert = false;
                }
            }

            if in_test_fn {
                brace_depth += trimmed.matches('{').count() as u32;
                brace_depth = brace_depth.saturating_sub(trimmed.matches('}').count() as u32);

                if trimmed.contains("Instant::now()") {
                    fn_has_instant = true;
                }
                if trimmed.contains(".elapsed()") {
                    fn_has_elapsed = true;
                }
                // Require .elapsed() specifically in an assertion context,
                // not just any line with "assert!" and the word "elapsed"
                if (trimmed.contains("assert!")
                    || trimmed.contains("assert_eq!")
                    || trimmed.contains("assert_ne!")
                    || trimmed.contains("assert_lt!")
                    || trimmed.contains("assert_le!"))
                    && trimmed.contains(".elapsed()")
                {
                    fn_has_duration_assert = true;
                }

                // End of test function
                if brace_depth == 0 && i > test_fn_start {
                    if fn_has_instant && fn_has_elapsed && fn_has_duration_assert {
                        violations.push(CbPatternViolation {
                            pattern_id: "CB-511".to_string(),
                            file: file.clone(),
                            line: test_fn_start,
                            description: "Test uses Instant::now() with duration assertions — may be flaky under load".to_string(),
                            severity: Severity::Warning,
                        });
                    }
                    in_test_fn = false;
                }
            }
        }
    }

    violations
}

/// CB-512: Error Propagation Gap - functions returning Result but using unwrap() internally
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub fn detect_cb512_error_propagation_gap(project_path: &Path) -> Vec<CbPatternViolation> {
    let src_dir = project_path.join("src");
    let entries = match walkdir_rs_files(&src_dir) {
        Ok(e) => e,
        Err(_) => return Vec::new(),
    };

    let mut violations = Vec::new();

    for entry in &entries {
        if is_test_file(entry) {
            continue;
        }
        let content = match fs::read_to_string(entry) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let lines: Vec<&str> = content.lines().collect();
        let test_lines = compute_test_code_lines(&lines);
        let file = entry
            .strip_prefix(project_path)
            .unwrap_or(entry)
            .display()
            .to_string();

        let mut in_result_fn = false;
        let mut fn_line = 0;
        let mut fn_depth = 0u32;
        let mut unwrap_count = 0u32;

        for (i, line) in lines.iter().enumerate() {
            if test_lines.contains(&i) {
                continue;
            }

            let trimmed = line.trim();

            // Detect function returning Result
            if (trimmed.starts_with("pub fn ")
                || trimmed.starts_with("fn ")
                || trimmed.starts_with("pub async fn ")
                || trimmed.starts_with("async fn "))
                && trimmed.contains("Result<")
            {
                in_result_fn = true;
                fn_line = i;
                fn_depth = 0;
                unwrap_count = 0;
            }

            if in_result_fn {
                fn_depth += trimmed.matches('{').count() as u32;
                fn_depth = fn_depth.saturating_sub(trimmed.matches('}').count() as u32);

                if trimmed.contains(DOT_UNWRAP) {
                    unwrap_count += 1;
                }

                // End of function
                if fn_depth == 0 && i > fn_line {
                    if unwrap_count >= 3 {
                        violations.push(CbPatternViolation {
                            pattern_id: "CB-512".to_string(),
                            file: file.clone(),
                            line: fn_line + 1,
                            description: format!(
                                "Function returns Result but has {unwrap_count} unwrap() calls - consider using ? operator"
                            ),
                            severity: Severity::Warning,
                        });
                    }
                    in_result_fn = false;
                }
            }
        }
    }

    violations
}

/// CB-513: Silent Error Swallowing - discarding error context with |_| closures
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub fn detect_cb513_silent_error_swallowing(project_path: &Path) -> Vec<CbPatternViolation> {
    let src_dir = project_path.join("src");
    let entries = match walkdir_rs_files(&src_dir) {
        Ok(e) => e,
        Err(_) => return Vec::new(),
    };

    let mut violations = Vec::new();

    for entry in &entries {
        if is_test_file(entry) {
            continue;
        }
        let content = match fs::read_to_string(entry) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let lines: Vec<&str> = content.lines().collect();
        let test_lines = compute_test_code_lines(&lines);
        let file = entry
            .strip_prefix(project_path)
            .unwrap_or(entry)
            .display()
            .to_string();

        for (i, line) in lines.iter().enumerate() {
            if test_lines.contains(&i) {
                continue;
            }
            let trimmed = line.trim();
            if trimmed.starts_with("//") || trimmed.starts_with("*") {
                continue;
            }

            // Detect .unwrap_or_else(|_| -- intentionally discarded error
            if trimmed.contains(UNWRAP_OR_ELSE_DISCARD) {
                violations.push(CbPatternViolation {
                    pattern_id: "CB-513".to_string(),
                    file: file.clone(),
                    line: i + 1,
                    description:
                        "Silent error swallowing: .unwrap_or_else(|_| discards error context"
                            .to_string(),
                    severity: Severity::Warning,
                });
                continue;
            }

            // Detect .map_err(|_| -- discards original error
            if trimmed.contains(MAP_ERR_DISCARD) {
                violations.push(CbPatternViolation {
                    pattern_id: "CB-513".to_string(),
                    file: file.clone(),
                    line: i + 1,
                    description:
                        "Silent error swallowing: .map_err(|_| discards original error context"
                            .to_string(),
                    severity: Severity::Warning,
                });
            }
        }
    }

    violations
}

/// CB-514: Debug Eprintln Leaks - debug print statements in production code
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub fn detect_cb514_debug_eprintln_leaks(project_path: &Path) -> Vec<CbPatternViolation> {
    let src_dir = project_path.join("src");
    let entries = match walkdir_rs_files(&src_dir) {
        Ok(e) => e,
        Err(_) => return Vec::new(),
    };

    let mut violations = Vec::new();

    for entry in &entries {
        if is_test_file(entry) {
            continue;
        }
        let content = match fs::read_to_string(entry) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let lines: Vec<&str> = content.lines().collect();
        let test_lines = compute_test_code_lines(&lines);
        let file = entry
            .strip_prefix(project_path)
            .unwrap_or(entry)
            .display()
            .to_string();

        for (i, line) in lines.iter().enumerate() {
            if test_lines.contains(&i) {
                continue;
            }
            let trimmed = line.trim();
            if trimmed.starts_with("//") || trimmed.starts_with("*") {
                continue;
            }

            if trimmed.contains(EPRINTLN_DEBUG)
                || trimmed.contains(EPRINTLN_DBG)
                || trimmed.contains(EPRINTLN_TRACE)
            {
                violations.push(CbPatternViolation {
                    pattern_id: "CB-514".to_string(),
                    file: file.clone(),
                    line: i + 1,
                    description: "Debug eprintln! leak in production code".to_string(),
                    severity: Severity::Warning,
                });
            }
        }
    }

    violations
}