Debian Codegraph @

internal/refactor/inline/inline_test.go

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