Debian Codegraph @

internal/encoder/opcode.go

raw
1 package encoder
2
3 import (
4 "bytes"
5 "fmt"
6 "reflect"
7 "sort"
8 "strings"
9 "unsafe"
10
11 "github.com/goccy/go-json/internal/runtime"
12 )
13
14 const uintptrSize = 4 << (^uintptr(0) >> 63)
15
16 // The offsets of the opcodes are in bytes from the head of the frame.
17 const (
18 slotSize = 2 * uintptrSize // the size of Slot.
19 slotIntOffset = uintptrSize // the offset of Slot.Int.
20 )
21
22 var (
23 _ = [1]struct{}{}[unsafe.Sizeof(Slot{})-slotSize]
24 _ = [1]struct{}{}[unsafe.Offsetof(Slot{}.Int)-slotIntOffset]
25 )
26
27 type OpFlags uint16
28
29 const (
30 AnonymousHeadFlags OpFlags = 1 << 0
31 AnonymousKeyFlags OpFlags = 1 << 1
32 IndirectFlags OpFlags = 1 << 2
33 IsTaggedKeyFlags OpFlags = 1 << 3
34 NilCheckFlags OpFlags = 1 << 4
35 AddrForMarshalerFlags OpFlags = 1 << 5
36 IsNextOpPtrTypeFlags OpFlags = 1 << 6
37 IsNilableTypeFlags OpFlags = 1 << 7
38 MarshalerContextFlags OpFlags = 1 << 8
39 NonEmptyInterfaceFlags OpFlags = 1 << 9
40 MapStringKeyFlags OpFlags = 1 << 10 // the key of the map is a string, written by OpMapKey itself
41 TailRecursiveFlags OpFlags = 1 << 11 // the recursive value is the last field of a value of its own type, encoded in its frame
42 InterfaceMapKeyFlags OpFlags = 1 << 12 // the key of a map of an interface type, whose name is of its dynamic value ( see appendInterfaceMapKey )
43 MapKeyFlags OpFlags = 1 << 13 // the key of a map, whose name is "" for a nil pointer, while a nil pointer value is null
44 )
45
46 type Opcode struct {
47 Op OpType // operation type
48 EmptyKind EmptyKind // what makes the value of the field empty for omitempty, for the generic field opcode
49 ZeroKind ZeroKind // what makes the value of the field zero for omitzero, for the generic field opcode
50 Idx uint32 // offset to access ptr
51 Next *Opcode // next opcode
52 End *Opcode // array/slice/struct/map end
53 NextField *Opcode // next struct field
54 Key string // struct field key
55 Offset uint32 // offset size from struct header
56 PtrNum uint8 // pointer number: e.g. double pointer is 2.
57 NumBitSize uint8
58 Flags OpFlags
59
60 Type unsafe.Pointer // pointer to the type descriptor of go type
61 Jmp *CompiledCode // for recursive call
62 Marshaler *MarshalerCall // the method of the marshaler, for MarshalJSON and MarshalText
63 FieldQuery *FieldQuery // field query for Interface / MarshalJSON / MarshalText
64 ElemIdx uint32 // offset to access array/slice elem
65 Length uint32 // offset to access slice length or array length
66 Indent uint32 // indent number
67 Size uint32 // array/slice elem size
68 DisplayIdx uint32 // opcode index
69 KeyChunk *[KeyChunkSize]byte // the key and the padding after it, which the VM copies as a chunk
70 Map *MapLayout // how the entries of the map are read, for the opcode of a map
71 }
72
73 func (c *Opcode) Validate() error {
74 var prevIdx uint32
75 for code := c; !code.IsEnd(); {
76 if prevIdx != 0 {
77 if code.DisplayIdx != prevIdx+1 {
78 return fmt.Errorf(
79 "invalid index. previous display index is %d but next is %d. dump = %s",
80 prevIdx, code.DisplayIdx, c.Dump(),
81 )
82 }
83 }
84 prevIdx = code.DisplayIdx
85 code = code.IterNext()
86 }
87 return nil
88 }
89
90 func (c *Opcode) IterNext() *Opcode {
91 if c == nil {
92 return nil
93 }
94 switch c.Op.CodeType() {
95 case CodeArrayElem, CodeSliceElem, CodeMapKey:
96 return c.End
97 default:
98 return c.Next
99 }
100 }
101
102 func (c *Opcode) IsEnd() bool {
103 if c == nil {
104 return true
105 }
106 return c.Op == OpEnd || c.Op == OpInterfaceEnd || c.Op == OpRecursiveEnd
107 }
108
109 func (c *Opcode) MaxIdx() uint32 {
110 maxIdx := uint32(0)
111 for _, value := range []uint32{
112 c.Idx,
113 c.ElemIdx,
114 c.Length,
115 c.Size,
116 } {
117 if maxIdx < value {
118 maxIdx = value
119 }
120 }
121 return maxIdx
122 }
123
124 // ToStringOp returns the opcode which encodes the value of t as a string, for the string option of a field.
125 func (t OpType) ToStringOp() OpType {
126 switch t {
127 case OpInt:
128 return OpIntString
129 case OpUint:
130 return OpUintString
131 case OpFloat32:
132 return OpFloat32String
133 case OpFloat64:
134 return OpFloat64String
135 case OpBool:
136 return OpBoolString
137 case OpString:
138 return OpStringString
139 case OpNumber:
140 return OpNumberString
141 case OpIntPtr:
142 return OpIntPtrString
143 case OpUintPtr:
144 return OpUintPtrString
145 case OpFloat32Ptr:
146 return OpFloat32PtrString
147 case OpFloat64Ptr:
148 return OpFloat64PtrString
149 case OpBoolPtr:
150 return OpBoolPtrString
151 case OpStringPtr:
152 return OpStringPtrString
153 case OpNumberPtr:
154 return OpNumberPtrString
155 }
156 return t
157 }
158
159 func (c *Opcode) ToFieldType(isString bool) OpType {
160 switch c.Op {
161 case OpInterface:
162 // the string option is not for a value of interface{}.
163 return OpStructFieldInterface
164 case OpInt:
165 if isString {
166 return OpStructFieldIntString
167 }
168 return OpStructFieldInt
169 case OpIntPtr:
170 if isString {
171 return OpStructFieldIntPtrString
172 }
173 return OpStructFieldIntPtr
174 case OpUint:
175 if isString {
176 return OpStructFieldUintString
177 }
178 return OpStructFieldUint
179 case OpUintPtr:
180 if isString {
181 return OpStructFieldUintPtrString
182 }
183 return OpStructFieldUintPtr
184 case OpFloat32:
185 if isString {
186 return OpStructFieldFloat32String
187 }
188 return OpStructFieldFloat32
189 case OpFloat32Ptr:
190 if isString {
191 return OpStructFieldFloat32PtrString
192 }
193 return OpStructFieldFloat32Ptr
194 case OpFloat64:
195 if isString {
196 return OpStructFieldFloat64String
197 }
198 return OpStructFieldFloat64
199 case OpFloat64Ptr:
200 if isString {
201 return OpStructFieldFloat64PtrString
202 }
203 return OpStructFieldFloat64Ptr
204 case OpString:
205 if isString {
206 return OpStructFieldStringString
207 }
208 return OpStructFieldString
209 case OpStringPtr:
210 if isString {
211 return OpStructFieldStringPtrString
212 }
213 return OpStructFieldStringPtr
214 case OpNumber:
215 if isString {
216 return OpStructFieldNumberString
217 }
218 return OpStructFieldNumber
219 case OpNumberPtr:
220 if isString {
221 return OpStructFieldNumberPtrString
222 }
223 return OpStructFieldNumberPtr
224 case OpBool:
225 if isString {
226 return OpStructFieldBoolString
227 }
228 return OpStructFieldBool
229 case OpBoolPtr:
230 if isString {
231 return OpStructFieldBoolPtrString
232 }
233 return OpStructFieldBoolPtr
234 case OpBytes:
235 return OpStructFieldBytes
236 case OpBytesPtr:
237 return OpStructFieldBytesPtr
238 case OpMap:
239 return OpStructFieldMap
240 case OpMapPtr:
241 c.Op = OpMap
242 return OpStructFieldMapPtr
243 case OpArray:
244 return OpStructFieldArray
245 case OpArrayPtr:
246 c.Op = OpArray
247 return OpStructFieldArrayPtr
248 case OpSlice:
249 return OpStructFieldSlice
250 case OpSlicePtr:
251 c.Op = OpSlice
252 return OpStructFieldSlicePtr
253 case OpMarshalJSON:
254 return OpStructFieldMarshalJSON
255 case OpMarshalJSONPtr:
256 return OpStructFieldMarshalJSONPtr
257 case OpMarshalText:
258 return OpStructFieldMarshalText
259 case OpMarshalTextPtr:
260 return OpStructFieldMarshalTextPtr
261 }
262 return OpStructField
263 }
264
265 func newOpCode(ctx *compileContext, typ reflect.Type, op OpType) *Opcode {
266 return newOpCodeWithNext(ctx, typ, op, newEndOp(ctx, typ))
267 }
268
269 // opcodeOffset returns the offset of the pointer of the slot.
270 func opcodeOffset(idx int) uint32 {
271 return uint32(idx) * slotSize
272 }
273
274 // opcodeIntOffset returns the offset of the value of the slot which is not a pointer.
275 func opcodeIntOffset(idx int) uint32 {
276 return opcodeOffset(idx) + slotIntOffset
277 }
278
279 func getCodeAddrByIdx(head *Opcode, idx uint32) *Opcode {
280 addr := uintptr(unsafe.Pointer(head)) + uintptr(idx)*unsafe.Sizeof(Opcode{})
281 return *(**Opcode)(unsafe.Pointer(&addr))
282 }
283
284 func copyOpcode(code *Opcode) *Opcode {
285 codeNum := ToEndCode(code).DisplayIdx + 1
286 codeSlice := make([]Opcode, codeNum)
287 head := (*Opcode)((*runtime.SliceHeader)(unsafe.Pointer(&codeSlice)).Data)
288 ptr := head
289 c := code
290 for {
291 *ptr = Opcode{
292 Op: c.Op,
293 Key: c.Key,
294 PtrNum: c.PtrNum,
295 NumBitSize: c.NumBitSize,
296 Flags: c.Flags,
297 Idx: c.Idx,
298 Offset: c.Offset,
299 Type: c.Type,
300 FieldQuery: c.FieldQuery,
301 DisplayIdx: c.DisplayIdx,
302 KeyChunk: c.KeyChunk,
303 Map: c.Map,
304 EmptyKind: c.EmptyKind,
305 ZeroKind: c.ZeroKind,
306 ElemIdx: c.ElemIdx,
307 Length: c.Length,
308 Size: c.Size,
309 Indent: c.Indent,
310 Jmp: c.Jmp,
311 Marshaler: c.Marshaler,
312 }
313 if c.End != nil {
314 ptr.End = getCodeAddrByIdx(head, c.End.DisplayIdx)
315 }
316 if c.NextField != nil {
317 ptr.NextField = getCodeAddrByIdx(head, c.NextField.DisplayIdx)
318 }
319 if c.Next != nil {
320 ptr.Next = getCodeAddrByIdx(head, c.Next.DisplayIdx)
321 }
322 if c.IsEnd() {
323 break
324 }
325 ptr = getCodeAddrByIdx(head, c.DisplayIdx+1)
326 c = c.IterNext()
327 }
328 return head
329 }
330
331 func setTotalLengthToInterfaceOp(code *Opcode) {
332 for c := code; !c.IsEnd(); {
333 switch c.Op {
334 case OpInterface, OpInterfacePtr, OpStructFieldInterface, OpStructFieldOmitEmptyInterface:
335 c.Length = uint32(code.TotalLength())
336 }
337 c = c.IterNext()
338 }
339 }
340
341 func ToEndCode(code *Opcode) *Opcode {
342 c := code
343 for !c.IsEnd() {
344 c = c.IterNext()
345 }
346 return c
347 }
348
349 func copyToInterfaceOpcode(code *Opcode) *Opcode {
350 copied := copyOpcode(code)
351 c := copied
352 c = ToEndCode(c)
353 // the slots to return to the previous frame are after every slot of the code:
354 // the slot of the end code is not the last one, because the fields of a struct share the slots.
355 c.Idx = opcodeOffset(copied.TotalLength())
356 c.setEndSlots()
357 c.Op = OpInterfaceEnd
358 return copied
359 }
360
361 // setEndSlots decides the slots of the opcode which returns to the previous frame from its Idx:
362 // Idx is for the opcode to return to, ElemIdx is for the offset of the previous frame and
363 // Length is for the indent to restore.
364 func (c *Opcode) setEndSlots() {
365 c.ElemIdx = c.Idx + slotSize + slotIntOffset
366 c.Length = c.Idx + 2*slotSize + slotIntOffset
367 }
368
369 func newOpCodeWithNext(ctx *compileContext, typ reflect.Type, op OpType, next *Opcode) *Opcode {
370 return &Opcode{
371 Op: op,
372 Idx: opcodeOffset(ctx.ptrIndex),
373 Next: next,
374 Type: runtime.TypePtr(typ),
375 DisplayIdx: ctx.opcodeIndex,
376 Indent: ctx.indent,
377 }
378 }
379
380 func newEndOp(ctx *compileContext, typ reflect.Type) *Opcode {
381 return newOpCodeWithNext(ctx, typ, OpEnd, nil)
382 }
383
384 func (c *Opcode) TotalLength() int {
385 var idx int
386 code := c
387 for !code.IsEnd() {
388 maxIdx := int(code.MaxIdx() / slotSize)
389 if idx < maxIdx {
390 idx = maxIdx
391 }
392 if code.Op == OpRecursiveEnd {
393 break
394 }
395 code = code.IterNext()
396 }
397 maxIdx := int(code.MaxIdx() / slotSize)
398 if idx < maxIdx {
399 idx = maxIdx
400 }
401 return idx + 1
402 }
403
404 func (c *Opcode) dumpHead(code *Opcode) string {
405 var length uint32
406 if code.Op.CodeType() == CodeArrayHead {
407 length = code.Length
408 } else {
409 length = code.Length / slotSize
410 }
411 return fmt.Sprintf(
412 `[%03d]%s%s ([idx:%d][elemIdx:%d][length:%d])`,
413 code.DisplayIdx,
414 strings.Repeat("-", int(code.Indent)),
415 code.Op,
416 code.Idx/slotSize,
417 code.ElemIdx/slotSize,
418 length,
419 )
420 }
421
422 func (c *Opcode) dumpMapHead(code *Opcode) string {
423 return fmt.Sprintf(
424 `[%03d]%s%s ([idx:%d])`,
425 code.DisplayIdx,
426 strings.Repeat("-", int(code.Indent)),
427 code.Op,
428 code.Idx/slotSize,
429 )
430 }
431
432 func (c *Opcode) dumpMapEnd(code *Opcode) string {
433 return fmt.Sprintf(
434 `[%03d]%s%s ([idx:%d])`,
435 code.DisplayIdx,
436 strings.Repeat("-", int(code.Indent)),
437 code.Op,
438 code.Idx/slotSize,
439 )
440 }
441
442 func (c *Opcode) dumpElem(code *Opcode) string {
443 var length uint32
444 if code.Op.CodeType() == CodeArrayElem {
445 length = code.Length
446 } else {
447 length = code.Length / slotSize
448 }
449 return fmt.Sprintf(
450 `[%03d]%s%s ([idx:%d][elemIdx:%d][length:%d][size:%d])`,
451 code.DisplayIdx,
452 strings.Repeat("-", int(code.Indent)),
453 code.Op,
454 code.Idx/slotSize,
455 code.ElemIdx/slotSize,
456 length,
457 code.Size,
458 )
459 }
460
461 func (c *Opcode) dumpField(code *Opcode) string {
462 return fmt.Sprintf(
463 `[%03d]%s%s ([idx:%d][key:%s][offset:%d])`,
464 code.DisplayIdx,
465 strings.Repeat("-", int(code.Indent)),
466 code.Op,
467 code.Idx/slotSize,
468 code.Key,
469 code.Offset,
470 )
471 }
472
473 func (c *Opcode) dumpKey(code *Opcode) string {
474 return fmt.Sprintf(
475 `[%03d]%s%s ([idx:%d])`,
476 code.DisplayIdx,
477 strings.Repeat("-", int(code.Indent)),
478 code.Op,
479 code.Idx/slotSize,
480 )
481 }
482
483 func (c *Opcode) dumpValue(code *Opcode) string {
484 return fmt.Sprintf(
485 `[%03d]%s%s ([idx:%d])`,
486 code.DisplayIdx,
487 strings.Repeat("-", int(code.Indent)),
488 code.Op,
489 code.Idx/slotSize,
490 )
491 }
492
493 func (c *Opcode) Dump() string {
494 codes := []string{}
495 for code := c; !code.IsEnd(); {
496 switch code.Op.CodeType() {
497 case CodeSliceHead:
498 codes = append(codes, c.dumpHead(code))
499 code = code.Next
500 case CodeMapHead:
501 codes = append(codes, c.dumpMapHead(code))
502 code = code.Next
503 case CodeArrayElem, CodeSliceElem:
504 codes = append(codes, c.dumpElem(code))
505 code = code.End
506 case CodeMapKey:
507 codes = append(codes, c.dumpKey(code))
508 code = code.End
509 case CodeMapValue:
510 codes = append(codes, c.dumpValue(code))
511 code = code.Next
512 case CodeMapEnd:
513 codes = append(codes, c.dumpMapEnd(code))
514 code = code.Next
515 case CodeStructField:
516 codes = append(codes, c.dumpField(code))
517 code = code.Next
518 case CodeStructEnd:
519 codes = append(codes, c.dumpField(code))
520 code = code.Next
521 default:
522 codes = append(codes, fmt.Sprintf(
523 "[%03d]%s%s ([idx:%d])",
524 code.DisplayIdx,
525 strings.Repeat("-", int(code.Indent)),
526 code.Op,
527 code.Idx/slotSize,
528 ))
529 code = code.Next
530 }
531 }
532 return strings.Join(codes, "\n")
533 }
534
535 func (c *Opcode) DumpDOT() string {
536 type edge struct {
537 from, to *Opcode
538 label string
539 weight int
540 }
541 var edges []edge
542
543 b := &bytes.Buffer{}
544 fmt.Fprintf(b, "digraph \"%p\" {\n", c.Type)
545 fmt.Fprintln(b, "mclimit=1.5;\nrankdir=TD;\nordering=out;\nnode[shape=box];")
546 for code := c; !code.IsEnd(); {
547 label := code.Op.String()
548 fmt.Fprintf(b, "\"%p\" [label=%q];\n", code, label)
549 if p := code.Next; p != nil {
550 edges = append(edges, edge{
551 from: code,
552 to: p,
553 label: "Next",
554 weight: 10,
555 })
556 }
557 if p := code.NextField; p != nil {
558 edges = append(edges, edge{
559 from: code,
560 to: p,
561 label: "NextField",
562 weight: 2,
563 })
564 }
565 if p := code.End; p != nil {
566 edges = append(edges, edge{
567 from: code,
568 to: p,
569 label: "End",
570 weight: 1,
571 })
572 }
573 if p := code.Jmp; p != nil {
574 edges = append(edges, edge{
575 from: code,
576 to: p.Code,
577 label: "Jmp",
578 weight: 1,
579 })
580 }
581
582 switch code.Op.CodeType() {
583 case CodeSliceHead:
584 code = code.Next
585 case CodeMapHead:
586 code = code.Next
587 case CodeArrayElem, CodeSliceElem:
588 code = code.End
589 case CodeMapKey:
590 code = code.End
591 case CodeMapValue:
592 code = code.Next
593 case CodeMapEnd:
594 code = code.Next
595 case CodeStructField:
596 code = code.Next
597 case CodeStructEnd:
598 code = code.Next
599 default:
600 code = code.Next
601 }
602 if code.IsEnd() {
603 fmt.Fprintf(b, "\"%p\" [label=%q];\n", code, code.Op.String())
604 }
605 }
606 sort.Slice(edges, func(i, j int) bool {
607 return edges[i].to.DisplayIdx < edges[j].to.DisplayIdx
608 })
609 for _, e := range edges {
610 fmt.Fprintf(b, "\"%p\" -> \"%p\" [label=%q][weight=%d];\n", e.from, e.to, e.label, e.weight)
611 }
612 fmt.Fprint(b, "}")
613 return b.String()
614 }
615
616 // newSliceHeaderCode takes two slots: the first one is for the address of the elements and the index,
617 // and the next one is for the length.
618 func newSliceHeaderCode(ctx *compileContext, typ reflect.Type) *Opcode {
619 idx := opcodeOffset(ctx.ptrIndex)
620 elemIdx := opcodeIntOffset(ctx.ptrIndex)
621 ctx.incPtrIndex()
622 length := opcodeIntOffset(ctx.ptrIndex)
623 return &Opcode{
624 Op: OpSlice,
625 Type: runtime.TypePtr(typ),
626 Idx: idx,
627 DisplayIdx: ctx.opcodeIndex,
628 ElemIdx: elemIdx,
629 Length: length,
630 Indent: ctx.indent,
631 }
632 }
633
634 func newSliceElemCode(ctx *compileContext, typ reflect.Type, head *Opcode, size uintptr) *Opcode {
635 return &Opcode{
636 Op: OpSliceElem,
637 Type: runtime.TypePtr(typ),
638 Idx: head.Idx,
639 DisplayIdx: ctx.opcodeIndex,
640 ElemIdx: head.ElemIdx,
641 Length: head.Length,
642 Indent: ctx.indent,
643 Size: uint32(size),
644 }
645 }
646
647 // newArrayHeaderCode takes a slot, which is for the address of the array and the index.
648 func newArrayHeaderCode(ctx *compileContext, typ reflect.Type, alen int) *Opcode {
649 idx := opcodeOffset(ctx.ptrIndex)
650 elemIdx := opcodeIntOffset(ctx.ptrIndex)
651 return &Opcode{
652 Op: OpArray,
653 Type: runtime.TypePtr(typ),
654 Idx: idx,
655 DisplayIdx: ctx.opcodeIndex,
656 ElemIdx: elemIdx,
657 Indent: ctx.indent,
658 Length: uint32(alen),
659 }
660 }
661
662 func newArrayElemCode(ctx *compileContext, typ reflect.Type, head *Opcode, length int, size uintptr) *Opcode {
663 return &Opcode{
664 Op: OpArrayElem,
665 Type: runtime.TypePtr(typ),
666 Idx: head.Idx,
667 DisplayIdx: ctx.opcodeIndex,
668 ElemIdx: head.ElemIdx,
669 Length: uint32(length),
670 Indent: ctx.indent,
671 Size: uint32(size),
672 }
673 }
674
675 func newMapHeaderCode(ctx *compileContext, typ reflect.Type) *Opcode {
676 idx := opcodeOffset(ctx.ptrIndex)
677 ctx.incPtrIndex()
678 return &Opcode{
679 Op: OpMap,
680 Type: runtime.TypePtr(typ),
681 Map: NewMapLayout(typ),
682 Idx: idx,
683 DisplayIdx: ctx.opcodeIndex,
684 Indent: ctx.indent,
685 }
686 }
687
688 func newMapKeyCode(ctx *compileContext, typ reflect.Type, head *Opcode) *Opcode {
689 return &Opcode{
690 Op: OpMapKey,
691 Type: runtime.TypePtr(typ),
692 Idx: head.Idx,
693 DisplayIdx: ctx.opcodeIndex,
694 Indent: ctx.indent,
695 }
696 }
697
698 func newMapValueCode(ctx *compileContext, typ reflect.Type, head *Opcode) *Opcode {
699 return &Opcode{
700 Op: OpMapValue,
701 Type: runtime.TypePtr(typ),
702 Idx: head.Idx,
703 DisplayIdx: ctx.opcodeIndex,
704 Indent: ctx.indent,
705 }
706 }
707
708 func newMapEndCode(ctx *compileContext, typ reflect.Type, head *Opcode) *Opcode {
709 return &Opcode{
710 Op: OpMapEnd,
711 Type: runtime.TypePtr(typ),
712 Idx: head.Idx,
713 DisplayIdx: ctx.opcodeIndex,
714 Indent: ctx.indent,
715 Next: newEndOp(ctx, typ),
716 }
717 }
718
719 func newRecursiveCode(ctx *compileContext, typ reflect.Type, jmp *CompiledCode) *Opcode {
720 return &Opcode{
721 Op: OpRecursive,
722 Type: runtime.TypePtr(typ),
723 Idx: opcodeOffset(ctx.ptrIndex),
724 Next: newEndOp(ctx, typ),
725 DisplayIdx: ctx.opcodeIndex,
726 Indent: ctx.indent,
727 Jmp: jmp,
728 }
729 }