Skip to main content

logicaffeine_lsp/
workspace.rs

1//! Workspace-wide symbol index: every `.lg`/`.md` file under the workspace
2//! folders, analyzed in the background, so symbols resolve across files the
3//! user never opened.
4//!
5//! Open-document state stays authoritative in [`crate::state::ServerState`];
6//! this index answers only what per-document resolution cannot — workspace
7//! symbol queries and cross-file definition lookups.
8
9use std::path::{Path, PathBuf};
10
11use dashmap::DashMap;
12use lsp_types::{Location, Range, SymbolKind, Url};
13
14use crate::index::DefinitionKind;
15use crate::line_index::LineIndex;
16use crate::pipeline;
17
18/// A module that publicly exports a given name — the backbone of the auto-import
19/// quickfix, cross-module completion, and "defined in module X" hover.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct ModuleExport {
22    /// The file that defines the name.
23    pub module_url: Url,
24    /// The module's import alias (`util.lg` → `Util`).
25    pub module_name: String,
26}
27
28/// Read-only view of the workspace's imports/exports, so LSP providers (auto-import,
29/// completion, hover) are unit-testable against a fake without a running server.
30pub trait WorkspaceView {
31    /// Every module that publicly exports `name` (a function/type/variant).
32    fn module_exporting(&self, name: &str) -> Vec<ModuleExport>;
33    /// The module aliases the file at `uri` imports.
34    fn imports_of(&self, uri: &Url) -> Vec<String>;
35    /// Every indexed module: its import alias and file Url.
36    fn module_names(&self) -> Vec<(String, Url)>;
37    /// The public names the module at `uri` exports. Default empty (fakes that
38    /// don't need it are unaffected).
39    fn exports_of(&self, _uri: &Url) -> Vec<String> {
40        Vec::new()
41    }
42    /// The symbol labels to offer for this file's imports (label, module alias).
43    /// Default: whole-module semantics (every export of every imported module) —
44    /// a fake that only implements `imports_of`/`exports_of` keeps its behavior.
45    /// The real index overrides this to honor selective imports.
46    fn imported_symbols(&self, uri: &Url) -> Vec<(String, String)> {
47        let module_urls: std::collections::HashMap<String, Url> =
48            self.module_names().into_iter().collect();
49        let mut out = Vec::new();
50        for alias in self.imports_of(uri) {
51            if let Some(url) = module_urls.get(&alias) {
52                for name in self.exports_of(url) {
53                    out.push((name, alias.clone()));
54                }
55            }
56        }
57        out
58    }
59
60    /// Whether the file at `uri` imports a module that publicly exports `name`.
61    fn is_imported(&self, uri: &Url, name: &str) -> bool {
62        let importers = self.imports_of(uri);
63        self.module_exporting(name)
64            .iter()
65            .any(|e| importers.iter().any(|a| a == &e.module_name))
66    }
67}
68
69/// The filesystem path a `file://` URL names. `None` for any other URL, and always on a
70/// target with no filesystem — the browser Studio, which has no workspace on disk.
71pub fn url_path(url: &Url) -> Option<PathBuf> {
72    #[cfg(any(unix, windows, target_os = "redox", target_os = "wasi"))]
73    return url.to_file_path().ok();
74    #[cfg(not(any(unix, windows, target_os = "redox", target_os = "wasi")))]
75    {
76        let _ = url;
77        None
78    }
79}
80
81/// The `file://` URL for a filesystem path — `None` where there is no filesystem.
82pub fn path_url(path: &Path) -> Option<Url> {
83    #[cfg(any(unix, windows, target_os = "redox", target_os = "wasi"))]
84    return Url::from_file_path(path).ok();
85    #[cfg(not(any(unix, windows, target_os = "redox", target_os = "wasi")))]
86    {
87        let _ = path;
88        None
89    }
90}
91
92/// Derive a module's import alias from its file path (`geometry.lg` → `Geometry`).
93pub fn module_alias_from_url(url: &Url) -> Option<String> {
94    let path = url_path(url)?;
95    let stem = path.file_stem()?.to_str()?;
96    let mut chars = stem.chars();
97    let first = chars.next()?;
98    Some(first.to_uppercase().collect::<String>() + chars.as_str())
99}
100
101/// Bounds: a workspace scan must never wedge the server on a monorepo.
102const MAX_FILES: usize = 2_000;
103const MAX_FILE_BYTES: u64 = 512 * 1024;
104const SKIP_DIRS: &[&str] = &["target", "node_modules", "dist", "out", "logs"];
105
106pub struct WorkspaceSymbol {
107    pub name: String,
108    pub kind: SymbolKind,
109    pub container: Option<String>,
110    pub location: Location,
111}
112
113/// One name occurrence in a file, for cross-file references and rename.
114pub struct FileReference {
115    pub name: String,
116    pub range: Range,
117    /// True when the file's own scope resolved this reference — its target
118    /// is local unless this very file defines the workspace-visible symbol.
119    pub resolved_locally: bool,
120}
121
122#[derive(Default)]
123pub struct WorkspaceIndex {
124    files: DashMap<Url, Vec<WorkspaceSymbol>>,
125    refs: DashMap<Url, Vec<FileReference>>,
126    /// Per-file import declarations (from the abstract's `Import` statements) —
127    /// the FULL dependency, so selective imports (`Import double from Util.`) keep
128    /// their selected-name list for scope-accurate completion.
129    imports: DashMap<Url, Vec<logicaffeine_language::analysis::Dependency>>,
130}
131
132impl WorkspaceIndex {
133    pub fn new() -> Self {
134        Self::default()
135    }
136
137    /// Analyze every LOGOS file under `root` (bounded). Blocking — run it on
138    /// a blocking task.
139    pub fn scan_folder(&self, root: &Path) {
140        let mut pending = vec![root.to_path_buf()];
141        let mut seen_files = 0usize;
142        while let Some(dir) = pending.pop() {
143            let Ok(entries) = std::fs::read_dir(&dir) else {
144                continue;
145            };
146            for entry in entries.flatten() {
147                let path = entry.path();
148                let name = entry.file_name();
149                let name = name.to_string_lossy();
150                if path.is_dir() {
151                    if !name.starts_with('.') && !SKIP_DIRS.contains(&name.as_ref()) {
152                        pending.push(path);
153                    }
154                    continue;
155                }
156                let is_logos = matches!(
157                    path.extension().and_then(|e| e.to_str()),
158                    Some("lg") | Some("md")
159                );
160                if !is_logos {
161                    continue;
162                }
163                if entry
164                    .metadata()
165                    .map(|m| m.len() > MAX_FILE_BYTES)
166                    .unwrap_or(true)
167                {
168                    continue;
169                }
170                if seen_files >= MAX_FILES {
171                    log::warn!(
172                        "workspace scan hit the {MAX_FILES}-file bound at {}; remaining files are unindexed",
173                        path.display()
174                    );
175                    return;
176                }
177                seen_files += 1;
178                self.index_file(&path);
179            }
180        }
181    }
182
183    /// (Re-)analyze one file into the index.
184    pub fn index_file(&self, path: &Path) {
185        let Some(uri) = path_url(path) else { return };
186        let Ok(source) = std::fs::read_to_string(path) else {
187            self.files.remove(&uri);
188            return;
189        };
190        let analysis = pipeline::analyze(&source);
191        let line_index = LineIndex::new(&source);
192
193        // Private definitions (`## To private …` / `## A[n] private …`) resolve
194        // inside their own file but are NOT importable — so they must never enter
195        // the workspace surface that feeds cross-module completion and auto-import.
196        let private_names: std::collections::HashSet<String> =
197            logicaffeine_compile::loader::defined_names_with_visibility(&source)
198                .into_iter()
199                .filter(|(_, private)| *private)
200                .map(|(name, _)| name)
201                .collect();
202
203        let symbols = analysis
204            .symbol_index
205            .definitions
206            .iter()
207            .filter(|def| def.span != logicaffeine_language::token::Span::default())
208            .filter(|def| !private_names.contains(&def.name))
209            .filter_map(|def| {
210                // Locals stay per-document; the workspace surface is API shape.
211                let kind = match def.kind {
212                    DefinitionKind::Function => SymbolKind::FUNCTION,
213                    DefinitionKind::Struct => SymbolKind::STRUCT,
214                    DefinitionKind::Enum => SymbolKind::ENUM,
215                    DefinitionKind::Field => SymbolKind::FIELD,
216                    DefinitionKind::Variant => SymbolKind::ENUM_MEMBER,
217                    DefinitionKind::Theorem => SymbolKind::CLASS,
218                    DefinitionKind::Block => SymbolKind::NAMESPACE,
219                    // A component is the unit a page is built from — the workspace-wide search
220                    // for "Card" should find the card, exactly as it finds a struct.
221                    DefinitionKind::Component => SymbolKind::CLASS,
222                    DefinitionKind::Action => SymbolKind::METHOD,
223                    DefinitionKind::StateField => SymbolKind::PROPERTY,
224                    DefinitionKind::Variable | DefinitionKind::Parameter => return None,
225                };
226                Some(WorkspaceSymbol {
227                    name: def.name.clone(),
228                    kind,
229                    container: def.detail.clone(),
230                    location: Location {
231                        uri: uri.clone(),
232                        range: Range {
233                            start: line_index.position(def.span.start),
234                            end: line_index.position(def.span.end),
235                        },
236                    },
237                })
238            })
239            .collect();
240
241        let references = analysis
242            .symbol_index
243            .references
244            .iter()
245            .map(|reference| FileReference {
246                name: reference.name.clone(),
247                range: Range {
248                    start: line_index.position(reference.span.start),
249                    end: line_index.position(reference.span.end),
250                },
251                resolved_locally: reference.definition_idx.is_some(),
252            })
253            .collect();
254
255        let imports = logicaffeine_language::analysis::scan_dependencies(&source);
256
257        self.files.insert(uri.clone(), symbols);
258        self.refs.insert(uri.clone(), references);
259        self.imports.insert(uri, imports);
260    }
261
262    pub fn remove(&self, uri: &Url) {
263        self.files.remove(uri);
264        self.refs.remove(uri);
265        self.imports.remove(uri);
266    }
267
268    /// Every module that publicly exports `name` (a function/type/variant).
269    pub fn module_exporting(&self, name: &str) -> Vec<ModuleExport> {
270        let mut out = Vec::new();
271        for entry in self.files.iter() {
272            let exports_it = entry.value().iter().any(|s| {
273                s.name == name
274                    && matches!(
275                        s.kind,
276                        SymbolKind::FUNCTION
277                            | SymbolKind::STRUCT
278                            | SymbolKind::ENUM
279                            | SymbolKind::ENUM_MEMBER
280                    )
281            });
282            if exports_it {
283                if let Some(alias) = module_alias_from_url(entry.key()) {
284                    out.push(ModuleExport {
285                        module_url: entry.key().clone(),
286                        module_name: alias,
287                    });
288                }
289            }
290        }
291        out.sort_by(|a, b| a.module_name.cmp(&b.module_name));
292        out
293    }
294
295    /// The module aliases the file at `uri` imports.
296    pub fn imports_of(&self, uri: &Url) -> Vec<String> {
297        self.imports
298            .get(uri)
299            .map(|v| v.iter().map(|d| d.alias.clone()).collect())
300            .unwrap_or_default()
301    }
302
303    /// The exact symbol labels to complete for this file's imports, paired with
304    /// the module they come from. A SELECTIVE `Import double from Util.` offers
305    /// only `double` (or its `as` alias); a whole-module `Import Util.` offers
306    /// every public export of Util — so completion never suggests a name the
307    /// import didn't actually bring into scope.
308    pub fn imported_symbols(&self, uri: &Url) -> Vec<(String, String)> {
309        let module_urls: std::collections::HashMap<String, Url> =
310            self.module_names().into_iter().collect();
311        let mut out = Vec::new();
312        let Some(deps) = self.imports.get(uri) else {
313            return out;
314        };
315        for dep in deps.iter() {
316            match &dep.selection {
317                Some(selection) => {
318                    for s in selection {
319                        let label = s.alias.clone().unwrap_or_else(|| s.name.clone());
320                        out.push((label, dep.alias.clone()));
321                    }
322                }
323                None => {
324                    if let Some(url) = module_urls.get(&dep.alias) {
325                        for name in self.exports_of(url) {
326                            out.push((name, dep.alias.clone()));
327                        }
328                    }
329                }
330            }
331        }
332        out
333    }
334
335    /// The public names the module at `uri` exports (function/type/variant).
336    pub fn exports_of(&self, uri: &Url) -> Vec<String> {
337        self.files
338            .get(uri)
339            .map(|symbols| {
340                symbols
341                    .iter()
342                    .filter(|s| {
343                        matches!(
344                            s.kind,
345                            SymbolKind::FUNCTION
346                                | SymbolKind::STRUCT
347                                | SymbolKind::ENUM
348                                | SymbolKind::ENUM_MEMBER
349                        )
350                    })
351                    .map(|s| s.name.clone())
352                    .collect()
353            })
354            .unwrap_or_default()
355    }
356
357    /// Every indexed module: its import alias and file Url.
358    pub fn module_names(&self) -> Vec<(String, Url)> {
359        let mut out: Vec<(String, Url)> = self
360            .files
361            .iter()
362            .filter_map(|e| module_alias_from_url(e.key()).map(|a| (a, e.key().clone())))
363            .collect();
364        out.sort();
365        out.dedup();
366        out
367    }
368
369    /// Does this file define `name` as workspace-visible API shape?
370    fn defines(&self, uri: &Url, name: &str) -> bool {
371        self.files
372            .get(uri)
373            .map(|symbols| symbols.iter().any(|s| s.name == name))
374            .unwrap_or(false)
375    }
376
377    /// Every cross-file occurrence of `name` outside `skip` (the URIs whose
378    /// LIVE buffers answer for themselves). A file's occurrence counts when
379    /// its own scope did NOT resolve it (so it reaches across files), or when
380    /// the file itself defines the symbol (its local uses ARE the symbol).
381    pub fn references_of(&self, name: &str, skip: &[&Url]) -> Vec<Location> {
382        let mut locations = Vec::new();
383        for entry in self.refs.iter() {
384            let uri = entry.key();
385            if skip.contains(&uri) {
386                continue;
387            }
388            let file_defines = self.defines(uri, name);
389            for reference in entry.value() {
390                if reference.name == name && (!reference.resolved_locally || file_defines) {
391                    locations.push(Location {
392                        uri: uri.clone(),
393                        range: reference.range,
394                    });
395                }
396            }
397        }
398        locations
399    }
400
401    /// Case-insensitive substring query across the workspace.
402    pub fn query(&self, needle: &str, limit: usize) -> Vec<WorkspaceSymbol> {
403        let needle = needle.to_lowercase();
404        let mut hits = Vec::new();
405        for entry in self.files.iter() {
406            for symbol in entry.value() {
407                if needle.is_empty() || symbol.name.to_lowercase().contains(&needle) {
408                    hits.push(WorkspaceSymbol {
409                        name: symbol.name.clone(),
410                        kind: symbol.kind,
411                        container: symbol.container.clone(),
412                        location: symbol.location.clone(),
413                    });
414                    if hits.len() >= limit {
415                        return hits;
416                    }
417                }
418            }
419        }
420        hits
421    }
422
423    /// The definition location for an exact name, for cross-file goto-def.
424    /// Callable (function) and type-like definitions win over incidental
425    /// name matches in other kinds.
426    pub fn definition_of(&self, name: &str) -> Option<Location> {
427        let mut fallback = None;
428        for entry in self.files.iter() {
429            for symbol in entry.value() {
430                if symbol.name != name {
431                    continue;
432                }
433                match symbol.kind {
434                    SymbolKind::FUNCTION | SymbolKind::STRUCT | SymbolKind::ENUM => {
435                        return Some(symbol.location.clone());
436                    }
437                    _ => fallback = Some(symbol.location.clone()),
438                }
439            }
440        }
441        fallback
442    }
443}
444
445impl WorkspaceView for WorkspaceIndex {
446    fn module_exporting(&self, name: &str) -> Vec<ModuleExport> {
447        WorkspaceIndex::module_exporting(self, name)
448    }
449    fn imports_of(&self, uri: &Url) -> Vec<String> {
450        WorkspaceIndex::imports_of(self, uri)
451    }
452    fn module_names(&self) -> Vec<(String, Url)> {
453        WorkspaceIndex::module_names(self)
454    }
455    fn exports_of(&self, uri: &Url) -> Vec<String> {
456        WorkspaceIndex::exports_of(self, uri)
457    }
458    fn imported_symbols(&self, uri: &Url) -> Vec<(String, String)> {
459        WorkspaceIndex::imported_symbols(self, uri)
460    }
461}
462
463#[cfg(test)]
464#[path = "../../logicaffeine_tests/unit/logicaffeine_lsp/workspace/tests.rs"]
465mod tests;