syster-base 0.2.3-alpha

Core library for SysML v2 and KerML parsing, AST, and semantic analysis
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
//! AnalysisHost and Analysis — Unified state management for IDE features.
//!
//! The `AnalysisHost` owns all mutable state and provides `Analysis` snapshots
//! for querying. This pattern ensures consistent reads across multiple queries.
//!
//! ## Usage
//!
//! ```ignore
//! let mut host = AnalysisHost::new();
//!
//! // Apply file changes
//! host.set_file_content(file_id, content);
//!
//! // Get a snapshot for queries
//! let analysis = host.analysis();
//! let hover = analysis.hover(file_id, line, col);
//! let symbols = analysis.document_symbols(file_id);
//! ```

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

use crate::base::FileId;
use crate::hir::{SymbolIndex, extract_with_filters};
use crate::syntax::SyntaxFile;

use super::{
    CompletionItem, DocumentLink, FoldingRange, GotoResult, HoverResult, InlayHint,
    ReferenceResult, SelectionRange, SemanticToken, SymbolInfo,
};

/// Owns all mutable state for the IDE layer.
///
/// Apply changes via `set_file_content()` and `remove_file()`,
/// then get a consistent snapshot via `analysis()`.
#[derive(Clone)]
pub struct AnalysisHost {
    /// Parsed files stored directly (no Workspace dependency)
    files: HashMap<PathBuf, SyntaxFile>,
    /// HIR-based symbol index built from parsed files
    symbol_index: SymbolIndex,
    /// Map from file path to FileId
    file_id_map: HashMap<String, FileId>,
    /// Reverse map from FileId to file path
    file_path_map: HashMap<FileId, String>,
    /// Whether the index needs rebuilding
    index_dirty: bool,
    /// Persistent cache: qualified_name → element_id
    /// Preserves IDs even when symbols are temporarily removed
    element_id_cache: HashMap<Arc<str>, Arc<str>>,
}

impl Default for AnalysisHost {
    fn default() -> Self {
        Self::new()
    }
}

impl AnalysisHost {
    /// Create a new empty AnalysisHost.
    pub fn new() -> Self {
        Self {
            files: HashMap::new(),
            symbol_index: SymbolIndex::new(),
            file_id_map: HashMap::new(),
            file_path_map: HashMap::new(),
            index_dirty: false,
            element_id_cache: HashMap::new(),
        }
    }

    /// Set the content of a file, parsing it and storing the result.
    ///
    /// Returns parse errors if any.
    pub fn set_file_content(
        &mut self,
        path: &str,
        content: &str,
    ) -> Vec<crate::parser::ParseError> {
        use crate::syntax::parser::parse_with_result;
        use std::path::Path;

        let path_buf = PathBuf::from(path);

        // Parse the content
        let result = parse_with_result(content, Path::new(path));

        if let Some(syntax_file) = result.content {
            self.files.insert(path_buf, syntax_file);
        }

        self.index_dirty = true;
        result.errors
    }

    /// Remove a file from storage.
    pub fn remove_file(&mut self, path: &str) {
        let path_buf = PathBuf::from(path);
        self.files.remove(&path_buf);
        self.index_dirty = true;
    }

    /// Remove a file from storage using PathBuf.
    pub fn remove_file_path(&mut self, path: &PathBuf) {
        self.files.remove(path);
        self.index_dirty = true;
    }

    /// Check if a file exists in storage.
    pub fn has_file(&self, path: &str) -> bool {
        let path_buf = PathBuf::from(path);
        self.files.contains_key(&path_buf)
    }

    /// Check if a file exists in storage using Path.
    pub fn has_file_path(&self, path: &std::path::Path) -> bool {
        self.files.contains_key(path)
    }

    /// Update or add a file with pre-parsed content.
    /// Used when caller already has parsed SyntaxFile.
    pub fn set_file(&mut self, path: PathBuf, file: SyntaxFile) {
        self.files.insert(path, file);
        self.index_dirty = true;
    }

    /// Get access to the parsed files.
    pub fn files(&self) -> &HashMap<PathBuf, SyntaxFile> {
        &self.files
    }

    /// Get the number of files loaded.
    pub fn file_count(&self) -> usize {
        self.files.len()
    }

    /// Mark the index as needing rebuild (call after external changes).
    pub fn mark_dirty(&mut self) {
        self.index_dirty = true;
    }

    /// Rebuild the symbol index from the current files.
    ///
    /// This is called automatically by `analysis()` if the index is dirty.
    /// Element IDs are preserved for symbols with matching qualified names,
    /// using a persistent cache that survives symbol removal.
    pub fn rebuild_index(&mut self) {
        // First, update cache with all current symbols' IDs
        for symbol in self.symbol_index.all_symbols() {
            if !symbol.element_id.as_ref().is_empty()
                && !symbol.element_id.starts_with("00000000-0000-0000-0000")
            {
                self.element_id_cache
                    .insert(symbol.qualified_name.clone(), symbol.element_id.clone());
            }
        }

        // Build file ID map from file paths
        self.file_id_map.clear();
        self.file_path_map.clear();

        // Reserve FileId(0) for imported symbols (XMI, etc.)
        let imported_file_id = FileId::new(0);

        for (i, path) in self.files.keys().enumerate() {
            let path_str = path.to_string_lossy().to_string();
            // Start from 1 to avoid collision with imported symbols
            let file_id = FileId::new((i + 1) as u32);
            self.file_id_map.insert(path_str.clone(), file_id);
            self.file_path_map.insert(file_id, path_str);
        }

        // Build symbol index directly from parsed files
        let mut new_index = SymbolIndex::new();

        // First, preserve imported symbols from FileId(0)
        let imported_symbols: Vec<_> = self
            .symbol_index
            .symbols_in_file(imported_file_id)
            .into_iter()
            .cloned()
            .collect();
        if !imported_symbols.is_empty() {
            new_index.add_file(imported_file_id, imported_symbols);
        }

        for (path, syntax_file) in &self.files {
            let path_str = path.to_string_lossy().to_string();
            if let Some(&file_id) = self.file_id_map.get(&path_str) {
                // Extract symbols and filters using unified extraction (handles both SysML and KerML)
                let mut result = extract_with_filters(file_id, syntax_file);
                
                // Preserve element IDs from cache (survives removal/re-add)
                for symbol in &mut result.symbols {
                    if let Some(cached_id) = self.element_id_cache.get(&symbol.qualified_name) {
                        symbol.element_id = cached_id.clone();
                    }
                }
                
                new_index.add_extraction_result(file_id, result);
            }
        }

        // Build visibility maps for import resolution
        new_index.ensure_visibility_maps();

        // Resolve all type references (pre-compute resolved_target)
        new_index.resolve_all_type_refs();

        self.symbol_index = new_index;
        self.index_dirty = false;
    }

    /// Get a consistent snapshot for querying.
    ///
    /// If the index is dirty, it will be rebuilt first.
    pub fn analysis(&mut self) -> Analysis<'_> {
        if self.index_dirty {
            self.rebuild_index();
        }

        Analysis {
            symbol_index: &self.symbol_index,
            file_id_map: &self.file_id_map,
            file_path_map: &self.file_path_map,
        }
    }

    /// Get the FileId for a path, if it exists.
    pub fn get_file_id(&self, path: &str) -> Option<FileId> {
        self.file_id_map.get(path).copied()
    }

    /// Get the FileId for a PathBuf, if it exists.
    pub fn get_file_id_for_path(&self, path: &std::path::Path) -> Option<FileId> {
        self.file_id_map
            .get(&path.to_string_lossy().to_string())
            .copied()
    }

    /// Get the path for a FileId, if it exists.
    pub fn get_file_path(&self, file_id: FileId) -> Option<&str> {
        self.file_path_map.get(&file_id).map(|s| s.as_str())
    }

    /// Get the path as PathBuf for a FileId, if it exists.
    pub fn get_file_path_buf(&self, file_id: FileId) -> Option<PathBuf> {
        self.file_path_map.get(&file_id).map(PathBuf::from)
    }

    /// Get the file_id_map (for compatibility during migration).
    pub fn file_id_map(&self) -> &HashMap<String, FileId> {
        &self.file_id_map
    }

    /// Get the symbol_index (for compatibility during migration).
    pub fn symbol_index(&self) -> &SymbolIndex {
        &self.symbol_index
    }

    /// Apply a function to all symbols in the index.
    ///
    /// Used to update symbol properties (like element_id) after loading metadata.
    pub fn update_symbols<F>(&mut self, f: F)
    where
        F: FnMut(&mut crate::hir::HirSymbol),
    {
        self.symbol_index.update_all_symbols(f);
    }

    /// Add symbols from an interchange Model (XMI, KPAR, etc.) to the host.
    ///
    /// This is used for importing models directly without text round-trip.
    /// The symbols' element IDs are preserved from the Model.
    ///
    /// All symbols are assigned to a synthetic FileId(0) since they don't come from text files.
    #[cfg(feature = "interchange")]
    pub fn add_symbols_from_model(&mut self, symbols: Vec<crate::hir::HirSymbol>) {
        use crate::base::FileId;

        // Use a synthetic file ID for imported symbols
        let synthetic_file = FileId::new(0);

        // Add to cache for persistence
        for symbol in &symbols {
            if !symbol.element_id.as_ref().is_empty() {
                self.element_id_cache
                    .insert(symbol.qualified_name.clone(), symbol.element_id.clone());
            }
        }

        // Add all symbols at once
        self.symbol_index.add_file(synthetic_file, symbols);
        self.index_dirty = false; // Symbols already extracted
    }
}

/// An immutable snapshot of the analysis state.
///
/// All IDE queries go through this struct to ensure consistent results.
pub struct Analysis<'a> {
    symbol_index: &'a SymbolIndex,
    file_id_map: &'a HashMap<String, FileId>,
    file_path_map: &'a HashMap<FileId, String>,
}

impl<'a> Analysis<'a> {
    // ==================== Symbol-based features ====================

    /// Get hover information at a position.
    pub fn hover(&self, file_id: FileId, line: u32, col: u32) -> Option<HoverResult> {
        super::hover(self.symbol_index, file_id, line, col)
    }

    /// Get type information at a position.
    ///
    /// Returns info if cursor is on a type annotation (`:`, `:>`, `::>`, etc.).
    pub fn type_info_at(&self, file_id: FileId, line: u32, col: u32) -> Option<super::TypeInfo> {
        super::type_info_at(self.symbol_index, file_id, line, col)
    }

    /// Go to definition at a position.
    pub fn goto_definition(&self, file_id: FileId, line: u32, col: u32) -> GotoResult {
        super::goto_definition(self.symbol_index, file_id, line, col)
    }

    /// Go to type definition at a position.
    ///
    /// Navigates from a usage to its type definition (e.g., from `engine : Engine` to `part def Engine`).
    pub fn goto_type_definition(&self, file_id: FileId, line: u32, col: u32) -> GotoResult {
        super::goto_type_definition(self.symbol_index, file_id, line, col)
    }

    /// Find all references to a symbol at a position.
    pub fn find_references(
        &self,
        file_id: FileId,
        line: u32,
        col: u32,
        include_declaration: bool,
    ) -> ReferenceResult {
        super::find_references(self.symbol_index, file_id, line, col, include_declaration)
    }

    /// Get completions at a position.
    pub fn completions(
        &self,
        file_id: FileId,
        line: u32,
        col: u32,
        trigger: Option<char>,
    ) -> Vec<CompletionItem> {
        super::completions(self.symbol_index, file_id, line, col, trigger)
    }

    /// Get all symbols in a document.
    pub fn document_symbols(&self, file_id: FileId) -> Vec<SymbolInfo> {
        super::document_symbols(self.symbol_index, file_id)
    }

    /// Search for symbols across the workspace.
    pub fn workspace_symbols(&self, query: Option<&str>) -> Vec<SymbolInfo> {
        super::workspace_symbols(self.symbol_index, query)
    }

    /// Get document links (import paths, etc.).
    pub fn document_links(&self, file_id: FileId) -> Vec<DocumentLink> {
        super::document_links(self.symbol_index, file_id)
    }

    // ==================== AST-based features ====================

    /// Get folding ranges for a file.
    pub fn folding_ranges(&self, file_id: FileId) -> Vec<FoldingRange> {
        super::folding_ranges(self.symbol_index, file_id)
    }

    /// Get selection ranges at positions.
    pub fn selection_ranges(&self, file_id: FileId, line: u32, col: u32) -> Vec<SelectionRange> {
        super::selection_ranges(self.symbol_index, file_id, line, col)
    }

    /// Get inlay hints for a file (optionally within a range).
    pub fn inlay_hints(
        &self,
        file_id: FileId,
        range: Option<(u32, u32, u32, u32)>,
    ) -> Vec<InlayHint> {
        super::inlay_hints(self.symbol_index, file_id, range)
    }

    /// Get semantic tokens for a file.
    pub fn semantic_tokens(&self, file_id: FileId) -> Vec<SemanticToken> {
        super::semantic_tokens(self.symbol_index, file_id)
    }

    // ==================== Accessors ====================

    /// Get the symbol index.
    pub fn symbol_index(&self) -> &SymbolIndex {
        self.symbol_index
    }

    /// Get the file ID map.
    pub fn file_id_map(&self) -> &HashMap<String, FileId> {
        self.file_id_map
    }

    /// Get the file path for a FileId.
    pub fn get_file_path(&self, file_id: FileId) -> Option<&str> {
        self.file_path_map.get(&file_id).map(|s| s.as_str())
    }

    /// Get the FileId for a path.
    pub fn get_file_id(&self, path: &str) -> Option<FileId> {
        self.file_id_map.get(path).copied()
    }
}

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

    #[test]
    fn test_analysis_host_basic() {
        let mut host = AnalysisHost::new();

        // Add a file
        let errors = host.set_file_content("test.sysml", "package Test {}");
        assert!(errors.is_empty());

        // Get analysis
        let analysis = host.analysis();

        // Should have the file
        assert!(analysis.get_file_id("test.sysml").is_some());
    }

    #[test]
    fn test_file_removal() {
        let mut host = AnalysisHost::new();

        // Add and remove a file
        host.set_file_content("test.sysml", "package Test {}");
        host.remove_file("test.sysml");

        let analysis = host.analysis();
        assert!(analysis.get_file_id("test.sysml").is_none());
    }
}