Debian Codegraph @

internal/refactor/inline/inline_test.go

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