/
type.go
571 lines (514 loc) · 15 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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vdl
import (
"fmt"
"strings"
)
// Kind represents the kind of type that a Type represents.
type Kind int
const (
// Variant kinds
Any Kind = iota // any type
Optional // value might not exist
// Scalar kinds
Bool // boolean
Byte // 8 bit unsigned integer
Uint16 // 16 bit unsigned integer
Uint32 // 32 bit unsigned integer
Uint64 // 64 bit unsigned integer
Int8 // 8 bit signed integer
Int16 // 16 bit signed integer
Int32 // 32 bit signed integer
Int64 // 64 bit signed integer
Float32 // 32 bit IEEE 754 floating point
Float64 // 64 bit IEEE 754 floating point
String // unicode string (encoded as UTF-8 in memory)
Enum // one of a set of labels
TypeObject // type represented as a value
// Composite kinds
Array // fixed-length ordered sequence of elements
List // variable-length ordered sequence of elements
Set // unordered collection of distinct keys
Map // unordered association between distinct keys and values
Struct // conjunction of an ordered sequence of (name,type) fields
Union // disjunction of an ordered sequence of (name,type) fields
// Internal kinds; they never appear in a *Type returned to the user.
internalNamed // placeholder for named types while they're being built.
)
var (
kindNames = [internalNamed]string{
"any",
"optional",
"bool",
"byte",
"uint16",
"uint32",
"uint64",
"int8",
"int16",
"int32",
"int64",
"float32",
"float64",
"string",
"enum",
"typeobject",
"array",
"list",
"set",
"map",
"struct",
"union",
}
camelCaseKindNames = [internalNamed]string{
"Any",
"Optional",
"Bool",
"Byte",
"Uint16",
"Uint32",
"Uint64",
"Int8",
"Int16",
"Int32",
"Int64",
"Float32",
"Float64",
"String",
"Enum",
"TypeObject",
"Array",
"List",
"Set",
"Map",
"Struct",
"Union",
}
)
func (k Kind) String() string {
return kindNames[k]
}
func (k Kind) CamelCase() string {
return camelCaseKindNames[k]
}
// IsNumber returns true iff the kind is a number.
func (k Kind) IsNumber() bool {
switch k {
case Byte, Uint16, Uint32, Uint64, Int8, Int16, Int32, Int64, Float32, Float64:
return true
}
return false
}
// BitLen returns the number of bits in the representation of the kind;
// e.g. Int32 returns 32. Returns -1 for non-number kinds.
func (k Kind) BitLen() int {
switch k {
case Byte, Int8:
return 8
case Uint16, Int16:
return 16
case Uint32, Int32, Float32:
return 32
case Uint64, Int64, Float64:
return 64
}
return -1
}
type kindBitMask uint32
func (k *kindBitMask) Set(kind Kind) {
*k |= (1 << uint(kind))
}
func (k kindBitMask) IsSet(kind Kind) bool {
return (k & (1 << uint(kind))) != 0
}
// SplitIdent splits the given identifier into its package path and local name.
// a/b.Foo -> (a/b, Foo)
// a.b/c.Foo -> (a.b/c, Foo)
// Foo -> ("", Foo)
// a/b -> ("", a/b)
func SplitIdent(ident string) (pkgpath, name string) {
dot := strings.LastIndex(ident, ".")
if dot == -1 {
return "", ident
}
return ident[:dot], ident[dot+1:]
}
// Type is the representation of a vanadium type. Types are hash-consed; each
// unique type is represented by exactly one *Type instance, so to test for type
// equality you just compare the *Type instances.
//
// Not all methods apply to all kinds of types. Restrictions are noted in the
// documentation for each method. Calling a method inappropriate to the kind of
// type causes a run-time panic.
//
// Cyclic types are supported; e.g. you can represent a tree via:
// type Node struct {
// Val string
// Children []Node
// }
type Type struct {
kind Kind // used by all kinds
name string // used by all kinds
labels []string // used by Enum
len int // used by Array
elem *Type // used by Optional, Array, List, Map
key *Type // used by Set, Map
fields []Field // used by Struct, Union
fieldIndices map[string]int // used by Struct, Union
unique string // used by all kinds, filled in by typeCons
containsKind kindBitMask // does this type recursively contain a given kind
}
// Field describes a single field in a Struct or Union.
type Field struct {
Name string
Type *Type
}
// Kind returns the kind of type t.
func (t *Type) Kind() Kind { return t.kind }
// Name returns the name of type t. Empty names are allowed.
func (t *Type) Name() string { return t.name }
// String returns a human-readable description of type t. Do not rely on the
// output format; it may change without notice. See Unique for a format that is
// guaranteed never to change.
func (t *Type) String() string {
return t.Unique()
}
// Unique returns a unique representation of type t. Two types A and B are
// guaranteed to return the same unique string iff A is equal to B. The format
// is guaranteed to never change.
//
// A typical use case is to hash the unique representation to produce
// globally-unique type ids.
func (t *Type) Unique() string {
if t.unique != "" {
return t.unique
}
return t.uniqueSlow()
}
//go:noinline
func (t *Type) uniqueSlow() string {
// The only time that t.unique isn't set is while we're in the process of
// building the type, and we're printing the type for errors. The type might
// have unnamed cycles, so we need to use short cycle names.
buf := make([]byte, 0, 256)
buf = uniqueTypeStr(buf, t, make(map[*Type]bool), true, -1)
return string(buf)
}
// CanBeNil returns true iff values of t can be nil.
//
// Any and Optional values can be nil.
func (t *Type) CanBeNil() bool {
return t.kind == Any || t.kind == Optional
}
// CanBeNamed returns true iff t can be made into a named type.
//
// Any and TypeObject cannot be named.
func (t *Type) CanBeNamed() bool {
return t.kind != Any && t.kind != TypeObject
}
// CanBeKey returns true iff t can be used as a set or map key.
//
// Any, List, Map, Optional, Set and TypeObject cannot be keys, nor can
// composite types that contain these types.
func (t *Type) CanBeKey() bool {
return !t.ContainsKind(WalkAll, Any, List, Map, Optional, Set, TypeObject)
}
// CanBeOptional returns true iff t can be made into an optional type.
//
// Only named structs can be optional.
func (t *Type) CanBeOptional() bool {
// Our philosophy is that we should retain the full type information in our
// generated code, and generating annotations to distinguish optional from
// non-optional types is awkward for unnamed types.
//
// Allowing optionality for named types other than structs is also awkward.
// E.g. if we allowed optional named maps, it's unclear how we'd generate it
// in Go. We might just generate a map, which is already a reference type and
// may be nil, but then we can't distinguish optional map types from
// non-optional map types.
return t.name != "" && t.kind == Struct
}
// IsBytes returns true iff the kind of type is []byte or [N]byte.
func (t *Type) IsBytes() bool {
return (t.kind == List || t.kind == Array) && t.elem.kind == Byte
}
// EnumLabel returns the Enum label at the given index. It panics if the index
// is out of range.
func (t *Type) EnumLabel(index int) string {
if t.kind != Enum {
t.panicErrKind("EnumLabel", Enum)
}
return t.labels[index]
}
// EnumIndex returns the Enum index for the given label. Returns -1 if the
// label doesn't exist.
func (t *Type) EnumIndex(label string) int {
if t.kind != Enum {
t.panicErrKind("EnumIndex", Enum)
}
// We typically have a small number of labels, so linear search is fine.
for index, l := range t.labels {
if l == label {
return index
}
}
return -1
}
// NumEnumLabel returns the number of labels in an Enum.
func (t *Type) NumEnumLabel() int {
if t.kind != Enum {
t.panicErrKind("NumEnumLabel", Enum)
}
return len(t.labels)
}
// Len returns the length of an Array.
func (t *Type) Len() int {
if t.kind != Array {
t.panicErrKind("Len", Array)
}
return t.len
}
// Elem returns the element type of an Optional, Array, List or Map.
func (t *Type) Elem() *Type {
switch t.kind {
case Optional, Array, List, Map:
default:
t.panicErrKind("Elem", Optional, Array, List, Map)
}
return t.elem
}
// NonOptional returns t.Elem() if t is Optional, otherwise returns t.
func (t *Type) NonOptional() *Type {
if t.kind == Optional {
return t.elem
}
return t
}
// Key returns the key type of a Set or Map.
func (t *Type) Key() *Type {
switch t.kind {
case Set, Map:
default:
t.panicErrKind("Key", Set, Map)
}
return t.key
}
// Field returns a description of the Struct or Union field at the given index.
func (t *Type) Field(index int) Field {
switch t.kind {
case Struct, Union:
default:
t.panicErrKind("Field", Struct, Union)
}
return t.fields[index]
}
// FieldByName returns a description of the Struct or Union field with the given
// name, and its index. Returns -1 if the name doesn't exist.
func (t *Type) FieldByName(name string) (Field, int) {
switch t.kind {
case Struct, Union:
default:
// Call panic directly to reduce the inlining cost of this method.
panic("vdl: FieldByName mismatched kind; got: " + t.kindString() + "want: struct union")
}
if index, ok := t.fieldIndices[name]; ok {
return t.fields[index], index
}
return Field{}, -1
}
// FieldIndexByName returns the index of the Struct or Union field with
// the given name. Returns -1 if the name doesn't exist.
func (t *Type) FieldIndexByName(name string) int {
switch t.kind {
case Struct, Union:
default:
// Call panic directly to reduce the inlining cost of this method.
panic("vdl: FieldIndexByName mismatched kind; got: " + t.kindString() + "want: struct union")
}
if index, ok := t.fieldIndices[name]; ok {
return index
}
return -1
}
// NumField returns the number of fields in a Struct or Union.
func (t *Type) NumField() int {
switch t.kind {
case Struct, Union:
default:
t.panicErrKind("NumField", Struct, Union)
}
return len(t.fields)
}
// AssignableFrom returns true iff values of t may be assigned from f:
// o Allowed if t and the type of f are identical.
// o Allowed if t is Any.
// o Allowed if t is Optional, and f is Any(nil).
//
// The first rule establishes strict static typing. The second rule relaxes
// things for Any, which is dynamically typed. The third rule relaxes things
// further, to allow implicit conversions from Any(nil) to all Optional types.
func (t *Type) AssignableFrom(f *Value) bool {
return t == f.t || t.kind == Any || (t.kind == Optional && f.t.kind == Any && f.IsNil())
}
// VDLIsZero returns true if t is nil or AnyType.
func (t *Type) VDLIsZero() bool {
return t == nil || t == AnyType
}
// VDLWrite uses enc to encode type t.
//
// Unlike regular VDLWrite implementations, this handles the case where t
// contains a nil value, to make code generation simpler.
func (t *Type) VDLWrite(enc Encoder) error {
if t == nil {
t = AnyType
}
return enc.WriteValueTypeObject(t)
}
// ptype implements the TypeOrPending interface.
func (t *Type) ptype() *Type { return t }
// Prevent these error and panic related functions from being inlined
// so that they don't count toward the cost of inlining their callers.
//go:noinline
func (t *Type) errKind(method string, allowed ...Kind) error {
return fmt.Errorf("vdl: %s mismatched kind; got: %v, want: %v", method, t.kind, allowed)
}
//go:noinline
func (t *Type) errBytes(method string) error {
return fmt.Errorf("vdl: %s mismatched type; got: %v, want: bytes", method, t.kind)
}
//go:noinline
func (t *Type) panicErrKind(method string, allowed ...Kind) {
panic(t.errKind(method, allowed...))
}
//go:noinline
func (t *Type) panicErrBytes(method string) {
panic(t.errBytes(method))
}
//go:noline
func (t *Type) kindString() string {
return t.kind.String()
}
// ContainsKind returns true iff t or subtypes of t match any of the kinds.
func (t *Type) ContainsKind(mode WalkMode, kinds ...Kind) bool {
var containsKind bool
for _, kind := range kinds {
if t.containsKind.IsSet(kind) {
containsKind = true
break
}
}
if mode == WalkAll || !containsKind {
return containsKind
}
return !t.Walk(mode, func(visit *Type) bool {
for _, kind := range kinds {
if kind == visit.kind {
return false
}
}
return true
})
}
// ContainsType returns true iff t or subtypes of t match any of the types.
func (t *Type) ContainsType(mode WalkMode, types ...*Type) bool {
return !t.Walk(mode, func(visit *Type) bool {
for _, ty := range types {
if ty == visit {
return false
}
}
return true
})
}
// Walk performs a DFS walk through the type graph starting from t, calling fn
// for each visited type. If fn returns false on a visited type, the walk is
// terminated early, and false is returned by Walk. The mode controls which
// types in the type graph we will visit.
func (t *Type) Walk(mode WalkMode, fn func(*Type) bool) bool {
return typeWalk(mode, t, fn, make(map[*Type]bool))
}
// WalkMode is the mode to perform a Walk through the type graph.
type WalkMode int
const (
// WalkAll indicates we should walk through all types in the type graph.
WalkAll WalkMode = iota
// WalkInline indicates we should only visit subtypes of array, struct and
// union. Values of array, struct and union always include values of their
// subtypes, thus the subtypes are considered to be inline. Values of
// optional, list, set and map might not include values of their subtypes, and
// are not considered to be inline.
WalkInline
)
func (t *Type) subTypesInline() bool {
switch t.kind {
case Array, Struct, Union:
return true
}
return false
}
func typeWalk(mode WalkMode, t *Type, fn func(*Type) bool, seen map[*Type]bool) bool {
if seen[t] {
return true
}
seen[t] = true
if !fn(t) {
return false
}
if mode == WalkInline && !t.subTypesInline() {
return true
}
switch t.kind {
case Optional, Array, List:
return typeWalk(mode, t.elem, fn, seen)
case Set:
return typeWalk(mode, t.key, fn, seen)
case Map:
return typeWalk(mode, t.key, fn, seen) && typeWalk(mode, t.elem, fn, seen)
case Struct, Union:
for _, field := range t.fields {
if !typeWalk(mode, field.Type, fn, seen) {
return false
}
}
}
return true
}
// IsPartOfCycle returns true iff t is part of a cycle. Note that t is not
// considered to be part of a cycle if it merely contains another type that is
// part of a cycle; the type graph must cycle back through t to return true.
func (t *Type) IsPartOfCycle() bool {
return partOfCycle(t, make(map[*Type]bool))
}
func partOfCycle(t *Type, inCycle map[*Type]bool) bool {
if c, ok := inCycle[t]; ok {
return c
}
inCycle[t] = true
switch t.kind {
case Optional, Array, List:
if partOfCycle(t.elem, inCycle) {
return true
}
case Set:
if partOfCycle(t.key, inCycle) {
return true
}
case Map:
if partOfCycle(t.key, inCycle) {
return true
}
if partOfCycle(t.elem, inCycle) {
return true
}
case Struct, Union:
for _, x := range t.fields {
if partOfCycle(x.Type, inCycle) {
return true
}
}
}
inCycle[t] = false
return false
}