-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathhandlers.v
More file actions
1263 lines (1164 loc) · 35 KB
/
handlers.v
File metadata and controls
1263 lines (1164 loc) · 35 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 os
fn (mut app App) operation_at_pos(method Method, request Request) Response {
line_nr := request.params.position.line + 1
col := request.params.position.char
path := request.params.text_document.uri
// Intercept completion on import lines
if method == .completion {
if content := app.open_files[path] {
lines := content.split_into_lines()
if line_nr - 1 < lines.len {
current_line := lines[line_nr - 1]
if current_line.trim_space().starts_with('import') {
work_dir := os.dir(uri_to_path(path))
completions := get_import_completions(current_line, work_dir)
if completions.len > 0 {
return Response{
id: request.id
result: completions
}
}
}
}
}
}
line_info := match method {
.completion {
'${line_nr}:${col}'
}
.hover {
'${line_nr}:hv^${col}'
}
.signature_help {
'${line_nr}:fn^${col}'
}
.definition {
'${line_nr}:gd^${col}'
}
else {
''
}
}
mut result := app.run_v_line_info(method, path, line_info)
if method == .completion {
// Check the character immediately before the cursor.
// If it is not '.', the user is not doing member access, so augment
// the compiler result with V keywords and builtins.
cursor_line := request.params.position.line
content := app.open_files[path] or { '' }
lines := content.split_into_lines()
trigger_char := if cursor_line < lines.len && col > 0 {
line := lines[cursor_line]
char_col := col - 1
if char_col < line.len {
line[char_col].ascii_str()
} else {
''
}
} else {
''
}
if trigger_char != '.' {
mut details := []Detail{}
if result is []Detail {
details = result as []Detail
}
details << make_keyword_completions()
// Build dedup map from compiler + keyword results.
mut seen_labels := map[string]bool{}
for d in details {
seen_labels[d.label] = true
}
working_dir := os.dir(uri_to_path(path))
// Augment with fn completions from sibling files in the same module.
if working_dir != '' {
module_fns := app.collect_module_fn_completions(path, working_dir)
for d in module_fns {
if d.label !in seen_labels {
details << d
seen_labels[d.label] = true
}
}
}
// Also include functions declared in the current file itself.
// The compiler's -line-info does not always return all local functions
// (e.g. at the start of a function body or when syntax errors exist).
current_content := app.open_files[path] or { '' }
for d in parse_module_fn_completions(current_content) {
if d.label !in seen_labels {
details << d
seen_labels[d.label] = true
}
}
result = details
}
}
log(result.str())
return Response{
id: request.id
result: result
}
}
fn (mut app App) on_did_open(request Request) {
uri := request.params.text_document.uri
log('on_did_open: ${uri}')
real_path := uri_to_path(uri)
content := os.read_file(real_path) or {
log('Failed to read file ${real_path}: ${err}')
return
}
app.open_files[uri] = content
app.text = content
log('STORED CONTENT for uri=${uri}, FILE COUNT: ${app.open_files.len}')
}
// Returns instant red wavy errors
fn (mut app App) on_did_change(request Request) ?Notification {
log('on did change(len=${request.params.content_changes.len})')
if request.params.content_changes.len == 0 || request.params.content_changes[0].text == '' {
log('on_did_change() no params')
return none
}
uri := request.params.text_document.uri
content := request.params.content_changes[0].text
app.text = content
app.open_files[uri] = content // Update tracked file
path := uri
v_errors := app.run_v_check(path, app.text)
log('run_v_check errors:${v_errors}')
mut diagnostics := []LSPDiagnostic{}
mut seen_positions := map[string]bool{}
for v_err in v_errors {
pos_key := '${v_err.line_nr}:${v_err.col}'
if pos_key in seen_positions {
continue
}
seen_positions[pos_key] = true
diagnostics << v_error_to_lsp_diagnostic(v_err)
}
params := PublishDiagnosticsParams{
uri: request.params.text_document.uri
diagnostics: diagnostics
}
notification := Notification{
method: 'textDocument/publishDiagnostics'
params: params
}
log('returning notification: ${notification}')
return notification
}
fn (mut app App) find_references(request Request) Response {
path := request.params.text_document.uri
real_path := uri_to_path(path)
line := request.params.position.line
col := request.params.position.char
// Get symbol name at cursor
symbol := app.get_word_at_position(real_path, line, col)
if symbol == '' {
return Response{
id: request.id
result: []Location{}
}
}
// Search all .v files in working directory
working_dir := os.dir(real_path)
locations := app.search_symbol_in_project(working_dir, symbol)
return Response{
id: request.id
result: locations
}
}
fn (mut app App) handle_rename(request Request) Response {
path := request.params.text_document.uri
real_path := uri_to_path(path)
line := request.params.position.line
col := request.params.position.char
new_name := request.params.new_name
// Get symbol name at cursor
symbol := app.get_word_at_position(real_path, line, col)
if symbol == '' {
return Response{
id: request.id
result: WorkspaceEdit{}
}
}
// Find all references
working_dir := os.dir(real_path)
locations := app.search_symbol_in_project(working_dir, symbol)
// Build WorkspaceEdit
mut changes := map[string][]TextEdit{}
for loc in locations {
edit := TextEdit{
range: LSPRange{
start: loc.range.start
end: Position{
line: loc.range.start.line
char: loc.range.start.char + symbol.len
}
}
new_text: new_name
}
if loc.uri in changes {
changes[loc.uri] << edit
} else {
changes[loc.uri] = [edit]
}
}
return Response{
id: request.id
result: WorkspaceEdit{
changes: changes
}
}
}
fn (app &App) get_word_at_position(file_path string, line int, col int) string {
content := app.open_files[path_to_uri(file_path)] or {
os.read_file(file_path) or { return '' }
}
lines := content.split_into_lines()
if line >= lines.len {
return ''
}
text := lines[line]
if col >= text.len {
return ''
}
// Find word boundaries (V identifiers: letters, digits, underscores)
mut start := col
mut end := col
for start > 0 && is_ident_char(text[start - 1]) {
start--
}
for end < text.len && is_ident_char(text[end]) {
end++
}
if start == end {
return ''
}
return text[start..end]
}
fn is_ident_char(c u8) bool {
return (c >= `a` && c <= `z`) || (c >= `A` && c <= `Z`) || (c >= `0` && c <= `9`) || c == `_`
}
// get_word_at_col extracts the identifier at column `col` within a single line.
// Returns '' if the character at `col` is not an identifier character.
fn get_word_at_col(line string, col int) string {
if col >= line.len {
return ''
}
if !is_ident_char(line[col]) {
return ''
}
mut start := col
mut end := col
for start > 0 && is_ident_char(line[start - 1]) {
start--
}
for end < line.len && is_ident_char(line[end]) {
end++
}
if start == end {
return ''
}
return line[start..end]
}
// find_declaration_line searches `lines` for a top-level declaration whose name
// exactly matches `symbol` and returns its 0-based line index, or -1 if not found.
fn find_declaration_line(lines []string, symbol string) int {
for i, raw_line in lines {
line := raw_line.trim_space()
stripped := if line.starts_with('pub ') { line[4..] } else { line }
decl_prefixes := ['fn ', 'struct ', 'enum ', 'interface ', 'type ', 'const ']
for prefix in decl_prefixes {
if stripped.starts_with(prefix) {
rest := stripped[prefix.len..]
// Handle method receivers: fn (recv) name(
actual_rest := if rest.starts_with('(') {
close := rest.index(')') or { break }
rest[close + 1..].trim_space()
} else {
rest
}
name := first_word_paren(actual_rest)
if name == symbol {
return i
}
break
}
}
}
return -1
}
// extract_doc_comment walks backward from `decl_line` collecting consecutive
// `//` comment lines (V's vdoc convention) and returns them joined with newlines.
fn extract_doc_comment(lines []string, decl_line int) string {
mut comments := []string{}
mut i := decl_line - 1
for i >= 0 {
trimmed := lines[i].trim_space()
if trimmed.starts_with('//') {
comments << trimmed[2..].trim_space()
i--
} else {
break
}
}
if comments.len == 0 {
return ''
}
comments = comments.reverse()
// Use Markdown hard line breaks (two trailing spaces + newline) so each
// comment line renders on its own line in the hover popup.
return comments.join(' \n')
}
// get_module_name extracts the module name declared in V source content.
// Returns '' if no module declaration is found.
fn get_module_name(content string) string {
for line in content.split_into_lines() {
trimmed := line.trim_space()
if trimmed.starts_with('module ') {
name := trimmed[7..].trim_space()
if name != '' {
return name
}
}
}
return ''
}
// parse_imports extracts the module paths from `import` statements in `content`.
// Returns a list of module paths, e.g. ['os', 'math', 'v.util'].
fn parse_imports(content string) []string {
mut imports := []string{}
for line in content.split_into_lines() {
trimmed := line.trim_space()
if !trimmed.starts_with('import ') {
continue
}
rest := trimmed[7..].trim_space()
// Strip optional `as alias` suffix
module_path := rest.split(' ')[0].trim_space()
if module_path != '' {
imports << module_path
}
}
return imports
}
// get_import_completions returns completion items for an `import` line.
// It lists vlib modules and local project modules matching the typed prefix.
fn get_import_completions(line string, work_dir string) []Detail {
trimmed := line.trim_space()
if !trimmed.starts_with('import') {
return []
}
// typed is everything after 'import', e.g. '', 'enc', 'encoding', 'encoding.'
typed := if trimmed.len > 7 { trimmed[7..].trim_space() } else { '' }
mut results := []Detail{}
// Split on '.' to determine nesting level.
// e.g. 'encoding.' → parts = ['encoding', ''], base = ['encoding'], prefix = ''
// e.g. 'encoding.b' → parts = ['encoding', 'b'], base = ['encoding'], prefix = 'b'
// e.g. 'enc' → parts = ['enc'], base = [], prefix = 'enc'
parts := typed.split('.')
base_path_parts := parts[..parts.len - 1] // all but last
prefix := parts.last() // filter on last segment
// Build vlib search path
vlib_dir := os.join_path(@VEXEROOT, 'vlib')
search_dir := if base_path_parts.len > 0 {
os.join_path(vlib_dir, base_path_parts.join(os.path_separator))
} else {
vlib_dir
}
// List matching subdirectories in vlib
if os.is_dir(search_dir) {
entries := os.ls(search_dir) or { [] }
for entry in entries {
if !entry.starts_with(prefix) {
continue
}
full_path := os.join_path(search_dir, entry)
if !os.is_dir(full_path) {
continue
}
// Include dirs that contain at least one non-test .v file directly,
// or that contain subdirectories (namespaces like encoding/).
children := os.ls(full_path) or { [] }
has_v := children.any(it.ends_with('.v') && !it.ends_with('_test.v'))
has_subdir := children.any(os.is_dir(os.join_path(full_path, it)))
if !has_v && !has_subdir {
continue
}
results << Detail{
kind: 9 // CompletionItemKind.Module
label: entry
detail: 'V stdlib module'
insert_text: entry
}
}
}
// Also add local project modules (top-level only, when no dots typed yet)
if work_dir != '' && base_path_parts.len == 0 {
entries := os.ls(work_dir) or { [] }
for entry in entries {
if !entry.starts_with(prefix) || entry.starts_with('.') {
continue
}
full_path := os.join_path(work_dir, entry)
if !os.is_dir(full_path) {
continue
}
v_files := os.ls(full_path) or { [] }
has_v := v_files.any(it.ends_with('.v') && !it.ends_with('_test.v'))
if !has_v {
continue
}
results << Detail{
kind: 9
label: entry
detail: 'Local module'
insert_text: entry
}
}
}
return results
}
// find_doc_comment_for_symbol searches for the vdoc comment for `symbol` across
// multiple sources in priority order:
// 1. current file lines (already split)
// 2. other open files in app.open_files
// 3. all .v files in the project working directory
// 4. vlib/builtin/ (always, for built-in functions like println)
// 5. vlib/<module>/ for each module imported in the current file
fn (app &App) find_doc_comment_for_symbol(symbol string, current_lines []string, current_file_uri string) string {
// 1. Current file
decl_line := find_declaration_line(current_lines, symbol)
if decl_line >= 0 {
doc := extract_doc_comment(current_lines, decl_line)
if doc != '' {
return doc
}
}
// 2 & 3. Other open files then all project .v files
working_dir := os.dir(uri_to_path(current_file_uri))
mut searched_uris := map[string]bool{}
searched_uris[current_file_uri] = true
// Search open files first (in memory, no disk I/O)
for uri, content in app.open_files {
if uri in searched_uris {
continue
}
searched_uris[uri] = true
lines := content.split_into_lines()
dl := find_declaration_line(lines, symbol)
if dl >= 0 {
doc := extract_doc_comment(lines, dl)
if doc != '' {
return doc
}
}
}
// Search remaining .v files on disk in the working directory
for v_file in os.walk_ext(working_dir, '.v') {
uri := path_to_uri(v_file)
if uri in searched_uris {
continue
}
searched_uris[uri] = true
content := os.read_file(v_file) or { continue }
lines := content.split_into_lines()
dl := find_declaration_line(lines, symbol)
if dl >= 0 {
doc := extract_doc_comment(lines, dl)
if doc != '' {
return doc
}
}
}
// 4. vlib/builtin/ — always search for built-in symbols
builtin_dir := os.join_path(@VEXEROOT, 'vlib', 'builtin')
if os.is_dir(builtin_dir) {
doc := search_doc_in_vlib_dir(builtin_dir, symbol)
if doc != '' {
return doc
}
}
// 5. Imported stdlib modules
current_content := app.open_files[current_file_uri] or { '' }
for module_path in parse_imports(current_content) {
// Convert 'v.util' → 'v/util', 'os' → 'os'
module_rel := module_path.replace('.', os.path_separator)
module_dir := os.join_path(@VEXEROOT, 'vlib', module_rel)
if !os.is_dir(module_dir) {
continue
}
doc := search_doc_in_vlib_dir(module_dir, symbol)
if doc != '' {
return doc
}
}
return ''
}
// search_doc_in_vlib_dir searches all non-test .v files in `dir` for a
// declaration of `symbol` and returns its vdoc comment, or '' if not found.
fn search_doc_in_vlib_dir(dir string, symbol string) string {
for v_file in os.walk_ext(dir, '.v') {
// Skip test files to avoid false positives and improve performance
if v_file.ends_with('_test.v') {
continue
}
content := os.read_file(v_file) or { continue }
lines := content.split_into_lines()
dl := find_declaration_line(lines, symbol)
if dl >= 0 {
doc := extract_doc_comment(lines, dl)
if doc != '' {
return doc
}
}
}
return ''
}
fn (mut app App) handle_formatting(request Request) Response {
path := request.params.text_document.uri
real_path := uri_to_path(path)
// Get the current content of the file
content := app.open_files[path] or {
os.read_file(real_path) or {
log('Failed to read file for formatting: ${err}')
return Response{
id: request.id
result: []TextEdit{}
}
}
}
// Write content to a temp file
temp_file := os.join_path(os.temp_dir(), 'vls_fmt_${os.getpid()}_${os.file_name(real_path)}')
os.write_file(temp_file, content) or {
log('Failed to write temp file for formatting: ${err}')
return Response{
id: request.id
result: []TextEdit{}
}
}
// Run fmt
result := os.execute('v fmt -inprocess "${temp_file}"')
// Clean up temp file
os.rm(temp_file) or { log('Failed to remove temp file: ${err}') }
// Check for errors
if result.exit_code != 0 {
log('v fmt failed with code ${result.exit_code}: ${result.output}')
return Response{
id: request.id
result: []TextEdit{}
}
}
// If content is unchanged, return empty edits
if result.output == content {
return Response{
id: request.id
result: []TextEdit{}
}
}
// Calculate the range of the entire document
lines := content.split_into_lines()
last_line := lines.len - 1
last_char := if lines.len > 0 { lines[last_line].len } else { 0 }
// Return a single TextEdit that replaces the entire document
edit := TextEdit{
range: LSPRange{
start: Position{
line: 0
char: 0
}
end: Position{
line: last_line
char: last_char
}
}
new_text: result.output
}
return Response{
id: request.id
result: [edit]
}
}
// handle_document_symbols parses the current file's text using a simple
// line-by-line token scan and returns top-level declaration symbols so the
// editor can populate its Outline / breadcrumbs view.
fn (mut app App) handle_document_symbols(request Request) Response {
uri := request.params.text_document.uri
content := app.open_files[uri] or { '' }
symbols := parse_document_symbols(content)
return Response{
id: request.id
result: symbols
}
}
// handle_inlay_hints returns type inlay hints for `:=` declarations within the
// requested range whose RHS is a recognizable literal (int, f64, string, bool).
fn (mut app App) handle_inlay_hints(request Request) Response {
uri := request.params.text_document.uri
content := app.open_files[uri] or { '' }
lines := content.split_into_lines()
start_line := request.params.range.start.line
end_line := request.params.range.end.line
// Build fn index lazily: current file + open files + vlib modules imported in this file
file_path := uri_to_path(uri)
working_dir := os.dir(file_path)
mut index_files := []string{}
// Collect all open file paths
for open_uri, _ in app.open_files {
p := uri_to_path(open_uri)
if p != '' && p != file_path {
index_files << p
}
}
// Only scan project directory if working_dir is a real, accessible directory.
// Guard against fake URIs (e.g. tests using file:///test.v) which resolve
// working_dir to '/' and would cause a full filesystem walk.
if working_dir != '' && working_dir != '/' && os.is_dir(working_dir) {
project_files := os.walk_ext(working_dir, '.v')
for pf in project_files {
if !pf.ends_with('_test.v') && pf != file_path {
index_files << pf
}
}
// Add vlib modules imported by this file
imported_mods := parse_imports(content)
for mod in imported_mods {
mod_path := mod.replace('.', '/')
vlib_mod_dir := os.join_path(@VEXEROOT, 'vlib', mod_path)
if os.is_dir(vlib_mod_dir) {
vlib_files := os.walk_ext(vlib_mod_dir, '.v')
for vf in vlib_files {
if !vf.ends_with('_test.v') {
index_files << vf
}
}
}
}
}
mut fn_index := build_fn_index(index_files)
// Also index functions defined in the current file (in-memory content).
parse_fn_signatures_into(content, '', mut fn_index)
mut hints := []InlayHint{}
mut in_const_block := false
for line_idx in start_line .. (end_line + 1) {
if line_idx >= lines.len {
break
}
raw := lines[line_idx]
trimmed := raw.trim_space()
// Skip comments and blank lines
if trimmed == '' || trimmed.starts_with('//') {
continue
}
// Track const block boundaries
if trimmed == 'const (' {
in_const_block = true
continue
}
if in_const_block && trimmed == ')' {
in_const_block = false
continue
}
mut var_name := ''
mut rhs := ''
if in_const_block {
// Inside `const (` block: lines look like `name = value`
eq_idx := trimmed.index(' = ') or { continue }
var_name = trimmed[..eq_idx].trim_space()
rhs = trimmed[eq_idx + 3..].trim_space()
} else if trimmed.starts_with('const ') && trimmed.contains(' = ') {
// Single-line const: `const name = value`
after_const := trimmed[6..]
eq_idx := after_const.index(' = ') or { continue }
var_name = after_const[..eq_idx].trim_space()
rhs = after_const[eq_idx + 3..].trim_space()
} else {
// Short variable declaration: `name := value` or `mut name := value`
assign_idx := trimmed.index(' := ') or { continue }
lhs := trimmed[..assign_idx].trim_space()
rhs = trimmed[assign_idx + 4..].trim_space()
var_name = lhs
if lhs.starts_with('mut ') {
var_name = lhs[4..].trim_space()
}
}
// Skip multi-assignment or invalid identifiers
if var_name.contains(' ') || var_name.contains(',') || var_name == '' {
continue
}
// Strip error-handling suffix from RHS: `os.read_file(p) or { [] }` → `os.read_file(p)`
mut clean_rhs := rhs
if or_idx := rhs.index(' or ') {
clean_rhs = rhs[..or_idx].trim_space()
}
if q_idx := rhs.index(' ?') {
_ = q_idx // optional chaining — leave as is
}
// Try literal inference first, then fn index lookup
mut inferred := infer_type_from_literal(clean_rhs)
if inferred == '' {
inferred = lookup_fn_return_type(clean_rhs, fn_index)
// Strip result/optional prefix for display: `!string` → `string`, `?string` → `?string`
if inferred.starts_with('!') {
inferred = inferred[1..]
}
}
if inferred == '' {
continue
}
// Position the hint right after the variable name in the raw line
name_col := raw.index(var_name) or { continue }
hints << InlayHint{
position: Position{
line: line_idx
char: name_col + var_name.len
}
label: ': ${inferred}'
kind: inlay_hint_kind_type
padding_left: false
}
}
return Response{
id: request.id
result: hints
}
}
// infer_type_from_literal returns the V type name for a simple literal RHS value,
// or '' if the type cannot be determined without compiler assistance.
fn infer_type_from_literal(rhs string) string {
r := rhs.trim_space()
if r == '' {
return ''
}
// Boolean
if r == 'true' || r == 'false' {
return 'bool'
}
// String literals: single-quote, double-quote, or backtick
first := r[0]
if first == `'` || first == `"` || first == '`'[0] {
return 'string'
}
// Already explicitly typed (struct/array/map init): skip
if r.contains('{') || r.contains('[') {
return ''
}
// Float literal: contains a '.' and digits only
if r.contains('.') {
mut is_float := true
for c in r {
if !((c >= `0` && c <= `9`) || c == `.` || c == `-` || c == `_`) {
is_float = false
break
}
}
if is_float {
return 'f64'
}
}
// Integer literal: hex (0x), octal (0o), binary (0b), or plain digits
if r.starts_with('0x') || r.starts_with('0X') || r.starts_with('0o') || r.starts_with('0b') {
return 'int'
}
mut is_int := true
for c in r {
if !((c >= `0` && c <= `9`) || c == `-` || c == `_`) {
is_int = false
break
}
}
if is_int && r.len > 0 {
return 'int'
}
return ''
}
// extract_fn_call parses a RHS expression like `os.temp_dir()` or `get_value()`
// and returns (module_name, fn_name). Returns ('', '') if not a simple call.
// Skips method calls on receivers (e.g. `obj.method()`).
fn extract_fn_call(rhs string) (string, string) {
r := rhs.trim_space()
// Must end with `)` (allowing trailing comments stripped by caller)
if !r.ends_with(')') {
return '', ''
}
// Find the opening paren
paren_idx := r.index('(') or { return '', '' }
call_part := r[..paren_idx]
if call_part.contains('.') {
// Could be `module.fn` or `receiver.method` — only handle one dot
dot_idx := call_part.last_index('.') or { return '', '' }
mod_part := call_part[..dot_idx]
fn_part := call_part[dot_idx + 1..]
// Skip if module part looks like a variable (lowercase first char only heuristic
// won't work reliably, so we allow both and let the index miss on methods)
if mod_part == '' || fn_part == '' {
return '', ''
}
return mod_part, fn_part
}
// Plain call: `get_value()`
if call_part == '' {
return '', ''
}
return '', call_part
}
// parse_fn_signatures_into scans V source `content` for simple fn declarations
// and populates `index` with fn_name → return_type and mod_name.fn_name → return_type.
// Only captures non-method, non-multi-return, non-void signatures.
fn parse_fn_signatures_into(content string, mod_name string, mut index map[string]string) {
for line in content.split_into_lines() {
trimmed := line.trim_space()
// Match `fn name(` or `pub fn name(`
mut after_fn := ''
if trimmed.starts_with('pub fn ') {
after_fn = trimmed[7..]
} else if trimmed.starts_with('fn ') {
after_fn = trimmed[3..]
} else {
continue
}
// Skip method receivers: `(mut app App) name(`
if after_fn.starts_with('(') {
continue
}
paren_idx := after_fn.index('(') or { continue }
fn_name := after_fn[..paren_idx].trim_space()
if fn_name == '' || fn_name.contains(' ') || fn_name.contains('[') {
continue
}
// Find closing paren to locate return type
close_paren := after_fn.index(')') or { continue }
after_params := after_fn[close_paren + 1..].trim_space()
// after_params could be: `string {`, `!string {`, `?string {`,
// `(string, int) {` (multi-return — skip), ` {` (void — skip)
if after_params == '' || after_params.starts_with('{') {
continue
}
// Multi-return: starts with `(`
if after_params.starts_with('(') {
continue
}
// Strip trailing ` {` or just `{`
ret := after_params.all_before('{').trim_space()
if ret == '' {
continue
}
index[fn_name] = ret
if mod_name != '' {
index['${mod_name}.${fn_name}'] = ret
}
}
}
// build_fn_index scans the given V source files and returns a map of
// fn_name → return_type and module_prefix.fn_name → return_type.
// Only captures simple (non-method, non-multi-return) signatures.
fn build_fn_index(files []string) map[string]string {
mut index := map[string]string{}
for fpath in files {
content := os.read_file(fpath) or { continue }
mod_name := os.file_name(fpath).replace('.v', '')
parse_fn_signatures_into(content, mod_name, mut index)
}
return index
}
// lookup_fn_return_type looks up the return type of a function call RHS in the
// provided index. For qualified calls like `os.temp_dir()`, it checks both
// `os.temp_dir` and just `temp_dir`.
fn lookup_fn_return_type(rhs string, index map[string]string) string {
mod_name, fn_name := extract_fn_call(rhs)
if fn_name == '' {
return ''
}
// Strip any error handling suffix from RHS for lookup: `os.read_file(p) or { ... }`
// extract_fn_call already handles plain `)` endings; but callers may pass full line
if mod_name != '' {
qualified := '${mod_name}.${fn_name}'
if qualified in index {
return index[qualified]
}
}
if fn_name in index {
return index[fn_name]
}
return ''
}
// parse_document_symbols scans `content` line by line and extracts top-level
// V declarations: functions, methods, structs, enums, interfaces, constants,
// and type aliases. It is intentionally simple – the goal is to get the
// Outline view working quickly, not to replicate a full parser.
fn parse_document_symbols(content string) []DocumentSymbol {
lines := content.split_into_lines()
mut symbols := []DocumentSymbol{}
for i, raw_line in lines {
line := raw_line.trim_space()
// Skip blank lines and pure comment lines
if line == '' || line.starts_with('//') {
continue
}
// Collect an optional leading `pub ` so we can strip it for name extraction
stripped := if line.starts_with('pub ') { line[4..] } else { line }
if stripped.starts_with('fn ') {
name := extract_fn_name(stripped[3..])
if name == '' {
continue
}
kind := if name.contains(') ') {
// receiver present → method
sym_kind_method
} else {
sym_kind_function
}
symbols << make_symbol(name, kind, i, raw_line)
} else if stripped.starts_with('struct ') {
name := first_word(stripped[7..])
if name != '' {
symbols << make_symbol(name, sym_kind_struct, i, raw_line)
}
} else if stripped.starts_with('enum ') {
name := first_word(stripped[5..])