wasm-slim 0.1.1

WASM bundle size optimizer
Documentation
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
//! Panic pattern detection for WASM size optimization
//!
//! Identifies panic-inducing code patterns that bloat WASM binaries.
//! Each panic site adds 500-2000 bytes for formatting and unwinding infrastructure.
//!
//! Based on [Rust WASM book](https://rustwasm.github.io/docs/book/reference/code-size.html#avoid-panicking)

use crate::infra::{FileSystem, RealFileSystem};
use rayon::prelude::*;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use syn::{visit::Visit, BinOp, ExprBinary, ExprIndex, ExprMethodCall};
use thiserror::Error;

/// Errors that can occur during panic detection
#[derive(Error, Debug)]
pub enum PanicDetectionError {
    /// I/O error
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    /// Regex compilation error
    #[error("Regex error: {0}")]
    Regex(#[from] regex::Error),

    /// Parse error
    #[error("Failed to parse {0}: {1}")]
    ParseError(PathBuf, String),
}

/// Type of panic pattern detected
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum PanicPattern {
    /// .unwrap() call
    Unwrap,
    /// .expect("message") call
    Expect,
    /// Array indexing arr\[i\]
    Index,
    /// Division operator / or %
    Division,
    /// panic!() macro
    PanicMacro,
    /// assert!() macro (in release builds)
    AssertMacro,
}

impl PanicPattern {
    /// Get human-readable name
    pub fn name(&self) -> &'static str {
        match self {
            PanicPattern::Unwrap => "unwrap()",
            PanicPattern::Expect => "expect()",
            PanicPattern::Index => "array[index]",
            PanicPattern::Division => "division operator",
            PanicPattern::PanicMacro => "panic!()",
            PanicPattern::AssertMacro => "assert!()",
        }
    }

    /// Get recommended alternative
    pub fn alternative(&self) -> &'static str {
        match self {
            PanicPattern::Unwrap | PanicPattern::Expect => "match or if let",
            PanicPattern::Index => ".get(index)",
            PanicPattern::Division => ".checked_div() or .checked_rem()",
            PanicPattern::PanicMacro => "Result<T, E> or Option<T>",
            PanicPattern::AssertMacro => "debug_assert!() or runtime checks",
        }
    }

    /// Get estimated size per occurrence (bytes)
    pub fn size_per_occurrence(&self) -> u64 {
        match self {
            PanicPattern::Unwrap => 800,
            PanicPattern::Expect => 1200, // Higher due to custom message
            PanicPattern::Index => 1000,
            PanicPattern::Division => 600,
            PanicPattern::PanicMacro => 1500,
            PanicPattern::AssertMacro => 1000,
        }
    }
}

/// A detected panic site
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DetectedPanic {
    /// File path
    pub file: PathBuf,
    /// Line number (0 if unknown)
    pub line: usize,
    /// Type of panic pattern
    pub pattern: PanicPattern,
    /// Code snippet (if available)
    pub snippet: Option<String>,
}

/// Complete panic analysis results
#[derive(Debug, Serialize, Deserialize)]
pub struct PanicResults {
    /// Total panics detected
    pub total_panics: usize,
    /// Panics by type
    pub by_pattern: Vec<(PanicPattern, usize)>,
    /// All detected panic sites
    pub panic_sites: Vec<DetectedPanic>,
    /// Estimated size impact in KB
    pub estimated_size_kb: u64,
    /// Recommendations
    pub recommendations: Vec<String>,
}

/// Panic pattern detector
pub struct PanicDetector<FS: FileSystem + Sync + Send = RealFileSystem> {
    project_root: PathBuf,
    fs: FS,
}

impl PanicDetector<RealFileSystem> {
    /// Create a new panic detector with the real filesystem
    pub fn new(project_root: impl Into<PathBuf>) -> Self {
        Self::with_fs(project_root, RealFileSystem)
    }
}

impl<FS: FileSystem + Sync + Send> PanicDetector<FS> {
    /// Create a new panic detector with a custom filesystem implementation
    pub fn with_fs(project_root: impl Into<PathBuf>, fs: FS) -> Self {
        Self {
            project_root: project_root.into(),
            fs,
        }
    }

    /// Scan the project for panic patterns
    pub fn scan_project(&self) -> Result<PanicResults, PanicDetectionError> {
        // Find all Rust source files
        let rust_files = self.find_rust_files()?;

        // Parallel scan of all files
        let all_panics: Vec<DetectedPanic> = rust_files
            .par_iter()
            .flat_map(|source_file| {
                self.scan_file(source_file).unwrap_or_else(|e| {
                    eprintln!("Warning: Failed to scan {}: {}", source_file.display(), e);
                    Vec::new()
                })
            })
            .collect();

        // Build results
        self.build_results(all_panics)
    }

    /// Scan a single source file
    fn scan_file(&self, source_file: &Path) -> Result<Vec<DetectedPanic>, PanicDetectionError> {
        let content = self.fs.read_to_string(source_file)?;

        let mut panics = Vec::new();

        // Try AST parsing first (most reliable)
        if let Ok(ast_panics) = self.scan_with_ast(&content, source_file) {
            panics.extend(ast_panics);
        }

        // Add regex fallback for patterns AST might miss
        let regex_panics = self.scan_with_regex(&content, source_file)?;
        panics.extend(regex_panics);

        Ok(panics)
    }

    /// Scan using AST parsing
    fn scan_with_ast(
        &self,
        content: &str,
        source_file: &Path,
    ) -> Result<Vec<DetectedPanic>, PanicDetectionError> {
        let syntax_tree: syn::File = syn::parse_str(content).map_err(|e| {
            PanicDetectionError::ParseError(source_file.to_path_buf(), e.to_string())
        })?;

        let mut visitor = PanicVisitor::new(source_file);
        visitor.visit_file(&syntax_tree);

        Ok(visitor.panics)
    }

    /// Scan using regex patterns (fallback)
    fn scan_with_regex(
        &self,
        content: &str,
        source_file: &Path,
    ) -> Result<Vec<DetectedPanic>, PanicDetectionError> {
        let mut panics = Vec::new();

        // Pattern: panic!
        let panic_re = Regex::new(r"panic!\s*\(")?;
        for (line_num, line) in content.lines().enumerate() {
            if panic_re.is_match(line) {
                panics.push(DetectedPanic {
                    file: source_file.to_path_buf(),
                    line: line_num + 1,
                    pattern: PanicPattern::PanicMacro,
                    snippet: Some(line.trim().to_string()),
                });
            }
        }

        // Pattern: assert!
        let assert_re = Regex::new(r"assert!\s*\(")?;
        for (line_num, line) in content.lines().enumerate() {
            if assert_re.is_match(line) && !line.contains("debug_assert!") {
                panics.push(DetectedPanic {
                    file: source_file.to_path_buf(),
                    line: line_num + 1,
                    pattern: PanicPattern::AssertMacro,
                    snippet: Some(line.trim().to_string()),
                });
            }
        }

        Ok(panics)
    }

    /// Find all Rust source files in the project
    fn find_rust_files(&self) -> Result<Vec<PathBuf>, PanicDetectionError> {
        let mut rust_files = Vec::new();

        // Search in src/ and tests/ directories
        for dir_name in &["src", "tests", "benches", "examples"] {
            let dir_path = self.project_root.join(dir_name);
            if dir_path.exists() {
                Self::collect_rust_files(&dir_path, &mut rust_files, &self.fs)?;
            }
        }

        Ok(rust_files)
    }

    /// Recursively collect .rs files
    fn collect_rust_files(
        dir: &Path,
        files: &mut Vec<PathBuf>,
        fs: &FS,
    ) -> Result<(), PanicDetectionError> {
        if dir.is_dir() {
            for entry in fs.read_dir(dir)? {
                let entry = entry?;
                let path = entry.path();

                if path.is_dir() {
                    Self::collect_rust_files(&path, files, fs)?;
                } else if path.extension().and_then(|s| s.to_str()) == Some("rs") {
                    files.push(path);
                }
            }
        }
        Ok(())
    }

    /// Build final results with statistics and recommendations
    fn build_results(
        &self,
        panic_sites: Vec<DetectedPanic>,
    ) -> Result<PanicResults, PanicDetectionError> {
        Ok(super::panic_advisor::build_results(panic_sites))
    }
}

/// AST visitor for detecting panic patterns
struct PanicVisitor<'a> {
    source_file: &'a Path,
    panics: Vec<DetectedPanic>,
}

impl<'a> PanicVisitor<'a> {
    fn new(source_file: &'a Path) -> Self {
        Self {
            source_file,
            panics: Vec::new(),
        }
    }

    fn add_panic(&mut self, pattern: PanicPattern, line: usize) {
        self.panics.push(DetectedPanic {
            file: self.source_file.to_path_buf(),
            line,
            pattern,
            snippet: None,
        });
    }
}

impl<'a> Visit<'a> for PanicVisitor<'a> {
    /// Visit method calls to detect unwrap(), expect()
    fn visit_expr_method_call(&mut self, node: &'a ExprMethodCall) {
        let method_name = node.method.to_string();

        match method_name.as_str() {
            "unwrap" => {
                self.add_panic(PanicPattern::Unwrap, 0);
            }
            "expect" => {
                self.add_panic(PanicPattern::Expect, 0);
            }
            _ => {}
        }

        // Continue visiting children
        syn::visit::visit_expr_method_call(self, node);
    }

    /// Visit binary operations to detect division
    fn visit_expr_binary(&mut self, node: &'a ExprBinary) {
        match node.op {
            BinOp::Div(_) | BinOp::Rem(_) => {
                self.add_panic(PanicPattern::Division, 0);
            }
            _ => {}
        }

        // Continue visiting children
        syn::visit::visit_expr_binary(self, node);
    }

    /// Visit index expressions to detect arr\[i\]
    fn visit_expr_index(&mut self, node: &'a ExprIndex) {
        self.add_panic(PanicPattern::Index, 0);

        // Continue visiting children
        syn::visit::visit_expr_index(self, node);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_panic_pattern_name_returns_correct_names() {
        assert_eq!(PanicPattern::Unwrap.name(), "unwrap()");
        assert_eq!(PanicPattern::Expect.name(), "expect()");
        assert_eq!(PanicPattern::Index.name(), "array[index]");
        assert_eq!(PanicPattern::Division.name(), "division operator");
    }

    #[test]
    fn test_panic_pattern_alternative_returns_suggestions() {
        assert_eq!(PanicPattern::Unwrap.alternative(), "match or if let");
        assert_eq!(PanicPattern::Index.alternative(), ".get(index)");
        assert_eq!(
            PanicPattern::Division.alternative(),
            ".checked_div() or .checked_rem()"
        );
    }

    #[test]
    fn test_panic_pattern_size_per_occurrence_returns_nonzero() {
        assert!(PanicPattern::Unwrap.size_per_occurrence() > 0);
        assert!(
            PanicPattern::Expect.size_per_occurrence() > PanicPattern::Unwrap.size_per_occurrence()
        );
        assert!(PanicPattern::PanicMacro.size_per_occurrence() > 1000);
    }

    #[test]
    fn test_scan_with_ast_detects_unwrap() {
        let detector = PanicDetector::new(".");
        let code = r#"
            fn main() {
                let x = Some(5);
                x.unwrap();
            }
        "#;

        let result = detector.scan_with_ast(code, Path::new("test.rs"));
        assert!(result.is_ok());

        let panics = result.unwrap();
        assert_eq!(panics.len(), 1);
        assert_eq!(panics[0].pattern, PanicPattern::Unwrap);
    }

    #[test]
    fn test_scan_with_ast_detects_expect() {
        let detector = PanicDetector::new(".");
        let code = r#"
            fn main() {
                let x: Result<i32, String> = Ok(5);
                x.expect("failed");
            }
        "#;

        let result = detector.scan_with_ast(code, Path::new("test.rs"));
        assert!(result.is_ok());

        let panics = result.unwrap();
        assert_eq!(panics.len(), 1);
        assert_eq!(panics[0].pattern, PanicPattern::Expect);
    }

    #[test]
    fn test_scan_with_ast_detects_index() {
        let detector = PanicDetector::new(".");
        let code = r#"
            fn main() {
                let arr = [1, 2, 3];
                let x = arr[0];
            }
        "#;

        let result = detector.scan_with_ast(code, Path::new("test.rs"));
        assert!(result.is_ok());

        let panics = result.unwrap();
        assert_eq!(panics.len(), 1);
        assert_eq!(panics[0].pattern, PanicPattern::Index);
    }

    #[test]
    fn test_scan_with_ast_detects_division() {
        let detector = PanicDetector::new(".");
        let code = r#"
            fn main() {
                let x = 10 / 2;
                let y = 10 % 3;
            }
        "#;

        let result = detector.scan_with_ast(code, Path::new("test.rs"));
        assert!(result.is_ok());

        let panics = result.unwrap();
        assert_eq!(panics.len(), 2); // Both / and %
        assert!(panics.iter().all(|p| p.pattern == PanicPattern::Division));
    }

    #[test]
    fn test_scan_with_regex_detects_panic_macro() {
        let detector = PanicDetector::new(".");
        let code = r#"
            fn main() {
                panic!("error");
            }
        "#;

        let result = detector.scan_with_regex(code, Path::new("test.rs"));
        assert!(result.is_ok());

        let panics = result.unwrap();
        assert!(panics.iter().any(|p| p.pattern == PanicPattern::PanicMacro));
    }

    #[test]
    fn test_scan_with_regex_detects_assert_macro() {
        let detector = PanicDetector::new(".");
        let code = r#"
            fn main() {
                assert!(x > 0);
                debug_assert!(y > 0);  // Should NOT be detected
            }
        "#;

        let result = detector.scan_with_regex(code, Path::new("test.rs"));
        assert!(result.is_ok());

        let panics = result.unwrap();
        let assert_panics: Vec<_> = panics
            .iter()
            .filter(|p| p.pattern == PanicPattern::AssertMacro)
            .collect();
        assert_eq!(assert_panics.len(), 1); // Only assert!, not debug_assert!
    }

    #[test]
    fn test_generate_recommendations_critical_level() {
        use crate::analyzer::panic_advisor::generate_recommendations;
        let by_pattern = vec![(PanicPattern::Unwrap, 150)];

        let recs = generate_recommendations(150, &by_pattern, 120);

        assert!(!recs.is_empty());
        assert!(recs[0].contains("[P0]"));
        assert!(recs[0].contains("Critical"));
    }

    #[test]
    fn test_generate_recommendations_low_level() {
        use crate::analyzer::panic_advisor::generate_recommendations;
        let by_pattern = vec![(PanicPattern::Unwrap, 5)];

        let recs = generate_recommendations(5, &by_pattern, 4);

        assert!(!recs.is_empty());
        assert!(recs[0].contains("[P3]"));
        assert!(recs[0].contains("Low"));
    }
}