ryo-symbol 0.1.0

Symbol system for Rust codebase - unique identifiers and file path management
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
//! Self-contained workspace file path

use std::ffi::OsStr;
use std::hash::{Hash, Hasher};
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use serde::de::{DeserializeSeed, Deserializer, MapAccess, Visitor};
use serde::ser::{Serialize, SerializeStruct, Serializer};

use crate::crate_name::CrateName;

/// Normalized relative path from workspace root (self-contained)
///
/// # Design
///
/// This type holds the relative path, workspace root, and crate name, making it
/// completely self-contained. You can get the absolute path and derive symbol
/// paths without any external context or provider.
///
/// - `relative`: Path from workspace_root (used for Hash/Eq/Serialize)
/// - `workspace_root`: Shared workspace root (Arc for lightweight sharing)
/// - `crate_name`: The crate this file belongs to (required)
///
/// # Creation
///
/// **Always create via `WorkspacePathResolver`**. Direct construction
/// with `new_unchecked()` is for internal/test use only.
///
/// ```ignore
/// let resolver = WorkspacePathResolver::new("/path/to/workspace".into());
/// let path = resolver.resolve("src/lib.rs")?;
/// ```
#[derive(Debug, Clone)]
pub struct WorkspaceFilePath {
    relative: PathBuf,
    workspace_root: Arc<Path>,
    crate_name: CrateName,
}

impl WorkspaceFilePath {
    /// Internal constructor (for normalized paths only)
    pub(crate) fn new_unchecked(
        relative: PathBuf,
        workspace_root: Arc<Path>,
        crate_name: CrateName,
    ) -> Self {
        Self {
            relative,
            workspace_root,
            crate_name,
        }
    }

    /// Test utility constructor (available with test-utils feature)
    #[cfg(any(test, feature = "test-utils"))]
    pub fn new_for_test(
        relative: impl Into<PathBuf>,
        workspace_root: impl Into<PathBuf>,
        crate_name: impl AsRef<str>,
    ) -> Self {
        Self {
            relative: relative.into(),
            workspace_root: Arc::from(workspace_root.into()),
            crate_name: CrateName::new_for_test(crate_name.as_ref()),
        }
    }

    /// Get the relative path
    pub fn as_relative(&self) -> &Path {
        &self.relative
    }

    /// Get the workspace root
    pub fn workspace_root(&self) -> &Path {
        &self.workspace_root
    }

    /// Get the crate name
    pub fn crate_name(&self) -> &CrateName {
        &self.crate_name
    }

    /// Get absolute path (no I/O, self-contained)
    pub fn to_absolute(&self) -> PathBuf {
        self.workspace_root.join(&self.relative)
    }

    /// Get canonicalized absolute path (with I/O)
    pub fn canonicalize(&self) -> io::Result<PathBuf> {
        std::fs::canonicalize(self.to_absolute())
    }

    /// Get the file name
    pub fn file_name(&self) -> Option<&OsStr> {
        self.relative.file_name()
    }

    /// Get the file extension
    pub fn extension(&self) -> Option<&OsStr> {
        self.relative.extension()
    }

    /// Get the parent directory
    pub fn parent(&self) -> Option<&Path> {
        self.relative.parent()
    }

    /// Check if this is a Rust source file
    pub fn is_rust_file(&self) -> bool {
        self.extension().is_some_and(|ext| ext == "rs")
    }

    /// Check if this is a binary entry point (main.rs or src/bin/*.rs)
    ///
    /// Binary entry points are handled separately from library code because:
    /// - `main.rs` and `lib.rs` both map to the crate root in module path terms
    /// - They represent different logical crates (binary vs library)
    /// - Storing them together causes data overwrite issues
    ///
    /// # Returns
    /// `true` if this file is:
    /// - `src/main.rs` or `*/src/main.rs`
    /// - `src/bin/*.rs` or `*/src/bin/*.rs`
    pub fn is_binary_entry(&self) -> bool {
        let path_str = self.relative.to_string_lossy();

        // Check for main.rs
        if path_str.ends_with("/main.rs") || path_str == "main.rs" {
            return true;
        }

        // Check for src/bin/*.rs pattern
        if path_str.contains("/bin/") && path_str.ends_with(".rs") {
            return true;
        }

        false
    }

    /// Create a new WorkspaceFilePath with different context
    ///
    /// This is useful after deserialization when both workspace_root and crate_name
    /// need to be set or updated.
    pub fn with_context(&self, workspace_root: Arc<Path>, crate_name: CrateName) -> Self {
        Self {
            relative: self.relative.clone(),
            workspace_root,
            crate_name,
        }
    }

    /// Create a new WorkspaceFilePath with different relative path
    ///
    /// This is useful for creating sibling files (e.g., creating `src/storage.rs`
    /// when you have `src/lib.rs`). The workspace_root and crate_name are inherited
    /// from the original path.
    ///
    /// # Example
    /// ```ignore
    /// let lib_rs = resolver.resolve("src/lib.rs")?;
    /// let storage_rs = lib_rs.with_relative("src/storage.rs");
    /// ```
    pub fn with_relative(&self, relative: impl Into<PathBuf>) -> Self {
        Self {
            relative: relative.into(),
            workspace_root: self.workspace_root.clone(),
            crate_name: self.crate_name.clone(),
        }
    }

    /// Create a sibling file in the same directory
    ///
    /// This is useful for creating module files (e.g., creating `src/storage.rs`
    /// when you have `src/lib.rs`).
    ///
    /// # Example
    /// ```ignore
    /// let lib_rs = resolver.resolve("src/lib.rs")?;
    /// let storage_rs = lib_rs.sibling("storage.rs");
    /// assert_eq!(storage_rs.as_relative(), Path::new("src/storage.rs"));
    /// ```
    pub fn sibling(&self, file_name: &str) -> Self {
        let parent = self.relative.parent().unwrap_or(Path::new(""));
        let new_relative = parent.join(file_name);
        self.with_relative(new_relative)
    }

    // === File I/O Operations ===

    /// Write content to this file, creating parent directories if needed
    ///
    /// This is the preferred way to write files in a workspace context.
    /// It automatically creates any missing parent directories before writing.
    ///
    /// # Example
    /// ```ignore
    /// let path = resolver.resolve("src/new_module/lib.rs")?;
    /// path.write("// New module\n")?;  // Creates src/new_module/ if needed
    /// ```
    pub fn write(&self, content: impl AsRef<[u8]>) -> io::Result<()> {
        write_with_parents(self.to_absolute(), content)
    }

    /// Read content from this file
    pub fn read(&self) -> io::Result<String> {
        std::fs::read_to_string(self.to_absolute())
    }

    /// Read content as bytes from this file
    pub fn read_bytes(&self) -> io::Result<Vec<u8>> {
        std::fs::read(self.to_absolute())
    }

    /// Check if the file exists
    pub fn exists(&self) -> bool {
        self.to_absolute().exists()
    }
}

/// Write content to a file, creating parent directories if needed
///
/// This is a standalone utility function for cases where you have a raw `PathBuf`
/// instead of a `WorkspaceFilePath`. Prefer using `WorkspaceFilePath::write()` when possible.
///
/// # Example
/// ```ignore
/// use ryo_symbol::write_with_parents;
///
/// write_with_parents("/path/to/new/file.rs", "content")?;
/// ```
pub fn write_with_parents(path: impl AsRef<Path>, content: impl AsRef<[u8]>) -> io::Result<()> {
    let path = path.as_ref();
    if let Some(parent) = path.parent() {
        if !parent.as_os_str().is_empty() && !parent.exists() {
            std::fs::create_dir_all(parent)?;
        }
    }
    std::fs::write(path, content)
}

// Hash/Eq based on relative path and crate_name (workspace_root is not included)
// This allows distinguishing files from different crates with the same relative path
// (e.g., "src/lib.rs" in crate-a vs crate-b)
impl PartialEq for WorkspaceFilePath {
    fn eq(&self, other: &Self) -> bool {
        self.relative == other.relative && self.crate_name == other.crate_name
    }
}

impl Eq for WorkspaceFilePath {}

impl Hash for WorkspaceFilePath {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.relative.hash(state);
        self.crate_name.hash(state);
    }
}

impl AsRef<Path> for WorkspaceFilePath {
    fn as_ref(&self) -> &Path {
        &self.relative
    }
}

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

// === Serialization ===
//
// Serialize as a struct with "path" (POSIX format) and "crate_name".
// workspace_root is injected during deserialization via WorkspaceFilePathSeed.

impl Serialize for WorkspaceFilePath {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("WorkspaceFilePath", 2)?;
        // Convert to POSIX format for cross-platform compatibility
        let posix_path = self.relative.to_string_lossy().replace('\\', "/");
        state.serialize_field("path", &posix_path)?;
        state.serialize_field("crate_name", &self.crate_name)?;
        state.end()
    }
}

// === Deserialization ===
//
// WorkspaceFilePath requires workspace_root context during deserialization.
// Use WorkspaceFilePathSeed with DeserializeSeed to inject the context.
// This is the responsibility of the Analysis layer, not Symbol layer.

/// Seed for deserializing WorkspaceFilePath with workspace_root injection
///
/// Since WorkspaceFilePath requires workspace_root which isn't stored in the
/// serialized form, use this seed to provide it during deserialization.
/// crate_name is stored in the serialized form and will be restored.
///
/// # Example
/// ```ignore
/// use serde::de::DeserializeSeed;
/// let seed = WorkspaceFilePathSeed::new(resolver.workspace_root_arc());
/// let path: WorkspaceFilePath = seed.deserialize(&mut deserializer)?;
/// ```
#[allow(dead_code)]
pub struct WorkspaceFilePathSeed {
    workspace_root: Arc<Path>,
}

impl WorkspaceFilePathSeed {
    /// Create a new seed with the workspace root
    #[allow(dead_code)]
    pub fn new(workspace_root: Arc<Path>) -> Self {
        Self { workspace_root }
    }
}

impl<'de> DeserializeSeed<'de> for WorkspaceFilePathSeed {
    type Value = WorkspaceFilePath;

    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct WorkspaceFilePathVisitor {
            workspace_root: Arc<Path>,
        }

        impl<'de> Visitor<'de> for WorkspaceFilePathVisitor {
            type Value = WorkspaceFilePath;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a struct with 'path' and 'crate_name' fields")
            }

            fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                let mut path: Option<String> = None;
                let mut crate_name: Option<CrateName> = None;

                while let Some(key) = map.next_key::<&str>()? {
                    match key {
                        "path" => path = Some(map.next_value()?),
                        "crate_name" => crate_name = Some(map.next_value()?),
                        _ => {
                            let _ = map.next_value::<serde::de::IgnoredAny>()?;
                        }
                    }
                }

                let path = path.ok_or_else(|| serde::de::Error::missing_field("path"))?;
                let crate_name =
                    crate_name.ok_or_else(|| serde::de::Error::missing_field("crate_name"))?;

                Ok(WorkspaceFilePath::new_unchecked(
                    PathBuf::from(path),
                    self.workspace_root,
                    crate_name,
                ))
            }
        }

        deserializer.deserialize_struct(
            "WorkspaceFilePath",
            &["path", "crate_name"],
            WorkspaceFilePathVisitor {
                workspace_root: self.workspace_root,
            },
        )
    }
}

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

    #[test]
    fn test_basic_operations() {
        let path = WorkspaceFilePath::new_for_test("src/lib.rs", "/workspace", "my_crate");

        assert_eq!(path.as_relative(), Path::new("src/lib.rs"));
        assert_eq!(path.workspace_root(), Path::new("/workspace"));
        assert_eq!(path.crate_name().as_str(), "my_crate");
        assert_eq!(path.to_absolute(), PathBuf::from("/workspace/src/lib.rs"));
        assert_eq!(path.file_name(), Some(OsStr::new("lib.rs")));
        assert_eq!(path.extension(), Some(OsStr::new("rs")));
        assert!(path.is_rust_file());
    }

    #[test]
    fn test_equality_considers_crate_name() {
        let path1 = WorkspaceFilePath::new_for_test("src/lib.rs", "/workspace1", "crate1");
        let path2 = WorkspaceFilePath::new_for_test("src/lib.rs", "/workspace2", "crate1");
        let path3 = WorkspaceFilePath::new_for_test("src/lib.rs", "/workspace1", "crate2");
        let path4 = WorkspaceFilePath::new_for_test("src/main.rs", "/workspace1", "crate1");

        // Same relative path + same crate_name = equal (workspace_root ignored)
        assert_eq!(path1, path2);
        // Same relative path but different crate_name = not equal
        assert_ne!(path1, path3);
        // Different relative path = not equal
        assert_ne!(path1, path4);
    }

    #[test]
    fn test_serialization() {
        let path = WorkspaceFilePath::new_for_test("src/lib.rs", "/workspace", "my_crate");
        let json = serde_json::to_string(&path).unwrap();
        assert_eq!(json, r#"{"path":"src/lib.rs","crate_name":"my_crate"}"#);
    }

    #[test]
    fn test_deserialization_with_seed() {
        use serde::de::DeserializeSeed;

        let json = r#"{"path":"src/lib.rs","crate_name":"my_crate"}"#;
        let workspace_root = Arc::from(Path::new("/workspace"));
        let seed = WorkspaceFilePathSeed::new(workspace_root);

        let mut de = serde_json::Deserializer::from_str(json);
        let path = seed.deserialize(&mut de).unwrap();

        assert_eq!(path.as_relative(), Path::new("src/lib.rs"));
        assert_eq!(path.crate_name().as_str(), "my_crate");
        assert_eq!(path.workspace_root(), Path::new("/workspace"));
    }

    #[test]
    fn test_with_context() {
        let path = WorkspaceFilePath::new_for_test("src/lib.rs", "/old", "old_crate");
        let new_path = path.with_context(
            Arc::from(Path::new("/new")),
            CrateName::new_for_test("new_crate"),
        );
        assert_eq!(new_path.workspace_root(), Path::new("/new"));
        assert_eq!(new_path.crate_name().as_str(), "new_crate");
    }

    #[test]
    fn test_write_creates_parent_directories() {
        use tempfile::tempdir;

        let temp = tempdir().unwrap();
        let workspace_root = temp.path();

        // Create a path with nested directories that don't exist
        let path = WorkspaceFilePath::new_for_test(
            "src/deep/nested/module/lib.rs",
            workspace_root.to_str().unwrap(),
            "test_crate",
        );

        // Parent directories don't exist yet
        assert!(!path.to_absolute().parent().unwrap().exists());

        // Write should succeed and create all parent directories
        path.write("// test content").unwrap();

        // Verify file exists and has correct content
        assert!(path.exists());
        assert_eq!(path.read().unwrap(), "// test content");
    }

    #[test]
    fn test_write_with_parents_utility() {
        use tempfile::tempdir;

        let temp = tempdir().unwrap();
        let file_path = temp.path().join("a/b/c/file.txt");

        // Parent directories don't exist
        assert!(!file_path.parent().unwrap().exists());

        // write_with_parents should create them
        write_with_parents(&file_path, "hello").unwrap();

        // Verify
        assert!(file_path.exists());
        assert_eq!(std::fs::read_to_string(&file_path).unwrap(), "hello");
    }
}