Debian Codegraph @

typeparams/example/genericmethods/main.go

raw symbols SCIP
1 // Copyright 2022 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 //go:build go1.18
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 // !+printmethods
42 func PrintMethods(pkg *types.Package) {
43 // Look up *Named types in the package scope.
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 //!-printmethods
68
69 /*
70 //!+printoutput
71 Pair:
72 func (p.Pair[L, _]).Left() L
73 func (p.Pair[_, R]).Right() R
74
75 Pair[int, int]:
76 func (p.Pair[int, int]).Left() int
77 func (p.Pair[int, int]).Right() int
78
79 Pair[L, _]:
80 func (p.Pair[L, _]).Left() L
81 func (p.Pair[L, _]).Right() _
82
83 //!-printoutput
84 */
85
86 // !+compareorigins
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 //!-compareorigins
99
100 /*
101 //!+compareoutput
102 Pair.Left == Pair[int, int].Left: false
103 Pair.Left == OriginMethod(Pair[int, int].Left): true
104 //!-compareoutput
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 }