-
-
Notifications
You must be signed in to change notification settings - Fork 304
/
Server.zig
2970 lines (2534 loc) · 113 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 requests = @import("requests.zig");
const types = @import("types.zig");
const analysis = @import("analysis.zig");
const ast = @import("ast.zig");
const references = @import("references.zig");
const offsets = @import("offsets.zig");
const semantic_tokens = @import("semantic_tokens.zig");
const inlay_hints = @import("inlay_hints.zig");
const code_actions = @import("code_actions.zig");
const shared = @import("shared.zig");
const Ast = std.zig.Ast;
const tracy = @import("tracy.zig");
const uri_utils = @import("uri.zig");
const diff = @import("diff.zig");
const ComptimeInterpreter = @import("ComptimeInterpreter.zig");
const data = @import("data/data.zig");
const snipped_data = @import("data/snippets.zig");
const log = std.log.scoped(.server);
// Server fields
config: *Config,
allocator: std.mem.Allocator = undefined,
arena: std.heap.ArenaAllocator = undefined,
document_store: DocumentStore = undefined,
builtin_completions: std.ArrayListUnmanaged(types.CompletionItem),
client_capabilities: ClientCapabilities = .{},
offset_encoding: offsets.Encoding = .utf16,
status: enum {
/// the server has not received a `initialize` request
uninitialized,
/// the server has recieved 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,
},
// Code was based off of https://github.com/andersfr/zig-lsp/blob/master/server.zig
const ClientCapabilities = struct {
supports_snippets: bool = false,
supports_semantic_tokens: bool = false,
supports_inlay_hints: bool = false,
supports_will_save: bool = false,
supports_will_save_wait_until: bool = false,
hover_supports_md: bool = false,
completion_doc_supports_md: bool = false,
label_details_support: bool = false,
supports_configuration: bool = false,
};
const not_implemented_response =
\\,"error":{"code":-32601,"message":"NotImplemented"}}
;
const null_result_response =
\\,"result":null}
;
const empty_result_response =
\\,"result":{}}
;
const empty_array_response =
\\,"result":[]}
;
const edit_not_applied_response =
\\,"result":{"applied":false,"failureReason":"feature not implemented"}}
;
const no_completions_response =
\\,"result":{"isIncomplete":false,"items":[]}}
;
const no_signatures_response =
\\,"result":{"signatures":[]}}
;
const no_semantic_tokens_response =
\\,"result":{"data":[]}}
;
/// Sends a request or response
fn send(writer: anytype, allocator: std.mem.Allocator, reqOrRes: anytype) !void {
const tracy_zone = tracy.trace(@src());
defer tracy_zone.end();
var arr = std.ArrayListUnmanaged(u8){};
defer arr.deinit(allocator);
try std.json.stringify(reqOrRes, .{}, arr.writer(allocator));
try writer.print("Content-Length: {}\r\n\r\n", .{arr.items.len});
try writer.writeAll(arr.items);
}
pub fn sendErrorResponse(writer: anytype, allocator: std.mem.Allocator, code: types.ErrorCodes, message: []const u8) !void {
try send(writer, allocator, .{
.@"error" = types.ResponseError{
.code = @enumToInt(code),
.message = message,
.data = .Null,
},
});
}
fn respondGeneric(writer: anytype, id: types.RequestId, response: []const u8) !void {
var buffered_writer = std.io.bufferedWriter(writer);
const buf_writer = buffered_writer.writer();
const tracy_zone = tracy.trace(@src());
defer tracy_zone.end();
const id_len = switch (id) {
.Integer => |id_val| blk: {
if (id_val == 0) break :blk 1;
var digits: usize = 1;
var value = @divTrunc(id_val, 10);
while (value != 0) : (value = @divTrunc(value, 10)) {
digits += 1;
}
break :blk digits;
},
.String => |str_val| str_val.len + 2,
};
// Numbers of character that will be printed from this string: len - 1 brackets
const json_fmt = "{{\"jsonrpc\":\"2.0\",\"id\":";
try buf_writer.print("Content-Length: {}\r\n\r\n" ++ json_fmt, .{response.len + id_len + json_fmt.len - 1});
switch (id) {
.Integer => |int| try buf_writer.print("{}", .{int}),
.String => |str| try buf_writer.print("\"{s}\"", .{str}),
}
try buf_writer.writeAll(response);
try buffered_writer.flush();
}
fn showMessage(server: *Server, writer: anytype, message_type: types.MessageType, message: []const u8) !void {
try send(writer, server.arena.allocator(), types.Notification{
.method = "window/showMessage",
.params = .{
.ShowMessage = .{
.type = message_type,
.message = message,
},
},
});
}
fn publishDiagnostics(server: *Server, writer: anytype, handle: DocumentStore.Handle) !void {
const tracy_zone = tracy.trace(@src());
defer tracy_zone.end();
const tree = handle.tree;
var allocator = server.arena.allocator();
var diagnostics = std.ArrayListUnmanaged(types.Diagnostic){};
for (tree.errors) |err| {
var mem_buffer: [256]u8 = undefined;
var fbs = std.io.fixedBufferStream(&mem_buffer);
try tree.renderError(err, fbs.writer());
try diagnostics.append(allocator, .{
.range = offsets.tokenToRange(tree, err.token, server.offset_encoding),
.severity = .Error,
.code = @tagName(err.tag),
.source = "zls",
.message = try server.arena.allocator().dupe(u8, fbs.getWritten()),
// .relatedInformation = undefined
});
}
if (server.config.enable_ast_check_diagnostics and tree.errors.len == 0) {
try getAstCheckDiagnostics(server, handle, &diagnostics);
}
if (server.config.warn_style) {
var node: u32 = 0;
while (node < tree.nodes.len) : (node += 1) {
if (ast.isBuiltinCall(tree, node)) {
const builtin_token = tree.nodes.items(.main_token)[node];
const call_name = tree.tokenSlice(builtin_token);
if (!std.mem.eql(u8, call_name, "@import")) continue;
var buffer: [2]Ast.Node.Index = undefined;
const params = ast.builtinCallParams(tree, node, &buffer).?;
if (params.len != 1) continue;
const import_str_token = tree.nodes.items(.main_token)[params[0]];
const import_str = tree.tokenSlice(import_str_token);
if (std.mem.startsWith(u8, import_str, "\"./")) {
try diagnostics.append(allocator, .{
.range = offsets.tokenToRange(tree, import_str_token, server.offset_encoding),
.severity = .Hint,
.code = "dot_slash_import",
.source = "zls",
.message = "A ./ is not needed in imports",
});
}
}
}
// TODO: style warnings for types, values and declarations below root scope
if (tree.errors.len == 0) {
for (tree.rootDecls()) |decl_idx| {
const decl = tree.nodes.items(.tag)[decl_idx];
switch (decl) {
.fn_proto,
.fn_proto_multi,
.fn_proto_one,
.fn_proto_simple,
.fn_decl,
=> blk: {
var buf: [1]Ast.Node.Index = undefined;
const func = ast.fnProto(tree, decl_idx, &buf).?;
if (func.extern_export_inline_token != null) break :blk;
if (func.name_token) |name_token| {
const is_type_function = analysis.isTypeFunction(tree, func);
const func_name = tree.tokenSlice(name_token);
if (!is_type_function and !analysis.isCamelCase(func_name)) {
try diagnostics.append(allocator, .{
.range = offsets.tokenToRange(tree, name_token, server.offset_encoding),
.severity = .Hint,
.code = "bad_style",
.source = "zls",
.message = "Functions should be camelCase",
});
} else if (is_type_function and !analysis.isPascalCase(func_name)) {
try diagnostics.append(allocator, .{
.range = offsets.tokenToRange(tree, name_token, server.offset_encoding),
.severity = .Hint,
.code = "bad_style",
.source = "zls",
.message = "Type functions should be PascalCase",
});
}
}
},
else => {},
}
}
}
}
for (handle.cimports.items(.hash)) |hash, i| {
const result = server.document_store.cimports.get(hash) orelse continue;
if (result != .failure) continue;
const stderr = std.mem.trim(u8, result.failure, " ");
var pos_and_diag_iterator = std.mem.split(u8, stderr, ":");
_ = pos_and_diag_iterator.next(); // skip file path
_ = pos_and_diag_iterator.next(); // skip line
_ = pos_and_diag_iterator.next(); // skip character
const node = handle.cimports.items(.node)[i];
try diagnostics.append(allocator, .{
.range = offsets.nodeToRange(handle.tree, node, server.offset_encoding),
.severity = .Error,
.code = "cImport",
.source = "zls",
.message = try allocator.dupe(u8, pos_and_diag_iterator.rest()),
});
}
if (server.config.highlight_global_var_declarations) {
const main_tokens = tree.nodes.items(.main_token);
const tags = tree.tokens.items(.tag);
for (tree.rootDecls()) |decl| {
const decl_tag = tree.nodes.items(.tag)[decl];
const decl_main_token = tree.nodes.items(.main_token)[decl];
switch (decl_tag) {
.simple_var_decl,
.aligned_var_decl,
.local_var_decl,
.global_var_decl,
=> {
if (tags[main_tokens[decl]] != .keyword_var) continue; // skip anything immutable
// uncomment this to get a list :)
//log.debug("possible global variable \"{s}\"", .{tree.tokenSlice(decl_main_token + 1)});
try diagnostics.append(allocator, .{
.range = offsets.tokenToRange(tree, decl_main_token, server.offset_encoding),
.severity = .Hint,
.code = "highlight_global_var_declarations",
.source = "zls",
.message = "Global var declaration",
});
},
else => {},
}
}
}
if (handle.interpreter) |int| {
try diagnostics.ensureUnusedCapacity(allocator, int.errors.count());
var err_it = int.errors.iterator();
while (err_it.next()) |err| {
try diagnostics.append(allocator, .{
.range = offsets.nodeToRange(tree, err.key_ptr.*, server.offset_encoding),
.severity = .Error,
.code = err.value_ptr.code,
.source = "zls",
.message = err.value_ptr.message,
});
}
}
// try diagnostics.appendSlice(allocator, handle.interpreter.?.diagnostics.items);
try send(writer, server.arena.allocator(), types.Notification{
.method = "textDocument/publishDiagnostics",
.params = .{
.PublishDiagnostics = .{
.uri = handle.uri,
.diagnostics = diagnostics.items,
},
},
});
}
fn getAstCheckDiagnostics(
server: *Server,
handle: DocumentStore.Handle,
diagnostics: *std.ArrayListUnmanaged(types.Diagnostic),
) !void {
var allocator = server.arena.allocator();
const zig_exe_path = server.config.zig_exe_path orelse return;
var process = std.ChildProcess.init(&[_][]const u8{ zig_exe_path, "ast-check", "--color", "off" }, server.allocator);
process.stdin_behavior = .Pipe;
process.stderr_behavior = .Pipe;
process.spawn() catch |err| {
log.warn("Failed to spawn zig ast-check process, error: {}", .{err});
return;
};
try process.stdin.?.writeAll(handle.text);
process.stdin.?.close();
process.stdin = null;
const stderr_bytes = try process.stderr.?.reader().readAllAlloc(server.allocator, std.math.maxInt(usize));
defer server.allocator.free(stderr_bytes);
const term = process.wait() catch |err| {
log.warn("Failed to await zig ast-check process, error: {}", .{err});
return;
};
if (term != .Exited) return;
// NOTE: I believe that with color off it's one diag per line; is this correct?
var line_iterator = std.mem.split(u8, stderr_bytes, "\n");
while (line_iterator.next()) |line| lin: {
if (!std.mem.startsWith(u8, line, "<stdin>")) continue;
var pos_and_diag_iterator = std.mem.split(u8, line, ":");
const maybe_first = pos_and_diag_iterator.next();
if (maybe_first) |first| {
if (first.len <= 1) break :lin;
} else break;
const utf8_position = types.Position{
.line = (try std.fmt.parseInt(u32, pos_and_diag_iterator.next().?, 10)) - 1,
.character = (try std.fmt.parseInt(u32, pos_and_diag_iterator.next().?, 10)) - 1,
};
// zig uses utf-8 encoding for character offsets
const position = offsets.convertPositionEncoding(handle.text, utf8_position, .utf8, server.offset_encoding);
const range = offsets.tokenPositionToRange(handle.text, position, server.offset_encoding);
const msg = pos_and_diag_iterator.rest()[1..];
if (std.mem.startsWith(u8, msg, "error: ")) {
try diagnostics.append(allocator, .{
.range = range,
.severity = .Error,
.code = "ast_check",
.source = "zls",
.message = try server.arena.allocator().dupe(u8, msg["error: ".len..]),
});
} else if (std.mem.startsWith(u8, msg, "note: ")) {
var latestDiag = &diagnostics.items[diagnostics.items.len - 1];
var fresh = if (latestDiag.relatedInformation) |related_information|
try server.arena.allocator().realloc(@ptrCast([]types.DiagnosticRelatedInformation, related_information), related_information.len + 1)
else
try server.arena.allocator().alloc(types.DiagnosticRelatedInformation, 1);
const location = types.Location{
.uri = handle.uri,
.range = range,
};
fresh[fresh.len - 1] = .{
.location = location,
.message = try server.arena.allocator().dupe(u8, msg["note: ".len..]),
};
latestDiag.relatedInformation = fresh;
} else {
try diagnostics.append(allocator, .{
.range = range,
.severity = .Error,
.code = "ast_check",
.source = "zls",
.message = try server.arena.allocator().dupe(u8, msg),
});
}
}
}
/// caller owns returned memory.
fn autofix(server: *Server, allocator: std.mem.Allocator, handle: *const DocumentStore.Handle) !std.ArrayListUnmanaged(types.TextEdit) {
var diagnostics = std.ArrayListUnmanaged(types.Diagnostic){};
try getAstCheckDiagnostics(server, handle.*, &diagnostics);
var builder = code_actions.Builder{
.arena = &server.arena,
.document_store = &server.document_store,
.handle = handle,
.offset_encoding = server.offset_encoding,
};
var actions = std.ArrayListUnmanaged(types.CodeAction){};
for (diagnostics.items) |diagnostic| {
try builder.generateCodeAction(diagnostic, &actions);
}
var text_edits = std.ArrayListUnmanaged(types.TextEdit){};
for (actions.items) |action| {
if (action.kind != .SourceFixAll) continue;
if (action.edit.changes.size != 1) continue;
const edits = action.edit.changes.get(handle.uri) orelse continue;
try text_edits.appendSlice(allocator, edits.items);
}
return text_edits;
}
fn typeToCompletion(
server: *Server,
list: *std.ArrayListUnmanaged(types.CompletionItem),
field_access: analysis.FieldAccessReturn,
orig_handle: *const DocumentStore.Handle,
) error{OutOfMemory}!void {
var allocator = server.arena.allocator();
const tracy_zone = tracy.trace(@src());
defer tracy_zone.end();
const type_handle = field_access.original;
switch (type_handle.type.data) {
.slice => {
if (!type_handle.type.is_type_val) {
try list.append(allocator, .{
.label = "len",
.detail = "const len: usize",
.kind = .Field,
.insertText = "len",
.insertTextFormat = .PlainText,
});
try list.append(allocator, .{
.label = "ptr",
.kind = .Field,
.insertText = "ptr",
.insertTextFormat = .PlainText,
});
}
},
.error_union => {},
.pointer => |n| {
if (server.config.operator_completions) {
try list.append(allocator, .{
.label = "*",
.kind = .Operator,
.insertText = "*",
.insertTextFormat = .PlainText,
});
}
try server.nodeToCompletion(
list,
.{ .node = n, .handle = type_handle.handle },
null,
orig_handle,
type_handle.type.is_type_val,
null,
);
},
.other => |n| try server.nodeToCompletion(
list,
.{ .node = n, .handle = type_handle.handle },
field_access.unwrapped,
orig_handle,
type_handle.type.is_type_val,
null,
),
.primitive, .array_index => {},
.@"comptime" => |co| {
const ti = co.type.getTypeInfo();
switch (ti) {
.@"struct" => |st| {
var fit = st.fields.iterator();
while (fit.next()) |entry| {
try list.append(allocator, .{
.label = entry.key_ptr.*,
.kind = .Field,
.insertText = entry.key_ptr.*,
.insertTextFormat = .PlainText,
});
}
var it = st.scope.declarations.iterator();
while (it.next()) |entry| {
try list.append(allocator, .{
.label = entry.key_ptr.*,
.kind = if (entry.value_ptr.isConstant()) .Constant else .Variable,
.insertText = entry.key_ptr.*,
.insertTextFormat = .PlainText,
});
}
},
else => {},
}
},
}
}
fn nodeToCompletion(
server: *Server,
list: *std.ArrayListUnmanaged(types.CompletionItem),
node_handle: analysis.NodeWithHandle,
unwrapped: ?analysis.TypeWithHandle,
orig_handle: *const DocumentStore.Handle,
is_type_val: bool,
parent_is_type_val: ?bool,
) error{OutOfMemory}!void {
const tracy_zone = tracy.trace(@src());
defer tracy_zone.end();
var allocator = server.arena.allocator();
const node = node_handle.node;
const handle = node_handle.handle;
const tree = handle.tree;
const node_tags = tree.nodes.items(.tag);
const token_tags = tree.tokens.items(.tag);
const doc_kind: types.MarkupContent.Kind = if (server.client_capabilities.completion_doc_supports_md)
.Markdown
else
.PlainText;
const doc = if (try analysis.getDocComments(
allocator,
handle.tree,
node,
doc_kind,
)) |doc_comments|
types.MarkupContent{
.kind = doc_kind,
.value = doc_comments,
}
else
null;
if (ast.isContainer(handle.tree, node)) {
const context = DeclToCompletionContext{
.server = server,
.completions = list,
.orig_handle = orig_handle,
.parent_is_type_val = is_type_val,
};
try analysis.iterateSymbolsContainer(
&server.document_store,
&server.arena,
node_handle,
orig_handle,
declToCompletion,
context,
!is_type_val,
);
}
if (is_type_val) return;
switch (node_tags[node]) {
.fn_proto,
.fn_proto_multi,
.fn_proto_one,
.fn_proto_simple,
.fn_decl,
=> {
var buf: [1]Ast.Node.Index = undefined;
const func = ast.fnProto(tree, node, &buf).?;
if (func.name_token) |name_token| {
const use_snippets = server.config.enable_snippets and server.client_capabilities.supports_snippets;
const insert_text = if (use_snippets) blk: {
const skip_self_param = !(parent_is_type_val orelse true) and
try analysis.hasSelfParam(&server.arena, &server.document_store, handle, func);
break :blk try analysis.getFunctionSnippet(server.arena.allocator(), tree, func, skip_self_param);
} else tree.tokenSlice(func.name_token.?);
const is_type_function = analysis.isTypeFunction(handle.tree, func);
try list.append(allocator, .{
.label = handle.tree.tokenSlice(name_token),
.kind = if (is_type_function) .Struct else .Function,
.documentation = doc,
.detail = analysis.getFunctionSignature(handle.tree, func),
.insertText = insert_text,
.insertTextFormat = if (use_snippets) .Snippet else .PlainText,
});
}
},
.global_var_decl,
.local_var_decl,
.aligned_var_decl,
.simple_var_decl,
=> {
const var_decl = ast.varDecl(tree, node).?;
const is_const = token_tags[var_decl.ast.mut_token] == .keyword_const;
if (try analysis.resolveVarDeclAlias(&server.document_store, &server.arena, node_handle)) |result| {
const context = DeclToCompletionContext{
.server = server,
.completions = list,
.orig_handle = orig_handle,
};
return try declToCompletion(context, result);
}
try list.append(allocator, .{
.label = handle.tree.tokenSlice(var_decl.ast.mut_token + 1),
.kind = if (is_const) .Constant else .Variable,
.documentation = doc,
.detail = analysis.getVariableSignature(tree, var_decl),
.insertText = tree.tokenSlice(var_decl.ast.mut_token + 1),
.insertTextFormat = .PlainText,
});
},
.container_field,
.container_field_align,
.container_field_init,
=> {
const field = ast.containerField(tree, node).?;
if (!field.ast.tuple_like) {
try list.append(allocator, .{
.label = handle.tree.tokenSlice(field.ast.main_token),
.kind = .Field,
.documentation = doc,
.detail = analysis.getContainerFieldSignature(handle.tree, field),
.insertText = tree.tokenSlice(field.ast.main_token),
.insertTextFormat = .PlainText,
});
}
},
.array_type,
.array_type_sentinel,
=> {
try list.append(allocator, .{
.label = "len",
.detail = "const len: usize",
.kind = .Field,
.insertText = "len",
.insertTextFormat = .PlainText,
});
},
.ptr_type,
.ptr_type_aligned,
.ptr_type_bit_range,
.ptr_type_sentinel,
=> {
const ptr_type = ast.ptrType(tree, node).?;
switch (ptr_type.size) {
.One, .C, .Many => if (server.config.operator_completions) {
try list.append(allocator, .{
.label = "*",
.kind = .Operator,
.insertText = "*",
.insertTextFormat = .PlainText,
});
},
.Slice => {
try list.append(allocator, .{
.label = "ptr",
.kind = .Field,
.insertText = "ptr",
.insertTextFormat = .PlainText,
});
try list.append(allocator, .{
.label = "len",
.detail = "const len: usize",
.kind = .Field,
.insertText = "len",
.insertTextFormat = .PlainText,
});
return;
},
}
if (unwrapped) |actual_type| {
try server.typeToCompletion(list, .{ .original = actual_type }, orig_handle);
}
return;
},
.optional_type => {
if (server.config.operator_completions) {
try list.append(allocator, .{
.label = "?",
.kind = .Operator,
.insertText = "?",
.insertTextFormat = .PlainText,
});
}
return;
},
.string_literal => {
try list.append(allocator, .{
.label = "len",
.detail = "const len: usize",
.kind = .Field,
.insertText = "len",
.insertTextFormat = .PlainText,
});
},
else => if (analysis.nodeToString(tree, node)) |string| {
try list.append(allocator, .{
.label = string,
.kind = .Field,
.documentation = doc,
.detail = offsets.nodeToSlice(tree, node),
.insertText = string,
.insertTextFormat = .PlainText,
});
},
}
}
pub fn identifierFromPosition(pos_index: usize, handle: DocumentStore.Handle) []const u8 {
if (pos_index + 1 >= handle.text.len) return "";
var start_idx = pos_index;
while (start_idx > 0 and isSymbolChar(handle.text[start_idx - 1])) {
start_idx -= 1;
}
var end_idx = pos_index;
while (end_idx < handle.text.len and isSymbolChar(handle.text[end_idx])) {
end_idx += 1;
}
if (end_idx <= start_idx) return "";
return handle.text[start_idx..end_idx];
}
fn isSymbolChar(char: u8) bool {
return std.ascii.isAlphanumeric(char) or char == '_';
}
fn gotoDefinitionSymbol(
server: *Server,
decl_handle: analysis.DeclWithHandle,
resolve_alias: bool,
) error{OutOfMemory}!?types.Location {
const tracy_zone = tracy.trace(@src());
defer tracy_zone.end();
var handle = decl_handle.handle;
const name_token = switch (decl_handle.decl.*) {
.ast_node => |node| block: {
if (resolve_alias) {
if (try analysis.resolveVarDeclAlias(&server.document_store, &server.arena, .{ .node = node, .handle = handle })) |result| {
handle = result.handle;
break :block result.nameToken();
}
}
break :block analysis.getDeclNameToken(handle.tree, node) orelse return null;
},
else => decl_handle.nameToken(),
};
return types.Location{
.uri = handle.uri,
.range = offsets.tokenToRange(handle.tree, name_token, server.offset_encoding),
};
}
fn hoverSymbol(server: *Server, decl_handle: analysis.DeclWithHandle) error{OutOfMemory}!?types.Hover {
const tracy_zone = tracy.trace(@src());
defer tracy_zone.end();
const handle = decl_handle.handle;
const tree = handle.tree;
const hover_kind: types.MarkupContent.Kind = if (server.client_capabilities.hover_supports_md) .Markdown else .PlainText;
var doc_str: ?[]const u8 = null;
const def_str = switch (decl_handle.decl.*) {
.ast_node => |node| def: {
if (try analysis.resolveVarDeclAlias(&server.document_store, &server.arena, .{ .node = node, .handle = handle })) |result| {
return try server.hoverSymbol(result);
}
doc_str = try analysis.getDocComments(server.arena.allocator(), tree, node, hover_kind);
var buf: [1]Ast.Node.Index = undefined;
if (ast.varDecl(tree, node)) |var_decl| {
break :def analysis.getVariableSignature(tree, var_decl);
} else if (ast.fnProto(tree, node, &buf)) |fn_proto| {
break :def analysis.getFunctionSignature(tree, fn_proto);
} else if (ast.containerField(tree, node)) |field| {
break :def analysis.getContainerFieldSignature(tree, field);
} else {
break :def analysis.nodeToString(tree, node) orelse return null;
}
},
.param_payload => |pay| def: {
const param = pay.param;
if (param.first_doc_comment) |doc_comments| {
doc_str = try analysis.collectDocComments(server.arena.allocator(), handle.tree, doc_comments, hover_kind, false);
}
const first_token = ast.paramFirstToken(tree, param);
const last_token = ast.paramLastToken(tree, param);
const start = offsets.tokenToIndex(tree, first_token);
const end = offsets.tokenToLoc(tree, last_token).end;
break :def tree.source[start..end];
},
.pointer_payload, .array_payload, .array_index, .switch_payload, .label_decl => tree.tokenSlice(decl_handle.nameToken()),
};
var bound_type_params = analysis.BoundTypeParams{};
const resolved_type = try decl_handle.resolveType(&server.document_store, &server.arena, &bound_type_params);
const resolved_type_str = if (resolved_type) |rt|
if (rt.type.is_type_val) switch (rt.type.data) {
.@"comptime" => |*co| try std.fmt.allocPrint(server.arena.allocator(), "{ }", .{co.interpreter.formatTypeInfo(co.type.getTypeInfo())}),
else => "type",
} else switch (rt.type.data) { // TODO: Investigate random weird numbers like 897 that cause index of bounds
.pointer,
.slice,
.error_union,
.primitive,
=> |p| if (p >= tree.nodes.len) "unknown" else offsets.nodeToSlice(tree, p),
.other => |p| if (p >= tree.nodes.len) "unknown" else switch (tree.nodes.items(.tag)[p]) {
.container_decl,
.container_decl_arg,
.container_decl_arg_trailing,
.container_decl_trailing,
.container_decl_two,
.container_decl_two_trailing,
.tagged_union,
.tagged_union_trailing,
.tagged_union_two,
.tagged_union_two_trailing,
.tagged_union_enum_tag,
.tagged_union_enum_tag_trailing,
=> tree.tokenSlice(tree.nodes.items(.main_token)[p] - 2), // NOTE: This is a hacky nightmare but it works :P
.fn_proto,
.fn_proto_multi,
.fn_proto_one,
.fn_proto_simple,
.fn_decl,
=> "fn", // TODO:(?) Add more info?
.array_type,
.array_type_sentinel,
.ptr_type,
.ptr_type_aligned,
.ptr_type_bit_range,
.ptr_type_sentinel,
=> offsets.nodeToSlice(tree, p),
else => "unknown", // TODO: Implement more "other" type expressions; better safe than sorry
},
else => "unknown",
}
else
"unknown";
var hover_text: []const u8 = undefined;
if (hover_kind == .Markdown) {
hover_text =
if (doc_str) |doc|
try std.fmt.allocPrint(server.arena.allocator(), "```zig\n{s}\n```\n```zig\n({s})\n```\n{s}", .{ def_str, resolved_type_str, doc })
else
try std.fmt.allocPrint(server.arena.allocator(), "```zig\n{s}\n```\n```zig\n({s})\n```", .{ def_str, resolved_type_str });
} else {
hover_text =
if (doc_str) |doc|
try std.fmt.allocPrint(server.arena.allocator(), "{s} ({s})\n{s}", .{ def_str, resolved_type_str, doc })
else
try std.fmt.allocPrint(server.arena.allocator(), "{s} ({s})", .{ def_str, resolved_type_str });
}
return types.Hover{
.contents = .{ .value = hover_text },
};
}
fn getLabelGlobal(pos_index: usize, handle: *const DocumentStore.Handle) error{OutOfMemory}!?analysis.DeclWithHandle {
const tracy_zone = tracy.trace(@src());
defer tracy_zone.end();
const name = identifierFromPosition(pos_index, handle.*);
if (name.len == 0) return null;
return try analysis.lookupLabel(handle, name, pos_index);
}
fn getSymbolGlobal(
server: *Server,
pos_index: usize,
handle: *const DocumentStore.Handle,
) error{OutOfMemory}!?analysis.DeclWithHandle {
const tracy_zone = tracy.trace(@src());
defer tracy_zone.end();
const name = identifierFromPosition(pos_index, handle.*);
if (name.len == 0) return null;
return try analysis.lookupSymbolGlobal(&server.document_store, &server.arena, handle, name, pos_index);
}
fn gotoDefinitionLabel(
server: *Server,
pos_index: usize,
handle: *const DocumentStore.Handle,
) error{OutOfMemory}!?types.Location {
const tracy_zone = tracy.trace(@src());
defer tracy_zone.end();
const decl = (try getLabelGlobal(pos_index, handle)) orelse return null;
return try server.gotoDefinitionSymbol(decl, false);
}
fn gotoDefinitionGlobal(
server: *Server,
pos_index: usize,
handle: *const DocumentStore.Handle,
resolve_alias: bool,
) error{OutOfMemory}!?types.Location {
const tracy_zone = tracy.trace(@src());
defer tracy_zone.end();
const decl = (try server.getSymbolGlobal(pos_index, handle)) orelse return null;
return try server.gotoDefinitionSymbol(decl, resolve_alias);
}
fn hoverDefinitionLabel(server: *Server, pos_index: usize, handle: *const DocumentStore.Handle) error{OutOfMemory}!?types.Hover {
const tracy_zone = tracy.trace(@src());
defer tracy_zone.end();
const decl = (try getLabelGlobal(pos_index, handle)) orelse return null;
return try server.hoverSymbol(decl);
}
fn hoverDefinitionBuiltin(server: *Server, pos_index: usize, handle: *const DocumentStore.Handle) error{OutOfMemory}!?types.Hover {
const tracy_zone = tracy.trace(@src());
defer tracy_zone.end();
const name = identifierFromPosition(pos_index, handle.*);
if (name.len == 0) return null;
for (data.builtins) |builtin| {
if (std.mem.eql(u8, builtin.name[1..], name)) {
return types.Hover{
.contents = .{
.value = try std.fmt.allocPrint(
server.arena.allocator(),
"```zig\n{s}\n```\n{s}",
.{ builtin.signature, builtin.documentation },
),
},
};
}