|
| 1 | +//go:build !llgo |
| 2 | + |
| 3 | +package cl |
| 4 | + |
| 5 | +import ( |
| 6 | + "go/token" |
| 7 | + "go/types" |
| 8 | + "testing" |
| 9 | + |
| 10 | + "github.com/xgo-dev/llvm" |
| 11 | +) |
| 12 | + |
| 13 | +func TestNeedsNamedClosureChange(t *testing.T) { |
| 14 | + pkg := types.NewPackage("example.com/p", "p") |
| 15 | + params := types.NewTuple(types.NewParam(token.NoPos, pkg, "value", types.Typ[types.Int])) |
| 16 | + results := types.NewTuple(types.NewParam(token.NoPos, pkg, "", types.Typ[types.Bool])) |
| 17 | + sig := types.NewSignatureType(nil, nil, nil, params, results, false) |
| 18 | + named := types.NewNamed(types.NewTypeName(token.NoPos, pkg, "Func", nil), sig, nil) |
| 19 | + different := types.NewSignatureType(nil, nil, nil, nil, results, false) |
| 20 | + |
| 21 | + tests := []struct { |
| 22 | + name string |
| 23 | + got types.Type |
| 24 | + want types.Type |
| 25 | + ok bool |
| 26 | + }{ |
| 27 | + {name: "anonymous to named", got: sig, want: named, ok: true}, |
| 28 | + {name: "named to anonymous", got: named, want: sig, ok: true}, |
| 29 | + {name: "identical named", got: named, want: named}, |
| 30 | + {name: "different signatures", got: different, want: named}, |
| 31 | + {name: "non functions", got: types.Typ[types.Int], want: types.Typ[types.Int64]}, |
| 32 | + } |
| 33 | + for _, tt := range tests { |
| 34 | + t.Run(tt.name, func(t *testing.T) { |
| 35 | + if got := needsNamedClosureChange(tt.got, tt.want); got != tt.ok { |
| 36 | + t.Fatalf("needsNamedClosureChange(%v, %v) = %v, want %v", tt.got, tt.want, got, tt.ok) |
| 37 | + } |
| 38 | + }) |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +func TestNamedClosureValuesKeepTheirDeclaredType(t *testing.T) { |
| 43 | + const source = `package main |
| 44 | +
|
| 45 | +type Func func(int) bool |
| 46 | +
|
| 47 | +func call(fn Func) bool { return fn(1) } |
| 48 | +
|
| 49 | +func direct() bool { |
| 50 | + want := 1 |
| 51 | + return call(func(got int) bool { return got == want }) |
| 52 | +} |
| 53 | +
|
| 54 | +func iterator() func(Func) { |
| 55 | + return func(yield Func) { _ = yield(1) } |
| 56 | +} |
| 57 | +
|
| 58 | +func ranged() int { |
| 59 | + n := 0 |
| 60 | + for range iterator() { n++ } |
| 61 | + return n |
| 62 | +} |
| 63 | +
|
| 64 | +func main() { |
| 65 | + if !direct() || ranged() != 1 { panic("named closure conversion failed") } |
| 66 | +} |
| 67 | +` |
| 68 | + _, module := mustCompileLLPkgFromSrc(t, source) |
| 69 | + if err := llvm.VerifyModule(module, llvm.ReturnStatusAction); err != nil { |
| 70 | + t.Fatalf("named closure module is invalid: %v\n%s", err, module.String()) |
| 71 | + } |
| 72 | +} |
0 commit comments