Commit 7765e59d67 for golang
commit 7765e59d678d66618dc2a9bd3ab5fb60b588f429
Author: Alan Donovan <adonovan@google.com>
Date: Wed Dec 2 14:39:42 2026 -0500
all: use go/types/exportdata instead of vendored gcexportdata
Replace the remaining uses of golang.org/x/tools/go/gcexportdata
(in go/internal/gcimporter, cmd/export, and
internal/analysis/gotestchecker) with direct calls to the new
go/types/exportdata package. All of them handle only i-format
export data produced by cmd/export or gotestchecker itself.
This removes gcexportdata and x/tools/internal/pkgbits from both
vendor trees, and x/tools/internal/exportdata from cmd/vendor.
The std vendor tree still contains x/tools/internal/exportdata,
as the vendored unitchecker still imports it directly.
For #69491
Change-Id: I50c46b0d75cb925f784354879cead067cb989a08
Reviewed-on: https://go-review.googlesource.com/c/go/+/869381
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Mark Freeman <mark@golang.org>
diff --git a/src/cmd/export/main.go b/src/cmd/export/main.go
index b180053f37..d159322825 100644
--- a/src/cmd/export/main.go
+++ b/src/cmd/export/main.go
@@ -21,11 +21,10 @@ import (
"go/parser"
"go/token"
"go/types"
+ "go/types/exportdata"
"log"
"os"
"strings"
-
- "golang.org/x/tools/go/gcexportdata"
)
const message = `export is a tool to write type information of Go programs.
@@ -108,15 +107,11 @@ func export(configFile string) error {
}
// Write export data.
- f, err := os.Create(cfg.Output)
+ data, err := exportdata.Encode(fset, pkg, exportdata.EncodeOptions{})
if err != nil {
return err
}
- if err := gcexportdata.Write(f, fset, pkg); err != nil {
- f.Close() // ignore error
- return err
- }
- return f.Close()
+ return os.WriteFile(cfg.Output, data, 0666)
}
func readConfig(filename string) (*config, error) {
@@ -153,13 +148,11 @@ func makeTypesImporter(cfg *config, fset *token.FileSet) types.Importer {
if !ok {
return nil, fmt.Errorf("can't resolve export %s", pkgPath)
}
- f, err := os.Open(cfgPath)
+ data, err := os.ReadFile(cfgPath)
if err != nil {
return nil, err
}
- defer f.Close()
- // TODO(adonovan): use go/types/exportdata.
- return gcexportdata.Read(f, fset, imports, pkgPath)
+ return exportdata.Decode(fset, pkgPath, data, exportdata.PackagesFromMap(imports), exportdata.DecodeOptions{})
})
}
diff --git a/src/cmd/vendor/golang.org/x/tools/go/gcexportdata/exportdata.go b/src/cmd/vendor/golang.org/x/tools/go/gcexportdata/exportdata.go
deleted file mode 100644
index 3493c5ff32..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/go/gcexportdata/exportdata.go
+++ /dev/null
@@ -1,153 +0,0 @@
-// Copyright 2011 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// This file locates the export data within compiler-produced archives.
-// It should be kept in sync with $GOROOT/src/internal/exportdata/exportdata.go.
-
-package gcexportdata
-
-import (
- "bufio"
- "fmt"
- "strings"
- // This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-)
-
-// findExportData positions the reader r at the beginning of the
-// export data section of an underlying cmd/compile created archive
-// file by reading from it. The reader must be positioned at the
-// start of the file before calling this function.
-// This returns the length of the export data in bytes.
-//
-// This function is needed by [gcexportdata.Read], which must
-// accept inputs produced by the last two releases of cmd/compile,
-// plus tip.
-func findExportData(r *bufio.Reader) (size int64, err error) {
- arsize, err := findPackageDefinition(r)
- if err != nil {
- return
- }
- size = int64(arsize)
-
- objapi, headers, err := readObjectHeaders(r)
- if err != nil {
- return
- }
- size -= int64(len(objapi))
- for _, h := range headers {
- size -= int64(len(h))
- }
-
- // Check for the binary export data section header "$$B\n".
- line, err := r.ReadSlice('\n')
- if err != nil {
- return
- }
- hdr := string(line)
- if hdr != "$$B\n" {
- err = fmt.Errorf("unknown export data header: %q", hdr)
- return
- }
- size -= int64(len(hdr))
-
- // For files with a binary export data header "$$B\n",
- // these are always terminated by an end-of-section marker "\n$$\n".
- // So the last bytes must always be this constant.
- //
- // The end-of-section marker is not a part of the export data itself.
- // Do not include these in size.
- //
- // It would be nice to have sanity check that the final bytes after
- // the export data are indeed the end-of-section marker. The split
- // of gcexportdata.NewReader and gcexportdata.Read make checking this
- // ugly so this package gives up enforcing this. The compiler and go/types
- // importer do enforce this, which seems good enough.
- const endofsection = "\n$$\n"
- size -= int64(len(endofsection))
-
- if size < 0 {
- err = fmt.Errorf("invalid size (%d) in the archive file: %d bytes remain without section headers (recompile package)", arsize, size)
- return
- }
-
- return
-}
-
-// findPackageDefinition positions the reader r at the beginning of a package
-// definition file ("__.PKGDEF") within a GC-created archive by reading
-// from it, and returns the size of the package definition file in the archive.
-//
-// The reader must be positioned at the start of the archive file before calling
-// this function, and "__.PKGDEF" is assumed to be the first file in the archive.
-//
-// See cmd/internal/archive for details on the archive format.
-func findPackageDefinition(r *bufio.Reader) (size int, err error) {
- // Uses ReadSlice to limit risk of malformed inputs.
-
- // Read first line to make sure this is an object file.
- line, err := r.ReadSlice('\n')
- if err != nil {
- err = fmt.Errorf("can't find export data (%v)", err)
- return
- }
-
- // Is the first line an archive file signature?
- if string(line) != "!<arch>\n" {
- err = fmt.Errorf("not the start of an archive file (%q)", line)
- return
- }
-
- // package export block should be first
- size = readArchiveHeader(r, "__.PKGDEF")
- if size <= 0 {
- err = fmt.Errorf("not a package file")
- return
- }
-
- return
-}
-
-// readObjectHeaders reads object headers from the reader. Object headers are
-// lines that do not start with an end-of-section marker "$$". The first header
-// is the objabi header. On success, the reader will be positioned at the beginning
-// of the end-of-section marker.
-//
-// It returns an error if any header does not fit in r.Size() bytes.
-func readObjectHeaders(r *bufio.Reader) (objapi string, headers []string, err error) {
- // line is a temporary buffer for headers.
- // Use bounded reads (ReadSlice, Peek) to limit risk of malformed inputs.
- var line []byte
-
- // objapi header should be the first line
- if line, err = r.ReadSlice('\n'); err != nil {
- err = fmt.Errorf("can't find export data (%v)", err)
- return
- }
- objapi = string(line)
-
- // objapi header begins with "go object ".
- if !strings.HasPrefix(objapi, "go object ") {
- err = fmt.Errorf("not a go object file: %s", objapi)
- return
- }
-
- // process remaining object header lines
- for {
- // check for an end of section marker "$$"
- line, err = r.Peek(2)
- if err != nil {
- return
- }
- if string(line) == "$$" {
- return // stop
- }
-
- // read next header
- line, err = r.ReadSlice('\n')
- if err != nil {
- return
- }
- headers = append(headers, string(line))
- }
-}
diff --git a/src/cmd/vendor/golang.org/x/tools/go/gcexportdata/exportdata_copy.go b/src/cmd/vendor/golang.org/x/tools/go/gcexportdata/exportdata_copy.go
deleted file mode 100644
index 4155c24053..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/go/gcexportdata/exportdata_copy.go
+++ /dev/null
@@ -1,89 +0,0 @@
-// Copyright 2026 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package gcexportdata
-
-import (
- "fmt"
- "go/token"
- "go/types"
- "sync"
-)
-
-// The declarations in this file are copied from internal/exportdata.
-
-const (
- // Enable debug during development: it adds some additional checks, and
- // prevents errors from being recovered.
- debug = false
-)
-
-func assert(cond bool) {
- if !cond {
- panic("internal error: assertion failed")
- }
-}
-
-func errorf(format string, args ...any) {
- panic(fmt.Sprintf(format, args...))
-}
-
-// Synthesize a token.Pos
-type fakeFileSet struct {
- fset *token.FileSet
- files map[string]*fileInfo
-}
-
-type fileInfo struct {
- file *token.File
- lastline int
-}
-
-const maxlines = 64 * 1024
-
-func (s *fakeFileSet) pos(file string, line, column int) token.Pos {
- _ = column // TODO(mdempsky): Make use of column.
-
- // Since we don't know the set of needed file positions, we reserve maxlines
- // positions per file. We delay calling token.File.SetLines until all
- // positions have been calculated (by way of fakeFileSet.setLines), so that
- // we can avoid setting unnecessary lines. See also golang/go#46586.
- f := s.files[file]
- if f == nil {
- f = &fileInfo{file: s.fset.AddFile(file, -1, maxlines)}
- s.files[file] = f
- }
- if line > maxlines {
- line = 1
- }
- if line > f.lastline {
- f.lastline = line
- }
-
- // Return a fake position assuming that f.file consists only of newlines.
- return token.Pos(f.file.Base() + line - 1)
-}
-
-func (s *fakeFileSet) setLines() {
- fakeLinesOnce.Do(func() {
- fakeLines = make([]int, maxlines)
- for i := range fakeLines {
- fakeLines[i] = i
- }
- })
- for _, f := range s.files {
- f.file.SetLines(fakeLines[:f.lastline])
- }
-}
-
-var (
- fakeLines []int
- fakeLinesOnce sync.Once
-)
-
-type byPath []*types.Package
-
-func (a byPath) Len() int { return len(a) }
-func (a byPath) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
-func (a byPath) Less(i, j int) bool { return a[i].Path() < a[j].Path() }
diff --git a/src/cmd/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go b/src/cmd/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go
deleted file mode 100644
index b6bd69a94b..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go
+++ /dev/null
@@ -1,223 +0,0 @@
-// Copyright 2016 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Package gcexportdata provides functions for writing and reading
-// export data, a serialized representation of a [types.Package].
-// It describes the API of a Go package, including the names,
-// kinds, types, and locations of all exported declarations.
-//
-// Files produced by [Write] contain only export data and may be passed
-// directly to [Read].
-//
-// Export data may also be obtained using "go list -export -json".
-// The Export field names a file whose format depends on the Go version:
-//
-// - Before Go 1.28, the file is a compiler-produced archive. Use
-// [NewReader] to extract its export data before calling [Read].
-// - Starting with Go 1.28, the file contains only export data. Pass it
-// directly to [Read]; [NewReader] is unnecessary.
-//
-// The export data format evolves with each Go release. As a matter of
-// policy, [Read] supports reading files produced by only the last two
-// Go releases plus tip; see https://go.dev/issue/68898.
-//
-// The name of this package reflects its origins at a time when
-// cmd/compile was named gc, and [Read] parsed export data
-// from .a archives produced by the Go compiler.
-// Support for compiler-produced export data will be removed in Go 1.29.
-// This does not affect files produced by [Write] or by "go list -export"
-// with Go 1.28 or later.
-// For more information on the compiler's export data, see the
-// "Export" section in the GOROOT/src/cmd/compile/README file.
-//
-// # Deprecations
-//
-// The [NewImporter], [Find], and [NewReader] functions are deprecated
-// and should not be used in new code.
-// The [WriteBundle] and [ReadBundle] functions are obsolete experiments
-// and are no longer supported (https://go.dev/issue/69573).
-package gcexportdata
-
-import (
- "bufio"
- "bytes"
- "encoding/json"
- "fmt"
- "go/token"
- "go/types"
- "io"
- "os/exec"
-
- "golang.org/x/tools/internal/exportdata"
-)
-
-// Find returns the name of an object (.o) or archive (.a) file
-// containing type information for the specified import path,
-// using the go command.
-// If no file was found, an empty filename is returned.
-//
-// A relative srcDir is interpreted relative to the current working directory.
-//
-// Find also returns the package's resolved (canonical) import path,
-// reflecting the effects of srcDir and vendoring on importPath.
-//
-// Deprecated: Use the higher-level API in golang.org/x/tools/go/packages,
-// which is more efficient.
-func Find(importPath, srcDir string) (filename, path string) {
- cmd := exec.Command("go", "list", "-json", "-export", "--", importPath)
- cmd.Dir = srcDir
- out, err := cmd.Output()
- if err != nil {
- return "", ""
- }
- var data struct {
- ImportPath string
- Export string
- }
- json.Unmarshal(out, &data)
- return data.Export, data.ImportPath
-}
-
-// NewReader returns a reader for export data read from r. Export data
-// may be read from:
-//
-// - The export data section of an object (.o) or archive file (.a).
-// In this case, the new reader may provide additional trailing data
-// beyond the end of the export data.
-// - The output of [Write] or "go list -export" with Go 1.28 or later.
-// In this case, the new reader contains no trailing data.
-//
-// Deprecated: This package will stop supporting the reading of export
-// data from compiler-produced archive files in Go 1.29. To read files
-// produced by [Write] or "go list -export" with Go 1.28 or later, use
-// [Read] directly instead.
-func NewReader(r io.Reader) (io.Reader, error) {
- buf := bufio.NewReader(r)
- peek, err := buf.Peek(1)
- if err != nil {
- return nil, err
- }
- if peek[0] == 'i' {
- // We were given an output of cmd/export. The entire file is
- // export data.
- return buf, nil
- }
-
- size, err := findExportData(buf)
- if err != nil {
- return nil, err
- }
-
- // We were given an archive and found the __.PKGDEF in it.
- // This tells us the size of the export data, and we don't
- // need to return the entire file.
- return &io.LimitedReader{
- R: buf,
- N: size,
- }, nil
-}
-
-// readAll works the same way as io.ReadAll, but avoids allocations and copies
-// by preallocating a byte slice of the necessary size if the size is known up
-// front. This is always possible when the input is an archive. In that case,
-// NewReader will return the known size using an io.LimitedReader.
-func readAll(r io.Reader) ([]byte, error) {
- if lr, ok := r.(*io.LimitedReader); ok {
- data := make([]byte, lr.N)
- _, err := io.ReadFull(lr, data)
- return data, err
- }
- return io.ReadAll(r)
-}
-
-// Read reads export data from in, decodes it, and returns type
-// information for the package.
-//
-// Read is capable of reading export data produced by [Write] at the
-// same source code version, or by "go list -export" using the last two
-// Go releases (plus tip). Reading files from older Go releases may
-// produce an error.
-//
-// Files produced by [Write] or "go list -export" with Go 1.28 or later
-// may be passed directly to Read. For compiler-produced archives, use
-// [NewReader] to extract the export data first. See the package
-// documentation for the supported formats.
-//
-// The package path (effectively its linker symbol prefix) is
-// specified by path, since unlike the package name, this information
-// may not be recorded in the export data.
-//
-// File position information is added to fset.
-//
-// Read may inspect and add to the imports map to ensure that references
-// within the export data to other packages are consistent. The caller
-// must ensure that imports[path] does not exist, or exists but is
-// incomplete (see types.Package.Complete), and Read inserts the
-// resulting package into this map entry.
-//
-// On return, the state of the reader is undefined.
-func Read(in io.Reader, fset *token.FileSet, imports map[string]*types.Package, path string) (*types.Package, error) {
- data, err := readAll(in)
- if err != nil {
- return nil, fmt.Errorf("reading export data for %q: %v", path, err)
- }
-
- if bytes.HasPrefix(data, []byte("!<arch>")) {
- return nil, fmt.Errorf("can't read export data for %q directly from an archive file (call gcexportdata.NewReader first to extract export data)", path)
- }
-
- // The indexed export format starts with an 'i'; the older
- // binary export format starts with a 'c', 'd', or 'v'
- // (from "version"). Select appropriate importer.
- if len(data) > 0 {
- switch data[0] {
- case 'v', 'c', 'd':
- // binary, produced by cmd/compile till go1.10
- return nil, fmt.Errorf("binary (%c) import format is no longer supported", data[0])
-
- case 'i':
- // indexed, produced by cmd/compile till go1.19,
- // and also by [Write]. Starting with go1.28,
- // go list -export runs cmd/export, which emits this format.
- return exportdata.Decode(fset, path, data, exportdata.PackagesFromMap(imports), exportdata.DecodeOptions{})
-
- case 'u':
- // unified, produced by cmd/compile since go1.20.
- // Produced by go list -export from go1.20 to go1.27.
- _, pkg, err := uImportData(fset, imports, data[1:], path)
- return pkg, err
-
- default:
- l := min(len(data), 10)
- return nil, fmt.Errorf("unexpected export data with prefix %q for path %s", string(data[:l]), path)
- }
- }
- return nil, fmt.Errorf("empty export data for %s", path)
-}
-
-// Write writes encoded type information for the specified package to out.
-// The FileSet provides file position information for named objects.
-func Write(out io.Writer, fset *token.FileSet, pkg *types.Package) error {
- if fset == nil {
- // For compatibility, tolerate a nil FileSet,
- // in which case position information is missing.
- fset = token.NewFileSet()
- }
- data, err := exportdata.Encode(fset, pkg, exportdata.EncodeOptions{})
- if err != nil {
- return err
- }
- _, err = out.Write(data) // data begins with 'i'
- return err
-}
-
-// Deprecated: ReadBundle is an unsupported obsolete experimental API. It returns an error.
-func ReadBundle(in io.Reader, fset *token.FileSet, imports map[string]*types.Package) ([]*types.Package, error) {
- return nil, fmt.Errorf("ReadBundle is an unsupported obsolete experimental API")
-}
-
-// Deprecated: WriteBundle is an unsupported obsolete experimental API. It returns an error.
-func WriteBundle(io.Writer, *token.FileSet, []*types.Package) error {
- return fmt.Errorf("WriteBundle is an unsupported obsolete experimental API")
-}
diff --git a/src/cmd/vendor/golang.org/x/tools/go/gcexportdata/importer.go b/src/cmd/vendor/golang.org/x/tools/go/gcexportdata/importer.go
deleted file mode 100644
index 37a7247e26..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/go/gcexportdata/importer.go
+++ /dev/null
@@ -1,75 +0,0 @@
-// Copyright 2016 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package gcexportdata
-
-import (
- "fmt"
- "go/token"
- "go/types"
- "os"
-)
-
-// NewImporter returns a new instance of the types.Importer interface
-// that reads type information from export data files written by gc.
-// The Importer also satisfies types.ImporterFrom.
-//
-// Export data files are located using "go build" workspace conventions
-// and the build.Default context.
-//
-// Use this importer instead of go/importer.For("gc", ...) to avoid the
-// version-skew problems described in the documentation of this package,
-// or to control the FileSet or access the imports map populated during
-// package loading.
-//
-// Deprecated: Use the higher-level API in golang.org/x/tools/go/packages,
-// which is more efficient.
-func NewImporter(fset *token.FileSet, imports map[string]*types.Package) types.ImporterFrom {
- return importer{fset, imports}
-}
-
-type importer struct {
- fset *token.FileSet
- imports map[string]*types.Package
-}
-
-func (imp importer) Import(importPath string) (*types.Package, error) {
- return imp.ImportFrom(importPath, "", 0)
-}
-
-func (imp importer) ImportFrom(importPath, srcDir string, mode types.ImportMode) (_ *types.Package, err error) {
- filename, path := Find(importPath, srcDir)
- if filename == "" {
- if importPath == "unsafe" {
- // Even for unsafe, call Find first in case
- // the package was vendored.
- return types.Unsafe, nil
- }
- return nil, fmt.Errorf("can't find import: %s", importPath)
- }
-
- if pkg, ok := imp.imports[path]; ok && pkg.Complete() {
- return pkg, nil // cache hit
- }
-
- // open file
- f, err := os.Open(filename)
- if err != nil {
- return nil, err
- }
- defer func() {
- f.Close()
- if err != nil {
- // add file name to error
- err = fmt.Errorf("reading export data: %s: %v", filename, err)
- }
- }()
-
- r, err := NewReader(f)
- if err != nil {
- return nil, err
- }
-
- return Read(r, imp.fset, imp.imports, path)
-}
diff --git a/src/cmd/vendor/golang.org/x/tools/go/gcexportdata/support.go b/src/cmd/vendor/golang.org/x/tools/go/gcexportdata/support.go
deleted file mode 100644
index 2610b992ca..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/go/gcexportdata/support.go
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2024 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package gcexportdata
-
-import (
- "bufio"
- "io"
- "strconv"
- "strings"
- // This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-)
-
-// Copy of $GOROOT/src/cmd/internal/archive.ReadHeader.
-func readArchiveHeader(b *bufio.Reader, name string) int {
- // architecture-independent object file output
- const HeaderSize = 60
-
- var buf [HeaderSize]byte
- if _, err := io.ReadFull(b, buf[:]); err != nil {
- return -1
- }
- aname := strings.Trim(string(buf[0:16]), " ")
- if !strings.HasPrefix(aname, name) {
- return -1
- }
- asize := strings.Trim(string(buf[48:58]), " ")
- i, _ := strconv.Atoi(asize)
- return i
-}
diff --git a/src/cmd/vendor/golang.org/x/tools/go/gcexportdata/ureader.go b/src/cmd/vendor/golang.org/x/tools/go/gcexportdata/ureader.go
deleted file mode 100644
index e6c797d7bf..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/go/gcexportdata/ureader.go
+++ /dev/null
@@ -1,856 +0,0 @@
-// Copyright 2021 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// This file reads the unified export data emitted by cmd/compile until go1.27.
-// (Derived from go/internal/gcimporter/ureader.go.)
-
-package gcexportdata
-
-import (
- "fmt"
- "go/token"
- "go/types"
- "sort"
- "strings"
-
- "golang.org/x/tools/internal/pkgbits"
- // This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-)
-
-// A pkgReader holds the shared state for reading a unified IR package
-// description.
-type pkgReader struct {
- pkgbits.PkgDecoder
-
- fake fakeFileSet
-
- ctxt *types.Context
- imports map[string]*types.Package // previously imported packages, indexed by path
-
- // lazily initialized arrays corresponding to the unified IR
- // PosBase, Pkg, and Type sections, respectively.
- posBases []string // position bases (i.e., file names)
- pkgs []*types.Package
- typs []types.Type
-
- // laterFns holds functions that need to be invoked at the end of
- // import reading.
- //
- // TODO(mdempsky): Is it safe to have a single "later" slice or do
- // we need to have multiple passes? See comments on CL 386002 and
- // go.dev/issue/52104.
- laterFns []func()
- // laterFors is used in case of 'type A B' to ensure that B is processed before A.
- laterFors map[types.Type]int
-
- // ifaces holds a list of constructed Interfaces, which need to have
- // Complete called after importing is done.
- ifaces []*types.Interface
-}
-
-// later adds a function to be invoked at the end of import reading.
-func (pr *pkgReader) later(fn func()) {
- pr.laterFns = append(pr.laterFns, fn)
-}
-
-// See cmd/compile/internal/noder.derivedInfo.
-type derivedInfo struct {
- idx pkgbits.Index
-}
-
-// See cmd/compile/internal/noder.typeInfo.
-type typeInfo struct {
- idx pkgbits.Index
- derived bool
-}
-
-func uImportData(fset *token.FileSet, imports map[string]*types.Package, data []byte, path string) (_ int, pkg *types.Package, err error) {
- if !debug {
- defer func() {
- if x := recover(); x != nil {
- err = fmt.Errorf("internal error in importing %q (%v); please report an issue", path, x)
- }
- }()
- }
-
- s := string(data)
- input := pkgbits.NewPkgDecoder(path, s)
- pkg = readUnifiedPackage(fset, nil, imports, input)
- return
-}
-
-// laterFor adds a function to be invoked at the end of import reading, and records the type that function is finishing.
-func (pr *pkgReader) laterFor(t types.Type, fn func()) {
- if pr.laterFors == nil {
- pr.laterFors = make(map[types.Type]int)
- }
- pr.laterFors[t] = len(pr.laterFns)
- pr.laterFns = append(pr.laterFns, fn)
-}
-
-// readUnifiedPackage reads a package description from the given
-// unified IR export data decoder.
-func readUnifiedPackage(fset *token.FileSet, ctxt *types.Context, imports map[string]*types.Package, input pkgbits.PkgDecoder) *types.Package {
- pr := pkgReader{
- PkgDecoder: input,
-
- fake: fakeFileSet{
- fset: fset,
- files: make(map[string]*fileInfo),
- },
-
- ctxt: ctxt,
- imports: imports,
-
- posBases: make([]string, input.NumElems(pkgbits.RelocPosBase)),
- pkgs: make([]*types.Package, input.NumElems(pkgbits.RelocPkg)),
- typs: make([]types.Type, input.NumElems(pkgbits.RelocType)),
- }
- defer pr.fake.setLines()
-
- r := pr.newReader(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
- pkg := r.pkg()
- if r.Version().Has(pkgbits.HasInit) {
- r.Bool()
- }
-
- for i, n := 0, r.Len(); i < n; i++ {
- // As if r.obj(), but avoiding the Scope.Lookup call,
- // to avoid eager loading of imports.
- r.Sync(pkgbits.SyncObject)
- if r.Version().Has(pkgbits.DerivedFuncInstance) {
- assert(!r.Bool())
- }
- r.p.objIdx(r.Reloc(pkgbits.RelocObj))
- assert(r.Len() == 0)
- }
-
- r.Sync(pkgbits.SyncEOF)
-
- for _, fn := range pr.laterFns {
- fn()
- }
-
- for _, iface := range pr.ifaces {
- iface.Complete()
- }
-
- // Imports() of pkg are all of the transitive packages that were loaded.
- var imps []*types.Package
- for _, imp := range pr.pkgs {
- if imp != nil && imp != pkg {
- imps = append(imps, imp)
- }
- }
- sort.Sort(byPath(imps))
- pkg.SetImports(imps)
-
- pkg.MarkComplete()
- return pkg
-}
-
-// A reader holds the state for reading a single unified IR element
-// within a package.
-type reader struct {
- pkgbits.Decoder
-
- p *pkgReader
-
- dict *readerDict
-}
-
-// A readerDict holds the state for type parameters that parameterize
-// the current unified IR element.
-type readerDict struct {
- rtbounds []typeInfo // contains constraint types for each parameter in rtparams
- rtparams []*types.TypeParam // contains receiver type parameters for an element
-
- tbounds []typeInfo // contains constraint types for each parameter in tparams
- tparams []*types.TypeParam // contains type parameters for an element
-
- // derived is a slice of types derived from tparams, which may be
- // instantiated while reading the current element.
- derived []derivedInfo
- derivedTypes []types.Type // lazily instantiated from derived
-}
-
-func (pr *pkgReader) newReader(k pkgbits.RelocKind, idx pkgbits.Index, marker pkgbits.SyncMarker) *reader {
- return &reader{
- Decoder: pr.NewDecoder(k, idx, marker),
- p: pr,
- }
-}
-
-func (pr *pkgReader) tempReader(k pkgbits.RelocKind, idx pkgbits.Index, marker pkgbits.SyncMarker) *reader {
- return &reader{
- Decoder: pr.TempDecoder(k, idx, marker),
- p: pr,
- }
-}
-
-func (pr *pkgReader) retireReader(r *reader) {
- pr.RetireDecoder(&r.Decoder)
-}
-
-// @@@ Positions
-
-func (r *reader) pos() token.Pos {
- r.Sync(pkgbits.SyncPos)
- if !r.Bool() {
- return token.NoPos
- }
-
- // TODO(mdempsky): Delta encoding.
- posBase := r.posBase()
- line := r.Uint()
- col := r.Uint()
- return r.p.fake.pos(posBase, int(line), int(col))
-}
-
-func (r *reader) posBase() string {
- return r.p.posBaseIdx(r.Reloc(pkgbits.RelocPosBase))
-}
-
-func (pr *pkgReader) posBaseIdx(idx pkgbits.Index) string {
- if b := pr.posBases[idx]; b != "" {
- return b
- }
-
- var filename string
- {
- r := pr.tempReader(pkgbits.RelocPosBase, idx, pkgbits.SyncPosBase)
-
- // Within types2, position bases have a lot more details (e.g.,
- // keeping track of where //line directives appeared exactly).
- //
- // For go/types, we just track the file name.
-
- filename = r.String()
-
- if r.Bool() { // file base
- // Was: "b = token.NewTrimmedFileBase(filename, true)"
- } else { // line base
- pos := r.pos()
- line := r.Uint()
- col := r.Uint()
-
- // Was: "b = token.NewLineBase(pos, filename, true, line, col)"
- _, _, _ = pos, line, col
- }
- pr.retireReader(r)
- }
- b := filename
- pr.posBases[idx] = b
- return b
-}
-
-// @@@ Packages
-
-func (r *reader) pkg() *types.Package {
- r.Sync(pkgbits.SyncPkg)
- return r.p.pkgIdx(r.Reloc(pkgbits.RelocPkg))
-}
-
-func (pr *pkgReader) pkgIdx(idx pkgbits.Index) *types.Package {
- // TODO(mdempsky): Consider using some non-nil pointer to indicate
- // the universe scope, so we don't need to keep re-reading it.
- if pkg := pr.pkgs[idx]; pkg != nil {
- return pkg
- }
-
- pkg := pr.newReader(pkgbits.RelocPkg, idx, pkgbits.SyncPkgDef).doPkg()
- pr.pkgs[idx] = pkg
- return pkg
-}
-
-func (r *reader) doPkg() *types.Package {
- path := r.String()
- switch path {
- // cmd/compile emits path="main" for main packages because
- // that's the linker symbol prefix it used; but we need
- // the package's path as it would be reported by go list,
- // hence "main" below.
- // See test at go/packages.TestMainPackagePathInModeTypes.
- case "", "main":
- path = r.p.PkgPath()
- case "builtin":
- return nil // universe
- case "unsafe":
- return types.Unsafe
- }
-
- if pkg := r.p.imports[path]; pkg != nil {
- return pkg
- }
-
- name := r.String()
-
- pkg := types.NewPackage(path, name)
- r.p.imports[path] = pkg
-
- return pkg
-}
-
-// @@@ Types
-
-func (r *reader) typ() types.Type {
- return r.p.typIdx(r.typInfo(), r.dict)
-}
-
-func (r *reader) typInfo() typeInfo {
- r.Sync(pkgbits.SyncType)
- if r.Bool() {
- return typeInfo{idx: pkgbits.Index(r.Len()), derived: true}
- }
- return typeInfo{idx: r.Reloc(pkgbits.RelocType), derived: false}
-}
-
-func (pr *pkgReader) typIdx(info typeInfo, dict *readerDict) types.Type {
- idx := info.idx
- var where *types.Type
- if info.derived {
- where = &dict.derivedTypes[idx]
- idx = dict.derived[idx].idx
- } else {
- where = &pr.typs[idx]
- }
-
- if typ := *where; typ != nil {
- return typ
- }
-
- var typ types.Type
- {
- r := pr.tempReader(pkgbits.RelocType, idx, pkgbits.SyncTypeIdx)
- r.dict = dict
-
- typ = r.doTyp()
- assert(typ != nil)
- pr.retireReader(r)
- }
- // See comment in pkgReader.typIdx explaining how this happens.
- if prev := *where; prev != nil {
- return prev
- }
-
- *where = typ
- return typ
-}
-
-func (r *reader) doTyp() (res types.Type) {
- switch tag := pkgbits.CodeType(r.Code(pkgbits.SyncType)); tag {
- default:
- errorf("unhandled type tag: %v", tag)
- panic("unreachable")
-
- case pkgbits.TypeBasic:
- return types.Typ[r.Len()]
-
- case pkgbits.TypeNamed:
- obj, targs := r.obj()
- name := obj.(*types.TypeName)
- if len(targs) != 0 {
- t, _ := types.Instantiate(r.p.ctxt, name.Type(), targs, false)
- return t
- }
- return name.Type()
-
- case pkgbits.TypeTypeParam:
- n := r.Len()
- if n < len(r.dict.rtbounds) {
- return r.dict.rtparams[n]
- }
- return r.dict.tparams[n-len(r.dict.rtbounds)]
-
- case pkgbits.TypeArray:
- len := int64(r.Uint64())
- return types.NewArray(r.typ(), len)
- case pkgbits.TypeChan:
- dir := types.ChanDir(r.Len())
- return types.NewChan(dir, r.typ())
- case pkgbits.TypeMap:
- return types.NewMap(r.typ(), r.typ())
- case pkgbits.TypePointer:
- return types.NewPointer(r.typ())
- case pkgbits.TypeSignature:
- return r.signature(nil, nil, nil)
- case pkgbits.TypeSlice:
- return types.NewSlice(r.typ())
- case pkgbits.TypeStruct:
- return r.structType()
- case pkgbits.TypeInterface:
- return r.interfaceType()
- case pkgbits.TypeUnion:
- return r.unionType()
- }
-}
-
-func (r *reader) structType() *types.Struct {
- fields := make([]*types.Var, r.Len())
- var tags []string
- for i := range fields {
- pos := r.pos()
- pkg, name := r.selector()
- ftyp := r.typ()
- tag := r.String()
- embedded := r.Bool()
-
- fields[i] = types.NewField(pos, pkg, name, ftyp, embedded)
- if tag != "" {
- for len(tags) < i {
- tags = append(tags, "")
- }
- tags = append(tags, tag)
- }
- }
- return types.NewStruct(fields, tags)
-}
-
-func (r *reader) unionType() *types.Union {
- terms := make([]*types.Term, r.Len())
- for i := range terms {
- terms[i] = types.NewTerm(r.Bool(), r.typ())
- }
- return types.NewUnion(terms)
-}
-
-func (r *reader) interfaceType() *types.Interface {
- methods := make([]*types.Func, r.Len())
- embeddeds := make([]types.Type, r.Len())
- implicit := len(methods) == 0 && len(embeddeds) == 1 && r.Bool()
-
- for i := range methods {
- pos := r.pos()
- pkg, name := r.selector()
- mtyp := r.signature(nil, nil, nil)
- methods[i] = types.NewFunc(pos, pkg, name, mtyp)
- }
-
- for i := range embeddeds {
- embeddeds[i] = r.typ()
- }
-
- iface := types.NewInterfaceType(methods, embeddeds)
- if implicit {
- iface.MarkImplicit()
- }
-
- // We need to call iface.Complete(), but if there are any embedded
- // defined types, then we may not have set their underlying
- // interface type yet. So we need to defer calling Complete until
- // after we've called SetUnderlying everywhere.
- //
- // TODO(mdempsky): After CL 424876 lands, it should be safe to call
- // iface.Complete() immediately.
- r.p.ifaces = append(r.p.ifaces, iface)
-
- return iface
-}
-
-func (r *reader) signature(recv *types.Var, rtparams, tparams []*types.TypeParam) *types.Signature {
- r.Sync(pkgbits.SyncSignature)
-
- params := r.params(types.ParamVar)
- results := r.params(types.ResultVar)
- variadic := r.Bool()
-
- return types.NewSignatureType(recv, rtparams, tparams, params, results, variadic)
-}
-
-func (r *reader) params(kind types.VarKind) *types.Tuple {
- r.Sync(pkgbits.SyncParams)
-
- params := make([]*types.Var, r.Len())
- for i := range params {
- params[i] = r.param(kind)
- }
-
- return types.NewTuple(params...)
-}
-
-func (r *reader) param(kind types.VarKind) *types.Var {
- r.Sync(pkgbits.SyncParam)
-
- pos := r.pos()
- pkg, name := r.localIdent()
- typ := r.typ()
-
- param := types.NewParam(pos, pkg, name, typ)
- param.SetKind(kind) // ∈ {Recv,Param,Result}Var
- return param
-}
-
-// @@@ Objects
-
-func (r *reader) obj() (types.Object, []types.Type) {
- r.Sync(pkgbits.SyncObject)
-
- if r.Version().Has(pkgbits.DerivedFuncInstance) {
- assert(!r.Bool())
- }
-
- pkg, name := r.p.objIdx(r.Reloc(pkgbits.RelocObj))
- obj := pkgScope(pkg).Lookup(name)
-
- targs := make([]types.Type, r.Len())
- for i := range targs {
- targs[i] = r.typ()
- }
-
- return obj, targs
-}
-
-func (pr *pkgReader) objIdx(idx pkgbits.Index) (*types.Package, string) {
-
- var objPkg *types.Package
- var objName string
- var tag pkgbits.CodeObj
- {
- rname := pr.tempReader(pkgbits.RelocName, idx, pkgbits.SyncObject1)
-
- objPkg, objName = rname.qualifiedIdent()
- assert(objName != "")
-
- tag = pkgbits.CodeObj(rname.Code(pkgbits.SyncCodeObj))
- pr.retireReader(rname)
- }
-
- if tag == pkgbits.ObjStub {
- assert(objPkg == nil || objPkg == types.Unsafe)
- return objPkg, objName
- }
-
- // Ignore local types promoted to global scope (#55110).
- if _, suffix := splitVargenSuffix(objName); suffix != "" {
- return objPkg, objName
- }
-
- // TODO(mark): This, like the above splitVargenSuffix, is not ideal.
- // Ignore generic methods promoted to global scope.
- if strings.Contains(objName, ".") {
- return objPkg, objName
- }
-
- if objPkg.Scope().Lookup(objName) == nil {
- dict := pr.objDictIdx(idx)
-
- r := pr.newReader(pkgbits.RelocObj, idx, pkgbits.SyncObject1)
- r.dict = dict
-
- declare := func(obj types.Object) {
- objPkg.Scope().Insert(obj)
- }
-
- switch tag {
- default:
- panic("weird")
-
- case pkgbits.ObjAlias:
- pos := r.pos()
- var tparams []*types.TypeParam
- if r.Version().Has(pkgbits.AliasTypeParamNames) {
- tparams = r.typeParamNames(false)
- }
- typ := r.typ()
- tname := types.NewTypeName(pos, objPkg, objName, nil)
- types.NewAlias(tname, typ).SetTypeParams(tparams)
- declare(tname)
-
- case pkgbits.ObjConst:
- pos := r.pos()
- typ := r.typ()
- val := r.Value()
- declare(types.NewConst(pos, objPkg, objName, typ, val))
-
- case pkgbits.ObjFunc:
- pos := r.pos()
- if r.Version().Has(pkgbits.GenericMethods) {
- assert(!r.Bool()) // generic methods are read in their defining type
- }
- tparams := r.typeParamNames(false)
- sig := r.signature(nil, nil, tparams)
- declare(types.NewFunc(pos, objPkg, objName, sig))
-
- case pkgbits.ObjType:
- pos := r.pos()
-
- obj := types.NewTypeName(pos, objPkg, objName, nil)
- named := types.NewNamed(obj, nil, nil)
- declare(obj)
-
- named.SetTypeParams(r.typeParamNames(false))
-
- setUnderlying := func(underlying types.Type) {
- // If the underlying type is an interface, we need to
- // duplicate its methods so we can replace the receiver
- // parameter's type (#49906).
- if iface, ok := types.Unalias(underlying).(*types.Interface); ok && iface.NumExplicitMethods() != 0 {
- methods := make([]*types.Func, iface.NumExplicitMethods())
- for i := range methods {
- fn := iface.ExplicitMethod(i)
- sig := fn.Type().(*types.Signature)
-
- recv := types.NewVar(fn.Pos(), fn.Pkg(), "", named)
- recv.SetKind(types.RecvVar)
- methods[i] = types.NewFunc(fn.Pos(), fn.Pkg(), fn.Name(), types.NewSignatureType(recv, nil, nil, sig.Params(), sig.Results(), sig.Variadic()))
- }
-
- embeds := make([]types.Type, iface.NumEmbeddeds())
- for i := range embeds {
- embeds[i] = iface.EmbeddedType(i)
- }
-
- newIface := types.NewInterfaceType(methods, embeds)
- r.p.ifaces = append(r.p.ifaces, newIface)
- underlying = newIface
- }
-
- named.SetUnderlying(underlying)
- }
-
- // Since go.dev/cl/455279, we can assume rhs.Underlying() will
- // always be non-nil. However, to temporarily support users of
- // older snapshot releases, we continue to fallback to the old
- // behavior for now.
- //
- // TODO(mdempsky): Remove fallback code and simplify after
- // allowing time for snapshot users to upgrade.
- rhs := r.typ()
- if underlying := rhs.Underlying(); underlying != nil {
- setUnderlying(underlying)
- } else {
- pk := r.p
- pk.laterFor(named, func() {
- // First be sure that the rhs is initialized, if it needs to be initialized.
- delete(pk.laterFors, named) // prevent cycles
- if i, ok := pk.laterFors[rhs]; ok {
- f := pk.laterFns[i]
- pk.laterFns[i] = func() {} // function is running now, so replace it with a no-op
- f() // initialize RHS
- }
- setUnderlying(rhs.Underlying())
- })
- }
-
- if r.Version().Has(pkgbits.GenericMethods) {
- // V4 (go1.27.0) emitted all non-generic methods
- // before all generic ones, discarding source
- // order: a bug (go.dev/issue/81188).
- // V5 (go1.27.x) fixes it by emitting an explicit
- // index along with each method.
- type indexedMethod struct {
- index int // (or -1 in V4)
- fn *types.Func
- }
-
- var methods []indexedMethod
-
- // ordinary methods
- for range r.Len() {
- idx, m := r.method()
- methods = append(methods, indexedMethod{idx, m})
- }
-
- // generic methods
- for range r.Len() {
- // Careful: objIdx is used to read in package-scoped declarations, which
- // methods are not. Instead, decode it here. This makes it easier to
- // associate it with the type and avoids the main objIdx loop.
- idx := r.Reloc(pkgbits.RelocObj)
-
- r := pr.tempReader(pkgbits.RelocObj, idx, pkgbits.SyncObject1)
- r.dict = pr.objDictIdx(idx)
-
- pos := r.pos()
- assert(r.Bool()) // generic method
- pkg, name := r.selector()
- rtparams := r.typeParamNames(true)
- recv := r.param(types.RecvVar)
- methodIdx := -1
- if r.Version().Has(pkgbits.PreserveMethodOrder) {
- methodIdx = r.Len()
- }
- tparams := r.typeParamNames(false)
- sig := r.signature(recv, rtparams, tparams)
-
- pr.retireReader(r)
- methods = append(methods, indexedMethod{methodIdx, types.NewFunc(pos, pkg, name, sig)})
- }
-
- if r.Version().Has(pkgbits.PreserveMethodOrder) {
- sort.Slice(methods, func(i, j int) bool {
- return methods[i].index < methods[j].index
- })
- }
-
- for _, m := range methods {
- named.AddMethod(m.fn)
- }
-
- } else {
- for range r.Len() {
- _, m := r.method()
- named.AddMethod(m)
- }
- }
-
- case pkgbits.ObjVar:
- pos := r.pos()
- typ := r.typ()
- v := types.NewVar(pos, objPkg, objName, typ)
- v.SetKind(types.PackageVar)
- declare(v)
- }
- }
-
- return objPkg, objName
-}
-
-func (pr *pkgReader) objDictIdx(idx pkgbits.Index) *readerDict {
-
- var dict readerDict
-
- {
- r := pr.tempReader(pkgbits.RelocObjDict, idx, pkgbits.SyncObject1)
- if implicits := r.Len(); implicits != 0 {
- errorf("unexpected object with %v implicit type parameter(s)", implicits)
- }
-
- nreceivers := 0
- if r.Version().Has(pkgbits.GenericMethods) {
- nreceivers = r.Len()
- }
- nexplicits := r.Len()
-
- dict.rtbounds = make([]typeInfo, nreceivers)
- for i := range dict.rtbounds {
- dict.rtbounds[i] = r.typInfo()
- }
-
- dict.tbounds = make([]typeInfo, nexplicits)
- for i := range dict.tbounds {
- dict.tbounds[i] = r.typInfo()
- }
-
- dict.derived = make([]derivedInfo, r.Len())
- dict.derivedTypes = make([]types.Type, len(dict.derived))
- for i := range dict.derived {
- dict.derived[i] = derivedInfo{idx: r.Reloc(pkgbits.RelocType)}
- if r.Version().Has(pkgbits.DerivedInfoNeeded) {
- assert(!r.Bool())
- }
- }
-
- pr.retireReader(r)
- }
- // function references follow, but reader doesn't need those
-
- return &dict
-}
-
-func (r *reader) typeParamNames(isGenMeth bool) []*types.TypeParam {
- r.Sync(pkgbits.SyncTypeParamNames)
-
- // Note: This code assumes there are no implicit type parameters.
- // This is fine since it only reads exported declarations, which
- // never have implicits.
-
- var in []typeInfo
- var out *[]*types.TypeParam
- if isGenMeth {
- in = r.dict.rtbounds
- out = &r.dict.rtparams
- } else {
- in = r.dict.tbounds
- out = &r.dict.tparams
- }
-
- if len(in) == 0 {
- return nil
- }
-
- // Careful: Type parameter lists may have cycles. To allow for this,
- // we construct the type parameter list in two passes: first we
- // create all the TypeNames and TypeParams, then we construct and
- // set the bound type.
-
- // We have to save tparams outside of the closure, because typeParamNames
- // can be called multiple times with the same dictionary instance.
- tparams := make([]*types.TypeParam, len(in))
- *out = tparams
-
- for i := range in {
- pos := r.pos()
- pkg, name := r.localIdent()
-
- tname := types.NewTypeName(pos, pkg, name, nil)
- tparams[i] = types.NewTypeParam(tname, nil)
- }
-
- // The reader dictionary will continue mutating before we have time
- // to call delayed functions; make a local copy of the constraints.
- types := make([]types.Type, len(in))
- for i, info := range in {
- types[i] = r.p.typIdx(info, r.dict)
- }
-
- // This needs to happen later to make sure SetUnderlying has been called.
- r.p.later(func() {
- for i, typ := range types {
- tparams[i].SetConstraint(typ)
- }
- })
-
- return tparams
-}
-
-func (r *reader) method() (int, *types.Func) {
- r.Sync(pkgbits.SyncMethod)
- idx := -1
- if r.Version().Has(pkgbits.PreserveMethodOrder) {
- idx = r.Len()
- }
- pos := r.pos()
- pkg, name := r.selector()
-
- rparams := r.typeParamNames(false)
- sig := r.signature(r.param(types.RecvVar), rparams, nil)
-
- _ = r.pos() // TODO(mdempsky): Remove; this is a hacker for linker.go.
- return idx, types.NewFunc(pos, pkg, name, sig)
-}
-
-func (r *reader) qualifiedIdent() (*types.Package, string) { return r.ident(pkgbits.SyncSym) }
-func (r *reader) localIdent() (*types.Package, string) { return r.ident(pkgbits.SyncLocalIdent) }
-func (r *reader) selector() (*types.Package, string) { return r.ident(pkgbits.SyncSelector) }
-
-func (r *reader) ident(marker pkgbits.SyncMarker) (*types.Package, string) {
- r.Sync(marker)
- return r.pkg(), r.String()
-}
-
-// pkgScope returns pkg.Scope().
-// If pkg is nil, it returns types.Universe instead.
-//
-// TODO(mdempsky): Remove after x/tools can depend on Go 1.19.
-func pkgScope(pkg *types.Package) *types.Scope {
- if pkg != nil {
- return pkg.Scope()
- }
- return types.Universe
-}
-
-// See cmd/compile/internal/types.SplitVargenSuffix.
-func splitVargenSuffix(name string) (base, suffix string) {
- i := len(name)
- for i > 0 && name[i-1] >= '0' && name[i-1] <= '9' {
- i--
- }
- const dot = "·"
- if i >= len(dot) && name[i-len(dot):i] == dot {
- i -= len(dot)
- return name[:i], name[i:]
- }
- return name, ""
-}
diff --git a/src/cmd/vendor/golang.org/x/tools/internal/exportdata/bimport.go b/src/cmd/vendor/golang.org/x/tools/internal/exportdata/bimport.go
deleted file mode 100644
index d4cef2e798..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/internal/exportdata/bimport.go
+++ /dev/null
@@ -1,98 +0,0 @@
-// Copyright 2015 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// This file defines small helpers for the encoder and decoder.
-
-package exportdata
-
-import (
- "fmt"
- "go/token"
- "go/types"
- "sync"
- // This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-)
-
-const (
- // Enable debug during development: it adds some additional checks, and
- // prevents errors from being recovered.
- debug = false
-
- // If trace is set, debugging output is printed to std out.
- trace = false
-)
-
-func errorf(format string, args ...any) {
- panic(fmt.Sprintf(format, args...))
-}
-
-const deltaNewFile = -64 // see cmd/compile/internal/gc/bexport.go
-
-// Synthesize a token.Pos
-type fakeFileSet struct {
- fset *token.FileSet
- files map[string]*fileInfo
-}
-
-type fileInfo struct {
- file *token.File
- lastline int
-}
-
-const maxlines = 64 * 1024
-
-func (s *fakeFileSet) pos(file string, line, column int) token.Pos {
- _ = column // TODO(mdempsky): Make use of column.
-
- // Since we don't know the set of needed file positions, we reserve maxlines
- // positions per file. We delay calling token.File.SetLines until all
- // positions have been calculated (by way of fakeFileSet.setLines), so that
- // we can avoid setting unnecessary lines. See also golang/go#46586.
- f := s.files[file]
- if f == nil {
- f = &fileInfo{file: s.fset.AddFile(file, -1, maxlines)}
- s.files[file] = f
- }
- if line > maxlines {
- line = 1
- }
- if line > f.lastline {
- f.lastline = line
- }
-
- // Return a fake position assuming that f.file consists only of newlines.
- return token.Pos(f.file.Base() + line - 1)
-}
-
-func (s *fakeFileSet) setLines() {
- fakeLinesOnce.Do(func() {
- fakeLines = make([]int, maxlines)
- for i := range fakeLines {
- fakeLines[i] = i
- }
- })
- for _, f := range s.files {
- f.file.SetLines(fakeLines[:f.lastline])
- }
-}
-
-var (
- fakeLines []int
- fakeLinesOnce sync.Once
-)
-
-func chanDir(d int) types.ChanDir {
- // tag values must match the constants in cmd/compile/internal/gc/go.go
- switch d {
- case 1 /* Crecv */ :
- return types.RecvOnly
- case 2 /* Csend */ :
- return types.SendOnly
- case 3 /* Cboth */ :
- return types.SendRecv
- default:
- errorf("unexpected channel dir %d", d)
- return 0
- }
-}
diff --git a/src/cmd/vendor/golang.org/x/tools/internal/exportdata/codec.go b/src/cmd/vendor/golang.org/x/tools/internal/exportdata/codec.go
deleted file mode 100644
index d2c1e32b09..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/internal/exportdata/codec.go
+++ /dev/null
@@ -1,216 +0,0 @@
-// Copyright 2026 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Package exportdata provides a codec for type export data.
-// The [Encode] function returns an encoding of a [types.Package] that
-// may be decoded by calling [Decode].
-//
-// Issue https://go.dev/issue/69491 proposes to publish this package
-// in the go1.28 standard library at go/types/exportdata. Once the
-// package exists, this package will delegate to it and eventually
-// wither away.
-//
-// # Protocol stability
-//
-// The details of the encoding are not specified and it may change;
-// indeed it must change when new language features are introduced.
-// However, it is a versioned protocol, and Decode is guaranteed to
-// support data produced by [Encode] either at the exact same source
-// version or at a tagged version no older than the two most recent Go
-// toolchain releases. Older versions may be rejected.
-//
-// This package may be used to decode the files produced by the "go
-// list -export" command. (See also [golang.org/x/tools/go/packages.Load],
-// which may provide a more convenient interface for doing so.)
-//
-// This package's encoding, historically called "indexed" format, is
-// intentionally not compatible with the "unified" encoding used by
-// the Go compiler. (This avoids constraining the compiler; see
-// https://go.dev/issue/79427.)
-//
-// The encoding is deterministic: if the encoder is applied twice to
-// the same types.Package data structure, both encodings are equal.
-// This property may be important to avoid spurious changes in
-// applications such as build systems.
-//
-// Decoding followed by encoding does not necessarily reproduce the
-// exact same bytes. Importing an exported package may yield a
-// types.Package that, while it represents the same set of Go objects
-// as the original, may differ in the details of its internal
-// representation. Because of these differences, re-encoding the
-// imported package may yield a different, but equally valid, encoding
-// of the package.
-//
-// # Deep vs shallow
-//
-// One of the [EncodeOptions] controls whether the encoding is "deep"
-// or "shallow". A deep encoding describes all exported package-level
-// objects in the encoded package, along with all the objects that are
-// reachable from them through the type data structures, following
-// function parameters and results, methods, struct fields, and so on.
-// The indirect packages may be described incompletely. A deep
-// encoding is thus self-contained with respect to transitive
-// dependencies: when type checking a package, it suffices to decode
-// one "deep" export data file for each of its direct imports.
-//
-// The export data used by the Go compiler is also "deep". Because the
-// set of inputs is determined by the package's import dependencies
-// alone, and is not based on the contents of any file, deep export
-// data suits build systems (such as Bazel) that need to know each
-// action's inputs in advance, for example to distribute them to
-// remote workers.
-//
-// By contrast, a shallow encoding describes only the objects exported
-// from the encoded package; objects from packages that it imports,
-// either directly or indirectly, are referenced by name. This makes
-// the encoding asymptotically smaller, but not self-contained. When
-// decoding a shallow encoding, it is necessary to decode additional
-// files for transitive dependencies, though typically only a small
-// subset, because most imports do not contribute types to a package's
-// exported API. (Consider the "fmt" package: nearly every package
-// imports it and uses it within the bodies of its functions, yet few
-// packages refer to types from "fmt" in their own API.) Thus it may
-// be necessary to recursively obtain packages for those dependencies,
-// by decoding their export data, before the package itself can be
-// decoded.
-//
-// With shallow export data, the set of files needed to decode a
-// package is discovered only by decoding, so a build system that must
-// know each action's inputs in advance would have to supply the
-// entire transitive closure. Shallow export data therefore suits an
-// interactive tool that can read export data for any package on
-// demand from a local cache (such as gopls) better than a distributed
-// build system.
-//
-// # Canonical packages and objects
-//
-// The type checker's data structures, including [types.Package] and
-// [types.Object] use referential equality. Thus, a program that
-// decodes several packages must represent each package path by a
-// single canonical [types.Package], and each object within it by a
-// single canonical [types.Object]. Consequently, an object reached
-// through the export data of two different imports is the same
-// reference in both, just as if the packages had been type-checked
-// together from source.
-//
-// Conceptually, all decode operations share an import mapping from
-// each package path to its canonical types.Package. When [Decode]
-// encounters a reference to an object of another package, it consults
-// the mapping to find the [types.Package]. In "shallow" mode, it is
-// the application's responsibility to ensure that the dependency
-// package exists and is populated; in "deep" mode, a missing package
-// is created using [types.NewPackage] and then partially populated as
-// needed as a consequence of decoding the primary package.
-//
-// Decode does not manipulate the import mapping directly. It takes a
-// function, getPackages, that abstracts both the mapping and the
-// creation of new packages. For convenience, we provide
-// [PackagesFromMap], a simple implementation of this function based
-// on an ordinary map.
-//
-// # Miscellaneous
-//
-// It is valid to encode and decode packages containing type errors.
-// The codec will do its best to preserve the data structures, though
-// it does not guarantee to do so without loss.
-package exportdata
-
-import (
- "bytes"
- "fmt"
- "go/token"
- "go/types"
-)
-
-// Encode returns the encoding of pkg.
-// Positions of objects are interpreted using fset, which must be non-nil.
-func Encode(fset *token.FileSet, pkg *types.Package, opts EncodeOptions) ([]byte, error) {
- if fset == nil {
- panic("nil FileSet")
- }
- var buf bytes.Buffer
- buf.WriteByte('i')
- if err := iexportCommon(&buf, fset, opts.Shallow, iexportVersion, pkg); err != nil {
- return nil, err
- }
- return buf.Bytes(), nil
-}
-
-// EncodeOptions controls the encoding of export data by [Encode].
-type EncodeOptions struct {
- // Shallow causes the data to include only the package's own
- // objects, and to refer to other packages' objects
- // symbolically. This avoids redundantly re-encoding objects
- // from indirect dependencies at the cost of having to look up
- // (some) indirect dependencies during decoding.
- //
- // By default the data is "deep": it includes a complete
- // description of all objects referred to by the encoded
- // package, even if they are declared in a dependency. Thus
- // the decoder needs access only to export data for its direct
- // dependencies.
- Shallow bool
-}
-
-// Decode decodes export data for the package with the given path.
-// (The encoding does not record the path.)
-//
-// Decode calls getPackages once, before decoding any objects, with
-// a reference to each package mentioned by the data, including the
-// package being decoded, so that the caller may obtain them in
-// parallel. getPackages must return a slice of the same length
-// whose ith element is the canonical package for refs[i]; its path
-// and name must match. In deep mode the packages may be empty, and
-// Decode populates them. In shallow mode the packages for
-// dependencies must be complete. Any error returned by getPackages
-// is returned by Decode, unwrapped; this may be used to read only
-// the list of packages mentioned by the data.
-//
-// Position information is added to fset, which must be non-nil.
-//
-// The data must have been produced by [Encode], either at the exact
-// same source version, or at a tagged version no older than the two
-// most recent Go toolchain releases.
-func Decode(fset *token.FileSet, path string, data []byte, getPackages func([]PackageRef) ([]*types.Package, error), opts DecodeOptions) (*types.Package, error) {
- if fset == nil {
- panic("nil FileSet")
- }
- if len(data) == 0 {
- return nil, fmt.Errorf("decoding %q: export data is empty", path)
- }
- if data[0] != 'i' {
- return nil, fmt.Errorf("decoding %q: not indexed export data", path)
- }
- return iimportCommon(fset, getPackages, data[1:], path)
-}
-
-// A PackageRef identifies a package mentioned by export data.
-type PackageRef struct {
- Path, Name string
-}
-
-// DecodeOptions controls the decoding of export data by [Decode].
-type DecodeOptions struct {
- // for future use
-}
-
-// PackagesFromMap is a convenience function that returns a getPackages
-// function suitable for [Decode] that obtains packages from m,
-// a mapping from package path to canonical package, as used by
-// [go/importer] and gcexportdata. Each requested package that is not
-// found in m is created with [types.NewPackage] and inserted into m.
-func PackagesFromMap(m map[string]*types.Package) func([]PackageRef) ([]*types.Package, error) {
- return func(refs []PackageRef) ([]*types.Package, error) {
- pkgs := make([]*types.Package, len(refs))
- for i, ref := range refs {
- pkg, ok := m[ref.Path]
- if !ok {
- pkg = types.NewPackage(ref.Path, ref.Name)
- m[ref.Path] = pkg
- }
- pkgs[i] = pkg
- }
- return pkgs, nil
- }
-}
diff --git a/src/cmd/vendor/golang.org/x/tools/internal/exportdata/iexport.go b/src/cmd/vendor/golang.org/x/tools/internal/exportdata/iexport.go
deleted file mode 100644
index e755a67e52..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/internal/exportdata/iexport.go
+++ /dev/null
@@ -1,1825 +0,0 @@
-// Copyright 2019 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Indexed package export.
-//
-// The indexed export data format is an evolution of the previous
-// binary export data format. Its chief contribution is introducing an
-// index table, which allows efficient random access of individual
-// declarations and inline function bodies. In turn, this allows
-// avoiding unnecessary work for compilation units that import large
-// packages.
-//
-//
-// The top-level data format is structured as:
-//
-// Header struct {
-// Tag byte // 'i' = "indexed" format
-// Version uvarint
-// Shallow bool // since iexportVersionShallowFlag
-// StringSize uvarint
-// FileSize uvarint // since iexportVersionFullPos
-// DataSize uvarint
-// }
-//
-// Strings [StringSize]byte
-// Files [FileSize]byte // since iexportVersionFullPos; see File below
-// Data [DataSize]byte
-//
-// MainIndex []struct{
-// PkgPath stringOff
-// PkgName stringOff
-// PkgHeight uvarint
-//
-// Decls []struct{
-// Name stringOff
-// Offset declOff
-// }
-// }
-//
-// FileIndex []fileOff // since iexportVersionFullPos
-//
-// uvarint (or varint) means a uint64 (or int64) written out using
-// uvarint (or varint) encoding; bool means a uvarint 0 or 1.
-//
-// []T means a uvarint followed by that many T objects. In other
-// words:
-//
-// Len uvarint
-// Elems [Len]T
-//
-// stringOff means a uvarint that indicates an offset within the
-// Strings section. At that offset is another uvarint, followed by
-// that many bytes, which form the string value.
-//
-// fileOff means a uvarint that indicates the offset within the Files
-// section of a File record (see below).
-//
-// declOff means a uvarint that indicates an offset within the Data
-// section where the associated declaration can be found.
-//
-//
-// There are five kinds of declarations, distinguished by their first
-// byte:
-//
-// type Var struct {
-// Tag byte // 'V'
-// Pos Pos
-// Type typeOff
-// }
-//
-// type Func struct {
-// Tag byte // 'F' or 'G'
-// Pos Pos
-// TypeParams []typeOff // only present if Tag == 'G'
-// Signature Signature
-// }
-//
-// type Const struct {
-// Tag byte // 'C'
-// Pos Pos
-// Value Value
-// }
-//
-// type Type struct {
-// Tag byte // 'T' or 'U'
-// Pos Pos
-// TypeParams []typeOff // only present if Tag == 'U'
-// Underlying typeOff
-//
-// Methods []struct{ // omitted if Underlying is an interface type
-// Pos Pos
-// Name stringOff
-// Recv Param
-// Signature Signature
-// }
-// }
-//
-// type Alias struct {
-// Tag byte // 'A' or 'B'
-// Pos Pos
-// TypeParams []typeOff // only present if Tag == 'B'
-// Type typeOff
-// }
-//
-// // "Automatic" declaration of each typeparam
-// type TypeParam struct {
-// Tag byte // 'P'
-// Pos Pos
-// Implicit bool
-// Constraint typeOff
-// }
-//
-// typeOff means a uvarint that either indicates a predeclared type,
-// or an offset into the Data section. If the uvarint is less than
-// predeclReserved, then it indicates the index into the predeclared
-// types list (see predeclared in bexport.go for order). Otherwise,
-// subtracting predeclReserved yields the offset of a type descriptor.
-//
-// Value means a type, kind, and type-specific value. See
-// (*exportWriter).value for details.
-//
-//
-// There are several kinds of type descriptors, distinguished by an itag:
-//
-// type DefinedType struct {
-// Tag itag // definedType
-// Name stringOff
-// PkgPath stringOff
-// }
-//
-// type PointerType struct {
-// Tag itag // pointerType
-// Elem typeOff
-// }
-//
-// type SliceType struct {
-// Tag itag // sliceType
-// Elem typeOff
-// }
-//
-// type ArrayType struct {
-// Tag itag // arrayType
-// Len uint64
-// Elem typeOff
-// }
-//
-// type ChanType struct {
-// Tag itag // chanType
-// Dir uint64 // 1 RecvOnly; 2 SendOnly; 3 SendRecv
-// Elem typeOff
-// }
-//
-// type MapType struct {
-// Tag itag // mapType
-// Key typeOff
-// Elem typeOff
-// }
-//
-// type FuncType struct {
-// Tag itag // signatureType
-// PkgPath stringOff
-// Signature Signature
-// }
-//
-// type StructType struct {
-// Tag itag // structType
-// PkgPath stringOff
-// Fields []struct {
-// Pos Pos
-// Name stringOff
-// Type typeOff
-// Embedded bool
-// Note stringOff
-// }
-// }
-//
-// type InterfaceType struct {
-// Tag itag // interfaceType
-// PkgPath stringOff
-// Embeddeds []struct {
-// Pos Pos
-// Type typeOff
-// }
-// Methods []struct {
-// Pos Pos
-// Name stringOff
-// Signature Signature
-// }
-// }
-//
-// // Reference to a struct or interface literal of another
-// // package (shallow mode only; see typepath.go).
-// type ExternalType struct {
-// Tag itag // externalType
-// Ref LiteralRef
-// }
-//
-// type LiteralRef struct {
-// PkgPath stringOff
-// Root stringOff // name of exported package-level object
-// Steps []uvarint // component indices; see typePath
-// }
-//
-// // Reference to a type param declaration
-// type TypeParamType struct {
-// Tag itag // typeParamType
-// Name stringOff
-// PkgPath stringOff
-// }
-//
-// // Instantiation of a generic type (like List[T2] or List[int])
-// type InstanceType struct {
-// Tag itag // instanceType
-// Pos pos
-// TypeArgs []typeOff
-// BaseType typeOff
-// }
-//
-// type UnionType struct {
-// Tag itag // interfaceType
-// Terms []struct {
-// tilde bool
-// Type typeOff
-// }
-// }
-//
-//
-//
-// type Signature struct {
-// Params []Param
-// Results []Param
-// Variadic bool // omitted if Results is empty
-// }
-//
-// type Param struct {
-// Pos Pos
-// Name stringOff
-// Type typOff
-// }
-//
-// Since iexportVersionFullPos, position encoding is the same in deep
-// and shallow mode. A Pos encodes either NoPos or a (file, offset)
-// pair, where file is the unsigned index into FileIndex, and offset
-// is the unsigned byte offset. To exploit locality we delta-encode
-// adjacent offsets within a declaration or type descriptor, with
-// initial state (0, 0). Each Pos record has one of three forms:
-//
-// none
-// absolute (file, offset uint)
-// relative (Δoffset int)
-//
-// represented as follows:
-//
-// type Pos struct {
-// X varint
-// Offset uvarint // present iff X is positive odd
-// }
-//
-// X == -1 => none (NoPos, no state change)
-// X even => relative (same file, offset += X>>1)
-// X positive odd => absolute (file = X>>1, offset = Offset)
-//
-// Negative odd X values are invalid.
-// (Both 'none' and zero 'relative' records are rare in practice.
-//
-// Each element FileIndex[i] gives the offset within Files of the ith
-// File record:
-//
-// type File struct {
-// Name stringOff
-// Size uvarint
-// LineCount uvarint
-// Lines []struct {
-// DeltaIndex uvarint
-// ResidualOffset varint
-// }
-// Infos []struct {
-// DeltaOffset uvarint
-// Filename stringOff
-// Line uvarint
-// Column uvarint
-// }
-// }
-//
-// Lines is a sparse table of the start offsets of (only) the lines
-// that contain a position mentioned in the data, in increasing order.
-// Each element encodes a (0-based) line index and its start offset
-// relative to the previous element (initially (0, 0)): DeltaIndex is
-// index - prev.index, and ResidualOffset is the residual of offset
-// relative to the prediction prev.offset + DeltaIndex*avg, where
-// avg = Size / max(1, LineCount) is the mean line length.
-// See [writeLines].
-//
-// Infos is a synthesized list of //line directive information, in the
-// form of arguments to [token.File.AddLineColumnInfo] (Column 0 means
-// unknown), with offsets delta-encoded relative to the previous entry
-// (initially 0). The entries do not generally correspond to the
-// original directives, which may lie on unrecorded lines, but cause
-// the decoder's token.File to compute the same adjusted position as
-// the original for every mentioned position. See [writeLineInfos].
-//
-// See [exportWriter.posV3] and [iexporter.encodeFile] for the implementation.
-//
-// In earlier versions, deep mode used [exportWriter.posV1], in which
-// Pos encodes a file:line:column triple, incorporating a simple delta
-// encoding scheme within a data object. (Earlier shallow data,
-// which has no compatibility guarantee, used an encoding that is no
-// longer supported.)
-
-package exportdata
-
-import (
- "bytes"
- "encoding/binary"
- "fmt"
- "go/constant"
- "go/token"
- "go/types"
- "io"
- "math"
- "math/big"
- "reflect"
- "slices"
- "sort"
- "strconv"
- "strings"
- // This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-)
-
-// iexportCommon encodes export data (without the leading 'i' tag byte).
-// In principle this operation can only fail if out.Write fails,
-// but that's impossible for bytes.Buffer---and as a matter of
-// fact iexportCommon doesn't even check for I/O errors.
-// TODO(adonovan): handle I/O errors properly.
-func iexportCommon(out io.Writer, fset *token.FileSet, shallow bool, version int, pkg *types.Package) (err error) {
- if !debug {
- defer func() {
- if e := recover(); e != nil {
- if ierr, ok := e.(internalError); ok {
- // internalError usually means we exported a
- // bad go/types data structure: a violation
- // of an implicit precondition of Export.
- err = ierr
- return
- }
- // Not an internal error; panic again.
- panic(e)
- }
- }()
- }
-
- p := iexporter{
- fset: fset,
- version: version,
- shallow: shallow,
- allPkgs: map[*types.Package]bool{},
- stringIndex: map[string]uint64{},
- declIndex: map[types.Object]uint64{},
- tparamNames: map[types.Object]string{},
- typIndex: map[types.Type]uint64{},
- localpkg: pkg,
- }
-
- for i, pt := range predeclared() {
- p.typIndex[pt] = uint64(i)
- }
- if len(p.typIndex) > predeclReserved {
- panic(internalErrorf("too many predeclared types: %d > %d", len(p.typIndex), predeclReserved))
- }
-
- // Initialize work queue with exported declarations.
- scope := pkg.Scope()
- for _, name := range scope.Names() {
- if token.IsExported(name) {
- p.pushDecl(scope.Lookup(name))
- }
- }
-
- // Loop until no more work.
- for !p.declTodo.empty() {
- p.doDecl(p.declTodo.popHead())
- }
-
- // Encode the table of files referenced by posV3 positions.
- // (p.files is empty in earlier versions.)
- var files intWriter
- fileOffset := make([]uint64, len(p.files)) // fileOffset[i] is offset in files of p.files[i]
- for i, fp := range p.files {
- fileOffset[i] = uint64(files.Len())
- p.encodeFile(&files, fp.file, fp.needed)
- }
-
- // Append indices to data0 section.
- dataLen := uint64(p.data0.Len())
- w := p.newWriter()
- w.writeIndex(p.declIndex)
- if p.version >= iexportVersionFullPos {
- w.uint64(uint64(len(fileOffset)))
- for _, offset := range fileOffset {
- w.uint64(offset)
- }
- }
- w.flush()
-
- // Assemble header.
- var hdr intWriter
- hdr.uint64(uint64(p.version))
- if p.version >= iexportVersionShallowFlag {
- hdr.bool(shallow)
- }
- hdr.uint64(uint64(p.strings.Len()))
- if p.version >= iexportVersionFullPos || p.shallow {
- hdr.uint64(uint64(files.Len()))
- }
- hdr.uint64(dataLen)
-
- // Flush output.
- if buf, ok := out.(*bytes.Buffer); ok {
- buf.Grow(hdr.Len() + p.strings.Len() + files.Len() + p.data0.Len())
- }
- io.Copy(out, &hdr)
- io.Copy(out, &p.strings)
- if p.version >= iexportVersionFullPos {
- io.Copy(out, &files)
- }
- io.Copy(out, &p.data0)
-
- return nil
-}
-
-// encodeFile writes to w a File record sufficient to faithfully
-// restore position information (both raw and //line-adjusted) for all
-// needed offsets in file.
-// Sorts and compacts the underlying array of needed.
-func (p *iexporter) encodeFile(w *intWriter, file *token.File, offsets []uint32) {
- _ = offsets[0] // precondition: some offsets are needed
-
- // Sort the set of needed offsets and remove duplicates.
- slices.Sort(offsets)
- offsets = slices.Compact(offsets)
-
- size := file.Size()
- allLines := file.Lines()
-
- w.uint64(p.stringOff(file.Name()))
- w.uint64(uint64(size))
- w.uint64(uint64(len(allLines)))
-
- avg := size / max(1, len(allLines)) // be defensive of synthetic positions in empty files
- lines := sparseLines(allLines, offsets)
- writeLines(w, avg, lines)
- writeLineInfos(p, w, file, offsets, lines)
-}
-
-// A lineStart records the byte offset of the start of a (0-based) line.
-type lineStart struct{ index, offset int }
-
-// sparseLines returns the start offsets of only those lines in allLines
-// that contain at least one of the sorted needed offsets.
-func sparseLines(allLines []int, needed []uint32) []lineStart {
- if len(allLines) == 0 {
- return nil
- }
- var sparse []lineStart
- from := 0 // index in allLines of the first line after sparse's last entry
- for _, off := range needed {
- o := int(off)
- if from > 0 && o < allLines[from] {
- continue // same line as previous offset
- }
- // Find the last line in allLines[from:] starting at or before o.
- i, exact := slices.BinarySearch(allLines[from:], o)
- if !exact {
- i--
- }
- if i < 0 {
- continue // o precedes allLines[0]
- }
- index := from + i
- sparse = append(sparse, lineStart{index: index, offset: allLines[index]})
- from = index + 1
- if from == len(allLines) {
- break // remaining offsets are all on the last line
- }
- }
- return sparse
-}
-
-// writeLines writes a sparse list of line starts, in increasing
-// order, as (index, offset) pairs delta-encoded relative to the
-// previous pair (initially (0, 0)). Each offset is encoded as the
-// residual relative to the prediction that lines have length avg.
-// See [readLines].
-func writeLines(w *intWriter, avg int, lines []lineStart) {
- w.uint64(uint64(len(lines)))
- var prev lineStart
- for _, line := range lines {
- w.uint64(uint64(line.index - prev.index))
- w.int64(int64(line.offset - predictLineStart(prev, line.index, avg)))
- prev = line
- }
-}
-
-// predictLineStart predicts the start offset of the line with the
-// specified (0-based) index, given the previous line start and the
-// mean line length.
-func predictLineStart(prev lineStart, index, avg int) int {
- return prev.offset + (index-prev.index)*avg
-}
-
-// mayHaveLineInfos reports whether file may have alternative
-// position information (from //line directives). If it reports
-// false, adjusted and unadjusted positions are equal throughout file.
-//
-// The go/token API provides no way to ask this question, so we use
-// reflection to inspect the unexported field token.File.infos, if
-// present; otherwise we conservatively report true. This avoids the
-// cost of computing the adjusted position of every needed offset,
-// which is substantial (+15% deep encoding time for std).
-// (FileSet.Write would expose the infos without the hack, but it
-// clones every line table: +8% time and +35% allocation.)
-//
-// The read of infos is not synchronized by token.File's mutex, but
-// infos is appended to only during parsing, which is complete
-// before export.
-//
-// TODO(adonovan): when this code moves to std, use go/token internals.
-func mayHaveLineInfos(file *token.File) bool {
- if fileInfosField < 0 {
- return true // unexpected layout
- }
- return reflect.ValueOf(file).Elem().Field(fileInfosField).Len() > 0
-}
-
-// fileInfosField is the index of the field token.File.infos,
-// or -1 if token.File has no such slice field.
-// (Reflection is memory-safe, so there is no need to check
-// the rest of the layout.)
-var fileInfosField = func() int {
- f, ok := reflect.TypeFor[token.File]().FieldByName("infos")
- if !ok || f.Type.Kind() != reflect.Slice {
- return -1
- }
- return f.Index[0]
-}()
-
-// A lineInfo represents one synthesized [token.File.AddLineColumnInfo] entry:
-// at unadjusted line rawLine (and byte offset alt.Offset), the adjusted
-// position is alt.
-type lineInfo struct {
- rawLine int
- alt token.Position
-}
-
-// writeLineInfos synthesizes and writes the //line directive information
-// (alternative positions; see [token.File.AddLineColumnInfo]) needed to
-// reconstruct the adjusted position of each needed offset.
-//
-// Most files have no //line directives, and cost a single zero byte.
-//
-// The go/token API provides no way to enumerate a file's line infos;
-// moreover, an actual directive's offset may lie on a line omitted from
-// the sparse line table, which would skew line deltas in the decoder.
-// Instead, we simulate the decoder's computation of the adjusted
-// position at each needed offset, and emit an entry (at that offset)
-// wherever the simulation disagrees with the actual adjusted position.
-// Because entries are located only at needed offsets, whose lines are
-// faithfully recorded by the sparse line table, the decoder's
-// token.File computes the exact same adjusted positions.
-func writeLineInfos(p *iexporter, w *intWriter, file *token.File, needed []uint32, lines []lineStart) {
- if len(lines) == 0 || !mayHaveLineInfos(file) {
- w.uint64(0)
- return
- }
-
- var (
- infos []lineInfo
- prev *lineInfo
- lineIdx = 0
- size = file.Size()
- name = file.Name()
- )
- for _, off := range needed {
- o := int(off)
- if o < lines[0].offset {
- continue // precedes first line
- }
- if o >= size {
- // Every object's Pos is at an identifier, so o < size in
- // valid Go. An EOF position (possible after a syntax error)
- // cannot be passed to AddLineColumnInfo, which requires o < size.
- break
- }
- for lineIdx+1 < len(lines) && o >= lines[lineIdx+1].offset {
- lineIdx++
- }
- line := lines[lineIdx]
- raw := token.Position{
- Filename: name,
- Offset: o,
- Line: line.index + 1,
- Column: o - line.offset + 1,
- }
- want := file.PositionFor(file.Pos(o), true)
- if adjust(prev, raw) != want {
- infos = append(infos, lineInfo{rawLine: raw.Line, alt: want})
- prev = &infos[len(infos)-1]
- }
- }
-
- w.uint64(uint64(len(infos)))
- prevOffset := 0
- for _, info := range infos {
- w.uint64(uint64(info.alt.Offset - prevOffset))
- w.uint64(p.stringOff(info.alt.Filename))
- w.uint64(uint64(info.alt.Line))
- w.uint64(uint64(info.alt.Column))
- prevOffset = info.alt.Offset
- }
-}
-
-// adjust returns the adjusted position that the decoder's token.File
-// will compute for an offset whose unadjusted position is raw, given
-// that info (if non-nil) is the closest preceding lineInfo.
-//
-// It must agree with the private (*token.File).unpack method in
-// $GOROOT/src/go/token/position.go; this is checked by TestPositions.
-func adjust(info *lineInfo, raw token.Position) token.Position {
- if info == nil {
- return raw // no line info: adjusted == unadjusted
- }
- d := raw.Line - info.rawLine // lines since info
- pos := token.Position{
- Filename: info.alt.Filename,
- Offset: raw.Offset,
- Line: info.alt.Line + d,
- Column: raw.Column,
- }
- switch {
- case info.alt.Column == 0:
- pos.Column = 0 // column unknown until next directive
- case d == 0:
- pos.Column = info.alt.Column + (raw.Offset - info.alt.Offset) // same line as info
- }
- return pos
-}
-
-// writeIndex writes out an object index. mainIndex indicates whether
-// we're writing out the main index, which is also read by
-// non-compiler tools and includes a complete package description
-// (i.e., name and height).
-func (w *exportWriter) writeIndex(index map[types.Object]uint64) {
- type pkgObj struct {
- obj types.Object
- name string // qualified name; differs from obj.Name for type params
- }
- // Build a map from packages to objects from that package.
- pkgObjs := map[*types.Package][]pkgObj{}
-
- // For the main index, make sure to include every package that
- // we reference, even if we're not exporting (or reexporting)
- // any symbols from it.
- if w.p.localpkg != nil {
- pkgObjs[w.p.localpkg] = nil
- }
- for pkg := range w.p.allPkgs {
- pkgObjs[pkg] = nil
- }
-
- for obj := range index {
- name := w.p.exportName(obj)
- pkgObjs[obj.Pkg()] = append(pkgObjs[obj.Pkg()], pkgObj{obj, name})
- }
-
- var pkgs []*types.Package
- for pkg, objs := range pkgObjs {
- pkgs = append(pkgs, pkg)
-
- sort.Slice(objs, func(i, j int) bool {
- return objs[i].name < objs[j].name
- })
- }
-
- sort.Slice(pkgs, func(i, j int) bool {
- return w.exportPath(pkgs[i]) < w.exportPath(pkgs[j])
- })
-
- w.uint64(uint64(len(pkgs)))
- for _, pkg := range pkgs {
- w.string(w.exportPath(pkg))
- w.string(pkg.Name())
- w.uint64(uint64(0)) // package height is not needed for go/types
-
- objs := pkgObjs[pkg]
- w.uint64(uint64(len(objs)))
- for _, obj := range objs {
- w.string(obj.name)
- w.uint64(index[obj.obj])
- }
- }
-}
-
-// exportName returns the 'exported' name of an object. It differs from
-// obj.Name() only for type parameters (see tparamExportName for details).
-func (p *iexporter) exportName(obj types.Object) (res string) {
- if name := p.tparamNames[obj]; name != "" {
- return name
- }
- return obj.Name()
-}
-
-type iexporter struct {
- fset *token.FileSet
- version int
-
- shallow bool // don't encode types from other packages; refer to them by name (or typePath)
- typeIndexes map[*types.Package]map[types.Type]typePath // paths to literals of other packages in shallow mode; lazily populated
- localpkg *types.Package
-
- // allPkgs tracks all packages that have been referenced by
- // the export data, so we can ensure to include them in the
- // main index.
- allPkgs map[*types.Package]bool
-
- declTodo objQueue
-
- strings intWriter
- stringIndex map[string]uint64
-
- // Since iexportVersionFullPos, object positions are encoded as
- // (file, offset) pairs referencing a table of files. Each file
- // records sparse line starts and //line info for needed offsets.
- files []*filePositions
- fileIndex map[*token.File]*filePositions
- lastFile *filePositions // single-entry cache for consecutive positions
-
- data0 intWriter
- declIndex map[types.Object]uint64
- tparamNames map[types.Object]string // typeparam->exported name
- typIndex map[types.Type]uint64
-
- indent int // for tracing support
-}
-
-type filePositions struct {
- file *token.File
- index int // index in iexporter.files
- needed []uint32 // unordered list of needed file offsets (32 bits suffice; see fileIndexAndOffset)
-}
-
-func (p *iexporter) trace(format string, args ...any) {
- if !trace {
- // Call sites should also be guarded, but having this check here allows
- // easily enabling/disabling debug trace statements.
- return
- }
- fmt.Printf(strings.Repeat("..", p.indent)+format+"\n", args...)
-}
-
-// stringOff returns the offset of s within the string section.
-// If not already present, it's added to the end.
-func (p *iexporter) stringOff(s string) uint64 {
- off, ok := p.stringIndex[s]
- if !ok {
- off = uint64(p.strings.Len())
- p.stringIndex[s] = off
-
- p.strings.uint64(uint64(len(s)))
- p.strings.WriteString(s)
- }
- return off
-}
-
-// fileIndexAndOffset resolves pos to a file index in p.files and a byte
-// offset within that file, recording the offset as needed.
-// It returns (-1, 0) if pos is invalid or not found in p.fset.
-func (p *iexporter) fileIndexAndOffset(pos token.Pos) (int, int64) {
- if !pos.IsValid() {
- return -1, 0
- }
-
- // Consecutive positions are usually in the same file.
- fp := p.lastFile
- if fp == nil || pos < token.Pos(fp.file.Base()) || pos > fp.file.End() {
- file := p.fset.File(pos)
- if file == nil {
- return -1, 0
- }
- fp = p.fileIndex[file]
- if fp == nil {
- // Offsets are recorded in 32 bits, to save memory.
- if uint64(file.Size()) > math.MaxUint32 {
- panic(internalErrorf("file %s is too large (%d bytes)", file.Name(), file.Size()))
- }
- fp = &filePositions{file: file, index: len(p.files)}
- p.files = append(p.files, fp)
- if p.fileIndex == nil {
- p.fileIndex = make(map[*token.File]*filePositions)
- }
- p.fileIndex[file] = fp
- }
- p.lastFile = fp
- }
-
- offset := uint32(fp.file.Offset(pos))
- if n := len(fp.needed); n == 0 || fp.needed[n-1] != offset {
- fp.needed = append(fp.needed, offset)
- }
- return fp.index, int64(offset)
-}
-
-// pushDecl adds n to the declaration work queue, if not already present.
-func (p *iexporter) pushDecl(obj types.Object) {
- // Package unsafe is known to the compiler and predeclared.
- // Caller should not ask us to do export it.
- if obj.Pkg() == types.Unsafe {
- panic("cannot export package unsafe")
- }
-
- // Shallow export data: don't index decls from other packages.
- if p.shallow && obj.Pkg() != p.localpkg {
- return
- }
-
- if _, ok := p.declIndex[obj]; ok {
- return
- }
-
- p.declIndex[obj] = ^uint64(0) // mark obj present in work queue
- p.declTodo.pushTail(obj)
-}
-
-// exportWriter handles writing out individual data section chunks.
-type exportWriter struct {
- p *iexporter
- data intWriter
-
- // posV0/posV1 state
- prevFile string
- prevLine int64
- prevColumn int64
-
- // posV3 state (initially file 0, offset 0)
- prevFileIdx int
- prevOffset int64
-}
-
-func (w *exportWriter) exportPath(pkg *types.Package) string {
- if pkg == w.p.localpkg {
- return ""
- }
- return pkg.Path()
-}
-
-func (p *iexporter) doDecl(obj types.Object) {
- if trace {
- p.trace("exporting decl %v (%T)", obj, obj)
- p.indent++
- defer func() {
- p.indent--
- p.trace("=> %s", obj)
- }()
- }
- w := p.newWriter()
-
- switch obj := obj.(type) {
- case *types.Var:
- w.tag(varTag)
- w.pos(obj.Pos())
- w.typ(obj.Type(), obj.Pkg())
-
- case *types.Func:
- sig := obj.Type().(*types.Signature)
- if sig.Recv() != nil {
- // We shouldn't see methods in the package scope,
- // but the type checker may repair "func () F() {}"
- // to "func (Invalid) F()" and then treat it like "func F()",
- // so allow that. See golang/go#57729.
- if sig.Recv().Type() != types.Typ[types.Invalid] {
- panic(internalErrorf("unexpected method: %v", sig))
- }
- }
-
- // Function.
- if sig.TypeParams().Len() == 0 {
- w.tag(funcTag)
- } else {
- w.tag(genericFuncTag)
- }
- w.pos(obj.Pos())
- // The tparam list of the function type is the declaration of the type
- // params. So, write out the type params right now. Then those type params
- // will be referenced via their type offset (via typOff) in all other
- // places in the signature and function where they are used.
- //
- // While importing the type parameters, tparamList computes and records
- // their export name, so that it can be later used when writing the index.
- if tparams := sig.TypeParams(); tparams.Len() > 0 {
- w.tparamList(obj.Name(), tparams, obj.Pkg())
- }
- w.signature(sig)
-
- case *types.Const:
- w.tag(constTag)
- w.pos(obj.Pos())
- w.value(obj.Type(), obj.Val(), obj.Pkg())
-
- case *types.TypeName:
- t := obj.Type()
-
- if tparam, ok := types.Unalias(t).(*types.TypeParam); ok {
- w.tag(typeParamTag)
- w.pos(obj.Pos())
- constraint := tparam.Constraint()
- if p.version >= iexportVersionGo1_18 {
- implicit := false
- if iface, _ := types.Unalias(constraint).(*types.Interface); iface != nil {
- implicit = iface.IsImplicit()
- }
- w.bool(implicit)
- }
- w.typ(constraint, obj.Pkg())
- break
- }
-
- if obj.IsAlias() {
- alias, materialized := t.(*types.Alias) // perhaps false for certain built-ins?
-
- var tparams *types.TypeParamList
- if materialized {
- tparams = alias.TypeParams()
- }
- if tparams.Len() == 0 {
- w.tag(aliasTag)
- } else {
- w.tag(genericAliasTag)
- }
- w.pos(obj.Pos())
- if tparams.Len() > 0 {
- w.tparamList(obj.Name(), tparams, obj.Pkg())
- }
- if materialized {
- // Preserve materialized aliases,
- // even of non-exported types.
- t = alias.Rhs()
- }
- w.typ(t, obj.Pkg())
- break
- }
-
- // Defined type.
- named, ok := t.(*types.Named)
- if !ok {
- panic(internalErrorf("%s is not a defined type", t))
- }
-
- if named.TypeParams().Len() == 0 {
- w.tag(typeTag)
- } else {
- w.tag(genericTypeTag)
- }
- w.pos(obj.Pos())
-
- if named.TypeParams().Len() > 0 {
- // While importing the type parameters, tparamList computes and records
- // their export name, so that it can be later used when writing the index.
- w.tparamList(obj.Name(), named.TypeParams(), obj.Pkg())
- }
-
- underlying := named.Underlying()
- w.typ(underlying, obj.Pkg())
-
- if types.IsInterface(t) {
- break
- }
-
- n := named.NumMethods()
- w.uint64(uint64(n))
- for i := range n {
- m := named.Method(i)
- w.pos(m.Pos())
- w.string(m.Name())
- sig := m.Type().(*types.Signature)
- if w.p.version >= iexportVersionGenericMethods && w.bool(sig.TypeParams().Len() > 0) {
- w.tparamList(obj.Name()+"."+m.Name(), sig.TypeParams(), obj.Pkg())
- }
-
- // Receiver type parameters are type arguments of the receiver type, so
- // their name must be qualified before exporting recv.
- if rparams := sig.RecvTypeParams(); rparams.Len() > 0 {
- prefix := obj.Name() + "." + m.Name()
- for rparam := range rparams.TypeParams() {
- name := tparamExportName(prefix, rparam)
- w.p.tparamNames[rparam.Obj()] = name
- }
- }
- w.param(sig.Recv())
- w.signature(sig)
- }
-
- default:
- panic(internalErrorf("unexpected object: %v", obj))
- }
-
- p.declIndex[obj] = w.flush()
-}
-
-func (w *exportWriter) tag(tag byte) {
- w.data.WriteByte(tag)
-}
-
-func (w *exportWriter) pos(pos token.Pos) {
- if w.p.version >= iexportVersionFullPos {
- w.posV3(pos)
- } else if w.p.version >= iexportVersionPosCol {
- w.posV1(pos)
- } else {
- w.posV0(pos)
- }
-}
-
-// posV3 encodes a position (used in both modes since
-// iexportVersionFullPos) as a (file, offset) pair, delta-encoded
-// within a declaration or type descriptor. See the description of Pos
-// in the format comment at the top of this file, and
-// [importReader.posV3] for the decoder.
-func (w *exportWriter) posV3(pos token.Pos) {
- file, offset := w.p.fileIndexAndOffset(pos)
- switch {
- case file < 0: // NoPos
- w.int64(-1)
- case file == w.prevFileIdx: // same file
- w.int64((offset - w.prevOffset) << 1)
- w.prevOffset = offset
- default: // new file
- w.int64(int64(file)<<1 | 1)
- w.uint64(uint64(offset))
- w.prevFileIdx = file
- w.prevOffset = offset
- }
-}
-
-func (w *exportWriter) posV1(pos token.Pos) {
- p := w.p.fset.Position(pos)
- file := p.Filename
- line := int64(p.Line)
- column := int64(p.Column)
-
- deltaColumn := (column - w.prevColumn) << 1
- deltaLine := (line - w.prevLine) << 1
-
- if file != w.prevFile {
- deltaLine |= 1
- }
- if deltaLine != 0 {
- deltaColumn |= 1
- }
-
- w.int64(deltaColumn)
- if deltaColumn&1 != 0 {
- w.int64(deltaLine)
- if deltaLine&1 != 0 {
- w.string(file)
- }
- }
-
- w.prevFile = file
- w.prevLine = line
- w.prevColumn = column
-}
-
-func (w *exportWriter) posV0(pos token.Pos) {
- p := w.p.fset.Position(pos)
- file := p.Filename
- line := int64(p.Line)
-
- // When file is the same as the last position (common case),
- // we can save a few bytes by delta encoding just the line
- // number.
- //
- // Note: Because data objects may be read out of order (or not
- // at all), we can only apply delta encoding within a single
- // object. This is handled implicitly by tracking prevFile and
- // prevLine as fields of exportWriter.
-
- if file == w.prevFile {
- delta := line - w.prevLine
- w.int64(delta)
- if delta == deltaNewFile {
- w.int64(-1)
- }
- } else {
- w.int64(deltaNewFile)
- w.int64(line) // line >= 0
- w.string(file)
- w.prevFile = file
- }
- w.prevLine = line
-}
-
-func (w *exportWriter) pkg(pkg *types.Package) {
- if pkg == nil {
- // [exportWriter.typ] accepts a nil pkg only for types
- // of constants, which cannot contain named objects
- // such as fields or methods and thus should never
- // reach this method (#76222).
- panic("nil package")
- }
- // Ensure any referenced packages are declared in the main index.
- w.p.allPkgs[pkg] = true
-
- w.string(w.exportPath(pkg))
-}
-
-func (w *exportWriter) qualifiedType(obj *types.TypeName) {
- name := w.p.exportName(obj)
-
- // Ensure any referenced declarations are written out too.
- w.p.pushDecl(obj)
- w.string(name)
- w.pkg(obj.Pkg())
-}
-
-// typ emits the specified type.
-//
-// Objects within the type (struct fields and interface methods) are
-// qualified by pkg.
-func (w *exportWriter) typ(t types.Type, pkg *types.Package) {
- if pkg == nil {
- pkg = w.p.localpkg
- }
- w.data.uint64(w.p.typOff(t, pkg))
-}
-
-func (p *iexporter) newWriter() *exportWriter {
- return &exportWriter{p: p}
-}
-
-func (w *exportWriter) flush() uint64 {
- off := uint64(w.p.data0.Len())
- io.Copy(&w.p.data0, &w.data)
- return off
-}
-
-func (p *iexporter) typOff(t types.Type, pkg *types.Package) uint64 {
- off, ok := p.typIndex[t]
- if !ok {
- w := p.newWriter()
- w.doTyp(t, pkg)
- off = predeclReserved + w.flush()
- p.typIndex[t] = off
- }
- return off
-}
-
-func (w *exportWriter) startType(k itag) {
- w.data.uint64(uint64(k))
-}
-
-// doTyp is the implementation of [exportWriter.typ].
-func (w *exportWriter) doTyp(t types.Type, pkg *types.Package) {
- if trace {
- w.p.trace("exporting type %s (%T)", t, t)
- w.p.indent++
- defer func() {
- w.p.indent--
- w.p.trace("=> %s", t)
- }()
- }
- switch t := t.(type) {
- case *types.Alias:
- if targs := t.TypeArgs(); targs.Len() > 0 {
- w.startType(instanceType)
- w.pos(t.Obj().Pos())
- w.typeList(targs, pkg)
- w.typ(t.Origin(), pkg)
- return
- }
- w.startType(aliasType)
- w.qualifiedType(t.Obj())
-
- case *types.Named:
- if targs := t.TypeArgs(); targs.Len() > 0 {
- w.startType(instanceType)
- // TODO(rfindley): investigate if this position is correct, and if it
- // matters.
- w.pos(t.Obj().Pos())
- w.typeList(targs, pkg)
- w.typ(t.Origin(), pkg)
- return
- }
- w.startType(definedType)
- w.qualifiedType(t.Obj())
-
- case *types.TypeParam:
- w.startType(typeParamType)
- w.qualifiedType(t.Obj())
-
- case *types.Pointer:
- w.startType(pointerType)
- w.typ(t.Elem(), pkg)
-
- case *types.Slice:
- w.startType(sliceType)
- w.typ(t.Elem(), pkg)
-
- case *types.Array:
- w.startType(arrayType)
- w.uint64(uint64(t.Len()))
- w.typ(t.Elem(), pkg)
-
- case *types.Chan:
- w.startType(chanType)
- // 1 RecvOnly; 2 SendOnly; 3 SendRecv
- var dir uint64
- switch t.Dir() {
- case types.RecvOnly:
- dir = 1
- case types.SendOnly:
- dir = 2
- case types.SendRecv:
- dir = 3
- }
- w.uint64(dir)
- w.typ(t.Elem(), pkg)
-
- case *types.Map:
- w.startType(mapType)
- w.typ(t.Key(), pkg)
- w.typ(t.Elem(), pkg)
-
- case *types.Signature:
- w.startType(signatureType)
- w.pkg(pkg) // qualifies param/result vars
- w.signature(t)
-
- case *types.Struct:
- // In shallow mode, a literal of another package is
- // encoded as a reference to it (see typepath.go).
- if w.p.shallow && w.externalLiteral(t) {
- return
- }
-
- w.startType(structType)
- n := t.NumFields()
- // Even for struct{} we must emit some qualifying package, because that's
- // what the compiler does, and thus that's what the importer expects.
- fieldPkg := pkg
- if n > 0 {
- fieldPkg = t.Field(0).Pkg()
- }
- if fieldPkg == nil {
- // TODO(rfindley): improve this very hacky logic.
- //
- // The importer expects a package to be set for all struct types, even
- // those with no fields. A better encoding might be to set NumFields
- // before pkg. setPkg panics with a nil package, which may be possible
- // to reach with invalid packages (and perhaps valid packages, too?), so
- // (arbitrarily) set the localpkg if available.
- //
- // Alternatively, we may be able to simply guarantee that pkg != nil, by
- // reconsidering the encoding of constant values.
- if w.p.shallow {
- fieldPkg = w.p.localpkg
- } else {
- panic(internalErrorf("no package to set for empty struct"))
- }
- }
- w.pkg(fieldPkg)
- w.uint64(uint64(n))
-
- for i := range n {
- f := t.Field(i)
- w.pos(f.Pos())
- w.string(f.Name()) // unexported fields implicitly qualified by prior setPkg
- w.typ(f.Type(), fieldPkg)
- w.bool(f.Anonymous())
- w.string(t.Tag(i)) // note (or tag)
- }
-
- case *types.Interface:
- // (See comment for case *types.Struct.)
- if w.p.shallow && w.externalLiteral(t) {
- return
- }
-
- w.startType(interfaceType)
- methodPkg := pkg
- for i := range t.NumExplicitMethods() {
- if mp := t.ExplicitMethod(i).Pkg(); mp != nil {
- methodPkg = mp
- break
- }
- }
- w.pkg(methodPkg) // qualifies unexported method funcs
-
- n := t.NumEmbeddeds()
- w.uint64(uint64(n))
- for i := 0; i < n; i++ {
- ft := t.EmbeddedType(i)
- if named, _ := types.Unalias(ft).(*types.Named); named != nil {
- w.pos(named.Obj().Pos())
- } else {
- // e.g. ~int
- w.pos(token.NoPos)
- }
- w.typ(ft, pkg)
- }
-
- n = t.NumExplicitMethods()
- w.uint64(uint64(n))
- for i := 0; i < n; i++ {
- m := t.ExplicitMethod(i)
- w.pos(m.Pos())
- w.string(m.Name())
- sig := m.Type().(*types.Signature)
- w.signature(sig)
- }
-
- case *types.Union:
- w.startType(unionType)
- nt := t.Len()
- w.uint64(uint64(nt))
- for i := range nt {
- term := t.Term(i)
- w.bool(term.Tilde())
- w.typ(term.Type(), pkg)
- }
-
- default:
- panic(internalErrorf("unexpected type: %v, %v", t, reflect.TypeOf(t)))
- }
-}
-
-// externalLiteral reports whether t, a struct or interface literal,
-// should be encoded in shallow mode as a reference to a literal of
-// another package, and if so, writes the reference.
-//
-// If t has members (fields or explicit methods) declared in a package
-// other than the local one, and t is reachable from the API of that
-// package, externalLiteral writes a reference to it (see typepath.go),
-// so that the importer uses the canonical literal and members. It
-// reports an internal error if t cannot be reached: the importer will
-// create fresh member objects, which is a bug unless the package is
-// ill-typed.
-func (w *exportWriter) externalLiteral(t types.Type) bool {
- p := w.p
-
- // TODO(golang/go#61674): a literal created by instantiation (such
- // as the underlying type of B in "type B a.A[int]") is not
- // reachable from the API of a, so it is encoded in full, and the
- // importer creates fresh member objects: even members that the
- // instance shares with its origin, whose types do not depend on
- // type parameters, lose their identity, and the fresh members do
- // not record their origin. We plan to fix this once the real
- // implementation of this codec lives in the standard library,
- // where the importer can set Var.Origin and Func.Origin.
- var pkg *types.Package // package of first member
- for m := range literalMembers(t) {
- if pkg == nil {
- pkg = m.Pkg()
- if pkg == nil || pkg == p.localpkg {
- return false // local literal (or ill-typed)
- }
- }
- if origin(m) != m {
- return false // instance
- }
- }
- if pkg == nil {
- return false // no member objects whose identity must be preserved
- }
-
- // Memoize each package's newTypeIndex traversal.
- ix := p.typeIndexes[pkg]
- if ix == nil {
- ix = newTypeIndex(pkg)
- if p.typeIndexes == nil {
- p.typeIndexes = make(map[*types.Package]map[types.Type]typePath)
- }
- p.typeIndexes[pkg] = ix
- }
- path, ok := ix[t]
- if !ok {
- return false // e.g. literal created by instantiation (golang/go#61674)
- }
-
- w.startType(externalType)
- w.pkg(pkg)
- w.string(path.root)
- w.uint64(uint64(len(path.steps)))
- for _, i := range path.steps {
- w.uint64(uint64(i))
- }
- return true
-}
-
-func (w *exportWriter) signature(sig *types.Signature) {
- w.paramList(sig.Params())
- w.paramList(sig.Results())
- if sig.Params().Len() > 0 {
- w.bool(sig.Variadic())
- }
-}
-
-func (w *exportWriter) typeList(ts *types.TypeList, pkg *types.Package) {
- w.uint64(uint64(ts.Len()))
- for t := range ts.Types() {
- w.typ(t, pkg)
- }
-}
-
-func (w *exportWriter) tparamList(prefix string, list *types.TypeParamList, pkg *types.Package) {
- ll := uint64(list.Len())
- w.uint64(ll)
- for tparam := range list.TypeParams() {
- // Set the type parameter exportName before exporting its type.
- exportName := tparamExportName(prefix, tparam)
- w.p.tparamNames[tparam.Obj()] = exportName
- w.typ(tparam, pkg)
- }
-}
-
-const blankMarker = "$"
-
-// tparamExportName returns the 'exported' name of a type parameter, which
-// differs from its actual object name: it is prefixed with a qualifier, and
-// blank type parameter names are disambiguated by their index in the type
-// parameter list.
-func tparamExportName(prefix string, tparam *types.TypeParam) string {
- assert(prefix != "")
- name := tparam.Obj().Name()
- if name == "_" {
- name = blankMarker + strconv.Itoa(tparam.Index())
- }
- return prefix + "." + name
-}
-
-// tparamName returns the real name of a type parameter, after stripping its
-// qualifying prefix and reverting blank-name encoding. See tparamExportName
-// for details.
-func tparamName(exportName string) string {
- // Remove the "path" from the type param name that makes it unique.
- ix := strings.LastIndex(exportName, ".")
- if ix < 0 {
- errorf("malformed type parameter export name %s: missing prefix", exportName)
- }
- name := exportName[ix+1:]
- if strings.HasPrefix(name, blankMarker) {
- return "_"
- }
- return name
-}
-
-func (w *exportWriter) paramList(tup *types.Tuple) {
- n := tup.Len()
- w.uint64(uint64(n))
- for i := range n {
- w.param(tup.At(i))
- }
-}
-
-func (w *exportWriter) param(obj types.Object) {
- w.pos(obj.Pos())
- w.localIdent(obj)
- w.typ(obj.Type(), obj.Pkg())
-}
-
-// only called for constants
-func (w *exportWriter) value(typ types.Type, v constant.Value, pkg *types.Package) {
- if pkg == nil {
- pkg = w.p.localpkg
- }
- w.typ(typ, pkg)
- if w.p.version >= iexportVersionGo1_18 {
- w.int64(int64(v.Kind()))
- }
-
- if v.Kind() == constant.Unknown {
- // golang/go#60605: treat unknown constant values as if they have invalid type
- //
- // This loses some fidelity over the package type-checked from source, but that
- // is acceptable.
- //
- // TODO(rfindley): we should switch on the recorded constant kind rather
- // than the constant type
- return
- }
-
- switch b := typ.Underlying().(*types.Basic); b.Info() & types.IsConstType {
- case types.IsBoolean:
- w.bool(constant.BoolVal(v))
- case types.IsInteger:
- var i big.Int
- if i64, exact := constant.Int64Val(v); exact {
- i.SetInt64(i64)
- } else if ui64, exact := constant.Uint64Val(v); exact {
- i.SetUint64(ui64)
- } else {
- i.SetString(v.ExactString(), 10)
- }
- w.mpint(&i, typ)
- case types.IsFloat:
- w.float(v, typ)
- case types.IsComplex:
- w.float(constant.Real(v), typ)
- w.float(constant.Imag(v), typ)
- case types.IsString:
- w.string(constant.StringVal(v))
- default:
- if b.Kind() == types.Invalid {
- // package contains type errors
- break
- }
- panic(internalErrorf("unexpected type %v (%v)", typ, typ.Underlying()))
- }
-}
-
-// constantToFloat converts a constant.Value with kind constant.Float to a
-// big.Float.
-func constantToFloat(x constant.Value) *big.Float {
- x = constant.ToFloat(x)
- // Use the same floating-point precision (512) as cmd/compile
- // (see Mpprec in cmd/compile/internal/gc/mpfloat.go).
- const mpprec = 512
- var f big.Float
- f.SetPrec(mpprec)
- if v, exact := constant.Float64Val(x); exact {
- // float64
- f.SetFloat64(v)
- } else if num, denom := constant.Num(x), constant.Denom(x); num.Kind() == constant.Int {
- // TODO(gri): add big.Rat accessor to constant.Value.
- n := valueToRat(num)
- d := valueToRat(denom)
- f.SetRat(n.Quo(n, d))
- } else {
- // Value too large to represent as a fraction => inaccessible.
- // TODO(gri): add big.Float accessor to constant.Value.
- _, ok := f.SetString(x.ExactString())
- assert(ok)
- }
- return &f
-}
-
-// float exports a floating-point constant value.
-func (w *exportWriter) float(x constant.Value, typ types.Type) {
- if w.p.version < iexportVersionRationalFloats {
- w.mpfloat(constantToFloat(x), typ) // 512-bit mantissa f.p.
- return
- }
-
- // lossless encoding
- switch v := constant.Val(constant.ToFloat(x)).(type) {
- case *big.Rat:
- if n := v.Num(); v.IsInt() && n.BitLen() <= 8*untypedMaxBytes {
- w.uint64(floatTagInt) // integer
- w.mpint(n, types.Typ[types.UntypedFloat])
- } else {
- w.uint64(floatTagRat) // rational
- w.bigInt(n)
- w.bigInt(v.Denom())
- }
- case *big.Float:
- w.uint64(floatTagFloat) // 512-bit mantissa f.p.
- w.mpfloat(v, typ)
- default:
- panic(internalErrorf("unexpected float constant %v (%T)", x, v))
- }
-}
-
-// bigInt exports an arbitrary-precision integer as its big-endian
-// magnitude bytes (as a string) followed by a sign bool.
-func (w *exportWriter) bigInt(v *big.Int) {
- w.string(string(v.Bytes())) // (big endian)
- w.bool(v.Sign() < 0)
-}
-
-func valueToRat(x constant.Value) *big.Rat {
- // Convert little-endian to big-endian.
- // I can't believe this is necessary.
- bytes := constant.Bytes(x)
- for i := 0; i < len(bytes)/2; i++ {
- bytes[i], bytes[len(bytes)-1-i] = bytes[len(bytes)-1-i], bytes[i]
- }
- i := new(big.Int).SetBytes(bytes)
- if constant.Sign(x) < 0 {
- i.Neg(i) // constant.Bytes returns the absolute value
- }
- return new(big.Rat).SetInt(i)
-}
-
-// mpint exports a multi-precision integer.
-//
-// For unsigned types, small values are written out as a single
-// byte. Larger values are written out as a length-prefixed big-endian
-// byte string, where the length prefix is encoded as its complement.
-// For example, bytes 0, 1, and 2 directly represent the integer
-// values 0, 1, and 2; while bytes 255, 254, and 253 indicate a 1-,
-// 2-, and 3-byte big-endian string follow.
-//
-// Encoding for signed types use the same general approach as for
-// unsigned types, except small values use zig-zag encoding and the
-// bottom bit of length prefix byte for large values is reserved as a
-// sign bit.
-//
-// The exact boundary between small and large encodings varies
-// according to the maximum number of bytes needed to encode a value
-// of type typ. As a special case, 8-bit types are always encoded as a
-// single byte.
-//
-// TODO(mdempsky): Is this level of complexity really worthwhile?
-func (w *exportWriter) mpint(x *big.Int, typ types.Type) {
- basic, ok := typ.Underlying().(*types.Basic)
- if !ok {
- panic(internalErrorf("unexpected type %v (%T)", typ.Underlying(), typ.Underlying()))
- }
-
- signed, maxBytes := intSize(basic)
-
- negative := x.Sign() < 0
- if !signed && negative {
- panic(internalErrorf("negative unsigned integer; type %v, value %v", typ, x))
- }
-
- b := x.Bytes()
- if len(b) > 0 && b[0] == 0 {
- panic(internalErrorf("leading zeros"))
- }
- if uint(len(b)) > maxBytes {
- panic(internalErrorf("bad mpint length: %d > %d (type %v, value %v)", len(b), maxBytes, typ, x))
- }
-
- maxSmall := 256 - maxBytes
- if signed {
- maxSmall = 256 - 2*maxBytes
- }
- if maxBytes == 1 {
- maxSmall = 256
- }
-
- // Check if x can use small value encoding.
- if len(b) <= 1 {
- var ux uint
- if len(b) == 1 {
- ux = uint(b[0])
- }
- if signed {
- ux <<= 1
- if negative {
- ux--
- }
- }
- if ux < maxSmall {
- w.data.WriteByte(byte(ux))
- return
- }
- }
-
- n := 256 - uint(len(b))
- if signed {
- n = 256 - 2*uint(len(b))
- if negative {
- n |= 1
- }
- }
- if n < maxSmall || n >= 256 {
- panic(internalErrorf("encoding mistake: %d, %v, %v => %d", len(b), signed, negative, n))
- }
-
- w.data.WriteByte(byte(n))
- w.data.Write(b)
-}
-
-// mpfloat exports a multi-precision floating point number.
-//
-// The number's value is decomposed into mantissa × 2**exponent, where
-// mantissa is an integer. The value is written out as mantissa (as a
-// multi-precision integer) and then the exponent, except exponent is
-// omitted if mantissa is zero.
-func (w *exportWriter) mpfloat(f *big.Float, typ types.Type) {
- if f.IsInf() {
- panic("infinite constant")
- }
-
- // Break into f = mant × 2**exp, with 0.5 <= mant < 1.
- var mant big.Float
- exp := int64(f.MantExp(&mant))
-
- // Scale so that mant is an integer.
- prec := mant.MinPrec()
- mant.SetMantExp(&mant, int(prec))
- exp -= int64(prec)
-
- manti, acc := mant.Int(nil)
- if acc != big.Exact {
- panic(internalErrorf("mantissa scaling failed for %f (%s)", f, acc))
- }
- w.mpint(manti, typ)
- if manti.Sign() != 0 {
- w.int64(exp)
- }
-}
-
-func (w *exportWriter) bool(b bool) bool {
- var x uint64
- if b {
- x = 1
- }
- w.uint64(x)
- return b
-}
-
-func (w *exportWriter) int64(x int64) { w.data.int64(x) }
-func (w *exportWriter) uint64(x uint64) { w.data.uint64(x) }
-func (w *exportWriter) string(s string) { w.uint64(w.p.stringOff(s)) }
-
-func (w *exportWriter) localIdent(obj types.Object) {
- // Anonymous parameters.
- if obj == nil {
- w.string("")
- return
- }
-
- name := obj.Name()
- if name == "_" {
- w.string("_")
- return
- }
-
- w.string(name)
-}
-
-type intWriter struct {
- bytes.Buffer
-}
-
-func (w *intWriter) int64(x int64) {
- var buf [binary.MaxVarintLen64]byte
- n := binary.PutVarint(buf[:], x)
- w.Write(buf[:n])
-}
-
-func (w *intWriter) uint64(x uint64) {
- var buf [binary.MaxVarintLen64]byte
- n := binary.PutUvarint(buf[:], x)
- w.Write(buf[:n])
-}
-
-func (w *intWriter) bool(b bool) {
- var x uint64
- if b {
- x = 1
- }
- w.uint64(x)
-}
-
-func assert(cond bool) {
- if !cond {
- panic("internal error: assertion failed")
- }
-}
-
-// The below is copied from go/src/cmd/compile/internal/gc/syntax.go.
-
-// objQueue is a FIFO queue of types.Object. The zero value of objQueue is
-// a ready-to-use empty queue.
-type objQueue struct {
- ring []types.Object
- head, tail int
-}
-
-// empty returns true if q contains no Nodes.
-func (q *objQueue) empty() bool {
- return q.head == q.tail
-}
-
-// pushTail appends n to the tail of the queue.
-func (q *objQueue) pushTail(obj types.Object) {
- if len(q.ring) == 0 {
- q.ring = make([]types.Object, 16)
- } else if q.head+len(q.ring) == q.tail {
- // Grow the ring.
- nring := make([]types.Object, len(q.ring)*2)
- // Copy the old elements.
- part := q.ring[q.head%len(q.ring):]
- if q.tail-q.head <= len(part) {
- part = part[:q.tail-q.head]
- copy(nring, part)
- } else {
- pos := copy(nring, part)
- copy(nring[pos:], q.ring[:q.tail%len(q.ring)])
- }
- q.ring, q.head, q.tail = nring, 0, q.tail-q.head
- }
-
- q.ring[q.tail%len(q.ring)] = obj
- q.tail++
-}
-
-// popHead pops a node from the head of the queue. It panics if q is empty.
-func (q *objQueue) popHead() types.Object {
- if q.empty() {
- panic("dequeue empty")
- }
- obj := q.ring[q.head%len(q.ring)]
- q.head++
- return obj
-}
-
-// internalError represents an error generated inside this package.
-type internalError string
-
-func (e internalError) Error() string { return "exportdata: " + string(e) }
-
-// TODO(adonovan): make this call panic, so that it's symmetric with errorf.
-// Otherwise it's easy to forget to do anything with the error.
-//
-// TODO(adonovan): also, consider switching the names "errorf" and
-// "internalErrorf" as the former is used for bugs, whose cause is
-// internal inconsistency, whereas the latter is used for ordinary
-// situations like bad input, whose cause is external.
-func internalErrorf(format string, args ...any) error {
- return internalError(fmt.Sprintf(format, args...))
-}
diff --git a/src/cmd/vendor/golang.org/x/tools/internal/exportdata/iimport.go b/src/cmd/vendor/golang.org/x/tools/internal/exportdata/iimport.go
deleted file mode 100644
index b36f69220a..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/internal/exportdata/iimport.go
+++ /dev/null
@@ -1,1147 +0,0 @@
-// Copyright 2018 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Indexed package import.
-// See iexport.go for the export data format.
-
-package exportdata
-
-import (
- "bytes"
- "encoding/binary"
- "fmt"
- "go/constant"
- "go/token"
- "go/types"
- "io"
- "math/big"
- "slices"
- "sort"
- "strings"
- // This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-)
-
-type intReader struct {
- *bytes.Reader
- path string
-}
-
-func (r *intReader) int64() int64 {
- i, err := binary.ReadVarint(r.Reader)
- if err != nil {
- errorf("import %q: read varint error: %v", r.path, err)
- }
- return i
-}
-
-func (r *intReader) uint64() uint64 {
- i, err := binary.ReadUvarint(r.Reader)
- if err != nil {
- errorf("import %q: read varint error: %v", r.path, err)
- }
- return i
-}
-
-// Keep this in sync with constants in iexport.go.
-const (
- iexportVersionGo1_11 = 0
- iexportVersionPosCol = 1
- iexportVersionGo1_18 = 2
- iexportVersionGenerics = 2
- // TODO(adonovan): reject versions older than this.
- iexportVersionGenericMethods = 3
- iexportVersionRationalFloats = 4 // allow float constants to be represented as multiprecision rationals
- iexportVersionShallowFlag = 5 // header records deep/shallow mode
- iexportVersionFullPos = 6 // both modes use posV3 and a file table, which records //line info
- iexportVersion = iexportVersionFullPos
-
- iexportVersionCurrent = 6
-)
-
-type ident struct {
- pkg *types.Package
- name string
-}
-
-const predeclReserved = 32
-
-type itag uint64
-
-// Tags for the encoding of float constant values
-// (iexportVersionRationalFloats and later); see (*exportWriter).float.
-const (
- floatTagInt = iota // integer-valued big.Rat: mpint (untyped sizing)
- floatTagRat // other big.Rat: numerator and denominator, each a bigInt
- floatTagFloat // big.Float: mpfloat
-
- // untypedMaxBytes is the maximum magnitude size of an mpint
- // encoded with untyped sizing; see [intSize].
- untypedMaxBytes = 64
-)
-
-const (
- // Types
- definedType itag = iota
- pointerType
- sliceType
- arrayType
- chanType
- mapType
- signatureType
- structType
- interfaceType
- typeParamType
- instanceType
- unionType
- aliasType
- externalType // shallow mode only
-)
-
-// Object tags
-const (
- varTag = 'V'
- funcTag = 'F'
- genericFuncTag = 'G'
- constTag = 'C'
- aliasTag = 'A'
- genericAliasTag = 'B'
- typeParamTag = 'P'
- typeTag = 'T'
- genericTypeTag = 'U'
-)
-
-// iimportCommon decodes export data (without the leading 'i' tag byte).
-// See [Decode] for the contract of getPackages.
-func iimportCommon(fset *token.FileSet, getPackages func([]PackageRef) ([]*types.Package, error), data []byte, path string) (_ *types.Package, err error) {
- const currentVersion = iexportVersionCurrent
- version := int64(-1)
- if !debug {
- defer func() {
- if e := recover(); e != nil {
- if version > currentVersion {
- err = fmt.Errorf("cannot import %q (%v), export data is newer version - update tool", path, e)
- } else {
- err = fmt.Errorf("internal error while importing %q (%v); please report an issue", path, e)
- }
- }
- }()
- }
-
- r := &intReader{bytes.NewReader(data), path}
-
- version = int64(r.uint64())
- switch version {
- case iexportVersionFullPos, iexportVersionShallowFlag, iexportVersionRationalFloats, iexportVersionGenericMethods, iexportVersionGo1_18, iexportVersionPosCol, iexportVersionGo1_11:
- // known version
- default:
- // unknown version
- if version > iexportVersionFullPos {
- errorf("unstable iexport format version %d, just rebuild compiler and std library", version)
- } else {
- errorf("unknown iexport format version %d", version)
- }
- }
-
- shallow := version >= iexportVersionShallowFlag && r.uint64() != 0
-
- sLen := int64(r.uint64())
- var fLen int64
- if version >= iexportVersionFullPos {
- fLen = int64(r.uint64())
- }
- dLen := int64(r.uint64())
-
- whence, _ := r.Seek(0, io.SeekCurrent)
- stringData := data[whence : whence+sLen]
- fileData := data[whence+sLen : whence+sLen+fLen]
- declData := data[whence+sLen+fLen : whence+sLen+fLen+dLen]
- r.Seek(sLen+fLen+dLen, io.SeekCurrent)
-
- p := iimporter{
- fset: fset,
- version: int(version),
- ipath: path,
- shallow: shallow,
-
- stringData: stringData,
- stringCache: make(map[uint64]string),
- fileData: fileData,
- pkgCache: make(map[uint64]*types.Package),
-
- declData: declData,
- pkgIndex: make(map[*types.Package]map[string]uint64),
- typCache: make(map[uint64]types.Type),
- // Separate map for typeparams, keyed by their package and unique
- // name.
- tparamIndex: make(map[ident]types.Type),
- }
- if version < iexportVersionFullPos {
- p.fake = fakeFileSet{
- fset: fset,
- files: make(map[string]*fileInfo),
- }
- defer p.fake.setLines() // set lines for files in fset
- }
-
- for i, pt := range predeclared() {
- p.typCache[uint64(i)] = pt
- }
-
- // Gather the relevant packages from the manifest.
- n := r.uint64()
- var (
- refs = make([]PackageRef, n)
- pathOffsets = make([]uint64, n)
- nameIndexes = make([]map[string]uint64, n)
- )
- for i := range refs {
- pkgPathOff := r.uint64()
- pkgPath := p.stringAt(pkgPathOff)
- pkgName := p.stringAt(r.uint64())
- _ = r.uint64() // package height; unused by go/types
-
- if pkgPath == "" {
- pkgPath = path
- }
- refs[i] = PackageRef{Path: pkgPath, Name: pkgName}
- pathOffsets[i] = pkgPathOff
-
- // Read index for package.
- nameIndex := make(map[string]uint64)
- nSyms := r.uint64()
- // In shallow mode, only the current package (i=0) has an index.
- assert(!(shallow && i > 0 && nSyms != 0))
- for ; nSyms > 0; nSyms-- {
- name := p.stringAt(r.uint64())
- nameIndex[name] = r.uint64()
- }
-
- nameIndexes[i] = nameIndex
- }
-
- if version >= iexportVersionFullPos {
- p.fileOffset = make([]uint64, r.uint64())
- for i := range p.fileOffset {
- p.fileOffset[i] = r.uint64()
- }
- p.fileCache = make([]*token.File, len(p.fileOffset))
- }
-
- // Request packages all at once from the client,
- // enabling a parallel implementation.
- pkgList, err := getPackages(refs)
- if err != nil {
- return nil, err // don't wrap this error
- }
- if len(pkgList) != len(refs) {
- errorf("internal error: getPackages returned %d packages, want %d", len(pkgList), len(refs))
- }
-
- // Check the results and complete the index.
- for i, ref := range refs {
- pkg := pkgList[i]
- if pkg == nil {
- errorf("internal error: getPackages returned nil package for %q", ref.Path)
- } else if pkg.Path() != ref.Path {
- errorf("internal error: getPackages returned wrong path %q, want %q", pkg.Path(), ref.Path)
- } else if pkg.Name() != ref.Name {
- errorf("internal error: getPackages returned wrong name %s for package %q, want %s", pkg.Name(), ref.Path, ref.Name)
- }
- p.pkgCache[pathOffsets[i]] = pkg
- p.pkgIndex[pkg] = nameIndexes[i]
- }
-
- if len(pkgList) == 0 {
- errorf("no packages found for %s", path)
- panic("unreachable")
- }
- pkgs := pkgList[:1]
-
- // record all referenced packages as imports
- list := slices.Clone(pkgList[1:])
- sort.Sort(byPath(list))
- pkgs[0].SetImports(list)
-
- for _, pkg := range pkgs {
- if pkg.Complete() {
- continue
- }
-
- names := make([]string, 0, len(p.pkgIndex[pkg]))
- for name := range p.pkgIndex[pkg] {
- names = append(names, name)
- }
- sort.Strings(names)
- for _, name := range names {
- p.doDecl(pkg, name)
- }
-
- // package was imported completely and without errors
- pkg.MarkComplete()
- }
-
- // SetConstraint can't be called if the constraint type is not yet complete.
- // When type params are created in the typeParamTag case of (*importReader).obj(),
- // the associated constraint type may not be complete due to recursion.
- // Therefore, we defer calling SetConstraint there, and call it here instead
- // after all types are complete.
- for _, d := range p.later {
- d.t.SetConstraint(d.constraint)
- }
-
- for _, typ := range p.interfaceList {
- typ.Complete()
- }
-
- // Workaround for golang/go#61561. See the doc for instanceList for details.
- for _, typ := range p.instanceList {
- if iface, _ := typ.Underlying().(*types.Interface); iface != nil {
- iface.Complete()
- }
- }
-
- return pkgs[0], nil
-}
-
-type setConstraintArgs struct {
- t *types.TypeParam
- constraint types.Type
-}
-
-type iimporter struct {
- fset *token.FileSet
- version int
- ipath string
-
- shallow bool
-
- stringData []byte
- stringCache map[uint64]string
- fileOffset []uint64 // fileOffset[i] is offset in fileData for info about file encoded as i
- fileData []byte
- fileCache []*token.File // memoized decoding of file encoded as i
- pkgCache map[uint64]*types.Package
-
- declData []byte
- pkgIndex map[*types.Package]map[string]uint64
- typCache map[uint64]types.Type
- tparamIndex map[ident]types.Type
-
- fake fakeFileSet
- interfaceList []*types.Interface
-
- // Workaround for the go/types bug golang/go#61561: instances produced during
- // instantiation may contain incomplete interfaces. Here we only complete the
- // underlying type of the instance, which is the most common case but doesn't
- // handle parameterized interface literals defined deeper in the type.
- instanceList []types.Type // instances for later completion (see golang/go#61561)
-
- // Arguments for calls to SetConstraint that are deferred due to recursive types
- later []setConstraintArgs
-
- indent int // for tracing support
-}
-
-func (p *iimporter) trace(format string, args ...any) {
- if !trace {
- // Call sites should also be guarded, but having this check here allows
- // easily enabling/disabling debug trace statements.
- return
- }
- fmt.Printf(strings.Repeat("..", p.indent)+format+"\n", args...)
-}
-
-func (p *iimporter) doDecl(pkg *types.Package, name string) {
- if debug {
- p.trace("import decl %s", name)
- p.indent++
- defer func() {
- p.indent--
- p.trace("=> %s", name)
- }()
- }
- // See if we've already imported this declaration.
- if obj := pkg.Scope().Lookup(name); obj != nil {
- return
- }
-
- off, ok := p.pkgIndex[pkg][name]
- if !ok {
- // In deep mode, the index should be complete. In shallow
- // mode, we should have already recursively loaded necessary
- // dependencies so the above Lookup succeeds.
- errorf("%v.%v not in index", pkg, name)
- }
-
- r := &importReader{p: p}
- r.declReader.Reset(p.declData[off:])
-
- r.obj(pkg, name)
-}
-
-func (p *iimporter) stringAt(off uint64) string {
- if s, ok := p.stringCache[off]; ok {
- return s
- }
-
- slen, n := binary.Uvarint(p.stringData[off:])
- if n <= 0 {
- errorf("varint failed")
- }
- spos := off + uint64(n)
- s := string(p.stringData[spos : spos+slen])
- p.stringCache[off] = s
- return s
-}
-
-// fileAt returns the decoded token.File for index, decoding it lazily
-// (avoiding work for files of already-complete dependencies in deep mode).
-func (p *iimporter) fileAt(index int) *token.File {
- file := p.fileCache[index]
- if file == nil {
- off := p.fileOffset[index]
- file = p.decodeFile(intReader{bytes.NewReader(p.fileData[off:]), p.ipath})
- p.fileCache[index] = file
- }
- return file
-}
-
-func (p *iimporter) decodeFile(rd intReader) *token.File {
- filename := p.stringAt(rd.uint64())
- size := int(rd.uint64())
- nlines := int(rd.uint64()) // total line count (see TODO below)
- file := p.fset.AddFile(filename, -1, size)
-
- avg := size / max(1, nlines)
- sparse := readLines(rd, avg)
-
- // Expand the sparse line starts into a dense slice for SetLines,
- // which requires a strictly increasing sequence of offsets < size.
- //
- // We truncate the line table after the last needed line: lines
- // beyond it are never referenced by any encoded position, and
- // this saves memory. (The cost is that File.LineCount is not
- // faithful.)
- //
- // Each gap (prev, line.index) between needed lines is filled with
- // consecutive offsets ending at line.offset - 1. Because the
- // original file had at least (line.index - prev - 1) bytes of
- // intervening lines, the first filler offset is >= the true end of
- // line prev, so every byte on a needed line---such as the end of an
- // identifier [start, start+len(name)]---remains on that line. This
- // avoids having to record the actual end offset of each needed line.
- //
- // TODO(adonovan): the dense line table required by SetLines
- // dominates the decoder's allocation; most of its entries are
- // filler. When this code moves to std, consider using go/token
- // internals to install a sparse (or more compact) line table,
- // which would also permit a faithful LineCount using nlines.
- //
- // TODO(adonovan): let Decode calls that share a FileSet also share
- // token.Files that are commonly mentioned by deep export data
- // (e.g. reflect/value.go), merging their needed lines.
- //
- // Neither TODO requires a change to the format.
- var lines []int
- if n := len(sparse); n > 0 {
- lines = make([]int, sparse[n-1].index+1)
- prev := 0
- for _, line := range sparse {
- for j := prev + 1; j < line.index; j++ {
- lines[j] = line.offset - (line.index - j)
- }
- lines[line.index] = line.offset
- prev = line.index
- }
- }
- if len(lines) > 1 && !file.SetLines(lines) { // AddFile already set lines to []int{0}
- errorf("SetLines failed: %d", lines) // can't happen
- }
-
- // Restore //line directive information (alternative positions).
- // See writeLineInfos.
- offset := 0
- for n := int(rd.uint64()); n > 0; n-- {
- offset += int(rd.uint64())
- altFile := p.stringAt(rd.uint64())
- line := int(rd.uint64())
- column := int(rd.uint64())
- file.AddLineColumnInfo(offset, altFile, line, column)
- }
- return file
-}
-
-// readLines reads a sparse list of line starts. See [writeLines].
-func readLines(rd intReader, avg int) []lineStart {
- lines := make([]lineStart, rd.uint64())
- var prev lineStart
- for i := range lines {
- index := prev.index + int(rd.uint64())
- offset := predictLineStart(prev, index, avg) + int(rd.int64())
- lines[i] = lineStart{index, offset}
- prev = lines[i]
- }
- return lines
-}
-
-func (p *iimporter) pkgAt(off uint64) *types.Package {
- if pkg, ok := p.pkgCache[off]; ok {
- return pkg
- }
- path := p.stringAt(off)
- errorf("missing package %q in %q", path, p.ipath)
- return nil
-}
-
-func (p *iimporter) typAt(off uint64, base *types.Named) types.Type {
- if t, ok := p.typCache[off]; ok && canReuse(base, t) {
- return t
- }
-
- if off < predeclReserved {
- errorf("predeclared type missing from cache: %v", off)
- }
-
- r := &importReader{p: p}
- r.declReader.Reset(p.declData[off-predeclReserved:])
- t := r.doType(base)
-
- if canReuse(base, t) {
- p.typCache[off] = t
- }
- return t
-}
-
-// canReuse reports whether the type rhs on the RHS of the declaration for def
-// may be re-used.
-//
-// Specifically, if def is non-nil and rhs is an interface type with methods, it
-// may not be re-used because we have a convention of setting the receiver type
-// for interface methods to def.
-func canReuse(def *types.Named, rhs types.Type) bool {
- if def == nil {
- return true
- }
- iface, _ := types.Unalias(rhs).(*types.Interface)
- if iface == nil {
- return true
- }
- // Don't use iface.Empty() here as iface may not be complete.
- return iface.NumEmbeddeds() == 0 && iface.NumExplicitMethods() == 0
-}
-
-type importReader struct {
- p *iimporter
- declReader bytes.Reader
-
- // posV0/posV1 state
- prevFile string
- prevLine int64
- prevColumn int64
-
- // posV3 state (initially file 0, offset 0)
- prevFileIdx int
- prevOffset int64
-}
-
-// markBlack is redefined in iimport_go123.go, to work around golang/go#69912.
-//
-// If TypeNames are not marked black (in the sense of go/types cycle
-// detection), they may be mutated when dot-imported. Fix this by punching a
-// hole through the type, when compiling with Go 1.23. (The bug has been fixed
-// for 1.24, but the fix was not worth back-porting).
-var markBlack = func(name *types.TypeName) {}
-
-// obj decodes and declares the package-level object denoted by (pkg, name).
-func (r *importReader) obj(pkg *types.Package, name string) {
- tag := r.byte()
- pos := r.pos()
-
- switch tag {
- case aliasTag, genericAliasTag:
- var tparams []*types.TypeParam
- if tag == genericAliasTag {
- tparams = r.tparamList()
- }
- obj := types.NewTypeName(pos, pkg, name, nil)
- types.NewAlias(obj, r.typ()).SetTypeParams(tparams)
- markBlack(obj) // workaround for golang/go#69912
- r.declare(obj)
-
- case constTag:
- typ, val := r.value()
-
- r.declare(types.NewConst(pos, pkg, name, typ, val))
-
- case funcTag, genericFuncTag:
- var tparams []*types.TypeParam
- if tag == genericFuncTag {
- tparams = r.tparamList()
- }
- sig := r.signature(pkg, nil, nil, tparams)
- r.declare(types.NewFunc(pos, pkg, name, sig))
-
- case typeTag, genericTypeTag:
- // Types can be recursive. We need to setup a stub
- // declaration before recursing.
- obj := types.NewTypeName(pos, pkg, name, nil)
- named := types.NewNamed(obj, nil, nil)
-
- markBlack(obj) // workaround for golang/go#69912
-
- // Declare obj before calling r.tparamList, so the new type name is recognized
- // if used in the constraint of one of its own typeparams (see #48280).
- r.declare(obj)
- if tag == genericTypeTag {
- tparams := r.tparamList()
- named.SetTypeParams(tparams)
- }
-
- underlying := r.p.typAt(r.uint64(), named).Underlying()
- named.SetUnderlying(underlying)
-
- if !isInterface(underlying) {
- for n := r.uint64(); n > 0; n-- {
- mpos := r.pos()
- mname := r.ident()
- var tpars []*types.TypeParam
- if r.p.version >= iexportVersionGenericMethods && r.bool() {
- tpars = r.tparamList()
- }
- recv := r.param(pkg, types.RecvVar)
-
- // If the receiver has any targs, set those as the
- // rparams of the method (since those are the
- // typeparams being used in the method sig/body).
- //
- // Avoid dependency on typesinternal.RecvBase here.
- t := recv.Type()
- if ptr, ok := types.Unalias(t).(*types.Pointer); ok {
- t = ptr.Elem()
- }
- targs := types.Unalias(t).(*types.Named).TypeArgs()
- var rparams []*types.TypeParam
- if targs.Len() > 0 {
- rparams = make([]*types.TypeParam, targs.Len())
- for i := range rparams {
- rparams[i] = types.Unalias(targs.At(i)).(*types.TypeParam)
- }
- }
- msig := r.signature(pkg, recv, rparams, tpars)
- named.AddMethod(types.NewFunc(mpos, pkg, mname, msig))
- }
- }
-
- case typeParamTag:
- // We need to "declare" a typeparam in order to have a name that
- // can be referenced recursively (if needed) in the type param's
- // bound.
- if r.p.version < iexportVersionGenerics {
- errorf("unexpected type param type")
- }
- name0 := tparamName(name)
- tn := types.NewTypeName(pos, pkg, name0, nil)
- t := types.NewTypeParam(tn, nil)
-
- // To handle recursive references to the typeparam within its
- // bound, save the partial type in tparamIndex before reading the bounds.
- id := ident{pkg, name}
- r.p.tparamIndex[id] = t
- var implicit bool
- if r.p.version >= iexportVersionGo1_18 {
- implicit = r.bool()
- }
- constraint := r.typ()
- if implicit {
- iface, _ := types.Unalias(constraint).(*types.Interface)
- if iface == nil {
- errorf("non-interface constraint marked implicit")
- }
- iface.MarkImplicit()
- }
- // The constraint type may not be complete, if we
- // are in the middle of a type recursion involving type
- // constraints. So, we defer SetConstraint until we have
- // completely set up all types in ImportData.
- r.p.later = append(r.p.later, setConstraintArgs{t: t, constraint: constraint})
-
- case varTag:
- typ := r.typ()
-
- v := types.NewVar(pos, pkg, name, typ)
- v.SetKind(types.PackageVar)
- r.declare(v)
-
- default:
- errorf("unexpected tag: %v", tag)
- }
-}
-
-func (r *importReader) declare(obj types.Object) {
- obj.Pkg().Scope().Insert(obj)
-}
-
-func (r *importReader) value() (typ types.Type, val constant.Value) {
- typ = r.typ()
- if r.p.version >= iexportVersionGo1_18 {
- // TODO: add support for using the kind.
- if constant.Kind(r.int64()) == constant.Unknown {
- // The exporter writes no value for unknown constants (go.dev/issue/60605).
- return typ, constant.MakeUnknown()
- }
- }
-
- switch b := typ.Underlying().(*types.Basic); b.Info() & types.IsConstType {
- case types.IsBoolean:
- val = constant.MakeBool(r.bool())
-
- case types.IsString:
- val = constant.MakeString(r.string())
-
- case types.IsInteger:
- var x big.Int
- r.mpint(&x, b)
- val = constant.Make(&x)
-
- case types.IsFloat:
- val = r.float(b)
-
- case types.IsComplex:
- re := r.float(b)
- im := r.float(b)
- val = constant.BinaryOp(re, token.ADD, constant.MakeImag(im))
-
- default:
- if b.Kind() == types.Invalid {
- val = constant.MakeUnknown()
- return
- }
- errorf("unexpected type %v", typ) // panics
- panic("unreachable")
- }
-
- return
-}
-
-func intSize(b *types.Basic) (signed bool, maxBytes uint) {
- if (b.Info() & types.IsUntyped) != 0 {
- return true, untypedMaxBytes
- }
-
- switch b.Kind() {
- case types.Float32, types.Complex64:
- return true, 3
- case types.Float64, types.Complex128:
- return true, 7
- }
-
- signed = (b.Info() & types.IsUnsigned) == 0
- switch b.Kind() {
- case types.Int8, types.Uint8:
- maxBytes = 1
- case types.Int16, types.Uint16:
- maxBytes = 2
- case types.Int32, types.Uint32:
- maxBytes = 4
- default:
- maxBytes = 8
- }
-
- return
-}
-
-func (r *importReader) mpint(x *big.Int, typ *types.Basic) {
- signed, maxBytes := intSize(typ)
-
- maxSmall := 256 - maxBytes
- if signed {
- maxSmall = 256 - 2*maxBytes
- }
- if maxBytes == 1 {
- maxSmall = 256
- }
-
- n, _ := r.declReader.ReadByte()
- if uint(n) < maxSmall {
- v := int64(n)
- if signed {
- v >>= 1
- if n&1 != 0 {
- v = ^v
- }
- }
- x.SetInt64(v)
- return
- }
-
- v := -n
- if signed {
- v = -(n &^ 1) >> 1
- }
- if v < 1 || uint(v) > maxBytes {
- errorf("weird decoding: %v, %v => %v", n, signed, v)
- }
- b := make([]byte, v)
- io.ReadFull(&r.declReader, b)
- x.SetBytes(b)
- if signed && n&1 != 0 {
- x.Neg(x)
- }
-}
-
-func (r *importReader) mpfloat(typ *types.Basic) constant.Value {
- var mant big.Int
- r.mpint(&mant, typ)
- var f big.Float
- f.SetInt(&mant)
- if f.Sign() != 0 {
- f.SetMantExp(&f, int(r.int64()))
- }
- return constant.Make(&f)
-}
-
-// float decodes a float constant encoded by (*exportWriter).float.
-func (r *importReader) float(typ *types.Basic) constant.Value {
- if r.p.version < iexportVersionRationalFloats {
- // 512-bit binary f.p. (legacy)
- return r.mpfloat(typ)
- }
- switch tag := r.uint64(); tag {
- case floatTagInt:
- // exact integer
- var n big.Int
- r.mpint(&n, types.Typ[types.UntypedFloat])
- return constant.ToFloat(constant.Make(&n))
- case floatTagRat:
- // exact rational
- num := r.bigInt()
- denom := r.bigInt()
- return constant.Make(new(big.Rat).SetFrac(num, denom))
- case floatTagFloat:
- // 512-bit binary f.p.
- return r.mpfloat(typ)
- default:
- errorf("unknown float tag %d", tag)
- panic("unreachable")
- }
-}
-
-// bigInt decodes an integer encoded by (*exportWriter).bigInt.
-func (r *importReader) bigInt() *big.Int {
- v := new(big.Int).SetBytes([]byte(r.string())) // (big endian)
- if r.bool() {
- v.Neg(v)
- }
- return v
-}
-
-func (r *importReader) ident() string {
- return r.string()
-}
-
-func (r *importReader) qualifiedIdent() (*types.Package, string) {
- name := r.string()
- pkg := r.pkg()
- return pkg, name
-}
-
-func (r *importReader) pos() token.Pos {
- if r.p.version >= iexportVersionFullPos {
- return r.posV3()
- }
- if r.p.version >= iexportVersionPosCol {
- r.posV1()
- } else {
- r.posV0()
- }
-
- if r.prevFile == "" && r.prevLine == 0 && r.prevColumn == 0 {
- return token.NoPos
- }
- return r.p.fake.pos(r.prevFile, int(r.prevLine), int(r.prevColumn))
-}
-
-func (r *importReader) posV0() {
- delta := r.int64()
- if delta != deltaNewFile {
- r.prevLine += delta
- } else if l := r.int64(); l == -1 {
- r.prevLine += deltaNewFile
- } else {
- r.prevFile = r.string()
- r.prevLine = l
- }
-}
-
-func (r *importReader) posV1() {
- delta := r.int64()
- r.prevColumn += delta >> 1
- if delta&1 != 0 {
- delta = r.int64()
- r.prevLine += delta >> 1
- if delta&1 != 0 {
- r.prevFile = r.string()
- }
- }
-}
-
-// posV3 decodes a position. See [exportWriter.posV3] for the encoding.
-func (r *importReader) posV3() token.Pos {
- switch x := r.int64(); {
- case x == -1: // NoPos
- return token.NoPos
- case x&1 == 0: // same file
- r.prevOffset += x >> 1
- default: // new file
- r.prevFileIdx = int(x >> 1)
- r.prevOffset = int64(r.uint64())
- }
- return r.p.fileAt(r.prevFileIdx).Pos(int(r.prevOffset))
-}
-
-func (r *importReader) typ() types.Type {
- return r.p.typAt(r.uint64(), nil)
-}
-
-func isInterface(t types.Type) bool {
- _, ok := types.Unalias(t).(*types.Interface)
- return ok
-}
-
-func (r *importReader) pkg() *types.Package { return r.p.pkgAt(r.uint64()) }
-func (r *importReader) string() string { return r.p.stringAt(r.uint64()) }
-
-func (r *importReader) doType(base *types.Named) (res types.Type) {
- k := r.kind()
- if debug {
- r.p.trace("importing type %d (base: %v)", k, base)
- r.p.indent++
- defer func() {
- r.p.indent--
- r.p.trace("=> %s", res)
- }()
- }
- switch k {
- default:
- errorf("unexpected kind tag in %q: %v", r.p.ipath, k)
- return nil
-
- case aliasType, definedType:
- pkg, name := r.qualifiedIdent()
- r.p.doDecl(pkg, name)
- return pkg.Scope().Lookup(name).(*types.TypeName).Type()
- case pointerType:
- return types.NewPointer(r.typ())
- case sliceType:
- return types.NewSlice(r.typ())
- case arrayType:
- n := r.uint64()
- return types.NewArray(r.typ(), int64(n))
- case chanType:
- dir := chanDir(int(r.uint64()))
- return types.NewChan(dir, r.typ())
- case mapType:
- return types.NewMap(r.typ(), r.typ())
- case signatureType:
- paramPkg := r.pkg()
- return r.signature(paramPkg, nil, nil, nil)
-
- case structType:
- fieldPkg := r.pkg()
-
- fields := make([]*types.Var, r.uint64())
- tags := make([]string, len(fields))
- for i := range fields {
- fpos := r.pos()
- fname := r.ident()
- ftyp := r.typ()
- emb := r.bool()
- tag := r.string()
-
- // TODO(golang/go#61674): fields of instances of literals of
- // other packages should preserve identity (or Origin); see
- // exportWriter.externalLiteral.
- fields[i] = types.NewField(fpos, fieldPkg, fname, ftyp, emb)
- tags[i] = tag
- }
- return types.NewStruct(fields, tags)
-
- case interfaceType:
- methodPkg := r.pkg() // qualifies methods and their param/result vars
-
- embeddeds := make([]types.Type, r.uint64())
- for i := range embeddeds {
- _ = r.pos()
- embeddeds[i] = r.typ()
- }
-
- methods := make([]*types.Func, r.uint64())
- for i := range methods {
- mpos := r.pos()
- mname := r.ident()
-
- // TODO(mdempsky): Matches bimport.go, but I
- // don't agree with this.
- var recv *types.Var
- if base != nil {
- recv = types.NewVar(token.NoPos, methodPkg, "", base)
- recv.SetKind(types.RecvVar)
- }
- msig := r.signature(methodPkg, recv, nil, nil)
-
- // TODO(golang/go#61674): as for struct fields.
- methods[i] = types.NewFunc(mpos, methodPkg, mname, msig)
- }
-
- typ := types.NewInterfaceType(methods, embeddeds)
- r.p.interfaceList = append(r.p.interfaceList, typ)
- return typ
-
- case typeParamType:
- if r.p.version < iexportVersionGenerics {
- errorf("unexpected type param type")
- }
- pkg, name := r.qualifiedIdent()
- id := ident{pkg, name}
- if t, ok := r.p.tparamIndex[id]; ok {
- // We're already in the process of importing this typeparam.
- return t
- }
- // Otherwise, import the definition of the typeparam now.
- r.p.doDecl(pkg, name)
- return r.p.tparamIndex[id]
-
- case instanceType:
- if r.p.version < iexportVersionGenerics {
- errorf("unexpected instantiation type")
- }
- // pos does not matter for instances: they are positioned on the original
- // type.
- _ = r.pos()
- len := r.uint64()
- targs := make([]types.Type, len)
- for i := range targs {
- targs[i] = r.typ()
- }
- baseType := r.typ()
- // The imported instantiated type doesn't include any methods, so
- // we must always use the methods of the base (orig) type.
- // TODO provide a non-nil *Environment
- t, _ := types.Instantiate(nil, baseType, targs, false)
-
- // Workaround for golang/go#61561. See the doc for instanceList for details.
- r.p.instanceList = append(r.p.instanceList, t)
- return t
-
- case unionType:
- if r.p.version < iexportVersionGenerics {
- errorf("unexpected instantiation type")
- }
- terms := make([]*types.Term, r.uint64())
- for i := range terms {
- terms[i] = types.NewTerm(r.bool(), r.typ())
- }
- return types.NewUnion(terms)
-
- case externalType:
- if !r.p.shallow {
- errorf("unexpected external type in deep export data")
- }
- t := r.literalRef()
- switch t.(type) {
- case *types.Struct, *types.Interface:
- default:
- errorf("external type %v is not a struct or interface literal", t)
- }
- return t
- }
-}
-
-func (r *importReader) kind() itag {
- return itag(r.uint64())
-}
-
-// literalRef decodes a reference to a struct or interface literal
-// of another package, written by [exportWriter.externalLiteral].
-func (r *importReader) literalRef() types.Type {
- pkg := r.pkg()
- path := typePath{root: r.string()}
- path.steps = make([]int, r.uint64())
- for i := range path.steps {
- path.steps[i] = int(r.uint64())
- }
- return resolveTypePath(pkg, path)
-}
-
-func (r *importReader) signature(paramPkg *types.Package, recv *types.Var, rparams []*types.TypeParam, tparams []*types.TypeParam) *types.Signature {
- params := r.paramList(paramPkg, types.ParamVar)
- results := r.paramList(paramPkg, types.ResultVar)
- variadic := params.Len() > 0 && r.bool()
- return types.NewSignatureType(recv, rparams, tparams, params, results, variadic)
-}
-
-func (r *importReader) tparamList() []*types.TypeParam {
- n := r.uint64()
- if n == 0 {
- return nil
- }
- xs := make([]*types.TypeParam, n)
- for i := range xs {
- // Note: the standard library importer is tolerant of nil types here,
- // though would panic in SetTypeParams.
- xs[i] = types.Unalias(r.typ()).(*types.TypeParam)
- }
- return xs
-}
-
-func (r *importReader) paramList(pkg *types.Package, kind types.VarKind) *types.Tuple {
- xs := make([]*types.Var, r.uint64())
- for i := range xs {
- xs[i] = r.param(pkg, kind)
- }
- return types.NewTuple(xs...)
-}
-
-func (r *importReader) param(pkg *types.Package, kind types.VarKind) *types.Var {
- pos := r.pos()
- name := r.ident()
- typ := r.typ()
- param := types.NewParam(pos, pkg, name, typ)
- param.SetKind(kind) // ∈ {Recv,Param,Result}Var
- return param
-}
-
-func (r *importReader) bool() bool {
- return r.uint64() != 0
-}
-
-func (r *importReader) int64() int64 {
- n, err := binary.ReadVarint(&r.declReader)
- if err != nil {
- errorf("readVarint: %v", err)
- }
- return n
-}
-
-func (r *importReader) uint64() uint64 {
- n, err := binary.ReadUvarint(&r.declReader)
- if err != nil {
- errorf("readUvarint: %v", err)
- }
- return n
-}
-
-func (r *importReader) byte() byte {
- x, err := r.declReader.ReadByte()
- if err != nil {
- errorf("declReader.ReadByte: %v", err)
- }
- return x
-}
-
-type byPath []*types.Package
-
-func (a byPath) Len() int { return len(a) }
-func (a byPath) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
-func (a byPath) Less(i, j int) bool { return a[i].Path() < a[j].Path() }
diff --git a/src/cmd/vendor/golang.org/x/tools/internal/exportdata/predeclared.go b/src/cmd/vendor/golang.org/x/tools/internal/exportdata/predeclared.go
deleted file mode 100644
index 6468a9efc2..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/internal/exportdata/predeclared.go
+++ /dev/null
@@ -1,92 +0,0 @@
-// Copyright 2024 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package exportdata
-
-import (
- "go/types"
- "sync"
- // This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-)
-
-// predecl is a cache for the predeclared types in types.Universe.
-//
-// Cache a distinct result based on the runtime value of any.
-// The pointer value of the any type varies based on GODEBUG settings.
-var predeclMu sync.Mutex
-var predecl map[types.Type][]types.Type
-
-func predeclared() []types.Type {
- anyt := types.Universe.Lookup("any").Type()
-
- predeclMu.Lock()
- defer predeclMu.Unlock()
-
- if pre, ok := predecl[anyt]; ok {
- return pre
- }
-
- if predecl == nil {
- predecl = make(map[types.Type][]types.Type)
- }
-
- decls := []types.Type{ // basic types
- types.Typ[types.Bool],
- types.Typ[types.Int],
- types.Typ[types.Int8],
- types.Typ[types.Int16],
- types.Typ[types.Int32],
- types.Typ[types.Int64],
- types.Typ[types.Uint],
- types.Typ[types.Uint8],
- types.Typ[types.Uint16],
- types.Typ[types.Uint32],
- types.Typ[types.Uint64],
- types.Typ[types.Uintptr],
- types.Typ[types.Float32],
- types.Typ[types.Float64],
- types.Typ[types.Complex64],
- types.Typ[types.Complex128],
- types.Typ[types.String],
-
- // basic type aliases
- types.Universe.Lookup("byte").Type(),
- types.Universe.Lookup("rune").Type(),
-
- // error
- types.Universe.Lookup("error").Type(),
-
- // untyped types
- types.Typ[types.UntypedBool],
- types.Typ[types.UntypedInt],
- types.Typ[types.UntypedRune],
- types.Typ[types.UntypedFloat],
- types.Typ[types.UntypedComplex],
- types.Typ[types.UntypedString],
- types.Typ[types.UntypedNil],
-
- // package unsafe
- types.Typ[types.UnsafePointer],
-
- // invalid type
- types.Typ[types.Invalid], // only appears in packages with errors
-
- // used internally by gc; never used by this package or in .a files
- anyType{},
-
- // comparable
- types.Universe.Lookup("comparable").Type(),
-
- // any
- anyt,
- }
-
- predecl[anyt] = decls
- return decls
-}
-
-type anyType struct{}
-
-func (t anyType) Underlying() types.Type { return t }
-func (t anyType) String() string { return "any" }
diff --git a/src/cmd/vendor/golang.org/x/tools/internal/exportdata/typepath.go b/src/cmd/vendor/golang.org/x/tools/internal/exportdata/typepath.go
deleted file mode 100644
index a8c6d48e1c..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/internal/exportdata/typepath.go
+++ /dev/null
@@ -1,209 +0,0 @@
-// Copyright 2026 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package exportdata
-
-// This file defines type paths, which shallow export data uses to
-// refer to struct and interface literals declared in other packages.
-//
-// When doing a shallow import, the importer creates only the local
-// package, and obtains the symbols of dependencies from the client.
-// However, the types of the local package may contain struct or
-// interface literals declared (perhaps deeply) within another package.
-// For example:
-//
-// package a
-// func F() chan *map[string]struct{ X int }
-//
-// package b
-// import "a"
-// var B = a.F()
-//
-// Here the type of b.B contains a struct literal declared in package
-// a. To preserve the identity of the struct type and its field
-// objects, the exporter does not encode the literal, but instead
-// records a path to it from the API of package a, and the importer
-// follows that path within its symbols for package a.
-//
-// A path consists of the name of an exported package-level object,
-// followed by a sequence of indices, each selecting a component of the
-// current type (an element, field, parameter, method, and so on).
-//
-// Within the path's package, the traversal descends into the
-// package's own named types, even unexported ones, whenever it
-// reaches them; it does not descend into the named types of other
-// packages, nor into instances. Export data includes the same set of
-// declarations for a package, so every path found by the exporter is
-// valid within any representation of the package, whether
-// type-checked from source or imported from export data.
-//
-// The traversal does not descend into type parameters or their
-// constraints: a literal reachable only through a constraint
-// cannot appear in the types of another package.
-//
-// A literal created by instantiation (for example, the underlying type
-// of b.B in "type B a.A[int]") cannot be reached by destructuring.
-// Such literals are encoded in full; see the TODO in
-// [exportWriter.externalLiteral].
-//
-// Unlike objectpath, this encoding is part of the export data
-// format, and is versioned with it.
-
-import (
- "go/types"
- "iter"
- "slices"
-)
-
-// A typePath denotes a type relative to its package, expressed as a
-// sequence of type-destructuring operations applied to the type of a
-// package-level object.
-type typePath struct {
- root string // name of an exported package-level object
- steps []int // component indices, starting from the root object's type
-}
-
-// newTypeIndex returns the canonical paths of the literal struct and
-// interface types reachable from the API of pkg.
-//
-// (Used during export.)
-func newTypeIndex(pkg *types.Package) map[types.Type]typePath {
- var (
- paths = make(map[types.Type]typePath) // literal -> first path found
- seen = make(map[*types.Named]bool)
- root string // name of current root object
- visit func(t types.Type, stack []int)
- )
- visit = func(t types.Type, stack []int) {
- switch t := types.Unalias(t).(type) {
- case *types.Named:
- // Descend only into this package's own non-instantiated named types.
- // TODO(golang/go#61674): descending into instances too
- // would find instantiated literals reachable from them; see
- // the TODO in [exportWriter.externalLiteral].
- if t.Obj().Pkg() != pkg || t.TypeArgs().Len() > 0 || seen[t] {
- return
- }
- seen[t] = true
-
- case *types.Struct, *types.Interface:
- if _, ok := paths[t]; ok {
- return // already visited
- }
- paths[t] = typePath{root, slices.Clone(stack)}
- }
-
- // Traverse all child types.
- for i := 0; ; i++ {
- tch, ok := child(t, i)
- if !ok {
- break
- }
- visit(tch, append(stack, i))
- }
- }
- stack := make([]int, 0, 16)
- scope := pkg.Scope()
- for _, name := range scope.Names() { // (deterministic)
- obj := scope.Lookup(name)
- if obj.Exported() {
- root = obj.Name()
- visit(obj.Type(), stack)
- }
- }
- return paths
-}
-
-// literalMembers returns the fields of a struct literal, or the
-// explicit methods of an interface literal.
-func literalMembers(t types.Type) iter.Seq[types.Object] {
- return func(yield func(types.Object) bool) {
- switch t := t.(type) {
- case *types.Struct:
- t.Fields()(func(f *types.Var) bool { return yield(f) })
- case *types.Interface:
- t.ExplicitMethods()(func(m *types.Func) bool { return yield(m) })
- }
- }
-}
-
-// origin returns the origin of member obj (a field or method).
-func origin(obj types.Object) types.Object {
- switch obj := obj.(type) {
- case *types.Var:
- return obj.Origin()
- case *types.Func:
- return obj.Origin()
- }
- return obj
-}
-
-// resolveTypePath returns the type denoted by path within pkg.
-//
-// (Used during import.)
-func resolveTypePath(pkg *types.Package, path typePath) types.Type {
- obj := pkg.Scope().Lookup(path.root)
- if obj == nil {
- errorf("type path: package %s has no member %q", pkg.Path(), path.root)
- }
- t := obj.Type()
- for _, i := range path.steps {
- tch, ok := child(t, i)
- if !ok {
- errorf("type path %s.%s%v: no component %d of %s", pkg.Path(), path.root, path.steps, i, t)
- }
- t = tch
- }
- return types.Unalias(t)
-}
-
-// child returns the ith component type of t, or false if there is
-// none. It is the sole definition of the meaning of a typePath step,
-// used both by the exporter's traversal and by the importer's
-// resolution. The components are, in order:
-//
-// - pointer, slice, array, chan: the element type;
-// - map: the key and element types;
-// - signature: the parameter types, then the result types;
-// - struct: the field types;
-// - interface: the explicit method types;
-// - named: the underlying type, then the method types.
-//
-// Aliases are transparent.
-func child(t types.Type, i int) (types.Type, bool) {
- switch t := types.Unalias(t).(type) {
- case *types.Pointer, *types.Slice, *types.Array, *types.Chan:
- if i == 0 {
- return t.(interface{ Elem() types.Type }).Elem(), true
- }
- case *types.Map:
- switch i {
- case 0:
- return t.Key(), true
- case 1:
- return t.Elem(), true
- }
- case *types.Signature:
- if n := t.Params().Len(); i < n {
- return t.Params().At(i).Type(), true
- } else if i-n < t.Results().Len() {
- return t.Results().At(i - n).Type(), true
- }
- case *types.Struct:
- if i < t.NumFields() {
- return t.Field(i).Type(), true
- }
- case *types.Interface:
- if i < t.NumExplicitMethods() {
- return t.ExplicitMethod(i).Type(), true
- }
- case *types.Named:
- if i == 0 {
- return t.Underlying(), true
- } else if i-1 < t.NumMethods() {
- return t.Method(i - 1).Type(), true
- }
- }
- return nil, false
-}
diff --git a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/codes.go b/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/codes.go
deleted file mode 100644
index 21f44d9656..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/codes.go
+++ /dev/null
@@ -1,79 +0,0 @@
-// Copyright 2021 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pkgbits
-
-// This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-
-// A Code is an enum value that can be encoded into bitstreams.
-//
-// Code types are preferable for enum types, because they allow
-// Decoder to detect desyncs.
-type Code interface {
- // Marker returns the SyncMarker for the Code's dynamic type.
- Marker() SyncMarker
-
- // Value returns the Code's ordinal value.
- Value() int
-}
-
-// A CodeVal distinguishes among go/constant.Value encodings.
-type CodeVal int
-
-func (c CodeVal) Marker() SyncMarker { return SyncVal }
-func (c CodeVal) Value() int { return int(c) }
-
-// Note: These values are public and cannot be changed without
-// updating the go/types importers.
-
-const (
- ValBool CodeVal = iota
- ValString
- ValInt64
- ValBigInt
- ValBigRat
- ValBigFloat
-)
-
-// A CodeType distinguishes among go/types.Type encodings.
-type CodeType int
-
-func (c CodeType) Marker() SyncMarker { return SyncType }
-func (c CodeType) Value() int { return int(c) }
-
-// Note: These values are public and cannot be changed without
-// updating the go/types importers.
-
-const (
- TypeBasic CodeType = iota
- TypeNamed
- TypePointer
- TypeSlice
- TypeArray
- TypeChan
- TypeMap
- TypeSignature
- TypeStruct
- TypeInterface
- TypeUnion
- TypeTypeParam
-)
-
-// A CodeObj distinguishes among go/types.Object encodings.
-type CodeObj int
-
-func (c CodeObj) Marker() SyncMarker { return SyncCodeObj }
-func (c CodeObj) Value() int { return int(c) }
-
-// Note: These values are public and cannot be changed without
-// updating the go/types importers.
-
-const (
- ObjAlias CodeObj = iota
- ObjConst
- ObjType
- ObjFunc
- ObjVar
- ObjStub
-)
diff --git a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/decoder.go b/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/decoder.go
deleted file mode 100644
index f05e2696ee..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/decoder.go
+++ /dev/null
@@ -1,520 +0,0 @@
-// Copyright 2021 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pkgbits
-
-import (
- "encoding/binary"
- "errors"
- "fmt"
- "go/constant"
- "go/token"
- "io"
- "math/big"
- "os"
- "runtime"
- "strings"
- // This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-)
-
-// A PkgDecoder provides methods for decoding a package's Unified IR
-// export data.
-type PkgDecoder struct {
- // version is the file format version.
- version Version
-
- // sync indicates whether the file uses sync markers.
- sync bool
-
- // pkgPath is the package path for the package to be decoded.
- //
- // TODO(mdempsky): Remove; unneeded since CL 391014.
- pkgPath string
-
- // elemData is the full data payload of the encoded package.
- // Elements are densely and contiguously packed together.
- //
- // The last 8 bytes of elemData are the package fingerprint.
- elemData string
-
- // elemEnds stores the byte-offset end positions of element
- // bitstreams within elemData.
- //
- // For example, element I's bitstream data starts at elemEnds[I-1]
- // (or 0, if I==0) and ends at elemEnds[I].
- //
- // Note: elemEnds is indexed by absolute indices, not
- // section-relative indices.
- elemEnds []uint32
-
- // elemEndsEnds stores the index-offset end positions of relocation
- // sections within elemEnds.
- //
- // For example, section K's end positions start at elemEndsEnds[K-1]
- // (or 0, if K==0) and end at elemEndsEnds[K].
- elemEndsEnds [numRelocs]uint32
-
- scratchRelocEnt []RelocEnt
-}
-
-// PkgPath returns the package path for the package
-//
-// TODO(mdempsky): Remove; unneeded since CL 391014.
-func (pr *PkgDecoder) PkgPath() string { return pr.pkgPath }
-
-// SyncMarkers reports whether pr uses sync markers.
-func (pr *PkgDecoder) SyncMarkers() bool { return pr.sync }
-
-// NewPkgDecoder returns a PkgDecoder initialized to read the Unified
-// IR export data from input. pkgPath is the package path for the
-// compilation unit that produced the export data.
-func NewPkgDecoder(pkgPath, input string) PkgDecoder {
- pr := PkgDecoder{
- pkgPath: pkgPath,
- }
-
- // TODO(mdempsky): Implement direct indexing of input string to
- // avoid copying the position information.
-
- r := strings.NewReader(input)
-
- var ver uint32
- assert(binary.Read(r, binary.LittleEndian, &ver) == nil)
- pr.version = Version(ver)
-
- if pr.version >= numVersions {
- panic(fmt.Errorf("cannot decode %q, export data version %d is greater than maximum supported version %d", pkgPath, pr.version, numVersions-1))
- }
-
- if pr.version.Has(Flags) {
- var flags uint32
- assert(binary.Read(r, binary.LittleEndian, &flags) == nil)
- pr.sync = flags&flagSyncMarkers != 0
- }
-
- assert(binary.Read(r, binary.LittleEndian, pr.elemEndsEnds[:]) == nil)
-
- pr.elemEnds = make([]uint32, pr.elemEndsEnds[len(pr.elemEndsEnds)-1])
- assert(binary.Read(r, binary.LittleEndian, pr.elemEnds[:]) == nil)
-
- pos, err := r.Seek(0, io.SeekCurrent)
- assert(err == nil)
-
- pr.elemData = input[pos:]
-
- const fingerprintSize = 8
- assert(len(pr.elemData)-fingerprintSize == int(pr.elemEnds[len(pr.elemEnds)-1]))
-
- return pr
-}
-
-// NumElems returns the number of elements in section k.
-func (pr *PkgDecoder) NumElems(k RelocKind) int {
- count := int(pr.elemEndsEnds[k])
- if k > 0 {
- count -= int(pr.elemEndsEnds[k-1])
- }
- return count
-}
-
-// TotalElems returns the total number of elements across all sections.
-func (pr *PkgDecoder) TotalElems() int {
- return len(pr.elemEnds)
-}
-
-// Fingerprint returns the package fingerprint.
-func (pr *PkgDecoder) Fingerprint() [8]byte {
- var fp [8]byte
- copy(fp[:], pr.elemData[len(pr.elemData)-8:])
- return fp
-}
-
-// AbsIdx returns the absolute index for the given (section, index)
-// pair.
-func (pr *PkgDecoder) AbsIdx(k RelocKind, idx Index) int {
- absIdx := int(idx)
- if k > 0 {
- absIdx += int(pr.elemEndsEnds[k-1])
- }
- if absIdx >= int(pr.elemEndsEnds[k]) {
- panicf("%v:%v is out of bounds; %v", k, idx, pr.elemEndsEnds)
- }
- return absIdx
-}
-
-// DataIdx returns the raw element bitstream for the given (section,
-// index) pair.
-func (pr *PkgDecoder) DataIdx(k RelocKind, idx Index) string {
- absIdx := pr.AbsIdx(k, idx)
-
- var start uint32
- if absIdx > 0 {
- start = pr.elemEnds[absIdx-1]
- }
- end := pr.elemEnds[absIdx]
-
- return pr.elemData[start:end]
-}
-
-// StringIdx returns the string value for the given string index.
-func (pr *PkgDecoder) StringIdx(idx Index) string {
- return pr.DataIdx(RelocString, idx)
-}
-
-// NewDecoder returns a Decoder for the given (section, index) pair,
-// and decodes the given SyncMarker from the element bitstream.
-func (pr *PkgDecoder) NewDecoder(k RelocKind, idx Index, marker SyncMarker) Decoder {
- r := pr.NewDecoderRaw(k, idx)
- r.Sync(marker)
- return r
-}
-
-// TempDecoder returns a Decoder for the given (section, index) pair,
-// and decodes the given SyncMarker from the element bitstream.
-// If possible the Decoder should be RetireDecoder'd when it is no longer
-// needed, this will avoid heap allocations.
-func (pr *PkgDecoder) TempDecoder(k RelocKind, idx Index, marker SyncMarker) Decoder {
- r := pr.TempDecoderRaw(k, idx)
- r.Sync(marker)
- return r
-}
-
-func (pr *PkgDecoder) RetireDecoder(d *Decoder) {
- pr.scratchRelocEnt = d.Relocs
- d.Relocs = nil
-}
-
-// NewDecoderRaw returns a Decoder for the given (section, index) pair.
-//
-// Most callers should use NewDecoder instead.
-func (pr *PkgDecoder) NewDecoderRaw(k RelocKind, idx Index) Decoder {
- r := Decoder{
- common: pr,
- k: k,
- Idx: idx,
- }
-
- r.Data.Reset(pr.DataIdx(k, idx))
- r.Sync(SyncRelocs)
- r.Relocs = make([]RelocEnt, r.Len())
- for i := range r.Relocs {
- r.Sync(SyncReloc)
- r.Relocs[i] = RelocEnt{RelocKind(r.Len()), Index(r.Len())}
- }
-
- return r
-}
-
-func (pr *PkgDecoder) TempDecoderRaw(k RelocKind, idx Index) Decoder {
- r := Decoder{
- common: pr,
- k: k,
- Idx: idx,
- }
-
- r.Data.Reset(pr.DataIdx(k, idx))
- r.Sync(SyncRelocs)
- l := r.Len()
- if cap(pr.scratchRelocEnt) >= l {
- r.Relocs = pr.scratchRelocEnt[:l]
- pr.scratchRelocEnt = nil
- } else {
- r.Relocs = make([]RelocEnt, l)
- }
- for i := range r.Relocs {
- r.Sync(SyncReloc)
- r.Relocs[i] = RelocEnt{RelocKind(r.Len()), Index(r.Len())}
- }
-
- return r
-}
-
-// A Decoder provides methods for decoding an individual element's
-// bitstream data.
-type Decoder struct {
- common *PkgDecoder
-
- Relocs []RelocEnt
- Data strings.Reader
-
- k RelocKind
- Idx Index
-}
-
-func (r *Decoder) checkErr(err error) {
- if err != nil {
- panicf("unexpected decoding error: %w", err)
- }
-}
-
-func (r *Decoder) rawUvarint() uint64 {
- x, err := readUvarint(&r.Data)
- r.checkErr(err)
- return x
-}
-
-// readUvarint is a type-specialized copy of encoding/binary.ReadUvarint.
-// This avoids the interface conversion and thus has better escape properties,
-// which flows up the stack.
-func readUvarint(r *strings.Reader) (uint64, error) {
- var x uint64
- var s uint
- for i := range binary.MaxVarintLen64 {
- b, err := r.ReadByte()
- if err != nil {
- if i > 0 && err == io.EOF {
- err = io.ErrUnexpectedEOF
- }
- return x, err
- }
- if b < 0x80 {
- if i == binary.MaxVarintLen64-1 && b > 1 {
- return x, overflow
- }
- return x | uint64(b)<<s, nil
- }
- x |= uint64(b&0x7f) << s
- s += 7
- }
- return x, overflow
-}
-
-var overflow = errors.New("pkgbits: readUvarint overflows a 64-bit integer")
-
-func (r *Decoder) rawVarint() int64 {
- ux := r.rawUvarint()
-
- // Zig-zag decode.
- x := int64(ux >> 1)
- if ux&1 != 0 {
- x = ^x
- }
- return x
-}
-
-func (r *Decoder) rawReloc(k RelocKind, idx int) Index {
- e := r.Relocs[idx]
- assert(e.Kind == k)
- return e.Idx
-}
-
-// Sync decodes a sync marker from the element bitstream and asserts
-// that it matches the expected marker.
-//
-// If r.common.sync is false, then Sync is a no-op.
-func (r *Decoder) Sync(mWant SyncMarker) {
- if !r.common.sync {
- return
- }
-
- pos, _ := r.Data.Seek(0, io.SeekCurrent)
- mHave := SyncMarker(r.rawUvarint())
- writerPCs := make([]int, r.rawUvarint())
- for i := range writerPCs {
- writerPCs[i] = int(r.rawUvarint())
- }
-
- if mHave == mWant {
- return
- }
-
- // There's some tension here between printing:
- //
- // (1) full file paths that tools can recognize (e.g., so emacs
- // hyperlinks the "file:line" text for easy navigation), or
- //
- // (2) short file paths that are easier for humans to read (e.g., by
- // omitting redundant or irrelevant details, so it's easier to
- // focus on the useful bits that remain).
- //
- // The current formatting favors the former, as it seems more
- // helpful in practice. But perhaps the formatting could be improved
- // to better address both concerns. For example, use relative file
- // paths if they would be shorter, or rewrite file paths to contain
- // "$GOROOT" (like objabi.AbsFile does) if tools can be taught how
- // to reliably expand that again.
-
- fmt.Printf("export data desync: package %q, section %v, index %v, offset %v\n", r.common.pkgPath, r.k, r.Idx, pos)
-
- fmt.Printf("\nfound %v, written at:\n", mHave)
- if len(writerPCs) == 0 {
- fmt.Printf("\t[stack trace unavailable; recompile package %q with -d=syncframes]\n", r.common.pkgPath)
- }
- for _, pc := range writerPCs {
- fmt.Printf("\t%s\n", r.common.StringIdx(r.rawReloc(RelocString, pc)))
- }
-
- fmt.Printf("\nexpected %v, reading at:\n", mWant)
- var readerPCs [32]uintptr // TODO(mdempsky): Dynamically size?
- n := runtime.Callers(2, readerPCs[:])
- for _, pc := range fmtFrames(readerPCs[:n]...) {
- fmt.Printf("\t%s\n", pc)
- }
-
- // We already printed a stack trace for the reader, so now we can
- // simply exit. Printing a second one with panic or base.Fatalf
- // would just be noise.
- os.Exit(1)
-}
-
-// Bool decodes and returns a bool value from the element bitstream.
-func (r *Decoder) Bool() bool {
- r.Sync(SyncBool)
- x, err := r.Data.ReadByte()
- r.checkErr(err)
- assert(x < 2)
- return x != 0
-}
-
-// Int64 decodes and returns an int64 value from the element bitstream.
-func (r *Decoder) Int64() int64 {
- r.Sync(SyncInt64)
- return r.rawVarint()
-}
-
-// Uint64 decodes and returns a uint64 value from the element bitstream.
-func (r *Decoder) Uint64() uint64 {
- r.Sync(SyncUint64)
- return r.rawUvarint()
-}
-
-// Len decodes and returns a non-negative int value from the element bitstream.
-func (r *Decoder) Len() int { x := r.Uint64(); v := int(x); assert(uint64(v) == x); return v }
-
-// Int decodes and returns an int value from the element bitstream.
-func (r *Decoder) Int() int { x := r.Int64(); v := int(x); assert(int64(v) == x); return v }
-
-// Uint decodes and returns a uint value from the element bitstream.
-func (r *Decoder) Uint() uint { x := r.Uint64(); v := uint(x); assert(uint64(v) == x); return v }
-
-// Code decodes a Code value from the element bitstream and returns
-// its ordinal value. It's the caller's responsibility to convert the
-// result to an appropriate Code type.
-//
-// TODO(mdempsky): Ideally this method would have signature "Code[T
-// Code] T" instead, but we don't allow generic methods and the
-// compiler can't depend on generics yet anyway.
-func (r *Decoder) Code(mark SyncMarker) int {
- r.Sync(mark)
- return r.Len()
-}
-
-// Reloc decodes a relocation of expected section k from the element
-// bitstream and returns an index to the referenced element.
-func (r *Decoder) Reloc(k RelocKind) Index {
- r.Sync(SyncUseReloc)
- return r.rawReloc(k, r.Len())
-}
-
-// String decodes and returns a string value from the element
-// bitstream.
-func (r *Decoder) String() string {
- r.Sync(SyncString)
- return r.common.StringIdx(r.Reloc(RelocString))
-}
-
-// Strings decodes and returns a variable-length slice of strings from
-// the element bitstream.
-func (r *Decoder) Strings() []string {
- res := make([]string, r.Len())
- for i := range res {
- res[i] = r.String()
- }
- return res
-}
-
-// Value decodes and returns a constant.Value from the element
-// bitstream.
-func (r *Decoder) Value() constant.Value {
- r.Sync(SyncValue)
- isComplex := r.Bool()
- val := r.scalar()
- if isComplex {
- val = constant.BinaryOp(val, token.ADD, constant.MakeImag(r.scalar()))
- }
- return val
-}
-
-func (r *Decoder) scalar() constant.Value {
- switch tag := CodeVal(r.Code(SyncVal)); tag {
- default:
- panic(fmt.Errorf("unexpected scalar tag: %v", tag))
-
- case ValBool:
- return constant.MakeBool(r.Bool())
- case ValString:
- return constant.MakeString(r.String())
- case ValInt64:
- return constant.MakeInt64(r.Int64())
- case ValBigInt:
- return constant.Make(r.bigInt())
- case ValBigRat:
- num := r.bigInt()
- denom := r.bigInt()
- return constant.Make(new(big.Rat).SetFrac(num, denom))
- case ValBigFloat:
- return constant.Make(r.bigFloat())
- }
-}
-
-func (r *Decoder) bigInt() *big.Int {
- v := new(big.Int).SetBytes([]byte(r.String()))
- if r.Bool() {
- v.Neg(v)
- }
- return v
-}
-
-func (r *Decoder) bigFloat() *big.Float {
- v := new(big.Float).SetPrec(512)
- assert(v.UnmarshalText([]byte(r.String())) == nil)
- return v
-}
-
-// @@@ Helpers
-
-// TODO(mdempsky): These should probably be removed. I think they're a
-// smell that the export data format is not yet quite right.
-
-// PeekPkgPath returns the package path for the specified package
-// index.
-func (pr *PkgDecoder) PeekPkgPath(idx Index) string {
- var path string
- {
- r := pr.TempDecoder(RelocPkg, idx, SyncPkgDef)
- path = r.String()
- pr.RetireDecoder(&r)
- }
- if path == "" {
- path = pr.pkgPath
- }
- return path
-}
-
-// PeekObj returns the package path, object name, and CodeObj for the
-// specified object index.
-func (pr *PkgDecoder) PeekObj(idx Index) (string, string, CodeObj) {
- var ridx Index
- var name string
- var rcode int
- {
- r := pr.TempDecoder(RelocName, idx, SyncObject1)
- r.Sync(SyncSym)
- r.Sync(SyncPkg)
- ridx = r.Reloc(RelocPkg)
- name = r.String()
- rcode = r.Code(SyncCodeObj)
- pr.RetireDecoder(&r)
- }
-
- path := pr.PeekPkgPath(ridx)
- assert(name != "")
-
- tag := CodeObj(rcode)
-
- return path, name, tag
-}
-
-// Version reports the version of the bitstream.
-func (w *Decoder) Version() Version { return w.common.version }
diff --git a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/doc.go b/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/doc.go
deleted file mode 100644
index f5a9badf45..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/doc.go
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright 2022 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Package pkgbits implements low-level coding abstractions for
-// Unified IR's export data format.
-//
-// At a low-level, a package is a collection of bitstream elements.
-// Each element has a "kind" and a dense, non-negative index.
-// Elements can be randomly accessed given their kind and index.
-//
-// Individual elements are sequences of variable-length values (e.g.,
-// integers, booleans, strings, go/constant values, cross-references
-// to other elements). Package pkgbits provides APIs for encoding and
-// decoding these low-level values, but the details of mapping
-// higher-level Go constructs into elements is left to higher-level
-// abstractions.
-//
-// Elements may cross-reference each other with "relocations." For
-// example, an element representing a pointer type has a relocation
-// referring to the element type.
-//
-// Go constructs may be composed as a constellation of multiple
-// elements. For example, a declared function may have one element to
-// describe the object (e.g., its name, type, position), and a
-// separate element to describe its function body. This allows readers
-// some flexibility in efficiently seeking or re-reading data (e.g.,
-// inlining requires re-reading the function body for each inlined
-// call, without needing to re-read the object-level details).
-//
-// This is a copy of internal/pkgbits in the Go implementation.
-package pkgbits
-
-// This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
diff --git a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/encoder.go b/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/encoder.go
deleted file mode 100644
index ac9c8e8b3f..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/encoder.go
+++ /dev/null
@@ -1,393 +0,0 @@
-// Copyright 2021 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pkgbits
-
-import (
- "bytes"
- "crypto/md5"
- "encoding/binary"
- "go/constant"
- "io"
- "math/big"
- "runtime"
- "strings"
- // This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-)
-
-// A PkgEncoder provides methods for encoding a package's Unified IR
-// export data.
-type PkgEncoder struct {
- // version of the bitstream.
- version Version
-
- // elems holds the bitstream for previously encoded elements.
- elems [numRelocs][]string
-
- // stringsIdx maps previously encoded strings to their index within
- // the RelocString section, to allow deduplication. That is,
- // elems[RelocString][stringsIdx[s]] == s (if present).
- stringsIdx map[string]Index
-
- // syncFrames is the number of frames to write at each sync
- // marker. A negative value means sync markers are omitted.
- syncFrames int
-}
-
-// SyncMarkers reports whether pw uses sync markers.
-func (pw *PkgEncoder) SyncMarkers() bool { return pw.syncFrames >= 0 }
-
-// NewPkgEncoder returns an initialized PkgEncoder.
-//
-// syncFrames is the number of caller frames that should be serialized
-// at Sync points. Serializing additional frames results in larger
-// export data files, but can help diagnosing desync errors in
-// higher-level Unified IR reader/writer code. If syncFrames is
-// negative, then sync markers are omitted entirely.
-func NewPkgEncoder(version Version, syncFrames int) PkgEncoder {
- return PkgEncoder{
- version: version,
- stringsIdx: make(map[string]Index),
- syncFrames: syncFrames,
- }
-}
-
-// DumpTo writes the package's encoded data to out0 and returns the
-// package fingerprint.
-func (pw *PkgEncoder) DumpTo(out0 io.Writer) (fingerprint [8]byte) {
- h := md5.New()
- out := io.MultiWriter(out0, h)
-
- writeUint32 := func(x uint32) {
- assert(binary.Write(out, binary.LittleEndian, x) == nil)
- }
-
- writeUint32(uint32(pw.version))
-
- if pw.version.Has(Flags) {
- var flags uint32
- if pw.SyncMarkers() {
- flags |= flagSyncMarkers
- }
- writeUint32(flags)
- }
-
- // Write elemEndsEnds.
- var sum uint32
- for _, elems := range &pw.elems {
- sum += uint32(len(elems))
- writeUint32(sum)
- }
-
- // Write elemEnds.
- sum = 0
- for _, elems := range &pw.elems {
- for _, elem := range elems {
- sum += uint32(len(elem))
- writeUint32(sum)
- }
- }
-
- // Write elemData.
- for _, elems := range &pw.elems {
- for _, elem := range elems {
- _, err := io.WriteString(out, elem)
- assert(err == nil)
- }
- }
-
- // Write fingerprint.
- copy(fingerprint[:], h.Sum(nil))
- _, err := out0.Write(fingerprint[:])
- assert(err == nil)
-
- return
-}
-
-// StringIdx adds a string value to the strings section, if not
-// already present, and returns its index.
-func (pw *PkgEncoder) StringIdx(s string) Index {
- if idx, ok := pw.stringsIdx[s]; ok {
- assert(pw.elems[RelocString][idx] == s)
- return idx
- }
-
- idx := Index(len(pw.elems[RelocString]))
- pw.elems[RelocString] = append(pw.elems[RelocString], s)
- pw.stringsIdx[s] = idx
- return idx
-}
-
-// NewEncoder returns an Encoder for a new element within the given
-// section, and encodes the given SyncMarker as the start of the
-// element bitstream.
-func (pw *PkgEncoder) NewEncoder(k RelocKind, marker SyncMarker) Encoder {
- e := pw.NewEncoderRaw(k)
- e.Sync(marker)
- return e
-}
-
-// NewEncoderRaw returns an Encoder for a new element within the given
-// section.
-//
-// Most callers should use NewEncoder instead.
-func (pw *PkgEncoder) NewEncoderRaw(k RelocKind) Encoder {
- idx := Index(len(pw.elems[k]))
- pw.elems[k] = append(pw.elems[k], "") // placeholder
-
- return Encoder{
- p: pw,
- k: k,
- Idx: idx,
- }
-}
-
-// An Encoder provides methods for encoding an individual element's
-// bitstream data.
-type Encoder struct {
- p *PkgEncoder
-
- Relocs []RelocEnt
- RelocMap map[RelocEnt]uint32
- Data bytes.Buffer // accumulated element bitstream data
-
- encodingRelocHeader bool
-
- k RelocKind
- Idx Index // index within relocation section
-}
-
-// Flush finalizes the element's bitstream and returns its Index.
-func (w *Encoder) Flush() Index {
- var sb strings.Builder
-
- // Backup the data so we write the relocations at the front.
- var tmp bytes.Buffer
- io.Copy(&tmp, &w.Data)
-
- // TODO(mdempsky): Consider writing these out separately so they're
- // easier to strip, along with function bodies, so that we can prune
- // down to just the data that's relevant to go/types.
- if w.encodingRelocHeader {
- panic("encodingRelocHeader already true; recursive flush?")
- }
- w.encodingRelocHeader = true
- w.Sync(SyncRelocs)
- w.Len(len(w.Relocs))
- for _, rEnt := range w.Relocs {
- w.Sync(SyncReloc)
- w.Len(int(rEnt.Kind))
- w.Len(int(rEnt.Idx))
- }
-
- io.Copy(&sb, &w.Data)
- io.Copy(&sb, &tmp)
- w.p.elems[w.k][w.Idx] = sb.String()
-
- return w.Idx
-}
-
-func (w *Encoder) checkErr(err error) {
- if err != nil {
- panicf("unexpected encoding error: %v", err)
- }
-}
-
-func (w *Encoder) rawUvarint(x uint64) {
- var buf [binary.MaxVarintLen64]byte
- n := binary.PutUvarint(buf[:], x)
- _, err := w.Data.Write(buf[:n])
- w.checkErr(err)
-}
-
-func (w *Encoder) rawVarint(x int64) {
- // Zig-zag encode.
- ux := uint64(x) << 1
- if x < 0 {
- ux = ^ux
- }
-
- w.rawUvarint(ux)
-}
-
-func (w *Encoder) rawReloc(r RelocKind, idx Index) int {
- e := RelocEnt{r, idx}
- if w.RelocMap != nil {
- if i, ok := w.RelocMap[e]; ok {
- return int(i)
- }
- } else {
- w.RelocMap = make(map[RelocEnt]uint32)
- }
-
- i := len(w.Relocs)
- w.RelocMap[e] = uint32(i)
- w.Relocs = append(w.Relocs, e)
- return i
-}
-
-func (w *Encoder) Sync(m SyncMarker) {
- if !w.p.SyncMarkers() {
- return
- }
-
- // Writing out stack frame string references requires working
- // relocations, but writing out the relocations themselves involves
- // sync markers. To prevent infinite recursion, we simply trim the
- // stack frame for sync markers within the relocation header.
- var frames []string
- if !w.encodingRelocHeader && w.p.syncFrames > 0 {
- pcs := make([]uintptr, w.p.syncFrames)
- n := runtime.Callers(2, pcs)
- frames = fmtFrames(pcs[:n]...)
- }
-
- // TODO(mdempsky): Save space by writing out stack frames as a
- // linked list so we can share common stack frames.
- w.rawUvarint(uint64(m))
- w.rawUvarint(uint64(len(frames)))
- for _, frame := range frames {
- w.rawUvarint(uint64(w.rawReloc(RelocString, w.p.StringIdx(frame))))
- }
-}
-
-// Bool encodes and writes a bool value into the element bitstream,
-// and then returns the bool value.
-//
-// For simple, 2-alternative encodings, the idiomatic way to call Bool
-// is something like:
-//
-// if w.Bool(x != 0) {
-// // alternative #1
-// } else {
-// // alternative #2
-// }
-//
-// For multi-alternative encodings, use Code instead.
-func (w *Encoder) Bool(b bool) bool {
- w.Sync(SyncBool)
- var x byte
- if b {
- x = 1
- }
- err := w.Data.WriteByte(x)
- w.checkErr(err)
- return b
-}
-
-// Int64 encodes and writes an int64 value into the element bitstream.
-func (w *Encoder) Int64(x int64) {
- w.Sync(SyncInt64)
- w.rawVarint(x)
-}
-
-// Uint64 encodes and writes a uint64 value into the element bitstream.
-func (w *Encoder) Uint64(x uint64) {
- w.Sync(SyncUint64)
- w.rawUvarint(x)
-}
-
-// Len encodes and writes a non-negative int value into the element bitstream.
-func (w *Encoder) Len(x int) { assert(x >= 0); w.Uint64(uint64(x)) }
-
-// Int encodes and writes an int value into the element bitstream.
-func (w *Encoder) Int(x int) { w.Int64(int64(x)) }
-
-// Uint encodes and writes a uint value into the element bitstream.
-func (w *Encoder) Uint(x uint) { w.Uint64(uint64(x)) }
-
-// Reloc encodes and writes a relocation for the given (section,
-// index) pair into the element bitstream.
-//
-// Note: Only the index is formally written into the element
-// bitstream, so bitstream decoders must know from context which
-// section an encoded relocation refers to.
-func (w *Encoder) Reloc(r RelocKind, idx Index) {
- w.Sync(SyncUseReloc)
- w.Len(w.rawReloc(r, idx))
-}
-
-// Code encodes and writes a Code value into the element bitstream.
-func (w *Encoder) Code(c Code) {
- w.Sync(c.Marker())
- w.Len(c.Value())
-}
-
-// String encodes and writes a string value into the element
-// bitstream.
-//
-// Internally, strings are deduplicated by adding them to the strings
-// section (if not already present), and then writing a relocation
-// into the element bitstream.
-func (w *Encoder) String(s string) {
- w.StringRef(w.p.StringIdx(s))
-}
-
-// StringRef writes a reference to the given index, which must be a
-// previously encoded string value.
-func (w *Encoder) StringRef(idx Index) {
- w.Sync(SyncString)
- w.Reloc(RelocString, idx)
-}
-
-// Strings encodes and writes a variable-length slice of strings into
-// the element bitstream.
-func (w *Encoder) Strings(ss []string) {
- w.Len(len(ss))
- for _, s := range ss {
- w.String(s)
- }
-}
-
-// Value encodes and writes a constant.Value into the element
-// bitstream.
-func (w *Encoder) Value(val constant.Value) {
- w.Sync(SyncValue)
- if w.Bool(val.Kind() == constant.Complex) {
- w.scalar(constant.Real(val))
- w.scalar(constant.Imag(val))
- } else {
- w.scalar(val)
- }
-}
-
-func (w *Encoder) scalar(val constant.Value) {
- switch v := constant.Val(val).(type) {
- default:
- panicf("unhandled %v (%v)", val, val.Kind())
- case bool:
- w.Code(ValBool)
- w.Bool(v)
- case string:
- w.Code(ValString)
- w.String(v)
- case int64:
- w.Code(ValInt64)
- w.Int64(v)
- case *big.Int:
- w.Code(ValBigInt)
- w.bigInt(v)
- case *big.Rat:
- w.Code(ValBigRat)
- w.bigInt(v.Num())
- w.bigInt(v.Denom())
- case *big.Float:
- w.Code(ValBigFloat)
- w.bigFloat(v)
- }
-}
-
-func (w *Encoder) bigInt(v *big.Int) {
- b := v.Bytes()
- w.String(string(b)) // TODO: More efficient encoding.
- w.Bool(v.Sign() < 0)
-}
-
-func (w *Encoder) bigFloat(v *big.Float) {
- b := v.Append(nil, 'p', -1)
- w.String(string(b)) // TODO: More efficient encoding.
-}
-
-// Version reports the version of the bitstream.
-func (w *Encoder) Version() Version { return w.p.version }
diff --git a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/flags.go b/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/flags.go
deleted file mode 100644
index 654222745f..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/flags.go
+++ /dev/null
@@ -1,9 +0,0 @@
-// Copyright 2022 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pkgbits
-
-const (
- flagSyncMarkers = 1 << iota // file format contains sync markers
-)
diff --git a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/reloc.go b/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/reloc.go
deleted file mode 100644
index 99494aa31b..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/reloc.go
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2021 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pkgbits
-
-// This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-
-// A RelocKind indicates a particular section within a unified IR export.
-type RelocKind int32
-
-// An Index represents a bitstream element index within a particular
-// section.
-type Index int32
-
-// A relocEnt (relocation entry) is an entry in an element's local
-// reference table.
-//
-// TODO(mdempsky): Rename this too.
-type RelocEnt struct {
- Kind RelocKind
- Idx Index
-}
-
-// Reserved indices within the meta relocation section.
-const (
- PublicRootIdx Index = 0
- PrivateRootIdx Index = 1
-)
-
-const (
- RelocString RelocKind = iota
- RelocMeta
- RelocPosBase
- RelocPkg
- RelocName
- RelocType
- RelocObj
- RelocObjExt
- RelocObjDict
- RelocBody
-
- numRelocs = iota
-)
diff --git a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/support.go b/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/support.go
deleted file mode 100644
index b0011600d2..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/support.go
+++ /dev/null
@@ -1,18 +0,0 @@
-// Copyright 2022 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pkgbits
-
-// This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-import "fmt"
-
-func assert(b bool) {
- if !b {
- panic("assertion failed")
- }
-}
-
-func panicf(format string, args ...any) {
- panic(fmt.Errorf(format, args...))
-}
diff --git a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/sync.go b/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/sync.go
deleted file mode 100644
index 4cf7f1ee39..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/sync.go
+++ /dev/null
@@ -1,137 +0,0 @@
-// Copyright 2021 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pkgbits
-
-import (
- "fmt"
- "runtime"
- "strings"
- // This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-)
-
-// fmtFrames formats a backtrace for reporting reader/writer desyncs.
-func fmtFrames(pcs ...uintptr) []string {
- res := make([]string, 0, len(pcs))
- walkFrames(pcs, func(file string, line int, name string, offset uintptr) {
- // Trim package from function name. It's just redundant noise.
- name = strings.TrimPrefix(name, "cmd/compile/internal/noder.")
-
- res = append(res, fmt.Sprintf("%s:%v: %s +0x%v", file, line, name, offset))
- })
- return res
-}
-
-type frameVisitor func(file string, line int, name string, offset uintptr)
-
-// walkFrames calls visit for each call frame represented by pcs.
-//
-// pcs should be a slice of PCs, as returned by runtime.Callers.
-func walkFrames(pcs []uintptr, visit frameVisitor) {
- if len(pcs) == 0 {
- return
- }
-
- frames := runtime.CallersFrames(pcs)
- for {
- frame, more := frames.Next()
- visit(frame.File, frame.Line, frame.Function, frame.PC-frame.Entry)
- if !more {
- return
- }
- }
-}
-
-// SyncMarker is an enum type that represents markers that may be
-// written to export data to ensure the reader and writer stay
-// synchronized.
-type SyncMarker int
-
-//go:generate stringer -type=SyncMarker -trimprefix=Sync
-
-const (
- _ SyncMarker = iota
-
- // Public markers (known to go/types importers).
-
- // Low-level coding markers.
- SyncEOF
- SyncBool
- SyncInt64
- SyncUint64
- SyncString
- SyncValue
- SyncVal
- SyncRelocs
- SyncReloc
- SyncUseReloc
-
- // Higher-level object and type markers.
- SyncPublic
- SyncPos
- SyncPosBase
- SyncObject
- SyncObject1
- SyncPkg
- SyncPkgDef
- SyncMethod
- SyncType
- SyncTypeIdx
- SyncTypeParamNames
- SyncSignature
- SyncParams
- SyncParam
- SyncCodeObj
- SyncSym
- SyncLocalIdent
- SyncSelector
-
- // Private markers (only known to cmd/compile).
- SyncPrivate
-
- SyncFuncExt
- SyncVarExt
- SyncTypeExt
- SyncPragma
-
- SyncExprList
- SyncExprs
- SyncExpr
- SyncExprType
- SyncAssign
- SyncOp
- SyncFuncLit
- SyncCompLit
-
- SyncDecl
- SyncFuncBody
- SyncOpenScope
- SyncCloseScope
- SyncCloseAnotherScope
- SyncDeclNames
- SyncDeclName
-
- SyncStmts
- SyncBlockStmt
- SyncIfStmt
- SyncForStmt
- SyncSwitchStmt
- SyncRangeStmt
- SyncCaseClause
- SyncCommClause
- SyncSelectStmt
- SyncDecls
- SyncLabeledStmt
- SyncUseObjLocal
- SyncAddLocal
- SyncLinkname
- SyncStmt1
- SyncStmtsEnd
- SyncLabel
- SyncOptLabel
-
- SyncMultiExpr
- SyncRType
- SyncConvRTTI
-)
diff --git a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/syncmarker_string.go b/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/syncmarker_string.go
deleted file mode 100644
index 582ad56d3e..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/syncmarker_string.go
+++ /dev/null
@@ -1,92 +0,0 @@
-// Code generated by "stringer -type=SyncMarker -trimprefix=Sync"; DO NOT EDIT.
-
-package pkgbits
-
-import "strconv"
-
-func _() {
- // An "invalid array index" compiler error signifies that the constant values have changed.
- // Re-run the stringer command to generate them again.
- var x [1]struct{}
- _ = x[SyncEOF-1]
- _ = x[SyncBool-2]
- _ = x[SyncInt64-3]
- _ = x[SyncUint64-4]
- _ = x[SyncString-5]
- _ = x[SyncValue-6]
- _ = x[SyncVal-7]
- _ = x[SyncRelocs-8]
- _ = x[SyncReloc-9]
- _ = x[SyncUseReloc-10]
- _ = x[SyncPublic-11]
- _ = x[SyncPos-12]
- _ = x[SyncPosBase-13]
- _ = x[SyncObject-14]
- _ = x[SyncObject1-15]
- _ = x[SyncPkg-16]
- _ = x[SyncPkgDef-17]
- _ = x[SyncMethod-18]
- _ = x[SyncType-19]
- _ = x[SyncTypeIdx-20]
- _ = x[SyncTypeParamNames-21]
- _ = x[SyncSignature-22]
- _ = x[SyncParams-23]
- _ = x[SyncParam-24]
- _ = x[SyncCodeObj-25]
- _ = x[SyncSym-26]
- _ = x[SyncLocalIdent-27]
- _ = x[SyncSelector-28]
- _ = x[SyncPrivate-29]
- _ = x[SyncFuncExt-30]
- _ = x[SyncVarExt-31]
- _ = x[SyncTypeExt-32]
- _ = x[SyncPragma-33]
- _ = x[SyncExprList-34]
- _ = x[SyncExprs-35]
- _ = x[SyncExpr-36]
- _ = x[SyncExprType-37]
- _ = x[SyncAssign-38]
- _ = x[SyncOp-39]
- _ = x[SyncFuncLit-40]
- _ = x[SyncCompLit-41]
- _ = x[SyncDecl-42]
- _ = x[SyncFuncBody-43]
- _ = x[SyncOpenScope-44]
- _ = x[SyncCloseScope-45]
- _ = x[SyncCloseAnotherScope-46]
- _ = x[SyncDeclNames-47]
- _ = x[SyncDeclName-48]
- _ = x[SyncStmts-49]
- _ = x[SyncBlockStmt-50]
- _ = x[SyncIfStmt-51]
- _ = x[SyncForStmt-52]
- _ = x[SyncSwitchStmt-53]
- _ = x[SyncRangeStmt-54]
- _ = x[SyncCaseClause-55]
- _ = x[SyncCommClause-56]
- _ = x[SyncSelectStmt-57]
- _ = x[SyncDecls-58]
- _ = x[SyncLabeledStmt-59]
- _ = x[SyncUseObjLocal-60]
- _ = x[SyncAddLocal-61]
- _ = x[SyncLinkname-62]
- _ = x[SyncStmt1-63]
- _ = x[SyncStmtsEnd-64]
- _ = x[SyncLabel-65]
- _ = x[SyncOptLabel-66]
- _ = x[SyncMultiExpr-67]
- _ = x[SyncRType-68]
- _ = x[SyncConvRTTI-69]
-}
-
-const _SyncMarker_name = "EOFBoolInt64Uint64StringValueValRelocsRelocUseRelocPublicPosPosBaseObjectObject1PkgPkgDefMethodTypeTypeIdxTypeParamNamesSignatureParamsParamCodeObjSymLocalIdentSelectorPrivateFuncExtVarExtTypeExtPragmaExprListExprsExprExprTypeAssignOpFuncLitCompLitDeclFuncBodyOpenScopeCloseScopeCloseAnotherScopeDeclNamesDeclNameStmtsBlockStmtIfStmtForStmtSwitchStmtRangeStmtCaseClauseCommClauseSelectStmtDeclsLabeledStmtUseObjLocalAddLocalLinknameStmt1StmtsEndLabelOptLabelMultiExprRTypeConvRTTI"
-
-var _SyncMarker_index = [...]uint16{0, 3, 7, 12, 18, 24, 29, 32, 38, 43, 51, 57, 60, 67, 73, 80, 83, 89, 95, 99, 106, 120, 129, 135, 140, 147, 150, 160, 168, 175, 182, 188, 195, 201, 209, 214, 218, 226, 232, 234, 241, 248, 252, 260, 269, 279, 296, 305, 313, 318, 327, 333, 340, 350, 359, 369, 379, 389, 394, 405, 416, 424, 432, 437, 445, 450, 458, 467, 472, 480}
-
-func (i SyncMarker) String() string {
- i -= 1
- if i < 0 || i >= SyncMarker(len(_SyncMarker_index)-1) {
- return "SyncMarker(" + strconv.FormatInt(int64(i+1), 10) + ")"
- }
- return _SyncMarker_name[_SyncMarker_index[i]:_SyncMarker_index[i+1]]
-}
diff --git a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/version.go b/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/version.go
deleted file mode 100644
index 932a92679b..0000000000
--- a/src/cmd/vendor/golang.org/x/tools/internal/pkgbits/version.go
+++ /dev/null
@@ -1,113 +0,0 @@
-// Copyright 2024 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pkgbits
-
-// This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-
-// Version indicates a version of a unified IR bitstream.
-// Each Version indicates the addition, removal, or change of
-// new data in the bitstream.
-//
-// These are serialized to disk and the interpretation remains fixed.
-type Version uint32
-
-const (
- // V0: initial prototype.
- //
- // All data that is not assigned a Field is in version V0
- // and has not been deprecated.
- V0 Version = iota
-
- // V1: adds the Flags uint32 word
- V1
-
- // V2: removes unused legacy fields and supports type parameters for aliases.
- // - remove the legacy "has init" bool from the public root
- // - remove obj's "derived func instance" bool
- // - add a TypeParamNames field to ObjAlias
- // - remove derived info "needed" bool
- V2
-
- // V3: introduces a more compact format for composite literal element lists
- // - negative lengths indicate that (some) elements may have keys
- // - positive lengths indicate that no element has a key
- // - a negative struct field index indicates an embedded field
- V3
-
- // V4: encodes generic methods as standalone function objects
- V4
-
- // V5: encodes the index of methods to preserve relative order
- // of nongeneric and generic methods (go.dev/issue/81188).
- V5
-
- numVersions = iota
-)
-
-// Field denotes a unit of data in the serialized unified IR bitstream.
-// It is conceptually a like field in a structure.
-//
-// We only really need Fields when the data may or may not be present
-// in a stream based on the Version of the bitstream.
-//
-// Unlike much of pkgbits, Fields are not serialized and
-// can change values as needed.
-type Field int
-
-const (
- // Flags in a uint32 in the header of a bitstream
- // that is used to indicate whether optional features are enabled.
- Flags Field = iota
-
- // Deprecated: HasInit was a bool indicating whether a package
- // has any init functions.
- HasInit
-
- // Deprecated: DerivedFuncInstance was a bool indicating
- // whether an object was a function instance.
- DerivedFuncInstance
-
- // ObjAlias has a list of TypeParamNames.
- AliasTypeParamNames
-
- // Deprecated: DerivedInfoNeeded was a bool indicating
- // whether a type was a derived type.
- DerivedInfoNeeded
-
- // Composite literals use a more compact format for element lists.
- CompactCompLiterals
-
- // Generic methods may appear as standalone function objects.
- GenericMethods
-
- // Method index is encoded to preserve relative order of
- // nongeneric and generic methods.
- PreserveMethodOrder
-
- numFields = iota
-)
-
-// introduced is the version a field was added.
-var introduced = [numFields]Version{
- Flags: V1,
- AliasTypeParamNames: V2,
- CompactCompLiterals: V3,
- GenericMethods: V4,
- PreserveMethodOrder: V5,
-}
-
-// removed is the version a field was removed in or 0 for fields
-// that have not yet been deprecated.
-// (So removed[f]-1 is the last version it is included in.)
-var removed = [numFields]Version{
- HasInit: V2,
- DerivedFuncInstance: V2,
- DerivedInfoNeeded: V2,
-}
-
-// Has reports whether field f is present in a bitstream at version v.
-func (v Version) Has(f Field) bool {
- return introduced[f] <= v && (v < removed[f] || removed[f] == V0)
-}
diff --git a/src/cmd/vendor/modules.txt b/src/cmd/vendor/modules.txt
index 4380b25e1c..bdc0c141df 100644
--- a/src/cmd/vendor/modules.txt
+++ b/src/cmd/vendor/modules.txt
@@ -78,10 +78,7 @@ golang.org/x/text/unicode/norm
## explicit; go 1.26.0
golang.org/x/tools/cmd/bisect
golang.org/x/tools/cover
-golang.org/x/tools/go/gcexportdata
golang.org/x/tools/internal/bisect
-golang.org/x/tools/internal/exportdata
-golang.org/x/tools/internal/pkgbits
# rsc.io/markdown v0.0.0-20240306144322-0bf8f97ee8ef
## explicit; go 1.20
rsc.io/markdown
diff --git a/src/go/build/deps_test.go b/src/go/build/deps_test.go
index f3b84ff85b..c0e1f182a1 100644
--- a/src/go/build/deps_test.go
+++ b/src/go/build/deps_test.go
@@ -649,13 +649,11 @@ var depsRules = `
< go/analysis;
# x/tools
- # These are the only allowed dependencies of gcexportdata. Any change here
- # must be mirrored in x/tools/go/gcexportdata/deps_test.go.
+ # These are the only allowed dependencies of x/tools/internal/exportdata.
+ # Any change here must be mirrored in x/tools/deps_test.go.
FMT, STR, crypto/md5, encoding/binary, encoding/json, go/analysis, go/build, go/token, go/types
- < golang.org/x/tools/go/types/objectpath,
- golang.org/x/tools/internal/pkgbits
- < golang.org/x/tools/internal/exportdata
- < golang.org/x/tools/go/gcexportdata;
+ < golang.org/x/tools/go/types/objectpath
+ < golang.org/x/tools/internal/exportdata;
# The vendored golang.org/x/tools analysis framework (passes and
# unitchecker), for cmd/vet and cmd/fix (via internal/analysis/...).
@@ -664,7 +662,7 @@ var depsRules = `
# are x/tools' business; only their imports of other packages, and
# their importers, are policy.
FMT, archive/zip, crypto/sha256, encoding/gob, flag, go/format, log,
- golang.org/x/tools/go/gcexportdata
+ golang.org/x/tools/internal/exportdata
< golang.org/x/tools/...
< internal/analysis/fipsdit, internal/analysis/suite/fix, internal/analysis/suite/vet, internal/analysis/unitchecker;
@@ -677,8 +675,8 @@ var depsRules = `
go/types !< internal/analysis/gotestchecker/protocol;
# go test's analysis driver
- golang.org/x/tools/..., golang.org/x/tools/go/gcexportdata,
- golang.org/x/tools/go/types/objectpath, runtime/debug,
+ golang.org/x/tools/..., golang.org/x/tools/go/types/objectpath,
+ go/types/exportdata, runtime/debug,
internal/analysis/gotestchecker/protocol
< internal/analysis/gotestchecker;
@@ -686,7 +684,7 @@ var depsRules = `
DEBUG, crypto/sha256, go/build, go/types, text/scanner
< internal/exportdata, internal/pkgbits;
- golang.org/x/tools/go/gcexportdata, internal/exportdata, internal/pkgbits
+ go/types/exportdata, internal/exportdata, internal/pkgbits
< go/internal/gcimporter;
internal/exportdata, internal/pkgbits
diff --git a/src/go/internal/gcimporter/gcimporter.go b/src/go/internal/gcimporter/gcimporter.go
index 2f4c191064..259823d784 100644
--- a/src/go/internal/gcimporter/gcimporter.go
+++ b/src/go/internal/gcimporter/gcimporter.go
@@ -10,12 +10,11 @@ import (
"fmt"
"go/token"
"go/types"
+ typesexportdata "go/types/exportdata"
"internal/exportdata"
"internal/pkgbits"
"io"
"os"
-
- "golang.org/x/tools/go/gcexportdata"
)
// Import imports a gc-generated package given its import path and srcDir, adds
@@ -77,8 +76,13 @@ func Import(fset *token.FileSet, packages map[string]*types.Package, path, srcDi
return
}
if peek[0] == 'i' {
- // TODO(adonovan): use go/types/exportdata.
- pkg, err = gcexportdata.Read(buf, fset, packages, path)
+ // Indexed export data, produced by cmd/export (go list -export).
+ var data []byte
+ data, err = io.ReadAll(buf)
+ if err != nil {
+ return
+ }
+ pkg, err = typesexportdata.Decode(fset, path, data, typesexportdata.PackagesFromMap(packages), typesexportdata.DecodeOptions{})
return
}
data, err := exportdata.ReadUnified(buf, false)
diff --git a/src/internal/analysis/gotestchecker/run.go b/src/internal/analysis/gotestchecker/run.go
index ec4b0bb4c8..fee51499b8 100644
--- a/src/internal/analysis/gotestchecker/run.go
+++ b/src/internal/analysis/gotestchecker/run.go
@@ -7,7 +7,6 @@ package gotestchecker
// This file defines the analysis of a single package.
import (
- "bytes"
"encoding/gob"
"encoding/json"
"fmt"
@@ -16,6 +15,7 @@ import (
"go/parser"
"go/token"
"go/types"
+ "go/types/exportdata"
"internal/analysis/gotestchecker/protocol"
"log"
"maps"
@@ -28,8 +28,6 @@ import (
"strings"
"sync"
"sync/atomic"
-
- "golang.org/x/tools/go/gcexportdata"
)
// run analyzes the package described by the named request file (see
@@ -139,8 +137,7 @@ func analyze(areq *protocol.AnalyzeRequest, vars []Var, prof *profiler) error {
if err != nil {
return nil, err
}
- // TODO(adonovan): use go/types/exportdata.
- return gcexportdata.Read(bytes.NewReader(data), fset, imports, path)
+ return exportdata.Decode(fset, path, data, exportdata.PackagesFromMap(imports), exportdata.DecodeOptions{})
})
tc := &types.Config{
Importer: importer,
@@ -185,12 +182,11 @@ func analyze(areq *protocol.AnalyzeRequest, vars []Var, prof *profiler) error {
}
if areq.TypeExport != "" {
if err := prof.doErr(phaseExport, -1, func() error {
- var buf bytes.Buffer
- // TODO(adonovan): use go/types/exportdata.
- if err := gcexportdata.Write(&buf, fset, pkg); err != nil {
+ data, err := exportdata.Encode(fset, pkg, exportdata.EncodeOptions{})
+ if err != nil {
return fmt.Errorf("type export failed: %v", err)
}
- return os.WriteFile(areq.TypeExport, buf.Bytes(), 0666)
+ return os.WriteFile(areq.TypeExport, data, 0666)
}); err != nil {
return err
}
diff --git a/src/vendor/golang.org/x/tools/go/gcexportdata/exportdata.go b/src/vendor/golang.org/x/tools/go/gcexportdata/exportdata.go
deleted file mode 100644
index 3493c5ff32..0000000000
--- a/src/vendor/golang.org/x/tools/go/gcexportdata/exportdata.go
+++ /dev/null
@@ -1,153 +0,0 @@
-// Copyright 2011 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// This file locates the export data within compiler-produced archives.
-// It should be kept in sync with $GOROOT/src/internal/exportdata/exportdata.go.
-
-package gcexportdata
-
-import (
- "bufio"
- "fmt"
- "strings"
- // This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-)
-
-// findExportData positions the reader r at the beginning of the
-// export data section of an underlying cmd/compile created archive
-// file by reading from it. The reader must be positioned at the
-// start of the file before calling this function.
-// This returns the length of the export data in bytes.
-//
-// This function is needed by [gcexportdata.Read], which must
-// accept inputs produced by the last two releases of cmd/compile,
-// plus tip.
-func findExportData(r *bufio.Reader) (size int64, err error) {
- arsize, err := findPackageDefinition(r)
- if err != nil {
- return
- }
- size = int64(arsize)
-
- objapi, headers, err := readObjectHeaders(r)
- if err != nil {
- return
- }
- size -= int64(len(objapi))
- for _, h := range headers {
- size -= int64(len(h))
- }
-
- // Check for the binary export data section header "$$B\n".
- line, err := r.ReadSlice('\n')
- if err != nil {
- return
- }
- hdr := string(line)
- if hdr != "$$B\n" {
- err = fmt.Errorf("unknown export data header: %q", hdr)
- return
- }
- size -= int64(len(hdr))
-
- // For files with a binary export data header "$$B\n",
- // these are always terminated by an end-of-section marker "\n$$\n".
- // So the last bytes must always be this constant.
- //
- // The end-of-section marker is not a part of the export data itself.
- // Do not include these in size.
- //
- // It would be nice to have sanity check that the final bytes after
- // the export data are indeed the end-of-section marker. The split
- // of gcexportdata.NewReader and gcexportdata.Read make checking this
- // ugly so this package gives up enforcing this. The compiler and go/types
- // importer do enforce this, which seems good enough.
- const endofsection = "\n$$\n"
- size -= int64(len(endofsection))
-
- if size < 0 {
- err = fmt.Errorf("invalid size (%d) in the archive file: %d bytes remain without section headers (recompile package)", arsize, size)
- return
- }
-
- return
-}
-
-// findPackageDefinition positions the reader r at the beginning of a package
-// definition file ("__.PKGDEF") within a GC-created archive by reading
-// from it, and returns the size of the package definition file in the archive.
-//
-// The reader must be positioned at the start of the archive file before calling
-// this function, and "__.PKGDEF" is assumed to be the first file in the archive.
-//
-// See cmd/internal/archive for details on the archive format.
-func findPackageDefinition(r *bufio.Reader) (size int, err error) {
- // Uses ReadSlice to limit risk of malformed inputs.
-
- // Read first line to make sure this is an object file.
- line, err := r.ReadSlice('\n')
- if err != nil {
- err = fmt.Errorf("can't find export data (%v)", err)
- return
- }
-
- // Is the first line an archive file signature?
- if string(line) != "!<arch>\n" {
- err = fmt.Errorf("not the start of an archive file (%q)", line)
- return
- }
-
- // package export block should be first
- size = readArchiveHeader(r, "__.PKGDEF")
- if size <= 0 {
- err = fmt.Errorf("not a package file")
- return
- }
-
- return
-}
-
-// readObjectHeaders reads object headers from the reader. Object headers are
-// lines that do not start with an end-of-section marker "$$". The first header
-// is the objabi header. On success, the reader will be positioned at the beginning
-// of the end-of-section marker.
-//
-// It returns an error if any header does not fit in r.Size() bytes.
-func readObjectHeaders(r *bufio.Reader) (objapi string, headers []string, err error) {
- // line is a temporary buffer for headers.
- // Use bounded reads (ReadSlice, Peek) to limit risk of malformed inputs.
- var line []byte
-
- // objapi header should be the first line
- if line, err = r.ReadSlice('\n'); err != nil {
- err = fmt.Errorf("can't find export data (%v)", err)
- return
- }
- objapi = string(line)
-
- // objapi header begins with "go object ".
- if !strings.HasPrefix(objapi, "go object ") {
- err = fmt.Errorf("not a go object file: %s", objapi)
- return
- }
-
- // process remaining object header lines
- for {
- // check for an end of section marker "$$"
- line, err = r.Peek(2)
- if err != nil {
- return
- }
- if string(line) == "$$" {
- return // stop
- }
-
- // read next header
- line, err = r.ReadSlice('\n')
- if err != nil {
- return
- }
- headers = append(headers, string(line))
- }
-}
diff --git a/src/vendor/golang.org/x/tools/go/gcexportdata/exportdata_copy.go b/src/vendor/golang.org/x/tools/go/gcexportdata/exportdata_copy.go
deleted file mode 100644
index 4155c24053..0000000000
--- a/src/vendor/golang.org/x/tools/go/gcexportdata/exportdata_copy.go
+++ /dev/null
@@ -1,89 +0,0 @@
-// Copyright 2026 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package gcexportdata
-
-import (
- "fmt"
- "go/token"
- "go/types"
- "sync"
-)
-
-// The declarations in this file are copied from internal/exportdata.
-
-const (
- // Enable debug during development: it adds some additional checks, and
- // prevents errors from being recovered.
- debug = false
-)
-
-func assert(cond bool) {
- if !cond {
- panic("internal error: assertion failed")
- }
-}
-
-func errorf(format string, args ...any) {
- panic(fmt.Sprintf(format, args...))
-}
-
-// Synthesize a token.Pos
-type fakeFileSet struct {
- fset *token.FileSet
- files map[string]*fileInfo
-}
-
-type fileInfo struct {
- file *token.File
- lastline int
-}
-
-const maxlines = 64 * 1024
-
-func (s *fakeFileSet) pos(file string, line, column int) token.Pos {
- _ = column // TODO(mdempsky): Make use of column.
-
- // Since we don't know the set of needed file positions, we reserve maxlines
- // positions per file. We delay calling token.File.SetLines until all
- // positions have been calculated (by way of fakeFileSet.setLines), so that
- // we can avoid setting unnecessary lines. See also golang/go#46586.
- f := s.files[file]
- if f == nil {
- f = &fileInfo{file: s.fset.AddFile(file, -1, maxlines)}
- s.files[file] = f
- }
- if line > maxlines {
- line = 1
- }
- if line > f.lastline {
- f.lastline = line
- }
-
- // Return a fake position assuming that f.file consists only of newlines.
- return token.Pos(f.file.Base() + line - 1)
-}
-
-func (s *fakeFileSet) setLines() {
- fakeLinesOnce.Do(func() {
- fakeLines = make([]int, maxlines)
- for i := range fakeLines {
- fakeLines[i] = i
- }
- })
- for _, f := range s.files {
- f.file.SetLines(fakeLines[:f.lastline])
- }
-}
-
-var (
- fakeLines []int
- fakeLinesOnce sync.Once
-)
-
-type byPath []*types.Package
-
-func (a byPath) Len() int { return len(a) }
-func (a byPath) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
-func (a byPath) Less(i, j int) bool { return a[i].Path() < a[j].Path() }
diff --git a/src/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go b/src/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go
deleted file mode 100644
index b6bd69a94b..0000000000
--- a/src/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go
+++ /dev/null
@@ -1,223 +0,0 @@
-// Copyright 2016 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Package gcexportdata provides functions for writing and reading
-// export data, a serialized representation of a [types.Package].
-// It describes the API of a Go package, including the names,
-// kinds, types, and locations of all exported declarations.
-//
-// Files produced by [Write] contain only export data and may be passed
-// directly to [Read].
-//
-// Export data may also be obtained using "go list -export -json".
-// The Export field names a file whose format depends on the Go version:
-//
-// - Before Go 1.28, the file is a compiler-produced archive. Use
-// [NewReader] to extract its export data before calling [Read].
-// - Starting with Go 1.28, the file contains only export data. Pass it
-// directly to [Read]; [NewReader] is unnecessary.
-//
-// The export data format evolves with each Go release. As a matter of
-// policy, [Read] supports reading files produced by only the last two
-// Go releases plus tip; see https://go.dev/issue/68898.
-//
-// The name of this package reflects its origins at a time when
-// cmd/compile was named gc, and [Read] parsed export data
-// from .a archives produced by the Go compiler.
-// Support for compiler-produced export data will be removed in Go 1.29.
-// This does not affect files produced by [Write] or by "go list -export"
-// with Go 1.28 or later.
-// For more information on the compiler's export data, see the
-// "Export" section in the GOROOT/src/cmd/compile/README file.
-//
-// # Deprecations
-//
-// The [NewImporter], [Find], and [NewReader] functions are deprecated
-// and should not be used in new code.
-// The [WriteBundle] and [ReadBundle] functions are obsolete experiments
-// and are no longer supported (https://go.dev/issue/69573).
-package gcexportdata
-
-import (
- "bufio"
- "bytes"
- "encoding/json"
- "fmt"
- "go/token"
- "go/types"
- "io"
- "os/exec"
-
- "golang.org/x/tools/internal/exportdata"
-)
-
-// Find returns the name of an object (.o) or archive (.a) file
-// containing type information for the specified import path,
-// using the go command.
-// If no file was found, an empty filename is returned.
-//
-// A relative srcDir is interpreted relative to the current working directory.
-//
-// Find also returns the package's resolved (canonical) import path,
-// reflecting the effects of srcDir and vendoring on importPath.
-//
-// Deprecated: Use the higher-level API in golang.org/x/tools/go/packages,
-// which is more efficient.
-func Find(importPath, srcDir string) (filename, path string) {
- cmd := exec.Command("go", "list", "-json", "-export", "--", importPath)
- cmd.Dir = srcDir
- out, err := cmd.Output()
- if err != nil {
- return "", ""
- }
- var data struct {
- ImportPath string
- Export string
- }
- json.Unmarshal(out, &data)
- return data.Export, data.ImportPath
-}
-
-// NewReader returns a reader for export data read from r. Export data
-// may be read from:
-//
-// - The export data section of an object (.o) or archive file (.a).
-// In this case, the new reader may provide additional trailing data
-// beyond the end of the export data.
-// - The output of [Write] or "go list -export" with Go 1.28 or later.
-// In this case, the new reader contains no trailing data.
-//
-// Deprecated: This package will stop supporting the reading of export
-// data from compiler-produced archive files in Go 1.29. To read files
-// produced by [Write] or "go list -export" with Go 1.28 or later, use
-// [Read] directly instead.
-func NewReader(r io.Reader) (io.Reader, error) {
- buf := bufio.NewReader(r)
- peek, err := buf.Peek(1)
- if err != nil {
- return nil, err
- }
- if peek[0] == 'i' {
- // We were given an output of cmd/export. The entire file is
- // export data.
- return buf, nil
- }
-
- size, err := findExportData(buf)
- if err != nil {
- return nil, err
- }
-
- // We were given an archive and found the __.PKGDEF in it.
- // This tells us the size of the export data, and we don't
- // need to return the entire file.
- return &io.LimitedReader{
- R: buf,
- N: size,
- }, nil
-}
-
-// readAll works the same way as io.ReadAll, but avoids allocations and copies
-// by preallocating a byte slice of the necessary size if the size is known up
-// front. This is always possible when the input is an archive. In that case,
-// NewReader will return the known size using an io.LimitedReader.
-func readAll(r io.Reader) ([]byte, error) {
- if lr, ok := r.(*io.LimitedReader); ok {
- data := make([]byte, lr.N)
- _, err := io.ReadFull(lr, data)
- return data, err
- }
- return io.ReadAll(r)
-}
-
-// Read reads export data from in, decodes it, and returns type
-// information for the package.
-//
-// Read is capable of reading export data produced by [Write] at the
-// same source code version, or by "go list -export" using the last two
-// Go releases (plus tip). Reading files from older Go releases may
-// produce an error.
-//
-// Files produced by [Write] or "go list -export" with Go 1.28 or later
-// may be passed directly to Read. For compiler-produced archives, use
-// [NewReader] to extract the export data first. See the package
-// documentation for the supported formats.
-//
-// The package path (effectively its linker symbol prefix) is
-// specified by path, since unlike the package name, this information
-// may not be recorded in the export data.
-//
-// File position information is added to fset.
-//
-// Read may inspect and add to the imports map to ensure that references
-// within the export data to other packages are consistent. The caller
-// must ensure that imports[path] does not exist, or exists but is
-// incomplete (see types.Package.Complete), and Read inserts the
-// resulting package into this map entry.
-//
-// On return, the state of the reader is undefined.
-func Read(in io.Reader, fset *token.FileSet, imports map[string]*types.Package, path string) (*types.Package, error) {
- data, err := readAll(in)
- if err != nil {
- return nil, fmt.Errorf("reading export data for %q: %v", path, err)
- }
-
- if bytes.HasPrefix(data, []byte("!<arch>")) {
- return nil, fmt.Errorf("can't read export data for %q directly from an archive file (call gcexportdata.NewReader first to extract export data)", path)
- }
-
- // The indexed export format starts with an 'i'; the older
- // binary export format starts with a 'c', 'd', or 'v'
- // (from "version"). Select appropriate importer.
- if len(data) > 0 {
- switch data[0] {
- case 'v', 'c', 'd':
- // binary, produced by cmd/compile till go1.10
- return nil, fmt.Errorf("binary (%c) import format is no longer supported", data[0])
-
- case 'i':
- // indexed, produced by cmd/compile till go1.19,
- // and also by [Write]. Starting with go1.28,
- // go list -export runs cmd/export, which emits this format.
- return exportdata.Decode(fset, path, data, exportdata.PackagesFromMap(imports), exportdata.DecodeOptions{})
-
- case 'u':
- // unified, produced by cmd/compile since go1.20.
- // Produced by go list -export from go1.20 to go1.27.
- _, pkg, err := uImportData(fset, imports, data[1:], path)
- return pkg, err
-
- default:
- l := min(len(data), 10)
- return nil, fmt.Errorf("unexpected export data with prefix %q for path %s", string(data[:l]), path)
- }
- }
- return nil, fmt.Errorf("empty export data for %s", path)
-}
-
-// Write writes encoded type information for the specified package to out.
-// The FileSet provides file position information for named objects.
-func Write(out io.Writer, fset *token.FileSet, pkg *types.Package) error {
- if fset == nil {
- // For compatibility, tolerate a nil FileSet,
- // in which case position information is missing.
- fset = token.NewFileSet()
- }
- data, err := exportdata.Encode(fset, pkg, exportdata.EncodeOptions{})
- if err != nil {
- return err
- }
- _, err = out.Write(data) // data begins with 'i'
- return err
-}
-
-// Deprecated: ReadBundle is an unsupported obsolete experimental API. It returns an error.
-func ReadBundle(in io.Reader, fset *token.FileSet, imports map[string]*types.Package) ([]*types.Package, error) {
- return nil, fmt.Errorf("ReadBundle is an unsupported obsolete experimental API")
-}
-
-// Deprecated: WriteBundle is an unsupported obsolete experimental API. It returns an error.
-func WriteBundle(io.Writer, *token.FileSet, []*types.Package) error {
- return fmt.Errorf("WriteBundle is an unsupported obsolete experimental API")
-}
diff --git a/src/vendor/golang.org/x/tools/go/gcexportdata/importer.go b/src/vendor/golang.org/x/tools/go/gcexportdata/importer.go
deleted file mode 100644
index 37a7247e26..0000000000
--- a/src/vendor/golang.org/x/tools/go/gcexportdata/importer.go
+++ /dev/null
@@ -1,75 +0,0 @@
-// Copyright 2016 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package gcexportdata
-
-import (
- "fmt"
- "go/token"
- "go/types"
- "os"
-)
-
-// NewImporter returns a new instance of the types.Importer interface
-// that reads type information from export data files written by gc.
-// The Importer also satisfies types.ImporterFrom.
-//
-// Export data files are located using "go build" workspace conventions
-// and the build.Default context.
-//
-// Use this importer instead of go/importer.For("gc", ...) to avoid the
-// version-skew problems described in the documentation of this package,
-// or to control the FileSet or access the imports map populated during
-// package loading.
-//
-// Deprecated: Use the higher-level API in golang.org/x/tools/go/packages,
-// which is more efficient.
-func NewImporter(fset *token.FileSet, imports map[string]*types.Package) types.ImporterFrom {
- return importer{fset, imports}
-}
-
-type importer struct {
- fset *token.FileSet
- imports map[string]*types.Package
-}
-
-func (imp importer) Import(importPath string) (*types.Package, error) {
- return imp.ImportFrom(importPath, "", 0)
-}
-
-func (imp importer) ImportFrom(importPath, srcDir string, mode types.ImportMode) (_ *types.Package, err error) {
- filename, path := Find(importPath, srcDir)
- if filename == "" {
- if importPath == "unsafe" {
- // Even for unsafe, call Find first in case
- // the package was vendored.
- return types.Unsafe, nil
- }
- return nil, fmt.Errorf("can't find import: %s", importPath)
- }
-
- if pkg, ok := imp.imports[path]; ok && pkg.Complete() {
- return pkg, nil // cache hit
- }
-
- // open file
- f, err := os.Open(filename)
- if err != nil {
- return nil, err
- }
- defer func() {
- f.Close()
- if err != nil {
- // add file name to error
- err = fmt.Errorf("reading export data: %s: %v", filename, err)
- }
- }()
-
- r, err := NewReader(f)
- if err != nil {
- return nil, err
- }
-
- return Read(r, imp.fset, imp.imports, path)
-}
diff --git a/src/vendor/golang.org/x/tools/go/gcexportdata/support.go b/src/vendor/golang.org/x/tools/go/gcexportdata/support.go
deleted file mode 100644
index 2610b992ca..0000000000
--- a/src/vendor/golang.org/x/tools/go/gcexportdata/support.go
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2024 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package gcexportdata
-
-import (
- "bufio"
- "io"
- "strconv"
- "strings"
- // This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-)
-
-// Copy of $GOROOT/src/cmd/internal/archive.ReadHeader.
-func readArchiveHeader(b *bufio.Reader, name string) int {
- // architecture-independent object file output
- const HeaderSize = 60
-
- var buf [HeaderSize]byte
- if _, err := io.ReadFull(b, buf[:]); err != nil {
- return -1
- }
- aname := strings.Trim(string(buf[0:16]), " ")
- if !strings.HasPrefix(aname, name) {
- return -1
- }
- asize := strings.Trim(string(buf[48:58]), " ")
- i, _ := strconv.Atoi(asize)
- return i
-}
diff --git a/src/vendor/golang.org/x/tools/go/gcexportdata/ureader.go b/src/vendor/golang.org/x/tools/go/gcexportdata/ureader.go
deleted file mode 100644
index e6c797d7bf..0000000000
--- a/src/vendor/golang.org/x/tools/go/gcexportdata/ureader.go
+++ /dev/null
@@ -1,856 +0,0 @@
-// Copyright 2021 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// This file reads the unified export data emitted by cmd/compile until go1.27.
-// (Derived from go/internal/gcimporter/ureader.go.)
-
-package gcexportdata
-
-import (
- "fmt"
- "go/token"
- "go/types"
- "sort"
- "strings"
-
- "golang.org/x/tools/internal/pkgbits"
- // This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-)
-
-// A pkgReader holds the shared state for reading a unified IR package
-// description.
-type pkgReader struct {
- pkgbits.PkgDecoder
-
- fake fakeFileSet
-
- ctxt *types.Context
- imports map[string]*types.Package // previously imported packages, indexed by path
-
- // lazily initialized arrays corresponding to the unified IR
- // PosBase, Pkg, and Type sections, respectively.
- posBases []string // position bases (i.e., file names)
- pkgs []*types.Package
- typs []types.Type
-
- // laterFns holds functions that need to be invoked at the end of
- // import reading.
- //
- // TODO(mdempsky): Is it safe to have a single "later" slice or do
- // we need to have multiple passes? See comments on CL 386002 and
- // go.dev/issue/52104.
- laterFns []func()
- // laterFors is used in case of 'type A B' to ensure that B is processed before A.
- laterFors map[types.Type]int
-
- // ifaces holds a list of constructed Interfaces, which need to have
- // Complete called after importing is done.
- ifaces []*types.Interface
-}
-
-// later adds a function to be invoked at the end of import reading.
-func (pr *pkgReader) later(fn func()) {
- pr.laterFns = append(pr.laterFns, fn)
-}
-
-// See cmd/compile/internal/noder.derivedInfo.
-type derivedInfo struct {
- idx pkgbits.Index
-}
-
-// See cmd/compile/internal/noder.typeInfo.
-type typeInfo struct {
- idx pkgbits.Index
- derived bool
-}
-
-func uImportData(fset *token.FileSet, imports map[string]*types.Package, data []byte, path string) (_ int, pkg *types.Package, err error) {
- if !debug {
- defer func() {
- if x := recover(); x != nil {
- err = fmt.Errorf("internal error in importing %q (%v); please report an issue", path, x)
- }
- }()
- }
-
- s := string(data)
- input := pkgbits.NewPkgDecoder(path, s)
- pkg = readUnifiedPackage(fset, nil, imports, input)
- return
-}
-
-// laterFor adds a function to be invoked at the end of import reading, and records the type that function is finishing.
-func (pr *pkgReader) laterFor(t types.Type, fn func()) {
- if pr.laterFors == nil {
- pr.laterFors = make(map[types.Type]int)
- }
- pr.laterFors[t] = len(pr.laterFns)
- pr.laterFns = append(pr.laterFns, fn)
-}
-
-// readUnifiedPackage reads a package description from the given
-// unified IR export data decoder.
-func readUnifiedPackage(fset *token.FileSet, ctxt *types.Context, imports map[string]*types.Package, input pkgbits.PkgDecoder) *types.Package {
- pr := pkgReader{
- PkgDecoder: input,
-
- fake: fakeFileSet{
- fset: fset,
- files: make(map[string]*fileInfo),
- },
-
- ctxt: ctxt,
- imports: imports,
-
- posBases: make([]string, input.NumElems(pkgbits.RelocPosBase)),
- pkgs: make([]*types.Package, input.NumElems(pkgbits.RelocPkg)),
- typs: make([]types.Type, input.NumElems(pkgbits.RelocType)),
- }
- defer pr.fake.setLines()
-
- r := pr.newReader(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
- pkg := r.pkg()
- if r.Version().Has(pkgbits.HasInit) {
- r.Bool()
- }
-
- for i, n := 0, r.Len(); i < n; i++ {
- // As if r.obj(), but avoiding the Scope.Lookup call,
- // to avoid eager loading of imports.
- r.Sync(pkgbits.SyncObject)
- if r.Version().Has(pkgbits.DerivedFuncInstance) {
- assert(!r.Bool())
- }
- r.p.objIdx(r.Reloc(pkgbits.RelocObj))
- assert(r.Len() == 0)
- }
-
- r.Sync(pkgbits.SyncEOF)
-
- for _, fn := range pr.laterFns {
- fn()
- }
-
- for _, iface := range pr.ifaces {
- iface.Complete()
- }
-
- // Imports() of pkg are all of the transitive packages that were loaded.
- var imps []*types.Package
- for _, imp := range pr.pkgs {
- if imp != nil && imp != pkg {
- imps = append(imps, imp)
- }
- }
- sort.Sort(byPath(imps))
- pkg.SetImports(imps)
-
- pkg.MarkComplete()
- return pkg
-}
-
-// A reader holds the state for reading a single unified IR element
-// within a package.
-type reader struct {
- pkgbits.Decoder
-
- p *pkgReader
-
- dict *readerDict
-}
-
-// A readerDict holds the state for type parameters that parameterize
-// the current unified IR element.
-type readerDict struct {
- rtbounds []typeInfo // contains constraint types for each parameter in rtparams
- rtparams []*types.TypeParam // contains receiver type parameters for an element
-
- tbounds []typeInfo // contains constraint types for each parameter in tparams
- tparams []*types.TypeParam // contains type parameters for an element
-
- // derived is a slice of types derived from tparams, which may be
- // instantiated while reading the current element.
- derived []derivedInfo
- derivedTypes []types.Type // lazily instantiated from derived
-}
-
-func (pr *pkgReader) newReader(k pkgbits.RelocKind, idx pkgbits.Index, marker pkgbits.SyncMarker) *reader {
- return &reader{
- Decoder: pr.NewDecoder(k, idx, marker),
- p: pr,
- }
-}
-
-func (pr *pkgReader) tempReader(k pkgbits.RelocKind, idx pkgbits.Index, marker pkgbits.SyncMarker) *reader {
- return &reader{
- Decoder: pr.TempDecoder(k, idx, marker),
- p: pr,
- }
-}
-
-func (pr *pkgReader) retireReader(r *reader) {
- pr.RetireDecoder(&r.Decoder)
-}
-
-// @@@ Positions
-
-func (r *reader) pos() token.Pos {
- r.Sync(pkgbits.SyncPos)
- if !r.Bool() {
- return token.NoPos
- }
-
- // TODO(mdempsky): Delta encoding.
- posBase := r.posBase()
- line := r.Uint()
- col := r.Uint()
- return r.p.fake.pos(posBase, int(line), int(col))
-}
-
-func (r *reader) posBase() string {
- return r.p.posBaseIdx(r.Reloc(pkgbits.RelocPosBase))
-}
-
-func (pr *pkgReader) posBaseIdx(idx pkgbits.Index) string {
- if b := pr.posBases[idx]; b != "" {
- return b
- }
-
- var filename string
- {
- r := pr.tempReader(pkgbits.RelocPosBase, idx, pkgbits.SyncPosBase)
-
- // Within types2, position bases have a lot more details (e.g.,
- // keeping track of where //line directives appeared exactly).
- //
- // For go/types, we just track the file name.
-
- filename = r.String()
-
- if r.Bool() { // file base
- // Was: "b = token.NewTrimmedFileBase(filename, true)"
- } else { // line base
- pos := r.pos()
- line := r.Uint()
- col := r.Uint()
-
- // Was: "b = token.NewLineBase(pos, filename, true, line, col)"
- _, _, _ = pos, line, col
- }
- pr.retireReader(r)
- }
- b := filename
- pr.posBases[idx] = b
- return b
-}
-
-// @@@ Packages
-
-func (r *reader) pkg() *types.Package {
- r.Sync(pkgbits.SyncPkg)
- return r.p.pkgIdx(r.Reloc(pkgbits.RelocPkg))
-}
-
-func (pr *pkgReader) pkgIdx(idx pkgbits.Index) *types.Package {
- // TODO(mdempsky): Consider using some non-nil pointer to indicate
- // the universe scope, so we don't need to keep re-reading it.
- if pkg := pr.pkgs[idx]; pkg != nil {
- return pkg
- }
-
- pkg := pr.newReader(pkgbits.RelocPkg, idx, pkgbits.SyncPkgDef).doPkg()
- pr.pkgs[idx] = pkg
- return pkg
-}
-
-func (r *reader) doPkg() *types.Package {
- path := r.String()
- switch path {
- // cmd/compile emits path="main" for main packages because
- // that's the linker symbol prefix it used; but we need
- // the package's path as it would be reported by go list,
- // hence "main" below.
- // See test at go/packages.TestMainPackagePathInModeTypes.
- case "", "main":
- path = r.p.PkgPath()
- case "builtin":
- return nil // universe
- case "unsafe":
- return types.Unsafe
- }
-
- if pkg := r.p.imports[path]; pkg != nil {
- return pkg
- }
-
- name := r.String()
-
- pkg := types.NewPackage(path, name)
- r.p.imports[path] = pkg
-
- return pkg
-}
-
-// @@@ Types
-
-func (r *reader) typ() types.Type {
- return r.p.typIdx(r.typInfo(), r.dict)
-}
-
-func (r *reader) typInfo() typeInfo {
- r.Sync(pkgbits.SyncType)
- if r.Bool() {
- return typeInfo{idx: pkgbits.Index(r.Len()), derived: true}
- }
- return typeInfo{idx: r.Reloc(pkgbits.RelocType), derived: false}
-}
-
-func (pr *pkgReader) typIdx(info typeInfo, dict *readerDict) types.Type {
- idx := info.idx
- var where *types.Type
- if info.derived {
- where = &dict.derivedTypes[idx]
- idx = dict.derived[idx].idx
- } else {
- where = &pr.typs[idx]
- }
-
- if typ := *where; typ != nil {
- return typ
- }
-
- var typ types.Type
- {
- r := pr.tempReader(pkgbits.RelocType, idx, pkgbits.SyncTypeIdx)
- r.dict = dict
-
- typ = r.doTyp()
- assert(typ != nil)
- pr.retireReader(r)
- }
- // See comment in pkgReader.typIdx explaining how this happens.
- if prev := *where; prev != nil {
- return prev
- }
-
- *where = typ
- return typ
-}
-
-func (r *reader) doTyp() (res types.Type) {
- switch tag := pkgbits.CodeType(r.Code(pkgbits.SyncType)); tag {
- default:
- errorf("unhandled type tag: %v", tag)
- panic("unreachable")
-
- case pkgbits.TypeBasic:
- return types.Typ[r.Len()]
-
- case pkgbits.TypeNamed:
- obj, targs := r.obj()
- name := obj.(*types.TypeName)
- if len(targs) != 0 {
- t, _ := types.Instantiate(r.p.ctxt, name.Type(), targs, false)
- return t
- }
- return name.Type()
-
- case pkgbits.TypeTypeParam:
- n := r.Len()
- if n < len(r.dict.rtbounds) {
- return r.dict.rtparams[n]
- }
- return r.dict.tparams[n-len(r.dict.rtbounds)]
-
- case pkgbits.TypeArray:
- len := int64(r.Uint64())
- return types.NewArray(r.typ(), len)
- case pkgbits.TypeChan:
- dir := types.ChanDir(r.Len())
- return types.NewChan(dir, r.typ())
- case pkgbits.TypeMap:
- return types.NewMap(r.typ(), r.typ())
- case pkgbits.TypePointer:
- return types.NewPointer(r.typ())
- case pkgbits.TypeSignature:
- return r.signature(nil, nil, nil)
- case pkgbits.TypeSlice:
- return types.NewSlice(r.typ())
- case pkgbits.TypeStruct:
- return r.structType()
- case pkgbits.TypeInterface:
- return r.interfaceType()
- case pkgbits.TypeUnion:
- return r.unionType()
- }
-}
-
-func (r *reader) structType() *types.Struct {
- fields := make([]*types.Var, r.Len())
- var tags []string
- for i := range fields {
- pos := r.pos()
- pkg, name := r.selector()
- ftyp := r.typ()
- tag := r.String()
- embedded := r.Bool()
-
- fields[i] = types.NewField(pos, pkg, name, ftyp, embedded)
- if tag != "" {
- for len(tags) < i {
- tags = append(tags, "")
- }
- tags = append(tags, tag)
- }
- }
- return types.NewStruct(fields, tags)
-}
-
-func (r *reader) unionType() *types.Union {
- terms := make([]*types.Term, r.Len())
- for i := range terms {
- terms[i] = types.NewTerm(r.Bool(), r.typ())
- }
- return types.NewUnion(terms)
-}
-
-func (r *reader) interfaceType() *types.Interface {
- methods := make([]*types.Func, r.Len())
- embeddeds := make([]types.Type, r.Len())
- implicit := len(methods) == 0 && len(embeddeds) == 1 && r.Bool()
-
- for i := range methods {
- pos := r.pos()
- pkg, name := r.selector()
- mtyp := r.signature(nil, nil, nil)
- methods[i] = types.NewFunc(pos, pkg, name, mtyp)
- }
-
- for i := range embeddeds {
- embeddeds[i] = r.typ()
- }
-
- iface := types.NewInterfaceType(methods, embeddeds)
- if implicit {
- iface.MarkImplicit()
- }
-
- // We need to call iface.Complete(), but if there are any embedded
- // defined types, then we may not have set their underlying
- // interface type yet. So we need to defer calling Complete until
- // after we've called SetUnderlying everywhere.
- //
- // TODO(mdempsky): After CL 424876 lands, it should be safe to call
- // iface.Complete() immediately.
- r.p.ifaces = append(r.p.ifaces, iface)
-
- return iface
-}
-
-func (r *reader) signature(recv *types.Var, rtparams, tparams []*types.TypeParam) *types.Signature {
- r.Sync(pkgbits.SyncSignature)
-
- params := r.params(types.ParamVar)
- results := r.params(types.ResultVar)
- variadic := r.Bool()
-
- return types.NewSignatureType(recv, rtparams, tparams, params, results, variadic)
-}
-
-func (r *reader) params(kind types.VarKind) *types.Tuple {
- r.Sync(pkgbits.SyncParams)
-
- params := make([]*types.Var, r.Len())
- for i := range params {
- params[i] = r.param(kind)
- }
-
- return types.NewTuple(params...)
-}
-
-func (r *reader) param(kind types.VarKind) *types.Var {
- r.Sync(pkgbits.SyncParam)
-
- pos := r.pos()
- pkg, name := r.localIdent()
- typ := r.typ()
-
- param := types.NewParam(pos, pkg, name, typ)
- param.SetKind(kind) // ∈ {Recv,Param,Result}Var
- return param
-}
-
-// @@@ Objects
-
-func (r *reader) obj() (types.Object, []types.Type) {
- r.Sync(pkgbits.SyncObject)
-
- if r.Version().Has(pkgbits.DerivedFuncInstance) {
- assert(!r.Bool())
- }
-
- pkg, name := r.p.objIdx(r.Reloc(pkgbits.RelocObj))
- obj := pkgScope(pkg).Lookup(name)
-
- targs := make([]types.Type, r.Len())
- for i := range targs {
- targs[i] = r.typ()
- }
-
- return obj, targs
-}
-
-func (pr *pkgReader) objIdx(idx pkgbits.Index) (*types.Package, string) {
-
- var objPkg *types.Package
- var objName string
- var tag pkgbits.CodeObj
- {
- rname := pr.tempReader(pkgbits.RelocName, idx, pkgbits.SyncObject1)
-
- objPkg, objName = rname.qualifiedIdent()
- assert(objName != "")
-
- tag = pkgbits.CodeObj(rname.Code(pkgbits.SyncCodeObj))
- pr.retireReader(rname)
- }
-
- if tag == pkgbits.ObjStub {
- assert(objPkg == nil || objPkg == types.Unsafe)
- return objPkg, objName
- }
-
- // Ignore local types promoted to global scope (#55110).
- if _, suffix := splitVargenSuffix(objName); suffix != "" {
- return objPkg, objName
- }
-
- // TODO(mark): This, like the above splitVargenSuffix, is not ideal.
- // Ignore generic methods promoted to global scope.
- if strings.Contains(objName, ".") {
- return objPkg, objName
- }
-
- if objPkg.Scope().Lookup(objName) == nil {
- dict := pr.objDictIdx(idx)
-
- r := pr.newReader(pkgbits.RelocObj, idx, pkgbits.SyncObject1)
- r.dict = dict
-
- declare := func(obj types.Object) {
- objPkg.Scope().Insert(obj)
- }
-
- switch tag {
- default:
- panic("weird")
-
- case pkgbits.ObjAlias:
- pos := r.pos()
- var tparams []*types.TypeParam
- if r.Version().Has(pkgbits.AliasTypeParamNames) {
- tparams = r.typeParamNames(false)
- }
- typ := r.typ()
- tname := types.NewTypeName(pos, objPkg, objName, nil)
- types.NewAlias(tname, typ).SetTypeParams(tparams)
- declare(tname)
-
- case pkgbits.ObjConst:
- pos := r.pos()
- typ := r.typ()
- val := r.Value()
- declare(types.NewConst(pos, objPkg, objName, typ, val))
-
- case pkgbits.ObjFunc:
- pos := r.pos()
- if r.Version().Has(pkgbits.GenericMethods) {
- assert(!r.Bool()) // generic methods are read in their defining type
- }
- tparams := r.typeParamNames(false)
- sig := r.signature(nil, nil, tparams)
- declare(types.NewFunc(pos, objPkg, objName, sig))
-
- case pkgbits.ObjType:
- pos := r.pos()
-
- obj := types.NewTypeName(pos, objPkg, objName, nil)
- named := types.NewNamed(obj, nil, nil)
- declare(obj)
-
- named.SetTypeParams(r.typeParamNames(false))
-
- setUnderlying := func(underlying types.Type) {
- // If the underlying type is an interface, we need to
- // duplicate its methods so we can replace the receiver
- // parameter's type (#49906).
- if iface, ok := types.Unalias(underlying).(*types.Interface); ok && iface.NumExplicitMethods() != 0 {
- methods := make([]*types.Func, iface.NumExplicitMethods())
- for i := range methods {
- fn := iface.ExplicitMethod(i)
- sig := fn.Type().(*types.Signature)
-
- recv := types.NewVar(fn.Pos(), fn.Pkg(), "", named)
- recv.SetKind(types.RecvVar)
- methods[i] = types.NewFunc(fn.Pos(), fn.Pkg(), fn.Name(), types.NewSignatureType(recv, nil, nil, sig.Params(), sig.Results(), sig.Variadic()))
- }
-
- embeds := make([]types.Type, iface.NumEmbeddeds())
- for i := range embeds {
- embeds[i] = iface.EmbeddedType(i)
- }
-
- newIface := types.NewInterfaceType(methods, embeds)
- r.p.ifaces = append(r.p.ifaces, newIface)
- underlying = newIface
- }
-
- named.SetUnderlying(underlying)
- }
-
- // Since go.dev/cl/455279, we can assume rhs.Underlying() will
- // always be non-nil. However, to temporarily support users of
- // older snapshot releases, we continue to fallback to the old
- // behavior for now.
- //
- // TODO(mdempsky): Remove fallback code and simplify after
- // allowing time for snapshot users to upgrade.
- rhs := r.typ()
- if underlying := rhs.Underlying(); underlying != nil {
- setUnderlying(underlying)
- } else {
- pk := r.p
- pk.laterFor(named, func() {
- // First be sure that the rhs is initialized, if it needs to be initialized.
- delete(pk.laterFors, named) // prevent cycles
- if i, ok := pk.laterFors[rhs]; ok {
- f := pk.laterFns[i]
- pk.laterFns[i] = func() {} // function is running now, so replace it with a no-op
- f() // initialize RHS
- }
- setUnderlying(rhs.Underlying())
- })
- }
-
- if r.Version().Has(pkgbits.GenericMethods) {
- // V4 (go1.27.0) emitted all non-generic methods
- // before all generic ones, discarding source
- // order: a bug (go.dev/issue/81188).
- // V5 (go1.27.x) fixes it by emitting an explicit
- // index along with each method.
- type indexedMethod struct {
- index int // (or -1 in V4)
- fn *types.Func
- }
-
- var methods []indexedMethod
-
- // ordinary methods
- for range r.Len() {
- idx, m := r.method()
- methods = append(methods, indexedMethod{idx, m})
- }
-
- // generic methods
- for range r.Len() {
- // Careful: objIdx is used to read in package-scoped declarations, which
- // methods are not. Instead, decode it here. This makes it easier to
- // associate it with the type and avoids the main objIdx loop.
- idx := r.Reloc(pkgbits.RelocObj)
-
- r := pr.tempReader(pkgbits.RelocObj, idx, pkgbits.SyncObject1)
- r.dict = pr.objDictIdx(idx)
-
- pos := r.pos()
- assert(r.Bool()) // generic method
- pkg, name := r.selector()
- rtparams := r.typeParamNames(true)
- recv := r.param(types.RecvVar)
- methodIdx := -1
- if r.Version().Has(pkgbits.PreserveMethodOrder) {
- methodIdx = r.Len()
- }
- tparams := r.typeParamNames(false)
- sig := r.signature(recv, rtparams, tparams)
-
- pr.retireReader(r)
- methods = append(methods, indexedMethod{methodIdx, types.NewFunc(pos, pkg, name, sig)})
- }
-
- if r.Version().Has(pkgbits.PreserveMethodOrder) {
- sort.Slice(methods, func(i, j int) bool {
- return methods[i].index < methods[j].index
- })
- }
-
- for _, m := range methods {
- named.AddMethod(m.fn)
- }
-
- } else {
- for range r.Len() {
- _, m := r.method()
- named.AddMethod(m)
- }
- }
-
- case pkgbits.ObjVar:
- pos := r.pos()
- typ := r.typ()
- v := types.NewVar(pos, objPkg, objName, typ)
- v.SetKind(types.PackageVar)
- declare(v)
- }
- }
-
- return objPkg, objName
-}
-
-func (pr *pkgReader) objDictIdx(idx pkgbits.Index) *readerDict {
-
- var dict readerDict
-
- {
- r := pr.tempReader(pkgbits.RelocObjDict, idx, pkgbits.SyncObject1)
- if implicits := r.Len(); implicits != 0 {
- errorf("unexpected object with %v implicit type parameter(s)", implicits)
- }
-
- nreceivers := 0
- if r.Version().Has(pkgbits.GenericMethods) {
- nreceivers = r.Len()
- }
- nexplicits := r.Len()
-
- dict.rtbounds = make([]typeInfo, nreceivers)
- for i := range dict.rtbounds {
- dict.rtbounds[i] = r.typInfo()
- }
-
- dict.tbounds = make([]typeInfo, nexplicits)
- for i := range dict.tbounds {
- dict.tbounds[i] = r.typInfo()
- }
-
- dict.derived = make([]derivedInfo, r.Len())
- dict.derivedTypes = make([]types.Type, len(dict.derived))
- for i := range dict.derived {
- dict.derived[i] = derivedInfo{idx: r.Reloc(pkgbits.RelocType)}
- if r.Version().Has(pkgbits.DerivedInfoNeeded) {
- assert(!r.Bool())
- }
- }
-
- pr.retireReader(r)
- }
- // function references follow, but reader doesn't need those
-
- return &dict
-}
-
-func (r *reader) typeParamNames(isGenMeth bool) []*types.TypeParam {
- r.Sync(pkgbits.SyncTypeParamNames)
-
- // Note: This code assumes there are no implicit type parameters.
- // This is fine since it only reads exported declarations, which
- // never have implicits.
-
- var in []typeInfo
- var out *[]*types.TypeParam
- if isGenMeth {
- in = r.dict.rtbounds
- out = &r.dict.rtparams
- } else {
- in = r.dict.tbounds
- out = &r.dict.tparams
- }
-
- if len(in) == 0 {
- return nil
- }
-
- // Careful: Type parameter lists may have cycles. To allow for this,
- // we construct the type parameter list in two passes: first we
- // create all the TypeNames and TypeParams, then we construct and
- // set the bound type.
-
- // We have to save tparams outside of the closure, because typeParamNames
- // can be called multiple times with the same dictionary instance.
- tparams := make([]*types.TypeParam, len(in))
- *out = tparams
-
- for i := range in {
- pos := r.pos()
- pkg, name := r.localIdent()
-
- tname := types.NewTypeName(pos, pkg, name, nil)
- tparams[i] = types.NewTypeParam(tname, nil)
- }
-
- // The reader dictionary will continue mutating before we have time
- // to call delayed functions; make a local copy of the constraints.
- types := make([]types.Type, len(in))
- for i, info := range in {
- types[i] = r.p.typIdx(info, r.dict)
- }
-
- // This needs to happen later to make sure SetUnderlying has been called.
- r.p.later(func() {
- for i, typ := range types {
- tparams[i].SetConstraint(typ)
- }
- })
-
- return tparams
-}
-
-func (r *reader) method() (int, *types.Func) {
- r.Sync(pkgbits.SyncMethod)
- idx := -1
- if r.Version().Has(pkgbits.PreserveMethodOrder) {
- idx = r.Len()
- }
- pos := r.pos()
- pkg, name := r.selector()
-
- rparams := r.typeParamNames(false)
- sig := r.signature(r.param(types.RecvVar), rparams, nil)
-
- _ = r.pos() // TODO(mdempsky): Remove; this is a hacker for linker.go.
- return idx, types.NewFunc(pos, pkg, name, sig)
-}
-
-func (r *reader) qualifiedIdent() (*types.Package, string) { return r.ident(pkgbits.SyncSym) }
-func (r *reader) localIdent() (*types.Package, string) { return r.ident(pkgbits.SyncLocalIdent) }
-func (r *reader) selector() (*types.Package, string) { return r.ident(pkgbits.SyncSelector) }
-
-func (r *reader) ident(marker pkgbits.SyncMarker) (*types.Package, string) {
- r.Sync(marker)
- return r.pkg(), r.String()
-}
-
-// pkgScope returns pkg.Scope().
-// If pkg is nil, it returns types.Universe instead.
-//
-// TODO(mdempsky): Remove after x/tools can depend on Go 1.19.
-func pkgScope(pkg *types.Package) *types.Scope {
- if pkg != nil {
- return pkg.Scope()
- }
- return types.Universe
-}
-
-// See cmd/compile/internal/types.SplitVargenSuffix.
-func splitVargenSuffix(name string) (base, suffix string) {
- i := len(name)
- for i > 0 && name[i-1] >= '0' && name[i-1] <= '9' {
- i--
- }
- const dot = "·"
- if i >= len(dot) && name[i-len(dot):i] == dot {
- i -= len(dot)
- return name[:i], name[i:]
- }
- return name, ""
-}
diff --git a/src/vendor/golang.org/x/tools/internal/pkgbits/codes.go b/src/vendor/golang.org/x/tools/internal/pkgbits/codes.go
deleted file mode 100644
index 21f44d9656..0000000000
--- a/src/vendor/golang.org/x/tools/internal/pkgbits/codes.go
+++ /dev/null
@@ -1,79 +0,0 @@
-// Copyright 2021 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pkgbits
-
-// This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-
-// A Code is an enum value that can be encoded into bitstreams.
-//
-// Code types are preferable for enum types, because they allow
-// Decoder to detect desyncs.
-type Code interface {
- // Marker returns the SyncMarker for the Code's dynamic type.
- Marker() SyncMarker
-
- // Value returns the Code's ordinal value.
- Value() int
-}
-
-// A CodeVal distinguishes among go/constant.Value encodings.
-type CodeVal int
-
-func (c CodeVal) Marker() SyncMarker { return SyncVal }
-func (c CodeVal) Value() int { return int(c) }
-
-// Note: These values are public and cannot be changed without
-// updating the go/types importers.
-
-const (
- ValBool CodeVal = iota
- ValString
- ValInt64
- ValBigInt
- ValBigRat
- ValBigFloat
-)
-
-// A CodeType distinguishes among go/types.Type encodings.
-type CodeType int
-
-func (c CodeType) Marker() SyncMarker { return SyncType }
-func (c CodeType) Value() int { return int(c) }
-
-// Note: These values are public and cannot be changed without
-// updating the go/types importers.
-
-const (
- TypeBasic CodeType = iota
- TypeNamed
- TypePointer
- TypeSlice
- TypeArray
- TypeChan
- TypeMap
- TypeSignature
- TypeStruct
- TypeInterface
- TypeUnion
- TypeTypeParam
-)
-
-// A CodeObj distinguishes among go/types.Object encodings.
-type CodeObj int
-
-func (c CodeObj) Marker() SyncMarker { return SyncCodeObj }
-func (c CodeObj) Value() int { return int(c) }
-
-// Note: These values are public and cannot be changed without
-// updating the go/types importers.
-
-const (
- ObjAlias CodeObj = iota
- ObjConst
- ObjType
- ObjFunc
- ObjVar
- ObjStub
-)
diff --git a/src/vendor/golang.org/x/tools/internal/pkgbits/decoder.go b/src/vendor/golang.org/x/tools/internal/pkgbits/decoder.go
deleted file mode 100644
index f05e2696ee..0000000000
--- a/src/vendor/golang.org/x/tools/internal/pkgbits/decoder.go
+++ /dev/null
@@ -1,520 +0,0 @@
-// Copyright 2021 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pkgbits
-
-import (
- "encoding/binary"
- "errors"
- "fmt"
- "go/constant"
- "go/token"
- "io"
- "math/big"
- "os"
- "runtime"
- "strings"
- // This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-)
-
-// A PkgDecoder provides methods for decoding a package's Unified IR
-// export data.
-type PkgDecoder struct {
- // version is the file format version.
- version Version
-
- // sync indicates whether the file uses sync markers.
- sync bool
-
- // pkgPath is the package path for the package to be decoded.
- //
- // TODO(mdempsky): Remove; unneeded since CL 391014.
- pkgPath string
-
- // elemData is the full data payload of the encoded package.
- // Elements are densely and contiguously packed together.
- //
- // The last 8 bytes of elemData are the package fingerprint.
- elemData string
-
- // elemEnds stores the byte-offset end positions of element
- // bitstreams within elemData.
- //
- // For example, element I's bitstream data starts at elemEnds[I-1]
- // (or 0, if I==0) and ends at elemEnds[I].
- //
- // Note: elemEnds is indexed by absolute indices, not
- // section-relative indices.
- elemEnds []uint32
-
- // elemEndsEnds stores the index-offset end positions of relocation
- // sections within elemEnds.
- //
- // For example, section K's end positions start at elemEndsEnds[K-1]
- // (or 0, if K==0) and end at elemEndsEnds[K].
- elemEndsEnds [numRelocs]uint32
-
- scratchRelocEnt []RelocEnt
-}
-
-// PkgPath returns the package path for the package
-//
-// TODO(mdempsky): Remove; unneeded since CL 391014.
-func (pr *PkgDecoder) PkgPath() string { return pr.pkgPath }
-
-// SyncMarkers reports whether pr uses sync markers.
-func (pr *PkgDecoder) SyncMarkers() bool { return pr.sync }
-
-// NewPkgDecoder returns a PkgDecoder initialized to read the Unified
-// IR export data from input. pkgPath is the package path for the
-// compilation unit that produced the export data.
-func NewPkgDecoder(pkgPath, input string) PkgDecoder {
- pr := PkgDecoder{
- pkgPath: pkgPath,
- }
-
- // TODO(mdempsky): Implement direct indexing of input string to
- // avoid copying the position information.
-
- r := strings.NewReader(input)
-
- var ver uint32
- assert(binary.Read(r, binary.LittleEndian, &ver) == nil)
- pr.version = Version(ver)
-
- if pr.version >= numVersions {
- panic(fmt.Errorf("cannot decode %q, export data version %d is greater than maximum supported version %d", pkgPath, pr.version, numVersions-1))
- }
-
- if pr.version.Has(Flags) {
- var flags uint32
- assert(binary.Read(r, binary.LittleEndian, &flags) == nil)
- pr.sync = flags&flagSyncMarkers != 0
- }
-
- assert(binary.Read(r, binary.LittleEndian, pr.elemEndsEnds[:]) == nil)
-
- pr.elemEnds = make([]uint32, pr.elemEndsEnds[len(pr.elemEndsEnds)-1])
- assert(binary.Read(r, binary.LittleEndian, pr.elemEnds[:]) == nil)
-
- pos, err := r.Seek(0, io.SeekCurrent)
- assert(err == nil)
-
- pr.elemData = input[pos:]
-
- const fingerprintSize = 8
- assert(len(pr.elemData)-fingerprintSize == int(pr.elemEnds[len(pr.elemEnds)-1]))
-
- return pr
-}
-
-// NumElems returns the number of elements in section k.
-func (pr *PkgDecoder) NumElems(k RelocKind) int {
- count := int(pr.elemEndsEnds[k])
- if k > 0 {
- count -= int(pr.elemEndsEnds[k-1])
- }
- return count
-}
-
-// TotalElems returns the total number of elements across all sections.
-func (pr *PkgDecoder) TotalElems() int {
- return len(pr.elemEnds)
-}
-
-// Fingerprint returns the package fingerprint.
-func (pr *PkgDecoder) Fingerprint() [8]byte {
- var fp [8]byte
- copy(fp[:], pr.elemData[len(pr.elemData)-8:])
- return fp
-}
-
-// AbsIdx returns the absolute index for the given (section, index)
-// pair.
-func (pr *PkgDecoder) AbsIdx(k RelocKind, idx Index) int {
- absIdx := int(idx)
- if k > 0 {
- absIdx += int(pr.elemEndsEnds[k-1])
- }
- if absIdx >= int(pr.elemEndsEnds[k]) {
- panicf("%v:%v is out of bounds; %v", k, idx, pr.elemEndsEnds)
- }
- return absIdx
-}
-
-// DataIdx returns the raw element bitstream for the given (section,
-// index) pair.
-func (pr *PkgDecoder) DataIdx(k RelocKind, idx Index) string {
- absIdx := pr.AbsIdx(k, idx)
-
- var start uint32
- if absIdx > 0 {
- start = pr.elemEnds[absIdx-1]
- }
- end := pr.elemEnds[absIdx]
-
- return pr.elemData[start:end]
-}
-
-// StringIdx returns the string value for the given string index.
-func (pr *PkgDecoder) StringIdx(idx Index) string {
- return pr.DataIdx(RelocString, idx)
-}
-
-// NewDecoder returns a Decoder for the given (section, index) pair,
-// and decodes the given SyncMarker from the element bitstream.
-func (pr *PkgDecoder) NewDecoder(k RelocKind, idx Index, marker SyncMarker) Decoder {
- r := pr.NewDecoderRaw(k, idx)
- r.Sync(marker)
- return r
-}
-
-// TempDecoder returns a Decoder for the given (section, index) pair,
-// and decodes the given SyncMarker from the element bitstream.
-// If possible the Decoder should be RetireDecoder'd when it is no longer
-// needed, this will avoid heap allocations.
-func (pr *PkgDecoder) TempDecoder(k RelocKind, idx Index, marker SyncMarker) Decoder {
- r := pr.TempDecoderRaw(k, idx)
- r.Sync(marker)
- return r
-}
-
-func (pr *PkgDecoder) RetireDecoder(d *Decoder) {
- pr.scratchRelocEnt = d.Relocs
- d.Relocs = nil
-}
-
-// NewDecoderRaw returns a Decoder for the given (section, index) pair.
-//
-// Most callers should use NewDecoder instead.
-func (pr *PkgDecoder) NewDecoderRaw(k RelocKind, idx Index) Decoder {
- r := Decoder{
- common: pr,
- k: k,
- Idx: idx,
- }
-
- r.Data.Reset(pr.DataIdx(k, idx))
- r.Sync(SyncRelocs)
- r.Relocs = make([]RelocEnt, r.Len())
- for i := range r.Relocs {
- r.Sync(SyncReloc)
- r.Relocs[i] = RelocEnt{RelocKind(r.Len()), Index(r.Len())}
- }
-
- return r
-}
-
-func (pr *PkgDecoder) TempDecoderRaw(k RelocKind, idx Index) Decoder {
- r := Decoder{
- common: pr,
- k: k,
- Idx: idx,
- }
-
- r.Data.Reset(pr.DataIdx(k, idx))
- r.Sync(SyncRelocs)
- l := r.Len()
- if cap(pr.scratchRelocEnt) >= l {
- r.Relocs = pr.scratchRelocEnt[:l]
- pr.scratchRelocEnt = nil
- } else {
- r.Relocs = make([]RelocEnt, l)
- }
- for i := range r.Relocs {
- r.Sync(SyncReloc)
- r.Relocs[i] = RelocEnt{RelocKind(r.Len()), Index(r.Len())}
- }
-
- return r
-}
-
-// A Decoder provides methods for decoding an individual element's
-// bitstream data.
-type Decoder struct {
- common *PkgDecoder
-
- Relocs []RelocEnt
- Data strings.Reader
-
- k RelocKind
- Idx Index
-}
-
-func (r *Decoder) checkErr(err error) {
- if err != nil {
- panicf("unexpected decoding error: %w", err)
- }
-}
-
-func (r *Decoder) rawUvarint() uint64 {
- x, err := readUvarint(&r.Data)
- r.checkErr(err)
- return x
-}
-
-// readUvarint is a type-specialized copy of encoding/binary.ReadUvarint.
-// This avoids the interface conversion and thus has better escape properties,
-// which flows up the stack.
-func readUvarint(r *strings.Reader) (uint64, error) {
- var x uint64
- var s uint
- for i := range binary.MaxVarintLen64 {
- b, err := r.ReadByte()
- if err != nil {
- if i > 0 && err == io.EOF {
- err = io.ErrUnexpectedEOF
- }
- return x, err
- }
- if b < 0x80 {
- if i == binary.MaxVarintLen64-1 && b > 1 {
- return x, overflow
- }
- return x | uint64(b)<<s, nil
- }
- x |= uint64(b&0x7f) << s
- s += 7
- }
- return x, overflow
-}
-
-var overflow = errors.New("pkgbits: readUvarint overflows a 64-bit integer")
-
-func (r *Decoder) rawVarint() int64 {
- ux := r.rawUvarint()
-
- // Zig-zag decode.
- x := int64(ux >> 1)
- if ux&1 != 0 {
- x = ^x
- }
- return x
-}
-
-func (r *Decoder) rawReloc(k RelocKind, idx int) Index {
- e := r.Relocs[idx]
- assert(e.Kind == k)
- return e.Idx
-}
-
-// Sync decodes a sync marker from the element bitstream and asserts
-// that it matches the expected marker.
-//
-// If r.common.sync is false, then Sync is a no-op.
-func (r *Decoder) Sync(mWant SyncMarker) {
- if !r.common.sync {
- return
- }
-
- pos, _ := r.Data.Seek(0, io.SeekCurrent)
- mHave := SyncMarker(r.rawUvarint())
- writerPCs := make([]int, r.rawUvarint())
- for i := range writerPCs {
- writerPCs[i] = int(r.rawUvarint())
- }
-
- if mHave == mWant {
- return
- }
-
- // There's some tension here between printing:
- //
- // (1) full file paths that tools can recognize (e.g., so emacs
- // hyperlinks the "file:line" text for easy navigation), or
- //
- // (2) short file paths that are easier for humans to read (e.g., by
- // omitting redundant or irrelevant details, so it's easier to
- // focus on the useful bits that remain).
- //
- // The current formatting favors the former, as it seems more
- // helpful in practice. But perhaps the formatting could be improved
- // to better address both concerns. For example, use relative file
- // paths if they would be shorter, or rewrite file paths to contain
- // "$GOROOT" (like objabi.AbsFile does) if tools can be taught how
- // to reliably expand that again.
-
- fmt.Printf("export data desync: package %q, section %v, index %v, offset %v\n", r.common.pkgPath, r.k, r.Idx, pos)
-
- fmt.Printf("\nfound %v, written at:\n", mHave)
- if len(writerPCs) == 0 {
- fmt.Printf("\t[stack trace unavailable; recompile package %q with -d=syncframes]\n", r.common.pkgPath)
- }
- for _, pc := range writerPCs {
- fmt.Printf("\t%s\n", r.common.StringIdx(r.rawReloc(RelocString, pc)))
- }
-
- fmt.Printf("\nexpected %v, reading at:\n", mWant)
- var readerPCs [32]uintptr // TODO(mdempsky): Dynamically size?
- n := runtime.Callers(2, readerPCs[:])
- for _, pc := range fmtFrames(readerPCs[:n]...) {
- fmt.Printf("\t%s\n", pc)
- }
-
- // We already printed a stack trace for the reader, so now we can
- // simply exit. Printing a second one with panic or base.Fatalf
- // would just be noise.
- os.Exit(1)
-}
-
-// Bool decodes and returns a bool value from the element bitstream.
-func (r *Decoder) Bool() bool {
- r.Sync(SyncBool)
- x, err := r.Data.ReadByte()
- r.checkErr(err)
- assert(x < 2)
- return x != 0
-}
-
-// Int64 decodes and returns an int64 value from the element bitstream.
-func (r *Decoder) Int64() int64 {
- r.Sync(SyncInt64)
- return r.rawVarint()
-}
-
-// Uint64 decodes and returns a uint64 value from the element bitstream.
-func (r *Decoder) Uint64() uint64 {
- r.Sync(SyncUint64)
- return r.rawUvarint()
-}
-
-// Len decodes and returns a non-negative int value from the element bitstream.
-func (r *Decoder) Len() int { x := r.Uint64(); v := int(x); assert(uint64(v) == x); return v }
-
-// Int decodes and returns an int value from the element bitstream.
-func (r *Decoder) Int() int { x := r.Int64(); v := int(x); assert(int64(v) == x); return v }
-
-// Uint decodes and returns a uint value from the element bitstream.
-func (r *Decoder) Uint() uint { x := r.Uint64(); v := uint(x); assert(uint64(v) == x); return v }
-
-// Code decodes a Code value from the element bitstream and returns
-// its ordinal value. It's the caller's responsibility to convert the
-// result to an appropriate Code type.
-//
-// TODO(mdempsky): Ideally this method would have signature "Code[T
-// Code] T" instead, but we don't allow generic methods and the
-// compiler can't depend on generics yet anyway.
-func (r *Decoder) Code(mark SyncMarker) int {
- r.Sync(mark)
- return r.Len()
-}
-
-// Reloc decodes a relocation of expected section k from the element
-// bitstream and returns an index to the referenced element.
-func (r *Decoder) Reloc(k RelocKind) Index {
- r.Sync(SyncUseReloc)
- return r.rawReloc(k, r.Len())
-}
-
-// String decodes and returns a string value from the element
-// bitstream.
-func (r *Decoder) String() string {
- r.Sync(SyncString)
- return r.common.StringIdx(r.Reloc(RelocString))
-}
-
-// Strings decodes and returns a variable-length slice of strings from
-// the element bitstream.
-func (r *Decoder) Strings() []string {
- res := make([]string, r.Len())
- for i := range res {
- res[i] = r.String()
- }
- return res
-}
-
-// Value decodes and returns a constant.Value from the element
-// bitstream.
-func (r *Decoder) Value() constant.Value {
- r.Sync(SyncValue)
- isComplex := r.Bool()
- val := r.scalar()
- if isComplex {
- val = constant.BinaryOp(val, token.ADD, constant.MakeImag(r.scalar()))
- }
- return val
-}
-
-func (r *Decoder) scalar() constant.Value {
- switch tag := CodeVal(r.Code(SyncVal)); tag {
- default:
- panic(fmt.Errorf("unexpected scalar tag: %v", tag))
-
- case ValBool:
- return constant.MakeBool(r.Bool())
- case ValString:
- return constant.MakeString(r.String())
- case ValInt64:
- return constant.MakeInt64(r.Int64())
- case ValBigInt:
- return constant.Make(r.bigInt())
- case ValBigRat:
- num := r.bigInt()
- denom := r.bigInt()
- return constant.Make(new(big.Rat).SetFrac(num, denom))
- case ValBigFloat:
- return constant.Make(r.bigFloat())
- }
-}
-
-func (r *Decoder) bigInt() *big.Int {
- v := new(big.Int).SetBytes([]byte(r.String()))
- if r.Bool() {
- v.Neg(v)
- }
- return v
-}
-
-func (r *Decoder) bigFloat() *big.Float {
- v := new(big.Float).SetPrec(512)
- assert(v.UnmarshalText([]byte(r.String())) == nil)
- return v
-}
-
-// @@@ Helpers
-
-// TODO(mdempsky): These should probably be removed. I think they're a
-// smell that the export data format is not yet quite right.
-
-// PeekPkgPath returns the package path for the specified package
-// index.
-func (pr *PkgDecoder) PeekPkgPath(idx Index) string {
- var path string
- {
- r := pr.TempDecoder(RelocPkg, idx, SyncPkgDef)
- path = r.String()
- pr.RetireDecoder(&r)
- }
- if path == "" {
- path = pr.pkgPath
- }
- return path
-}
-
-// PeekObj returns the package path, object name, and CodeObj for the
-// specified object index.
-func (pr *PkgDecoder) PeekObj(idx Index) (string, string, CodeObj) {
- var ridx Index
- var name string
- var rcode int
- {
- r := pr.TempDecoder(RelocName, idx, SyncObject1)
- r.Sync(SyncSym)
- r.Sync(SyncPkg)
- ridx = r.Reloc(RelocPkg)
- name = r.String()
- rcode = r.Code(SyncCodeObj)
- pr.RetireDecoder(&r)
- }
-
- path := pr.PeekPkgPath(ridx)
- assert(name != "")
-
- tag := CodeObj(rcode)
-
- return path, name, tag
-}
-
-// Version reports the version of the bitstream.
-func (w *Decoder) Version() Version { return w.common.version }
diff --git a/src/vendor/golang.org/x/tools/internal/pkgbits/doc.go b/src/vendor/golang.org/x/tools/internal/pkgbits/doc.go
deleted file mode 100644
index f5a9badf45..0000000000
--- a/src/vendor/golang.org/x/tools/internal/pkgbits/doc.go
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright 2022 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Package pkgbits implements low-level coding abstractions for
-// Unified IR's export data format.
-//
-// At a low-level, a package is a collection of bitstream elements.
-// Each element has a "kind" and a dense, non-negative index.
-// Elements can be randomly accessed given their kind and index.
-//
-// Individual elements are sequences of variable-length values (e.g.,
-// integers, booleans, strings, go/constant values, cross-references
-// to other elements). Package pkgbits provides APIs for encoding and
-// decoding these low-level values, but the details of mapping
-// higher-level Go constructs into elements is left to higher-level
-// abstractions.
-//
-// Elements may cross-reference each other with "relocations." For
-// example, an element representing a pointer type has a relocation
-// referring to the element type.
-//
-// Go constructs may be composed as a constellation of multiple
-// elements. For example, a declared function may have one element to
-// describe the object (e.g., its name, type, position), and a
-// separate element to describe its function body. This allows readers
-// some flexibility in efficiently seeking or re-reading data (e.g.,
-// inlining requires re-reading the function body for each inlined
-// call, without needing to re-read the object-level details).
-//
-// This is a copy of internal/pkgbits in the Go implementation.
-package pkgbits
-
-// This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
diff --git a/src/vendor/golang.org/x/tools/internal/pkgbits/encoder.go b/src/vendor/golang.org/x/tools/internal/pkgbits/encoder.go
deleted file mode 100644
index ac9c8e8b3f..0000000000
--- a/src/vendor/golang.org/x/tools/internal/pkgbits/encoder.go
+++ /dev/null
@@ -1,393 +0,0 @@
-// Copyright 2021 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pkgbits
-
-import (
- "bytes"
- "crypto/md5"
- "encoding/binary"
- "go/constant"
- "io"
- "math/big"
- "runtime"
- "strings"
- // This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-)
-
-// A PkgEncoder provides methods for encoding a package's Unified IR
-// export data.
-type PkgEncoder struct {
- // version of the bitstream.
- version Version
-
- // elems holds the bitstream for previously encoded elements.
- elems [numRelocs][]string
-
- // stringsIdx maps previously encoded strings to their index within
- // the RelocString section, to allow deduplication. That is,
- // elems[RelocString][stringsIdx[s]] == s (if present).
- stringsIdx map[string]Index
-
- // syncFrames is the number of frames to write at each sync
- // marker. A negative value means sync markers are omitted.
- syncFrames int
-}
-
-// SyncMarkers reports whether pw uses sync markers.
-func (pw *PkgEncoder) SyncMarkers() bool { return pw.syncFrames >= 0 }
-
-// NewPkgEncoder returns an initialized PkgEncoder.
-//
-// syncFrames is the number of caller frames that should be serialized
-// at Sync points. Serializing additional frames results in larger
-// export data files, but can help diagnosing desync errors in
-// higher-level Unified IR reader/writer code. If syncFrames is
-// negative, then sync markers are omitted entirely.
-func NewPkgEncoder(version Version, syncFrames int) PkgEncoder {
- return PkgEncoder{
- version: version,
- stringsIdx: make(map[string]Index),
- syncFrames: syncFrames,
- }
-}
-
-// DumpTo writes the package's encoded data to out0 and returns the
-// package fingerprint.
-func (pw *PkgEncoder) DumpTo(out0 io.Writer) (fingerprint [8]byte) {
- h := md5.New()
- out := io.MultiWriter(out0, h)
-
- writeUint32 := func(x uint32) {
- assert(binary.Write(out, binary.LittleEndian, x) == nil)
- }
-
- writeUint32(uint32(pw.version))
-
- if pw.version.Has(Flags) {
- var flags uint32
- if pw.SyncMarkers() {
- flags |= flagSyncMarkers
- }
- writeUint32(flags)
- }
-
- // Write elemEndsEnds.
- var sum uint32
- for _, elems := range &pw.elems {
- sum += uint32(len(elems))
- writeUint32(sum)
- }
-
- // Write elemEnds.
- sum = 0
- for _, elems := range &pw.elems {
- for _, elem := range elems {
- sum += uint32(len(elem))
- writeUint32(sum)
- }
- }
-
- // Write elemData.
- for _, elems := range &pw.elems {
- for _, elem := range elems {
- _, err := io.WriteString(out, elem)
- assert(err == nil)
- }
- }
-
- // Write fingerprint.
- copy(fingerprint[:], h.Sum(nil))
- _, err := out0.Write(fingerprint[:])
- assert(err == nil)
-
- return
-}
-
-// StringIdx adds a string value to the strings section, if not
-// already present, and returns its index.
-func (pw *PkgEncoder) StringIdx(s string) Index {
- if idx, ok := pw.stringsIdx[s]; ok {
- assert(pw.elems[RelocString][idx] == s)
- return idx
- }
-
- idx := Index(len(pw.elems[RelocString]))
- pw.elems[RelocString] = append(pw.elems[RelocString], s)
- pw.stringsIdx[s] = idx
- return idx
-}
-
-// NewEncoder returns an Encoder for a new element within the given
-// section, and encodes the given SyncMarker as the start of the
-// element bitstream.
-func (pw *PkgEncoder) NewEncoder(k RelocKind, marker SyncMarker) Encoder {
- e := pw.NewEncoderRaw(k)
- e.Sync(marker)
- return e
-}
-
-// NewEncoderRaw returns an Encoder for a new element within the given
-// section.
-//
-// Most callers should use NewEncoder instead.
-func (pw *PkgEncoder) NewEncoderRaw(k RelocKind) Encoder {
- idx := Index(len(pw.elems[k]))
- pw.elems[k] = append(pw.elems[k], "") // placeholder
-
- return Encoder{
- p: pw,
- k: k,
- Idx: idx,
- }
-}
-
-// An Encoder provides methods for encoding an individual element's
-// bitstream data.
-type Encoder struct {
- p *PkgEncoder
-
- Relocs []RelocEnt
- RelocMap map[RelocEnt]uint32
- Data bytes.Buffer // accumulated element bitstream data
-
- encodingRelocHeader bool
-
- k RelocKind
- Idx Index // index within relocation section
-}
-
-// Flush finalizes the element's bitstream and returns its Index.
-func (w *Encoder) Flush() Index {
- var sb strings.Builder
-
- // Backup the data so we write the relocations at the front.
- var tmp bytes.Buffer
- io.Copy(&tmp, &w.Data)
-
- // TODO(mdempsky): Consider writing these out separately so they're
- // easier to strip, along with function bodies, so that we can prune
- // down to just the data that's relevant to go/types.
- if w.encodingRelocHeader {
- panic("encodingRelocHeader already true; recursive flush?")
- }
- w.encodingRelocHeader = true
- w.Sync(SyncRelocs)
- w.Len(len(w.Relocs))
- for _, rEnt := range w.Relocs {
- w.Sync(SyncReloc)
- w.Len(int(rEnt.Kind))
- w.Len(int(rEnt.Idx))
- }
-
- io.Copy(&sb, &w.Data)
- io.Copy(&sb, &tmp)
- w.p.elems[w.k][w.Idx] = sb.String()
-
- return w.Idx
-}
-
-func (w *Encoder) checkErr(err error) {
- if err != nil {
- panicf("unexpected encoding error: %v", err)
- }
-}
-
-func (w *Encoder) rawUvarint(x uint64) {
- var buf [binary.MaxVarintLen64]byte
- n := binary.PutUvarint(buf[:], x)
- _, err := w.Data.Write(buf[:n])
- w.checkErr(err)
-}
-
-func (w *Encoder) rawVarint(x int64) {
- // Zig-zag encode.
- ux := uint64(x) << 1
- if x < 0 {
- ux = ^ux
- }
-
- w.rawUvarint(ux)
-}
-
-func (w *Encoder) rawReloc(r RelocKind, idx Index) int {
- e := RelocEnt{r, idx}
- if w.RelocMap != nil {
- if i, ok := w.RelocMap[e]; ok {
- return int(i)
- }
- } else {
- w.RelocMap = make(map[RelocEnt]uint32)
- }
-
- i := len(w.Relocs)
- w.RelocMap[e] = uint32(i)
- w.Relocs = append(w.Relocs, e)
- return i
-}
-
-func (w *Encoder) Sync(m SyncMarker) {
- if !w.p.SyncMarkers() {
- return
- }
-
- // Writing out stack frame string references requires working
- // relocations, but writing out the relocations themselves involves
- // sync markers. To prevent infinite recursion, we simply trim the
- // stack frame for sync markers within the relocation header.
- var frames []string
- if !w.encodingRelocHeader && w.p.syncFrames > 0 {
- pcs := make([]uintptr, w.p.syncFrames)
- n := runtime.Callers(2, pcs)
- frames = fmtFrames(pcs[:n]...)
- }
-
- // TODO(mdempsky): Save space by writing out stack frames as a
- // linked list so we can share common stack frames.
- w.rawUvarint(uint64(m))
- w.rawUvarint(uint64(len(frames)))
- for _, frame := range frames {
- w.rawUvarint(uint64(w.rawReloc(RelocString, w.p.StringIdx(frame))))
- }
-}
-
-// Bool encodes and writes a bool value into the element bitstream,
-// and then returns the bool value.
-//
-// For simple, 2-alternative encodings, the idiomatic way to call Bool
-// is something like:
-//
-// if w.Bool(x != 0) {
-// // alternative #1
-// } else {
-// // alternative #2
-// }
-//
-// For multi-alternative encodings, use Code instead.
-func (w *Encoder) Bool(b bool) bool {
- w.Sync(SyncBool)
- var x byte
- if b {
- x = 1
- }
- err := w.Data.WriteByte(x)
- w.checkErr(err)
- return b
-}
-
-// Int64 encodes and writes an int64 value into the element bitstream.
-func (w *Encoder) Int64(x int64) {
- w.Sync(SyncInt64)
- w.rawVarint(x)
-}
-
-// Uint64 encodes and writes a uint64 value into the element bitstream.
-func (w *Encoder) Uint64(x uint64) {
- w.Sync(SyncUint64)
- w.rawUvarint(x)
-}
-
-// Len encodes and writes a non-negative int value into the element bitstream.
-func (w *Encoder) Len(x int) { assert(x >= 0); w.Uint64(uint64(x)) }
-
-// Int encodes and writes an int value into the element bitstream.
-func (w *Encoder) Int(x int) { w.Int64(int64(x)) }
-
-// Uint encodes and writes a uint value into the element bitstream.
-func (w *Encoder) Uint(x uint) { w.Uint64(uint64(x)) }
-
-// Reloc encodes and writes a relocation for the given (section,
-// index) pair into the element bitstream.
-//
-// Note: Only the index is formally written into the element
-// bitstream, so bitstream decoders must know from context which
-// section an encoded relocation refers to.
-func (w *Encoder) Reloc(r RelocKind, idx Index) {
- w.Sync(SyncUseReloc)
- w.Len(w.rawReloc(r, idx))
-}
-
-// Code encodes and writes a Code value into the element bitstream.
-func (w *Encoder) Code(c Code) {
- w.Sync(c.Marker())
- w.Len(c.Value())
-}
-
-// String encodes and writes a string value into the element
-// bitstream.
-//
-// Internally, strings are deduplicated by adding them to the strings
-// section (if not already present), and then writing a relocation
-// into the element bitstream.
-func (w *Encoder) String(s string) {
- w.StringRef(w.p.StringIdx(s))
-}
-
-// StringRef writes a reference to the given index, which must be a
-// previously encoded string value.
-func (w *Encoder) StringRef(idx Index) {
- w.Sync(SyncString)
- w.Reloc(RelocString, idx)
-}
-
-// Strings encodes and writes a variable-length slice of strings into
-// the element bitstream.
-func (w *Encoder) Strings(ss []string) {
- w.Len(len(ss))
- for _, s := range ss {
- w.String(s)
- }
-}
-
-// Value encodes and writes a constant.Value into the element
-// bitstream.
-func (w *Encoder) Value(val constant.Value) {
- w.Sync(SyncValue)
- if w.Bool(val.Kind() == constant.Complex) {
- w.scalar(constant.Real(val))
- w.scalar(constant.Imag(val))
- } else {
- w.scalar(val)
- }
-}
-
-func (w *Encoder) scalar(val constant.Value) {
- switch v := constant.Val(val).(type) {
- default:
- panicf("unhandled %v (%v)", val, val.Kind())
- case bool:
- w.Code(ValBool)
- w.Bool(v)
- case string:
- w.Code(ValString)
- w.String(v)
- case int64:
- w.Code(ValInt64)
- w.Int64(v)
- case *big.Int:
- w.Code(ValBigInt)
- w.bigInt(v)
- case *big.Rat:
- w.Code(ValBigRat)
- w.bigInt(v.Num())
- w.bigInt(v.Denom())
- case *big.Float:
- w.Code(ValBigFloat)
- w.bigFloat(v)
- }
-}
-
-func (w *Encoder) bigInt(v *big.Int) {
- b := v.Bytes()
- w.String(string(b)) // TODO: More efficient encoding.
- w.Bool(v.Sign() < 0)
-}
-
-func (w *Encoder) bigFloat(v *big.Float) {
- b := v.Append(nil, 'p', -1)
- w.String(string(b)) // TODO: More efficient encoding.
-}
-
-// Version reports the version of the bitstream.
-func (w *Encoder) Version() Version { return w.p.version }
diff --git a/src/vendor/golang.org/x/tools/internal/pkgbits/flags.go b/src/vendor/golang.org/x/tools/internal/pkgbits/flags.go
deleted file mode 100644
index 654222745f..0000000000
--- a/src/vendor/golang.org/x/tools/internal/pkgbits/flags.go
+++ /dev/null
@@ -1,9 +0,0 @@
-// Copyright 2022 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pkgbits
-
-const (
- flagSyncMarkers = 1 << iota // file format contains sync markers
-)
diff --git a/src/vendor/golang.org/x/tools/internal/pkgbits/reloc.go b/src/vendor/golang.org/x/tools/internal/pkgbits/reloc.go
deleted file mode 100644
index 99494aa31b..0000000000
--- a/src/vendor/golang.org/x/tools/internal/pkgbits/reloc.go
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2021 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pkgbits
-
-// This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-
-// A RelocKind indicates a particular section within a unified IR export.
-type RelocKind int32
-
-// An Index represents a bitstream element index within a particular
-// section.
-type Index int32
-
-// A relocEnt (relocation entry) is an entry in an element's local
-// reference table.
-//
-// TODO(mdempsky): Rename this too.
-type RelocEnt struct {
- Kind RelocKind
- Idx Index
-}
-
-// Reserved indices within the meta relocation section.
-const (
- PublicRootIdx Index = 0
- PrivateRootIdx Index = 1
-)
-
-const (
- RelocString RelocKind = iota
- RelocMeta
- RelocPosBase
- RelocPkg
- RelocName
- RelocType
- RelocObj
- RelocObjExt
- RelocObjDict
- RelocBody
-
- numRelocs = iota
-)
diff --git a/src/vendor/golang.org/x/tools/internal/pkgbits/support.go b/src/vendor/golang.org/x/tools/internal/pkgbits/support.go
deleted file mode 100644
index b0011600d2..0000000000
--- a/src/vendor/golang.org/x/tools/internal/pkgbits/support.go
+++ /dev/null
@@ -1,18 +0,0 @@
-// Copyright 2022 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pkgbits
-
-// This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-import "fmt"
-
-func assert(b bool) {
- if !b {
- panic("assertion failed")
- }
-}
-
-func panicf(format string, args ...any) {
- panic(fmt.Errorf(format, args...))
-}
diff --git a/src/vendor/golang.org/x/tools/internal/pkgbits/sync.go b/src/vendor/golang.org/x/tools/internal/pkgbits/sync.go
deleted file mode 100644
index 4cf7f1ee39..0000000000
--- a/src/vendor/golang.org/x/tools/internal/pkgbits/sync.go
+++ /dev/null
@@ -1,137 +0,0 @@
-// Copyright 2021 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pkgbits
-
-import (
- "fmt"
- "runtime"
- "strings"
- // This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-)
-
-// fmtFrames formats a backtrace for reporting reader/writer desyncs.
-func fmtFrames(pcs ...uintptr) []string {
- res := make([]string, 0, len(pcs))
- walkFrames(pcs, func(file string, line int, name string, offset uintptr) {
- // Trim package from function name. It's just redundant noise.
- name = strings.TrimPrefix(name, "cmd/compile/internal/noder.")
-
- res = append(res, fmt.Sprintf("%s:%v: %s +0x%v", file, line, name, offset))
- })
- return res
-}
-
-type frameVisitor func(file string, line int, name string, offset uintptr)
-
-// walkFrames calls visit for each call frame represented by pcs.
-//
-// pcs should be a slice of PCs, as returned by runtime.Callers.
-func walkFrames(pcs []uintptr, visit frameVisitor) {
- if len(pcs) == 0 {
- return
- }
-
- frames := runtime.CallersFrames(pcs)
- for {
- frame, more := frames.Next()
- visit(frame.File, frame.Line, frame.Function, frame.PC-frame.Entry)
- if !more {
- return
- }
- }
-}
-
-// SyncMarker is an enum type that represents markers that may be
-// written to export data to ensure the reader and writer stay
-// synchronized.
-type SyncMarker int
-
-//go:generate stringer -type=SyncMarker -trimprefix=Sync
-
-const (
- _ SyncMarker = iota
-
- // Public markers (known to go/types importers).
-
- // Low-level coding markers.
- SyncEOF
- SyncBool
- SyncInt64
- SyncUint64
- SyncString
- SyncValue
- SyncVal
- SyncRelocs
- SyncReloc
- SyncUseReloc
-
- // Higher-level object and type markers.
- SyncPublic
- SyncPos
- SyncPosBase
- SyncObject
- SyncObject1
- SyncPkg
- SyncPkgDef
- SyncMethod
- SyncType
- SyncTypeIdx
- SyncTypeParamNames
- SyncSignature
- SyncParams
- SyncParam
- SyncCodeObj
- SyncSym
- SyncLocalIdent
- SyncSelector
-
- // Private markers (only known to cmd/compile).
- SyncPrivate
-
- SyncFuncExt
- SyncVarExt
- SyncTypeExt
- SyncPragma
-
- SyncExprList
- SyncExprs
- SyncExpr
- SyncExprType
- SyncAssign
- SyncOp
- SyncFuncLit
- SyncCompLit
-
- SyncDecl
- SyncFuncBody
- SyncOpenScope
- SyncCloseScope
- SyncCloseAnotherScope
- SyncDeclNames
- SyncDeclName
-
- SyncStmts
- SyncBlockStmt
- SyncIfStmt
- SyncForStmt
- SyncSwitchStmt
- SyncRangeStmt
- SyncCaseClause
- SyncCommClause
- SyncSelectStmt
- SyncDecls
- SyncLabeledStmt
- SyncUseObjLocal
- SyncAddLocal
- SyncLinkname
- SyncStmt1
- SyncStmtsEnd
- SyncLabel
- SyncOptLabel
-
- SyncMultiExpr
- SyncRType
- SyncConvRTTI
-)
diff --git a/src/vendor/golang.org/x/tools/internal/pkgbits/syncmarker_string.go b/src/vendor/golang.org/x/tools/internal/pkgbits/syncmarker_string.go
deleted file mode 100644
index 582ad56d3e..0000000000
--- a/src/vendor/golang.org/x/tools/internal/pkgbits/syncmarker_string.go
+++ /dev/null
@@ -1,92 +0,0 @@
-// Code generated by "stringer -type=SyncMarker -trimprefix=Sync"; DO NOT EDIT.
-
-package pkgbits
-
-import "strconv"
-
-func _() {
- // An "invalid array index" compiler error signifies that the constant values have changed.
- // Re-run the stringer command to generate them again.
- var x [1]struct{}
- _ = x[SyncEOF-1]
- _ = x[SyncBool-2]
- _ = x[SyncInt64-3]
- _ = x[SyncUint64-4]
- _ = x[SyncString-5]
- _ = x[SyncValue-6]
- _ = x[SyncVal-7]
- _ = x[SyncRelocs-8]
- _ = x[SyncReloc-9]
- _ = x[SyncUseReloc-10]
- _ = x[SyncPublic-11]
- _ = x[SyncPos-12]
- _ = x[SyncPosBase-13]
- _ = x[SyncObject-14]
- _ = x[SyncObject1-15]
- _ = x[SyncPkg-16]
- _ = x[SyncPkgDef-17]
- _ = x[SyncMethod-18]
- _ = x[SyncType-19]
- _ = x[SyncTypeIdx-20]
- _ = x[SyncTypeParamNames-21]
- _ = x[SyncSignature-22]
- _ = x[SyncParams-23]
- _ = x[SyncParam-24]
- _ = x[SyncCodeObj-25]
- _ = x[SyncSym-26]
- _ = x[SyncLocalIdent-27]
- _ = x[SyncSelector-28]
- _ = x[SyncPrivate-29]
- _ = x[SyncFuncExt-30]
- _ = x[SyncVarExt-31]
- _ = x[SyncTypeExt-32]
- _ = x[SyncPragma-33]
- _ = x[SyncExprList-34]
- _ = x[SyncExprs-35]
- _ = x[SyncExpr-36]
- _ = x[SyncExprType-37]
- _ = x[SyncAssign-38]
- _ = x[SyncOp-39]
- _ = x[SyncFuncLit-40]
- _ = x[SyncCompLit-41]
- _ = x[SyncDecl-42]
- _ = x[SyncFuncBody-43]
- _ = x[SyncOpenScope-44]
- _ = x[SyncCloseScope-45]
- _ = x[SyncCloseAnotherScope-46]
- _ = x[SyncDeclNames-47]
- _ = x[SyncDeclName-48]
- _ = x[SyncStmts-49]
- _ = x[SyncBlockStmt-50]
- _ = x[SyncIfStmt-51]
- _ = x[SyncForStmt-52]
- _ = x[SyncSwitchStmt-53]
- _ = x[SyncRangeStmt-54]
- _ = x[SyncCaseClause-55]
- _ = x[SyncCommClause-56]
- _ = x[SyncSelectStmt-57]
- _ = x[SyncDecls-58]
- _ = x[SyncLabeledStmt-59]
- _ = x[SyncUseObjLocal-60]
- _ = x[SyncAddLocal-61]
- _ = x[SyncLinkname-62]
- _ = x[SyncStmt1-63]
- _ = x[SyncStmtsEnd-64]
- _ = x[SyncLabel-65]
- _ = x[SyncOptLabel-66]
- _ = x[SyncMultiExpr-67]
- _ = x[SyncRType-68]
- _ = x[SyncConvRTTI-69]
-}
-
-const _SyncMarker_name = "EOFBoolInt64Uint64StringValueValRelocsRelocUseRelocPublicPosPosBaseObjectObject1PkgPkgDefMethodTypeTypeIdxTypeParamNamesSignatureParamsParamCodeObjSymLocalIdentSelectorPrivateFuncExtVarExtTypeExtPragmaExprListExprsExprExprTypeAssignOpFuncLitCompLitDeclFuncBodyOpenScopeCloseScopeCloseAnotherScopeDeclNamesDeclNameStmtsBlockStmtIfStmtForStmtSwitchStmtRangeStmtCaseClauseCommClauseSelectStmtDeclsLabeledStmtUseObjLocalAddLocalLinknameStmt1StmtsEndLabelOptLabelMultiExprRTypeConvRTTI"
-
-var _SyncMarker_index = [...]uint16{0, 3, 7, 12, 18, 24, 29, 32, 38, 43, 51, 57, 60, 67, 73, 80, 83, 89, 95, 99, 106, 120, 129, 135, 140, 147, 150, 160, 168, 175, 182, 188, 195, 201, 209, 214, 218, 226, 232, 234, 241, 248, 252, 260, 269, 279, 296, 305, 313, 318, 327, 333, 340, 350, 359, 369, 379, 389, 394, 405, 416, 424, 432, 437, 445, 450, 458, 467, 472, 480}
-
-func (i SyncMarker) String() string {
- i -= 1
- if i < 0 || i >= SyncMarker(len(_SyncMarker_index)-1) {
- return "SyncMarker(" + strconv.FormatInt(int64(i+1), 10) + ")"
- }
- return _SyncMarker_name[_SyncMarker_index[i]:_SyncMarker_index[i+1]]
-}
diff --git a/src/vendor/golang.org/x/tools/internal/pkgbits/version.go b/src/vendor/golang.org/x/tools/internal/pkgbits/version.go
deleted file mode 100644
index 932a92679b..0000000000
--- a/src/vendor/golang.org/x/tools/internal/pkgbits/version.go
+++ /dev/null
@@ -1,113 +0,0 @@
-// Copyright 2024 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pkgbits
-
-// This package is dependency-restricted; see x/tools/go/gcexportdata.TestDeps.
-
-// Version indicates a version of a unified IR bitstream.
-// Each Version indicates the addition, removal, or change of
-// new data in the bitstream.
-//
-// These are serialized to disk and the interpretation remains fixed.
-type Version uint32
-
-const (
- // V0: initial prototype.
- //
- // All data that is not assigned a Field is in version V0
- // and has not been deprecated.
- V0 Version = iota
-
- // V1: adds the Flags uint32 word
- V1
-
- // V2: removes unused legacy fields and supports type parameters for aliases.
- // - remove the legacy "has init" bool from the public root
- // - remove obj's "derived func instance" bool
- // - add a TypeParamNames field to ObjAlias
- // - remove derived info "needed" bool
- V2
-
- // V3: introduces a more compact format for composite literal element lists
- // - negative lengths indicate that (some) elements may have keys
- // - positive lengths indicate that no element has a key
- // - a negative struct field index indicates an embedded field
- V3
-
- // V4: encodes generic methods as standalone function objects
- V4
-
- // V5: encodes the index of methods to preserve relative order
- // of nongeneric and generic methods (go.dev/issue/81188).
- V5
-
- numVersions = iota
-)
-
-// Field denotes a unit of data in the serialized unified IR bitstream.
-// It is conceptually a like field in a structure.
-//
-// We only really need Fields when the data may or may not be present
-// in a stream based on the Version of the bitstream.
-//
-// Unlike much of pkgbits, Fields are not serialized and
-// can change values as needed.
-type Field int
-
-const (
- // Flags in a uint32 in the header of a bitstream
- // that is used to indicate whether optional features are enabled.
- Flags Field = iota
-
- // Deprecated: HasInit was a bool indicating whether a package
- // has any init functions.
- HasInit
-
- // Deprecated: DerivedFuncInstance was a bool indicating
- // whether an object was a function instance.
- DerivedFuncInstance
-
- // ObjAlias has a list of TypeParamNames.
- AliasTypeParamNames
-
- // Deprecated: DerivedInfoNeeded was a bool indicating
- // whether a type was a derived type.
- DerivedInfoNeeded
-
- // Composite literals use a more compact format for element lists.
- CompactCompLiterals
-
- // Generic methods may appear as standalone function objects.
- GenericMethods
-
- // Method index is encoded to preserve relative order of
- // nongeneric and generic methods.
- PreserveMethodOrder
-
- numFields = iota
-)
-
-// introduced is the version a field was added.
-var introduced = [numFields]Version{
- Flags: V1,
- AliasTypeParamNames: V2,
- CompactCompLiterals: V3,
- GenericMethods: V4,
- PreserveMethodOrder: V5,
-}
-
-// removed is the version a field was removed in or 0 for fields
-// that have not yet been deprecated.
-// (So removed[f]-1 is the last version it is included in.)
-var removed = [numFields]Version{
- HasInit: V2,
- DerivedFuncInstance: V2,
- DerivedInfoNeeded: V2,
-}
-
-// Has reports whether field f is present in a bitstream at version v.
-func (v Version) Has(f Field) bool {
- return introduced[f] <= v && (v < removed[f] || removed[f] == V0)
-}
diff --git a/src/vendor/modules.txt b/src/vendor/modules.txt
index 46e04af937..8095009761 100644
--- a/src/vendor/modules.txt
+++ b/src/vendor/modules.txt
@@ -82,7 +82,6 @@ golang.org/x/tools/go/ast/astutil
golang.org/x/tools/go/ast/edge
golang.org/x/tools/go/ast/inspector
golang.org/x/tools/go/cfg
-golang.org/x/tools/go/gcexportdata
golang.org/x/tools/go/types/objectpath
golang.org/x/tools/go/types/typeutil
golang.org/x/tools/internal/analysis/analyzerutil
@@ -100,7 +99,6 @@ golang.org/x/tools/internal/fmtstr
golang.org/x/tools/internal/moreiters
golang.org/x/tools/internal/moremaps
golang.org/x/tools/internal/packagepath
-golang.org/x/tools/internal/pkgbits
golang.org/x/tools/internal/refactor
golang.org/x/tools/internal/refactor/inline
golang.org/x/tools/internal/stdlib