/
compositelit.go
346 lines (325 loc) · 9.12 KB
/
compositelit.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
334
335
336
337
338
339
340
341
342
343
344
345
346
/*
* gomacro - A Go interpreter with Lisp-like macros
*
* Copyright (C) 2017-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/.
*
*
* compositelit.go
*
* Created on May 28, 2017
* Author Massimiliano Ghilardi
*/
package fast
import (
"go/ast"
r "reflect"
"github.com/cosmos72/gomacro/base/untyped"
xr "github.com/cosmos72/gomacro/xreflect"
)
func (c *Comp) CompositeLit(node *ast.CompositeLit, t xr.Type) *Expr {
var ellipsis bool
// node.Type is nil when exploiting type inference
if node.Type != nil {
var et xr.Type
et, ellipsis = c.compileType2(node.Type, false)
if et != nil {
if t == nil || et.AssignableTo(t) {
t = et
} else {
c.Errorf("invalid type for composite literal: <%v> %v, expecting %v", et, node.Type, t)
}
}
}
if t == nil {
c.Errorf("no explicit type and no inferred type, cannot compile composite literal: %v", node)
}
switch t.Kind() {
case xr.Array:
return c.compositeLitArray(t.Resolve(), ellipsis, node)
case xr.Map:
return c.compositeLitMap(t, node)
case xr.Slice:
return c.compositeLitSlice(t.Resolve(), node)
case xr.Struct:
return c.compositeLitStruct(t.Resolve(), node)
case xr.Ptr:
switch t.Elem().Kind() {
case xr.Array, r.Map, r.Slice, r.Struct:
return c.addressOf(node, t.Resolve())
}
}
c.Errorf("invalid type for composite literal: <%v> %v", t, node.Type)
return nil
}
func (c *Comp) compositeLitArray(t xr.Type, ellipsis bool, node *ast.CompositeLit) *Expr {
n := len(node.Elts)
if n == 0 {
return exprX1(t, func(env *Env) xr.Value {
// array len is already encoded in its type
return xr.New(t).Elem()
})
}
size, keys, funvals := c.compositeLitElements(t, ellipsis, node)
if ellipsis {
// rebuild type with correct length
t = c.Universe.ArrayOf(size, t.Elem())
}
telem := t.Elem()
rtelem := telem.ReflectType()
zeroelem := xr.Zero(telem)
return exprX1(t, func(env *Env) xr.Value {
obj := xr.New(t).Elem()
var val xr.Value
for i, funval := range funvals {
val = funval(env)
if !val.IsValid() || val == None {
val = zeroelem
} else if val.Type() != rtelem {
val = convert(val, rtelem)
}
obj.Index(keys[i]).Set(val)
}
return obj
})
}
func (c *Comp) compositeLitSlice(t xr.Type, node *ast.CompositeLit) *Expr {
rtype := t.ReflectType()
n := len(node.Elts)
if n == 0 {
return exprX1(t, func(env *Env) xr.Value {
return xr.MakeSlice(t, 0, 0)
})
}
size, keys, funvals := c.compositeLitElements(t, false, node)
rtelem := rtype.Elem()
zeroelem := xr.ZeroR(rtelem)
return exprX1(t, func(env *Env) xr.Value {
obj := xr.MakeSlice(t, size, size)
var val xr.Value
for i, funval := range funvals {
val = funval(env)
if !val.IsValid() || val == None {
val = zeroelem
} else if val.Type() != rtelem {
val = convert(val, rtelem)
}
obj.Index(keys[i]).Set(val)
}
return obj
})
}
func (c *Comp) compositeLitElements(t xr.Type, ellipsis bool, node *ast.CompositeLit) (size int, keys []int, funvals []func(*Env) xr.Value) {
n := len(node.Elts)
tval := t.Elem()
seen := make(map[int]bool) // indexes already seen
keys = make([]int, n)
funvals = make([]func(*Env) xr.Value, n)
size = 0
key, lastkey := 0, -1
for i, el := range node.Elts {
elv := el
switch elkv := el.(type) {
case *ast.KeyValueExpr:
ekey := c.Expr1(elkv.Key, nil)
if !ekey.Const() {
c.Errorf("literal %s index must be non-negative integer constant: %v", t.Kind(), elkv.Key)
} else if ekey.Untyped() {
key = ekey.ConstTo(c.TypeOfInt()).(int)
} else {
key = untyped.ConvertLiteralCheckOverflow(ekey.Value, c.TypeOfInt()).(int)
}
lastkey = key
elv = elkv.Value
default:
lastkey++
}
if lastkey < 0 {
c.Errorf("literal %s index must be non-negative integer constant: %v", t.Kind(), lastkey)
} else if !ellipsis && t.Kind() == r.Array && lastkey >= t.Len() {
c.Errorf("%s index %d out of bounds [0:%d]", t.Kind(), lastkey, t.Len())
} else if seen[lastkey] {
c.Errorf("duplicate index in %s literal: %d", t.Kind(), lastkey)
}
seen[lastkey] = true
if size <= lastkey {
if lastkey == MaxInt {
c.Errorf("literal %s too large: found index == MaxInt", t.Kind())
}
size = lastkey + 1
}
keys[i] = lastkey
eval := c.Expr1(elv, tval)
if eval.Const() {
eval.ConstTo(tval)
} else if !eval.Type.AssignableTo(tval) {
c.Errorf("cannot use %v <%v> as type <%v> in %s value", elv, eval.Type, tval, t.Kind())
} else {
eval.To(c, tval)
}
funvals[i] = eval.AsX1()
}
return size, keys, funvals
}
func (c *Comp) compositeLitMap(t xr.Type, node *ast.CompositeLit) *Expr {
n := len(node.Elts)
if n == 0 {
return exprX1(t, func(env *Env) xr.Value {
return xr.MakeMap(t)
})
}
tkey := t.Key()
tval := t.Elem()
seen := make(map[interface{}]bool) // constant keys already seen
funkeys := make([]func(*Env) xr.Value, n)
funvals := make([]func(*Env) xr.Value, n)
for i, el := range node.Elts {
switch elkv := el.(type) {
case *ast.KeyValueExpr:
ekey := c.Expr1(elkv.Key, tkey)
if ekey.Const() {
ekey.ConstTo(tkey)
if seen[ekey.Value] {
c.Errorf("duplicate key %v in map literal", elkv.Key)
}
seen[ekey.Value] = true
} else if !ekey.Type.AssignableTo(tkey) {
c.Errorf("cannot use %v <%v> as type <%v> in map key", elkv.Key, ekey.Type, tkey)
} else {
ekey.To(c, tkey)
}
eval := c.Expr1(elkv.Value, tval)
if eval.Const() {
eval.ConstTo(tval)
} else if !eval.Type.AssignableTo(tval) {
c.Errorf("cannot use %v <%v> as type <%v> in map value", elkv.Value, eval.Type, tval)
} else {
eval.To(c, tval)
}
funkeys[i] = ekey.AsX1()
funvals[i] = eval.AsX1()
default:
c.Errorf("missing key in map literal: %v", el)
}
}
return exprX1(t, func(env *Env) xr.Value {
obj := xr.MakeMap(t)
var key, val xr.Value
for i, funkey := range funkeys {
key = funkey(env)
val = funvals[i](env)
obj.SetMapIndex(key, val)
}
return obj
})
}
func (c *Comp) compositeLitStruct(t xr.Type, node *ast.CompositeLit) *Expr {
n := len(node.Elts)
if n == 0 {
return exprX1(t, func(env *Env) xr.Value {
return xr.New(t).Elem()
})
}
var seen map[string]bool
var all map[string]xr.StructField
inits := make([]func(*Env) xr.Value, n)
indexes := make([]int, n)
var flagkv, flagv bool
for i, el := range node.Elts {
switch elkv := el.(type) {
case *ast.KeyValueExpr:
flagkv = true
if flagv {
c.Errorf("mixture of field:value and value in struct literal: %v", node)
}
switch k := elkv.Key.(type) {
case *ast.Ident:
name := k.Name
if seen[name] {
c.Errorf("duplicate field name in struct literal: %v", name)
} else if seen == nil {
seen = make(map[string]bool)
all = listStructFields(t, c.FileComp().Path)
}
field, ok := all[name]
if !ok {
c.Errorf("unknown field '%v' in struct literal of type %v", name, t)
}
expr := c.Expr1(elkv.Value, field.Type)
if expr.Const() {
expr.ConstTo(field.Type)
} else if !expr.Type.AssignableTo(field.Type) {
c.Errorf("cannot use %v <%v> as type <%v> in field value", elkv.Value, expr.Type, field.Type)
} else {
expr.To(c, field.Type)
}
inits[i] = expr.AsX1()
indexes[i] = field.Index[0]
default:
c.Errorf("invalid field name '%v' in struct literal", k)
}
default:
flagv = true
if flagkv {
c.Errorf("mixture of field:value and value in struct literal: %v", node)
}
field := t.Field(i)
expr := c.Expr1(el, field.Type)
if expr.Const() {
expr.ConstTo(field.Type)
} else if !expr.Type.AssignableTo(field.Type) {
c.Errorf("cannot use %v <%v> as type <%v> in field value", el, expr.Type, field.Type)
} else {
expr.To(c, field.Type)
}
if !ast.IsExported(field.Name) && field.Pkg.Path() != c.FileComp().Path {
c.Errorf("implicit assignment of unexported field '%v' in struct literal <%v>", field.Name, t)
}
inits[i] = expr.AsX1()
indexes[i] = field.Index[0]
}
}
if nfield := t.NumField(); flagv && n != nfield {
var label, plural = "few", "s"
if n > nfield {
label = "many"
} else if n == 1 {
plural = ""
}
c.Errorf("too %s values in struct initializer: <%v> has %d fields, found %d initializer%s",
label, t, nfield, n, plural)
}
return exprX1(t, func(env *Env) xr.Value {
obj := xr.New(t).Elem()
var val, field xr.Value
var tfield r.Type
for i, init := range inits {
val = init(env)
if !val.IsValid() || val == None {
continue
}
field = obj.Field(indexes[i])
tfield = field.Type()
if val.Type() != tfield {
val = convert(val, tfield)
}
field.Set(val)
}
return obj
})
}
// listStructFields lists the field names of a struct. It ignores embedded fields.
// Unexported fields are listed only if their package's path matches given pkgpath
func listStructFields(t xr.Type, pkgpath string) map[string]xr.StructField {
list := make(map[string]xr.StructField)
for i, n := 0, t.NumField(); i < n; i++ {
f := t.Field(i)
if ast.IsExported(f.Name) || f.Pkg.Path() == pkgpath {
list[f.Name] = f
}
}
return list
}