Debian Codegraph @

gopls/internal/protocol/generate/main.go

raw symbols SCIP
1 // Copyright 2022 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // The generate command generates Go declarations from VSCode's
6 // description of the Language Server Protocol.
7 //
8 // To run it, type 'go generate' in the parent (protocol) directory.
9 package main
10
11 // see https://github.com/golang/go/issues/61217 for discussion of an issue
12
13 import (
14 "bytes"
15 "encoding/json"
16 "flag"
17 "fmt"
18 "go/format"
19 "log"
20 "os"
21 "os/exec"
22 "path/filepath"
23 "slices"
24 "strings"
25 )
26
27 const vscodeRepo = "https://github.com/microsoft/vscode-languageserver-node"
28
29 // lspGitRef names a branch or tag in vscodeRepo.
30 // It implicitly determines the protocol version of the LSP used by gopls.
31 // For example, tag release/protocol/3.17.3 of the repo defines
32 // protocol version 3.17.0 (as declared by the metaData.version field).
33 // (Point releases are reflected in the git tag version even when they are cosmetic
34 // and don't change the protocol.)
35 var lspGitRef = "release/protocol/3.17.6-next.14"
36
37 var (
38 repodir = flag.String("d", "", "directory containing clone of "+vscodeRepo)
39 outputdir = flag.String("o", ".", "output directory")
40 // PJW: not for real code
41 lineNumbers = flag.Bool("l", false, "add line numbers to generated output")
42 )
43
44 func main() {
45 log.SetFlags(log.Lshortfile) // log file name and line number, not time
46 flag.Parse()
47
48 processinline()
49 }
50
51 func processinline() {
52 // A local repository may be specified during debugging.
53 // The default behavior is to download the canonical version.
54 if *repodir == "" {
55 tmpdir, err := os.MkdirTemp("", "")
56 if err != nil {
57 log.Fatal(err)
58 }
59 defer os.RemoveAll(tmpdir) // ignore error
60
61 // Clone the repository.
62 cmd := exec.Command("git", "clone", "--quiet", "--depth=1", "-c", "advice.detachedHead=false", vscodeRepo, "--branch="+lspGitRef, "--single-branch", tmpdir)
63 cmd.Stdout = os.Stderr
64 cmd.Stderr = os.Stderr
65 if err := cmd.Run(); err != nil {
66 log.Fatal(err)
67 }
68
69 *repodir = tmpdir
70 } else {
71 lspGitRef = fmt.Sprintf("(not git, local dir %s)", *repodir)
72 }
73
74 model := parse(filepath.Join(*repodir, "protocol/metaModel.json"))
75
76 // Although the LSP specification defines RenameParams as extending
77 // TextDocumentPositionParams, the metaModel.json definition flattens
78 // these properties (likely due to specific comments in the TS definition).
79 // See microsoft/vscode-languageserver-node#1698.
80 //
81 // TODO(hxjiang): delete the patch logic after releasing lsp 3.18.
82 for _, s := range model.Structures {
83 if s.Name == "RenameParams" {
84 s.Properties = slices.DeleteFunc(s.Properties, func(t NameType) bool {
85 return t.Name == "position" || t.Name == "textDocument"
86 })
87 if !slices.ContainsFunc(s.Extends, func(t *Type) bool {
88 return t.Kind == "reference" && t.Name == "TextDocumentPositionParams"
89 }) {
90 s.Extends = append(s.Extends, &Type{
91 Kind: "reference",
92 Name: "TextDocumentPositionParams",
93 })
94 }
95 }
96 }
97
98 // Add a client to server LSP method "command/resolve" for interactive
99 // refactoring. The method's param and result are both "ExecuteCommandParams".
100 // The types are only accessible from the "workspace/executeCommand" request.
101 //
102 // See microsoft/language-server-protocol#1164.
103 for _, req := range model.Requests {
104 if req.Method == "workspace/executeCommand" {
105 model.Requests = append(model.Requests, &Request{
106 Method: "command/resolve",
107 ErrorData: req.ErrorData,
108 Direction: "clientToServer",
109 Params: req.Params,
110 Result: req.Params,
111 })
112 break
113 }
114 }
115
116 model.Requests = append(model.Requests, &Request{
117 Method: "interactive/listEnum",
118 Direction: "clientToServer",
119 Params: &Type{
120 Kind: "reference",
121 Name: "InteractiveListEnumParams",
122 },
123 Result: &Type{
124 Kind: "array",
125 Element: &Type{
126 Kind: "reference",
127 Name: "FormEnumEntry",
128 },
129 },
130 })
131
132 findTypeNames(model)
133 generateOutput(model)
134
135 fileHdr = fileHeader(model)
136
137 // write the files
138 writeclient()
139 writeserver()
140 writeprotocol()
141 writejsons()
142
143 checkTables()
144 }
145
146 // common file header for output files
147 var fileHdr string
148
149 func writeclient() {
150 out := new(bytes.Buffer)
151 fmt.Fprintln(out, fileHdr)
152 out.WriteString(
153 `import (
154 "context"
155 "encoding/json"
156 "fmt"
157
158 "golang.org/x/tools/internal/jsonrpc2"
159 )
160 `)
161 out.WriteString("type Client interface {\n")
162 for _, k := range cdecls.keys() {
163 out.WriteString(cdecls[k])
164 }
165 out.WriteString("}\n\n")
166 out.WriteString(`
167 func clientDispatch(ctx context.Context, client Client, reply jsonrpc2.Replier, r jsonrpc2.Request) (bool, error) {
168 resp, valid, err := ClientDispatchCall(ctx, client, r.Method(), r.Params())
169 if !valid {
170 return false, nil
171 }
172
173 if err != nil {
174 return valid, reply(ctx, nil, err)
175 } else {
176 return valid, reply(ctx, resp, nil)
177 }
178 }
179
180 func ClientDispatchCall(ctx context.Context, client Client, method string, raw json.RawMessage) (resp any, _ bool, err error) {
181 switch method {
182 `)
183 for _, k := range ccases.keys() {
184 out.WriteString(ccases[k])
185 }
186 out.WriteString(("\tdefault:\n\t\treturn nil, false, nil\n\t}\n}\n\n"))
187 for _, k := range cfuncs.keys() {
188 out.WriteString(cfuncs[k])
189 }
190 formatTo("tsclient.go", out.Bytes())
191 }
192
193 func writeserver() {
194 out := new(bytes.Buffer)
195 fmt.Fprintln(out, fileHdr)
196 out.WriteString(
197 `import (
198 "context"
199 "encoding/json"
200 "fmt"
201
202 "golang.org/x/tools/internal/jsonrpc2"
203 )
204 `)
205 out.WriteString("type Server interface {\n")
206 for _, k := range sdecls.keys() {
207 out.WriteString(sdecls[k])
208 }
209 out.WriteString(`
210 }
211 func serverDispatch(ctx context.Context, server Server, reply jsonrpc2.Replier, r jsonrpc2.Request) (bool, error) {
212 resp, valid, err := ServerDispatchCall(ctx, server, r.Method(), r.Params())
213 if !valid {
214 return false, nil
215 }
216
217 if err != nil {
218 return valid, reply(ctx, nil, err)
219 } else {
220 return valid, reply(ctx, resp, nil)
221 }
222 }
223
224 func ServerDispatchCall(ctx context.Context, server Server, method string, raw json.RawMessage) (resp any, _ bool, err error) {
225 switch method {
226 `)
227 for _, k := range scases.keys() {
228 out.WriteString(scases[k])
229 }
230 out.WriteString(("\tdefault:\n\t\treturn nil, false, nil\n\t}\n}\n\n"))
231 for _, k := range sfuncs.keys() {
232 out.WriteString(sfuncs[k])
233 }
234 formatTo("tsserver.go", out.Bytes())
235 }
236
237 func writeprotocol() {
238 out := new(bytes.Buffer)
239 fmt.Fprintln(out, fileHdr)
240 out.WriteString("import \"encoding/json\"\n\n")
241
242 // The following are unneeded, but make the new code a superset of the old
243 hack := func(newer, existing string) {
244 if _, ok := types[existing]; !ok {
245 log.Fatalf("types[%q] not found", existing)
246 }
247 types[newer] = strings.Replace(types[existing], existing, newer, 1)
248 }
249 hack("ConfigurationParams", "ParamConfiguration")
250 hack("InitializeParams", "ParamInitialize")
251 hack("PreviousResultId", "PreviousResultID")
252 hack("WorkspaceFoldersServerCapabilities", "WorkspaceFolders5Gn")
253 hack("_InitializeParams", "XInitializeParams")
254
255 for _, k := range types.keys() {
256 if k == "WatchKind" {
257 types[k] = "type WatchKind = uint32" // strict gopls compatibility needs the '='
258 }
259 out.WriteString(types[k])
260 }
261
262 out.WriteString("\nconst (\n")
263 for _, k := range consts.keys() {
264 out.WriteString(consts[k])
265 }
266 out.WriteString(")\n\n")
267 formatTo("tsprotocol.go", out.Bytes())
268 }
269
270 func writejsons() {
271 out := new(bytes.Buffer)
272 fmt.Fprintln(out, fileHdr)
273 out.WriteString("import \"encoding/json\"\n\n")
274 out.WriteString("import \"fmt\"\n")
275
276 out.WriteString(`
277 // UnmarshalError indicates that a JSON value did not conform to
278 // one of the expected cases of an LSP union type.
279 type UnmarshalError struct {
280 msg string
281 }
282
283 func (e UnmarshalError) Error() string {
284 return e.msg
285 }
286 `)
287
288 for _, k := range jsons.keys() {
289 out.WriteString(jsons[k])
290 }
291 formatTo("tsjson.go", out.Bytes())
292 }
293
294 // formatTo formats the Go source and writes it to *outputdir/basename.
295 func formatTo(basename string, src []byte) {
296 formatted, err := format.Source(src)
297 if err != nil {
298 failed := filepath.Join("/tmp", basename+".fail")
299 if err := os.WriteFile(failed, src, 0644); err != nil {
300 log.Fatal(err)
301 }
302 log.Fatalf("formatting %s: %v (see %s)", basename, err, failed)
303 }
304 if err := os.WriteFile(filepath.Join(*outputdir, basename), formatted, 0644); err != nil {
305 log.Fatal(err)
306 }
307 }
308
309 // create the common file header for the output files
310 func fileHeader(model *Model) string {
311 fname := filepath.Join(*repodir, ".git", "HEAD")
312 buf, err := os.ReadFile(fname)
313 if err != nil {
314 log.Fatal(err)
315 }
316 buf = bytes.TrimSpace(buf)
317 var githash string
318 if len(buf) == 40 {
319 githash = string(buf[:40])
320 } else if bytes.HasPrefix(buf, []byte("ref: ")) {
321 fname = filepath.Join(*repodir, ".git", string(buf[5:]))
322 buf, err = os.ReadFile(fname)
323 if err != nil {
324 log.Fatal(err)
325 }
326 githash = string(buf[:40])
327 } else {
328 log.Fatalf("githash cannot be recovered from %s", fname)
329 }
330
331 format := `// Copyright 2023 The Go Authors. All rights reserved.
332 // Use of this source code is governed by a BSD-style
333 // license that can be found in the LICENSE file.
334
335 // Code generated for LSP. DO NOT EDIT.
336
337 package protocol
338
339 // Code generated from %[1]s at ref %[2]s (hash %[3]s).
340 // %[4]s/blob/%[2]s/%[1]s
341 // LSP metaData.version = %[5]s.
342
343 `
344 return fmt.Sprintf(format,
345 "protocol/metaModel.json", // 1
346 lspGitRef, // 2
347 githash, // 3
348 vscodeRepo, // 4
349 model.Version.Version) // 5
350 }
351
352 func parse(fname string) *Model {
353 buf, err := os.ReadFile(fname)
354 if err != nil {
355 log.Fatal(err)
356 }
357 buf = addLineNumbers(buf)
358 model := new(Model)
359 if err := json.Unmarshal(buf, model); err != nil {
360 log.Fatal(err)
361 }
362 return model
363 }
364
365 // Type.Value has to be treated specially for literals and maps
366 func (t *Type) UnmarshalJSON(data []byte) error {
367 // First unmarshal only the unambiguous fields.
368 var x struct {
369 Kind string `json:"kind"`
370 Items []*Type `json:"items"`
371 Element *Type `json:"element"`
372 Name string `json:"name"`
373 Key *Type `json:"key"`
374 Value any `json:"value"`
375 Line int `json:"line"`
376 }
377 if err := json.Unmarshal(data, &x); err != nil {
378 return err
379 }
380 *t = Type{
381 Kind: x.Kind,
382 Items: x.Items,
383 Element: x.Element,
384 Name: x.Name,
385 Value: x.Value,
386 Line: x.Line,
387 }
388
389 // Then unmarshal the 'value' field based on the kind.
390 // This depends on Unmarshal ignoring fields it doesn't know about.
391 switch x.Kind {
392 case "map":
393 var x struct {
394 Key *Type `json:"key"`
395 Value *Type `json:"value"`
396 }
397 if err := json.Unmarshal(data, &x); err != nil {
398 return fmt.Errorf("Type.kind=map: %v", err)
399 }
400 t.Key = x.Key
401 t.Value = x.Value
402
403 case "literal":
404 var z struct {
405 Value ParseLiteral `json:"value"`
406 }
407
408 if err := json.Unmarshal(data, &z); err != nil {
409 return fmt.Errorf("Type.kind=literal: %v", err)
410 }
411 t.Value = z.Value
412
413 case "base", "reference", "array", "and", "or", "tuple",
414 "stringLiteral":
415 // no-op. never seen integerLiteral or booleanLiteral.
416
417 default:
418 return fmt.Errorf("cannot decode Type.kind %q: %s", x.Kind, data)
419 }
420 return nil
421 }
422
423 // which table entries were not used
424 func checkTables() {
425 for k := range disambiguate {
426 if !usedDisambiguate[k] {
427 log.Printf("disambiguate[%v] unused", k)
428 }
429 }
430 for k := range renameProp {
431 if !usedRenameProp[k] {
432 log.Printf("renameProp {%q, %q} unused", k[0], k[1])
433 }
434 }
435 for k := range goplsStar {
436 if !usedGoplsStar[k] {
437 log.Printf("goplsStar {%q, %q} unused", k[0], k[1])
438 }
439 }
440 for k := range goplsType {
441 if !usedGoplsType[k] {
442 log.Printf("unused goplsType[%q]->%s", k, goplsType[k])
443 }
444 }
445 }