Debian Codegraph @

typeparams/example/instantiation/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 "bytes"
11 "errors"
12 "fmt"
13 "go/ast"
14 "go/parser"
15 "go/token"
16 "go/types"
17 "log"
18 )
19
20 const src = `
21 //!+input
22 package p
23
24 type Pair[L, R comparable] struct {
25 left L
26 right R
27 }
28
29 func (p Pair[L, _]) Left() L {
30 return p.left
31 }
32
33 func Equal[L, R comparable](x, y Pair[L, R]) bool {
34 return x.left == y.left && x.right == y.right
35 }
36
37 var X Pair[int, string]
38 var Y Pair[string, int]
39
40 var E = Equal[int, string]
41 //!-input
42 `
43
44 // !+check
45 func CheckInstances(fset *token.FileSet, file *ast.File) (*types.Package, error) {
46 conf := types.Config{}
47 info := &types.Info{
48 Instances: make(map[*ast.Ident]types.Instance),
49 }
50 pkg, err := conf.Check("p", fset, []*ast.File{file}, info)
51 for id, inst := range info.Instances {
52 posn := fset.Position(id.Pos())
53 fmt.Printf("%s: %s instantiated with %s: %s\n", posn, id.Name, FormatTypeList(inst.TypeArgs), inst.Type)
54 }
55 return pkg, err
56 }
57
58 //!-check
59
60 /*
61 //!+checkoutput
62 hello.go:21:9: Equal instantiated with [int, string]: func(x p.Pair[int, string], y p.Pair[int, string]) bool
63 hello.go:10:9: Pair instantiated with [L, _]: p.Pair[L, _]
64 hello.go:14:34: Pair instantiated with [L, R]: p.Pair[L, R]
65 hello.go:18:7: Pair instantiated with [int, string]: p.Pair[int, string]
66 hello.go:19:7: Pair instantiated with [string, int]: p.Pair[string, int]
67
68 //!-checkoutput
69 */
70
71 func FormatTypeList(list *types.TypeList) string {
72 var buf bytes.Buffer
73 buf.WriteRune('[')
74 for i := 0; i < list.Len(); i++ {
75 if i > 0 {
76 buf.WriteString(", ")
77 }
78 buf.WriteString(list.At(i).String())
79 }
80 buf.WriteRune(']')
81 return buf.String()
82 }
83
84 // !+instantiate
85 func Instantiate(pkg *types.Package) error {
86 Pair := pkg.Scope().Lookup("Pair").Type()
87 X := pkg.Scope().Lookup("X").Type()
88 Y := pkg.Scope().Lookup("Y").Type()
89
90 // X and Y have different types, because their type arguments are different.
91 Compare("X", "Y", X, Y)
92
93 // Create a shared context for the subsequent instantiations.
94 ctxt := types.NewContext()
95
96 // Instantiating with [int, string] yields an instance that is identical (but
97 // not equal) to X.
98 Int, String := types.Typ[types.Int], types.Typ[types.String]
99 inst1, _ := types.Instantiate(ctxt, Pair, []types.Type{Int, String}, true)
100 Compare("X", "inst1", X, inst1)
101
102 // Instantiating again returns the same exact instance, because of the shared
103 // Context.
104 inst2, _ := types.Instantiate(ctxt, Pair, []types.Type{Int, String}, true)
105 Compare("inst1", "inst2", inst1, inst2)
106
107 // Instantiating with 'any' is an error, because any is not comparable.
108 Any := types.Universe.Lookup("any").Type()
109 _, err := types.Instantiate(ctxt, Pair, []types.Type{Int, Any}, true)
110 var argErr *types.ArgumentError
111 if errors.As(err, &argErr) {
112 fmt.Printf("Argument %d: %v\n", argErr.Index, argErr.Err)
113 }
114
115 return nil
116 }
117
118 func Compare(leftName, rightName string, left, right types.Type) {
119 fmt.Printf("Identical(%s, %s) : %t\n", leftName, rightName, types.Identical(left, right))
120 fmt.Printf("%s == %s : %t\n\n", leftName, rightName, left == right)
121 }
122
123 //!-instantiate
124
125 /*
126 //!+instantiateoutput
127 Identical(p.Pair[int, string], p.Pair[string, int]) : false
128 p.Pair[int, string] == p.Pair[string, int] : false
129
130 Identical(p.Pair[int, string], p.Pair[int, string]) : true
131 p.Pair[int, string] == p.Pair[int, string] : false
132
133 Identical(p.Pair[string, int], p.Pair[int, string]) : false
134 p.Pair[string, int] == p.Pair[int, string] : false
135
136 Identical(p.Pair[int, string], p.Pair[int, string]) : true
137 p.Pair[int, string] == p.Pair[int, string] : true
138
139 Argument 1: any does not implement comparable
140 //!-instantiateoutput
141 */
142
143 func main() {
144 fset := token.NewFileSet()
145 f, err := parser.ParseFile(fset, "hello.go", src, 0)
146 if err != nil {
147 log.Fatal(err)
148 }
149 fmt.Println("=== CheckInstances ===")
150 pkg, err := CheckInstances(fset, f)
151 if err != nil {
152 log.Fatal(err)
153 }
154 fmt.Println("=== Instantiate ===")
155 if err := Instantiate(pkg); err != nil {
156 log.Fatal(err)
157 }
158 }