Commit a298359589 for golang

commit a2983595895d361e4fdde746d61dc4778c08d077
Author: Alan Donovan <adonovan@google.com>
Date:   Mon Nov 23 18:15:25 2026 -0500

    go/types/exportdata: publish codec for i-format type export data

    This CL publishes x/tools/internal/exportdata as a new std
    package, providing an API to both encode and decode go/types'
    data structures, in both deep and shallow modes.

    The codec is a copy. After the go1.28 release, the x/tools impl
    will delegate to this one, and eventually its impl will disappear
    after go1.29.

    The env_test.go file is new code; it provides the std
    implementation of various test helpers.

    Fixes #69491

    Change-Id: I0e935bab012ec7b46dca54c50e3d2db30a85a504
    Reviewed-on: https://go-review.googlesource.com/c/go/+/866708
    SLSA-Policy-Verified: SLSA Policy Verification Service <devtools-gerritcodereview-exitgate@google.com>
    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/api/next/69491.txt b/api/next/69491.txt
new file mode 100644
index 0000000000..5132cd877b
--- /dev/null
+++ b/api/next/69491.txt
@@ -0,0 +1,9 @@
+pkg go/types/exportdata, func Decode(*token.FileSet, string, []uint8, func([]PackageRef) ([]*types.Package, error), DecodeOptions) (*types.Package, error) #69491
+pkg go/types/exportdata, func Encode(*token.FileSet, *types.Package, EncodeOptions) ([]uint8, error) #69491
+pkg go/types/exportdata, func PackagesFromMap(map[string]*types.Package) func([]PackageRef) ([]*types.Package, error) #69491
+pkg go/types/exportdata, type DecodeOptions struct #69491
+pkg go/types/exportdata, type EncodeOptions struct #69491
+pkg go/types/exportdata, type EncodeOptions struct, Shallow bool #69491
+pkg go/types/exportdata, type PackageRef struct #69491
+pkg go/types/exportdata, type PackageRef struct, Name string #69491
+pkg go/types/exportdata, type PackageRef struct, Path string #69491
diff --git a/doc/next/6-stdlib/99-minor/go/types/exportdata/69491.md b/doc/next/6-stdlib/99-minor/go/types/exportdata/69491.md
new file mode 100644
index 0000000000..a8a3c753cf
--- /dev/null
+++ b/doc/next/6-stdlib/99-minor/go/types/exportdata/69491.md
@@ -0,0 +1,10 @@
+<!-- go.dev/issue/69491 -->
+
+The new [go/types/exportdata] package provides a codec for type
+export data. [Encode] returns an encoding of a [go/types.Package],
+and [Decode] reconstructs the package from that encoding, allowing
+tools to save and reload type information without type-checking
+from source. The encoding may be "deep", describing all objects
+reachable from the package's API, or "shallow", describing only the
+package's own objects.
+This package may be used to decode the files produced by `go list -export`.
diff --git a/src/cmd/export/main.go b/src/cmd/export/main.go
index c4e15dc3b5..b180053f37 100644
--- a/src/cmd/export/main.go
+++ b/src/cmd/export/main.go
@@ -158,6 +158,7 @@ func makeTypesImporter(cfg *config, fset *token.FileSet) types.Importer {
 			return nil, err
 		}
 		defer f.Close()
+		// TODO(adonovan): use go/types/exportdata.
 		return gcexportdata.Read(f, fset, imports, pkgPath)
 	})
 }
diff --git a/src/cmd/go/alldocs.go b/src/cmd/go/alldocs.go
index 471fd4c3a4..63e650a10e 100644
--- a/src/cmd/go/alldocs.go
+++ b/src/cmd/go/alldocs.go
@@ -999,8 +999,7 @@
 // file containing up-to-date export data for the given package,
 // and the BuildID field to the build ID of the exported package.
 // The Export file encodes complete type information for the package's
-// public API. To decode it, use the golang.org/x/tools/go/gcexportdata
-// package.
+// public API. To decode it, use the go/types/exportdata package.
 //
 // The -find flag causes list to identify the named packages but not
 // resolve their dependencies: the Imports and Deps lists will be empty.
diff --git a/src/cmd/go/internal/list/list.go b/src/cmd/go/internal/list/list.go
index aac58ceaf0..1fb6cd97de 100644
--- a/src/cmd/go/internal/list/list.go
+++ b/src/cmd/go/internal/list/list.go
@@ -201,8 +201,7 @@ The -export flag causes list to set the Export field to the name of a
 file containing up-to-date export data for the given package,
 and the BuildID field to the build ID of the exported package.
 The Export file encodes complete type information for the package's
-public API. To decode it, use the golang.org/x/tools/go/gcexportdata
-package.
+public API. To decode it, use the go/types/exportdata package.

 The -find flag causes list to identify the named packages but not
 resolve their dependencies: the Imports and Deps lists will be empty.
diff --git a/src/go/build/deps_test.go b/src/go/build/deps_test.go
index a551515252..f3b84ff85b 100644
--- a/src/go/build/deps_test.go
+++ b/src/go/build/deps_test.go
@@ -642,6 +642,9 @@ var depsRules = `
 	hash/maphash, container/heap, go/constant, go/parser, internal/buildcfg, internal/goversion, internal/types/errors
 	< go/types;

+	encoding/binary, go/types
+	< go/types/exportdata;
+
 	FMT, flag, go/types, time
 	< go/analysis;

diff --git a/src/go/internal/gcimporter/gcimporter.go b/src/go/internal/gcimporter/gcimporter.go
index fa3efa632f..2f4c191064 100644
--- a/src/go/internal/gcimporter/gcimporter.go
+++ b/src/go/internal/gcimporter/gcimporter.go
@@ -77,6 +77,7 @@ 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)
 		return
 	}
diff --git a/src/go/types/exportdata/bimport.go b/src/go/types/exportdata/bimport.go
new file mode 100644
index 0000000000..31e3ef9b34
--- /dev/null
+++ b/src/go/types/exportdata/bimport.go
@@ -0,0 +1,97 @@
+// 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"
+)
+
+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/go/types/exportdata/codec.go b/src/go/types/exportdata/codec.go
new file mode 100644
index 0000000000..7b750a22ec
--- /dev/null
+++ b/src/go/types/exportdata/codec.go
@@ -0,0 +1,211 @@
+// 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].
+//
+// # 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/go/types/exportdata/codec_test.go b/src/go/types/exportdata/codec_test.go
new file mode 100644
index 0000000000..0a9e7d6e9f
--- /dev/null
+++ b/src/go/types/exportdata/codec_test.go
@@ -0,0 +1,463 @@
+// 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_test
+
+// This file defines focused tests of the codec.
+
+import (
+	"go/ast"
+	"go/parser"
+	goparser "go/parser"
+	"go/token"
+	"go/types"
+	"strings"
+	"sync"
+	"testing"
+
+	"go/types/exportdata"
+)
+
+// TestEncodeDecode checks superficial aspects of the Encode/Decode
+// API in deep and shallow modes. (The rest is covered thoroughly by
+// other tests.)
+func TestEncodeDecode(t *testing.T) {
+	const (
+		srcA = `package a; type T struct{ X int }; func F() T { return T{} }`
+		srcB = `package b; import "a"; var V = a.F(); type U a.T`
+	)
+	fset := token.NewFileSet()
+	check := func(path, src string, imports map[string]*types.Package) *types.Package {
+		t.Helper()
+		f, err := parser.ParseFile(fset, path+".go", src, 0)
+		if err != nil {
+			t.Fatal(err)
+		}
+		conf := types.Config{
+			Importer: importerFunc(func(path string) (*types.Package, error) {
+				return imports[path], nil
+			}),
+		}
+		pkg, err := conf.Check(path, fset, []*ast.File{f}, nil)
+		if err != nil {
+			t.Fatal(err)
+		}
+		return pkg
+	}
+	a := check("a", srcA, nil)
+	b := check("b", srcB, map[string]*types.Package{"a": a})
+
+	for _, shallow := range []bool{false, true} {
+		data, err := exportdata.Encode(fset, b, exportdata.EncodeOptions{Shallow: shallow})
+		if err != nil {
+			t.Fatalf("Encode(%v): %v", shallow, err)
+		}
+		if len(data) == 0 || data[0] != 'i' {
+			t.Errorf("Encode(%v): data does not begin with 'i'", shallow)
+		}
+
+		// getPackages is called once, with all mentioned packages,
+		// the one being decoded first.
+		imports := map[string]*types.Package{}
+		if shallow {
+			imports["a"] = a // shallow mode requires complete dependencies
+		}
+		b2, err := exportdata.Decode(fset, "b", data, exportdata.PackagesFromMap(imports), exportdata.DecodeOptions{})
+		if err != nil {
+			t.Fatalf("Decode(%v): %v", shallow, err)
+		}
+		if b2 != imports["b"] {
+			t.Errorf("Decode(%v) did not return the package from getPackages", shallow)
+		}
+		// Decode populates the package returned by getPackages.
+		if b2.Scope().Lookup("V") == nil {
+			t.Errorf("Decode(%v) did not populate package", shallow)
+		}
+	}
+}
+
+// TestVeryLongFile tests the position of an import object declared in
+// a very long input file. Positions are preserved exactly
+// (since iexportVersionFullPos).
+func TestVeryLongFile(t *testing.T) {
+	// parse and typecheck
+	longFile := "package foo" + strings.Repeat("\n", 123456) + "var X int"
+	fset1 := token.NewFileSet()
+	f, err := parser.ParseFile(fset1, "foo.go", longFile, 0)
+	if err != nil {
+		t.Fatal(err)
+	}
+	var conf types.Config
+	pkg, err := conf.Check("foo", fset1, []*ast.File{f}, nil)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	// export
+	data, err := exportdata.Encode(fset1, pkg, exportdata.EncodeOptions{})
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	// import
+	imports := make(map[string]*types.Package)
+	fset2 := token.NewFileSet()
+	pkg2, err := exportdata.Decode(fset2, pkg.Path(), data, exportdata.PackagesFromMap(imports), exportdata.DecodeOptions{})
+	if err != nil {
+		t.Fatalf("BImportData(%s): %v", pkg.Path(), err)
+	}
+
+	// compare
+	posn1 := fset1.Position(pkg.Scope().Lookup("X").Pos())
+	posn2 := fset2.Position(pkg2.Scope().Lookup("X").Pos())
+	if posn2 != posn1 {
+		t.Errorf("X position = %s, want %s", posn2, posn1)
+	}
+}
+
+const src = `
+package p
+
+type (
+	T0 = int32
+	T1 = struct{}
+	T2 = struct{ T1 }
+	Invalid = foo // foo is undeclared
+)
+`
+
+func checkPkg(t *testing.T, pkg *types.Package, label string) {
+	T1 := types.NewStruct(nil, nil)
+	T2 := types.NewStruct([]*types.Var{types.NewField(0, pkg, "T1", T1, true)}, nil)
+
+	for _, test := range []struct {
+		name string
+		typ  types.Type
+	}{
+		{"T0", types.Typ[types.Int32]},
+		{"T1", T1},
+		{"T2", T2},
+		{"Invalid", types.Typ[types.Invalid]},
+	} {
+		obj := pkg.Scope().Lookup(test.name)
+		if obj == nil {
+			t.Errorf("%s: %s not found", label, test.name)
+			continue
+		}
+		tname, _ := obj.(*types.TypeName)
+		if tname == nil {
+			t.Errorf("%s: %v not a type name", label, obj)
+			continue
+		}
+		if !tname.IsAlias() {
+			t.Errorf("%s: %v: not marked as alias", label, tname)
+			continue
+		}
+		if got := tname.Type(); !types.Identical(got, test.typ) {
+			t.Errorf("%s: %v: got %v; want %v", label, tname, got, test.typ)
+		}
+	}
+}
+
+func TestAliases(t *testing.T) {
+	// parse and typecheck
+	fset1 := token.NewFileSet()
+	f, err := parser.ParseFile(fset1, "p.go", src, 0)
+	if err != nil {
+		t.Fatal(err)
+	}
+	var conf types.Config
+	pkg1, err := conf.Check("p", fset1, []*ast.File{f}, nil)
+	if err == nil {
+		// foo in undeclared in src; we should see an error
+		t.Fatal("invalid source type-checked without error")
+	}
+	if pkg1 == nil {
+		// despite incorrect src we should see a (partially) type-checked package
+		t.Fatal("nil package returned")
+	}
+	checkPkg(t, pkg1, "export")
+
+	// export
+	// Use an empty FileSet here (as gcexportdata.Write does for a nil
+	// one) to confirm that positions not in the FileSet don't panic.
+	data, err := exportdata.Encode(token.NewFileSet(), pkg1, exportdata.EncodeOptions{})
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	// import
+	imports := make(map[string]*types.Package)
+	fset2 := token.NewFileSet()
+	pkg2, err := exportdata.Decode(fset2, pkg1.Path(), data, exportdata.PackagesFromMap(imports), exportdata.DecodeOptions{})
+	if err != nil {
+		t.Fatalf("Decode(%s): %v", pkg1.Path(), err)
+	}
+	checkPkg(t, pkg2, "import")
+}
+
+// TestExactFloats checks that, as of iexportVersionRationalFloats,
+// floating point constants round-trip without loss (go.dev/issue/82186).
+func TestExactFloats(t *testing.T) {
+	const src = `package p
+
+const (
+	Third                = 1.0 / 3
+	NegSeventh           = -1.0 / 7
+	Zero                 = 0.0
+	Int                  = 42.0
+	NegInt               = -2.0
+	BigInt               = 1e100       // integer; fits untyped mpint
+	MaxMpint             = 0x1p512 - 1 // largest integer encoded as mpint
+	TooBigInt            = 0x1p512     // too large for mpint; encoded as rational
+	HugeInt              = -1e300      // too large for mpint; encoded as rational
+	Huge                 = 1e10000 / 3 // not representable as a rational by go/constant
+	Tiny                 = 1e-10000
+	Complex              = 1.0/3 + (2.0/7)*1i
+	F32       float32    = 1.0 / 3
+	F64       float64    = 1.0 / 3
+	F64Int    float64    = 1e20
+	C128      complex128 = 1.0/3 + 1i
+)
+`
+	fset := token.NewFileSet()
+	f, err := parser.ParseFile(fset, "p.go", src, 0)
+	if err != nil {
+		t.Fatal(err)
+	}
+	var conf types.Config
+	pkg, err := conf.Check("p", fset, []*ast.File{f}, nil)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	data, err := exportdata.Encode(fset, pkg, exportdata.EncodeOptions{})
+	if err != nil {
+		t.Fatalf("iexport: %v", err)
+	}
+	pkg2, err := exportdata.Decode(token.NewFileSet(), pkg.Path(), data, exportdata.PackagesFromMap(make(map[string]*types.Package)), exportdata.DecodeOptions{})
+	if err != nil {
+		t.Fatalf("Decode: %v", err)
+	}
+
+	for _, name := range pkg.Scope().Names() {
+		want := pkg.Scope().Lookup(name).(*types.Const).Val()
+		got := pkg2.Scope().Lookup(name).(*types.Const).Val()
+		// Compare exact representations: constant.Compare considers
+		// 1/3 equal to its 512-bit float approximation.
+		if got.ExactString() != want.ExactString() {
+			t.Errorf("%s: got %s, want %s (exact: got %s, want %s)",
+				name, got, want, got.ExactString(), want.ExactString())
+		}
+	}
+}
+
+func TestIssue61561(t *testing.T) {
+	const src = `package p
+
+type I[P any] interface {
+	m(P)
+	n() P
+}
+
+type J = I[int]
+
+type StillBad[P any] *interface{b(P)}
+
+type K = StillBad[string]
+`
+	fset := token.NewFileSet()
+	f, err := goparser.ParseFile(fset, "p.go", src, 0)
+	if f == nil {
+		// Some test cases may have parse errors, but we must always have a
+		// file.
+		t.Fatalf("ParseFile returned nil file. Err: %v", err)
+	}
+
+	config := &types.Config{}
+	pkg1, err := config.Check("p", fset, []*ast.File{f}, nil)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	// Export it. (Shallowness isn't important here.)
+	data, err := exportdata.Encode(fset, pkg1, exportdata.EncodeOptions{Shallow: true})
+	if err != nil {
+		t.Fatalf("export: %v", err) // any failure to export is a bug
+	}
+
+	// Re-import it.
+	imports := make(map[string]*types.Package)
+	pkg2, err := exportdata.Decode(fset, "p", data, exportdata.PackagesFromMap(imports), exportdata.DecodeOptions{})
+	if err != nil {
+		t.Fatalf("import: %v", err) // any failure of IExport+IImport is a bug.
+	}
+
+	insts := []types.Type{
+		pkg2.Scope().Lookup("J").Type(),
+		// The incomplete interface is contained within a
+		// nested type expression (golang/go#61561).
+		pkg2.Scope().Lookup("K").Type().Underlying().(*types.Pointer).Elem(),
+	}
+
+	// Use the interface instances concurrently.
+	for _, inst := range insts {
+		var wg sync.WaitGroup
+		for range 2 {
+			wg.Go(func() {
+				_ = types.NewMethodSet(inst)
+			})
+		}
+		wg.Wait()
+	}
+}
+
+// This is a regression test for a failure to export a package
+// containing type errors.
+//
+// Though the issues and tests are specific, they may be representatives of a
+// class of exporter bugs on ill-typed code that we have yet to flush out.
+//
+// TODO(adonovan): systematize our search for similar problems using
+// fuzz testing.
+func TestExportInvalid(t *testing.T) {
+
+	tests := []struct {
+		name    string
+		src     string
+		objName string
+		invalid bool // the object's underlying type must be invalid
+	}{
+		// The lack of a receiver causes Recv.Type=Invalid.
+		// (The type checker then treats Foo as a package-level
+		// function, inserting it into the package scope.)
+		// The exporter needs to apply the same treatment.
+		{"issue 57729", `package p; func () Foo() {}`, "Foo", false},
+
+		// It must be possible to export a constant with unknown kind, even if its
+		// type is known.
+		{"issue 60605", `package p; const EPSILON float64 = 1e-`, "EPSILON", false},
+
+		// We must not crash when exporting a struct with unknown package.
+		{"issue 60891", `package p; type I[P any] int; const C I[struct{}] = 42`, "C", false},
+
+		// Objects whose types or values are invalid must be preserved.
+		{"invalid value", `package p; const UnknownValue = "" + 0`, "UnknownValue", true},
+		{"invalid type", `package p; type UnknownType undefined`, "UnknownType", true},
+	}
+
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			// Parse the ill-typed input.
+			fset := token.NewFileSet()
+
+			f, err := goparser.ParseFile(fset, "p.go", test.src, 0)
+			if f == nil {
+				// Some test cases may have parse errors, but we must always have a
+				// file.
+				t.Fatalf("ParseFile returned nil file. Err: %v", err)
+			}
+
+			// Type check it, expecting errors.
+			config := &types.Config{
+				Error: func(err error) { t.Log(err) }, // don't abort at first error
+			}
+			pkg1, _ := config.Check("p", fset, []*ast.File{f}, nil)
+
+			// Export it.
+			// (Shallowness isn't important here.)
+			data, err := exportdata.Encode(fset, pkg1, exportdata.EncodeOptions{Shallow: true})
+			if err != nil {
+				t.Fatalf("export: %v", err) // any failure to export is a bug
+			}
+
+			// Re-import it.
+			imports := make(map[string]*types.Package)
+			pkg2, err := exportdata.Decode(fset, "p", data, exportdata.PackagesFromMap(imports), exportdata.DecodeOptions{})
+			if err != nil {
+				t.Fatalf("import: %v", err) // any failure of IExport+IImport is a bug.
+			}
+
+			// Check that the expected object is present in both packages.
+			// We can't assert the type hasn't changed: it may have, in some cases.
+			hasObj1 := pkg1.Scope().Lookup(test.objName) != nil
+			hasObj2 := pkg2.Scope().Lookup(test.objName) != nil
+			if hasObj1 != hasObj2 {
+				t.Errorf("export+import changed Lookup(%q)!=nil: was %t, became %t", test.objName, hasObj1, hasObj2)
+			}
+			if test.invalid && hasObj2 {
+				obj := pkg2.Scope().Lookup(test.objName)
+				if typ := obj.Type().Underlying(); typ.String() != "invalid type" {
+					t.Errorf("%s has underlying type %s, want invalid type", test.objName, typ)
+				}
+			}
+		})
+	}
+}
+
+type importMap map[string]*types.Package
+
+func (m importMap) Import(path string) (*types.Package, error) { return m[path], nil }
+
+func TestIssue69912(t *testing.T) {
+	fset := token.NewFileSet()
+
+	check := func(pkgname, src string, imports importMap) (*types.Package, error) {
+		f, err := goparser.ParseFile(fset, "a.go", src, 0)
+		if err != nil {
+			return nil, err
+		}
+		config := &types.Config{
+			Importer: imports,
+		}
+		return config.Check(pkgname, fset, []*ast.File{f}, nil)
+	}
+
+	const libSrc = `package lib
+
+type T int
+`
+
+	lib, err := check("lib", libSrc, nil)
+	if err != nil {
+		t.Fatalf("Checking lib: %v", err)
+	}
+
+	// Export it.
+	data, err := exportdata.Encode(fset, lib, exportdata.EncodeOptions{})
+	if err != nil {
+		t.Fatalf("export: %v", err) // any failure to export is a bug
+	}
+
+	// Re-import it.
+	imports := make(map[string]*types.Package)
+	lib2, err := exportdata.Decode(fset, "lib", data, exportdata.PackagesFromMap(imports), exportdata.DecodeOptions{})
+	if err != nil {
+		t.Fatalf("import: %v", err) // any failure of export+import is a bug.
+	}
+
+	// Use the resulting package concurrently, via dot-imports.
+
+	const pSrc = `package p
+
+import . "lib"
+
+type S struct {
+	f T
+}
+`
+	importer := importMap{
+		"lib": lib2,
+	}
+	var wg sync.WaitGroup
+	for range 10 {
+		wg.Go(func() {
+			_, err := check("p", pSrc, importer)
+			if err != nil {
+				t.Errorf("check failed: %v", err)
+			}
+		})
+	}
+	wg.Wait()
+}
diff --git a/src/go/types/exportdata/compare_test.go b/src/go/types/exportdata/compare_test.go
new file mode 100644
index 0000000000..ebbafbfac8
--- /dev/null
+++ b/src/go/types/exportdata/compare_test.go
@@ -0,0 +1,427 @@
+// 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 exportdata_test
+
+// This file defines helpers for comparing decoded packages with the originals.
+
+import (
+	"fmt"
+	"go/constant"
+	"go/token"
+	"go/types"
+	"math/big"
+	"path/filepath"
+	"reflect"
+	"runtime"
+	"sort"
+	"strings"
+	"testing"
+
+	"go/types/exportdata"
+)
+
+// fileLine returns the file and line (and, optionally, column) of obj.
+func fileLine(fset *token.FileSet, obj types.Object, column bool) string {
+	posn := fset.Position(obj.Pos())
+	filename := filepath.Clean(strings.ReplaceAll(posn.Filename, "$GOROOT", runtime.GOROOT()))
+	if column {
+		return fmt.Sprintf("%s:%d:%d", filename, posn.Line, posn.Column)
+	}
+	return fmt.Sprintf("%s:%d", filename, posn.Line)
+}
+
+func equalType(x, y types.Type) error {
+	x = types.Unalias(x)
+	y = types.Unalias(y)
+	if reflect.TypeOf(x) != reflect.TypeOf(y) {
+		return fmt.Errorf("unequal kinds: %T vs %T", x, y)
+	}
+	switch x := x.(type) {
+	case *types.Interface:
+		y := y.(*types.Interface)
+		if x.NumEmbeddeds() != y.NumEmbeddeds() {
+			return fmt.Errorf("unequal number of embedded interfaces: %d vs %d",
+				x.NumEmbeddeds(), y.NumEmbeddeds())
+		}
+		for i := 0; i < x.NumEmbeddeds(); i++ {
+			xi := x.EmbeddedType(i)
+			yi := y.EmbeddedType(i)
+			if xi.String() != yi.String() {
+				return fmt.Errorf("mismatched %dth embedded interface: %s vs %s",
+					i, xi, yi)
+			}
+		}
+		if x.NumExplicitMethods() != y.NumExplicitMethods() {
+			return fmt.Errorf("unequal methods: %d vs %d",
+				x.NumExplicitMethods(), y.NumExplicitMethods())
+		}
+		for i := 0; i < x.NumExplicitMethods(); i++ {
+			xm := x.ExplicitMethod(i)
+			ym := y.ExplicitMethod(i)
+			if xm.Name() != ym.Name() {
+				return fmt.Errorf("mismatched %dth method: %s vs %s", i, xm, ym)
+			}
+			if err := equalType(xm.Type(), ym.Type()); err != nil {
+				return fmt.Errorf("mismatched %s method: %s", xm.Name(), err)
+			}
+		}
+		if x.NumMethods() != y.NumMethods() {
+			return fmt.Errorf("unequal methods: %d vs %d",
+				x.NumMethods(), y.NumMethods())
+		}
+		for i := 0; i < x.NumMethods(); i++ {
+			xm := x.Method(i)
+			ym := y.Method(i)
+			if xm.Name() != ym.Name() {
+				return fmt.Errorf("mismatched %dth method: %s vs %s", i, xm, ym)
+			}
+			if err := equalType(xm.Type(), ym.Type()); err != nil {
+				return fmt.Errorf("mismatched %s method: %s", xm.Name(), err)
+			}
+		}
+		// Constraints are handled explicitly in the *TypeParam case below, so we
+		// don't yet need to consider embeddeds here.
+		// TODO(rfindley): consider the type set here.
+	case *types.Array:
+		y := y.(*types.Array)
+		if x.Len() != y.Len() {
+			return fmt.Errorf("unequal array lengths: %d vs %d", x.Len(), y.Len())
+		}
+		if err := equalType(x.Elem(), y.Elem()); err != nil {
+			return fmt.Errorf("array elements: %s", err)
+		}
+	case *types.Basic:
+		y := y.(*types.Basic)
+		if x.Kind() != y.Kind() {
+			return fmt.Errorf("unequal basic types: %s vs %s", x, y)
+		}
+	case *types.Chan:
+		y := y.(*types.Chan)
+		if x.Dir() != y.Dir() {
+			return fmt.Errorf("unequal channel directions: %d vs %d", x.Dir(), y.Dir())
+		}
+		if err := equalType(x.Elem(), y.Elem()); err != nil {
+			return fmt.Errorf("channel elements: %s", err)
+		}
+	case *types.Map:
+		y := y.(*types.Map)
+		if err := equalType(x.Key(), y.Key()); err != nil {
+			return fmt.Errorf("map keys: %s", err)
+		}
+		if err := equalType(x.Elem(), y.Elem()); err != nil {
+			return fmt.Errorf("map values: %s", err)
+		}
+	case *types.Named:
+		y := y.(*types.Named)
+		return cmpNamed(x, y)
+	case *types.Pointer:
+		y := y.(*types.Pointer)
+		if err := equalType(x.Elem(), y.Elem()); err != nil {
+			return fmt.Errorf("pointer elements: %s", err)
+		}
+	case *types.Signature:
+		y := y.(*types.Signature)
+		if err := equalType(x.Params(), y.Params()); err != nil {
+			return fmt.Errorf("parameters: %s", err)
+		}
+		if err := equalType(x.Results(), y.Results()); err != nil {
+			return fmt.Errorf("results: %s", err)
+		}
+		if x.Variadic() != y.Variadic() {
+			return fmt.Errorf("unequal variadicity: %t vs %t",
+				x.Variadic(), y.Variadic())
+		}
+		if (x.Recv() != nil) != (y.Recv() != nil) {
+			return fmt.Errorf("unequal receivers: %s vs %s", x.Recv(), y.Recv())
+		}
+		if x.Recv() != nil {
+			if xk, yk := x.Recv().Kind(), y.Recv().Kind(); xk != yk {
+				return fmt.Errorf("receiver: unequal var kinds: %v vs %v", xk, yk)
+			}
+			// TODO(adonovan): enable this check. It fails for the methods of
+			// a defined type whose underlying type is another named
+			// interface, such as Error in "type E error": the receiver is
+			// the declaring interface (error) when type-checked from source,
+			// but the defined type (E) when decoded.
+			// if xr, yr := x.Recv().Type().String(), y.Recv().Type().String(); xr != yr {
+			// 	return fmt.Errorf("unequal receiver types: %s vs %s", xr, yr)
+			// }
+		}
+		if err := equalTypeParams(x.TypeParams(), y.TypeParams()); err != nil {
+			return fmt.Errorf("type params: %s", err)
+		}
+		if err := equalTypeParams(x.RecvTypeParams(), y.RecvTypeParams()); err != nil {
+			return fmt.Errorf("recv type params: %s", err)
+		}
+	case *types.Slice:
+		y := y.(*types.Slice)
+		if err := equalType(x.Elem(), y.Elem()); err != nil {
+			return fmt.Errorf("slice elements: %s", err)
+		}
+	case *types.Struct:
+		y := y.(*types.Struct)
+		if x.NumFields() != y.NumFields() {
+			return fmt.Errorf("unequal struct fields: %d vs %d",
+				x.NumFields(), y.NumFields())
+		}
+		for i := 0; i < x.NumFields(); i++ {
+			xf := x.Field(i)
+			yf := y.Field(i)
+			if xf.Name() != yf.Name() {
+				return fmt.Errorf("mismatched fields: %s vs %s", xf, yf)
+			}
+			if err := equalType(xf.Type(), yf.Type()); err != nil {
+				return fmt.Errorf("struct field %s: %s", xf.Name(), err)
+			}
+			if x.Tag(i) != y.Tag(i) {
+				return fmt.Errorf("struct field %s has unequal tags: %q vs %q",
+					xf.Name(), x.Tag(i), y.Tag(i))
+			}
+		}
+	case *types.Tuple:
+		y := y.(*types.Tuple)
+		if x.Len() != y.Len() {
+			return fmt.Errorf("unequal tuple lengths: %d vs %d", x.Len(), y.Len())
+		}
+		for i := 0; i < x.Len(); i++ {
+			if err := equalType(x.At(i).Type(), y.At(i).Type()); err != nil {
+				return fmt.Errorf("tuple element %d: %s", i, err)
+			}
+			if xk, yk := x.At(i).Kind(), y.At(i).Kind(); xk != yk {
+				return fmt.Errorf("tuple element %d: unequal var kinds: %v vs %v", i, xk, yk)
+			}
+		}
+	case *types.TypeParam:
+		y := y.(*types.TypeParam)
+		if x.String() != y.String() {
+			return fmt.Errorf("unequal named types: %s vs %s", x, y)
+		}
+		// For now, just compare constraints by type string to short-circuit
+		// cycles. We have to make interfaces explicit as export data currently
+		// doesn't support marking interfaces as implicit.
+		// TODO(rfindley): remove makeExplicit once export data contains an
+		// implicit bit.
+		xc := makeExplicit(x.Constraint()).String()
+		yc := makeExplicit(y.Constraint()).String()
+		if xc != yc {
+			return fmt.Errorf("unequal constraints: %s vs %s", xc, yc)
+		}
+
+	default:
+		panic(fmt.Sprintf("unexpected %T type", x))
+	}
+	return nil
+}
+
+// cmpNamed compares two named types x and y, returning an error for any
+// discrepancies. It does not compare their underlying types.
+func cmpNamed(x, y *types.Named) error {
+	xOrig := x.Origin()
+	yOrig := y.Origin()
+	if xOrig.String() != yOrig.String() {
+		return fmt.Errorf("unequal named types: %s vs %s", x, y)
+	}
+	if err := equalTypeParams(x.TypeParams(), y.TypeParams()); err != nil {
+		return fmt.Errorf("type parameters: %s", err)
+	}
+	if err := equalTypeArgs(x.TypeArgs(), y.TypeArgs()); err != nil {
+		return fmt.Errorf("type arguments: %s", err)
+	}
+	if x.NumMethods() != y.NumMethods() {
+		return fmt.Errorf("unequal methods: %d vs %d",
+			x.NumMethods(), y.NumMethods())
+	}
+	// Unfortunately method sorting is not canonical, so sort before comparing.
+	var xms, yms []*types.Func
+	for i := 0; i < x.NumMethods(); i++ {
+		xms = append(xms, x.Method(i))
+		yms = append(yms, y.Method(i))
+	}
+	for _, ms := range [][]*types.Func{xms, yms} {
+		sort.Slice(ms, func(i, j int) bool {
+			return ms[i].Name() < ms[j].Name()
+		})
+	}
+	for i, xm := range xms {
+		ym := yms[i]
+		if xm.Name() != ym.Name() {
+			return fmt.Errorf("mismatched %dth method: %s vs %s", i, xm, ym)
+		}
+		// Calling equalType here leads to infinite recursion, so just compare
+		// strings.
+		if xm.String() != ym.String() {
+			return fmt.Errorf("unequal methods: %s vs %s", xm, ym)
+		}
+	}
+	return nil
+}
+
+// makeExplicit returns an explicit version of typ, if typ is an implicit
+// interface. Otherwise it returns typ unmodified.
+func makeExplicit(typ types.Type) types.Type {
+	if iface, _ := typ.(*types.Interface); iface != nil && iface.IsImplicit() {
+		var methods []*types.Func
+		for i := 0; i < iface.NumExplicitMethods(); i++ {
+			methods = append(methods, iface.Method(i))
+		}
+		var embeddeds []types.Type
+		for etyp := range iface.EmbeddedTypes() {
+			embeddeds = append(embeddeds, etyp)
+		}
+		return types.NewInterfaceType(methods, embeddeds)
+	}
+	return typ
+}
+
+func equalTypeArgs(x, y *types.TypeList) error {
+	if x.Len() != y.Len() {
+		return fmt.Errorf("unequal lengths: %d vs %d", x.Len(), y.Len())
+	}
+	for i := 0; i < x.Len(); i++ {
+		if err := equalType(x.At(i), y.At(i)); err != nil {
+			return fmt.Errorf("type %d: %s", i, err)
+		}
+	}
+	return nil
+}
+
+func equalTypeParams(x, y *types.TypeParamList) error {
+	if x.Len() != y.Len() {
+		return fmt.Errorf("unequal lengths: %d vs %d", x.Len(), y.Len())
+	}
+	for i := 0; i < x.Len(); i++ {
+		if err := equalType(x.At(i), y.At(i)); err != nil {
+			return fmt.Errorf("type parameter %d: %s", i, err)
+		}
+	}
+	return nil
+}
+
+// testPkgData imports a package from export data and compares it with pkg.
+func testPkgData(t *testing.T, fset *token.FileSet, pkg *types.Package, data []byte) *types.Package {
+	imports := make(map[string]*types.Package)
+	fset2 := token.NewFileSet()
+	pkg2, err := exportdata.Decode(fset2, pkg.Path(), data, exportdata.PackagesFromMap(imports), exportdata.DecodeOptions{})
+	if err != nil {
+		t.Errorf("Decode(%s): %v", pkg.Path(), err)
+	}
+
+	testPkg(t, fset, pkg, fset2, pkg2, true)
+	return pkg2
+}
+
+// testPkg compares the decoded package pkg2 with pkg, type-checked
+// from source. If exact, positions must agree on the column too, as
+// they do for data written by the current encoder (but not, for
+// example, for data written by older versions of cmd/export).
+func testPkg(t *testing.T, fset *token.FileSet, pkg *types.Package, fset2 *token.FileSet, pkg2 *types.Package, exact bool) {
+	if _, err := exportdata.Encode(fset2, pkg2, exportdata.EncodeOptions{}); err != nil {
+		t.Errorf("reexport %q: %v", pkg.Path(), err)
+	}
+
+	// Compare the packages' corresponding members.
+	for _, name := range pkg.Scope().Names() {
+		if !token.IsExported(name) {
+			continue
+		}
+		obj1 := pkg.Scope().Lookup(name)
+		obj2 := pkg2.Scope().Lookup(name)
+		if obj2 == nil {
+			t.Errorf("%s.%s not found, want %s", pkg.Path(), name, obj1)
+			continue
+		}
+
+		fl1 := fileLine(fset, obj1, exact)
+		fl2 := fileLine(fset2, obj2, exact)
+		if fl1 != fl2 {
+			t.Errorf("%s.%s: got posn %s, want %s",
+				pkg.Path(), name, fl2, fl1)
+		}
+
+		if err := cmpObj(obj1, obj2); err != nil {
+			t.Errorf("%s.%s: %s\ngot:  %s\nwant: %s",
+				pkg.Path(), name, err, obj2, obj1)
+		}
+	}
+}
+
+// cmpObj reports how x and y differ. They are assumed to belong to different
+// universes so cannot be compared directly. It is an adapted version of
+// equalObj in bexport_test.go.
+func cmpObj(x, y types.Object) error {
+	if reflect.TypeOf(x) != reflect.TypeOf(y) {
+		return fmt.Errorf("%T vs %T", x, y)
+	}
+	xt := x.Type()
+	yt := y.Type()
+	switch x := x.(type) {
+	case *types.Var, *types.Func:
+		// ok
+	case *types.Const:
+		xval := x.Val()
+		yval := y.(*types.Const).Val()
+		equal := constant.Compare(xval, token.EQL, yval)
+		if !equal {
+			// try approx. comparison
+			xkind := xval.Kind()
+			ykind := yval.Kind()
+			if xkind == constant.Complex || ykind == constant.Complex {
+				equal = same(constant.Real(xval), constant.Real(yval)) &&
+					same(constant.Imag(xval), constant.Imag(yval))
+			} else if xkind == constant.Float || ykind == constant.Float {
+				equal = same(xval, yval)
+			} else if xkind == constant.Unknown && ykind == constant.Unknown {
+				equal = true
+			}
+		}
+		if !equal {
+			return fmt.Errorf("unequal constants %s vs %s", xval, yval)
+		}
+	case *types.TypeName:
+		if xalias, yalias := x.IsAlias(), y.(*types.TypeName).IsAlias(); xalias != yalias {
+			return fmt.Errorf("mismatching IsAlias(): %s vs %s", x, y)
+		}
+
+		// equalType does not recurse into the underlying types of named types, so
+		// we must pass the underlying type explicitly here. However, in doing this
+		// we may skip checking the features of the named types themselves, in
+		// situations where the type name is not referenced by the underlying or
+		// any other top-level declarations. Therefore, we must explicitly compare
+		// named types here, before passing their underlying types into equalType.
+		xn, _ := types.Unalias(xt).(*types.Named)
+		yn, _ := types.Unalias(yt).(*types.Named)
+		if (xn == nil) != (yn == nil) {
+			return fmt.Errorf("mismatching types: %T vs %T", xt, yt)
+		}
+		if xn != nil {
+			if err := cmpNamed(xn, yn); err != nil {
+				return err
+			}
+		}
+		xt = xt.Underlying()
+		yt = yt.Underlying()
+	default:
+		return fmt.Errorf("unexpected %T", x)
+	}
+	return equalType(xt, yt)
+}
+
+// Use the same floating-point precision (512) as cmd/compile
+// (see Mpprec in cmd/compile/internal/gc/mpfloat.go).
+const mpprec = 512
+
+// same compares non-complex numeric values and reports if they are approximately equal.
+func same(x, y constant.Value) bool {
+	xf := exportdata.ConstantToFloat(x)
+	yf := exportdata.ConstantToFloat(y)
+	d := new(big.Float).Sub(xf, yf)
+	d.Abs(d)
+	eps := big.NewFloat(1.0 / (1 << (mpprec - 1))) // allow for 1 bit of error
+	return d.Cmp(eps) < 0
+}
+
+type importerFunc func(path string) (*types.Package, error)
+
+func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) }
diff --git a/src/go/types/exportdata/compat_test.go b/src/go/types/exportdata/compat_test.go
new file mode 100644
index 0000000000..79f22b744e
--- /dev/null
+++ b/src/go/types/exportdata/compat_test.go
@@ -0,0 +1,305 @@
+// 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_test
+
+// This file defines TestCompatibility, which decodes data written by past encoders.
+
+import (
+	"encoding/binary"
+	"fmt"
+	"go/ast"
+	"go/parser"
+	"go/token"
+	"go/types"
+	"os"
+	"path/filepath"
+	"regexp"
+	"slices"
+	"sort"
+	"strconv"
+	"strings"
+	"testing"
+
+	"go/types/exportdata"
+)
+
+// producers records each supported producer of export data and the
+// version of the encoding it emits. Decode is obliged to read the
+// output of every producer that is no older than the two most recent
+// Go toolchain releases (see its doc comment).
+//
+// When the encoder starts to emit a new version, add an entry for it
+// and run main.go. When a producer falls outside the
+// window, delete its entry; TestCompatibility will then report any
+// golden files, and any support in the decoder, that are no longer
+// needed.
+var producers = []struct {
+	name    string
+	version int    // version of the encoding
+	shallow bool   // whether it emits shallow (as well as deep) data
+	date    string // release date (YYYY-MM-DD), if any
+}{
+	// gcexportdata.Write, at the most recent x/tools tag. Its
+	// shallow data (from internal/gcimporter.IExportShallow) was
+	// explicitly unstable and not self-describing, so it is not
+	// supported.
+	{"x/tools v0.53.0 gcexportdata.Write", 4, false, "2026-11-17"},
+
+	// Encode, as of this source tree. It is also the encoder that
+	// will be used by cmd/export (go list -export) in go1.28.
+	{"x/tools (development)", 6, true, ""},
+}
+
+// allowedVersions lists the versions accepted by the decoder although no
+// supported producer emits them.
+//
+// TODO(adonovan): remove support for these versions from the decoder.
+var allowedVersions = []int{0, 1, 2, 3, 5}
+
+// TestCompatibility checks that Decode can read the export data written
+// by each supported producer (see producers), which is recorded in
+// testdata/golden/vN.{deep,shallow}.i, where N is the version of the
+// encoding. Each file holds the export data for the reference package,
+// testdata/golden/src/ref, and is compared with that package
+// type-checked from source, to the fidelity of its version.
+//
+// A golden file is generated once, when its version is first emitted
+// by a producer, and is never regenerated. The files for the current
+// encoder are written by main.go. (The file for v4 was written using
+// gcexportdata.Write at x/tools v0.53.0, which predates Encode.)
+//
+// The test also checks that the decoder accepts exactly the versions
+// of the supported producers (plus allowedVersions).
+//
+// TODO(adonovan): now that this test exists, the encoder need no
+// longer support old versions.
+func TestCompatibility(t *testing.T) {
+	// The reference package uses generic methods.
+	needsGo1Point(t, 27)
+
+	fset, dep, ref := loadGoldenReference(t)
+
+	// Compute the expected set of golden files.
+	want := make(map[string]bool)   // golden file base names
+	supported := make(map[int]bool) // versions of supported producers
+	for _, p := range producers {
+		supported[p.version] = true
+		want[filepath.Base(goldenFilename(p.version, false))] = true
+		if p.shallow {
+			want[filepath.Base(goldenFilename(p.version, true))] = true
+		}
+	}
+
+	// Check that the golden files are exactly the expected ones.
+	files, err := filepath.Glob(filepath.Join("testdata", "golden", "*.i"))
+	if err != nil {
+		t.Fatal(err)
+	}
+	have := make(map[string]bool)
+	for _, file := range files {
+		have[filepath.Base(file)] = true
+	}
+	for name := range have {
+		if !want[name] {
+			t.Errorf("golden file %s is not needed by any supported producer; delete it", name)
+		}
+	}
+	for name := range want {
+		if !have[name] {
+			t.Errorf("golden file %s is missing (see main.go)", name)
+		}
+	}
+
+	// Check that the decoder accepts exactly the expected versions.
+	t.Run("versions", func(t *testing.T) {
+		var wantVersions []int
+		for v := range supported {
+			wantVersions = append(wantVersions, v)
+		}
+		wantVersions = append(wantVersions, allowedVersions...)
+		sort.Ints(wantVersions)
+		if got := decoderVersions(); !slices.Equal(got, wantVersions) {
+			t.Errorf("decoder accepts versions %v, want %v (supported producers %v, plus allowedVersions)",
+				got, wantVersions, slices.Sorted(func(yield func(int) bool) {
+					for v := range supported {
+						if !yield(v) {
+							return
+						}
+					}
+				}))
+		}
+	})
+
+	// Decode each golden file and compare it with the reference package.
+	goldenRx := regexp.MustCompile(`^v([0-9]+)\.(deep|shallow)\.i$`)
+	for _, file := range files {
+		name := filepath.Base(file)
+		t.Run(name, func(t *testing.T) {
+			m := goldenRx.FindStringSubmatch(name)
+			if m == nil {
+				t.Fatalf("invalid golden file name %s", name)
+			}
+			version, _ := strconv.Atoi(m[1])
+			shallow := m[2] == "shallow"
+
+			data, err := os.ReadFile(file)
+			if err != nil {
+				t.Fatal(err)
+			}
+			if v, _ := binary.Uvarint(data[1:]); int(v) != version {
+				t.Fatalf("%s contains version %d", name, v)
+			}
+
+			// In shallow mode, the decoder requires
+			// complete packages for all dependencies.
+			imports := make(map[string]*types.Package)
+			if shallow {
+				imports[dep.Path()] = dep
+			}
+			fset2 := token.NewFileSet()
+			ref2, err := exportdata.Decode(fset2, ref.Path(), data, exportdata.PackagesFromMap(imports), exportdata.DecodeOptions{})
+			if err != nil {
+				t.Fatalf("Decode: %v", err)
+			}
+			compareGolden(t, version, fset, ref, fset2, ref2)
+		})
+	}
+}
+
+// goldenFilename returns the name of the golden file for the
+// specified version and mode.
+func goldenFilename(version int, shallow bool) string {
+	mode := "deep"
+	if shallow {
+		mode = "shallow"
+	}
+	return filepath.Join("testdata", "golden", fmt.Sprintf("v%d.%s.i", version, mode))
+}
+
+// loadGoldenReference parses and type-checks the reference package
+// and its dependency.
+func loadGoldenReference(t *testing.T) (*token.FileSet, *types.Package, *types.Package) {
+	fset := token.NewFileSet()
+	check := func(path, dir string, imports map[string]*types.Package) *types.Package {
+		names, err := filepath.Glob(filepath.Join("testdata", "golden", "src", dir, "*.go"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		sort.Strings(names)
+		var files []*ast.File
+		for _, name := range names {
+			src, err := os.ReadFile(name)
+			if err != nil {
+				t.Fatal(err)
+			}
+			// Use a short, stable file name, as it is recorded in the export data.
+			f, err := parser.ParseFile(fset, dir+"/"+filepath.Base(name), src, parser.SkipObjectResolution)
+			if err != nil {
+				t.Fatal(err)
+			}
+			files = append(files, f)
+		}
+		conf := types.Config{
+			GoVersion: "go1.27",
+			Importer: importerFunc(func(path string) (*types.Package, error) {
+				if pkg, ok := imports[path]; ok {
+					return pkg, nil
+				}
+				return nil, fmt.Errorf("no package %q", path)
+			}),
+		}
+		pkg, err := conf.Check(path, fset, files, nil)
+		if err != nil {
+			t.Fatal(err)
+		}
+		return pkg
+	}
+	dep := check("example.com/dep", "dep", nil)
+	ref := check("example.com/ref", "ref", map[string]*types.Package{dep.Path(): dep})
+	return fset, dep, ref
+}
+
+// compareGolden compares the decoded package pkg2 with the reference
+// package pkg, to the fidelity of the specified version.
+func compareGolden(t *testing.T, version int, fset *token.FileSet, pkg *types.Package, fset2 *token.FileSet, pkg2 *types.Package) {
+	t.Helper()
+	// The positions of all names declared by pkg's package-level
+	// objects: objects, fields, methods, parameters, and results.
+	want := objectPositions(pkg)
+	got := objectPositions(pkg2)
+	if len(want) < 100 {
+		t.Fatalf("only %d objects; test is broken", len(want))
+	}
+
+	for _, name := range pkg.Scope().Names() {
+		obj1 := pkg.Scope().Lookup(name)
+		obj2 := pkg2.Scope().Lookup(name)
+		if !obj1.Exported() {
+			continue
+		}
+		if obj2 == nil {
+			t.Errorf("%s not found", name)
+			continue
+		}
+		if err := cmpObj(obj1, obj2); err != nil {
+			t.Errorf("%s: %s\ngot:  %s\nwant: %s", name, err, obj2, obj1)
+		}
+	}
+
+	for key, wspan := range want {
+		if wspan.pkg != pkg {
+			// e.g. a field of an alias for a type in another package.
+			// (In shallow mode, such objects are not decoded.)
+			continue
+		}
+		gspan, ok := got[key]
+		if !ok {
+			if token.IsExported(strings.Fields(key)[0]) {
+				t.Errorf("%s: missing", key)
+			}
+			continue
+		}
+		switch {
+		case version >= 6: // iexportVersionFullPos
+			// Positions are preserved exactly, both with and
+			// without //line adjustment.
+			for _, adjusted := range []bool{false, true} {
+				w := fset.PositionFor(wspan.pos, adjusted)
+				g := fset2.PositionFor(gspan.pos, adjusted)
+				// On Windows, go/scanner joins relative //line
+				// filenames using backslash, but the golden
+				// files record forward slashes.
+				w.Filename = filepath.ToSlash(w.Filename)
+				if g != w {
+					t.Errorf("%s (adjusted=%t): got %v (offset %d), want %v (offset %d)",
+						key, adjusted, g, g.Offset, w, w.Offset)
+				}
+			}
+		default:
+			// Deep export data records only the adjusted file and line.
+			w := fset.Position(wspan.pos)
+			g := fset2.Position(gspan.pos)
+			w.Filename = filepath.ToSlash(w.Filename) // see above
+			if g.Filename != w.Filename || g.Line != w.Line {
+				t.Errorf("%s: got %s:%d, want %s:%d", key, g.Filename, g.Line, w.Filename, w.Line)
+			}
+		}
+	}
+}
+
+// decoderVersions returns the versions of the encoding accepted by
+// Decode, by presenting it with headers of each version.
+func decoderVersions() []int {
+	var versions []int
+	for v := range 20 {
+		data := binary.AppendUvarint([]byte{'i'}, uint64(v))
+		data = append(data, make([]byte, 64)...) // garbage
+		_, err := exportdata.Decode(token.NewFileSet(), "p", data, exportdata.PackagesFromMap(make(map[string]*types.Package)), exportdata.DecodeOptions{})
+		if err == nil || !strings.Contains(err.Error(), "version") {
+			versions = append(versions, v)
+		}
+	}
+	return versions
+}
diff --git a/src/go/types/exportdata/corpus_test.go b/src/go/types/exportdata/corpus_test.go
new file mode 100644
index 0000000000..a3f73302fb
--- /dev/null
+++ b/src/go/types/exportdata/corpus_test.go
@@ -0,0 +1,386 @@
+// 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_test
+
+// This file defines TestCorpus, which checks export data for a corpus
+// of small test cases, testdata/corpus/*.txtar. Each archive is a
+// self-contained module (with its own go.mod file) whose packages are
+// checked in three ways:
+//
+//   - deep: each package is type-checked from source, using packages
+//     decoded from the export data of its dependencies, then encoded
+//     and decoded in deep mode by this package's codec.
+//   - shallow: likewise, but in shallow mode.
+//   - golist: the package's export data is obtained from "go list
+//     -export" and read by readExportFile. With go1.27 and
+//     earlier, this is the compiler's unified export data, read by
+//     the legacy reader; since go1.28, it is indexed export data
+//     produced by cmd/export, read by Decode.
+//
+// In each case, the decoded package is compared with the package
+// type-checked from source. Some cases make additional assertions;
+// see corpusChecks.
+//
+// The archives are extracted into a temporary directory, combined by a
+// go.work file, and loaded by a single "go list" command. The module
+// path of archive NAME.txtar must be example.com/NAME. An archive
+// whose go.mod requires a newer Go version than the go command is
+// skipped.
+//
+// Apart from readExportFile (see load_test.go), this file depends only
+// on the standard library and the public API of the codec, so that it
+// may be used by a future go/types/exportdata package.
+
+import (
+	"bytes"
+	"fmt"
+	"go/build"
+	"go/token"
+	"go/types"
+	"go/version"
+	"os"
+	"path/filepath"
+	"slices"
+	"sort"
+	"strings"
+	"testing"
+
+	"go/types/exportdata"
+)
+
+// corpusChecks holds additional assertions for some corpus cases,
+// keyed by archive name. Each is called (in deep and golist modes)
+// with a function that decodes the package of the specified path,
+// using (and updating) the specified map of imported packages.
+var corpusChecks = map[string]func(t *testing.T, decode func(path string, imports map[string]*types.Package) *types.Package){
+	"exports": func(t *testing.T, decode func(string, map[string]*types.Package) *types.Package) {
+		// The package's Imports list must include all packages
+		// explicitly imported by the package, plus all packages
+		// referenced indirectly via exported objects.
+		// For now, we just test the presence of a few packages
+		// that we know are there for sure. (CL 8924)
+		pkg := decode("example.com/exports", make(map[string]*types.Package))
+		got := fmt.Sprint(pkg.Imports())
+		for _, want := range []string{"go/ast", "go/token"} {
+			if !strings.Contains(got, want) {
+				t.Errorf(`Package("exports").Imports() = %s, does not contain %s`, got, want)
+			}
+		}
+	},
+
+	"issue13566": func(t *testing.T, decode func(string, map[string]*types.Package) *types.Package) {
+		// make sure all indirectly imported packages have names
+		pkg := decode("example.com/issue13566/b", make(map[string]*types.Package))
+		for _, imp := range pkg.Imports() {
+			if imp.Name() == "" {
+				t.Errorf("no name for %s package", imp.Path())
+			}
+		}
+	},
+
+	"issue58296": func(t *testing.T, decode func(string, map[string]*types.Package) *types.Package) {
+		// The export data reader for c cannot rely on Package.Imports
+		// being populated for a or b. (For the imports {a,b} it is unset.)
+		imports := map[string]*types.Package{
+			"example.com/issue58296/a": types.NewPackage("example.com/issue58296/a", "a"),
+			"example.com/issue58296/b": types.NewPackage("example.com/issue58296/b", "b"),
+		}
+
+		// make sure a and b are both imported by c.
+		pkg := decode("example.com/issue58296/c", imports)
+		var names []string
+		for _, imp := range pkg.Imports() {
+			names = append(names, imp.Name())
+		}
+		sort.Strings(names)
+		if got, want := strings.Join(names, ","), "a,b"; got != want {
+			t.Errorf("got imports %v for package c. wanted %v", names, want)
+		}
+	},
+
+	"genericaliases": func(t *testing.T, decode func(string, map[string]*types.Package) *types.Package) {
+		// Alias type parameters and alias chains must be preserved (go.dev/issue/68778).
+		pkg := decode("example.com/genericaliases", make(map[string]*types.Package))
+		for name, want := range map[string]string{
+			"A":       "type pkg.A[T any] = *T",
+			"B":       "type pkg.B[R any, S *R] = []S",
+			"C":       "type pkg.C[U any] = pkg.B[U, pkg.A[U]]",
+			"Named":   "type pkg.Named int",
+			"Chained": "type pkg.Chained = pkg.C[pkg.Named]",
+		} {
+			obj := pkg.Scope().Lookup(name)
+			if obj == nil {
+				t.Errorf("failed to find %q in package %s", name, pkg)
+				continue
+			}
+			got := strings.ReplaceAll(obj.String(), pkg.Path(), "pkg")
+			if got != want {
+				t.Errorf("(%q).String()=%q. wanted %q", name, got, want)
+			}
+		}
+	},
+
+	"aliases": func(t *testing.T, decode func(string, map[string]*types.Package) *types.Package) {
+		// Import c using stubs for a and b (go.dev/issue/68778).
+		pkg := decode("example.com/aliases/c", map[string]*types.Package{
+			"example.com/aliases/a": types.NewPackage("example.com/aliases/a", "a"),
+			"example.com/aliases/b": types.NewPackage("example.com/aliases/b", "b"),
+		})
+
+		// Check c's objects and types.
+		var objs []string
+		for _, name := range pkg.Scope().Names() {
+			obj := pkg.Scope().Lookup(name)
+			objs = append(objs, fmt.Sprintf("%s : %s", obj.Name(), obj.Type()))
+		}
+		sort.Strings(objs)
+		want := strings.Join([]string{
+			"S : struct{F int}",
+			"T : struct{F int}",
+			"U : example.com/aliases/a.A[string]",
+			"V : example.com/aliases/a.A[int]",
+			"W : example.com/aliases/b.B[string]",
+			"X : example.com/aliases/b.B[int]",
+			"Y : example.com/aliases/c.c[string]",
+			"Z : example.com/aliases/c.c[int]",
+			"c : example.com/aliases/c.c[V any]",
+		}, ",")
+		if got := strings.Join(objs, ","); got != want {
+			t.Errorf("got imports %v for package c. wanted %v", objs, want)
+		}
+	},
+}
+
+// corpusGoListFailures lists the cases whose packages "go list -export"
+// currently fails to build, with the reason. They are excluded from
+// "go list -export", and their golist mode is skipped.
+var corpusGoListFailures = map[string]string{
+	// TODO(adonovan): delete when cmd/export uses an encoder with the fix.
+	"issue82747": "cmd/export in go1.28 predates the fix for go.dev/issue/82747",
+}
+
+func TestCorpus(t *testing.T) {
+	needsGoBuild(t)
+
+	corpus := loadCorpus(t)
+
+	// Type-check every package (including std dependencies) from source.
+	fset := token.NewFileSet()
+	checked := make(map[string]*types.Package) // keyed by package path
+	for _, lp := range corpus.list {
+		checked[lp.ImportPath] = checkListPackage(t, fset, lp, checked)
+	}
+
+	// Check that every entry in corpusChecks has an archive.
+	for name := range corpusChecks {
+		if !slices.ContainsFunc(corpus.cases, func(c corpusCase) bool { return c.name == name }) {
+			t.Errorf("corpusChecks[%q] has no archive", name)
+		}
+	}
+
+	for _, c := range corpus.cases {
+		t.Run(c.name, func(t *testing.T) {
+			if c.skip != "" {
+				t.Skip(c.skip)
+			}
+
+			// The case's packages, in dependency order.
+			isCase := func(lp *listPackage) bool { return lp.Module != nil && lp.Module.Path == "example.com/"+c.name }
+			pkgs := slices.DeleteFunc(slices.Clone(corpus.list), func(lp *listPackage) bool { return !isCase(lp) })
+			if len(pkgs) == 0 {
+				t.Fatalf("no packages in module example.com/%s", c.name)
+			}
+			check := corpusChecks[c.name]
+
+			// deep and shallow round trips through the codec
+			caseList := dependencyClosure(corpus.list, isCase)
+			for _, shallow := range []bool{false, true} {
+				mode := "deep"
+				if shallow {
+					mode = "shallow"
+				}
+				t.Run(mode, func(t *testing.T) {
+					exports := roundTripPackages(t, fset, caseList, checked, shallow, isCase)
+					// The checks decode with empty or stub imports,
+					// which only self-contained (deep) data permits.
+					if check != nil && !shallow {
+						check(t, func(path string, imports map[string]*types.Package) *types.Package {
+							pkg, err := exportdata.Decode(token.NewFileSet(), path, exports[path], exportdata.PackagesFromMap(imports), exportdata.DecodeOptions{})
+							if err != nil {
+								t.Fatalf("Decode(%s): %v", path, err)
+							}
+							return pkg
+						})
+					}
+				})
+			}
+
+			// export data from "go list -export"
+			t.Run("golist", func(t *testing.T) {
+				if reason, ok := corpusGoListFailures[c.name]; ok {
+					t.Skip(reason)
+				}
+				exports := corpus.exports
+				for _, lp := range pkgs {
+					pkg := checked[lp.ImportPath]
+					fset2 := token.NewFileSet()
+					pkg2 := readExportFile(t, fset2, make(map[string]*types.Package), lp.ImportPath, exports[lp.ImportPath])
+					testPkg(t, fset, pkg, fset2, pkg2, false)
+				}
+				if check != nil {
+					check(t, func(path string, imports map[string]*types.Package) *types.Package {
+						return readExportFile(t, token.NewFileSet(), imports, path, exports[path])
+					})
+				}
+			})
+		})
+	}
+}
+
+// dependencyClosure returns the packages of list selected by keep,
+// and all their dependencies, preserving the order of list.
+func dependencyClosure(list []*listPackage, keep func(*listPackage) bool) []*listPackage {
+	byPath := make(map[string]*listPackage)
+	for _, lp := range list {
+		byPath[lp.ImportPath] = lp
+	}
+	needed := make(map[string]bool)
+	var visit func(*listPackage)
+	visit = func(lp *listPackage) {
+		if !needed[lp.ImportPath] {
+			needed[lp.ImportPath] = true
+			for _, imp := range lp.Imports {
+				visit(byPath[imp])
+			}
+		}
+	}
+	for _, lp := range list {
+		if keep(lp) {
+			visit(lp)
+		}
+	}
+	var result []*listPackage
+	for _, lp := range list {
+		if needed[lp.ImportPath] {
+			result = append(result, lp)
+		}
+	}
+	return result
+}
+
+// -- loading the corpus --
+
+// A corpusCase is a test case, a module extracted from a txtar archive.
+type corpusCase struct {
+	name string // archive name, without .txtar
+	skip string // reason to skip the case, if nonempty
+}
+
+type corpus struct {
+	dir     string            // temporary directory
+	env     []string          // environment for go commands
+	cases   []corpusCase      // all cases, sorted by name
+	list    []*listPackage    // all packages, in dependency order
+	exports map[string]string // export data file from "go list -export", keyed by package path
+}
+
+// loadCorpus extracts the archives in testdata/corpus into a
+// temporary directory, combines the modules whose Go version is
+// supported by the go command using a go.work file, and loads
+// their packages (and their dependencies) using "go list".
+func loadCorpus(t *testing.T) *corpus {
+	files, err := filepath.Glob(filepath.Join("testdata", "corpus", "*.txtar"))
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(files) == 0 {
+		t.Fatal("no corpus files")
+	}
+
+	c := &corpus{dir: t.TempDir(), exports: make(map[string]string)}
+	c.env = []string{
+		"GOWORK=" + filepath.Join(c.dir, "go.work"),
+		"GOTOOLCHAIN=local",
+		"GOPROXY=off",
+		"GOFLAGS=",
+		"CGO_ENABLED=0", // so that source type-checking needs no cgo processing
+	}
+
+	// The go command is that of the toolchain running the test,
+	// since "go test" puts its GOROOT/bin first in PATH.
+	tags := build.Default.ReleaseTags
+	goVersion := tags[len(tags)-1] // e.g. "go1.28"
+
+	var (
+		uses           []string
+		patterns       []string // all non-skipped cases
+		exportPatterns []string // ...except corpusGoListFailures
+	)
+	for _, file := range files {
+		ar, err := parseTxtarFile(file)
+		if err != nil {
+			t.Fatal(err)
+		}
+		cc := corpusCase{name: strings.TrimSuffix(filepath.Base(file), ".txtar")}
+		for _, f := range ar.Files {
+			filename := filepath.Join(c.dir, cc.name, filepath.FromSlash(f.Name))
+			if err := os.MkdirAll(filepath.Dir(filename), 0o777); err != nil {
+				t.Fatal(err)
+			}
+			if err := os.WriteFile(filename, f.Data, 0o666); err != nil {
+				t.Fatal(err)
+			}
+
+			// Skip the case if go.mod requires a newer Go version.
+			if f.Name == "go.mod" {
+				for line := range strings.Lines(string(f.Data)) {
+					if gover, ok := strings.CutPrefix(line, "go "); ok {
+						gover = "go" + strings.TrimSpace(gover)
+						if version.Compare(gover, goVersion) > 0 {
+							cc.skip = fmt.Sprintf("module requires %s; go command is %s", gover, goVersion)
+						}
+					}
+				}
+			}
+		}
+		if cc.skip == "" {
+			uses = append(uses, "./"+cc.name)
+			pattern := "example.com/" + cc.name + "/..."
+			patterns = append(patterns, pattern)
+			if _, ok := corpusGoListFailures[cc.name]; !ok {
+				exportPatterns = append(exportPatterns, pattern)
+			}
+		}
+		c.cases = append(c.cases, cc)
+	}
+
+	// Write the go.work file.
+	var work bytes.Buffer
+	fmt.Fprintf(&work, "go %s\n\nuse (\n", strings.TrimPrefix(goVersion, "go"))
+	for _, use := range uses {
+		fmt.Fprintf(&work, "\t%s\n", use)
+	}
+	fmt.Fprintf(&work, ")\n")
+	if err := os.WriteFile(filepath.Join(c.dir, "go.work"), work.Bytes(), 0o666); err != nil {
+		t.Fatal(err)
+	}
+
+	c.list = c.goList(t, patterns, "-deps")
+	for _, lp := range c.goList(t, exportPatterns, "-export") {
+		c.exports[lp.ImportPath] = lp.Export
+	}
+	return c
+}
+
+// goList runs "go list -json" with the specified flags on the
+// specified patterns, and returns the decoded packages.
+func (c *corpus) goList(t *testing.T, patterns []string, flags ...string) []*listPackage {
+	t.Helper()
+	pkgs, err := goList(c.dir, c.env, flags, patterns)
+	if err != nil {
+		t.Fatal(err)
+	}
+	return pkgs
+}
diff --git a/src/go/types/exportdata/env_test.go b/src/go/types/exportdata/env_test.go
new file mode 100644
index 0000000000..9bebdc2a98
--- /dev/null
+++ b/src/go/types/exportdata/env_test.go
@@ -0,0 +1,113 @@
+// 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_test
+
+// This file defines the parts of the tests that depend on their
+// environment, the standard library. The tests were copied from
+// golang.org/x/tools/internal/exportdata; all test files other than
+// this one are identical to the ones there, modulo the import path of
+// the package under test.
+//
+// Two files there have no counterpart here: compile_test.go, which
+// runs the go1.27 compiler directly, and main.go, which writes the
+// golden files for TestCompatibility (see compat_test.go). The
+// golden files are generated in x/tools and copied, along with the
+// rest of testdata, into this package.
+
+import (
+	"fmt"
+	"go/token"
+	"go/types"
+	"internal/testenv"
+	"internal/txtar"
+	"os"
+	"path/filepath"
+	"runtime"
+	"testing"
+	"unsafe"
+
+	"go/types/exportdata"
+)
+
+// TestMain skips all tests on small machines, approximated as those
+// with 32-bit pointers, as some of them (such as TestStd) load the
+// export data of the entire standard library.
+// (The x/tools counterpart uses testenv.ExitIfSmallMachine.)
+//
+// It also skips all tests on wasm, which has 64-bit pointers but
+// similarly limited resources.
+//
+// TODO(adonovan): refine the check if needed, for example by skipping
+// only the expensive tests (via a new seam), so that the cheap codec
+// tests still run on 32-bit platforms.
+func TestMain(m *testing.M) {
+	if unsafe.Sizeof(uintptr(0)) < 8 {
+		fmt.Fprintln(os.Stderr, "skipping test: 32-bit machines lack sufficient memory")
+		os.Exit(0)
+	}
+	if runtime.GOARCH == "wasm" {
+		fmt.Fprintln(os.Stderr, "skipping test: can't execve on wasm")
+		os.Exit(0)
+	}
+	os.Exit(m.Run())
+}
+
+// needsGoTool skips the test if the go command is not available.
+func needsGoTool(t testing.TB) {
+	testenv.MustHaveExec(t)
+	if _, err := testenv.GoTool(); err != nil {
+		t.Skipf("skipping test: %v", err)
+	}
+}
+
+// needsGoBuild skips the test if the go command cannot build packages.
+func needsGoBuild(t testing.TB) { testenv.MustHaveGoBuild(t) }
+
+// needsGo1Point skips the test if the Go version is older than 1.x.
+// In the standard library, the go command is always the current one.
+func needsGo1Point(t testing.TB, x int) {}
+
+// needsGOROOTDir skips the test if GOROOT/dir does not exist.
+func needsGOROOTDir(t *testing.T, dir string) {
+	t.Helper()
+	if _, err := os.Stat(filepath.Join(testenv.GOROOT(t), dir)); err != nil {
+		t.Skipf("skipping test: %v", err)
+	}
+}
+
+// goTool returns the name of the go command.
+func goTool() (string, error) { return testenv.GoTool() }
+
+// parseTxtarFile parses the specified txtar archive.
+func parseTxtarFile(filename string) (*txtar.Archive, error) { return txtar.ParseFile(filename) }
+
+// stdTestPatterns returns the go list patterns of packages checked by
+// TestStd, and the minimum expected number of packages.
+func stdTestPatterns() ([]string, int) {
+	// At the time of writing, 'GOOS=plan9 go list std | wc -l' reports 465;
+	// most other platforms have more.
+	return []string{"std"}, 400
+}
+
+// readExportFile reads the export data file produced by "go list
+// -export" for the package of the specified path.
+//
+// Since go1.28, go list -export produces indexed export data,
+// which is decoded by the package under test.
+func readExportFile(t *testing.T, fset *token.FileSet, imports map[string]*types.Package, path, filename string) *types.Package {
+	t.Helper()
+	if filename == "" {
+		t.Fatalf("no export data for %s", path)
+	}
+	data, err := os.ReadFile(filename)
+	if err != nil {
+		t.Fatal(err)
+	}
+	pkg, err := exportdata.Decode(fset, path, data, exportdata.PackagesFromMap(imports), exportdata.DecodeOptions{})
+	if err != nil {
+		t.Fatalf("reading export data for %s: %v", path, err)
+	}
+	return pkg
+}
diff --git a/src/go/types/exportdata/golistexport_test.go b/src/go/types/exportdata/golistexport_test.go
new file mode 100644
index 0000000000..d698652c9c
--- /dev/null
+++ b/src/go/types/exportdata/golistexport_test.go
@@ -0,0 +1,339 @@
+// 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.
+
+package exportdata_test
+
+// The tests in this file read export data for standard packages, as
+// reported by "go list -export". With go1.27 and earlier, this is the
+// compiler's unified export data, read by the legacy gcexportdata
+// reader; since go1.28, it is indexed export data produced by
+// cmd/export, read by Decode.
+//
+// Some of these tests originated in the standard library, in
+// $GOROOT/src/go/internal/gcimporter/gcimporter_test.go.
+
+import (
+	"go/constant"
+	"go/token"
+	"go/types"
+	"runtime"
+	"strings"
+	"sync"
+	"testing"
+)
+
+func needsCompiler(t *testing.T, compiler string) {
+	if runtime.Compiler == compiler {
+		return
+	}
+	switch compiler {
+	case "gc":
+		t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler)
+	}
+}
+
+// stdExports returns a mapping from package path to the name of the
+// export data file reported by "go list -export", for each package
+// in the standard library.
+var stdExports = sync.OnceValues(func() (map[string]string, error) {
+	pkgs, err := goList("", stdEnv, []string{"-export"}, []string{"std"})
+	if err != nil {
+		return nil, err
+	}
+	exports := make(map[string]string)
+	for _, lp := range pkgs {
+		exports[lp.ImportPath] = lp.Export
+	}
+	return exports, nil
+})
+
+// importStd reads the export data reported by "go list -export" for
+// the specified standard package, using the specified map of
+// imported packages, which may be nil.
+func importStd(t *testing.T, path string, imports map[string]*types.Package) *types.Package {
+	t.Helper()
+	exports, err := stdExports()
+	if err != nil {
+		t.Fatal(err)
+	}
+	if imports == nil {
+		imports = make(map[string]*types.Package)
+	}
+	return readExportFile(t, token.NewFileSet(), imports, path, exports[path])
+}
+
+// TestGoListExportStd reads the export data reported by "go list
+// -export" for each standard package, and compares it with the
+// package type-checked from source.
+func TestGoListExportStd(t *testing.T) {
+	if testing.Short() {
+		t.Skip("the imports can be expensive, and this test is especially slow when the build cache is empty")
+	}
+	// This package only handles gc export data.
+	needsCompiler(t, "gc")
+	needsGoBuild(t) // to find stdlib export data in the build cache
+
+	// Type-check every package from source, in dependency order.
+	fset, list, checked := loadPackages(t, "std")
+
+	const minPkgs = 225 // 'GOOS=plan9 go1.18 list std | wc -l' reports 228; most other platforms have more.
+	if len(list) < minPkgs {
+		t.Fatalf("too few packages (%d) were loaded", len(list))
+	}
+
+	exports, err := stdExports()
+	if err != nil {
+		t.Fatal(err)
+	}
+	for _, lp := range list {
+		if lp.ImportPath == "unsafe" {
+			continue // no export data
+		}
+		if len(lp.GoFiles) == 0 {
+			continue // test-only package
+		}
+		t.Run(lp.ImportPath, func(t *testing.T) {
+			fset2 := token.NewFileSet()
+			pkg2 := readExportFile(t, fset2, make(map[string]*types.Package), lp.ImportPath, exports[lp.ImportPath])
+			testPkg(t, fset, checked[lp.ImportPath], fset2, pkg2, false)
+		})
+	}
+}
+
+var importedObjectTests = []struct {
+	name string
+	want string
+}{
+	// non-interfaces
+	{"crypto.Hash", "type Hash uint"},
+	{"go/ast.ObjKind", "type ObjKind int"},
+	{"go/types.Qualifier", "type Qualifier func(*Package) string"},
+	{"go/types.Comparable", "func Comparable(T Type) bool"},
+	{"math.Pi", "const Pi untyped float"},
+	{"math.Sin", "func Sin(x float64) float64"},
+	{"go/ast.NotNilFilter", "func NotNilFilter(_ string, v reflect.Value) bool"},
+
+	// interfaces
+	{"context.Context", "type Context interface{Deadline() (deadline time.Time, ok bool); Done() <-chan struct{}; Err() error; Value(key any) any}"},
+	{"crypto.Decrypter", "type Decrypter interface{Decrypt(rand io.Reader, msg []byte, opts DecrypterOpts) (plaintext []byte, err error); Public() PublicKey}"},
+	{"encoding.BinaryMarshaler", "type BinaryMarshaler interface{MarshalBinary() (data []byte, err error)}"},
+	{"io.Reader", "type Reader interface{Read(p []byte) (n int, err error)}"},
+	{"io.ReadWriter", "type ReadWriter interface{Reader; Writer}"},
+	{"go/ast.Node", "type Node interface{End() go/token.Pos; Pos() go/token.Pos}"},
+	{"go/types.Type", "type Type interface{String() string; Underlying() Type}"},
+}
+
+func TestImportedTypes(t *testing.T) {
+	// This package only handles gc export data.
+	needsCompiler(t, "gc")
+	needsGoBuild(t) // to find stdlib export data in the build cache
+
+	for _, test := range importedObjectTests {
+		obj := importObject(t, test.name)
+		if obj == nil {
+			continue // error reported elsewhere
+		}
+		got := types.ObjectString(obj, types.RelativeTo(obj.Pkg()))
+
+		// TODO(rsc): Delete this block once go.dev/cl/368254 lands.
+		if got != test.want && test.want == strings.ReplaceAll(got, "interface{}", "any") {
+			got = test.want
+		}
+
+		if got != test.want {
+			t.Errorf("%s: got %q; want %q", test.name, got, test.want)
+		}
+
+		if named, _ := types.Unalias(obj.Type()).(*types.Named); named != nil {
+			verifyInterfaceMethodRecvs(t, named, 0)
+		}
+	}
+}
+
+func TestImportedConsts(t *testing.T) {
+	needsGoBuild(t) // to find stdlib export data in the build cache
+
+	tests := []struct {
+		name string
+		want constant.Kind
+	}{
+		{"math.Pi", constant.Float},
+		{"math.MaxFloat64", constant.Float},
+		{"math.MaxInt64", constant.Int},
+	}
+
+	for _, test := range tests {
+		obj := importObject(t, test.name)
+		if got := obj.(*types.Const).Val().Kind(); got != test.want {
+			t.Errorf("%s: imported as constant.Kind(%v), want constant.Kind(%v)", test.name, got, test.want)
+		}
+	}
+}
+
+func TestImportedVarKinds(t *testing.T) {
+	needsGoBuild(t) // to find stdlib export data in the build cache
+
+	check := func(name string, v *types.Var, want types.VarKind) {
+		if got := v.Kind(); got != want {
+			t.Errorf("%s: imported as %v, want %v", name, got, want)
+		}
+	}
+
+	sig := importObject(t, "bufio.NewReader").(*types.Func).Signature()
+	check("bufio.NewReader param", sig.Params().At(0), types.ParamVar)
+	check("bufio.NewReader result", sig.Results().At(0), types.ResultVar)
+
+	read, _, _ := types.LookupFieldOrMethod(importObject(t, "bufio.Reader").Type(), true, nil, "Read")
+	check("bufio.Reader.Read receiver", read.(*types.Func).Signature().Recv(), types.RecvVar)
+
+	iface := importObject(t, "io.Reader").Type().Underlying().(*types.Interface)
+	check("io.Reader.Read receiver", iface.ExplicitMethod(0).Signature().Recv(), types.RecvVar)
+}
+
+// importObject imports the object specified by a name of the form
+// <import path>.<object name>, e.g. go/types.Type.
+//
+// If any errors occur they are reported via t and the resulting object will
+// be nil.
+func importObject(t *testing.T, name string) types.Object {
+	s := strings.Split(name, ".")
+	if len(s) != 2 {
+		t.Fatal("inconsistent test data")
+	}
+	importPath := s[0]
+	objName := s[1]
+
+	pkg := importStd(t, importPath, nil)
+	obj := pkg.Scope().Lookup(objName)
+	if obj == nil {
+		t.Errorf("%s: object not found", name)
+		return nil
+	}
+	return obj
+}
+
+// verifyInterfaceMethodRecvs verifies that method receiver types
+// are named if the methods belong to a named interface type.
+func verifyInterfaceMethodRecvs(t *testing.T, named *types.Named, level int) {
+	// avoid endless recursion in case of an embedding bug that lead to a cycle
+	if level > 10 {
+		t.Errorf("%s: embeds itself", named)
+		return
+	}
+
+	iface, _ := named.Underlying().(*types.Interface)
+	if iface == nil {
+		return // not an interface
+	}
+
+	// check explicitly declared methods
+	for m := range iface.ExplicitMethods() {
+		recv := m.Type().(*types.Signature).Recv()
+		if recv == nil {
+			t.Errorf("%s: missing receiver type", m)
+			continue
+		}
+		if recv.Type() != named {
+			t.Errorf("%s: got recv type %s; want %s", m, recv.Type(), named)
+		}
+	}
+
+	// check embedded interfaces (if they are named, too)
+	for etyp := range iface.EmbeddedTypes() {
+		// embedding of interfaces cannot have cycles; recursion will terminate
+		if etype, _ := types.Unalias(etyp).(*types.Named); etype != nil {
+			verifyInterfaceMethodRecvs(t, etype, level+1)
+		}
+	}
+}
+
+func TestIssue5815(t *testing.T) {
+	// This package only handles gc export data.
+	needsCompiler(t, "gc")
+	needsGoBuild(t) // to find stdlib export data in the build cache
+
+	pkg := importStd(t, "strings", nil)
+
+	scope := pkg.Scope()
+	for _, name := range scope.Names() {
+		obj := scope.Lookup(name)
+		if obj.Pkg() == nil {
+			t.Errorf("no pkg for %s", obj)
+		}
+		if tname, _ := obj.(*types.TypeName); tname != nil {
+			named := types.Unalias(tname.Type()).(*types.Named)
+			for m := range named.Methods() {
+				if m.Pkg() == nil {
+					t.Errorf("no pkg for %s", m)
+				}
+			}
+		}
+	}
+}
+
+// Smoke test to ensure that imported methods get the correct package.
+func TestCorrectMethodPackage(t *testing.T) {
+	// This package only handles gc export data.
+	needsCompiler(t, "gc")
+	needsGoBuild(t) // to find stdlib export data in the build cache
+
+	imports := make(map[string]*types.Package)
+	importStd(t, "net/http", imports)
+
+	mutex := imports["sync"].Scope().Lookup("Mutex").(*types.TypeName).Type()
+	mset := types.NewMethodSet(types.NewPointer(mutex)) // methods of *sync.Mutex
+	sel := mset.Lookup(nil, "Lock")
+	lock := sel.Obj().(*types.Func)
+	if got, want := lock.Pkg().Path(), "sync"; got != want {
+		t.Errorf("got package path %q; want %q", got, want)
+	}
+}
+
+func TestIssue13898(t *testing.T) {
+	// This package only handles gc export data.
+	needsCompiler(t, "gc")
+	needsGoBuild(t) // to find stdlib export data in the build cache
+
+	// import go/internal/gcimporter which imports go/types partially
+	imports := make(map[string]*types.Package)
+	importStd(t, "go/internal/gcimporter", imports)
+
+	// look for go/types package
+	var goTypesPkg *types.Package
+	for path, pkg := range imports {
+		if path == "go/types" {
+			goTypesPkg = pkg
+			break
+		}
+	}
+	if goTypesPkg == nil {
+		t.Fatal("go/types not found")
+	}
+
+	// look for go/types.Object type
+	obj := lookupObj(t, goTypesPkg.Scope(), "Object")
+	typ, ok := types.Unalias(obj.Type()).(*types.Named)
+	if !ok {
+		t.Fatalf("go/types.Object type is %v; wanted named type", typ)
+	}
+
+	// lookup go/types.Object.Pkg method
+	m, index, indirect := types.LookupFieldOrMethod(typ, false, nil, "Pkg")
+	if m == nil {
+		t.Fatalf("go/types.Object.Pkg not found (index = %v, indirect = %v)", index, indirect)
+	}
+
+	// the method must belong to go/types
+	if m.Pkg().Path() != "go/types" {
+		t.Fatalf("found %v; want go/types", m.Pkg())
+	}
+}
+
+func lookupObj(t *testing.T, scope *types.Scope, name string) types.Object {
+	if obj := scope.Lookup(name); obj != nil {
+		return obj
+	}
+	t.Fatalf("%s not found", name)
+	return nil
+}
diff --git a/src/go/types/exportdata/iexport.go b/src/go/types/exportdata/iexport.go
new file mode 100644
index 0000000000..80cbc88d60
--- /dev/null
+++ b/src/go/types/exportdata/iexport.go
@@ -0,0 +1,1824 @@
+// 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"
+)
+
+// 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/go/types/exportdata/iexport_internal_test.go b/src/go/types/exportdata/iexport_internal_test.go
new file mode 100644
index 0000000000..0dfdce9f52
--- /dev/null
+++ b/src/go/types/exportdata/iexport_internal_test.go
@@ -0,0 +1,22 @@
+// 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 exportdata
+
+// This file defines white-box tests, and hooks for the external tests.
+
+import "testing"
+
+// ConstantToFloat exposes constantToFloat to the external tests.
+var ConstantToFloat = constantToFloat
+
+// TestFileInfosField checks that mayHaveLineInfos can find the
+// token.File.infos field. If this fails, the layout has changed, and
+// fileInfosField must be updated; until then the encoder conservatively
+// (and expensively) computes adjusted positions for every file.
+func TestFileInfosField(t *testing.T) {
+	if fileInfosField < 0 {
+		t.Fatal("unexpected layout of token.File; update fileInfosField")
+	}
+}
diff --git a/src/go/types/exportdata/iimport.go b/src/go/types/exportdata/iimport.go
new file mode 100644
index 0000000000..0dcfe97512
--- /dev/null
+++ b/src/go/types/exportdata/iimport.go
@@ -0,0 +1,1146 @@
+// 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"
+)
+
+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/go/types/exportdata/israce_test.go b/src/go/types/exportdata/israce_test.go
new file mode 100644
index 0000000000..a0473ed706
--- /dev/null
+++ b/src/go/types/exportdata/israce_test.go
@@ -0,0 +1,11 @@
+// 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.
+
+//go:build race
+
+package exportdata_test
+
+func init() {
+	isRace = true
+}
diff --git a/src/go/types/exportdata/load_test.go b/src/go/types/exportdata/load_test.go
new file mode 100644
index 0000000000..83567c63e8
--- /dev/null
+++ b/src/go/types/exportdata/load_test.go
@@ -0,0 +1,133 @@
+// 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_test
+
+// This file defines helpers for loading packages using "go list".
+
+import (
+	"bytes"
+	"encoding/json"
+	"fmt"
+	"go/ast"
+	"go/parser"
+	"go/token"
+	"go/types"
+	"io"
+	"os/exec"
+	"path/filepath"
+	"strings"
+	"testing"
+)
+
+// A listPackage holds the subset of "go list -json" output that we need.
+type listPackage struct {
+	ImportPath string
+	Name       string
+	Dir        string
+	GoFiles    []string
+	Imports    []string
+	ImportMap  map[string]string
+	Export     string
+	Module     *struct {
+		Path      string
+		GoVersion string
+	}
+	Error *struct{ Err string }
+}
+
+// stdEnv is the environment for go list commands on the standard library.
+// Cgo is disabled so that source type-checking needs no cgo processing.
+var stdEnv = []string{"GOWORK=off", "GOTOOLCHAIN=local", "GOFLAGS=", "CGO_ENABLED=0"}
+
+// goList runs "go list -json" with the specified flags and patterns
+// in the specified directory, with the specified additions to the
+// environment, and returns the decoded packages.
+func goList(dir string, env, flags, patterns []string) ([]*listPackage, error) {
+	args := append([]string{"list", "-json"}, flags...)
+	args = append(args, "--")
+	args = append(args, patterns...)
+	gocmd, err := goTool()
+	if err != nil {
+		return nil, err
+	}
+	cmd := exec.Command(gocmd, args...)
+	cmd.Dir = dir
+	cmd.Env = append(cmd.Environ(), env...)
+	cmd.Stderr = new(strings.Builder)
+	out, err := cmd.Output()
+	if err != nil {
+		return nil, fmt.Errorf("go %s failed: %v\n%s", strings.Join(args, " "), err, cmd.Stderr)
+	}
+	var pkgs []*listPackage
+	dec := json.NewDecoder(bytes.NewReader(out))
+	for {
+		lp := new(listPackage)
+		if err := dec.Decode(lp); err != nil {
+			if err == io.EOF {
+				break
+			}
+			return nil, fmt.Errorf("decoding go list output: %v", err)
+		}
+		if lp.Error != nil {
+			return nil, fmt.Errorf("go list: %s: %s", lp.ImportPath, lp.Error.Err)
+		}
+		pkgs = append(pkgs, lp)
+	}
+	return pkgs, nil
+}
+
+// checkListPackage parses and type-checks the specified package, whose
+// dependencies (keyed by package path) have already been checked.
+func checkListPackage(t testing.TB, fset *token.FileSet, lp *listPackage, checked map[string]*types.Package) *types.Package {
+	t.Helper()
+	if lp.ImportPath == "unsafe" {
+		return types.Unsafe
+	}
+	var files []*ast.File
+	for _, name := range lp.GoFiles {
+		f, err := parser.ParseFile(fset, filepath.Join(lp.Dir, name), nil, parser.SkipObjectResolution)
+		if err != nil {
+			t.Fatal(err)
+		}
+		files = append(files, f)
+	}
+	conf := types.Config{
+		Importer: importerFunc(func(path string) (*types.Package, error) {
+			if mapped, ok := lp.ImportMap[path]; ok {
+				path = mapped // e.g. vendoring
+			}
+			if pkg, ok := checked[path]; ok {
+				return pkg, nil
+			}
+			return nil, fmt.Errorf("%s: missing dependency %q", lp.ImportPath, path)
+		}),
+	}
+	if lp.Module != nil && lp.Module.GoVersion != "" {
+		conf.GoVersion = "go" + lp.Module.GoVersion
+	}
+	pkg := types.NewPackage(lp.ImportPath, lp.Name)
+	if err := types.NewChecker(&conf, fset, pkg, nil).Files(files); err != nil {
+		t.Fatalf("type-checking %s: %v", lp.ImportPath, err)
+	}
+	return pkg
+}
+
+// loadPackages type-checks the packages denoted by the patterns, and
+// their dependencies, from source. It returns the packages in
+// dependency order, as reported by "go list", and a mapping from
+// package path to the type-checked package.
+func loadPackages(t testing.TB, patterns ...string) (*token.FileSet, []*listPackage, map[string]*types.Package) {
+	t.Helper()
+	list, err := goList("", stdEnv, []string{"-deps"}, patterns)
+	if err != nil {
+		t.Fatal(err)
+	}
+	fset := token.NewFileSet()
+	checked := make(map[string]*types.Package) // keyed by package path
+	for _, lp := range list {
+		checked[lp.ImportPath] = checkListPackage(t, fset, lp, checked)
+	}
+	return fset, list, checked
+}
diff --git a/src/go/types/exportdata/position_test.go b/src/go/types/exportdata/position_test.go
new file mode 100644
index 0000000000..1b513f4cce
--- /dev/null
+++ b/src/go/types/exportdata/position_test.go
@@ -0,0 +1,194 @@
+// 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_test
+
+// This file tests the encoding of positions.
+
+import (
+	"go/ast"
+	"go/parser"
+	"go/token"
+	"go/types"
+	"testing"
+
+	"go/types/exportdata"
+)
+
+// TestPositions checks that Encode/Decode faithfully preserve both
+// the adjusted (//line) and unadjusted start and end positions of all
+// objects, including columns and offsets, across files, NoPos entries,
+// and a variety of //line directive scenarios. It exercises the
+// synthesis of line infos by the encoder (see writeLineInfos), which
+// must agree with go/token's own logic.
+func TestPositions(t *testing.T) {
+	// a.go has many kinds of //line directive.
+	const srcA = `package p
+
+var Alpha int
+
+//line foo.go:10
+var Bravo, Charlie int
+
+//line bar.go:20:5
+type T struct {
+	Xray   int
+	Yankee string
+}
+
+func (T) MethodA(x int) (y int) { return }
+func (T2) MethodFromA(x int) {}
+
+type Constraint interface {
+	~int
+	InterfaceMethod(arg int)
+}
+
+/*line baz.go:30:1*/ var Delta int; var Echo int
+
+//line :40
+var Foxtrot int
+
+//line :45:3
+var Golf int
+
+//line qux.go:50
+var Hotel = 1; /*line qux.go:60:7*/ var India int
+
+//line nocol.go:70
+var (
+	Juliet int; Kilo int
+)
+
+//line withcol.go:80:3
+var Lima,
+	Mike int
+
+//line same.go:100
+var November int
+//line other.go:102
+var Oscar int // only the filename differs from the prediction
+/*line other.go:103:1*/ var Papa int // only the column differs
+//line other.go:200:1
+var Quebec int // only the line differs
+`
+	// b.go has no //line directives, and declares methods on a.go's T
+	// (and vice versa) to exercise cross-file position transitions.
+	const srcB = `package p
+
+type T2 struct{}
+
+func (T) MethodB(c int) {}
+
+var Zulu struct{ Quux int }
+
+func Fb(a, b int) {}
+`
+	fset := token.NewFileSet()
+	var files []*ast.File
+	for _, f := range []struct{ name, src string }{{"a.go", srcA}, {"b.go", srcB}} {
+		file, err := parser.ParseFile(fset, f.name, f.src, 0)
+		if err != nil {
+			t.Fatal(err)
+		}
+		files = append(files, file)
+	}
+	pkg, err := new(types.Config).Check("p", fset, files, nil)
+	if err != nil {
+		t.Fatal(err)
+	}
+	want := objectPositions(pkg)
+	if len(want) < 25 {
+		t.Fatalf("only %d objects; test is broken", len(want))
+	}
+
+	for _, shallow := range []bool{false, true} {
+		data, err := exportdata.Encode(fset, pkg, exportdata.EncodeOptions{Shallow: shallow})
+		if err != nil {
+			t.Fatal(err)
+		}
+		fset2 := token.NewFileSet()
+		pkg2, err := exportdata.Decode(fset2, "p", data, exportdata.PackagesFromMap(map[string]*types.Package{}), exportdata.DecodeOptions{})
+		if err != nil {
+			t.Fatal(err)
+		}
+		got := objectPositions(pkg2)
+		for key, wspan := range want {
+			gspan, ok := got[key]
+			if !ok {
+				t.Errorf("shallow=%t: %s: missing", shallow, key)
+				continue
+			}
+			for _, end := range []bool{false, true} {
+				wpos, gpos := wspan.pos, gspan.pos
+				if end {
+					wpos += token.Pos(wspan.len)
+					gpos += token.Pos(gspan.len)
+				}
+				for _, adjusted := range []bool{false, true} {
+					w := fset.PositionFor(wpos, adjusted)
+					g := fset2.PositionFor(gpos, adjusted)
+					if g != w {
+						t.Errorf("shallow=%t: %s (end=%t, adjusted=%t): got %v (offset %d), want %v (offset %d)",
+							shallow, key, end, adjusted, g, g.Offset, w, w.Offset)
+					}
+				}
+			}
+		}
+	}
+}
+
+type objSpan struct {
+	pos token.Pos
+	len int
+	pkg *types.Package // package of the object
+}
+
+// objectPositions returns the positions and identifier lengths of the
+// package-level objects of pkg, and of their fields, methods,
+// parameters, and results.
+func objectPositions(pkg *types.Package) map[string]objSpan {
+	posns := make(map[string]objSpan)
+	add := func(key string, obj types.Object) {
+		posns[key] = objSpan{obj.Pos(), len(obj.Name()), obj.Pkg()}
+	}
+	var addTuple func(prefix string, tuple *types.Tuple)
+	addSig := func(prefix string, sig *types.Signature) {
+		addTuple(prefix+".param", sig.Params())
+		addTuple(prefix+".result", sig.Results())
+	}
+	addTuple = func(prefix string, tuple *types.Tuple) {
+		for i := range tuple.Len() {
+			v := tuple.At(i)
+			add(prefix+"."+v.Name(), v)
+		}
+	}
+	for _, name := range pkg.Scope().Names() {
+		obj := pkg.Scope().Lookup(name)
+		add(name, obj)
+		switch obj := obj.(type) {
+		case *types.Func:
+			addSig(name, obj.Signature())
+		case *types.TypeName:
+			if named, ok := obj.Type().(*types.Named); ok { // not an alias
+				for m := range named.Methods() {
+					add(name+"."+m.Name(), m)
+					addSig(name+"."+m.Name(), m.Signature())
+				}
+			}
+		}
+		switch u := obj.Type().Underlying().(type) {
+		case *types.Struct:
+			for f := range u.Fields() {
+				add(name+"."+f.Name(), f)
+			}
+		case *types.Interface:
+			for m := range u.ExplicitMethods() {
+				add(name+"."+m.Name(), m)
+				addSig(name+"."+m.Name(), m.Signature())
+			}
+		}
+	}
+	return posns
+}
diff --git a/src/go/types/exportdata/predeclared.go b/src/go/types/exportdata/predeclared.go
new file mode 100644
index 0000000000..4d7d392d39
--- /dev/null
+++ b/src/go/types/exportdata/predeclared.go
@@ -0,0 +1,91 @@
+// 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"
+)
+
+// 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/go/types/exportdata/std_test.go b/src/go/types/exportdata/std_test.go
new file mode 100644
index 0000000000..7789fec45d
--- /dev/null
+++ b/src/go/types/exportdata/std_test.go
@@ -0,0 +1,278 @@
+// 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_test
+
+// This file defines TestStd, which checks the codec on the standard library.
+
+import (
+	"fmt"
+	"go/ast"
+	"go/parser"
+	"go/token"
+	"go/types"
+	"os"
+	"path/filepath"
+	"strings"
+	"sync"
+	"testing"
+	"unsafe"
+
+	"go/types/exportdata"
+)
+
+// TestStd checks the codec on every package of the standard library
+// (and others; see stdTestPatterns), in deep and shallow modes.
+//
+// Each package is type-checked from source, using packages decoded
+// from the export data of its dependencies (as produced by this
+// test), and then encoded. The result is decoded and compared with
+// the package type-checked from source in the conventional way.
+func TestStd(t *testing.T) {
+	if testing.Short() {
+		t.Skip("skipping RAM hungry test in -short mode")
+	}
+	if isRace {
+		t.Skipf("stdlib tests take too long in race mode and flake on builders")
+	}
+	needsGoTool(t)
+
+	// Decoding rapidly consumes FileSet address space,
+	// so disable the test on 32-bit machines.
+	if unsafe.Sizeof(token.NoPos) < 8 {
+		t.Skip("skipping test on 32-bit machine")
+	}
+
+	patterns, minPkgs := stdTestPatterns()
+	fset, list, checked := loadPackages(t, patterns...)
+	if len(list) < minPkgs {
+		t.Errorf("too few packages (%d) were loaded", len(list))
+	}
+
+	for _, shallow := range []bool{false, true} {
+		mode := "deep"
+		if shallow {
+			mode = "shallow"
+		}
+		t.Run(mode, func(t *testing.T) {
+			roundTripPackages(t, fset, list, checked, shallow, func(*listPackage) bool { return true })
+		})
+	}
+}
+
+// roundTripPackages type-checks each package in list (which must be
+// closed under dependencies, in dependency order) from source, using
+// packages decoded from the export data of its dependencies, and then
+// encodes it in the specified mode. For each package selected by
+// compare, it decodes the result and compares it with the package
+// type-checked from source (checked). It returns the export data,
+// keyed by package path.
+func roundTripPackages(t *testing.T, fset *token.FileSet, list []*listPackage, checked map[string]*types.Package, shallow bool, compare func(*listPackage) bool) map[string][]byte {
+	var (
+		mu      sync.Mutex
+		exports = make(map[string][]byte) // keyed by package path
+	)
+	getExport := func(path string) ([]byte, error) {
+		mu.Lock()
+		defer mu.Unlock()
+		data, ok := exports[path]
+		if !ok {
+			return nil, fmt.Errorf("missing export data for %s", path)
+		}
+		return data, nil
+	}
+
+	// decode decodes the export data of the package of the
+	// specified path, using and updating the specified map of
+	// packages. In shallow mode, the decoder requires complete
+	// packages for all dependencies, so decode loads them too.
+	var decode func(fset *token.FileSet, path string, packages map[string]*types.Package) (*types.Package, error)
+	decode = func(fset *token.FileSet, path string, packages map[string]*types.Package) (*types.Package, error) {
+		data, err := getExport(path)
+		if err != nil {
+			return nil, err
+		}
+		getPackages := exportdata.PackagesFromMap(packages)
+		if shallow {
+			getPackages = func(refs []exportdata.PackageRef) ([]*types.Package, error) {
+				pkgs := make([]*types.Package, len(refs))
+				for i, ref := range refs {
+					pkg, ok := packages[ref.Path]
+					if !ok {
+						pkg = types.NewPackage(ref.Path, ref.Name)
+						packages[ref.Path] = pkg
+						if ref.Path != path {
+							// side effect: populate package scope
+							if _, err := decode(fset, ref.Path, packages); err != nil {
+								return nil, err
+							}
+						}
+					}
+					pkgs[i] = pkg
+				}
+				return pkgs, nil
+			}
+		}
+		return exportdata.Decode(fset, path, data, getPackages, exportdata.DecodeOptions{})
+	}
+
+	// Process the packages in parallel, in dependency order.
+	done := make(map[string]chan struct{})
+	for _, lp := range list {
+		done[lp.ImportPath] = make(chan struct{})
+	}
+	var wg sync.WaitGroup
+	for _, lp := range list {
+		wg.Go(func() {
+			defer close(done[lp.ImportPath])
+			for _, imp := range lp.Imports {
+				<-done[imp]
+			}
+			if lp.ImportPath == "unsafe" || len(lp.GoFiles) == 0 {
+				return // no export data
+			}
+
+			// Parse the files.
+			var files []*ast.File
+			for _, name := range lp.GoFiles {
+				f, err := parser.ParseFile(fset, filepath.Join(lp.Dir, name), nil, parser.SkipObjectResolution)
+				if err != nil {
+					t.Error(err)
+					return
+				}
+				files = append(files, f)
+			}
+
+			// Type-check them using packages decoded from export data.
+			packages := make(map[string]*types.Package) // keyed by package path
+			conf := &types.Config{
+				Error: func(e error) {
+					t.Errorf("type error: %v", e)
+				},
+				Importer: importerFunc(func(importPath string) (*types.Package, error) {
+					path := importPath
+					if mapped, ok := lp.ImportMap[path]; ok {
+						path = mapped // e.g. vendoring
+					}
+					if path == "unsafe" {
+						return types.Unsafe, nil // unsafe has no export data
+					}
+					return decode(fset, path, packages)
+				}),
+			}
+			if lp.Module != nil && lp.Module.GoVersion != "" {
+				conf.GoVersion = "go" + lp.Module.GoVersion
+			}
+			// (Use NewChecker+Files to ensure Package.Name is set explicitly.)
+			pkg := types.NewPackage(lp.ImportPath, lp.Name)
+			_ = types.NewChecker(conf, fset, pkg, nil).Files(files) // errors reported above
+
+			// Encode it.
+			data, err := exportdata.Encode(fset, pkg, exportdata.EncodeOptions{Shallow: shallow})
+			if err != nil {
+				t.Errorf("Encode(%s): %v", lp.ImportPath, err)
+				return
+			}
+			mu.Lock()
+			exports[lp.ImportPath] = data
+			mu.Unlock()
+
+			// Decode it and compare with the package type-checked from source.
+			if !compare(lp) {
+				return
+			}
+			fset2 := token.NewFileSet()
+			pkg2, err := decode(fset2, lp.ImportPath, make(map[string]*types.Package))
+			if err != nil {
+				t.Errorf("Decode(%s): %v", lp.ImportPath, err)
+				return
+			}
+			testPkg(t, fset, checked[lp.ImportPath], fset2, pkg2, true)
+			checkPositionFidelity(t, fset2, pkg2)
+		})
+	}
+	wg.Wait()
+	return exports
+}
+
+// checkPositionFidelity asserts that the apparent location of a few
+// objects decoded from export data, such as fmt.Println, corresponds
+// to its source location: in other words, export+import preserves
+// high-fidelity positions.
+func checkPositionFidelity(t *testing.T, fset *token.FileSet, pkg *types.Package) {
+	// We hard-code a few interesting test-case objects.
+	var obj types.Object
+	switch pkg.Path() {
+	case "fmt":
+		// func fmt.Println
+		obj = pkg.Scope().Lookup("Println")
+	case "net/http":
+		// method (*http.Request).ParseForm
+		req := pkg.Scope().Lookup("Request")
+		obj, _, _ = types.LookupFieldOrMethod(req.Type(), true, pkg, "ParseForm")
+	default:
+		return
+	}
+	if obj == nil {
+		t.Errorf("object not found in package %s", pkg.Path())
+		return
+	}
+
+	// Now check the source fidelity of the object's position.
+	posn := fset.Position(obj.Pos())
+	data, err := os.ReadFile(posn.Filename)
+	if err != nil {
+		t.Errorf("can't read source file declaring %v: %v", obj, err)
+		return
+	}
+
+	// Check line and column denote a source interval containing the object's identifier.
+	line := strings.Split(string(data), "\n")[posn.Line-1]
+
+	if id := line[posn.Column-1 : posn.Column-1+len(obj.Name())]; id != obj.Name() {
+		t.Errorf("%+v: expected declaration of %v at this line, column; got %q", posn, obj, line)
+	}
+
+	// Check offset.
+	if id := string(data[posn.Offset : posn.Offset+len(obj.Name())]); id != obj.Name() {
+		t.Errorf("%+v: expected declaration of %v at this offset; got %q", posn, obj, id)
+	}
+
+	// Check commutativity of Position() and start+len(name) operations:
+	// Position(startPos+len(name)) == Position(startPos) + len(name).
+	// This important property is a consequence of the way in which the
+	// decoder fills the gaps in the sparse line-start offset table.
+	endPosn := fset.Position(obj.Pos() + token.Pos(len(obj.Name())))
+	wantEndPosn := token.Position{
+		Filename: posn.Filename,
+		Offset:   posn.Offset + len(obj.Name()),
+		Line:     posn.Line,
+		Column:   posn.Column + len(obj.Name()),
+	}
+	if endPosn != wantEndPosn {
+		t.Errorf("%+v: expected end Position of %v here; was at %+v", wantEndPosn, obj, endPosn)
+	}
+}
+
+// BenchmarkEncodeShallow measures writing shallow export data for
+// each package of the standard library, as gopls does after
+// type-checking a package.
+func BenchmarkEncodeShallow(b *testing.B) {
+	needsGoTool(b)
+
+	fset, list, checked := loadPackages(b, "std")
+
+	for b.Loop() {
+		for _, lp := range list {
+			if lp.ImportPath == "unsafe" {
+				continue
+			}
+			if _, err := exportdata.Encode(fset, checked[lp.ImportPath], exportdata.EncodeOptions{Shallow: true}); err != nil {
+				b.Fatal(err)
+			}
+		}
+	}
+}
+
+var isRace = false
diff --git a/src/go/types/exportdata/sync.sh b/src/go/types/exportdata/sync.sh
new file mode 100755
index 0000000000..d47ff982de
--- /dev/null
+++ b/src/go/types/exportdata/sync.sh
@@ -0,0 +1,59 @@
+#!/bin/bash
+#
+# sync.sh: copy x/tools/internal/exportdata into GOROOT's go/types/exportdata.
+#
+# Delete after go1.29 when x/tools always delegates to the std codec.
+
+set -euo pipefail
+
+# We assume both packages are in the workspace (go.work).
+src=$(go list -f {{.Dir}} golang.org/x/tools/internal/exportdata)
+dst=$(go list -f {{.Dir}} go/types/exportdata)
+
+# Positive list of common files.
+# (anything new must be classified as shared or x/tools-only (delegate*.go, compile_test.go,
+# main.go) or forked (env_test.go).
+files=(
+	bimport.go
+	codec.go
+	codec_test.go
+	compare_test.go
+	compat_test.go
+	corpus_test.go
+	golistexport_test.go
+	iexport.go
+	iexport_internal_test.go
+	iimport.go
+	israce_test.go
+	load_test.go
+	position_test.go
+	predeclared.go
+	std_test.go
+	typeparam_test.go
+	typepath.go
+	typepath_test.go
+)
+
+for f in "${files[@]}"; do
+	# - Drop the "//go:build !go1.28" line and the blank line after it.
+	# - Drop x/tools-only comments marking the dependency restriction.
+	# - Rewrite the import path of the package under test.
+	sed -e '/^\/\/go:build !go1\.28$/{N;d;}' \
+		-e '/This package is dependency-restricted; see x\/tools/d' \
+		-e 's|"golang.org/x/tools/internal/exportdata"|"go/types/exportdata"|' \
+		"$src/$f" >"$dst/$f"
+done
+
+# Copy testdata golden files verbatim.
+rsync -a --delete "$src/testdata/" "$dst/testdata/"
+
+# Reformat.
+gofmt -l "$dst" ||
+  { echo "gofmt failed"; exit 1; } >&2
+
+# Check for leftover x/tools imports.
+grep -ln '"golang.org/x/tools/' $(ls "$dst/"*.go | grep -v env_test.go) &&
+  { echo "unrenamed x/tools imports"; exit 1; } >&2
+
+# List edited files.
+git diff --name-only "$dst"
diff --git a/src/go/types/exportdata/testdata/corpus/aliases.txtar b/src/go/types/exportdata/testdata/corpus/aliases.txtar
new file mode 100644
index 0000000000..a1ad24b395
--- /dev/null
+++ b/src/go/types/exportdata/testdata/corpus/aliases.txtar
@@ -0,0 +1,51 @@
+Generic type aliases across packages (go.dev/issue/68778).
+
+-- go.mod --
+module example.com/aliases
+
+go 1.26
+
+-- a/a.go --
+package a
+
+type A[T any] = *T
+
+type B = struct{ F int }
+
+func F() B {
+	type a[T any] = struct{ F T }
+	return a[int]{}
+}
+
+-- b/b.go --
+package b
+
+import "example.com/aliases/a"
+
+type B[S any] = struct {
+	F a.A[[]S]
+}
+
+-- c/c.go --
+package c
+
+import (
+	"example.com/aliases/a"
+	"example.com/aliases/b"
+)
+
+type c[V any] = struct {
+	G b.B[[3]V]
+}
+
+var S struct{ F int } = a.B{}
+var T struct{ F int } = a.F()
+
+var U a.A[string] = (*string)(nil)
+var V a.A[int] = (*int)(nil)
+
+var W b.B[string] = struct{ F *[]string }{}
+var X b.B[int] = struct{ F *[]int }{}
+
+var Y c[string] = struct{ G struct{ F *[][3]string } }{}
+var Z c[int] = struct{ G struct{ F *[][3]int } }{}
diff --git a/src/go/types/exportdata/testdata/corpus/exports.txtar b/src/go/types/exportdata/testdata/corpus/exports.txtar
new file mode 100644
index 0000000000..434d2d12ca
--- /dev/null
+++ b/src/go/types/exportdata/testdata/corpus/exports.txtar
@@ -0,0 +1,95 @@
+A variety of declarations, formerly TestImportTestdata, which dates
+from the original go/types gcimporter. The constant init1 is for
+go.dev/issue/3682 (dotted identifiers in export data).
+The empty .s file permits bodyless function declarations.
+
+-- go.mod --
+module example.com/exports
+
+go 1.26
+
+-- exports.go --
+package exports
+
+import (
+	"go/ast"
+)
+
+// Issue 3682: Correctly read dotted identifiers from export data.
+const init1 = 0
+
+func init() {}
+
+const (
+	C0 int = 0
+	C1     = 3.14159265
+	C2     = 2.718281828i
+	C3     = -123.456e-789
+	C4     = +123.456E+789
+	C5     = 1234i
+	C6     = "foo\n"
+	C7     = `bar\n`
+)
+
+type (
+	T1  int
+	T2  [10]int
+	T3  []int
+	T4  *int
+	T5  chan int
+	T6a chan<- int
+	T6b chan (<-chan int)
+	T6c chan<- (chan int)
+	T7  <-chan *ast.File
+	T8  struct{}
+	T9  struct {
+		a    int
+		b, c float32
+		d    []string `go:"tag"`
+	}
+	T10 struct {
+		T8
+		T9
+		_ *T10
+	}
+	T11 map[int]string
+	T12 interface{}
+	T13 interface {
+		m1()
+		m2(int) float32
+	}
+	T14 interface {
+		T12
+		T13
+		m3(x ...struct{}) []T9
+	}
+	T15 func()
+	T16 func(int)
+	T17 func(x int)
+	T18 func() float32
+	T19 func() (x float32)
+	T20 func(...interface{})
+	T21 struct{ next *T21 }
+	T22 struct{ link *T23 }
+	T23 struct{ link *T22 }
+	T24 *T24
+	T25 *T26
+	T26 *T27
+	T27 *T25
+	T28 func(T28) T28
+)
+
+var (
+	V0 int
+	V1 = -991.0
+)
+
+func F1()         {}
+func F2(x int)    {}
+func F3() int     { return 0 }
+func F4() float32 { return 0 }
+func F5(a, b, c int, u, v, w struct{ x, y T1 }, more ...interface{}) (p, q, r chan<- T10)
+
+func (p *T1) M1()
+
+-- empty.s --
diff --git a/src/go/types/exportdata/testdata/corpus/genericaliases.txtar b/src/go/types/exportdata/testdata/corpus/genericaliases.txtar
new file mode 100644
index 0000000000..3bfc88f7da
--- /dev/null
+++ b/src/go/types/exportdata/testdata/corpus/genericaliases.txtar
@@ -0,0 +1,17 @@
+Declarations and uses of generic type aliases (go.dev/issue/68778).
+Formerly TestIExportDataTypeParameterizedAliases.
+
+-- go.mod --
+module example.com/genericaliases
+
+go 1.26
+
+-- pkg.go --
+package pkg
+
+type A[T any] = *T
+type B[R any, S *R] = []S
+type C[U any] = B[U, A[U]]
+
+type Named int
+type Chained = C[Named] // B[Named, A[Named]] = B[Named, *Named] = []*Named
diff --git a/src/go/types/exportdata/testdata/corpus/generics.txtar b/src/go/types/exportdata/testdata/corpus/generics.txtar
new file mode 100644
index 0000000000..1d8f9172cd
--- /dev/null
+++ b/src/go/types/exportdata/testdata/corpus/generics.txtar
@@ -0,0 +1,44 @@
+A variety of generic declarations, formerly TestGenericExport
+(go.dev/issue/48392).
+
+-- go.mod --
+module example.com/generics
+
+go 1.26
+
+-- generic.go --
+package generic
+
+type Any any
+
+type T[A, B any] struct { Left A; Right B }
+
+func (T[P, Q]) m() {}
+
+var X T[int, string] = T[int, string]{1, "hi"}
+
+func ToInt[P interface{ ~int }](p P) int { return int(p) }
+
+var IntID = ToInt[int]
+
+type G[C comparable] int
+
+func ImplicitFunc[T ~int]() {}
+
+type ImplicitType[T ~int] int
+
+// Exercise constant import/export
+const C1 = 42
+const C2 int = 42
+const C3 float64 = 42
+
+type Constraint[T any] interface {
+       m(T)
+}
+
+// TODO(rfindley): revert to multiple blanks once the restriction on multiple
+// blanks is removed from the type checker.
+// type Blanks[_ any, _ Constraint[int]] int
+// func (Blanks[_, _]) m() {}
+type Blanks[_ any] int
+func (Blanks[_]) m() {}
diff --git a/src/go/types/exportdata/testdata/corpus/genmeth.txtar b/src/go/types/exportdata/testdata/corpus/genmeth.txtar
new file mode 100644
index 0000000000..087e50e8df
--- /dev/null
+++ b/src/go/types/exportdata/testdata/corpus/genmeth.txtar
@@ -0,0 +1,78 @@
+Generic methods (go.dev/issue/77273; CL 766661). Requires go1.27.
+
+-- go.mod --
+module example.com/genmeth
+
+go 1.27
+
+-- a/a.go --
+// Function bodies are never read, so panics are used
+// for brevity. Struct contents are also never filled
+// in.
+
+package a
+
+// monads
+type Either[A, B any] struct {}
+
+func (Either[A, B]) A() A { panic(42) }
+func (Either[A, B]) B() B { panic(42) }
+
+type Option[T any] struct {}
+
+func (Option[T]) Get() T { panic(42) }
+func (Option[T]) GetOrDefault[U any](u U) Either[T, U] { panic(42) }
+func (Option[T]) MapIfPresent[U any](f func(T) U) Option[U] { panic(42) }
+
+// pointer receiver
+type Box[P any] struct {}
+
+func (*Box[P]) Get() P { panic(42) }
+func (*Box[P]) Set(p P) { panic(42) }
+
+// streaming
+type List[E any] []E
+func (List[E]) Map[R any](f func(E) R) List[R] { panic(42) }
+func (List[E]) FlatMap[R any](f func(E) List[R]) List[R] { panic(42) }
+func (List[E1]) Zip[E2, R any](l List[E2], f func(E1, E2) R) List[R] { panic(42) }
+
+type Pair[A, B any] struct {}
+type BiList[A, B any] List[Pair[A, B]]
+
+func (BiList[A, B]) Flip() BiList[B, A] { panic(42) }
+func (BiList[A, B]) MapKeys[R any](f func(A) R) BiList[R, B] { panic(42) }
+func (BiList[A, B]) MapValues[R any](f func(B) R) BiList[A, R] { panic(42) }
+func (BiList[A, B]) FlatMapValues[R any](f func(B) List[R]) BiList[A, R] { panic(42) }
+func (BiList[A, B]) MapEntries[K, V any](f func(Pair[A, B]) Pair[K, V]) BiList[K, V] { panic(42) }
+
+type OrderedList[E comparable] []E
+func (OrderedList[E]) Min() Option[E] { panic(42) }
+func (OrderedList[E]) Max() Option[E] { panic(42) }
+
+-- b/b.go --
+package b
+
+import "example.com/genmeth/a"
+
+func _() {
+	var ex func(int) a.List[int]
+	var fl func(a.List[int]) a.List[int]
+
+	var l a.List[int]
+	l = l.Map(ex).FlatMap(fl)
+
+	var bl a.BiList[int, any]
+	bl = bl.MapKeys(ex).Flip().FlatMapValues(fl).Flip()
+
+	var id func(int) int
+
+	var op a.Option[int]
+	var _ int = op.MapIfPresent(id).Get()
+
+	var ol a.OrderedList[int]
+	var _ int = ol.Min().Get()
+
+	var b a.Box[int]
+	b.Set(42)
+	var _ int = b.Get()
+}
diff --git a/src/go/types/exportdata/testdata/corpus/issue13566.txtar b/src/go/types/exportdata/testdata/corpus/issue13566.txtar
new file mode 100644
index 0000000000..69d729764a
--- /dev/null
+++ b/src/go/types/exportdata/testdata/corpus/issue13566.txtar
@@ -0,0 +1,27 @@
+All indirectly imported packages must have names (go.dev/issue/13566).
+
+-- go.mod --
+module example.com/issue13566
+
+go 1.26
+
+-- a/a.go --
+// Input for TestIssue13566
+
+package a
+
+import "encoding/json"
+
+type A struct {
+	a    *A
+	json json.RawMessage
+}
+
+-- b/b.go --
+// Input for TestIssue13566
+
+package b
+
+import "example.com/issue13566/a"
+
+type A a.A
diff --git a/src/go/types/exportdata/testdata/corpus/issue15920.txtar b/src/go/types/exportdata/testdata/corpus/issue15920.txtar
new file mode 100644
index 0000000000..41b663e7b9
--- /dev/null
+++ b/src/go/types/exportdata/testdata/corpus/issue15920.txtar
@@ -0,0 +1,15 @@
+A defined type whose underlying type is error (go.dev/issue/15920).
+
+-- go.mod --
+module example.com/issue15920
+
+go 1.26
+
+-- p.go --
+package p
+
+// The underlying type of Error is the underlying type of error.
+// Make sure we can import this again without problems.
+type Error error
+
+func F() Error { return nil }
diff --git a/src/go/types/exportdata/testdata/corpus/issue20046.txtar b/src/go/types/exportdata/testdata/corpus/issue20046.txtar
new file mode 100644
index 0000000000..83fedd2ccd
--- /dev/null
+++ b/src/go/types/exportdata/testdata/corpus/issue20046.txtar
@@ -0,0 +1,13 @@
+The method of an interface-typed variable must be imported (go.dev/issue/20046).
+
+-- go.mod --
+module example.com/issue20046
+
+go 1.26
+
+-- p.go --
+package p
+
+var V interface {
+	M()
+}
diff --git a/src/go/types/exportdata/testdata/corpus/issue25301.txtar b/src/go/types/exportdata/testdata/corpus/issue25301.txtar
new file mode 100644
index 0000000000..b600a68116
--- /dev/null
+++ b/src/go/types/exportdata/testdata/corpus/issue25301.txtar
@@ -0,0 +1,21 @@
+An interface embedding an alias of an interface (go.dev/issue/25301).
+
+-- go.mod --
+module example.com/issue25301
+
+go 1.26
+
+-- issue25301.go --
+package issue25301
+
+type (
+	A = interface {
+		M()
+	}
+	T interface {
+		A
+	}
+	S struct{}
+)
+
+func (S) M() { println("m") }
diff --git a/src/go/types/exportdata/testdata/corpus/issue51219.txtar b/src/go/types/exportdata/testdata/corpus/issue51219.txtar
new file mode 100644
index 0000000000..2eb8a0a643
--- /dev/null
+++ b/src/go/types/exportdata/testdata/corpus/issue51219.txtar
@@ -0,0 +1,66 @@
+Recursive type parameter constraints across packages, formerly
+TestRecursiveExport_Issue51219 (go.dev/issue/51219).
+
+-- go.mod --
+module example.com/issue51219
+
+go 1.26
+
+-- a/a.go --
+package a
+
+type Interaction[DataT InteractionDataConstraint] struct {
+}
+
+type InteractionDataConstraint interface {
+	[]byte |
+		UserCommandInteractionData
+}
+
+type UserCommandInteractionData struct {
+	resolvedInteractionWithOptions
+}
+
+type resolvedInteractionWithOptions struct {
+	Resolved Resolved
+}
+
+type Resolved struct {
+	Users ResolvedData[User]
+}
+
+type ResolvedData[T ResolvedDataConstraint] map[uint64]T
+
+type ResolvedDataConstraint interface {
+	User | Message
+}
+
+type User struct{}
+
+type Message struct {
+	Interaction *Interaction[[]byte]
+}
+
+-- b/b.go --
+package b
+
+import (
+	"example.com/issue51219/a"
+)
+
+// InteractionRequest is an incoming request Interaction
+type InteractionRequest[T a.InteractionDataConstraint] struct {
+	a.Interaction[T]
+}
+
+-- p/p.go --
+package p
+
+import (
+	"example.com/issue51219/b"
+)
+
+// ResponseWriterMock mocks corde's ResponseWriter interface
+type ResponseWriterMock struct {
+	x b.InteractionRequest[[]byte]
+}
diff --git a/src/go/types/exportdata/testdata/corpus/issue51836.txtar b/src/go/types/exportdata/testdata/corpus/issue51836.txtar
new file mode 100644
index 0000000000..53f4bcdda9
--- /dev/null
+++ b/src/go/types/exportdata/testdata/corpus/issue51836.txtar
@@ -0,0 +1,23 @@
+Generic types in two packages of the same name (go.dev/issue/51836).
+
+-- go.mod --
+module example.com/issue51836
+
+go 1.26
+
+-- aa.go --
+package a
+
+import (
+	"example.com/issue51836/a"
+)
+
+type T[K any] struct {
+	t a.T[K]
+}
+
+-- a/a.go --
+package a
+
+type T[K any] struct {
+}
diff --git a/src/go/types/exportdata/testdata/corpus/issue57015.txtar b/src/go/types/exportdata/testdata/corpus/issue57015.txtar
new file mode 100644
index 0000000000..dfeb7ae3d7
--- /dev/null
+++ b/src/go/types/exportdata/testdata/corpus/issue57015.txtar
@@ -0,0 +1,20 @@
+Instantiation with an interface embedding an error type (go.dev/issue/57015).
+
+-- go.mod --
+module example.com/issue57015
+
+go 1.26
+
+-- issue57015.go --
+package issue57015
+
+type E error
+
+type X[T any] struct {}
+
+func F() X[interface {
+	E
+}] {
+	panic(0)
+}
+
diff --git a/src/go/types/exportdata/testdata/corpus/issue58296.txtar b/src/go/types/exportdata/testdata/corpus/issue58296.txtar
new file mode 100644
index 0000000000..bd0d3666c6
--- /dev/null
+++ b/src/go/types/exportdata/testdata/corpus/issue58296.txtar
@@ -0,0 +1,32 @@
+c imports b imports a; c must be importable with stub packages
+for a and b, as when go/packages is used without NeedDeps (go.dev/issue/58296).
+
+-- go.mod --
+module example.com/issue58296
+
+go 1.26
+
+-- a/a.go --
+package a
+
+type A int
+
+func (A) f() {}
+
+-- b/b.go --
+package b
+
+import "example.com/issue58296/a"
+
+type B struct {
+	a a.A
+}
+
+-- c/c.go --
+package c
+
+import "example.com/issue58296/b"
+
+type C struct {
+	b b.B
+}
diff --git a/src/go/types/exportdata/testdata/corpus/issue73854.txtar b/src/go/types/exportdata/testdata/corpus/issue73854.txtar
new file mode 100644
index 0000000000..e8488d4c18
--- /dev/null
+++ b/src/go/types/exportdata/testdata/corpus/issue73854.txtar
@@ -0,0 +1,16 @@
+Encoding a constant whose type is an instantiated generic type, such
+as Generic[interface{}], must not panic (go.dev/issue/73854).
+
+-- go.mod --
+module example.com/issue73854
+
+go 1.26
+
+-- pkg.go --
+package pkg
+
+type Generic[T any] int
+
+const C1 Generic[interface{}] = 1
+const C2 Generic[func()] = 2
+const C3 Generic[struct{}] = 3
diff --git a/src/go/types/exportdata/testdata/corpus/issue82747.txtar b/src/go/types/exportdata/testdata/corpus/issue82747.txtar
new file mode 100644
index 0000000000..1813ca89cb
--- /dev/null
+++ b/src/go/types/exportdata/testdata/corpus/issue82747.txtar
@@ -0,0 +1,51 @@
+Interface methods declared in another package must be qualified by
+their declaring package, so that c type-checks against the decoded
+a and b (go.dev/issue/82747). Formerly
+TestCrossPackageDefinedInterfaceMethods.
+
+-- go.mod --
+module example.com/issue82747
+
+go 1.26
+
+-- a/a.go --
+package a
+
+type AI interface {
+	m()
+}
+
+type GI[T any] interface {
+	gm(T)
+}
+
+type Impl struct{}
+
+func (Impl) m()     {}
+func (Impl) gm(int) {}
+
+-- b/b.go --
+package b
+
+import "example.com/issue82747/a"
+
+type BI a.AI
+type BGI[T any] a.GI[T]
+type Err error
+
+func Accept(BI)             {}
+func AcceptG[T any](BGI[T]) {}
+
+-- c/c.go --
+package c
+
+import (
+	"example.com/issue82747/a"
+	"example.com/issue82747/b"
+)
+
+func F(err b.Err) string {
+	b.Accept(a.Impl{})
+	b.AcceptG[int](a.Impl{})
+	return err.Error()
+}
diff --git a/src/go/types/exportdata/testdata/corpus/unexportedfields.txtar b/src/go/types/exportdata/testdata/corpus/unexportedfields.txtar
new file mode 100644
index 0000000000..5af89ea369
--- /dev/null
+++ b/src/go/types/exportdata/testdata/corpus/unexportedfields.txtar
@@ -0,0 +1,34 @@
+Unexported struct fields must retain their implicit package qualifier.
+Historically this led to a spurious error in b: "cannot convert a.M
+(variable of type a.MyTime) to type time.Time", because the private
+fields of Time and MyTime were not identical (CL 445097). Formerly
+TestUnexportedStructFields.
+
+-- go.mod --
+module example.com/unexportedfields
+
+go 1.26
+
+-- time/time.go --
+package time
+
+type Time struct{ x, y int }
+
+-- a/a.go --
+package a
+
+import "example.com/unexportedfields/time"
+
+type MyTime time.Time
+
+var M MyTime
+
+-- b/b.go --
+package b
+
+import (
+	"example.com/unexportedfields/a"
+	"example.com/unexportedfields/time"
+)
+
+var _ = time.Time(a.M)
diff --git a/src/go/types/exportdata/testdata/golden/src/dep/dep.go b/src/go/types/exportdata/testdata/golden/src/dep/dep.go
new file mode 100644
index 0000000000..2fe3a79fda
--- /dev/null
+++ b/src/go/types/exportdata/testdata/golden/src/dep/dep.go
@@ -0,0 +1,29 @@
+// 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 dep is a dependency of the reference package for TestCompatibility.
+package dep
+
+type T struct {
+	X int
+	y string
+}
+
+func (T) M() int               { return 0 }
+func (*T) PM(x int) (y int)    { return }
+func (t T) unexported() string { return t.y }
+
+type I interface{ M() int }
+
+type G[P any] struct{ F P }
+
+func (g G[P]) Get() P { return g.F }
+
+type A = G[int]
+
+type GA[P any] = []P
+
+const C = 1.0 / 3
+
+var V T
diff --git a/src/go/types/exportdata/testdata/golden/src/go.mod b/src/go/types/exportdata/testdata/golden/src/go.mod
new file mode 100644
index 0000000000..e4ca11ba03
--- /dev/null
+++ b/src/go/types/exportdata/testdata/golden/src/go.mod
@@ -0,0 +1,3 @@
+module example.com
+
+go 1.27
diff --git a/src/go/types/exportdata/testdata/golden/src/ref/line.go b/src/go/types/exportdata/testdata/golden/src/ref/line.go
new file mode 100644
index 0000000000..d8559651a5
--- /dev/null
+++ b/src/go/types/exportdata/testdata/golden/src/ref/line.go
@@ -0,0 +1,19 @@
+// 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 ref
+
+// Declarations affected by //line directives.
+
+//line foo.go:10
+var LineA int
+
+//line bar.go:20:5
+type LineT struct{ F int }
+
+/*line baz.go:30:1*/
+var LineB int
+
+//line :40
+var LineC int
diff --git a/src/go/types/exportdata/testdata/golden/src/ref/ref.go b/src/go/types/exportdata/testdata/golden/src/ref/ref.go
new file mode 100644
index 0000000000..30d053fcba
--- /dev/null
+++ b/src/go/types/exportdata/testdata/golden/src/ref/ref.go
@@ -0,0 +1,143 @@
+// 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 ref is the reference package for TestCompatibility.
+// Its export data, as written by each supported encoder, is
+// recorded in the golden files of the parent directory.
+//
+// Once a golden file has been written, this package must not be
+// changed in any way that affects its exported API or the
+// positions of its declarations. To extend it, add new files.
+package ref
+
+import "example.com/dep"
+
+// Constants of various kinds (cf. go.dev/issue/82186).
+const (
+	C0  int = 0
+	C1      = 3.14159265
+	C2      = 2.718281828i
+	C3      = -123.456e-789
+	C4      = +123.456e+789
+	C5      = 1234i
+	C6      = "foo\n"
+	C7      = `bar\n`
+	C8      = 1.0 / 3
+	C9      = -1.0 / 7
+	C10     = 1e10000 / 3
+	C11     = 1.0/3 + (2.0/7)*1i
+	C12     = 0x1p512
+	C13     = 'x'
+	C14     = true
+
+	F32 float32    = 1.0 / 3
+	F64 float64    = 1e20
+	C64 complex128 = 1.0/3 + 1i
+)
+
+// Types of various kinds.
+type (
+	T1  int
+	T2  [10]int
+	T3  []int
+	T4  *int
+	T5  chan int
+	T6a chan<- int
+	T6b chan (<-chan int)
+	T6c chan<- (chan int)
+	T8  struct{}
+	T9  struct {
+		a    int
+		b, c float32
+		d    []string `go:"tag"`
+	}
+	T10 struct {
+		T8
+		T9
+		_ *T10
+	}
+	T11 map[int]string
+	T12 interface{}
+	T13 interface {
+		m1()
+		m2(int) float32
+	}
+	T14 interface {
+		T12
+		T13
+		m3(x ...struct{}) []T9
+	}
+	T15 func()
+	T17 func(x int)
+	T19 func() (x float32)
+	T20 func(...any)
+	T21 struct{ next *T21 }
+	T22 struct{ link *T23 }
+	T23 struct{ link *T22 }
+	T24 *T24
+	T28 func(T28) T28
+)
+
+var (
+	V0 int
+	V1 = -991.0
+	V2 struct{ X, y int }
+)
+
+func F1()                                                          {}
+func F2(x int)                                                     {}
+func F3() int                                                      { return 0 }
+func F5(a, b int, u struct{ x T1 }, more ...any) (p, q chan<- T10) { return }
+
+func (p *T1) M1()          {}
+func (T1) M2(x int) string { return "" }
+
+// References to another package.
+type (
+	Embed struct {
+		dep.T
+		*dep.G[string]
+	}
+	Iface interface {
+		dep.I
+		N()
+	}
+	DepAlias    = dep.A
+	DepGenAlias = dep.GA[string]
+	DepNamed    dep.T
+)
+
+var DV dep.T
+
+func UseDep(x dep.I) dep.G[int] { return dep.G[int]{} }
+
+// Generic declarations.
+type List[E any] []E
+
+func (l List[E]) Map(f func(E) E) List[E] { return nil }
+
+func Map[E, R any](l []E, f func(E) R) []R { return nil }
+
+type Number interface{ ~int | ~float64 }
+
+func Sum[N Number](xs ...N) N {
+	var s N
+	return s
+}
+
+type Pair[K comparable, V any] struct {
+	Key K
+	Val V
+}
+
+type PairAlias[T any] = Pair[string, T]
+
+type Rec[T Rec[T]] interface{ Self() T }
+
+var Inst = Pair[int, List[string]]{}
+
+// A generic method (go1.27).
+type Box[T any] struct{ v T }
+
+func (b Box[T]) Convert[U any](f func(T) U) Box[U] { return Box[U]{f(b.v)} }
diff --git a/src/go/types/exportdata/testdata/golden/v4.deep.i b/src/go/types/exportdata/testdata/golden/v4.deep.i
new file mode 100644
index 0000000000..64a8b24179
Binary files /dev/null and b/src/go/types/exportdata/testdata/golden/v4.deep.i differ
diff --git a/src/go/types/exportdata/testdata/golden/v6.deep.i b/src/go/types/exportdata/testdata/golden/v6.deep.i
new file mode 100644
index 0000000000..8460b36b69
Binary files /dev/null and b/src/go/types/exportdata/testdata/golden/v6.deep.i differ
diff --git a/src/go/types/exportdata/testdata/golden/v6.shallow.i b/src/go/types/exportdata/testdata/golden/v6.shallow.i
new file mode 100644
index 0000000000..0f0f7bf7df
Binary files /dev/null and b/src/go/types/exportdata/testdata/golden/v6.shallow.i differ
diff --git a/src/go/types/exportdata/typeparam_test.go b/src/go/types/exportdata/typeparam_test.go
new file mode 100644
index 0000000000..8ab0d0ea5b
--- /dev/null
+++ b/src/go/types/exportdata/typeparam_test.go
@@ -0,0 +1,122 @@
+// 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 exportdata_test
+
+// This file round-trips the files of $GOROOT/test/typeparam through the codec.
+
+import (
+	"bytes"
+	"fmt"
+	"go/ast"
+	"go/parser"
+	"go/token"
+	"go/types"
+	"maps"
+	"os"
+	"path/filepath"
+	"runtime"
+	"slices"
+	"strconv"
+	"strings"
+	"testing"
+
+	"go/types/exportdata"
+)
+
+// TestRoundTripTypeparamTests round-trips each file of
+// $GOROOT/test/typeparam through Encode and Decode, and compares the
+// result with the package type-checked from source.
+func TestRoundTripTypeparamTests(t *testing.T) {
+	needsGOROOTDir(t, "test")
+
+	// Check go files in test/typeparam.
+	rootDir := filepath.Join(runtime.GOROOT(), "test", "typeparam")
+	list, err := os.ReadDir(rootDir)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	// Imported std packages are type-checked from source, so that
+	// this test of the codec does not depend on the export data
+	// produced by the toolchain. A single "go list" command
+	// enumerates the packages imported by all the files, and
+	// their dependencies.
+	fset := token.NewFileSet()
+	imports := make(map[string]bool)
+	for _, entry := range list {
+		if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".go") {
+			continue
+		}
+		f, err := parser.ParseFile(fset, filepath.Join(rootDir, entry.Name()), nil, parser.ImportsOnly)
+		if err != nil {
+			continue // reported later
+		}
+		for _, spec := range f.Imports {
+			path, _ := strconv.Unquote(spec.Path.Value)
+			imports[path] = true
+		}
+	}
+	deps, err := goList("", stdEnv, []string{"-deps"}, slices.Sorted(maps.Keys(imports)))
+	if err != nil {
+		t.Fatal(err)
+	}
+	checked := make(map[string]*types.Package) // keyed by package path
+	for _, lp := range deps {
+		checked[lp.ImportPath] = checkListPackage(t, fset, lp, checked)
+	}
+	imp := importerFunc(func(path string) (*types.Package, error) {
+		if pkg, ok := checked[path]; ok {
+			return pkg, nil
+		}
+		return nil, fmt.Errorf("no package %q", path)
+	})
+
+	for _, entry := range list {
+		if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".go") {
+			// For now, only consider standalone go files.
+			continue
+		}
+
+		t.Run(entry.Name(), func(t *testing.T) {
+			filename := filepath.Join(rootDir, entry.Name())
+			src, err := os.ReadFile(filename)
+			if err != nil {
+				t.Fatal(err)
+			}
+
+			testExportSrc(t, fset, imp, filename, src)
+		})
+	}
+}
+
+// testExportSrc type-checks the specified file using the importer,
+// encodes and decodes the package, and compares the result with the
+// original.
+func testExportSrc(t *testing.T, fset *token.FileSet, imp types.Importer, filename string, src []byte) {
+	// We're bypassing the logic of run.go here, so we consider
+	// every file, but skip errorcheck tests that contain
+	// (intentional) syntax or type errors.
+	fail := t.Fatal
+	if bytes.HasPrefix(src, []byte("// errorcheck")) {
+		fail = func(args ...any) { t.Skip(append([]any{"errorcheck test:"}, args...)...) }
+	}
+	f, err := parser.ParseFile(fset, filename, src, 0)
+	if err != nil {
+		fail(err)
+	}
+	conf := types.Config{Importer: imp}
+	pkg, err := conf.Check("", fset, []*ast.File{f}, nil)
+	if err != nil {
+		fail(err)
+	}
+
+	// export
+	data, err := exportdata.Encode(fset, pkg, exportdata.EncodeOptions{})
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	testPkgData(t, fset, pkg, data)
+}
diff --git a/src/go/types/exportdata/typepath.go b/src/go/types/exportdata/typepath.go
new file mode 100644
index 0000000000..a8c6d48e1c
--- /dev/null
+++ b/src/go/types/exportdata/typepath.go
@@ -0,0 +1,209 @@
+// 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/go/types/exportdata/typepath_test.go b/src/go/types/exportdata/typepath_test.go
new file mode 100644
index 0000000000..cac08450d7
--- /dev/null
+++ b/src/go/types/exportdata/typepath_test.go
@@ -0,0 +1,222 @@
+// 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_test
+
+// This file tests the type paths of shallow export data.
+
+import (
+	"go/ast"
+	"go/parser"
+	"go/token"
+	"go/types"
+	"testing"
+
+	"go/types/exportdata"
+)
+
+// TestShallowTypePaths checks that shallow export data preserves the
+// identity of struct and interface literals, and their members,
+// declared in other packages.
+//
+// TODO(golang/go#61674): it should also check instances of such
+// literals (BA, V, BI, W1, W2 below), whose members that are shared
+// with the origin literal should be preserved, and whose other members
+// should record their origin. For now, the test merely checks that
+// they can be exported (without reports) and imported.
+func TestShallowTypePaths(t *testing.T) {
+	const srcA = `package a
+
+func F() (_ chan *map[string]struct{ X int }) { return }
+
+func G() (_ interface{ M() }) { return }
+
+type t int
+func (t) M() (_ struct{ Y int }) { return }
+func New() (_ t) { return }
+
+type T struct{ t2 }
+type t2 struct{ X struct{ Z int } }
+
+type J interface{ M() }
+
+type S struct{ F int }
+
+type A[P any] struct{ F P; G int }
+
+func H[T any]() (_ struct{ X T; Y int }) { return }
+
+type I2[P any] interface{ M() P; N() }
+
+type g[T any] struct{ X struct{ Y T } }
+func NewG() (_ g[int]) { return }
+
+type G2[T any] struct{ X struct{ Y T } }
+var VG G2[int]
+`
+	const srcB = `package b
+
+import "a"
+
+var B = a.F()
+var C = a.G()
+var D = a.New().M()
+var E = a.T{}.X
+type I a.J
+type BS a.S
+type BA a.A[int]
+var V = a.H[string]()
+type BI a.I2[int]
+var Local struct{ W int }
+var W1 = a.NewG().X
+var W2 = a.VG.X
+`
+	fset := token.NewFileSet()
+	check := func(path, src string, imports map[string]*types.Package) *types.Package {
+		t.Helper()
+		f, err := parser.ParseFile(fset, path+".go", src, 0)
+		if err != nil {
+			t.Fatal(err)
+		}
+		conf := types.Config{
+			Importer: importerFunc(func(path string) (*types.Package, error) { return imports[path], nil }),
+		}
+		pkg, err := conf.Check(path, fset, []*ast.File{f}, nil)
+		if err != nil {
+			t.Fatal(err)
+		}
+		return pkg
+	}
+	export := func(pkg *types.Package) []byte {
+		t.Helper()
+		data, err := exportdata.Encode(fset, pkg, exportdata.EncodeOptions{Shallow: true})
+		if err != nil {
+			t.Fatalf("export %s: %v", pkg.Path(), err)
+		}
+		return data
+	}
+	import_ := func(data []byte, path string, imports map[string]*types.Package) *types.Package {
+		t.Helper()
+		pkg, err := exportdata.Decode(fset, path, data, exportdata.PackagesFromMap(imports), exportdata.DecodeOptions{})
+		if err != nil {
+			t.Fatalf("import %s: %v", path, err)
+		}
+		return pkg
+	}
+
+	// Package a, type-checked from source, and imported from shallow export data.
+	aSrc := check("a", srcA, nil)
+	aBin := import_(export(aSrc), "a", make(map[string]*types.Package))
+
+	for _, test := range []struct {
+		name string
+		aDep *types.Package // the package a against which b is type-checked
+	}{
+		// As in gopls: b is type-checked against a imported from export data.
+		{"export", aBin},
+		// b is type-checked against a type-checked from source;
+		// the paths must nonetheless be valid in a from export data.
+		{"source", aSrc},
+	} {
+		t.Run(test.name, func(t *testing.T) {
+			bSrc := check("b", srcB, map[string]*types.Package{"a": test.aDep})
+			b := import_(export(bSrc), "b", map[string]*types.Package{"a": aBin})
+			a := aBin
+
+			typeOf := func(pkg *types.Package, name string) types.Type {
+				return pkg.Scope().Lookup(name).Type()
+			}
+			result := func(pkg *types.Package, name string) types.Type {
+				return typeOf(pkg, name).(*types.Signature).Results().At(0).Type()
+			}
+			under := func(t types.Type) types.Type { return t.Underlying() }
+			elem := func(t types.Type) types.Type {
+				return t.(interface{ Elem() types.Type }).Elem()
+			}
+
+			// Each case selects a literal in b and the corresponding
+			// literal in a, which are identical in b type-checked from
+			// source. We check that they, and each pair of their
+			// members, are identical after export+import of b.
+			for _, c := range []struct {
+				name string
+				b, a func(pkg *types.Package) types.Type
+			}{
+				{"B",
+					func(b *types.Package) types.Type { return elem(elem(elem(typeOf(b, "B")))) },
+					func(a *types.Package) types.Type { return elem(elem(elem(result(a, "F")))) }},
+				{"C",
+					func(b *types.Package) types.Type { return typeOf(b, "C") },
+					func(a *types.Package) types.Type { return result(a, "G") }},
+				{"D", // method of unexported type a.t
+					func(b *types.Package) types.Type { return typeOf(b, "D") },
+					func(a *types.Package) types.Type {
+						tt := types.Unalias(result(a, "New")).(*types.Named)
+						return tt.Method(0).Type().(*types.Signature).Results().At(0).Type()
+					}},
+				{"E", // field of embedded unexported type a.t2
+					func(b *types.Package) types.Type { return typeOf(b, "E") },
+					func(a *types.Package) types.Type {
+						t2 := under(typeOf(a, "T")).(*types.Struct).Field(0).Type()
+						return under(t2).(*types.Struct).Field(0).Type()
+					}},
+				{"I", // interface methods forwarded by "type I a.J"
+					func(b *types.Package) types.Type { return under(typeOf(b, "I")) },
+					func(a *types.Package) types.Type { return under(typeOf(a, "J")) }},
+				{"BS", // struct fields forwarded by "type BS a.S" (golang/go#60819)
+					func(b *types.Package) types.Type { return under(typeOf(b, "BS")) },
+					func(a *types.Package) types.Type { return under(typeOf(a, "S")) }},
+			} {
+				srcB, srcA := c.b(bSrc), c.a(test.aDep)
+				gotB, gotA := c.b(b), c.a(a)
+				if srcB != srcA {
+					t.Fatalf("%s: in source, literals are not identical", c.name)
+				}
+				if gotB != gotA {
+					t.Errorf("%s: after import, literals are not identical", c.name)
+				}
+				srcMembers := literalMembers(srcB)
+				gotMembers := literalMembers(gotB)
+				srcAMembers := literalMembers(srcA)
+				gotAMembers := literalMembers(gotA)
+				for i := range srcMembers {
+					want := srcMembers[i] == srcAMembers[i]
+					got := gotMembers[i] == gotAMembers[i]
+					if got != want {
+						t.Errorf("%s: member %v: after import, identical to member of a = %t, want %t",
+							c.name, gotMembers[i], got, want)
+					}
+					// Fresh members are expressed in terms of b's imported
+					// view of a, so compare them only by name and type string.
+					if gotMembers[i].Name() != srcMembers[i].Name() ||
+						gotMembers[i].Type().String() != srcMembers[i].Type().String() {
+						t.Errorf("%s: member %d: got %v, want %v", c.name, i, gotMembers[i], srcMembers[i])
+					}
+				}
+			}
+
+			// Local literals belong to b.
+			if f := typeOf(b, "Local").(*types.Struct).Field(0); f.Pkg() != b {
+				t.Errorf("Local.W: Pkg = %v, want %v", f.Pkg(), b)
+			}
+		})
+	}
+}
+
+// literalMembers returns the fields of a struct literal, or the
+// explicit methods of an interface literal.
+func literalMembers(t types.Type) []types.Object {
+	var members []types.Object
+	switch t := t.(type) {
+	case *types.Struct:
+		for i := range t.NumFields() {
+			members = append(members, t.Field(i))
+		}
+	case *types.Interface:
+		for i := range t.NumExplicitMethods() {
+			members = append(members, t.ExplicitMethod(i))
+		}
+	}
+	return members
+}
diff --git a/src/internal/analysis/gotestchecker/run.go b/src/internal/analysis/gotestchecker/run.go
index cf6b2f9cd5..ec4b0bb4c8 100644
--- a/src/internal/analysis/gotestchecker/run.go
+++ b/src/internal/analysis/gotestchecker/run.go
@@ -139,6 +139,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)
 	})
 	tc := &types.Config{
@@ -185,6 +186,7 @@ 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 {
 				return fmt.Errorf("type export failed: %v", err)
 			}