cargo-fa 0.11.1

Static analysis tool for framealloc - detect memory intent violations before runtime
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
//! Diagnostic types and codes for cargo-fa.

use crate::cli::Severity;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// A diagnostic message from static analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Diagnostic {
    /// Diagnostic code (e.g., FA601)
    pub code: DiagnosticCode,
    
    /// Severity level
    pub severity: Severity,
    
    /// Primary message
    pub message: String,
    
    /// Source location
    pub location: Location,
    
    /// Additional context/notes
    pub notes: Vec<String>,
    
    /// Suggested fix
    pub suggestion: Option<Suggestion>,
    
    /// Related locations
    pub related: Vec<RelatedLocation>,
}

/// Source code location.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Location {
    pub file: PathBuf,
    pub line: usize,
    pub column: usize,
    pub end_line: Option<usize>,
    pub end_column: Option<usize>,
}

/// A related location for multi-span diagnostics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RelatedLocation {
    pub location: Location,
    pub message: String,
}

/// A suggested fix.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Suggestion {
    pub message: String,
    pub replacement: Option<String>,
    pub applicability: Applicability,
}

/// How confident we are in the suggestion.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum Applicability {
    /// Can be applied automatically
    MachineApplicable,
    /// Probably correct but needs review
    MaybeIncorrect,
    /// Needs human decision
    HasPlaceholders,
    /// Just informational
    Unspecified,
}

/// Diagnostic code with metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiagnosticCode {
    pub code: String,
    pub category: Category,
}

/// Diagnostic categories.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum Category {
    /// FA6xx: Lifetime/escape issues
    Lifetime,
    /// FA7xx: Async safety
    AsyncSafety,
    /// FA8xx: Architecture violations
    Architecture,
    /// FA2xx: Threading
    Threading,
    /// FA3xx: Budgets
    Budgets,
}

impl DiagnosticCode {
    pub fn new(code: &str) -> Self {
        let category = match &code[2..3] {
            "6" => Category::Lifetime,
            "7" => Category::AsyncSafety,
            "8" => Category::Architecture,
            "2" => Category::Threading,
            "3" => Category::Budgets,
            _ => Category::Lifetime,
        };
        
        Self {
            code: code.to_string(),
            category,
        }
    }
}

impl std::fmt::Display for DiagnosticCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.code)
    }
}

// =============================================================================
// Predefined diagnostic codes (FA2xx - Threading) - v0.6.0
// =============================================================================

/// FA201: Cross-thread frame access without transfer
pub fn fa201(location: Location, context: &str) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA201"),
        severity: Severity::Error,
        message: "frame allocation used across thread boundary without explicit transfer".to_string(),
        location,
        notes: vec![
            format!("detected in context: {}", context),
            "frame allocations are thread-local and cannot be safely shared".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: "use frame_box_for_transfer() for explicit cross-thread handoff".to_string(),
            replacement: None,
            applicability: Applicability::MaybeIncorrect,
        }),
        related: vec![],
    }
}

/// FA202: Frame barrier mismatch
pub fn fa202(location: Location) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA202"),
        severity: Severity::Warning,
        message: "thread not registered with FrameBarrier but shares frame boundary".to_string(),
        location,
        notes: vec![
            "threads sharing frame boundaries should be synchronized via FrameBarrier".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: "register thread with FrameBarrier or ensure proper synchronization".to_string(),
            replacement: None,
            applicability: Applicability::HasPlaceholders,
        }),
        related: vec![],
    }
}

/// FA203: Thread budget not configured
pub fn fa203(location: Location) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA203"),
        severity: Severity::Hint,
        message: "thread performs allocations without explicit budget configuration".to_string(),
        location,
        notes: vec![
            "explicit budgets help prevent unexpected memory growth".to_string(),
            "consider setting per-thread frame budgets".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: "configure thread budget with ThreadBudgetManager".to_string(),
            replacement: None,
            applicability: Applicability::Unspecified,
        }),
        related: vec![],
    }
}

/// FA204: Deferred queue overflow risk
pub fn fa204(location: Location, pattern: &str) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA204"),
        severity: Severity::Warning,
        message: "pattern may cause deferred free queue overflow".to_string(),
        location,
        notes: vec![
            format!("detected pattern: {}", pattern),
            "unbounded cross-thread frees can cause memory pressure".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: "configure bounded deferred queue with DeferredConfig::bounded()".to_string(),
            replacement: None,
            applicability: Applicability::HasPlaceholders,
        }),
        related: vec![],
    }
}

/// FA205: Frame sync race potential
pub fn fa205(location: Location, barrier_location: Option<Location>) -> Diagnostic {
    let mut diag = Diagnostic {
        code: DiagnosticCode::new("FA205"),
        severity: Severity::Error,
        message: "end_frame() called without barrier synchronization in multi-threaded context".to_string(),
        location,
        notes: vec![
            "concurrent end_frame() calls can cause undefined behavior".to_string(),
            "use FrameBarrier to synchronize frame boundaries".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: "coordinate frame boundaries with FrameBarrier::wait_all()".to_string(),
            replacement: None,
            applicability: Applicability::HasPlaceholders,
        }),
        related: vec![],
    };
    
    if let Some(barrier_loc) = barrier_location {
        diag.related.push(RelatedLocation {
            location: barrier_loc,
            message: "barrier defined here".to_string(),
        });
    }
    
    diag
}

// =============================================================================
// Predefined diagnostic codes (FA6xx - Lifetime/Escape)
// =============================================================================

/// FA601: Frame allocation escapes scope
pub fn fa601(location: Location, escaped_to: &str) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA601"),
        severity: Severity::Warning,
        message: "frame allocation may escape frame scope".to_string(),
        location,
        notes: vec![
            format!("allocation appears to be stored in: {}", escaped_to),
            "frame allocations are invalidated at end_frame()".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: "consider using pool_box() or heap_box() for data that outlives the frame".to_string(),
            replacement: None,
            applicability: Applicability::HasPlaceholders,
        }),
        related: vec![],
    }
}

/// FA602: Allocation in hot loop
pub fn fa602(location: Location, alloc_type: &str, loop_type: &str) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA602"),
        severity: Severity::Warning,
        message: format!("{} allocation inside {} loop", alloc_type, loop_type),
        location,
        notes: vec![
            "allocations in tight loops can cause performance issues".to_string(),
            "consider pre-allocating or using frame_vec()".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: "move allocation outside loop or use a pre-allocated buffer".to_string(),
            replacement: None,
            applicability: Applicability::HasPlaceholders,
        }),
        related: vec![],
    }
}

/// FA603: Missing frame boundaries
pub fn fa603(location: Location) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA603"),
        severity: Severity::Warning,
        message: "frame-structured loop without frame lifecycle calls".to_string(),
        location,
        notes: vec![
            "detected a main loop pattern without begin_frame()/end_frame()".to_string(),
            "frame allocations may accumulate indefinitely".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: "add alloc.begin_frame() at loop start and alloc.end_frame() at loop end".to_string(),
            replacement: None,
            applicability: Applicability::HasPlaceholders,
        }),
        related: vec![],
    }
}

/// FA604: Retention policy mismatch
pub fn fa604(location: Location, policy: &str, actual_usage: &str) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA604"),
        severity: Severity::Hint,
        message: format!("retention policy '{}' may not match usage pattern", policy),
        location,
        notes: vec![
            format!("observed usage: {}", actual_usage),
        ],
        suggestion: Some(Suggestion {
            message: "review retention policy choice".to_string(),
            replacement: None,
            applicability: Applicability::Unspecified,
        }),
        related: vec![],
    }
}

/// FA605: Discard policy but stored beyond frame
pub fn fa605(location: Location) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA605"),
        severity: Severity::Warning,
        message: "allocation with Discard policy stored beyond frame scope".to_string(),
        location,
        notes: vec![
            "RetentionPolicy::Discard means data is lost at frame end".to_string(),
            "but this allocation appears to be stored in a persistent structure".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: "use PromoteToPool or PromoteToHeap if data needs to persist".to_string(),
            replacement: None,
            applicability: Applicability::HasPlaceholders,
        }),
        related: vec![],
    }
}

// =============================================================================
// Predefined diagnostic codes (FA7xx - Async Safety)
// =============================================================================

/// FA701: Frame allocation in async function
pub fn fa701(location: Location) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA701"),
        severity: Severity::Error,
        message: "frame allocation in async function".to_string(),
        location,
        notes: vec![
            "async functions may suspend across frame boundaries".to_string(),
            "frame allocations become invalid after end_frame()".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: "use pool_box() or heap_box() for data in async contexts".to_string(),
            replacement: None,
            applicability: Applicability::MaybeIncorrect,
        }),
        related: vec![],
    }
}

/// FA702: Frame allocation crosses await point
pub fn fa702(location: Location, await_location: Location) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA702"),
        severity: Severity::Error,
        message: "frame allocation used across await point".to_string(),
        location,
        notes: vec![
            "the allocation is created before an await".to_string(),
            "and used after the await completes".to_string(),
            "frames may have been reset during the await".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: "complete frame work before awaiting, or use persistent allocation".to_string(),
            replacement: None,
            applicability: Applicability::HasPlaceholders,
        }),
        related: vec![RelatedLocation {
            location: await_location,
            message: "await point here".to_string(),
        }],
    }
}

/// FA703: FrameBox captured by closure/task
pub fn fa703(location: Location, capture_type: &str) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA703"),
        severity: Severity::Error,
        message: format!("FrameBox captured by {}", capture_type),
        location,
        notes: vec![
            format!("{} may outlive the current frame", capture_type),
            "FrameBox becomes invalid after end_frame()".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: "use PoolBox or HeapBox for data captured by closures/tasks".to_string(),
            replacement: None,
            applicability: Applicability::MaybeIncorrect,
        }),
        related: vec![],
    }
}

// =============================================================================
// Predefined diagnostic codes (FA8xx - Architecture)
// =============================================================================

/// FA801: Tag mismatch
pub fn fa801(location: Location, expected_tag: &str, actual_tag: &str, module: &str) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA801"),
        severity: Severity::Warning,
        message: format!("allocation tag '{}' unexpected in module '{}'", actual_tag, module),
        location,
        notes: vec![
            format!("expected tags for this module: {}", expected_tag),
            "tag mismatches may indicate architectural confusion".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: format!("use tag '{}' or move allocation to appropriate module", expected_tag),
            replacement: None,
            applicability: Applicability::HasPlaceholders,
        }),
        related: vec![],
    }
}

/// FA802: Unknown tag
pub fn fa802(location: Location, tag: &str) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA802"),
        severity: Severity::Hint,
        message: format!("unknown allocation tag '{}'", tag),
        location,
        notes: vec![
            "this tag is not in the known_tags list in .fa.toml".to_string(),
            "consider adding it or using an existing tag".to_string(),
        ],
        suggestion: None,
        related: vec![],
    }
}

/// FA803: Cross-module allocation
pub fn fa803(location: Location, from_module: &str, to_module: &str) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA803"),
        severity: Severity::Warning,
        message: format!("allocation intent crosses module boundary: {} -> {}", from_module, to_module),
        location,
        notes: vec![
            "allocations typically should stay within their module's concerns".to_string(),
        ],
        suggestion: None,
        related: vec![],
    }
}

// =============================================================================
// Predefined diagnostic codes (FA9xx - Rapier Integration)
// =============================================================================

/// FA901: QueryFilter imported from wrong module
pub fn fa901(location: Location) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA901"),
        severity: Severity::Warning,
        message: "QueryFilter should be imported from rapier::pipeline, not rapier::geometry".to_string(),
        location,
        notes: vec![
            "In Rapier 0.31, QueryFilter was moved from geometry to pipeline module".to_string(),
            "Using the old import will cause compilation errors".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: "change import to: use rapier2d::pipeline::QueryFilter".to_string(),
            replacement: Some("rapier::pipeline".to_string()),
            applicability: Applicability::MachineApplicable,
        }),
        related: vec![],
    }
}

/// FA902: BroadPhase renamed to BroadPhaseBvh
pub fn fa902(location: Location) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA902"),
        severity: Severity::Warning,
        message: "BroadPhase has been renamed to BroadPhaseBvh in Rapier 0.31".to_string(),
        location,
        notes: vec![
            "The broad phase implementation changed in Rapier 0.31".to_string(),
            "Update all references to use BroadPhaseBvh".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: "replace BroadPhase with BroadPhaseBvh".to_string(),
            replacement: Some("BroadPhaseBvh".to_string()),
            applicability: Applicability::MachineApplicable,
        }),
        related: vec![],
    }
}

/// FA903: Use step_with_events instead of step
pub fn fa903(location: Location) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA903"),
        severity: Severity::Hint,
        message: "Consider using step_with_events() instead of step() for frame-aware event collection".to_string(),
        location,
        notes: vec![
            "step_with_events() returns frame-allocated contact and proximity events".to_string(),
            "step() discards events and provides no frame allocation benefits".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: "use step_with_events(&alloc) to get frame-allocated events".to_string(),
            replacement: Some("step_with_events(&alloc)".to_string()),
            applicability: Applicability::HasPlaceholders,
        }),
        related: vec![],
    }
}

/// FA904: Ray casting without prior step
pub fn fa904(location: Location) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA904"),
        severity: Severity::Warning,
        message: "Ray casting may not work correctly without calling step() first to update the broad phase".to_string(),
        location,
        notes: vec![
            "The broad phase BVH must be updated after inserting colliders".to_string(),
            "Call step() once before ray casting to ensure colliders are registered".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: "call physics.step() before cast_ray()".to_string(),
            replacement: None,
            applicability: Applicability::HasPlaceholders,
        }),
        related: vec![],
    }
}

/// FA905: frame_alloc_slice replaced
pub fn fa905(location: Location) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA905"),
        severity: Severity::Warning,
        message: "frame_alloc_slice has been replaced with frame_alloc_batch + manual copying".to_string(),
        location,
        notes: vec![
            "frame_alloc_slice was removed in favor of more explicit batch allocation".to_string(),
            "Use frame_alloc_batch() and manually copy elements for better performance".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: "use frame_alloc_batch() + manual copying".to_string(),
            replacement: None,
            applicability: Applicability::HasPlaceholders,
        }),
        related: vec![],
    }
}

impl Diagnostic {
    /// Create a diagnostic builder
    pub fn builder(code: &str) -> DiagnosticBuilder {
        DiagnosticBuilder::new(code)
    }
}

/// Builder for constructing diagnostics
pub struct DiagnosticBuilder {
    code: DiagnosticCode,
    severity: Severity,
    message: Option<String>,
    location: Option<Location>,
    notes: Vec<String>,
    suggestion: Option<Suggestion>,
    related: Vec<RelatedLocation>,
}

impl DiagnosticBuilder {
    pub fn new(code: &str) -> Self {
        Self {
            code: DiagnosticCode::new(code),
            severity: Severity::Warning,
            message: None,
            location: None,
            notes: Vec::new(),
            suggestion: None,
            related: Vec::new(),
        }
    }
    
    pub fn severity(mut self, severity: Severity) -> Self {
        self.severity = severity;
        self
    }
    
    pub fn message(mut self, msg: impl Into<String>) -> Self {
        self.message = Some(msg.into());
        self
    }
    
    pub fn location(mut self, loc: Location) -> Self {
        self.location = Some(loc);
        self
    }
    
    pub fn note(mut self, note: impl Into<String>) -> Self {
        self.notes.push(note.into());
        self
    }
    
    pub fn suggestion(mut self, msg: impl Into<String>) -> Self {
        self.suggestion = Some(Suggestion {
            message: msg.into(),
            replacement: None,
            applicability: Applicability::Unspecified,
        });
        self
    }
    
    pub fn build(self) -> Diagnostic {
        Diagnostic {
            code: self.code,
            severity: self.severity,
            message: self.message.unwrap_or_default(),
            location: self.location.unwrap_or(Location {
                file: PathBuf::new(),
                line: 0,
                column: 0,
                end_line: None,
                end_column: None,
            }),
            notes: self.notes,
            suggestion: self.suggestion,
            related: self.related,
        }
    }
}

// =============================================================================
// Predefined diagnostic codes (FA8xx - GPU Memory Safety) - v0.11.0
// =============================================================================

/// FA804: Device-local buffer mapped for CPU access
pub fn fa804(location: Location) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA804"),
        severity: Severity::Error,
        message: "device-local buffer mapped for CPU access".to_string(),
        location,
        notes: vec![
            "device-local memory cannot be mapped for CPU access".to_string(),
            "attempting to map device-local memory will fail at runtime".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: "use MemoryType::HostVisible or MemoryType::HostCoherent for mapped buffers".to_string(),
            replacement: None,
            applicability: Applicability::MaybeIncorrect,
        }),
        related: vec![],
    }
}

/// FA805: Staging buffer reused across frames without reset
pub fn fa805(location: Location) -> Diagnostic {
    Diagnostic {
        code: DiagnosticCode::new("FA805"),
        severity: Severity::Warning,
        message: "staging buffer reused across frames without reset".to_string(),
        location,
        notes: vec![
            "reusing staging buffers across frames can lead to data corruption".to_string(),
            "staging buffers should be created fresh each frame or properly reset".to_string(),
        ],
        suggestion: Some(Suggestion {
            message: "create new staging buffers each frame or properly reset them with begin_frame()".to_string(),
            replacement: None,
            applicability: Applicability::MaybeIncorrect,
        }),
        related: vec![],
    }
}