/
server.ex
2303 lines (1897 loc) · 69.6 KB
/
server.ex
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
defmodule ElixirLS.LanguageServer.Server do
@moduledoc """
Language Server Protocol server
This server tracks open files, attempts to rebuild the project when a file changes, and handles
requests from the IDE (for things like autocompletion, hover, etc.)
Notifications from the IDE are handled synchronously, whereas requests can be handled synchronously
or asynchronously.
When possible, handling the request asynchronously has several advantages. The asynchronous
request handling cannot modify the server state. That way, if the process handling the request
crashes, we can report that error to the client and continue knowing that the state is
uncorrupted. Also, asynchronous requests can be cancelled by the client if they're taking too long
or the user no longer cares about the result.
"""
use GenServer
require Logger
alias ElixirLS.LanguageServer.{
SourceFile,
Build,
Protocol,
JsonRpc,
Dialyzer,
Diagnostics,
MixProjectCache,
Parser
}
alias ElixirLS.LanguageServer.Providers.{
Completion,
Hover,
Definition,
Implementation,
References,
Formatting,
SignatureHelp,
DocumentSymbols,
WorkspaceSymbols,
OnTypeFormatting,
CodeLens,
ExecuteCommand,
FoldingRange,
SelectionRanges
}
alias ElixirLS.Utils.Launch
alias ElixirLS.LanguageServer.Tracer
alias ElixirLS.Utils.MixfileHelpers
use Protocol
defstruct [
:server_instance_id,
:build_ref,
:dialyzer_sup,
:client_capabilities,
:root_uri,
:project_dir,
:settings,
last_published_diagnostics_uris: [],
parser_diagnostics: %{},
document_versions_on_build: %{},
build_diagnostics: [],
dialyzer_diagnostics: [],
needs_build?: false,
full_build_done?: false,
build_running?: false,
analysis_ready?: false,
received_shutdown?: false,
requests: %{},
requests_ids_by_pid: %{},
# Tracks source files that are currently open in the editor
source_files: %{},
awaiting_contracts: [],
mix_project?: false,
mix_env: nil,
mix_target: nil,
no_mixfile_warned?: false,
default_settings: %{}
]
defmodule InvalidParamError do
defexception [:uri, :message]
@impl true
def exception(uri) do
msg = "invalid URI: #{inspect(uri)}"
%InvalidParamError{message: msg, uri: uri}
end
end
defmodule ContentModifiedError do
defexception [:uri, :message]
@impl true
def exception(uri) do
msg = "document URI: #{inspect(uri)} modified"
%ContentModifiedError{message: msg, uri: uri}
end
end
@default_watched_extensions [
".ex",
".exs",
".erl",
".hrl",
".yrl",
".xrl",
".eex",
".leex",
".heex",
".sface"
]
@default_config_timeout 3
## Client API
def start_link(name \\ nil) do
GenServer.start_link(__MODULE__, :ok, name: name || __MODULE__)
end
def receive_packet(server \\ __MODULE__, packet) do
GenServer.cast(server, {:receive_packet, packet})
end
def build_finished(server \\ __MODULE__, result) do
GenServer.cast(server, {:build_finished, result})
end
def dialyzer_finished(server \\ __MODULE__, diagnostics, build_ref) do
GenServer.cast(server, {:dialyzer_finished, diagnostics, build_ref})
end
def parser_finished(server \\ __MODULE__, diagnostics) do
GenServer.cast(server, {:parser_finished, diagnostics})
end
def rebuild(server \\ __MODULE__) do
GenServer.cast(server, :rebuild)
end
def suggest_contracts(server \\ __MODULE__, uri) do
GenServer.call(server, {:suggest_contracts, uri}, :infinity)
end
defguardp is_initialized(server_instance_id) when not is_nil(server_instance_id)
## Server Callbacks
@impl GenServer
def init(:ok) do
{:ok, %__MODULE__{}}
end
@impl GenServer
def terminate(reason, _state) do
case reason do
:normal ->
:ok
:shutdown ->
:ok
{:shutdown, _} ->
:ok
_other ->
do_sanity_check()
message = Exception.format_exit(reason)
JsonRpc.telemetry(
"lsp_server_error",
%{
"elixir_ls.lsp_process" => inspect(__MODULE__),
"elixir_ls.lsp_server_error" => message
},
%{}
)
Logger.error("Terminating #{__MODULE__}: #{message}")
unless :persistent_term.get(:language_server_test_mode, false) do
Process.sleep(2000)
System.halt(1)
else
IO.warn("Terminating #{__MODULE__}: #{message}")
end
end
:ok
end
@impl GenServer
def handle_call({:request_finished, id, result}, _from, state = %__MODULE__{}) do
# in case the request has been cancelled we silently ignore
{popped_request, updated_requests} = Map.pop(state.requests, id)
requests_ids_by_pid =
if popped_request do
{pid, ref, command, start_time} = popped_request
# we are no longer interested in :DOWN message
Process.demonitor(ref, [:flush])
case result do
{:error, type, msg, send_telemetry} ->
JsonRpc.respond_with_error(id, type, msg)
do_sanity_check(msg || to_string(type))
if send_telemetry do
JsonRpc.telemetry(
"lsp_request_error",
%{
"elixir_ls.lsp_command" => String.replace(command, "/", "_"),
"elixir_ls.lsp_error" => to_string(type),
"elixir_ls.lsp_error_message" => msg || to_string(type)
},
%{}
)
end
{:ok, result} ->
elapsed = System.monotonic_time(:millisecond) - start_time
JsonRpc.respond(id, result)
JsonRpc.telemetry(
"lsp_request",
%{"elixir_ls.lsp_command" => String.replace(command, "/", "_")},
%{
"elixir_ls.lsp_request_time" => elapsed
}
)
end
Map.delete(state.requests_ids_by_pid, pid)
else
state.requests_ids_by_pid
end
state = %{state | requests: updated_requests, requests_ids_by_pid: requests_ids_by_pid}
{:reply, :ok, state}
end
@impl GenServer
def handle_call({:suggest_contracts, uri = "file:" <> _}, from, state = %__MODULE__{}) do
case state do
%{analysis_ready?: true, source_files: %{^uri => %{dirty?: false}}} ->
abs_path = SourceFile.Path.absolute_from_uri(uri, state.project_dir)
parent = self()
spawn(fn ->
contracts = Dialyzer.suggest_contracts(parent, [abs_path])
GenServer.reply(from, contracts)
end)
{:noreply, state}
%{source_files: %{^uri => _}} ->
# file not saved or analysis not finished
awaiting_contracts = reject_awaiting_contracts(state.awaiting_contracts, uri)
{:noreply, %{state | awaiting_contracts: [{from, uri} | awaiting_contracts]}}
_ ->
# file not or no longer open
{:reply, [], state}
end
end
def handle_call({:suggest_contracts, _uri}, _from, state = %__MODULE__{}) do
{:reply, [], state}
end
@impl GenServer
def handle_cast({:build_finished, {status, diagnostics}}, state = %__MODULE__{})
when status in [:ok, :noop, :error, :no_mixfile] and is_list(diagnostics) do
{:noreply, handle_build_result(status, diagnostics, state)}
end
@impl GenServer
def handle_cast({:dialyzer_finished, diagnostics, build_ref}, state = %__MODULE__{}) do
{:noreply, handle_dialyzer_result(diagnostics, build_ref, state)}
end
@impl GenServer
def handle_cast({:parser_finished, diagnostics}, state = %__MODULE__{}) do
state =
%{state | parser_diagnostics: diagnostics}
|> publish_diagnostics()
{:noreply, state}
end
@impl GenServer
def handle_cast({:receive_packet, request(id, _method, _) = packet}, state = %__MODULE__{}) do
new_state = handle_request_packet(id, packet, state)
{:noreply, new_state}
end
@impl GenServer
def handle_cast({:receive_packet, request(id, method)}, state = %__MODULE__{}) do
new_state = handle_request_packet(id, request(id, method, nil), state)
{:noreply, new_state}
end
@impl GenServer
def handle_cast(
{:receive_packet, notification(_method) = packet},
state = %__MODULE__{received_shutdown?: false, server_instance_id: server_instance_id}
)
when is_initialized(server_instance_id) do
new_state = handle_notification(packet, state)
{:noreply, new_state}
end
@impl GenServer
def handle_cast({:receive_packet, notification(_) = packet}, state = %__MODULE__{}) do
case packet do
notification("exit") ->
new_state = handle_notification(packet, state)
{:noreply, new_state}
_ ->
{:noreply, state}
end
end
@impl GenServer
def handle_cast(:rebuild, state = %__MODULE__{}) do
{:noreply, trigger_build(state)}
end
@impl GenServer
def handle_info(:default_config, state = %__MODULE__{settings: nil}) do
Logger.warning(
"Did not receive workspace/didChangeConfiguration notification after #{@default_config_timeout} seconds. " <>
"The server will use default config."
)
state = set_settings(state, state.default_settings)
{:noreply, state}
end
def handle_info(:default_config, state = %__MODULE__{}) do
# we got workspace/didChangeConfiguration in time, nothing to do here
{:noreply, state}
end
@impl GenServer
def handle_info(
{:DOWN, ref, _, _pid, reason},
%__MODULE__{build_ref: ref, build_running?: true} = state
) do
state = %{state | build_running?: false}
# in case the build was interrupted make sure that cwd is reset to project dir
case File.cd(state.project_dir) do
:ok ->
:ok
{:error, reason} ->
message =
"Cannot change directory to project dir #{state.project_dir}: #{inspect(reason)}"
Logger.error(message)
JsonRpc.show_message(:error, message)
unless :persistent_term.get(:language_server_test_mode, false) do
Process.sleep(2000)
System.halt(1)
else
IO.warn(message)
end
end
state =
case reason do
:normal ->
WorkspaceSymbols.notify_build_complete()
state
_ ->
message = Exception.format_exit(reason)
JsonRpc.telemetry(
"build_error",
%{"elixir_ls.build_error" => message},
%{}
)
path = Path.join(state.project_dir, MixfileHelpers.mix_exs())
handle_build_result(
:error,
[Diagnostics.from_shutdown_reason(reason, path, state.project_dir)],
state
)
end
state =
if state.needs_build? do
trigger_build(state)
else
state
end
{:noreply, state}
end
@impl GenServer
def handle_info(
{:DOWN, ref, :process, pid, reason},
%__MODULE__{requests: requests, requests_ids_by_pid: requests_ids_by_pid} = state
) do
{id, updated_requests_ids_by_pid} = Map.pop(requests_ids_by_pid, pid)
updated_requests =
if id do
{{^pid, ^ref, command, _start_time}, updated_requests} = Map.pop!(requests, id)
error_msg = Exception.format_exit(reason)
JsonRpc.respond_with_error(id, :internal_error, error_msg)
do_sanity_check(error_msg)
JsonRpc.telemetry(
"lsp_request_error",
%{
"elixir_ls.lsp_command" => String.replace(command, "/", "_"),
"elixir_ls.lsp_error" => :internal_error,
"elixir_ls.lsp_error_message" => error_msg
},
%{}
)
updated_requests
else
requests
end
{:noreply,
%{state | requests: updated_requests, requests_ids_by_pid: updated_requests_ids_by_pid}}
end
## Helpers
defp handle_notification(notification("initialized"), state = %__MODULE__{}) do
# according to https://github.com/microsoft/language-server-protocol/issues/567#issuecomment-1060605611
# this is the best point to pull configuration
state = pull_configuration(state)
unless state.settings do
# We still don't have the configuration. Let's wait for workspace/didChangeConfiguration
Process.send_after(self(), :default_config, @default_config_timeout * 1000)
end
supports_dynamic_configuration_change_registration =
get_in(state.client_capabilities, [
"workspace",
"didChangeConfiguration",
"dynamicRegistration"
])
if supports_dynamic_configuration_change_registration do
Logger.info("Registering for workspace/didChangeConfiguration notifications")
listen_for_configuration_changes(state.server_instance_id)
else
Logger.info("Client does not support workspace/didChangeConfiguration dynamic registration")
end
supports_dynamic_file_watcher_registration =
get_in(state.client_capabilities, [
"workspace",
"didChangeWatchedFiles",
"dynamicRegistration"
])
if supports_dynamic_file_watcher_registration do
Logger.info("Registering for workspace/didChangeWatchedFiles notifications")
add_watched_extensions(state.server_instance_id, @default_watched_extensions)
else
Logger.info("Client does not support workspace/didChangeWatchedFiles dynamic registration")
end
state
end
defp handle_notification(
cancel_request(id),
%__MODULE__{requests: requests, requests_ids_by_pid: requests_ids_by_pid} = state
) do
{request, updated_requests} = Map.pop(requests, id)
updated_requests_ids_by_pid =
if request do
{pid, ref, _command, _start_time} = request
# we are no longer interested in :DOWN message
Process.demonitor(ref, [:flush])
Process.exit(pid, :cancelled)
JsonRpc.respond_with_error(id, :request_cancelled, "Request cancelled")
Map.delete(requests_ids_by_pid, pid)
else
Logger.debug("Received $/cancelRequest for unknown request id: #{inspect(id)}")
requests_ids_by_pid
end
%{state | requests: updated_requests, requests_ids_by_pid: updated_requests_ids_by_pid}
end
# We don't start performing builds until we receive settings from the client in case they've set
# the `projectDir` or `mixEnv` settings.
# note that clients supporting `workspace/configuration` will send nil and we need to pull
defp handle_notification(did_change_configuration(changed_settings), state = %__MODULE__{}) do
Logger.info("Received workspace/didChangeConfiguration")
prev_settings = state.settings || %{}
case changed_settings do
%{"elixirLS" => settings} when is_map(settings) ->
Logger.info(
"Received client configuration via workspace/didChangeConfiguration\n#{inspect(settings)}"
)
# deprecated push based configuration - interesting config updated
new_settings = Map.merge(prev_settings, settings)
set_settings(state, new_settings)
nil ->
# pull based configuration
# on notification the server should pull current configuration
# see https://github.com/microsoft/language-server-protocol/issues/1792
pull_configuration(state)
_ ->
# deprecated push based configuration - some other config updated
set_settings(state, prev_settings)
end
end
defp handle_notification(notification("exit"), state = %__MODULE__{}) do
code = if state.received_shutdown?, do: 0, else: 1
unless :persistent_term.get(:language_server_test_mode, false) do
System.stop(code)
else
Logger.info("Received exit with code #{code}")
end
state
end
defp handle_notification(did_open(uri, language_id, version, text), state = %__MODULE__{}) do
if Map.has_key?(state.source_files, uri) do
# An open notification must not be sent more than once without a corresponding
# close notification send before
Logger.warning(
"Received textDocument/didOpen for file that is already open. Received uri: #{inspect(uri)}"
)
state
else
unless String.valid?(text) do
JsonRpc.telemetry(
"lsp_server_error",
%{
"elixir_ls.lsp_process" => inspect(__MODULE__),
"elixir_ls.lsp_server_error" => "File not valid on open:\n#{inspect(text)}"
},
%{}
)
Logger.error("File not valid on open:\n#{inspect(text)}")
end
source_file = %SourceFile{text: text, version: version, language_id: language_id}
Parser.parse_with_debounce(uri, source_file)
put_in(state.source_files[uri], source_file)
end
end
defp handle_notification(did_close(uri), state = %__MODULE__{}) do
if not Map.has_key?(state.source_files, uri) do
# A close notification requires a previous open notification to be sent
Logger.warning(
"Received textDocument/didClose for file that is not open. Received uri: #{inspect(uri)}"
)
state
else
awaiting_contracts = reject_awaiting_contracts(state.awaiting_contracts, uri)
Parser.notify_closed(uri)
%{
state
| source_files: Map.delete(state.source_files, uri),
awaiting_contracts: awaiting_contracts
}
end
end
defp handle_notification(did_change(uri, version, content_changes), state = %__MODULE__{}) do
if not Map.has_key?(state.source_files, uri) do
# The source file was not marked as open either due to a bug in the
# client or a restart of the server. So just ignore the message and do
# not update the state
Logger.warning(
"Received textDocument/didChange for file that is not open. Received uri: #{inspect(uri)}"
)
state
else
state =
update_in(state.source_files[uri], fn source_file ->
# LSP 3.17: The version number points to the version after all provided content changes have
# been applied
updated_source_file =
%SourceFile{source_file | version: version, dirty?: true}
|> SourceFile.apply_content_changes(content_changes)
Parser.parse_with_debounce(uri, updated_source_file)
unless String.valid?(updated_source_file.text) do
JsonRpc.telemetry(
"lsp_server_error",
%{
"elixir_ls.lsp_process" => inspect(__MODULE__),
"elixir_ls.lsp_server_error" =>
"File not valid after: #{inspect(content_changes)} text was:\n#{inspect(source_file.text)}"
},
%{}
)
Logger.error(
"File not valid after: #{inspect(content_changes)} text was:\n#{inspect(source_file.text)}"
)
end
updated_source_file
end)
state
end
end
defp handle_notification(did_save(uri), state = %__MODULE__{}) do
if not Map.has_key?(state.source_files, uri) do
Logger.warning(
"Received textDocument/didSave for file that is not open. Received uri: #{inspect(uri)}"
)
state
else
WorkspaceSymbols.notify_uris_modified([uri])
state = update_in(state.source_files[uri], &%{&1 | dirty?: false})
trigger_build(state)
end
end
defp handle_notification(
did_change_watched_files(changes),
state = %__MODULE__{project_dir: project_dir}
)
when is_binary(project_dir) do
changes = Enum.filter(changes, &match?(%{"uri" => "file:" <> _}, &1))
# `settings` may not always be available here, like during testing
additional_watched_extensions =
Map.get(state.settings || %{}, "additionalWatchedExtensions", [])
needs_build =
Enum.any?(changes, fn %{"uri" => uri = "file:" <> _, "type" => type} ->
path = SourceFile.Path.from_uri(uri)
relative_path = Path.relative_to(path, state.project_dir)
first_path_segment = relative_path |> Path.split() |> hd
first_path_segment not in [".elixir_ls", "_build"] and
Path.extname(path) in (additional_watched_extensions ++ @default_watched_extensions) and
(type in [1, 3] or not Map.has_key?(state.source_files, uri) or
state.source_files[uri].dirty?)
end)
deleted_paths =
for change <- changes,
change["type"] == 3,
do: SourceFile.Path.from_uri(change["uri"])
for path <- deleted_paths do
Tracer.notify_file_deleted(path)
end
source_files =
changes
|> Enum.reduce(state.source_files, fn
%{"type" => 3}, acc ->
# deleted file still open in editor, keep dirty flag
acc
%{"uri" => uri = "file:" <> _}, acc ->
# file created/updated - set dirty flag to false if file contents are equal
case acc[uri] do
%SourceFile{text: source_file_text, dirty?: true} = source_file ->
case File.read(SourceFile.Path.from_uri(uri)) do
{:ok, ^source_file_text} ->
Map.put(acc, uri, %SourceFile{source_file | dirty?: false})
{:ok, _} ->
acc
{:error, reason} ->
Logger.warning("Unable to read #{uri}: #{inspect(reason)}")
# keep dirty if read fails
acc
end
_ ->
# file not open or not dirty
acc
end
end)
state = %{state | source_files: source_files}
changes
|> Enum.map(& &1["uri"])
|> WorkspaceSymbols.notify_uris_modified()
if needs_build do
trigger_build(state)
else
state
end
end
defp handle_notification(did_change_watched_files(_changes), state = %__MODULE__{}) do
# swallow notification if we are not in mix_project
state
end
defp handle_notification(%{"method" => "$/" <> _}, state = %__MODULE__{}) do
# not supported "$/" notifications may be safely ignored
state
end
defp handle_notification(packet, state = %__MODULE__{}) do
Logger.warning("Received unmatched notification: #{inspect(packet)}")
state
end
defp handle_request_packet(
id,
packet,
state = %__MODULE__{server_instance_id: server_instance_id}
)
when not is_initialized(server_instance_id) do
start_time = System.monotonic_time(:millisecond)
case packet do
initialize_req(_id, _root_uri, _client_capabilities) ->
try do
{:ok, result, state} = handle_request(packet, state)
elapsed = System.monotonic_time(:millisecond) - start_time
JsonRpc.respond(id, result)
JsonRpc.telemetry("lsp_request", %{"elixir_ls.lsp_command" => "initialize"}, %{
"elixir_ls.lsp_request_time" => elapsed
})
state
catch
kind, payload ->
{payload, stacktrace} = Exception.blame(kind, payload, __STACKTRACE__)
error_msg = Exception.format(kind, payload, stacktrace)
# on error in initialize the protocol requires to respond with
# https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#initializeError
# the initialize request can fail on broken OTP installs, no point in retrying
JsonRpc.respond_with_error(id, :internal_error, error_msg, %{
"retry" => false
})
do_sanity_check(error_msg)
JsonRpc.telemetry(
"lsp_request_error",
%{
"elixir_ls.lsp_command" => "initialize",
"elixir_ls.lsp_error" => :internal_error,
"elixir_ls.lsp_error_message" => error_msg
},
%{}
)
state
end
_ ->
JsonRpc.respond_with_error(id, :server_not_initialized)
JsonRpc.telemetry(
"lsp_request_error",
%{
"elixir_ls.lsp_command" => "initialize",
"elixir_ls.lsp_error" => :server_not_initialized,
"elixir_ls.lsp_error_message" => "Server not initialized"
},
%{}
)
state
end
end
defp handle_request_packet(
id,
packet = %{"method" => command},
state = %__MODULE__{received_shutdown?: false}
) do
command =
case packet do
execute_command_req(_id, custom_command_with_server_id, _args) ->
command <> ":" <> (ExecuteCommand.get_command(custom_command_with_server_id) || "")
_ ->
command
end
start_time = System.monotonic_time(:millisecond)
try do
case handle_request(packet, state) do
{:ok, result, state} ->
elapsed = System.monotonic_time(:millisecond) - start_time
JsonRpc.respond(id, result)
JsonRpc.telemetry(
"lsp_request",
%{"elixir_ls.lsp_command" => String.replace(command, "/", "_")},
%{
"elixir_ls.lsp_request_time" => elapsed
}
)
state
{:error, type, msg, send_telemetry, state} ->
JsonRpc.respond_with_error(id, type, msg)
do_sanity_check(msg)
if send_telemetry do
JsonRpc.telemetry(
"lsp_request_error",
%{
"elixir_ls.lsp_command" => String.replace(command, "/", "_"),
"elixir_ls.lsp_error" => type,
"elixir_ls.lsp_error_message" => msg
},
%{}
)
end
state
{:async, fun, state} ->
{pid, ref} = handle_request_async(id, fun)
%{
state
| requests: Map.put(state.requests, id, {pid, ref, command, start_time}),
requests_ids_by_pid: Map.put(state.requests_ids_by_pid, pid, id)
}
end
rescue
e in InvalidParamError ->
JsonRpc.respond_with_error(id, :invalid_params, e.message)
JsonRpc.telemetry(
"lsp_request_error",
%{
"elixir_ls.lsp_command" => String.replace(command, "/", "_"),
"elixir_ls.lsp_error" => :invalid_params,
"elixir_ls.lsp_error_message" => e.message
},
%{}
)
state
catch
kind, payload ->
{payload, stacktrace} = Exception.blame(kind, payload, __STACKTRACE__)
error_msg = Exception.format(kind, payload, stacktrace)
JsonRpc.respond_with_error(id, :internal_error, error_msg)
do_sanity_check(error_msg)
JsonRpc.telemetry(
"lsp_request_error",
%{
"elixir_ls.lsp_command" => String.replace(command, "/", "_"),
"elixir_ls.lsp_error" => :internal_error,
"elixir_ls.lsp_error_message" => error_msg
},
%{}
)
state
end
end
defp handle_request_packet(id, _packet = %{"method" => command}, state = %__MODULE__{}) do
JsonRpc.respond_with_error(id, :invalid_request)
JsonRpc.telemetry(
"lsp_request_error",
%{
"elixir_ls.lsp_command" => String.replace(command, "/", "_"),
"elixir_ls.lsp_error" => :invalid_request,
"elixir_ls.lsp_error_message" => "Invalid Request"
},
%{}
)
state
end
defp handle_request(
initialize_req(_id, root_uri, client_capabilities),
state = %__MODULE__{server_instance_id: server_instance_id}
)
when not is_initialized(server_instance_id) do
show_version_warnings()
server_instance_id =
:crypto.strong_rand_bytes(32) |> Base.url_encode64() |> binary_part(0, 32)
state =
case root_uri do
"file://" <> _ ->
%{state | root_uri: root_uri}
nil ->
state
end
state = %{
state
| client_capabilities: client_capabilities,
server_instance_id: server_instance_id
}
:persistent_term.put(:language_server_client_capabilities, client_capabilities)
{:ok,
%{
"capabilities" => server_capabilities(server_instance_id),
"serverInfo" => %{
"name" => "ElixirLS",
"version" => "#{Launch.language_server_version()}"
}
}, state}
end
defp handle_request(request(_id, "shutdown", _params), state = %__MODULE__{}) do
{:ok, nil, %{state | received_shutdown?: true}}
end
defp handle_request(definition_req(_id, uri, line, character), state = %__MODULE__{}) do
source_file = get_source_file(state, uri)
fun = fn ->
{line, character} = SourceFile.lsp_position_to_elixir(source_file.text, {line, character})
parser_context = Parser.parse_immediate(uri, source_file, {line, character})
Definition.definition(uri, parser_context, line, character, state.project_dir)
end
{:async, fun, state}
end
defp handle_request(implementation_req(_id, uri, line, character), state = %__MODULE__{}) do
source_file = get_source_file(state, uri)
fun = fn ->
{line, character} = SourceFile.lsp_position_to_elixir(source_file.text, {line, character})
parser_context = Parser.parse_immediate(uri, source_file, {line, character})
Implementation.implementation(uri, parser_context, line, character, state.project_dir)
end
{:async, fun, state}
end