Debian Codegraph @

internal/encoder/code.go

raw
1 package encoder
2
3 import (
4 "fmt"
5 "reflect"
6 "unsafe"
7
8 "github.com/goccy/go-json/internal/runtime"
9 )
10
11 type Code interface {
12 Kind() CodeKind
13 ToOpcode(*compileContext) Opcodes
14 Filter(*FieldQuery) Code
15 }
16
17 type AnonymousCode interface {
18 ToAnonymousOpcode(*compileContext) Opcodes
19 }
20
21 type Opcodes []*Opcode
22
23 func (o Opcodes) First() *Opcode {
24 if len(o) == 0 {
25 return nil
26 }
27 return o[0]
28 }
29
30 func (o Opcodes) Last() *Opcode {
31 if len(o) == 0 {
32 return nil
33 }
34 return o[len(o)-1]
35 }
36
37 func (o Opcodes) Add(codes ...*Opcode) Opcodes {
38 return append(o, codes...)
39 }
40
41 type CodeKind int
42
43 const (
44 CodeKindInterface CodeKind = iota
45 CodeKindPtr
46 CodeKindInt
47 CodeKindUint
48 CodeKindFloat
49 CodeKindString
50 CodeKindBool
51 CodeKindStruct
52 CodeKindMap
53 CodeKindSlice
54 CodeKindArray
55 CodeKindBytes
56 CodeKindMarshalJSON
57 CodeKindMarshalText
58 CodeKindRecursive
59 )
60
61 type IntCode struct {
62 typ reflect.Type
63 bitSize uint8
64 isString bool
65 isPtr bool
66 }
67
68 func (c *IntCode) Kind() CodeKind {
69 return CodeKindInt
70 }
71
72 func (c *IntCode) ToOpcode(ctx *compileContext) Opcodes {
73 var code *Opcode
74 switch {
75 case c.isPtr:
76 code = newOpCode(ctx, c.typ, OpIntPtr)
77 case c.isString:
78 code = newOpCode(ctx, c.typ, OpIntString)
79 default:
80 code = newOpCode(ctx, c.typ, OpInt)
81 }
82 code.NumBitSize = c.bitSize
83 ctx.incIndex()
84 return Opcodes{code}
85 }
86
87 func (c *IntCode) Filter(_ *FieldQuery) Code {
88 return c
89 }
90
91 type UintCode struct {
92 typ reflect.Type
93 bitSize uint8
94 isString bool
95 isPtr bool
96 }
97
98 func (c *UintCode) Kind() CodeKind {
99 return CodeKindUint
100 }
101
102 func (c *UintCode) ToOpcode(ctx *compileContext) Opcodes {
103 var code *Opcode
104 switch {
105 case c.isPtr:
106 code = newOpCode(ctx, c.typ, OpUintPtr)
107 case c.isString:
108 code = newOpCode(ctx, c.typ, OpUintString)
109 default:
110 code = newOpCode(ctx, c.typ, OpUint)
111 }
112 code.NumBitSize = c.bitSize
113 ctx.incIndex()
114 return Opcodes{code}
115 }
116
117 func (c *UintCode) Filter(_ *FieldQuery) Code {
118 return c
119 }
120
121 type FloatCode struct {
122 typ reflect.Type
123 bitSize uint8
124 isPtr bool
125 }
126
127 func (c *FloatCode) Kind() CodeKind {
128 return CodeKindFloat
129 }
130
131 func (c *FloatCode) ToOpcode(ctx *compileContext) Opcodes {
132 var code *Opcode
133 switch {
134 case c.isPtr:
135 switch c.bitSize {
136 case 32:
137 code = newOpCode(ctx, c.typ, OpFloat32Ptr)
138 default:
139 code = newOpCode(ctx, c.typ, OpFloat64Ptr)
140 }
141 default:
142 switch c.bitSize {
143 case 32:
144 code = newOpCode(ctx, c.typ, OpFloat32)
145 default:
146 code = newOpCode(ctx, c.typ, OpFloat64)
147 }
148 }
149 ctx.incIndex()
150 return Opcodes{code}
151 }
152
153 func (c *FloatCode) Filter(_ *FieldQuery) Code {
154 return c
155 }
156
157 type StringCode struct {
158 typ reflect.Type
159 isPtr bool
160 }
161
162 func (c *StringCode) Kind() CodeKind {
163 return CodeKindString
164 }
165
166 func (c *StringCode) ToOpcode(ctx *compileContext) Opcodes {
167 isJSONNumberType := c.typ == jsonNumberType
168 var code *Opcode
169 if c.isPtr {
170 if isJSONNumberType {
171 code = newOpCode(ctx, c.typ, OpNumberPtr)
172 } else {
173 code = newOpCode(ctx, c.typ, OpStringPtr)
174 }
175 } else {
176 if isJSONNumberType {
177 code = newOpCode(ctx, c.typ, OpNumber)
178 } else {
179 code = newOpCode(ctx, c.typ, OpString)
180 }
181 }
182 ctx.incIndex()
183 return Opcodes{code}
184 }
185
186 func (c *StringCode) Filter(_ *FieldQuery) Code {
187 return c
188 }
189
190 type BoolCode struct {
191 typ reflect.Type
192 isPtr bool
193 }
194
195 func (c *BoolCode) Kind() CodeKind {
196 return CodeKindBool
197 }
198
199 func (c *BoolCode) ToOpcode(ctx *compileContext) Opcodes {
200 var code *Opcode
201 switch {
202 case c.isPtr:
203 code = newOpCode(ctx, c.typ, OpBoolPtr)
204 default:
205 code = newOpCode(ctx, c.typ, OpBool)
206 }
207 ctx.incIndex()
208 return Opcodes{code}
209 }
210
211 func (c *BoolCode) Filter(_ *FieldQuery) Code {
212 return c
213 }
214
215 type BytesCode struct {
216 typ reflect.Type
217 isPtr bool
218 }
219
220 func (c *BytesCode) Kind() CodeKind {
221 return CodeKindBytes
222 }
223
224 func (c *BytesCode) ToOpcode(ctx *compileContext) Opcodes {
225 var code *Opcode
226 switch {
227 case c.isPtr:
228 code = newOpCode(ctx, c.typ, OpBytesPtr)
229 default:
230 code = newOpCode(ctx, c.typ, OpBytes)
231 }
232 ctx.incIndex()
233 return Opcodes{code}
234 }
235
236 func (c *BytesCode) Filter(_ *FieldQuery) Code {
237 return c
238 }
239
240 type SliceCode struct {
241 typ reflect.Type
242 value Code
243 }
244
245 func (c *SliceCode) Kind() CodeKind {
246 return CodeKindSlice
247 }
248
249 func (c *SliceCode) ToOpcode(ctx *compileContext) Opcodes {
250 // header => opcode => elem => end
251 // ^ |
252 // |________|
253 size := c.typ.Elem().Size()
254 header := newSliceHeaderCode(ctx, c.typ)
255 ctx.incIndex()
256
257 ctx.incIndent()
258 codes := c.value.ToOpcode(ctx)
259 ctx.decIndent()
260
261 codes.First().Flags |= IndirectFlags
262 // the opcodes after the elements refer to the slots of the header, and they don't take a slot.
263 elemCode := newSliceElemCode(ctx, c.typ.Elem(), header, size)
264 ctx.incOpcodeIndex()
265 end := newOpCode(ctx, c.typ, OpSliceEnd)
266 ctx.incOpcodeIndex()
267 header.End = end
268 header.Next = codes.First()
269 codes.Last().Next = elemCode
270 elemCode.Next = codes.First()
271 elemCode.End = end
272 return Opcodes{header}.Add(codes...).Add(elemCode).Add(end)
273 }
274
275 func (c *SliceCode) Filter(_ *FieldQuery) Code {
276 return c
277 }
278
279 type ArrayCode struct {
280 typ reflect.Type
281 value Code
282 }
283
284 func (c *ArrayCode) Kind() CodeKind {
285 return CodeKindArray
286 }
287
288 func (c *ArrayCode) ToOpcode(ctx *compileContext) Opcodes {
289 // header => opcode => elem => end
290 // ^ |
291 // |________|
292 elem := c.typ.Elem()
293 alen := c.typ.Len()
294 size := elem.Size()
295
296 header := newArrayHeaderCode(ctx, c.typ, alen)
297 ctx.incIndex()
298
299 ctx.incIndent()
300 codes := c.value.ToOpcode(ctx)
301 ctx.decIndent()
302
303 codes.First().Flags |= IndirectFlags
304
305 // the opcodes after the elements refer to the slot of the header, and they don't take a slot.
306 elemCode := newArrayElemCode(ctx, elem, header, alen, size)
307 ctx.incOpcodeIndex()
308
309 end := newOpCode(ctx, c.typ, OpArrayEnd)
310 ctx.incOpcodeIndex()
311
312 header.End = end
313 header.Next = codes.First()
314 codes.Last().Next = elemCode
315 elemCode.Next = codes.First()
316 elemCode.End = end
317
318 return Opcodes{header}.Add(codes...).Add(elemCode).Add(end)
319 }
320
321 func (c *ArrayCode) Filter(_ *FieldQuery) Code {
322 return c
323 }
324
325 type MapCode struct {
326 typ reflect.Type
327 key Code
328 value Code
329 }
330
331 func (c *MapCode) Kind() CodeKind {
332 return CodeKindMap
333 }
334
335 func (c *MapCode) ToOpcode(ctx *compileContext) Opcodes {
336 // header => code => value => code => key => code => value => code => end
337 // ^ |
338 // |_______________________|
339 header := newMapHeaderCode(ctx, c.typ)
340 ctx.incIndex()
341
342 if c.isStringKey() {
343 // header => value => key => end: the key of an entry is written by the header for the first entry and
344 // by OpMapKey for the others, which give the value to its opcode.
345 // ^ |
346 // |_________|
347 header.Flags |= MapStringKeyFlags
348
349 ctx.incIndent()
350 valueCodes := c.value.ToOpcode(ctx)
351 ctx.decIndent()
352 valueCodes.First().Flags |= IndirectFlags
353 header.Map.ScalarValue = len(valueCodes) == 1 && isScalarOp(valueCodes.First().Op) &&
354 header.Map.ValueWords >= 0 && header.Map.ValueWords <= MapScalarValueWords
355
356 key := newMapKeyCode(ctx, c.typ.Key(), header)
357 key.Flags |= MapStringKeyFlags
358 ctx.incOpcodeIndex()
359
360 end := newMapEndCode(ctx, c.typ, header)
361 ctx.incOpcodeIndex()
362
363 header.Next = valueCodes.First()
364 valueCodes.Last().Next = key
365 key.Next = valueCodes.First()
366 header.End = end
367 key.End = end
368 return Opcodes{header}.Add(valueCodes...).Add(key).Add(end)
369 }
370
371 keyCodes := c.key.ToOpcode(ctx)
372 if first := keyCodes.First(); first.Op == OpMarshalText && first.Flags&IsNilableTypeFlags != 0 {
373 // the opcode of the key is given the address of the key, and the marshaler of a key of a pointer
374 // type is called with the pointer.
375 first.Flags |= IndirectFlags
376 }
377
378 // the opcodes other than the header refer to the slot of the header, and they don't take a slot.
379 value := newMapValueCode(ctx, c.typ.Elem(), header)
380 ctx.incOpcodeIndex()
381
382 ctx.incIndent()
383 valueCodes := c.value.ToOpcode(ctx)
384 ctx.decIndent()
385
386 valueCodes.First().Flags |= IndirectFlags
387
388 key := newMapKeyCode(ctx, c.typ.Key(), header)
389 ctx.incOpcodeIndex()
390
391 end := newMapEndCode(ctx, c.typ, header)
392 ctx.incOpcodeIndex()
393
394 header.Next = keyCodes.First()
395 keyCodes.Last().Next = value
396 value.Next = valueCodes.First()
397 valueCodes.Last().Next = key
398 key.Next = keyCodes.First()
399
400 header.End = end
401 key.End = end
402 value.End = end
403 return Opcodes{header}.Add(keyCodes...).Add(value).Add(valueCodes...).Add(key).Add(end)
404 }
405
406 // isStringKey is whether the key of the map is a plain string, which OpMapKey writes itself: not a pointer,
407 // not json.Number, and not a type with a marshaler, whose code is not a StringCode.
408 func (c *MapCode) isStringKey() bool {
409 key, ok := c.key.(*StringCode)
410 return ok && !key.isPtr && key.typ != jsonNumberType
411 }
412
413 func (c *MapCode) Filter(_ *FieldQuery) Code {
414 return c
415 }
416
417 type StructCode struct {
418 typ reflect.Type
419 fields []*StructFieldCode
420 isPtr bool
421 disableIndirectConversion bool
422 isIndirect bool
423 isRecursive bool
424 // isHiddenByItself is whether the struct is a recursive one embedded in itself, which has nothing to write.
425 isHiddenByItself bool
426 // fieldQuery is the query which the fields of a recursive struct are filtered by: the code which is jumped
427 // to is filtered by it when the recursive codes are linked.
428 fieldQuery *FieldQuery
429 }
430
431 func (c *StructCode) Kind() CodeKind {
432 return CodeKindStruct
433 }
434
435 func (c *StructCode) lastFieldCode(field *StructFieldCode, firstField *Opcode) *Opcode {
436 if isEmbeddedStruct(field) {
437 return c.lastAnonymousFieldCode(firstField)
438 }
439 lastField := firstField
440 for lastField.NextField != nil {
441 lastField = lastField.NextField
442 }
443 return lastField
444 }
445
446 func (c *StructCode) lastAnonymousFieldCode(firstField *Opcode) *Opcode {
447 // firstField is special StructHead operation for anonymous structure.
448 // So, StructHead's next operation is truly struct head operation.
449 for firstField.Op == OpStructHead || firstField.Op == OpStructField {
450 firstField = firstField.Next
451 }
452 return lastFieldOpcode(firstField)
453 }
454
455 // lastFieldOpcode returns the last field of the chain of the fields which starts from field.
456 // If a field of the chain is an embedded struct, which is a head without a value followed by
457 // the fields of the struct, the chain continues with those fields.
458 func lastFieldOpcode(field *Opcode) *Opcode {
459 for field.NextField != nil {
460 field = field.NextField
461 for field.Flags&AnonymousHeadFlags != 0 && (field.Op == OpStructField || field.Op == OpStructHead) {
462 field = field.Next
463 }
464 }
465 return field
466 }
467
468 // fieldSlots makes the fields of a struct share the slots.
469 //
470 // The slot of the first field holds the address of the struct, which every field refers to. The slots after it
471 // are for the value of a field, and they are used only while that field is encoded, so every field takes the
472 // same ones: the length of a frame depends on how deep the values are nested, not on how many fields there are.
473 type fieldSlots struct {
474 structIndex int
475 isFirst bool
476 }
477
478 func newFieldSlots(ctx *compileContext) *fieldSlots {
479 return &fieldSlots{structIndex: ctx.ptrIndex, isFirst: true}
480 }
481
482 // reuse is called before a field is compiled.
483 func (s *fieldSlots) reuse(ctx *compileContext) {
484 if s.isFirst {
485 s.isFirst = false
486 return
487 }
488 ctx.ptrIndex = s.structIndex + 1
489 }
490
491 func (c *StructCode) ToOpcode(ctx *compileContext) Opcodes {
492 // header => code => structField => code => end
493 // ^ |
494 // |__________|
495 if c.isRecursive {
496 recursive := newRecursiveCode(ctx, c.typ, &CompiledCode{})
497 recursive.Type = runtime.TypePtr(c.typ)
498 recursive.FieldQuery = c.fieldQuery
499 ctx.incIndex()
500 *ctx.recursiveCodes = append(*ctx.recursiveCodes, recursive)
501 return Opcodes{recursive}
502 }
503 codes := Opcodes{}
504 var prevField *Opcode
505 ctx.incIndent()
506 fieldSlots := newFieldSlots(ctx)
507 for idx, field := range c.fields {
508 isFirstField := idx == 0
509 isEndField := idx == len(c.fields)-1
510 fieldSlots.reuse(ctx)
511 fieldCodes := field.ToOpcode(ctx, isFirstField, isEndField)
512 for _, code := range fieldCodes {
513 if c.isIndirect {
514 code.Flags |= IndirectFlags
515 }
516 }
517 firstField := fieldCodes.First()
518 if len(codes) > 0 {
519 codes.Last().Next = firstField
520 firstField.Idx = codes.First().Idx
521 }
522 if prevField != nil {
523 prevField.NextField = firstField
524 }
525 if isEndField {
526 endField := fieldCodes.Last()
527 if len(codes) > 0 {
528 codes.First().End = endField
529 } else {
530 firstField.End = endField
531 }
532 codes = codes.Add(fieldCodes...)
533 break
534 }
535 prevField = c.lastFieldCode(field, firstField)
536 codes = codes.Add(fieldCodes...)
537 }
538 if len(codes) == 0 {
539 head := &Opcode{
540 Op: OpStructHead,
541 Idx: opcodeOffset(ctx.ptrIndex),
542 Type: runtime.TypePtr(c.typ),
543 DisplayIdx: ctx.opcodeIndex,
544 Indent: ctx.indent,
545 }
546 ctx.incOpcodeIndex()
547 end := &Opcode{
548 Op: OpStructEnd,
549 Idx: opcodeOffset(ctx.ptrIndex),
550 DisplayIdx: ctx.opcodeIndex,
551 Indent: ctx.indent,
552 }
553 head.NextField = end
554 head.Next = end
555 head.End = end
556 codes = codes.Add(head, end)
557 ctx.incIndex()
558 }
559 ctx.decIndent()
560 markFieldRuns(codes)
561 ctx.structTypeToCodes[uintptr(runtime.TypePtr(c.typ))] = codes
562 return codes
563 }
564
565 // fieldRunOps are, for the opcode of a field, the opcodes of a run of two and of three such fields in a row.
566 var fieldRunOps = map[OpType][2]OpType{
567 OpStructFieldInt: {OpStructFieldInt2, OpStructFieldInt3},
568 OpStructFieldUint: {OpStructFieldUint2, OpStructFieldUint3},
569 OpStructFieldFloat64: {OpStructFieldFloat642, OpStructFieldFloat643},
570 OpStructFieldString: {OpStructFieldString2, OpStructFieldString3},
571 OpStructFieldBool: {OpStructFieldBool2, OpStructFieldBool3},
572 }
573
574 // maxFieldRun is the number of the fields of a run.
575 const maxFieldRun = 3
576
577 // markFieldRuns gives the first field of a run of fields of the same kind in a row the opcode of the run: the
578 // VM encodes the fields after it without a dispatch. The fields keep their opcodes, which the VM falls
579 // through; a run is never entered but at its first field, since only an omitted field is jumped over.
580 func markFieldRuns(codes Opcodes) {
581 for i := 0; i < len(codes); {
582 runs, ok := fieldRunOps[codes[i].Op]
583 if !ok {
584 i++
585 continue
586 }
587 n := 1
588 for i+n < len(codes) && n < maxFieldRun && codes[i+n].Op == codes[i].Op && codes[i+n-1].Next == codes[i+n] {
589 n++
590 }
591 if n > 1 {
592 codes[i].Op = runs[n-2]
593 }
594 i += n
595 }
596 }
597
598 func (c *StructCode) ToAnonymousOpcode(ctx *compileContext) Opcodes {
599 // header => code => structField => code => end
600 // ^ |
601 // |__________|
602 if c.isRecursive {
603 recursive := newRecursiveCode(ctx, c.typ, &CompiledCode{Embedded: true})
604 recursive.Type = runtime.TypePtr(c.typ)
605 recursive.FieldQuery = c.fieldQuery
606 ctx.incIndex()
607 *ctx.recursiveCodes = append(*ctx.recursiveCodes, recursive)
608 return Opcodes{recursive}
609 }
610 codes := Opcodes{}
611 var prevField *Opcode
612 fieldSlots := newFieldSlots(ctx)
613 for idx, field := range c.fields {
614 isFirstField := idx == 0
615 isEndField := idx == len(c.fields)-1
616 fieldSlots.reuse(ctx)
617 fieldCodes := field.ToAnonymousOpcode(ctx, isFirstField, isEndField)
618 for _, code := range fieldCodes {
619 if c.isIndirect {
620 code.Flags |= IndirectFlags
621 }
622 }
623 firstField := fieldCodes.First()
624 if len(codes) > 0 {
625 codes.Last().Next = firstField
626 firstField.Idx = codes.First().Idx
627 }
628 if prevField != nil {
629 prevField.NextField = firstField
630 }
631 if isEndField {
632 lastField := fieldCodes.Last()
633 if len(codes) > 0 {
634 codes.First().End = lastField
635 } else {
636 firstField.End = lastField
637 }
638 }
639 // the next field is linked from the last field of this one:
640 // if this field is an embedded struct, it is the last field of that struct, as ToOpcode does.
641 prevField = c.lastFieldCode(field, firstField)
642 codes = codes.Add(fieldCodes...)
643 }
644 // The opcodes of an embedded struct are only the fields: they have neither the braces nor the check
645 // of nil. So they are not registered to structTypeToCodes, which is where a recursive code jumps to.
646 return codes
647 }
648
649 func (c *StructCode) removeFieldsByTags(tags runtime.StructTags) {
650 fields := make([]*StructFieldCode, 0, len(c.fields))
651 for _, field := range c.fields {
652 if field.isAnonymous {
653 structCode := field.getAnonymousStruct()
654 if structCode != nil && !structCode.isRecursive {
655 structCode.removeFieldsByTags(tags)
656 if len(structCode.fields) > 0 {
657 fields = append(fields, field)
658 }
659 continue
660 }
661 }
662 if tags.ExistsKey(field.key) {
663 continue
664 }
665 fields = append(fields, field)
666 }
667 c.fields = fields
668 }
669
670 func (c *StructCode) enableIndirect() {
671 if c.isIndirect {
672 return
673 }
674 c.isIndirect = true
675 if len(c.fields) == 0 {
676 return
677 }
678 structCode := c.fields[0].getStruct()
679 if structCode == nil {
680 return
681 }
682 structCode.enableIndirect()
683 }
684
685 func (c *StructCode) Filter(query *FieldQuery) Code {
686 if c.isRecursive {
687 // the code of a recursive struct is a jump: the code which is jumped to is filtered when it is linked.
688 filtered := *c
689 filtered.fieldQuery = query
690 return &filtered
691 }
692 fieldMap := map[string]*FieldQuery{}
693 for _, field := range query.Fields {
694 fieldMap[field.Name] = field
695 }
696 fields := make([]*StructFieldCode, 0, len(c.fields))
697 for _, field := range c.fields {
698 query, exists := fieldMap[field.key]
699 if !exists {
700 continue
701 }
702 fieldCode := &StructFieldCode{
703 typ: field.typ,
704 key: field.key,
705 tag: field.tag,
706 value: field.value,
707 offset: field.offset,
708 isAnonymous: field.isAnonymous,
709 isTaggedKey: field.isTaggedKey,
710 isNilableType: field.isNilableType,
711 isNilCheck: field.isNilCheck,
712 isAddrForMarshaler: field.isAddrForMarshaler,
713 isNextOpPtrType: field.isNextOpPtrType,
714 }
715 if len(query.Fields) > 0 {
716 fieldCode.value = fieldCode.value.Filter(query)
717 }
718 fields = append(fields, fieldCode)
719 }
720 return &StructCode{
721 typ: c.typ,
722 fields: fields,
723 isPtr: c.isPtr,
724 disableIndirectConversion: c.disableIndirectConversion,
725 isIndirect: c.isIndirect,
726 isRecursive: c.isRecursive,
727 }
728 }
729
730 type StructFieldCode struct {
731 typ reflect.Type
732 key string
733 tag *runtime.StructTag
734 value Code
735 offset uintptr
736 isAnonymous bool
737 isTaggedKey bool
738 isNilableType bool
739 isNilCheck bool
740 isAddrForMarshaler bool
741 isNextOpPtrType bool
742 isMarshalerContext bool
743 }
744
745 // runKind returns the kind of the field if it is one which has the opcodes of a run ( fieldRunOps ): a field of
746 // int, uint, float64, string or bool, not a pointer, without omitempty or the string option, and not embedded.
747 func (c *StructFieldCode) runKind() (CodeKind, bool) {
748 if c.isAnonymous || c.tag.IsOmitEmpty || c.tag.IsOmitZero || c.tag.IsString {
749 return 0, false
750 }
751 switch value := c.value.(type) {
752 case *IntCode:
753 return CodeKindInt, !value.isPtr && !value.isString
754 case *UintCode:
755 return CodeKindUint, !value.isPtr && !value.isString
756 case *FloatCode:
757 return CodeKindFloat, !value.isPtr && value.bitSize == 64
758 case *StringCode:
759 return CodeKindString, !value.isPtr && value.typ != jsonNumberType
760 case *BoolCode:
761 return CodeKindBool, !value.isPtr
762 }
763 return 0, false
764 }
765
766 // isRecursiveValueOf is whether the field is a value of typ, the struct it is a field of, or a pointer to one:
767 // what markTailRecursion encodes without a frame when the field is the last.
768 func (c *StructFieldCode) isRecursiveValueOf(typ reflect.Type) bool {
769 if c.isAnonymous {
770 return false
771 }
772 structCode := c.getStruct()
773 return structCode != nil && structCode.isRecursive && structCode.typ == typ
774 }
775
776 func (c *StructFieldCode) getStruct() *StructCode {
777 value := c.value
778 ptr, ok := value.(*PtrCode)
779 if ok {
780 value = ptr.value
781 }
782 structCode, ok := value.(*StructCode)
783 if ok {
784 return structCode
785 }
786 return nil
787 }
788
789 func (c *StructFieldCode) getAnonymousStruct() *StructCode {
790 if !c.isAnonymous {
791 return nil
792 }
793 return c.getStruct()
794 }
795
796 func optimizeStructField(code *Opcode, tag *runtime.StructTag) OpType {
797 fieldType := code.ToFieldType(tag.IsString)
798 if tag.IsOmitEmpty {
799 fieldType = fieldType.FieldToOmitEmptyField()
800 }
801 return fieldType
802 }
803
804 // headOpcode returns the opcode of the head of the struct, which precedes the opcode of the first field.
805 // It is made before the first field, so that it has the index before the ones of the field.
806 //
807 // The head is not fused with the first field: that made an opcode per type of a field for the head, which was
808 // more than half of the VM, for a dispatch saved per struct. The head writes the brace, and the first field
809 // is encoded by the same opcode as the other fields.
810 func (c *StructFieldCode) headOpcode(ctx *compileContext, flags OpFlags) *Opcode {
811 head := &Opcode{
812 Op: OpStructHead,
813 Idx: opcodeOffset(ctx.ptrIndex),
814 Flags: flags & AnonymousHeadFlags,
815 Type: runtime.TypePtr(c.typ),
816 DisplayIdx: ctx.opcodeIndex,
817 Indent: ctx.indent,
818 }
819 ctx.incOpcodeIndex()
820 return head
821 }
822
823 // withHead links the head to the opcodes of the first field.
824 func withHead(head *Opcode, codes Opcodes) Opcodes {
825 head.Next = codes.First()
826 head.NextField = codes.First()
827 return append(Opcodes{head}, codes...)
828 }
829
830 // isLongKey is whether the key of the field is longer than a chunk: then the field is not encoded by one opcode
831 // with its value, but by the generic field opcode, which writes a key of any length, and the opcode of the value.
832 func (c *StructFieldCode) isLongKey(field *Opcode) bool {
833 return len(field.Key) > KeyChunkSize
834 }
835
836 // isGenericField is whether the field is encoded by the generic field opcode and the opcode of the value: a
837 // field of a long key, or of omitzero, whose check the generic opcode makes for a value of any type.
838 func (c *StructFieldCode) isGenericField(field *Opcode) bool {
839 return c.isLongKey(field) || c.tag.IsOmitZero
840 }
841
842 func (c *StructFieldCode) fieldOpcodes(ctx *compileContext, field *Opcode, valueCodes Opcodes) Opcodes {
843 value := valueCodes.First()
844 var op OpType
845 if c.isGenericField(field) {
846 op = OpStructField
847 if c.tag.IsOmitEmpty || c.tag.IsOmitZero {
848 op = OpStructFieldOmitEmpty
849 }
850 if c.tag.IsString {
851 value.Op = value.Op.ToStringOp()
852 }
853 // the generic field opcode gives the opcode of the value the address of the field, while the opcode of
854 // a map takes the map: the map is followed from the address, as the value of a map or of a list is.
855 switch value.Op {
856 case OpMap:
857 value.Op = OpMapPtr
858 value.PtrNum = 1
859 case OpMapPtr:
860 value.PtrNum++
861 }
862 } else {
863 op = optimizeStructField(value, c.tag)
864 }
865 field.Op = op
866 if op == OpStructFieldOmitEmpty {
867 if c.tag.IsOmitEmpty {
868 field.EmptyKind = emptyKindOf(c.typ)
869 }
870 if c.tag.IsOmitZero {
871 field.ZeroKind = zeroKindOf(c.typ)
872 }
873 }
874 if value.Flags&MarshalerContextFlags != 0 {
875 field.Flags |= MarshalerContextFlags
876 }
877 // the field of interface{} enters the value as the opcode of the value does: it needs to know the interface.
878 if value.Flags&NonEmptyInterfaceFlags != 0 {
879 field.Flags |= NonEmptyInterfaceFlags
880 }
881 field.NumBitSize = value.NumBitSize
882 field.PtrNum = value.PtrNum
883 field.FieldQuery = value.FieldQuery
884 field.Marshaler = value.Marshaler
885
886 fieldCodes := Opcodes{field}
887 if op.IsMultipleOpField() {
888 field.Next = value
889 fieldCodes = fieldCodes.Add(valueCodes...)
890 } else {
891 ctx.decIndex()
892 }
893 return fieldCodes
894 }
895
896 func (c *StructFieldCode) addStructEndCode(ctx *compileContext, codes Opcodes) Opcodes {
897 end := &Opcode{
898 Op: OpStructEnd,
899 Idx: opcodeOffset(ctx.ptrIndex),
900 DisplayIdx: ctx.opcodeIndex,
901 Indent: ctx.indent,
902 }
903 codes.Last().Next = end
904 code := codes.First()
905 for code.Op == OpStructField || code.Op == OpStructHead {
906 code = code.Next
907 }
908 lastFieldOpcode(code).NextField = end
909
910 codes = codes.Add(end)
911 ctx.incOpcodeIndex()
912 return codes
913 }
914
915 // KeyChunkSize is the size of the chunk which the VM copies a key by: a key up to it is written by the
916 // opcode of its field, as a chunk. A longer key is written by the generic field opcode, and its value by the
917 // opcode of the value.
918 const KeyChunkSize = 32
919
920 // PaddedKey returns the key whose memory has the bytes after it up to a chunk,
921 // so that a chunk is copied from the key without reading the memory of others.
922 func PaddedKey(key string) string {
923 buf := make([]byte, len(key)+KeyChunkSize)
924 copy(buf, key)
925 return unsafe.String(unsafe.SliceData(buf), len(key))
926 }
927
928 // keyChunk returns the chunk at the start of a padded key.
929 func keyChunk(paddedKey string) *[KeyChunkSize]byte {
930 return (*[KeyChunkSize]byte)(unsafe.Pointer(unsafe.StringData(paddedKey)))
931 }
932
933 // EmptyKind is what makes the value of a field empty for omitempty, as encoding/json decides it by the kind
934 // of the type of the field: false, 0, a nil pointer or interface value, or an empty array, slice, map or string.
935 type EmptyKind uint8
936
937 const (
938 EmptyNever EmptyKind = iota
939 EmptyNil // a nil pointer or interface value: the first word is zero
940 EmptyBool
941 EmptyInt // an integer of NumBitSize bits which is 0
942 EmptyFloat32
943 EmptyFloat64
944 EmptyLen // a string or a slice whose length is zero
945 EmptyMapLen // a map whose length is zero
946 EmptyAlways // an array of no element
947 )
948
949 // emptyKindOf returns what makes a value of the type empty.
950 func emptyKindOf(typ reflect.Type) EmptyKind {
951 switch typ.Kind() {
952 case reflect.Ptr, reflect.Interface:
953 return EmptyNil
954 case reflect.Bool:
955 return EmptyBool
956 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
957 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
958 return EmptyInt
959 case reflect.Float32:
960 return EmptyFloat32
961 case reflect.Float64:
962 return EmptyFloat64
963 case reflect.String, reflect.Slice:
964 return EmptyLen
965 case reflect.Map:
966 return EmptyMapLen
967 case reflect.Array:
968 if typ.Len() == 0 {
969 return EmptyAlways
970 }
971 }
972 return EmptyNever
973 }
974
975 // IsEmptyField is whether the value at p, of a field whose kind of emptiness is kind, is empty for omitempty.
976 func IsEmptyField(kind EmptyKind, bitSize uint8, p unsafe.Pointer) bool {
977 switch kind {
978 case EmptyNil:
979 return *(*unsafe.Pointer)(p) == nil
980 case EmptyBool:
981 return !*(*bool)(p)
982 case EmptyInt:
983 switch bitSize {
984 case 8:
985 return *(*uint8)(p) == 0
986 case 16:
987 return *(*uint16)(p) == 0
988 case 32:
989 return *(*uint32)(p) == 0
990 }
991 return *(*uint64)(p) == 0
992 case EmptyFloat32:
993 return *(*float32)(p) == 0
994 case EmptyFloat64:
995 return *(*float64)(p) == 0
996 case EmptyLen:
997 return (*runtime.SliceHeader)(p).Len == 0
998 case EmptyMapLen:
999 return MapLen(*(*unsafe.Pointer)(p)) == 0
1000 case EmptyAlways:
1001 return true
1002 }
1003 return false
1004 }
1005
1006 func (c *StructFieldCode) structKey(ctx *compileContext) string {
1007 if ctx.escapeKey {
1008 rctx := &RuntimeContext{Option: &Option{Flag: HTMLEscapeOption}}
1009 return PaddedKey(fmt.Sprintf(`%s:`, string(AppendString(rctx, []byte{}, c.key))))
1010 }
1011 return PaddedKey(fmt.Sprintf(`"%s":`, c.key))
1012 }
1013
1014 func (c *StructFieldCode) flags() OpFlags {
1015 var flags OpFlags
1016 if c.isTaggedKey {
1017 flags |= IsTaggedKeyFlags
1018 }
1019 if c.isNilableType {
1020 flags |= IsNilableTypeFlags
1021 }
1022 if c.isNilCheck {
1023 flags |= NilCheckFlags
1024 }
1025 if c.isAddrForMarshaler {
1026 flags |= AddrForMarshalerFlags
1027 }
1028 if c.isNextOpPtrType {
1029 flags |= IsNextOpPtrTypeFlags
1030 }
1031 if c.isAnonymous {
1032 flags |= AnonymousKeyFlags
1033 }
1034 if c.isMarshalerContext {
1035 flags |= MarshalerContextFlags
1036 }
1037 return flags
1038 }
1039
1040 func (c *StructFieldCode) toValueOpcodes(ctx *compileContext) Opcodes {
1041 if c.isAnonymous {
1042 anonymCode, ok := c.value.(AnonymousCode)
1043 if ok {
1044 return anonymCode.ToAnonymousOpcode(ctx)
1045 }
1046 }
1047 return c.value.ToOpcode(ctx)
1048 }
1049
1050 func (c *StructFieldCode) ToOpcode(ctx *compileContext, isFirstField, isEndField bool) Opcodes {
1051 var head *Opcode
1052 if isFirstField {
1053 head = c.headOpcode(ctx, c.flags())
1054 }
1055 key := c.structKey(ctx)
1056 field := &Opcode{
1057 Idx: opcodeOffset(ctx.ptrIndex),
1058 Flags: c.flags(),
1059 Key: key,
1060 KeyChunk: keyChunk(key),
1061 Offset: uint32(c.offset),
1062 Type: runtime.TypePtr(c.typ),
1063 DisplayIdx: ctx.opcodeIndex,
1064 Indent: ctx.indent,
1065 }
1066 ctx.incIndex()
1067 valueCodes := c.toValueOpcodes(ctx)
1068 codes := c.fieldOpcodes(ctx, field, valueCodes)
1069 if isEndField {
1070 if isEnableStructEndOptimization(c.value) && !c.isGenericField(field) {
1071 field.Op = field.Op.FieldToEnd()
1072 } else {
1073 codes = c.addStructEndCode(ctx, codes)
1074 }
1075 }
1076 if head != nil {
1077 codes = withHead(head, codes)
1078 }
1079 return codes
1080 }
1081
1082 func (c *StructFieldCode) ToAnonymousOpcode(ctx *compileContext, isFirstField, isEndField bool) Opcodes {
1083 var head *Opcode
1084 if isFirstField {
1085 head = c.headOpcode(ctx, c.flags()|AnonymousHeadFlags)
1086 }
1087 key := c.structKey(ctx)
1088 field := &Opcode{
1089 Idx: opcodeOffset(ctx.ptrIndex),
1090 Flags: c.flags() | AnonymousHeadFlags,
1091 Key: key,
1092 KeyChunk: keyChunk(key),
1093 Offset: uint32(c.offset),
1094 Type: runtime.TypePtr(c.typ),
1095 DisplayIdx: ctx.opcodeIndex,
1096 Indent: ctx.indent,
1097 }
1098 ctx.incIndex()
1099 valueCodes := c.toValueOpcodes(ctx)
1100 codes := c.fieldOpcodes(ctx, field, valueCodes)
1101 if head != nil {
1102 codes = withHead(head, codes)
1103 }
1104 return codes
1105 }
1106
1107 func isEnableStructEndOptimization(value Code) bool {
1108 switch value.Kind() {
1109 case CodeKindInt,
1110 CodeKindUint,
1111 CodeKindFloat,
1112 CodeKindString,
1113 CodeKindBool,
1114 CodeKindBytes:
1115 return true
1116 case CodeKindPtr:
1117 return isEnableStructEndOptimization(value.(*PtrCode).value)
1118 default:
1119 return false
1120 }
1121 }
1122
1123 type InterfaceCode struct {
1124 typ reflect.Type
1125 fieldQuery *FieldQuery
1126 isPtr bool
1127 }
1128
1129 func (c *InterfaceCode) Kind() CodeKind {
1130 return CodeKindInterface
1131 }
1132
1133 func (c *InterfaceCode) ToOpcode(ctx *compileContext) Opcodes {
1134 var code *Opcode
1135 switch {
1136 case c.isPtr:
1137 code = newOpCode(ctx, c.typ, OpInterfacePtr)
1138 default:
1139 code = newOpCode(ctx, c.typ, OpInterface)
1140 }
1141 code.FieldQuery = c.fieldQuery
1142 if c.typ.NumMethod() > 0 {
1143 code.Flags |= NonEmptyInterfaceFlags
1144 }
1145 ctx.incIndex()
1146 return Opcodes{code}
1147 }
1148
1149 func (c *InterfaceCode) Filter(query *FieldQuery) Code {
1150 return &InterfaceCode{
1151 typ: c.typ,
1152 fieldQuery: query,
1153 isPtr: c.isPtr,
1154 }
1155 }
1156
1157 type MarshalJSONCode struct {
1158 typ reflect.Type
1159 fieldQuery *FieldQuery
1160 isAddrForMarshaler bool
1161 isNilableType bool
1162 isMarshalerContext bool
1163 }
1164
1165 func (c *MarshalJSONCode) Kind() CodeKind {
1166 return CodeKindMarshalJSON
1167 }
1168
1169 func (c *MarshalJSONCode) ToOpcode(ctx *compileContext) Opcodes {
1170 code := newOpCode(ctx, c.typ, OpMarshalJSON)
1171 code.FieldQuery = c.fieldQuery
1172 code.Marshaler = c.marshalerCall()
1173 if c.isAddrForMarshaler {
1174 code.Flags |= AddrForMarshalerFlags
1175 }
1176 if c.isMarshalerContext {
1177 code.Flags |= MarshalerContextFlags
1178 }
1179 if c.isNilableType {
1180 code.Flags |= IsNilableTypeFlags
1181 } else {
1182 code.Flags &= ^IsNilableTypeFlags
1183 }
1184 ctx.incIndex()
1185 return Opcodes{code}
1186 }
1187
1188 // marshalerCall returns the direct call of the method, or nil if the method is called through the interface:
1189 // a value of the size of a pointer whose method is on the pointer is copied first, see addrForMarshaler.
1190 func (c *MarshalJSONCode) marshalerCall() *MarshalerCall {
1191 recv := c.typ
1192 if c.isAddrForMarshaler {
1193 if c.typ.Size() == unsafe.Sizeof(unsafe.Pointer(nil)) {
1194 return nil
1195 }
1196 recv = reflect.PointerTo(c.typ)
1197 }
1198 iface := marshalJSONInterface
1199 if c.isMarshalerContext {
1200 iface = marshalJSONContextInterface
1201 }
1202 return newMarshalerCall(recv, iface)
1203 }
1204
1205 func (c *MarshalJSONCode) Filter(query *FieldQuery) Code {
1206 return &MarshalJSONCode{
1207 typ: c.typ,
1208 fieldQuery: query,
1209 isAddrForMarshaler: c.isAddrForMarshaler,
1210 isNilableType: c.isNilableType,
1211 isMarshalerContext: c.isMarshalerContext,
1212 }
1213 }
1214
1215 type MarshalTextCode struct {
1216 typ reflect.Type
1217 fieldQuery *FieldQuery
1218 isAddrForMarshaler bool
1219 isNilableType bool
1220 // isInterfaceMapKey is whether the code is the one of the key of a map of an interface type, whose name is
1221 // of the dynamic value of the key ( see appendInterfaceMapKey ).
1222 isInterfaceMapKey bool
1223 // isMapKey is whether the code is the one of the key of a map, whose name is "" for a nil pointer.
1224 isMapKey bool
1225 }
1226
1227 func (c *MarshalTextCode) Kind() CodeKind {
1228 return CodeKindMarshalText
1229 }
1230
1231 func (c *MarshalTextCode) ToOpcode(ctx *compileContext) Opcodes {
1232 code := newOpCode(ctx, c.typ, OpMarshalText)
1233 code.FieldQuery = c.fieldQuery
1234 if c.isInterfaceMapKey {
1235 // the opcode is given the address of the key, whose name AppendMarshalText makes without a marshaler.
1236 code.Flags |= InterfaceMapKeyFlags
1237 code.Flags &= ^IsNilableTypeFlags
1238 ctx.incIndex()
1239 return Opcodes{code}
1240 }
1241 code.Marshaler = c.marshalerCall()
1242 if c.isAddrForMarshaler {
1243 code.Flags |= AddrForMarshalerFlags
1244 }
1245 if c.isMapKey {
1246 code.Flags |= MapKeyFlags
1247 }
1248 if c.isNilableType {
1249 code.Flags |= IsNilableTypeFlags
1250 } else {
1251 code.Flags &= ^IsNilableTypeFlags
1252 }
1253 ctx.incIndex()
1254 return Opcodes{code}
1255 }
1256
1257 // marshalerCall returns the direct call of the method, or nil if the method is called through the interface:
1258 // see MarshalJSONCode.marshalerCall.
1259 func (c *MarshalTextCode) marshalerCall() *MarshalerCall {
1260 recv := c.typ
1261 if c.isAddrForMarshaler {
1262 if c.typ.Size() == unsafe.Sizeof(unsafe.Pointer(nil)) {
1263 return nil
1264 }
1265 recv = reflect.PointerTo(c.typ)
1266 }
1267 return newMarshalerCall(recv, marshalTextInterface)
1268 }
1269
1270 func (c *MarshalTextCode) Filter(query *FieldQuery) Code {
1271 return &MarshalTextCode{
1272 typ: c.typ,
1273 fieldQuery: query,
1274 isAddrForMarshaler: c.isAddrForMarshaler,
1275 isNilableType: c.isNilableType,
1276 isInterfaceMapKey: c.isInterfaceMapKey,
1277 isMapKey: c.isMapKey,
1278 }
1279 }
1280
1281 type PtrCode struct {
1282 typ reflect.Type
1283 value Code
1284 ptrNum uint8
1285 }
1286
1287 func (c *PtrCode) Kind() CodeKind {
1288 return CodeKindPtr
1289 }
1290
1291 func (c *PtrCode) ToOpcode(ctx *compileContext) Opcodes {
1292 codes := c.value.ToOpcode(ctx)
1293 codes.First().Op = convertPtrOp(codes.First())
1294 codes.First().PtrNum = c.ptrNum
1295 return codes
1296 }
1297
1298 func (c *PtrCode) ToAnonymousOpcode(ctx *compileContext) Opcodes {
1299 var codes Opcodes
1300 anonymCode, ok := c.value.(AnonymousCode)
1301 if ok {
1302 codes = anonymCode.ToAnonymousOpcode(ctx)
1303 } else {
1304 codes = c.value.ToOpcode(ctx)
1305 }
1306 codes.First().Op = convertPtrOp(codes.First())
1307 codes.First().PtrNum = c.ptrNum
1308 return codes
1309 }
1310
1311 func (c *PtrCode) Filter(query *FieldQuery) Code {
1312 return &PtrCode{
1313 typ: c.typ,
1314 value: c.value.Filter(query),
1315 ptrNum: c.ptrNum,
1316 }
1317 }
1318
1319 func convertPtrOp(code *Opcode) OpType {
1320 ptrHeadOp := code.Op.HeadToPtrHead()
1321 if code.Op != ptrHeadOp {
1322 if code.PtrNum > 0 {
1323 // ptr field and ptr head
1324 code.PtrNum--
1325 }
1326 return ptrHeadOp
1327 }
1328 switch code.Op {
1329 case OpInt:
1330 return OpIntPtr
1331 case OpUint:
1332 return OpUintPtr
1333 case OpFloat32:
1334 return OpFloat32Ptr
1335 case OpFloat64:
1336 return OpFloat64Ptr
1337 case OpString:
1338 return OpStringPtr
1339 case OpBool:
1340 return OpBoolPtr
1341 case OpBytes:
1342 return OpBytesPtr
1343 case OpNumber:
1344 return OpNumberPtr
1345 case OpArray:
1346 return OpArrayPtr
1347 case OpSlice:
1348 return OpSlicePtr
1349 case OpMap:
1350 return OpMapPtr
1351 case OpMarshalJSON:
1352 return OpMarshalJSONPtr
1353 case OpMarshalText:
1354 return OpMarshalTextPtr
1355 case OpInterface:
1356 return OpInterfacePtr
1357 case OpRecursive:
1358 return OpRecursivePtr
1359 }
1360 return code.Op
1361 }
1362
1363 func isEmbeddedStruct(field *StructFieldCode) bool {
1364 if !field.isAnonymous {
1365 return false
1366 }
1367 t := field.typ
1368 if t.Kind() == reflect.Ptr {
1369 t = t.Elem()
1370 }
1371 return t.Kind() == reflect.Struct
1372 }