-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
main.vala
1885 lines (1677 loc) · 81 KB
/
main.vala
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
using LanguageServer;
using Gee;
class Vls.Request : Object {
private int64? int_value;
private string? string_value;
private string? method;
public Request (Variant id, string? method = null) {
assert (id.is_of_type (VariantType.INT64) || id.is_of_type (VariantType.STRING));
if (id.is_of_type (VariantType.INT64))
int_value = (int64) id;
else
string_value = (string) id;
this.method = method;
}
public string to_string () {
string id_string = int_value != null ? int_value.to_string () : string_value;
return id_string + (method != null ? @":$method" : "");
}
public static uint hash (Request req) {
if (req.int_value != null)
return GLib.int64_hash (req.int_value);
else
return GLib.str_hash (req.string_value);
}
public static bool equal (Request reqA, Request reqB) {
if (reqA.int_value != null) {
assert (reqB.int_value != null);
return reqA.int_value == reqB.int_value;
} else {
assert (reqB.string_value != null);
return reqA.string_value == reqB.string_value;
}
}
}
class Vls.Server : Object {
private static bool received_signal = false;
Jsonrpc.Server server;
MainLoop loop;
HashTable<string, NotificationHandler> notif_handlers;
HashTable<string, CallHandler> call_handlers;
InitializeParams init_params;
const uint check_update_context_period_ms = 100;
const int64 update_context_delay_inc_us = 500 * 1000;
const int64 update_context_delay_max_us = 1000 * 1000;
const uint wait_for_context_update_delay_ms = 200;
Project project;
#if PARSE_SYSTEM_GIRS
/**
* Contains documentation from found GIR files.
*/
GirDocumentation documentation;
#endif
HashSet<Request> pending_requests;
bool shutting_down = false;
bool is_initialized = false;
/**
* The global cancellable object
*/
public static Cancellable cancellable = new Cancellable ();
[CCode (has_target = false)]
delegate void NotificationHandler (Vls.Server self, Jsonrpc.Client client, Variant @params);
[CCode (has_target = false)]
delegate void CallHandler (Vls.Server self, Jsonrpc.Server server, Jsonrpc.Client client, string method, Variant id, Variant @params);
private void log_handler (string? log_domain, LogLevelFlags log_levels, string message) {
string level = "";
if ((log_levels & LogLevelFlags.LEVEL_MASK) == LogLevelFlags.LEVEL_MASK)
level = "-ALL";
else if ((log_levels & LogLevelFlags.LEVEL_CRITICAL) != 0)
level = "-CRITICAL";
else if ((log_levels & LogLevelFlags.LEVEL_DEBUG) != 0)
level = "-DEBUG";
else if ((log_levels & LogLevelFlags.LEVEL_ERROR) != 0)
level = "-ERROR";
else if ((log_levels & LogLevelFlags.LEVEL_INFO) != 0)
level = "-INFO";
else if ((log_levels & LogLevelFlags.LEVEL_MESSAGE) != 0)
level = "-MESSAGE";
else if ((log_levels & LogLevelFlags.LEVEL_WARNING) != 0)
level = "-WARNING";
printerr ("%s: %s\n", log_domain == null ? @"vls$level" : log_domain, message);
}
uint[] g_sources = {};
ulong client_closed_event_id;
ulong project_changed_event_id;
static construct {
Process.@signal (ProcessSignal.INT, () => {
if (!Server.received_signal)
cancellable.cancel ();
Server.received_signal = true;
});
Process.@signal (ProcessSignal.TERM, () => {
if (!Server.received_signal)
cancellable.cancel ();
Server.received_signal = true;
});
}
public Server (MainLoop loop) {
// capture logging
Log.set_handler (null, LogLevelFlags.LEVEL_MASK, log_handler);
Log.set_handler ("jsonrpc-server", LogLevelFlags.LEVEL_MASK, log_handler);
this.loop = loop;
this.server = new Jsonrpc.Server ();
// hack to prevent other things from corrupting JSON-RPC pipe:
// create a new handle to stdout, and close the old one (or move it to stderr)
#if WINDOWS
var new_stdout_fd = Windows._dup (Posix.STDOUT_FILENO);
Windows._close (Posix.STDOUT_FILENO);
Windows._dup2 (Posix.STDERR_FILENO, Posix.STDOUT_FILENO);
void* new_stdin_handle = Windows._get_osfhandle (Posix.STDIN_FILENO);
void* new_stdout_handle = Windows._get_osfhandle (new_stdout_fd);
// we can't use the names 'stdin' or 'stdout' for these variables
// since it causes build problems for mingw-w64-x86_64-gcc
var input_stream = new Win32InputStream (new_stdin_handle, false);
var output_stream = new Win32OutputStream (new_stdout_handle, false);
#else
var new_stdout_fd = Posix.dup (Posix.STDOUT_FILENO);
Posix.close (Posix.STDOUT_FILENO);
Posix.dup2 (Posix.STDERR_FILENO, Posix.STDOUT_FILENO);
var input_stream = new UnixInputStream (Posix.STDIN_FILENO, false);
var output_stream = new UnixOutputStream (new_stdout_fd, false);
// set nonblocking
try {
if (!Unix.set_fd_nonblocking (Posix.STDIN_FILENO, true)
|| !Unix.set_fd_nonblocking (new_stdout_fd, true))
error ("could not set pipes to nonblocking.\n");
} catch (Error e) {
debug ("failed to set FDs to nonblocking");
loop.quit ();
return;
}
#endif
// shutdown if/when we get a signal
g_sources += Timeout.add (1 * 1000, () => {
if (Server.received_signal) {
shutdown_real ();
return Source.REMOVE;
}
return !this.shutting_down;
});
server.accept_io_stream (new SimpleIOStream (input_stream, output_stream));
#if WITH_JSONRPC_GLIB_3_30
client_closed_event_id = server.client_closed.connect (client => {
shutdown_real ();
});
#endif
notif_handlers = new HashTable<string, NotificationHandler> (str_hash, str_equal);
call_handlers = new HashTable<string, CallHandler> (str_hash, str_equal);
pending_requests = new HashSet<Request> (Request.hash, Request.equal);
server.notification.connect ((client, method, @params) => {
debug (@"Got notification! $method");
if (!is_initialized) {
debug ("Server is not initialized");
} else if (notif_handlers.contains (method))
((NotificationHandler) notif_handlers[method]) (this, client, @params);
else
debug (@"no notification handler for $method");
});
server.handle_call.connect ((client, method, id, @params) => {
debug (@"Got call! $method");
if (!is_initialized && !(method == "initialize" ||
method == "shutdown" ||
method == "exit")) {
debug ("Server is not initialized");
return false;
} else if (call_handlers.contains (method)) {
((CallHandler) call_handlers[method]) (this, server, client, method, id, @params);
return true;
} else {
debug (@"no call handler for $method");
return false;
}
});
call_handlers["initialize"] = this.initialize;
call_handlers["shutdown"] = this.shutdown;
notif_handlers["exit"] = this.exit;
call_handlers["textDocument/definition"] = this.textDocumentDefinition;
notif_handlers["textDocument/didOpen"] = this.textDocumentDidOpen;
notif_handlers["textDocument/didClose"] = this.textDocumentDidClose;
notif_handlers["textDocument/didChange"] = this.textDocumentDidChange;
call_handlers["textDocument/documentSymbol"] = this.textDocumentDocumentSymbol;
call_handlers["textDocument/completion"] = this.textDocumentCompletion;
call_handlers["textDocument/signatureHelp"] = this.textDocumentSignatureHelp;
call_handlers["textDocument/hover"] = this.textDocumentHover;
call_handlers["textDocument/references"] = this.textDocumentReferences;
call_handlers["textDocument/documentHighlight"] = this.textDocumentReferences;
call_handlers["textDocument/implementation"] = this.textDocumentImplementation;
call_handlers["workspace/symbol"] = this.workspaceSymbol;
notif_handlers["$/cancelRequest"] = this.cancelRequest;
debug ("Finished constructing");
}
// a{sv} only
public Variant buildDict (...) {
var builder = new VariantBuilder (new VariantType ("a{sv}"));
var l = va_list ();
while (true) {
string? key = l.arg ();
if (key == null) {
break;
}
Variant val = l.arg ();
builder.add ("{sv}", key, val);
}
return builder.end ();
}
void showMessage (Jsonrpc.Client client, string message, MessageType type) {
if (type == MessageType.Error)
warning (message);
try {
client.send_notification ("window/showMessage", buildDict (
type: new Variant.int16 (type),
message: new Variant.string (message)
), cancellable);
} catch (Error e) {
debug (@"showMessage: failed to notify client: $(e.message)");
}
}
void initialize (Jsonrpc.Server self, Jsonrpc.Client client, string method, Variant id, Variant @params) {
init_params = Util.parse_variant<InitializeParams> (@params);
File root_dir;
if (init_params.rootUri != null)
root_dir = File.new_for_uri (init_params.rootUri);
else if (init_params.rootPath != null)
root_dir = File.new_for_path (init_params.rootPath);
else
root_dir = File.new_for_path (Environment.get_current_dir ());
if (!root_dir.is_native ()) {
showMessage (client, "Non-native files not supported", MessageType.Error);
error ("Non-native files not supported");
}
string root_path = Util.realpath ((!) root_dir.get_path ());
debug (@"[initialize] root path is $root_path");
// respond
try {
client.reply (id, buildDict (
capabilities: buildDict (
textDocumentSync: new Variant.int16 (TextDocumentSyncKind.Incremental),
definitionProvider: new Variant.boolean (true),
documentSymbolProvider: new Variant.boolean (true),
completionProvider: buildDict(
triggerCharacters: new Variant.strv (new string[] {".", ">"})
),
signatureHelpProvider: buildDict(
triggerCharacters: new Variant.strv (new string[] {"(", ","})
),
hoverProvider: new Variant.boolean (true),
referencesProvider: new Variant.boolean (true),
documentHighlightProvider: new Variant.boolean (true),
implementationProvider: new Variant.boolean (true),
workspaceSymbolProvider: new Variant.boolean (true)
),
serverInfo: buildDict (
name: new Variant.string ("Vala Language Server"),
version: new Variant.string (Config.version)
)
), cancellable);
} catch (Error e) {
error (@"[initialize] failed to reply to client: $(e.message)");
}
var meson_file = root_dir.get_child ("meson.build");
ArrayList<File> cc_files = new ArrayList<File> ();
try {
cc_files = Util.find_files (root_dir, /compile_commands\.json/, 2);
} catch (Error e) {
warning ("could not enumerate root dir - %s", e.message);
}
// TODO: autotools, make(?), cmake(?)
if (meson_file.query_exists (cancellable)) {
try {
project = new MesonProject (root_path, cancellable);
} catch (Error e) {
if (!(e is ProjectError.VERSION_UNSUPPORTED)) {
showMessage (client, @"Failed to initialize Meson project - $(e.message)", MessageType.Error);
}
}
}
// try compile_commands.json if Meson failed
if (project == null && !cc_files.is_empty) {
foreach (var cc_file in cc_files) {
string cc_file_path = Util.realpath (cc_file.get_path ());
try {
project = new CcProject (root_path, cc_file_path, cancellable);
debug ("[initialize] initialized CcProject with %s", cc_file_path);
break;
} catch (Error e) {
debug ("[initialize] CcProject failed with %s - %s", cc_file_path, e.message);
continue;
}
}
}
// use DefaultProject as a last resort
if (project == null) {
project = new DefaultProject (root_path);
var cmake_file = root_dir.get_child ("CMakeLists.txt");
var autogen_sh = root_dir.get_child ("autogen.sh");
if (cmake_file.query_exists (cancellable))
showMessage (client, @"CMake build system is not currently supported. Only Meson is. See https://github.com/benwaffle/vala-language-server/issues/73", MessageType.Warning);
if (autogen_sh.query_exists (cancellable))
showMessage (client, @"Autotools build system is not currently supported. Consider switching to Meson.", MessageType.Warning);
}
try {
project.build_if_stale (cancellable);
} catch (Error e) {
showMessage (client, @"failed to build project - $(e.message)", MessageType.Error);
warning ("[initialize] failed to build project - %s", e.message);
return;
}
#if PARSE_SYSTEM_GIRS
// create documentation (compiles GIR files too)
documentation = new GirDocumentation (project.get_packages ());
#endif
// build and publish diagnostics
try {
debug ("Building project ...");
project.build_if_stale ();
debug ("Publishing diagnostics ...");
foreach (var compilation in project.get_compilations ())
publishDiagnostics (compilation, client);
} catch (Error e) {
showMessage (client, @"Failed to build project - $(e.message)", MessageType.Error);
}
// listen for context update requests
update_context_client = client;
g_sources += Timeout.add (check_update_context_period_ms, () => {
check_update_context ();
return !this.shutting_down;
});
project_changed_event_id = project.changed.connect (project_changed_event);
is_initialized = true;
}
void project_changed_event () {
request_context_update (update_context_client);
debug ("requested context update for project change event");
}
void cancelRequest (Jsonrpc.Client client, Variant @params) {
Variant? id = @params.lookup_value ("id", null);
if (id == null)
return;
var req = new Request (id);
if (pending_requests.remove (req))
debug (@"[cancelRequest] cancelled request $req");
else
debug (@"[cancelRequest] request $req not found");
}
public static void reply_null (Variant id, Jsonrpc.Client client, string method) {
try {
client.reply (id, new Variant.maybe (VariantType.VARIANT, null), cancellable);
} catch (Error e) {
debug (@"[$method] failed to reply to client: $(e.message)");
}
}
void textDocumentDidOpen (Jsonrpc.Client client, Variant @params) {
var document = @params.lookup_value ("textDocument", VariantType.VARDICT);
string? uri = (string) document.lookup_value ("uri", VariantType.STRING);
string languageId = (string) document.lookup_value ("languageId", VariantType.STRING);
string fileContents = (string) document.lookup_value ("text", VariantType.STRING);
if (languageId != "vala" && languageId != "genie") {
warning (@"[textDocument/didOpen] $languageId file sent to vala language server");
return;
}
if (uri == null) {
warning (@"[textDocument/didOpen] null URI sent to vala language server");
return;
}
try {
project.open (uri, cancellable);
} catch (Error e) {
warning ("[textDocument/didOpen] failed to open %s - %s", uri, e.message);
return;
}
foreach (Pair<Vala.SourceFile, Compilation> doc_w_bt in project.lookup_compile_input_source_file (uri)) {
var doc = doc_w_bt.first;
// We want to load the document unconditionally, to avoid
// errors later on in textDocument/didChange. However, we
// only want to edit it if it is an actual TextDocument.
if (doc.content == null)
doc.get_mapped_contents ();
if (doc is TextDocument) {
debug (@"[textDocument/didOpen] opened $(Uri.unescape_string (uri))");
if (doc.content != fileContents) {
doc.content = fileContents;
request_context_update (client);
debug (@"[textDocument/didOpen] requested context update");
}
} else {
debug (@"[textDocument/didOpen] opened read-only $(Uri.unescape_string (uri))");
}
}
}
void textDocumentDidClose (Jsonrpc.Client client, Variant @params) {
var document = @params.lookup_value ("textDocument", VariantType.VARDICT);
string? uri = (string) document.lookup_value ("uri", VariantType.STRING);
if (uri == null) {
warning (@"[textDocument/didClose] null URI sent to vala language server");
return;
}
try {
if (project.close (uri)) {
request_context_update (client);
debug (@"[textDocument/didClose] requested context update");
}
} catch (Error e) {
warning ("[textDocument/didClose] failed to close %s - %s", uri, e.message);
}
}
Jsonrpc.Client? update_context_client = null;
int64 update_context_requests = 0;
int64 update_context_time_us = 0;
void textDocumentDidChange (Jsonrpc.Client client, Variant @params) {
var document = @params.lookup_value ("textDocument", VariantType.VARDICT);
var changes = @params.lookup_value ("contentChanges", VariantType.ARRAY);
var uri = (string) document.lookup_value ("uri", VariantType.STRING);
var version = (int64) document.lookup_value ("version", VariantType.INT64);
foreach (Pair<Vala.SourceFile, Compilation> pair in project.lookup_compile_input_source_file (uri)) {
var source_file = pair.first;
if (!(source_file is TextDocument)) {
debug (@"[textDocument/didChange] Ignoring change to system file");
return;
}
var source = (TextDocument) source_file;
if (source.version >= version) {
debug (@"[textDocument/didChange] rejecting outdated version of $uri");
return;
}
if (source_file.content == null) {
error (@"[textDocument/didChange] source content is null!");
}
// update the document
var iter = changes.iterator ();
Variant? elem = null;
var sb = new StringBuilder (source.content);
while ((elem = iter.next_value ()) != null) {
var changeEvent = Util.parse_variant<TextDocumentContentChangeEvent> (elem);
if (changeEvent.range == null) {
sb.assign (changeEvent.text);
} else {
var start = changeEvent.range.start;
var end = changeEvent.range.end;
size_t pos_begin = Util.get_string_pos (sb.str, start.line, start.character);
size_t pos_end = Util.get_string_pos (sb.str, end.line, end.character);
sb.erase ((ssize_t) pos_begin, (ssize_t) (pos_end - pos_begin));
sb.insert ((ssize_t) pos_begin, changeEvent.text);
}
}
source.content = sb.str;
source.last_updated = new DateTime.now ();
source.version = (int) version;
request_context_update (client);
}
}
void request_context_update (Jsonrpc.Client client) {
update_context_client = client;
update_context_requests += 1;
int64 delay_us = int64.min (update_context_delay_inc_us * update_context_requests, update_context_delay_max_us);
update_context_time_us = get_monotonic_time () + delay_us;
debug (@"Context(s) update (re-)scheduled in $((int) (delay_us / 1000)) ms");
}
/**
* Reconfigure the project if needed, and check whether we need to rebuild
* the project if we have context update requests.
*/
void check_update_context () {
if (update_context_requests > 0 && get_monotonic_time () >= update_context_time_us) {
debug ("updating contexts and publishing diagnostics...");
update_context_requests = 0;
update_context_time_us = 0;
try {
project.reconfigure_if_stale (cancellable);
project.build_if_stale (cancellable);
foreach (var compilation in project.get_compilations ())
/* This must come after the resetting of the two variables above,
* since it's possible for publishDiagnostics to eventually call
* one of our JSON-RPC callbacks through g_main_context_iteration (),
* if we get a new message while sending the textDocument/publishDiagnostics
* notifications. */
publishDiagnostics (compilation, update_context_client);
} catch (Error e) {
warning ("Failed to rebuild and/or reconfigure project: %s", e.message);
}
}
}
public delegate void OnContextUpdatedFunc (bool request_cancelled);
/**
* Rather than satisfying all requests in `check_update_context ()`,
* to avoid race conditions, we have to spawn a timeout to check for
* the right conditions to call `on_context_updated_func ()`.
*/
public void wait_for_context_update (Variant id, owned OnContextUpdatedFunc on_context_updated_func) {
// we've already updated the context
if (update_context_requests == 0)
on_context_updated_func (false);
else {
var req = new Request (id);
if (!pending_requests.add (req))
debug (@"Request ($req): request already in pending requests, this should not happen");
else
debug (@"Request ($req): added request to pending requests");
wait_for_context_update_aux (req, (owned) on_context_updated_func);
}
}
/**
* Execute `on_context_updated_func ()` or wait.
*/
void wait_for_context_update_aux (Request req, owned OnContextUpdatedFunc on_context_updated_func) {
// we've already updated the context
if (update_context_requests == 0) {
if (!pending_requests.remove (req)) {
debug (@"Request ($req): context updated but request cancelled");
on_context_updated_func (true);
} else {
debug (@"Request ($req): context updated");
on_context_updated_func (false);
}
} else {
Timeout.add (wait_for_context_update_delay_ms, () => {
if (pending_requests.contains (req))
wait_for_context_update_aux (req, (owned) on_context_updated_func);
else {
debug (@"Request ($req): cancelled before context update");
on_context_updated_func (true);
}
return Source.REMOVE;
});
}
}
void publishDiagnostics (Compilation target, Jsonrpc.Client client) {
var files_not_published = new HashSet<Vala.SourceFile> (Util.source_file_hash, Util.source_file_equal);
var diags_without_source = new Json.Array ();
debug ("publishing diagnostics for Compilation target %s", target.id);
foreach (var file in target.code_context.get_source_files ())
files_not_published.add (file);
var doc_diags = new HashMap<Vala.SourceFile, Json.Array> ();
target.reporter.messages.foreach (err => {
if (err.loc == null) {
diags_without_source.add_element (Json.gobject_serialize (new Diagnostic () {
severity = err.severity,
message = err.message
}));
return;
}
assert (err.loc.file != null);
if (!(err.loc.file in target.code_context.get_source_files ())) {
warning (@"diagnostic has source not in compilation! - $(err.message)");
return;
}
var diag = new Diagnostic () {
range = new Range () {
start = new Position () {
line = err.loc.begin.line - 1,
character = err.loc.begin.column - 1
},
end = new Position () {
line = err.loc.end.line - 1,
character = err.loc.end.column
}
},
severity = err.severity,
message = err.message
};
var node = Json.gobject_serialize (diag);
if (!doc_diags.has_key (err.loc.file))
doc_diags[err.loc.file] = new Json.Array ();
doc_diags[err.loc.file].add_element (node);
});
// at the end, report diags for each source file
foreach (var entry in doc_diags.entries) {
Variant diags_variant_array;
var gfile = File.new_for_path (entry.key.filename);
files_not_published.remove (entry.key);
try {
diags_variant_array = Json.gvariant_deserialize (
new Json.Node.alloc ().init_array (entry.value),
null);
} catch (Error e) {
warning (@"[publishDiagnostics] failed to deserialize diags for `$(gfile.get_uri ())': $(e.message)");
continue;
}
try {
client.send_notification (
"textDocument/publishDiagnostics",
buildDict (
uri: new Variant.string (gfile.get_uri ()),
diagnostics: diags_variant_array
),
cancellable);
} catch (Error e) {
debug (@"[publishDiagnostics] failed to notify client: $(e.message)");
}
}
foreach (var entry in files_not_published) {
var gfile = File.new_for_path (entry.filename);
try {
client.send_notification (
"textDocument/publishDiagnostics",
buildDict (
uri: new Variant.string (gfile.get_uri ()),
diagnostics: new Variant.array (VariantType.VARIANT, new Variant[]{})
),
cancellable);
} catch (Error e) {
debug (@"[publishDiagnostics] failed to publish empty diags for $(gfile.get_uri ()): $(e.message)");
}
}
try {
Variant diags_wo_src_variant_array = Json.gvariant_deserialize (
new Json.Node.alloc ().init_array (diags_without_source),
null);
client.send_notification (
"textDocument/publishDiagnostics",
buildDict (
diagnostics: diags_wo_src_variant_array
),
cancellable);
} catch (Error e) {
debug (@"[publishDiagnostics] failed to publish diags without source: $(e.message)");
}
}
public static Vala.CodeNode get_best (FindSymbol fs, Vala.SourceFile file) {
Vala.CodeNode? best = null;
foreach (var node in fs.result) {
if (best == null) {
best = node;
} else {
var best_begin = new Position.from_libvala (best.source_reference.begin);
var best_end = new Position.from_libvala (best.source_reference.end);
var node_begin = new Position.from_libvala (node.source_reference.begin);
var node_end = new Position.from_libvala (node.source_reference.end);
// it turns out that if multiple CodeNodes share the same range, the first one we
// encounter will usually be the "right" one
if (best_begin.compare_to (node_begin) <= 0 && node_end.compare_to (best_end) <= 0 &&
(!(best_begin.compare_to (node_begin) == 0 && node_end.compare_to (best_end) == 0) ||
// allow exception for local variables (pick the last one) - this helps foreach
(best is Vala.LocalVariable && node is Vala.LocalVariable) ||
// allow exception for lone properties - their implicit _* fields are declared in the same location
(best is Vala.Field && node is Vala.Property)
)) {
best = node;
}
}
}
assert (best != null);
// var sr = best.source_reference;
// var from = (long)Util.get_string_pos (file.content, sr.begin.line-1, sr.begin.column-1);
// var to = (long)Util.get_string_pos (file.content, sr.end.line-1, sr.end.column);
// string contents = file.content [from:to];
// debug ("Got best node: %s @ %s = %s", best.type_name, sr.to_string(), contents);
return (!) best;
}
/**
* Gets the symbol you really want, not something from a generated file.
*
* If `sym` comes from a generated file (eg. a VAPI), then
* it would be more useful to show the file specific to the compilation
* that generated the file.
*/
Vala.Symbol find_real_sym (Vala.Symbol sym) {
Compilation alter_comp;
if (sym.source_reference == null || sym.source_reference.file == null)
return sym;
if (project.lookup_compilation_for_output_file (sym.source_reference.file.filename, out alter_comp)) {
Vala.Symbol? matching_sym;
if (sym is Vala.Symbol) {
if ((matching_sym = Util.find_matching_symbol (alter_comp.code_context, (Vala.Symbol)sym)) != null) {
return matching_sym;
}
}
}
return sym;
}
void textDocumentDefinition (Jsonrpc.Server self, Jsonrpc.Client client, string method, Variant id, Variant @params) {
var p = Util.parse_variant<LanguageServer.TextDocumentPositionParams> (@params);
var results = project.lookup_compile_input_source_file (p.textDocument.uri);
if (results.is_empty) {
debug (@"[$method] file `$(p.textDocument.uri)' not found");
reply_null (id, client, method);
return;
}
wait_for_context_update (id, request_cancelled => {
if (request_cancelled) {
reply_null (id, client, method);
return;
}
// ignore multiple results
Vala.SourceFile file = results[0].first;
Compilation compilation = results[0].second;
Vala.CodeContext.push (compilation.code_context);
var fs = new FindSymbol (file, p.position);
if (fs.result.size == 0) {
try {
client.reply (id, new Variant.maybe (VariantType.VARIANT, null), cancellable);
} catch (Error e) {
debug("[textDocument/definition] failed to reply to client: %s", e.message);
}
Vala.CodeContext.pop ();
return;
}
Vala.CodeNode? best = get_best (fs, file);
if (best is Vala.Expression && !(best is Vala.Literal)) {
var b = (Vala.Expression)best;
debug ("best (%p) is a Expression (symbol_reference = %p)", best, b.symbol_reference);
if (b.symbol_reference != null && b.symbol_reference.source_reference != null) {
best = b.symbol_reference;
debug ("best is now the symbol_referenece => %p (%s)", best, best.to_string ());
}
} else if (best is Vala.DataType) {
var dt = best as Vala.DataType;
if (dt.type_symbol != null)
best = dt.type_symbol;
else if (dt.symbol != null)
best = dt.symbol;
} else {
try {
client.reply (id, new Variant.maybe (VariantType.VARIANT, null), cancellable);
} catch (Error e) {
debug("[textDocument/definition] failed to reply to client: %s", e.message);
}
Vala.CodeContext.pop ();
return;
}
if (best is Vala.Symbol)
best = find_real_sym ((Vala.Symbol) best);
var location = new Location.from_sourceref (best.source_reference);
debug ("[textDocument/definition] found location ... %s", location.uri);
try {
client.reply (id, Util.object_to_variant (location), cancellable);
} catch (Error e) {
debug("[textDocument/definition] failed to reply to client: %s", e.message);
}
Vala.CodeContext.pop ();
});
}
void textDocumentDocumentSymbol (Jsonrpc.Server self, Jsonrpc.Client client, string method, Variant id, Variant @params) {
var p = Util.parse_variant<LanguageServer.TextDocumentPositionParams>(@params);
var results = project.lookup_compile_input_source_file (p.textDocument.uri);
if (results.is_empty) {
debug (@"[$method] file `$(p.textDocument.uri)' not found");
reply_null (id, client, method);
return;
}
wait_for_context_update (id, request_cancelled => {
if (request_cancelled) {
reply_null (id, client, method);
return;
}
// ignore multiple results
Vala.SourceFile file = results[0].first;
Compilation compilation = results[0].second;
Vala.CodeContext.push (compilation.code_context);
var array = new Json.Array ();
var syms = new ListSymbols (file);
if (init_params.capabilities.textDocument.documentSymbol.hierarchicalDocumentSymbolSupport)
foreach (var dsym in syms) {
// debug(@"found $(dsym.name)");
array.add_element (Json.gobject_serialize (dsym));
}
else {
foreach (var dsym in syms.flattened ()) {
// debug(@"found $(dsym.name)");
array.add_element (Json.gobject_serialize (new SymbolInformation.from_document_symbol (dsym, p.textDocument.uri)));
}
}
try {
Variant result = Json.gvariant_deserialize (new Json.Node.alloc ().init_array (array), null);
client.reply (id, result, cancellable);
} catch (Error e) {
debug (@"[textDocument/documentSymbol] failed to reply to client: $(e.message)");
}
Vala.CodeContext.pop ();
});
}
public static Range get_best_range (Vala.Symbol sym) {
var range = new Range.from_sourceref (sym.source_reference);
if (sym is Vala.Method) {
var m = (Vala.Method) sym;
if (m.body != null && m.body.source_reference != null)
range = range.union (get_best_range (m.body));
}
return range;
}
public static string get_expr_repr (Vala.Expression expr) {
if (expr is Vala.Literal)
return expr.to_string ();
var sr = expr.source_reference;
var file = sr.file;
if (file.content == null)
file.content = (string) file.get_mapped_contents ();
var from = (long) Util.get_string_pos (file.content, sr.begin.line-1, sr.begin.column-1);
var to = (long) Util.get_string_pos (file.content, sr.end.line-1, sr.end.column);
return file.content [from:to];
}
public delegate bool FindFunc (Vala.CodeNode node);
public static Vala.CodeNode? find_ancestor (Vala.CodeNode start_node, FindFunc filter) {
for (Vala.CodeNode? current_node = start_node;
current_node != null;
current_node = current_node.parent_node)
if (filter (current_node))
return current_node;
return null;
}
/**
* Return the string representation of a symbol's type. This is used as the detailed
* information for a completion item.
*/
public static string? get_symbol_data_type (Vala.Symbol? sym, bool only_type_names = false,
Vala.Symbol? parent = null, bool show_inits = false, string? name_override = null) {
if (sym == null) {
return null;
} else if (sym is Vala.Property) {
var prop_sym = sym as Vala.Property;
if (prop_sym.property_type == null)
return null;
string weak_kw = (prop_sym.property_type.value_owned ||
!(prop_sym.property_type is Vala.ReferenceType)) ? "" : "weak ";
if (only_type_names)
return @"$weak_kw$(prop_sym.property_type)";
else {
string? parent_str = get_symbol_data_type (parent, only_type_names);
if (parent_str != null)
parent_str = @"$(parent_str)::";
else
parent_str = "";
return @"$weak_kw$(prop_sym.property_type) $parent_str$(prop_sym.name)";
}
} else if (sym is Vala.Callable) {
var method_sym = sym as Vala.Callable;
if (method_sym.return_type == null)
return null;
var creation_method = sym as Vala.CreationMethod;
string? ret_type = method_sym.return_type.to_string ();
string delg_type = (method_sym is Vala.Delegate) ? "delegate " : "";
bool is_async = method_sym is Vala.Method &&
((Vala.Method)method_sym).coroutine &&
!((Vala.Method)method_sym).get_async_begin_parameters ().is_empty;
string param_string = "";
bool at_least_one = false;
var parameters = (is_async && name_override == "begin") ?
((Vala.Method)method_sym).get_async_begin_parameters () : method_sym.get_parameters ();
foreach (var p in parameters) {
if (at_least_one)
param_string += ", ";
param_string += get_symbol_data_type (p, only_type_names, null, show_inits);
at_least_one = true;
}
string type_params = "";
if (method_sym is Vala.Method) {
var m = (Vala.Method) method_sym;
at_least_one = false;
foreach (var type_param in m.get_type_parameters ()) {
if (!at_least_one)
type_params += "<";
else
type_params += ",";
type_params += type_param.name;
at_least_one = true;
}
if (at_least_one)
type_params += ">";
}
string extern_kw = method_sym.is_extern ? "extern " : "";
string async_type = is_async ? "async ": "";
string signal_type = (method_sym is Vala.Signal) ? "signal " : "";
string err_string = "";
var error_types = new Vala.ArrayList<Vala.DataType> ();
method_sym.get_error_types (error_types);
if (!error_types.is_empty) {
err_string = " throws ";
at_least_one = false;
foreach (var dt in error_types) {
if (at_least_one)
err_string += ", ";
err_string += get_symbol_data_type (dt.type_symbol, true);
at_least_one = true;
}
}
string? parent_str = parent != null ? parent.to_string () : null;
if (creation_method == null) {
if (parent_str != null)
parent_str = @"$parent_str::";
else
parent_str = "";
return extern_kw + async_type + signal_type + delg_type +
(ret_type ?? "void") + @" $parent_str$(name_override ?? sym.name)$type_params ($param_string)$err_string";
} else {
string sym_name = name_override ?? (sym.name == ".new" ? (parent_str ?? creation_method.class_name) : sym.name);