| 1 | // Copyright 2018 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // Indexed package import. |
| 6 | // See iexport.go for the export data format. |
| 7 | |
| 8 | package gcimporter |
| 9 | |
| 10 | import ( |
| 11 | "bytes" |
| 12 | "encoding/binary" |
| 13 | "fmt" |
| 14 | "go/constant" |
| 15 | "go/token" |
| 16 | "go/types" |
| 17 | "io" |
| 18 | "math/big" |
| 19 | "slices" |
| 20 | "sort" |
| 21 | "strings" |
| 22 | |
| 23 | "golang.org/x/tools/go/types/objectpath" |
| 24 | "golang.org/x/tools/internal/aliases" |
| 25 | "golang.org/x/tools/internal/typesinternal" |
| 26 | ) |
| 27 | |
| 28 | type intReader struct { |
| 29 | *bytes.Reader |
| 30 | path string |
| 31 | } |
| 32 | |
| 33 | func (r *intReader) int64() int64 { |
| 34 | i, err := binary.ReadVarint(r.Reader) |
| 35 | if err != nil { |
| 36 | errorf("import %q: read varint error: %v", r.path, err) |
| 37 | } |
| 38 | return i |
| 39 | } |
| 40 | |
| 41 | func (r *intReader) uint64() uint64 { |
| 42 | i, err := binary.ReadUvarint(r.Reader) |
| 43 | if err != nil { |
| 44 | errorf("import %q: read varint error: %v", r.path, err) |
| 45 | } |
| 46 | return i |
| 47 | } |
| 48 | |
| 49 | // Keep this in sync with constants in iexport.go. |
| 50 | const ( |
| 51 | iexportVersionGo1_11 = 0 |
| 52 | iexportVersionPosCol = 1 |
| 53 | iexportVersionGo1_18 = 2 |
| 54 | iexportVersionGenerics = 2 |
| 55 | iexportVersion = iexportVersionGenerics |
| 56 | |
| 57 | iexportVersionCurrent = 2 |
| 58 | ) |
| 59 | |
| 60 | type ident struct { |
| 61 | pkg *types.Package |
| 62 | name string |
| 63 | } |
| 64 | |
| 65 | const predeclReserved = 32 |
| 66 | |
| 67 | type itag uint64 |
| 68 | |
| 69 | const ( |
| 70 | // Types |
| 71 | definedType itag = iota |
| 72 | pointerType |
| 73 | sliceType |
| 74 | arrayType |
| 75 | chanType |
| 76 | mapType |
| 77 | signatureType |
| 78 | structType |
| 79 | interfaceType |
| 80 | typeParamType |
| 81 | instanceType |
| 82 | unionType |
| 83 | aliasType |
| 84 | ) |
| 85 | |
| 86 | // Object tags |
| 87 | const ( |
| 88 | varTag = 'V' |
| 89 | funcTag = 'F' |
| 90 | genericFuncTag = 'G' |
| 91 | constTag = 'C' |
| 92 | aliasTag = 'A' |
| 93 | genericAliasTag = 'B' |
| 94 | typeParamTag = 'P' |
| 95 | typeTag = 'T' |
| 96 | genericTypeTag = 'U' |
| 97 | ) |
| 98 | |
| 99 | // IImportData imports a package from the serialized package data |
| 100 | // and returns 0 and a reference to the package. |
| 101 | // If the export data version is not recognized or the format is otherwise |
| 102 | // compromised, an error is returned. |
| 103 | func IImportData(fset *token.FileSet, imports map[string]*types.Package, data []byte, path string) (int, *types.Package, error) { |
| 104 | pkgs, err := iimportCommon(fset, GetPackagesFromMap(imports), data, false, path, false, nil) |
| 105 | if err != nil { |
| 106 | return 0, nil, err |
| 107 | } |
| 108 | return 0, pkgs[0], nil |
| 109 | } |
| 110 | |
| 111 | // IImportBundle imports a set of packages from the serialized package bundle. |
| 112 | func IImportBundle(fset *token.FileSet, imports map[string]*types.Package, data []byte) ([]*types.Package, error) { |
| 113 | return iimportCommon(fset, GetPackagesFromMap(imports), data, true, "", false, nil) |
| 114 | } |
| 115 | |
| 116 | // A GetPackagesFunc function obtains the non-nil symbols for a set of |
| 117 | // packages, creating and recursively importing them as needed. An |
| 118 | // implementation should store each package symbol is in the Pkg |
| 119 | // field of the items array. |
| 120 | // |
| 121 | // Any error causes importing to fail. This can be used to quickly read |
| 122 | // the import manifest of an export data file without fully decoding it. |
| 123 | type GetPackagesFunc = func(items []GetPackagesItem) error |
| 124 | |
| 125 | // A GetPackagesItem is a request from the importer for the package |
| 126 | // symbol of the specified name and path. |
| 127 | type GetPackagesItem struct { |
| 128 | Name, Path string |
| 129 | Pkg *types.Package // to be filled in by GetPackagesFunc call |
| 130 | |
| 131 | // private importer state |
| 132 | pathOffset uint64 |
| 133 | nameIndex map[string]uint64 |
| 134 | } |
| 135 | |
| 136 | // GetPackagesFromMap returns a GetPackagesFunc that retrieves |
| 137 | // packages from the given map of package path to package. |
| 138 | // |
| 139 | // The returned function may mutate m: each requested package that is not |
| 140 | // found is created with types.NewPackage and inserted into m. |
| 141 | func GetPackagesFromMap(m map[string]*types.Package) GetPackagesFunc { |
| 142 | return func(items []GetPackagesItem) error { |
| 143 | for i, item := range items { |
| 144 | pkg, ok := m[item.Path] |
| 145 | if !ok { |
| 146 | pkg = types.NewPackage(item.Path, item.Name) |
| 147 | m[item.Path] = pkg |
| 148 | } |
| 149 | items[i].Pkg = pkg |
| 150 | } |
| 151 | return nil |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | func iimportCommon(fset *token.FileSet, getPackages GetPackagesFunc, data []byte, bundle bool, path string, shallow bool, reportf ReportFunc) (pkgs []*types.Package, err error) { |
| 156 | const currentVersion = iexportVersionCurrent |
| 157 | version := int64(-1) |
| 158 | if !debug { |
| 159 | defer func() { |
| 160 | if e := recover(); e != nil { |
| 161 | if bundle { |
| 162 | err = fmt.Errorf("%v", e) |
| 163 | } else if version > currentVersion { |
| 164 | err = fmt.Errorf("cannot import %q (%v), export data is newer version - update tool", path, e) |
| 165 | } else { |
| 166 | err = fmt.Errorf("internal error while importing %q (%v); please report an issue", path, e) |
| 167 | } |
| 168 | } |
| 169 | }() |
| 170 | } |
| 171 | |
| 172 | r := &intReader{bytes.NewReader(data), path} |
| 173 | |
| 174 | if bundle { |
| 175 | if v := r.uint64(); v != bundleVersion { |
| 176 | errorf("unknown bundle format version %d", v) |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | version = int64(r.uint64()) |
| 181 | switch version { |
| 182 | case iexportVersionGo1_18, iexportVersionPosCol, iexportVersionGo1_11: |
| 183 | default: |
| 184 | if version > iexportVersionGo1_18 { |
| 185 | errorf("unstable iexport format version %d, just rebuild compiler and std library", version) |
| 186 | } else { |
| 187 | errorf("unknown iexport format version %d", version) |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | sLen := int64(r.uint64()) |
| 192 | var fLen int64 |
| 193 | var fileOffset []uint64 |
| 194 | if shallow { |
| 195 | // Shallow mode uses a different position encoding. |
| 196 | fLen = int64(r.uint64()) |
| 197 | fileOffset = make([]uint64, r.uint64()) |
| 198 | for i := range fileOffset { |
| 199 | fileOffset[i] = r.uint64() |
| 200 | } |
| 201 | } |
| 202 | dLen := int64(r.uint64()) |
| 203 | |
| 204 | whence, _ := r.Seek(0, io.SeekCurrent) |
| 205 | stringData := data[whence : whence+sLen] |
| 206 | fileData := data[whence+sLen : whence+sLen+fLen] |
| 207 | declData := data[whence+sLen+fLen : whence+sLen+fLen+dLen] |
| 208 | r.Seek(sLen+fLen+dLen, io.SeekCurrent) |
| 209 | |
| 210 | p := iimporter{ |
| 211 | version: int(version), |
| 212 | ipath: path, |
| 213 | shallow: shallow, |
| 214 | reportf: reportf, |
| 215 | |
| 216 | stringData: stringData, |
| 217 | stringCache: make(map[uint64]string), |
| 218 | fileOffset: fileOffset, |
| 219 | fileData: fileData, |
| 220 | fileCache: make([]*token.File, len(fileOffset)), |
| 221 | pkgCache: make(map[uint64]*types.Package), |
| 222 | |
| 223 | declData: declData, |
| 224 | pkgIndex: make(map[*types.Package]map[string]uint64), |
| 225 | typCache: make(map[uint64]types.Type), |
| 226 | // Separate map for typeparams, keyed by their package and unique |
| 227 | // name. |
| 228 | tparamIndex: make(map[ident]types.Type), |
| 229 | |
| 230 | fake: fakeFileSet{ |
| 231 | fset: fset, |
| 232 | files: make(map[string]*fileInfo), |
| 233 | }, |
| 234 | } |
| 235 | defer p.fake.setLines() // set lines for files in fset |
| 236 | |
| 237 | for i, pt := range predeclared() { |
| 238 | p.typCache[uint64(i)] = pt |
| 239 | } |
| 240 | |
| 241 | // Gather the relevant packages from the manifest. |
| 242 | items := make([]GetPackagesItem, r.uint64()) |
| 243 | uniquePkgPaths := make(map[string]bool) |
| 244 | for i := range items { |
| 245 | pkgPathOff := r.uint64() |
| 246 | pkgPath := p.stringAt(pkgPathOff) |
| 247 | pkgName := p.stringAt(r.uint64()) |
| 248 | _ = r.uint64() // package height; unused by go/types |
| 249 | |
| 250 | if pkgPath == "" { |
| 251 | pkgPath = path |
| 252 | } |
| 253 | items[i].Name = pkgName |
| 254 | items[i].Path = pkgPath |
| 255 | items[i].pathOffset = pkgPathOff |
| 256 | |
| 257 | // Read index for package. |
| 258 | nameIndex := make(map[string]uint64) |
| 259 | nSyms := r.uint64() |
| 260 | // In shallow mode, only the current package (i=0) has an index. |
| 261 | assert(!(shallow && i > 0 && nSyms != 0)) |
| 262 | for ; nSyms > 0; nSyms-- { |
| 263 | name := p.stringAt(r.uint64()) |
| 264 | nameIndex[name] = r.uint64() |
| 265 | } |
| 266 | |
| 267 | items[i].nameIndex = nameIndex |
| 268 | |
| 269 | uniquePkgPaths[pkgPath] = true |
| 270 | } |
| 271 | // Debugging #63822; hypothesis: there are duplicate PkgPaths. |
| 272 | if len(uniquePkgPaths) != len(items) { |
| 273 | reportf("found duplicate PkgPaths while reading export data manifest: %v", items) |
| 274 | } |
| 275 | |
| 276 | // Request packages all at once from the client, |
| 277 | // enabling a parallel implementation. |
| 278 | if err := getPackages(items); err != nil { |
| 279 | return nil, err // don't wrap this error |
| 280 | } |
| 281 | |
| 282 | // Check the results and complete the index. |
| 283 | pkgList := make([]*types.Package, len(items)) |
| 284 | for i, item := range items { |
| 285 | pkg := item.Pkg |
| 286 | if pkg == nil { |
| 287 | errorf("internal error: getPackages returned nil package for %q", item.Path) |
| 288 | } else if pkg.Path() != item.Path { |
| 289 | errorf("internal error: getPackages returned wrong path %q, want %q", pkg.Path(), item.Path) |
| 290 | } else if pkg.Name() != item.Name { |
| 291 | errorf("internal error: getPackages returned wrong name %s for package %q, want %s", pkg.Name(), item.Path, item.Name) |
| 292 | } |
| 293 | p.pkgCache[item.pathOffset] = pkg |
| 294 | p.pkgIndex[pkg] = item.nameIndex |
| 295 | pkgList[i] = pkg |
| 296 | } |
| 297 | |
| 298 | if bundle { |
| 299 | pkgs = make([]*types.Package, r.uint64()) |
| 300 | for i := range pkgs { |
| 301 | pkg := p.pkgAt(r.uint64()) |
| 302 | imps := make([]*types.Package, r.uint64()) |
| 303 | for j := range imps { |
| 304 | imps[j] = p.pkgAt(r.uint64()) |
| 305 | } |
| 306 | pkg.SetImports(imps) |
| 307 | pkgs[i] = pkg |
| 308 | } |
| 309 | } else { |
| 310 | if len(pkgList) == 0 { |
| 311 | errorf("no packages found for %s", path) |
| 312 | panic("unreachable") |
| 313 | } |
| 314 | pkgs = pkgList[:1] |
| 315 | |
| 316 | // record all referenced packages as imports |
| 317 | list := slices.Clone(pkgList[1:]) |
| 318 | sort.Sort(byPath(list)) |
| 319 | pkgs[0].SetImports(list) |
| 320 | } |
| 321 | |
| 322 | for _, pkg := range pkgs { |
| 323 | if pkg.Complete() { |
| 324 | continue |
| 325 | } |
| 326 | |
| 327 | names := make([]string, 0, len(p.pkgIndex[pkg])) |
| 328 | for name := range p.pkgIndex[pkg] { |
| 329 | names = append(names, name) |
| 330 | } |
| 331 | sort.Strings(names) |
| 332 | for _, name := range names { |
| 333 | p.doDecl(pkg, name) |
| 334 | } |
| 335 | |
| 336 | // package was imported completely and without errors |
| 337 | pkg.MarkComplete() |
| 338 | } |
| 339 | |
| 340 | // SetConstraint can't be called if the constraint type is not yet complete. |
| 341 | // When type params are created in the typeParamTag case of (*importReader).obj(), |
| 342 | // the associated constraint type may not be complete due to recursion. |
| 343 | // Therefore, we defer calling SetConstraint there, and call it here instead |
| 344 | // after all types are complete. |
| 345 | for _, d := range p.later { |
| 346 | d.t.SetConstraint(d.constraint) |
| 347 | } |
| 348 | |
| 349 | for _, typ := range p.interfaceList { |
| 350 | typ.Complete() |
| 351 | } |
| 352 | |
| 353 | // Workaround for golang/go#61561. See the doc for instanceList for details. |
| 354 | for _, typ := range p.instanceList { |
| 355 | if iface, _ := typ.Underlying().(*types.Interface); iface != nil { |
| 356 | iface.Complete() |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | return pkgs, nil |
| 361 | } |
| 362 | |
| 363 | type setConstraintArgs struct { |
| 364 | t *types.TypeParam |
| 365 | constraint types.Type |
| 366 | } |
| 367 | |
| 368 | type iimporter struct { |
| 369 | version int |
| 370 | ipath string |
| 371 | |
| 372 | shallow bool |
| 373 | reportf ReportFunc // if non-nil, used to report bugs |
| 374 | |
| 375 | stringData []byte |
| 376 | stringCache map[uint64]string |
| 377 | fileOffset []uint64 // fileOffset[i] is offset in fileData for info about file encoded as i |
| 378 | fileData []byte |
| 379 | fileCache []*token.File // memoized decoding of file encoded as i |
| 380 | pkgCache map[uint64]*types.Package |
| 381 | |
| 382 | declData []byte |
| 383 | pkgIndex map[*types.Package]map[string]uint64 |
| 384 | typCache map[uint64]types.Type |
| 385 | tparamIndex map[ident]types.Type |
| 386 | |
| 387 | fake fakeFileSet |
| 388 | interfaceList []*types.Interface |
| 389 | |
| 390 | // Workaround for the go/types bug golang/go#61561: instances produced during |
| 391 | // instantiation may contain incomplete interfaces. Here we only complete the |
| 392 | // underlying type of the instance, which is the most common case but doesn't |
| 393 | // handle parameterized interface literals defined deeper in the type. |
| 394 | instanceList []types.Type // instances for later completion (see golang/go#61561) |
| 395 | |
| 396 | // Arguments for calls to SetConstraint that are deferred due to recursive types |
| 397 | later []setConstraintArgs |
| 398 | |
| 399 | indent int // for tracing support |
| 400 | } |
| 401 | |
| 402 | func (p *iimporter) trace(format string, args ...any) { |
| 403 | if !trace { |
| 404 | // Call sites should also be guarded, but having this check here allows |
| 405 | // easily enabling/disabling debug trace statements. |
| 406 | return |
| 407 | } |
| 408 | fmt.Printf(strings.Repeat("..", p.indent)+format+"\n", args...) |
| 409 | } |
| 410 | |
| 411 | func (p *iimporter) doDecl(pkg *types.Package, name string) { |
| 412 | if debug { |
| 413 | p.trace("import decl %s", name) |
| 414 | p.indent++ |
| 415 | defer func() { |
| 416 | p.indent-- |
| 417 | p.trace("=> %s", name) |
| 418 | }() |
| 419 | } |
| 420 | // See if we've already imported this declaration. |
| 421 | if obj := pkg.Scope().Lookup(name); obj != nil { |
| 422 | return |
| 423 | } |
| 424 | |
| 425 | off, ok := p.pkgIndex[pkg][name] |
| 426 | if !ok { |
| 427 | // In deep mode, the index should be complete. In shallow |
| 428 | // mode, we should have already recursively loaded necessary |
| 429 | // dependencies so the above Lookup succeeds. |
| 430 | errorf("%v.%v not in index", pkg, name) |
| 431 | } |
| 432 | |
| 433 | r := &importReader{p: p} |
| 434 | r.declReader.Reset(p.declData[off:]) |
| 435 | |
| 436 | r.obj(pkg, name) |
| 437 | } |
| 438 | |
| 439 | func (p *iimporter) stringAt(off uint64) string { |
| 440 | if s, ok := p.stringCache[off]; ok { |
| 441 | return s |
| 442 | } |
| 443 | |
| 444 | slen, n := binary.Uvarint(p.stringData[off:]) |
| 445 | if n <= 0 { |
| 446 | errorf("varint failed") |
| 447 | } |
| 448 | spos := off + uint64(n) |
| 449 | s := string(p.stringData[spos : spos+slen]) |
| 450 | p.stringCache[off] = s |
| 451 | return s |
| 452 | } |
| 453 | |
| 454 | func (p *iimporter) fileAt(index uint64) *token.File { |
| 455 | file := p.fileCache[index] |
| 456 | if file == nil { |
| 457 | off := p.fileOffset[index] |
| 458 | file = p.decodeFile(intReader{bytes.NewReader(p.fileData[off:]), p.ipath}) |
| 459 | p.fileCache[index] = file |
| 460 | } |
| 461 | return file |
| 462 | } |
| 463 | |
| 464 | func (p *iimporter) decodeFile(rd intReader) *token.File { |
| 465 | filename := p.stringAt(rd.uint64()) |
| 466 | size := int(rd.uint64()) |
| 467 | file := p.fake.fset.AddFile(filename, -1, size) |
| 468 | |
| 469 | // SetLines requires a nondecreasing sequence. |
| 470 | // Because it is common for clients to derive the interval |
| 471 | // [start, start+len(name)] from a start position, and we |
| 472 | // want to ensure that the end offset is on the same line, |
| 473 | // we fill in the gaps of the sparse encoding with values |
| 474 | // that strictly increase by the largest possible amount. |
| 475 | // This allows us to avoid having to record the actual end |
| 476 | // offset of each needed line. |
| 477 | |
| 478 | lines := make([]int, int(rd.uint64())) |
| 479 | var index, offset int |
| 480 | for i, n := 0, int(rd.uint64()); i < n; i++ { |
| 481 | index += int(rd.uint64()) |
| 482 | offset += int(rd.uint64()) |
| 483 | lines[index] = offset |
| 484 | |
| 485 | // Ensure monotonicity between points. |
| 486 | for j := index - 1; j > 0 && lines[j] == 0; j-- { |
| 487 | lines[j] = lines[j+1] - 1 |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | // Ensure monotonicity after last point. |
| 492 | for j := len(lines) - 1; j > 0 && lines[j] == 0; j-- { |
| 493 | size-- |
| 494 | lines[j] = size |
| 495 | } |
| 496 | |
| 497 | if !file.SetLines(lines) { |
| 498 | errorf("SetLines failed: %d", lines) // can't happen |
| 499 | } |
| 500 | return file |
| 501 | } |
| 502 | |
| 503 | func (p *iimporter) pkgAt(off uint64) *types.Package { |
| 504 | if pkg, ok := p.pkgCache[off]; ok { |
| 505 | return pkg |
| 506 | } |
| 507 | path := p.stringAt(off) |
| 508 | errorf("missing package %q in %q", path, p.ipath) |
| 509 | return nil |
| 510 | } |
| 511 | |
| 512 | func (p *iimporter) typAt(off uint64, base *types.Named) types.Type { |
| 513 | if t, ok := p.typCache[off]; ok && canReuse(base, t) { |
| 514 | return t |
| 515 | } |
| 516 | |
| 517 | if off < predeclReserved { |
| 518 | errorf("predeclared type missing from cache: %v", off) |
| 519 | } |
| 520 | |
| 521 | r := &importReader{p: p} |
| 522 | r.declReader.Reset(p.declData[off-predeclReserved:]) |
| 523 | t := r.doType(base) |
| 524 | |
| 525 | if canReuse(base, t) { |
| 526 | p.typCache[off] = t |
| 527 | } |
| 528 | return t |
| 529 | } |
| 530 | |
| 531 | // canReuse reports whether the type rhs on the RHS of the declaration for def |
| 532 | // may be re-used. |
| 533 | // |
| 534 | // Specifically, if def is non-nil and rhs is an interface type with methods, it |
| 535 | // may not be re-used because we have a convention of setting the receiver type |
| 536 | // for interface methods to def. |
| 537 | func canReuse(def *types.Named, rhs types.Type) bool { |
| 538 | if def == nil { |
| 539 | return true |
| 540 | } |
| 541 | iface, _ := types.Unalias(rhs).(*types.Interface) |
| 542 | if iface == nil { |
| 543 | return true |
| 544 | } |
| 545 | // Don't use iface.Empty() here as iface may not be complete. |
| 546 | return iface.NumEmbeddeds() == 0 && iface.NumExplicitMethods() == 0 |
| 547 | } |
| 548 | |
| 549 | type importReader struct { |
| 550 | p *iimporter |
| 551 | declReader bytes.Reader |
| 552 | prevFile string |
| 553 | prevLine int64 |
| 554 | prevColumn int64 |
| 555 | } |
| 556 | |
| 557 | // markBlack is redefined in iimport_go123.go, to work around golang/go#69912. |
| 558 | // |
| 559 | // If TypeNames are not marked black (in the sense of go/types cycle |
| 560 | // detection), they may be mutated when dot-imported. Fix this by punching a |
| 561 | // hole through the type, when compiling with Go 1.23. (The bug has been fixed |
| 562 | // for 1.24, but the fix was not worth back-porting). |
| 563 | var markBlack = func(name *types.TypeName) {} |
| 564 | |
| 565 | // obj decodes and declares the package-level object denoted by (pkg, name). |
| 566 | func (r *importReader) obj(pkg *types.Package, name string) { |
| 567 | tag := r.byte() |
| 568 | pos := r.pos() |
| 569 | |
| 570 | switch tag { |
| 571 | case aliasTag, genericAliasTag: |
| 572 | var tparams []*types.TypeParam |
| 573 | if tag == genericAliasTag { |
| 574 | tparams = r.tparamList() |
| 575 | } |
| 576 | typ := r.typ() |
| 577 | obj := aliases.New(pos, pkg, name, typ, tparams) |
| 578 | markBlack(obj) // workaround for golang/go#69912 |
| 579 | r.declare(obj) |
| 580 | |
| 581 | case constTag: |
| 582 | typ, val := r.value() |
| 583 | |
| 584 | r.declare(types.NewConst(pos, pkg, name, typ, val)) |
| 585 | |
| 586 | case funcTag, genericFuncTag: |
| 587 | var tparams []*types.TypeParam |
| 588 | if tag == genericFuncTag { |
| 589 | tparams = r.tparamList() |
| 590 | } |
| 591 | sig := r.signature(pkg, nil, nil, tparams) |
| 592 | r.declare(types.NewFunc(pos, pkg, name, sig)) |
| 593 | |
| 594 | case typeTag, genericTypeTag: |
| 595 | // Types can be recursive. We need to setup a stub |
| 596 | // declaration before recursing. |
| 597 | obj := types.NewTypeName(pos, pkg, name, nil) |
| 598 | named := types.NewNamed(obj, nil, nil) |
| 599 | |
| 600 | markBlack(obj) // workaround for golang/go#69912 |
| 601 | |
| 602 | // Declare obj before calling r.tparamList, so the new type name is recognized |
| 603 | // if used in the constraint of one of its own typeparams (see #48280). |
| 604 | r.declare(obj) |
| 605 | if tag == genericTypeTag { |
| 606 | tparams := r.tparamList() |
| 607 | named.SetTypeParams(tparams) |
| 608 | } |
| 609 | |
| 610 | underlying := r.p.typAt(r.uint64(), named).Underlying() |
| 611 | named.SetUnderlying(underlying) |
| 612 | |
| 613 | if !isInterface(underlying) { |
| 614 | for n := r.uint64(); n > 0; n-- { |
| 615 | mpos := r.pos() |
| 616 | mname := r.ident() |
| 617 | recv := r.param(pkg) |
| 618 | |
| 619 | // If the receiver has any targs, set those as the |
| 620 | // rparams of the method (since those are the |
| 621 | // typeparams being used in the method sig/body). |
| 622 | _, recvNamed := typesinternal.ReceiverNamed(recv) |
| 623 | targs := recvNamed.TypeArgs() |
| 624 | var rparams []*types.TypeParam |
| 625 | if targs.Len() > 0 { |
| 626 | rparams = make([]*types.TypeParam, targs.Len()) |
| 627 | for i := range rparams { |
| 628 | rparams[i] = types.Unalias(targs.At(i)).(*types.TypeParam) |
| 629 | } |
| 630 | } |
| 631 | msig := r.signature(pkg, recv, rparams, nil) |
| 632 | |
| 633 | named.AddMethod(types.NewFunc(mpos, pkg, mname, msig)) |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | case typeParamTag: |
| 638 | // We need to "declare" a typeparam in order to have a name that |
| 639 | // can be referenced recursively (if needed) in the type param's |
| 640 | // bound. |
| 641 | if r.p.version < iexportVersionGenerics { |
| 642 | errorf("unexpected type param type") |
| 643 | } |
| 644 | name0 := tparamName(name) |
| 645 | tn := types.NewTypeName(pos, pkg, name0, nil) |
| 646 | t := types.NewTypeParam(tn, nil) |
| 647 | |
| 648 | // To handle recursive references to the typeparam within its |
| 649 | // bound, save the partial type in tparamIndex before reading the bounds. |
| 650 | id := ident{pkg, name} |
| 651 | r.p.tparamIndex[id] = t |
| 652 | var implicit bool |
| 653 | if r.p.version >= iexportVersionGo1_18 { |
| 654 | implicit = r.bool() |
| 655 | } |
| 656 | constraint := r.typ() |
| 657 | if implicit { |
| 658 | iface, _ := types.Unalias(constraint).(*types.Interface) |
| 659 | if iface == nil { |
| 660 | errorf("non-interface constraint marked implicit") |
| 661 | } |
| 662 | iface.MarkImplicit() |
| 663 | } |
| 664 | // The constraint type may not be complete, if we |
| 665 | // are in the middle of a type recursion involving type |
| 666 | // constraints. So, we defer SetConstraint until we have |
| 667 | // completely set up all types in ImportData. |
| 668 | r.p.later = append(r.p.later, setConstraintArgs{t: t, constraint: constraint}) |
| 669 | |
| 670 | case varTag: |
| 671 | typ := r.typ() |
| 672 | |
| 673 | v := types.NewVar(pos, pkg, name, typ) |
| 674 | typesinternal.SetVarKind(v, typesinternal.PackageVar) |
| 675 | r.declare(v) |
| 676 | |
| 677 | default: |
| 678 | errorf("unexpected tag: %v", tag) |
| 679 | } |
| 680 | } |
| 681 | |
| 682 | func (r *importReader) declare(obj types.Object) { |
| 683 | obj.Pkg().Scope().Insert(obj) |
| 684 | } |
| 685 | |
| 686 | func (r *importReader) value() (typ types.Type, val constant.Value) { |
| 687 | typ = r.typ() |
| 688 | if r.p.version >= iexportVersionGo1_18 { |
| 689 | // TODO: add support for using the kind. |
| 690 | _ = constant.Kind(r.int64()) |
| 691 | } |
| 692 | |
| 693 | switch b := typ.Underlying().(*types.Basic); b.Info() & types.IsConstType { |
| 694 | case types.IsBoolean: |
| 695 | val = constant.MakeBool(r.bool()) |
| 696 | |
| 697 | case types.IsString: |
| 698 | val = constant.MakeString(r.string()) |
| 699 | |
| 700 | case types.IsInteger: |
| 701 | var x big.Int |
| 702 | r.mpint(&x, b) |
| 703 | val = constant.Make(&x) |
| 704 | |
| 705 | case types.IsFloat: |
| 706 | val = r.mpfloat(b) |
| 707 | |
| 708 | case types.IsComplex: |
| 709 | re := r.mpfloat(b) |
| 710 | im := r.mpfloat(b) |
| 711 | val = constant.BinaryOp(re, token.ADD, constant.MakeImag(im)) |
| 712 | |
| 713 | default: |
| 714 | if b.Kind() == types.Invalid { |
| 715 | val = constant.MakeUnknown() |
| 716 | return |
| 717 | } |
| 718 | errorf("unexpected type %v", typ) // panics |
| 719 | panic("unreachable") |
| 720 | } |
| 721 | |
| 722 | return |
| 723 | } |
| 724 | |
| 725 | func intSize(b *types.Basic) (signed bool, maxBytes uint) { |
| 726 | if (b.Info() & types.IsUntyped) != 0 { |
| 727 | return true, 64 |
| 728 | } |
| 729 | |
| 730 | switch b.Kind() { |
| 731 | case types.Float32, types.Complex64: |
| 732 | return true, 3 |
| 733 | case types.Float64, types.Complex128: |
| 734 | return true, 7 |
| 735 | } |
| 736 | |
| 737 | signed = (b.Info() & types.IsUnsigned) == 0 |
| 738 | switch b.Kind() { |
| 739 | case types.Int8, types.Uint8: |
| 740 | maxBytes = 1 |
| 741 | case types.Int16, types.Uint16: |
| 742 | maxBytes = 2 |
| 743 | case types.Int32, types.Uint32: |
| 744 | maxBytes = 4 |
| 745 | default: |
| 746 | maxBytes = 8 |
| 747 | } |
| 748 | |
| 749 | return |
| 750 | } |
| 751 | |
| 752 | func (r *importReader) mpint(x *big.Int, typ *types.Basic) { |
| 753 | signed, maxBytes := intSize(typ) |
| 754 | |
| 755 | maxSmall := 256 - maxBytes |
| 756 | if signed { |
| 757 | maxSmall = 256 - 2*maxBytes |
| 758 | } |
| 759 | if maxBytes == 1 { |
| 760 | maxSmall = 256 |
| 761 | } |
| 762 | |
| 763 | n, _ := r.declReader.ReadByte() |
| 764 | if uint(n) < maxSmall { |
| 765 | v := int64(n) |
| 766 | if signed { |
| 767 | v >>= 1 |
| 768 | if n&1 != 0 { |
| 769 | v = ^v |
| 770 | } |
| 771 | } |
| 772 | x.SetInt64(v) |
| 773 | return |
| 774 | } |
| 775 | |
| 776 | v := -n |
| 777 | if signed { |
| 778 | v = -(n &^ 1) >> 1 |
| 779 | } |
| 780 | if v < 1 || uint(v) > maxBytes { |
| 781 | errorf("weird decoding: %v, %v => %v", n, signed, v) |
| 782 | } |
| 783 | b := make([]byte, v) |
| 784 | io.ReadFull(&r.declReader, b) |
| 785 | x.SetBytes(b) |
| 786 | if signed && n&1 != 0 { |
| 787 | x.Neg(x) |
| 788 | } |
| 789 | } |
| 790 | |
| 791 | func (r *importReader) mpfloat(typ *types.Basic) constant.Value { |
| 792 | var mant big.Int |
| 793 | r.mpint(&mant, typ) |
| 794 | var f big.Float |
| 795 | f.SetInt(&mant) |
| 796 | if f.Sign() != 0 { |
| 797 | f.SetMantExp(&f, int(r.int64())) |
| 798 | } |
| 799 | return constant.Make(&f) |
| 800 | } |
| 801 | |
| 802 | func (r *importReader) ident() string { |
| 803 | return r.string() |
| 804 | } |
| 805 | |
| 806 | func (r *importReader) qualifiedIdent() (*types.Package, string) { |
| 807 | name := r.string() |
| 808 | pkg := r.pkg() |
| 809 | return pkg, name |
| 810 | } |
| 811 | |
| 812 | func (r *importReader) pos() token.Pos { |
| 813 | if r.p.shallow { |
| 814 | // precise offsets are encoded only in shallow mode |
| 815 | return r.posv2() |
| 816 | } |
| 817 | if r.p.version >= iexportVersionPosCol { |
| 818 | r.posv1() |
| 819 | } else { |
| 820 | r.posv0() |
| 821 | } |
| 822 | |
| 823 | if r.prevFile == "" && r.prevLine == 0 && r.prevColumn == 0 { |
| 824 | return token.NoPos |
| 825 | } |
| 826 | return r.p.fake.pos(r.prevFile, int(r.prevLine), int(r.prevColumn)) |
| 827 | } |
| 828 | |
| 829 | func (r *importReader) posv0() { |
| 830 | delta := r.int64() |
| 831 | if delta != deltaNewFile { |
| 832 | r.prevLine += delta |
| 833 | } else if l := r.int64(); l == -1 { |
| 834 | r.prevLine += deltaNewFile |
| 835 | } else { |
| 836 | r.prevFile = r.string() |
| 837 | r.prevLine = l |
| 838 | } |
| 839 | } |
| 840 | |
| 841 | func (r *importReader) posv1() { |
| 842 | delta := r.int64() |
| 843 | r.prevColumn += delta >> 1 |
| 844 | if delta&1 != 0 { |
| 845 | delta = r.int64() |
| 846 | r.prevLine += delta >> 1 |
| 847 | if delta&1 != 0 { |
| 848 | r.prevFile = r.string() |
| 849 | } |
| 850 | } |
| 851 | } |
| 852 | |
| 853 | func (r *importReader) posv2() token.Pos { |
| 854 | file := r.uint64() |
| 855 | if file == 0 { |
| 856 | return token.NoPos |
| 857 | } |
| 858 | tf := r.p.fileAt(file - 1) |
| 859 | return tf.Pos(int(r.uint64())) |
| 860 | } |
| 861 | |
| 862 | func (r *importReader) typ() types.Type { |
| 863 | return r.p.typAt(r.uint64(), nil) |
| 864 | } |
| 865 | |
| 866 | func isInterface(t types.Type) bool { |
| 867 | _, ok := types.Unalias(t).(*types.Interface) |
| 868 | return ok |
| 869 | } |
| 870 | |
| 871 | func (r *importReader) pkg() *types.Package { return r.p.pkgAt(r.uint64()) } |
| 872 | func (r *importReader) string() string { return r.p.stringAt(r.uint64()) } |
| 873 | |
| 874 | func (r *importReader) doType(base *types.Named) (res types.Type) { |
| 875 | k := r.kind() |
| 876 | if debug { |
| 877 | r.p.trace("importing type %d (base: %v)", k, base) |
| 878 | r.p.indent++ |
| 879 | defer func() { |
| 880 | r.p.indent-- |
| 881 | r.p.trace("=> %s", res) |
| 882 | }() |
| 883 | } |
| 884 | switch k { |
| 885 | default: |
| 886 | errorf("unexpected kind tag in %q: %v", r.p.ipath, k) |
| 887 | return nil |
| 888 | |
| 889 | case aliasType, definedType: |
| 890 | pkg, name := r.qualifiedIdent() |
| 891 | r.p.doDecl(pkg, name) |
| 892 | return pkg.Scope().Lookup(name).(*types.TypeName).Type() |
| 893 | case pointerType: |
| 894 | return types.NewPointer(r.typ()) |
| 895 | case sliceType: |
| 896 | return types.NewSlice(r.typ()) |
| 897 | case arrayType: |
| 898 | n := r.uint64() |
| 899 | return types.NewArray(r.typ(), int64(n)) |
| 900 | case chanType: |
| 901 | dir := chanDir(int(r.uint64())) |
| 902 | return types.NewChan(dir, r.typ()) |
| 903 | case mapType: |
| 904 | return types.NewMap(r.typ(), r.typ()) |
| 905 | case signatureType: |
| 906 | paramPkg := r.pkg() |
| 907 | return r.signature(paramPkg, nil, nil, nil) |
| 908 | |
| 909 | case structType: |
| 910 | fieldPkg := r.pkg() |
| 911 | |
| 912 | fields := make([]*types.Var, r.uint64()) |
| 913 | tags := make([]string, len(fields)) |
| 914 | for i := range fields { |
| 915 | var field *types.Var |
| 916 | if r.p.shallow { |
| 917 | field, _ = r.objectPathObject().(*types.Var) |
| 918 | } |
| 919 | |
| 920 | fpos := r.pos() |
| 921 | fname := r.ident() |
| 922 | ftyp := r.typ() |
| 923 | emb := r.bool() |
| 924 | tag := r.string() |
| 925 | |
| 926 | // Either this is not a shallow import, the field is local, or the |
| 927 | // encoded objectPath failed to produce an object (a bug). |
| 928 | // |
| 929 | // Even in this last, buggy case, fall back on creating a new field. As |
| 930 | // discussed in iexport.go, this is not correct, but mostly works and is |
| 931 | // preferable to failing (for now at least). |
| 932 | if field == nil { |
| 933 | field = types.NewField(fpos, fieldPkg, fname, ftyp, emb) |
| 934 | } |
| 935 | |
| 936 | fields[i] = field |
| 937 | tags[i] = tag |
| 938 | } |
| 939 | return types.NewStruct(fields, tags) |
| 940 | |
| 941 | case interfaceType: |
| 942 | methodPkg := r.pkg() // qualifies methods and their param/result vars |
| 943 | |
| 944 | embeddeds := make([]types.Type, r.uint64()) |
| 945 | for i := range embeddeds { |
| 946 | _ = r.pos() |
| 947 | embeddeds[i] = r.typ() |
| 948 | } |
| 949 | |
| 950 | methods := make([]*types.Func, r.uint64()) |
| 951 | for i := range methods { |
| 952 | var method *types.Func |
| 953 | if r.p.shallow { |
| 954 | method, _ = r.objectPathObject().(*types.Func) |
| 955 | } |
| 956 | |
| 957 | mpos := r.pos() |
| 958 | mname := r.ident() |
| 959 | |
| 960 | // TODO(mdempsky): Matches bimport.go, but I |
| 961 | // don't agree with this. |
| 962 | var recv *types.Var |
| 963 | if base != nil { |
| 964 | recv = types.NewVar(token.NoPos, methodPkg, "", base) |
| 965 | } |
| 966 | msig := r.signature(methodPkg, recv, nil, nil) |
| 967 | |
| 968 | if method == nil { |
| 969 | method = types.NewFunc(mpos, methodPkg, mname, msig) |
| 970 | } |
| 971 | methods[i] = method |
| 972 | } |
| 973 | |
| 974 | typ := types.NewInterfaceType(methods, embeddeds) |
| 975 | r.p.interfaceList = append(r.p.interfaceList, typ) |
| 976 | return typ |
| 977 | |
| 978 | case typeParamType: |
| 979 | if r.p.version < iexportVersionGenerics { |
| 980 | errorf("unexpected type param type") |
| 981 | } |
| 982 | pkg, name := r.qualifiedIdent() |
| 983 | id := ident{pkg, name} |
| 984 | if t, ok := r.p.tparamIndex[id]; ok { |
| 985 | // We're already in the process of importing this typeparam. |
| 986 | return t |
| 987 | } |
| 988 | // Otherwise, import the definition of the typeparam now. |
| 989 | r.p.doDecl(pkg, name) |
| 990 | return r.p.tparamIndex[id] |
| 991 | |
| 992 | case instanceType: |
| 993 | if r.p.version < iexportVersionGenerics { |
| 994 | errorf("unexpected instantiation type") |
| 995 | } |
| 996 | // pos does not matter for instances: they are positioned on the original |
| 997 | // type. |
| 998 | _ = r.pos() |
| 999 | len := r.uint64() |
| 1000 | targs := make([]types.Type, len) |
| 1001 | for i := range targs { |
| 1002 | targs[i] = r.typ() |
| 1003 | } |
| 1004 | baseType := r.typ() |
| 1005 | // The imported instantiated type doesn't include any methods, so |
| 1006 | // we must always use the methods of the base (orig) type. |
| 1007 | // TODO provide a non-nil *Environment |
| 1008 | t, _ := types.Instantiate(nil, baseType, targs, false) |
| 1009 | |
| 1010 | // Workaround for golang/go#61561. See the doc for instanceList for details. |
| 1011 | r.p.instanceList = append(r.p.instanceList, t) |
| 1012 | return t |
| 1013 | |
| 1014 | case unionType: |
| 1015 | if r.p.version < iexportVersionGenerics { |
| 1016 | errorf("unexpected instantiation type") |
| 1017 | } |
| 1018 | terms := make([]*types.Term, r.uint64()) |
| 1019 | for i := range terms { |
| 1020 | terms[i] = types.NewTerm(r.bool(), r.typ()) |
| 1021 | } |
| 1022 | return types.NewUnion(terms) |
| 1023 | } |
| 1024 | } |
| 1025 | |
| 1026 | func (r *importReader) kind() itag { |
| 1027 | return itag(r.uint64()) |
| 1028 | } |
| 1029 | |
| 1030 | // objectPathObject is the inverse of exportWriter.objectPath. |
| 1031 | // |
| 1032 | // In shallow mode, certain fields and methods may need to be looked up in an |
| 1033 | // imported package. See the doc for exportWriter.objectPath for a full |
| 1034 | // explanation. |
| 1035 | func (r *importReader) objectPathObject() types.Object { |
| 1036 | objPath := objectpath.Path(r.string()) |
| 1037 | if objPath == "" { |
| 1038 | return nil |
| 1039 | } |
| 1040 | pkg := r.pkg() |
| 1041 | obj, err := objectpath.Object(pkg, objPath) |
| 1042 | if err != nil { |
| 1043 | if r.p.reportf != nil { |
| 1044 | r.p.reportf("failed to find object for objectPath %q: %v", objPath, err) |
| 1045 | } |
| 1046 | } |
| 1047 | return obj |
| 1048 | } |
| 1049 | |
| 1050 | func (r *importReader) signature(paramPkg *types.Package, recv *types.Var, rparams []*types.TypeParam, tparams []*types.TypeParam) *types.Signature { |
| 1051 | params := r.paramList(paramPkg) |
| 1052 | results := r.paramList(paramPkg) |
| 1053 | variadic := params.Len() > 0 && r.bool() |
| 1054 | return types.NewSignatureType(recv, rparams, tparams, params, results, variadic) |
| 1055 | } |
| 1056 | |
| 1057 | func (r *importReader) tparamList() []*types.TypeParam { |
| 1058 | n := r.uint64() |
| 1059 | if n == 0 { |
| 1060 | return nil |
| 1061 | } |
| 1062 | xs := make([]*types.TypeParam, n) |
| 1063 | for i := range xs { |
| 1064 | // Note: the standard library importer is tolerant of nil types here, |
| 1065 | // though would panic in SetTypeParams. |
| 1066 | xs[i] = types.Unalias(r.typ()).(*types.TypeParam) |
| 1067 | } |
| 1068 | return xs |
| 1069 | } |
| 1070 | |
| 1071 | func (r *importReader) paramList(pkg *types.Package) *types.Tuple { |
| 1072 | xs := make([]*types.Var, r.uint64()) |
| 1073 | for i := range xs { |
| 1074 | xs[i] = r.param(pkg) |
| 1075 | } |
| 1076 | return types.NewTuple(xs...) |
| 1077 | } |
| 1078 | |
| 1079 | func (r *importReader) param(pkg *types.Package) *types.Var { |
| 1080 | pos := r.pos() |
| 1081 | name := r.ident() |
| 1082 | typ := r.typ() |
| 1083 | return types.NewParam(pos, pkg, name, typ) |
| 1084 | } |
| 1085 | |
| 1086 | func (r *importReader) bool() bool { |
| 1087 | return r.uint64() != 0 |
| 1088 | } |
| 1089 | |
| 1090 | func (r *importReader) int64() int64 { |
| 1091 | n, err := binary.ReadVarint(&r.declReader) |
| 1092 | if err != nil { |
| 1093 | errorf("readVarint: %v", err) |
| 1094 | } |
| 1095 | return n |
| 1096 | } |
| 1097 | |
| 1098 | func (r *importReader) uint64() uint64 { |
| 1099 | n, err := binary.ReadUvarint(&r.declReader) |
| 1100 | if err != nil { |
| 1101 | errorf("readUvarint: %v", err) |
| 1102 | } |
| 1103 | return n |
| 1104 | } |
| 1105 | |
| 1106 | func (r *importReader) byte() byte { |
| 1107 | x, err := r.declReader.ReadByte() |
| 1108 | if err != nil { |
| 1109 | errorf("declReader.ReadByte: %v", err) |
| 1110 | } |
| 1111 | return x |
| 1112 | } |
| 1113 | |
| 1114 | type byPath []*types.Package |
| 1115 | |
| 1116 | func (a byPath) Len() int { return len(a) } |
| 1117 | func (a byPath) Swap(i, j int) { a[i], a[j] = a[j], a[i] } |
| 1118 | func (a byPath) Less(i, j int) bool { return a[i].Path() < a[j].Path() } |