-
-
Notifications
You must be signed in to change notification settings - Fork 371
/
type.go
516 lines (487 loc) · 12.5 KB
/
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
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
package main
import (
"bufio"
"bytes"
"fmt"
)
type TypeClass int
const (
ClassBoolean TypeClass = iota
ClassNumeric
ClassComplex
ClassString
ClassArray
ClassSlice
ClassStruct
ClassPointer
ClassFunction
ClassInterface
ClassMap
ClassChan
TraitAny
TraitOrdered
TraitComparable
TraitIndexable
TraitReceivable
TraitSendable
TraitHashable
TraitPrintable
TraitLenCapable
TraitGlobal
)
type Type struct {
id string
class TypeClass
namedUserType bool
ktyp *Type // map key, chan elem, array elem, slice elem, pointee type
vtyp *Type // map val
utyp *Type // underlying type
styp []*Type // function arguments
rtyp []*Type // function return values
elems []*Var // struct fields and interface methods
literal func() string
complexLiteral func() string
// TODO: cache types
// pointerTo *Type
}
func (smith *Smith) initTypes() {
smith.predefinedTypes = []*Type{
{id: "string", class: ClassString, literal: func() string { return "\"foo\"" }},
{id: "bool", class: ClassBoolean, literal: func() string { return "false" }},
{id: "int", class: ClassNumeric, literal: func() string { return "1" }},
{id: "byte", class: ClassNumeric, literal: func() string { return "byte(0)" }},
{id: "interface{}", class: ClassInterface, literal: func() string { return "interface{}(nil)" }},
{id: "rune", class: ClassNumeric, literal: func() string { return "rune(0)" }},
{id: "float32", class: ClassNumeric, literal: func() string { return "float32(1.0)" }},
{id: "float64", class: ClassNumeric, literal: func() string { return "1.0" }},
{id: "complex64", class: ClassComplex, literal: func() string { return "complex64(1i)" }},
{id: "complex128", class: ClassComplex, literal: func() string { return "1i" }},
{id: "uint", class: ClassNumeric, literal: func() string { return "uint(1)" }},
{id: "uintptr", class: ClassNumeric, literal: func() string { return "uintptr(0)" }},
{id: "int16", class: ClassNumeric, literal: func() string { return "int16(1)" }},
{id: "error", class: ClassInterface, literal: func() string { return "error(nil)" }},
}
for _, t := range smith.predefinedTypes {
t.utyp = t
}
smith.stringType = smith.predefinedTypes[0]
smith.boolType = smith.predefinedTypes[1]
smith.intType = smith.predefinedTypes[2]
smith.byteType = smith.predefinedTypes[3]
smith.efaceType = smith.predefinedTypes[4]
smith.runeType = smith.predefinedTypes[5]
smith.float32Type = smith.predefinedTypes[6]
smith.float64Type = smith.predefinedTypes[7]
smith.complex64Type = smith.predefinedTypes[8]
smith.complex128Type = smith.predefinedTypes[9]
smith.stringType.complexLiteral = func() string {
if smith.rndBool() {
return `"ab\x0acd"`
}
return "`abc\\x0acd`"
}
}
func fmtTypeList(list []*Type, parens bool) string {
var buf bytes.Buffer
if parens || len(list) > 1 {
buf.Write([]byte{'('})
}
for i, t := range list {
if i != 0 {
buf.Write([]byte{','})
}
fmt.Fprintf(&buf, "%v", t.id)
}
if parens || len(list) > 1 {
buf.Write([]byte{')'})
}
return buf.String()
}
func (smith *Smith) atype(trait TypeClass) *Type {
smith.typeDepth++
defer func() {
smith.typeDepth--
}()
for {
if smith.typeDepth >= 3 || smith.rndBool() {
var cand []*Type
for _, t := range smith.types() {
if smith.satisfiesTrait(t, trait) {
cand = append(cand, t)
}
}
if len(cand) > 0 {
return cand[smith.rnd(len(cand))]
}
}
t := smith.typeLit()
if t != nil && smith.satisfiesTrait(t, trait) {
return t
}
}
}
func (smith *Smith) typeLit() *Type {
switch smith.choice("array", "chan", "struct", "pointer", "interface", "slice", "function", "map") {
case "array":
return smith.arrayOf(smith.atype(TraitAny))
case "chan":
return smith.chanOf(smith.atype(TraitAny))
case "struct":
var elems []*Var
var buf bytes.Buffer
fmt.Fprintf(&buf, "struct { ")
for smith.rndBool() {
e := &Var{id: smith.newId("Field"), typ: smith.atype(TraitAny)}
elems = append(elems, e)
fmt.Fprintf(&buf, "%v %v\n", e.id, e.typ.id)
}
fmt.Fprintf(&buf, "}")
id := buf.String()
return &Type{
id: id,
class: ClassStruct,
elems: elems,
literal: func() string {
return F("(%v{})", id)
},
complexLiteral: func() string {
if smith.rndBool() {
// unnamed
var buf bytes.Buffer
fmt.Fprintf(&buf, "(%v{", id)
for i := 0; i < len(elems); i++ {
fmt.Fprintf(&buf, "%v, ", smith.rvalue(elems[i].typ))
}
fmt.Fprintf(&buf, "})")
return buf.String()
} else {
// named
var buf bytes.Buffer
fmt.Fprintf(&buf, "(%v{", id)
for i := 0; i < len(elems); i++ {
if smith.rndBool() {
fmt.Fprintf(&buf, "%v: %v, ", elems[i].id, smith.rvalue(elems[i].typ))
}
}
fmt.Fprintf(&buf, "})")
return buf.String()
}
},
}
case "pointer":
return pointerTo(smith.atype(TraitAny))
case "interface":
var buf bytes.Buffer
fmt.Fprintf(&buf, "interface { ")
for smith.rndBool() {
fmt.Fprintf(&buf, " %v %v %v\n", smith.newId("Method"),
fmtTypeList(smith.atypeList(TraitAny), true),
fmtTypeList(smith.atypeList(TraitAny), false))
}
fmt.Fprintf(&buf, "}")
return &Type{
id: buf.String(),
class: ClassInterface,
literal: func() string {
return F("%v(nil)", buf.String())
},
}
case "slice":
return smith.sliceOf(smith.atype(TraitAny))
case "function":
return smith.funcOf(smith.atypeList(TraitAny), smith.atypeList(TraitAny))
case "map":
ktyp := smith.atype(TraitHashable)
vtyp := smith.atype(TraitAny)
return &Type{
id: F("map[%v]%v", ktyp.id, vtyp.id),
class: ClassMap,
ktyp: ktyp,
vtyp: vtyp,
literal: func() string {
if smith.rndBool() {
cap := ""
if smith.rndBool() {
cap = "," + smith.rvalue(smith.intType)
}
return F("make(map[%v]%v %v)", ktyp.id, vtyp.id, cap)
} else {
return F("map[%v]%v{}", ktyp.id, vtyp.id)
}
},
}
default:
panic("bad")
}
}
func (smith *Smith) satisfiesTrait(t *Type, trait TypeClass) bool {
if trait < TraitAny {
return t.class == trait
}
switch trait {
case TraitAny:
return true
case TraitOrdered:
return t.class == ClassNumeric || t.class == ClassString
case TraitComparable:
return t.class == ClassBoolean || t.class == ClassNumeric || t.class == ClassString ||
t.class == ClassPointer || t.class == ClassChan || t.class == ClassInterface
case TraitIndexable:
return t.class == ClassArray || t.class == ClassSlice || t.class == ClassString ||
t.class == ClassMap
case TraitReceivable:
return t.class == ClassChan
case TraitSendable:
return t.class == ClassChan
case TraitHashable:
if t.class == ClassFunction || t.class == ClassMap || t.class == ClassSlice {
return false
}
if t.class == ClassArray && !smith.satisfiesTrait(t.ktyp, TraitHashable) {
return false
}
if t.class == ClassStruct {
for _, e := range t.elems {
if !smith.satisfiesTrait(e.typ, TraitHashable) {
return false
}
}
}
return true
case TraitPrintable:
return t.class == ClassBoolean || t.class == ClassNumeric || t.class == ClassString ||
t.class == ClassPointer || t.class == ClassInterface
case TraitLenCapable:
return t.class == ClassString || t.class == ClassSlice || t.class == ClassArray ||
t.class == ClassMap || t.class == ClassChan
case TraitGlobal:
for _, t1 := range smith.predefinedTypes {
if t == t1 {
return true
}
}
return false
default:
panic("bad")
}
}
func (smith *Smith) atypeList(trait TypeClass) []*Type {
n := smith.rnd(4) + 1
list := make([]*Type, n)
for i := 0; i < n; i++ {
list[i] = smith.atype(trait)
}
return list
}
func typeList(t *Type, n int) []*Type {
list := make([]*Type, n)
for i := 0; i < n; i++ {
list[i] = t
}
return list
}
func pointerTo(elem *Type) *Type {
return &Type{
id: F("*%v", elem.id),
class: ClassPointer,
ktyp: elem,
literal: func() string {
return F("(*%v)(nil)", elem.id)
}}
}
func (smith *Smith) chanOf(elem *Type) *Type {
return &Type{
id: F("chan %v", elem.id),
class: ClassChan,
ktyp: elem,
literal: func() string {
cap := ""
if smith.rndBool() {
cap = "," + smith.rvalue(smith.intType)
}
return F("make(chan %v %v)", elem.id, cap)
},
}
}
func (smith *Smith) sliceOf(elem *Type) *Type {
return &Type{
id: F("[]%v", elem.id),
class: ClassSlice,
ktyp: elem,
literal: func() string {
return F("[]%v{}", elem.id)
},
complexLiteral: func() string {
switch smith.choice("normal", "keyed") {
case "normal":
return F("[]%v{%v}", elem.id, smith.fmtRvalueList(typeList(elem, smith.rnd(3))))
case "keyed":
n := smith.rnd(3)
var indexes []int
loop:
for len(indexes) < n {
i := smith.rnd(10)
for _, i1 := range indexes {
if i1 == i {
continue loop
}
}
indexes = append(indexes, i)
}
var buf bytes.Buffer
fmt.Fprintf(&buf, "[]%v{", elem.id)
for i, idx := range indexes {
if i != 0 {
fmt.Fprintf(&buf, ",")
}
fmt.Fprintf(&buf, "%v: %v", idx, smith.rvalue(elem))
}
fmt.Fprintf(&buf, "}")
return buf.String()
default:
panic("bad")
}
},
}
}
func (smith *Smith) arrayOf(elem *Type) *Type {
size := smith.rnd(3)
return &Type{
id: F("[%v]%v", size, elem.id),
class: ClassArray,
ktyp: elem,
literal: func() string {
return F("[%v]%v{}", size, elem.id)
},
complexLiteral: func() string {
switch smith.choice("normal", "keyed") {
case "normal":
return F("[%v]%v{%v}", smith.choice(F("%v", size), "..."), elem.id, smith.fmtRvalueList(typeList(elem, size)))
case "keyed":
var buf bytes.Buffer
fmt.Fprintf(&buf, "[%v]%v{", size, elem.id)
for i := 0; i < size; i++ {
if i != 0 {
fmt.Fprintf(&buf, ",")
}
fmt.Fprintf(&buf, "%v: %v", i, smith.rvalue(elem))
}
fmt.Fprintf(&buf, "}")
return buf.String()
default:
panic("bad")
}
},
}
}
func (smith *Smith) funcOf(alist, rlist []*Type) *Type {
t := &Type{
id: F("func%v %v", fmtTypeList(alist, true), fmtTypeList(rlist, false)),
class: ClassFunction,
styp: alist,
rtyp: rlist,
}
t.literal = func() string {
return F("((func%v %v)(nil))", fmtTypeList(alist, true), fmtTypeList(rlist, false))
}
t.complexLiteral = func() string {
return smith.genFuncLit(t)
}
return t
}
func (smith *Smith) genFuncLit(ft *Type) string {
//return F("((func%v %v)(nil))", fmtTypeList(ft.styp, true), fmtTypeList(ft.rtyp, false))
if smith.curBlockPos == -1 {
smith.line("")
}
f := &Func{args: ft.styp, rets: ft.rtyp}
curFunc0 := smith.curFunc
smith.curFunc = f
curBlock0 := smith.curBlock
curBlockPos0 := smith.curBlockPos
curBlockLen0 := len(smith.curBlock.sub)
exprDepth0 := smith.exprDepth
exprCount0 := smith.exprCount
smith.exprDepth = 0
smith.exprCount = 0
defer func() {
smith.curBlock = curBlock0
smith.curFunc = curFunc0
smith.exprDepth = exprDepth0
smith.exprCount = exprCount0
smith.curBlockPos = curBlockPos0 + (len(smith.curBlock.sub) - curBlockLen0)
}()
fb := &Block{parent: smith.curBlock, subBlock: smith.curBlock.sub[smith.curBlockPos]}
smith.curBlock = fb
smith.enterBlock(true)
smith.enterBlock(true)
argIds := make([]string, len(f.args))
argStr := ""
for i, a := range f.args {
argIds[i] = smith.newId("Param")
if i != 0 {
argStr += ", "
}
argStr += argIds[i] + " " + a.id
}
smith.line("func(%v)%v {", argStr, fmtTypeList(f.rets, false))
for i, a := range f.args {
smith.defineVar(argIds[i], a)
}
smith.curBlock.funcBoundary = true
smith.genBlock()
smith.leaveBlock()
smith.stmtReturn()
smith.line("}")
smith.leaveBlock()
//b := curBlock.sub[curBlockPos]
//copy(curBlock.sub[curBlockPos:], curBlock.sub[curBlockPos+1:])
//curBlock.sub = curBlock.sub[:len(curBlock.sub)-1]
var buf bytes.Buffer
w := bufio.NewWriter(&buf)
serializeBlock(w, fb, 0)
w.Flush()
s := buf.String()
//fmt.Printf("GEN FUNC:\n%v\n", s)
return s[:len(s)-1]
}
func dependsOn(t, t0 *Type) bool {
if t == nil {
return false
}
if t.class == ClassInterface {
// We don't know how to walk all types referenced by an interface yet.
return true
}
if t0 == nil && t.namedUserType {
return true
}
if t == t0 {
return true
}
if dependsOn(t.ktyp, t0) {
return true
}
if dependsOn(t.vtyp, t0) {
return true
}
if dependsOn(t.ktyp, t0) {
return true
}
for _, t1 := range t.styp {
if dependsOn(t1, t0) {
return true
}
}
for _, t1 := range t.rtyp {
if dependsOn(t1, t0) {
return true
}
}
for _, e := range t.elems {
if dependsOn(e.typ, t0) {
return true
}
}
return false
}