Debian Codegraph @

internal/decoder/interface.go

raw
1 package decoder
2
3 import (
4 "encoding/json"
5 "reflect"
6 "strconv"
7 "unsafe"
8
9 "github.com/goccy/go-json/internal/errors"
10 "github.com/goccy/go-json/internal/runtime"
11 )
12
13 type interfaceDecoder struct {
14 typ reflect.Type
15 // hasMethods is set for an interface type which has methods, whose value is not replaced by the decoded value
16 // ( see decodeWithMethods ): the value of an interface{} is read without reflect ( see Decode ).
17 hasMethods bool
18 // values are how the values of the types which the interface value holds are decoded, by the type of an
19 // interface{}, or by the itab of an interface type with methods ( see valueDecoderOf ).
20 values runtime.TypeCache[ifaceValueDecoder]
21 structName string
22 fieldName string
23 sliceDecoder *sliceDecoder
24 mapDecoder *mapDecoder
25 floatDecoder *floatDecoder
26 numberDecoder *numberDecoder
27 stringDecoder *stringDecoder
28 }
29
30 func newEmptyInterfaceDecoder(structName, fieldName string) *interfaceDecoder {
31 ifaceDecoder := &interfaceDecoder{
32 typ: emptyInterfaceType,
33 structName: structName,
34 fieldName: fieldName,
35 floatDecoder: newFloatDecoder(structName, fieldName, func(p unsafe.Pointer, v float64) {
36 *(*any)(p) = v
37 }),
38 numberDecoder: newNumberDecoder(structName, fieldName, func(p unsafe.Pointer, v json.Number) {
39 *(*any)(p) = v
40 }),
41 stringDecoder: newStringDecoder(structName, fieldName),
42 }
43 ifaceDecoder.sliceDecoder = newSliceDecoder(
44 ifaceDecoder,
45 emptyInterfaceType,
46 emptyInterfaceType.Size(),
47 structName, fieldName,
48 )
49 ifaceDecoder.mapDecoder = newMapDecoder(
50 interfaceMapType,
51 stringType,
52 ifaceDecoder.stringDecoder,
53 interfaceMapType.Elem(),
54 ifaceDecoder,
55 structName,
56 fieldName,
57 )
58 return ifaceDecoder
59 }
60
61 func newInterfaceDecoder(typ reflect.Type, structName, fieldName string) *interfaceDecoder {
62 emptyIfaceDecoder := newEmptyInterfaceDecoder(structName, fieldName)
63 stringDecoder := newStringDecoder(structName, fieldName)
64 return &interfaceDecoder{
65 typ: typ,
66 hasMethods: typ.NumMethod() > 0,
67 structName: structName,
68 fieldName: fieldName,
69 sliceDecoder: newSliceDecoder(
70 emptyIfaceDecoder,
71 emptyInterfaceType,
72 emptyInterfaceType.Size(),
73 structName, fieldName,
74 ),
75 mapDecoder: newMapDecoder(
76 interfaceMapType,
77 stringType,
78 stringDecoder,
79 interfaceMapType.Elem(),
80 emptyIfaceDecoder,
81 structName,
82 fieldName,
83 ),
84 floatDecoder: newFloatDecoder(structName, fieldName, func(p unsafe.Pointer, v float64) {
85 *(*any)(p) = v
86 }),
87 numberDecoder: newNumberDecoder(structName, fieldName, func(p unsafe.Pointer, v json.Number) {
88 *(*any)(p) = v
89 }),
90 stringDecoder: stringDecoder,
91 }
92 }
93
94 var (
95 emptyInterfaceType = reflect.TypeOf((*any)(nil)).Elem()
96 EmptyInterfaceType = emptyInterfaceType
97 interfaceMapType = reflect.TypeOf((*map[string]any)(nil)).Elem()
98 stringType = reflect.TypeOf("")
99 )
100
101 type emptyInterface struct {
102 typ unsafe.Pointer
103 ptr unsafe.Pointer
104 }
105
106 func (d *interfaceDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) {
107 if d.hasMethods {
108 return d.decodeWithMethods(ctx, cursor, depth, p)
109 }
110 // p is an interface{}: a nil one, the most common, is decoded as it is, and the value of another one may be
111 // decoded into what it points to
112 h := (*emptyInterface)(p)
113 if h.ptr == nil {
114 return d.decodeEmptyInterface(ctx, cursor, depth, p)
115 }
116 v := d.values.Load(uintptr(h.typ))
117 if v == nil {
118 var err error
119 if v, err = d.valueDecoderOf(ctx, h.typ, *(*any)(p)); err != nil {
120 return 0, err
121 }
122 }
123 return d.decodeValue(ctx, cursor, depth, p, v, h.ptr)
124 }
125
126 // ifaceValueKind is how the value which an interface value holds is decoded, as encoding/json does.
127 type ifaceValueKind uint8
128
129 const (
130 // ifaceValueReplaced is a value of an interface{} which is replaced by the value decoded as the one of an
131 // interface{}.
132 ifaceValueReplaced ifaceValueKind = iota
133 // ifaceValuePointee is a pointer to a value which is not an interface value: the value is decoded into what it
134 // points to, as a value of the pointer type, whose unmarshalers are used.
135 ifaceValuePointee
136 // ifaceValueKept is a value of an interface type with methods which is not a pointer: it is kept, and can be
137 // decoded from null only, which sets the interface value to nil.
138 ifaceValueKept
139 )
140
141 // ifaceValueDecoder is how a value of a type which an interface value holds is decoded, which depends on the type
142 // only: it is found once for a type.
143 type ifaceValueDecoder struct {
144 kind ifaceValueKind
145 // dec is the decoder of a pointer of ifaceValuePointee.
146 dec Decoder
147 // textType is the pointer type of ifaceValuePointee which implements encoding.TextUnmarshaler: a value which
148 // is not a string is a type error of the interface value ( see ifaceTextUnmarshalerKindError ).
149 textType reflect.Type
150 }
151
152 // valueDecoderOf finds how the value iface, of the type typ, which the interface value holds is decoded, and
153 // keeps it for the type by key: the type of an interface{}, or the itab of an interface type with methods.
154 func (d *interfaceDecoder) valueDecoderOf(ctx *RuntimeContext, key unsafe.Pointer, iface any) (*ifaceValueDecoder, error) {
155 v := &ifaceValueDecoder{kind: ifaceValueReplaced}
156 if d.hasMethods {
157 v.kind = ifaceValueKept
158 }
159 if typ := reflect.TypeOf(iface); typ.Kind() == reflect.Ptr && typ.Elem() != d.typ {
160 dec, err := ctx.DecoderOf((*emptyInterface)(unsafe.Pointer(&iface)).typ)
161 if err != nil {
162 return nil, err
163 }
164 v.kind, v.dec = ifaceValuePointee, dec
165 if text, ok := dec.(*unmarshalTextDecoder); ok {
166 v.textType = text.typ
167 }
168 }
169 return d.values.Store(uintptr(key), v), nil
170 }
171
172 // decodeValue decodes the value at cursor into the interface value at p, which holds a value decoded as v says,
173 // whose data word is ptr.
174 func (d *interfaceDecoder) decodeValue(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer, v *ifaceValueDecoder, ptr unsafe.Pointer) (int64, error) {
175 switch v.kind {
176 case ifaceValueReplaced:
177 return d.decodeEmptyInterface(ctx, cursor, depth, p)
178 case ifaceValuePointee:
179 buf := ctx.Buf
180 cursor = skipWhiteSpace(buf, cursor)
181 if buf[cursor] == 'n' {
182 // null sets the interface value to nil, not what it points to
183 if err := validateNull(buf, cursor); err != nil {
184 return 0, err
185 }
186 *(*[2]unsafe.Pointer)(p) = [2]unsafe.Pointer{}
187 return cursor + 4, nil
188 }
189 if v.textType != nil && isOtherValue(buf[cursor], stringValue) {
190 return ctx.ifaceTextUnmarshalerKindError(cursor, depth, d.typ, v.textType)
191 }
192 return v.dec.Decode(ctx, cursor, depth, ptr)
193 }
194 return d.decodeKept(ctx, cursor, depth, p)
195 }
196
197 // decodeKept decodes the value at cursor into the interface value at p of an interface type with methods, whose
198 // value is not decoded into: null sets it to nil, and any other value is a type error, which keeps it, as
199 // encoding/json does.
200 func (d *interfaceDecoder) decodeKept(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) {
201 buf := ctx.Buf
202 cursor = skipWhiteSpace(buf, cursor)
203 if buf[cursor] == 'n' {
204 if err := validateNull(buf, cursor); err != nil {
205 return 0, err
206 }
207 *(*[2]unsafe.Pointer)(p) = [2]unsafe.Pointer{}
208 return cursor + 4, nil
209 }
210 return ctx.keptInterfaceTypeError(cursor, depth, d.typ, p)
211 }
212
213 // nonEmptyInterface is the layout of a value of an interface type with methods: the itab of the type it holds,
214 // which is nil for a nil value, and the data word.
215 type nonEmptyInterface struct {
216 itab unsafe.Pointer
217 ptr unsafe.Pointer
218 }
219
220 // decodeWithMethods decodes the value of an interface type which has methods: a value which is a pointer is
221 // decoded into what it points to, as encoding/json does. How a value is decoded is kept by its itab, which is of
222 // one type for the interface type of the decoder.
223 func (d *interfaceDecoder) decodeWithMethods(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) {
224 h := (*nonEmptyInterface)(p)
225 if h.itab == nil || h.ptr == nil {
226 // a nil value, or a nil pointer
227 return d.decodeKept(ctx, cursor, depth, p)
228 }
229 v := d.values.Load(uintptr(h.itab))
230 if v == nil {
231 var err error
232 if v, err = d.valueDecoderOf(ctx, h.itab, reflect.NewAt(d.typ, p).Elem().Interface()); err != nil {
233 return 0, err
234 }
235 }
236 return d.decodeValue(ctx, cursor, depth, p, v, h.ptr)
237 }
238
239 // decodeFloatSlow decodes the number at cursor into the interface{} at p, which the fast parse doesn't: a number
240 // which is not valid by the grammar is a syntax error, and a number out of the range of a float64 is a type error,
241 // after which the decoding goes on ( see floatRangeErrorOfInterface ). It is not inlined, so that the decoding of
242 // the values of interface{} keeps the size it had.
243 //
244 //go:noinline
245 func decodeFloatSlow(ctx *RuntimeContext, cursor int64, p unsafe.Pointer) (int64, error) {
246 buf := ctx.Buf
247 end, err := numberEnd(buf, cursor)
248 if err != nil {
249 return 0, err
250 }
251 b := buf[cursor:end]
252 f, parseErr := strconv.ParseFloat(*(*string)(unsafe.Pointer(&b)), 64)
253 // a number of the grammar which ParseFloat fails is out of the range of float64
254 if inRange := parseErr == nil; !inRange {
255 ctx.floatRangeErrorOfInterface(cursor, end, f, p)
256 return end, nil
257 }
258 **(**any)(unsafe.Pointer(&p)) = ctx.boxFloat(f)
259 return end, nil
260 }
261
262 func (d *interfaceDecoder) decodeEmptyInterface(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) {
263 buf := ctx.Buf
264 cursor = skipWhiteSpace(buf, cursor)
265 switch buf[cursor] {
266 case '{':
267 depth++
268 if depth > maxDecodeNestingDepth {
269 return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor)
270 }
271 m, cursor, err := decodeNewStringAnyMap(ctx, d, cursor, depth)
272 if err != nil {
273 return 0, err
274 }
275 **(**any)(unsafe.Pointer(&p)) = m
276 return cursor, nil
277 case '[':
278 return d.decodeAnySlice(ctx, cursor, depth, p)
279 case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
280 if (ctx.Option.Flags & UseNumberOption) != 0 {
281 return d.numberDecoder.Decode(ctx, cursor, depth, p)
282 }
283 if f, next, ok := parseFloatFast(buf, cursor); ok && validEndNumberChar[buf[next]] {
284 **(**any)(unsafe.Pointer(&p)) = ctx.boxFloat(f)
285 return next, nil
286 }
287 return decodeFloatSlow(ctx, cursor, p)
288 case '"':
289 if end := plainStringEnd(buf, cursor+1); end >= 0 {
290 **(**any)(unsafe.Pointer(&p)) = ctx.boxString(ctx.makeString(buf[cursor+1 : end]))
291 return end + 1, nil
292 }
293 s, c, _, err := d.stringDecoder.decodeString(ctx, cursor)
294 if err != nil {
295 return 0, err
296 }
297 **(**any)(unsafe.Pointer(&p)) = ctx.boxString(s)
298 return c, nil
299 case 't':
300 if err := validateTrue(buf, cursor); err != nil {
301 return 0, err
302 }
303 cursor += 4
304 **(**any)(unsafe.Pointer(&p)) = true
305 return cursor, nil
306 case 'f':
307 if err := validateFalse(buf, cursor); err != nil {
308 return 0, err
309 }
310 cursor += 5
311 **(**any)(unsafe.Pointer(&p)) = false
312 return cursor, nil
313 case 'n':
314 if err := validateNull(buf, cursor); err != nil {
315 return 0, err
316 }
317 cursor += 4
318 **(**any)(unsafe.Pointer(&p)) = nil
319 return cursor, nil
320 }
321 return cursor, errors.ErrInvalidBeginningOfValue(buf[cursor], cursor)
322 }
323
324 // decodeStringAnyMap decodes the object at cursor into m, a map[string]interface{}, by the assignment of Go:
325 // the values are decoded as interface{} by d. depth counts the object already.
326 func decodeStringAnyMap(ctx *RuntimeContext, d *interfaceDecoder, m map[string]any, cursor, depth int64) (int64, error) {
327 buf := ctx.Buf
328 cursor++ // '{'
329 cursor = skipWhiteSpace(buf, cursor)
330 if buf[cursor] == '}' {
331 return cursor + 1, nil
332 }
333 for {
334 key, c, ok, err := d.stringDecoder.decodeString(ctx, cursor)
335 if err != nil {
336 return 0, err
337 }
338 if !ok {
339 // null is not a key
340 return 0, errors.ErrSyntax("invalid character 'n' looking for beginning of object key string", skipWhiteSpace(buf, cursor)+1)
341 }
342 cursor = skipWhiteSpace(buf, c)
343 if buf[cursor] != ':' {
344 return 0, errors.ErrExpected("colon after object key", cursor)
345 }
346 cursor++
347 c, err = d.decodeEmptyInterface(ctx, cursor, depth, unsafe.Pointer(&ctx.slot))
348 if err != nil {
349 ctx.slot = nil
350 return 0, err
351 }
352 m[key] = ctx.slot
353 ctx.slot = nil
354 cursor = skipWhiteSpace(buf, c)
355 switch buf[cursor] {
356 case '}':
357 return cursor + 1, nil
358 case ',':
359 cursor++
360 default:
361 return 0, errors.ErrExpected("comma after object value", cursor)
362 }
363 }
364 }
365
366 // decodeNewStringAnyMap decodes the object at cursor into a new map[string]interface{}. The entries are pushed
367 // to the stack of entries of the context, each key with its value, and put into a map of their number at the end
368 // of the object: a map filled entry by entry grows and moves its entries several times on the way, which took
369 // more time than the entries themselves. A key which is repeated is put later, so that the last one wins as in a
370 // map filled in order.
371 func decodeNewStringAnyMap(ctx *RuntimeContext, d *interfaceDecoder, cursor, depth int64) (map[string]any, int64, error) {
372 buf := ctx.Buf
373 cursor++ // '{'
374 cursor = skipWhiteSpace(buf, cursor)
375 if buf[cursor] == '}' {
376 return map[string]any{}, cursor + 1, nil
377 }
378 base := len(ctx.entryStack)
379 fail := func(err error) (map[string]any, int64, error) {
380 ctx.slot = nil
381 ctx.popEntries(base)
382 return nil, 0, err
383 }
384 for {
385 if cursor = skipWhiteSpace(buf, cursor); buf[cursor] != '"' {
386 return fail(syntaxErrorAt(buf, cursor, whereKey))
387 }
388 var key string
389 var c int64
390 if end := plainStringEnd(buf, cursor+1); end >= 0 {
391 key, c = ctx.makeString(buf[cursor+1:end]), end+1
392 } else {
393 var err error
394 if key, c, _, err = d.stringDecoder.decodeString(ctx, cursor); err != nil {
395 return fail(err)
396 }
397 }
398 cursor = skipWhiteSpace(buf, c)
399 if buf[cursor] != ':' {
400 return fail(syntaxErrorAt(buf, cursor, whereAfterKey))
401 }
402 cursor++
403 c, err := d.decodeEmptyInterface(ctx, cursor, depth, unsafe.Pointer(&ctx.slot))
404 if err != nil {
405 return fail(err)
406 }
407 // the key and the value are pushed together, after the value, whose own entries are popped already.
408 ctx.entryStack = append(ctx.entryStack, anyEntry{key: key, value: ctx.slot})
409 ctx.slot = nil
410 cursor = skipWhiteSpace(buf, c)
411 switch buf[cursor] {
412 case '}':
413 entries := ctx.entryStack[base:]
414 m := make(map[string]any, len(entries))
415 for i := range entries {
416 m[entries[i].key] = entries[i].value
417 }
418 ctx.popEntries(base)
419 return m, cursor + 1, nil
420 case ',':
421 cursor++
422 default:
423 return fail(errors.ErrExpected("comma after object value", cursor))
424 }
425 }
426 }
427
428 // emptyAnySlice is the value of an empty array as interface{}: an empty []interface{}, which all of them share,
429 // so that it is not allocated for each. It has no room for an element, so that nothing is written through it.
430 var emptyAnySlice any = []any{}
431
432 // decodeAnySlice decodes the array at cursor as a []interface{}: the elements are pushed to the stack
433 // of the context, and copied into a slice of their number at the end of the array.
434 func (d *interfaceDecoder) decodeAnySlice(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) {
435 buf := ctx.Buf
436 depth++
437 if depth > maxDecodeNestingDepth {
438 return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor)
439 }
440 cursor++ // '['
441 cursor = skipWhiteSpace(buf, cursor)
442 if buf[cursor] == ']' {
443 **(**any)(unsafe.Pointer(&p)) = emptyAnySlice
444 return cursor + 1, nil
445 }
446 base := len(ctx.anyStack)
447 for {
448 c, err := d.decodeEmptyInterface(ctx, cursor, depth, unsafe.Pointer(&ctx.slot))
449 if err != nil {
450 ctx.slot = nil
451 ctx.popAny(base)
452 return 0, err
453 }
454 ctx.anyStack = append(ctx.anyStack, ctx.slot)
455 ctx.slot = nil
456 cursor = skipWhiteSpace(buf, c)
457 switch buf[cursor] {
458 case ']':
459 elems := make([]any, len(ctx.anyStack)-base)
460 copy(elems, ctx.anyStack[base:])
461 ctx.popAny(base)
462 **(**any)(unsafe.Pointer(&p)) = elems
463 return cursor + 1, nil
464 case ',':
465 cursor++
466 default:
467 ctx.popAny(base)
468 return 0, errors.ErrInvalidCharacter(buf[cursor], "slice", cursor)
469 }
470 }
471 }
472
473 func NewPathDecoder() Decoder {
474 ifaceDecoder := &interfaceDecoder{
475 typ: emptyInterfaceType,
476 structName: "",
477 fieldName: "",
478 floatDecoder: newFloatDecoder("", "", func(p unsafe.Pointer, v float64) {
479 *(*any)(p) = v
480 }),
481 numberDecoder: newNumberDecoder("", "", func(p unsafe.Pointer, v json.Number) {
482 *(*any)(p) = v
483 }),
484 stringDecoder: newStringDecoder("", ""),
485 }
486 ifaceDecoder.sliceDecoder = newSliceDecoder(
487 ifaceDecoder,
488 emptyInterfaceType,
489 emptyInterfaceType.Size(),
490 "", "",
491 )
492 ifaceDecoder.mapDecoder = newMapDecoder(
493 interfaceMapType,
494 stringType,
495 ifaceDecoder.stringDecoder,
496 interfaceMapType.Elem(),
497 ifaceDecoder,
498 "", "",
499 )
500 return ifaceDecoder
501 }
502
503 var (
504 truebytes = []byte("true")
505 falsebytes = []byte("false")
506 )
507
508 func (d *interfaceDecoder) DecodePath(ctx *RuntimeContext, cursor, depth int64) ([][]byte, int64, error) {
509 buf := ctx.Buf
510 cursor = skipWhiteSpace(buf, cursor)
511 switch buf[cursor] {
512 case '{':
513 return d.mapDecoder.DecodePath(ctx, cursor, depth)
514 case '[':
515 return d.sliceDecoder.DecodePath(ctx, cursor, depth)
516 case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
517 return d.floatDecoder.DecodePath(ctx, cursor, depth)
518 case '"':
519 return d.stringDecoder.DecodePath(ctx, cursor, depth)
520 case 't':
521 if err := validateTrue(buf, cursor); err != nil {
522 return nil, 0, err
523 }
524 cursor += 4
525 return [][]byte{truebytes}, cursor, nil
526 case 'f':
527 if err := validateFalse(buf, cursor); err != nil {
528 return nil, 0, err
529 }
530 cursor += 5
531 return [][]byte{falsebytes}, cursor, nil
532 case 'n':
533 if err := validateNull(buf, cursor); err != nil {
534 return nil, 0, err
535 }
536 cursor += 4
537 return [][]byte{nullbytes}, cursor, nil
538 }
539 return nil, cursor, errors.ErrInvalidBeginningOfValue(buf[cursor], cursor)
540 }