surrealql-language-server 0.3.0

Language Server Protocol implementation for SurrealQL
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
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
//! The transport-agnostic language server.
//!
//! [`LanguageServerCore`] owns every piece of mutable state plus the
//! complete LSP request/notification handling logic. The native
//! `Backend` and the WASM `WasmLanguageServer` are thin adapters: they
//! receive transport-specific input (tower-lsp invocations or
//! JSON-RPC strings handed in from JavaScript), call the equivalent
//! method here, and return whatever the core produces.
//!
//! The three trait-bound generics [`LspNotifier`], [`WorkspaceLoader`]
//! and [`MetadataProvider`] keep this module ignorant of how
//! diagnostics are actually shipped, where `.surql` files come from,
//! and how live SurrealDB metadata is fetched. See
//! [`crate::core::client`] for the trait definitions and
//! [`crate::native`] / [`crate::wasm`] for the per-target impls.

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

use ls_types::*;

use crate::config::ServerSettings;
use crate::core::client::{LspNotifier, MetadataProvider, WorkspaceLoader};
use crate::core::completion_context::{
    ColumnSlot, active_query_fact, column_completion_context, completion_prefix,
    completion_table_qualifier, is_table_name_context,
};
use crate::core::state::{ServerState, merged_workspace, workspace_signature};
use crate::grammar::{BuiltinFunction, builtin_function};
use crate::runtime;
use crate::semantic::analyzer::analyze_document;
use crate::semantic::model::{field_completion_tables, is_record_type_context};
use crate::semantic::text::{position_to_offset, token_at, word_range};
use crate::semantic::types::{
    DocumentAnalysis, FunctionDef, LiveMetadataSnapshot, MergedSemanticModel, SymbolOrigin,
    WorkspaceIndex,
};

/// Hosting-agnostic language server. Generic over the three boundary
/// traits so that a native (tower-lsp + walkdir + surrealdb) and a
/// browser (wasm-bindgen) front-end can share every line of business
/// logic.
pub struct LanguageServerCore<N: LspNotifier, W: WorkspaceLoader, M: MetadataProvider> {
    notifier: Arc<N>,
    workspace_loader: Arc<W>,
    metadata_provider: Arc<M>,
    state: Arc<runtime::sync::RwLock<ServerState>>,
    /// Serializes every settings/metadata application (the native
    /// adapter spawns `didChangeConfiguration` / `didSave` handlers,
    /// so two read-merge-apply sequences would otherwise interleave
    /// and lose updates or invert the metadata-error status).
    config_lock: Arc<runtime::sync::Mutex<()>>,
}

impl<N, W, M> LanguageServerCore<N, W, M>
where
    N: LspNotifier,
    W: WorkspaceLoader,
    M: MetadataProvider,
{
    pub fn new(notifier: N, workspace_loader: W, metadata_provider: M) -> Self {
        Self {
            notifier: Arc::new(notifier),
            workspace_loader: Arc::new(workspace_loader),
            metadata_provider: Arc::new(metadata_provider),
            state: Arc::new(runtime::sync::RwLock::new(ServerState::default())),
            config_lock: Arc::new(runtime::sync::Mutex::new(())),
        }
    }

    /// Borrow the outbound notifier (used by the native adapter to
    /// drive `did_save`/`did_change_configuration` background tasks).
    pub fn notifier(&self) -> &Arc<N> {
        &self.notifier
    }

    /// LSP capability advertisement, identical for both targets.
    pub fn server_capabilities() -> ServerCapabilities {
        ServerCapabilities {
            text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::FULL)),
            completion_provider: Some(CompletionOptions {
                resolve_provider: Some(false),
                trigger_characters: Some(vec![
                    ".".into(),
                    ":".into(),
                    "<".into(),
                    "$".into(),
                    "(".into(),
                ]),
                ..CompletionOptions::default()
            }),
            hover_provider: Some(HoverProviderCapability::Simple(true)),
            definition_provider: Some(OneOf::Left(true)),
            references_provider: Some(OneOf::Left(true)),
            rename_provider: Some(OneOf::Right(RenameOptions {
                prepare_provider: Some(true),
                work_done_progress_options: Default::default(),
            })),
            signature_help_provider: Some(SignatureHelpOptions {
                trigger_characters: Some(vec!["(".into(), ",".into()]),
                retrigger_characters: Some(vec![",".into()]),
                work_done_progress_options: Default::default(),
            }),
            code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
            document_highlight_provider: Some(OneOf::Left(true)),
            inlay_hint_provider: Some(OneOf::Right(InlayHintServerCapabilities::Options(
                InlayHintOptions {
                    resolve_provider: Some(false),
                    ..InlayHintOptions::default()
                },
            ))),
            call_hierarchy_provider: Some(CallHierarchyServerCapability::Simple(true)),
            semantic_tokens_provider: Some(
                SemanticTokensServerCapabilities::SemanticTokensOptions(SemanticTokensOptions {
                    legend: crate::semantic::highlight::legend(),
                    full: Some(SemanticTokensFullOptions::Bool(true)),
                    range: Some(true),
                    work_done_progress_options: Default::default(),
                }),
            ),
            document_symbol_provider: Some(OneOf::Left(true)),
            workspace_symbol_provider: Some(OneOf::Left(true)),
            workspace: Some(WorkspaceServerCapabilities {
                workspace_folders: Some(WorkspaceFoldersServerCapabilities {
                    supported: Some(true),
                    change_notifications: Some(OneOf::Left(true)),
                }),
                file_operations: None,
            }),
            ..ServerCapabilities::default()
        }
    }

    // ──────────────────────────────────────────────────────────────────
    // Lifecycle
    // ──────────────────────────────────────────────────────────────────

    /// Stash the client-supplied initialization options + workspace
    /// folders. The heavy work (workspace walk, live metadata fetch) is
    /// deferred to [`Self::apply_settings`], usually triggered by
    /// `initialized → reload_from_client_configuration`.
    pub async fn initialize(&self, params: InitializeParams) -> InitializeResult {
        let (settings, warnings) = ServerSettings::from_sources_with_warnings(
            params.initialization_options.as_ref(),
            None,
        );
        let workspace_folders = resolve_workspace_folders(&params);

        {
            let mut state = self.state.write().await;
            state.settings = Arc::new(settings);
            state.workspace_folders = workspace_folders;
            // The client can't receive `window/logMessage` until the
            // initialize handshake completes; `initialized` drains these.
            state.pending_settings_warnings = warnings;
        }

        InitializeResult {
            server_info: Some(ServerInfo {
                name: "surreal-language-server".to_string(),
                version: Some(env!("CARGO_PKG_VERSION").to_string()),
            }),
            capabilities: Self::server_capabilities(),
            ..Default::default()
        }
    }

    /// Pull the latest configuration from the client and re-run
    /// [`Self::apply_settings`]. Logs an info message on completion.
    pub async fn initialized(&self) {
        let pending_warnings = {
            let mut state = self.state.write().await;
            std::mem::take(&mut state.pending_settings_warnings)
        };
        self.report_settings_warnings(&pending_warnings).await;
        self.reload_from_client_configuration().await;
        self.notifier
            .log_message(
                MessageType::INFO,
                "SurrealQL semantic language server ready".to_string(),
            )
            .await;
    }

    /// Asks the client for the `surrealql` configuration section
    /// (`workspace/configuration`), merges the response with whatever
    /// settings are already in flight, and applies the result.
    pub async fn reload_from_client_configuration(&self) {
        // Ask the client before taking the config lock — a slow
        // configuration pull must not stall other settings work.
        let configuration = self.notifier.request_configuration().await;
        let (settings, warnings) =
            ServerSettings::from_sources_with_warnings(None, configuration.as_ref());
        // A client without configuration support answers `None`, and
        // VS Code / Neovim answer the pull with JSON `null` when no
        // `surrealql` section is configured — both always yield zero
        // warnings. Reporting those would reset the dedup signature
        // and fire a spurious "resolved" line right after the
        // initialize-stashed warnings. (A *real* clean section does
        // report: it replaces the previous settings, so its empty
        // warning set genuinely resolves them.)
        if configuration.as_ref().is_some_and(|value| !value.is_null()) {
            self.report_settings_warnings(&warnings).await;
        }

        let _guard = self.config_lock.lock().await;
        let current_settings = {
            let state = self.state.read().await;
            (*state.settings).clone()
        };
        let settings = settings.merge_with_env_if_missing(current_settings);
        self.apply_settings_inner(settings).await;
    }

    /// Log settings warnings, once per *distinct* warning set — a
    /// persistently misconfigured editor would otherwise re-log the
    /// same lines on every configuration pull and `didChange`. Same
    /// pattern as [`Self::report_metadata_errors`]: the state lock is
    /// released before any notifier await.
    async fn report_settings_warnings(&self, warnings: &[String]) {
        let mut signature = warnings.to_vec();
        signature.sort();

        let previous = {
            let mut state = self.state.write().await;
            state.last_settings_warnings.replace(signature.clone())
        };

        if previous.as_ref() == Some(&signature) {
            return;
        }

        if signature.is_empty() {
            if previous.is_some_and(|previous| !previous.is_empty()) {
                self.notifier
                    .log_message(
                        MessageType::INFO,
                        "SurrealQL settings: previous warnings resolved".to_string(),
                    )
                    .await;
            }
            return;
        }

        for warning in warnings {
            self.notifier
                .log_message(
                    MessageType::WARNING,
                    format!("SurrealQL settings: {warning}"),
                )
                .await;
        }
    }

    /// Persist new settings, re-load the saved workspace, refresh live
    /// metadata, rebuild the merged model, and republish diagnostics
    /// for every open document.
    ///
    /// Native callers wrap this in `tokio::spawn` so notification
    /// handlers return immediately. WASM callers `await` it directly
    /// — there is no advantage to background scheduling on a
    /// single-threaded event loop.
    pub async fn apply_settings(&self, settings: ServerSettings) {
        let _guard = self.config_lock.lock().await;
        self.apply_settings_inner(settings).await;
    }

    /// [`Self::apply_settings`] body; callers must hold `config_lock`.
    async fn apply_settings_inner(&self, settings: ServerSettings) {
        let (workspace_folders, last_walked) = {
            let mut state = self.state.write().await;
            state.settings = Arc::new(settings.clone());
            (state.workspace_folders.clone(), state.last_walked.clone())
        };

        let folder_signature = workspace_signature(&workspace_folders);
        let need_walk = last_walked
            .as_ref()
            .map(|previous| previous != &folder_signature)
            .unwrap_or(true);

        let saved_workspace = if settings.metadata.filesystem_enabled() {
            if need_walk {
                Arc::new(self.workspace_loader.load(&workspace_folders).await)
            } else {
                let s = self.state.read().await;
                Arc::clone(&s.saved_workspace)
            }
        } else {
            self.state.write().await.last_walked = None;
            Arc::new(Default::default())
        };

        let live_metadata = Arc::new(self.metadata_provider.fetch(&settings).await);
        self.report_metadata_errors(&live_metadata).await;
        if need_walk {
            self.report_scan_stats(&saved_workspace).await;
        }
        let (open_documents, uris_for_diag) = {
            let s = self.state.read().await;
            (
                s.open_documents.clone(),
                s.open_documents.keys().cloned().collect::<Vec<_>>(),
            )
        };
        let workspace = merged_workspace(&saved_workspace, &open_documents);
        let model = Arc::new(MergedSemanticModel::build(&workspace, &live_metadata));

        {
            let mut state = self.state.write().await;
            state.saved_workspace = Arc::clone(&saved_workspace);
            state.live_metadata = Arc::clone(&live_metadata);
            state.model = Arc::clone(&model);
            if need_walk {
                state.last_walked = Some(folder_signature);
            }
        }

        let saved_for_diag = saved_workspace;
        let model_for_diag = model;
        let settings_for_diag = Arc::new(settings);
        for uri in uris_for_diag {
            let analysis = open_documents
                .get(&uri)
                .cloned()
                .or_else(|| saved_for_diag.documents.get(&uri).cloned());
            if let Some(analysis) = analysis {
                let mut diagnostics = analysis.syntax_diagnostics.clone();
                diagnostics
                    .extend(model_for_diag.semantic_diagnostics(&analysis, &settings_for_diag));
                self.notifier.publish_diagnostics(uri, diagnostics).await;
            }
        }
    }

    // ──────────────────────────────────────────────────────────────────
    // Document lifecycle
    // ──────────────────────────────────────────────────────────────────

    pub async fn did_open(&self, params: DidOpenTextDocumentParams) {
        let document = params.text_document;
        self.upsert_open_document(document.uri, document.text).await;
    }

    pub async fn did_change(&self, params: DidChangeTextDocumentParams) {
        let Some(change) = params.content_changes.into_iter().last() else {
            return;
        };
        self.upsert_open_document(params.text_document.uri, change.text)
            .await;
    }

    pub async fn did_save(&self, params: DidSaveTextDocumentParams) {
        let (refresh_remote, uri) = {
            let state = self.state.read().await;
            (
                state.settings.metadata.refresh_on_save,
                params.text_document.uri.clone(),
            )
        };
        self.sync_saved_document_from_disk(&uri).await;
        self.recompute_model().await;
        if refresh_remote {
            self.refresh_remote_metadata_if_needed().await;
        }
        self.publish_diagnostics_for_uri(&uri).await;
    }

    pub async fn did_close(&self, params: DidCloseTextDocumentParams) {
        let uri = params.text_document.uri;
        {
            let mut state = self.state.write().await;
            state.open_documents.remove(&uri);
        }
        self.sync_saved_document_from_disk(&uri).await;
        self.recompute_model().await;
        self.notifier.publish_diagnostics(uri, Vec::new()).await;
    }

    pub async fn did_change_configuration(&self, params: DidChangeConfigurationParams) {
        // Clients that support configuration pulls send `null` here as
        // a "something changed, ask me" signal.
        if params.settings.is_null() {
            self.reload_from_client_configuration().await;
            return;
        }

        // Merge over the in-flight settings — a partial payload (e.g.
        // one that only carries `metadata.*`) must not wipe the
        // connection details that arrived via initializationOptions.
        // The read-merge-apply sequence runs under the config lock so
        // two spawned configuration changes can't lose each other's
        // updates.
        let (settings, warnings) =
            ServerSettings::from_sources_with_warnings(None, Some(&params.settings));
        self.report_settings_warnings(&warnings).await;

        let _guard = self.config_lock.lock().await;
        let current_settings = {
            let state = self.state.read().await;
            (*state.settings).clone()
        };
        let settings = settings.merge_with_env_if_missing(current_settings);
        self.apply_settings_inner(settings).await;
    }

    pub async fn did_change_workspace_folders(&self, params: DidChangeWorkspaceFoldersParams) {
        {
            let mut state = self.state.write().await;
            for removed in params.event.removed {
                if let Some(path) = removed.uri.to_file_path() {
                    let path = path.into_owned();
                    state.workspace_folders.retain(|folder| folder != &path);
                }
            }
            for added in params.event.added {
                if let Some(path) = added.uri.to_file_path() {
                    let path = path.into_owned();
                    if !state.workspace_folders.contains(&path) {
                        state.workspace_folders.push(path);
                    }
                }
            }
        }

        let settings = {
            let state = self.state.read().await;
            (*state.settings).clone()
        };
        self.apply_settings(settings).await;
    }

    /// Re-run the workspace loader and rebuild the merged model
    /// without touching settings or live metadata. The WASM adapter
    /// uses this after the host pushes / drops a saved document so
    /// the change is reflected immediately.
    pub async fn reload_workspace(&self) {
        let folders = {
            let state = self.state.read().await;
            state.workspace_folders.clone()
        };
        let workspace = Arc::new(self.workspace_loader.load(&folders).await);
        self.report_scan_stats(&workspace).await;
        {
            let mut state = self.state.write().await;
            state.saved_workspace = workspace;
        }
        self.recompute_model().await;
        self.republish_open_diagnostics().await;
    }

    /// Replace the current live metadata snapshot. Used by the WASM
    /// target so Surrealist can push DEFINE strings over from its
    /// already-open SurrealDB connection.
    pub async fn replace_live_metadata(
        &self,
        snapshot: crate::semantic::types::LiveMetadataSnapshot,
    ) {
        {
            let mut state = self.state.write().await;
            state.live_metadata = Arc::new(snapshot);
        }
        self.recompute_model().await;
        self.republish_open_diagnostics().await;
    }

    // ──────────────────────────────────────────────────────────────────
    // Per-request handlers
    // ──────────────────────────────────────────────────────────────────

    pub async fn completion(&self, params: CompletionParams) -> Option<CompletionResponse> {
        let uri = params.text_document_position.text_document.uri;
        let position = params.text_document_position.position;
        let (analysis, model, settings) = self.snapshot_for_uri(&uri).await?;

        let record_type_context = is_record_type_context(&analysis.text, position);
        let prefix = completion_prefix(&analysis.text, position, record_type_context);

        // When the cursor sits in a slot that only accepts a table name
        // (e.g. `SELECT * FROM |`, `INSERT INTO |`, `UPDATE |`), restrict
        // suggestions to known tables — otherwise the dropdown is flooded
        // with keywords/functions/fields/params the user can't legally use
        // there.
        if !record_type_context && is_table_name_context(&analysis.text, position) {
            let items = model.table_completion_items(
                prefix.trim_matches(|ch: char| ch == ':'),
                settings.active_auth_context(),
            );
            return Some(CompletionResponse::Array(items));
        }

        let statement_fact = active_query_fact(&analysis, position);
        let qualifier = completion_table_qualifier(&analysis.text, position);
        let trimmed_prefix = prefix.trim_matches(|ch: char| ch == ':');

        // Decide whether the cursor is in a column-name slot. A `tbl.`
        // qualifier is always treated as a strict slot (the only legal
        // continuations are field names of `tbl`).
        let column_slot = if qualifier.is_some() {
            Some(ColumnSlot::Strict { allow_star: false })
        } else if record_type_context {
            None
        } else {
            column_completion_context(&analysis.text, position)
        };

        if let Some(ColumnSlot::Strict { allow_star }) = column_slot {
            let field_tables = field_completion_tables(statement_fact, qualifier.as_deref());
            if !field_tables.is_empty() {
                let multi_table_context = qualifier.is_none() && field_tables.len() > 1;
                let mut items = model.column_completion_items(
                    trimmed_prefix,
                    &field_tables,
                    multi_table_context,
                    settings.active_auth_context(),
                );
                if allow_star && (trimmed_prefix.is_empty() || "*".starts_with(trimmed_prefix)) {
                    items.insert(
                        0,
                        CompletionItem {
                            label: "*".to_string(),
                            kind: Some(CompletionItemKind::OPERATOR),
                            detail: Some("All columns".to_string()),
                            insert_text: Some("*".to_string()),
                            sort_text: Some("0-aaa-star".to_string()),
                            ..CompletionItem::default()
                        },
                    );
                }
                return Some(CompletionResponse::Array(items));
            }
        }

        let items = model.completion_items(
            trimmed_prefix,
            record_type_context,
            settings.active_auth_context(),
            statement_fact,
            qualifier.as_deref(),
        );
        Some(CompletionResponse::Array(items))
    }

    pub async fn hover(&self, params: HoverParams) -> Option<Hover> {
        let uri = params.text_document_position_params.text_document.uri;
        let position = params.text_document_position_params.position;
        let (analysis, model, settings) = self.snapshot_for_uri(&uri).await?;

        let token = token_at(&analysis.text, position)?;
        let range = word_range(&analysis.text, position)?;
        let contents = model.hover_markdown_for_token(
            token.trim_matches(|ch: char| {
                matches!(ch, '(' | ')' | '[' | ']' | '{' | '}' | ',' | ';')
            }),
            settings.active_auth_context(),
        )?;

        Some(Hover {
            contents: HoverContents::Markup(MarkupContent {
                kind: MarkupKind::Markdown,
                value: contents,
            }),
            range: Some(range),
        })
    }

    pub async fn document_symbol(
        &self,
        params: DocumentSymbolParams,
    ) -> Option<DocumentSymbolResponse> {
        let uri = params.text_document.uri;
        let (analysis, _, _) = self.snapshot_for_uri(&uri).await?;
        Some(DocumentSymbolResponse::Nested(
            analysis.document_symbols.clone(),
        ))
    }

    /// Full-document semantic tokens. Re-parses the document and maps
    /// tree-sitter node kinds onto the standard LSP token legend (see
    /// [`crate::semantic::highlight`]).
    pub async fn semantic_tokens_full(
        &self,
        params: SemanticTokensParams,
    ) -> Option<SemanticTokensResult> {
        let uri = params.text_document.uri;
        let (analysis, _, _) = self.snapshot_for_uri(&uri).await?;
        let data =
            crate::semantic::highlight::collect_semantic_tokens(&analysis.tree, &analysis.text);
        Some(SemanticTokensResult::Tokens(SemanticTokens {
            result_id: None,
            data,
        }))
    }

    /// Semantic tokens for a viewport range — same mapping as
    /// [`Self::semantic_tokens_full`], restricted to nodes overlapping
    /// `params.range`.
    pub async fn semantic_tokens_range(
        &self,
        params: SemanticTokensRangeParams,
    ) -> Option<SemanticTokensRangeResult> {
        let uri = params.text_document.uri;
        let (analysis, _, _) = self.snapshot_for_uri(&uri).await?;
        let data = crate::semantic::highlight::collect_semantic_tokens_range(
            &analysis.tree,
            &analysis.text,
            params.range,
        );
        Some(SemanticTokensRangeResult::Tokens(SemanticTokens {
            result_id: None,
            data,
        }))
    }

    pub async fn goto_definition(
        &self,
        params: GotoDefinitionParams,
    ) -> Option<GotoDefinitionResponse> {
        let uri = params.text_document_position_params.text_document.uri;
        let position = params.text_document_position_params.position;
        let (analysis, model, _) = self.snapshot_for_uri(&uri).await?;
        let token = token_at(&analysis.text, position)?;

        let token = token.trim().to_string();
        model
            .definition_for_token(&token)
            .map(GotoDefinitionResponse::Scalar)
    }

    pub async fn references(&self, params: ReferenceParams) -> Vec<Location> {
        let uri = params.text_document_position.text_document.uri;
        let position = params.text_document_position.position;
        let Some((analysis, model, _)) = self.snapshot_for_uri(&uri).await else {
            return Vec::new();
        };
        let Some(token) = token_at(&analysis.text, position) else {
            return Vec::new();
        };
        model.references_for_function(token.trim())
    }

    pub async fn prepare_rename(
        &self,
        params: TextDocumentPositionParams,
    ) -> Option<PrepareRenameResponse> {
        let uri = params.text_document.uri;
        let position = params.position;
        let (analysis, model, _) = self.snapshot_for_uri(&uri).await?;
        let token = token_at(&analysis.text, position)?;
        let name = token.trim();
        let location = model.definition_for_function(name)?;
        Some(PrepareRenameResponse::RangeWithPlaceholder {
            range: location.range,
            placeholder: name.to_string(),
        })
    }

    pub async fn rename(&self, params: RenameParams) -> Option<WorkspaceEdit> {
        let uri = params.text_document_position.text_document.uri;
        let position = params.text_document_position.position;
        let (analysis, model, _) = self.snapshot_for_uri(&uri).await?;
        let token = token_at(&analysis.text, position)?;
        let changes = model.rename_edits(token.trim(), &params.new_name)?;
        Some(WorkspaceEdit {
            changes: Some(changes),
            ..WorkspaceEdit::default()
        })
    }

    pub async fn signature_help(&self, params: SignatureHelpParams) -> Option<SignatureHelp> {
        let uri = params.text_document_position_params.text_document.uri;
        let position = params.text_document_position_params.position;
        let (analysis, model, _) = self.snapshot_for_uri(&uri).await?;
        let offset = position_to_offset(&analysis.text, position);
        let prefix = &analysis.text[..offset];
        let open_paren = prefix.rfind('(')?;
        let function_name = prefix[..open_paren]
            .trim_end()
            .split_whitespace()
            .last()
            .map(str::trim)
            .unwrap_or_default();
        let active_parameter = prefix[open_paren + 1..]
            .chars()
            .filter(|ch| *ch == ',')
            .count() as u32;

        if let Some(function) = model.functions.get(function_name) {
            return Some(SignatureHelp {
                signatures: vec![SignatureInformation {
                    label: format!(
                        "{}({})",
                        function.name,
                        function
                            .params
                            .iter()
                            .map(|param| match &param.type_expr {
                                Some(type_expr) => format!("{}: {}", param.name, type_expr),
                                None => param.name.clone(),
                            })
                            .collect::<Vec<_>>()
                            .join(", ")
                    ),
                    documentation: function.comment.clone().map(|value| {
                        Documentation::MarkupContent(MarkupContent {
                            kind: MarkupKind::Markdown,
                            value,
                        })
                    }),
                    parameters: Some(
                        function
                            .params
                            .iter()
                            .map(|param| ParameterInformation {
                                label: ParameterLabel::Simple(match &param.type_expr {
                                    Some(type_expr) => format!("{}: {}", param.name, type_expr),
                                    None => param.name.clone(),
                                }),
                                documentation: None,
                            })
                            .collect(),
                    ),
                    active_parameter: Some(active_parameter),
                }],
                active_signature: Some(0),
                active_parameter: Some(active_parameter),
            });
        }

        let function = builtin_function(function_name)?;
        Some(SignatureHelp {
            signatures: vec![builtin_signature_information(function)],
            active_signature: Some(0),
            active_parameter: Some(active_parameter),
        })
    }

    pub async fn code_action(&self, params: CodeActionParams) -> Option<CodeActionResponse> {
        let uri = params.text_document.uri;
        let (analysis, model, _) = self.snapshot_for_uri(&uri).await?;
        Some(model.code_actions(&uri, &analysis, &params.context.diagnostics))
    }

    pub async fn document_highlight(
        &self,
        params: DocumentHighlightParams,
    ) -> Vec<DocumentHighlight> {
        let uri = params.text_document_position_params.text_document.uri;
        let position = params.text_document_position_params.position;
        let Some((analysis, model, _)) = self.snapshot_for_uri(&uri).await else {
            return Vec::new();
        };
        let Some(token) = token_at(&analysis.text, position) else {
            return Vec::new();
        };
        model
            .references_for_function(token.trim())
            .into_iter()
            .filter(|location| location.uri == uri)
            .map(|location| DocumentHighlight {
                range: location.range,
                kind: Some(DocumentHighlightKind::READ),
            })
            .collect()
    }

    /// Emit `parameter_name:` hints next to each argument of every
    /// custom function call in the requested viewport range. Builtin
    /// functions don't expose structured parameter names (their
    /// signatures are free-form strings), so they're skipped.
    pub async fn inlay_hint(&self, params: InlayHintParams) -> Vec<InlayHint> {
        let uri = params.text_document.uri;
        let Some((analysis, model, _)) = self.snapshot_for_uri(&uri).await else {
            return Vec::new();
        };

        let range_start = position_to_offset(&analysis.text, params.range.start);
        let range_end = position_to_offset(&analysis.text, params.range.end);

        crate::semantic::analyzer::collect_inlay_hints(
            analysis.tree.root_node(),
            &analysis.text,
            range_start,
            range_end,
            &model,
        )
    }

    pub async fn prepare_call_hierarchy(
        &self,
        params: CallHierarchyPrepareParams,
    ) -> Option<Vec<CallHierarchyItem>> {
        let uri = params.text_document_position_params.text_document.uri;
        let position = params.text_document_position_params.position;
        let (analysis, model, _) = self.snapshot_for_uri(&uri).await?;
        let token = token_at(&analysis.text, position)?;
        let function = model.functions.get(token.trim())?;
        Some(vec![call_hierarchy_item(function)])
    }

    pub async fn incoming_calls(
        &self,
        params: CallHierarchyIncomingCallsParams,
    ) -> Vec<CallHierarchyIncomingCall> {
        let item = params.item;
        let state = self.state.read().await;
        let callers = state
            .model
            .function_callers
            .get(&item.name)
            .cloned()
            .unwrap_or_default();
        let mut calls = Vec::new();
        for caller_name in callers {
            if let Some(function) = state.model.functions.get(&caller_name) {
                calls.push(CallHierarchyIncomingCall {
                    from: call_hierarchy_item(function),
                    from_ranges: vec![function.selection_range],
                });
            }
        }
        calls
    }

    pub async fn outgoing_calls(
        &self,
        params: CallHierarchyOutgoingCallsParams,
    ) -> Vec<CallHierarchyOutgoingCall> {
        let item = params.item;
        let state = self.state.read().await;
        let Some(function) = state.model.functions.get(&item.name) else {
            return Vec::new();
        };
        let mut calls = Vec::new();
        for callee_name in &function.called_functions {
            if let Some(callee) = state.model.functions.get(callee_name) {
                calls.push(CallHierarchyOutgoingCall {
                    to: call_hierarchy_item(callee),
                    from_ranges: vec![function.selection_range],
                });
            }
        }
        calls
    }

    pub async fn workspace_symbol(
        &self,
        params: WorkspaceSymbolParams,
    ) -> Option<WorkspaceSymbolResponse> {
        let state = self.state.read().await;
        Some(state.model.workspace_symbol_items(&params.query).into())
    }

    // ──────────────────────────────────────────────────────────────────
    // Internal helpers
    // ──────────────────────────────────────────────────────────────────

    async fn upsert_open_document(&self, uri: Uri, text: String) {
        let Some(analysis) = analyze_document(uri.clone(), &text, SymbolOrigin::Local) else {
            return;
        };
        {
            let mut state = self.state.write().await;
            state.open_documents.insert(uri.clone(), Arc::new(analysis));
        }
        self.recompute_model().await;
        self.publish_diagnostics_for_uri(&uri).await;
    }

    async fn sync_saved_document_from_disk(&self, uri: &Uri) {
        let Some(text) = self.workspace_loader.read_document(uri).await else {
            return;
        };
        let Some(analysis) = analyze_document(uri.clone(), &text, SymbolOrigin::Local) else {
            return;
        };
        let mut state = self.state.write().await;
        let mut workspace = (*state.saved_workspace).clone();
        workspace.documents.insert(uri.clone(), Arc::new(analysis));
        state.saved_workspace = Arc::new(workspace);
    }

    async fn recompute_model(&self) {
        let (workspace, live_metadata) = {
            let state = self.state.read().await;
            (
                merged_workspace(&state.saved_workspace, &state.open_documents),
                Arc::clone(&state.live_metadata),
            )
        };

        let model = Arc::new(MergedSemanticModel::build(&workspace, &live_metadata));
        let mut state = self.state.write().await;
        state.model = model;
    }

    async fn refresh_remote_metadata_if_needed(&self) {
        // Under the config lock so a concurrent apply_settings can't
        // interleave its fetch/report/store with this one (which
        // would let a stale "clean" fetch overwrite a fresh failure
        // report, or vice versa).
        let _guard = self.config_lock.lock().await;
        let settings = {
            let state = self.state.read().await;
            Arc::clone(&state.settings)
        };
        let live_metadata = Arc::new(self.metadata_provider.fetch(&settings).await);
        self.report_metadata_errors(&live_metadata).await;
        {
            let mut state = self.state.write().await;
            state.live_metadata = live_metadata;
        }
        self.recompute_model().await;
    }

    /// Forward live-metadata fetch failures (bad endpoint, auth
    /// failure, timeout, per-table query errors) to the IDE. Before
    /// this existed, `LiveMetadataSnapshot.errors` was collected and
    /// then dropped — a misconfigured connection looked identical to
    /// an empty schema.
    ///
    /// Each *distinct* failure set toasts once (`window/showMessage`)
    /// with full details in the log, and recovery back to a clean
    /// fetch logs an INFO line. The state lock is released before any
    /// notifier call — the wasm executor is single-threaded and a
    /// held lock across an await can deadlock it.
    async fn report_metadata_errors(&self, snapshot: &LiveMetadataSnapshot) {
        let mut signature = snapshot.errors.clone();
        signature.sort();

        let previous = {
            let mut state = self.state.write().await;
            state.last_metadata_errors.replace(signature.clone())
        };

        if previous.as_ref() == Some(&signature) {
            return;
        }

        if signature.is_empty() {
            if previous.is_some_and(|previous| !previous.is_empty()) {
                self.notifier
                    .log_message(
                        MessageType::INFO,
                        "SurrealQL: live schema metadata is available again".to_string(),
                    )
                    .await;
            }
            return;
        }

        for error in &snapshot.errors {
            self.notifier
                .log_message(MessageType::WARNING, format!("SurrealQL metadata: {error}"))
                .await;
        }

        let first = &snapshot.errors[0];
        let message = match snapshot.errors.len() {
            1 => format!("SurrealQL: live schema metadata unavailable: {first}"),
            more => format!(
                "SurrealQL: live schema metadata unavailable: {first} (+{} more — see the log)",
                more - 1
            ),
        };
        self.notifier
            .show_message(MessageType::WARNING, message)
            .await;
    }

    /// Summarize what a fresh workspace walk had to skip (unreadable
    /// entries, oversized files, the file-count cap) so silent
    /// truncation doesn't masquerade as full coverage.
    async fn report_scan_stats(&self, workspace: &WorkspaceIndex) {
        let stats = workspace.scan_stats;
        if stats == Default::default() {
            return;
        }

        let mut parts = Vec::new();
        if stats.walk_errors > 0 {
            parts.push(format!(
                "{} unreadable directory entries",
                stats.walk_errors
            ));
        }
        if stats.skipped_oversize > 0 {
            parts.push(format!("{} oversized files", stats.skipped_oversize));
        }
        if stats.skipped_unreadable > 0 {
            parts.push(format!("{} unreadable files", stats.skipped_unreadable));
        }
        if stats.file_cap_hit {
            parts.push("the workspace file limit was reached".to_string());
        }
        self.notifier
            .log_message(
                MessageType::WARNING,
                format!("SurrealQL: workspace scan skipped {}.", parts.join(", ")),
            )
            .await;

        if stats.file_cap_hit {
            self.notifier
                .show_message(
                    MessageType::WARNING,
                    "SurrealQL: the workspace contains more .surql files than the indexing \
                     limit; some files were not indexed."
                        .to_string(),
                )
                .await;
        }
    }

    /// Republish diagnostics for every open editor buffer after the
    /// merged model changes without a document edit (e.g. live
    /// metadata arriving from the host).
    async fn republish_open_diagnostics(&self) {
        let uris = {
            let state = self.state.read().await;
            state.open_documents.keys().cloned().collect::<Vec<_>>()
        };
        for uri in uris {
            self.publish_diagnostics_for_uri(&uri).await;
        }
    }

    async fn publish_diagnostics_for_uri(&self, uri: &Uri) {
        let (analysis, model, settings) = {
            let state = self.state.read().await;
            let analysis = state
                .open_documents
                .get(uri)
                .cloned()
                .or_else(|| state.saved_workspace.documents.get(uri).cloned());
            (
                analysis,
                Arc::clone(&state.model),
                Arc::clone(&state.settings),
            )
        };

        if let Some(analysis) = analysis {
            let mut diagnostics = analysis.syntax_diagnostics.clone();
            diagnostics.extend(model.semantic_diagnostics(&analysis, &settings));
            self.notifier
                .publish_diagnostics(uri.clone(), diagnostics)
                .await;
        }
    }

    async fn snapshot_for_uri(
        &self,
        uri: &Uri,
    ) -> Option<(
        Arc<DocumentAnalysis>,
        Arc<MergedSemanticModel>,
        Arc<ServerSettings>,
    )> {
        let state = self.state.read().await;
        let analysis = state
            .open_documents
            .get(uri)
            .cloned()
            .or_else(|| state.saved_workspace.documents.get(uri).cloned())?;
        Some((
            analysis,
            Arc::clone(&state.model),
            Arc::clone(&state.settings),
        ))
    }
}

// ──────────────────────────────────────────────────────────────────────
// Free helpers
// ──────────────────────────────────────────────────────────────────────

fn resolve_workspace_folders(params: &InitializeParams) -> Vec<PathBuf> {
    params
        .workspace_folders
        .as_ref()
        .map(|folders| {
            folders
                .iter()
                .filter_map(|folder| folder.uri.to_file_path().map(|p| p.into_owned()))
                .collect()
        })
        .unwrap_or_default()
}

fn call_hierarchy_item(function: &FunctionDef) -> CallHierarchyItem {
    CallHierarchyItem {
        name: function.name.clone(),
        kind: SymbolKind::FUNCTION,
        tags: None,
        detail: function.comment.clone(),
        uri: function.location.uri.clone(),
        range: function.location.range,
        selection_range: function.selection_range,
        data: None,
    }
}

fn builtin_signature_information(function: &BuiltinFunction) -> SignatureInformation {
    let parameters = function
        .signature
        .split_once('(')
        .and_then(|(_, rest)| rest.split_once(')'))
        .map(|(params, _)| {
            params
                .split(',')
                .map(str::trim)
                .filter(|param| !param.is_empty())
                .map(|param| ParameterInformation {
                    label: ParameterLabel::Simple(param.to_string()),
                    documentation: None,
                })
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();

    SignatureInformation {
        label: function.signature.to_string(),
        documentation: Some(Documentation::MarkupContent(MarkupContent {
            kind: MarkupKind::Markdown,
            value: format!(
                "{}\n\n[Docs]({})",
                function.summary, function.documentation_url
            ),
        })),
        parameters: Some(parameters),
        active_parameter: None,
    }
}

/// Extension methods used by [`LanguageServerCore::reload_from_client_configuration`]
/// to merge incoming `workspace/configuration` snapshots with the
/// initial settings (which usually carry the connection details from
/// `initializationOptions`).
trait SettingsMergeExt {
    fn merge_with_env_if_missing(self, fallback: ServerSettings) -> ServerSettings;
}

impl SettingsMergeExt for ServerSettings {
    fn merge_with_env_if_missing(mut self, fallback: ServerSettings) -> ServerSettings {
        if self.connection.endpoint.is_none() {
            self.connection.endpoint = fallback.connection.endpoint;
        }
        if self.connection.namespace.is_none() {
            self.connection.namespace = fallback.connection.namespace;
        }
        if self.connection.database.is_none() {
            self.connection.database = fallback.connection.database;
        }
        if self.connection.username.is_none() {
            self.connection.username = fallback.connection.username;
        }
        if self.connection.password.is_none() {
            self.connection.password = fallback.connection.password;
        }
        if self.connection.token.is_none() {
            self.connection.token = fallback.connection.token;
        }
        if self.active_auth_context.is_none() {
            self.active_auth_context = fallback.active_auth_context;
        }
        if self.auth_contexts.is_empty() {
            self.auth_contexts = fallback.auth_contexts;
        }
        let default_mode = crate::config::MetadataSettings::default().mode;
        if self.metadata.mode == default_mode && fallback.metadata.mode != default_mode {
            self.metadata.mode = fallback.metadata.mode;
        }
        self
    }
}