-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathgopls.go
254 lines (224 loc) · 6.12 KB
/
gopls.go
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
package gore
import (
"cmp"
"context"
"io"
"os/exec"
"path/filepath"
"strings"
"go.lsp.dev/jsonrpc2"
"go.lsp.dev/protocol"
)
type goplsCompleter struct {
conn jsonrpc2.Conn
dir string
path string
source string
autoImport bool
opened []fileSource
}
type fileSource struct {
path, source string
}
type rw struct {
io.ReadCloser
io.WriteCloser
}
func (rw rw) Close() error {
return cmp.Or(rw.ReadCloser.Close(), rw.WriteCloser.Close())
}
func (c *goplsCompleter) init(dir, path, source string, autoImport bool) error {
ctx := context.Background()
cmd := exec.CommandContext(ctx, "gopls")
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
stdin, err := cmd.StdinPipe()
if err != nil {
return err
}
if err := cmd.Start(); err != nil {
return err
}
c.conn = jsonrpc2.NewConn(jsonrpc2.NewStream(rw{stdout, stdin}))
c.conn.Go(ctx, func(ctx context.Context,
rep jsonrpc2.Replier, req jsonrpc2.Request) error {
return nil
})
rootURI := protocol.DocumentURI("file://" + filepath.ToSlash(dir))
initializeParams := protocol.InitializeParams{
RootURI: rootURI,
Capabilities: protocol.ClientCapabilities{},
InitializationOptions: map[string]any{"completeUnimported": autoImport},
}
var initializeResponse protocol.InitializeResult
if _, err := c.conn.Call(ctx, protocol.MethodInitialize,
initializeParams, &initializeResponse); err != nil {
return err
}
debugf("initializeResponse: %v", initializeResponse)
if err := protocol.Call(ctx, c.conn, protocol.MethodInitialized, nil, nil); err != nil {
return err
}
if err := c.open(path, source); err != nil {
return err
}
c.dir, c.path, c.source, c.autoImport = dir, path, source, autoImport
c.opened = nil // reset opened files (do not include the main file)
return nil
}
func (c *goplsCompleter) open(path, source string) error {
ctx := context.Background()
debugf("open: %q: %q", path, source)
fileURI := protocol.DocumentURI("file://" + filepath.ToSlash(path))
didOpenTextDocumentParams := protocol.DidOpenTextDocumentParams{
TextDocument: protocol.TextDocumentItem{
URI: fileURI,
Text: source,
},
}
err := protocol.Call(ctx, c.conn, protocol.MethodTextDocumentDidOpen,
didOpenTextDocumentParams, nil)
if err != nil {
return err
}
for i := range c.opened {
if c.opened[i].path == path {
c.opened[i].source = source
return nil
}
}
c.opened = append(c.opened, fileSource{path, source})
return nil
}
func (c *goplsCompleter) reconnect() error {
opened := c.opened
if err := c.init(c.dir, c.path, c.source, c.autoImport); err != nil {
return err
}
for _, f := range opened {
if err := c.open(f.path, f.source); err != nil {
return err
}
}
return nil
}
func (c *goplsCompleter) update(source string) error {
ctx := context.Background()
select {
case <-c.conn.Done():
if err := c.reconnect(); err != nil {
return err
}
default:
}
for c.source != source {
i, j, k := diffString(c.source, source)
debugf("update: %q", c.source[i:j])
debugf(" --> %q", source[i:k])
fileURI := protocol.DocumentURI("file://" + filepath.ToSlash(c.path))
didChangeTextDocumentParams := protocol.DidChangeTextDocumentParams{
TextDocument: protocol.VersionedTextDocumentIdentifier{
TextDocumentIdentifier: protocol.TextDocumentIdentifier{
URI: fileURI,
},
},
ContentChanges: []protocol.TextDocumentContentChangeEvent{
{
Range: protocol.Range{
Start: getPos(c.source, i),
End: getPos(c.source, j),
},
Text: source[i:k],
},
},
}
if err := protocol.Call(ctx, c.conn, protocol.MethodTextDocumentDidChange,
didChangeTextDocumentParams, nil); err != nil {
return err
}
c.source = source[:k] + c.source[j:]
}
return nil
}
func (c *goplsCompleter) complete(source string, pos int, exprMode bool) ([]string, int, error) {
ctx := context.Background()
if err := c.update(source); err != nil {
return nil, 0, err
}
fileURI := protocol.DocumentURI("file://" + filepath.ToSlash(c.path))
completionParams := protocol.CompletionParams{
TextDocumentPositionParams: protocol.TextDocumentPositionParams{
TextDocument: protocol.TextDocumentIdentifier{URI: fileURI},
Position: getPos(source, pos),
},
Context: &protocol.CompletionContext{
TriggerKind: protocol.CompletionTriggerKindInvoked,
},
}
var completionList protocol.CompletionList
if err := protocol.Call(ctx, c.conn, protocol.MethodTextDocumentCompletion,
completionParams, &completionList); err != nil {
return nil, 0, err
}
candidates := make([]string, 0, len(completionList.Items))
for _, item := range completionList.Items {
label := item.Label
if item.Kind == protocol.CompletionItemKindKeyword ||
item.Kind == protocol.CompletionItemKindFunction && label == printerName ||
item.Kind == protocol.CompletionItemKindModule && label == "pp" ||
strings.HasPrefix(label, "pp.") {
continue
}
if exprMode &&
(item.Kind == protocol.CompletionItemKindMethod ||
item.Kind == protocol.CompletionItemKindFunction) {
label += "("
}
candidates = append(candidates, label)
pos = fromPos(source, item.TextEdit.Range.Start)
}
return candidates, pos, nil
}
func (c *goplsCompleter) close() error {
if err := c.conn.Close(); err != nil {
return err
}
<-c.conn.Done()
return nil
}
func diffString(s, t string) (int, int, int) {
var i, j int
for s != "" {
var u string
if l := strings.IndexAny(s, "{ ;\n"); l >= 0 {
u, s = s[:l+1], s[l+1:]
} else {
u, s = s, ""
}
if l := strings.Index(t, u); l > 0 && len(u) > 2 {
return i, j, i + l
} else if l == 0 {
if i != j {
return i, j, i
}
i += len(u)
j = i
t = t[len(u):]
} else {
j += len(u)
}
}
return i, j, i + len(t)
}
func getPos(source string, pos int) protocol.Position {
line := strings.Count(source[:pos], "\n")
char := pos - strings.LastIndex(source[:pos], "\n") - 1
return protocol.Position{Line: uint32(line), Character: uint32(char)}
}
func fromPos(source string, pos protocol.Position) int {
lines := strings.SplitN(source, "\n", int(pos.Line)+1)
return len(strings.Join(lines[:pos.Line], "")) +
int(pos.Line) + int(pos.Character)
}