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
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
//! File path resolver for converting symbol paths to file paths
//!
//! Centralizes the logic for resolving SymbolPath to WorkspaceFilePath.
//! This is the reverse of SymbolPathResolver.

use std::path::PathBuf;

use crate::crate_name::CrateName;
use crate::error::ResolutionError;
use crate::file_path::WorkspaceFilePath;
use crate::metadata::{CrateInfo, TargetKind};
use crate::path::SymbolPath;
use crate::registry::SymbolRegistry;
use crate::resolver::WorkspacePathResolver;

/// Resolves symbol paths to file paths
///
/// # Design
///
/// This resolver centralizes the conversion from Rust symbol paths to
/// file system paths (WorkspaceFilePath). It provides two resolution strategies:
///
/// 1. **Registry-based** (preferred): Uses SymbolRegistry span info
/// 2. **Inference-based** (fallback): Infers file path from module structure
///
/// # Example
///
/// ```ignore
/// let resolver = FilePathResolver::new(workspace_root);
///
/// // With registry (preferred - uses span info)
/// let path = resolver.resolve_with_registry(&symbol_path, &registry)?;
///
/// // Without registry (inference-based)
/// let path = resolver.resolve_by_inference(&symbol_path)?;
/// ```
#[derive(Debug, Clone)]
pub struct FilePathResolver {
    workspace_resolver: WorkspacePathResolver,
}

impl FilePathResolver {
    /// Create a new resolver with the given workspace root
    pub fn new(workspace_root: PathBuf) -> Self {
        Self {
            workspace_resolver: WorkspacePathResolver::new(workspace_root),
        }
    }

    /// Create from an existing WorkspacePathResolver
    pub fn from_workspace_resolver(workspace_resolver: WorkspacePathResolver) -> Self {
        Self { workspace_resolver }
    }

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

    /// Resolve SymbolPath to WorkspaceFilePath using SymbolRegistry
    ///
    /// This is the preferred method as it uses span information from the registry.
    ///
    /// # Returns
    ///
    /// - `Ok(WorkspaceFilePath)` - The file containing the symbol
    /// - `Err(ResolutionError::SymbolNotFound)` - Symbol not in registry
    /// - `Err(ResolutionError::NoSpanInfo)` - Symbol found but has no span
    pub fn resolve_with_registry(
        &self,
        path: &SymbolPath,
        registry: &SymbolRegistry,
    ) -> Result<WorkspaceFilePath, ResolutionError> {
        let symbol_id = registry
            .lookup(path)
            .ok_or_else(|| ResolutionError::SymbolNotFound(path.to_string()))?;

        let span = registry
            .span(symbol_id)
            .ok_or_else(|| ResolutionError::NoSpanInfo(path.to_string()))?;

        Ok(span.file.clone())
    }

    /// Resolve SymbolPath to WorkspaceFilePath, falling back to inference
    ///
    /// Tries registry first, then falls back to inference if:
    /// - Symbol not found in registry
    /// - Symbol has no span info
    ///
    /// # Arguments
    ///
    /// - `path` - The symbol path to resolve
    /// - `registry` - Optional registry for span-based resolution
    pub fn resolve(
        &self,
        path: &SymbolPath,
        registry: Option<&SymbolRegistry>,
    ) -> Result<WorkspaceFilePath, ResolutionError> {
        // Try registry-based resolution first
        if let Some(reg) = registry {
            if let Ok(file_path) = self.resolve_with_registry(path, reg) {
                return Ok(file_path);
            }
        }

        // Fallback to inference
        self.resolve_by_inference(path)
    }

    /// Resolve SymbolPath to WorkspaceFilePath by inferring from module structure
    ///
    /// Follows Rust's module conventions:
    /// - `crate_name` → `src/lib.rs` or `src/main.rs`
    /// - `crate_name::foo` → `src/foo.rs` or `src/foo/mod.rs`
    /// - `crate_name::foo::bar` → `src/foo/bar.rs` or `src/foo/bar/mod.rs`
    /// - `crate_name::foo::bar::Item` → same as `crate_name::foo::bar`
    ///
    /// # Note
    ///
    /// This method cannot distinguish between:
    /// - A module file (`foo.rs` defines module `foo`)
    /// - An item in a parent module (`foo` is an item in `lib.rs`)
    ///
    /// Use `resolve_with_registry` when accuracy is critical.
    pub fn resolve_by_inference(
        &self,
        path: &SymbolPath,
    ) -> Result<WorkspaceFilePath, ResolutionError> {
        // Get crate name from symbol path (first segment)
        let crate_name = CrateName::new_unchecked(path.crate_name());

        // Skip crate name, get remaining segments
        let segments: Vec<&str> = path.segments().skip(1).collect();

        if segments.is_empty() {
            // Crate root → src/lib.rs
            return Ok(self
                .workspace_resolver
                .resolve_relative_with_crate("src/lib.rs", crate_name));
        }

        // Try progressively shorter paths (item might be in parent module)
        // e.g., crate::foo::bar::Baz → try foo/bar.rs, then foo.rs, then lib.rs
        for depth in (0..=segments.len()).rev() {
            let module_segments = &segments[..depth];

            if module_segments.is_empty() {
                // Check lib.rs
                return Ok(self
                    .workspace_resolver
                    .resolve_relative_with_crate("src/lib.rs", crate_name));
            }

            // Build file path: src/foo/bar.rs
            let mut path_buf = PathBuf::from("src");
            for seg in module_segments {
                path_buf.push(seg);
            }
            path_buf.set_extension("rs");

            let file_path = self
                .workspace_resolver
                .resolve_relative_with_crate(&path_buf, crate_name.clone());

            // We return the first candidate (deepest module path)
            // Caller should verify file exists if needed
            if depth == segments.len() || depth == segments.len() - 1 {
                return Ok(file_path);
            }
        }

        // Should not reach here, but return lib.rs as ultimate fallback
        Ok(self
            .workspace_resolver
            .resolve_relative_with_crate("src/lib.rs", crate_name))
    }

    /// Resolve with mod.rs fallback
    ///
    /// First tries `src/foo/bar.rs`, then `src/foo/bar/mod.rs`.
    /// Returns both candidates for caller to check existence.
    pub fn resolve_candidates(&self, path: &SymbolPath) -> Vec<WorkspaceFilePath> {
        // Get crate name from symbol path (first segment)
        let crate_name = CrateName::new_unchecked(path.crate_name());

        let segments: Vec<&str> = path.segments().skip(1).collect();

        if segments.is_empty() {
            return vec![
                self.workspace_resolver
                    .resolve_relative_with_crate("src/lib.rs", crate_name.clone()),
                self.workspace_resolver
                    .resolve_relative_with_crate("src/main.rs", crate_name),
            ];
        }

        // For module path, try both file.rs and dir/mod.rs patterns
        let mut candidates = Vec::with_capacity(2);

        // Build module path
        let mut path_buf = PathBuf::from("src");
        for seg in &segments {
            path_buf.push(seg);
        }

        // Candidate 1: src/foo/bar.rs
        let mut file_path = path_buf.clone();
        file_path.set_extension("rs");
        candidates.push(
            self.workspace_resolver
                .resolve_relative_with_crate(&file_path, crate_name.clone()),
        );

        // Candidate 2: src/foo/bar/mod.rs
        let mut mod_path = path_buf;
        mod_path.push("mod.rs");
        candidates.push(
            self.workspace_resolver
                .resolve_relative_with_crate(&mod_path, crate_name),
        );

        candidates
    }

    /// Resolve SymbolPath to WorkspaceFilePath candidates using Cargo metadata.
    ///
    /// This is the accurate, metadata-driven file resolution method that correctly handles:
    /// - Bin-only crates (no lib.rs, only main.rs)
    /// - Mixed crates (both lib.rs and main.rs)
    /// - Library-only crates
    /// - Workspace crates in subdirectories
    ///
    /// # Main Symbol Handling
    ///
    /// This method handles the `main::` prefix correctly by skipping both "main" and
    /// the crate name when processing segments:
    ///
    /// ```ignore
    /// // Library symbol:
    /// "my_crate::models::User"
    /// segments: skip(1) → ["models", "User"]
    ///
    /// // Binary symbol:
    /// "main::my_crate::models::User"
    /// segments: skip(2) → ["models", "User"]  // Skip both "main" and "my_crate"
    /// ```
    ///
    /// # Crate Root Resolution
    ///
    /// For crate root symbols (0 or 1 segments after crate name):
    ///
    /// ```ignore
    /// // Library crate:
    /// "my_crate" or "my_crate::Item" → ["src/lib.rs"]
    ///
    /// // Bin-only crate:
    /// "main::my_app" or "main::my_app::Item" → ["src/main.rs"]
    ///
    /// // Mixed crate (both lib and bin):
    /// "my_crate::Item" → ["src/lib.rs", "src/main.rs"]
    /// "main::my_crate::Item" → ["src/main.rs", "src/lib.rs"]
    /// ```
    ///
    /// The `resolve_crate_root_candidates()` method consults `crate_info.entry_points`
    /// to determine which files to include.
    ///
    /// # Sub-Module Resolution
    ///
    /// For nested modules (2+ segments after crate name):
    ///
    /// ```ignore
    /// "my_crate::models::User" → ["src/models.rs", "src/models/mod.rs"]
    /// "main::my_app::cli::Args" → ["src/cli.rs", "src/cli/mod.rs"]
    /// ```
    ///
    /// # Arguments
    ///
    /// * `path` - The symbol path to resolve (may have `main::` prefix)
    /// * `crate_info` - Cargo metadata for the target crate
    ///
    /// # Returns
    ///
    /// A vector of candidate file paths, ordered by preference:
    /// 1. For crate root: entry point files (lib.rs, main.rs, or both)
    /// 2. For modules: file.rs first, then file/mod.rs
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Bin-only crate (only main.rs):
    /// let path = SymbolPath::parse("main::my_app::Status")?;
    /// let candidates = resolver.resolve_candidates_with_crate_info(&path, &crate_info);
    /// // → ["src/main.rs"] (crate root, bin-only)
    ///
    /// // Library crate with module:
    /// let path = SymbolPath::parse("my_lib::models::User")?;
    /// let candidates = resolver.resolve_candidates_with_crate_info(&path, &crate_info);
    /// // → ["src/models.rs", "src/models/mod.rs"]
    /// ```
    ///
    /// # See Also
    ///
    /// - [`SymbolPath::module_path_str()`] - Inverse operation (file → symbol path)
    /// - [`SymbolPath::is_main_symbol()`] - Checks for `main::` prefix
    /// - `resolve_crate_root_candidates()` - Handles entry point resolution
    pub fn resolve_candidates_with_crate_info(
        &self,
        path: &SymbolPath,
        crate_info: &CrateInfo,
    ) -> Vec<WorkspaceFilePath> {
        let crate_name = CrateName::new_unchecked(&crate_info.module_name);

        // For main symbols (main::my_crate::Item), skip both "main" and crate name
        // For library symbols (my_crate::Item), skip crate name only
        let skip_count = if path.is_main_symbol() { 2 } else { 1 };
        let segments: Vec<&str> = path.segments().skip(skip_count).collect();

        // Get crate's source directory relative to workspace root
        // e.g., "crates/core/src" or "src"
        let crate_src_path = &crate_info.src_path;

        if segments.is_empty() || segments.len() == 1 {
            // Crate root or crate root item (e.g., crate or crate::Item)
            // Both should resolve to the crate's entry point (lib.rs or main.rs)
            return self.resolve_crate_root_candidates(crate_info, &crate_name);
        }

        // For sub-modules (2+ segments after crate), use crate's src_path as base
        let mut candidates = Vec::with_capacity(2);

        // Build module path relative to crate's src directory
        let mut path_buf = PathBuf::from(crate_src_path.as_str());
        for seg in &segments {
            path_buf.push(seg);
        }

        // Candidate 1: crates/xxx/src/foo/bar.rs
        let mut file_path = path_buf.clone();
        file_path.set_extension("rs");
        candidates.push(
            self.workspace_resolver
                .resolve_relative_with_crate(&file_path, crate_name.clone()),
        );

        // Candidate 2: crates/xxx/src/foo/bar/mod.rs
        let mut mod_path = path_buf;
        mod_path.push("mod.rs");
        candidates.push(
            self.workspace_resolver
                .resolve_relative_with_crate(&mod_path, crate_name),
        );

        candidates
    }

    /// Resolve crate root candidates using entry_points from CrateInfo
    fn resolve_crate_root_candidates(
        &self,
        crate_info: &CrateInfo,
        crate_name: &CrateName,
    ) -> Vec<WorkspaceFilePath> {
        let mut candidates = Vec::new();

        // Check for lib target first (preferred)
        let has_lib = crate_info
            .entry_points
            .iter()
            .any(|t| t.kind == TargetKind::Lib);

        // Check for bin target
        let bin_target = crate_info
            .entry_points
            .iter()
            .find(|t| t.kind == TargetKind::Bin);

        if has_lib {
            // Lib target exists - add lib.rs
            let lib_path = crate_info.src_path.join("lib.rs");
            candidates.push(
                self.workspace_resolver
                    .resolve_relative_with_crate(lib_path.as_str(), crate_name.clone()),
            );
        }

        if let Some(bin) = bin_target {
            // Bin target exists - add its path (usually main.rs but could be custom)
            // Use the actual path from entry_points
            candidates.push(
                self.workspace_resolver
                    .resolve_relative_with_crate(bin.src_path.as_str(), crate_name.clone()),
            );
        }

        // Fallback: if no targets found, use default paths
        if candidates.is_empty() {
            let src_path = &crate_info.src_path;
            candidates.push(
                self.workspace_resolver.resolve_relative_with_crate(
                    format!("{}/lib.rs", src_path),
                    crate_name.clone(),
                ),
            );
            candidates.push(
                self.workspace_resolver.resolve_relative_with_crate(
                    format!("{}/main.rs", src_path),
                    crate_name.clone(),
                ),
            );
        }

        candidates
    }

    /// Resolve using CrateInfo, checking file existence
    ///
    /// Returns the first candidate that exists in the provided file set.
    /// This is the recommended method for production use.
    ///
    /// # Arguments
    ///
    /// * `path` - The symbol path to resolve
    /// * `crate_info` - Cargo metadata for the crate
    /// * `existing_files` - Set of files that exist (for existence checking)
    pub fn resolve_with_crate_info<F>(
        &self,
        path: &SymbolPath,
        crate_info: &CrateInfo,
        file_exists: F,
    ) -> Result<WorkspaceFilePath, ResolutionError>
    where
        F: Fn(&WorkspaceFilePath) -> bool,
    {
        let candidates = self.resolve_candidates_with_crate_info(path, crate_info);

        for candidate in candidates {
            if file_exists(&candidate) {
                return Ok(candidate);
            }
        }

        Err(ResolutionError::SymbolNotFound(format!(
            "No file found for symbol '{}' in crate '{}'",
            path, crate_info.name
        )))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::kind::SymbolKind;
    use crate::span::FileSpan;

    fn make_path(s: &str) -> SymbolPath {
        SymbolPath::parse(s).unwrap()
    }

    fn make_resolver() -> FilePathResolver {
        FilePathResolver::new(PathBuf::from("/workspace"))
    }

    #[test]
    fn test_resolve_crate_root() {
        let resolver = make_resolver();
        let path = make_path("my_crate");

        let result = resolver.resolve_by_inference(&path).unwrap();
        assert_eq!(result.as_relative(), std::path::Path::new("src/lib.rs"));
    }

    #[test]
    fn test_resolve_simple_module() {
        let resolver = make_resolver();
        let path = make_path("my_crate::foo");

        let result = resolver.resolve_by_inference(&path).unwrap();
        assert_eq!(result.as_relative(), std::path::Path::new("src/foo.rs"));
    }

    #[test]
    fn test_resolve_nested_module() {
        let resolver = make_resolver();
        let path = make_path("my_crate::foo::bar");

        let result = resolver.resolve_by_inference(&path).unwrap();
        assert_eq!(result.as_relative(), std::path::Path::new("src/foo/bar.rs"));
    }

    #[test]
    fn test_resolve_item_in_module() {
        let resolver = make_resolver();
        // Item "Baz" in module foo::bar
        let path = make_path("my_crate::foo::bar::Baz");

        let result = resolver.resolve_by_inference(&path).unwrap();
        // Should resolve to the module file
        assert_eq!(
            result.as_relative(),
            std::path::Path::new("src/foo/bar/Baz.rs")
        );
    }

    #[test]
    fn test_resolve_candidates() {
        let resolver = make_resolver();
        let path = make_path("my_crate::foo::bar");

        let candidates = resolver.resolve_candidates(&path);
        assert_eq!(candidates.len(), 2);
        assert_eq!(
            candidates[0].as_relative(),
            std::path::Path::new("src/foo/bar.rs")
        );
        assert_eq!(
            candidates[1].as_relative(),
            std::path::Path::new("src/foo/bar/mod.rs")
        );
    }

    #[test]
    fn test_resolve_with_registry() {
        let resolver = make_resolver();
        let mut registry = SymbolRegistry::new();

        let symbol_path = make_path("my_crate::MyStruct");
        let file = WorkspaceFilePath::new_for_test("src/lib.rs", "/workspace", "my_crate");
        let span = FileSpan::new(file.clone(), 100, 150);

        let id = registry
            .register(symbol_path.clone(), SymbolKind::Struct)
            .unwrap();
        registry.set_span(id, span).unwrap();

        let result = resolver
            .resolve_with_registry(&symbol_path, &registry)
            .unwrap();
        assert_eq!(result, file);
    }

    #[test]
    fn test_resolve_fallback_to_inference() {
        let resolver = make_resolver();
        let registry = SymbolRegistry::new(); // Empty registry

        let path = make_path("my_crate::foo");

        // Symbol not in registry, should fall back to inference
        let result = resolver.resolve(&path, Some(&registry)).unwrap();
        assert_eq!(result.as_relative(), std::path::Path::new("src/foo.rs"));
    }
}