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
//! Registry update operations for delta-based mutation execution.
//!
//! # Overview
//!
//! During parallel Mutation execution, SymbolRegistry changes are managed as deltas.
//! Each Mutation shares Registry as read-only and returns changes as `RegistryUpdate`.
//! All deltas are applied at Tick end.
//!
//! # Design
//!
//! ```text
//! 1 Tick flow:
//! ┌─────────────────────────────────────────────────────┐
//! │  Mutation A (modify X)  ──┐                         │
//! │  Mutation B (modify Y)  ──┼─→ Collect deltas → Apply to Registry
//! │  Mutation C (modify Z)  ──┘                         │
//! └─────────────────────────────────────────────────────┘
//! ```
//!
//! See `docs/parallel-execution-design.md` for full design details.

use super::{
    FileSpan, InvalidSymbolId, RegistrationError, RenameError, SymbolId, SymbolKind, SymbolPath,
    SymbolRegistry, Visibility,
};
use serde::Serialize;

/// Registry change request (delta).
///
/// Represents a single atomic change to the SymbolRegistry.
/// Collected during Mutation execution and applied at Tick end.
///
/// NOTE: Deserialize is NOT derived because FileSpan contains WorkspaceFilePath
/// which requires context during deserialization.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub enum RegistryUpdate {
    /// Add a new symbol.
    Add {
        /// Canonical SymbolPath of the new symbol.
        path: SymbolPath,
        /// Kind classification (struct / fn / trait / ...).
        kind: SymbolKind,
        /// Source-file span where the symbol is declared.
        span: FileSpan,
    },

    /// Remove an existing symbol.
    Remove {
        /// Target symbol to remove.
        id: SymbolId,
    },

    /// Rename a symbol (change its path).
    Rename {
        /// Target symbol to rename.
        id: SymbolId,
        /// New canonical SymbolPath to assign.
        new_path: SymbolPath,
    },

    /// Update symbol's file span (position changed).
    UpdateSpan {
        /// Target symbol whose span is being updated.
        id: SymbolId,
        /// Replacement file span.
        new_span: FileSpan,
    },

    /// Update symbol's visibility.
    UpdateVisibility {
        /// Target symbol whose visibility is being updated.
        id: SymbolId,
        /// Replacement visibility value.
        new_visibility: Visibility,
    },

    /// Update symbol's kind.
    UpdateKind {
        /// Target symbol whose kind is being updated.
        id: SymbolId,
        /// Replacement kind classification.
        new_kind: SymbolKind,
    },
}

impl RegistryUpdate {
    /// Get the target SymbolId if this update modifies an existing symbol.
    ///
    /// Returns `None` for `Add` operations (no existing symbol).
    pub fn target_id(&self) -> Option<SymbolId> {
        match self {
            RegistryUpdate::Add { .. } => None,
            RegistryUpdate::Remove { id }
            | RegistryUpdate::Rename { id, .. }
            | RegistryUpdate::UpdateSpan { id, .. }
            | RegistryUpdate::UpdateVisibility { id, .. }
            | RegistryUpdate::UpdateKind { id, .. } => Some(*id),
        }
    }

    /// Check if this update is a destructive operation.
    ///
    /// Destructive operations (Remove, Rename) require special handling
    /// for conflict detection.
    pub fn is_destructive(&self) -> bool {
        matches!(
            self,
            RegistryUpdate::Remove { .. } | RegistryUpdate::Rename { .. }
        )
    }
}

/// Batch of registry updates from a single Mutation.
#[derive(Debug, Clone, Default)]
pub struct RegistryUpdateBatch {
    updates: Vec<RegistryUpdate>,
}

impl RegistryUpdateBatch {
    /// Create an empty batch.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a batch with pre-allocated capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            updates: Vec::with_capacity(capacity),
        }
    }

    /// Add an update to the batch.
    pub fn push(&mut self, update: RegistryUpdate) {
        self.updates.push(update);
    }

    /// Add a symbol addition.
    pub fn add_symbol(&mut self, path: SymbolPath, kind: SymbolKind, span: FileSpan) {
        self.push(RegistryUpdate::Add { path, kind, span });
    }

    /// Add a symbol removal.
    pub fn remove_symbol(&mut self, id: SymbolId) {
        self.push(RegistryUpdate::Remove { id });
    }

    /// Add a symbol rename.
    pub fn rename_symbol(&mut self, id: SymbolId, new_path: SymbolPath) {
        self.push(RegistryUpdate::Rename { id, new_path });
    }

    /// Add a span update.
    pub fn update_span(&mut self, id: SymbolId, new_span: FileSpan) {
        self.push(RegistryUpdate::UpdateSpan { id, new_span });
    }

    /// Get the updates.
    pub fn updates(&self) -> &[RegistryUpdate] {
        &self.updates
    }

    /// Consume and return the updates.
    pub fn into_updates(self) -> Vec<RegistryUpdate> {
        self.updates
    }

    /// Check if the batch is empty.
    pub fn is_empty(&self) -> bool {
        self.updates.is_empty()
    }

    /// Get the number of updates.
    pub fn len(&self) -> usize {
        self.updates.len()
    }

    /// Apply all updates to the registry.
    ///
    /// Updates are applied in order. If any update fails, the operation
    /// stops and returns the error. Previously applied updates are NOT
    /// rolled back (partial application).
    ///
    /// # Returns
    /// - `Ok(applied_count)`: Number of successfully applied updates
    /// - `Err(ApplyError)`: First error encountered
    pub fn apply(self, registry: &mut SymbolRegistry) -> Result<usize, ApplyError> {
        let mut applied = 0;

        for update in self.updates {
            update.apply(registry)?;
            applied += 1;
        }

        Ok(applied)
    }
}

/// Error during registry update application.
#[derive(Debug, thiserror::Error)]
pub enum ApplyError {
    /// Symbol registration failed.
    #[error("registration failed: {0}")]
    Registration(#[from] RegistrationError),

    /// Invalid symbol ID.
    #[error("invalid symbol id: {0}")]
    InvalidId(#[from] InvalidSymbolId),

    /// Rename failed.
    #[error("rename failed: {0}")]
    Rename(#[from] RenameError),
}

impl RegistryUpdate {
    /// Apply this update to the registry.
    pub fn apply(self, registry: &mut SymbolRegistry) -> Result<(), ApplyError> {
        match self {
            RegistryUpdate::Add { path, kind, span } => {
                let id = registry.register(path, kind)?;
                registry.set_span(id, span)?;
            }
            RegistryUpdate::Remove { id } => {
                // remove() returns None if not found, but we treat it as success
                // (idempotent deletion)
                let _ = registry.remove(id);
            }
            RegistryUpdate::Rename { id, new_path } => {
                registry.rename(id, new_path)?;
            }
            RegistryUpdate::UpdateSpan { id, new_span } => {
                registry.set_span(id, new_span)?;
            }
            RegistryUpdate::UpdateVisibility { id, new_visibility } => {
                registry.set_visibility(id, new_visibility)?;
            }
            RegistryUpdate::UpdateKind { id, new_kind } => {
                registry.set_kind(id, new_kind)?;
            }
        }
        Ok(())
    }
}

impl IntoIterator for RegistryUpdateBatch {
    type Item = RegistryUpdate;
    type IntoIter = std::vec::IntoIter<RegistryUpdate>;

    fn into_iter(self) -> Self::IntoIter {
        self.updates.into_iter()
    }
}

impl<'a> IntoIterator for &'a RegistryUpdateBatch {
    type Item = &'a RegistryUpdate;
    type IntoIter = std::slice::Iter<'a, RegistryUpdate>;

    fn into_iter(self) -> Self::IntoIter {
        self.updates.iter()
    }
}

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

    /// Create a test FileSpan.
    fn test_span() -> FileSpan {
        FileSpan::new(
            WorkspaceFilePath::new_for_test("test/file.rs", "/", "test"),
            0,
            10,
        )
    }

    #[test]
    fn test_target_id() {
        use slotmap::KeyData;

        let id = SymbolId::from(KeyData::from_ffi(1));
        let path = SymbolPath::parse("foo::bar").unwrap();

        // Add has no target
        let add = RegistryUpdate::Add {
            path: path.clone(),
            kind: SymbolKind::Function,
            span: test_span(),
        };
        assert!(add.target_id().is_none());

        // Remove has target
        let remove = RegistryUpdate::Remove { id };
        assert_eq!(remove.target_id(), Some(id));

        // Rename has target
        let rename = RegistryUpdate::Rename { id, new_path: path };
        assert_eq!(rename.target_id(), Some(id));
    }

    #[test]
    fn test_is_destructive() {
        use slotmap::KeyData;

        let id = SymbolId::from(KeyData::from_ffi(1));
        let path = SymbolPath::parse("foo::bar").unwrap();

        assert!(!RegistryUpdate::Add {
            path: path.clone(),
            kind: SymbolKind::Function,
            span: test_span(),
        }
        .is_destructive());

        assert!(RegistryUpdate::Remove { id }.is_destructive());
        assert!(RegistryUpdate::Rename { id, new_path: path }.is_destructive());

        assert!(!RegistryUpdate::UpdateSpan {
            id,
            new_span: test_span()
        }
        .is_destructive());
    }

    #[test]
    fn test_batch_builder() {
        use slotmap::KeyData;

        let id = SymbolId::from(KeyData::from_ffi(1));
        let path = SymbolPath::parse("foo::bar").unwrap();

        let mut batch = RegistryUpdateBatch::new();
        assert!(batch.is_empty());

        batch.add_symbol(path.clone(), SymbolKind::Function, test_span());
        batch.remove_symbol(id);

        assert_eq!(batch.len(), 2);
        assert!(!batch.is_empty());
    }

    #[test]
    fn test_batch_apply_add() {
        let mut registry = SymbolRegistry::new();
        let path = SymbolPath::parse("test::NewSymbol").unwrap();

        let mut batch = RegistryUpdateBatch::new();
        batch.add_symbol(path.clone(), SymbolKind::Function, test_span());

        let applied = batch.apply(&mut registry).unwrap();
        assert_eq!(applied, 1);

        // Verify symbol was added
        let id = registry.lookup(&path).expect("symbol should exist");
        assert_eq!(registry.kind(id), Some(SymbolKind::Function));
        assert!(registry.span(id).is_some());
    }

    #[test]
    fn test_batch_apply_remove() {
        let mut registry = SymbolRegistry::new();
        let path = SymbolPath::parse("test::ToRemove").unwrap();
        let id = registry.register(path.clone(), SymbolKind::Struct).unwrap();

        let mut batch = RegistryUpdateBatch::new();
        batch.remove_symbol(id);

        let applied = batch.apply(&mut registry).unwrap();
        assert_eq!(applied, 1);

        // Verify symbol was removed
        assert!(registry.lookup(&path).is_none());
        assert!(!registry.contains(id));
    }

    #[test]
    fn test_batch_apply_rename() {
        let mut registry = SymbolRegistry::new();
        let old_path = SymbolPath::parse("test::OldName").unwrap();
        let new_path = SymbolPath::parse("test::NewName").unwrap();
        let id = registry
            .register(old_path.clone(), SymbolKind::Struct)
            .unwrap();

        let mut batch = RegistryUpdateBatch::new();
        batch.rename_symbol(id, new_path.clone());

        let applied = batch.apply(&mut registry).unwrap();
        assert_eq!(applied, 1);

        // Verify rename
        assert!(registry.lookup(&old_path).is_none());
        assert_eq!(registry.lookup(&new_path), Some(id));
    }

    #[test]
    fn test_batch_apply_multiple() {
        use super::Visibility;

        let mut registry = SymbolRegistry::new();
        let path1 = SymbolPath::parse("test::First").unwrap();
        let path2 = SymbolPath::parse("test::Second").unwrap();

        let id1 = registry
            .register(path1.clone(), SymbolKind::Struct)
            .unwrap();

        let mut batch = RegistryUpdateBatch::new();
        batch.add_symbol(path2.clone(), SymbolKind::Function, test_span());
        batch.push(RegistryUpdate::UpdateVisibility {
            id: id1,
            new_visibility: Visibility::Public,
        });

        let applied = batch.apply(&mut registry).unwrap();
        assert_eq!(applied, 2);

        // Verify both operations
        assert!(registry.lookup(&path2).is_some());
        assert_eq!(registry.visibility(id1), Some(&Visibility::Public));
    }

    #[test]
    fn test_batch_apply_empty() {
        let mut registry = SymbolRegistry::new();
        let batch = RegistryUpdateBatch::new();

        let applied = batch.apply(&mut registry).unwrap();
        assert_eq!(applied, 0);
    }
}