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
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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
use crate::{
    CompletionItem, Diagnostic, Judge, Position, Range, Severity, Symbol, SymbolKind,
};
use ra_ap_base_db::{
    CrateGraph, CrateOrigin, Env, SourceDatabase, SourceDatabaseFileInputExt, SourceRoot,
    SourceRootDatabase,
};
use ra_ap_ide::{Analysis, AnalysisHost, Edition as IdeEdition, FilePosition};
use ra_ap_ide_db::base_db::salsa::Durability;
use ra_ap_syntax::{
    ast::{self, HasName},
    AstNode, Edition, SourceFile, SyntaxKind, TextRange, TextSize,
};
use ra_ap_vfs::{file_set::FileSet, FileId, VfsPath};
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::PathBuf;
use triomphe::Arc;

pub struct RustJudge {
    /// Optional project root for semantic analysis
    #[allow(dead_code)]
    project_root: Option<PathBuf>,
    /// Persistent analysis host for semantic analysis
    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 RustJudge {
    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 {
            project_root: None,
            host: RefCell::new(AnalysisHost::default()),
            file_ids: RefCell::new(HashMap::new()),
            next_file_id: RefCell::new(0),
            has_workspace: false,
        }
    }

    /// Create a RustJudge with a project root for semantic analysis
    pub fn with_project(project_root: PathBuf) -> Self {
        if let Ok(judge) = Self::with_workspace(&project_root) {
            return judge;
        }

        Self {
            project_root: Some(project_root),
            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 {
                    project_root: Some(project_path.to_path_buf()),
                    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);
                Err(format!("Failed to load workspace: {:?}", e))
            }
        }
    }

    fn text_range_to_position(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 }
    }

    fn text_range_to_range(source: &str, range: TextRange) -> Range {
        Range {
            start: Self::text_range_to_position(source, range.start()),
            end: Self::text_range_to_position(source, range.end()),
        }
    }

    /// Extract the word prefix at the cursor position
    pub fn extract_word_prefix(source: &str, position: Position) -> String {
        let lines: Vec<&str> = source.lines().collect();

        if position.line >= lines.len() {
            return String::new();
        }

        let line = lines[position.line];
        if position.column > line.len() {
            return String::new();
        }

        // Find the start of the current word by going backwards from cursor
        let mut start = position.column;
        let chars: Vec<char> = line.chars().collect();

        while start > 0 {
            let prev_char = chars.get(start - 1);
            match prev_char {
                Some(c) if c.is_alphanumeric() || *c == '_' => {
                    start -= 1;
                }
                _ => break,
            }
        }

        // Extract the prefix
        chars
            .iter()
            .skip(start)
            .take(position.column - start)
            .collect()
    }

    /// 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();

                // 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,
                    IdeEdition::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
    }

    /// Get syntax-based completions as fallback
    fn syntax_completions(
        &self,
        source: &str,
        position: Position,
    ) -> Result<Vec<CompletionItem>, String> {
        // Extract the word prefix being typed at the cursor position
        let prefix = Self::extract_word_prefix(source, position);

        let mut all_items = Vec::new();

        // First, add symbols from the current file (functions, structs, etc.)
        if let Ok(symbols) = self.symbols(source) {
            for symbol in symbols {
                all_items.push(CompletionItem {
                    label: symbol.name.clone(),
                    kind: symbol.kind,
                    detail: symbol.detail.clone(),
                    documentation: Some(format!(
                        "Defined at line {}",
                        symbol.range.start.line + 1
                    )),
                });
            }
        }

        // Then add keyword completions
        all_items.extend(self.get_keyword_completions());

        // Filter based on prefix (case-insensitive for better UX)
        if !prefix.is_empty() {
            all_items.retain(|item| item.label.starts_with(&prefix));
        }

        Ok(all_items)
    }

    /// Get all keyword completions
    fn get_keyword_completions(&self) -> Vec<CompletionItem> {
        vec![
            CompletionItem {
                label: "fn".to_string(),
                kind: SymbolKind::Function,
                detail: Some("fn name() {}".to_string()),
                documentation: Some("Function declaration".to_string()),
            },
            CompletionItem {
                label: "struct".to_string(),
                kind: SymbolKind::Struct,
                detail: Some("struct Name {}".to_string()),
                documentation: Some("Struct declaration".to_string()),
            },
            CompletionItem {
                label: "enum".to_string(),
                kind: SymbolKind::Enum,
                detail: Some("enum Name {}".to_string()),
                documentation: Some("Enum declaration".to_string()),
            },
            CompletionItem {
                label: "impl".to_string(),
                kind: SymbolKind::Impl,
                detail: Some("impl Type {}".to_string()),
                documentation: Some("Implementation block".to_string()),
            },
            CompletionItem {
                label: "trait".to_string(),
                kind: SymbolKind::Trait,
                detail: Some("trait Name {}".to_string()),
                documentation: Some("Trait declaration".to_string()),
            },
            CompletionItem {
                label: "mod".to_string(),
                kind: SymbolKind::Module,
                detail: Some("mod name {}".to_string()),
                documentation: Some("Module declaration".to_string()),
            },
            CompletionItem {
                label: "const".to_string(),
                kind: SymbolKind::Const,
                detail: Some("const NAME: Type = value;".to_string()),
                documentation: Some("Constant declaration".to_string()),
            },
            CompletionItem {
                label: "static".to_string(),
                kind: SymbolKind::Static,
                detail: Some("static NAME: Type = value;".to_string()),
                documentation: Some("Static variable declaration".to_string()),
            },
            CompletionItem {
                label: "type".to_string(),
                kind: SymbolKind::Type,
                detail: Some("type Name = Type;".to_string()),
                documentation: Some("Type alias".to_string()),
            },
            CompletionItem {
                label: "let".to_string(),
                kind: SymbolKind::Variable,
                detail: Some("let name = value;".to_string()),
                documentation: Some("Variable binding".to_string()),
            },
            CompletionItem {
                label: "mut".to_string(),
                kind: SymbolKind::Variable,
                detail: Some("mut".to_string()),
                documentation: Some("Mutable binding".to_string()),
            },
            CompletionItem {
                label: "pub".to_string(),
                kind: SymbolKind::Module,
                detail: Some("pub".to_string()),
                documentation: Some("Public visibility".to_string()),
            },
            CompletionItem {
                label: "use".to_string(),
                kind: SymbolKind::Module,
                detail: Some("use path::to::item;".to_string()),
                documentation: Some("Import items".to_string()),
            },
            CompletionItem {
                label: "if".to_string(),
                kind: SymbolKind::Function,
                detail: Some("if condition {}".to_string()),
                documentation: Some("Conditional".to_string()),
            },
            CompletionItem {
                label: "else".to_string(),
                kind: SymbolKind::Function,
                detail: Some("else {}".to_string()),
                documentation: Some("Else clause".to_string()),
            },
            CompletionItem {
                label: "match".to_string(),
                kind: SymbolKind::Function,
                detail: Some("match value {}".to_string()),
                documentation: Some("Pattern matching".to_string()),
            },
            CompletionItem {
                label: "for".to_string(),
                kind: SymbolKind::Function,
                detail: Some("for item in iter {}".to_string()),
                documentation: Some("For loop".to_string()),
            },
            CompletionItem {
                label: "while".to_string(),
                kind: SymbolKind::Function,
                detail: Some("while condition {}".to_string()),
                documentation: Some("While loop".to_string()),
            },
            CompletionItem {
                label: "loop".to_string(),
                kind: SymbolKind::Function,
                detail: Some("loop {}".to_string()),
                documentation: Some("Infinite loop".to_string()),
            },
            CompletionItem {
                label: "return".to_string(),
                kind: SymbolKind::Function,
                detail: Some("return value;".to_string()),
                documentation: Some("Return from function".to_string()),
            },
            // Common macros
            CompletionItem {
                label: "println!".to_string(),
                kind: SymbolKind::Function,
                detail: Some("println!(...)".to_string()),
                documentation: Some("Print to stdout with newline".to_string()),
            },
            CompletionItem {
                label: "print!".to_string(),
                kind: SymbolKind::Function,
                detail: Some("print!(...)".to_string()),
                documentation: Some("Print to stdout".to_string()),
            },
            CompletionItem {
                label: "format!".to_string(),
                kind: SymbolKind::Function,
                detail: Some("format!(...)".to_string()),
                documentation: Some("Format string".to_string()),
            },
            CompletionItem {
                label: "vec!".to_string(),
                kind: SymbolKind::Function,
                detail: Some("vec![...]".to_string()),
                documentation: Some("Create a vector".to_string()),
            },
            CompletionItem {
                label: "assert!".to_string(),
                kind: SymbolKind::Function,
                detail: Some("assert!(...)".to_string()),
                documentation: Some("Assert condition".to_string()),
            },
            CompletionItem {
                label: "panic!".to_string(),
                kind: SymbolKind::Function,
                detail: Some("panic!(...)".to_string()),
                documentation: Some("Panic with a message".to_string()),
            },
            // Common types
            CompletionItem {
                label: "String".to_string(),
                kind: SymbolKind::Struct,
                detail: Some("String".to_string()),
                documentation: Some("Heap-allocated string".to_string()),
            },
            CompletionItem {
                label: "Vec".to_string(),
                kind: SymbolKind::Struct,
                detail: Some("Vec<T>".to_string()),
                documentation: Some("Growable array".to_string()),
            },
            CompletionItem {
                label: "Option".to_string(),
                kind: SymbolKind::Enum,
                detail: Some("Option<T>".to_string()),
                documentation: Some("Optional value".to_string()),
            },
            CompletionItem {
                label: "Result".to_string(),
                kind: SymbolKind::Enum,
                detail: Some("Result<T, E>".to_string()),
                documentation: Some("Result of an operation".to_string()),
            },
            CompletionItem {
                label: "Some".to_string(),
                kind: SymbolKind::Enum,
                detail: Some("Some(value)".to_string()),
                documentation: Some("Option variant with value".to_string()),
            },
            CompletionItem {
                label: "None".to_string(),
                kind: SymbolKind::Enum,
                detail: Some("None".to_string()),
                documentation: Some("Option variant without value".to_string()),
            },
            CompletionItem {
                label: "Ok".to_string(),
                kind: SymbolKind::Enum,
                detail: Some("Ok(value)".to_string()),
                documentation: Some("Result success variant".to_string()),
            },
            CompletionItem {
                label: "Err".to_string(),
                kind: SymbolKind::Enum,
                detail: Some("Err(error)".to_string()),
                documentation: Some("Result error variant".to_string()),
            },
            CompletionItem {
                label: "Self".to_string(),
                kind: SymbolKind::Type,
                detail: Some("Self".to_string()),
                documentation: Some("Type alias for current type".to_string()),
            },
            CompletionItem {
                label: "self".to_string(),
                kind: SymbolKind::Variable,
                detail: Some("self".to_string()),
                documentation: Some("Current instance".to_string()),
            },
        ]
    }
}

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

impl Judge for RustJudge {
    fn diagnostics(&self, source: &str) -> Vec<Diagnostic> {
        let parse = SourceFile::parse(source, Edition::CURRENT);
        let mut diagnostics = Vec::new();

        // Collect syntax errors
        for error in parse.errors() {
            let range = error.range();
            diagnostics.push(Diagnostic {
                severity: Severity::Error,
                message: error.to_string(),
                range: Some(Self::text_range_to_range(source, range)),
            });
        }

        diagnostics
    }

    fn symbols(&self, source: &str) -> Result<Vec<Symbol>, String> {
        let parse = SourceFile::parse(source, Edition::CURRENT);
        let root = parse.syntax_node();
        let mut symbols = Vec::new();

        // Walk the syntax tree and find all items
        for node in root.descendants() {
            match node.kind() {
                SyntaxKind::FN => {
                    if let Some(func) = ast::Fn::cast(node.clone()) {
                        if let Some(name) = func.name() {
                            let range = name.syntax().text_range();

                            // Build function signature
                            let params = if let Some(param_list) = func.param_list() {
                                param_list.to_string()
                            } else {
                                "()".to_string()
                            };

                            let ret_type = if let Some(ret) = func.ret_type() {
                                format!(" {}", ret)
                            } else {
                                String::new()
                            };

                            symbols.push(Symbol {
                                kind: SymbolKind::Function,
                                name: name.to_string(),
                                range: Self::text_range_to_range(source, range),
                                detail: Some(format!(
                                    "fn {}{}{}",
                                    name, params, ret_type
                                )),
                            });
                        }
                    }
                }
                SyntaxKind::STRUCT => {
                    if let Some(s) = ast::Struct::cast(node.clone()) {
                        if let Some(name) = s.name() {
                            let range = name.syntax().text_range();
                            symbols.push(Symbol {
                                kind: SymbolKind::Struct,
                                name: name.to_string(),
                                range: Self::text_range_to_range(source, range),
                                detail: Some(format!("struct {}", name)),
                            });
                        }
                    }
                }
                SyntaxKind::ENUM => {
                    if let Some(e) = ast::Enum::cast(node.clone()) {
                        if let Some(name) = e.name() {
                            let range = name.syntax().text_range();
                            symbols.push(Symbol {
                                kind: SymbolKind::Enum,
                                name: name.to_string(),
                                range: Self::text_range_to_range(source, range),
                                detail: Some(format!("enum {}", name)),
                            });
                        }
                    }
                }
                SyntaxKind::TRAIT => {
                    if let Some(t) = ast::Trait::cast(node.clone()) {
                        if let Some(name) = t.name() {
                            let range = name.syntax().text_range();
                            symbols.push(Symbol {
                                kind: SymbolKind::Trait,
                                name: name.to_string(),
                                range: Self::text_range_to_range(source, range),
                                detail: Some(format!("trait {}", name)),
                            });
                        }
                    }
                }
                SyntaxKind::MODULE => {
                    if let Some(m) = ast::Module::cast(node.clone()) {
                        if let Some(name) = m.name() {
                            let range = name.syntax().text_range();
                            symbols.push(Symbol {
                                kind: SymbolKind::Module,
                                name: name.to_string(),
                                range: Self::text_range_to_range(source, range),
                                detail: Some(format!("mod {}", name)),
                            });
                        }
                    }
                }
                SyntaxKind::CONST => {
                    if let Some(c) = ast::Const::cast(node.clone()) {
                        if let Some(name) = c.name() {
                            let range = name.syntax().text_range();

                            let ty = if let Some(ty) = c.ty() {
                                format!(": {}", ty)
                            } else {
                                String::new()
                            };

                            symbols.push(Symbol {
                                kind: SymbolKind::Const,
                                name: name.to_string(),
                                range: Self::text_range_to_range(source, range),
                                detail: Some(format!("const {}{}", name, ty)),
                            });
                        }
                    }
                }
                SyntaxKind::STATIC => {
                    if let Some(s) = ast::Static::cast(node.clone()) {
                        if let Some(name) = s.name() {
                            let range = name.syntax().text_range();

                            let ty = if let Some(ty) = s.ty() {
                                format!(": {}", ty)
                            } else {
                                String::new()
                            };

                            symbols.push(Symbol {
                                kind: SymbolKind::Static,
                                name: name.to_string(),
                                range: Self::text_range_to_range(source, range),
                                detail: Some(format!("static {}{}", name, ty)),
                            });
                        }
                    }
                }
                SyntaxKind::TYPE_ALIAS => {
                    if let Some(t) = ast::TypeAlias::cast(node.clone()) {
                        if let Some(name) = t.name() {
                            let range = name.syntax().text_range();

                            let ty = if let Some(ty) = t.ty() {
                                format!(" = {}", ty)
                            } else {
                                String::new()
                            };

                            symbols.push(Symbol {
                                kind: SymbolKind::Type,
                                name: name.to_string(),
                                range: Self::text_range_to_range(source, range),
                                detail: Some(format!("type {}{}", name, ty)),
                            });
                        }
                    }
                }
                SyntaxKind::IMPL => {
                    if let Some(i) = ast::Impl::cast(node.clone()) {
                        if let Some(self_ty) = i.self_ty() {
                            let type_name = self_ty.to_string();
                            let range = self_ty.syntax().text_range();

                            let trait_name = if let Some(trait_ref) = i.trait_() {
                                format!("{} for ", trait_ref)
                            } else {
                                String::new()
                            };

                            symbols.push(Symbol {
                                kind: SymbolKind::Impl,
                                name: format!("impl {}{}", trait_name, type_name),
                                range: Self::text_range_to_range(source, range),
                                detail: Some(format!("impl {}{}", trait_name, type_name)),
                            });
                        }
                    }
                }
                SyntaxKind::MACRO_RULES => {
                    if let Some(m) = ast::MacroRules::cast(node.clone()) {
                        if let Some(name) = m.name() {
                            let range = name.syntax().text_range();
                            symbols.push(Symbol {
                                kind: SymbolKind::Macro,
                                name: name.to_string(),
                                range: Self::text_range_to_range(source, range),
                                detail: Some(format!("macro_rules! {}", name)),
                            });
                        }
                    }
                }
                _ => {}
            }
        }

        Ok(symbols)
    }

    fn symbol_at_position(
        &self,
        source: &str,
        position: Position,
    ) -> Result<Option<Symbol>, String> {
        let symbols = self.symbols(source)?;

        Ok(symbols.into_iter().find(|sym| {
            position.line >= sym.range.start.line
                && position.line <= sym.range.end.line
                && (position.line > sym.range.start.line
                    || position.column >= sym.range.start.column)
                && (position.line < sym.range.end.line
                    || position.column <= sym.range.end.column)
        }))
    }

    fn completions(
        &self,
        source: &str,
        position: Position,
    ) -> Result<Vec<CompletionItem>, String> {
        // Extract the prefix being typed for filtering
        let prefix = Self::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 => SymbolKind::Function,
                                ra_ap_ide::SymbolKind::Struct => SymbolKind::Struct,
                                ra_ap_ide::SymbolKind::Enum => SymbolKind::Enum,
                                ra_ap_ide::SymbolKind::Trait => SymbolKind::Trait,
                                ra_ap_ide::SymbolKind::Module => SymbolKind::Module,
                                ra_ap_ide::SymbolKind::Const => SymbolKind::Const,
                                ra_ap_ide::SymbolKind::Static => SymbolKind::Static,
                                ra_ap_ide::SymbolKind::TypeAlias => SymbolKind::Type,
                                _ => SymbolKind::Variable,
                            },
                            _ => SymbolKind::Variable,
                        };

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

                    Ok::<Vec<CompletionItem>, String>(items)
                }
                None => Ok::<Vec<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 syntax-based completions
                    self.syntax_completions(source, position)
                }
            }
            Ok(Err(_)) | Err(_) => {
                // Error or panic from rust-analyzer
                // Fall back to syntax-based completions which work reliably
                self.syntax_completions(source, position)
            }
        }
    }

    fn format(&self, source: &str) -> Result<String, String> {
        // Validate syntax
        let parse = SourceFile::parse(source, Edition::CURRENT);
        if !parse.errors().is_empty() {
            return Err(format!("Syntax errors: {:?}", parse.errors()));
        }

        // For actual formatting, we'd use rustfmt
        // For now, just return the source if it's valid
        Ok(source.to_string())
    }
}

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

    #[test]
    fn test_parse_valid_rust() {
        let judge = RustJudge::new();
        let source = r#"
            fn main() {
                println!("Hello, world!");
            }
        "#;

        let diagnostics = judge.diagnostics(source);
        assert!(diagnostics.is_empty());
    }

    #[test]
    fn test_parse_invalid_rust() {
        let judge = RustJudge::new();
        let source = r#"
            fn main( {
                println!("Hello, world!");
            }
        "#;

        let diagnostics = judge.diagnostics(source);
        assert!(!diagnostics.is_empty());
        assert_eq!(diagnostics[0].severity, Severity::Error);
    }

    #[test]
    fn test_find_symbols() {
        let judge = RustJudge::new();
        let source = r#"
            struct Foo;

            fn bar() {}

            trait Baz {}
        "#;

        let symbols = judge.symbols(source).unwrap();
        assert_eq!(symbols.len(), 3);

        assert_eq!(symbols[0].kind, SymbolKind::Struct);
        assert_eq!(symbols[0].name, "Foo");

        assert_eq!(symbols[1].kind, SymbolKind::Function);
        assert_eq!(symbols[1].name, "bar");

        assert_eq!(symbols[2].kind, SymbolKind::Trait);
        assert_eq!(symbols[2].name, "Baz");
    }

    #[test]
    fn test_function_with_types() {
        let judge = RustJudge::new();
        let source = r#"
            fn greet(name: &str) -> String {
                format!("Hello, {}!", name)
            }
        "#;

        let symbols = judge.symbols(source).unwrap();
        assert_eq!(symbols.len(), 1);
        assert_eq!(symbols[0].kind, SymbolKind::Function);
        assert_eq!(symbols[0].name, "greet");
        assert!(symbols[0].detail.as_ref().unwrap().contains("name"));
    }

    #[test]
    fn test_struct_with_impl() {
        let judge = RustJudge::new();
        let source = r#"
            struct Person {
                name: String,
            }

            impl Person {
                fn new(name: String) -> Self {
                    Self { name }
                }
            }
        "#;

        let symbols = judge.symbols(source).unwrap();
        assert!(symbols
            .iter()
            .any(|s| s.kind == SymbolKind::Struct && s.name == "Person"));
        assert!(symbols.iter().any(|s| s.kind == SymbolKind::Impl));
        assert!(symbols
            .iter()
            .any(|s| s.kind == SymbolKind::Function && s.name == "new"));
    }
}