-
-
Notifications
You must be signed in to change notification settings - Fork 446
Expand file tree
/
Copy pathServer.zig
More file actions
2029 lines (1778 loc) · 86.5 KB
/
Copy pathServer.zig
File metadata and controls
2029 lines (1778 loc) · 86.5 KB
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
//! - Store global state
//! - The main loop
//! - Job/Request scheduling
//! - many Request handlers defined here. Except for the major ones which are in `src/features`
const Server = @This();
const std = @import("std");
const zig_builtin = @import("builtin");
const build_options = @import("build_options");
const Config = @import("Config.zig");
const configuration = @import("configuration.zig");
const DocumentStore = @import("DocumentStore.zig");
const lsp = @import("lsp");
const types = lsp.types;
const Analyser = @import("analysis.zig");
const offsets = @import("offsets.zig");
const tracy = @import("tracy");
const diff = @import("diff.zig");
const Uri = @import("Uri.zig");
const InternPool = @import("analyser/analyser.zig").InternPool;
const DiagnosticsCollection = @import("DiagnosticsCollection.zig");
const build_runner_shared = @import("build_runner/shared.zig");
const signature_help = @import("features/signature_help.zig");
const references = @import("features/references.zig");
const semantic_tokens = @import("features/semantic_tokens.zig");
const inlay_hints = @import("features/inlay_hints.zig");
const code_actions = @import("features/code_actions.zig");
const folding_range = @import("features/folding_range.zig");
const document_symbol = @import("features/document_symbol.zig");
const completions = @import("features/completions.zig");
const goto = @import("features/goto.zig");
const hover_handler = @import("features/hover.zig");
const selection_range = @import("features/selection_range.zig");
const diagnostics_gen = @import("features/diagnostics.zig");
const BuildOnSave = diagnostics_gen.BuildOnSave;
const BuildOnSaveSupport = build_runner_shared.BuildOnSaveSupport;
const log = std.log.scoped(.server);
// public fields
io: std.Io,
allocator: std.mem.Allocator,
config_manager: *configuration.Manager,
document_store: DocumentStore,
transport: ?*lsp.Transport = null,
offset_encoding: offsets.Encoding = .@"utf-16",
status: Status = .uninitialized,
// private fields
wait_group: std.Io.Group = .init,
ip: InternPool = undefined,
/// Stores messages that should be displayed with `window/showMessage` once the server has been initialized.
pending_show_messages: std.ArrayList(types.window.ShowMessageParams) = .empty,
client_capabilities: ClientCapabilities = .{},
diagnostics_collection: DiagnosticsCollection,
workspaces: std.ArrayList(Workspace) = .empty,
// Code was based off of https://github.com/andersfr/zig-lsp/blob/master/server.zig
const ClientCapabilities = struct {
supports_snippets: bool = false,
supports_apply_edits: bool = false,
supports_will_save_wait_until: bool = false,
supports_publish_diagnostics: bool = false,
supports_code_action_fixall: bool = false,
supports_semantic_tokens_overlapping: bool = false,
hover_supports_md: bool = false,
signature_help_supports_md: bool = false,
completion_doc_supports_md: bool = false,
supports_completion_insert_replace_support: bool = false,
/// deprecated can be marked through the `CompletionItem.deprecated` field
supports_completion_deprecated_old: bool = false,
/// deprecated can be marked through the `CompletionItem.tags` field
supports_completion_deprecated_tag: bool = false,
label_details_support: bool = false,
/// The client supports `workspace/configuration` requests.
supports_configuration: bool = false,
/// The client supports dynamically registering for the `workspace/didChangeConfiguration` notification.
supports_workspace_did_change_configuration_dynamic_registration: bool = false,
/// The client supports dynamically registering for the `workspace/didChangeWatchedFiles` notification.
supports_workspace_did_change_watched_files: bool = false,
supports_textDocument_definition_linkSupport: bool = false,
/// The detail entries for big structs such as std.zig.CrossTarget were
/// bricking the preview window in Sublime Text.
/// https://github.com/zigtools/zls/pull/261
max_detail_length: u32 = 1024 * 1024,
client_name: ?[]const u8 = null,
fn deinit(self: *ClientCapabilities, allocator: std.mem.Allocator) void {
if (self.client_name) |name| allocator.free(name);
self.* = undefined;
}
};
pub const Error = error{
ParseError,
InvalidRequest,
MethodNotFound,
InvalidParams,
InternalError,
/// Error code indicating that a server received a notification or
/// request before the server has received the `initialize` request.
ServerNotInitialized,
/// A request failed but it was syntactically correct, e.g the
/// method name was known and the parameters were valid. The error
/// message should contain human readable information about why
/// the request failed.
///
/// @since 3.17.0
RequestFailed,
/// The server cancelled the request. This error code should
/// only be used for requests that explicitly support being
/// server cancellable.
///
/// @since 3.17.0
ServerCancelled,
/// The server detected that the content of a document got
/// modified outside normal conditions. A server should
/// NOT send this error code if it detects a content change
/// in it unprocessed messages. The result even computed
/// on an older state might still be useful for the client.
///
/// If a client decides that a result is not of any use anymore
/// the client should cancel the request.
ContentModified,
/// The client has canceled a request and a server as detected
/// the cancel.
RequestCancelled,
} || std.mem.Allocator.Error || std.Io.Cancelable;
pub const Status = enum {
/// the server has not received a `initialize` request
uninitialized,
/// the server has received a `initialize` request and is awaiting the `initialized` notification
initializing,
/// the server has been initialized and is ready to received requests
initialized,
/// the server has been shutdown and can't handle any more requests
shutdown,
/// the server is received a `exit` notification and has been shutdown
exiting_success,
/// the server is received a `exit` notification but has not been shutdown
exiting_failure,
};
fn sendToClientResponse(server: *Server, id: lsp.JsonRPCMessage.ID, result: anytype) error{ Canceled, OutOfMemory }![]u8 {
const tracy_zone = tracy.traceNamed(@src(), "sendToClientResponse(" ++ @typeName(@TypeOf(result)) ++ ")");
defer tracy_zone.end();
// TODO validate result type is a possible response
// TODO validate response is from a client to server request
// TODO validate result type
const response: lsp.TypedJsonRPCResponse(@TypeOf(result)) = .{
.id = id,
.result_or_error = .{ .result = result },
};
return try sendToClientInternal(server.io, server.allocator, server.transport, response);
}
fn sendToClientRequest(server: *Server, id: lsp.JsonRPCMessage.ID, method: []const u8, params: anytype) error{ Canceled, OutOfMemory }![]u8 {
const tracy_zone = tracy.traceNamed(@src(), "sendToClientRequest(" ++ @typeName(@TypeOf(params)) ++ ")");
defer tracy_zone.end();
// TODO validate method is a request
// TODO validate method is server to client
// TODO validate params type
const request: lsp.TypedJsonRPCRequest(@TypeOf(params)) = .{
.id = id,
.method = method,
.params = params,
};
return try sendToClientInternal(server.io, server.allocator, server.transport, request);
}
fn sendToClientNotification(server: *Server, method: []const u8, params: anytype) error{ Canceled, OutOfMemory }![]u8 {
const tracy_zone = tracy.traceNamed(@src(), "sendToClientRequest(" ++ @typeName(@TypeOf(params)) ++ ")");
defer tracy_zone.end();
// TODO validate method is a notification
// TODO validate method is server to client
// TODO validate params type
const notification: lsp.TypedJsonRPCNotification(@TypeOf(params)) = .{
.method = method,
.params = params,
};
return try sendToClientInternal(server.io, server.allocator, server.transport, notification);
}
fn sendToClientResponseError(server: *Server, id: lsp.JsonRPCMessage.ID, err: lsp.JsonRPCMessage.Response.Error) error{ Canceled, OutOfMemory }![]u8 {
const tracy_zone = tracy.trace(@src());
defer tracy_zone.end();
const response: lsp.JsonRPCMessage = .{
.response = .{ .id = id, .result_or_error = .{ .@"error" = err } },
};
return try sendToClientInternal(server.io, server.allocator, server.transport, response);
}
fn sendToClientInternal(io: std.Io, allocator: std.mem.Allocator, transport: ?*lsp.Transport, message: anytype) error{ Canceled, OutOfMemory }![]u8 {
const message_stringified = try std.json.Stringify.valueAlloc(allocator, message, .{
.emit_null_optional_fields = false,
});
errdefer allocator.free(message_stringified);
if (transport) |t| {
const tracy_zone = tracy.traceNamed(@src(), "Transport.writeJsonMessage");
defer tracy_zone.end();
t.writeJsonMessage(io, message_stringified) catch |err| switch (err) {
error.Canceled => return error.Canceled,
else => log.err("failed to write message: {}", .{err}),
};
}
return message_stringified;
}
/// Send a `window/showMessage` notification to the client that will display a message in the user interface.
pub fn showMessage(
server: *Server,
message_type: types.window.MessageType,
comptime fmt: []const u8,
args: anytype,
) void {
var message = std.fmt.allocPrint(server.allocator, fmt, args) catch return;
defer server.allocator.free(message);
switch (message_type) {
.Error => log.err("{s}", .{message}),
.Warning => log.warn("{s}", .{message}),
.Info => log.info("{s}", .{message}),
.Log, .Debug => log.debug("{s}", .{message}),
_ => log.debug("{s}", .{message}),
}
switch (server.status) {
.uninitialized => {
server.pending_show_messages.ensureUnusedCapacity(server.allocator, 1) catch return;
server.pending_show_messages.appendAssumeCapacity(.{
.type = message_type,
.message = message,
});
message = "";
return;
},
.initializing,
.initialized,
=> {},
.shutdown,
.exiting_success,
.exiting_failure,
=> return,
}
if (server.sendToClientNotification("window/showMessage", types.window.ShowMessageParams{
.type = message_type,
.message = message,
})) |json_message| {
server.allocator.free(json_message);
} else |err| {
log.warn("failed to show message: {}", .{err});
}
}
pub fn initAnalyser(server: *Server, arena: std.mem.Allocator, handle: ?*DocumentStore.Handle) Analyser {
return .init(
server.allocator,
arena,
&server.document_store,
&server.ip,
handle,
);
}
/// If `force_autofix` is enabled, implement autofix without relying on a `source.fixall` code action.
pub fn autofixWorkaround(server: *Server) enum {
/// Autofix is implemented using `textDocument/willSaveWaitUntil`.
will_save_wait_until,
/// Autofix is implemented by send a `workspace/applyEdit` request after receiving a `textDocument/didSave` notification.
on_save,
/// No workaround implementation of autofix is possible.
unavailable,
/// The `force_autofix` config option is disabled.
none,
} {
if (!server.config_manager.config.force_autofix) return .none;
if (server.client_capabilities.supports_will_save_wait_until) return .will_save_wait_until;
if (server.client_capabilities.supports_apply_edits) return .on_save;
return .unavailable;
}
/// caller owns returned memory.
fn autofix(server: *Server, arena: std.mem.Allocator, handle: *DocumentStore.Handle) error{ Canceled, OutOfMemory }!std.ArrayList(types.TextEdit) {
if (handle.tree.errors.len != 0) return .empty;
if (handle.tree.mode == .zon) return .empty;
var error_bundle = try diagnostics_gen.getAstCheckDiagnostics(server, handle);
defer error_bundle.deinit(server.allocator);
if (error_bundle.errorMessageCount() == 0) return .empty;
var analyser = server.initAnalyser(arena, handle);
defer analyser.deinit();
var builder: code_actions.Builder = .{
.arena = arena,
.analyser = &analyser,
.handle = handle,
.offset_encoding = server.offset_encoding,
.only_kinds = .init(.{
.@"source.fixAll" = true,
}),
};
try builder.generateCodeAction(error_bundle);
for (builder.actions.items) |action| {
std.debug.assert(action.kind.?.eql(.@"source.fixAll")); // We request only source.fixall code actions
}
defer builder.fixall_text_edits = .empty;
return builder.fixall_text_edits;
}
fn generateDiagnostics(server: *Server, handle: *DocumentStore.Handle) void {
if (!server.client_capabilities.supports_publish_diagnostics) return;
const do = struct {
fn do(param_server: *Server, param_handle: *DocumentStore.Handle) std.Io.Cancelable!void {
diagnostics_gen.generateDiagnostics(param_server, param_handle) catch |err| switch (err) {
error.Canceled => return error.Canceled,
error.OutOfMemory => {},
};
}
}.do;
server.wait_group.async(server.io, do, .{ server, handle });
}
fn initializeHandler(server: *Server, arena: std.mem.Allocator, request: types.InitializeParams) Error!types.InitializeResult {
var support_full_semantic_tokens = true;
if (request.clientInfo) |clientInfo| {
server.client_capabilities.client_name = try server.allocator.dupe(u8, clientInfo.name);
if (std.mem.startsWith(u8, clientInfo.name, "Visual Studio Code") or
std.mem.startsWith(u8, clientInfo.name, "VSCodium") or
std.mem.startsWith(u8, clientInfo.name, "Code - OSS"))
{
// VS Code doesn't really utilize `textDocument/semanticTokens/range`.
// This will cause some visual artifacts when scrolling through the
// document quickly but will considerably improve performance
// especially on large files.
support_full_semantic_tokens = false;
} else if (std.mem.eql(u8, clientInfo.name, "Sublime Text LSP")) {
server.client_capabilities.max_detail_length = 256;
} else if (std.mem.startsWith(u8, clientInfo.name, "emacs")) {
// Assumes that `emacs` means `emacs-lsp/lsp-mode`. Eglot uses `Eglot`.
}
}
if (request.capabilities.general) |general| {
if (general.positionEncodings) |position_encodings| {
server.offset_encoding = outer: for (position_encodings) |encoding| {
switch (encoding) {
.@"utf-8" => break :outer .@"utf-8",
.@"utf-16" => break :outer .@"utf-16",
.@"utf-32" => break :outer .@"utf-32",
.custom_value => {},
}
} else server.offset_encoding;
}
}
server.diagnostics_collection.offset_encoding = server.offset_encoding;
if (request.capabilities.textDocument) |textDocument| {
server.client_capabilities.supports_publish_diagnostics = textDocument.publishDiagnostics != null;
if (textDocument.hover) |hover| {
if (hover.contentFormat) |content_format| {
for (content_format) |format| {
if (format == .plaintext) {
break;
}
if (format == .markdown) {
server.client_capabilities.hover_supports_md = true;
break;
}
}
}
}
if (textDocument.completion) |completion| {
if (completion.completionItem) |completionItem| {
server.client_capabilities.label_details_support = completionItem.labelDetailsSupport orelse false;
server.client_capabilities.supports_snippets = completionItem.snippetSupport orelse false;
server.client_capabilities.supports_completion_deprecated_old = completionItem.deprecatedSupport orelse false;
server.client_capabilities.supports_completion_insert_replace_support = completionItem.insertReplaceSupport orelse false;
if (completionItem.tagSupport) |tagSupport| {
for (tagSupport.valueSet) |tag| {
switch (tag) {
.Deprecated => {
server.client_capabilities.supports_completion_deprecated_tag = true;
break;
},
_ => {},
}
}
}
if (completionItem.documentationFormat) |documentation_format| {
for (documentation_format) |format| {
if (format == .plaintext) {
break;
}
if (format == .markdown) {
server.client_capabilities.completion_doc_supports_md = true;
break;
}
}
}
}
}
if (textDocument.synchronization) |synchronization| {
server.client_capabilities.supports_will_save_wait_until = synchronization.willSaveWaitUntil orelse false;
}
if (textDocument.definition) |definition| {
server.client_capabilities.supports_textDocument_definition_linkSupport = definition.linkSupport orelse false;
}
if (textDocument.signatureHelp) |signature_help_capabilities| {
if (signature_help_capabilities.signatureInformation) |signature_information| {
if (signature_information.documentationFormat) |content_format| {
for (content_format) |format| {
if (format == .plaintext) {
break;
}
if (format == .markdown) {
server.client_capabilities.signature_help_supports_md = true;
break;
}
}
}
}
}
if (textDocument.semanticTokens) |semanticTokens| {
server.client_capabilities.supports_semantic_tokens_overlapping = semanticTokens.overlappingTokenSupport orelse false;
}
}
if (request.capabilities.window) |window| {
if (window.workDoneProgress) |wdp| {
server.document_store.lsp_capabilities.supports_work_done_progress = wdp;
}
}
if (request.capabilities.workspace) |workspace| {
server.client_capabilities.supports_apply_edits = workspace.applyEdit orelse false;
server.client_capabilities.supports_configuration = workspace.configuration orelse false;
if (workspace.didChangeConfiguration) |did_change| {
if (did_change.dynamicRegistration orelse false) {
server.client_capabilities.supports_workspace_did_change_configuration_dynamic_registration = true;
}
}
if (workspace.didChangeWatchedFiles) |did_change| {
if (did_change.dynamicRegistration orelse false) {
server.client_capabilities.supports_workspace_did_change_watched_files = true;
}
}
if (workspace.semanticTokens) |workspace_semantic_tokens| {
server.document_store.lsp_capabilities.supports_semantic_tokens_refresh = workspace_semantic_tokens.refreshSupport orelse false;
}
if (workspace.inlayHint) |inlay_hint| {
server.document_store.lsp_capabilities.supports_inlay_hints_refresh = inlay_hint.refreshSupport orelse false;
}
}
if (request.clientInfo) |clientInfo| {
log.info("Client Info: {s} ({s})", .{ clientInfo.name, clientInfo.version orelse "unknown version" });
}
log.debug("Offset Encoding: '{t}'", .{server.offset_encoding});
if (request.workspaceFolders) |workspace_folders| {
for (workspace_folders) |src| {
const uri = Uri.parse(arena, src.uri) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.InvalidParams,
};
try server.addWorkspace(uri);
}
}
server.status = .initializing;
{
for (server.pending_show_messages.items) |params| {
if (server.sendToClientNotification("window/showMessage", params)) |json_message| {
server.allocator.free(json_message);
} else |err| {
log.warn("failed to show message: {}", .{err});
}
}
for (server.pending_show_messages.items) |params| server.allocator.free(params.message);
server.pending_show_messages.clearAndFree(server.allocator);
}
if (request.initializationOptions) |initialization_options| {
if (std.json.parseFromValueLeaky(configuration.UnresolvedConfig, arena, initialization_options, .{
.ignore_unknown_fields = true,
})) |*new_cfg| {
try server.config_manager.setConfiguration(.lsp_initialization, new_cfg);
if (server.client_capabilities.supports_configuration) {
// Do not resolve configuration until we received `workspace/configuration`.
} else {
try server.resolveConfiguration();
}
} else |err| {
log.err("failed to read initialization_options: {}", .{err});
}
}
return .{
.serverInfo = .{
.name = "zls",
.version = build_options.version_string,
},
.capabilities = .{
.positionEncoding = switch (server.offset_encoding) {
.@"utf-8" => .@"utf-8",
.@"utf-16" => .@"utf-16",
.@"utf-32" => .@"utf-32",
},
.signatureHelpProvider = .{
.triggerCharacters = &.{"("},
.retriggerCharacters = &.{","},
},
.textDocumentSync = .{
.text_document_sync_options = .{
.openClose = true,
.change = .Incremental,
.save = .{ .bool = true },
.willSaveWaitUntil = true,
},
},
.renameProvider = .{
.rename_options = .{ .prepareProvider = true },
},
.completionProvider = .{
.resolveProvider = false,
.triggerCharacters = &.{ ".", ":", "@", "]", "\"", "/" },
.completionItem = .{ .labelDetailsSupport = true },
},
.documentHighlightProvider = .{ .bool = true },
.hoverProvider = .{ .bool = true },
.codeActionProvider = .{ .code_action_options = .{ .codeActionKinds = code_actions.supported_code_actions } },
.declarationProvider = .{ .bool = true },
.definitionProvider = .{ .bool = true },
.typeDefinitionProvider = .{ .bool = true },
.implementationProvider = .{ .bool = false },
.referencesProvider = .{ .bool = true },
.documentSymbolProvider = .{ .bool = true },
.colorProvider = .{ .bool = false },
.documentFormattingProvider = .{ .bool = true },
.documentRangeFormattingProvider = .{ .bool = false },
.foldingRangeProvider = .{ .bool = true },
.selectionRangeProvider = .{ .bool = true },
.workspaceSymbolProvider = .{ .bool = true },
.workspace = .{
.workspaceFolders = .{
.supported = true,
.changeNotifications = .{ .bool = true },
},
},
.semanticTokensProvider = .{
.semantic_tokens_options = .{
.full = .{ .bool = support_full_semantic_tokens },
.range = .{ .bool = true },
.legend = .{
.tokenTypes = std.meta.fieldNames(semantic_tokens.TokenType),
.tokenModifiers = std.meta.fieldNames(semantic_tokens.TokenModifiers),
},
},
},
.inlayHintProvider = .{ .bool = true },
},
};
}
fn initializedHandler(server: *Server, arena: std.mem.Allocator, notification: types.InitializedParams) Error!void {
_ = notification;
if (server.status != .initializing) {
log.warn("received a initialized notification but the server has not send a initialize request!", .{});
}
server.status = .initialized;
if (server.client_capabilities.supports_configuration and
server.client_capabilities.supports_workspace_did_change_configuration_dynamic_registration)
{
try server.registerCapability("workspace/didChangeConfiguration", null);
}
if (server.client_capabilities.supports_workspace_did_change_watched_files) {
// `{ "watchers": [ { "globPattern": "**/*.{zig,zon}" } ] }`
var watcher: std.json.ObjectMap = .init(arena);
try watcher.putNoClobber("globPattern", .{ .string = "**/*.{zig,zon}" });
var watchers_arr: std.json.Array = try .initCapacity(arena, 1);
watchers_arr.appendAssumeCapacity(.{ .object = watcher });
var fs_watcher_obj: std.json.ObjectMap = .init(arena);
try fs_watcher_obj.putNoClobber("watchers", .{ .array = watchers_arr });
const json_val: std.json.Value = .{ .object = fs_watcher_obj };
try server.registerCapability("workspace/didChangeWatchedFiles", json_val);
}
if (server.client_capabilities.supports_configuration) {
// We defer calling `server.resolveConfiguration()` until after workspace configuration has been received.
try server.requestConfiguration();
} else {
// The client does not support the `workspace/configuration` (pull model) request
// and it is unknown whether the client will use the
// `workspace/didChangeConfiguration` (push model) notification instead.
// In case they don't, we resolve configuration early and re-resolve if push model is used.
try server.resolveConfiguration();
}
const rng_impl: std.Random.IoSource = .{ .io = server.io };
const rng = rng_impl.interface();
if (rng.intRangeLessThan(usize, 0, 32768) == 0) {
server.showMessage(.Warning, "HELP ME, I AM STUCK INSIDE AN LSP!", .{});
}
}
fn shutdownHandler(server: *Server, _: std.mem.Allocator, _: void) Error!?void {
defer server.status = .shutdown;
if (server.status != .initialized) return error.InvalidRequest; // received a shutdown request but the server is not initialized!
}
fn exitHandler(server: *Server, _: std.mem.Allocator, _: void) Error!void {
server.status = switch (server.status) {
.initialized => .exiting_failure,
.shutdown => .exiting_success,
else => unreachable,
};
}
fn registerCapability(server: *Server, method: []const u8, registersOptions: ?types.LSPAny) Error!void {
const id = try std.fmt.allocPrint(server.allocator, "register-{s}", .{method});
defer server.allocator.free(id);
log.debug("Dynamically registering method '{s}'", .{method});
const json_message = try server.sendToClientRequest(
.{ .string = id },
"client/registerCapability",
types.Registration.Params{ .registrations = &.{
.{
.id = id,
.method = method,
.registerOptions = registersOptions,
},
} },
);
server.allocator.free(json_message);
}
/// Request configuration options with the `workspace/configuration` request.
fn requestConfiguration(server: *Server) Error!void {
const configuration_items: [1]types.workspace.configuration.Item = .{
.{
.section = "zls",
.scopeUri = if (server.workspaces.items.len == 1) server.workspaces.items[0].uri.raw else null,
},
};
const json_message = try server.sendToClientRequest(
.{ .string = "i_haz_configuration" },
"workspace/configuration",
types.workspace.configuration.Params{
.items = &configuration_items,
},
);
server.allocator.free(json_message);
}
/// Handle the response of the `workspace/configuration` request.
fn handleConfiguration(server: *Server, json: std.json.Value) error{ Canceled, OutOfMemory }!void {
const tracy_zone = tracy.trace(@src());
defer tracy_zone.end();
const result: std.json.Value = switch (json) {
.array => |arr| blk: {
if (arr.items.len != 1) {
log.err("Response to 'workspace/configuration' expects an array of size 1 but received {d}", .{arr.items.len});
break :blk null;
}
break :blk switch (arr.items[0]) {
.object => arr.items[0],
.null => null,
else => {
log.err("Response to 'workspace/configuration' expects an array of objects but got an array of {t}.", .{json});
break :blk null;
},
};
},
else => blk: {
log.err("Response to 'workspace/configuration' expects an array but received {t}", .{json});
break :blk null;
},
} orelse {
try server.resolveConfiguration();
return;
};
var arena_allocator: std.heap.ArenaAllocator = .init(server.allocator);
defer arena_allocator.deinit();
const arena = arena_allocator.allocator();
var new_config = std.json.parseFromValueLeaky(
configuration.UnresolvedConfig,
arena,
result,
.{ .ignore_unknown_fields = true },
) catch |err| {
log.err("Failed to parse response from 'workspace/configuration': {}", .{err});
try server.resolveConfiguration();
return;
};
const maybe_root_dir: ?[]const u8 = dir: {
if (server.workspaces.items.len != 1) break :dir null;
const workspace = server.workspaces.items[0];
break :dir workspace.uri.toFsPath(arena) catch |err| {
log.err("failed to parse root uri for workspace {s}: {}", .{ workspace.uri.raw, err });
break :dir null;
};
};
inline for (configuration.file_system_config_options) |file_config| {
var runtime_known_config_name: []const u8 = ""; // avoid unnecessary function instantiations of `std.Io.Writer.print`
runtime_known_config_name = file_config.name;
const field: *?[]const u8 = &@field(new_config, file_config.name);
if (field.*) |maybe_relative| resolve: {
if (maybe_relative.len == 0) break :resolve;
if (std.Io.Dir.path.isAbsolute(maybe_relative)) break :resolve;
const root_dir = maybe_root_dir orelse {
log.err("relative path only supported for {s} with exactly one workspace", .{runtime_known_config_name});
break;
};
const absolute = try std.Io.Dir.path.resolve(arena, &.{
root_dir, maybe_relative,
});
field.* = absolute;
}
}
try server.config_manager.setConfiguration(.lsp_configuration, &new_config);
try server.resolveConfiguration();
}
const Workspace = struct {
uri: Uri,
build_on_save: if (BuildOnSaveSupport.isSupportedComptime()) ?BuildOnSave else void,
build_on_save_mode: if (BuildOnSaveSupport.isSupportedComptime()) ?enum { watch, manual } else void,
fn init(server: *Server, uri: Uri) error{OutOfMemory}!Workspace {
const duped_uri = try uri.dupe(server.allocator);
errdefer duped_uri.deinit(server.allocator);
return .{
.uri = duped_uri,
.build_on_save = if (BuildOnSaveSupport.isSupportedComptime()) null else {},
.build_on_save_mode = if (BuildOnSaveSupport.isSupportedComptime()) null else {},
};
}
fn deinit(workspace: *Workspace, allocator: std.mem.Allocator) void {
if (BuildOnSaveSupport.isSupportedComptime()) {
if (workspace.build_on_save) |*build_on_save| build_on_save.deinit();
}
workspace.uri.deinit(allocator);
}
fn sendManualWatchUpdate(workspace: *Workspace) void {
comptime std.debug.assert(BuildOnSaveSupport.isSupportedComptime());
const build_on_save = if (workspace.build_on_save) |*build_on_save| build_on_save else return;
const mode = workspace.build_on_save_mode orelse return;
if (mode != .manual) return;
build_on_save.sendManualWatchUpdate();
}
fn refreshBuildOnSave(workspace: *Workspace, args: struct {
server: *Server,
/// Whether the build on save process should be restarted if it is already running.
restart: bool,
}) error{ Canceled, OutOfMemory }!void {
comptime std.debug.assert(BuildOnSaveSupport.isSupportedComptime());
const config = &args.server.config_manager.config;
if (args.server.config_manager.zig_exe) |zig_exe| {
workspace.build_on_save_mode = switch (BuildOnSaveSupport.isSupportedRuntime(zig_exe.version)) {
.supported => .watch,
// If if build on save has been explicitly enabled, fallback to the implementation with manual updates
else => if (config.enable_build_on_save orelse false) .manual else null,
};
} else {
workspace.build_on_save_mode = null;
}
const build_on_save_supported = workspace.build_on_save_mode != null;
const build_on_save_wanted = config.enable_build_on_save orelse true;
const enable = build_on_save_supported and build_on_save_wanted;
if (workspace.build_on_save) |*build_on_save| {
if (enable and !args.restart) return;
log.debug("stopped Build-On-Save for '{s}'", .{workspace.uri.raw});
build_on_save.deinit();
workspace.build_on_save = null;
}
if (!enable) return;
const zig_exe_path = config.zig_exe_path orelse return;
const zig_lib_path = config.zig_lib_path orelse return;
const build_runner_path = config.build_runner_path orelse return;
const workspace_path = workspace.uri.toFsPath(args.server.allocator) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
error.UnsupportedScheme => return,
};
defer args.server.allocator.free(workspace_path);
std.debug.assert(workspace.build_on_save == null);
workspace.build_on_save = BuildOnSave.init(.{
.io = args.server.io,
.allocator = args.server.allocator,
.workspace_path = workspace_path,
.build_on_save_args = config.build_on_save_args,
.check_step_only = config.enable_build_on_save == null,
.zig_exe_path = zig_exe_path,
.zig_lib_path = zig_lib_path,
.build_runner_path = build_runner_path,
.collection = &args.server.diagnostics_collection,
}) catch |err| switch (err) {
error.Canceled => return error.Canceled,
else => {
log.err("failed to initilize Build-On-Save for '{s}': {}", .{ workspace.uri.raw, err });
return;
},
};
}
};
fn addWorkspace(server: *Server, uri: Uri) error{ Canceled, OutOfMemory }!void {
try server.workspaces.ensureUnusedCapacity(server.allocator, 1);
server.workspaces.appendAssumeCapacity(try Workspace.init(server, uri));
if (BuildOnSaveSupport.isSupportedComptime() and
// Don't initialize build on save until initialization finished.
// If the client supports the `workspace/configuration` request, wait
// until we have received workspace configuration from the server.
(server.status == .initialized and !server.client_capabilities.supports_configuration))
{
try server.workspaces.items[server.workspaces.items.len - 1].refreshBuildOnSave(.{
.server = server,
.restart = false,
});
}
const file_count = server.document_store.loadDirectoryRecursive(uri) catch |err| switch (err) {
error.Canceled, error.OutOfMemory => |e| return e,
error.UnsupportedScheme => return, // https://github.com/microsoft/language-server-protocol/issues/1264
else => {
log.err("failed to load files in workspace '{s}': {}", .{ uri.raw, err });
return;
},
};
log.info("added Workspace Folder: {s} ({d} files)", .{ uri.raw, file_count });
}
fn removeWorkspace(server: *Server, uri: Uri) void {
for (server.workspaces.items, 0..) |workspace, i| {
if (workspace.uri.eql(uri)) {
var removed_workspace = server.workspaces.swapRemove(i);
removed_workspace.deinit(server.allocator);
log.info("removed Workspace Folder: {s}", .{uri.raw});
break;
}
} else {
log.warn("could not remove Workspace Folder: {s}", .{uri.raw});
}
}
fn didChangeWatchedFilesHandler(server: *Server, arena: std.mem.Allocator, notification: types.workspace.did_change_watched_files.Params) Error!void {
var updated_files: usize = 0;
for (notification.changes) |change| {
const uri = Uri.parse(arena, change.uri) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.InvalidParams,
};
const file_extension = std.Io.Dir.path.extension(uri.raw);
if (!std.mem.eql(u8, file_extension, ".zig") and !std.mem.eql(u8, file_extension, ".zon")) continue;
switch (change.type) {
.Created, .Changed, .Deleted => |kind| {
const did_update_file = try server.document_store.refreshDocumentFromFileSystem(uri, kind == .Deleted);
updated_files += @intFromBool(did_update_file);
},
else => {},
}
}
if (updated_files != 0) {
log.debug("updated {d} watched file(s)", .{updated_files});
}
}
fn didChangeWorkspaceFoldersHandler(server: *Server, arena: std.mem.Allocator, notification: types.workspace.folders.DidChangeParams) Error!void {
for (notification.event.added) |folder| {
const uri = Uri.parse(arena, folder.uri) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.InvalidParams,
};
try server.addWorkspace(uri);
}
for (notification.event.removed) |folder| {
const uri = Uri.parse(arena, folder.uri) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.InvalidParams,
};
server.removeWorkspace(uri);
}
}
fn didChangeConfigurationHandler(server: *Server, arena: std.mem.Allocator, notification: types.workspace.configuration.did_change.Params) Error!void {
const settings = switch (notification.settings) {
.null => {
if (server.client_capabilities.supports_configuration and
server.client_capabilities.supports_workspace_did_change_configuration_dynamic_registration)
{
// The client has informed us that the configuration options have
// changed. The will request them with `workspace/configuration`.
try server.requestConfiguration();
}
return;
},
.object => |object| blk: {
if (server.client_capabilities.supports_configuration and
server.client_capabilities.supports_workspace_did_change_configuration_dynamic_registration)
{
log.debug("Ignoring 'workspace/didChangeConfiguration' notification in favor of 'workspace/configuration'", .{});
try server.requestConfiguration();
return;
}
break :blk object.get("zls") orelse notification.settings;
},
else => notification.settings, // We will definitely fail to parse this
};
const new_config = std.json.parseFromValueLeaky(
configuration.UnresolvedConfig,
arena,
settings,
.{ .ignore_unknown_fields = true },
) catch |err| {
log.err("failed to parse 'workspace/didChangeConfiguration' response: {}", .{err});
return error.ParseError;
};
try server.config_manager.setConfiguration(.lsp_configuration, &new_config);
try server.resolveConfiguration();
}
pub fn resolveConfiguration(server: *Server) error{ Canceled, OutOfMemory }!void {
var result = try server.config_manager.resolveConfiguration(server.allocator);
defer result.deinit(server.allocator);
for (result.messages) |msg| {
server.showMessage(.Error, "{s}", .{msg});
}
inline for (std.meta.fields(Config)) |field| {
if (@field(result.did_change, field.name)) {
var runtime_known_field_name: []const u8 = ""; // avoid unnecessary function instantiations of `std.Io.Writer.print`
runtime_known_field_name = field.name;
const new_value = @field(server.config_manager.config, field.name);
log.info("Set config option '{s}' to {f}", .{ runtime_known_field_name, std.json.fmt(new_value, .{}) });
}
}
const new_zig_exe_path: bool = result.did_change.zig_exe_path;
const new_zig_lib_path: bool = result.did_change.zig_lib_path;
const new_build_runner_path: bool = result.did_change.build_runner_path;
const new_enable_build_on_save: bool = result.did_change.enable_build_on_save;
const new_build_on_save_args: bool = result.did_change.build_on_save_args;
const new_force_autofix: bool = result.did_change.force_autofix;