forked from cosmos72/gomacro
/
generic_func.go
333 lines (298 loc) · 9.24 KB
/
generic_func.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/*
* 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_func.go
*
* Created on Jun 06, 2018
* Author Massimiliano Ghilardi
*/
package fast
import (
"bytes"
"go/ast"
"go/token"
"github.com/lifepod-solutions/gomacro/base"
"github.com/lifepod-solutions/gomacro/base/output"
xr "github.com/lifepod-solutions/gomacro/xreflect"
)
// an instantiated (and compiled) generic function.
type GenericFuncInstance struct {
Func *func(*Env) xr.Value
Type xr.Type
}
// a generic function declaration.
// either general, or partially specialized or fully specialized
type GenericFuncDecl struct {
Decl *ast.FuncLit // generic function declaration. use a *ast.FuncLit because we will compile it with Comp.FuncLit()
Params []string // generic param names
For []ast.Expr // partial or full specialization
}
// generic function
type GenericFunc struct {
Master GenericFuncDecl // master (i.e. non specialized) declaration
Special map[string]GenericFuncDecl // partially or fully specialized declarations. key is GenericFuncDecl.For converted to string
Instances map[I]*GenericFuncInstance // cache of instantiated functions. key is [N]interface{}{T1, T2...}
DeclScope *Comp // scope where generic function is declared
}
func (f *GenericFunc) Pos() token.Pos {
if f != nil {
return f.Master.Decl.Pos()
}
return token.NoPos
}
func (f *GenericFunc) String() string {
return f.Signature("")
}
func (f *GenericFunc) HasParam(name string) bool {
if f == nil {
return false
}
return f.Master.HasParam(name)
}
func (master *GenericFuncDecl) HasParam(name string) bool {
if master == nil {
return false
}
for _, param := range master.Params {
if name == param {
return true
}
}
return false
}
func (f *GenericFunc) Signature(name string) string {
if f == nil {
return "<nil>"
}
return f.Master.Signature(name)
}
func (master *GenericFuncDecl) Signature(name string) string {
if master == nil {
return "<nil>"
}
var buf bytes.Buffer // strings.Builder requires Go >= 1.10
if GENERICS_V1_CXX() {
buf.WriteString("template[")
for i, param := range master.Params {
if i != 0 {
buf.WriteString(", ")
}
buf.WriteString(param)
}
buf.WriteString("] ")
if len(name) == 0 {
(*output.Stringer).Fprintf(nil, &buf, "%v", master.Decl.Type)
} else {
(*output.Stringer).Fprintf(nil, &buf, "%v", &ast.FuncDecl{
Name: &ast.Ident{Name: name},
Type: master.Decl.Type,
})
}
return buf.String()
}
buf.WriteString(name)
buf.WriteString("#[")
for i, param := range master.Params {
if i != 0 {
buf.WriteString(", ")
}
buf.WriteString(param)
}
buf.WriteString("] ")
gname := buf.String()
buf.Reset()
(*output.Stringer).Fprintf(nil, &buf, "%v", &ast.FuncDecl{
Name: &ast.Ident{Name: gname},
Type: master.Decl.Type,
})
return buf.String()
}
// DeclGenericFunc stores a generic function or method declaration
// for later instantiation
func (c *Comp) DeclGenericFunc(decl *ast.FuncDecl) {
n := 0
if decl.Recv != nil {
n = len(decl.Recv.List)
}
if n != 2 {
c.Errorf("invalid generic function or method declaration: expecting exactly 2 receivers, found %d: %v", n, decl)
}
if decl.Recv.List[0] != nil {
c.Errorf("generic method declaration not yet implemented: %v", decl)
}
lit, _ := decl.Recv.List[1].Type.(*ast.CompositeLit)
if lit == nil {
c.Errorf("invalid generic function or method declaration: the second receiver should be an *ast.CompositeLit, found %T: %v",
decl.Recv.List[1].Type, decl)
}
params, fors := c.genericParams(lit.Elts, "function or method", decl)
fdecl := GenericFuncDecl{
Decl: &ast.FuncLit{
Type: decl.Type,
Body: decl.Body,
},
Params: params,
For: fors,
}
name := decl.Name.Name
if len(fors) == 0 {
// master (i.e. not specialized) declaration
if len(params) == 0 {
c.Errorf("cannot declare generic function with zero generic parameters: %v", decl.Type)
}
bind := c.NewBind(name, GenericFuncBind, c.TypeOfPtrGenericFunc())
// a generic function declaration has no runtime effect:
// it merely creates the bind for on-demand instantiation by other code
bind.Value = &GenericFunc{
Master: fdecl,
Special: make(map[string]GenericFuncDecl),
Instances: make(map[I]*GenericFuncInstance),
DeclScope: c,
}
return
}
if !GENERICS_V1_CXX() {
c.Errorf("generic function partial/full specializations are only supported by C++-style generics: %v", decl)
}
// partially or fully specialized declaration
bind := c.Binds[name]
if bind == nil {
c.Errorf("undefined identifier: %v", name)
}
fun, ok := bind.Value.(*GenericFunc)
if !ok {
c.Errorf("symbol is not a generic function, cannot declare function specializations on it: %s // %v", name, bind.Type)
}
key := c.Globals.Sprintf("%v", &ast.IndexExpr{X: decl.Name, Index: &ast.CompositeLit{Elts: fors}})
if len(fun.Master.Params) != len(fors) {
c.Errorf("generic function specialization for %d parameters, expecting %d: %s", len(fors), len(fun.Master.Params), key)
}
if _, ok := fun.Special[key]; ok {
c.Warnf("redefined generic function specialization: %s", key)
}
fun.Special[key] = fdecl
}
// GenericFunc compiles a generic function name#[T1, T2...] instantiating it if needed.
func (c *Comp) GenericFunc(node *ast.IndexExpr) *Expr {
maker := c.genericMaker(node, GenericFuncBind)
return c.genericFunc(maker, node)
}
// genericFunc compiles a generic function name#[T1, T2...] instantiating it if needed.
// node is used only for error messages
func (c *Comp) genericFunc(maker *genericMaker, node ast.Node) *Expr {
if maker == nil {
return nil
}
fun := maker.ifun.(*GenericFunc)
key := maker.ikey
instance, _ := fun.Instances[key]
g := &c.Globals
debug := g.Options&base.OptDebugGenerics != 0
if instance != nil {
if debug {
g.Debugf("found instantiated generic function %v", maker)
}
} else {
if debug {
g.Debugf("instantiating generic function %v", maker)
}
// hard part: instantiate the generic function.
// must be instantiated in the same *Comp where it was declared!
instance = maker.instantiateFunc(fun, node)
}
var efun, retfun func(*Env) xr.Value
eaddr := instance.Func
if *eaddr == nil {
// currently instantiating it, see comment in Comp.instantiateTemplateFunc() below.
// We must try again later to dereference instance.Func.
efun = func(env *Env) xr.Value {
return (*eaddr)(env)
}
} else {
efun = *eaddr
}
upn := maker.sym.Upn
if debug {
g.Debugf("generic function: %v, upn = %v, instance = %v", maker, upn, instance)
}
// switch to the correct *Env before evaluating expr
switch upn {
case 0:
retfun = efun
case 1:
retfun = func(env *Env) xr.Value {
return efun(env.Outer)
}
case 2:
retfun = func(env *Env) xr.Value {
return efun(env.Outer.Outer)
}
case c.Depth - 1:
retfun = func(env *Env) xr.Value {
return efun(env.FileEnv)
}
case c.Depth:
retfun = func(env *Env) xr.Value {
return efun(env.FileEnv.Outer)
}
default:
retfun = func(env *Env) xr.Value {
for i := upn; i > 0; i-- {
env = env.Outer
}
return efun(env)
}
}
// always return a new *Expr, in case caller modifies it
return exprFun(instance.Type, retfun)
}
// instantiateFunc instantiates and compiles a generic function.
// node is used only for error messages
func (maker *genericMaker) instantiateFunc(fun *GenericFunc, node ast.Node) *GenericFuncInstance {
// choose the specialization to use
_, special := maker.chooseFunc(fun)
// create a new nested Comp
c := NewComp(maker.comp, nil)
c.UpCost = 0
c.Depth--
// and inject generic arguments into it
special.injectBinds(c)
key := maker.ikey
panicking := true
defer func() {
if panicking {
delete(fun.Instances, key)
c.ErrorAt(node.Pos(), "error instantiating generic function: %v\n\t%v", maker, recover())
}
}()
if c.Globals.Options&base.OptDebugGenerics != 0 {
c.Debugf("forward-declaring generic function before instantiation: %v", maker)
}
// support for generic recursive functions, as for example
// template[T] func fib(n T) T { if n <= 2 { return 1 }; return fib#[T](n-1) + fib#[T](n-2) }
// requires to cache fib#[T] as instantiated **before** actually instantiating it.
//
// This is similar to the technique used for non-generic recursive function, as
// func fib(n int) int { if n <= 2 { return 1 }; return fib(n-1) + fib(n-2) }
// with the difference that the cache is fun.Instances[key] instead of Comp.Binds[name]
// for such trick to work, we must:
// 1. compute in advance the instantiated function type
// 2. check GenericFuncInstance.Func: if it's nil, take its address and dereference it later at runtime
t, _, _ := c.TypeFunction(special.decl.Decl.Type)
instance := &GenericFuncInstance{Type: t, Func: new(func(*Env) xr.Value)}
fun.Instances[key] = instance
// compile an expression that, when evaluated at runtime in the *Env
// where the generic function was declared, returns the instantiated function
expr := c.FuncLit(special.decl.Decl)
*instance.Func = expr.AsX1()
instance.Type = expr.Type
panicking = false
return instance
}