File: main.go

package info (click to toggle)
golang-golang-x-exp 0.0~git20230522.2e198f4-1~bpo12%2B1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-backports
  • size: 6,404 kB
  • sloc: ansic: 1,900; objc: 276; sh: 272; asm: 48; makefile: 26
file content (159 lines) | stat: -rw-r--r-- 4,096 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build go1.18
// +build go1.18

package main

import (
	"bytes"
	"errors"
	"fmt"
	"go/ast"
	"go/parser"
	"go/token"
	"go/types"
	"log"
)

const src = `
//!+input
package p

type Pair[L, R comparable] struct {
	left  L
	right R
}

func (p Pair[L, _]) Left() L {
	return p.left
}

func Equal[L, R comparable](x, y Pair[L, R]) bool {
	return x.left == y.left && x.right == y.right
}

var X Pair[int, string]
var Y Pair[string, int]

var E = Equal[int, string]
//!-input
`

// !+check
func CheckInstances(fset *token.FileSet, file *ast.File) (*types.Package, error) {
	conf := types.Config{}
	info := &types.Info{
		Instances: make(map[*ast.Ident]types.Instance),
	}
	pkg, err := conf.Check("p", fset, []*ast.File{file}, info)
	for id, inst := range info.Instances {
		posn := fset.Position(id.Pos())
		fmt.Printf("%s: %s instantiated with %s: %s\n", posn, id.Name, FormatTypeList(inst.TypeArgs), inst.Type)
	}
	return pkg, err
}

//!-check

/*
//!+checkoutput
hello.go:21:9: Equal instantiated with [int, string]: func(x p.Pair[int, string], y p.Pair[int, string]) bool
hello.go:10:9: Pair instantiated with [L, _]: p.Pair[L, _]
hello.go:14:34: Pair instantiated with [L, R]: p.Pair[L, R]
hello.go:18:7: Pair instantiated with [int, string]: p.Pair[int, string]
hello.go:19:7: Pair instantiated with [string, int]: p.Pair[string, int]

//!-checkoutput
*/

func FormatTypeList(list *types.TypeList) string {
	var buf bytes.Buffer
	buf.WriteRune('[')
	for i := 0; i < list.Len(); i++ {
		if i > 0 {
			buf.WriteString(", ")
		}
		buf.WriteString(list.At(i).String())
	}
	buf.WriteRune(']')
	return buf.String()
}

// !+instantiate
func Instantiate(pkg *types.Package) error {
	Pair := pkg.Scope().Lookup("Pair").Type()
	X := pkg.Scope().Lookup("X").Type()
	Y := pkg.Scope().Lookup("Y").Type()

	// X and Y have different types, because their type arguments are different.
	Compare("X", "Y", X, Y)

	// Create a shared context for the subsequent instantiations.
	ctxt := types.NewContext()

	// Instantiating with [int, string] yields an instance that is identical (but
	// not equal) to X.
	Int, String := types.Typ[types.Int], types.Typ[types.String]
	inst1, _ := types.Instantiate(ctxt, Pair, []types.Type{Int, String}, true)
	Compare("X", "inst1", X, inst1)

	// Instantiating again returns the same exact instance, because of the shared
	// Context.
	inst2, _ := types.Instantiate(ctxt, Pair, []types.Type{Int, String}, true)
	Compare("inst1", "inst2", inst1, inst2)

	// Instantiating with 'any' is an error, because any is not comparable.
	Any := types.Universe.Lookup("any").Type()
	_, err := types.Instantiate(ctxt, Pair, []types.Type{Int, Any}, true)
	var argErr *types.ArgumentError
	if errors.As(err, &argErr) {
		fmt.Printf("Argument %d: %v\n", argErr.Index, argErr.Err)
	}

	return nil
}

func Compare(leftName, rightName string, left, right types.Type) {
	fmt.Printf("Identical(%s, %s) : %t\n", leftName, rightName, types.Identical(left, right))
	fmt.Printf("%s == %s : %t\n\n", leftName, rightName, left == right)
}

//!-instantiate

/*
//!+instantiateoutput
Identical(p.Pair[int, string], p.Pair[string, int]) : false
p.Pair[int, string] == p.Pair[string, int] : false

Identical(p.Pair[int, string], p.Pair[int, string]) : true
p.Pair[int, string] == p.Pair[int, string] : false

Identical(p.Pair[string, int], p.Pair[int, string]) : false
p.Pair[string, int] == p.Pair[int, string] : false

Identical(p.Pair[int, string], p.Pair[int, string]) : true
p.Pair[int, string] == p.Pair[int, string] : true

Argument 1: any does not implement comparable
//!-instantiateoutput
*/

func main() {
	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, "hello.go", src, 0)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("=== CheckInstances ===")
	pkg, err := CheckInstances(fset, f)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("=== Instantiate ===")
	if err := Instantiate(pkg); err != nil {
		log.Fatal(err)
	}
}