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
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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
//! Workspace path resolver for normalizing and validating paths

use std::path::{Component, Path, PathBuf};
use std::sync::Arc;

use crate::crate_name::CrateName;
use crate::error::ResolveError;
use crate::file_path::WorkspaceFilePath;
use crate::metadata::WorkspaceMetadataProvider;
use crate::path::SymbolPath;
use crate::symbol_resolver::SymbolPathResolver;

/// Entry point type for a crate
///
/// Determines whether the crate root is `lib.rs` or `main.rs`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EntryPoint {
    /// Library crate: `src/lib.rs`
    #[default]
    Lib,
    /// Binary crate: `src/main.rs`
    Bin,
}

impl EntryPoint {
    /// Get the file name for this entry point
    pub fn file_name(&self) -> &'static str {
        match self {
            Self::Lib => "lib.rs",
            Self::Bin => "main.rs",
        }
    }

    /// Infer entry point from a file path
    ///
    /// Checks if the path ends with `main.rs` or `lib.rs`.
    pub fn from_path(path: &std::path::Path) -> Self {
        if let Some(file_name) = path.file_name().and_then(|n| n.to_str()) {
            if file_name == "main.rs" {
                return Self::Bin;
            }
        }
        Self::Lib
    }
}

/// Type of workspace structure
///
/// Determined by `[workspace]` section in Cargo.toml:
/// - `Workspace`: Has `[workspace]` section (multi-crate or single-crate in subdirectory)
/// - `Crate`: No `[workspace]` section (single crate at root)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WorkspaceType {
    /// Multi-crate workspace or single crate in subdirectory
    /// File layout: `crates/{crate}/src/*.rs` or `{crate}/src/*.rs`
    #[default]
    Workspace,
    /// Single crate at workspace root
    /// File layout: `src/*.rs`
    Crate,
}

/// Layout of a crate within a workspace
///
/// Determines the file path prefix for a crate's source files.
/// Used by `SymbolPathResolver` to convert `SymbolPath` → `WorkspaceFilePath`.
///
/// # Examples
///
/// ```ignore
/// // Single crate at workspace root: src/lib.rs
/// CrateLayout::Root
///
/// // Standard workspace: crates/my-crate/src/lib.rs
/// CrateLayout::InCrates { crate_dir_name: "my-crate".to_string() }
///
/// // Custom path: packages/core/src/lib.rs
/// CrateLayout::Custom { prefix: PathBuf::from("packages/core") }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum CrateLayout {
    /// Crate at workspace root: `src/*.rs`
    #[default]
    Root,
    /// Crate in `crates/` directory: `crates/{crate_dir_name}/src/*.rs`
    InCrates {
        /// Directory name (may differ from crate name due to hyphens)
        crate_dir_name: String,
    },
    /// Crate at custom path: `{prefix}/src/*.rs`
    Custom {
        /// Path prefix relative to workspace root
        prefix: PathBuf,
    },
}

impl CrateLayout {
    /// Create layout for a crate in `crates/` directory
    pub fn in_crates(crate_dir_name: impl Into<String>) -> Self {
        Self::InCrates {
            crate_dir_name: crate_dir_name.into(),
        }
    }

    /// Create layout for a crate at custom path
    pub fn custom(prefix: impl Into<PathBuf>) -> Self {
        Self::Custom {
            prefix: prefix.into(),
        }
    }

    /// Get the source directory path relative to workspace root
    ///
    /// Returns the path to the `src/` directory for this crate.
    pub fn src_dir(&self) -> PathBuf {
        match self {
            Self::Root => PathBuf::from("src"),
            Self::InCrates { crate_dir_name } => {
                PathBuf::from(format!("crates/{}/src", crate_dir_name))
            }
            Self::Custom { prefix } => prefix.join("src"),
        }
    }

    /// Convert a crate-relative path to a workspace-relative path.
    ///
    /// This is essential for converting generator output paths (e.g., `"src/lib.rs"`)
    /// to workspace-relative paths (e.g., `"crates/my-crate/src/lib.rs"`).
    ///
    /// # Arguments
    ///
    /// * `crate_relative` - Path relative to crate root (e.g., `"src/lib.rs"`, `"src/foo/bar.rs"`)
    ///
    /// # Returns
    ///
    /// Path relative to workspace root.
    ///
    /// # Examples
    ///
    /// ```
    /// use ryo_symbol::CrateLayout;
    /// use std::path::PathBuf;
    ///
    /// // Root layout: path unchanged
    /// let root = CrateLayout::Root;
    /// assert_eq!(root.to_workspace_relative("src/lib.rs"), PathBuf::from("src/lib.rs"));
    ///
    /// // InCrates layout: prepend crates/{name}/
    /// let in_crates = CrateLayout::in_crates("my-crate");
    /// assert_eq!(
    ///     in_crates.to_workspace_relative("src/lib.rs"),
    ///     PathBuf::from("crates/my-crate/src/lib.rs")
    /// );
    ///
    /// // Custom layout: prepend custom prefix
    /// let custom = CrateLayout::custom("packages/core");
    /// assert_eq!(
    ///     custom.to_workspace_relative("src/lib.rs"),
    ///     PathBuf::from("packages/core/src/lib.rs")
    /// );
    /// ```
    pub fn to_workspace_relative(&self, crate_relative: impl AsRef<Path>) -> PathBuf {
        let crate_relative = crate_relative.as_ref();

        match self {
            Self::Root => {
                // Root layout: path is already workspace-relative
                crate_relative.to_path_buf()
            }
            Self::InCrates { crate_dir_name } => {
                // InCrates: prepend "crates/{name}/"
                PathBuf::from(format!("crates/{}", crate_dir_name)).join(crate_relative)
            }
            Self::Custom { prefix } => {
                // Custom: prepend the custom prefix
                prefix.join(crate_relative)
            }
        }
    }

    /// Infer layout from a WorkspaceFilePath
    ///
    /// Analyzes the path structure to determine the crate layout.
    pub fn from_workspace_file_path(path: &WorkspaceFilePath) -> Self {
        let path_str = path.as_relative().to_string_lossy();

        // Check for crates/{name}/src/ pattern
        if let Some(idx) = path_str.find("crates/") {
            let after_crates = &path_str[idx + 7..];
            if let Some(end_idx) = after_crates.find('/') {
                let crate_dir_name = &after_crates[..end_idx];
                return Self::InCrates {
                    crate_dir_name: crate_dir_name.to_string(),
                };
            }
        }

        // Check for direct src/ (root layout)
        if path_str.starts_with("src/") {
            return Self::Root;
        }

        // Check for custom prefix (anything before /src/)
        if let Some(idx) = path_str.find("/src/") {
            let prefix = &path_str[..idx];
            return Self::Custom {
                prefix: PathBuf::from(prefix),
            };
        }

        // Default to root
        Self::Root
    }
}

/// Workspace path resolver
///
/// Normalizes and validates paths relative to a workspace root.
/// This is the **only** way to create `WorkspaceFilePath` instances.
///
/// # Responsibilities
/// - Convert any path (absolute/relative) to `WorkspaceFilePath`
/// - Normalize paths (resolve `..` and `.`)
/// - Validate paths are within workspace
/// - Share workspace_root via `Arc<Path>` for efficient cloning
///
/// # Example
/// ```ignore
/// let resolver = WorkspacePathResolver::new("/home/user/project".into());
///
/// // Absolute path
/// let p1 = resolver.resolve("/home/user/project/src/lib.rs")?;
///
/// // Relative path (resolved from CWD)
/// let p2 = resolver.resolve("./src/../src/lib.rs")?;
///
/// // Strict mode (also checks file existence)
/// let p3 = resolver.resolve_strict("src/lib.rs")?;
/// ```
#[derive(Debug, Clone)]
pub struct WorkspacePathResolver {
    workspace_root: Arc<Path>,
    workspace_type: WorkspaceType,
}

impl WorkspacePathResolver {
    /// Create a new resolver with the given workspace root
    ///
    /// Defaults to `WorkspaceType::Workspace`. Use `with_type` for explicit control.
    pub fn new(workspace_root: PathBuf) -> Self {
        Self {
            workspace_root: Arc::from(workspace_root),
            workspace_type: WorkspaceType::default(),
        }
    }

    /// Create a new resolver with explicit workspace type
    pub fn with_type(workspace_root: PathBuf, workspace_type: WorkspaceType) -> Self {
        Self {
            workspace_root: Arc::from(workspace_root),
            workspace_type,
        }
    }

    /// Get the workspace type
    pub fn workspace_type(&self) -> WorkspaceType {
        self.workspace_type
    }

    /// Resolve any path to a WorkspaceFilePath with provider-based crate resolution
    ///
    /// - Absolute path → convert to relative from workspace_root
    /// - Relative path → resolve from CWD, then convert
    /// - `..` / `.` → resolved
    /// - Outside workspace → error
    /// - crate_name → resolved from provider
    pub fn resolve_with_provider<P: WorkspaceMetadataProvider>(
        &self,
        path: impl AsRef<Path>,
        provider: &P,
    ) -> Result<WorkspaceFilePath, ResolveError> {
        let path = path.as_ref();

        // 1. Convert to absolute path
        let absolute = if path.is_absolute() {
            path.to_path_buf()
        } else {
            std::env::current_dir()?.join(path)
        };

        // 2. Normalize (resolve .. and ., no I/O)
        let normalized = normalize_path(&absolute);

        // 3. Convert to relative path from workspace_root
        let relative = normalized
            .strip_prefix(&*self.workspace_root)
            .map_err(|_| ResolveError::OutsideWorkspace {
                path: normalized.clone(),
                workspace: self.workspace_root.to_path_buf(),
            })?
            .to_path_buf();

        // 4. Create temporary path to resolve crate name
        // We need to create a temporary WorkspaceFilePath to pass to the provider
        // Use a placeholder crate name first, then resolve the real one
        let temp_crate = CrateName::new_unchecked("__temp__");
        let temp_path = WorkspaceFilePath::new_unchecked(
            relative.clone(),
            Arc::clone(&self.workspace_root),
            temp_crate,
        );

        // 5. Resolve crate name from provider
        let crate_name = provider
            .crate_for_file(&temp_path)
            .ok_or_else(|| ResolveError::CrateNotFound(normalized.clone()))?;

        Ok(WorkspaceFilePath::new_unchecked(
            relative,
            Arc::clone(&self.workspace_root),
            crate_name,
        ))
    }

    /// Resolve with file existence check (strict mode)
    pub fn resolve_strict_with_provider<P: WorkspaceMetadataProvider>(
        &self,
        path: impl AsRef<Path>,
        provider: &P,
    ) -> Result<WorkspaceFilePath, ResolveError> {
        let workspace_path = self.resolve_with_provider(path, provider)?;
        let absolute = workspace_path.to_absolute();

        if !absolute.exists() {
            return Err(ResolveError::FileNotFound(absolute));
        }

        Ok(workspace_path)
    }

    /// Resolve from a path that's already relative to workspace root (with explicit crate name)
    ///
    /// This skips CWD resolution and directly creates a WorkspaceFilePath.
    /// Useful when you already have a known-good relative path and crate name.
    pub fn resolve_relative_with_crate(
        &self,
        relative: impl AsRef<Path>,
        crate_name: CrateName,
    ) -> WorkspaceFilePath {
        let relative = relative.as_ref();
        let normalized = normalize_path(relative);
        WorkspaceFilePath::new_unchecked(normalized, Arc::clone(&self.workspace_root), crate_name)
    }

    /// Resolve from a path that's already relative to workspace root (with provider)
    ///
    /// This skips CWD resolution and uses the provider to resolve the crate name.
    pub fn resolve_relative_with_provider<P: WorkspaceMetadataProvider>(
        &self,
        relative: impl AsRef<Path>,
        provider: &P,
    ) -> Option<WorkspaceFilePath> {
        let relative = relative.as_ref();
        let normalized = normalize_path(relative);

        // Create temporary path to resolve crate name
        let temp_crate = CrateName::new_unchecked("__temp__");
        let temp_path = WorkspaceFilePath::new_unchecked(
            normalized.clone(),
            Arc::clone(&self.workspace_root),
            temp_crate,
        );

        // Resolve crate name from provider
        let crate_name = provider.crate_for_file(&temp_path)?;

        Some(WorkspaceFilePath::new_unchecked(
            normalized,
            Arc::clone(&self.workspace_root),
            crate_name,
        ))
    }

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

    /// Get the workspace root as Arc (for deserialization)
    pub fn workspace_root_arc(&self) -> Arc<Path> {
        Arc::clone(&self.workspace_root)
    }

    // ========== Module to File Resolution ==========

    /// Resolve module path to file path
    ///
    /// This method centralizes the logic for determining which file a module belongs to.
    /// It handles the distinction between:
    /// - **Crate root (depth 1)**: span points to the actual file (main.rs/lib.rs)
    /// - **Sub-modules (depth > 1)**: span points to declaration site (`mod foo;` in lib.rs),
    ///   so path-based inference is needed to get the actual file (foo.rs)
    ///
    /// # Arguments
    ///
    /// - `module_path`: The symbol path of the module
    /// - `crate_name`: The crate name for path inference
    /// - `span_file`: Optional span file (use for crate root to preserve main.rs vs lib.rs)
    ///
    /// # Example
    ///
    /// ```ignore
    /// let resolver = WorkspacePathResolver::new("/workspace".into());
    ///
    /// // For crate root with span → uses span file (preserves main.rs)
    /// let file = resolver.module_to_file(&module_path, &crate_name, Some(&span_file));
    ///
    /// // For sub-module → uses path-based inference
    /// let file = resolver.module_to_file(&module_path, &crate_name, None);
    /// ```
    pub fn module_to_file(
        &self,
        module_path: &SymbolPath,
        crate_name: &CrateName,
        span_file: Option<&WorkspaceFilePath>,
    ) -> WorkspaceFilePath {
        // Crate root (depth 1): span points to actual file (main.rs/lib.rs)
        if module_path.depth() == 1 {
            if let Some(span_file) = span_file {
                return span_file.clone();
            }
        }

        // Sub-module or no span: use path-based inference
        let symbol_resolver = SymbolPathResolver::from_crate_name(crate_name.clone());

        // Create a virtual child to get the containing file
        // (e.g., crate::storage → crate::storage::_ → src/storage.rs)
        if let Ok(virtual_child) = module_path.child("_") {
            symbol_resolver.to_workspace_file_path(&virtual_child, self.workspace_root_arc())
        } else {
            symbol_resolver.to_workspace_file_path(module_path, self.workspace_root_arc())
        }
    }

    // ========== Simplified API (infers crate_name from path) ==========

    /// Resolve any path to a WorkspaceFilePath (infers crate_name from path)
    ///
    /// This is a simplified API that attempts to infer the crate name from the path.
    /// It looks for `crates/<crate-name>/` in the path structure.
    ///
    /// For more control, use `resolve_with_provider` or `resolve_relative_with_crate`.
    pub fn resolve(&self, path: impl AsRef<Path>) -> Result<WorkspaceFilePath, ResolveError> {
        let path = path.as_ref();

        // 1. Convert to absolute path
        let absolute = if path.is_absolute() {
            path.to_path_buf()
        } else {
            std::env::current_dir()?.join(path)
        };

        // 2. Normalize (resolve .. and ., no I/O)
        let normalized = normalize_path(&absolute);

        // 3. Convert to relative path from workspace_root
        let relative = normalized
            .strip_prefix(&*self.workspace_root)
            .map_err(|_| ResolveError::OutsideWorkspace {
                path: normalized.clone(),
                workspace: self.workspace_root.to_path_buf(),
            })?
            .to_path_buf();

        // 4. Infer crate name from path
        let crate_name = infer_crate_name(&relative);

        Ok(WorkspaceFilePath::new_unchecked(
            relative,
            Arc::clone(&self.workspace_root),
            crate_name,
        ))
    }

    /// Resolve from a path that's already relative to workspace root (infers crate_name)
    ///
    /// This is a simplified API that skips CWD resolution and infers the crate name.
    pub fn resolve_relative(&self, relative: impl AsRef<Path>) -> Option<WorkspaceFilePath> {
        let relative = relative.as_ref();
        let normalized = normalize_path(relative);
        let crate_name = infer_crate_name(&normalized);

        Some(WorkspaceFilePath::new_unchecked(
            normalized,
            Arc::clone(&self.workspace_root),
            crate_name,
        ))
    }

    // ========== Validation API ==========

    /// Validate that a `crate::` prefixed path is unambiguous in this workspace
    ///
    /// In a multi-crate workspace (`WorkspaceType::Workspace`), paths starting with
    /// `crate::` are ambiguous because it's unclear which crate is being referred to.
    ///
    /// # Arguments
    ///
    /// - `path`: The path string to validate (e.g., "crate::domain::model")
    /// - `workspace_members`: List of workspace member paths for error message (e.g., ["crates/core", "crates/api"])
    ///
    /// # Returns
    ///
    /// - `Ok(())` if the path is unambiguous (single crate or doesn't start with `crate::`)
    /// - `Err(ResolveError::AmbiguousCratePath)` if ambiguous in multi-crate workspace
    ///
    /// # Example
    ///
    /// ```ignore
    /// let resolver = WorkspacePathResolver::with_type(root, WorkspaceType::Workspace);
    /// let members = vec!["crates/core".to_string(), "crates/api".to_string()];
    ///
    /// // This will error in multi-crate workspace
    /// resolver.validate_crate_path("crate::domain", &members)?;
    ///
    /// // These are OK
    /// resolver.validate_crate_path("core::domain", &members)?;  // explicit crate name
    /// resolver.validate_crate_path("src/domain.rs", &members)?; // file path
    /// ```
    pub fn validate_crate_path(
        &self,
        path: &str,
        workspace_members: &[String],
    ) -> Result<(), ResolveError> {
        // Only validate for multi-crate workspaces
        if self.workspace_type != WorkspaceType::Workspace {
            return Ok(());
        }

        // Only validate paths starting with "crate::"
        if !path.starts_with("crate::") {
            return Ok(());
        }

        // Single-member workspace is not ambiguous
        if workspace_members.len() <= 1 {
            return Ok(());
        }

        // Multi-crate workspace with crate:: path is ambiguous
        let first_member = workspace_members.first().cloned().unwrap_or_default();
        let crate_name = first_member
            .split('/')
            .next_back()
            .unwrap_or(&first_member)
            .to_string();

        // Extract module path from "crate::xxx" -> "xxx"
        let module_suffix = path.strip_prefix("crate::").unwrap_or("");
        let example_file_path = if module_suffix.is_empty() {
            format!("{}/src/lib.rs", first_member)
        } else {
            format!(
                "{}/src/{}.rs",
                first_member,
                module_suffix.replace("::", "/")
            )
        };

        Err(ResolveError::AmbiguousCratePath {
            path: path.to_string(),
            example_crate_path: first_member,
            example_file_path,
            example_crate_name: crate_name,
        })
    }
}

/// Infer crate name from a relative path
///
/// Looks for `crates/<crate-name>/` pattern in the path.
/// Falls back to "crate" if pattern not found.
fn infer_crate_name(path: &Path) -> CrateName {
    let path_str = path.to_string_lossy();

    // Look for "crates/<name>/" pattern
    if let Some(idx) = path_str.find("crates/") {
        let after_crates = &path_str[idx + 7..];
        if let Some(end_idx) = after_crates.find('/') {
            let crate_name = &after_crates[..end_idx];
            return CrateName::new_unchecked(crate_name);
        }
    }

    // Fallback: use first component if it looks like a crate (has src/)
    if path_str.contains("/src/") || path_str.starts_with("src/") {
        // Path is already in crate root, use "crate" as default
        return CrateName::new_unchecked("crate");
    }

    // Default fallback
    CrateName::new_unchecked("crate")
}

/// Normalize a path without I/O (resolve `..` and `.`)
///
/// # Precondition
/// For best results, input should be an absolute path.
/// Relative paths with `..` that exceed the root will have those
/// components silently dropped.
fn normalize_path(path: &Path) -> PathBuf {
    let mut components = Vec::new();

    for comp in path.components() {
        match comp {
            Component::ParentDir => {
                // `/foo/..` → `/`
                // Don't pop RootDir or Prefix (Windows)
                if let Some(Component::Normal(_)) = components.last() {
                    components.pop();
                }
            }
            Component::CurDir => {
                // `.` is skipped
            }
            c => components.push(c),
        }
    }

    components.iter().collect()
}

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

    #[test]
    fn test_normalize_path() {
        assert_eq!(
            normalize_path(Path::new("/foo/bar/../baz")),
            PathBuf::from("/foo/baz")
        );
        assert_eq!(
            normalize_path(Path::new("/foo/./bar")),
            PathBuf::from("/foo/bar")
        );
        assert_eq!(
            normalize_path(Path::new("/foo/bar/../../baz")),
            PathBuf::from("/baz")
        );
        assert_eq!(
            normalize_path(Path::new("foo/bar/../baz")),
            PathBuf::from("foo/baz")
        );
    }

    #[test]
    fn test_resolve_relative_with_crate() {
        let resolver = WorkspacePathResolver::new(PathBuf::from("/workspace"));
        let crate_name = CrateName::new_for_test("my_crate");

        let path = resolver.resolve_relative_with_crate("src/lib.rs", crate_name);
        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");
    }

    #[test]
    fn test_resolve_relative_with_dots_and_crate() {
        let resolver = WorkspacePathResolver::new(PathBuf::from("/workspace"));
        let crate_name = CrateName::new_for_test("my_crate");

        let path = resolver.resolve_relative_with_crate("src/../src/./lib.rs", crate_name);
        assert_eq!(path.as_relative(), Path::new("src/lib.rs"));
        assert_eq!(path.crate_name().as_str(), "my_crate");
    }

    #[test]
    fn test_resolve_relative_with_provider() {
        use crate::metadata::MockMetadataProvider;

        let resolver = WorkspacePathResolver::new(PathBuf::from("/workspace"));
        let provider = MockMetadataProvider::new("/workspace", "test_crate");

        let path = resolver
            .resolve_relative_with_provider("src/lib.rs", &provider)
            .unwrap();
        assert_eq!(path.as_relative(), Path::new("src/lib.rs"));
        assert_eq!(path.crate_name().as_str(), "test_crate");
    }

    // ========================================================================
    // CrateLayout::to_workspace_relative tests
    // ========================================================================

    #[test]
    fn test_crate_layout_to_workspace_relative_root() {
        // Root layout: src/lib.rs stays as src/lib.rs
        let layout = CrateLayout::Root;
        let result = layout.to_workspace_relative("src/lib.rs");
        assert_eq!(result, PathBuf::from("src/lib.rs"));
    }

    #[test]
    fn test_crate_layout_to_workspace_relative_in_crates() {
        // InCrates layout: src/lib.rs → crates/my-crate/src/lib.rs
        let layout = CrateLayout::in_crates("my-crate");
        let result = layout.to_workspace_relative("src/lib.rs");
        assert_eq!(result, PathBuf::from("crates/my-crate/src/lib.rs"));
    }

    #[test]
    fn test_crate_layout_to_workspace_relative_in_crates_nested() {
        // InCrates layout: src/foo/bar.rs → crates/my-crate/src/foo/bar.rs
        let layout = CrateLayout::in_crates("my-crate");
        let result = layout.to_workspace_relative("src/foo/bar.rs");
        assert_eq!(result, PathBuf::from("crates/my-crate/src/foo/bar.rs"));
    }

    #[test]
    fn test_crate_layout_to_workspace_relative_custom() {
        // Custom layout: src/lib.rs → packages/core/src/lib.rs
        let layout = CrateLayout::custom("packages/core");
        let result = layout.to_workspace_relative("src/lib.rs");
        assert_eq!(result, PathBuf::from("packages/core/src/lib.rs"));
    }

    #[test]
    fn test_crate_layout_to_workspace_relative_main_rs() {
        // Binary: src/main.rs → crates/my-cli/src/main.rs
        let layout = CrateLayout::in_crates("my-cli");
        let result = layout.to_workspace_relative("src/main.rs");
        assert_eq!(result, PathBuf::from("crates/my-cli/src/main.rs"));
    }
}