Debian Codegraph @

gopls/internal/protocol/command/commandmeta/meta.go

raw symbols SCIP
1 // Copyright 2021 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 // Package commandmeta provides metadata about LSP commands, by
6 // statically analyzing the command.Interface type.
7 //
8 // It is used to generate JSONRPC dispatch and marshaling.
9 // TODO(adonovan): combine with gopls/internal/protocol/command/gen.
10 package commandmeta
11
12 import (
13 "fmt"
14 "go/ast"
15 "go/token"
16 "go/types"
17 "reflect"
18 "slices"
19 "strings"
20 "unicode"
21
22 "golang.org/x/tools/go/ast/astutil"
23 "golang.org/x/tools/go/packages"
24 "golang.org/x/tools/internal/typesinternal"
25 // (does not depend on gopls itself)
26 )
27
28 // A Command describes a workspace/executeCommand extension command.
29 type Command struct {
30 MethodName string // e.g. "RunTests"
31 Name string // e.g. "gopls.run_tests"
32 Title string
33 Doc string
34 Args []*Field
35 Interactive bool
36 Result *Field
37 }
38
39 type Field struct {
40 Name string
41 Doc string
42 JSONTag string
43 Type types.Type
44 FieldMod string
45 // In some circumstances, we may want to recursively load additional field
46 // descriptors for fields of struct types, documenting their internals.
47 Fields []*Field
48 }
49
50 // Load returns a description of the workspace/executeCommand commands
51 // supported by gopls based on static analysis of the command.Interface type.
52 func Load() ([]*Command, error) {
53 pkgs, err := packages.Load(
54 &packages.Config{
55 Mode: packages.NeedTypes | packages.NeedTypesInfo | packages.NeedSyntax | packages.NeedImports | packages.NeedDeps,
56 BuildFlags: []string{"-tags=generate"},
57 },
58 "golang.org/x/tools/gopls/internal/protocol/command",
59 )
60 if err != nil {
61 return nil, fmt.Errorf("packages.Load: %v", err)
62 }
63 pkg := pkgs[0]
64 if len(pkg.Errors) > 0 {
65 return nil, pkg.Errors[0]
66 }
67
68 // command.Interface
69 obj := pkg.Types.Scope().Lookup("Interface").Type().Underlying().(*types.Interface)
70
71 // Load command metadata corresponding to each interface method.
72 var commands []*Command
73 loader := fieldLoader{make(map[types.Object]*Field)}
74 for m := range obj.Methods() {
75 c, err := loader.loadMethod(pkg, m)
76 if err != nil {
77 return nil, fmt.Errorf("loading %s: %v", m.Name(), err)
78 }
79 commands = append(commands, c)
80 }
81
82 // Sort commands for deterministic results.
83 slices.SortFunc(commands, func(a, b *Command) int {
84 return strings.Compare(a.Name, b.Name)
85 })
86 return commands, nil
87 }
88
89 // fieldLoader loads field information, memoizing results to prevent infinite
90 // recursion.
91 type fieldLoader struct {
92 loaded map[types.Object]*Field
93 }
94
95 var universeError = types.Universe.Lookup("error").Type()
96
97 func (l *fieldLoader) loadMethod(pkg *packages.Package, m *types.Func) (*Command, error) {
98 node, err := findField(pkg, m.Pos())
99 if err != nil {
100 return nil, err
101 }
102 title, doc := splitDoc(node.Doc.Text())
103 c := &Command{
104 MethodName: m.Name(),
105 Name: lspName(m.Name()),
106 Doc: doc,
107 Title: title,
108 }
109 sig := m.Type().Underlying().(*types.Signature)
110 rlen := sig.Results().Len()
111 if rlen > 2 || rlen == 0 {
112 return nil, fmt.Errorf("must have 1 or 2 returns, got %d", rlen)
113 }
114 finalResult := sig.Results().At(rlen - 1)
115 if !types.Identical(finalResult.Type(), universeError) {
116 return nil, fmt.Errorf("final return must be error")
117 }
118 if rlen == 2 {
119 obj := sig.Results().At(0)
120 c.Result, err = l.loadField(pkg, obj, "", "")
121 if err != nil {
122 return nil, err
123 }
124 }
125 for i := 0; i < sig.Params().Len(); i++ {
126 obj := sig.Params().At(i)
127 fld, err := l.loadField(pkg, obj, "", "")
128 if err != nil {
129 return nil, err
130 }
131 if i == 0 {
132 // Lazy check that the first argument is a context. We could relax this,
133 // but then the generated code gets more complicated.
134 if named, ok := types.Unalias(fld.Type).(*types.Named); !ok || named.Obj().Name() != "Context" || named.Obj().Pkg().Path() != "context" {
135 return nil, fmt.Errorf("first method parameter must be context.Context")
136 }
137 // Skip the context argument, as it is implied.
138 continue
139 }
140
141 // SPECIAL CASE: InteractiveParams contains FormAnswers []any, making it
142 // inherently fallible. However, we explicitly exempt it from this check
143 // because it is not parsed via UnmarshalArgs from the JSON Arguments array.
144 // Instead, the generator passes it directly from the top-level
145 // InteractiveParams, and the command handlers are responsible for
146 // manually type-asserting the user-provided answers at runtime.
147 if i == sig.Params().Len()-1 && typesinternal.IsPointerToNamed(fld.Type, "golang.org/x/tools/gopls/internal/protocol", "InteractiveParams") {
148 c.Interactive = true
149 continue
150 }
151 c.Args = append(c.Args, fld)
152 }
153 return c, nil
154 }
155
156 func (l *fieldLoader) loadField(pkg *packages.Package, obj *types.Var, doc, tag string) (*Field, error) {
157 if existing, ok := l.loaded[obj]; ok {
158 return existing, nil
159 }
160 fld := &Field{
161 Name: obj.Name(),
162 Doc: strings.TrimSpace(doc),
163 Type: obj.Type(),
164 JSONTag: reflect.StructTag(tag).Get("json"),
165 }
166
167 // This must be done here to handle nested types, such as:
168 //
169 // type Test struct { Subtests []Test }
170 l.loaded[obj] = fld
171
172 under := fld.Type.Underlying()
173 // Quick-and-dirty handling for various underlying types.
174 switch p := under.(type) {
175 case *types.Pointer:
176 under = p.Elem().Underlying()
177 case *types.Array:
178 under = p.Elem().Underlying()
179 fld.FieldMod = fmt.Sprintf("[%d]", p.Len())
180 case *types.Slice:
181 under = p.Elem().Underlying()
182 fld.FieldMod = "[]"
183 }
184
185 if s, ok := under.(*types.Struct); ok {
186 for i := 0; i < s.NumFields(); i++ {
187 obj2 := s.Field(i)
188 pkg2 := pkg
189 if obj2.Pkg() != pkg2.Types {
190 pkg2, ok = pkg.Imports[obj2.Pkg().Path()]
191 if !ok {
192 return nil, fmt.Errorf("missing import for %q: %q", pkg.ID, obj2.Pkg().Path())
193 }
194 }
195 node, err := findField(pkg2, obj2.Pos())
196 if err != nil {
197 return nil, err
198 }
199 tag := s.Tag(i)
200 structField, err := l.loadField(pkg2, obj2, node.Doc.Text(), tag)
201 if err != nil {
202 return nil, err
203 }
204 fld.Fields = append(fld.Fields, structField)
205 }
206 }
207 return fld, nil
208 }
209
210 // splitDoc parses a command doc string to separate the title from normal
211 // documentation.
212 //
213 // The doc comment should be of the form: "MethodName: Title\nDocumentation"
214 func splitDoc(text string) (title, doc string) {
215 docParts := strings.SplitN(text, "\n", 2)
216 titleParts := strings.SplitN(docParts[0], ":", 2)
217 if len(titleParts) > 1 {
218 title = strings.TrimSpace(titleParts[1])
219 }
220 if len(docParts) > 1 {
221 doc = strings.TrimSpace(docParts[1])
222 }
223 return title, doc
224 }
225
226 // lspName returns the normalized command name to use in the LSP.
227 func lspName(methodName string) string {
228 words := splitCamel(methodName)
229 for i := range words {
230 words[i] = strings.ToLower(words[i])
231 }
232 return "gopls." + strings.Join(words, "_")
233 }
234
235 // splitCamel splits s into words, according to camel-case word boundaries.
236 // Initialisms are grouped as a single word.
237 //
238 // For example:
239 //
240 // "RunTests" -> []string{"Run", "Tests"}
241 // "ClientOpenURL" -> []string{"Client", "Open", "URL"}
242 func splitCamel(s string) []string {
243 var words []string
244 for len(s) > 0 {
245 last := max(strings.LastIndexFunc(s, unicode.IsUpper), 0)
246 if last == len(s)-1 {
247 // Group initialisms as a single word.
248 last = 1 + strings.LastIndexFunc(s[:last], func(r rune) bool { return !unicode.IsUpper(r) })
249 }
250 words = append(words, s[last:])
251 s = s[:last]
252 }
253 for i := 0; i < len(words)/2; i++ {
254 j := len(words) - i - 1
255 words[i], words[j] = words[j], words[i]
256 }
257 return words
258 }
259
260 // findField finds the struct field or interface method positioned at pos,
261 // within the AST.
262 func findField(pkg *packages.Package, pos token.Pos) (*ast.Field, error) {
263 fset := pkg.Fset
264 var file *ast.File
265 for _, f := range pkg.Syntax {
266 if fset.File(f.FileStart).Name() == fset.File(pos).Name() {
267 file = f
268 break
269 }
270 }
271 if file == nil {
272 return nil, fmt.Errorf("no file for pos %v", pos)
273 }
274 path, _ := astutil.PathEnclosingInterval(file, pos, pos)
275 // This is fragile, but in the cases we care about, the field will be in
276 // path[1].
277 return path[1].(*ast.Field), nil
278 }