-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
1124 lines (962 loc) · 30.7 KB
/
main.go
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
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
)
// RPCRequest represents a JSON-RPC request structure
type RPCRequest struct {
Jsonrpc string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Method string `json:"method"`
Params json.RawMessage `json:"params,omitempty"`
}
// RPCResponse represents a JSON-RPC response structure
type RPCResponse struct {
Jsonrpc string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Result interface{} `json:"result,omitempty"`
Error *RPCError `json:"error,omitempty"`
}
// RPCError represents a JSON-RPC error object
type RPCError struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
}
// InitializeParams represents parameters for the 'initialize' request
type InitializeParams struct {
RootURI string `json:"rootUri"`
}
// InitializeResult represents the result of the 'initialize' request
type InitializeResult struct {
Capabilities ServerCapabilities `json:"capabilities"`
}
// ServerCapabilities defines the capabilities of the language server
type ServerCapabilities struct {
TextDocumentSync *TextDocumentSyncOptions `json:"textDocumentSync,omitempty"`
CompletionProvider *CompletionOptions `json:"completionProvider,omitempty"`
DefinitionProvider bool `json:"definitionProvider,omitempty"`
WorkspaceSymbolProvider bool `json:"workspaceSymbolProvider,omitempty"`
DocumentSymbolProvider bool `json:"documentSymbolProvider,omitempty"`
}
// TextDocumentSyncOptions defines options for text document synchronization
type TextDocumentSyncOptions struct {
Change int `json:"change"`
OpenClose bool `json:"openClose"`
Save bool `json:"save"`
}
// CompletionOptions defines options for the completion provider
type CompletionOptions struct {
TriggerCharacters []string `json:"triggerCharacters,omitempty"`
}
// WorkspaceSymbolParams represents the parameters for the 'workspace/symbol' request
type WorkspaceSymbolParams struct {
Query string `json:"query"`
}
// DocumentSymbolParams represents the parameters for the 'textDocument/documentSymbol' request
type DocumentSymbolParams struct {
TextDocument TextDocumentIdentifier `json:"textDocument"`
}
// SymbolInformation represents information about a symbol
type SymbolInformation struct {
Name string `json:"name"`
Kind int `json:"kind"`
Location Location `json:"location"`
ContainerName string `json:"containerName,omitempty"`
}
// DidOpenTextDocumentParams represents the 'textDocument/didOpen' notification
type DidOpenTextDocumentParams struct {
TextDocument TextDocument `json:"textDocument"`
}
// TextDocument represents a text document in the editor
type TextDocument struct {
URI string `json:"uri"`
LanguageID string `json:"languageId"`
Version int `json:"version"`
Text string `json:"text"`
}
// TextDocumentPositionParams represents the parameters used in requests that require a text document and position.
type TextDocumentPositionParams struct {
TextDocument TextDocumentIdentifier `json:"textDocument"`
Position Position `json:"position"`
}
// DidChangeTextDocumentParams represents the 'textDocument/didChange' notification
type DidChangeTextDocumentParams struct {
TextDocument TextDocumentIdentifier `json:"textDocument"`
ContentChanges []TextDocumentContentChangeEvent `json:"contentChanges"`
}
// TextDocumentIdentifier identifies a text document
type TextDocumentIdentifier struct {
URI string `json:"uri"`
}
// TextDocumentContentChangeEvent represents a change in the text document
type TextDocumentContentChangeEvent struct {
Text string `json:"text"`
}
// DidCloseTextDocumentParams represents the 'textDocument/didClose' notification
type DidCloseTextDocumentParams struct {
TextDocument TextDocumentIdentifier `json:"textDocument"`
}
// DidSaveTextDocumentParams represents the 'textDocument/didSave' notification
type DidSaveTextDocumentParams struct {
TextDocument TextDocumentIdentifier `json:"textDocument"`
Text string `json:"text,omitempty"`
}
// CompletionParams represents the 'textDocument/completion' request
type CompletionParams struct {
TextDocument PositionParams `json:"textDocument"`
Position Position `json:"position"`
}
// Position represents a position in a text document
type Position struct {
Line int `json:"line"`
Character int `json:"character"`
}
// PositionParams holds the URI for position-based requests
type PositionParams struct {
URI string `json:"uri"`
}
// CompletionItem represents a completion suggestion
type CompletionItem struct {
Label string `json:"label"`
Kind int `json:"kind,omitempty"`
Detail string `json:"detail,omitempty"`
Documentation *MarkupContent `json:"documentation,omitempty"`
}
// MarkupContent represents documentation content
type MarkupContent struct {
Kind string `json:"kind"`
Value string `json:"value"`
}
// CompletionList represents a list of completion items
type CompletionList struct {
IsIncomplete bool `json:"isIncomplete"`
Items []CompletionItem `json:"items"`
}
// Location represents a location in a text document
type Location struct {
URI string `json:"uri"`
Range Range `json:"range"`
}
// Range represents a range in a text document
type Range struct {
Start Position `json:"start"`
End Position `json:"end"`
}
// Server represents the language server
type Server struct {
tagEntries []TagEntry
rootPath string
cache FileCache
initialized bool
mu sync.Mutex
}
// FileCache stores the content of opened files for quick access
type FileCache struct {
mu sync.RWMutex
content map[string][]string
}
// GetOrLoadFileContent retrieves file content from cache or loads it from disk if not present
func (fc *FileCache) GetOrLoadFileContent(filePath string) ([]string, error) {
fc.mu.RLock()
content, ok := fc.content[filePath]
fc.mu.RUnlock()
if ok {
return content, nil
}
// Load the file content
lines, err := readFileLines(filePath)
if err != nil {
return nil, err
}
// Store content in cache
fc.mu.Lock()
fc.content[filePath] = lines
fc.mu.Unlock()
return lines, nil
}
// TagEntry represents a single ctags JSON entry
type TagEntry struct {
Type string `json:"_type"`
Name string `json:"name"`
Path string `json:"path"`
Pattern string `json:"pattern"`
Kind string `json:"kind"`
Line int `json:"line"`
Scope string `json:"scope,omitempty"`
ScopeKind string `json:"scopeKind,omitempty"`
TypeRef string `json:"typeref,omitempty"`
Language string `json:"language,omitempty"`
}
// getInstallInstructions returns OS-specific installation instructions for Universal Ctags
func getInstallInstructions() string {
switch runtime.GOOS {
case "darwin":
return "You can install Universal Ctags with: brew install universal-ctags"
case "linux":
return "You can install Universal Ctags with:\n" +
"- Ubuntu/Debian: sudo apt-get install universal-ctags\n" +
"- Fedora: sudo dnf install ctags\n" +
"- Arch Linux: sudo pacman -S ctags"
case "windows":
return "You can install Universal Ctags with:\n" +
"- Chocolatey: choco install universal-ctags\n" +
"- Scoop: scoop install universal-ctags\n" +
"Or download from: https://github.com/universal-ctags/ctags-win32/releases"
default:
return "Please visit https://github.com/universal-ctags/ctags for installation instructions"
}
}
// checkCtagsInstallation verifies that Universal Ctags is installed and supports required features
func checkCtagsInstallation() error {
cmd := exec.Command("ctags", "--version", "--output-format=json")
output, err := cmd.Output()
if err != nil || !strings.Contains(string(output), "Universal Ctags") {
return fmt.Errorf("ctags command not found or incorrect version. Universal Ctags with JSON support is required.\n%s", getInstallInstructions())
}
return nil
}
var version = "self compiled" // Populated with -X main.version
// Main Function
func main() {
config := parseFlags()
// Check for ctags installation before proceeding
if err := checkCtagsInstallation(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
if config.showHelp {
flagUsage()
os.Exit(0)
}
if config.showVersion {
fmt.Printf("CTags Language Server %s\n", version)
os.Exit(0)
}
server := &Server{
cache: FileCache{
content: make(map[string][]string),
},
}
reader := bufio.NewReader(os.Stdin)
for {
req, err := readMessage(reader)
if err != nil {
sendError(nil, -32600, "Malformed request", err.Error())
continue // Ignore malformed request
}
// Handle request in a separate goroutine
go handleRequest(server, req)
}
}
// readMessage reads a single JSON-RPC message from the reader
func readMessage(reader *bufio.Reader) (RPCRequest, error) {
contentLength := 0
for {
line, err := reader.ReadString('\r')
if err != nil {
return RPCRequest{}, fmt.Errorf("error reading header: %v", err)
}
b, err := reader.ReadByte()
if err != nil {
return RPCRequest{}, fmt.Errorf("error reading header: %v", err)
}
if b != '\n' {
return RPCRequest{}, fmt.Errorf("line endings must be \\r\\n")
}
if line == "\r" {
break // End of headers
}
if strings.HasPrefix(line, "Content-Length:") {
clStr := strings.TrimSpace(strings.TrimPrefix(line, "Content-Length:"))
cl, err := strconv.Atoi(clStr)
if err != nil {
return RPCRequest{}, fmt.Errorf("invalid Content-Length: %v", err)
}
contentLength = cl
}
}
body := make([]byte, contentLength)
_, err := io.ReadFull(reader, body)
if err != nil {
return RPCRequest{}, fmt.Errorf("error reading body: %v", err)
}
var req RPCRequest
err = json.Unmarshal(body, &req)
if err != nil {
return RPCRequest{}, fmt.Errorf("invalid JSON-RPC request: %v", err)
}
return req, nil
}
// Config holds command-line configuration options
type Config struct {
showHelp bool
showVersion bool
}
func parseFlags() *Config {
config := &Config{}
for _, arg := range os.Args[1:] {
switch arg {
case "-h", "--help":
config.showHelp = true
case "-v", "--version":
config.showVersion = true
}
}
return config
}
func flagUsage() {
fmt.Printf(`CTags Language Server
Provides LSP functionality using ctags JSON output.
Usage:
%s [options]
Options:
-h, --help Show this help message
-v, --version Show version information
`, os.Args[0])
}
// checkInitializedOrFail ensures that the server has been successfully initialized.
func checkInitializedOrFail(id json.RawMessage, server *Server, method string) bool {
// The following methods are allowed even if not initialized:
// - initialize (the first request)
// - shutdown and exit (for cleanup)
if method == "initialize" || method == "shutdown" || method == "exit" {
return true
}
if !server.initialized {
sendError(id, -32002, "Server not initialized", "Received request before successful initialization")
return false
}
return true
}
// handleRequest routes JSON-RPC requests to appropriate handlers
func handleRequest(server *Server, req RPCRequest) {
if !checkInitializedOrFail(req.ID, server, req.Method) {
// Server not initialized and request is not allowed.
return
}
switch req.Method {
case "initialize":
handleInitialize(server, req)
case "initialized":
handleInitialized(server, req)
case "shutdown":
handleShutdown(server, req)
case "exit":
handleExit(server, req)
case "textDocument/didOpen":
handleDidOpen(server, req)
case "textDocument/didChange":
handleDidChange(server, req)
case "textDocument/didClose":
handleDidClose(server, req)
case "textDocument/didSave":
handleDidSave(server, req)
case "textDocument/completion":
handleCompletion(server, req)
case "textDocument/definition":
handleDefinition(server, req)
case "workspace/symbol":
handleWorkspaceSymbol(server, req)
case "textDocument/documentSymbol":
handleDocumentSymbol(server, req)
case "$/cancelRequest":
handleCancelRequest(server, req)
case "$/setTrace":
handleSetTrace(server, req)
case "$/logTrace":
handleLogTrace(server, req)
default:
// Method not found
message := fmt.Sprintf("Method not found: %s", req.Method)
sendError(req.ID, -32601, message, nil)
}
}
// handleInitialize processes the 'initialize' request
func handleInitialize(server *Server, req RPCRequest) {
var params InitializeParams
err := json.Unmarshal(req.Params, ¶ms)
if err != nil {
sendError(req.ID, -32602, "Invalid params", nil)
return
}
if params.RootURI == "" {
// Use current working directory if RootURI is empty
cwd, err := os.Getwd()
if err != nil {
sendError(req.ID, -32603, "Failed to get current working directory", err.Error())
return
}
server.rootPath = cwd
} else {
// Convert RootURI to filesystem path
server.rootPath = uriToPath(params.RootURI)
}
// Load ctags entries
if err := server.scanWorkspace(); err != nil {
sendError(req.ID, -32603, "Internal error while scanning tags", err.Error())
return
}
// Define server capabilities
result := InitializeResult{
Capabilities: ServerCapabilities{
TextDocumentSync: &TextDocumentSyncOptions{
Change: 1, // Full synchronization
OpenClose: true,
Save: true,
},
CompletionProvider: &CompletionOptions{
TriggerCharacters: []string{".", "\""},
},
WorkspaceSymbolProvider: true,
DefinitionProvider: true,
DocumentSymbolProvider: true,
},
}
sendResult(req.ID, result)
server.initialized = true
}
// handleInitialized processes the 'initialized' notification
func handleInitialized(_ *Server, _ RPCRequest) {
// 'initialized' is a notification with no response
}
// handleShutdown processes the 'shutdown' request
func handleShutdown(_ *Server, req RPCRequest) {
sendResult(req.ID, nil)
}
// handleExit processes the 'exit' notification
func handleExit(_ *Server, _ RPCRequest) {
os.Exit(0)
}
// handleCancelRequest processes the '$/cancelRequest' notification
// (For canceling in-progress requests)
func handleCancelRequest(_ *Server, _ RPCRequest) {
// Not currently in use
}
// handleSetTrace() processes the '$/setTrace' notification
// (Controls trace output level)
func handleSetTrace(_ *Server, req RPCRequest) {
// Not currently in use
sendResult(req.ID, nil)
}
// handleLogTrace() processes the '$/logTrace' notification
// (For transmitting trace data)
func handleLogTrace(_ *Server, _ RPCRequest) {
// Not currently in use
}
// handleDidOpen processes the 'textDocument/didOpen' notification
func handleDidOpen(server *Server, req RPCRequest) {
var params DidOpenTextDocumentParams
err := json.Unmarshal(req.Params, ¶ms)
if err != nil {
return
}
uri := params.TextDocument.URI
content := strings.Split(params.TextDocument.Text, "\n")
// Cache the opened document's content
server.cache.mu.Lock()
server.cache.content[uriToPath(uri)] = content
server.cache.mu.Unlock()
}
// handleDidChange processes the 'textDocument/didChange' notification
func handleDidChange(server *Server, req RPCRequest) {
var params DidChangeTextDocumentParams
err := json.Unmarshal(req.Params, ¶ms)
if err != nil {
return
}
uri := params.TextDocument.URI
if len(params.ContentChanges) > 0 {
content := strings.Split(params.ContentChanges[0].Text, "\n")
// Update the cached content
server.cache.mu.Lock()
server.cache.content[uriToPath(uri)] = content
server.cache.mu.Unlock()
}
}
// handleDidClose processes the 'textDocument/didClose' notification
func handleDidClose(server *Server, req RPCRequest) {
var params DidCloseTextDocumentParams
err := json.Unmarshal(req.Params, ¶ms)
if err != nil {
return
}
uri := params.TextDocument.URI
// Remove the document from cache
server.cache.mu.Lock()
delete(server.cache.content, uriToPath(uri))
server.cache.mu.Unlock()
}
// handleDidSave processes the 'textDocument/didSave' notification
func handleDidSave(server *Server, req RPCRequest) {
var params DidSaveTextDocumentParams
err := json.Unmarshal(req.Params, ¶ms)
if err != nil {
return
}
// Get file path from URI
filePath := uriToPath(params.TextDocument.URI)
// Scan the file again
if err := server.scanSingleFileTag(filePath); err != nil {
log.Printf("Error rescanning file %s: %v", filePath, err)
}
}
// handleCompletion processes the 'textDocument/completion' request
func handleCompletion(server *Server, req RPCRequest) {
var params CompletionParams
err := json.Unmarshal(req.Params, ¶ms)
if err != nil {
sendError(req.ID, -32602, "Invalid params", nil)
return
}
currentFilePath := uriToPath(params.TextDocument.URI)
currentFileExt := filepath.Ext(currentFilePath)
// Get the line content and check if the character before the cursor is a dot
server.cache.mu.RLock()
lines, ok := server.cache.content[currentFilePath]
server.cache.mu.RUnlock()
if !ok || params.Position.Line >= len(lines) {
sendError(req.ID, -32603, "Internal error", "Line out of range")
return
}
lineContent := lines[params.Position.Line]
runes := []rune(lineContent)
isAfterDot := false
if params.Position.Character > 0 && params.Position.Character-1 < len(runes) {
prevChar := runes[params.Position.Character-1]
isAfterDot = prevChar == '.'
}
// Retrieve the current word at the cursor position
word, err := server.getCurrentWord(params.TextDocument.URI, params.Position)
if err != nil {
sendResult(req.ID, CompletionList{
IsIncomplete: false,
Items: []CompletionItem{},
})
return
}
var items []CompletionItem
seenItems := make(map[string]bool)
for _, entry := range server.tagEntries {
if strings.HasPrefix(strings.ToLower(entry.Name), strings.ToLower(word)) {
if seenItems[entry.Name] {
continue // Avoid duplicate entries
}
kind := GetLSPCompletionKind(entry.Kind)
// Get the file extension of the entry's file
entryFilePath := filepath.Join(server.rootPath, entry.Path)
entryFileExt := filepath.Ext(entryFilePath)
// Decide whether to include this entry
includeEntry := false
if isAfterDot {
// After a dot, only include methods and functions, excluding 'text' items
if (kind == CompletionItemKindMethod || kind == CompletionItemKindFunction) && entryFileExt == currentFileExt {
includeEntry = true
}
} else {
// Not after a dot
if kind == CompletionItemKindText {
// Always include 'text' items
includeEntry = true
} else if entryFileExt == currentFileExt {
// Include items from files with the same extension
includeEntry = true
}
}
if includeEntry {
seenItems[entry.Name] = true
items = append(items, CompletionItem{
Label: entry.Name,
Kind: kind,
Detail: fmt.Sprintf("%s:%d (%s)", entry.Path, entry.Line, entry.Kind),
Documentation: &MarkupContent{
Kind: "plaintext",
Value: entry.Pattern,
},
})
}
}
}
result := CompletionList{
IsIncomplete: false,
Items: items,
}
sendResult(req.ID, result)
}
// handleDefinition processes the 'textDocument/definition' request
func handleDefinition(server *Server, req RPCRequest) {
var params TextDocumentPositionParams
err := json.Unmarshal(req.Params, ¶ms)
if err != nil {
sendError(req.ID, -32602, "Invalid params", nil)
return
}
// Get the current word at the given position
symbol, err := server.getCurrentWord(params.TextDocument.URI, params.Position)
if err != nil {
sendResult(req.ID, nil) // No symbol found at position or error occurred
return
}
// Search for the symbol in the tagEntries
server.mu.Lock()
defer server.mu.Unlock()
var locations []Location
for _, entry := range server.tagEntries {
if entry.Name == symbol {
// Create a Location for the symbol's definition
filePath := filepath.Join(server.rootPath, entry.Path)
uri := filepathToURI(filePath)
// Use the refactored method to get file content
content, err := server.cache.GetOrLoadFileContent(filePath)
if err != nil {
log.Printf("Failed to get content for file %s: %v", filePath, err)
continue
}
// Find the symbol's range within the file
symbolRange := findSymbolRangeInFile(content, entry.Name, entry.Line)
location := Location{
URI: uri,
Range: symbolRange,
}
locations = append(locations, location)
}
}
// Send the locations back
if len(locations) == 0 {
sendResult(req.ID, nil) // No definition found
} else if len(locations) == 1 {
sendResult(req.ID, locations[0])
} else {
sendResult(req.ID, locations)
}
}
// handleWorkspaceSymbol processes the 'workspace/symbol' request
func handleWorkspaceSymbol(server *Server, req RPCRequest) {
var params WorkspaceSymbolParams
err := json.Unmarshal(req.Params, ¶ms)
if err != nil {
sendError(req.ID, -32602, "Invalid params", nil)
return
}
query := params.Query
var symbols []SymbolInformation
server.mu.Lock()
defer server.mu.Unlock()
for _, entry := range server.tagEntries {
if entry.Name == query {
kind, err := GetLSPSymbolKind(entry.Kind)
if err != nil {
// This tag has no symbol kind, skip
continue
}
filePath := filepath.Join(server.rootPath, entry.Path)
uri := filepathToURI(filePath)
// Use the refactored method to get file content
content, err := server.cache.GetOrLoadFileContent(filePath)
if err != nil {
log.Printf("Failed to get content for file %s: %v", filePath, err)
continue
}
// Find the symbol's range within the file
symbolRange := findSymbolRangeInFile(content, entry.Name, entry.Line)
symbol := SymbolInformation{
Name: entry.Name,
Kind: kind,
Location: Location{
URI: uri,
Range: symbolRange,
},
ContainerName: entry.Scope,
}
symbols = append(symbols, symbol)
}
}
sendResult(req.ID, symbols)
}
// handleDocumentSymbol processes the 'textDocument/documentSymbol' request
func handleDocumentSymbol(server *Server, req RPCRequest) {
var params DocumentSymbolParams
err := json.Unmarshal(req.Params, ¶ms)
if err != nil {
sendError(req.ID, -32602, "Invalid params", nil)
return
}
filePath := uriToPath(params.TextDocument.URI)
server.mu.Lock()
defer server.mu.Unlock()
var symbols []SymbolInformation
for _, entry := range server.tagEntries {
// Check if the symbol belongs to the requested document
absolutePath := filepath.Join(server.rootPath, entry.Path)
absolutePath, err := filepath.Abs(absolutePath)
if err != nil {
log.Printf("Failed to get absolute path for %s: %v", entry.Path, err)
continue
}
requestedPath, err := filepath.Abs(filePath)
if err != nil {
log.Printf("Failed to get absolute path for %s: %v", filePath, err)
continue
}
if absolutePath != requestedPath {
continue
}
kind, err := GetLSPSymbolKind(entry.Kind)
if err != nil {
// Skip symbols with unknown kinds
continue
}
uri := filepathToURI(absolutePath)
// Retrieve file content
content, err := server.cache.GetOrLoadFileContent(absolutePath)
if err != nil {
log.Printf("Failed to get content for file %s: %v", absolutePath, err)
continue
}
// Find the symbol's range within the file
symbolRange := findSymbolRangeInFile(content, entry.Name, entry.Line)
symbol := SymbolInformation{
Name: entry.Name,
Kind: kind,
Location: Location{URI: uri, Range: symbolRange},
ContainerName: entry.Scope,
}
symbols = append(symbols, symbol)
}
sendResult(req.ID, symbols)
}
// readFileLines reads the content of a file and returns it as a slice of lines
func readFileLines(filePath string) ([]string, error) {
contentBytes, err := os.ReadFile(filePath)
if err != nil {
return nil, err
}
content := string(contentBytes)
lines := strings.Split(content, "\n")
return lines, nil
}
// findSymbolRangeInFile searches for the symbol in the specified line and returns its range
func findSymbolRangeInFile(lines []string, symbolName string, lineNumber int) Range {
// Adjust line number to zero-based index
lineIdx := lineNumber - 1
if lineIdx < 0 || lineIdx >= len(lines) {
// Line number out of range; return a zero range
return Range{
Start: Position{Line: lineIdx, Character: 0},
End: Position{Line: lineIdx, Character: 0},
}
}
lineContent := lines[lineIdx]
startChar := strings.Index(lineContent, symbolName)
if startChar == -1 {
// Symbol not found in the expected line; default to line start
return Range{
Start: Position{Line: lineIdx, Character: 0},
End: Position{Line: lineIdx, Character: len([]rune(lineContent))},
}
}
// Calculate the end character position
endChar := startChar + len([]rune(symbolName))
return Range{
Start: Position{Line: lineIdx, Character: startChar},
End: Position{Line: lineIdx, Character: endChar},
}
}
// sendResult sends a successful JSON-RPC response
func sendResult(id json.RawMessage, result interface{}) {
response := RPCResponse{
Jsonrpc: "2.0",
ID: id,
Result: result,
}
sendResponse(response)
}
// sendError sends an error JSON-RPC response
func sendError(id json.RawMessage, code int, message string, data interface{}) {
response := RPCResponse{
Jsonrpc: "2.0",
ID: id,
Error: &RPCError{
Code: code,
Message: message,
Data: data,
},
}
sendResponse(response)
}
// sendResponse marshals and sends the JSON-RPC response with appropriate headers
func sendResponse(resp RPCResponse) {
body, err := json.Marshal(resp)
if err != nil {
log.Printf("Error marshaling response: %v", err)
return
}
// Write headers followed by the JSON body
fmt.Printf("Content-Length: %d\r\n\r\n%s", len(body), string(body))
}
// uriToPath converts a file URI to a filesystem path
func uriToPath(uri string) string {
if strings.HasPrefix(uri, "file://") {
return filepath.FromSlash(strings.TrimPrefix(uri, "file://"))
}
return uri
}
// filepathToURI converts a filesystem path to a file URI
func filepathToURI(path string) string {
absPath, err := filepath.Abs(path)
if err != nil {
return ""
}
return "file://" + filepath.ToSlash(absPath)
}
// scanWorkspace scans all files in the root path
func (s *Server) scanWorkspace() error {
var cmd *exec.Cmd
// Respect gitignore, fallback to all files
if isGitRepo(s.rootPath) {
// Use `git ls-files` to generate file list and pipe to ctags
cmd = pipeCommand("git", []string{"ls-files"}, "ctags", []string{"--output-format=json", "--fields=+n", "-L", "-"})
} else if isJjRepo(s.rootPath) {
// Use `jj file list` to generate file list and pipe to ctags
cmd = pipeCommand("jj", []string{"file", "list", "--repository", "."}, "ctags", []string{"--output-format=json", "--fields=+n", "-L", "-"})
} else {
// Fallback to `ctags -R`
cmd = exec.Command("ctags", "--output-format=json", "--fields=+n", "-R")
cmd.Dir = s.rootPath
}
return s.processTagsOutput(cmd)
}
// pipeCommand creates a command to pipe output from one command to another
func pipeCommand(producerCmd string, producerArgs []string, consumerCmd string, consumerArgs []string) *exec.Cmd {
producer := exec.Command(producerCmd, producerArgs...)
consumer := exec.Command(consumerCmd, consumerArgs...)
// Pipe producer's stdout to consumer's stdin
pipe, err := producer.StdoutPipe()
if err != nil {
log.Fatalf("Failed to create pipe between commands: %v", err)
}
consumer.Stdin = pipe
// Start the producer when the consumer is executed
go func() {
if err := producer.Start(); err != nil {
log.Fatalf("Failed to start producer command (%s): %v", producerCmd, err)
}
}()
return consumer
}
// isGitRepo checks if the directory is a Git repository
func isGitRepo(path string) bool {
cmd := exec.Command("git", "-C", path, "rev-parse", "--is-inside-work-tree")