| 1 | // Copyright 2019 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 | // This is a copy of bexport_test.go for iexport.go. |
| 6 | |
| 7 | package gcimporter_test |
| 8 | |
| 9 | import ( |
| 10 | "bytes" |
| 11 | "fmt" |
| 12 | "go/ast" |
| 13 | "go/constant" |
| 14 | "go/parser" |
| 15 | "go/token" |
| 16 | "go/types" |
| 17 | "math/big" |
| 18 | "os" |
| 19 | "os/exec" |
| 20 | "path/filepath" |
| 21 | "reflect" |
| 22 | "runtime" |
| 23 | "strings" |
| 24 | "testing" |
| 25 | |
| 26 | "golang.org/x/tools/go/gcexportdata" |
| 27 | "golang.org/x/tools/go/packages" |
| 28 | "golang.org/x/tools/internal/gcimporter" |
| 29 | "golang.org/x/tools/internal/testenv" |
| 30 | ) |
| 31 | |
| 32 | func iexport(fset *token.FileSet, version int, pkg *types.Package) ([]byte, error) { |
| 33 | var buf bytes.Buffer |
| 34 | const bundle, shallow = false, false |
| 35 | if err := gcimporter.IExportCommon(&buf, fset, bundle, shallow, version, []*types.Package{pkg}, nil); err != nil { |
| 36 | return nil, err |
| 37 | } |
| 38 | return buf.Bytes(), nil |
| 39 | } |
| 40 | |
| 41 | func skipIfModcacheGOROOT(t *testing.T) { |
| 42 | t.Helper() |
| 43 | modcache := os.Getenv("GOMODCACHE") |
| 44 | if modcache == "" { |
| 45 | out, err := exec.Command("go", "env", "GOMODCACHE").Output() |
| 46 | if err != nil { |
| 47 | t.Fatal(err) |
| 48 | } |
| 49 | modcache = strings.TrimSpace(string(out)) |
| 50 | } |
| 51 | if modcache != "" && strings.HasPrefix(runtime.GOROOT(), modcache) { |
| 52 | t.Skip("skipping test because GOROOT is in GOMODCACHE and cannot be overlaid") |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | func TestIExportData_stdlib(t *testing.T) { |
| 57 | testenv.NeedsGoPackages(t) |
| 58 | skipIfModcacheGOROOT(t) |
| 59 | if isRace { |
| 60 | t.Skipf("stdlib tests take too long in race mode and flake on builders") |
| 61 | } |
| 62 | if testing.Short() { |
| 63 | t.Skip("skipping RAM hungry test in -short mode") |
| 64 | } |
| 65 | |
| 66 | var errorsDir string // GOROOT/src/errors directory |
| 67 | { |
| 68 | cfg := packages.Config{ |
| 69 | Mode: packages.NeedName | packages.NeedFiles, |
| 70 | } |
| 71 | pkgs, err := packages.Load(&cfg, "errors") |
| 72 | if err != nil { |
| 73 | t.Fatal(err) |
| 74 | } |
| 75 | errorsDir = filepath.Dir(pkgs[0].GoFiles[0]) |
| 76 | } |
| 77 | |
| 78 | // Load types from syntax for all std packages. |
| 79 | // |
| 80 | // Append a file to package errors containing type and |
| 81 | // value errors to ensure they are properly encoded/decoded. |
| 82 | const bad = `package errors |
| 83 | const UnknownValue = "" + 0 |
| 84 | type UnknownType undefined |
| 85 | ` |
| 86 | cfg := packages.Config{ |
| 87 | Mode: packages.LoadAllSyntax | packages.NeedDeps, |
| 88 | Overlay: map[string][]byte{filepath.Join(errorsDir, "bad.go"): []byte(bad)}, |
| 89 | } |
| 90 | pkgs, err := packages.Load(&cfg, "std") // ~800ms |
| 91 | if err != nil { |
| 92 | t.Fatal(err) |
| 93 | } |
| 94 | fset := pkgs[0].Fset |
| 95 | |
| 96 | version := gcimporter.IExportVersion |
| 97 | |
| 98 | // Export and reimport each package, and check that they match. |
| 99 | var allPkgs []*types.Package |
| 100 | var errorsPkg *types.Package // reimported errors package |
| 101 | packages.Visit(pkgs, nil, func(ppkg *packages.Package) { // ~300ms |
| 102 | pkg := ppkg.Types |
| 103 | path := pkg.Path() |
| 104 | if path == "unsafe" || |
| 105 | strings.HasPrefix(path, "cmd/") || |
| 106 | strings.HasPrefix(path, "vendor/") { |
| 107 | return |
| 108 | } |
| 109 | allPkgs = append(allPkgs, pkg) |
| 110 | |
| 111 | // Export and reimport the package, and compare. |
| 112 | exportdata, err := iexport(fset, version, pkg) |
| 113 | if err != nil { |
| 114 | t.Error(err) |
| 115 | return |
| 116 | } |
| 117 | pkg2 := testPkgData(t, fset, version, pkg, exportdata) |
| 118 | if path == "errors" { |
| 119 | errorsPkg = pkg2 |
| 120 | } |
| 121 | }) |
| 122 | |
| 123 | // Assert that we saw a plausible sized library. |
| 124 | const minStdlibPackages = 248 |
| 125 | if n := len(allPkgs); n < minStdlibPackages { |
| 126 | t.Errorf("Loaded only %d packages, want at least %d", n, minStdlibPackages) |
| 127 | } |
| 128 | |
| 129 | // Check that reimported errors package has bad decls. |
| 130 | if errorsPkg == nil { |
| 131 | t.Fatalf("'errors' package not found") |
| 132 | } |
| 133 | for _, name := range []string{"UnknownType", "UnknownValue"} { |
| 134 | obj := errorsPkg.Scope().Lookup(name) |
| 135 | if obj == nil { |
| 136 | t.Errorf("errors.%s not found", name) |
| 137 | } |
| 138 | if typ := obj.Type().Underlying(); typ.String() != "invalid type" { |
| 139 | t.Errorf("errors.%s has underlying type %s, want invalid type", name, typ) |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | // (Sole) test of bundle functionality (250ms). |
| 144 | var bundle bytes.Buffer |
| 145 | if err := gcimporter.IExportBundle(&bundle, fset, allPkgs); err != nil { |
| 146 | t.Fatal(err) |
| 147 | } |
| 148 | fset2 := token.NewFileSet() |
| 149 | imports := make(map[string]*types.Package) |
| 150 | pkgs2, err := gcimporter.IImportBundle(fset2, imports, bundle.Bytes()) |
| 151 | if err != nil { |
| 152 | t.Fatal(err) |
| 153 | } |
| 154 | for i, pkg := range allPkgs { |
| 155 | testPkg(t, fset, version, pkg, fset2, pkgs2[i]) |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | // testPkgData imports a package from export data and compares it with pkg. |
| 160 | func testPkgData(t *testing.T, fset *token.FileSet, version int, pkg *types.Package, exportdata []byte) *types.Package { |
| 161 | imports := make(map[string]*types.Package) |
| 162 | fset2 := token.NewFileSet() |
| 163 | _, pkg2, err := gcimporter.IImportData(fset2, imports, exportdata, pkg.Path()) |
| 164 | if err != nil { |
| 165 | t.Errorf("IImportData(%s): %v", pkg.Path(), err) |
| 166 | } |
| 167 | |
| 168 | testPkg(t, fset, version, pkg, fset2, pkg2) |
| 169 | return pkg2 |
| 170 | } |
| 171 | |
| 172 | func testPkg(t *testing.T, fset *token.FileSet, version int, pkg *types.Package, fset2 *token.FileSet, pkg2 *types.Package) { |
| 173 | if _, err := iexport(fset2, version, pkg2); err != nil { |
| 174 | t.Errorf("reexport %q: %v", pkg.Path(), err) |
| 175 | } |
| 176 | |
| 177 | // Compare the packages' corresponding members. |
| 178 | for _, name := range pkg.Scope().Names() { |
| 179 | if !token.IsExported(name) { |
| 180 | continue |
| 181 | } |
| 182 | obj1 := pkg.Scope().Lookup(name) |
| 183 | obj2 := pkg2.Scope().Lookup(name) |
| 184 | if obj2 == nil { |
| 185 | t.Errorf("%s.%s not found, want %s", pkg.Path(), name, obj1) |
| 186 | continue |
| 187 | } |
| 188 | |
| 189 | fl1 := fileLine(fset, obj1) |
| 190 | fl2 := fileLine(fset2, obj2) |
| 191 | if fl1 != fl2 { |
| 192 | t.Errorf("%s.%s: got posn %s, want %s", |
| 193 | pkg.Path(), name, fl2, fl1) |
| 194 | } |
| 195 | |
| 196 | if err := cmpObj(obj1, obj2); err != nil { |
| 197 | t.Errorf("%s.%s: %s\ngot: %s\nwant: %s", |
| 198 | pkg.Path(), name, err, obj2, obj1) |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | // TestIExportData_long tests the position of an import object declared in |
| 204 | // a very long input file. Line numbers greater than maxlines are |
| 205 | // reported as line 1, not garbage or token.NoPos. |
| 206 | func TestIExportData_long(t *testing.T) { |
| 207 | // parse and typecheck |
| 208 | longFile := "package foo" + strings.Repeat("\n", 123456) + "var X int" |
| 209 | fset1 := token.NewFileSet() |
| 210 | f, err := parser.ParseFile(fset1, "foo.go", longFile, 0) |
| 211 | if err != nil { |
| 212 | t.Fatal(err) |
| 213 | } |
| 214 | var conf types.Config |
| 215 | pkg, err := conf.Check("foo", fset1, []*ast.File{f}, nil) |
| 216 | if err != nil { |
| 217 | t.Fatal(err) |
| 218 | } |
| 219 | |
| 220 | // export |
| 221 | exportdata, err := iexport(fset1, gcimporter.IExportVersion, pkg) |
| 222 | if err != nil { |
| 223 | t.Fatal(err) |
| 224 | } |
| 225 | |
| 226 | // import |
| 227 | imports := make(map[string]*types.Package) |
| 228 | fset2 := token.NewFileSet() |
| 229 | _, pkg2, err := gcimporter.IImportData(fset2, imports, exportdata, pkg.Path()) |
| 230 | if err != nil { |
| 231 | t.Fatalf("IImportData(%s): %v", pkg.Path(), err) |
| 232 | } |
| 233 | |
| 234 | // compare |
| 235 | posn1 := fset1.Position(pkg.Scope().Lookup("X").Pos()) |
| 236 | posn2 := fset2.Position(pkg2.Scope().Lookup("X").Pos()) |
| 237 | if want := "foo.go:1:1"; posn2.String() != want { |
| 238 | t.Errorf("X position = %s, want %s (orig was %s)", |
| 239 | posn2, want, posn1) |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | func TestIExportData_typealiases(t *testing.T) { |
| 244 | // parse and typecheck |
| 245 | fset1 := token.NewFileSet() |
| 246 | f, err := parser.ParseFile(fset1, "p.go", src, 0) |
| 247 | if err != nil { |
| 248 | t.Fatal(err) |
| 249 | } |
| 250 | var conf types.Config |
| 251 | pkg1, err := conf.Check("p", fset1, []*ast.File{f}, nil) |
| 252 | if err == nil { |
| 253 | // foo in undeclared in src; we should see an error |
| 254 | t.Fatal("invalid source type-checked without error") |
| 255 | } |
| 256 | if pkg1 == nil { |
| 257 | // despite incorrect src we should see a (partially) type-checked package |
| 258 | t.Fatal("nil package returned") |
| 259 | } |
| 260 | checkPkg(t, pkg1, "export") |
| 261 | |
| 262 | // export |
| 263 | // use a nil fileset here to confirm that it doesn't panic |
| 264 | exportdata, err := iexport(nil, gcimporter.IExportVersion, pkg1) |
| 265 | if err != nil { |
| 266 | t.Fatal(err) |
| 267 | } |
| 268 | |
| 269 | // import |
| 270 | imports := make(map[string]*types.Package) |
| 271 | fset2 := token.NewFileSet() |
| 272 | _, pkg2, err := gcimporter.IImportData(fset2, imports, exportdata, pkg1.Path()) |
| 273 | if err != nil { |
| 274 | t.Fatalf("IImportData(%s): %v", pkg1.Path(), err) |
| 275 | } |
| 276 | checkPkg(t, pkg2, "import") |
| 277 | } |
| 278 | |
| 279 | // cmpObj reports how x and y differ. They are assumed to belong to different |
| 280 | // universes so cannot be compared directly. It is an adapted version of |
| 281 | // equalObj in bexport_test.go. |
| 282 | func cmpObj(x, y types.Object) error { |
| 283 | if reflect.TypeOf(x) != reflect.TypeOf(y) { |
| 284 | return fmt.Errorf("%T vs %T", x, y) |
| 285 | } |
| 286 | xt := x.Type() |
| 287 | yt := y.Type() |
| 288 | switch x := x.(type) { |
| 289 | case *types.Var, *types.Func: |
| 290 | // ok |
| 291 | case *types.Const: |
| 292 | xval := x.Val() |
| 293 | yval := y.(*types.Const).Val() |
| 294 | equal := constant.Compare(xval, token.EQL, yval) |
| 295 | if !equal { |
| 296 | // try approx. comparison |
| 297 | xkind := xval.Kind() |
| 298 | ykind := yval.Kind() |
| 299 | if xkind == constant.Complex || ykind == constant.Complex { |
| 300 | equal = same(constant.Real(xval), constant.Real(yval)) && |
| 301 | same(constant.Imag(xval), constant.Imag(yval)) |
| 302 | } else if xkind == constant.Float || ykind == constant.Float { |
| 303 | equal = same(xval, yval) |
| 304 | } else if xkind == constant.Unknown && ykind == constant.Unknown { |
| 305 | equal = true |
| 306 | } |
| 307 | } |
| 308 | if !equal { |
| 309 | return fmt.Errorf("unequal constants %s vs %s", xval, yval) |
| 310 | } |
| 311 | case *types.TypeName: |
| 312 | if xalias, yalias := x.IsAlias(), y.(*types.TypeName).IsAlias(); xalias != yalias { |
| 313 | return fmt.Errorf("mismatching IsAlias(): %s vs %s", x, y) |
| 314 | } |
| 315 | |
| 316 | // equalType does not recurse into the underlying types of named types, so |
| 317 | // we must pass the underlying type explicitly here. However, in doing this |
| 318 | // we may skip checking the features of the named types themselves, in |
| 319 | // situations where the type name is not referenced by the underlying or |
| 320 | // any other top-level declarations. Therefore, we must explicitly compare |
| 321 | // named types here, before passing their underlying types into equalType. |
| 322 | xn, _ := types.Unalias(xt).(*types.Named) |
| 323 | yn, _ := types.Unalias(yt).(*types.Named) |
| 324 | if (xn == nil) != (yn == nil) { |
| 325 | return fmt.Errorf("mismatching types: %T vs %T", xt, yt) |
| 326 | } |
| 327 | if xn != nil { |
| 328 | if err := cmpNamed(xn, yn); err != nil { |
| 329 | return err |
| 330 | } |
| 331 | } |
| 332 | xt = xt.Underlying() |
| 333 | yt = yt.Underlying() |
| 334 | default: |
| 335 | return fmt.Errorf("unexpected %T", x) |
| 336 | } |
| 337 | return equalType(xt, yt) |
| 338 | } |
| 339 | |
| 340 | // Use the same floating-point precision (512) as cmd/compile |
| 341 | // (see Mpprec in cmd/compile/internal/gc/mpfloat.go). |
| 342 | const mpprec = 512 |
| 343 | |
| 344 | // same compares non-complex numeric values and reports if they are approximately equal. |
| 345 | func same(x, y constant.Value) bool { |
| 346 | xf := constantToFloat(x) |
| 347 | yf := constantToFloat(y) |
| 348 | d := new(big.Float).Sub(xf, yf) |
| 349 | d.Abs(d) |
| 350 | eps := big.NewFloat(1.0 / (1 << (mpprec - 1))) // allow for 1 bit of error |
| 351 | return d.Cmp(eps) < 0 |
| 352 | } |
| 353 | |
| 354 | // copy of the function with the same name in iexport.go. |
| 355 | func constantToFloat(x constant.Value) *big.Float { |
| 356 | var f big.Float |
| 357 | f.SetPrec(mpprec) |
| 358 | if v, exact := constant.Float64Val(x); exact { |
| 359 | // float64 |
| 360 | f.SetFloat64(v) |
| 361 | } else if num, denom := constant.Num(x), constant.Denom(x); num.Kind() == constant.Int { |
| 362 | // TODO(gri): add big.Rat accessor to constant.Value. |
| 363 | n := valueToRat(num) |
| 364 | d := valueToRat(denom) |
| 365 | f.SetRat(n.Quo(n, d)) |
| 366 | } else { |
| 367 | // Value too large to represent as a fraction => inaccessible. |
| 368 | // TODO(gri): add big.Float accessor to constant.Value. |
| 369 | _, ok := f.SetString(x.ExactString()) |
| 370 | if !ok { |
| 371 | panic("should not reach here") |
| 372 | } |
| 373 | } |
| 374 | return &f |
| 375 | } |
| 376 | |
| 377 | // copy of the function with the same name in iexport.go. |
| 378 | func valueToRat(x constant.Value) *big.Rat { |
| 379 | // Convert little-endian to big-endian. |
| 380 | // I can't believe this is necessary. |
| 381 | bytes := constant.Bytes(x) |
| 382 | for i := 0; i < len(bytes)/2; i++ { |
| 383 | bytes[i], bytes[len(bytes)-1-i] = bytes[len(bytes)-1-i], bytes[i] |
| 384 | } |
| 385 | return new(big.Rat).SetInt(new(big.Int).SetBytes(bytes)) |
| 386 | } |
| 387 | |
| 388 | // This is a regression test for a bug in iexport of types.Struct: |
| 389 | // unexported fields were losing their implicit package qualifier. |
| 390 | func TestUnexportedStructFields(t *testing.T) { |
| 391 | fset := token.NewFileSet() |
| 392 | export := make(map[string][]byte) |
| 393 | |
| 394 | // process parses and type-checks a single-file |
| 395 | // package and saves its export data. |
| 396 | process := func(path, content string) { |
| 397 | syntax, err := parser.ParseFile(fset, path+"/x.go", content, 0) |
| 398 | if err != nil { |
| 399 | t.Fatal(err) |
| 400 | } |
| 401 | packages := make(map[string]*types.Package) // keys are package paths |
| 402 | cfg := &types.Config{ |
| 403 | Importer: importerFunc(func(path string) (*types.Package, error) { |
| 404 | data, ok := export[path] |
| 405 | if !ok { |
| 406 | return nil, fmt.Errorf("missing export data for %s", path) |
| 407 | } |
| 408 | return gcexportdata.Read(bytes.NewReader(data), fset, packages, path) |
| 409 | }), |
| 410 | } |
| 411 | pkg := types.NewPackage(path, syntax.Name.Name) |
| 412 | check := types.NewChecker(cfg, fset, pkg, nil) |
| 413 | if err := check.Files([]*ast.File{syntax}); err != nil { |
| 414 | t.Fatal(err) |
| 415 | } |
| 416 | var out bytes.Buffer |
| 417 | if err := gcexportdata.Write(&out, fset, pkg); err != nil { |
| 418 | t.Fatal(err) |
| 419 | } |
| 420 | export[path] = out.Bytes() |
| 421 | } |
| 422 | |
| 423 | // Historically this led to a spurious error: |
| 424 | // "cannot convert a.M (variable of type a.MyTime) to type time.Time" |
| 425 | // because the private fields of Time and MyTime were not identical. |
| 426 | process("time", `package time; type Time struct { x, y int }`) |
| 427 | process("a", `package a; import "time"; type MyTime time.Time; var M MyTime`) |
| 428 | process("b", `package b; import ("a"; "time"); var _ = time.Time(a.M)`) |
| 429 | } |
| 430 | |
| 431 | type importerFunc func(path string) (*types.Package, error) |
| 432 | |
| 433 | func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) } |
| 434 | |
| 435 | // TestIExportDataTypeParameterizedAliases tests IExportData |
| 436 | // on both declarations and uses of type parameterized aliases. |
| 437 | func TestIExportDataTypeParameterizedAliases(t *testing.T) { |
| 438 | testenv.NeedsGo1Point(t, 23) |
| 439 | skipWindows(t) |
| 440 | if testenv.Go1Point() == 23 { |
| 441 | testenv.NeedsGoExperiment(t, "aliastypeparams") // testenv.Go1Point() >= 24 implies aliastypeparams=1 |
| 442 | } |
| 443 | |
| 444 | // High level steps: |
| 445 | // * parse and typecheck |
| 446 | // * export the data for the importer (via IExportData), |
| 447 | // * import the data (via either x/tools or GOROOT's gcimporter), and |
| 448 | // * check the imported types. |
| 449 | |
| 450 | const src = `package pkg |
| 451 | |
| 452 | type A[T any] = *T |
| 453 | type B[R any, S *R] = []S |
| 454 | type C[U any] = B[U, A[U]] |
| 455 | |
| 456 | type Named int |
| 457 | type Chained = C[Named] // B[Named, A[Named]] = B[Named, *Named] = []*Named |
| 458 | ` |
| 459 | |
| 460 | // parse and typecheck |
| 461 | fset1 := token.NewFileSet() |
| 462 | f, err := parser.ParseFile(fset1, "pkg", src, 0) |
| 463 | if err != nil { |
| 464 | t.Fatal(err) |
| 465 | } |
| 466 | var conf types.Config |
| 467 | pkg1, err := conf.Check("pkg", fset1, []*ast.File{f}, nil) |
| 468 | if err != nil { |
| 469 | t.Fatal(err) |
| 470 | } |
| 471 | |
| 472 | // Read the result of IExportData through x/tools/internal/gcimporter.IImportData. |
| 473 | // export |
| 474 | exportdata, err := iexport(fset1, gcimporter.IExportVersion, pkg1) |
| 475 | if err != nil { |
| 476 | t.Fatal(err) |
| 477 | } |
| 478 | |
| 479 | // import |
| 480 | imports := make(map[string]*types.Package) |
| 481 | fset2 := token.NewFileSet() |
| 482 | _, pkg2, err := gcimporter.IImportData(fset2, imports, exportdata, pkg1.Path()) |
| 483 | if err != nil { |
| 484 | t.Fatalf("IImportData(%s): %v", pkg1.Path(), err) |
| 485 | } |
| 486 | |
| 487 | pkg := pkg2 |
| 488 | for name, want := range map[string]string{ |
| 489 | "A": "type pkg.A[T any] = *T", |
| 490 | "B": "type pkg.B[R any, S *R] = []S", |
| 491 | "C": "type pkg.C[U any] = pkg.B[U, pkg.A[U]]", |
| 492 | "Named": "type pkg.Named int", |
| 493 | "Chained": "type pkg.Chained = pkg.C[pkg.Named]", |
| 494 | } { |
| 495 | obj := pkg.Scope().Lookup(name) |
| 496 | if obj == nil { |
| 497 | t.Errorf("failed to find %q in package %s", name, pkg) |
| 498 | continue |
| 499 | } |
| 500 | |
| 501 | got := strings.ReplaceAll(obj.String(), pkg.Path(), "pkg") |
| 502 | if got != want { |
| 503 | t.Errorf("(%q).String()=%q. wanted %q", name, got, want) |
| 504 | } |
| 505 | } |
| 506 | } |