-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlsp.go
More file actions
984 lines (890 loc) · 26.9 KB
/
lsp.go
File metadata and controls
984 lines (890 loc) · 26.9 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
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/tliron/commonlog"
"github.com/tliron/glsp"
protocol "github.com/tliron/glsp/protocol_3_16"
"github.com/tliron/glsp/server"
)
const lspName = "arca-lsp"
var (
lspHandler protocol.Handler
lspVersion = version
)
// fileStore keeps in-memory file contents for open documents.
var fileStore = map[string]string{}
// resolverCache keeps a GoTypeResolver per goModDir so that Go package
// type info is loaded only once per session.
var resolverCache = map[string]*GoTypeResolver{}
func getResolverFor(dir string) *GoTypeResolver {
if r, ok := resolverCache[dir]; ok {
return r
}
r := NewGoTypeResolver(dir)
resolverCache[dir] = r
return r
}
func lspCmd() int {
commonlog.Configure(1, nil) // minimal logging
lspHandler = protocol.Handler{
Initialize: lspInitialize,
Initialized: lspInitialized,
Shutdown: lspShutdown,
TextDocumentDidOpen: lspDidOpen,
TextDocumentDidChange: lspDidChange,
TextDocumentDidClose: lspDidClose,
TextDocumentDidSave: lspDidSave,
TextDocumentHover: lspHover,
TextDocumentDefinition: lspDefinition,
TextDocumentCompletion: lspCompletion,
}
srv := server.NewServer(&lspHandler, lspName, false)
if err := srv.RunStdio(); err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
return 0
}
func lspInitialize(ctx *glsp.Context, params *protocol.InitializeParams) (any, error) {
syncKind := protocol.TextDocumentSyncKindFull
capabilities := protocol.InitializeResult{
Capabilities: protocol.ServerCapabilities{
TextDocumentSync: &protocol.TextDocumentSyncOptions{
OpenClose: boolPtr(true),
Change: &syncKind,
Save: &protocol.SaveOptions{IncludeText: boolPtr(true)},
},
HoverProvider: &protocol.HoverOptions{},
DefinitionProvider: &protocol.DefinitionOptions{},
CompletionProvider: &protocol.CompletionOptions{
TriggerCharacters: []string{"."},
},
},
ServerInfo: &protocol.InitializeResultServerInfo{
Name: lspName,
Version: &lspVersion,
},
}
return capabilities, nil
}
func lspInitialized(ctx *glsp.Context, params *protocol.InitializedParams) error {
return nil
}
func lspShutdown(ctx *glsp.Context) error {
return nil
}
func lspDidOpen(ctx *glsp.Context, params *protocol.DidOpenTextDocumentParams) error {
uri := params.TextDocument.URI
fileStore[uri] = params.TextDocument.Text
return lspDiagnose(ctx, uri, params.TextDocument.Text)
}
func lspDidChange(ctx *glsp.Context, params *protocol.DidChangeTextDocumentParams) error {
uri := params.TextDocument.URI
if len(params.ContentChanges) > 0 {
// Full sync — last change has the full text
if change, ok := params.ContentChanges[len(params.ContentChanges)-1].(protocol.TextDocumentContentChangeEventWhole); ok {
fileStore[uri] = change.Text
return lspDiagnose(ctx, uri, change.Text)
}
}
return nil
}
func lspDidClose(ctx *glsp.Context, params *protocol.DidCloseTextDocumentParams) error {
delete(fileStore, params.TextDocument.URI)
return nil
}
func lspDidSave(ctx *glsp.Context, params *protocol.DidSaveTextDocumentParams) error {
uri := params.TextDocument.URI
if params.Text != nil {
fileStore[uri] = *params.Text
return lspDiagnose(ctx, uri, *params.Text)
}
if text, ok := fileStore[uri]; ok {
return lspDiagnose(ctx, uri, text)
}
return nil
}
// --- Diagnostics ---
func lspDiagnose(ctx *glsp.Context, uri string, source string) error {
filePath := strings.TrimPrefix(string(uri), "file://")
diagnostics := collectDiagnostics(source, filePath)
ctx.Notify(protocol.ServerTextDocumentPublishDiagnostics, protocol.PublishDiagnosticsParams{
URI: uri,
Diagnostics: diagnostics,
})
return nil
}
func collectDiagnostics(source string, filePath string) []protocol.Diagnostic {
diagnostics := []protocol.Diagnostic{} // must be empty slice, not nil (Neovim requires it)
severity := protocol.DiagnosticSeverityError
// Parse
lexer := NewLexer(source)
tokens, err := lexer.Tokenize()
if err != nil {
diagnostics = append(diagnostics, protocol.Diagnostic{
Range: posToRange(extractPosFromError(err.Error())),
Severity: &severity,
Source: strPtr(lspName),
Message: err.Error(),
})
return diagnostics
}
parser := NewParser(tokens)
prog, err := parser.ParseProgram()
if err != nil {
pos := extractPosFromError(err.Error())
diagnostics = append(diagnostics, protocol.Diagnostic{
Range: posToRange(pos),
Severity: &severity,
Source: strPtr(lspName),
Message: err.Error(),
})
return diagnostics
}
// Lower
goModDir := findGoModDir(filepath.Dir(filePath))
resolver := getResolverFor(goModDir)
lowerer := NewLowerer(prog, "", resolver)
lowerer.Lower(prog, "main", false)
for _, e := range lowerer.Errors() {
diagnostics = append(diagnostics, protocol.Diagnostic{
Range: posToRange(e.Pos),
Severity: &severity,
Source: strPtr(lspName),
Message: e.Message(),
})
}
return diagnostics
}
// --- Hover ---
func lspDefinition(ctx *glsp.Context, params *protocol.DefinitionParams) (any, error) {
uri := params.TextDocument.URI
source, ok := fileStore[uri]
if !ok {
return nil, nil
}
line := int(params.Position.Line) + 1
col := int(params.Position.Character) + 1
filePath := strings.TrimPrefix(string(uri), "file://")
defFile, defPos := getDefinitionLocation(source, filePath, line, col)
if defPos.Line == 0 {
return nil, nil
}
// Default to the current file's URI; override if definition is elsewhere (Go FFI)
defURI := uri
if defFile != "" && defFile != filePath {
// Map Arca package embed paths (e.g. "stdlib/db.go") to extracted cache paths
defFile = resolveEmbedFilePath(defFile)
defURI = "file://" + defFile
}
return protocol.Location{
URI: defURI,
Range: posToRange(defPos),
}, nil
}
// getDefinitionPos is kept for testing within the current file.
func getDefinitionPos(source string, filePath string, line, col int) Pos {
_, pos := getDefinitionLocation(source, filePath, line, col)
return pos
}
// getDefinitionLocation returns (file, pos) for the definition of the symbol at
// the given position. file is "" if the definition is in the same source.
func getDefinitionLocation(source string, filePath string, line, col int) (string, Pos) {
// Parse and lower
lexer := NewLexer(source)
tokens, err := lexer.Tokenize()
if err != nil {
return "", Pos{}
}
parser := NewParser(tokens)
prog, err := parser.ParseProgram()
if err != nil {
return "", Pos{}
}
goModDir := findGoModDir(filepath.Dir(filePath))
resolver := getResolverFor(goModDir)
lowerer := NewLowerer(prog, "", resolver)
lowerer.Lower(prog, "main", false)
word := getWordAt(source, line, col)
if word == "" {
return "", Pos{}
}
// Go FFI: package.member or receiver.method
receiver := getReceiverAt(source, line, col)
if receiver != "" {
if sym := lowerer.FindSymbolAt(receiver, Pos{line, col}); sym != nil {
// Go package-level member: fmt.Println, http.StatusOK
if sym.Kind == SymPackage {
if pkg, ok := lowerer.GoPackages()[sym.Name]; ok {
if file, pos := resolver.MemberPos(pkg.FullPath, word); pos.Line != 0 {
return file, pos
}
}
}
// Go method on a typed receiver: e.Start, db.Query
if sym.IRType != nil {
if shortPkg, typeName := extractPackageAndType(sym.IRType); shortPkg != "" {
if pkg, ok := lowerer.GoPackages()[shortPkg]; ok {
if file, pos := resolver.MethodPos(pkg.FullPath, typeName, word); pos.Line != 0 {
return file, pos
}
}
}
}
}
}
// Look up symbol via scope tree
if sym := lowerer.FindSymbolAt(word, Pos{line, col}); sym != nil {
return "", sym.Pos
}
// Function lookup (for calls to pub functions etc.)
if fn, ok := lowerer.Functions()[word]; ok {
return "", fn.NamePos
}
// Type lookup
if td, ok := lowerer.Types()[word]; ok {
return "", td.Pos
}
return "", Pos{}
}
// extractPackageAndType returns the Go package short name and type name from
// an IR type. Returns ("", "") if the type is not a Go-qualified named type.
func extractPackageAndType(t IRType) (string, string) {
// Unwrap pointer / ref: *sql.DB and Ref[sql.DB] both surface methods of sql.DB.
if pt, ok := t.(IRPointerType); ok {
return extractPackageAndType(pt.Inner)
}
if rt, ok := t.(IRRefType); ok {
return extractPackageAndType(rt.Inner)
}
named, ok := t.(IRNamedType)
if !ok {
return "", ""
}
name := strings.TrimPrefix(named.GoName, "*")
parts := strings.SplitN(name, ".", 2)
if len(parts) != 2 {
return "", ""
}
return parts[0], parts[1]
}
func lspCompletion(ctx *glsp.Context, params *protocol.CompletionParams) (any, error) {
uri := params.TextDocument.URI
source, ok := fileStore[uri]
if !ok {
return nil, nil
}
line := int(params.Position.Line) + 1
col := int(params.Position.Character) + 1
filePath := strings.TrimPrefix(string(uri), "file://")
items := getCompletionItems(source, filePath, line, col)
if items == nil {
return nil, nil
}
return items, nil
}
// getCompletionItems returns completion items at the given position.
// Currently only supports `.` completion after a receiver identifier.
func getCompletionItems(source string, filePath string, line, col int) []protocol.CompletionItem {
// Find the receiver just before the cursor (must be immediately after a dot)
receiver := getReceiverBeforeDot(source, line, col)
if receiver == "" {
return nil
}
// Insert a placeholder identifier after the dot so the source parses.
patched := insertCompletionPlaceholder(source, line, col)
// Parse and lower the patched source
lexer := NewLexer(patched)
tokens, err := lexer.Tokenize()
if err != nil {
return nil
}
parser := NewParser(tokens)
prog, err := parser.ParseProgram()
if err != nil {
return nil
}
goModDir := findGoModDir(filepath.Dir(filePath))
resolver := getResolverFor(goModDir)
lowerer := NewLowerer(prog, "", resolver)
lowerer.Lower(prog, "main", false)
// Parse the receiver expression on its own and lower it to get its type.
// This handles chained access (a.b.c) naturally via the existing field-type
// resolution in lowerFieldAccess.
recvLexer := NewLexer(receiver)
recvTokens, err := recvLexer.Tokenize()
if err != nil {
return nil
}
recvParser := NewParser(recvTokens)
recvExpr, err := recvParser.parseExpr()
if err != nil {
return nil
}
// Lower the receiver inside the scope at the cursor position so that
// local variables like `u`, `self`, etc. resolve correctly.
savedScope := lowerer.currentScope
if lowerer.rootScope != nil {
lowerer.currentScope = lowerer.rootScope.FindScopeAt(Pos{line, col})
}
loweredRecv := lowerer.lowerExpr(recvExpr)
lowerer.currentScope = savedScope
// Derive the current type info from the lowered receiver.
// - Package symbol: ident name lookup via GoPackages
// - Otherwise: use loweredRecv.irType() for type resolution
var curArcaType Type
var curIRType IRType = loweredRecv.irType()
var curKind string
var curPkgName string
// If it's a single identifier referring to a package, treat as package.
if ident, ok := recvExpr.(Ident); ok {
if sym := lowerer.FindSymbolAt(ident.Name, Pos{line, col}); sym != nil {
curKind = sym.Kind
curPkgName = sym.Name
if sym.Type != nil {
curArcaType = sym.Type
}
}
}
// Ref[T] auto-derefs at field / method access — peel Ref both on the
// AST-level curArcaType (from the symbol table) and the IR-level
// curIRType so downstream Arca-type-fields and Go-FFI-methods branches
// both look through the reference.
if nt, ok := curArcaType.(NamedType); ok && nt.Name == "Ref" && len(nt.Params) == 1 {
curArcaType = nt.Params[0]
}
if rt, ok := curIRType.(IRRefType); ok {
curIRType = rt.Inner
}
// If the IR type is a user-defined Arca type, map it to curArcaType
// so the Arca type fields branch fires.
if curArcaType == nil && curKind == "" {
if nt, ok := curIRType.(IRNamedType); ok {
if _, isArcaType := lowerer.Types()[nt.GoName]; isArcaType {
curArcaType = NamedType{Name: nt.GoName}
}
}
}
var items []protocol.CompletionItem
// Package members
if curKind == SymPackage {
if pkg, ok := lowerer.GoPackages()[curPkgName]; ok {
for _, m := range resolver.PackageMembers(pkg.FullPath) {
items = append(items, memberToCompletion(m))
}
}
return items
}
// Arca type fields
if curArcaType != nil {
if nt, ok := curArcaType.(NamedType); ok {
if td, ok := lowerer.Types()[nt.Name]; ok && len(td.Constructors) > 0 {
for _, f := range td.Constructors[0].Fields {
items = append(items, protocol.CompletionItem{
Label: f.Name,
Kind: completionKindPtr(protocol.CompletionItemKindField),
Detail: strPtr(typeName(f.Type)),
})
}
}
}
}
// Go FFI type methods/fields
if curIRType != nil {
if shortPkg, typeName := extractPackageAndType(curIRType); shortPkg != "" {
if pkg, ok := lowerer.GoPackages()[shortPkg]; ok {
for _, m := range resolver.TypeMembers(pkg.FullPath, typeName) {
items = append(items, memberToCompletion(m))
}
}
}
}
// Prelude-provided monadic methods on Result / Option. resolveDeep strips
// any HM type-var indirection left on the receiver so `let r = foo()`
// where `foo() -> Result[...]` still matches IRResultType, mirroring the
// lowerer's tryDesugarMonadicMethod path.
if methods := monadicMethodsFor(lowerer.resolveDeep(curIRType)); methods != nil {
methodKind := protocol.CompletionItemKindMethod
for _, m := range methods {
items = append(items, protocol.CompletionItem{
Label: m.Name,
Kind: &methodKind,
Detail: strPtr(m.Signature),
})
}
}
return items
}
func memberToCompletion(m MemberInfo) protocol.CompletionItem {
var kind protocol.CompletionItemKind
switch m.Kind {
case "func":
kind = protocol.CompletionItemKindFunction
case "method":
kind = protocol.CompletionItemKindMethod
case "field":
kind = protocol.CompletionItemKindField
case "type":
kind = protocol.CompletionItemKindClass
case "var":
kind = protocol.CompletionItemKindVariable
case "const":
kind = protocol.CompletionItemKindConstant
default:
kind = protocol.CompletionItemKindText
}
return protocol.CompletionItem{
Label: m.Name,
Kind: &kind,
Detail: strPtr(m.Detail),
}
}
func completionKindPtr(k protocol.CompletionItemKind) *protocol.CompletionItemKind {
return &k
}
// insertCompletionPlaceholder inserts dummy identifiers after any dangling
// dots in the source so incomplete expressions like `u.` or `fmt.` parse.
// This handles the case where the user is actively typing in one place
// while another line already has a trailing dot.
func insertCompletionPlaceholder(source string, line, col int) string {
const placeholder = "_arca_completion_placeholder_"
lines := strings.Split(source, "\n")
for i, lineText := range lines {
// Find trailing dots followed only by whitespace to end-of-line
trimmed := strings.TrimRight(lineText, " \t")
if strings.HasSuffix(trimmed, ".") {
// Accept the dot as the start of a member access when the
// preceding char is either an identifier (u.) or the close of
// a call / index expression (produce().). Other chars (e.g.
// an operator or float literal dot) are ignored.
if len(trimmed) >= 2 {
prev := trimmed[len(trimmed)-2]
if isIdentChar(prev) || prev == ')' || prev == ']' {
lines[i] = trimmed + placeholder + lineText[len(trimmed):]
}
}
}
}
return strings.Join(lines, "\n")
}
// getReceiverBeforeDot returns the full dotted expression before the cursor dot.
// For `app.db.`, returns "app.db". For `u.`, returns "u".
// Returns "" if no valid receiver expression found.
func getReceiverBeforeDot(source string, line, col int) string {
lines := strings.Split(source, "\n")
if line < 1 || line > len(lines) {
return ""
}
lineText := lines[line-1]
pos := col - 1
if pos > len(lineText) {
pos = len(lineText)
}
// Find the nearest '.' at or before cursor (skipping any trailing word chars)
dotIdx := -1
for i := pos - 1; i >= 0; i-- {
c := lineText[i]
if c == '.' {
dotIdx = i
break
}
if !isIdentChar(c) {
return ""
}
}
if dotIdx < 0 {
return ""
}
// Walk back to find the full dotted expression. Handles plain dotted
// access (a.b.c), call-chain receivers (foo().bar, produce().), and
// bracket/generic suffixes on the walked segments. Inside a balanced
// `)…(` or `]…[` pair we accept any character; at depth 0 only ident
// characters / dots / the opening of a new balanced pair are accepted.
end := dotIdx
start := end
depth := 0
walk:
for start > 0 {
c := lineText[start-1]
if depth > 0 {
start--
switch c {
case '(', '[':
depth--
case ')', ']':
depth++
}
continue
}
switch {
case c == ')' || c == ']':
depth++
start--
case isIdentChar(c) || c == '.':
start--
default:
break walk
}
}
// Unbalanced brackets → no valid receiver.
if depth != 0 {
return ""
}
if start == end {
return ""
}
return lineText[start:end]
}
func lspHover(ctx *glsp.Context, params *protocol.HoverParams) (*protocol.Hover, error) {
uri := params.TextDocument.URI
source, ok := fileStore[uri]
if !ok {
return nil, nil
}
line := int(params.Position.Line) + 1 // LSP is 0-based, Arca is 1-based
col := int(params.Position.Character) + 1
filePath := strings.TrimPrefix(string(uri), "file://")
info := getHoverInfo(source, filePath, line, col)
if info == "" {
return nil, nil
}
return &protocol.Hover{
Contents: protocol.MarkupContent{
Kind: protocol.MarkupKindMarkdown,
Value: info,
},
}, nil
}
func getHoverInfo(source string, filePath string, line, col int) string {
// Parse and lower to get type info
lexer := NewLexer(source)
tokens, err := lexer.Tokenize()
if err != nil {
return ""
}
parser := NewParser(tokens)
prog, err := parser.ParseProgram()
if err != nil {
return ""
}
goModDir := findGoModDir(filepath.Dir(filePath))
resolver := getResolverFor(goModDir)
lowerer := NewLowerer(prog, "", resolver)
lowerer.Lower(prog, "main", false)
// Find the token at the given position
word := getWordAt(source, line, col)
if word == "" {
return ""
}
// Check if this is a field access: receiver.field or receiver.method
receiver := getReceiverAt(source, line, col)
if receiver != "" {
if sym := lowerer.FindSymbolAt(receiver, Pos{line, col}); sym != nil {
// Arca field
if fieldType := lookupFieldType(lowerer.Types(), sym.Type, word); fieldType != nil {
return fmt.Sprintf("```arca\n%s: %s\n```", word, typeName(fieldType))
}
// Go FFI method or field on typed receiver
if hover := lookupGoMemberHover(sym.IRType, word, lowerer); hover != "" {
return hover
}
// Go package-level member (e.g. http.StatusOK)
if sym.Kind == SymPackage {
if hover := lookupGoPkgMemberHover(sym.Name, word, lowerer); hover != "" {
return hover
}
}
}
}
// Look up symbol via scope tree
if sym := lowerer.FindSymbolAt(word, Pos{line, col}); sym != nil {
return formatSymbolHover(sym, lowerer)
}
// Look up functions (not in scope — e.g. pub functions from other modules)
functions := lowerer.Functions()
if fn, ok := functions[word]; ok {
return formatFnHover(fn)
}
// Look up methods (including static fun) in all types
types := lowerer.Types()
for _, td := range types {
for _, m := range td.Methods {
if m.Name == word {
return formatMethodHover(td.Name, m)
}
}
}
// Look up types
if td, ok := types[word]; ok {
return formatTypeHover(td)
}
// Look up type aliases
typeAliases := lowerer.TypeAliases()
if ta, ok := typeAliases[word]; ok {
return formatTypeAliasHover(ta)
}
return ""
}
// irTypeDisplayName is the user-facing IR type renderer for hover /
// diagnostics. Delegates to the single Arca-side renderer so Ref, Map,
// Interface (→ Any), tuples, and the Go-name-to-Arca-name mapping are all
// handled consistently. Previously there were two parallel renderers and
// this one silently missed Ref/Map/Any.
func irTypeDisplayName(t IRType) string {
return irTypeDisplayStr(t)
}
func lookupGoPkgMemberHover(pkgShort, member string, lowerer *Lowerer) string {
pkg, ok := lowerer.GoPackages()[pkgShort]
if !ok {
return ""
}
// Try as function. Show the Arca-visible shape: params are wrapped
// (`*T` → `Option[Ref[T]]`) and returns go through goFuncReturnType so
// `(T, error)` shows as `Result[T, error]`, `(T, bool)` as `Option[T]`,
// etc. This matches what the user can actually call from Arca.
if info := lowerer.TypeResolver().ResolveFunc(pkg.FullPath, member); info != nil {
params := make([]string, len(info.Params))
for i, p := range info.Params {
name := p.Name
if name == "" {
name = fmt.Sprintf("arg%d", i)
}
params[i] = fmt.Sprintf("%s: %s", name, irTypeDisplayStr(wrapPointerInOption(goTypeToIR(p.Type))))
}
ret := ""
if len(info.Results) > 0 {
arcaRet := lowerer.goFuncReturnType(info).Type
ret = " -> " + irTypeDisplayStr(arcaRet)
}
return fmt.Sprintf("```arca\nfun %s.%s(%s)%s\n```", pkgShort, member, strings.Join(params, ", "), ret)
}
// Try as type
if info := lowerer.TypeResolver().ResolveType(pkg.FullPath, member); info != nil {
return fmt.Sprintf("```go\ntype %s.%s\n```", pkgShort, member)
}
// Package-level constant/variable — just show the name
return fmt.Sprintf("```go\n%s.%s\n```", pkgShort, member)
}
func lookupGoMemberHover(irType IRType, member string, lowerer *Lowerer) string {
if irType == nil {
return ""
}
// Extract Go package and type name from IR type
var named IRNamedType
switch tt := irType.(type) {
case IRNamedType:
named = tt
case IRPointerType:
if inner, ok := tt.Inner.(IRNamedType); ok {
named = inner
} else {
return ""
}
case IRRefType:
if inner, ok := tt.Inner.(IRNamedType); ok {
named = inner
} else {
return ""
}
default:
return ""
}
if !strings.Contains(named.GoName, ".") {
return ""
}
parts := strings.SplitN(named.GoName, ".", 2)
pkg, ok := lowerer.GoPackages()[parts[0]]
if !ok {
return ""
}
info := lowerer.TypeResolver().ResolveMethod(pkg.FullPath, parts[1], member)
if info == nil {
return ""
}
// Format method signature
params := make([]string, len(info.Params))
for i, p := range info.Params {
name := p.Name
if name == "" {
name = fmt.Sprintf("arg%d", i)
}
params[i] = fmt.Sprintf("%s: %s", name, goTypeToIRName(p.Type))
}
ret := ""
if len(info.Results) > 0 {
retTypes := make([]string, len(info.Results))
for i, r := range info.Results {
retTypes[i] = goTypeToIRName(r.Type)
}
ret = " -> " + strings.Join(retTypes, ", ")
}
return fmt.Sprintf("```go\nfun %s.%s(%s)%s\n```", parts[1], member, strings.Join(params, ", "), ret)
}
func formatSymbolHover(sym *SymbolInfo, lowerer *Lowerer) string {
switch sym.Kind {
case SymPackage:
if pkg, ok := lowerer.GoPackages()[sym.Name]; ok {
return fmt.Sprintf("```arca\nimport go \"%s\"\n```", pkg.FullPath)
}
return fmt.Sprintf("```arca\nimport go \"%s\"\n```", sym.Name)
case SymFunction:
if fn, ok := lowerer.Functions()[sym.Name]; ok {
return formatFnHover(fn)
}
case SymVariable, SymParameter:
typeStr := typeName(sym.Type)
if typeStr == "unknown" && sym.IRType != nil {
typeStr = irTypeDisplayName(sym.IRType)
}
return fmt.Sprintf("```arca\n%s %s: %s\n```", sym.Kind, sym.Name, typeStr)
}
return ""
}
func formatFnHover(fn FnDecl) string {
params := make([]string, len(fn.Params))
for i, p := range fn.Params {
params[i] = fmt.Sprintf("%s: %s", p.Name, typeName(p.Type))
}
ret := ""
if fn.ReturnType != nil {
ret = " -> " + typeName(fn.ReturnType)
}
return fmt.Sprintf("```arca\nfun %s(%s)%s\n```", fn.Name, strings.Join(params, ", "), ret)
}
func formatTypeHover(td TypeDecl) string {
if isEnum(td) {
variants := make([]string, len(td.Constructors))
for i, c := range td.Constructors {
variants[i] = c.Name
}
return fmt.Sprintf("```arca\ntype %s { %s }\n```", td.Name, strings.Join(variants, ", "))
}
if len(td.Constructors) == 1 {
ctor := td.Constructors[0]
fields := make([]string, len(ctor.Fields))
for i, f := range ctor.Fields {
fields[i] = fmt.Sprintf("%s: %s", f.Name, typeName(f.Type))
}
return fmt.Sprintf("```arca\ntype %s(%s)\n```", td.Name, strings.Join(fields, ", "))
}
return fmt.Sprintf("```arca\ntype %s\n```", td.Name)
}
func formatMethodHover(ownerType string, fn FnDecl) string {
params := make([]string, len(fn.Params))
for i, p := range fn.Params {
params[i] = fmt.Sprintf("%s: %s", p.Name, typeName(p.Type))
}
ret := ""
if fn.ReturnType != nil {
ret = " -> " + typeName(fn.ReturnType)
}
prefix := "fun"
if fn.Static {
prefix = "static fun"
}
return fmt.Sprintf("```arca\n%s %s.%s(%s)%s\n```", prefix, ownerType, fn.Name, strings.Join(params, ", "), ret)
}
func formatTypeAliasHover(ta TypeAliasDecl) string {
return fmt.Sprintf("```arca\ntype %s = %s\n```", ta.Name, typeName(ta.Type))
}
// --- Helpers ---
// getReceiverAt returns the identifier before a dot if the cursor is on a field/method name.
// e.g. for "user.email" with cursor on "email", returns "user".
func getReceiverAt(source string, line, col int) string {
lines := strings.Split(source, "\n")
if line < 1 || line > len(lines) {
return ""
}
lineText := lines[line-1]
// Find the start of the current word
start := col - 1
for start > 0 && isIdentChar(lineText[start-1]) {
start--
}
// Check if there's a dot before
if start < 1 || lineText[start-1] != '.' {
return ""
}
// Find the receiver word before the dot
dotPos := start - 1
end := dotPos
recStart := end
for recStart > 0 && isIdentChar(lineText[recStart-1]) {
recStart--
}
if recStart == end {
return ""
}
return lineText[recStart:end]
}
// lookupFieldType finds a field's type in an Arca type definition.
func lookupFieldType(types map[string]TypeDecl, ownerType Type, fieldName string) Type {
if ownerType == nil {
return nil
}
nt, ok := ownerType.(NamedType)
if !ok {
return nil
}
td, ok := types[nt.Name]
if !ok {
return nil
}
if f := findField(td, fieldName); f != nil {
return f.Type
}
return nil
}
func getWordAt(source string, line, col int) string {
lines := strings.Split(source, "\n")
if line < 1 || line > len(lines) {
return ""
}
lineText := lines[line-1]
if col < 1 || col > len(lineText)+1 {
return ""
}
// Find word boundaries
start := col - 1
end := col - 1
for start > 0 && isIdentChar(lineText[start-1]) {
start--
}
for end < len(lineText) && isIdentChar(lineText[end]) {
end++
}
if start == end {
return ""
}
return lineText[start:end]
}
func isIdentChar(c byte) bool {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'
}
func posToRange(pos Pos) protocol.Range {
line := uint32(0)
char := uint32(0)
if pos.Line > 0 {
line = uint32(pos.Line - 1)
}
if pos.Col > 0 {
char = uint32(pos.Col - 1)
}
return protocol.Range{
Start: protocol.Position{Line: line, Character: char},
End: protocol.Position{Line: line, Character: char + 1},
}
}
func extractPosFromError(msg string) Pos {
// Parse "line:col: message" format
var line, col int
if _, err := fmt.Sscanf(msg, "%d:%d:", &line, &col); err == nil {
return Pos{Line: line, Col: col}
}
return Pos{Line: 1, Col: 1}
}
func boolPtr(b bool) *bool { return &b }
func strPtr(s string) *string { return &s }