第 10 项。原报告说「代码动作只取光标行 range,所以生成测试/实现接口取 不到」——实测(gopls v0.23)推翻了一半,真问题在别处: 1. 选区被忽略。原来一律传整行,用户选中 foo() 按 Alt+Enter,gopls 收到 整行,只能给 refactor.extract.function;refactor.extract.variable 和 refactor.inline.call **只在范围正好圈住表达式时才返回**。 2. 噪音淹没有效动作。一次请求 6–9 项,其中 5 项是 gopls.doc(开 pkg.go.dev)、assembly、free_symbols、client_open_url、gc_details。 「Extract variable」被挤到第七位。 而「生成测试」(source.addTest)本来就有;「零宽位置会丢快速修复」也是 错的——gopls 会把位置摊到所属节点,行首零宽照样拿得到 quickfix。 改法: - 有选区用选区,没有才用整行; - 发两次请求:光标/选区(带同行诊断)+ 整文件且 only=refactor.rewrite (refactor.rewrite.addTags 这类只有范围覆盖到才出现); - 按**命令名**过滤那 5 个浏览命令(不是标题,标题会随版本变),只黑 已知噪音、其余放行,gopls 加新能力不会被误杀; - 同标题取第一次出现的那份(与用户眼前范围一致),再按 IsPreferred → quickfix → refactor → source 稳定排序; - 全是浏览命令时提示「这里有 N 项,但都只是打开文档/汇编之类的浏览 命令,已隐藏」,不再假装什么都没发生。 验证分三层: - 13 条 app 层单测:范围(含 UTF-16 中文列)、诊断相交、噪音判定、 合并去重首见优先、排序稳定性; - 3 条真 gopls 回归:选区给 extract.variable/inline.call、整行不给、 整文件 only=refactor.rewrite 给 addTags、缺 import 的 quickfix 依赖 诊断且对零宽位置也宽容; - 1 条 app 层全管线集成:选中表达式 → 必须出现 extract.variable 且不得 混入浏览命令。 真实窗口截图 docs/code-action-panel.png 只剩两项,5 个浏览命令没露头。 顺带把 Client.CodeActions 拆出 CodeActionsOnly(支持 context.only), queryCodeActions 从 goroutine 里拆出来以支持集成测试;actionKindLabel 给 source.addTest/organizeImports/fixAll 单列文案,并给 IsPreferred 加 「推荐 ·」前缀。
497 lines
14 KiB
Go
497 lines
14 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) {
|
||
return c.CodeActionsOnly(ctx, uri, r, diags, nil)
|
||
}
|
||
|
||
// CodeActionsOnly 同 CodeActions,但可以按 kind 过滤(LSP 的 context.only)。
|
||
//
|
||
// only 为空表示不过滤。gopls 支持 "quickfix"、"refactor"、"refactor.rewrite"、
|
||
// "source" 这些前缀;用它最实际的好处是「只问整文件级的重构」时不会顺带
|
||
// 把一堆焦点相关的动作再拉一遍。
|
||
func (c *Client) CodeActionsOnly(ctx context.Context, uri string, r Range, diags []Diagnostic, only []string) ([]CodeAction, error) {
|
||
if diags == nil {
|
||
// JSON 里 null 和 [] 对某些服务端不等价,统一给空数组。
|
||
diags = []Diagnostic{}
|
||
}
|
||
cctx := map[string]any{"diagnostics": diags}
|
||
if len(only) > 0 {
|
||
cctx["only"] = only
|
||
}
|
||
var out []CodeAction
|
||
err := c.conn.call(ctx, "textDocument/codeAction", map[string]any{
|
||
"textDocument": TextDocumentIdentifier{URI: uri},
|
||
"range": r,
|
||
"context": cctx,
|
||
}, &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
|
||
}
|