package lsp import ( "bufio" "context" "encoding/json" "errors" "fmt" "io" "strconv" "strings" "sync" ) // rpcError 是 JSON-RPC 的 error 对象。 type rpcError struct { Code int `json:"code"` Message string `json:"message"` } func (e *rpcError) Error() string { return fmt.Sprintf("lsp: %d %s", e.Code, e.Message) } // message 是 JSON-RPC 报文,请求、响应、通知共用。 type message struct { JSONRPC string `json:"jsonrpc"` ID *int64 `json:"id,omitempty"` Method string `json:"method,omitempty"` Params json.RawMessage `json:"params,omitempty"` Result json.RawMessage `json:"result,omitempty"` Error *rpcError `json:"error,omitempty"` } // conn 负责 Content-Length 分帧与请求/响应配对。 type conn struct { w io.WriteCloser bw *bufio.Writer r *bufio.Reader mu sync.Mutex nextID int64 pending map[int64]chan message writeCh chan []byte done chan struct{} once sync.Once onNotify func(method string, params json.RawMessage) logf func(string, ...any) } func newConn(w io.WriteCloser, r io.Reader, logf func(string, ...any)) *conn { if logf == nil { logf = func(string, ...any) {} } c := &conn{ w: w, bw: bufio.NewWriter(w), r: bufio.NewReader(r), pending: map[int64]chan message{}, writeCh: make(chan []byte, 512), done: make(chan struct{}), logf: logf, } go c.writeLoop() go c.readLoop() return c } // readFrame 读出一条报文,跳过头部。 func readFrame(r *bufio.Reader) ([]byte, error) { length := -1 for { line, err := r.ReadString('\n') if err != nil { return nil, err } line = strings.TrimRight(line, "\r\n") if line == "" { break } if k, v, ok := strings.Cut(line, ":"); ok && strings.EqualFold(strings.TrimSpace(k), "Content-Length") { n, err := strconv.Atoi(strings.TrimSpace(v)) if err != nil { return nil, fmt.Errorf("lsp: 非法的 Content-Length %q", v) } length = n } } if length < 0 { return nil, errors.New("lsp: 缺少 Content-Length") } buf := make([]byte, length) if _, err := io.ReadFull(r, buf); err != nil { return nil, err } return buf, nil } func (c *conn) writeLoop() { for { select { case body := <-c.writeCh: if _, err := fmt.Fprintf(c.bw, "Content-Length: %d\r\n\r\n", len(body)); err != nil { c.close() return } if _, err := c.bw.Write(body); err != nil { c.close() return } if err := c.bw.Flush(); err != nil { c.close() return } case <-c.done: return } } } func (c *conn) readLoop() { defer c.close() for { body, err := readFrame(c.r) if err != nil { return } var m message if err := json.Unmarshal(body, &m); err != nil { c.logf("lsp: 无法解析报文: %v", err) continue } switch { case m.Method == "" && m.ID != nil: c.mu.Lock() ch := c.pending[*m.ID] c.mu.Unlock() if ch != nil { select { case ch <- m: default: } } case m.Method != "" && m.ID != nil: go c.answer(m) case m.Method != "": if c.onNotify != nil { c.onNotify(m.Method, m.Params) } } } } // answer 回应服务端发来的请求,主要是 gopls 的配置询问。 func (c *conn) answer(m message) { var result any switch m.Method { case "workspace/configuration": var p struct { Items []json.RawMessage `json:"items"` } _ = json.Unmarshal(m.Params, &p) // gopls 会问客户端要 "gopls" 这一节的设置;回 null 等于「什么都不配」, // 而它默认不给内联提示,所以这里显式打开。 items := make([]any, len(p.Items)) for i := range items { items[i] = goplsSettings() } result = items case "workspace/workspaceFolders": result = []WorkspaceFolder{} default: result = nil } b, err := json.Marshal(result) if err != nil { b = []byte("null") } msg := message{JSONRPC: "2.0", ID: m.ID, Result: b} body, err := json.Marshal(msg) if err != nil { return } select { case c.writeCh <- body: case <-c.done: } } // send 把报文排进写队列,不阻塞调用方。 func (c *conn) send(m message) error { m.JSONRPC = "2.0" body, err := json.Marshal(m) if err != nil { return err } select { case c.writeCh <- body: return nil case <-c.done: return errors.New("lsp: 连接已关闭") } } // notify 发送通知。 func (c *conn) notify(method string, params any) error { raw, err := json.Marshal(params) if err != nil { return err } return c.send(message{Method: method, Params: raw}) } // call 发送请求并等待响应。 func (c *conn) call(ctx context.Context, method string, params any, result any) error { raw, err := json.Marshal(params) if err != nil { return err } c.mu.Lock() c.nextID++ id := c.nextID ch := make(chan message, 1) c.pending[id] = ch c.mu.Unlock() defer func() { c.mu.Lock() delete(c.pending, id) c.mu.Unlock() }() if err := c.send(message{ID: &id, Method: method, Params: raw}); err != nil { return err } select { case m := <-ch: if m.Error != nil { return m.Error } if result != nil && len(m.Result) > 0 { return json.Unmarshal(m.Result, result) } return nil case <-ctx.Done(): return ctx.Err() case <-c.done: return errors.New("lsp: 连接已关闭") } } // close 关闭连接,可重复调用。 func (c *conn) close() { c.once.Do(func() { close(c.done) _ = c.w.Close() }) } // goplsSettings 是给 gopls 的默认设置。 // // 只开「读代码有帮助」的提示,常量值/未用变量这类噪音保持关闭。 // 注意只写 hints:加 ui 这类不认识的节点会被 gopls 报「unexpected setting」。 func goplsSettings() map[string]any { hints := map[string]any{ "assignVariableTypes": true, "compositeLiteralFields": true, "compositeLiteralTypes": true, "constantValues": false, "functionTypeParameters": true, "parameterNames": true, "rangeVariableTypes": true, "unusedVariableNames": false, } return map[string]any{"hints": hints} }