nocturne 0.0.1

Code analyzer
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
use crate::{
    HoverInfo, Position, Range, Reference, SemanticJudge, SignatureHelp, TypeInfo,
};
use ra_ap_base_db::{
    CrateGraph, CrateOrigin, Env, SourceDatabase, SourceDatabaseFileInputExt, SourceRoot,
    SourceRootDatabase,
};
use ra_ap_ide::{
    Analysis, AnalysisHost, Edition, FilePosition, FileRange, HoverConfig, HoverDocFormat,
};
use ra_ap_ide_db::base_db::salsa::Durability;
use ra_ap_syntax::TextSize;
use ra_ap_vfs::{file_set::FileSet, FileId, VfsPath};
use std::cell::RefCell;
use std::collections::HashMap;
use triomphe::Arc;

use super::rust::RustJudge;

/// Semantic analyzer that provides type information and cross-reference analysis
pub struct SemanticRustJudge {
    base: RustJudge,
    /// Persistent analysis host with interior mutability
    host: RefCell<AnalysisHost>,
    /// Track file IDs for synchronization
    file_ids: RefCell<HashMap<String, FileId>>,
    /// Counter for generating new file IDs
    next_file_id: RefCell<u32>,
    /// Track if workspace is loaded
    has_workspace: bool,
}

impl SemanticRustJudge {
    pub fn new() -> Self {
        // Try to load workspace from current directory
        let current_dir = std::env::current_dir().ok();
        if let Some(dir) = current_dir {
            // Check if there's a Cargo.toml in current directory or parent
            if let Ok(judge) = Self::with_workspace(&dir) {
                return judge;
            }
        }

        // Fall back to minimal setup
        Self {
            base: RustJudge::new(),
            host: RefCell::new(AnalysisHost::default()),
            file_ids: RefCell::new(HashMap::new()),
            next_file_id: RefCell::new(0),
            has_workspace: false,
        }
    }

    /// Create a new instance with workspace data loaded from a Cargo project
    pub fn with_workspace(project_path: &std::path::Path) -> Result<Self, String> {
        use ra_ap_load_cargo::{
            load_workspace_at, LoadCargoConfig, ProcMacroServerChoice,
        };
        use ra_ap_project_model::CargoConfig;

        // Try to load the Cargo workspace
        let cargo_config = CargoConfig::default();
        let load_config = LoadCargoConfig {
            load_out_dirs_from_check: true,
            with_proc_macro_server: ProcMacroServerChoice::Sysroot,
            prefill_caches: false,
        };

        match load_workspace_at(project_path, &cargo_config, &load_config, &|_| {}) {
            Ok((db, _vfs, _proc_macro)) => {
                // Create an AnalysisHost from the loaded database
                let host = AnalysisHost::with_database(db);
                Ok(Self {
                    base: RustJudge::new(),
                    host: RefCell::new(host),
                    file_ids: RefCell::new(HashMap::new()),
                    next_file_id: RefCell::new(0),
                    has_workspace: true,
                })
            }
            Err(e) => {
                // If workspace loading fails, fall back to simple mode
                eprintln!("Warning: Failed to load Cargo workspace: {:?}", e);
                Ok(Self::new())
            }
        }
    }

    /// Update or create a file in the analysis host
    fn update_file(&self, file_path: &str, source: &str) -> Result<FileId, String> {
        let mut file_ids = self.file_ids.borrow_mut();
        let mut host = self.host.borrow_mut();

        // Get or create file ID
        let file_id = if let Some(&existing_id) = file_ids.get(file_path) {
            existing_id
        } else {
            // Generate new file ID
            let mut next_id = self.next_file_id.borrow_mut();
            let file_id = FileId::from_raw(*next_id);
            *next_id += 1;
            file_ids.insert(file_path.to_string(), file_id);

            // Add to VFS if not in workspace
            if !self.has_workspace {
                let db = host.raw_database_mut();
                let vfs_path = VfsPath::new_virtual_path(file_path.to_string());

                // Create or update source root
                let source_root_id = ra_ap_base_db::SourceRootId(0);
                let mut file_set = FileSet::default();

                // Add all existing files
                for (path, &id) in file_ids.iter() {
                    file_set.insert(id, VfsPath::new_virtual_path(path.clone()));
                }

                let source_root = SourceRoot::new_local(file_set);
                db.set_source_root_with_durability(
                    source_root_id,
                    Arc::new(source_root),
                    Durability::HIGH,
                );

                db.set_file_source_root_with_durability(
                    file_id,
                    source_root_id,
                    Durability::HIGH,
                );
            }

            file_id
        };

        // Update file content
        let db = host.raw_database_mut();
        db.set_file_text_with_durability(file_id, source, Durability::HIGH);

        Ok(file_id)
    }

    /// Create an analysis instance for a source string
    fn create_analysis(&self, source: &str) -> Result<(Analysis, FileId), String> {
        // Use the persistent host instead of creating a new one
        let file_id = self.update_file("/main.rs", source)?;

        // If workspace not loaded, set up minimal crate graph (only once)
        if !self.has_workspace {
            let file_ids = self.file_ids.borrow();
            // Only set up crate graph if this is the first file
            if file_ids.len() == 1 {
                let mut host = self.host.borrow_mut();
                let db = host.raw_database_mut();

                // Create minimal crate graph
                let mut crate_graph = CrateGraph::default();
                crate_graph.add_crate_root(
                    file_id,
                    Edition::Edition2021,
                    None,
                    None,
                    Arc::new(ra_ap_hir::CfgOptions::default()),
                    Some(Arc::new(ra_ap_hir::CfgOptions::default())),
                    Env::default(),
                    false,
                    CrateOrigin::Local {
                        repo: None,
                        name: None,
                    },
                );

                db.set_crate_graph_with_durability(
                    Arc::new(crate_graph),
                    Durability::HIGH,
                );
            }
        }

        // Return analysis from the persistent host
        let host = self.host.borrow();
        Ok((host.analysis(), file_id))
    }

    fn position_to_offset(&self, source: &str, position: Position) -> Option<TextSize> {
        let mut current_line = 0;
        let mut current_col = 0;

        for (idx, ch) in source.chars().enumerate() {
            if current_line == position.line && current_col == position.column {
                return Some(TextSize::from(idx as u32));
            }

            if ch == '\n' {
                current_line += 1;
                current_col = 0;
            } else {
                current_col += 1;
            }
        }

        None
    }

    fn text_size_to_position(&self, source: &str, offset: TextSize) -> Position {
        let offset_usize = usize::from(offset);
        let mut line = 0;
        let mut column = 0;

        for (idx, ch) in source.chars().enumerate() {
            if idx >= offset_usize {
                break;
            }
            if ch == '\n' {
                line += 1;
                column = 0;
            } else {
                column += 1;
            }
        }

        Position { line, column }
    }
}

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

// Delegate basic Judge methods to the base RustJudge
impl crate::Judge for SemanticRustJudge {
    fn diagnostics(&self, source: &str) -> Vec<crate::Diagnostic> {
        self.base.diagnostics(source)
    }

    fn symbols(&self, source: &str) -> Result<Vec<crate::Symbol>, String> {
        self.base.symbols(source)
    }

    fn symbol_at_position(
        &self,
        source: &str,
        position: Position,
    ) -> Result<Option<crate::Symbol>, String> {
        self.base.symbol_at_position(source, position)
    }

    fn completions(
        &self,
        source: &str,
        position: Position,
    ) -> Result<Vec<crate::CompletionItem>, String> {
        // Extract the prefix being typed for filtering
        let prefix = RustJudge::extract_word_prefix(source, position);

        // Wrap entire rust-analyzer operation in panic catching
        // The CrateWorkspaceDataQuery can panic anywhere in the call chain
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            // Try rust-analyzer semantic completions
            let (analysis, file_id) = self.create_analysis(source)?;

            let offset = self
                .position_to_offset(source, position)
                .ok_or_else(|| "Invalid position".to_string())?;

            let file_position = FilePosition { file_id, offset };

            // Get completions from rust-analyzer
            let config = ra_ap_ide::CompletionConfig {
                enable_postfix_completions: true,
                enable_imports_on_the_fly: false,
                enable_self_on_the_fly: true,
                enable_private_editable: false,
                add_semicolon_to_unit: false,
                enable_term_search: false,
                full_function_signatures: false,
                callable: None,
                snippet_cap: None,
                prefer_no_std: false,
                prefer_prelude: true,
                prefer_absolute: false,
                limit: None,
                term_search_fuel: 400,
                insert_use: ra_ap_ide_db::imports::insert_use::InsertUseConfig {
                    granularity:
                        ra_ap_ide_db::imports::insert_use::ImportGranularity::Crate,
                    enforce_granularity: true,
                    prefix_kind: ra_ap_ide_db::imports::insert_use::PrefixKind::Plain,
                    group: true,
                    skip_glob_imports: true,
                },
                snippets: Vec::new(),
            };

            let completions = analysis
                .completions(&config, file_position, None)
                .map_err(|e| format!("Completion analysis cancelled: {:?}", e))?;

            match completions {
                Some(completions) => {
                    let mut items = Vec::new();

                    for item in completions {
                        // Convert rust-analyzer completion to our format
                        let kind = match item.kind {
                            ra_ap_ide::CompletionItemKind::SymbolKind(sk) => match sk {
                                ra_ap_ide::SymbolKind::Function => {
                                    crate::SymbolKind::Function
                                }
                                ra_ap_ide::SymbolKind::Struct => {
                                    crate::SymbolKind::Struct
                                }
                                ra_ap_ide::SymbolKind::Enum => crate::SymbolKind::Enum,
                                ra_ap_ide::SymbolKind::Trait => crate::SymbolKind::Trait,
                                ra_ap_ide::SymbolKind::Module => {
                                    crate::SymbolKind::Module
                                }
                                ra_ap_ide::SymbolKind::Const => crate::SymbolKind::Const,
                                ra_ap_ide::SymbolKind::Static => {
                                    crate::SymbolKind::Static
                                }
                                ra_ap_ide::SymbolKind::TypeAlias => {
                                    crate::SymbolKind::Type
                                }
                                _ => crate::SymbolKind::Variable,
                            },
                            _ => crate::SymbolKind::Variable,
                        };

                        items.push(crate::CompletionItem {
                            label: item.label.to_string(),
                            kind,
                            detail: item.detail.map(|d| d.to_string()),
                            documentation: item.documentation.map(|d| format!("{:?}", d)),
                        });
                    }

                    Ok::<Vec<crate::CompletionItem>, String>(items)
                }
                None => Ok::<Vec<crate::CompletionItem>, String>(Vec::new()),
            }
        }));

        // Handle the result
        match result {
            Ok(Ok(mut items)) => {
                // Filter by prefix for fuzzy matching
                if !prefix.is_empty() {
                    items.retain(|item| {
                        item.label
                            .to_lowercase()
                            .starts_with(&prefix.to_lowercase())
                    });
                }

                // If we got semantic completions, use them (even if filtered to empty)
                // This prevents showing irrelevant base completions when RA has context
                if !items.is_empty() {
                    Ok(items)
                } else {
                    // Rust-analyzer returned nothing matching the prefix
                    // Fall back to base completions
                    self.base.completions(source, position)
                }
            }
            Ok(Err(_)) | Err(_) => {
                // Error or panic from rust-analyzer
                // Fall back to base completions which work reliably
                self.base.completions(source, position)
            }
        }
    }

    fn format(&self, source: &str) -> Result<String, String> {
        self.base.format(source)
    }
}

impl SemanticJudge for SemanticRustJudge {
    fn hover(
        &self,
        source: &str,
        position: Position,
    ) -> Result<Option<HoverInfo>, String> {
        let (analysis, file_id) = self.create_analysis(source)?;

        let offset = self
            .position_to_offset(source, position)
            .ok_or_else(|| "Invalid position".to_string())?;

        let file_range = FileRange {
            file_id,
            range: ra_ap_syntax::TextRange::new(offset, offset),
        };

        let hover_config = HoverConfig {
            links_in_hover: true,
            memory_layout: None,
            documentation: true,
            keywords: true,
            format: HoverDocFormat::Markdown,
            max_trait_assoc_items_count: None,
            max_fields_count: None,
            max_enum_variants_count: None,
        };

        match analysis.hover(&hover_config, file_range) {
            Ok(Some(hover_result)) => {
                let range_start =
                    self.text_size_to_position(source, hover_result.range.start());
                let range_end =
                    self.text_size_to_position(source, hover_result.range.end());

                Ok(Some(HoverInfo {
                    range: Range {
                        start: range_start,
                        end: range_end,
                    },
                    contents: hover_result.info.markup.as_str().to_string(),
                    type_info: None,
                }))
            }
            Ok(None) => Ok(None),
            Err(e) => Err(format!("Hover analysis failed: {}", e)),
        }
    }

    fn type_at_position(
        &self,
        source: &str,
        position: Position,
    ) -> Result<Option<TypeInfo>, String> {
        self.hover(source, position).map(|opt| {
            opt.map(|hover| TypeInfo {
                name: hover.contents.clone(),
                full_name: hover.contents,
                documentation: None,
            })
        })
    }

    fn find_references(
        &self,
        source: &str,
        position: Position,
    ) -> Result<Vec<Reference>, String> {
        let (analysis, file_id) = self.create_analysis(source)?;

        let offset = self
            .position_to_offset(source, position)
            .ok_or_else(|| "Invalid position".to_string())?;

        let file_pos = FilePosition { file_id, offset };

        match analysis.find_all_refs(file_pos, None) {
            Ok(Some(refs_vec)) => {
                let mut references = Vec::new();

                for ref_result in refs_vec {
                    // Add declaration
                    if let Some(decl) = ref_result.declaration {
                        let start = self.text_size_to_position(
                            source,
                            decl.nav.focus_range.unwrap_or(decl.nav.full_range).start(),
                        );
                        let end = self.text_size_to_position(
                            source,
                            decl.nav.focus_range.unwrap_or(decl.nav.full_range).end(),
                        );

                        references.push(Reference {
                            range: Range { start, end },
                            is_definition: true,
                        });
                    }

                    // Add references
                    for (_file_id, ranges) in ref_result.references {
                        for (range, _category) in ranges {
                            let start = self.text_size_to_position(source, range.start());
                            let end = self.text_size_to_position(source, range.end());

                            references.push(Reference {
                                range: Range { start, end },
                                is_definition: false,
                            });
                        }
                    }
                }

                Ok(references)
            }
            Ok(None) => Ok(Vec::new()),
            Err(e) => Err(format!("Find references failed: {}", e)),
        }
    }

    fn goto_definition(
        &self,
        source: &str,
        position: Position,
    ) -> Result<Option<Range>, String> {
        let (analysis, file_id) = self.create_analysis(source)?;

        let offset = self
            .position_to_offset(source, position)
            .ok_or_else(|| "Invalid position".to_string())?;

        let file_pos = FilePosition { file_id, offset };

        match analysis.goto_definition(file_pos) {
            Ok(Some(nav_targets)) => {
                if let Some(target) = nav_targets.info.first() {
                    let start = self.text_size_to_position(
                        source,
                        target.focus_range.unwrap_or(target.full_range).start(),
                    );
                    let end = self.text_size_to_position(
                        source,
                        target.focus_range.unwrap_or(target.full_range).end(),
                    );

                    Ok(Some(Range { start, end }))
                } else {
                    Ok(None)
                }
            }
            Ok(None) => Ok(None),
            Err(e) => Err(format!("Go to definition failed: {}", e)),
        }
    }

    fn signature_help(
        &self,
        source: &str,
        position: Position,
    ) -> Result<Option<SignatureHelp>, String> {
        let (analysis, file_id) = self.create_analysis(source)?;

        let offset = self
            .position_to_offset(source, position)
            .ok_or_else(|| "Invalid position".to_string())?;

        let file_pos = FilePosition { file_id, offset };

        match analysis.signature_help(file_pos) {
            Ok(Some(sig_help)) => {
                // The SignatureHelp struct has private fields, so we extract what we can
                Ok(Some(SignatureHelp {
                    label: sig_help.signature.clone(),
                    documentation: sig_help.doc.as_ref().map(|d| d.as_str().to_string()),
                    parameters: Vec::new(), // Parameters are private, would need to parse from signature
                    active_parameter: sig_help.active_parameter.map(|i| i as usize),
                }))
            }
            Ok(None) => Ok(None),
            Err(e) => Err(format!("Signature help failed: {}", e)),
        }
    }

    fn infer_type(
        &self,
        source: &str,
        position: Position,
    ) -> Result<Option<String>, String> {
        self.type_at_position(source, position)
            .map(|opt| opt.map(|ti| ti.name))
    }
}