- 编辑器:多标签、语法高亮、gopls 全套(补全/诊断/跳转/重命名/代码动作/内联提示/签名大纲) - 调试:Delve DAP(断点/条件断点/变量树/表达式求值/goroutine 列表) - 测试:结果树、覆盖率行着色、失败跳源码、-run 精确运行、行号可跑标记 - Git:状态着色、选择性暂存提交、pull/push、历史并排对比 - 本地历史 + 自动快照 + 崩溃恢复、会话/光标恢复 - 全局搜索替换(预览+确认,GBK 安全)、多终端、gopls 崩溃自愈 - 设计文档与验证记录见 docs/plans/
480 lines
13 KiB
Go
480 lines
13 KiB
Go
package lsp
|
||
|
||
import (
|
||
"bufio"
|
||
"context"
|
||
"encoding/json"
|
||
"errors"
|
||
"fmt"
|
||
"os"
|
||
"os/exec"
|
||
"strings"
|
||
"time"
|
||
)
|
||
|
||
// Options 配置一个 LSP 客户端。
|
||
type Options struct {
|
||
// Root 是工作区目录,gopls 以此为根。
|
||
Root string
|
||
// Logf 接收诊断日志,可为 nil。
|
||
Logf func(string, ...any)
|
||
// OnDiagnostics 在收到诊断通知时调用,来自 gopls 的读协程。
|
||
OnDiagnostics func(uri string, version int, ds []Diagnostic)
|
||
// OnExit 在 gopls 进程退出时调用(手动 Close 也会触发,调用方要自己
|
||
// 区分是意外崩溃还是主动关闭)。来自 wait 协程,不要在里面做重活。
|
||
OnExit func()
|
||
// Command 是语言服务器命令,默认 "gopls"。
|
||
Command string
|
||
}
|
||
|
||
// Client 是一个 gopls 连接。
|
||
type Client struct {
|
||
conn *conn
|
||
cmd *exec.Cmd
|
||
root string
|
||
logf func(string, ...any)
|
||
waitDone chan struct{}
|
||
}
|
||
|
||
// Start 拉起语言服务器并完成初始化握手。
|
||
func Start(ctx context.Context, opts Options) (*Client, error) {
|
||
bin := opts.Command
|
||
if bin == "" {
|
||
bin = "gopls"
|
||
}
|
||
logf := opts.Logf
|
||
if logf == nil {
|
||
logf = func(string, ...any) {}
|
||
}
|
||
path, err := exec.LookPath(bin)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("找不到 %s,请先执行:go install golang.org/x/tools/gopls@latest", bin)
|
||
}
|
||
|
||
cmd := exec.Command(path)
|
||
cmd.Dir = opts.Root
|
||
cmd.SysProcAttr = procAttr()
|
||
|
||
stdin, err := cmd.StdinPipe()
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
stdout, err := cmd.StdoutPipe()
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
stderr, err := cmd.StderrPipe()
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if err := cmd.Start(); err != nil {
|
||
return nil, fmt.Errorf("启动 %s 失败:%w", bin, err)
|
||
}
|
||
|
||
c := &Client{cmd: cmd, root: opts.Root, logf: logf, waitDone: make(chan struct{})}
|
||
c.conn = newConn(stdin, stdout, logf)
|
||
c.conn.onNotify = func(method string, params json.RawMessage) {
|
||
switch method {
|
||
case "textDocument/publishDiagnostics":
|
||
var p PublishDiagnosticsParams
|
||
if err := json.Unmarshal(params, &p); err != nil {
|
||
return
|
||
}
|
||
if opts.OnDiagnostics != nil {
|
||
opts.OnDiagnostics(p.URI, p.Version, p.Diagnostics)
|
||
}
|
||
case "window/showMessage":
|
||
var m struct {
|
||
Type int `json:"type"`
|
||
Message string `json:"message"`
|
||
}
|
||
if json.Unmarshal(params, &m) == nil {
|
||
logf("gopls 提示:%s", m.Message)
|
||
}
|
||
}
|
||
}
|
||
|
||
go func() {
|
||
sc := bufio.NewScanner(stderr)
|
||
sc.Buffer(make([]byte, 0, 64*1024), 1024*1024)
|
||
for sc.Scan() {
|
||
logf("gopls: %s", sc.Text())
|
||
}
|
||
}()
|
||
go func() {
|
||
if err := cmd.Wait(); err != nil {
|
||
logf("gopls 退出:%v", err)
|
||
}
|
||
close(c.waitDone)
|
||
if opts.OnExit != nil {
|
||
opts.OnExit()
|
||
}
|
||
}()
|
||
|
||
initCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||
defer cancel()
|
||
params := InitializeParams{
|
||
ProcessID: os.Getpid(),
|
||
ClientInfo: &ClientInfo{Name: "MyGoland", Version: "0.1.0"},
|
||
RootURI: PathToURI(opts.Root),
|
||
RootPath: opts.Root,
|
||
WorkspaceFolders: []WorkspaceFolder{{
|
||
URI: PathToURI(opts.Root),
|
||
Name: baseName(opts.Root),
|
||
}},
|
||
Capabilities: defaultCapabilities(),
|
||
}
|
||
var res InitializeResult
|
||
if err := c.conn.call(initCtx, "initialize", params, &res); err != nil {
|
||
c.Close()
|
||
return nil, fmt.Errorf("初始化失败:%w", err)
|
||
}
|
||
if res.ServerInfo != nil {
|
||
logf("语言服务器:%s %s", res.ServerInfo.Name, shorten(res.ServerInfo.Version, 60))
|
||
}
|
||
if err := c.conn.notify("initialized", struct{}{}); err != nil {
|
||
c.Close()
|
||
return nil, err
|
||
}
|
||
return c, nil
|
||
}
|
||
|
||
// baseName 返回路径的最后一段,跨平台处理分隔符。
|
||
func baseName(p string) string {
|
||
p = strings.TrimRight(p, `/\`)
|
||
if i := strings.LastIndexAny(p, `/\`); i >= 0 {
|
||
return p[i+1:]
|
||
}
|
||
return p
|
||
}
|
||
|
||
// shorten 截断过长的字符串,gopls 的版本字段可能是一整段构建信息。
|
||
func shorten(s string, n int) string {
|
||
if len(s) <= n {
|
||
return s
|
||
}
|
||
return s[:n] + "…"
|
||
}
|
||
|
||
// DidOpen 通知文档已打开。
|
||
func (c *Client) DidOpen(uri, languageID string, version int, text string) error {
|
||
return c.conn.notify("textDocument/didOpen", map[string]any{
|
||
"textDocument": TextDocumentItem{URI: uri, LanguageID: languageID, Version: version, Text: text},
|
||
})
|
||
}
|
||
|
||
// DidChange 通知文档的增量修改。
|
||
func (c *Client) DidChange(uri string, version int, changes []ContentChange) error {
|
||
return c.conn.notify("textDocument/didChange", map[string]any{
|
||
"textDocument": VersionedTextDocumentIdentifier{URI: uri, Version: version},
|
||
"contentChanges": changes,
|
||
})
|
||
}
|
||
|
||
// DidSave 通知文档已保存。
|
||
func (c *Client) DidSave(uri, text string) error {
|
||
params := map[string]any{"textDocument": TextDocumentIdentifier{URI: uri}}
|
||
if text != "" {
|
||
params["text"] = text
|
||
}
|
||
return c.conn.notify("textDocument/didSave", params)
|
||
}
|
||
|
||
// DidClose 通知文档已关闭。
|
||
func (c *Client) DidClose(uri string) error {
|
||
return c.conn.notify("textDocument/didClose", map[string]any{
|
||
"textDocument": TextDocumentIdentifier{URI: uri},
|
||
})
|
||
}
|
||
|
||
// Completion 请求补全。
|
||
func (c *Client) Completion(ctx context.Context, uri string, pos Position) ([]CompletionItem, error) {
|
||
var raw json.RawMessage
|
||
err := c.conn.call(ctx, "textDocument/completion", map[string]any{
|
||
"textDocument": TextDocumentIdentifier{URI: uri},
|
||
"position": pos,
|
||
}, &raw)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
return decodeCompletions(raw), nil
|
||
}
|
||
|
||
// decodeCompletions 兼容数组与 CompletionList 两种返回。
|
||
func decodeCompletions(raw json.RawMessage) []CompletionItem {
|
||
s := strings.TrimSpace(string(raw))
|
||
if s == "" || s == "null" {
|
||
return nil
|
||
}
|
||
if strings.HasPrefix(s, "[") {
|
||
var arr []CompletionItem
|
||
_ = json.Unmarshal(raw, &arr)
|
||
return arr
|
||
}
|
||
var list CompletionList
|
||
if err := json.Unmarshal(raw, &list); err == nil {
|
||
return list.Items
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// Hover 请求悬停信息。
|
||
func (c *Client) Hover(ctx context.Context, uri string, pos Position) (*Hover, error) {
|
||
var raw json.RawMessage
|
||
err := c.conn.call(ctx, "textDocument/hover", map[string]any{
|
||
"textDocument": TextDocumentIdentifier{URI: uri},
|
||
"position": pos,
|
||
}, &raw)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if len(raw) == 0 || string(raw) == "null" {
|
||
return nil, nil
|
||
}
|
||
var h Hover
|
||
if err := json.Unmarshal(raw, &h); err != nil {
|
||
return nil, err
|
||
}
|
||
return &h, nil
|
||
}
|
||
|
||
// Definition 请求定义位置。
|
||
func (c *Client) Definition(ctx context.Context, uri string, pos Position) ([]Location, error) {
|
||
var raw json.RawMessage
|
||
err := c.conn.call(ctx, "textDocument/definition", map[string]any{
|
||
"textDocument": TextDocumentIdentifier{URI: uri},
|
||
"position": pos,
|
||
}, &raw)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
return decodeLocations(raw), nil
|
||
}
|
||
|
||
// decodeLocations 兼容 Location、Location[] 与 LocationLink[]。
|
||
func decodeLocations(raw json.RawMessage) []Location {
|
||
s := strings.TrimSpace(string(raw))
|
||
if s == "" || s == "null" {
|
||
return nil
|
||
}
|
||
if strings.HasPrefix(s, "[") {
|
||
var arr []json.RawMessage
|
||
if err := json.Unmarshal(raw, &arr); err != nil {
|
||
return nil
|
||
}
|
||
out := make([]Location, 0, len(arr))
|
||
for _, x := range arr {
|
||
if loc, ok := decodeLocation(x); ok {
|
||
out = append(out, loc)
|
||
}
|
||
}
|
||
return out
|
||
}
|
||
if loc, ok := decodeLocation(raw); ok {
|
||
return []Location{loc}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
func decodeLocation(raw json.RawMessage) (Location, bool) {
|
||
var loc Location
|
||
if err := json.Unmarshal(raw, &loc); err == nil && loc.URI != "" {
|
||
return loc, true
|
||
}
|
||
var link struct {
|
||
TargetURI string `json:"targetUri"`
|
||
TargetRange Range `json:"targetRange"`
|
||
TargetSelectionRange Range `json:"targetSelectionRange"`
|
||
}
|
||
if err := json.Unmarshal(raw, &link); err == nil && link.TargetURI != "" {
|
||
r := link.TargetSelectionRange
|
||
if r == (Range{}) {
|
||
r = link.TargetRange
|
||
}
|
||
return Location{URI: link.TargetURI, Range: r}, true
|
||
}
|
||
return Location{}, false
|
||
}
|
||
|
||
// DocumentSymbol 请求文件的符号树。
|
||
//
|
||
// 服务端可能返回层级式的 DocumentSymbol,也可能返回平铺的 SymbolInformation,
|
||
// 后者会被转成同一形状,位置取 location.range。
|
||
func (c *Client) DocumentSymbol(ctx context.Context, uri string) ([]DocumentSymbol, error) {
|
||
var raw json.RawMessage
|
||
err := c.conn.call(ctx, "textDocument/documentSymbol", map[string]any{
|
||
"textDocument": TextDocumentIdentifier{URI: uri},
|
||
}, &raw)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
return decodeSymbols(raw), nil
|
||
}
|
||
|
||
// decodeSymbols 兼容 DocumentSymbol[] 与 SymbolInformation[]。
|
||
func decodeSymbols(raw json.RawMessage) []DocumentSymbol {
|
||
s := strings.TrimSpace(string(raw))
|
||
if s == "" || s == "null" {
|
||
return nil
|
||
}
|
||
var syms []DocumentSymbol
|
||
if err := json.Unmarshal(raw, &syms); err == nil && len(syms) > 0 && syms[0].Name != "" {
|
||
return syms
|
||
}
|
||
var infos []struct {
|
||
Name string `json:"name"`
|
||
Kind int `json:"kind"`
|
||
Location struct {
|
||
Range Range `json:"range"`
|
||
} `json:"location"`
|
||
}
|
||
if err := json.Unmarshal(raw, &infos); err != nil {
|
||
return nil
|
||
}
|
||
out := make([]DocumentSymbol, 0, len(infos))
|
||
for _, in := range infos {
|
||
out = append(out, DocumentSymbol{
|
||
Name: in.Name,
|
||
Kind: in.Kind,
|
||
Range: in.Location.Range,
|
||
SelectionRange: in.Location.Range,
|
||
})
|
||
}
|
||
return out
|
||
}
|
||
|
||
// References 请求符号的引用位置。
|
||
func (c *Client) References(ctx context.Context, uri string, pos Position, includeDecl bool) ([]Location, error) {
|
||
var locs []Location
|
||
err := c.conn.call(ctx, "textDocument/references", map[string]any{
|
||
"textDocument": TextDocumentIdentifier{URI: uri},
|
||
"position": pos,
|
||
"context": map[string]any{"includeDeclaration": includeDecl},
|
||
}, &locs)
|
||
return locs, err
|
||
}
|
||
|
||
// Rename 请求把符号改名为 newName,返回跨文件的修改。
|
||
func (c *Client) Rename(ctx context.Context, uri string, pos Position, newName string) (WorkspaceEdit, error) {
|
||
var we WorkspaceEdit
|
||
err := c.conn.call(ctx, "textDocument/rename", map[string]any{
|
||
"textDocument": TextDocumentIdentifier{URI: uri},
|
||
"position": pos,
|
||
"newName": newName,
|
||
}, &we)
|
||
return we, err
|
||
}
|
||
|
||
// CodeActions 请求指定范围上的代码动作(快速修复、整理 import 等)。
|
||
func (c *Client) CodeActions(ctx context.Context, uri string, r Range, diags []Diagnostic) ([]CodeAction, error) {
|
||
var out []CodeAction
|
||
err := c.conn.call(ctx, "textDocument/codeAction", map[string]any{
|
||
"textDocument": TextDocumentIdentifier{URI: uri},
|
||
"range": r,
|
||
"context": map[string]any{"diagnostics": diags},
|
||
}, &out)
|
||
return out, err
|
||
}
|
||
|
||
// OrganizeImports 请求整理 import,返回能直接落到缓冲区的修改。
|
||
//
|
||
// gopls 把这个能力挂在 source.organizeImports 代码动作上;请求时用 only
|
||
// 过滤、不带诊断——补缺/删无用 import 不依赖某一条诊断。range 对 source
|
||
// 动作无意义,给零值即可。
|
||
//
|
||
// 只收集本文件的改动:保存场景不会碰别的文件,遇到跨文件的 edit 直接忽略。
|
||
func (c *Client) OrganizeImports(ctx context.Context, uri string) ([]TextEdit, error) {
|
||
var acts []CodeAction
|
||
err := c.conn.call(ctx, "textDocument/codeAction", map[string]any{
|
||
"textDocument": TextDocumentIdentifier{URI: uri},
|
||
"range": Range{},
|
||
"context": map[string]any{
|
||
"diagnostics": []Diagnostic{},
|
||
"only": []string{"source.organizeImports"},
|
||
},
|
||
}, &acts)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
var edits []TextEdit
|
||
for _, act := range acts {
|
||
if !strings.HasPrefix(act.Kind, "source.organizeImports") {
|
||
continue
|
||
}
|
||
if act.Edit == nil {
|
||
continue
|
||
}
|
||
edits = append(edits, act.Edit.ByFile()[uri]...)
|
||
}
|
||
return edits, nil
|
||
}
|
||
|
||
// ExecuteCommand 让服务端执行一条命令。
|
||
func (c *Client) ExecuteCommand(ctx context.Context, cmd Command) error {
|
||
return c.conn.call(ctx, "workspace/executeCommand", map[string]any{
|
||
"command": cmd.Command,
|
||
"arguments": cmd.Arguments,
|
||
}, nil)
|
||
}
|
||
|
||
// Format 请求整篇格式化。
|
||
func (c *Client) Format(ctx context.Context, uri string, opts FormattingOptions) ([]TextEdit, error) {
|
||
var edits []TextEdit
|
||
err := c.conn.call(ctx, "textDocument/formatting", map[string]any{
|
||
"textDocument": TextDocumentIdentifier{URI: uri},
|
||
"options": opts,
|
||
}, &edits)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
return edits, nil
|
||
}
|
||
|
||
// Close 关闭语言服务器。
|
||
func (c *Client) Close() error {
|
||
if c == nil || c.conn == nil {
|
||
return nil
|
||
}
|
||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||
defer cancel()
|
||
_ = c.conn.call(ctx, "shutdown", nil, nil)
|
||
_ = c.conn.notify("exit", nil)
|
||
c.conn.close()
|
||
if c.cmd != nil && c.cmd.Process != nil {
|
||
select {
|
||
case <-c.waitDone:
|
||
case <-time.After(2 * time.Second):
|
||
_ = c.cmd.Process.Kill()
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// ErrClosed 表示连接已关闭。
|
||
var ErrClosed = errors.New("lsp: 连接已关闭")
|
||
|
||
// InlayHints 请求一段范围内的内联提示。
|
||
func (c *Client) InlayHints(ctx context.Context, uri string, rng Range) ([]InlayHint, error) {
|
||
var out []InlayHint
|
||
err := c.conn.call(ctx, "textDocument/inlayHint", map[string]any{
|
||
"textDocument": TextDocumentIdentifier{URI: uri},
|
||
"range": rng,
|
||
}, &out)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
return out, nil
|
||
}
|
||
|
||
// WorkspaceSymbols 在整个工作区里按名字找符号。
|
||
func (c *Client) WorkspaceSymbols(ctx context.Context, query string) ([]SymbolInformation, error) {
|
||
var out []SymbolInformation
|
||
err := c.conn.call(ctx, "workspace/symbol", map[string]any{
|
||
"query": query,
|
||
}, &out)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
return out, nil
|
||
}
|