Debian Codegraph @

gopls/internal/golang/freesymbols.go

raw symbols SCIP
1 // Copyright 2024 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 golang
6
7 // This file implements the "Browse free symbols" code action.
8
9 import (
10 "bytes"
11 "fmt"
12 "go/ast"
13 "go/token"
14 "go/types"
15 "html"
16 "slices"
17 "sort"
18 "strings"
19
20 "golang.org/x/tools/go/ast/astutil"
21 "golang.org/x/tools/gopls/internal/cache"
22 "golang.org/x/tools/gopls/internal/cache/metadata"
23 "golang.org/x/tools/gopls/internal/cache/parsego"
24 "golang.org/x/tools/gopls/internal/util/moremaps"
25 "golang.org/x/tools/gopls/internal/util/safetoken"
26 "golang.org/x/tools/internal/typesinternal"
27 )
28
29 // FreeSymbolsHTML returns an HTML document containing the report of
30 // free symbols referenced by the selection.
31 func FreeSymbolsHTML(viewID string, pkg *cache.Package, pgf *parsego.File, start, end token.Pos, web Web) []byte {
32
33 // Compute free references.
34 refs := freeRefs(pkg.Types(), pkg.TypesInfo(), pgf.File, start, end)
35
36 // -- model --
37
38 type Import struct {
39 Path metadata.PackagePath
40 Symbols []string
41 }
42 type Symbol struct {
43 Kind string
44 Type string
45 Refs []types.Object
46 }
47 var model struct {
48 Imported []Import
49 PkgLevel []Symbol
50 Local []Symbol
51 }
52
53 qualifier := typesinternal.NameRelativeTo(pkg.Types())
54
55 // Populate model.
56 {
57 // List the refs in order of dotted paths.
58 sort.Slice(refs, func(i, j int) bool {
59 return refs[i].dotted < refs[j].dotted
60 })
61
62 // Inspect the references.
63 imported := make(map[string][]*freeRef) // refs to imported symbols, by package path
64 seen := make(map[string]bool) // to de-dup dotted paths
65 for _, ref := range refs {
66 if seen[ref.dotted] {
67 continue // de-dup
68 }
69 seen[ref.dotted] = true
70
71 var symbols *[]Symbol
72 switch ref.scope {
73 case "file":
74 // imported symbol: group by package
75 if pkgname, ok := ref.objects[0].(*types.PkgName); ok {
76 path := pkgname.Imported().Path()
77 imported[path] = append(imported[path], ref)
78 }
79 continue
80 case "pkg":
81 symbols = &model.PkgLevel
82 case "local":
83 symbols = &model.Local
84 default:
85 panic(ref.scope)
86 }
87
88 // Package and local symbols are presented the same way.
89 // We treat each dotted path x.y.z as a separate entity.
90
91 // Compute kind and type of last object (y in obj.x.y).
92 typestr := " " + types.TypeString(ref.typ, qualifier)
93 var kind string
94 switch obj := ref.objects[len(ref.objects)-1].(type) {
95 case *types.Var:
96 kind = "var"
97 case *types.Func:
98 kind = "func"
99 case *types.TypeName:
100 if is[*types.TypeParam](obj.Type()) {
101 kind = "type parameter"
102 } else {
103 kind = "type"
104 }
105 typestr = "" // avoid "type T T"
106 case *types.Const:
107 kind = "const"
108 case *types.Label:
109 kind = "label"
110 typestr = "" // avoid "label L L"
111 }
112
113 *symbols = append(*symbols, Symbol{
114 Kind: kind,
115 Type: typestr,
116 Refs: ref.objects,
117 })
118 }
119
120 // Imported symbols.
121 // Produce one record per package, with a list of symbols.
122 for pkgPath, refs := range moremaps.Sorted(imported) {
123 var syms []string
124 for _, ref := range refs {
125 // strip package name (bytes.Buffer.Len -> Buffer.Len)
126 syms = append(syms, ref.dotted[len(ref.objects[0].Name())+len("."):])
127 }
128 sort.Strings(syms)
129 const max = 4
130 if len(syms) > max {
131 syms[max-1] = fmt.Sprintf("... (%d)", len(syms))
132 syms = syms[:max]
133 }
134
135 model.Imported = append(model.Imported, Import{
136 Path: PackagePath(pkgPath),
137 Symbols: syms,
138 })
139 }
140 }
141
142 // -- presentation --
143
144 var buf bytes.Buffer
145 buf.WriteString(`<!DOCTYPE html>
146 <html>
147 <head>
148 <style>
149 .col-pkg { color: #2eb007 }
150 .col-file { color: #a10b15 }
151 .col-local { color: #0cb7c9 }
152 li { font-family: monospace; }
153 p { max-width: 6in; }
154 </style>
155 <script src="/assets/common.js"></script>
156 <link rel="stylesheet" href="/assets/common.css">
157 </head>
158 <body>
159 <h1>Free symbols</h1>
160 <p>
161 The selected code contains references to these free* symbols:
162 </p>
163 `)
164
165 // Present the refs in three sections: imported, same package, local.
166
167 // -- imported symbols --
168
169 // Show one item per package, with a list of symbols.
170 fmt.Fprintf(&buf, "<h2><span class='col-file'>⬤</span> Imported symbols</h2>\n")
171 fmt.Fprintf(&buf, "<ul>\n")
172 for _, imp := range model.Imported {
173 fmt.Fprintf(&buf, "<li>import \"<a href='%s'>%s</a>\" // for %s</li>\n",
174 web.PkgURL(viewID, imp.Path, ""),
175 html.EscapeString(string(imp.Path)),
176 strings.Join(imp.Symbols, ", "))
177 }
178 if len(model.Imported) == 0 {
179 fmt.Fprintf(&buf, "<li>(none)</li>\n")
180 }
181 buf.WriteString("</ul>\n")
182
183 // -- package and local symbols --
184
185 showSymbols := func(scope, title string, symbols []Symbol) {
186 fmt.Fprintf(&buf, "<h2><span class='col-%s'>⬤</span> %s</h2>\n", scope, title)
187 fmt.Fprintf(&buf, "<ul>\n")
188 pre := buf.Len()
189 for _, sym := range symbols {
190 fmt.Fprintf(&buf, "<li>%s ", sym.Kind) // of rightmost symbol in dotted path
191 for i, obj := range sym.Refs {
192 if i > 0 {
193 buf.WriteByte('.')
194 }
195 buf.WriteString(objHTML(pkg.FileSet(), web, obj))
196 }
197 fmt.Fprintf(&buf, " %s</li>\n", html.EscapeString(sym.Type))
198 }
199 if buf.Len() == pre {
200 fmt.Fprintf(&buf, "<li>(none)</li>\n")
201 }
202 buf.WriteString("</ul>\n")
203 }
204 showSymbols("pkg", "Package-level symbols", model.PkgLevel)
205 showSymbols("local", "Local symbols", model.Local)
206
207 // -- code selection --
208
209 // Print the selection, highlighting references to free symbols.
210 buf.WriteString("<hr/>\n")
211 sort.Slice(refs, func(i, j int) bool {
212 return refs[i].expr.Pos() < refs[j].expr.Pos()
213 })
214 pos := start
215 emitTo := func(end token.Pos) {
216 if pos < end {
217 fileStart := pgf.File.FileStart
218 text := pgf.Mapper.Content[pos-fileStart : end-fileStart]
219 buf.WriteString(html.EscapeString(string(text)))
220 pos = end
221 }
222 }
223 buf.WriteString(`<pre>`)
224 for _, ref := range refs {
225 emitTo(ref.expr.Pos())
226 fmt.Fprintf(&buf, `<b class='col-%s'>`, ref.scope)
227 emitTo(ref.expr.End())
228 buf.WriteString(`</b>`)
229 }
230 emitTo(end)
231 buf.WriteString(`</pre>
232 <hr>
233 <p>
234 *A symbol is "free" if it is referenced within the selection but declared
235 outside of it.
236
237 The free variables are approximately the set of parameters that
238 would be needed if the block were extracted into its own function in
239 the same package.
240
241 Free identifiers may include local types and control labels as well.
242
243 Even when you don't intend to extract a block into a new function,
244 this information can help you to tell at a glance what names a block
245 of code depends on.
246 </p>
247 <p>
248 Each dotted path of identifiers (such as file.Name.Pos) is reported
249 as a separate item, so that you can see which parts of a complex
250 type are actually needed.
251
252 The free symbols referenced by the body of a function may
253 reveal that only a small part (a single field of a struct, say) of
254 one of the function's parameters is used, allowing you to simplify
255 and generalize the function by choosing a different type for that
256 parameter.
257 </p>
258 `)
259 return buf.Bytes()
260 }
261
262 // A freeRef records a reference to a dotted path obj.x.y,
263 // where obj (=objects[0]) is a free symbol.
264 type freeRef struct {
265 objects []types.Object // [obj x y]
266 dotted string // "obj.x.y" (used as sort key)
267 scope string // scope of obj: pkg|file|local
268 expr ast.Expr // =*Ident|*SelectorExpr
269 typ types.Type // type of obj.x.y
270 }
271
272 // freeRefs returns the list of references to free symbols (from
273 // within the selection to a symbol declared outside of it).
274 // It uses only info.{Scopes,Types,Uses}.
275 func freeRefs(pkg *types.Package, info *types.Info, file *ast.File, start, end token.Pos) []*freeRef {
276 // Keep us honest about which fields we access.
277 info = &types.Info{
278 Scopes: info.Scopes,
279 Types: info.Types,
280 Uses: info.Uses,
281 }
282
283 fileScope := info.Scopes[file]
284 pkgScope := fileScope.Parent()
285
286 // id is called for the leftmost id x in each dotted chain such as (x.y).z.
287 // suffix is the reversed suffix of selections (e.g. [z y]).
288 id := func(n *ast.Ident, suffix []types.Object) *freeRef {
289 obj := info.Uses[n]
290 if obj == nil {
291 return nil // not a reference
292 }
293 if start <= obj.Pos() && obj.Pos() < end {
294 return nil // defined within selection => not free
295 }
296 parent := obj.Parent()
297
298 // Compute dotted path.
299 objects := append(suffix, obj)
300 if obj.Pkg() != nil && obj.Pkg() != pkg && typesinternal.IsPackageLevel(obj) { // dot import
301 // Synthesize the implicit PkgName.
302 pkgName := types.NewPkgName(token.NoPos, pkg, obj.Pkg().Name(), obj.Pkg())
303 parent = fileScope
304 objects = append(objects, pkgName)
305 }
306 slices.Reverse(objects)
307 var dotted strings.Builder
308 for i, obj := range objects {
309 if obj == nil {
310 return nil // type error
311 }
312 if i > 0 {
313 dotted.WriteByte('.')
314 }
315 dotted.WriteString(obj.Name())
316 }
317
318 // Compute scope of base object.
319 var scope string
320 switch parent {
321 case nil:
322 return nil // interface method or struct field
323 case types.Universe:
324 return nil // built-in (not interesting)
325 case fileScope:
326 scope = "file" // defined at file scope (imported package)
327 case pkgScope:
328 scope = "pkg" // defined at package level
329 default:
330 scope = "local" // defined within current function
331 }
332
333 return &freeRef{
334 objects: objects,
335 dotted: dotted.String(),
336 scope: scope,
337 }
338 }
339
340 // sel(x.y.z, []) calls sel(x.y, [z]) calls id(x, [z, y]).
341 sel := func(sel *ast.SelectorExpr, suffix []types.Object) *freeRef {
342 for {
343 suffix = append(suffix, info.Uses[sel.Sel])
344
345 switch x := ast.Unparen(sel.X).(type) {
346 case *ast.Ident:
347 return id(x, suffix)
348 default:
349 return nil
350 case *ast.SelectorExpr:
351 sel = x
352 }
353 }
354 }
355
356 // Visit all the identifiers in the selected ASTs.
357 var free []*freeRef
358 path, _ := astutil.PathEnclosingInterval(file, start, end)
359 var visit func(n ast.Node) bool
360 visit = func(n ast.Node) bool {
361 // Is this node contained within the selection?
362 // (freesymbols permits inexact selections,
363 // like two stmts in a block.)
364 if n != nil && start <= n.Pos() && n.End() <= end {
365 var ref *freeRef
366 switch n := n.(type) {
367 case *ast.Ident:
368 ref = id(n, nil)
369 case *ast.SelectorExpr:
370 ref = sel(n, nil)
371 }
372
373 if ref != nil {
374 ref.expr = n.(ast.Expr)
375 if tv, ok := info.Types[ref.expr]; ok {
376 ref.typ = tv.Type
377 } else {
378 ref.typ = types.Typ[types.Invalid]
379 }
380 free = append(free, ref)
381 }
382
383 // After visiting x.sel, don't descend into sel.
384 // Descend into x only if we didn't get a ref for x.sel.
385 if sel, ok := n.(*ast.SelectorExpr); ok {
386 if ref == nil {
387 ast.Inspect(sel.X, visit)
388 }
389 return false
390 }
391 }
392
393 return true // descend
394 }
395 ast.Inspect(path[0], visit)
396 return free
397 }
398
399 // objHTML returns HTML for obj.Name(), possibly marked up as a link
400 // to the web server that, when visited, opens the declaration in the
401 // client editor.
402 func objHTML(fset *token.FileSet, web Web, obj types.Object) string {
403 text := obj.Name()
404 if posn := safetoken.StartPosition(fset, obj.Pos()); posn.IsValid() {
405 url := web.SrcURL(posn.Filename, posn.Line, posn.Column)
406 return sourceLink(text, url)
407 }
408 return text
409 }
410
411 // sourceLink returns HTML for a link to open a file in the client editor.
412 func sourceLink(text, url string) string {
413 // The /src URL returns nothing but has the side effect
414 // of causing the LSP client to open the requested file.
415 // So we use onclick to prevent the browser from navigating.
416 // We keep the href attribute as it causes the <a> to render
417 // as a link: blue, underlined, with URL hover information.
418 return fmt.Sprintf(`<a href="%[1]s" onclick='return httpGET("%[1]s")'>%[2]s</a>`,
419 html.EscapeString(url), text)
420 }