-
-
Notifications
You must be signed in to change notification settings - Fork 108
/
fields.go
350 lines (320 loc) · 7.98 KB
/
fields.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
package pogs
import (
"fmt"
"reflect"
"strings"
"zombiezen.com/go/capnproto2/internal/schema"
)
type fieldProps struct {
schemaName string // empty if doesn't map to schema
typ fieldType
fixedWhich string
tagged bool
}
type fieldType int
const (
mappedField fieldType = iota
whichField
embedField
)
func parseField(f reflect.StructField, hasDiscrim bool) fieldProps {
var p fieldProps
tag := f.Tag.Get("capnp")
p.tagged = tag != ""
tname, opts := nextOpt(tag)
switch tname {
case "-":
// omitted field
case "":
if f.Anonymous && isStructOrStructPtr(f.Type) {
p.typ = embedField
return p
}
if hasDiscrim && f.Name == "Which" {
p.typ = whichField
for len(opts) > 0 {
var curr string
curr, opts = nextOpt(opts)
if strings.HasPrefix(curr, "which=") {
p.fixedWhich = strings.TrimPrefix(curr, "which=")
break
}
}
return p
}
// TODO(light): check it's uppercase.
x := f.Name[0] - 'A' + 'a'
p.schemaName = string(x) + f.Name[1:]
default:
p.schemaName = tname
}
return p
}
func nextOpt(opts string) (head, tail string) {
i := strings.Index(opts, ",")
if i == -1 {
return opts, ""
}
return opts[:i], opts[i+1:]
}
type fieldLoc struct {
i int
path []int
}
func (loc fieldLoc) depth() int {
if len(loc.path) > 0 {
return len(loc.path)
}
return 1
}
func (loc fieldLoc) sub(i int) fieldLoc {
n := len(loc.path)
switch {
case !loc.isValid():
return fieldLoc{i: i}
case n > 0:
p := make([]int, n+1)
copy(p, loc.path)
p[n] = i
return fieldLoc{path: p}
default:
return fieldLoc{path: []int{loc.i, i}}
}
}
func (loc fieldLoc) isValid() bool {
return loc.i >= 0
}
type structProps struct {
fields []fieldLoc
whichLoc fieldLoc // i == -1: none; i == -2: fixed
fixedWhich uint16
}
func mapStruct(t reflect.Type, n schema.Node) (structProps, error) {
fields, err := n.StructNode().Fields()
if err != nil {
return structProps{}, err
}
sp := structProps{
fields: make([]fieldLoc, fields.Len()),
whichLoc: fieldLoc{i: -1},
}
for i := range sp.fields {
sp.fields[i] = fieldLoc{i: -1}
}
sm := structMapper{
sp: &sp,
t: t,
hasDiscrim: hasDiscriminant(n),
fields: fields,
}
if err := sm.visit(fieldLoc{i: -1}); err != nil {
return structProps{}, err
}
for len(sm.embedQueue) > 0 {
loc := sm.embedQueue[0]
copy(sm.embedQueue, sm.embedQueue[1:])
sm.embedQueue = sm.embedQueue[:len(sm.embedQueue)-1]
if err := sm.visit(loc); err != nil {
return structProps{}, err
}
}
return sp, nil
}
type structMapper struct {
sp *structProps
t reflect.Type
hasDiscrim bool
fields schema.Field_List
embedQueue []fieldLoc
}
func (sm *structMapper) visit(base fieldLoc) error {
t := sm.t
if base.isValid() {
t = typeFieldByLoc(t, base).Type
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.PkgPath != "" && !f.Anonymous {
// unexported field
continue
}
loc := base.sub(i)
p := parseField(f, sm.hasDiscrim)
if p.typ == embedField {
sm.embedQueue = append(sm.embedQueue, loc)
continue
}
if err := sm.visitField(loc, f, p); err != nil {
return err
}
}
return nil
}
func (sm *structMapper) visitField(loc fieldLoc, f reflect.StructField, p fieldProps) error {
switch p.typ {
case mappedField:
if p.schemaName == "" {
return nil
}
fi := fieldIndex(sm.fields, p.schemaName)
if fi < 0 {
return fmt.Errorf("%v has unknown field %s, maps to %s", sm.t, f.Name, p.schemaName)
}
switch oldloc := sm.sp.fields[fi]; {
case oldloc.i == -2:
// Prior tag collision, do nothing.
case oldloc.i == -3 && p.tagged && loc.depth() == len(oldloc.path):
// A tagged field wins over untagged fields.
sm.sp.fields[fi] = loc
case oldloc.isValid() && oldloc.depth() < loc.depth():
// This is deeper, don't override.
case oldloc.isValid() && oldloc.depth() == loc.depth():
oldp := parseField(typeFieldByLoc(sm.t, oldloc), sm.hasDiscrim)
if oldp.tagged && p.tagged {
// Tag collision
sm.sp.fields[fi] = fieldLoc{i: -2}
} else if p.tagged {
sm.sp.fields[fi] = loc
} else if !oldp.tagged {
// Multiple untagged fields. Keep path, because we need it for depth.
sm.sp.fields[fi].i = -3
}
default:
sm.sp.fields[fi] = loc
}
case whichField:
if sm.sp.whichLoc.i != -1 {
return fmt.Errorf("%v embeds multiple Which fields", sm.t)
}
switch {
case p.fixedWhich != "":
fi := fieldIndex(sm.fields, p.fixedWhich)
if fi < 0 {
return fmt.Errorf("%v.Which is tagged with unknown field %s", sm.t, p.fixedWhich)
}
dv := sm.fields.At(fi).DiscriminantValue()
if dv == schema.Field_noDiscriminant {
return fmt.Errorf("%v.Which is tagged with non-union field %s", sm.t, p.fixedWhich)
}
sm.sp.whichLoc = fieldLoc{i: -2}
sm.sp.fixedWhich = dv
case f.Type.Kind() != reflect.Uint16:
return fmt.Errorf("%v.Which is type %v, not uint16", sm.t, f.Type)
default:
sm.sp.whichLoc = loc
}
}
return nil
}
// fieldBySchemaName returns the field for the given name.
// Returns an invalid value if the field was not found or it is
// contained inside a nil anonymous struct pointer.
func (sp structProps) fieldByOrdinal(val reflect.Value, i int) reflect.Value {
return fieldByLoc(val, sp.fields[i], false)
}
// makeFieldBySchemaName returns the field for the given name, creating
// its parent anonymous structs if necessary. Returns an invalid value
// if the field was not found.
func (sp structProps) makeFieldByOrdinal(val reflect.Value, i int) reflect.Value {
return fieldByLoc(val, sp.fields[i], true)
}
// which returns the value of the discriminator field.
func (sp structProps) which(val reflect.Value) (discrim uint16, ok bool) {
if sp.whichLoc.i == -2 {
return sp.fixedWhich, true
}
f := fieldByLoc(val, sp.whichLoc, false)
if !f.IsValid() {
return 0, false
}
return uint16(f.Uint()), true
}
// setWhich sets the value of the discriminator field, creating its
// parent anonymous structs if necessary. Returns whether the struct
// had a field to set.
func (sp structProps) setWhich(val reflect.Value, discrim uint16) error {
if sp.whichLoc.i == -2 {
if discrim != sp.fixedWhich {
return fmt.Errorf("extract union field @%d into %v; expected @%d", discrim, val.Type(), sp.fixedWhich)
}
return nil
}
f := fieldByLoc(val, sp.whichLoc, true)
if !f.IsValid() {
return noWhichError{val.Type()}
}
f.SetUint(uint64(discrim))
return nil
}
type noWhichError struct {
t reflect.Type
}
func (e noWhichError) Error() string {
return fmt.Sprintf("%v has no field Which", e.t)
}
func isNoWhichError(e error) bool {
_, ok := e.(noWhichError)
return ok
}
func fieldByLoc(val reflect.Value, loc fieldLoc, mkparents bool) reflect.Value {
if !loc.isValid() {
return reflect.Value{}
}
if len(loc.path) > 0 {
for i, x := range loc.path {
if i > 0 {
if val.Kind() == reflect.Ptr {
if val.IsNil() {
if !mkparents {
return reflect.Value{}
}
val.Set(reflect.New(val.Type().Elem()))
}
val = val.Elem()
}
}
val = val.Field(x)
}
return val
}
return val.Field(loc.i)
}
func typeFieldByLoc(t reflect.Type, loc fieldLoc) reflect.StructField {
if len(loc.path) > 0 {
return t.FieldByIndex(loc.path)
}
return t.Field(loc.i)
}
func hasDiscriminant(n schema.Node) bool {
return n.Which() == schema.Node_Which_structNode && n.StructNode().DiscriminantCount() > 0
}
func shortDisplayName(n schema.Node) []byte {
dn, _ := n.DisplayNameBytes()
return dn[n.DisplayNamePrefixLength():]
}
func fieldIndex(fields schema.Field_List, name string) int {
for i := 0; i < fields.Len(); i++ {
b, _ := fields.At(i).NameBytes()
if bytesStrEqual(b, name) {
return i
}
}
return -1
}
func bytesStrEqual(b []byte, s string) bool {
if len(b) != len(s) {
return false
}
for i := range b {
if b[i] != s[i] {
return false
}
}
return true
}
func isStructOrStructPtr(t reflect.Type) bool {
return t.Kind() == reflect.Struct || t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
}