1use 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#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct ModuleExport {
22 pub module_url: Url,
24 pub module_name: String,
26}
27
28pub trait WorkspaceView {
31 fn module_exporting(&self, name: &str) -> Vec<ModuleExport>;
33 fn imports_of(&self, uri: &Url) -> Vec<String>;
35 fn module_names(&self) -> Vec<(String, Url)>;
37 fn exports_of(&self, _uri: &Url) -> Vec<String> {
40 Vec::new()
41 }
42 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 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
69pub 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
81pub 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
92pub 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
101const 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
113pub struct FileReference {
115 pub name: String,
116 pub range: Range,
117 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 imports: DashMap<Url, Vec<logicaffeine_language::analysis::Dependency>>,
130}
131
132impl WorkspaceIndex {
133 pub fn new() -> Self {
134 Self::default()
135 }
136
137 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 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 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 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 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 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 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 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 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 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 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 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 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 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;