Debian Codegraph @

internal/stdlib/generate.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 //go:build ignore
6
7 // The generate command reads all the GOROOT/api/go1.*.txt files and
8 // generates a single combined manifest.go file containing the Go
9 // standard library API symbols along with versions.
10 //
11 // It also runs "go list -deps std" and records the import graph. This
12 // information may be used, for example, to ensure that tools don't
13 // suggest fixes that import package P when analyzing one of P's
14 // dependencies.
15 package main
16
17 import (
18 "bytes"
19 "cmp"
20 "encoding/binary"
21 "encoding/json"
22 "errors"
23 "fmt"
24 "go/ast"
25 "go/format"
26 "go/parser"
27 "go/token"
28 "go/types"
29 "io/fs"
30 "log"
31 "os"
32 "os/exec"
33 "path/filepath"
34 "regexp"
35 "slices"
36 "strconv"
37 "strings"
38
39 "golang.org/x/tools/go/packages"
40 )
41
42 func main() {
43 log.SetFlags(log.Lshortfile) // to identify the source of the log messages
44
45 dir := apidir()
46 manifest(dir)
47 deps()
48 }
49
50 // -- generate std manifest --
51
52 func manifest(apidir string) {
53 // find the signatures
54 cfg := packages.Config{
55 Mode: packages.LoadTypes,
56 Env: append(os.Environ(), "CGO_ENABLED=0", "GOOS=linux", "GOARCH=amd64"),
57 }
58 // find the source. This is not totally reliable: different
59 // systems may get different versions of unreleased APIs.
60 // The result depends on the toolchain.
61 // The x/tools release process regenerates the table
62 // with the canonical toolchain.
63 stdpkgs, err := packages.Load(&cfg, "std")
64 if err != nil {
65 log.Fatal(err)
66 }
67 signatures := make(map[string]map[string]string) // PkgPath->FuncName->signature
68 // signatures start with func and may contain type parameters
69 // "func[T comparable](value T) unique.Handle[T]"
70 for _, pkg := range stdpkgs {
71 if strings.HasPrefix(pkg.PkgPath, "vendor/") ||
72 strings.HasPrefix(pkg.PkgPath, "internal/") ||
73 strings.Contains(pkg.PkgPath, "/internal/") {
74 continue
75 }
76 for _, name := range pkg.Types.Scope().Names() {
77 fixer := func(p *types.Package) string {
78 // fn.Signature() would have produced
79 // "func(fi io/fs.FileInfo, link string) (*archive/tar.Header, error)"},
80 // This produces
81 // "func FileInfoHeader(fi fs.FileInfo, link string) (*Header, error)""
82 // Note that the function name is superfluous, so it is removed below
83 if p != pkg.Types {
84 return p.Name()
85 }
86 return ""
87 }
88 obj := pkg.Types.Scope().Lookup(name)
89 if fn, ok := obj.(*types.Func); ok {
90 mp, ok := signatures[pkg.PkgPath]
91 if !ok {
92 mp = make(map[string]string)
93 signatures[pkg.PkgPath] = mp
94 }
95 sig := types.ObjectString(fn, fixer)
96 // remove the space and function name introduced by fixer
97 sig = strings.Replace(sig, " "+name, "", 1)
98 mp[name] = sig
99 }
100 }
101 }
102
103 // read the api data
104 pkgs := make(map[string]map[string]symInfo) // package -> symbol -> info
105 symRE := regexp.MustCompile(`^pkg (\S+).*?, (var|func|type|const|method \([^)]*\)) ([\pL\p{Nd}_]+)(.*)`)
106
107 // parse parses symbols out of GOROOT/api/*.txt data, with the specified minor version.
108 // Errors are reported against filename.
109 parse := func(filename string, data []byte, minor int) {
110 for linenum, line := range strings.Split(string(data), "\n") {
111 if line == "" || strings.HasPrefix(line, "#") {
112 continue
113 }
114 m := symRE.FindStringSubmatch(line)
115 if m == nil {
116 log.Fatalf("invalid input: %s:%d: %s", filename, linenum+1, line)
117 }
118 path, kind, sym, rest := m[1], m[2], m[3], m[4]
119
120 if _, recv, ok := strings.Cut(kind, "method "); ok {
121 // e.g. "method (*Func) Pos() token.Pos"
122 kind = "method" // (concrete)
123
124 recv := removeTypeParam(recv) // (*Foo[T]) -> (*Foo)
125
126 sym = recv + "." + sym // (*T).m
127
128 } else if method, ok := strings.CutPrefix(rest, " interface, "); ok && kind == "type" {
129 // e.g. "pkg reflect, type Type interface, Comparable() bool"
130 // or "pkg net, type Error interface, Temporary //deprecated"
131
132 kind = "method" // (abstract)
133
134 if strings.HasPrefix(method, "unexported methods") {
135 continue
136 }
137 if strings.Contains(method, " //deprecated") {
138 continue
139 }
140 name, _, ok := strings.Cut(method, "(")
141 if !ok {
142 log.Printf("unexpected: %s", line)
143 continue
144 }
145 sym = fmt.Sprintf("(%s).%s", sym, name) // (T).m
146
147 } else if field, ok := strings.CutPrefix(rest, " struct, "); ok && kind == "type" {
148 // e.g. "type ParenExpr struct, Lparen token.Pos"
149 kind = "field"
150 name, typ, _ := strings.Cut(field, " ")
151
152 // The api script uses the name
153 // "embedded" (ambiguously) for
154 // the name of an anonymous field.
155 if name == "embedded" {
156 // Strip "*pkg.T" down to "T".
157 typ = strings.TrimPrefix(typ, "*")
158 if _, after, ok := strings.Cut(typ, "."); ok {
159 typ = after
160 }
161 typ = removeTypeParam(typ) // embedded Foo[T] -> Foo
162 name = typ
163 }
164
165 sym += "." + name // T.f
166 }
167
168 symbols, ok := pkgs[path]
169 if !ok {
170 symbols = make(map[string]symInfo)
171 pkgs[path] = symbols
172 }
173
174 // Don't overwrite earlier entries:
175 // enums are redeclared in later versions
176 // as their encoding changes;
177 // deprecations count as updates too.
178 // TODO(adonovan): it would be better to mark
179 // deprecated as a boolean without changing the
180 // version.
181 if _, ok := symbols[sym]; !ok {
182 var sig string
183 if kind == "func" {
184 sig = signatures[path][sym]
185 }
186 symbols[sym] = symInfo{
187 kind: kind,
188 minor: minor,
189 signature: sig,
190 }
191 }
192 }
193 }
194
195 // Read and parse the GOROOT/api manifests.
196 for minor := 0; ; minor++ {
197 base := "go1.txt"
198 if minor > 0 {
199 base = fmt.Sprintf("go1.%d.txt", minor)
200 }
201 filename := filepath.Join(apidir, base)
202 data, err := os.ReadFile(filename)
203 if err != nil {
204 if errors.Is(err, fs.ErrNotExist) {
205 // All caught up.
206 // Synthesize one final file from any api/next/*.txt fragments.
207 // (They are consolidated into a go1.%d file some time between
208 // the freeze and the first release candidate.)
209 filenames, err := filepath.Glob(filepath.Join(apidir, "next", "*.txt"))
210 if err != nil {
211 log.Fatal(err)
212 }
213 var next bytes.Buffer
214 for _, filename := range filenames {
215 data, err := os.ReadFile(filename)
216 if err != nil {
217 log.Fatal(err)
218 }
219 next.Write(data)
220 }
221 parse(filename, next.Bytes(), minor) // (filename is a lie)
222 break
223 }
224 log.Fatal(err)
225 }
226 parse(filename, data, minor)
227 }
228
229 // The APIs of the syscall/js and unsafe packages need to be computed explicitly,
230 // because they're not included in the GOROOT/api/go1.*.txt files at this time.
231 pkgs["syscall/js"] = loadSymbols("syscall/js", "GOOS=js", "GOARCH=wasm")
232 pkgs["unsafe"] = exportedSymbols(types.Unsafe) // TODO(adonovan): set correct versions
233
234 // Write the combined manifest.
235 var buf bytes.Buffer
236 buf.WriteString(`// Copyright 2025 The Go Authors. All rights reserved.
237 // Use of this source code is governed by a BSD-style
238 // license that can be found in the LICENSE file.
239
240 // Code generated by generate.go. DO NOT EDIT.
241
242 package stdlib
243
244 var PackageSymbols = map[string][]Symbol{
245 `)
246
247 for _, path := range sortedKeys(pkgs) {
248 pkg := pkgs[path]
249 fmt.Fprintf(&buf, "\t%q: {\n", path)
250 for _, name := range sortedKeys(pkg) {
251 info := pkg[name]
252 fmt.Fprintf(&buf, "\t\t{%q, %s, %d, %q},\n",
253 name, strings.Title(info.kind), info.minor, info.signature)
254 }
255 fmt.Fprintln(&buf, "},")
256 }
257 fmt.Fprintln(&buf, "}")
258 fmtbuf, err := format.Source(buf.Bytes())
259 if err != nil {
260 log.Fatal(err)
261 }
262 if err := os.WriteFile("manifest.go", fmtbuf, 0o666); err != nil {
263 log.Fatal(err)
264 }
265 }
266
267 // find the api directory, In most situations it is in GOROOT/api, but not always.
268 // TODO(pjw): understand where it might be, and if there could be newer and older versions
269 func apidir() string {
270 stdout := new(bytes.Buffer)
271 cmd := exec.Command("go", "env", "GOROOT", "GOPATH")
272 cmd.Stdout = stdout
273 cmd.Stderr = os.Stderr
274 if err := cmd.Run(); err != nil {
275 log.Fatal(err)
276 }
277 // Prefer GOROOT/api over GOPATH/api.
278 for line := range strings.SplitSeq(stdout.String(), "\n") {
279 apidir := filepath.Join(line, "api")
280 info, err := os.Stat(apidir)
281 if err == nil && info.IsDir() {
282 return apidir
283 }
284 }
285 log.Fatal("could not find api dir")
286 return ""
287 }
288
289 type symInfo struct {
290 kind string // e.g. "func"
291 minor int // go1.%d
292 // for completion snippets
293 signature string // for Kind == stdlib.Func
294 }
295
296 // loadSymbols computes the exported symbols in the specified package
297 // by parsing and type-checking the current source.
298 func loadSymbols(pkg string, extraEnv ...string) map[string]symInfo {
299 pkgs, err := packages.Load(&packages.Config{
300 Mode: packages.NeedTypes,
301 Env: append(os.Environ(), extraEnv...),
302 }, pkg)
303 if err != nil {
304 log.Fatalln(err)
305 } else if len(pkgs) != 1 {
306 log.Fatalf("got %d packages, want one package %q", len(pkgs), pkg)
307 }
308 return exportedSymbols(pkgs[0].Types)
309 }
310
311 func exportedSymbols(pkg *types.Package) map[string]symInfo {
312 symbols := make(map[string]symInfo)
313 for _, name := range pkg.Scope().Names() {
314 if obj := pkg.Scope().Lookup(name); obj.Exported() {
315 var kind string
316 switch obj.(type) {
317 case *types.Func, *types.Builtin:
318 kind = "func"
319 case *types.Const:
320 kind = "const"
321 case *types.Var:
322 kind = "var"
323 case *types.TypeName:
324 kind = "type"
325 // TODO(adonovan): expand fields and methods of syscall/js.*
326 default:
327 log.Fatalf("unexpected object type: %v", obj)
328 }
329 symbols[name] = symInfo{kind: kind, minor: 0} // pretend go1.0
330 }
331 }
332 return symbols
333 }
334
335 func sortedKeys[M ~map[K]V, K cmp.Ordered, V any](m M) []K {
336 r := make([]K, 0, len(m))
337 for k := range m {
338 r = append(r, k)
339 }
340 slices.Sort(r)
341 return r
342 }
343
344 func removeTypeParam(s string) string {
345 i := strings.IndexByte(s, '[')
346 j := strings.LastIndexByte(s, ']')
347 if i > 0 && j > i {
348 s = s[:i] + s[j+len("["):]
349 }
350 return s
351 }
352
353 // -- generate dependency graph --
354
355 func deps() {
356 type Package struct {
357 // go list JSON output
358 ImportPath string // import path of package in dir
359 Imports []string // import paths used by this package
360
361 // encoding
362 index int
363 deps []int // indices of direct imports, sorted
364 }
365 pkgs := make(map[string]*Package)
366 var keys []string
367 for dec := json.NewDecoder(runGo("list", "-deps", "-json", "std")); dec.More(); {
368 var pkg Package
369 if err := dec.Decode(&pkg); err != nil {
370 log.Fatal(err)
371 }
372 pkgs[pkg.ImportPath] = &pkg
373 keys = append(keys, pkg.ImportPath)
374 }
375
376 // Sort and number the packages.
377 // There are 344 as of Mar 2025.
378 slices.Sort(keys)
379 for i, name := range keys {
380 pkgs[name].index = i
381 }
382
383 // Encode the dependencies.
384 for _, pkg := range pkgs {
385 for _, imp := range pkg.Imports {
386 if imp == "C" {
387 continue
388 }
389 pkg.deps = append(pkg.deps, pkgs[imp].index)
390 }
391 slices.Sort(pkg.deps)
392 }
393
394 // Emit the table.
395 var buf bytes.Buffer
396 buf.WriteString(`// Copyright 2025 The Go Authors. All rights reserved.
397 // Use of this source code is governed by a BSD-style
398 // license that can be found in the LICENSE file.
399
400 // Code generated by generate.go. DO NOT EDIT.
401
402 package stdlib
403
404 type pkginfo struct {
405 name string
406 deps string // list of indices of dependencies, as varint-encoded deltas
407 }
408 var deps = [...]pkginfo{
409 `)
410 for _, name := range keys {
411 prev := 0
412 var deps []int
413 for _, v := range pkgs[name].deps {
414 deps = append(deps, v-prev) // delta
415 prev = v
416 }
417 var data []byte
418 for _, v := range deps {
419 data = binary.AppendUvarint(data, uint64(v))
420 }
421 fmt.Fprintf(&buf, "\t{%q, %q},\n", name, data)
422 }
423 fmt.Fprintln(&buf, "}")
424
425 // Also write the list of bootstrap packages.
426 // (We can't use indices because it is not a subset of std.)
427 bootstrap, version := bootstrap()
428 minor := strings.Split(version, ".")[1] // "go1.2.3" -> "2"
429 buf.WriteString(`
430 // bootstrap is the list of bootstrap packages extracted from cmd/dist.
431 var bootstrap = map[string]bool{
432 `)
433 for _, pkg := range bootstrap {
434 fmt.Fprintf(&buf, "\t%q: true,\n", pkg)
435 }
436 fmt.Fprintf(&buf, `}
437
438 // BootstrapVersion is the minor version of Go used during toolchain
439 // bootstrapping. Packages for which [IsBootstrapPackage] must not use
440 // features of Go newer than this version.
441 const BootstrapVersion = Version(%s) // %s
442 `, minor, version)
443
444 // Format and update the dependencies file.
445 fmtbuf, err := format.Source(buf.Bytes())
446 if err != nil {
447 log.Fatal(err)
448 }
449 if err := os.WriteFile("deps.go", fmtbuf, 0o666); err != nil {
450 log.Fatal(err)
451 }
452
453 // Also generate the data for the test.
454 for _, t := range [...]struct{ flag, filename string }{
455 {"-deps=true", "testdata/nethttp.deps"},
456 {`-f={{join .Imports "\n"}}`, "testdata/nethttp.imports"},
457 } {
458 stdout := new(bytes.Buffer)
459 cmd := exec.Command("go", "list", t.flag, "net/http")
460 cmd.Stdout = stdout
461 cmd.Stderr = os.Stderr
462 cmd.Env = append(os.Environ(), "CGO_ENABLED=0", "GOOS=linux", "GOARCH=amd64")
463 if err := cmd.Run(); err != nil {
464 log.Fatal(err)
465 }
466 if err := os.WriteFile(t.filename, stdout.Bytes(), 0666); err != nil {
467 log.Fatal(err)
468 }
469 }
470 }
471
472 // bootstrap returns the list of bootstrap packages out of the
473 // source of the dist command, along with the minimum toolchain
474 // version.
475 //
476 // We assume it is "var bootstrapDirs []string" in buildtool.go, and
477 // is a list of string literals, either package names or "dir/...".
478 // TODO(adonovan): find a more robust solution.
479 func bootstrap() ([]string, string) {
480 fset := token.NewFileSet()
481 filename := strings.TrimSpace(runGo("list", "-f={{.Dir}}/buildtool.go", "cmd/dist").String())
482 f, err := parser.ParseFile(fset, filename, nil, 0)
483 if err != nil {
484 log.Fatalf("can't parse buildtool.go file in cmd/dist package: %v", err)
485 }
486
487 const bootstrapVarName = "bootstrapDirs"
488 var (
489 args = []string{"list"} // go list command to expand bootstrap packages
490 version string
491 )
492 for _, decl := range f.Decls {
493 decl, ok := decl.(*ast.GenDecl)
494 if !ok {
495 continue
496 }
497 for _, spec := range decl.Specs {
498 spec, ok := spec.(*ast.ValueSpec)
499 if !ok {
500 continue
501 }
502 if len(spec.Names) != 1 {
503 continue
504 }
505 switch spec.Names[0].Name {
506 case bootstrapVarName:
507 // var bootstrapDirs = []string{ ... }
508 if len(spec.Values) != 1 {
509 log.Fatalf("%s: %s var spec has %d values, want 1",
510 fset.Position(spec.Pos()), len(spec.Values))
511 }
512 value0 := spec.Values[0]
513 lit, ok := value0.(*ast.CompositeLit)
514 if !ok {
515 log.Fatalf("%s: %s assigned from %T, want slice literal",
516 fset.Position(value0.Pos()), value0)
517 }
518 // Construct a go list command from the package patterns.
519 for _, elt := range lit.Elts {
520 lit, ok := elt.(*ast.BasicLit)
521 if !ok {
522 log.Fatalf("%s: element is %T, want string literal",
523 fset.Position(elt.Pos()), elt)
524 }
525 pattern, err := strconv.Unquote(lit.Value)
526 if err != nil {
527 log.Fatalf("%s: %v", fset.Position(elt.Pos()), err)
528 }
529 args = append(args, pattern)
530 }
531
532 case "minBootstrap":
533 // const minBootstrap = "go1.2.3"
534 lit := spec.Values[0].(*ast.BasicLit)
535 version, _ = strconv.Unquote(lit.Value)
536 }
537 }
538 }
539 if len(args) < 2 {
540 log.Fatalf("can't find var %s in buildtool.go file in cmd/dist package: %v",
541 bootstrapVarName, err)
542 }
543 if version == "" {
544 log.Fatalf("can't find const minBootstrap version in buildtool.go file in cmd/dist package: %v",
545 err)
546 }
547
548 return strings.Split(strings.TrimSpace(runGo(args...).String()), "\n"), version
549 }
550
551 func runGo(args ...string) *bytes.Buffer {
552 cmd := exec.Command("go", args...)
553 cmd.Env = append(os.Environ(), "CGO_ENABLED=0", "GOOS=linux", "GOARCH=amd64")
554 stdout, err := cmd.Output()
555 if err != nil {
556 log.Fatalf("%s: failed: %v", cmd, err)
557 }
558 return bytes.NewBuffer(stdout)
559 }