-
Notifications
You must be signed in to change notification settings - Fork 93
/
generic_type.go
243 lines (219 loc) · 6.68 KB
/
generic_type.go
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/*
* gomacro - A Go interpreter with Lisp-like macros
*
* Copyright (C) 2018-2019 Massimiliano Ghilardi
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*
* generic_type.go
*
* Created on Jun 06, 2018
* Author Massimiliano Ghilardi
*/
package fast
import (
"bytes"
"go/ast"
"go/token"
"github.com/cosmos72/gomacro/base"
"github.com/cosmos72/gomacro/base/output"
xr "github.com/cosmos72/gomacro/xreflect"
)
// a generic type declaration.
// either general, or partially specialized or fully specialized
type GenericTypeDecl struct {
Decl ast.Expr // type declaration body. use an ast.Expr because we will compile it with Comp.Type()
Alias bool // true if declaration is an alias: 'type Foo = ...'
Params []string // generic param names
For []ast.Expr // for partial or full specialization
}
type GenericType struct {
Master GenericTypeDecl // master (i.e. non specialized) declaration
Special map[string]GenericTypeDecl // partially or fully specialized declarations. key is TemplateTypeDecl.For converted to string
Instances map[I]xr.Type // cache of instantiated types. key is [N]interface{}{T1, T2...}
}
func (t *GenericType) Pos() token.Pos {
if t != nil {
return t.Master.Decl.Pos()
}
return token.NoPos
}
func (t *GenericType) String() string {
if t == nil {
return "<nil>"
}
var buf bytes.Buffer // strings.Builder requires Go >= 1.10
decl := t.Master
if GENERICS_V1_CXX() {
buf.WriteString("template[")
for i, param := range decl.Params {
if i != 0 {
buf.WriteString(", ")
}
buf.WriteString(param)
}
buf.WriteString("] type ")
} else {
buf.WriteString("type #[")
for i, param := range decl.Params {
if i != 0 {
buf.WriteString(", ")
}
buf.WriteString(param)
}
buf.WriteByte(']')
}
if decl.Alias {
buf.WriteString("= ")
}
var str string
switch e := decl.Decl.(type) {
case *ast.ArrayType:
if e.Len == nil {
str = "slice"
} else {
str = "array"
}
case *ast.ChanType:
str = "chan"
case *ast.FuncType:
str = "func"
case *ast.InterfaceType:
str = "interface"
case *ast.MapType:
str = "map"
case *ast.StructType:
str = "struct"
default:
(*output.Stringer).Fprintf(nil, &buf, "%v", decl.Decl)
}
buf.WriteString(str)
return buf.String()
}
// DeclGenericType stores a generic type declaration
// for later instantiation
func (c *Comp) DeclGenericType(spec *ast.TypeSpec) {
lit, _ := spec.Type.(*ast.CompositeLit)
if lit == nil {
c.Errorf("invalid generic type declaration: expecting an *ast.CompositeLit, found %T: %v",
spec.Type, spec)
}
expr := lit.Type
if _, ok := expr.(*ast.CompositeLit); ok {
c.Errorf("invalid generic type declaration: expecting an *ast.CompositeLit, found &ast.CompositeLit{Type: &ast.CompositeLit{}}: %v",
spec)
}
params, fors := c.genericParams(lit.Elts, "type", spec)
tdecl := GenericTypeDecl{
Decl: lit.Type,
Alias: spec.Assign != token.NoPos,
Params: params,
For: fors,
}
name := spec.Name.Name
if len(fors) == 0 {
// master (i.e. not specialized) declaration
if len(params) == 0 {
c.Errorf("cannot declare generic type with zero generic parameters: %v", spec)
}
bind := c.NewBind(name, GenericTypeBind, c.TypeOfPtrGenericType())
// a generic type declaration has no runtime effect:
// it merely creates the bind for on-demand instantiation by other code
bind.Value = &GenericType{
Master: tdecl,
Special: make(map[string]GenericTypeDecl),
Instances: make(map[I]xr.Type),
}
return
}
// partially or fully specialized declaration
bind := c.Binds[name]
if bind == nil {
c.Errorf("undefined identifier: %v", name)
}
typ, ok := bind.Value.(*GenericType)
if !ok {
c.Errorf("symbol is not a generic type, cannot declare type specializations on it: %s // %v", name, bind.Type)
}
key := c.Globals.Sprintf("%v", &ast.IndexExpr{X: spec.Name, Index: &ast.CompositeLit{Elts: fors}})
if len(typ.Master.Params) != len(fors) {
c.Errorf("generic type specialization for %d parameters, expecting %d: %s", len(fors), len(typ.Master.Params), key)
}
if _, ok := typ.Special[key]; ok {
c.Warnf("redefined generic type specialization: %s", key)
}
typ.Special[key] = tdecl
}
// GenericType compiles a generic type name#[T1, T2...] instantiating it if needed.
func (c *Comp) GenericType(node *ast.IndexExpr) xr.Type {
maker := c.genericMaker(node, GenericTypeBind)
if maker == nil {
return nil
}
typ := maker.ifun.(*GenericType)
key := maker.ikey
g := &c.Globals
debug := g.Options&base.OptDebugGenerics != 0
instance, _ := typ.Instances[key]
if instance != nil {
if debug {
g.Debugf("found instantiated generic type %v", maker)
}
} else {
if debug {
g.Debugf("instantiating generic type %v", maker)
}
// hard part: instantiate the generic type.
// must be instantiated in the same *Comp where it was declared!
instance = maker.instantiateType(typ, node)
}
return instance
}
// instantiateType instantiates and compiles a generic function.
// node is used only for error messages
func (maker *genericMaker) instantiateType(typ *GenericType, node *ast.IndexExpr) xr.Type {
// choose the specialization to use
_, special := maker.chooseType(typ)
// create a new nested Comp
c := NewComp(maker.comp, nil)
c.UpCost = 0
c.Depth--
// and inject generic arguments in it
special.injectBinds(c)
key := maker.ikey
panicking := true
defer func() {
if panicking {
delete(typ.Instances, key) // remove the cached instance if present
c.ErrorAt(node.Pos(), "error instantiating generic type: %v\n\t%v", maker, recover())
}
}()
// compile the type instantiation
//
var t xr.Type
if !special.decl.Alias && maker.sym.Name != "_" {
if c.Globals.Options&base.OptDebugGenerics != 0 {
c.Debugf("forward-declaring generic type before instantiation: %v", maker)
}
// support for generic recursive types, as for example
// type List#[T] struct { First T; Rest *List#[T] }
// requires to cache List#[T] as instantiated **before** actually instantiating it.
//
// This is similar to the technique used for non-generic recursive types, as
// type List struct { First int; Rest *List }
// with the difference that the cache is typ.Instances[key] instead of Comp.Types[name]
t = c.Universe.NamedOf(maker.String(), c.FileComp().Path)
typ.Instances[key] = t
u := c.Type(special.decl.Decl)
c.SetUnderlyingType(t, u)
} else {
// either the generic type is an alias, or name == "_" (discards the result of type declaration)
t = c.Type(special.decl.Decl)
typ.Instances[key] = t
}
panicking = false
return t
}