-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathmain.v
More file actions
1983 lines (1899 loc) · 63.4 KB
/
Copy pathmain.v
File metadata and controls
1983 lines (1899 loc) · 63.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by a GPL license that can be found in the LICENSE file.
module main
import json2
import net
import os
import sync
import time
import io
// App represents the context of the server during its lifetime.
pub struct App {
cur_mod string = 'main'
exit bool = os.args.contains('exit')
mut:
text string // Current file content
open_files map[string]string // Map of file URI to file content
open_files_versions map[string]i64 // Per-URI document version from the client
temp_dir string // Temporary directory for multi-file compilation
workspace_roots []string // Workspace root directories from initialize
removed_workspace_roots []string // Roots explicitly removed by the client
capture_output bool // Test hook: capture outbound transport messages instead of writing
captured_output []string // Test hook buffer for outbound transport messages
supports_dynamic_watched_files_registration bool // Client supports dynamic workspace watcher registration
supports_work_done_progress bool // Client supports window/workDoneProgress + $/progress
sent_watched_files_registration bool // client/registerCapability watcher registration was sent
watched_files_registration_id string // Raw id of the watcher registration request, to match its response
watched_files_active bool // True once the client acknowledged watcher registration (not rejected)
inlay_hints_enabled bool = true // toggled via workspace/didChangeConfiguration
diagnostics_enabled bool = true // toggled via workspace/didChangeConfiguration
diag_cache map[string]DiagCacheEntry // Per-URI cached diagnostics
open_files_generation int // Incremented on every workspace file mutation
project_generations map[string]int // Per-project-dir revision, for scoped cache invalidation
cancelled_requests map[int]bool // Request ids cancelled via $/cancelRequest
cancelled_raw_ids map[string]bool // String/raw request ids cancelled via $/cancelRequest
current_request_raw_id string // Raw JSON id of the request being processed (echoed verbatim)
position_encoding PositionEncoding = .utf16 // Negotiated LSP position encoding (default UTF-16)
symbol_index map[string]IndexEntry // Persistent per-URI symbol index (see index.v)
indexed_dirs map[string]bool // Project dirs already walked into the index
indexed_dir_walk_ms map[string]i64 // Last walk time per dir, for watcher-less refresh
ref_occurrences map[string]OccEntry // Per-URI identifier occurrences for references (see index.v)
index_skipped_uris map[string]bool // Disk files omitted from the bounded index
index_incomplete_scopes map[string]bool // Index walks that could not finish
vlib_fn_cache map[string]map[string]string // Per-vlib-module fn→return-type index (immutable during a session)
tcp_conn ?&net.TcpConn // Non-nil when serving a TCP client
is_shutdown bool // True after shutdown request was acknowledged
exit_was_requested bool // True when the exit notification was received
received_initialize bool // True after initialize request was processed
next_request_id int = 1 // Counter for server-initiated request ids
diagnostics_scheduler ?&DiagnosticsScheduler // Production-only async diagnostics
run_command_manager ?&RunCommandManager // Async code-lens process lifecycle
execute_commands_synchronously bool // Test hook for deterministic command assertions
write_mutex &sync.Mutex = sync.new_mutex() // Serializes worker and request-loop writes
}
struct JsonError {
path string
message string
line_nr int
col int
len int
level string // 'error', 'warning', 'notice', or '' — populated by the V compiler
}
struct JsonVarAC {
details []Detail
}
// DiagCacheEntry stores a cached diagnostic result for one file.
struct DiagCacheEntry {
content_hash int
generation int
errors []JsonError
}
// Keep runtime-derived settings behind functions. Function-call module constants can crash V3's
// parallel constant precomputation while compiling VLS.
// find_v_dir resolves the V home directory by finding the V executable and
// returning its parent directory.
fn find_v_dir() string {
v_exe := resolve_v_compiler_exe()
if v_exe == 'v' || !os.is_file(v_exe) {
return ''
}
return os.dir(os.real_path(v_exe))
}
// logging_enabled gates all diagnostic logging. Logging is OFF by default:
// the old behavior wrote every received/sent JSON payload (which can contain
// full source text and secrets) to stderr AND re-opened/appended/closed a
// shared unrotated file on every one of the ~160 call sites (P1-13). Set the
// VLS_LOG environment variable to any non-empty value to enable logging to
// ${TMPDIR}/vls_out.txt for debugging.
fn logging_is_enabled() bool {
return os.getenv('VLS_LOG') != ''
}
fn current_log_file_path() string {
return os.join_path(os.temp_dir(), 'vls_out.txt')
}
fn log(s string) {
if !logging_is_enabled() {
return
}
eprintln(s)
mut output := os.open_append(current_log_file_path()) or { return }
output.writeln(s) or {
output.close()
return
}
output.close()
}
// StdinBufferedReader reads standard input through its raw descriptor so streaming
// clients are not blocked by the full-buffer behaviour of C fread. It deliberately
// stays concrete instead of passing through io.Reader: optimized musl builds can
// omit the custom interface dispatch entry and panic before the first LSP message.
struct StdinBufferedReader {
fd int
mut:
buf []u8
offset int
len int
end_of_stream bool
}
fn (mut reader StdinBufferedReader) fill_buffer() !bool {
if reader.end_of_stream {
return false
}
data, bytes_read := os.fd_read(reader.fd, reader.buf.len)
if bytes_read < 0 {
return error('failed to read from stdin')
}
if bytes_read == 0 {
reader.end_of_stream = true
reader.offset = 0
reader.len = 0
return false
}
reader.offset = 0
reader.len = copy(mut reader.buf, data.bytes())
if reader.len != bytes_read {
return error('failed to buffer stdin')
}
return true
}
fn (mut reader StdinBufferedReader) read(mut buffer []u8) !int {
if buffer.len == 0 {
return 0
}
if reader.offset >= reader.len {
if !reader.fill_buffer()! {
return io.Eof{}
}
}
bytes_read := copy(mut buffer, reader.buf[reader.offset..reader.len])
reader.offset += bytes_read
return bytes_read
}
fn (mut reader StdinBufferedReader) read_line(config io.BufferedReadLineConfig) !string {
if reader.end_of_stream && reader.offset >= reader.len {
return io.Eof{}
}
mut line := []u8{}
for {
if reader.offset >= reader.len {
if !reader.fill_buffer()! {
if line.len == 0 {
return io.Eof{}
}
return line.bytestr()
}
}
mut i := reader.offset
for ; i < reader.len; i++ {
if reader.buf[i] != config.delim {
continue
}
mut end := i
if config.delim == `\n` {
if i > reader.offset && reader.buf[i - 1] == `\r` {
end--
} else if i == reader.offset && line.len > 0 && line.last() == `\r` {
line.delete_last()
}
}
line << reader.buf[reader.offset..end]
reader.offset = i + 1
return line.bytestr()
}
line << reader.buf[reader.offset..i]
reader.offset = i
}
return io.Eof{}
}
fn new_stdin_buffered_reader_for_fd(fd int, cap int) &StdinBufferedReader {
return &StdinBufferedReader{
fd: fd
buf: []u8{len: cap}
}
}
// new_stdin_buffered_reader creates the streaming reader used by stdio mode.
fn new_stdin_buffered_reader() &StdinBufferedReader {
return new_stdin_buffered_reader_for_fd(0, transport_buffer_cap)
}
fn main() {
log('VLS started. Reading from stdin...')
// Check for --port PORT argument to start as a TCP multi-client server.
// TCP binds to loopback (127.0.0.1) by default; binding to any other
// interface requires the explicit --unsafe-allow-remote opt-in because the
// transport is unauthenticated (P0-06).
args := os.args
mut port := ''
mut host := '127.0.0.1'
mut allow_remote := false
for i, arg in args {
match arg {
'--port' {
if i + 1 < args.len {
port = args[i + 1]
}
}
'--host' {
if i + 1 < args.len {
host = args[i + 1]
}
}
'--unsafe-allow-remote' {
allow_remote = true
}
else {}
}
}
if port != '' {
run_tcp_server(host, port, allow_remote)
return
}
// Stdio mode (default).
temp_dir := os.join_path(os.temp_dir(), 'vls_${os.getpid()}')
os.mkdir_all(temp_dir) or {
eprintln('Failed to create temp directory: ${err}')
return
}
mut app := &App{
text: ''
open_files: map[string]string{}
temp_dir: temp_dir
diagnostics_scheduler: new_diagnostics_scheduler()
}
// os.File.read uses C fread, which waits for the entire buffer on an open
// pipe. LSP clients keep stdin open, so use the raw descriptor-backed pipe
// reader to consume each request as soon as it arrives.
mut reader := new_stdin_buffered_reader()
app.handle_requests(mut reader)
log('VLS exiting.')
os.rmdir_all(temp_dir) or {
$if debug {
log('Failed to clean up temp directory: ${err}')
}
}
// LSP spec §3.5: exit after proper shutdown → 0; exit without shutdown → 1.
if app.exit_was_requested && !app.is_shutdown {
exit(1)
}
}
// is_loopback_host reports whether `host` refers to the local machine only.
fn is_loopback_host(host string) bool {
return host in ['127.0.0.1', '::1', 'localhost', '']
}
// tcp_bind_address joins a host and port using the bracketed representation
// required for IPv6 literals.
fn tcp_bind_address(host string, port string) string {
mut bind_host := if host == '' { '127.0.0.1' } else { host }
if bind_host.contains(':') && !(bind_host.starts_with('[') && bind_host.ends_with(']')) {
bind_host = '[${bind_host}]'
}
return '${bind_host}:${port}'
}
// run_tcp_server listens on the given host/port and spawns a goroutine for each
// incoming client connection. Each client gets its own App instance so all
// state is fully isolated. Non-loopback binds require an explicit opt-in
// because the transport has no authentication or TLS (P0-06).
fn run_tcp_server(host string, port string, allow_remote bool) {
if !is_loopback_host(host) && !allow_remote {
msg :=
'VLS: refusing to bind TCP to non-loopback host "${host}" without --unsafe-allow-remote. ' + 'The TCP transport is unauthenticated and unencrypted; exposing it on a network is unsafe.'
log(msg)
eprintln(msg)
return
}
addr := tcp_bind_address(host, port)
log('VLS TCP server starting on ${addr}...')
mut listener := net.listen_tcp(.ip, addr) or {
log('Failed to start TCP listener on ${addr}: ${err}')
return
}
log('VLS TCP server listening on ${addr}')
for {
mut conn := listener.accept() or {
log('TCP accept error: ${err}')
continue
}
spawn handle_tcp_client(mut conn)
}
}
// handle_tcp_client creates a fresh App instance for the newly accepted TCP
// connection and drives the LSP request loop until the client disconnects.
fn handle_tcp_client(mut conn net.TcpConn) {
log('New TCP client connected')
temp_dir := os.join_path(os.temp_dir(), 'vls_${os.getpid()}_${time.now().unix_nano()}')
os.mkdir_all(temp_dir) or {
log('Failed to create temp directory for TCP client: ${err}')
conn.close() or {}
return
}
mut app := &App{
text: ''
open_files: map[string]string{}
temp_dir: temp_dir
tcp_conn: &conn
diagnostics_scheduler: new_diagnostics_scheduler()
}
mut reader := io.new_buffered_reader(reader: conn, cap: transport_buffer_cap)
app.handle_requests(mut reader)
log('TCP client disconnected')
os.rmdir_all(temp_dir) or {
$if debug {
log('Failed to clean up TCP client temp directory: ${err}')
}
}
conn.close() or {}
}
// write_data sends raw data to the client — either via the TCP connection when
// in multi-client mode, or to stdout in stdio mode.
fn (mut app App) write_data(data string) {
app.write_mutex.lock()
defer {
app.write_mutex.unlock()
}
if app.capture_output {
app.captured_output << data
return
}
if mut conn := app.tcp_conn {
conn.write_string(data) or { log('TCP write error: ${err}') }
} else {
print(data)
flush_stdout()
}
}
// send_framed prepends a Content-Length header to `content` and writes the
// message. LSP requires CRLF-delimited headers. A TCP connection is a raw byte
// stream, so it always gets literal `\r\n\r\n`; only Windows *stdio* uses `\n\n`,
// relying on text-mode stdout to translate each `\n` into `\r\n` on the wire
// (P0-11). This prevents Windows TCP from emitting LF-only framing.
fn (mut app App) send_framed(content string) {
mut is_tcp := false
if _ := app.tcp_conn {
is_tcp = true
}
header := if is_tcp {
'Content-Length: ${content.len}\r\n\r\n'
} else {
$if windows {
'Content-Length: ${content.len}\n\n'
} $else {
'Content-Length: ${content.len}\r\n\r\n'
}
}
full_message := '${header}${content}'
log('SEND: ${full_message}')
app.write_data(full_message)
}
// Transport framing limits (P0-11). These bound how much memory an untrusted
// client (local or over TCP) can force the server to allocate.
const transport_buffer_cap = 64 * 1024 // buffered reader capacity
const max_content_length = 64 * 1024 * 1024 // 64 MiB max JSON-RPC body
const max_header_bytes = 64 * 1024 // total header section size cap
const max_charset = 'utf-8' // LSP content is always UTF-8
fn read_request[T](mut reader T) !string {
mut len := -1
mut header_error := ''
mut header_bytes := 0
for {
line := reader.read_line() or {
if err is io.Eof {
return err
}
$if debug {
log('read_request: error reading header line: ${err}')
}
return err
}
header_bytes += line.len + 2 // account for the stripped CRLF
if header_bytes > max_header_bytes {
return error('invalid header: header section exceeds ${max_header_bytes} bytes')
}
trimmed_line := line.trim_space()
if trimmed_line == '' {
break
}
log('line=${line}')
lower := trimmed_line.to_lower()
if lower.starts_with('content-length:') {
len_str := trimmed_line.all_after(':').trim_space()
parsed_len := parse_content_length_header(len_str) or {
header_error = 'invalid header: invalid Content-Length'
continue
}
if parsed_len > max_content_length {
header_error = 'invalid header: Content-Length ${parsed_len} exceeds maximum ${max_content_length}'
continue
}
if len != -1 && len != parsed_len {
header_error = 'invalid header: conflicting Content-Length headers'
continue
}
len = parsed_len
continue
}
if lower.starts_with('content-type:') {
// LSP content is always UTF-8. Reject any explicitly declared
// non-UTF-8 charset instead of silently misdecoding bytes.
if charset_is_unsupported(trimmed_line.all_after(':')) {
header_error = 'invalid header: unsupported charset (only ${max_charset} is allowed)'
continue
}
continue
}
}
// Surface a header error before doing anything else, so a malformed
// Content-Length can never silently desynchronize the stream.
if header_error != '' {
return error(header_error)
}
if len < 0 {
return ''
}
mut buf := []u8{len: len}
mut total_bytes_read := 0
for total_bytes_read < len {
bytes_read_now := reader.read(mut buf[total_bytes_read..]) or {
log('read_request: error reading content body: ${err}')
return err
}
if bytes_read_now == 0 && total_bytes_read < len {
log('read_request: got EOF before reading full content body.')
return io.Eof{}
}
total_bytes_read += bytes_read_now
}
return buf.bytestr()
}
// charset_is_unsupported reports whether a Content-Type header value declares a
// charset other than UTF-8. LSP §3 mandates UTF-8 for all message content; the
// historical `utf8` spelling is also accepted.
fn charset_is_unsupported(content_type string) bool {
parameters := split_mime_parameters(content_type)
for parameter in parameters[1..] {
eq := parameter.index('=') or { continue }
if parameter[..eq].trim_space().to_lower() != 'charset' {
continue
}
charset := unquote_mime_parameter(parameter[eq + 1..]).to_lower()
if charset != 'utf-8' && charset != 'utf8' {
return true
}
}
return false
}
// split_mime_parameters separates a media type and its parameters without
// treating semicolons inside a quoted-string as delimiters.
fn split_mime_parameters(content_type string) []string {
mut parameters := []string{}
mut start := 0
mut quoted := false
mut escaped := false
for i, ch in content_type {
if escaped {
escaped = false
continue
}
if quoted && ch == `\\` {
escaped = true
continue
}
if ch == `"` {
quoted = !quoted
continue
}
if ch == `;` && !quoted {
parameters << content_type[start..i].trim_space()
start = i + 1
}
}
parameters << content_type[start..].trim_space()
return parameters
}
// unquote_mime_parameter parses a MIME quoted-string parameter value, including
// quoted-pair escapes. Malformed quoted values remain invalid charset values.
fn unquote_mime_parameter(raw string) string {
value := raw.trim_space()
if value.len < 2 || value[0] != `"` || value[value.len - 1] != `"` {
return value
}
mut decoded := []u8{cap: value.len - 2}
mut escaped := false
for ch in value[1..value.len - 1] {
if escaped {
decoded << ch
escaped = false
continue
}
if ch == `\\` {
escaped = true
continue
}
decoded << ch
}
if escaped {
return value
}
return decoded.bytestr()
}
fn parse_content_length_header(s string) !int {
t := s.trim_space()
if t == '' {
return error('empty Content-Length')
}
for ch in t {
if ch < `0` || ch > `9` {
return error('non-numeric Content-Length')
}
}
// Guard against overflow of the 32-bit int parse before using the value.
if t.len > 18 {
return error('Content-Length too large')
}
n := t.i64()
if n < 0 || n > max_content_length {
return error('Content-Length out of range')
}
return int(n)
}
// handle_requests is the main request handler loop for both stdio and TCP modes.
fn (mut app App) handle_requests[T](mut reader T) {
defer {
app.cancel_all_scheduled_diagnostics()
app.stop_run_commands()
}
for {
// Reset the per-request raw id so a stale id can never leak into an
// error response emitted before a new message is fully read.
app.current_request_raw_id = ''
content := read_request(mut reader) or {
if err is io.Eof {
log('Client closed connection. Exiting.')
break
}
if err.msg().starts_with('invalid header:') {
// The frame body was not consumed, so the stream is now
// desynchronized: the unread body would be misread as the next
// header. Report the error, then close the connection rather than
// attempting to resynchronize (P0-11).
app.write_error_response(make_parse_error_response(err.msg()))
break
}
$if debug {
log('Error reading request: ${err.msg()}')
}
break
}
if content.len == 0 {
continue
}
log('\n\nRECV: ${content}')
has_id := request_content_has_id(content)
// Preserve the exact id (numeric or string) so responses echo it
// verbatim; string ids would otherwise collapse to 0 (P0-02).
app.current_request_raw_id = extract_raw_id(content) or { '' }
// JSON-RPC ids may only be a string, number, or null (an absent raw id).
// A present id of any other type (object, array, boolean) is an Invalid
// Request: respond with a null id — the id could not be validly
// determined — rather than dispatching and echoing a bogus id (P0-02).
if app.current_request_raw_id != '' && !raw_id_is_valid(app.current_request_raw_id) {
app.current_request_raw_id = 'null'
app.write_error_response(make_invalid_request_error_response(0, 'Request id must be a string, number, or null'))
continue
}
// Decode the body WITHOUT the id field: json2 aborts the whole decode on
// a string value in an int field, which would otherwise make every
// string-id request undecodable. The numeric id is derived from the raw
// id (0 for non-numeric ids), while the exact id is echoed via the raw id.
body := json2.decode[RequestBody](content) or {
log('Failed to decode JSON request: ${err.msg()}. Content: "${content}"')
app.current_request_raw_id = 'null'
app.write_error_response(make_parse_error_response(err.msg()))
continue
}
// A message with an id + result/error but no method is a response to a
// server-initiated request (progress create, capability registration).
// Classify and record it only after the typed decode above validated the
// complete JSON payload, so malformed acknowledgements cannot activate
// capabilities or disappear without a parse error (P0-02).
if is_client_response_message(content) {
app.note_server_request_response(content)
log('Consumed client response to a server-initiated request: ${content}')
continue
}
lsp_request := Request{
id: raw_id_to_int(app.current_request_raw_id)
method: body.method
jsonrpc: body.jsonrpc
params: body.params
}
log('\n\nRECV (pretty): ${content}')
method := Method.from_string(lsp_request.method)
log('method="${method}" request.method="${lsp_request.method}" ${method == .completion}')
// Enforce request/notification direction (P0-03): a message with an id
// sent to a notification-only method is an InvalidRequest; a message
// without an id sent to a request-only method is dropped rather than
// processed into a response with a bogus id.
if has_id && method_is_notification_only(method) {
app.write_error_response(make_invalid_request_error_response(lsp_request.id, 'Method ${lsp_request.method} is a notification and cannot be sent as a request'))
continue
}
if !has_id && method_requires_response(method) {
log('Dropping notification-shaped message for request-only method ${lsp_request.method}')
continue
}
if method_requires_response(method) && app.request_is_cancelled(lsp_request.id) {
app.write_error_response(make_cancelled_error_response(lsp_request.id))
app.consume_cancelled_request(lsp_request.id)
continue
}
// After shutdown, reject all requests except exit.
if app.is_shutdown && method != .exit {
if has_id {
app.write_error_response(make_server_shutdown_error_response(lsp_request.id))
}
continue
}
// Before initialize, reject all requests (except initialize and exit).
// Per LSP §3.5, the server MUST respond with ServerNotInitialized (-32002)
// to any request received before the initialize handshake completes.
if !app.received_initialize && method != .initialize && method != .exit {
if has_id {
app.write_error_response(make_server_not_initialized_error_response(lsp_request.id))
}
continue
}
if has_id {
if err_msg := validate_request_params(method, lsp_request.params) {
app.write_error_response(make_invalid_params_error_response(lsp_request.id, err_msg))
continue
}
} else {
if err_msg := validate_notification_params(method, lsp_request.params) {
log('Invalid notification params for ${lsp_request.method}: ${err_msg}')
continue
}
}
match method {
.completion, .signature_help, .definition, .hover, .declaration, .type_definition, .implementation {
resp := app.operation_at_pos(method, lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.references {
resp := app.find_references(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.rename {
resp := app.handle_rename(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.prepare_rename {
resp := app.handle_prepare_rename(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.workspace_symbol {
resp := app.handle_workspace_symbol(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.formatting {
resp := app.handle_formatting(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.document_symbols {
resp := app.handle_document_symbols(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.inlay_hint {
resp := app.handle_inlay_hints(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.did_change {
notification := app.on_did_change(lsp_request) or { continue }
app.write_notification(notification)
}
.initialize {
// Reject double-initialize per LSP spec.
if app.received_initialize {
app.write_error_response(make_server_already_initialized_error_response(lsp_request.id))
continue
}
if err_msg := app.on_initialize(lsp_request) {
app.write_error_response(make_invalid_params_error_response(lsp_request.id, err_msg))
continue
}
// Return all supported capabilities, matching the LSP spec and what is implemented.
response := Response{
id: lsp_request.id
result: Capabilities{
capabilities: Capability{
// NOTE: Placeholder/stub capabilities are intentionally NOT
// advertised (P1-07 / Stage 0): on-type formatting (always
// empty), inline values (wrong abstraction), linked editing
// (wrong abstraction), file-operation hooks (no-ops), and
// willSave (never dispatched). Advertising only working
// features gives a better editor experience than broken UI.
text_document_sync: TextDocumentSyncOptions{
open_close: true
change: 2 // Incremental
save: SaveOptions{
include_text: true
}
will_save: false
will_save_wait_until: true
}
completion_provider: CompletionProvider{
trigger_characters: ['.']
}
signature_help_provider: SignatureHelpOptions{
trigger_characters: ['(', ',']
}
definition_provider: true
declaration_provider: true
type_definition_provider: true
implementation_provider: true
hover_provider: true
references_provider: true
rename_provider: RenameOptions{
prepare_provider: true
}
document_formatting_provider: true
document_symbol_provider: true
workspace_symbol_provider: true
inlay_hint_provider: true
code_action_provider: true
execute_command_provider: ExecuteCommandOptions{
commands: ['vls.runFile', 'vls.runTests']
}
code_lens_provider: CodeLensOptions{}
semantic_tokens_provider: SemanticTokensOptions{
legend: SemanticTokensLegend{
token_types: semantic_token_types()
token_modifiers: semantic_token_modifiers()
}
full: true
range: true
}
folding_range_provider: true
call_hierarchy_provider: true
document_highlight_provider: true
selection_range_provider: true
// Range formatting is NOT advertised: v fmt only formats whole
// files, so a correct range implementation needs a
// character-accurate, EOL-preserving diff restricted to the
// requested range, which is not yet implemented (P0-08).
document_range_formatting_provider: false
position_encoding: position_encoding_string(app.position_encoding)
workspace: WorkspaceCapability{
workspace_folders: WorkspaceFoldersServerCapability{
supported: true
change_notifications: true
}
}
}
server_info: ServerInfo{
name: 'vls'
version: '0.0.2'
}
}
}
app.write_response(response)
app.received_initialize = true
// Surface a clearly actionable message if the V compiler is not
// available, instead of silently returning empty diagnostics,
// completion, and navigation for every request (P1-03).
if !compiler_is_available() {
app.send_show_message('vls: the V compiler (`v`) was not found on PATH. Diagnostics, completion, and navigation will not work until `v` is installed and on PATH.', 1)
}
}
.did_open {
if !app.on_did_open(lsp_request) {
params := json2.decode[DidOpenTextDocumentParams](lsp_request.params) or { continue }
uri := params.text_document.uri
if doc_content := app.open_files[uri] {
app.write_notification(app.build_diagnostics_notification(uri, doc_content))
}
}
}
.did_close {
app.on_did_close(lsp_request)
// Clear published diagnostics for the closed document (P0-07 item 9).
if params := json2.decode[DidCloseTextDocumentParams](lsp_request.params) {
app.write_notification(Notification{
method: 'textDocument/publishDiagnostics'
params: PublishDiagnosticsParams{
uri: params.text_document.uri
diagnostics: []
}
})
}
}
.did_save {
notification := app.on_did_save(lsp_request) or { continue }
app.write_notification(notification)
}
.will_save_wait_until {
resp := app.on_will_save_wait_until(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.initialized {
log('Received initialized notification.')
app.on_initialized(lsp_request)
}
.set_trace {
log('Received and ignored method: ${lsp_request.method}')
}
.cancel_request {
app.on_cancel_request(lsp_request)
}
.shutdown {
app.accept_shutdown(lsp_request.id)
}
.exit {
log('Received exit notification. Terminating.')
app.exit_was_requested = true
break
}
.code_action {
resp := app.handle_code_action(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.semantic_tokens {
resp := app.handle_semantic_tokens(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.folding_range {
resp := app.handle_folding_range(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.callhierarchy_prepare {
resp := app.handle_prepare_call_hierarchy(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.callhierarchy_incoming {
resp := app.handle_call_hierarchy_incoming(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.callhierarchy_outgoing {
resp := app.handle_call_hierarchy_outgoing(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.workspace_did_change_configuration {
app.on_did_change_configuration(lsp_request)
}
.workspace_did_change_workspace_folders {
app.on_did_change_workspace_folders(lsp_request)
}
.document_highlight {
resp := app.handle_document_highlight(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.selection_range {
resp := app.handle_selection_range(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.semantic_tokens_range {
resp := app.handle_semantic_tokens_range(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.range_formatting {
resp := app.handle_range_formatting(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.did_change_watched_files {
app.on_did_change_watched_files(lsp_request)
}
.code_lens {
resp := app.handle_code_lens(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.code_lens_resolve {
resp := app.handle_code_lens_resolve(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.execute_command {
resp := app.handle_execute_command(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.inline_value {
resp := app.handle_inline_value(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.linked_editing_range {
resp := app.handle_linked_editing_range(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
.will_create_files, .will_rename_files, .will_delete_files {
// Return null — vls has no pre-operation file mutations to apply.
app.write_response(Response{
id: lsp_request.id
result: 'null'
})
}
.on_type_formatting {
resp := app.handle_on_type_formatting(lsp_request)
app.write_response_or_cancelled(lsp_request.id, resp)
}
else {
log('UNKNOWN method ${lsp_request.method}')
if has_id {
if method == .unknown {
app.write_error_response(make_method_not_found_error_response(lsp_request.id, lsp_request.method))
} else {
app.write_error_response(make_internal_error_response(lsp_request.id, 'Unhandled request dispatch for known method: ${lsp_request.method}'))
}
}
}
}
}
}
fn request_content_has_id(content string) bool {
return extract_raw_id(content) != none
}
// raw_id_to_int converts a raw JSON id token to an int for internal use. String
// ids (and absent ids) collapse to 0; the exact id is preserved separately via
// the raw id and echoed verbatim in responses.
fn raw_id_to_int(raw string) int {
if raw == '' || raw.starts_with('"') {
return 0
}
return raw.int()
}
// raw_id_is_valid reports whether a raw JSON id token is a legal JSON-RPC id: a
// string, a number, or null. Objects, arrays, and booleans are rejected. An
// absent id is represented by an empty token and is handled by the caller.
fn raw_id_is_valid(raw string) bool {
if raw == '' || raw == 'null' || raw[0] == `"` {
return true
}
c := raw[0]
return c == `-` || (c >= `0` && c <= `9`)
}
// json_is_ws reports whether a byte is JSON insignificant whitespace.
fn json_is_ws(c u8) bool {
return c == ` ` || c == `\t` || c == `\n` || c == `\r`
}
// read_json_string_token reads a JSON string starting at `content[i]` (which
// must be a double quote) and returns the decoded key text plus the index just
// past the closing quote.
fn read_json_string_token(content string, start int) (string, int) {
mut i := start + 1 // past opening quote
mut sb := []u8{}
for i < content.len {
c := content[i]
if c == `\\` && i + 1 < content.len {
nxt := content[i + 1]
if nxt == `u` {
// `\uXXXX` unicode escape (with surrogate-pair support). Decode to a