Debian Codegraph @

internal/refactor/inline/inline_test.go

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches 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 "bytes"
9 "crypto/sha256"
10 "encoding/binary"
11 "encoding/gob"
12 "fmt"
13 "go/ast"
14 "go/parser"
15 "go/token"
16 "go/types"
17 "os"
18 "path/filepath"
19 "reflect"
20 "regexp"
21 "strings"
22 "testing"
23 "unsafe"
24
25 "golang.org/x/tools/go/ast/astutil"
26 "golang.org/x/tools/go/packages"
27 "golang.org/x/tools/go/types/typeutil"
28 "golang.org/x/tools/internal/analysis/driverutil"
29 "golang.org/x/tools/internal/diff"
30 "golang.org/x/tools/internal/expect"
31 "golang.org/x/tools/internal/refactor"
32 "golang.org/x/tools/internal/refactor/inline"
33 "golang.org/x/tools/internal/testenv"
34 "golang.org/x/tools/internal/testfiles"
35 "golang.org/x/tools/txtar"
36 )
37
38 // TestData executes test scenarios specified by files in testdata/*.txtar.
39 // Each txtar file describes two sets of files, some containing Go source
40 // and others expected results.
41 //
42 // The Go source files and go.mod are parsed and type-checked as a Go module.
43 // Some of these files contain marker comments (in a form described below) describing
44 // the inlinings to perform and whether they should succeed or fail. A marker
45 // indicating success refers to another file in the txtar, not a .go
46 // file, that should contain the contents of the first file after inlining.
47 //
48 // The marker format for success is
49 //
50 // @inline(re"pat", wantfile)
51 //
52 // The first call in the marker's line that matches pat is inlined, and the contents
53 // of the resulting file must match the contents of wantfile.
54 //
55 // The marker format for failure is
56 //
57 // @inline(re"pat", re"errpat")
58 //
59 // The first argument selects the call for inlining as before, and the second
60 // is a regular expression that must match the text of resulting error.
61 func TestData(t *testing.T) {
62 testenv.NeedsGoPackages(t)
63
64 files, err := filepath.Glob("testdata/*.txtar")
65 if err != nil {
66 t.Fatal(err)
67 }
68 for _, file := range files {
69 t.Run(filepath.Base(file), func(t *testing.T) {
70 t.Parallel()
71
72 // The few tests that use cgo should be in
73 // files whose name includes "cgo".
74 if strings.Contains(t.Name(), "cgo") {
75 testenv.NeedsTool(t, "cgo")
76 }
77
78 // Some tests need specific Go versions.
79 // TODO(adonovan): remove when go1.26 is assured.
80 if strings.HasSuffix(t.Name(), "newexpr.txtar") {
81 testenv.NeedsGo1Point(t, 26)
82 }
83
84 // Extract archive to temporary tree.
85 ar, err := txtar.ParseFile(file)
86 if err != nil {
87 t.Fatal(err)
88 }
89 fs, err := txtar.FS(ar)
90 if err != nil {
91 t.Fatal(err)
92 }
93 dir := testfiles.CopyToTmp(t, fs)
94
95 // Load packages.
96 cfg := &packages.Config{
97 Dir: dir,
98 Mode: packages.LoadAllSyntax,
99 Env: append(os.Environ(),
100 "GO111MODULES=on",
101 "GOPATH=",
102 "GOWORK=off",
103 "GOPROXY=off"),
104 }
105 pkgs, err := packages.Load(cfg, "./...")
106 if err != nil {
107 t.Errorf("Load: %v", err)
108 }
109 // Report parse/type errors; they may be benign.
110 packages.Visit(pkgs, nil, func(pkg *packages.Package) {
111 for _, err := range pkg.Errors {
112 t.Logf("warning: %v", err)
113 }
114 })
115
116 // Process @inline notes in comments in initial packages.
117 for _, pkg := range pkgs {
118 for _, file := range pkg.Syntax {
119 tokFile := pkg.Fset.File(file.FileStart)
120 // Read file content (for @inline regexp, and inliner).
121 content, err := os.ReadFile(tokFile.Name())
122 if err != nil {
123 t.Error(err)
124 continue
125 }
126
127 // Read and process @inline notes.
128 notes, err := expect.ExtractGo(tokFile, file)
129 if err != nil {
130 t.Errorf("parsing notes in %q: %v", tokFile.Name(), err)
131 continue
132 }
133 for _, note := range notes {
134 posn := tokFile.PositionFor(note.Pos, false)
135 if note.Name != "inline" {
136 t.Errorf("%s: invalid marker @%s", posn, note.Name)
137 continue
138 }
139 if nargs := len(note.Args); nargs != 2 {
140 t.Errorf("@inline: want 2 args, got %d", nargs)
141 continue
142 }
143 pattern, ok := note.Args[0].(*regexp.Regexp)
144 if !ok {
145 t.Errorf("%s: @inline(rx, want): want regular expression rx", posn)
146 continue
147 }
148
149 // want is a []byte (success) or *Regexp (failure)
150 var want any
151 switch x := note.Args[1].(type) {
152 case string, expect.Identifier:
153 name := fmt.Sprint(x)
154 for _, file := range ar.Files {
155 if file.Name == name {
156 want = file.Data
157 break
158 }
159 }
160 if want == nil {
161 t.Errorf("%s: @inline(rx, want): archive entry %q not found", posn, x)
162 continue
163 }
164 case *regexp.Regexp:
165 want = x
166 default:
167 t.Errorf("%s: @inline(rx, want): want file name (to assert success) or error message regexp (to assert failure)", posn)
168 continue
169 }
170 if err := doInlineNote(t.Logf, pkg, file, content, pattern, posn, want); err != nil {
171 t.Errorf("%s: @inline(%v, %v): %v", posn, note.Args[0], note.Args[1], err)
172 continue
173 }
174 }
175 }
176 }
177 })
178 }
179 }
180
181 // doInlineNote executes an assertion specified by a single
182 // @inline(re"pattern", want) note in a comment. It finds the first
183 // match of regular expression 'pattern' on the same line, finds the
184 // innermost enclosing CallExpr, and inlines it.
185 //
186 // Finally it checks that, on success, the transformed file is equal
187 // to want (a []byte), or on failure that the error message matches
188 // want (a *Regexp).
189 func doInlineNote(logf func(string, ...any), pkg *packages.Package, file *ast.File, content []byte, pattern *regexp.Regexp, posn token.Position, want any) error {
190 // Find extent of pattern match within commented line.
191 var startPos, endPos token.Pos
192 {
193 tokFile := pkg.Fset.File(file.FileStart)
194 lineStartOffset := int(tokFile.LineStart(posn.Line)) - tokFile.Base()
195 line := content[lineStartOffset:]
196 if i := bytes.IndexByte(line, '\n'); i >= 0 {
197 line = line[:i]
198 }
199 matches := pattern.FindSubmatchIndex(line)
200 var start, end int // offsets
201 switch len(matches) {
202 case 2:
203 // no subgroups: return the range of the regexp expression
204 start, end = matches[0], matches[1]
205 case 4:
206 // one subgroup: return its range
207 start, end = matches[2], matches[3]
208 default:
209 return fmt.Errorf("invalid location regexp %q: expect either 0 or 1 subgroups, got %d",
210 pattern, len(matches)/2-1)
211 }
212 startPos = tokFile.Pos(lineStartOffset + start)
213 endPos = tokFile.Pos(lineStartOffset + end)
214 }
215
216 // Find innermost call enclosing the pattern match.
217 var caller *inline.Caller
218 {
219 path, _ := astutil.PathEnclosingInterval(file, startPos, endPos)
220 for _, n := range path {
221 if call, ok := n.(*ast.CallExpr); ok {
222 caller = &inline.Caller{
223 Fset: pkg.Fset,
224 Types: pkg.Types,
225 Info: pkg.TypesInfo,
226 File: file,
227 Call: call,
228 }
229 break
230 }
231 }
232 if caller == nil {
233 return fmt.Errorf("no enclosing call")
234 }
235 }
236
237 // Is it a static function call?
238 fn := typeutil.StaticCallee(caller.Info, caller.Call)
239 if fn == nil {
240 return fmt.Errorf("cannot inline: not a static call")
241 }
242
243 // Find callee function.
244 var calleePkg *packages.Package
245 {
246 // Is the call within the package?
247 if fn.Pkg() == caller.Types {
248 calleePkg = pkg // same as caller
249 } else {
250 // Different package. Load it now.
251 // (The primary load loaded all dependencies,
252 // but we choose to load it again, with
253 // a distinct token.FileSet and types.Importer,
254 // to keep the implementation honest.)
255 cfg := &packages.Config{
256 // TODO(adonovan): get the original module root more cleanly
257 Dir: filepath.Dir(filepath.Dir(pkg.GoFiles[0])),
258 Fset: token.NewFileSet(),
259 Mode: packages.LoadSyntax,
260 }
261 roots, err := packages.Load(cfg, fn.Pkg().Path())
262 if err != nil {
263 return fmt.Errorf("loading callee package: %v", err)
264 }
265 if packages.PrintErrors(roots) > 0 {
266 return fmt.Errorf("callee package had errors") // (see log)
267 }
268 calleePkg = roots[0]
269 }
270 }
271
272 calleeDecl, err := findFuncByPosition(calleePkg, caller.Fset.PositionFor(fn.Pos(), false))
273 if err != nil {
274 return err
275 }
276
277 // Do the inlining. For the purposes of the test,
278 // AnalyzeCallee and Inline are a single operation.
279 res, err := func() (*inline.Result, error) {
280 filename := calleePkg.Fset.File(calleeDecl.Pos()).Name()
281 content, err := os.ReadFile(filename)
282 if err != nil {
283 return nil, err
284 }
285 callee, err := inline.AnalyzeCallee(
286 logf,
287 calleePkg.Fset,
288 calleePkg.Types,
289 calleePkg.TypesInfo,
290 calleeDecl,
291 content)
292 if err != nil {
293 return nil, err
294 }
295
296 if err := checkTranscode(callee); err != nil {
297 return nil, err
298 }
299
300 check := checkNoMutation(caller.File)
301 defer check()
302 return inline.Inline(caller, callee, &inline.Options{Logf: logf})
303 }()
304 if err != nil {
305 if wantRE, ok := want.(*regexp.Regexp); ok {
306 if !wantRE.MatchString(err.Error()) {
307 return fmt.Errorf("Inline failed with wrong error: %v (want error matching %q)", err, want)
308 }
309 return nil // expected error
310 }
311 return fmt.Errorf("Inline failed: %v", err) // success was expected
312 }
313
314 // Inline succeeded.
315 got, err := applyEdits(caller.Types, caller.File.FileStart, content, res.Edits)
316 if err != nil {
317 return err
318 }
319 if want, ok := want.([]byte); ok {
320 got = append(bytes.TrimSpace(got), '\n')
321 want = append(bytes.TrimSpace(want), '\n')
322 // If the "want" file begins "...", it need only be a substring of the "got" result,
323 // rather than an exact match.
324 if rest, ok := bytes.CutPrefix(want, []byte("...\n")); ok {
325 want = rest
326 if !bytes.Contains(got, want) {
327 return fmt.Errorf("Inline returned wrong output:\n%s\nWant substring:\n%s", got, want)
328 }
329 } else {
330 if diff := diff.Unified("want", "got", string(want), string(got)); diff != "" {
331 return fmt.Errorf("Inline returned wrong output:\n-- got --\n%s\n-- want --\n%s\n-- diff --\n%s",
332 got, want, diff)
333 }
334 }
335 return nil
336 }
337 return fmt.Errorf("Inline succeeded unexpectedly: want error matching %q, got <<%s>>", want, got)
338 }
339
340 // findFuncByPosition returns the FuncDecl at the specified (package-agnostic) position.
341 func findFuncByPosition(pkg *packages.Package, posn token.Position) (*ast.FuncDecl, error) {
342 same := func(decl *ast.FuncDecl) bool {
343 // We can't rely on columns in export data:
344 // some variants replace it with 1.
345 // We can't expect file names to have the same prefix.
346 // export data for go1.20 std packages have $GOROOT written in
347 // them, so how are we supposed to find the source? Yuck!
348 // Ugh. need to samefile? Nope $GOROOT just won't work
349 // This is highly client specific anyway.
350 posn2 := pkg.Fset.PositionFor(decl.Name.Pos(), false)
351 return posn.Filename == posn2.Filename &&
352 posn.Line == posn2.Line
353 }
354 for _, file := range pkg.Syntax {
355 for _, decl := range file.Decls {
356 if decl, ok := decl.(*ast.FuncDecl); ok && same(decl) {
357 return decl, nil
358 }
359 }
360 }
361 return nil, fmt.Errorf("can't find FuncDecl at %v in package %q", posn, pkg.PkgPath)
362 }
363
364 // Each callee must declare a function or method named f,
365 // and each caller must call it.
366 const funcName = "f"
367
368 // A testcase is an item in a table-driven test.
369 //
370 // The table-driven tests are less flexible, but enable more compact
371 // expression of single-package test cases than is possible with the
372 // txtar notation.
373 //
374 // TODO(adonovan): improve coverage of the cross product of each
375 // strategy with the checklist of concerns enumerated in the package
376 // doc comment.
377 type testcase struct {
378 descr string // description; substrings enable test or inliner options (e.g. "IgnoreEffects", "NoPackageClause")
379 callee, caller string // Go source files (sans package decl) of caller, callee
380 want string // expected new portion of caller file, or "error: regexp"
381 }
382
383 func TestErrors(t *testing.T) {
384 runTests(t, []testcase{
385 {
386 "Inference of type parameters is not yet supported.",
387 `func f[T any](x T) T { return x }`,
388 `var _ = f(0)`,
389 `error: type parameter inference is not yet supported`,
390 },
391 {
392 "Methods on generic types are not yet supported.",
393 `type G[T any] struct{}; func (G[T]) f(x T) T { return x }`,
394 `var _ = G[int]{}.f(0)`,
395 `error: generic methods not yet supported`,
396 },
397 {
398 "[NoPackageClause] Can't inline a callee using newer Go to a caller using older Go (#75726).",
399 "//go:build go1.23\n\npackage p\nfunc f() int { return 0 }",
400 "//go:build go1.22\n\npackage p\nvar _ = f()",
401 `error: cannot inline call to p.f \(declared using go1.23\) into a file using go1.22`,
402 },
403 })
404 }
405
406 func TestBasics(t *testing.T) {
407 runTests(t, []testcase{
408 {
409 "Basic",
410 `func f(x int) int { return x }`,
411 `var _ = f(0)`,
412 `var _ = 0`,
413 },
414 {
415 "Empty body, no arg effects.",
416 `func f(x, y int) {}`,
417 `func _() { f(1, 2) }`,
418 `func _() {}`,
419 },
420 {
421 "Empty body, some arg effects.",
422 `func f(x, y, z int) {}`,
423 `func _() { f(1, recover().(int), 3) }`,
424 `func _() { _ = recover().(int) }`,
425 },
426 {
427 "Non-duplicable arguments are not substituted even if pure.",
428 `func f(s string, i int) { print(s, s, i, i) }`,
429 `func _() { f("hi", 0) }`,
430 `func _() {
431 var s string = "hi"
432 print(s, s, 0, 0)
433 }`,
434 },
435 {
436 "Workaround for T(x) misformatting (#63362).",
437 `func f(ch <-chan int) { <-ch }`,
438 `func _(ch chan int) { f(ch) }`,
439 `func _(ch chan int) { <-(<-chan int)(ch) }`,
440 },
441 {
442 // (a regression test for unnecessary braces)
443 "In block elision, blank decls don't count when computing name conflicts.",
444 `func f(x int) { var _ = x; var _ = 3 }`,
445 `func _() { var _ = 1; f(2) }`,
446 `func _() {
447 var _ = 1
448 var _ = 2
449 var _ = 3
450 }`,
451 },
452 {
453 // (a regression test for a missing conversion)
454 "Implicit return conversions are inserted in expr-context reduction.",
455 `func f(x int) error { return nil }`,
456 `func _() { if err := f(0); err != nil {} }`,
457 `func _() {
458 if err := error(nil); err != nil {
459 }
460 }`,
461 },
462 {
463 "Explicit type parameters.",
464 `func f[T any](x T) T { return x }`,
465 `var _ = f[int](0)`,
466 // TODO(jba): remove the unnecessary conversion.
467 `var _ = int(0)`,
468 },
469 })
470 }
471
472 func TestDuplicable(t *testing.T) {
473 t.Run("basic", func(t *testing.T) {
474 runTests(t, []testcase{
475 {
476 "Empty strings are duplicable.",
477 `func f(s string) { print(s, s) }`,
478 `func _() { f("") }`,
479 `func _() { print("", "") }`,
480 },
481 {
482 "Non-empty string literals are not duplicable.",
483 `func f(s string) { print(s, s) }`,
484 `func _() { f("hi") }`,
485 `func _() {
486 var s string = "hi"
487 print(s, s)
488 }`,
489 },
490 {
491 "Empty array literals are duplicable.",
492 `func f(a [2]int) { print(a, a) }`,
493 `func _() { f([2]int{}) }`,
494 `func _() { print([2]int{}, [2]int{}) }`,
495 },
496 {
497 "Non-empty array literals are not duplicable.",
498 `func f(a [2]int) { print(a, a) }`,
499 `func _() { f([2]int{1, 2}) }`,
500 `func _() {
501 var a [2]int = [2]int{1, 2}
502 print(a, a)
503 }`,
504 },
505 {
506 "Empty struct literals are duplicable.",
507 `func f(s S) { print(s, s) }; type S struct { x int }`,
508 `func _() { f(S{}) }`,
509 `func _() { print(S{}, S{}) }`,
510 },
511 {
512 "Non-empty struct literals are not duplicable.",
513 `func f(s S) { print(s, s) }; type S struct { x int }`,
514 `func _() { f(S{x: 1}) }`,
515 `func _() {
516 var s S = S{x: 1}
517 print(s, s)
518 }`,
519 },
520 })
521 })
522
523 t.Run("conversions", func(t *testing.T) {
524 runTests(t, []testcase{
525 {
526 "Conversions to integer are duplicable.",
527 `func f(i int) { print(i, i) }`,
528 `func _() { var i int8 = 1; f(int(i)) }`,
529 `func _() { var i int8 = 1; print(int(i), int(i)) }`,
530 },
531 {
532 "Implicit conversions from underlying types are duplicable.",
533 `func f(i I) { print(i, i) }; type I int; func print(args ...any) {}`,
534 `func _() { f(1) }`,
535 `func _() { print(I(1), I(1)) }`,
536 },
537 {
538 "Conversions to array are duplicable.",
539 `func f(a [2]int) { print(a, a) }; type A [2]int`,
540 `func _() { var a A; f([2]int(a)) }`,
541 `func _() { var a A; print([2]int(a), [2]int(a)) }`,
542 },
543 {
544 "Conversions from array are duplicable.",
545 `func f(a A) { print(a, a) }; type A [2]int`,
546 `func _() { var a [2]int; f(A(a)) }`,
547 `func _() { var a [2]int; print(A(a), A(a)) }`,
548 },
549 {
550 "Conversions from byte slice to string are duplicable.",
551 `func f(s string) { print(s, s) }`,
552 `func _() { var b []byte; f(string(b)) }`,
553 `func _() { var b []byte; print(string(b), string(b)) }`,
554 },
555 {
556 "Conversions from string to byte slice are not duplicable.",
557 `func f(b []byte) { print(b, b) }`,
558 `func _() { var s string; f([]byte(s)) }`,
559 `func _() {
560 var s string
561 var b []byte = []byte(s)
562 print(b, b)
563 }`,
564 },
565 {
566 "Conversions from string to uint8 slice are not duplicable.",
567 `func f(b []uint8) { print(b, b) }`,
568 `func _() { var s string; f([]uint8(s)) }`,
569 `func _() {
570 var s string
571 var b []uint8 = []uint8(s)
572 print(b, b)
573 }`,
574 },
575 {
576 "Conversions from string to rune slice are not duplicable.",
577 `func f(r []rune) { print(r, r) }`,
578 `func _() { var s string; f([]rune(s)) }`,
579 `func _() {
580 var s string
581 var r []rune = []rune(s)
582 print(r, r)
583 }`,
584 },
585 {
586 "Conversions from string to named type with underlying byte slice are not duplicable.",
587 `func f(b B) { print(b, b) }; type B []byte`,
588 `func _() { var s string; f(B(s)) }`,
589 `func _() {
590 var s string
591 var b B = B(s)
592 print(b, b)
593 }`,
594 },
595 {
596 "Conversions from string to named type of string are duplicable.",
597 `func f(s S) { print(s, s) }; type S string`,
598 `func _() { var s string; f(S(s)) }`,
599 `func _() { var s string; print(S(s), S(s)) }`,
600 },
601 {
602 "Built-in function calls are not duplicable.",
603 `func f(i int) { print(i, i) }`,
604 `func _() { f(len("")) }`,
605 `func _() {
606 var i int = len("")
607 print(i, i)
608 }`,
609 },
610 {
611 "Built-in function calls are not duplicable.",
612 `func f(c complex128) { print(c, c) }`,
613 `func _() { f(complex(1.0, 2.0)) }`,
614 `func _() {
615 var c complex128 = complex(1.0, 2.0)
616 print(c, c)
617 }`,
618 },
619 {
620 "Non built-in function calls are not duplicable.",
621 `func f(i int) { print(i, i) }
622 //go:noinline
623 func f1(i int) int { return i + 1 }`,
624 `func _() { f(f1(1)) }`,
625 `func _() {
626 var i int = f1(1)
627 print(i, i)
628 }`,
629 },
630 {
631 "Conversions between function types are duplicable.",
632 `func f(f F) { print(f, f) }; type F func(); func f1() {}`,
633 `func _() { f(F(f1)) }`,
634 `func _() { print(F(f1), F(f1)) }`,
635 },
636 })
637 })
638 }
639
640 func TestExprStmtReduction(t *testing.T) {
641 runTests(t, []testcase{
642 {
643 "A call in an unrestricted ExprStmt may be replaced by the body stmts.",
644 `func f() { var _ = len("") }`,
645 `func _() { f() }`,
646 `func _() { var _ = len("") }`,
647 },
648 {
649 "ExprStmts in the body of a switch case are unrestricted.",
650 `func f() { x := 1; print(x) }`,
651 `func _() { switch { case true: f() } }`,
652 `func _() {
653 switch {
654 case true:
655 x := 1
656 print(x)
657 }
658 }`,
659 },
660 {
661 "ExprStmts in the body of a select case are unrestricted.",
662 `func f() { x := 1; print(x) }`,
663 `func _() { select { default: f() } }`,
664 `func _() {
665 select {
666 default:
667 x := 1
668 print(x)
669 }
670 }`,
671 },
672 {
673 "Some ExprStmt contexts are restricted to simple statements.",
674 `func f() { var _ = len("") }`,
675 `func _(cond bool) { if f(); cond {} }`,
676 `func _(cond bool) {
677 if func() { var _ = len("") }(); cond {
678 }
679 }`,
680 },
681 {
682 "Braces must be preserved to avoid a name conflict (decl before).",
683 `func f() { x := 1; print(x) }`,
684 `func _() { x := 2; print(x); f() }`,
685 `func _() {
686 x := 2
687 print(x)
688 {
689 x := 1
690 print(x)
691 }
692 }`,
693 },
694 {
695 "Braces must be preserved to avoid a name conflict (decl after).",
696 `func f() { x := 1; print(x) }`,
697 `func _() { f(); x := 2; print(x) }`,
698 `func _() {
699 {
700 x := 1
701 print(x)
702 }
703 x := 2
704 print(x)
705 }`,
706 },
707 {
708 "Braces must be preserved to avoid a forward jump across a decl.",
709 `func f() { x := 1; print(x) }`,
710 `func _() { goto label; f(); label: }`,
711 `func _() {
712 goto label
713 {
714 x := 1
715 print(x)
716 }
717 label:
718 }`,
719 },
720 })
721 }
722
723 func TestPrecedenceParens(t *testing.T) {
724 // Ensure that parens are inserted when (and only when) necessary
725 // around the replacement for the call expression. (This is a special
726 // case in the way the inliner uses a combination of AST formatting
727 // for the call and text splicing for the rest of the file.)
728 runTests(t, []testcase{
729 {
730 "Multiplication in addition context (no parens).",
731 `func f(x, y int) int { return x * y }`,
732 `func _() { _ = 1 + f(2, 3) }`,
733 `func _() { _ = 1 + 2*3 }`,
734 },
735 {
736 "Addition in multiplication context (parens).",
737 `func f(x, y int) int { return x + y }`,
738 `func _() { _ = 1 * f(2, 3) }`,
739 `func _() { _ = 1 * (2 + 3) }`,
740 },
741 {
742 "Addition in negation context (parens).",
743 `func f(x, y int) int { return x + y }`,
744 `func _() { _ = -f(1, 2) }`,
745 `func _() { _ = -(1 + 2) }`,
746 },
747 {
748 "Addition in call context (no parens).",
749 `func f(x, y int) int { return x + y }`,
750 `func _() { println(f(1, 2)) }`,
751 `func _() { println(1 + 2) }`,
752 },
753 {
754 "Addition in slice operand context (parens).",
755 `func f(x, y string) string { return x + y }`,
756 `func _() { _ = f("x", "y")[1:2] }`,
757 `func _() { _ = ("x" + "y")[1:2] }`,
758 },
759 {
760 "String literal in slice operand context (no parens).",
761 `func f(x string) string { return x }`,
762 `func _() { _ = f("xy")[1:2] }`,
763 `func _() { _ = "xy"[1:2] }`,
764 },
765 })
766 }
767
768 func TestSubstitution(t *testing.T) {
769 runTests(t, []testcase{
770 {
771 "Arg to unref'd param can be eliminated if has no effects.",
772 `func f(x, y int) {}; var global int`,
773 `func _() { f(0, global) }`,
774 `func _() {}`,
775 },
776 {
777 "But not if it may contain last reference to a caller local var.",
778 `func f(int) {}`,
779 `func _() { var local int; f(local) }`,
780 `func _() { var local int; _ = local }`,
781 },
782 {
783 "Arguments that are used are detected",
784 `func f(int) {}`,
785 `func _() { var local int; _ = local; f(local) }`,
786 `func _() { var local int; _ = local }`,
787 },
788 {
789 "Arguments that are used by other arguments are detected",
790 `func f(x, y int) { print(x) }`,
791 `func _() { var z int; f(z, z) }`,
792 `func _() { var z int; print(z) }`,
793 },
794 {
795 "Arguments that are used by other variadic arguments are detected",
796 `func f(x int, ys ...int) { print(ys) }`,
797 `func _() { var z int; f(z, 1, 2, 3, z) }`,
798 `func _() { var z int; print([]int{1, 2, 3, z}) }`,
799 },
800 {
801 "Arguments that are used by other variadic arguments are detected, 2",
802 `func f(x int, ys ...int) { print(ys) }`,
803 `func _() { var z int; f(z) }`,
804 `func _() {
805 var z int
806 var _ int = z
807 print([]int{})
808 }`,
809 },
810 {
811 "Function parameters are always used",
812 `func f(int) {}`,
813 `func _() {
814 func(local int) {
815 f(local)
816 }(1)
817 }`,
818 `func _() {
819 func(local int) {
820
821 }(1)
822 }`,
823 },
824 {
825 "Regression test for detection of shadowing in nested functions.",
826 `func f(x int) { _ = func() { y := 1; print(y); print(x) } }`,
827 `func _(y int) { f(y) } `,
828 `func _(y int) {
829 var x int = y
830 _ = func() { y := 1; print(y); print(x) }
831 }`,
832 },
833 })
834 }
835
836 func TestTailCallStrategy(t *testing.T) {
837 runTests(t, []testcase{
838 {
839 "simple",
840 `func f() int { return 1 }`,
841 `func _() int { return f() }`,
842 `func _() int { return 1 }`,
843 },
844 {
845 "void",
846 `func f() { println() }`,
847 `func _() { f() }`,
848 `func _() { println() }`,
849 },
850 {
851 "void with defer", // => literalized
852 `func f() { defer f(); println() }`,
853 `func _() { f() }`,
854 `func _() { func() { defer f(); println() }() }`,
855 },
856 // Tests for issue #63336:
857 {
858 "non-trivial return conversion (caller.sig = callee.sig)",
859 `func f() error { if true { return nil } else { return e } }; var e struct{error}`,
860 `func _() error { return f() }`,
861 `func _() error {
862 if true {
863 return nil
864 } else {
865 return e
866 }
867 }`,
868 },
869 {
870 "non-trivial return conversion (caller.sig != callee.sig)",
871 `func f() error { return E{} }; type E struct{error}`,
872 `func _() any { return f() }`,
873 `func _() any { return error(E{}) }`,
874 },
875 })
876 }
877
878 func TestSpreadCalls(t *testing.T) {
879 runTests(t, []testcase{
880 {
881 "Edge case: cannot literalize spread method call.",
882 `type I int
883 func g() (I, I)
884 func (r I) f(x, y I) I {
885 defer g() // force literalization
886 return x + y + r
887 }`,
888 `func _() I { return recover().(I).f(g()) }`,
889 `error: can't yet inline spread call to method`,
890 },
891 {
892 "Spread argument evaluated for effect.",
893 `func f(int, int) {}; func g() (int, int)`,
894 `func _() { f(g()) }`,
895 `func _() { _, _ = g() }`,
896 },
897 {
898 "Edge case: receiver and spread argument, both evaluated for effect.",
899 `type T int; func (T) f(int, int) {}; func g() (int, int)`,
900 `func _() { T(0).f(g()) }`,
901 `func _() {
902 var (
903 _ = T(0)
904 _, _ = g()
905 )
906 }`,
907 },
908 {
909 "Spread call in return (#63398).",
910 `func f() (int, error) { return 0, nil }`,
911 `func _() (int, error) { return f() }`,
912 `func _() (int, error) { return 0, nil }`,
913 },
914 })
915 }
916
917 func TestAssignmentCallStrategy(t *testing.T) {
918 runTests(t, []testcase{
919 {
920 "splice: basic",
921 `func f(x int) (int, int) { return x, 2 }`,
922 `func _() { x, y := f(1); _, _ = x, y }`,
923 `func _() { x, y := 1, 2; _, _ = x, y }`,
924 },
925 {
926 "spread: basic",
927 `func f(x int) (any, any) { return g() }; func g() (error, error) { return nil, nil }`,
928 `func _() {
929 var x any
930 x, y := f(0)
931 _, _ = x, y
932 }`,
933 `func _() {
934 var x any
935 var y any
936 x, y = g()
937 _, _ = x, y
938 }`,
939 },
940 {
941 "spread: free var conflict",
942 `func f(x int) (any, any) { return g(x) }; func g(x int) (int, int) { return x, x }`,
943 `func _() {
944 y := 2
945 {
946 var x any
947 x, y := f(y)
948 _, _ = x, y
949 }
950 }`,
951 `func _() {
952 y := 2
953 {
954 var x any
955 x, y := func() (any, any) { return g(y) }()
956 _, _ = x, y
957 }
958 }`,
959 },
960 {
961 "convert: basic",
962 `func f(x int) (int32, int8) { return 1, 2 }`,
963 `func _() {
964 var x int32
965 x, y := f(0)
966 _, _ = x, y
967 }`,
968 `func _() {
969 var x int32
970 x, y := 1, int8(2)
971 _, _ = x, y
972 }`,
973 },
974 {
975 "convert: rune and byte",
976 `func f(x int) (rune, byte) { return 0, 0 }`,
977 `func _() {
978 x, y := f(0)
979 _, _ = x, y
980 }`,
981 `func _() {
982 x, y := rune(0), byte(0)
983 _, _ = x, y
984 }`,
985 },
986 {
987 "convert: interface conversions",
988 `func f(x int) (_, _ error) { return nil, nil }`,
989 `func _() {
990 x, y := f(0)
991 _, _ = x, y
992 }`,
993 `func _() {
994 x, y := error(nil), error(nil)
995 _, _ = x, y
996 }`,
997 },
998 {
999 "convert: implicit nil conversions",
1000 `func f(x int) (_, _ error) { return nil, nil }`,
1001 `func _() { x, y := f(0); _, _ = x, y }`,
1002 `func _() { x, y := error(nil), error(nil); _, _ = x, y }`,
1003 },
1004 {
1005 "convert: pruning nil assignments left",
1006 `func f(x int) (_, _ error) { return nil, nil }`,
1007 `func _() { _, y := f(0); _ = y }`,
1008 `func _() { y := error(nil); _ = y }`,
1009 },
1010 {
1011 "convert: pruning nil assignments right",
1012 `func f(x int) (_, _ error) { return nil, nil }`,
1013 `func _() { x, _ := f(0); _ = x }`,
1014 `func _() { x := error(nil); _ = x }`,
1015 },
1016 {
1017 "convert: partial assign",
1018 `func f(x int) (_, _ error) { return nil, nil }`,
1019 `func _() {
1020 var x error
1021 x, y := f(0)
1022 _, _ = x, y
1023 }`,
1024 `func _() {
1025 var x error
1026 x, y := nil, error(nil)
1027 _, _ = x, y
1028 }`,
1029 },
1030 {
1031 "convert: single assignment left",
1032 `func f() int { return 0 }`,
1033 `func _() {
1034 x, y := f(), "hello"
1035 _, _ = x, y
1036 }`,
1037 `func _() {
1038 x, y := 0, "hello"
1039 _, _ = x, y
1040 }`,
1041 },
1042 {
1043 "convert: single assignment left with conversion",
1044 `func f() int32 { return 0 }`,
1045 `func _() {
1046 x, y := f(), "hello"
1047 _, _ = x, y
1048 }`,
1049 `func _() {
1050 x, y := int32(0), "hello"
1051 _, _ = x, y
1052 }`,
1053 },
1054 {
1055 "convert: single assignment right",
1056 `func f() int32 { return 0 }`,
1057 `func _() {
1058 x, y := "hello", f()
1059 _, _ = x, y
1060 }`,
1061 `func _() {
1062 x, y := "hello", int32(0)
1063 _, _ = x, y
1064 }`,
1065 },
1066 {
1067 "convert: single assignment middle",
1068 `func f() int32 { return 0 }`,
1069 `func _() {
1070 x, y, z := "hello", f(), 1.56
1071 _, _, _ = x, y, z
1072 }`,
1073 `func _() {
1074 x, y, z := "hello", int32(0), 1.56
1075 _, _, _ = x, y, z
1076 }`,
1077 },
1078 })
1079 }
1080
1081 func TestVariadic(t *testing.T) {
1082 runTests(t, []testcase{
1083 {
1084 "Variadic cancellation (basic).",
1085 `func f(args ...any) { defer f(&args); println(args) }`,
1086 `func _(slice []any) { f(slice...) }`,
1087 `func _(slice []any) { func() { var args []any = slice; defer f(&args); println(args) }() }`,
1088 },
1089 {
1090 "Variadic cancellation (literalization with parameter elimination).",
1091 `func f(args ...any) { defer f(); println(args) }`,
1092 `func _(slice []any) { f(slice...) }`,
1093 `func _(slice []any) { func() { defer f(); println(slice) }() }`,
1094 },
1095 {
1096 "Variadic cancellation (reduction).",
1097 `func f(args ...any) { println(args) }`,
1098 `func _(slice []any) { f(slice...) }`,
1099 `func _(slice []any) { println(slice) }`,
1100 },
1101 {
1102 "Undo variadic elimination",
1103 `func f(args ...int) []int { return append([]int{1}, args...) }`,
1104 `func _(a, b int) { f(a, b) }`,
1105 `func _(a, b int) { _ = append([]int{1}, a, b) }`,
1106 },
1107 {
1108 "Variadic elimination (literalization).",
1109 `func f(x any, rest ...any) { defer println(x, rest) }`, // defer => literalization
1110 `func _() { f(1, 2, 3) }`,
1111 `func _() { func() { defer println(1, []any{2, 3}) }() }`,
1112 },
1113 {
1114 "Variadic elimination (reduction).",
1115 `func f(x int, rest ...int) { println(x, rest) }`,
1116 `func _() { f(1, 2, 3) }`,
1117 `func _() { println(1, []int{2, 3}) }`,
1118 },
1119 {
1120 "Spread call to variadic (1 arg, 1 param).",
1121 `func f(rest ...int) { println(rest) }; func g() (a, b int)`,
1122 `func _() { f(g()) }`,
1123 `func _() { func(rest ...int) { println(rest) }(g()) }`,
1124 },
1125 {
1126 "Spread call to variadic (1 arg, 2 params).",
1127 `func f(x int, rest ...int) { println(x, rest) }; func g() (a, b int)`,
1128 `func _() { f(g()) }`,
1129 `func _() { func(x int, rest ...int) { println(x, rest) }(g()) }`,
1130 },
1131 {
1132 "Spread call to variadic (1 arg, 3 params).",
1133 `func f(x, y int, rest ...int) { println(x, y, rest) }; func g() (a, b, c int)`,
1134 `func _() { f(g()) }`,
1135 `func _() { func(x, y int, rest ...int) { println(x, y, rest) }(g()) }`,
1136 },
1137 })
1138 }
1139
1140 func TestParameterBindingDecl(t *testing.T) {
1141 runTests(t, []testcase{
1142 {
1143 "IncDec counts as assignment.",
1144 `func f(x int) { x++ }`,
1145 `func _() { f(1) }`,
1146 `func _() {
1147 var x int = 1
1148 x++
1149 }`,
1150 },
1151 {
1152 "Binding declaration (x, y, z eliminated).",
1153 `func f(w, x, y any, z int) { println(w, y, z) }; func g(int) int`,
1154 `func _() { f(g(0), g(1), g(2), g(3)) }`,
1155 `func _() {
1156 var w, _ any = g(0), g(1)
1157 println(w, g(2), g(3))
1158 }`,
1159 },
1160 {
1161 "Reduction of stmt-context call to { return exprs }, with substitution",
1162 `func f(ch chan int) int { return <-ch }; func g() chan int`,
1163 `func _() { f(g()) }`,
1164 `func _() { <-g() }`,
1165 },
1166 {
1167 // Same again, with callee effects:
1168 "Binding decl in reduction of stmt-context call to { return exprs }",
1169 `func f(x int) int { return <-h(g(2), x) }; func g(int) int; func h(int, int) chan int`,
1170 `func _() { f(g(1)) }`,
1171 `func _() {
1172 var x int = g(1)
1173 <-h(g(2), x)
1174 }`,
1175 },
1176 {
1177 "No binding decl due to shadowing of int",
1178 `func f(int, y any, z int) { defer g(0); println(int, y, z) }; func g(int) int`,
1179 `func _() { f(g(1), g(2), g(3)) }`,
1180 `func _() { func(int, y any, z int) { defer g(0); println(int, y, z) }(g(1), g(2), g(3)) }`,
1181 },
1182 {
1183 "An indirect method selection (*x).g acts as a read.",
1184 `func f(x *T, y any) any { return x.g(y) }; type T struct{}; func (T) g(x any) any { return x }`,
1185 `func _(x *T) { f(x, recover()) }`,
1186 `func _(x *T) {
1187 var y any = recover()
1188 x.g(y)
1189 }`,
1190 },
1191 {
1192 "A direct method selection x.g is pure.",
1193 `func f(x *T, y any) any { return x.g(y) }; type T struct{}; func (*T) g(x any) any { return x }`,
1194 `func _(x *T) { f(x, recover()) }`,
1195 `func _(x *T) { x.g(recover()) }`,
1196 },
1197 {
1198 "Literalization can make use of a binding decl (all params).",
1199 `func f(x, y int) int { defer println(); return y + x }; func g(int) int`,
1200 `func _() { println(f(g(1), g(2))) }`,
1201 `func _() { println(func() int { var x, y int = g(1), g(2); defer println(); return y + x }()) }`,
1202 },
1203 {
1204 "Literalization can make use of a binding decl (some params).",
1205 `func f(x, y int) int { z := y + x; defer println(); return z }; func g(int) int`,
1206 `func _() { println(f(g(1), g(2))) }`,
1207 `func _() { println(func() int { var x int = g(1); z := g(2) + x; defer println(); return z }()) }`,
1208 },
1209 {
1210 "Literalization can't yet use of a binding decl if named results.",
1211 `func f(x, y int) (z int) { z = y + x; defer println(); return }; func g(int) int`,
1212 `func _() { println(f(g(1), g(2))) }`,
1213 `func _() { println(func(x int) (z int) { z = g(2) + x; defer println(); return }(g(1))) }`,
1214 },
1215 })
1216 }
1217
1218 func TestEmbeddedFields(t *testing.T) {
1219 runTests(t, []testcase{
1220 {
1221 "Embedded fields in x.f method selection (direct).",
1222 `type T int; func (t T) f() { print(t) }; type U struct{ T }`,
1223 `func _(u U) { u.f() }`,
1224 `func _(u U) { print(u.T) }`,
1225 },
1226 {
1227 "Embedded fields in x.f method selection (implicit *).",
1228 `type ( T int; U struct{*T}; V struct {U} ); func (t T) f() { print(t) }`,
1229 `func _(v V) { v.f() }`,
1230 `func _(v V) { print(*v.U.T) }`,
1231 },
1232 {
1233 "Embedded fields in x.f method selection (implicit &).",
1234 `type ( T int; U struct{T}; V struct {U} ); func (t *T) f() { print(t) }`,
1235 `func _(v V) { v.f() }`,
1236 `func _(v V) { print(&v.U.T) }`,
1237 },
1238 // Now the same tests again with T.f(recv).
1239 {
1240 "Embedded fields in T.f method selection.",
1241 `type T int; func (t T) f() { print(t) }; type U struct{ T }`,
1242 `func _(u U) { U.f(u) }`,
1243 `func _(u U) { print(u.T) }`,
1244 },
1245 {
1246 "Embedded fields in T.f method selection (implicit *).",
1247 `type ( T int; U struct{*T}; V struct {U} ); func (t T) f() { print(t) }`,
1248 `func _(v V) { V.f(v) }`,
1249 `func _(v V) { print(*v.U.T) }`,
1250 },
1251 {
1252 "Embedded fields in (*T).f method selection.",
1253 `type ( T int; U struct{T}; V struct {U} ); func (t *T) f() { print(t) }`,
1254 `func _(v V) { (*V).f(&v) }`,
1255 `func _(v V) { print(&(&v).U.T) }`,
1256 },
1257 {
1258 // x is a single-assign var, and x.f does not load through a pointer
1259 // (despite types.Selection.Indirect=true), so x is pure.
1260 "No binding decl is required for recv in method-to-method calls.",
1261 `type T struct{}; func (x *T) f() { g(); print(*x) }; func g()`,
1262 `func (x *T) _() { x.f() }`,
1263 `func (x *T) _() {
1264 g()
1265 print(*x)
1266 }`,
1267 },
1268 {
1269 "Same, with implicit &recv.",
1270 `type T struct{}; func (x *T) f() { g(); print(*x) }; func g()`,
1271 `func (x T) _() { x.f() }`,
1272 `func (x T) _() {
1273 {
1274 var x *T = &x
1275 g()
1276 print(*x)
1277 }
1278 }`,
1279 },
1280 })
1281 }
1282
1283 func TestSubstitutionGroups(t *testing.T) {
1284 runTests(t, []testcase{
1285 {
1286 // b -> a
1287 "Basic",
1288 `func f(a, b int) { print(a, b) }`,
1289 `func _() { var a int; f(a, a) }`,
1290 `func _() { var a int; print(a, a) }`,
1291 },
1292 {
1293 // a <-> b
1294 "Cocycle",
1295 `func f(a, b int) { print(a, b) }`,
1296 `func _() { var a, b int; f(a+b, a+b) }`,
1297 `func _() { var a, b int; print(a+b, a+b) }`,
1298 },
1299 {
1300 // a <-> b
1301 // a -> c
1302 // Don't compute b as substitutable due to bad cycle traversal.
1303 "Middle cycle",
1304 `func f(a, b, c int) { var d int; print(a, b, c, d) }`,
1305 `func _() { var a, b, c, d int; f(a+b+c, a+b, d) }`,
1306 `func _() {
1307 var a, b, c, d int
1308 {
1309 var a, b, c int = a + b + c, a + b, d
1310 var d int
1311 print(a, b, c, d)
1312 }
1313 }`,
1314 },
1315 {
1316 // a -> b
1317 // b -> c
1318 // b -> d
1319 // c
1320 //
1321 // Only c should be substitutable.
1322 "Singleton",
1323 `func f(a, b, c, d int) { var e int; print(a, b, c, d, e) }`,
1324 `func _() { var a, b, c, d, e int; f(a+b, c+d, c, e) }`,
1325 `func _() {
1326 var a, b, c, d, e int
1327 {
1328 var a, b, d int = a + b, c + d, e
1329 var e int
1330 print(a, b, c, d, e)
1331 }
1332 }`,
1333 },
1334 })
1335 }
1336
1337 func TestSubstitutionPreservesArgumentEffectOrder(t *testing.T) {
1338 runTests(t, []testcase{
1339 {
1340 "Arguments have effects, but parameters are evaluated in order.",
1341 `func f(a, b, c int) { print(a, b, c) }; func g(int) int`,
1342 `func _() { f(g(1), g(2), g(3)) }`,
1343 `func _() { print(g(1), g(2), g(3)) }`,
1344 },
1345 {
1346 "Arguments have effects, and parameters are evaluated out of order.",
1347 `func f(a, b, c int) { print(a, c, b) }; func g(int) int`,
1348 `func _() { f(g(1), g(2), g(3)) }`,
1349 `func _() {
1350 var a, b int = g(1), g(2)
1351 print(a, g(3), b)
1352 }`,
1353 },
1354 {
1355 "Pure arguments may commute with argument that have effects.",
1356 `func f(a, b, c int) { print(a, c, b) }; func g(int) int`,
1357 `func _() { f(g(1), 2, g(3)) }`,
1358 `func _() { print(g(1), g(3), 2) }`,
1359 },
1360 {
1361 "Impure arguments may commute with each other.",
1362 `func f(a, b, c, d int) { print(a, c, b, d) }; func g(int) int; var x, y int`,
1363 `func _() { f(g(1), x, y, g(2)) }`,
1364 `func _() { print(g(1), y, x, g(2)) }`,
1365 },
1366 {
1367 "Impure arguments do not commute with arguments that have effects (1)",
1368 `func f(a, b, c, d int) { print(a, c, b, d) }; func g(int) int; var x, y int`,
1369 `func _() { f(g(1), g(2), y, g(3)) }`,
1370 `func _() {
1371 var a, b int = g(1), g(2)
1372 print(a, y, b, g(3))
1373 }`,
1374 },
1375 {
1376 "Impure arguments do not commute with those that have effects (2).",
1377 `func f(a, b, c, d int) { print(a, c, b, d) }; func g(int) int; var x, y int`,
1378 `func _() { f(g(1), y, g(2), g(3)) }`,
1379 `func _() {
1380 var a, b int = g(1), y
1381 print(a, g(2), b, g(3))
1382 }`,
1383 },
1384 {
1385 "Callee effects commute with pure arguments.",
1386 `func f(a, b, c int) { print(a, c, recover().(int), b) }; func g(int) int`,
1387 `func _() { f(g(1), 2, g(3)) }`,
1388 `func _() { print(g(1), g(3), recover().(int), 2) }`,
1389 },
1390 {
1391 "Callee reads may commute with impure arguments.",
1392 `func f(a, b int) { print(a, x, b) }; func g(int) int; var x, y int`,
1393 `func _() { f(g(1), y) }`,
1394 `func _() { print(g(1), x, y) }`,
1395 },
1396 {
1397 "All impure parameters preceding a read hazard must be kept.",
1398 `func f(a, b, c int) { print(a, b, recover().(int), c) }; var x, y, z int`,
1399 `func _() { f(x, y, z) }`,
1400 `func _() {
1401 var c int = z
1402 print(x, y, recover().(int), c)
1403 }`,
1404 },
1405 {
1406 "All parameters preceding a write hazard must be kept.",
1407 `func f(a, b, c int) { print(a, b, recover().(int), c) }; func g(int) int; var x, y, z int`,
1408 `func _() { f(x, y, g(0)) }`,
1409 `func _() {
1410 var a, b, c int = x, y, g(0)
1411 print(a, b, recover().(int), c)
1412 }`,
1413 },
1414 {
1415 "[W1 R0 W2 W4 R3] -- test case for second iteration of effect loop",
1416 `func f(a, b, c, d, e int) { print(b, a, c, e, d) }; func g(int) int; var x, y int`,
1417 `func _() { f(x, g(1), g(2), y, g(3)) }`,
1418 `func _() {
1419 var a, b, c, d int = x, g(1), g(2), y
1420 print(b, a, c, g(3), d)
1421 }`,
1422 },
1423 {
1424 // In this example, the set() call is rejected as a substitution
1425 // candidate due to a shadowing conflict (z). This must entail that the
1426 // selection x.y (R) is also rejected, because it is lower numbered.
1427 //
1428 // Incidentally this program (which panics when executed) illustrates
1429 // that although effects occur left-to-right, read operations such
1430 // as x.y are not ordered wrt writes, depending on the compiler.
1431 // Changing x.y to identity(x).y forces the ordering and avoids the panic.
1432 "Hazards with args already rejected (e.g. due to shadowing) are detected too.",
1433 `func f(x, y int) (z int) { return x + y }; func set[T any](ptr *T, old, new T) int { println(old); *ptr = new; return 0; }`,
1434 `func _() { x := new(struct{ y int }); z := x; f(x.y, set(&x, z, nil)) }`,
1435 `func _() {
1436 x := new(struct{ y int })
1437 z := x
1438 {
1439 var x, y int = x.y, set(&x, z, nil)
1440 _ = x + y
1441 }
1442 }`,
1443 },
1444 {
1445 // Rejection of a later parameter for reasons other than callee
1446 // effects (e.g. escape) may create hazards with lower-numbered
1447 // parameters that require them to be rejected too.
1448 "Hazards with already eliminated parameters (variant)",
1449 `func f(x, y int) { _ = &y }; func g(int) int`,
1450 `func _() { f(g(1), g(2)) }`,
1451 `func _() {
1452 var _, y int = g(1), g(2)
1453 _ = &y
1454 }`,
1455 },
1456 {
1457 // In this case g(2) is rejected for substitution because it is
1458 // unreferenced but has effects, so parameter x must also be rejected
1459 // so that its argument v can be evaluated earlier in the binding decl.
1460 "Hazards with already eliminated parameters (unreferenced fx variant)",
1461 `func f(x, y int) { _ = x }; func g(int) int; var v int`,
1462 `func _() { f(v, g(2)) }`,
1463 `func _() {
1464 var x, _ int = v, g(2)
1465 _ = x
1466 }`,
1467 },
1468 {
1469 "Defer f() evaluates f() before unknown effects",
1470 `func f(int, y any, z int) { defer println(int, y, z) }; func g(int) int`,
1471 `func _() { f(g(1), g(2), g(3)) }`,
1472 `func _() { func() { defer println(g(1), g(2), g(3)) }() }`,
1473 },
1474 {
1475 "Effects are ignored when IgnoreEffects",
1476 `func f(x, y int) { println(y, x) }; func g(int) int`,
1477 `func _() { f(g(1), g(2)) }`,
1478 `func _() { println(g(2), g(1)) }`,
1479 },
1480 })
1481 }
1482
1483 func TestNamedResultVars(t *testing.T) {
1484 runTests(t, []testcase{
1485 {
1486 "Stmt-context call to {return g()} that mentions named result.",
1487 `func f() (x int) { return g(x) }; func g(int) int`,
1488 `func _() { f() }`,
1489 `func _() {
1490 var x int
1491 g(x)
1492 }`,
1493 },
1494 {
1495 "Ditto, with binding decl again.",
1496 `func f(y string) (x int) { return x+x+len(y+y) }`,
1497 `func _() { f(".") }`,
1498 `func _() {
1499 var (
1500 y string = "."
1501 x int
1502 )
1503 _ = x + x + len(y+y)
1504 }`,
1505 },
1506
1507 {
1508 "Ditto, with binding decl (due to repeated y refs).",
1509 `func f(y string) (x string) { return x+y+y }`,
1510 `func _() { f(".") }`,
1511 `func _() {
1512 var (
1513 y string = "."
1514 x string
1515 )
1516 _ = x + y + y
1517 }`,
1518 },
1519 {
1520 "Stmt-context call to {return binary} that mentions named result.",
1521 `func f() (x int) { return x+x }`,
1522 `func _() { f() }`,
1523 `func _() {
1524 var x int
1525 _ = x + x
1526 }`,
1527 },
1528 {
1529 "Tail call to {return expr} that mentions named result.",
1530 `func f() (x int) { return x }`,
1531 `func _() int { return f() }`,
1532 `func _() int { return func() (x int) { return x }() }`,
1533 },
1534 {
1535 "Tail call to {return} that implicitly reads named result.",
1536 `func f() (x int) { return }`,
1537 `func _() int { return f() }`,
1538 `func _() int { return func() (x int) { return }() }`,
1539 },
1540 {
1541 "Spread-context call to {return expr} that mentions named result.",
1542 `func f() (x, y int) { return x, y }`,
1543 `func _() { var _, _ = f() }`,
1544 `func _() { var _, _ = func() (x, y int) { return x, y }() }`,
1545 },
1546 {
1547 "Shadowing in binding decl for named results => literalization.",
1548 `func f(y string) (x y) { return x+x+len(y+y) }; type y = int`,
1549 `func _() { f(".") }`,
1550 `func _() { func(y string) (x y) { return x + x + len(y+y) }(".") }`,
1551 },
1552 })
1553 }
1554
1555 func TestSubstitutionPreservesParameterType(t *testing.T) {
1556 runTests(t, []testcase{
1557 {
1558 "Substitution preserves argument type (#63193).",
1559 `func f(x int16) { y := x; _ = (*int16)(&y) }`,
1560 `func _() { f(1) }`,
1561 `func _() {
1562 y := int16(1)
1563 _ = (*int16)(&y)
1564 }`,
1565 },
1566 {
1567 "Same, with non-constant (unnamed to named struct) conversion.",
1568 `func f(x T) { y := x; _ = (*T)(&y) }; type T struct{}`,
1569 `func _() { f(struct{}{}) }`,
1570 `func _() {
1571 y := T(struct{}{})
1572 _ = (*T)(&y)
1573 }`,
1574 },
1575 {
1576 "Same, with non-constant (chan to <-chan) conversion.",
1577 `func f(x T) { y := x; _ = (*T)(&y) }; type T = <-chan int; var ch chan int`,
1578 `func _() { f(ch) }`,
1579 `func _() {
1580 y := T(ch)
1581 _ = (*T)(&y)
1582 }`,
1583 },
1584 {
1585 "Same, with untyped nil to typed nil conversion.",
1586 `func f(x *int) { y := x; _ = (**int)(&y) }`,
1587 `func _() { f(nil) }`,
1588 `func _() {
1589 y := (*int)(nil)
1590 _ = (**int)(&y)
1591 }`,
1592 },
1593 {
1594 "Conversion of untyped int to named type is made explicit.",
1595 `type T int; func (x T) f() { x.g() }; func (T) g() {}`,
1596 `func _() { T.f(1) }`,
1597 `func _() { T(1).g() }`,
1598 },
1599 {
1600 "Implicit reference is made explicit outside of selector",
1601 `type T int; func (x *T) f() bool { return x == x.id() }; func (x *T) id() *T { return x }`,
1602 `func _() { var t T; _ = t.f() }`,
1603 `func _() { var t T; _ = &t == t.id() }`,
1604 },
1605 {
1606 "Implicit parenthesized reference is not made explicit in selector",
1607 `type T int; func (x *T) f() bool { return x == (x).id() }; func (x *T) id() *T { return x }`,
1608 `func _() { var t T; _ = t.f() }`,
1609 `func _() { var t T; _ = &t == (t).id() }`,
1610 },
1611 {
1612 "Implicit dereference is made explicit outside of selector", // TODO(rfindley): avoid unnecessary literalization here
1613 `type T int; func (x T) f() bool { return x == x.id() }; func (x T) id() T { return x }`,
1614 `func _() { var t *T; _ = t.f() }`,
1615 `func _() { var t *T; _ = func() bool { var x T = *t; return x == x.id() }() }`,
1616 },
1617 {
1618 "Check for shadowing error on type used in the conversion.",
1619 `func f(x T) { _ = &x == (*T)(nil) }; type T int16`,
1620 `func _() { type T bool; f(1) }`,
1621 `error: T.*shadowed.*by.*type`,
1622 },
1623 })
1624 }
1625
1626 func TestRedundantConversions(t *testing.T) {
1627 runTests(t, []testcase{
1628 {
1629 "Type conversion must be added if the constant is untyped.",
1630 `func f(i int32) { print(i) }; func print(x any) {}`,
1631 `func _() { f(1) }`,
1632 `func _() { print(int32(1)) }`,
1633 },
1634 {
1635 "Type conversion must not be added if the constant is typed.",
1636 `func f(i int32) { print(i) }; func print(x any) {}`,
1637 `func _() { f(int32(1)) }`,
1638 `func _() { print(int32(1)) }`,
1639 },
1640 {
1641 "No type conversion for argument to interface parameter",
1642 `type T int; func f(x any) { g(x) }; func g(any) {}`,
1643 `func _() { f(T(1)) }`,
1644 `func _() { g(T(1)) }`,
1645 },
1646 {
1647 "No type conversion for parenthesized argument to interface parameter",
1648 `type T int; func f(x any) { g((x)) }; func g(any) {}`,
1649 `func _() { f(T(1)) }`,
1650 `func _() { g((T(1))) }`,
1651 },
1652 {
1653 "Type conversion for argument to type parameter",
1654 `type T int; func f(x any) { g(x) }; func g[P any](P) {}`,
1655 `func _() { f(T(1)) }`,
1656 `func _() { g(any(T(1))) }`,
1657 },
1658 {
1659 "Strip redundant interface conversions",
1660 `type T interface{ M() }; func f(x any) { g(x) }; func g[P any](P) {}`,
1661 `func _() { f(T(nil)) }`,
1662 `func _() { g(any(nil)) }`,
1663 },
1664 {
1665 "No type conversion for argument to variadic interface parameter",
1666 `type T int; func f(x ...any) { g(x...) }; func g(...any) {}`,
1667 `func _() { f(T(1)) }`,
1668 `func _() { g(T(1)) }`,
1669 },
1670 {
1671 "Type conversion for variadic argument",
1672 `type T int; func f(x ...any) { g(x...) }; func g(...any) {}`,
1673 `func _() { f([]any{T(1)}...) }`,
1674 `func _() { g([]any{T(1)}...) }`,
1675 },
1676 {
1677 "Type conversion for argument to interface channel",
1678 `type T int; var c chan any; func f(x T) { c <- x }`,
1679 `func _() { f(1) }`,
1680 `func _() { c <- T(1) }`,
1681 },
1682 {
1683 "No type conversion for argument to concrete channel",
1684 `type T int32; var c chan T; func f(x T) { c <- x }`,
1685 `func _() { f(1) }`,
1686 `func _() { c <- 1 }`,
1687 },
1688 {
1689 "Type conversion for interface map key",
1690 `type T int; var m map[any]any; func f(x T) { m[x] = 1 }`,
1691 `func _() { f(1) }`,
1692 `func _() { m[T(1)] = 1 }`,
1693 },
1694 {
1695 "No type conversion for interface to interface map key",
1696 `type T int; var m map[any]any; func f(x any) { m[x] = 1 }`,
1697 `func _() { f(T(1)) }`,
1698 `func _() { m[T(1)] = 1 }`,
1699 },
1700 {
1701 "No type conversion for concrete map key",
1702 `type T int; var m map[T]any; func f(x T) { m[x] = 1 }`,
1703 `func _() { f(1) }`,
1704 `func _() { m[1] = 1 }`,
1705 },
1706 {
1707 "Type conversion for interface literal key/value",
1708 `type T int; type m map[any]any; func f(x, y T) { _ = m{x: y} }`,
1709 `func _() { f(1, 2) }`,
1710 `func _() { _ = m{T(1): T(2)} }`,
1711 },
1712 {
1713 "No type conversion for concrete literal key/value",
1714 `type T int; type m map[T]T; func f(x, y T) { _ = m{x: y} }`,
1715 `func _() { f(1, 2) }`,
1716 `func _() { _ = m{1: 2} }`,
1717 },
1718 {
1719 "Type conversion for interface literal element",
1720 `type T int; type s []any; func f(x T) { _ = s{x} }`,
1721 `func _() { f(1) }`,
1722 `func _() { _ = s{T(1)} }`,
1723 },
1724 {
1725 "No type conversion for concrete literal element",
1726 `type T int; type s []T; func f(x T) { _ = s{x} }`,
1727 `func _() { f(1) }`,
1728 `func _() { _ = s{1} }`,
1729 },
1730 {
1731 "Type conversion for interface unkeyed struct field",
1732 `type T int; type s struct{any}; func f(x T) { _ = s{x} }`,
1733 `func _() { f(1) }`,
1734 `func _() { _ = s{T(1)} }`,
1735 },
1736 {
1737 "No type conversion for concrete unkeyed struct field",
1738 `type T int; type s struct{T}; func f(x T) { _ = s{x} }`,
1739 `func _() { f(1) }`,
1740 `func _() { _ = s{1} }`,
1741 },
1742 {
1743 "Type conversion for interface field value",
1744 `type T int; type S struct{ F any }; func f(x T) { _ = S{F: x} }`,
1745 `func _() { f(1) }`,
1746 `func _() { _ = S{F: T(1)} }`,
1747 },
1748 {
1749 "No type conversion for concrete field value",
1750 `type T int; type S struct{ F T }; func f(x T) { _ = S{F: x} }`,
1751 `func _() { f(1) }`,
1752 `func _() { _ = S{F: 1} }`,
1753 },
1754 {
1755 "Type conversion for argument to interface channel",
1756 `type T int; var c chan any; func f(x any) { c <- x }`,
1757 `func _() { f(T(1)) }`,
1758 `func _() { c <- T(1) }`,
1759 },
1760 {
1761 "No type conversion for argument to concrete channel",
1762 `type T int32; var c chan T; func f(x T) { c <- x }`,
1763 `func _() { f(1) }`,
1764 `func _() { c <- 1 }`,
1765 },
1766 {
1767 "No type conversion for assignment to an explicit interface type",
1768 `type T int; func f(x any) { var y any; y = x; _ = y }`,
1769 `func _() { f(T(1)) }`,
1770 `func _() {
1771 var y any
1772 y = T(1)
1773 _ = y
1774 }`,
1775 },
1776 {
1777 "No type conversion for short variable assignment to an explicit interface type",
1778 `type T int; func f(e error) { var err any; i, err := 1, e; _, _ = i, err }`,
1779 `func _() { f(nil) }`,
1780 `func _() {
1781 var err any
1782 i, err := 1, nil
1783 _, _ = i, err
1784 }`,
1785 },
1786 {
1787 "No type conversion for initializer of an explicit interface type",
1788 `type T int; func f(x any) { var y any = x; _ = y }`,
1789 `func _() { f(T(1)) }`,
1790 `func _() {
1791 var y any = T(1)
1792 _ = y
1793 }`,
1794 },
1795 {
1796 "No type conversion for use as a composite literal key",
1797 `type T int; func f(x any) { _ = map[any]any{x: 1} }`,
1798 `func _() { f(T(1)) }`,
1799 `func _() { _ = map[any]any{T(1): 1} }`,
1800 },
1801 {
1802 "No type conversion for use as a composite literal value",
1803 `type T int; func f(x any) { _ = []any{x} }`,
1804 `func _() { f(T(1)) }`,
1805 `func _() { _ = []any{T(1)} }`,
1806 },
1807 {
1808 "No type conversion for use as a composite literal field",
1809 `type T int; func f(x any) { _ = struct{ F any }{F: x} }`,
1810 `func _() { f(T(1)) }`,
1811 `func _() { _ = struct{ F any }{F: T(1)} }`,
1812 },
1813 {
1814 "No type conversion for use in a send statement",
1815 `type T int; func f(x any) { var c chan any; c <- x }`,
1816 `func _() { f(T(1)) }`,
1817 `func _() {
1818 var c chan any
1819 c <- T(1)
1820 }`,
1821 },
1822 })
1823 }
1824
1825 func runTests(t *testing.T, tests []testcase) {
1826 for _, test := range tests {
1827 t.Run(test.descr, func(t *testing.T) {
1828 fset := token.NewFileSet()
1829 mustParse := func(filename string, content any) *ast.File {
1830 f, err := parser.ParseFile(fset, filename, content, parser.ParseComments|parser.SkipObjectResolution)
1831 if err != nil {
1832 t.Fatalf("ParseFile: %v", err)
1833 }
1834 return f
1835 }
1836
1837 addPackageClause := func(src string) string {
1838 if !strings.Contains(test.descr, "NoPackageClause") {
1839 src = "package p\n" + src
1840 }
1841 return src
1842 }
1843
1844 // Parse callee file and find first func decl named f.
1845 calleeContent := addPackageClause(test.callee)
1846 calleeFile := mustParse("callee.go", calleeContent)
1847 var decl *ast.FuncDecl
1848 for _, d := range calleeFile.Decls {
1849 if d, ok := d.(*ast.FuncDecl); ok && d.Name.Name == funcName {
1850 decl = d
1851 break
1852 }
1853 }
1854 if decl == nil {
1855 t.Fatalf("declaration of func %s not found: %s", funcName, test.callee)
1856 }
1857
1858 // Parse caller file and find first call to f().
1859 callerContent := addPackageClause(test.caller)
1860 callerFile := mustParse("caller.go", callerContent)
1861 var call *ast.CallExpr
1862 ast.Inspect(callerFile, func(n ast.Node) bool {
1863 if n, ok := n.(*ast.CallExpr); ok {
1864 switch fun := n.Fun.(type) {
1865 case *ast.SelectorExpr:
1866 if fun.Sel.Name == funcName {
1867 call = n
1868 }
1869 case *ast.Ident:
1870 if fun.Name == funcName {
1871 call = n
1872 }
1873 case *ast.IndexExpr:
1874 if id, ok := fun.X.(*ast.Ident); ok && id.Name == funcName {
1875 call = n
1876 }
1877 case *ast.IndexListExpr:
1878 if id, ok := fun.X.(*ast.Ident); ok && id.Name == funcName {
1879 call = n
1880 }
1881 }
1882 }
1883 return call == nil
1884 })
1885 if call == nil {
1886 t.Fatalf("call to %s not found: %s", funcName, test.caller)
1887 }
1888
1889 // Type check both files as one package.
1890 info := &types.Info{
1891 Defs: make(map[*ast.Ident]types.Object),
1892 Uses: make(map[*ast.Ident]types.Object),
1893 Types: make(map[ast.Expr]types.TypeAndValue),
1894 Implicits: make(map[ast.Node]types.Object),
1895 Selections: make(map[*ast.SelectorExpr]*types.Selection),
1896 Scopes: make(map[ast.Node]*types.Scope),
1897 FileVersions: make(map[*ast.File]string),
1898 }
1899 conf := &types.Config{Error: func(err error) { t.Error(err) }}
1900 pkg, err := conf.Check("p", fset, []*ast.File{callerFile, calleeFile}, info)
1901 if err != nil {
1902 t.Fatal("transformation introduced type errors")
1903 }
1904
1905 // Analyze callee and inline call.
1906 doIt := func() (*inline.Result, error) {
1907 callee, err := inline.AnalyzeCallee(t.Logf, fset, pkg, info, decl, []byte(calleeContent))
1908 if err != nil {
1909 return nil, err
1910 }
1911 if err := checkTranscode(callee); err != nil {
1912 t.Fatal(err)
1913 }
1914
1915 caller := &inline.Caller{
1916 Fset: fset,
1917 Types: pkg,
1918 Info: info,
1919 File: callerFile,
1920 Call: call,
1921 }
1922 check := checkNoMutation(caller.File)
1923 defer check()
1924 return inline.Inline(caller, callee, &inline.Options{
1925 Logf: t.Logf,
1926 IgnoreEffects: strings.Contains(test.descr, "IgnoreEffects"),
1927 })
1928 }
1929 res, err := doIt()
1930
1931 // Want error?
1932 if rest, ok := strings.CutPrefix(test.want, "error: "); ok {
1933 if err == nil {
1934 t.Fatalf("unexpected success: want error matching %q", rest)
1935 }
1936 msg := err.Error()
1937 if ok, err := regexp.MatchString(rest, msg); err != nil {
1938 t.Fatalf("invalid regexp: %v", err)
1939 } else if !ok {
1940 t.Fatalf("wrong error: %s (want match for %q)", msg, rest)
1941 }
1942 return
1943 }
1944
1945 // Want success.
1946 if err != nil {
1947 t.Fatal(err)
1948 }
1949
1950 gotContent, err := applyEdits(pkg, callerFile.FileStart, []byte(callerContent), res.Edits)
1951 if err != nil {
1952 t.Fatal(err)
1953 }
1954
1955 // Compute a single-hunk line-based diff.
1956 srcLines := strings.Split(callerContent, "\n")
1957 gotLines := strings.Split(string(gotContent), "\n")
1958 for len(srcLines) > 0 && len(gotLines) > 0 &&
1959 srcLines[0] == gotLines[0] {
1960 srcLines = srcLines[1:]
1961 gotLines = gotLines[1:]
1962 }
1963 for len(srcLines) > 0 && len(gotLines) > 0 &&
1964 srcLines[len(srcLines)-1] == gotLines[len(gotLines)-1] {
1965 srcLines = srcLines[:len(srcLines)-1]
1966 gotLines = gotLines[:len(gotLines)-1]
1967 }
1968 got := strings.Join(gotLines, "\n")
1969
1970 if strings.TrimSpace(got) != strings.TrimSpace(test.want) {
1971 t.Fatalf("\nInlining this call:\t%s\nof this callee: \t%s\nproduced:\n%s\nWant:\n\n%s",
1972 test.caller,
1973 test.callee,
1974 got,
1975 test.want)
1976 }
1977
1978 // Check that resulting code type-checks.
1979 newCallerFile := mustParse("newcaller.go", gotContent)
1980 if _, err := conf.Check("p", fset, []*ast.File{newCallerFile, calleeFile}, nil); err != nil {
1981 t.Fatalf("modified source failed to typecheck: <<%s>>", gotContent)
1982 }
1983 })
1984 }
1985 }
1986
1987 // -- helpers --
1988
1989 // checkNoMutation returns a function that, when called,
1990 // asserts that file was not modified since the checkNoMutation call.
1991 func checkNoMutation(file *ast.File) func() {
1992 pre := deepHash(file)
1993 return func() {
1994 post := deepHash(file)
1995 if pre != post {
1996 panic("Inline mutated caller.File")
1997 }
1998 }
1999 }
2000
2001 // checkTranscode replaces *callee by the results of gob-encoding and
2002 // then decoding it, to test that these operations are lossless.
2003 func checkTranscode(callee *inline.Callee) error {
2004 // Perform Gob transcoding so that it is exercised by the test.
2005 var enc bytes.Buffer
2006 if err := gob.NewEncoder(&enc).Encode(callee); err != nil {
2007 return fmt.Errorf("internal error: gob encoding failed: %v", err)
2008 }
2009 *callee = inline.Callee{}
2010 if err := gob.NewDecoder(&enc).Decode(callee); err != nil {
2011 return fmt.Errorf("internal error: gob decoding failed: %v", err)
2012 }
2013 return nil
2014 }
2015
2016 // deepHash computes a cryptographic hash of an ast.Node so that
2017 // if the data structure is mutated, the hash changes.
2018 // It assumes Go variables do not change address.
2019 //
2020 // TODO(adonovan): consider publishing this in the astutil package.
2021 //
2022 // TODO(adonovan): consider a variant that reports where in the tree
2023 // the mutation occurred (obviously at a cost in space).
2024 func deepHash(n ast.Node) any {
2025 seen := make(map[unsafe.Pointer]bool) // to break cycles
2026
2027 hasher := sha256.New()
2028 le := binary.LittleEndian
2029 writeUint64 := func(v uint64) {
2030 var bs [8]byte
2031 le.PutUint64(bs[:], v)
2032 hasher.Write(bs[:])
2033 }
2034
2035 var visit func(reflect.Value)
2036 visit = func(v reflect.Value) {
2037 switch v.Kind() {
2038 case reflect.Pointer:
2039 ptr := v.UnsafePointer()
2040 writeUint64(uint64(uintptr(ptr)))
2041 if !v.IsNil() {
2042 if !seen[ptr] {
2043 seen[ptr] = true
2044 // Skip types we don't handle yet, but don't care about.
2045 switch v.Interface().(type) {
2046 case *ast.Scope:
2047 return // involves a map
2048 }
2049
2050 visit(v.Elem())
2051 }
2052 }
2053
2054 case reflect.Struct:
2055 for i := 0; i < v.Type().NumField(); i++ {
2056 visit(v.Field(i))
2057 }
2058
2059 case reflect.Slice:
2060 ptr := v.UnsafePointer()
2061 // We may encounter different slices at the same address,
2062 // so don't mark ptr as "seen".
2063 writeUint64(uint64(uintptr(ptr)))
2064 writeUint64(uint64(v.Len()))
2065 writeUint64(uint64(v.Cap()))
2066 for i := 0; i < v.Len(); i++ {
2067 visit(v.Index(i))
2068 }
2069
2070 case reflect.Interface:
2071 if v.IsNil() {
2072 writeUint64(0)
2073 } else {
2074 rtype := reflect.ValueOf(v.Type()).UnsafePointer()
2075 writeUint64(uint64(uintptr(rtype)))
2076 visit(v.Elem())
2077 }
2078
2079 case reflect.String:
2080 writeUint64(uint64(v.Len()))
2081 hasher.Write([]byte(v.String()))
2082
2083 case reflect.Int:
2084 writeUint64(uint64(v.Int()))
2085
2086 case reflect.Uint:
2087 writeUint64(uint64(v.Uint()))
2088
2089 case reflect.Bool, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
2090 // Bools and fixed width numbers can be handled by binary.Write.
2091 binary.Write(hasher, le, v.Interface())
2092
2093 default: // reflect.Array, reflect.Chan, reflect.Func, reflect.Map, reflect.UnsafePointer, reflect.Uintptr
2094 panic(v) // unreachable in AST
2095 }
2096 }
2097 visit(reflect.ValueOf(n))
2098
2099 var hash [sha256.Size]byte
2100 hasher.Sum(hash[:0])
2101 return hash
2102 }
2103
2104 func TestDeepHash(t *testing.T) {
2105 // This test reproduces a bug in DeepHash that was encountered during work on
2106 // the inliner.
2107 //
2108 // TODO(rfindley): consider replacing this with a fuzz test.
2109 id := &ast.Ident{
2110 NamePos: 2,
2111 Name: "t",
2112 }
2113 c := &ast.CallExpr{
2114 Fun: id,
2115 }
2116 h1 := deepHash(c)
2117 id.NamePos = 1
2118 h2 := deepHash(c)
2119 if h1 == h2 {
2120 t.Fatal("bad")
2121 }
2122 }
2123
2124 // applyEdits transforms content by applying the specified edits
2125 // to the file whose positions are defined by fset), reformatting the file, and
2126 // removing unused imports (using pkg for names of imported packages).
2127 func applyEdits(pkg *types.Package, fileStart token.Pos, content []byte, edits []refactor.Edit) ([]byte, error) {
2128 dedits := make([]diff.Edit, len(edits))
2129 for i, edit := range edits {
2130 dedits[i] = diff.Edit{
2131 Start: int(edit.Pos - fileStart),
2132 End: int(edit.End - fileStart),
2133 New: string(edit.NewText),
2134 }
2135 }
2136 got, err := diff.ApplyBytes(content, dedits)
2137 if err != nil {
2138 return nil, err
2139 }
2140 got, err = driverutil.FormatSourceRemoveImports(pkg, got)
2141 if err != nil {
2142 return nil, err
2143 }
2144 return []byte(got), nil
2145 }