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
|
package gopls
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/grindlemire/go-tui/internal/lsp/log"
)
type DiagnosticCallback func(uri string, diagnostics []GoplsDiagnostic)
type SourceMapLookup func(gsxURI string) func(goLine, goCol int) (gsxLine, gsxCol int, found bool)
type GoplsDiagnostic struct {
Range Range `json:"range"`
Severity int `json:"severity"`
Message string `json:"message"`
Source string `json:"source"`
}
type GoplsProxy struct {
cmd *exec.Cmd
stdin io.WriteCloser
stdout *bufio.Reader
mu sync.Mutex
nextID atomic.Int64
pending map[int64]chan *Response
pendingMu sync.Mutex
virtualFiles map[string]*VirtualFile
virtualFilesMu sync.RWMutex
rootURI string
diagnosticCallback DiagnosticCallback
diagnosticMu sync.RWMutex
sourceMapLookup SourceMapLookup
ctx context.Context
cancel context.CancelFunc
}
type VirtualFile struct {
URI string
Content string
SourceMap *SourceMap
Version int
}
type Request struct {
JSONRPC string `json:"jsonrpc"`
ID int64 `json:"id,omitempty"`
Method string `json:"method"`
Params any `json:"params,omitempty"`
}
type Response struct {
JSONRPC string `json:"jsonrpc"`
ID int64 `json:"id,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *ResponseError `json:"error,omitempty"`
}
type ResponseError struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
type Position struct {
Line int `json:"line"`
Character int `json:"character"`
}
type Range struct {
Start Position `json:"start"`
End Position `json:"end"`
}
type Location struct {
URI string `json:"uri"`
Range Range `json:"range"`
}
type TextDocumentIdentifier struct {
URI string `json:"uri"`
}
type TextDocumentPositionParams struct {
TextDocument TextDocumentIdentifier `json:"textDocument"`
Position Position `json:"position"`
}
type CompletionParams struct {
TextDocumentPositionParams
Context *CompletionContext `json:"context,omitempty"`
}
type CompletionContext struct {
TriggerKind int `json:"triggerKind"`
TriggerCharacter string `json:"triggerCharacter,omitempty"`
}
type CompletionItem struct {
Label string `json:"label"`
Kind int `json:"kind,omitempty"`
Detail string `json:"detail,omitempty"`
Documentation *MarkupContent `json:"documentation,omitempty"`
InsertText string `json:"insertText,omitempty"`
FilterText string `json:"filterText,omitempty"`
}
type CompletionList struct {
IsIncomplete bool `json:"isIncomplete"`
Items []CompletionItem `json:"items"`
}
type Hover struct {
Contents MarkupContent `json:"contents"`
Range *Range `json:"range,omitempty"`
}
type MarkupContent struct {
Kind string `json:"kind"`
Value string `json:"value"`
}
func NewGoplsProxy(ctx context.Context) (*GoplsProxy, error) {
goplsPath, err := exec.LookPath("gopls")
if err != nil {
return nil, fmt.Errorf("gopls not found in PATH: %w", err)
}
proxyCtx, cancel := context.WithCancel(ctx)
cmd := exec.CommandContext(proxyCtx, goplsPath, "-mode=stdio")
cmd.Env = os.Environ()
stdin, err := cmd.StdinPipe()
if err != nil {
cancel()
return nil, fmt.Errorf("creating stdin pipe: %w", err)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
cancel()
return nil, fmt.Errorf("creating stdout pipe: %w", err)
}
cmd.Stderr = nil
p := &GoplsProxy{
cmd: cmd,
stdin: stdin,
stdout: bufio.NewReader(stdout),
pending: make(map[int64]chan *Response),
virtualFiles: make(map[string]*VirtualFile),
ctx: proxyCtx,
cancel: cancel,
}
if err := cmd.Start(); err != nil {
cancel()
return nil, fmt.Errorf("starting gopls: %w", err)
}
go p.readResponses()
return p, nil
}
func (p *GoplsProxy) Initialize(rootURI string) error {
p.rootURI = rootURI
initParams := map[string]any{
"processId": os.Getpid(),
"rootUri": rootURI,
"capabilities": map[string]any{
"textDocument": map[string]any{
"completion": map[string]any{
"completionItem": map[string]any{
"snippetSupport": false,
},
},
"hover": map[string]any{
"contentFormat": []string{"markdown", "plaintext"},
},
},
},
}
result, err := p.call("initialize", initParams)
if err != nil {
return fmt.Errorf("initialize: %w", err)
}
log.Gopls("Initialize result: %s", string(result))
if err := p.notify("initialized", map[string]any{}); err != nil {
return fmt.Errorf("initialized notification: %w", err)
}
return nil
}
func (p *GoplsProxy) SetDiagnosticCallback(cb DiagnosticCallback) {
p.diagnosticMu.Lock()
defer p.diagnosticMu.Unlock()
p.diagnosticCallback = cb
}
func (p *GoplsProxy) SetSourceMapLookup(lookup SourceMapLookup) {
p.sourceMapLookup = lookup
}
func (p *GoplsProxy) Shutdown() error {
_, err := p.call("shutdown", nil)
if err != nil {
return err
}
if err := p.notify("exit", nil); err != nil {
return err
}
done := make(chan error, 1)
go func() { done <- p.cmd.Wait() }()
select {
case err := <-done:
p.cancel()
return err
case <-time.After(5 * time.Second):
p.cancel()
return <-done
}
}
func (p *GoplsProxy) send(req Request) error {
data, err := json.Marshal(req)
if err != nil {
return err
}
log.Gopls("Sending: %s", string(data))
header := fmt.Sprintf("Content-Length: %d\r\n\r\n", len(data))
p.mu.Lock()
defer p.mu.Unlock()
if _, err := p.stdin.Write([]byte(header)); err != nil {
return err
}
if _, err := p.stdin.Write(data); err != nil {
return err
}
return nil
}
type Notification struct {
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params json.RawMessage `json:"params"`
}
type publishDiagnosticsParams struct {
URI string `json:"uri"`
Diagnostics []goplsDiagnostic `json:"diagnostics"`
}
type goplsDiagnostic struct {
Range Range `json:"range"`
Severity int `json:"severity"`
Message string `json:"message"`
Source string `json:"source"`
}
func (p *GoplsProxy) readResponses() {
for {
select {
case <-p.ctx.Done():
return
default:
}
msg, err := p.readMessage()
if err != nil {
log.Gopls("Error reading message: %v", err)
return
}
log.Gopls("Received: %s", string(msg))
var notif Notification
if err := json.Unmarshal(msg, ¬if); err == nil && notif.Method != "" {
p.handleNotification(¬if)
continue
}
var resp Response
if err := json.Unmarshal(msg, &resp); err != nil {
log.Gopls("Error parsing response: %v", err)
continue
}
if resp.ID == 0 {
continue
}
p.pendingMu.Lock()
if ch, ok := p.pending[resp.ID]; ok {
ch <- &resp
}
p.pendingMu.Unlock()
}
}
func (p *GoplsProxy) handleNotification(notif *Notification) {
log.Gopls("Received notification: method=%s", notif.Method)
if notif.Method != "textDocument/publishDiagnostics" {
return
}
var params publishDiagnosticsParams
if err := json.Unmarshal(notif.Params, ¶ms); err != nil {
log.Gopls("Error parsing diagnostics params: %v", err)
return
}
log.Gopls("Diagnostics for URI=%s count=%d", params.URI, len(params.Diagnostics))
for i, d := range params.Diagnostics {
log.Gopls(" [%d] %s: %s", i, d.Range, d.Message)
}
if IsVirtualGoFile(params.URI) {
log.Gopls("Skipping virtual file diagnostics: %s", params.URI)
return
}
if !IsGeneratedGoFile(params.URI) {
log.Gopls("Skipping - not a generated _gsx.go file: %s", params.URI)
return
}
gsxURI := GeneratedGoURIToTuiURI(params.URI)
lineOffset := 1
log.Gopls("Real file diagnostics for %s (offset=%d)", gsxURI, lineOffset)
log.Gopls("Mapped to gsxURI=%s", gsxURI)
var translatePos func(goLine, goCol int) (gsxLine, gsxCol int, found bool)
if p.sourceMapLookup != nil {
translatePos = p.sourceMapLookup(gsxURI)
}
if translatePos == nil {
log.Gopls("No source map available for %s", gsxURI)
return
}
var translated []GoplsDiagnostic
for _, diag := range params.Diagnostics {
isRedeclaration := strings.Contains(diag.Message, "redeclared") || strings.Contains(diag.Message, "already declared")
referencesGeneratedFile := strings.Contains(diag.Message, "_gsx.go")
isBlockRedeclaration := strings.Contains(diag.Message, "redeclared in this block")
if isRedeclaration && (referencesGeneratedFile || isBlockRedeclaration) {
log.Gopls("Skipping redeclaration error: %s", diag.Message)
continue
}
if strings.Contains(diag.Message, "unknown field") && strings.Contains(diag.Message, "in struct literal") {
log.Gopls("Skipping unknown field error: %s", diag.Message)
continue
}
adjustedStartLine := max(diag.Range.Start.Line-lineOffset, 0)
gsxStartLine, gsxStartCol, startFound := translatePos(adjustedStartLine, diag.Range.Start.Character)
adjustedEndLine := max(diag.Range.End.Line-lineOffset, 0)
gsxEndLine, gsxEndCol, endFound := translatePos(adjustedEndLine, diag.Range.End.Character)
if !startFound || !endFound {
log.Gopls("Could not translate diagnostic position: line=%d col=%d msg=%s",
diag.Range.Start.Line, diag.Range.Start.Character, diag.Message)
continue
}
log.Gopls("Translated: go=%d:%d -> gsx=%d:%d msg=%s",
diag.Range.Start.Line, diag.Range.Start.Character,
gsxStartLine, gsxStartCol, diag.Message)
translated = append(translated, GoplsDiagnostic{
Range: Range{
Start: Position{Line: gsxStartLine, Character: gsxStartCol},
End: Position{Line: gsxEndLine, Character: gsxEndCol},
},
Severity: diag.Severity,
Message: diag.Message,
Source: "gopls",
})
}
p.diagnosticMu.RLock()
cb := p.diagnosticCallback
p.diagnosticMu.RUnlock()
if cb != nil && len(translated) > 0 {
cb(gsxURI, translated)
}
}
func (p *GoplsProxy) readMessage() ([]byte, error) {
var contentLength int
for {
line, err := p.stdout.ReadString('\n')
if err != nil {
return nil, err
}
line = strings.TrimSpace(line)
if line == "" {
break
}
if after, ok := strings.CutPrefix(line, "Content-Length:"); ok {
lenStr := strings.TrimSpace(after)
contentLength, err = strconv.Atoi(lenStr)
if err != nil {
return nil, fmt.Errorf("invalid Content-Length: %w", err)
}
}
}
if contentLength == 0 {
return nil, fmt.Errorf("missing Content-Length header")
}
content := make([]byte, contentLength)
_, err := io.ReadFull(p.stdout, content)
if err != nil {
return nil, fmt.Errorf("reading content: %w", err)
}
return content, nil
}
func TuiURIToGoURI(tuiURI string) string {
if before, ok := strings.CutSuffix(tuiURI, ".gsx"); ok {
return before + "_gsx_generated.go"
}
return tuiURI + "_generated.go"
}
func GoURIToTuiURI(goURI string) string {
if before, ok := strings.CutSuffix(goURI, "_gsx_generated.go"); ok {
return before + ".gsx"
}
return goURI
}
func IsVirtualGoFile(uri string) bool {
return strings.HasSuffix(uri, "_gsx_generated.go")
}
func GetVirtualFilePath(gsxPath string) string {
dir := filepath.Dir(gsxPath)
base := filepath.Base(gsxPath)
if before, ok := strings.CutSuffix(base, ".gsx"); ok {
base = before + "_gsx_generated.go"
} else {
base = base + "_generated.go"
}
return filepath.Join(dir, base)
}
func IsGeneratedGoFile(uri string) bool {
return strings.HasSuffix(uri, "_gsx.go") && !strings.HasSuffix(uri, "_gsx_generated.go")
}
func GeneratedGoURIToTuiURI(goURI string) string {
if before, ok := strings.CutSuffix(goURI, "_gsx.go"); ok {
return before + ".gsx"
}
return goURI
}
|