| 1 | // Copyright 2022 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 | package gcimporter_test |
| 6 | |
| 7 | import ( |
| 8 | "fmt" |
| 9 | "go/ast" |
| 10 | "go/parser" |
| 11 | "go/token" |
| 12 | "go/types" |
| 13 | "os" |
| 14 | "strings" |
| 15 | "testing" |
| 16 | |
| 17 | "golang.org/x/sync/errgroup" |
| 18 | "golang.org/x/tools/go/packages" |
| 19 | "golang.org/x/tools/internal/gcimporter" |
| 20 | "golang.org/x/tools/internal/testenv" |
| 21 | ) |
| 22 | |
| 23 | // TestShallowStd type-checks the standard library using shallow export data. |
| 24 | func TestShallowStd(t *testing.T) { |
| 25 | if testing.Short() { |
| 26 | t.Skip("skipping in short mode; too slow (https://golang.org/issue/14113)") |
| 27 | } |
| 28 | testenv.NeedsTool(t, "go") |
| 29 | |
| 30 | // Load import graph of the standard library. |
| 31 | // (No parsing or type-checking.) |
| 32 | cfg := &packages.Config{ |
| 33 | Mode: packages.NeedImports | |
| 34 | packages.NeedName | |
| 35 | packages.NeedFiles | // see https://github.com/golang/go/issues/56632 |
| 36 | packages.NeedCompiledGoFiles, |
| 37 | Tests: false, |
| 38 | } |
| 39 | pkgs, err := packages.Load(cfg, "std") |
| 40 | if err != nil { |
| 41 | t.Fatalf("load: %v", err) |
| 42 | } |
| 43 | if len(pkgs) < 200 { |
| 44 | t.Fatalf("too few packages: %d", len(pkgs)) |
| 45 | } |
| 46 | |
| 47 | // Type check the packages in parallel postorder. |
| 48 | done := make(map[*packages.Package]chan struct{}) |
| 49 | packages.Visit(pkgs, nil, func(p *packages.Package) { |
| 50 | done[p] = make(chan struct{}) |
| 51 | }) |
| 52 | packages.Visit(pkgs, nil, |
| 53 | func(pkg *packages.Package) { |
| 54 | go func() { |
| 55 | // Wait for all deps to be done. |
| 56 | for _, imp := range pkg.Imports { |
| 57 | <-done[imp] |
| 58 | } |
| 59 | typecheck(t, pkg) |
| 60 | close(done[pkg]) |
| 61 | }() |
| 62 | }) |
| 63 | for _, root := range pkgs { |
| 64 | <-done[root] |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | // typecheck reads, parses, and type-checks a package. |
| 69 | // It squirrels the export data in the ppkg.ExportFile field. |
| 70 | func typecheck(t *testing.T, ppkg *packages.Package) { |
| 71 | if ppkg.PkgPath == "unsafe" { |
| 72 | return // unsafe is special |
| 73 | } |
| 74 | |
| 75 | // Create a local FileSet just for this package. |
| 76 | fset := token.NewFileSet() |
| 77 | |
| 78 | // Parse files in parallel. |
| 79 | syntax := make([]*ast.File, len(ppkg.CompiledGoFiles)) |
| 80 | var group errgroup.Group |
| 81 | for i, filename := range ppkg.CompiledGoFiles { |
| 82 | group.Go(func() error { |
| 83 | f, err := parser.ParseFile(fset, filename, nil, parser.SkipObjectResolution) |
| 84 | if err != nil { |
| 85 | return err // e.g. missing file |
| 86 | } |
| 87 | syntax[i] = f |
| 88 | return nil |
| 89 | }) |
| 90 | } |
| 91 | if err := group.Wait(); err != nil { |
| 92 | t.Fatal(err) |
| 93 | } |
| 94 | // Inv: all files were successfully parsed. |
| 95 | |
| 96 | // Build map of dependencies by package path. |
| 97 | // (We don't compute this mapping for the entire |
| 98 | // packages graph because it is not globally consistent.) |
| 99 | depsByPkgPath := make(map[string]*packages.Package) |
| 100 | { |
| 101 | var visit func(*packages.Package) |
| 102 | visit = func(pkg *packages.Package) { |
| 103 | if depsByPkgPath[pkg.PkgPath] == nil { |
| 104 | depsByPkgPath[pkg.PkgPath] = pkg |
| 105 | for path := range pkg.Imports { |
| 106 | visit(pkg.Imports[path]) |
| 107 | } |
| 108 | } |
| 109 | } |
| 110 | visit(ppkg) |
| 111 | } |
| 112 | |
| 113 | // importer state |
| 114 | var ( |
| 115 | loadFromExportData func(*packages.Package) (*types.Package, error) |
| 116 | importMap = map[string]*types.Package{ // keys are PackagePaths |
| 117 | ppkg.PkgPath: types.NewPackage(ppkg.PkgPath, ppkg.Name), |
| 118 | } |
| 119 | ) |
| 120 | loadFromExportData = func(imp *packages.Package) (*types.Package, error) { |
| 121 | export := []byte(imp.ExportFile) |
| 122 | getPackages := func(items []gcimporter.GetPackagesItem) error { |
| 123 | for i, item := range items { |
| 124 | pkg, ok := importMap[item.Path] |
| 125 | if !ok { |
| 126 | dep, ok := depsByPkgPath[item.Path] |
| 127 | if !ok { |
| 128 | return fmt.Errorf("can't find dependency: %q", item.Path) |
| 129 | } |
| 130 | pkg = types.NewPackage(item.Path, dep.Name) |
| 131 | importMap[item.Path] = pkg |
| 132 | loadFromExportData(dep) // side effect: populate package scope |
| 133 | } |
| 134 | items[i].Pkg = pkg |
| 135 | } |
| 136 | return nil |
| 137 | } |
| 138 | return gcimporter.IImportShallow(fset, getPackages, export, imp.PkgPath, nil) |
| 139 | } |
| 140 | |
| 141 | // Type-check the syntax trees. |
| 142 | cfg := &types.Config{ |
| 143 | Error: func(e error) { |
| 144 | t.Error(e) |
| 145 | }, |
| 146 | Importer: importerFunc(func(importPath string) (*types.Package, error) { |
| 147 | if importPath == "unsafe" { |
| 148 | return types.Unsafe, nil // unsafe has no exportdata |
| 149 | } |
| 150 | imp, ok := ppkg.Imports[importPath] |
| 151 | if !ok { |
| 152 | return nil, fmt.Errorf("missing import %q", importPath) |
| 153 | } |
| 154 | return loadFromExportData(imp) |
| 155 | }), |
| 156 | } |
| 157 | |
| 158 | // (Use NewChecker+Files to ensure Package.Name is set explicitly.) |
| 159 | tpkg := types.NewPackage(ppkg.PkgPath, ppkg.Name) |
| 160 | _ = types.NewChecker(cfg, fset, tpkg, nil).Files(syntax) // ignore error |
| 161 | // Check sanity. |
| 162 | postTypeCheck(t, fset, tpkg) |
| 163 | |
| 164 | // Save the export data. |
| 165 | data, err := gcimporter.IExportShallow(fset, tpkg, nil) |
| 166 | if err != nil { |
| 167 | t.Fatalf("internal error marshalling export data: %v", err) |
| 168 | } |
| 169 | ppkg.ExportFile = string(data) |
| 170 | } |
| 171 | |
| 172 | // postTypeCheck is called after a package is type checked. |
| 173 | // We use it to assert additional correctness properties, |
| 174 | // for example, that the apparent location of "fmt.Println" |
| 175 | // corresponds to its source location: in other words, |
| 176 | // export+import preserves high-fidelity positions. |
| 177 | func postTypeCheck(t *testing.T, fset *token.FileSet, pkg *types.Package) { |
| 178 | // We hard-code a few interesting test-case objects. |
| 179 | var obj types.Object |
| 180 | switch pkg.Path() { |
| 181 | case "fmt": |
| 182 | // func fmt.Println |
| 183 | obj = pkg.Scope().Lookup("Println") |
| 184 | case "net/http": |
| 185 | // method (*http.Request).ParseForm |
| 186 | req := pkg.Scope().Lookup("Request") |
| 187 | obj, _, _ = types.LookupFieldOrMethod(req.Type(), true, pkg, "ParseForm") |
| 188 | default: |
| 189 | return |
| 190 | } |
| 191 | if obj == nil { |
| 192 | t.Errorf("object not found in package %s", pkg.Path()) |
| 193 | return |
| 194 | } |
| 195 | |
| 196 | // Now check the source fidelity of the object's position. |
| 197 | posn := fset.Position(obj.Pos()) |
| 198 | data, err := os.ReadFile(posn.Filename) |
| 199 | if err != nil { |
| 200 | t.Errorf("can't read source file declaring %v: %v", obj, err) |
| 201 | return |
| 202 | } |
| 203 | |
| 204 | // Check line and column denote a source interval containing the object's identifier. |
| 205 | line := strings.Split(string(data), "\n")[posn.Line-1] |
| 206 | |
| 207 | if id := line[posn.Column-1 : posn.Column-1+len(obj.Name())]; id != obj.Name() { |
| 208 | t.Errorf("%+v: expected declaration of %v at this line, column; got %q", posn, obj, line) |
| 209 | } |
| 210 | |
| 211 | // Check offset. |
| 212 | if id := string(data[posn.Offset : posn.Offset+len(obj.Name())]); id != obj.Name() { |
| 213 | t.Errorf("%+v: expected declaration of %v at this offset; got %q", posn, obj, id) |
| 214 | } |
| 215 | |
| 216 | // Check commutativity of Position() and start+len(name) operations: |
| 217 | // Position(startPos+len(name)) == Position(startPos) + len(name). |
| 218 | // This important property is a consequence of the way in which the |
| 219 | // decoder fills the gaps in the sparse line-start offset table. |
| 220 | endPosn := fset.Position(obj.Pos() + token.Pos(len(obj.Name()))) |
| 221 | wantEndPosn := token.Position{ |
| 222 | Filename: posn.Filename, |
| 223 | Offset: posn.Offset + len(obj.Name()), |
| 224 | Line: posn.Line, |
| 225 | Column: posn.Column + len(obj.Name()), |
| 226 | } |
| 227 | if endPosn != wantEndPosn { |
| 228 | t.Errorf("%+v: expected end Position of %v here; was at %+v", wantEndPosn, obj, endPosn) |
| 229 | } |
| 230 | } |