Debian Codegraph @

gopls/internal/golang/splitpkg/splitpkg.go

raw symbols SCIP
1 // Copyright 2025 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 splitpkg
6
7 // This file produces the "Split package" HTML report.
8 //
9 // The server persistently holds, for each PackageID, the current set
10 // of components and the mapping from declared names to components. On
11 // each page reload or JS reload() call, the server type-checks the
12 // package, computes its symbol reference graph, projects it onto
13 // components, then returns the component reference graph, and if it
14 // is cyclic, which edges form cycles. Thus changes to the package
15 // source are reflected in the client UI at the next page reload or JS
16 // reload() event.
17 //
18 // See also:
19 // - ../codeaction.go - offers the CodeAction command
20 // - ../../server/command.go - handles the command by opening a web page
21 // - ../../server/server.go - handles the HTTP request and calls this function
22 // - ../../server/assets/splitpkg.js - client-side logic
23 // - ../../test/integration/web/splitpkg_test.go - integration test of server
24 //
25 // TODO(adonovan): future work
26 //
27 // Refine symbol reference graph:
28 // - deal with enums (values must stay together; implicit dependency on iota expression)
29 // - deal with coupled vars "var x, y = f()"
30 // - deal with declared methods (coupled to receiver named type)
31 // - deal with fields/interface methods (loosely coupled to struct/interface type)
32 // In both cases the field/method name must be either exported or in the same component.
33 //
34 // UI:
35 // - make shift click extend selection of a range of checkboxes.
36 // - display two-level grouping of decls and specs: var ( x int; y int )
37 // - indicate when package has type errors (data may be incomplete).
38 //
39 // Code transformation:
40 // - add "Split" button that is green when acyclic. It should:
41 // 1) move each component into a new package, or separate file of
42 // the same package. (The UI will need to hold this user
43 // intent in the list of components.)
44 // 2) ensure that each declaration referenced from another package
45 // is public, renaming as needed.
46 // 3) update package decls, imports, package docs, file docs,
47 // doc comments, etc.
48 // Should we call this feature "Reorganize package" or "Decompose package"
49 // until the "Split" button actually exists?
50
51 import (
52 "bytes"
53 "crypto/sha256"
54 _ "embed"
55 "encoding/json"
56 "fmt"
57 "go/ast"
58 "go/token"
59 "go/types"
60 "html/template"
61 "log"
62 "strconv"
63 "strings"
64
65 "golang.org/x/tools/gopls/internal/cache"
66 "golang.org/x/tools/gopls/internal/cache/metadata"
67 "golang.org/x/tools/gopls/internal/filecache"
68 "golang.org/x/tools/gopls/internal/protocol"
69 "golang.org/x/tools/gopls/internal/util/moremaps"
70 "golang.org/x/tools/gopls/internal/util/safetoken"
71 "golang.org/x/tools/internal/typesinternal"
72 )
73
74 //go:embed splitpkg.html.tmpl
75 var htmlTmpl string
76
77 // HTML returns the HTML for the main "Split package" page, for the
78 // /splitpkg endpoint. The real magic happens in JavaScript; see
79 // ../../server/assets/splitpkg.js.
80 func HTML(pkgpath metadata.PackagePath) []byte {
81 t, err := template.New("splitpkg.html").Parse(htmlTmpl)
82 if err != nil {
83 log.Fatal(err)
84 }
85 data := struct {
86 Title string
87 }{
88 Title: fmt.Sprintf("Split package %s", pkgpath),
89 }
90 var buf bytes.Buffer
91 if err := t.Execute(&buf, data); err != nil {
92 log.Fatal(err)
93 }
94 return buf.Bytes()
95 }
96
97 const cacheKind = "splitpkg" // filecache kind
98
99 func cacheKey(pkgID metadata.PackageID) [32]byte {
100 return sha256.Sum256([]byte(pkgID))
101 }
102
103 // UpdateComponentsJSON parses the JSON description of components and
104 // their assigned declarations and updates the component state for the
105 // specified package.
106 func UpdateComponentsJSON(pkgID metadata.PackageID, data []byte) error {
107 return filecache.Set(cacheKind, cacheKey(pkgID), data)
108 }
109
110 // Web is an abstraction of gopls' web server.
111 type Web interface {
112 // SrcURL forms URLs that cause the editor to open a file at a specific position.
113 SrcURL(filename string, line, col8 int) protocol.URI
114 }
115
116 // JSON returns the JSON encoding of the data needed by
117 // the /splitpkg-json endpoint for the specified package. It includes:
118 // - the set of names declared by the package, grouped by file;
119 // - the set of components and their assigned declarations from
120 // the most recent call to [UpdateComponentsJSON]; and
121 // - the component graph derived from them, along with the
122 // sets of reference that give rise to each edge.
123 func JSON(pkg *cache.Package, web Web) ([]byte, error) {
124 // Retrieve package's most recent state from the file cache.
125 var comp ComponentsJSON
126 data, err := filecache.Get(cacheKind, cacheKey(pkg.Metadata().ID), filecache.Bytes)
127 if err != nil {
128 if err != filecache.ErrNotFound {
129 return nil, err
130 }
131 // cache miss: use zero value
132 } else if err := json.Unmarshal(data, &comp); err != nil {
133 return nil, err
134 }
135
136 // Prepare to construct symbol reference graph.
137 var (
138 info = pkg.TypesInfo()
139 symbols = make(map[types.Object]*symbol)
140 )
141
142 // setName records the UI name for an object.
143 // (The UI name disambiguates "init", "_", etc.)
144 setName := func(obj types.Object, name string) {
145 symbols[obj] = &symbol{
146 name: name,
147 component: comp.Assignments[name], // missing => "default"
148 }
149 }
150
151 // Pass 1: name everything, since naming is order-dependent.
152 var initCounter, blankCounter int
153 for _, pgf := range pkg.CompiledGoFiles() {
154 for _, decl := range pgf.File.Decls {
155 switch decl := decl.(type) {
156 case *ast.FuncDecl:
157 if fn, ok := info.Defs[decl.Name].(*types.Func); ok {
158 // For now we treat methods as first class decls,
159 // but since they are coupled to the named type
160 // they should be omitted in the UI for brevity.
161 name := fn.Name()
162 if recv := fn.Signature().Recv(); recv != nil {
163 fn = fn.Origin()
164 _, named := typesinternal.ReceiverNamed(recv)
165 name = named.Obj().Name() + "." + name
166 } else if name == "init" {
167 // Disambiguate top-level init functions.
168 name += suffix(&initCounter)
169 }
170 if name == "_" { // (function or method)
171 name += suffix(&blankCounter)
172 }
173 setName(fn, name)
174 }
175
176 case *ast.GenDecl:
177 switch decl.Tok {
178 case token.CONST, token.VAR:
179 for _, spec := range decl.Specs {
180 spec := spec.(*ast.ValueSpec)
181 for _, id := range spec.Names {
182 if obj := info.Defs[id]; obj != nil {
183 name := obj.Name()
184 if name == "_" {
185 name += suffix(&blankCounter)
186 }
187 setName(obj, name)
188 }
189 }
190 }
191
192 case token.TYPE:
193 for _, spec := range decl.Specs {
194 spec := spec.(*ast.TypeSpec)
195 if obj := info.Defs[spec.Name]; obj != nil {
196 name := obj.Name()
197 if name == "_" {
198 name += suffix(&blankCounter)
199 }
200 setName(obj, name)
201 }
202 }
203 }
204 }
205 }
206 }
207
208 // Pass 2: compute symbol reference graph, project onto
209 // component dependency graph, and build JSON response.
210 var (
211 files []*fileJSON
212 refs []*refJSON
213 )
214 for _, pgf := range pkg.CompiledGoFiles() {
215 identURL := func(id *ast.Ident) string {
216 posn := safetoken.Position(pgf.Tok, id.Pos())
217 return web.SrcURL(posn.Filename, posn.Line, posn.Column)
218 }
219 newCollector := func(from *symbol) *refCollector {
220 return &refCollector{
221 from: from,
222 identURL: identURL,
223 pkg: pkg.Types(),
224 info: info,
225 symbols: symbols,
226 }
227 }
228 var decls []*declJSON
229 for _, decl := range pgf.File.Decls {
230 var (
231 kind string
232 specs []*specJSON
233 )
234 switch decl := decl.(type) {
235 case *ast.FuncDecl:
236 kind = "func"
237 if fn, ok := info.Defs[decl.Name].(*types.Func); ok {
238 symbol := symbols[fn]
239 rc := newCollector(symbol).collect(decl)
240 refs = append(refs, rc.refs...)
241 specs = append(specs, &specJSON{
242 Name: symbol.name,
243 URL: identURL(decl.Name),
244 })
245 }
246
247 case *ast.GenDecl:
248 kind = decl.Tok.String()
249
250 switch decl.Tok {
251 case token.CONST, token.VAR:
252 for _, spec := range decl.Specs {
253 spec := spec.(*ast.ValueSpec)
254 for i, id := range spec.Names {
255 if obj := info.Defs[id]; obj != nil {
256 symbol := symbols[obj]
257 rc := newCollector(symbol)
258 // If there's a type,
259 // all RHSs depend on it.
260 if spec.Type != nil {
261 rc.collect(spec.Type)
262 }
263 switch len(spec.Values) {
264 case len(spec.Names):
265 // var x, y = a, b
266 rc.collect(spec.Values[i])
267 case 1:
268 // var x, y = f()
269 rc.collect(spec.Values[0])
270 case 0:
271 // var x T
272 }
273 refs = append(refs, rc.refs...)
274 specs = append(specs, &specJSON{
275 Name: symbol.name,
276 URL: identURL(id),
277 })
278 }
279 }
280 }
281
282 case token.TYPE:
283 for _, spec := range decl.Specs {
284 spec := spec.(*ast.TypeSpec)
285 if obj := info.Defs[spec.Name]; obj != nil {
286 symbol := symbols[obj]
287 rc := newCollector(symbol).collect(spec.Type)
288 refs = append(refs, rc.refs...)
289 specs = append(specs, &specJSON{
290 Name: symbol.name,
291 URL: identURL(spec.Name),
292 })
293 }
294 }
295 }
296 }
297 if len(specs) > 0 {
298 decls = append(decls, &declJSON{Kind: kind, Specs: specs})
299 }
300 }
301 files = append(files, &fileJSON{
302 Base: pgf.URI.Base(),
303 URL: web.SrcURL(pgf.URI.Path(), 1, 1),
304 Decls: decls,
305 })
306 }
307
308 // Compute the graph of dependencies between components, by
309 // projecting the symbol dependency graph through component
310 // assignments.
311 var (
312 g = make(graph)
313 edgeRefs = make(map[[2]int][]*refJSON) // refs that induce each intercomponent edge
314 )
315 for _, ref := range refs {
316 from, to := ref.from, ref.to
317 if from.component != to.component {
318 // inter-component reference
319 m, ok := g[from.component]
320 if !ok {
321 m = make(map[int]bool)
322 g[from.component] = m
323 }
324 m[to.component] = true
325
326 key := [2]int{from.component, to.component}
327 edgeRefs[key] = append(edgeRefs[key], ref)
328 }
329 }
330
331 // Detect cycles in the component graph
332 // and record cyclic (⚠) components.
333 cycles := [][]int{} // non-nil for JSON
334 scmap := make(map[int]int) // maps component index to 1 + SCC index (0 => acyclic)
335 for i, scc := range sccs(g) {
336 for c := range scc {
337 scmap[c] = i + 1
338 }
339 cycles = append(cycles, moremaps.KeySlice(scc))
340 }
341
342 // Record intercomponent edges and their references.
343 edges := []*edgeJSON{} // non-nil for JSON
344 for edge, refs := range edgeRefs {
345 from, to := edge[0], edge[1]
346 edges = append(edges, &edgeJSON{
347 From: from,
348 To: to,
349 Refs: refs,
350 Cyclic: scmap[from] > 0 && scmap[from] == scmap[to],
351 })
352 }
353
354 return json.Marshal(ResultJSON{
355 Files: files,
356 Components: comp,
357 Edges: edges,
358 Cycles: cycles,
359 })
360 }
361
362 // A refCollector gathers intra-package references to top-level
363 // symbols from within one syntax tree, in lexical order.
364 type refCollector struct {
365 from *symbol
366 identURL func(*ast.Ident) string
367 pkg *types.Package
368 info *types.Info
369 index map[types.Object]*refJSON
370 symbols map[types.Object]*symbol
371
372 refs []*refJSON // output
373 }
374
375 // A symbol describes a declared name and its assigned component.
376 type symbol struct {
377 name string // unique name in the UI and JSON/HTTP protocol
378 component int // index of assigned component
379 }
380
381 // collect adds the free references of n to the collection.
382 func (rc *refCollector) collect(n ast.Node) *refCollector {
383 var f func(n ast.Node) bool
384 f = func(n ast.Node) bool {
385 switch n := n.(type) {
386 case *ast.SelectorExpr:
387 if sel, ok := rc.info.Selections[n]; ok {
388 rc.addRef(n.Sel, sel.Obj())
389 ast.Inspect(n.X, f)
390 return false // don't visit n.Sel
391 }
392
393 case *ast.Ident:
394 if obj := rc.info.Uses[n]; obj != nil {
395 rc.addRef(n, obj)
396 }
397 }
398 return true
399 }
400 ast.Inspect(n, f)
401
402 return rc
403 }
404
405 // addRef records a reference from id to obj.
406 func (rc *refCollector) addRef(id *ast.Ident, obj types.Object) {
407 if obj.Pkg() != rc.pkg {
408 return // cross-package reference
409 }
410
411 // Un-instantiate methods.
412 if fn, ok := obj.(*types.Func); ok && fn.Signature().Recv() != nil {
413 obj = fn.Origin() // G[int].method -> G[T].method
414 }
415
416 // We only care about refs to package-level symbols.
417 // And methods, for now.
418 decl := rc.symbols[obj]
419 if decl == nil {
420 return // not a package-level symbol or top-level method
421 }
422
423 if ref, ok := rc.index[obj]; !ok {
424 ref = &refJSON{
425 From: rc.from.name,
426 To: decl.name,
427 URL: rc.identURL(id),
428 from: rc.from,
429 to: decl,
430 }
431 if rc.index == nil {
432 rc.index = make(map[types.Object]*refJSON)
433 }
434 rc.index[obj] = ref
435 rc.refs = append(rc.refs, ref)
436 }
437 }
438
439 // suffix returns a subscripted decimal suffix,
440 // preincrementing the specified counter.
441 func suffix(counter *int) string {
442 *counter++
443 n := *counter
444 return subscripter.Replace(strconv.Itoa(n))
445 }
446
447 var subscripter = strings.NewReplacer(
448 "0", "₀",
449 "1", "₁",
450 "2", "₂",
451 "3", "₃",
452 "4", "₄",
453 "5", "₅",
454 "6", "₆",
455 "7", "₇",
456 "8", "₈",
457 "9", "₉",
458 )
459
460 // -- JSON types --
461
462 // ResultJSON describes the result of a /splitpkg-json query.
463 // It is public for testing.
464 type ResultJSON struct {
465 Components ComponentsJSON // component names and their assigned declarations
466 Files []*fileJSON // files of the packages and their declarations and references
467 Edges []*edgeJSON // inter-component edges and their references
468 Cycles [][]int // sets of strongly-connected components
469 }
470
471 // request body of a /splitpkg-components update;
472 // also part of /splitpkg-json response.
473 type ComponentsJSON struct {
474 Names []string `json:",omitempty"` // if empty, implied Names[0]=="default".
475 Assignments map[string]int `json:",omitempty"` // maps specJSON.Name to component index; missing => 0
476 }
477
478 // edgeJSON describes an inter-component dependency.
479 type edgeJSON struct {
480 From, To int // component IDs
481 Refs []*refJSON // references that give rise to this edge
482 Cyclic bool // edge is part of nontrivial strongly connected component
483 }
484
485 // fileJSON records groups decl/spec information about a single file.
486 type fileJSON struct {
487 Base string // file base name
488 URL string // showDocument link for file
489 Decls []*declJSON `json:",omitempty"`
490 }
491
492 // declJSON groups specs (e.g. "var ( x int; y int )").
493 type declJSON struct {
494 Kind string // const, var, type, func
495 Specs []*specJSON `json:",omitempty"`
496 }
497
498 // specJSON describes a single declared name.
499 // (A coupled declaration "var x, y = f()" results in two specJSONs.)
500 type specJSON struct {
501 Name string // x or T.x
502 URL string // showDocument link for declaring identifier
503 }
504
505 // refJSON records the first reference from a given declaration to a symbol.
506 // (Repeat uses of the same identifier are omitted.)
507 type refJSON struct {
508 From, To string // x or T.x of referenced spec
509 URL string // showDocument link for referring identifier
510
511 from, to *symbol // transient
512 }