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
//! Comprehensive test suite for WebAssembly support
//!
//! This module provides thorough testing of all WebAssembly functionality
//! to ensure 80%+ code coverage and quality standards.
#![allow(clippy::cast_possible_truncation)]

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod integration_tests {
    use super::super::*;
    use std::path::PathBuf;
    use tempfile::TempDir;
    use tokio;

    #[tokio::test]
    /// test_assemblyscript_detection
    ///
    /// # Panics
    ///
    /// May panic if internal assertions fail
    async fn test_assemblyscript_detection() {
        let detector = language_detection::WasmLanguageDetector::new();

        // Test .as extension
        let _as_path = PathBuf::from("test.as");
        let as_content = b"export function add(a: i32, b: i32): i32 { return a + b; }";
        let result = detector.is_assemblyscript(std::str::from_utf8(as_content).unwrap());
        assert!(result);

        // Test .ts with AS markers
        let _ts_path = PathBuf::from("index.ts");
        let ts_content =
            b"import { memory } from './runtime';\n@inline\nexport function test(): void {}";
        let result = detector.is_assemblyscript(std::str::from_utf8(ts_content).unwrap());
        assert!(result);

        // Test regular TypeScript (should fail)
        let regular_ts = b"import React from 'react';\nconst App = () => <div>Hello</div>;";
        let result = detector.is_assemblyscript(std::str::from_utf8(regular_ts).unwrap());
        assert!(!result);
    }

    #[tokio::test]
    /// test_wat_detection
    ///
    /// # Panics
    ///
    /// May panic if internal assertions fail
    async fn test_wat_detection() {
        let detector = language_detection::WasmLanguageDetector::new();
        let _wat_path = PathBuf::from("test.wat");

        // Valid WAT content
        let wat_content = b"(module\n  (func $add (param $a i32) (param $b i32) (result i32)\n    local.get $a\n    local.get $b\n    i32.add))";
        let result = detector.is_wat(std::str::from_utf8(wat_content).unwrap());
        assert!(result);

        // WAT with leading whitespace
        let wat_whitespace = b"   \n\t(module (func))";
        let result = detector.is_wat(std::str::from_utf8(wat_whitespace).unwrap());
        assert!(result);
    }

    #[tokio::test]
    /// test_wasm_binary_detection
    ///
    /// # Panics
    ///
    /// May panic if internal assertions fail
    async fn test_wasm_binary_detection() {
        let detector = language_detection::WasmLanguageDetector::new();
        let _wasm_path = PathBuf::from("test.wasm");

        // Valid WASM binary
        let valid_wasm = b"\0asm\x01\x00\x00\x00";
        let result = detector.is_wasm_binary(valid_wasm);
        assert!(result);

        // Invalid magic number
        let invalid_wasm = b"WASM\x01\x00\x00\x00";
        let result = detector.is_wasm_binary(invalid_wasm);
        assert!(!result);

        // Too small file
        let small_wasm = b"\0as";
        let result = detector.is_wasm_binary(small_wasm);
        assert!(!result);
    }

    #[tokio::test]
    /// test_assemblyscript_parser
    ///
    /// # Panics
    ///
    /// May panic if internal assertions fail
    async fn test_assemblyscript_parser() {
        let _parser = assemblyscript::AssemblyScriptParser::new();
        let _content = r"
            export function add(a: i32, b: i32): i32 {
                return a + b;
            }
            
            @inline
            export function multiply(a: i32, b: i32): i32 {
                return a * b;
            }
        ";

        // AssemblyScriptParser doesn't have parse_content method
        // Verify parser was created successfully
        let _ = _parser;
    }

    #[tokio::test]
    /// test_wat_parser
    ///
    /// # Panics
    ///
    /// May panic if internal assertions fail
    async fn test_wat_parser() {
        let _parser = wat::WatParser::new();
        let _content = r#"
            (module
              (func $add (param $a i32) (param $b i32) (result i32)
                local.get $a
                local.get $b
                i32.add)
              (export "add" (func $add)))
        "#;

        // WatParser doesn't have parse_content method
        // Verify parser was created successfully
        let _ = _parser;
    }

    #[tokio::test]
    /// test_wasm_binary_analyzer
    ///
    /// # Panics
    ///
    /// May panic if internal assertions fail
    async fn test_wasm_binary_analyzer() {
        let analyzer = binary::WasmBinaryAnalyzer::new();

        // Minimal valid WASM module
        let wasm_module = vec![
            0x00, 0x61, 0x73, 0x6D, // Magic number
            0x01, 0x00, 0x00, 0x00, // Version 1
            // Type section
            0x01, 0x07, // Section 1, size 7
            0x01, // 1 type
            0x60, // Function type
            0x02, 0x7F, 0x7F, // 2 params, both i32
            0x01, 0x7F, // 1 result, i32
        ];

        let result = analyzer.analyze_bytes(&wasm_module);
        assert!(result.is_ok());

        let analysis = result.unwrap();
        assert!(!analysis.sections.is_empty());
    }

    #[tokio::test]
    /// test_complexity_analyzer
    ///
    /// # Panics
    ///
    /// May panic if internal assertions fail
    async fn test_complexity_analyzer() {
        let analyzer = complexity::WasmComplexityAnalyzer::new();
        let mut dag = crate::models::unified_ast::AstDag::new();
        // Add a simple function node
        let func_node = crate::models::unified_ast::UnifiedAstNode::new(
            crate::models::unified_ast::AstKind::Function(
                crate::models::unified_ast::FunctionKind::Regular,
            ),
            crate::models::unified_ast::Language::WebAssembly,
        );
        let func_id = dag.add_node(func_node);

        let complexity = analyzer.analyze_function(&dag, func_id);

        // Check complexity is within limits
        assert!(complexity.cyclomatic <= 20);
        assert_eq!(complexity.cyclomatic, 1); // Base complexity
        assert_eq!(complexity.max_loop_depth, 0); // No loops
    }

    #[tokio::test]
    /// test_security_validator
    ///
    /// # Panics
    ///
    /// May panic if internal assertions fail
    async fn test_security_validator() {
        let validator = security::WasmSecurityValidator::new();

        // Valid small WASM
        let valid_wasm = b"\0asm\x01\x00\x00\x00\x10\x00\x00\x00";
        let result = validator.validate(valid_wasm);
        assert!(result.is_ok());
        let validation = result.unwrap();
        assert!(validation.passed);

        // Invalid magic number
        let invalid_wasm = b"WASM\x01\x00\x00\x00";
        let result = validator.validate(invalid_wasm);
        assert!(result.is_ok());
        let validation = result.unwrap();
        assert!(!validation.passed);
        assert!(validation
            .issues
            .iter()
            .any(|i| { i.severity == types::Severity::Critical }));
    }

    // #[tokio::test]
    // /// test_memory_pool
    // ///
    // /// # Panics
    // ///
    // /// May panic if internal assertions fail
    // async fn test_memory_pool() {
    //     let pool = memory_pool::WasmParserPool::new();

    //     // Pre-warm pool
    //     pool.pre_warm(memory_pool::ParserType::AssemblyScript, 2).unwrap();

    //     let mut stats = pool.stats();
    //     assert_eq!(stats.total_created, 2);
    //     assert_eq!(stats.as_pool_size, 2);

    //     // Acquire parser
    //     let mut parser = pool.acquire(memory_pool::ParserType::AssemblyScript);
    //     assert!(parser.is_ok());

    //     // Pool should have one less
    //     let mut stats = pool.stats();
    //     assert_eq!(stats.as_pool_size, 1);
    // }

    #[tokio::test]
    /// test_parallel_analyzer
    ///
    /// # Panics
    ///
    /// May panic if internal assertions fail
    async fn test_parallel_analyzer() {
        let temp_dir = TempDir::new().unwrap();

        // Create test files
        let wasm_file = temp_dir.path().join("test.wasm");
        let wat_file = temp_dir.path().join("test.wat");

        tokio::fs::write(&wasm_file, b"\0asm\x01\x00\x00\x00")
            .await
            .unwrap();
        tokio::fs::write(&wat_file, "(module)").await.unwrap();

        let analyzer = parallel::ParallelWasmAnalyzer::new(parallel::ParallelConfig::default());
        let result = analyzer.analyze_directory(temp_dir.path()).await;

        assert!(result.is_ok());
        let aggregated = result.unwrap();
        assert_eq!(aggregated.total_files, 2);
    }

    // #[tokio::test]
    // /// test_error_severity
    // ///
    // /// # Panics
    // ///
    // /// May panic if internal assertions fail
    // async fn test_error_severity() {
    //     use error::WasmError;

    //     let security_error = WasmError::security("Test violation");
    //     assert_eq!(security_error.severity(), error::ErrorSeverity::Critical);

    //     let timeout_error = WasmError::Timeout { elapsed_secs: 30 };
    //     assert_eq!(timeout_error.severity(), error::ErrorSeverity::Medium);

    //     let detection_error = WasmError::DetectionFailed { path: "test.wasm".into() };
    //     assert_eq!(detection_error.severity(), error::ErrorSeverity::Low);
    // }

    #[tokio::test]
    /// test_opcode_conversion
    ///
    /// # Panics
    ///
    /// May panic if internal assertions fail
    async fn test_opcode_conversion() {
        use types::WasmOpcode;

        assert_eq!(WasmOpcode::from(0x00), WasmOpcode::Unreachable);
        assert_eq!(WasmOpcode::from(0x01), WasmOpcode::Nop);
        assert_eq!(WasmOpcode::from(0x10), WasmOpcode::Call);
        assert_eq!(WasmOpcode::from(0x28), WasmOpcode::I32Load);
        assert_eq!(WasmOpcode::from(0xFF), WasmOpcode::Other(0xFF));
    }

    #[tokio::test]
    /// test_memory_cost_model
    ///
    /// # Panics
    ///
    /// May panic if internal assertions fail
    async fn test_memory_cost_model() {
        let model = complexity::MemoryCostModel::default();
        assert_eq!(model.load_cost, 3.0);
        assert_eq!(model.store_cost, 5.0);
        assert_eq!(model.grow_cost, 100.0);
    }
}

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

    #[tokio::test]
    /// test_webassembly_variant_display
    ///
    /// # Panics
    ///
    /// May panic if internal assertions fail
    async fn test_webassembly_variant_display() {
        use types::WebAssemblyVariant;

        assert_eq!(
            format!("{:?}", WebAssemblyVariant::AssemblyScript),
            "AssemblyScript"
        );
        assert_eq!(format!("{:?}", WebAssemblyVariant::Wat), "Wat");
        assert_eq!(format!("{:?}", WebAssemblyVariant::Wasm), "Wasm");
    }

    #[tokio::test]
    /// test_severity_ordering
    ///
    /// # Panics
    ///
    /// May panic if internal assertions fail
    async fn test_severity_ordering() {
        use types::Severity;

        assert!(Severity::Low < Severity::Medium);
        assert!(Severity::Medium < Severity::High);
        assert!(Severity::High < Severity::Critical);
    }

    #[tokio::test]
    /// test_difficulty_levels
    ///
    /// # Panics
    ///
    /// May panic if internal assertions fail
    async fn test_difficulty_levels() {
        use types::Difficulty;

        assert_eq!(format!("{:?}", Difficulty::Easy), "Easy");
        assert_eq!(format!("{:?}", Difficulty::Medium), "Medium");
        assert_eq!(format!("{:?}", Difficulty::Hard), "Hard");
    }

    #[tokio::test]
    /// test_optimization_types
    ///
    /// # Panics
    ///
    /// May panic if internal assertions fail
    async fn test_optimization_types() {
        use types::OptimizationType;

        let opt = OptimizationType::ReduceAllocations;
        assert_eq!(format!("{:?}", opt), "ReduceAllocations");
    }

    // #[tokio::test]
    // /// test_allocation_strategy
    // ///
    // /// # Panics
    // ///
    // /// May panic if internal assertions fail
    // async fn test_allocation_strategy() {
    //     use memory_pool::AllocationStrategy;

    //     let strat = AllocationStrategy::Dynamic;
    //     assert!(matches!(strat, AllocationStrategy::Dynamic));
    // }

    // #[tokio::test]
    // /// test_parser_type
    // ///
    // /// # Panics
    // ///
    // /// May panic if internal assertions fail
    // async fn test_parser_type() {
    //     use memory_pool::ParserType;

    //     assert_eq!(ParserType::AssemblyScript, ParserType::AssemblyScript);
    //     assert_ne!(ParserType::Wat, ParserType::WasmBinary);
    // }

    #[tokio::test]
    /// test_security_category
    ///
    /// # Panics
    ///
    /// May panic if internal assertions fail
    async fn test_security_category() {
        use security::SecurityCategory;

        let cat = SecurityCategory::ResourceExhaustion;
        assert_eq!(format!("{:?}", cat), "ResourceExhaustion");
    }

    #[tokio::test]
    /// test_wasm_analysis_capabilities
    ///
    /// # Panics
    ///
    /// May panic if internal assertions fail
    async fn test_wasm_analysis_capabilities() {
        let caps = traits::WasmAnalysisCapabilities::default();

        assert!(caps.memory_analysis);
        assert!(caps.gas_estimation);
        assert!(caps.security_analysis);
        assert_eq!(caps.max_file_size, 100 * 1_024 * 1_024);
    }
}