ryo-analysis 0.1.0

Code graph and discovery engine for the RYO project
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
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
//! BorrowTrackerV2 - VarId-based borrow tracking for DataFlowGraphV2.
//!
//! Key improvements over V1:
//! - Uses VarId instead of petgraph::NodeIndex
//! - Integrates seamlessly with DataFlowGraphV2
//! - Same borrow conflict detection semantics

use super::var_id::VarId;
use smallvec::SmallVec;
use std::collections::HashMap;
use std::fmt;

// ============================================================================
// Borrow Kind (shared vocabulary)
// ============================================================================

/// Kind of borrow.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BorrowKind {
    /// Shared/immutable borrow (&T).
    Shared,
    /// Mutable borrow (&mut T).
    Mutable,
}

impl BorrowKind {
    /// Check if this borrow conflicts with another.
    ///
    /// Mutable borrows conflict with everything.
    /// Shared borrows only conflict with mutable borrows.
    pub fn conflicts_with(&self, other: BorrowKind) -> bool {
        matches!(
            (self, other),
            (BorrowKind::Mutable, _) | (_, BorrowKind::Mutable)
        )
    }
}

// ============================================================================
// Borrow State V2
// ============================================================================

/// The ownership/borrow state of a variable (V2 - uses VarId).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum BorrowStateV2 {
    /// Variable owns its value (T).
    #[default]
    Owned,

    /// Variable is a shared reference (&T).
    SharedRef {
        /// The variable being borrowed from.
        source: VarId,
        /// Line where the borrow started.
        start_line: u32,
    },

    /// Variable is a mutable reference (&mut T).
    MutRef {
        /// The variable being borrowed from.
        source: VarId,
        /// Line where the borrow started.
        start_line: u32,
    },

    /// Ownership has been moved to another variable.
    Moved {
        /// The variable that now owns the value.
        to: VarId,
        /// Line where the move occurred.
        at_line: u32,
    },

    /// Variable has been dropped (out of scope).
    Dropped {
        /// Line where the drop occurred.
        at_line: u32,
    },

    /// Copy semantics - value was copied, original still valid.
    Copied {
        /// The variable that received the copy.
        to: VarId,
        /// Line where the copy occurred.
        at_line: u32,
    },
}

impl BorrowStateV2 {
    /// Check if the variable can be used (read).
    pub fn can_read(&self) -> bool {
        matches!(
            self,
            BorrowStateV2::Owned
                | BorrowStateV2::SharedRef { .. }
                | BorrowStateV2::MutRef { .. }
                | BorrowStateV2::Copied { .. }
        )
    }

    /// Check if the variable can be mutated.
    pub fn can_mutate(&self) -> bool {
        matches!(self, BorrowStateV2::Owned | BorrowStateV2::MutRef { .. })
    }

    /// Check if the variable has been invalidated (moved or dropped).
    pub fn is_invalidated(&self) -> bool {
        matches!(
            self,
            BorrowStateV2::Moved { .. } | BorrowStateV2::Dropped { .. }
        )
    }

    /// Check if this is a reference (shared or mutable).
    pub fn is_reference(&self) -> bool {
        matches!(
            self,
            BorrowStateV2::SharedRef { .. } | BorrowStateV2::MutRef { .. }
        )
    }

    /// Get the source variable if this is a reference.
    pub fn borrow_source(&self) -> Option<VarId> {
        match self {
            BorrowStateV2::SharedRef { source, .. } | BorrowStateV2::MutRef { source, .. } => {
                Some(*source)
            }
            _ => None,
        }
    }
}

// ============================================================================
// Active Borrow V2
// ============================================================================

/// Represents an active borrow of a variable (V2 - uses VarId).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActiveBorrowV2 {
    /// The variable that holds the borrow (the reference variable).
    pub borrower: VarId,
    /// The kind of borrow.
    pub kind: BorrowKind,
    /// Line where the borrow started.
    pub start_line: u32,
    /// Line where the borrow ended (None = still active).
    pub end_line: Option<u32>,
}

impl ActiveBorrowV2 {
    /// Create a new active borrow.
    pub fn new(borrower: VarId, kind: BorrowKind, start_line: u32) -> Self {
        Self {
            borrower,
            kind,
            start_line,
            end_line: None,
        }
    }

    /// Check if this borrow is still active at the given line.
    pub fn is_active_at(&self, line: u32) -> bool {
        line >= self.start_line && self.end_line.is_none_or(|end| line < end)
    }

    /// End this borrow at the given line.
    pub fn end_at(&mut self, line: u32) {
        self.end_line = Some(line);
    }

    /// Check if this borrow conflicts with a new borrow.
    pub fn conflicts_with(&self, new_kind: BorrowKind, at_line: u32) -> bool {
        self.is_active_at(at_line) && self.kind.conflicts_with(new_kind)
    }
}

// ============================================================================
// Borrow Conflict
// ============================================================================

/// A detected borrow conflict.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BorrowConflict {
    /// The variable being borrowed.
    pub variable: VarId,
    /// The existing borrow that conflicts.
    pub existing: ActiveBorrowV2,
    /// The new borrow kind that was attempted.
    pub new_kind: BorrowKind,
    /// Line where the new borrow was attempted.
    pub new_line: u32,
}

impl BorrowConflict {
    /// Create a new borrow conflict.
    pub fn new(
        variable: VarId,
        existing: ActiveBorrowV2,
        new_kind: BorrowKind,
        new_line: u32,
    ) -> Self {
        Self {
            variable,
            existing,
            new_kind,
            new_line,
        }
    }
}

impl fmt::Display for BorrowConflict {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let existing_kind = match self.existing.kind {
            BorrowKind::Shared => "shared",
            BorrowKind::Mutable => "mutable",
        };
        let new_kind = match self.new_kind {
            BorrowKind::Shared => "shared",
            BorrowKind::Mutable => "mutable",
        };

        if self.existing.kind == BorrowKind::Mutable && self.new_kind == BorrowKind::Mutable {
            write!(
                f,
                "cannot borrow as mutable more than once: \
                 first borrow at line {}, second borrow at line {}",
                self.existing.start_line, self.new_line
            )
        } else {
            write!(
                f,
                "cannot borrow as {} because already borrowed as {}: \
                 existing borrow at line {}, new borrow at line {}",
                new_kind, existing_kind, self.existing.start_line, self.new_line
            )
        }
    }
}

// ============================================================================
// Move Error
// ============================================================================

/// A use-after-move error.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MoveError {
    /// The variable that was moved.
    pub variable: VarId,
    /// Line where the move occurred.
    pub moved_at: u32,
    /// Line where the invalid use occurred.
    pub used_at: u32,
}

impl fmt::Display for MoveError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "use of moved value: moved at line {}, used at line {}",
            self.moved_at, self.used_at
        )
    }
}

// ============================================================================
// Borrow Analysis Result
// ============================================================================

/// Result of borrow analysis for a symbol.
#[derive(Debug, Clone)]
pub struct BorrowAnalysis {
    /// Borrow conflicts found.
    pub conflicts: Vec<BorrowConflict>,
    /// Use-after-move errors found.
    pub move_errors: Vec<MoveError>,
}

impl BorrowAnalysis {
    /// Check if there are any issues.
    pub fn has_issues(&self) -> bool {
        !self.conflicts.is_empty() || !self.move_errors.is_empty()
    }

    /// Get total issue count.
    pub fn issue_count(&self) -> usize {
        self.conflicts.len() + self.move_errors.len()
    }
}

// ============================================================================
// Borrow Tracker V2
// ============================================================================

/// Tracks active borrows for a set of variables (V2 - uses VarId).
///
/// Integrates with DataFlowGraphV2 for borrow conflict detection.
#[derive(Debug, Clone, Default)]
pub struct BorrowTrackerV2 {
    /// Active borrows indexed by the borrowed variable.
    /// Uses SmallVec since most variables have 0-2 borrows.
    borrows: HashMap<VarId, SmallVec<[ActiveBorrowV2; 2]>>,
}

impl BorrowTrackerV2 {
    /// Create a new empty tracker.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create with pre-allocated capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            borrows: HashMap::with_capacity(capacity),
        }
    }

    /// Add a borrow.
    ///
    /// Returns any conflicts with existing borrows.
    pub fn add_borrow(
        &mut self,
        source: VarId,
        borrower: VarId,
        kind: BorrowKind,
        line: u32,
    ) -> Vec<BorrowConflict> {
        let conflicts = self.conflicts(source, kind, line);

        self.borrows
            .entry(source)
            .or_default()
            .push(ActiveBorrowV2::new(borrower, kind, line));

        conflicts
    }

    /// End a borrow.
    pub fn end_borrow(&mut self, borrower: VarId, line: u32) {
        for borrows in self.borrows.values_mut() {
            for borrow in borrows.iter_mut() {
                if borrow.borrower == borrower && borrow.end_line.is_none() {
                    borrow.end_at(line);
                }
            }
        }
    }

    /// Query conflicts with a potential new borrow.
    pub fn conflicts(&self, source: VarId, kind: BorrowKind, at_line: u32) -> Vec<BorrowConflict> {
        self.borrows
            .get(&source)
            .map(|borrows| {
                borrows
                    .iter()
                    .filter(|b| b.conflicts_with(kind, at_line))
                    .map(|b| BorrowConflict::new(source, b.clone(), kind, at_line))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Get all active borrows of a variable at a given line.
    pub fn active_borrows_at(&self, source: VarId, line: u32) -> Vec<&ActiveBorrowV2> {
        self.borrows
            .get(&source)
            .map(|borrows| borrows.iter().filter(|b| b.is_active_at(line)).collect())
            .unwrap_or_default()
    }

    /// Get all active borrows of a variable (regardless of line).
    pub fn active_borrows(&self, source: VarId) -> &[ActiveBorrowV2] {
        self.borrows
            .get(&source)
            .map(|v| v.as_slice())
            .unwrap_or(&[])
    }

    /// Clear all borrows.
    pub fn clear(&mut self) {
        self.borrows.clear();
    }

    /// Check if any borrows are currently active for a variable.
    pub fn has_active_borrows(&self, source: VarId, at_line: u32) -> bool {
        self.borrows
            .get(&source)
            .map(|borrows| borrows.iter().any(|b| b.is_active_at(at_line)))
            .unwrap_or(false)
    }

    /// Check if a mutable borrow is active for a variable.
    pub fn has_active_mut_borrow(&self, source: VarId, at_line: u32) -> bool {
        self.borrows
            .get(&source)
            .map(|borrows| {
                borrows
                    .iter()
                    .any(|b| b.is_active_at(at_line) && b.kind == BorrowKind::Mutable)
            })
            .unwrap_or(false)
    }

    /// Get the number of tracked variables.
    pub fn tracked_var_count(&self) -> usize {
        self.borrows.len()
    }

    /// Get the total number of borrows (active and ended).
    pub fn total_borrow_count(&self) -> usize {
        self.borrows.values().map(|v| v.len()).sum()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::symbol::SymbolId;
    use slotmap::SlotMap;

    /// Test helper to create VarIds from a shared mapping.
    struct TestVars {
        symbols: SlotMap<SymbolId, &'static str>,
        mapping: super::super::var_id::VarSymbolMapping,
    }

    impl TestVars {
        fn new() -> Self {
            Self {
                symbols: SlotMap::with_key(),
                mapping: super::super::var_id::VarSymbolMapping::new(),
            }
        }

        fn var(&mut self, name: &'static str) -> VarId {
            let sym = self.symbols.insert(name);
            self.mapping.register(sym)
        }
    }

    #[test]
    fn test_borrow_state_can_read() {
        let mut vars = TestVars::new();
        let v = vars.var("v");

        assert!(BorrowStateV2::Owned.can_read());
        assert!(BorrowStateV2::SharedRef {
            source: v,
            start_line: 1
        }
        .can_read());
        assert!(BorrowStateV2::MutRef {
            source: v,
            start_line: 1
        }
        .can_read());
        assert!(!BorrowStateV2::Moved { to: v, at_line: 1 }.can_read());
        assert!(!BorrowStateV2::Dropped { at_line: 1 }.can_read());
    }

    #[test]
    fn test_borrow_state_can_mutate() {
        let mut vars = TestVars::new();
        let v = vars.var("v");

        assert!(BorrowStateV2::Owned.can_mutate());
        assert!(BorrowStateV2::MutRef {
            source: v,
            start_line: 1
        }
        .can_mutate());
        assert!(!BorrowStateV2::SharedRef {
            source: v,
            start_line: 1
        }
        .can_mutate());
        assert!(!BorrowStateV2::Moved { to: v, at_line: 1 }.can_mutate());
    }

    #[test]
    fn test_active_borrow_is_active_at() {
        let mut vars = TestVars::new();
        let borrower = vars.var("borrower");
        let mut borrow = ActiveBorrowV2::new(borrower, BorrowKind::Shared, 10);

        assert!(borrow.is_active_at(10));
        assert!(borrow.is_active_at(15));
        assert!(borrow.is_active_at(100));
        assert!(!borrow.is_active_at(5));

        borrow.end_at(20);
        assert!(borrow.is_active_at(10));
        assert!(borrow.is_active_at(15));
        assert!(!borrow.is_active_at(20));
        assert!(!borrow.is_active_at(25));
    }

    #[test]
    fn test_borrow_tracker_no_conflict_shared() {
        let mut tracker = BorrowTrackerV2::new();
        let mut vars = TestVars::new();
        let source = vars.var("source");
        let b1 = vars.var("b1");
        let b2 = vars.var("b2");

        // Multiple shared borrows should not conflict
        let conflicts = tracker.add_borrow(source, b1, BorrowKind::Shared, 10);
        assert!(conflicts.is_empty());

        let conflicts = tracker.add_borrow(source, b2, BorrowKind::Shared, 15);
        assert!(conflicts.is_empty());
    }

    #[test]
    fn test_borrow_tracker_conflict_mut_mut() {
        let mut tracker = BorrowTrackerV2::new();
        let mut vars = TestVars::new();
        let source = vars.var("source");
        let b1 = vars.var("b1");
        let b2 = vars.var("b2");

        let conflicts = tracker.add_borrow(source, b1, BorrowKind::Mutable, 10);
        assert!(conflicts.is_empty());

        // Second mutable borrow should conflict
        let conflicts = tracker.add_borrow(source, b2, BorrowKind::Mutable, 15);
        assert_eq!(conflicts.len(), 1);
        assert_eq!(conflicts[0].existing.borrower, b1);
        assert_eq!(conflicts[0].new_kind, BorrowKind::Mutable);
    }

    #[test]
    fn test_borrow_tracker_conflict_shared_then_mut() {
        let mut tracker = BorrowTrackerV2::new();
        let mut vars = TestVars::new();
        let source = vars.var("source");
        let b1 = vars.var("b1");
        let b2 = vars.var("b2");

        let conflicts = tracker.add_borrow(source, b1, BorrowKind::Shared, 10);
        assert!(conflicts.is_empty());

        // Mutable borrow while shared borrow is active should conflict
        let conflicts = tracker.add_borrow(source, b2, BorrowKind::Mutable, 15);
        assert_eq!(conflicts.len(), 1);
    }

    #[test]
    fn test_borrow_tracker_end_borrow() {
        let mut tracker = BorrowTrackerV2::new();
        let mut vars = TestVars::new();
        let source = vars.var("source");
        let borrower = vars.var("borrower");
        let b2 = vars.var("b2");

        tracker.add_borrow(source, borrower, BorrowKind::Mutable, 10);
        tracker.end_borrow(borrower, 20);

        // After ending the borrow, new mutable borrow should not conflict
        let conflicts = tracker.add_borrow(source, b2, BorrowKind::Mutable, 25);
        assert!(conflicts.is_empty());
    }

    #[test]
    fn test_borrow_tracker_has_active_borrows() {
        let mut tracker = BorrowTrackerV2::new();
        let mut vars = TestVars::new();
        let source = vars.var("source");
        let borrower = vars.var("borrower");

        assert!(!tracker.has_active_borrows(source, 10));

        tracker.add_borrow(source, borrower, BorrowKind::Shared, 10);
        assert!(tracker.has_active_borrows(source, 15));

        tracker.end_borrow(borrower, 20);
        assert!(!tracker.has_active_borrows(source, 25));
    }

    #[test]
    fn test_borrow_tracker_stats() {
        let mut tracker = BorrowTrackerV2::new();
        let mut vars = TestVars::new();
        let s1 = vars.var("s1");
        let s2 = vars.var("s2");
        let b1 = vars.var("b1");
        let b2 = vars.var("b2");
        let b3 = vars.var("b3");

        tracker.add_borrow(s1, b1, BorrowKind::Shared, 10);
        tracker.add_borrow(s1, b2, BorrowKind::Shared, 15);
        tracker.add_borrow(s2, b3, BorrowKind::Mutable, 20);

        assert_eq!(tracker.tracked_var_count(), 2);
        assert_eq!(tracker.total_borrow_count(), 3);
    }
}