Debian Codegraph @

internal/refactor/inline/everything_test.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // Copyright 2023 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 inline_test
6
7 import (
8 "flag"
9 "fmt"
10 "go/ast"
11 "go/parser"
12 "go/types"
13 "log"
14 "os"
15 "path/filepath"
16 "slices"
17 "strings"
18 "testing"
19
20 "golang.org/x/tools/go/packages"
21 "golang.org/x/tools/go/types/typeutil"
22 "golang.org/x/tools/internal/diff"
23 "golang.org/x/tools/internal/refactor/inline"
24 "golang.org/x/tools/internal/testenv"
25 )
26
27 var packagesFlag = flag.String("packages", "", "set of packages for TestEverything")
28
29 // TestEverything invokes the inliner on every single call site in a
30 // given package. and checks that it produces either a reasonable
31 // error, or output that parses and type-checks.
32 //
33 // It does nothing during ordinary testing, but may be used to find
34 // inlining bugs in large corpora.
35 //
36 // Use this command to inline everything in golang.org/x/tools:
37 //
38 // $ go test ./internal/refactor/inline/ -run=Everything -packages=../../../
39 //
40 // And these commands to inline everything in the kubernetes repository:
41 //
42 // $ go test -c -o /tmp/everything ./internal/refactor/inline/
43 // $ (cd kubernetes && /tmp/everything -test.run=Everything -packages=./...)
44 //
45 // TODO(adonovan):
46 // - report counters (number of attempts, failed AnalyzeCallee, failed
47 // Inline, etc.)
48 // - Make a pretty log of the entire output so that we can peruse it
49 // for opportunities for systematic improvement.
50 func TestEverything(t *testing.T) {
51 testenv.NeedsGoPackages(t)
52 if testing.Short() {
53 t.Skipf("skipping slow test in -short mode")
54 }
55 if *packagesFlag == "" {
56 return
57 }
58
59 // Load this package plus dependencies from typed syntax.
60 cfg := &packages.Config{
61 Mode: packages.LoadAllSyntax,
62 Env: append(os.Environ(),
•63 "GO111MODULE=on",
64 "GOPATH=",
65 "GOWORK=off",
66 "GOPROXY=off"),
67 }
68 pkgs, err := packages.Load(cfg, *packagesFlag)
69 if err != nil {
70 t.Errorf("Load: %v", err)
71 }
72 // Report parse/type errors.
73 // Also, build transitive dependency mapping.
74 deps := make(map[string]*packages.Package) // key is PkgPath
75 packages.Visit(pkgs, nil, func(pkg *packages.Package) {
76 deps[pkg.Types.Path()] = pkg
77 for _, err := range pkg.Errors {
78 t.Fatal(err)
79 }
80 })
81
82 // Memoize repeated calls for same file.
83 fileContent := make(map[string][]byte)
84 readFile := func(filename string) ([]byte, error) {
85 content, ok := fileContent[filename]
86 if !ok {
87 var err error
88 content, err = os.ReadFile(filename)
89 if err != nil {
90 return nil, err
91 }
92 fileContent[filename] = content
93 }
94 return content, nil
95 }
96
97 for _, callerPkg := range pkgs {
98 // Find all static function calls in the package.
99 for _, callerFile := range callerPkg.Syntax {
100 noMutCheck := checkNoMutation(callerFile)
101 ast.Inspect(callerFile, func(n ast.Node) bool {
102 call, ok := n.(*ast.CallExpr)
103 if !ok {
104 return true
105 }
106 fn := typeutil.StaticCallee(callerPkg.TypesInfo, call)
107 if fn == nil {
108 return true
109 }
110
111 // Prepare caller info.
112 callPosn := callerPkg.Fset.PositionFor(call.Lparen, false)
113 callerContent, err := readFile(callPosn.Filename)
114 if err != nil {
115 t.Fatal(err)
116 }
117 caller := &inline.Caller{
118 Fset: callerPkg.Fset,
119 Types: callerPkg.Types,
120 Info: callerPkg.TypesInfo,
121 File: callerFile,
122 Call: call,
123 }
124
125 // Analyze callee.
126 calleePkg, ok := deps[fn.Pkg().Path()]
127 if !ok {
128 t.Fatalf("missing package for callee %v", fn)
129 }
130 calleePosn := callerPkg.Fset.PositionFor(fn.Pos(), false)
131 calleeDecl, err := findFuncByPosition(calleePkg, calleePosn)
132 if err != nil {
133 t.Fatal(err)
134 }
135 calleeContent, err := readFile(calleePosn.Filename)
136 if err != nil {
137 t.Fatal(err)
138 }
139
140 // Create a subtest for each inlining operation.
141 name := fmt.Sprintf("%s@%v", fn.Name(), filepath.Base(callPosn.String()))
142 t.Run(name, func(t *testing.T) {
143 // TODO(adonovan): add a panic handler.
144
145 t.Logf("callee declared at %v",
146 filepath.Base(calleePosn.String()))
147
148 t.Logf("run this command to reproduce locally:\n$ gopls codeaction -kind=refactor.inline -exec -diff %s:#%d",
149 callPosn.Filename, callPosn.Offset)
150
151 callee, err := inline.AnalyzeCallee(
152 t.Logf,
153 calleePkg.Fset,
154 calleePkg.Types,
155 calleePkg.TypesInfo,
156 calleeDecl,
157 calleeContent)
158 if err != nil {
159 // Ignore the expected kinds of errors.
160 for _, ignore := range []string{
161 "has no body",
162 "type parameters are not yet",
163 "line directives",
164 "cgo-generated",
165 } {
166 if strings.Contains(err.Error(), ignore) {
167 return
168 }
169 }
170 t.Fatalf("AnalyzeCallee: %v", err)
171 }
172 if err := checkTranscode(callee); err != nil {
173 t.Fatal(err)
174 }
175
176 res, err := inline.Inline(caller, callee, &inline.Options{
177 Logf: t.Logf,
178 })
179 if err != nil {
180 // Write error to a log, but this ok.
181 t.Log(err)
182 return
183 }
184
185 got, err := applyEdits(caller.Types, caller.File.FileStart, callerContent, res.Edits)
186 if err != nil {
187 t.Fatalf("can't apply inliner edits: %v", err)
188 }
189
190 // Print the diff.
191 t.Logf("Got diff:\n%s",
192 diff.Unified("old", "new", string(callerContent), string(got)))
193
194 // Parse and type-check the transformed source.
195 f, err := parser.ParseFile(caller.Fset, callPosn.Filename, got, parser.SkipObjectResolution)
196 if err != nil {
197 t.Fatalf("transformed source does not parse: %v", err)
198 }
199 // Splice into original file list.
200 syntax := slices.Clone(callerPkg.Syntax)
201 for i := range callerPkg.Syntax {
202 if syntax[i] == callerFile {
203 syntax[i] = f
204 break
205 }
206 }
207
208 var typeErrors []string
209 conf := &types.Config{
210 Error: func(err error) {
211 typeErrors = append(typeErrors, err.Error())
212 },
213 Importer: importerFunc(func(importPath string) (*types.Package, error) {
214 // Note: deps is properly keyed by package path,
215 // not import path, but we can't assume
216 // Package.Imports[importPath] exists in the
217 // case of newly added imports of indirect
218 // dependencies. Seems not to matter to this test.
219 dep, ok := deps[importPath]
220 if ok {
221 return dep.Types, nil
222 }
223 return nil, fmt.Errorf("missing package: %q", importPath)
224 }),
225 }
226 if _, err := conf.Check("p", caller.Fset, syntax, nil); err != nil {
227 t.Fatalf("transformed package has type errors:\n\n%s\n\nTransformed file:\n\n%s",
228 strings.Join(typeErrors, "\n"),
229 got)
230 }
231 })
232 return true
233 })
234 noMutCheck()
235 }
236 }
237 log.Printf("Analyzed %d packages", len(pkgs))
238 }
239
240 type importerFunc func(path string) (*types.Package, error)
241
242 func (f importerFunc) Import(path string) (*types.Package, error) {
243 return f(path)
244 }