Debian Codegraph @

internal/encoder/frame.go

raw
1 package encoder
2
3 import (
4 "slices"
5 "unsafe"
6 )
7
8 // The frames of the VM.
9 //
10 // The value held by an interface value and the value of a recursive type are encoded by the opcodes of their
11 // own type, in a frame of slots after the frame of the opcodes which reached them. The opcode which ends
12 // such a frame has three slots: the opcode to return to, the offset of the previous frame and the indent to
13 // restore.
14 //
15 // Entering and leaving a frame is done here, not in the VM: it needs several calls and many variables, and
16 // the VM, which is a large function, has to spill and restore its variables around each of them.
17
18 type nonEmptyInterface struct {
19 itab *struct {
20 ityp unsafe.Pointer // static interface type
21 typ unsafe.Pointer // dynamic concrete type
22 // unused fields...
23 }
24 ptr unsafe.Pointer
25 }
26
27 func storeSlotPtr(base unsafe.Pointer, idx uint32, p unsafe.Pointer) {
28 *(*uintptr)(unsafe.Add(base, idx)) = uintptr(p)
29 }
30
31 func storeSlotInt(base unsafe.Pointer, idx uint32, v uintptr) {
32 *(*uintptr)(unsafe.Add(base, idx)) = v
33 }
34
35 func loadSlotPtr(base unsafe.Pointer, idx uint32) unsafe.Pointer {
36 return *(*unsafe.Pointer)(unsafe.Add(base, idx))
37 }
38
39 func loadSlotInt(base unsafe.Pointer, idx uint32) uintptr {
40 return *(*uintptr)(unsafe.Add(base, idx))
41 }
42
43 // recordSeen records the value to detect a cycle, after the nesting got deep: a cycle keeps passing the same
44 // values, so it is still detected, and the values which are not nested deeply cost nothing.
45 func (c *RuntimeContext) recordSeen(code *Opcode, p unsafe.Pointer) error {
46 if p != nil {
47 if slices.Contains(c.SeenPtr, p) {
48 return ErrUnsupportedValue(code, p)
49 }
50 }
51 c.SeenPtr = append(c.SeenPtr, p)
52 return nil
53 }
54
55 // enterFrame allocates the frame of the code after the current one, stores the value at its first slot and
56 // what the end opcode restores, and returns the base of the slots of the new frame.
57 func (c *RuntimeContext) enterFrame(first, end, next *Opcode, p unsafe.Pointer, curLen, nextLen uintptr, indent uint32) unsafe.Pointer {
58 oldOffset := c.SlotOffset
59 c.SlotOffset += curLen * slotSize
60 c.ReserveSlots(oldOffset/slotSize + curLen + nextLen)
61 base := unsafe.Add(c.Ptr(), c.SlotOffset)
62 storeSlotPtr(base, first.Idx, p)
63 storeSlotPtr(base, end.Idx, unsafe.Pointer(next))
64 storeSlotInt(base, end.ElemIdx, oldOffset)
65 // the indent and the tail levels of the frame left are in one slot: both are small.
66 storeSlotInt(base, end.Length, uintptr(c.BaseIndent)|uintptr(c.TailLevels)<<32)
67 c.BaseIndent = indent
68 c.TailLevels = 0
69 c.RecursiveLevel++
70 return base
71 }
72
73 // EnterInterface enters the frame of the value held by the interface value at p, which is the operand of
74 // code. It returns the first opcode of the frame and the base of its slots, or a nil opcode if the value is
75 // nil, which the caller writes as null.
76 //
77 // If the value is a scalar, no frame is entered: it returns the opcode of the scalar, the address of the value
78 // and true, and the caller encodes the value by the opcode in its own frame. It saves the frame and two
79 // dispatches for the values which JSON has in a value of interface{}.
80 //
81 //go:noinline
82 func (c *RuntimeContext) EnterInterface(code *Opcode, p unsafe.Pointer) (*Opcode, unsafe.Pointer, bool, error) {
83 var typ, ifacePtr unsafe.Pointer
84 if code.Flags&NonEmptyInterfaceFlags != 0 {
85 iface := (*nonEmptyInterface)(p)
86 ifacePtr = iface.ptr
87 if iface.itab != nil {
88 typ = iface.itab.typ
89 }
90 } else {
91 iface := (*emptyInterface)(p)
92 ifacePtr = iface.ptr
93 typ = iface.typ
94 }
95 if ifacePtr == nil {
96 isDirectedNil := typ != nil && ShapeOf(typ) == ValueShapeAggregate && !IfaceIndir(typ)
97 if !isDirectedNil {
98 return nil, nil, false, nil
99 }
100 }
101 codeSet := c.RecentCodeSet(uintptr(typ))
102 if codeSet == nil {
103 var err error
104 codeSet, err = CompileToGetCodeSet(c, uintptr(typ))
105 if err != nil {
106 return nil, nil, false, err
107 }
108 }
109 if codeSet.Scalar != nil {
110 // a scalar is never stored directly in an interface value: the data word is its address.
111 return codeSet.Scalar, ifacePtr, true, nil
112 }
113 // after every path which doesn't go into the value, so that a record always has its end.
114 if c.RecursiveLevel > StartDetectingCyclesAfter {
115 if err := c.recordSeen(code, p); err != nil {
116 return nil, nil, false, err
117 }
118 }
119 var first *Opcode
120 if (c.Option.Flag & HTMLEscapeOption) != 0 {
121 first = codeSet.InterfaceEscapeKeyCode
122 } else {
123 first = codeSet.InterfaceNoescapeKeyCode
124 }
125 // The opcodes take the address of the value. The data word of the interface value is the address for
126 // most of the types, and the value itself for a type of a pointer shape which is not a pointer, such as a
127 // map: then the address of the data word, in the interface value at p, is the address of the value.
128 value := ifacePtr
129 if !codeSet.DataWordIsAddr {
130 value = unsafe.Add(p, unsafe.Sizeof(uintptr(0)))
131 }
132 base := c.enterFrame(first, codeSet.EndCode, code.Next, value,
133 uintptr(code.Length)+interfaceEndSlots, uintptr(codeSet.CodeLength)+interfaceEndSlots, c.BaseIndent+code.Indent)
134 return first, base, false, nil
135 }
136
137 // interfaceEndSlots is the number of the slots which a frame of an interface value has after the ones of
138 // the code.
139 const interfaceEndSlots = 3
140
141 // EnterRecursive enters the frame of the value of the recursive type at p, which is the operand of code.
142 // It returns the first opcode of the frame and the base of its slots.
143 //
144 //go:noinline
145 func (c *RuntimeContext) EnterRecursive(code *Opcode, p unsafe.Pointer) (*Opcode, unsafe.Pointer, error) {
146 if c.RecursiveLevel > StartDetectingCyclesAfter {
147 if err := c.recordSeen(code, p); err != nil {
148 return nil, nil, err
149 }
150 }
151 first := code.Jmp.Code
152 indentDiffFromTop := first.Indent - 1
153 base := c.enterFrame(first, first.End.Next, code.Next, p,
154 code.Jmp.CurLen, code.Jmp.NextLen, c.BaseIndent+code.Indent-indentDiffFromTop)
155 return first, base, nil
156 }
157
158 // LeaveFrame leaves the frame which the end opcode ends, and returns the opcode to go on with and the base of
159 // the slots of the previous frame.
160 //
161 //go:noinline
162 func (c *RuntimeContext) LeaveFrame(end *Opcode) (*Opcode, unsafe.Pointer) {
163 base := unsafe.Add(c.Ptr(), c.SlotOffset)
164 c.RecursiveLevel--
165 if c.RecursiveLevel > StartDetectingCyclesAfter {
166 c.SeenPtr = c.SeenPtr[:len(c.SeenPtr)-1]
167 }
168 saved := loadSlotInt(base, end.Length)
169 c.BaseIndent = uint32(saved)
170 c.TailLevels = uint32(saved >> 32)
171 c.SlotOffset = loadSlotInt(base, end.ElemIdx)
172 return (*Opcode)(loadSlotPtr(base, end.Idx)), unsafe.Add(c.Ptr(), c.SlotOffset)
173 }
174
175 // The last field of a value of a recursive type may be a value of the same type: a list. Such a value is
176 // encoded in the frame of the value it is the field of ( TailRecursiveFlags ): the slots of that value are not
177 // needed any more, and the only thing left to do for it is to close its braces, which the end of the last
178 // value of the list does for every value of the list. No frame is entered and left for a value of the list, so
179 // the slots, the offsets and the opcode to return to are neither stored nor restored, and the end of a value
180 // is not dispatched: that makes a list as cheap as a nest of values of different types. The VM does it inline,
181 // as the functions here cost more than the inliner allows into it; the end opcode of the list has what the
182 // indent is deeper by for a value of it.
183
184 // RecordSeen records the value of a recursive type at p for the detection of cycles: the VM calls it before
185 // it begins a value of a list, when the level is deep enough for the detection.
186 func (c *RuntimeContext) RecordSeen(code *Opcode, p unsafe.Pointer) error {
187 return c.recordSeen(code, p)
188 }