gitstack

grindlemire/go-tui code browser

10.2 KB Go 404 lines 2026-06-03 ยท d15bb9f raw
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
// Package lsp provides a Language Server Protocol implementation for .gsx files.
package lsp

import (
	"bufio"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
	"sync"

	"github.com/grindlemire/go-tui/internal/lsp/gopls"
	"github.com/grindlemire/go-tui/internal/lsp/log"
	"github.com/grindlemire/go-tui/internal/tuigen"
)

// Server represents the TUI LSP server.
type Server struct {
	// Input/output for JSON-RPC communication
	reader *bufio.Reader
	writer io.Writer
	mu     sync.Mutex // protects writer

	// Request routing
	router *Router

	// Document management
	docs *DocumentManager

	// Component index for workspace symbols and go-to-definition
	index *ComponentIndex

	// Workspace AST cache for files not open in editor
	workspaceASTs   map[string]*tuigen.File // URI -> AST
	workspaceASTsMu sync.RWMutex

	// gopls proxy for Go expression intelligence
	goplsProxy *gopls.GoplsProxy

	// Virtual file cache for gopls
	virtualFiles *gopls.VirtualFileCache

	// Gopls diagnostics per URI
	goplsDiagnostics   map[string][]gopls.GoplsDiagnostic
	goplsDiagnosticsMu sync.RWMutex

	// Server state
	initialized bool
	shutdown    bool
	rootURI     string

	// Context for gopls
	ctx    context.Context
	cancel context.CancelFunc
}

// NewServer creates a new LSP server that communicates over the given reader/writer.
func NewServer(reader io.Reader, writer io.Writer) *Server {
	ctx, cancel := context.WithCancel(context.Background())
	s := &Server{
		reader:           bufio.NewReader(reader),
		writer:           writer,
		docs:             NewDocumentManager(),
		index:            NewComponentIndex(),
		workspaceASTs:    make(map[string]*tuigen.File),
		virtualFiles:     gopls.NewVirtualFileCache(),
		goplsDiagnostics: make(map[string][]gopls.GoplsDiagnostic),
		ctx:              ctx,
		cancel:           cancel,
	}
	// Create provider registry for all LSP feature providers.
	registry := s.CreateProviderRegistry()
	s.router = NewRouter(s, registry)
	return s
}

// SetLogFile sets a file for debug logging.
func (s *Server) SetLogFile(f *os.File) {
	log.SetOutput(f)
}

// InitGopls initializes the gopls proxy. Call this after Initialize.
func (s *Server) InitGopls() error {
	if s.rootURI == "" {
		log.Server("Cannot init gopls without rootURI")
		return nil
	}

	proxy, err := gopls.NewGoplsProxy(s.ctx)
	if err != nil {
		log.Server("Failed to start gopls: %v", err)
		return nil // Non-fatal, continue without gopls
	}

	if err := proxy.Initialize(s.rootURI); err != nil {
		log.Server("Failed to initialize gopls: %v", err)
		proxy.Shutdown()
		return nil // Non-fatal
	}

	s.goplsProxy = proxy
	log.Server("gopls proxy initialized successfully")

	// Set up diagnostic callback to receive gopls diagnostics
	proxy.SetDiagnosticCallback(s.handleGoplsDiagnostics)

	// Set up source map lookup for position translation
	proxy.SetSourceMapLookup(s.lookupSourceMap)

	// Update virtual files for all already-open documents
	for _, doc := range s.docs.All() {
		s.UpdateVirtualFile(doc)
	}

	return nil
}

// lookupSourceMap returns a position translation function for the given .gsx URI.
// Uses the in-memory virtual file source map, which is always up-to-date with the current document.
func (s *Server) lookupSourceMap(gsxURI string) func(goLine, goCol int) (gsxLine, gsxCol int, found bool) {
	// Use the virtual file cache (in-memory, always current)
	cached := s.virtualFiles.Get(gsxURI)
	if cached == nil || cached.SourceMap == nil {
		log.Server("No virtual file source map for %s", gsxURI)
		return nil
	}

	log.Server("Using in-memory source map for %s (%d mappings)", gsxURI, cached.SourceMap.Len())
	return cached.SourceMap.GoToTui
}

// handleGoplsDiagnostics receives diagnostics from gopls and republishes them.
func (s *Server) handleGoplsDiagnostics(uri string, diagnostics []gopls.GoplsDiagnostic) {
	log.Server("Received %d gopls diagnostics for %s", len(diagnostics), uri)

	// Store the gopls diagnostics
	s.goplsDiagnosticsMu.Lock()
	s.goplsDiagnostics[uri] = diagnostics
	s.goplsDiagnosticsMu.Unlock()

	// Republish diagnostics for this document
	doc := s.docs.Get(uri)
	if doc != nil {
		s.publishDiagnostics(doc)
	}
}

// ShutdownGopls shuts down the gopls proxy.
func (s *Server) ShutdownGopls() {
	if s.goplsProxy != nil {
		s.goplsProxy.Shutdown()
		s.goplsProxy = nil
	}
	if s.cancel != nil {
		s.cancel()
	}
}

// UpdateVirtualFile updates the virtual .go file for a .gsx document.
func (s *Server) UpdateVirtualFile(doc *Document) {
	if s.goplsProxy == nil || doc.AST == nil {
		return
	}

	// Generate virtual Go file
	log.Server("=== Generating virtual Go file for %s ===", doc.URI)
	goContent, sourceMap := gopls.GenerateVirtualGo(doc.AST)
	goURI := gopls.TuiURIToGoURI(doc.URI)

	// Log the generated content
	log.Server("Generated Go content:\n%s", goContent)

	// Log all mappings
	log.Server("=== Source mappings (%d total) ===", sourceMap.Len())
	for i, m := range sourceMap.AllMappings() {
		log.Server("  [%d] TuiLine=%d TuiCol=%d -> GoLine=%d GoCol=%d Len=%d",
			i, m.TuiLine, m.TuiCol, m.GoLine, m.GoCol, m.Length)
	}
	log.Server("=== End mappings ===")

	// Check if we already have this file open in gopls
	cached := s.virtualFiles.Get(doc.URI)
	if cached != nil {
		// Update existing file
		if err := s.goplsProxy.UpdateVirtualFile(goURI, goContent, doc.Version); err != nil {
			log.Server("Failed to update virtual file: %v", err)
		}
	} else {
		// Open new file
		if err := s.goplsProxy.OpenVirtualFile(goURI, goContent, doc.Version); err != nil {
			log.Server("Failed to open virtual file: %v", err)
		}
	}

	// Update cache
	s.virtualFiles.Put(doc.URI, goURI, goContent, sourceMap, doc.Version)
}

// CloseVirtualFile closes the virtual .go file for a .gsx document.
func (s *Server) CloseVirtualFile(uri string) {
	if s.goplsProxy == nil {
		return
	}

	cached := s.virtualFiles.Get(uri)
	if cached != nil {
		if err := s.goplsProxy.CloseVirtualFile(cached.GoURI); err != nil {
			log.Server("Failed to close virtual file: %v", err)
		}
		s.virtualFiles.Remove(uri)
	}
}

// Run starts the LSP server main loop.
func (s *Server) Run(ctx context.Context) error {
	log.Server("LSP server starting")

	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		default:
		}

		msg, err := s.readMessage()
		if err != nil {
			if err == io.EOF {
				log.Server("Connection closed")
				return nil
			}
			log.Server("Error reading message: %v", err)
			return fmt.Errorf("reading message: %w", err)
		}

		log.Server("Received: %s", string(msg))

		response, err := s.handleMessage(msg)
		if err != nil {
			log.Server("Error handling message: %v", err)
			// Send error response if we have an ID
			continue
		}

		if response != nil {
			if err := s.writeMessage(response); err != nil {
				log.Server("Error writing response: %v", err)
				return fmt.Errorf("writing response: %w", err)
			}
		}

		if s.shutdown {
			log.Server("Server shutdown requested")
			return nil
		}
	}
}

// readMessage reads a JSON-RPC message from the input.
// Messages are formatted as HTTP-like headers followed by content:
// Content-Length: <length>\r\n
// \r\n
// <content>
func (s *Server) readMessage() ([]byte, error) {
	// Read headers
	var contentLength int
	for {
		line, err := s.reader.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")
	}

	// Read content
	content := make([]byte, contentLength)
	_, err := io.ReadFull(s.reader, content)
	if err != nil {
		return nil, fmt.Errorf("reading content: %w", err)
	}

	return content, nil
}

// writeMessage writes a JSON-RPC message to the output.
func (s *Server) writeMessage(msg []byte) error {
	s.mu.Lock()
	defer s.mu.Unlock()

	header := fmt.Sprintf("Content-Length: %d\r\n\r\n", len(msg))
	if _, err := s.writer.Write([]byte(header)); err != nil {
		return err
	}
	if _, err := s.writer.Write(msg); err != nil {
		return err
	}

	log.Server("Sent: %s", string(msg))
	return nil
}

// sendNotification sends a notification (no response expected).
func (s *Server) sendNotification(method string, params any) error {
	msg := map[string]any{
		"jsonrpc": "2.0",
		"method":  method,
		"params":  params,
	}
	data, err := json.Marshal(msg)
	if err != nil {
		return err
	}
	return s.writeMessage(data)
}

// Request represents a JSON-RPC request.
type Request struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      any             `json:"id,omitempty"` // can be number or string
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
}

// Response represents a JSON-RPC response.
type Response struct {
	JSONRPC string `json:"jsonrpc"`
	ID      any    `json:"id,omitempty"`
	Result  any    `json:"result"`
	Error   *Error `json:"error,omitempty"`
}

// Error represents a JSON-RPC error.
type Error struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
}

// JSON-RPC error codes
const (
	CodeParseError     = -32700
	CodeInvalidRequest = -32600
	CodeMethodNotFound = -32601
	CodeInvalidParams  = -32602
	CodeInternalError  = -32603
)

// handleMessage processes a single JSON-RPC message.
func (s *Server) handleMessage(msg []byte) ([]byte, error) {
	var req Request
	if err := json.Unmarshal(msg, &req); err != nil {
		return s.errorResponse(nil, CodeParseError, "Parse error")
	}

	log.Server("Handling method: %s", req.Method)

	// Route to appropriate handler via router
	result, rpcErr := s.router.Route(req)

	// Notifications don't get responses
	if req.ID == nil {
		return nil, nil
	}

	if rpcErr != nil {
		return s.errorResponse(req.ID, rpcErr.Code, rpcErr.Message)
	}

	resp := Response{
		JSONRPC: "2.0",
		ID:      req.ID,
		Result:  result,
	}
	return json.Marshal(resp)
}

// errorResponse creates an error response.
func (s *Server) errorResponse(id any, code int, message string) ([]byte, error) {
	resp := Response{
		JSONRPC: "2.0",
		ID:      id,
		Error: &Error{
			Code:    code,
			Message: message,
		},
	}
	return json.Marshal(resp)
}