shape-lsp 0.3.2

Language Server Protocol implementation for Shape
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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
//! Module cache for cross-file navigation
//!
//! Provides module resolution and caching for import statements, enabling
//! go-to-definition and find-references across .shape files.

use dashmap::DashMap;
use shape_ast::ast::{Program, Span};
#[cfg(test)]
use shape_ast::parser::parse_program;
use shape_runtime::extension_context::ExtensionModuleSchemaCache;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};

/// Process-local extension module schema cache for the LSP.
///
/// Mirrors the B3 migration: shape-runtime no longer owns a process-global
/// `EXTENSION_MODULE_SCHEMA_CACHE` static, so editor tooling (which creates
/// fresh [`shape_runtime::module_loader::ModuleLoader`] instances per request
/// and has no persistent Runtime) keeps its own cache here to avoid
/// repeatedly `dlopen`-ing the same extension `.so` across completion /
/// navigation requests.
pub(crate) fn lsp_extension_schema_cache() -> &'static Arc<ExtensionModuleSchemaCache> {
    static CACHE: OnceLock<Arc<ExtensionModuleSchemaCache>> = OnceLock::new();
    CACHE.get_or_init(|| Arc::new(ExtensionModuleSchemaCache::new()))
}

fn module_path_segments(path: &str) -> Vec<&str> {
    if path.contains("::") {
        path.split("::")
            .filter(|segment| !segment.is_empty())
            .collect()
    } else {
        path.split('.')
            .filter(|segment| !segment.is_empty())
            .collect()
    }
}

fn is_std_module_path(path: &str) -> bool {
    module_path_segments(path)
        .first()
        .is_some_and(|segment| *segment == "std")
}

/// Kind of exported symbol
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SymbolKind {
    Function,
    Pattern,
    Variable,
    TypeAlias,
    Trait,
    Enum,
    Annotation,
}

/// An exported symbol from a module
#[derive(Debug, Clone)]
pub struct ExportedSymbol {
    /// The symbol name
    pub name: String,
    /// Optional alias (if exported with 'as')
    pub alias: Option<String>,
    /// Kind of symbol
    pub kind: SymbolKind,
    /// Location in source file
    pub span: Span,
}

impl ExportedSymbol {
    /// Get the exported name (alias if present, otherwise original name)
    pub fn exported_name(&self) -> &str {
        self.alias.as_ref().unwrap_or(&self.name)
    }
}

/// Information about a loaded module
#[derive(Debug, Clone)]
pub struct ModuleInfo {
    /// Absolute path to the module file
    pub path: PathBuf,
    /// Parsed program (shared to avoid cloning)
    pub program: Arc<Program>,
    /// Exported symbols from this module
    pub exports: Vec<ExportedSymbol>,
}

/// Module cache for tracking and resolving imports
#[derive(Debug, Default)]
pub struct ModuleCache {
    /// Map of module path to module info
    modules: DashMap<PathBuf, ModuleInfo>,
}

impl ModuleCache {
    /// Create a new module cache
    pub fn new() -> Self {
        Self {
            modules: DashMap::new(),
        }
    }

    fn loader_for_context(
        current_file: &Path,
        workspace_root: Option<&Path>,
        current_source: Option<&str>,
    ) -> shape_runtime::module_loader::ModuleLoader {
        let mut loader = shape_runtime::module_loader::ModuleLoader::new();
        loader.configure_for_context_with_source(
            current_file,
            workspace_root,
            current_source,
            lsp_extension_schema_cache(),
        );
        loader
    }

    /// Resolve an import path to an absolute file path using runtime module resolution.
    pub fn resolve_import(
        &self,
        import_path: &str,
        current_file: &Path,
        workspace_root: Option<&Path>,
    ) -> Option<PathBuf> {
        let loader = Self::loader_for_context(current_file, workspace_root, None);

        let context_dir = current_file.parent().map(Path::to_path_buf);
        let resolved = loader.resolve_module_path_with_context(import_path, context_dir.as_ref());
        if let Ok(path) = resolved {
            return Some(path);
        }

        // Compatibility fallback for legacy dot-separated import paths.
        if import_path.contains("::")
            || import_path.starts_with("./")
            || import_path.starts_with("../")
            || import_path.starts_with('/')
        {
            return None;
        }

        let canonical = import_path.replace('.', "::");
        loader
            .resolve_module_path_with_context(&canonical, context_dir.as_ref())
            .ok()
    }

    /// Load a module from a file path
    ///
    /// If the module is already cached, returns the cached version.
    /// Otherwise, reads and parses the file, extracts exports, and caches it.
    pub fn load_module(&self, path: &Path) -> Option<ModuleInfo> {
        self.load_module_with_context(path, path, None)
    }

    /// Context-aware module load using the same module-loader setup as import resolution.
    pub fn load_module_with_context(
        &self,
        path: &Path,
        current_file: &Path,
        workspace_root: Option<&Path>,
    ) -> Option<ModuleInfo> {
        // Check cache first
        if let Some(cached) = self.modules.get(path) {
            return Some(cached.clone());
        }

        // Load via runtime module loader for unified parse/export semantics.
        let mut loader = Self::loader_for_context(current_file, workspace_root, None);
        let module = loader.load_module_from_file(path).ok()?;
        let program = Arc::new(module.ast.clone());

        // Extract exports from the program
        let exports = extract_exports(&program);

        let module_info = ModuleInfo {
            path: path.to_path_buf(),
            program: program.clone(),
            exports,
        };

        // Cache the module
        self.modules.insert(path.to_path_buf(), module_info.clone());

        Some(module_info)
    }

    /// Load a module by import path using unified module-loader context.
    ///
    /// This supports both filesystem modules and in-memory extension artifacts.
    pub fn load_module_by_import_with_context_and_source(
        &self,
        import_path: &str,
        current_file: &Path,
        workspace_root: Option<&Path>,
        current_source: Option<&str>,
    ) -> Option<ModuleInfo> {
        let mut loader = Self::loader_for_context(current_file, workspace_root, current_source);
        let context_dir = current_file.parent().map(Path::to_path_buf);
        let module = loader
            .load_module_with_context(import_path, context_dir.as_ref())
            .ok()?;

        let cache_path = PathBuf::from(format!(
            "__shape_lsp_virtual__/{}.shape",
            import_path.replace("::", "/").replace('.', "/")
        ));
        let program = Arc::new(module.ast.clone());
        let exports = extract_exports(&program);
        let module_info = ModuleInfo {
            path: cache_path.clone(),
            program: program.clone(),
            exports,
        };
        self.modules.insert(cache_path, module_info.clone());
        Some(module_info)
    }

    /// Get a cached module (without loading if not present)
    pub fn get_module(&self, path: &Path) -> Option<ModuleInfo> {
        self.modules.get(path).map(|entry| entry.clone())
    }

    /// Invalidate a module in the cache (when file changes)
    pub fn invalidate(&self, path: &Path) {
        self.modules.remove(path);
    }

    /// Clear the entire cache
    pub fn clear(&self) {
        self.modules.clear();
    }

    /// List importable module paths for the current workspace context.
    ///
    /// Includes:
    /// - `std.*` modules from stdlib
    /// - project module search paths from `shape.toml` (`[modules].paths`)
    /// - path dependencies from `shape.toml` (`[dependencies]`)
    pub fn list_importable_modules_with_context(
        &self,
        current_file: &Path,
        workspace_root: Option<&Path>,
    ) -> Vec<String> {
        self.list_importable_modules_with_context_and_source(current_file, workspace_root, None)
    }

    /// List importable module paths with optional current source for frontmatter-aware context.
    pub fn list_importable_modules_with_context_and_source(
        &self,
        current_file: &Path,
        workspace_root: Option<&Path>,
        current_source: Option<&str>,
    ) -> Vec<String> {
        let mut loader = shape_runtime::module_loader::ModuleLoader::new();
        loader.configure_for_context_with_source(
            current_file,
            workspace_root,
            current_source,
            lsp_extension_schema_cache(),
        );
        loader.list_importable_modules_with_context(current_file, workspace_root)
    }

    /// List importable module paths using the process CWD as context.
    pub fn list_importable_modules(&self) -> Vec<String> {
        let current_file = std::env::current_dir()
            .unwrap_or_else(|_| PathBuf::from("."))
            .join("__shape_lsp__.shape");
        self.list_importable_modules_with_context(&current_file, None)
    }

    /// List all stdlib module import paths (e.g., `std::core::math`).
    pub fn list_stdlib_modules(&self) -> Vec<String> {
        self.list_importable_modules()
            .into_iter()
            .filter(|module_path| is_std_module_path(module_path))
            .collect()
    }

    /// Return direct children under a stdlib prefix for hierarchical completion.
    ///
    /// For example, with prefix `std::core` it can return entries like:
    /// - `math` (leaf, no children)
    /// - `indicators` (non-leaf)
    pub fn list_stdlib_children(&self, prefix: &str) -> Vec<ModuleChild> {
        let effective_prefix = if prefix.is_empty() { "std" } else { prefix };
        if !is_std_module_path(effective_prefix) {
            return Vec::new();
        }

        self.list_module_children(effective_prefix)
    }

    /// Return direct children under an import prefix for hierarchical completion.
    pub fn list_module_children_with_context(
        &self,
        prefix: &str,
        current_file: &Path,
        workspace_root: Option<&Path>,
    ) -> Vec<ModuleChild> {
        let base = if prefix.is_empty() {
            "std".to_string()
        } else {
            prefix.to_string()
        };

        let mut children: HashMap<String, ModuleChild> = HashMap::new();
        let base_segments = module_path_segments(&base);
        let base_len = base_segments.len();
        for module_path in self.list_importable_modules_with_context(current_file, workspace_root) {
            let module_segments = module_path_segments(&module_path);
            if module_segments.len() <= base_len {
                continue;
            }
            if module_segments[..base_len] != base_segments[..] {
                continue;
            }

            let child = module_segments[base_len];
            let has_children = module_segments.len() > base_len + 1;

            let entry = children.entry(child.to_string()).or_insert(ModuleChild {
                name: child.to_string(),
                has_leaf_module: false,
                has_children: false,
            });
            if has_children {
                entry.has_children = true;
            } else {
                entry.has_leaf_module = true;
            }
        }

        let mut out: Vec<ModuleChild> = children.into_values().collect();
        out.sort_by(|a, b| a.name.cmp(&b.name));
        out
    }

    /// Return direct children under an import prefix using process CWD as context.
    pub fn list_module_children(&self, prefix: &str) -> Vec<ModuleChild> {
        let current_file = std::env::current_dir()
            .unwrap_or_else(|_| PathBuf::from("."))
            .join("__shape_lsp__.shape");
        self.list_module_children_with_context(prefix, &current_file, None)
    }

    /// Find all modules that export a symbol with the given name.
    /// Scans importable modules and returns (import_path, ExportedSymbol) pairs.
    pub fn find_exported_symbol_with_context(
        &self,
        name: &str,
        current_file: &Path,
        workspace_root: Option<&Path>,
    ) -> Vec<(String, ExportedSymbol)> {
        let mut results = Vec::new();

        for import_path in self.list_importable_modules_with_context(current_file, workspace_root) {
            let Some(resolved) = self.resolve_import(&import_path, current_file, workspace_root)
            else {
                continue;
            };
            let Some(module_info) =
                self.load_module_with_context(&resolved, current_file, workspace_root)
            else {
                continue;
            };

            for export in &module_info.exports {
                if export.exported_name() == name {
                    results.push((import_path.clone(), export.clone()));
                }
            }
        }

        results
    }

    /// Scans importable modules using process CWD as context.
    pub fn find_exported_symbol(&self, name: &str) -> Vec<(String, ExportedSymbol)> {
        let current_file = std::env::current_dir()
            .unwrap_or_else(|_| PathBuf::from("."))
            .join("__shape_lsp__.shape");
        self.find_exported_symbol_with_context(name, &current_file, None)
    }

    /// Enumerate all `.shape` files under the workspace root.
    ///
    /// W2.6 workspace-indexing groundwork (consumed by W2.7 workspace/symbol
    /// eager-index handler + this crate's cross-file references/rename
    /// resolution). Walks the workspace tree once on demand; skips common
    /// build/dependency directories. Returns absolute paths.
    ///
    /// Excludes:
    /// - hidden directories (`.git`, `.cache`, etc.)
    /// - `target/`, `node_modules/`, `dist/`, `build/`
    /// - paths under `current_file`'s parent if it's the same as the file
    ///   (no de-dup needed; caller handles).
    ///
    /// Bounded by [`MAX_WORKSPACE_FILES`] (4096) to avoid runaway on
    /// monorepos; if the cap is hit the result is truncated and the caller
    /// gets a best-effort subset.
    pub fn enumerate_workspace_shape_files(&self, workspace_root: &Path) -> Vec<PathBuf> {
        let mut files = Vec::new();
        let mut stack = vec![workspace_root.to_path_buf()];
        while let Some(dir) = stack.pop() {
            if files.len() >= MAX_WORKSPACE_FILES {
                break;
            }
            let Ok(entries) = std::fs::read_dir(&dir) else {
                continue;
            };
            for entry in entries.flatten() {
                let path = entry.path();
                let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
                    continue;
                };
                // Skip hidden directories + well-known build/dep dirs
                if name.starts_with('.')
                    || matches!(name, "target" | "node_modules" | "dist" | "build")
                {
                    continue;
                }
                if path.is_dir() {
                    stack.push(path);
                } else if path.extension().and_then(|e| e.to_str()) == Some("shape") {
                    files.push(path);
                    if files.len() >= MAX_WORKSPACE_FILES {
                        break;
                    }
                }
            }
        }
        files
    }
}

/// Bound on workspace-file enumeration to keep the LSP responsive on
/// monorepos. Mirrors rust-analyzer's per-crate file caps; if a workspace
/// genuinely has more than this many `.shape` files, the user is editing in
/// a context where eager indexing is the wrong default and they should
/// scope the LSP via `shape.toml` `[modules].paths`.
pub const MAX_WORKSPACE_FILES: usize = 4096;

/// W2.7 willRenameFiles helper — derive the canonical Shape `from` module
/// path (`a::b::c`) for a `.shape` file relative to the workspace root.
///
/// Returns `None` when the file is outside the workspace root, has no
/// `.shape` extension, or contains a path segment that is not a valid
/// Shape identifier (e.g. starts with a digit, contains `-`). The latter
/// is conservative — files that cannot be imported by any Shape `from`
/// clause produce no rewrite edits.
///
/// Examples (workspace root = `/ws`):
/// - `/ws/foo.shape` → `Some("foo")`
/// - `/ws/lib/util.shape` → `Some("lib::util")`
/// - `/ws/src/sub/mod.shape` → `Some("src::sub::mod")`
/// - `/ws/2bad.shape` → `None` (leading digit)
/// - `/other/foo.shape` → `None` (outside workspace)
pub fn path_to_module_path(file: &Path, workspace_root: &Path) -> Option<String> {
    let rel = file.strip_prefix(workspace_root).ok()?;
    let stem = rel.file_stem().and_then(|s| s.to_str())?;
    if rel.extension().and_then(|e| e.to_str()) != Some("shape") {
        return None;
    }
    let mut segments: Vec<String> = Vec::new();
    for component in rel.parent()?.components() {
        let std::path::Component::Normal(seg) = component else {
            continue;
        };
        let seg = seg.to_str()?;
        if !is_valid_shape_identifier(seg) {
            return None;
        }
        segments.push(seg.to_string());
    }
    if !is_valid_shape_identifier(stem) {
        return None;
    }
    segments.push(stem.to_string());
    if segments.is_empty() {
        return None;
    }
    Some(segments.join("::"))
}

fn is_valid_shape_identifier(s: &str) -> bool {
    let mut chars = s.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    if !(first.is_ascii_alphabetic() || first == '_') {
        return false;
    }
    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

/// Child entry used for hierarchical module completion.
#[derive(Debug, Clone)]
pub struct ModuleChild {
    pub name: String,
    pub has_leaf_module: bool,
    pub has_children: bool,
}

fn map_module_export_kind(kind: shape_runtime::module_loader::ModuleExportKind) -> SymbolKind {
    use shape_runtime::module_loader::ModuleExportKind as RuntimeKind;
    match kind {
        RuntimeKind::Function => SymbolKind::Function,
        RuntimeKind::BuiltinFunction => SymbolKind::Function,
        RuntimeKind::TypeAlias => SymbolKind::TypeAlias,
        RuntimeKind::BuiltinType => SymbolKind::TypeAlias,
        RuntimeKind::Trait => SymbolKind::Trait,
        RuntimeKind::Enum => SymbolKind::Enum,
        RuntimeKind::Annotation => SymbolKind::Annotation,
        RuntimeKind::Value => SymbolKind::Variable,
    }
}

/// Extract exported symbols from a program AST
fn extract_exports(program: &Program) -> Vec<ExportedSymbol> {
    shape_runtime::module_loader::collect_exported_symbols(program)
        .unwrap_or_default()
        .into_iter()
        .map(|sym| ExportedSymbol {
            name: sym.name,
            alias: sym.alias,
            kind: map_module_export_kind(sym.kind),
            span: sym.span,
        })
        .collect()
}

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

    #[test]
    fn test_resolve_stdlib_import() {
        let cache = ModuleCache::new();
        let current_file =
            PathBuf::from("/home/dev/dev/finance/analysis-suite/shape/examples/test.shape");

        let resolved = cache.resolve_import("std::core::math", &current_file, None);

        assert!(resolved.is_some());
        let path = resolved.unwrap();
        let path_str = path.to_string_lossy();
        assert!(
            path_str.contains("stdlib/core/math.shape")
                || path_str.contains("stdlib-src/core/math.shape"),
            "Expected stdlib math path, got: {}",
            path_str
        );
    }

    #[test]
    fn test_relative_import_is_supported() {
        let tmp = tempfile::tempdir().unwrap();
        let current_file = tmp.path().join("main.shape");
        let util = tmp.path().join("utils.shape");
        std::fs::write(&current_file, "from ./utils use { helper }").unwrap();
        std::fs::write(&util, "pub fn helper() { 1 }").unwrap();

        let cache = ModuleCache::new();

        let resolved = cache.resolve_import("./utils", &current_file, None);
        assert_eq!(resolved.as_deref(), Some(util.as_path()));
    }

    #[test]
    fn test_non_std_import_returns_none() {
        let cache = ModuleCache::new();
        let current_file = PathBuf::from("/home/user/project/src/main.shape");

        // Non-std imports return None (handled by dependency resolution elsewhere)
        let resolved = cache.resolve_import("finance::indicators", &current_file, None);
        assert!(resolved.is_none());
    }

    #[test]
    fn test_exported_symbol_name() {
        let symbol = ExportedSymbol {
            name: "originalName".to_string(),
            alias: Some("aliasName".to_string()),
            kind: SymbolKind::Function,
            span: Span::default(),
        };

        assert_eq!(symbol.exported_name(), "aliasName");

        let symbol_no_alias = ExportedSymbol {
            name: "originalName".to_string(),
            alias: None,
            kind: SymbolKind::Function,
            span: Span::default(),
        };

        assert_eq!(symbol_no_alias.exported_name(), "originalName");
    }

    #[test]
    fn test_extract_exports() {
        let source = r#"
pub fn myFunc(x) {
    return x + 1;
}

fn localFunc() {
    return 42;
}
"#;

        let program = parse_program(source).unwrap();
        let exports = extract_exports(&program);

        assert_eq!(exports.len(), 1);
        assert_eq!(exports[0].name, "myFunc");
        assert_eq!(exports[0].kind, SymbolKind::Function);
    }

    #[test]
    fn test_list_stdlib_modules_not_empty() {
        let cache = ModuleCache::new();
        let modules = cache.list_stdlib_modules();
        assert!(
            !modules.is_empty(),
            "expected stdlib module list to be non-empty"
        );
        assert!(
            modules.iter().all(|m| m.starts_with("std::")),
            "all stdlib modules should be std::-prefixed: {:?}",
            modules
        );
    }

    #[test]
    fn test_list_stdlib_children_for_std_prefix() {
        let cache = ModuleCache::new();
        let children = cache.list_stdlib_children("std");
        assert!(
            !children.is_empty(),
            "expected stdlib root to have child modules"
        );
        assert!(
            children.iter().any(|c| c.name == "core"),
            "expected std.core child in stdlib tree"
        );
    }

    #[test]
    fn test_list_importable_modules_with_project_modules_and_deps() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::write(
            root.join("shape.toml"),
            r#"
[modules]
paths = ["lib"]

[dependencies]
mydep = { path = "deps/mydep" }
"#,
        )
        .unwrap();

        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::create_dir_all(root.join("lib")).unwrap();
        std::fs::create_dir_all(root.join("deps/mydep")).unwrap();

        std::fs::write(root.join("src/main.shape"), "let x = 1").unwrap();
        std::fs::write(root.join("lib/tools.shape"), "pub fn tool() { 1 }").unwrap();
        std::fs::write(root.join("deps/mydep/index.shape"), "pub fn root() { 1 }").unwrap();
        std::fs::write(root.join("deps/mydep/util.shape"), "pub fn util() { 1 }").unwrap();

        let cache = ModuleCache::new();
        let modules =
            cache.list_importable_modules_with_context(&root.join("src/main.shape"), None);

        assert!(
            modules.iter().any(|m| m == "tools"),
            "expected module path from [modules].paths, got: {:?}",
            modules
        );
        assert!(
            modules.iter().any(|m| m == "mydep"),
            "expected dependency index module path, got: {:?}",
            modules
        );
        assert!(
            modules.iter().any(|m| m == "mydep::util"),
            "expected dependency submodule path, got: {:?}",
            modules
        );
    }

    #[test]
    fn test_enumerate_workspace_shape_files() {
        // W2.6 groundwork — workspace-file enumeration for cross-file
        // references / rename + W2.7 workspace symbol indexing consumer.
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::write(root.join("a.shape"), "let x = 1").unwrap();
        std::fs::create_dir_all(root.join("sub")).unwrap();
        std::fs::write(root.join("sub/b.shape"), "fn foo() { 2 }").unwrap();
        // Excluded by hidden-dir filter
        std::fs::create_dir_all(root.join(".git")).unwrap();
        std::fs::write(root.join(".git/c.shape"), "ignored").unwrap();
        // Excluded by build-dir filter
        std::fs::create_dir_all(root.join("target")).unwrap();
        std::fs::write(root.join("target/d.shape"), "ignored").unwrap();
        // Non-shape file: excluded by extension filter
        std::fs::write(root.join("e.txt"), "ignored").unwrap();

        let cache = ModuleCache::new();
        let files = cache.enumerate_workspace_shape_files(root);
        let names: Vec<String> = files
            .iter()
            .filter_map(|p| p.file_name().and_then(|n| n.to_str()).map(String::from))
            .collect();
        assert!(names.contains(&"a.shape".to_string()), "expected a.shape, got {:?}", names);
        assert!(names.contains(&"b.shape".to_string()), "expected b.shape, got {:?}", names);
        assert!(
            !names.contains(&"c.shape".to_string()),
            "hidden dir .git must be excluded, got {:?}",
            names
        );
        assert!(
            !names.contains(&"d.shape".to_string()),
            "build dir target must be excluded, got {:?}",
            names
        );
        assert!(
            !names.contains(&"e.txt".to_string()),
            "non-.shape file must be excluded, got {:?}",
            names
        );
    }

    #[test]
    fn test_path_to_module_path_w27() {
        // W2.7 willRenameFiles — derive Shape module path from file path.
        let root = PathBuf::from("/ws");
        assert_eq!(
            path_to_module_path(&root.join("foo.shape"), &root).as_deref(),
            Some("foo")
        );
        assert_eq!(
            path_to_module_path(&root.join("lib/util.shape"), &root).as_deref(),
            Some("lib::util")
        );
        assert_eq!(
            path_to_module_path(&root.join("src/sub/mod.shape"), &root).as_deref(),
            Some("src::sub::mod")
        );
        // Non-.shape: rejected.
        assert!(path_to_module_path(&root.join("foo.txt"), &root).is_none());
        // Outside workspace: rejected.
        assert!(path_to_module_path(&PathBuf::from("/other/x.shape"), &root).is_none());
        // Invalid identifier in segment (leading digit): rejected.
        assert!(path_to_module_path(&root.join("2bad.shape"), &root).is_none());
        assert!(path_to_module_path(&root.join("a-b/x.shape"), &root).is_none());
        // Underscore-only / leading-underscore: allowed (valid Shape ident).
        assert_eq!(
            path_to_module_path(&root.join("_priv/_x.shape"), &root).as_deref(),
            Some("_priv::_x")
        );
    }

    #[test]
    fn test_module_cache_invalidation() {
        let cache = ModuleCache::new();
        let path = PathBuf::from("/test/module.shape");

        // Create a mock module info
        let program = Arc::new(Program {
            items: vec![],
            docs: shape_ast::ast::ProgramDocs::default(),
        });
        let module_info = ModuleInfo {
            path: path.clone(),
            program,
            exports: vec![],
        };

        // Insert into cache
        cache.modules.insert(path.clone(), module_info.clone());
        assert!(cache.get_module(&path).is_some());

        // Invalidate
        cache.invalidate(&path);
        assert!(cache.get_module(&path).is_none());
    }
}