| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
package main |
| 8 |
|
| 9 |
import ( |
| 10 |
"fmt" |
| 11 |
"go/ast" |
| 12 |
"go/parser" |
| 13 |
"go/token" |
| 14 |
"go/types" |
| 15 |
"log" |
| 16 |
|
| 17 |
"golang.org/x/exp/typeparams" |
| 18 |
) |
| 19 |
|
| 20 |
const src = ` |
| 21 |
//!+input |
| 22 |
package p |
| 23 |
|
| 24 |
type Pair[L, R any] struct { |
| 25 |
left L |
| 26 |
right R |
| 27 |
} |
| 28 |
|
| 29 |
func (p Pair[L, _]) Left() L { |
| 30 |
return p.left |
| 31 |
} |
| 32 |
|
| 33 |
func (p Pair[_, R]) Right() R { |
| 34 |
return p.right |
| 35 |
} |
| 36 |
|
| 37 |
var IntPair Pair[int, int] |
| 38 |
//!-input |
| 39 |
` |
| 40 |
|
| 41 |
|
| 42 |
func PrintMethods(pkg *types.Package) { |
| 43 |
|
| 44 |
lookup := func(name string) *types.Named { |
| 45 |
return pkg.Scope().Lookup(name).Type().(*types.Named) |
| 46 |
} |
| 47 |
|
| 48 |
Pair := lookup("Pair") |
| 49 |
IntPair := lookup("IntPair") |
| 50 |
PrintMethodSet("Pair", Pair) |
| 51 |
PrintMethodSet("Pair[int, int]", IntPair) |
| 52 |
LeftObj, _, _ := types.LookupFieldOrMethod(Pair, false, pkg, "Left") |
| 53 |
LeftRecvType := LeftObj.Type().(*types.Signature).Recv().Type() |
| 54 |
PrintMethodSet("Pair[L, _]", LeftRecvType) |
| 55 |
} |
| 56 |
|
| 57 |
func PrintMethodSet(name string, typ types.Type) { |
| 58 |
fmt.Println(name + ":") |
| 59 |
methodSet := types.NewMethodSet(typ) |
| 60 |
for i := 0; i < methodSet.Len(); i++ { |
| 61 |
method := methodSet.At(i).Obj() |
| 62 |
fmt.Println(method) |
| 63 |
} |
| 64 |
fmt.Println() |
| 65 |
} |
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
func CompareOrigins(pkg *types.Package) { |
| 88 |
Pair := pkg.Scope().Lookup("Pair").Type().(*types.Named) |
| 89 |
IntPair := pkg.Scope().Lookup("IntPair").Type().(*types.Named) |
| 90 |
Left, _, _ := types.LookupFieldOrMethod(Pair, false, pkg, "Left") |
| 91 |
LeftInt, _, _ := types.LookupFieldOrMethod(IntPair, false, pkg, "Left") |
| 92 |
|
| 93 |
fmt.Println("Pair.Left == Pair[int, int].Left:", Left == LeftInt) |
| 94 |
origin := typeparams.OriginMethod(LeftInt.(*types.Func)) |
| 95 |
fmt.Println("Pair.Left == OriginMethod(Pair[int, int].Left):", Left == origin) |
| 96 |
} |
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
func main() { |
| 108 |
fset := token.NewFileSet() |
| 109 |
f, err := parser.ParseFile(fset, "hello.go", src, 0) |
| 110 |
if err != nil { |
| 111 |
log.Fatal(err) |
| 112 |
} |
| 113 |
conf := types.Config{} |
| 114 |
pkg, err := conf.Check("p", fset, []*ast.File{f}, nil) |
| 115 |
if err != nil { |
| 116 |
log.Fatal(err) |
| 117 |
} |
| 118 |
fmt.Println("=== PrintMethods ===") |
| 119 |
PrintMethods(pkg) |
| 120 |
fmt.Println("=== CompareOrigins ===") |
| 121 |
CompareOrigins(pkg) |
| 122 |
} |