forked from zigtools/zls
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server.zig
2142 lines (1862 loc) · 86.2 KB
/
Server.zig
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
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 types = @import("lsp.zig");
const Analyser = @import("analysis.zig");
const ast = @import("ast.zig");
const offsets = @import("offsets.zig");
const Ast = std.zig.Ast;
const tracy = @import("tracy");
const diff = @import("diff.zig");
const ComptimeInterpreter = @import("ComptimeInterpreter.zig");
const InternPool = @import("analyser/analyser.zig").InternPool;
const Transport = @import("Transport.zig");
const known_folders = @import("known-folders");
const BuildRunnerVersion = @import("build_runner/BuildRunnerVersion.zig").BuildRunnerVersion;
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 log = std.log.scoped(.zls_server);
// public fields
allocator: std.mem.Allocator,
// use updateConfiguration or updateConfiguration2 for setting config options
config: Config = .{},
/// will default to lookup in the system and user configuration folder provided by known-folders.
config_path: ?[]const u8 = null,
document_store: DocumentStore,
transport: ?*Transport = null,
offset_encoding: offsets.Encoding = .@"utf-16",
status: Status = .uninitialized,
// private fields
thread_pool: if (zig_builtin.single_threaded) void else std.Thread.Pool,
wait_group: if (zig_builtin.single_threaded) void else std.Thread.WaitGroup,
job_queue: std.fifo.LinearFifo(Job, .Dynamic),
job_queue_lock: std.Thread.Mutex = .{},
ip: InternPool = .{},
// ensure that build on save is only executed once at a time
running_build_on_save_processes: std.atomic.Value(usize) = std.atomic.Value(usize).init(0),
/// avoid Zig deadlocking when spawning multiple `zig ast-check` processes at the same time.
/// See https://github.com/ziglang/zig/issues/16369
zig_ast_check_lock: std.Thread.Mutex = .{},
config_arena: std.heap.ArenaAllocator.State = .{},
client_capabilities: ClientCapabilities = .{},
// 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: bool = false,
supports_will_save_wait_until: bool = false,
supports_publish_diagnostics: bool = false,
supports_code_action_fixall: 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,
supports_configuration: bool = false,
supports_workspace_did_change_configuration_dynamic_registration: 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,
workspace_folders: []types.URI = &.{},
fn deinit(self: *ClientCapabilities, allocator: std.mem.Allocator) void {
for (self.workspace_folders) |uri| allocator.free(uri);
allocator.free(self.workspace_folders);
self.* = undefined;
}
};
pub const Error = error{
OutOfMemory,
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,
};
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,
};
const Job = union(enum) {
incoming_message: std.json.Parsed(types.Message),
generate_diagnostics: DocumentStore.Uri,
run_build_on_save,
fn deinit(self: Job, allocator: std.mem.Allocator) void {
switch (self) {
.incoming_message => |parsed_message| parsed_message.deinit(),
.generate_diagnostics => |uri| allocator.free(uri),
.run_build_on_save => {},
}
}
const SynchronizationMode = enum {
/// this `Job` requires exclusive access to `Server` and `DocumentStore`
/// all previous jobs will be awaited
exclusive,
/// this `Job` requires shared access to `Server` and `DocumentStore`
/// other non exclusive jobs can be processed in parallel
shared,
/// this `Job` operates atomically and does not require any synchronisation
atomic,
};
fn syncMode(self: Job) SynchronizationMode {
return switch (self) {
.incoming_message => |parsed_message| if (isBlockingMessage(parsed_message.value)) .exclusive else .shared,
.generate_diagnostics => .shared,
.run_build_on_save => .atomic,
};
}
};
fn sendToClientResponse(server: *Server, id: types.Message.ID, result: anytype) error{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
return try server.sendToClientInternal(id, null, null, "result", result);
}
fn sendToClientRequest(server: *Server, id: types.Message.ID, method: []const u8, params: anytype) error{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
return try server.sendToClientInternal(id, method, null, "params", params);
}
fn sendToClientNotification(server: *Server, method: []const u8, params: anytype) error{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
return try server.sendToClientInternal(null, method, null, "params", params);
}
fn sendToClientResponseError(server: *Server, id: types.Message.ID, err: ?types.Message.Response.Error) error{OutOfMemory}![]u8 {
const tracy_zone = tracy.trace(@src());
defer tracy_zone.end();
return try server.sendToClientInternal(id, null, err, "", null);
}
fn sendToClientInternal(
server: *Server,
maybe_id: ?types.Message.ID,
maybe_method: ?[]const u8,
maybe_err: ?types.Message.Response.Error,
extra_name: []const u8,
extra: anytype,
) error{OutOfMemory}![]u8 {
var buffer = std.ArrayListUnmanaged(u8){};
errdefer buffer.deinit(server.allocator);
var writer = buffer.writer(server.allocator);
try writer.writeAll(
\\{"jsonrpc":"2.0"
);
if (maybe_id) |id| {
try writer.writeAll(
\\,"id":
);
try std.json.stringify(id, .{}, writer);
}
if (maybe_method) |method| {
try writer.writeAll(
\\,"method":
);
try std.json.stringify(method, .{}, writer);
}
switch (@TypeOf(extra)) {
void => {},
?void => {
try writer.print(
\\,"{s}":null
, .{extra_name});
},
else => {
try writer.print(
\\,"{s}":
, .{extra_name});
try std.json.stringify(extra, .{ .emit_null_optional_fields = false }, writer);
},
}
if (maybe_err) |err| {
try writer.writeAll(
\\,"error":
);
try std.json.stringify(err, .{}, writer);
}
try writer.writeByte('}');
if (server.transport) |transport| {
const tracy_zone_transport = tracy.traceNamed(@src(), "Transport.writeJsonMessage");
defer tracy_zone_transport.end();
transport.writeJsonMessage(buffer.items) catch |err| {
log.err("failed to write response: {}", .{err});
};
}
return buffer.toOwnedSlice(server.allocator);
}
fn showMessage(
server: *Server,
message_type: types.MessageType,
comptime fmt: []const u8,
args: anytype,
) void {
const 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}),
}
switch (server.status) {
.initializing,
.initialized,
=> {},
.uninitialized,
.shutdown,
.exiting_success,
.exiting_failure,
=> return,
}
if (server.sendToClientNotification("window/showMessage", types.ShowMessageParams{
.type = message_type,
.message = message,
})) |json_message| {
server.allocator.free(json_message);
} else |err| {
log.warn("failed to show message: {}", .{err});
}
}
fn initAnalyser(server: *Server, handle: ?*DocumentStore.Handle) Analyser {
return Analyser.init(
server.allocator,
&server.document_store,
&server.ip,
handle,
server.config.dangerous_comptime_experiments_do_not_enable,
);
}
fn getAutofixMode(server: *Server) enum {
on_save,
will_save_wait_until,
fixall,
none,
} {
if (!server.config.enable_autofix) return .none;
// TODO https://github.com/zigtools/zls/issues/1093
// if (server.client_capabilities.supports_code_action_fixall) return .fixall;
if (server.client_capabilities.supports_apply_edits) {
if (server.client_capabilities.supports_will_save_wait_until) return .will_save_wait_until;
return .on_save;
}
return .none;
}
/// caller owns returned memory.
fn autofix(server: *Server, arena: std.mem.Allocator, handle: *DocumentStore.Handle) error{OutOfMemory}!std.ArrayListUnmanaged(types.TextEdit) {
if (handle.tree.errors.len != 0) return .{};
var diagnostics = std.ArrayListUnmanaged(types.Diagnostic){};
try diagnostics_gen.getAstCheckDiagnostics(server, arena, handle, &diagnostics);
if (diagnostics.items.len == 0) return .{};
var analyser = server.initAnalyser(handle);
defer analyser.deinit();
var builder = code_actions.Builder{
.arena = arena,
.analyser = &analyser,
.handle = handle,
.offset_encoding = server.offset_encoding,
};
var actions = std.ArrayListUnmanaged(types.CodeAction){};
var remove_capture_actions = std.AutoHashMapUnmanaged(types.Range, void){};
for (diagnostics.items) |diagnostic| {
try builder.generateCodeAction(diagnostic, &actions, &remove_capture_actions);
}
var text_edits = std.ArrayListUnmanaged(types.TextEdit){};
for (actions.items) |action| {
std.debug.assert(action.kind != null);
std.debug.assert(action.edit != null);
std.debug.assert(action.edit.?.changes != null);
if (action.kind.? != .@"source.fixAll") continue;
const changes = action.edit.?.changes.?.map;
if (changes.count() != 1) continue;
const edits: []const types.TextEdit = changes.get(handle.uri) orelse continue;
try text_edits.appendSlice(arena, edits);
}
return text_edits;
}
fn initializeHandler(server: *Server, _: std.mem.Allocator, request: types.InitializeParams) Error!types.InitializeResult {
var skip_set_fixall = false;
if (request.clientInfo) |clientInfo| {
log.info("Client is '{s}-{s}'", .{ clientInfo.name, clientInfo.version orelse "<no version>" });
if (std.mem.eql(u8, clientInfo.name, "Sublime Text LSP")) {
server.client_capabilities.max_detail_length = 256;
// TODO investigate why fixall doesn't work in sublime text
server.client_capabilities.supports_code_action_fixall = false;
skip_set_fixall = true;
} else if (std.mem.eql(u8, clientInfo.name, "Visual Studio Code")) {
server.client_capabilities.supports_code_action_fixall = true;
skip_set_fixall = true;
}
}
if (request.capabilities.general) |general| {
var supports_utf8 = false;
var supports_utf16 = false;
var supports_utf32 = false;
if (general.positionEncodings) |position_encodings| {
for (position_encodings) |encoding| {
switch (encoding) {
.@"utf-8" => supports_utf8 = true,
.@"utf-16" => supports_utf16 = true,
.@"utf-32" => supports_utf32 = true,
.custom_value => {},
}
}
}
if (supports_utf8) {
server.offset_encoding = .@"utf-8";
} else if (supports_utf32) {
server.offset_encoding = .@"utf-32";
} else {
server.offset_encoding = .@"utf-16";
}
}
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;
},
.placeholder__ => {},
}
}
}
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 = synchronization.willSave orelse false;
server.client_capabilities.supports_will_save_wait_until = synchronization.willSaveWaitUntil orelse false;
}
if (textDocument.codeAction) |codeaction| {
if (codeaction.codeActionLiteralSupport) |literalSupport| {
if (!skip_set_fixall) {
for (literalSupport.codeActionKind.valueSet) |code_action_kind| {
if (code_action_kind.eql(.@"source.fixAll")) {
server.client_capabilities.supports_code_action_fixall = true;
break;
}
}
}
}
}
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 (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 (request.workspaceFolders) |workspace_folders| {
server.client_capabilities.workspace_folders = try server.allocator.alloc(types.URI, workspace_folders.len);
@memset(server.client_capabilities.workspace_folders, "");
for (server.client_capabilities.workspace_folders, workspace_folders) |*dest, src| {
dest.* = try server.allocator.dupe(u8, src.uri);
}
}
if (request.trace) |trace| {
// To support --enable-message-tracing, only allow turning this on here
if (trace != .off) {
if (server.transport) |transport| {
transport.message_tracing = true;
}
}
}
log.debug("Offset Encoding: {s}", .{@tagName(server.offset_encoding)});
server.status = .initializing;
if (!zig_builtin.is_test) {
var maybe_config_result = if (server.config_path) |config_path|
configuration.loadFromFile(server.allocator, config_path)
else
configuration.load(server.allocator);
if (maybe_config_result) |*config_result| {
defer config_result.deinit(server.allocator);
switch (config_result.*) {
.success => |config_with_path| try server.updateConfiguration2(config_with_path.config.value),
.failure => |payload| blk: {
try server.updateConfiguration(.{});
const message = try payload.toMessage(server.allocator) orelse break :blk;
defer server.allocator.free(message);
server.showMessage(.Error, "Failed to load configuration options:\n{s}", .{message});
},
.not_found => {
log.info("No config file zls.json found. This is not an error.", .{});
try server.updateConfiguration(.{});
},
}
} else |err| {
log.err("failed to load configuration: {}", .{err});
}
} else {
server.updateConfiguration(.{}) catch |err| {
log.err("failed to load configuration: {}", .{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 = .{
.TextDocumentSyncOptions = .{
.openClose = true,
.change = .Incremental,
.save = .{ .bool = true },
.willSave = true,
.willSaveWaitUntil = true,
},
},
.renameProvider = .{ .bool = true },
.completionProvider = .{
.resolveProvider = false,
.triggerCharacters = &[_][]const u8{ ".", ":", "@", "]", "/" },
.completionItem = .{ .labelDetailsSupport = true },
},
.documentHighlightProvider = .{ .bool = true },
.hoverProvider = .{ .bool = true },
.codeActionProvider = .{ .bool = true },
.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 = false },
.workspace = .{
.workspaceFolders = .{
.supported = true,
.changeNotifications = .{ .bool = true },
},
},
.semanticTokensProvider = .{
.SemanticTokensOptions = .{
.full = .{ .bool = true },
.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, _: 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_workspace_did_change_configuration_dynamic_registration) {
try server.registerCapability("workspace/didChangeConfiguration");
}
if (server.client_capabilities.supports_configuration)
try server.requestConfiguration();
if (std.crypto.random.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 cancelRequestHandler(server: *Server, _: std.mem.Allocator, request: types.CancelParams) Error!void {
_ = server;
_ = request;
// TODO implement $/cancelRequest
}
fn setTraceHandler(server: *Server, _: std.mem.Allocator, request: types.SetTraceParams) Error!void {
if (server.transport) |transport| {
transport.message_tracing = request.value != .off;
}
}
fn registerCapability(server: *Server, method: []const u8) 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.RegistrationParams{ .registrations = &.{
types.Registration{
.id = id,
.method = method,
},
} },
);
server.allocator.free(json_message);
}
fn requestConfiguration(server: *Server) Error!void {
const configuration_items = comptime config: {
var comp_config: [std.meta.fields(Config).len]types.ConfigurationItem = undefined;
for (std.meta.fields(Config), 0..) |field, index| {
comp_config[index] = .{
.section = "zls." ++ field.name,
};
}
break :config comp_config;
};
const json_message = try server.sendToClientRequest(
.{ .string = "i_haz_configuration" },
"workspace/configuration",
types.ConfigurationParams{
.items = &configuration_items,
},
);
server.allocator.free(json_message);
}
fn handleConfiguration(server: *Server, json: std.json.Value) error{OutOfMemory}!void {
const tracy_zone = tracy.trace(@src());
defer tracy_zone.end();
const fields = std.meta.fields(configuration.Configuration);
const result = switch (json) {
.array => |arr| if (arr.items.len == fields.len) arr.items else {
log.err("workspace/configuration expectes an array of size {d} but received {d}", .{ fields.len, arr.items.len });
return;
},
else => {
log.err("workspace/configuration expectes an array but received {s}", .{@tagName(json)});
return;
},
};
var arena_allocator = std.heap.ArenaAllocator.init(server.allocator);
defer arena_allocator.deinit();
const arena = arena_allocator.allocator();
var new_config: configuration.Configuration = .{};
inline for (fields, result) |field, json_value| {
const maybe_new_value = std.json.parseFromValueLeaky(field.type, arena, json_value, .{}) catch |err| blk: {
log.err("failed to parse configuration option '{s}': {}", .{ field.name, err });
break :blk null;
};
if (maybe_new_value) |new_value| {
@field(new_config, field.name) = new_value;
}
}
server.updateConfiguration(new_config) catch |err| {
log.err("failed to update configuration: {}", .{err});
};
}
fn didChangeWorkspaceFoldersHandler(server: *Server, arena: std.mem.Allocator, notification: types.DidChangeWorkspaceFoldersParams) Error!void {
_ = arena;
var folders = std.ArrayListUnmanaged(types.URI).fromOwnedSlice(server.client_capabilities.workspace_folders);
errdefer folders.deinit(server.allocator);
var i: usize = 0;
while (i < folders.items.len) {
const uri = folders.items[i];
for (notification.event.removed) |removed| {
if (std.mem.eql(u8, removed.uri, uri)) {
server.allocator.free(folders.swapRemove(i));
break;
}
} else {
i += 1;
}
}
try folders.ensureUnusedCapacity(server.allocator, notification.event.added.len);
for (notification.event.added) |added| {
folders.appendAssumeCapacity(try server.allocator.dupe(u8, added.uri));
}
server.client_capabilities.workspace_folders = try folders.toOwnedSlice(server.allocator);
}
fn didChangeConfigurationHandler(server: *Server, arena: std.mem.Allocator, notification: types.DidChangeConfigurationParams) Error!void {
const settings = switch (notification.settings) {
.null => {
if (server.client_capabilities.supports_configuration) {
try server.requestConfiguration();
}
return;
},
.object => |object| object.get("zls") orelse notification.settings,
else => notification.settings,
};
const new_config = std.json.parseFromValueLeaky(
configuration.Configuration,
arena,
settings,
.{ .ignore_unknown_fields = true },
) catch |err| {
log.err("failed to parse 'workspace/didChangeConfiguration' response: {}", .{err});
return error.ParseError;
};
try server.updateConfiguration(new_config);
}
pub fn updateConfiguration2(server: *Server, new_config: Config) error{OutOfMemory}!void {
var cfg: configuration.Configuration = .{};
inline for (std.meta.fields(Config)) |field| {
@field(cfg, field.name) = @field(new_config, field.name);
}
try server.updateConfiguration(cfg);
}
pub fn updateConfiguration(server: *Server, new_config: configuration.Configuration) error{OutOfMemory}!void {
// NOTE every changed configuration will increase the amount of memory allocated by the arena
// This is unlikely to cause any big issues since the user is probably not going set settings
// often in one session
var config_arena_allocator = server.config_arena.promote(server.allocator);
defer server.config_arena = config_arena_allocator.state;
const config_arena = config_arena_allocator.allocator();
var new_cfg: configuration.Configuration = .{};
inline for (std.meta.fields(Config)) |field| {
@field(new_cfg, field.name) = if (@field(new_config, field.name)) |new_value| new_value else @field(server.config, field.name);
}
server.validateConfiguration(&new_cfg);
const resolve_result = try resolveConfiguration(server.allocator, config_arena, &new_cfg);
defer resolve_result.deinit();
server.validateConfiguration(&new_cfg);
// <---------------------------------------------------------->
// apply changes
// <---------------------------------------------------------->
const new_zig_exe_path =
new_config.zig_exe_path != null and
(server.config.zig_exe_path == null or !std.mem.eql(u8, server.config.zig_exe_path.?, new_config.zig_exe_path.?));
const new_zig_lib_path =
new_config.zig_lib_path != null and
(server.config.zig_lib_path == null or !std.mem.eql(u8, server.config.zig_lib_path.?, new_config.zig_lib_path.?));
const new_build_runner_path =
new_config.build_runner_path != null and
(server.config.build_runner_path == null or !std.mem.eql(u8, server.config.build_runner_path.?, new_config.build_runner_path.?));
inline for (std.meta.fields(Config)) |field| {
if (@field(new_cfg, field.name)) |new_config_value| {
const old_config_value = @field(server.config, field.name);
switch (@TypeOf(old_config_value)) {
?[]const u8 => {
const override_old_value =
if (old_config_value) |old_value| !std.mem.eql(u8, old_value, new_config_value) else true;
if (override_old_value) {
log.info("Set config option '{s}' to '{s}'", .{ field.name, new_config_value });
@field(server.config, field.name) = try config_arena.dupe(u8, new_config_value);
}
},
[]const u8 => {
if (!std.mem.eql(u8, old_config_value, new_config_value)) {
log.info("Set config option '{s}' to '{s}'", .{ field.name, new_config_value });
@field(server.config, field.name) = try config_arena.dupe(u8, new_config_value);
}
},
else => {
if (old_config_value != new_config_value) {
switch (@typeInfo(@TypeOf(new_config_value))) {
.Bool,
.Int,
.Float,
=> log.info("Set config option '{s}' to '{}'", .{ field.name, new_config_value }),
.Enum => log.info("Set config option '{s}' to '{s}'", .{ field.name, @tagName(new_config_value) }),
else => @compileError("unexpected config type ++ (" ++ @typeName(@TypeOf(new_config_value)) ++ ")"),
}
@field(server.config, field.name) = new_config_value;
}
},
}
}
}
server.document_store.config = DocumentStore.Config.fromMainConfig(server.config);
if (new_zig_exe_path or new_build_runner_path) blk: {
if (!std.process.can_spawn) break :blk;
for (server.document_store.build_files.keys()) |build_file_uri| {
try server.document_store.invalidateBuildFile(build_file_uri);
}
}
if (new_zig_exe_path or new_zig_lib_path) {
for (server.document_store.cimports.values()) |*result| {
result.deinit(server.document_store.allocator);
}
server.document_store.cimports.clearAndFree(server.document_store.allocator);
}
if (server.status == .initialized) {
if (new_zig_exe_path and server.client_capabilities.supports_publish_diagnostics) {
for (server.document_store.handles.values()) |handle| {
if (!handle.isOpen()) continue;
try server.pushJob(.{ .generate_diagnostics = try server.allocator.dupe(u8, handle.uri) });
}
}
const json_message = try server.sendToClientRequest(
.{ .string = "semantic_tokens_refresh" },
"workspace/semanticTokens/refresh",
{},
);
server.allocator.free(json_message);
}
// <---------------------------------------------------------->
// don't modify config options after here, only show messages
// <---------------------------------------------------------->
if (std.process.can_spawn and server.status == .initialized and server.config.zig_exe_path == null) {
// TODO there should a way to supress this message
server.showMessage(.Warning, "zig executable could not be found", .{});
}
if (resolve_result.zig_runtime_version) |zig_version| version_check: {
// keep in mind that the ZLS version is `MAJOR.MINOR.PATCH-dev` when `git describe` failed.
const zls_version = build_options.version;
const zls_version_string = build_options.version_string;
const minimum_runtime_zig_version = comptime std.SemanticVersion.parse(build_options.minimum_runtime_zig_version_string) catch unreachable;
const zig_version_is_tagged = zig_version.pre == null and zig_version.build == null;
const zls_version_is_tagged = zls_version.pre == null and zls_version.build == null;
const zig_version_simple = std.SemanticVersion{ .major = zig_version.major, .minor = zig_version.minor, .patch = 0 };
const zls_version_simple = std.SemanticVersion{ .major = zls_version.major, .minor = zls_version.minor, .patch = 0 };
const are_different_tagged_versions = zig_version_is_tagged and zls_version_is_tagged and zig_version_simple.order(zls_version_simple) != .eq;
const minimum_zig_version_unsatisfied = zig_version.order(minimum_runtime_zig_version) == .lt;
if (are_different_tagged_versions or
(zig_version_is_tagged and !zls_version_is_tagged and minimum_zig_version_unsatisfied))
{
server.showMessage(
.Warning,
"Zig {} should be used with ZLS {} but ZLS {s} is being used.",
.{ zig_version, zig_version_simple, zls_version_string },
);
break :version_check;
}
if (zls_version_is_tagged and !zig_version_is_tagged) {
server.showMessage(
.Warning,
"ZLS {s} should be used with Zig {} but found Zig {}.",
.{ zls_version_string, zls_version_simple, zig_version },
);
break :version_check;
}
if (minimum_zig_version_unsatisfied) {
// don't report a warning when using a Zig version that has a matching build runner
if (resolve_result.build_runner_version != null and resolve_result.build_runner_version.?.isTaggedRelease()) break :version_check;
server.showMessage(
.Warning,
"ZLS {s} requires at least Zig {} but got Zig {}. Update Zig to avoid unexpected behavior.",
.{ zls_version_string, minimum_runtime_zig_version, zig_version },
);
break :version_check;
}
}
if (server.config.prefer_ast_check_as_child_process) {
if (!std.process.can_spawn) {
log.info("'prefer_ast_check_as_child_process' is ignored because your OS can't spawn a child process", .{});
} else if (server.status == .initialized and server.config.zig_exe_path == null) {
log.info("'prefer_ast_check_as_child_process' is ignored because Zig could not be found", .{});
}
}
}
fn validateConfiguration(server: *Server, config: *configuration.Configuration) void {
inline for (comptime std.meta.fieldNames(Config)) |field_name| {
const FileCheckInfo = struct {
kind: enum { file, directory },
is_accessible: bool,
};
@setEvalBranchQuota(2_000);
const file_info: FileCheckInfo = comptime if (std.mem.indexOf(u8, field_name, "path") != null) blk: {
if (std.mem.eql(u8, field_name, "zig_exe_path") or
std.mem.eql(u8, field_name, "builtin_path") or
std.mem.eql(u8, field_name, "build_runner_path"))
{
break :blk .{ .kind = .file, .is_accessible = true };
} else if (std.mem.eql(u8, field_name, "zig_lib_path")) {
break :blk .{ .kind = .directory, .is_accessible = true };
} else if (std.mem.eql(u8, field_name, "global_cache_path") or
std.mem.eql(u8, field_name, "build_runner_global_cache_path"))
{