| 1 |
package encoder |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"encoding" |
| 6 |
"encoding/json" |
| 7 |
"reflect" |
| 8 |
"slices" |
| 9 |
"sort" |
| 10 |
"unsafe" |
| 11 |
|
| 12 |
"github.com/goccy/go-json/internal/errors" |
| 13 |
"github.com/goccy/go-json/internal/runtime" |
| 14 |
) |
| 15 |
|
| 16 |
// CompileToGetCodeSet returns the opcodes of the type, compiling them if the type is new. |
| 17 |
func CompileToGetCodeSet(ctx *RuntimeContext, typeptr uintptr) (*OpcodeSet, error) { |
| 18 |
if codeSet := ctx.RecentCodeSet(typeptr); codeSet != nil { |
| 19 |
return codeSet, nil |
| 20 |
} |
| 21 |
key := ctx.codeSetKey(typeptr) |
| 22 |
set := &ctx.recentCodeSets[recentCodeSetIndex(key)] |
| 23 |
for i := range set { |
| 24 |
if set[i].typeptr == key { |
| 25 |
return getFilteredCodeSetIfNeeded(ctx, set[i].codeSet) |
| 26 |
} |
| 27 |
} |
| 28 |
codeSet, err := compileToGetUnfilteredCodeSet(typeptr, ctx.Option.Flag&OptimizeFieldOrderOption != 0) |
| 29 |
if err != nil { |
| 30 |
return nil, err |
| 31 |
} |
| 32 |
// the type takes the first entry of its set, and the one encoded before it is kept in the second. |
| 33 |
copy(set[1:], set[:]) |
| 34 |
set[0] = recentCodeSet{typeptr: key, codeSet: codeSet} |
| 35 |
return getFilteredCodeSetIfNeeded(ctx, codeSet) |
| 36 |
} |
| 37 |
|
| 38 |
// codeSetKey is what the opcodes of a type are looked up by in a context: the address of the type, whose |
| 39 |
// lowest bit is free by the alignment of a type and is set when the fields are ordered by the encoder. |
| 40 |
func (c *RuntimeContext) codeSetKey(typeptr uintptr) uintptr { |
| 41 |
return typeptr | uintptr(c.Option.Flag&OptimizeFieldOrderOption)/uintptr(OptimizeFieldOrderOption) |
| 42 |
} |
| 43 |
|
| 44 |
// RecentCodeSet returns the opcodes of the type if the context encoded it recently and has no context which |
| 45 |
// may filter the fields, or nil: then CompileToGetCodeSet is to be called. |
| 46 |
// |
| 47 |
// A runtime context remembers the opcodes of the types it encoded last: the same types are encoded again |
| 48 |
// and again in most of the programs, and this is cheaper than a lookup of the table shared by every goroutine. |
| 49 |
// This is inlined into the callers: the values of interface{} come through it one by one. |
| 50 |
func (c *RuntimeContext) RecentCodeSet(typeptr uintptr) *OpcodeSet { |
| 51 |
key := c.codeSetKey(typeptr) |
| 52 |
set := &c.recentCodeSets[recentCodeSetIndex(key)] |
| 53 |
if c.Option.Flag&ContextOption == 0 { |
| 54 |
if set[0].typeptr == key { |
| 55 |
return set[0].codeSet |
| 56 |
} |
| 57 |
if set[1].typeptr == key { |
| 58 |
return set[1].codeSet |
| 59 |
} |
| 60 |
} |
| 61 |
return nil |
| 62 |
} |
| 63 |
|
| 64 |
func recentCodeSetIndex(typeptr uintptr) uint64 { |
| 65 |
return (uint64(typeptr) * runtime.TypeHashMultiplier) >> recentCodeSetHashShift |
| 66 |
} |
| 67 |
|
| 68 |
// compileToGetUnfilteredCodeSet is CompileToGetCodeSet without the filter by the field query of the context. |
| 69 |
// The opcodes with the fields ordered by the encoder are cached apart from the ones in the order of the struct. |
| 70 |
func compileToGetUnfilteredCodeSet(typeptr uintptr, optimizeFieldOrder bool) (*OpcodeSet, error) { |
| 71 |
cache := &cachedOpcodeSets |
| 72 |
if optimizeFieldOrder { |
| 73 |
cache = &cachedOptimizedOpcodeSets |
| 74 |
} |
| 75 |
if codeSet := cache.Load(typeptr); codeSet != nil { |
| 76 |
return codeSet, nil |
| 77 |
} |
| 78 |
codeSet, err := newCompiler(optimizeFieldOrder).compile(typeptr) |
| 79 |
if err != nil { |
| 80 |
return nil, err |
| 81 |
} |
| 82 |
return cache.Store(typeptr, codeSet), nil |
| 83 |
} |
| 84 |
|
| 85 |
type marshalerContext interface { |
| 86 |
MarshalJSON(context.Context) ([]byte, error) |
| 87 |
} |
| 88 |
|
| 89 |
var ( |
| 90 |
marshalJSONType = reflect.TypeOf((*json.Marshaler)(nil)).Elem() |
| 91 |
marshalJSONContextType = reflect.TypeOf((*marshalerContext)(nil)).Elem() |
| 92 |
marshalTextType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() |
| 93 |
jsonNumberType = reflect.TypeOf(json.Number("")) |
| 94 |
cachedOpcodeSets runtime.TypeCache[OpcodeSet] |
| 95 |
// cachedOptimizedOpcodeSets are the opcodes with the fields ordered by the encoder. |
| 96 |
cachedOptimizedOpcodeSets runtime.TypeCache[OpcodeSet] |
| 97 |
) |
| 98 |
|
| 99 |
func getFilteredCodeSetIfNeeded(ctx *RuntimeContext, codeSet *OpcodeSet) (*OpcodeSet, error) { |
| 100 |
if (ctx.Option.Flag & ContextOption) == 0 { |
| 101 |
return codeSet, nil |
| 102 |
} |
| 103 |
query := FieldQueryFromContext(ctx.Option.Context) |
| 104 |
if query == nil { |
| 105 |
return codeSet, nil |
| 106 |
} |
| 107 |
ctx.Option.Flag |= FieldQueryOption |
| 108 |
cacheCodeSet := codeSet.getQueryCache(query.Hash()) |
| 109 |
if cacheCodeSet != nil { |
| 110 |
return cacheCodeSet, nil |
| 111 |
} |
| 112 |
// the fields of the code are already in their order: the compiler orders only the fields of the recursive |
| 113 |
// structs it compiles when it links them, as the code was compiled. |
| 114 |
compiler := newCompiler(ctx.Option.Flag&OptimizeFieldOrderOption != 0) |
| 115 |
compiler.isFiltered = true |
| 116 |
queryCodeSet, err := compiler.codeToOpcodeSet(codeSet.Type, codeSet.Code.Filter(query)) |
| 117 |
if err != nil { |
| 118 |
return nil, err |
| 119 |
} |
| 120 |
codeSet.setQueryCache(query.Hash(), queryCodeSet) |
| 121 |
return queryCodeSet, nil |
| 122 |
} |
| 123 |
|
| 124 |
type Compiler struct { |
| 125 |
structTypeToCode map[uintptr]*StructCode |
| 126 |
// optimizeFieldOrder is whether the fields of a struct are ordered as they are encoded fastest. |
| 127 |
optimizeFieldOrder bool |
| 128 |
// embeddingChain is the types of the structs whose fields are written to the JSON object being compiled: |
| 129 |
// the struct of the object and the structs embedded in it, down to the one being compiled. |
| 130 |
embeddingChain []uintptr |
| 131 |
// structFieldCounts is, for a struct which has been compiled as a value of its own ( not embedded ), how |
| 132 |
// many fields its code has, with the fields of the structs in it: see sharedStructFieldCount. |
| 133 |
structFieldCounts map[uintptr]int |
| 134 |
// fieldCount is how many fields have been compiled. |
| 135 |
fieldCount int |
| 136 |
// nextIsEmbedded is whether the struct compiled next is an embedded struct, whose fields are written to |
| 137 |
// the JSON object of the struct which embeds it. |
| 138 |
nextIsEmbedded bool |
| 139 |
// isFiltered is whether the code being compiled to opcodes is filtered by a field query: then the opcodes |
| 140 |
// which a struct has in one place are not the ones of the struct in another. |
| 141 |
isFiltered bool |
| 142 |
} |
| 143 |
|
| 144 |
// sharedStructFieldCount is how many fields the code of a struct has, with the fields of the structs in it, |
| 145 |
// above which the struct is encoded, where it is again a value in the same type, by a jump to one code of it |
| 146 |
// as a recursive struct is, instead of by a copy of its code. A type whose structs refer to each other in |
| 147 |
// many places would otherwise have a code of a size exponential to their depth, which takes the memory and |
| 148 |
// the time of compiling it ( the structs of an API with many resources expanded into each other ). A smaller |
| 149 |
// struct is copied, which saves the jump for each value. |
| 150 |
const sharedStructFieldCount = 128 |
| 151 |
|
| 152 |
func newCompiler(optimizeFieldOrder bool) *Compiler { |
| 153 |
return &Compiler{ |
| 154 |
structTypeToCode: map[uintptr]*StructCode{}, |
| 155 |
optimizeFieldOrder: optimizeFieldOrder, |
| 156 |
structFieldCounts: map[uintptr]int{}, |
| 157 |
} |
| 158 |
} |
| 159 |
|
| 160 |
func (c *Compiler) compile(typeptr uintptr) (*OpcodeSet, error) { |
| 161 |
// noescape trick for header.typ ( reflect.*rtype ) |
| 162 |
typ := runtime.TypeOfPtr(*(*unsafe.Pointer)(unsafe.Pointer(&typeptr))) |
| 163 |
if typ.Kind() == reflect.Ptr { |
| 164 |
// a pointer is the address of a value, so the opcodes are the ones of the value it points to. |
| 165 |
code, err := c.pointeeCode(typ.Elem()) |
| 166 |
if err != nil { |
| 167 |
return nil, err |
| 168 |
} |
| 169 |
return c.codeToOpcodeSet(typ, code) |
| 170 |
} |
| 171 |
code, err := c.valueCode(typ) |
| 172 |
if err != nil { |
| 173 |
return nil, err |
| 174 |
} |
| 175 |
return c.codeToOpcodeSet(typ, code) |
| 176 |
} |
| 177 |
|
| 178 |
// pointeeCode returns the code for the value which a pointer points to. |
| 179 |
// It is addressable, as an element of a slice is. |
| 180 |
func (c *Compiler) pointeeCode(typ reflect.Type) (Code, error) { |
| 181 |
code, err := c.listElemCode(typ) |
| 182 |
if err != nil { |
| 183 |
return nil, err |
| 184 |
} |
| 185 |
if code.Kind() == CodeKindStruct { |
| 186 |
structCode := code.(*StructCode) |
| 187 |
structCode.enableIndirect() |
| 188 |
} |
| 189 |
return code, nil |
| 190 |
} |
| 191 |
|
| 192 |
// valueCode returns the code for a value which is not addressable and whose address is given to the opcode: |
| 193 |
// the value passed to Marshal and the value held by an interface value. |
| 194 |
// It is the same as the value of a map, which is not addressable either. |
| 195 |
func (c *Compiler) valueCode(typ reflect.Type) (Code, error) { |
| 196 |
code, err := c.mapValueCode(typ) |
| 197 |
if err != nil { |
| 198 |
return nil, err |
| 199 |
} |
| 200 |
if code.Kind() == CodeKindStruct { |
| 201 |
structCode := code.(*StructCode) |
| 202 |
structCode.enableIndirect() |
| 203 |
} |
| 204 |
return code, nil |
| 205 |
} |
| 206 |
|
| 207 |
func (c *Compiler) codeToOpcodeSet(typ reflect.Type, code Code) (*OpcodeSet, error) { |
| 208 |
noescapeKeyCode, err := c.codeToOpcode(&compileContext{ |
| 209 |
structTypeToCodes: map[uintptr]Opcodes{}, |
| 210 |
recursiveCodes: &Opcodes{}, |
| 211 |
}, typ, code) |
| 212 |
if err != nil { |
| 213 |
return nil, err |
| 214 |
} |
| 215 |
if err := noescapeKeyCode.Validate(); err != nil { |
| 216 |
return nil, err |
| 217 |
} |
| 218 |
escapeKeyCode, err := c.codeToOpcode(&compileContext{ |
| 219 |
structTypeToCodes: map[uintptr]Opcodes{}, |
| 220 |
recursiveCodes: &Opcodes{}, |
| 221 |
escapeKey: true, |
| 222 |
}, typ, code) |
| 223 |
if err != nil { |
| 224 |
return nil, err |
| 225 |
} |
| 226 |
noescapeKeyCode = copyOpcode(noescapeKeyCode) |
| 227 |
escapeKeyCode = copyOpcode(escapeKeyCode) |
| 228 |
setTotalLengthToInterfaceOp(noescapeKeyCode) |
| 229 |
setTotalLengthToInterfaceOp(escapeKeyCode) |
| 230 |
interfaceNoescapeKeyCode := copyToInterfaceOpcode(noescapeKeyCode) |
| 231 |
interfaceEscapeKeyCode := copyToInterfaceOpcode(escapeKeyCode) |
| 232 |
codeLength := noescapeKeyCode.TotalLength() |
| 233 |
return &OpcodeSet{ |
| 234 |
Type: typ, |
| 235 |
IfaceIndir: runtime.IfaceIndir(typ), |
| 236 |
DataWordIsAddr: runtime.IfaceIndir(typ) || typ.Kind() == reflect.Ptr, |
| 237 |
NoescapeKeyCode: noescapeKeyCode, |
| 238 |
EscapeKeyCode: escapeKeyCode, |
| 239 |
InterfaceNoescapeKeyCode: interfaceNoescapeKeyCode, |
| 240 |
InterfaceEscapeKeyCode: interfaceEscapeKeyCode, |
| 241 |
CodeLength: codeLength, |
| 242 |
EndCode: ToEndCode(interfaceNoescapeKeyCode), |
| 243 |
Scalar: scalarOpcode(noescapeKeyCode), |
| 244 |
Code: code, |
| 245 |
QueryCache: map[string]*OpcodeSet{}, |
| 246 |
}, nil |
| 247 |
} |
| 248 |
|
| 249 |
// scalarOpcode returns the opcode if the code is a single opcode of a scalar followed by the end, or nil. |
| 250 |
func scalarOpcode(code *Opcode) *Opcode { |
| 251 |
if isScalarOp(code.Op) && code.Next != nil && code.Next.Op == OpEnd { |
| 252 |
return code |
| 253 |
} |
| 254 |
return nil |
| 255 |
} |
| 256 |
|
| 257 |
// isScalarOp is whether the opcode writes a scalar from the address of its value, which appendScalar of the VMs |
| 258 |
// does for such an opcode wherever the value is. |
| 259 |
func isScalarOp(op OpType) bool { |
| 260 |
switch op { |
| 261 |
case OpInt, OpUint, OpFloat32, OpFloat64, OpString, OpBool, OpBytes, OpNumber: |
| 262 |
return true |
| 263 |
} |
| 264 |
return false |
| 265 |
} |
| 266 |
|
| 267 |
func (c *Compiler) typeToCodeWithPtr(typ reflect.Type, isPtr bool) (Code, error) { |
| 268 |
switch { |
| 269 |
case c.implementsMarshalJSON(typ): |
| 270 |
return c.marshalJSONCode(typ) |
| 271 |
case c.implementsMarshalText(typ): |
| 272 |
return c.marshalTextCode(typ) |
| 273 |
} |
| 274 |
switch typ.Kind() { |
| 275 |
case reflect.Ptr: |
| 276 |
return c.ptrCode(typ) |
| 277 |
case reflect.Slice: |
| 278 |
elem := typ.Elem() |
| 279 |
if elem.Kind() == reflect.Uint8 { |
| 280 |
p := reflect.PointerTo(elem) |
| 281 |
if !c.implementsMarshalJSONType(p) && !p.Implements(marshalTextType) { |
| 282 |
return c.bytesCode(typ, false) |
| 283 |
} |
| 284 |
} |
| 285 |
return c.sliceCode(typ) |
| 286 |
case reflect.Array: |
| 287 |
return c.arrayCode(typ) |
| 288 |
case reflect.Map: |
| 289 |
return c.mapCode(typ) |
| 290 |
case reflect.Struct: |
| 291 |
return c.structCode(typ, isPtr) |
| 292 |
case reflect.Interface: |
| 293 |
return c.interfaceCode(typ, false) |
| 294 |
case reflect.Int: |
| 295 |
return c.intCode(typ, false) |
| 296 |
case reflect.Int8: |
| 297 |
return c.int8Code(typ, false) |
| 298 |
case reflect.Int16: |
| 299 |
return c.int16Code(typ, false) |
| 300 |
case reflect.Int32: |
| 301 |
return c.int32Code(typ, false) |
| 302 |
case reflect.Int64: |
| 303 |
return c.int64Code(typ, false) |
| 304 |
case reflect.Uint: |
| 305 |
return c.uintCode(typ, false) |
| 306 |
case reflect.Uint8: |
| 307 |
return c.uint8Code(typ, false) |
| 308 |
case reflect.Uint16: |
| 309 |
return c.uint16Code(typ, false) |
| 310 |
case reflect.Uint32: |
| 311 |
return c.uint32Code(typ, false) |
| 312 |
case reflect.Uint64: |
| 313 |
return c.uint64Code(typ, false) |
| 314 |
case reflect.Uintptr: |
| 315 |
return c.uintCode(typ, false) |
| 316 |
case reflect.Float32: |
| 317 |
return c.float32Code(typ, false) |
| 318 |
case reflect.Float64: |
| 319 |
return c.float64Code(typ, false) |
| 320 |
case reflect.String: |
| 321 |
return c.stringCode(typ, false) |
| 322 |
case reflect.Bool: |
| 323 |
return c.boolCode(typ, false) |
| 324 |
} |
| 325 |
return nil, &errors.UnsupportedTypeError{Type: typ} |
| 326 |
} |
| 327 |
|
| 328 |
const intSize = 32 << (^uint(0) >> 63) |
| 329 |
|
| 330 |
//nolint:unparam |
| 331 |
func (c *Compiler) intCode(typ reflect.Type, isPtr bool) (*IntCode, error) { |
| 332 |
return &IntCode{typ: typ, bitSize: intSize, isPtr: isPtr}, nil |
| 333 |
} |
| 334 |
|
| 335 |
//nolint:unparam |
| 336 |
func (c *Compiler) int8Code(typ reflect.Type, isPtr bool) (*IntCode, error) { |
| 337 |
return &IntCode{typ: typ, bitSize: 8, isPtr: isPtr}, nil |
| 338 |
} |
| 339 |
|
| 340 |
//nolint:unparam |
| 341 |
func (c *Compiler) int16Code(typ reflect.Type, isPtr bool) (*IntCode, error) { |
| 342 |
return &IntCode{typ: typ, bitSize: 16, isPtr: isPtr}, nil |
| 343 |
} |
| 344 |
|
| 345 |
//nolint:unparam |
| 346 |
func (c *Compiler) int32Code(typ reflect.Type, isPtr bool) (*IntCode, error) { |
| 347 |
return &IntCode{typ: typ, bitSize: 32, isPtr: isPtr}, nil |
| 348 |
} |
| 349 |
|
| 350 |
//nolint:unparam |
| 351 |
func (c *Compiler) int64Code(typ reflect.Type, isPtr bool) (*IntCode, error) { |
| 352 |
return &IntCode{typ: typ, bitSize: 64, isPtr: isPtr}, nil |
| 353 |
} |
| 354 |
|
| 355 |
//nolint:unparam |
| 356 |
func (c *Compiler) uintCode(typ reflect.Type, isPtr bool) (*UintCode, error) { |
| 357 |
return &UintCode{typ: typ, bitSize: intSize, isPtr: isPtr}, nil |
| 358 |
} |
| 359 |
|
| 360 |
//nolint:unparam |
| 361 |
func (c *Compiler) uint8Code(typ reflect.Type, isPtr bool) (*UintCode, error) { |
| 362 |
return &UintCode{typ: typ, bitSize: 8, isPtr: isPtr}, nil |
| 363 |
} |
| 364 |
|
| 365 |
//nolint:unparam |
| 366 |
func (c *Compiler) uint16Code(typ reflect.Type, isPtr bool) (*UintCode, error) { |
| 367 |
return &UintCode{typ: typ, bitSize: 16, isPtr: isPtr}, nil |
| 368 |
} |
| 369 |
|
| 370 |
//nolint:unparam |
| 371 |
func (c *Compiler) uint32Code(typ reflect.Type, isPtr bool) (*UintCode, error) { |
| 372 |
return &UintCode{typ: typ, bitSize: 32, isPtr: isPtr}, nil |
| 373 |
} |
| 374 |
|
| 375 |
//nolint:unparam |
| 376 |
func (c *Compiler) uint64Code(typ reflect.Type, isPtr bool) (*UintCode, error) { |
| 377 |
return &UintCode{typ: typ, bitSize: 64, isPtr: isPtr}, nil |
| 378 |
} |
| 379 |
|
| 380 |
//nolint:unparam |
| 381 |
func (c *Compiler) float32Code(typ reflect.Type, isPtr bool) (*FloatCode, error) { |
| 382 |
return &FloatCode{typ: typ, bitSize: 32, isPtr: isPtr}, nil |
| 383 |
} |
| 384 |
|
| 385 |
//nolint:unparam |
| 386 |
func (c *Compiler) float64Code(typ reflect.Type, isPtr bool) (*FloatCode, error) { |
| 387 |
return &FloatCode{typ: typ, bitSize: 64, isPtr: isPtr}, nil |
| 388 |
} |
| 389 |
|
| 390 |
//nolint:unparam |
| 391 |
func (c *Compiler) stringCode(typ reflect.Type, isPtr bool) (*StringCode, error) { |
| 392 |
return &StringCode{typ: typ, isPtr: isPtr}, nil |
| 393 |
} |
| 394 |
|
| 395 |
//nolint:unparam |
| 396 |
func (c *Compiler) boolCode(typ reflect.Type, isPtr bool) (*BoolCode, error) { |
| 397 |
return &BoolCode{typ: typ, isPtr: isPtr}, nil |
| 398 |
} |
| 399 |
|
| 400 |
//nolint:unparam |
| 401 |
func (c *Compiler) intStringCode(typ reflect.Type) (*IntCode, error) { |
| 402 |
return &IntCode{typ: typ, bitSize: intSize, isString: true}, nil |
| 403 |
} |
| 404 |
|
| 405 |
//nolint:unparam |
| 406 |
func (c *Compiler) int8StringCode(typ reflect.Type) (*IntCode, error) { |
| 407 |
return &IntCode{typ: typ, bitSize: 8, isString: true}, nil |
| 408 |
} |
| 409 |
|
| 410 |
//nolint:unparam |
| 411 |
func (c *Compiler) int16StringCode(typ reflect.Type) (*IntCode, error) { |
| 412 |
return &IntCode{typ: typ, bitSize: 16, isString: true}, nil |
| 413 |
} |
| 414 |
|
| 415 |
//nolint:unparam |
| 416 |
func (c *Compiler) int32StringCode(typ reflect.Type) (*IntCode, error) { |
| 417 |
return &IntCode{typ: typ, bitSize: 32, isString: true}, nil |
| 418 |
} |
| 419 |
|
| 420 |
//nolint:unparam |
| 421 |
func (c *Compiler) int64StringCode(typ reflect.Type) (*IntCode, error) { |
| 422 |
return &IntCode{typ: typ, bitSize: 64, isString: true}, nil |
| 423 |
} |
| 424 |
|
| 425 |
//nolint:unparam |
| 426 |
func (c *Compiler) uintStringCode(typ reflect.Type) (*UintCode, error) { |
| 427 |
return &UintCode{typ: typ, bitSize: intSize, isString: true}, nil |
| 428 |
} |
| 429 |
|
| 430 |
//nolint:unparam |
| 431 |
func (c *Compiler) uint8StringCode(typ reflect.Type) (*UintCode, error) { |
| 432 |
return &UintCode{typ: typ, bitSize: 8, isString: true}, nil |
| 433 |
} |
| 434 |
|
| 435 |
//nolint:unparam |
| 436 |
func (c *Compiler) uint16StringCode(typ reflect.Type) (*UintCode, error) { |
| 437 |
return &UintCode{typ: typ, bitSize: 16, isString: true}, nil |
| 438 |
} |
| 439 |
|
| 440 |
//nolint:unparam |
| 441 |
func (c *Compiler) uint32StringCode(typ reflect.Type) (*UintCode, error) { |
| 442 |
return &UintCode{typ: typ, bitSize: 32, isString: true}, nil |
| 443 |
} |
| 444 |
|
| 445 |
//nolint:unparam |
| 446 |
func (c *Compiler) uint64StringCode(typ reflect.Type) (*UintCode, error) { |
| 447 |
return &UintCode{typ: typ, bitSize: 64, isString: true}, nil |
| 448 |
} |
| 449 |
|
| 450 |
//nolint:unparam |
| 451 |
func (c *Compiler) bytesCode(typ reflect.Type, isPtr bool) (*BytesCode, error) { |
| 452 |
return &BytesCode{typ: typ, isPtr: isPtr}, nil |
| 453 |
} |
| 454 |
|
| 455 |
//nolint:unparam |
| 456 |
func (c *Compiler) interfaceCode(typ reflect.Type, isPtr bool) (*InterfaceCode, error) { |
| 457 |
return &InterfaceCode{typ: typ, isPtr: isPtr}, nil |
| 458 |
} |
| 459 |
|
| 460 |
//nolint:unparam |
| 461 |
func (c *Compiler) marshalJSONCode(typ reflect.Type) (*MarshalJSONCode, error) { |
| 462 |
return &MarshalJSONCode{ |
| 463 |
typ: typ, |
| 464 |
isAddrForMarshaler: c.isPtrMarshalJSONType(typ), |
| 465 |
isNilableType: c.isNilableType(typ), |
| 466 |
isMarshalerContext: typ.Implements(marshalJSONContextType) || reflect.PointerTo(typ).Implements(marshalJSONContextType), |
| 467 |
}, nil |
| 468 |
} |
| 469 |
|
| 470 |
//nolint:unparam |
| 471 |
func (c *Compiler) marshalTextCode(typ reflect.Type) (*MarshalTextCode, error) { |
| 472 |
return &MarshalTextCode{ |
| 473 |
typ: typ, |
| 474 |
isAddrForMarshaler: c.isPtrMarshalTextType(typ), |
| 475 |
isNilableType: c.isNilableType(typ), |
| 476 |
}, nil |
| 477 |
} |
| 478 |
|
| 479 |
func (c *Compiler) ptrCode(typ reflect.Type) (*PtrCode, error) { |
| 480 |
code, err := c.typeToCodeWithPtr(typ.Elem(), true) |
| 481 |
if err != nil { |
| 482 |
return nil, err |
| 483 |
} |
| 484 |
ptr, ok := code.(*PtrCode) |
| 485 |
if ok { |
| 486 |
return &PtrCode{typ: typ, value: ptr.value, ptrNum: ptr.ptrNum + 1}, nil |
| 487 |
} |
| 488 |
return &PtrCode{typ: typ, value: code, ptrNum: 1}, nil |
| 489 |
} |
| 490 |
|
| 491 |
func (c *Compiler) sliceCode(typ reflect.Type) (*SliceCode, error) { |
| 492 |
elem := typ.Elem() |
| 493 |
code, err := c.listElemCode(elem) |
| 494 |
if err != nil { |
| 495 |
return nil, err |
| 496 |
} |
| 497 |
if code.Kind() == CodeKindStruct { |
| 498 |
structCode := code.(*StructCode) |
| 499 |
structCode.enableIndirect() |
| 500 |
} |
| 501 |
return &SliceCode{typ: typ, value: code}, nil |
| 502 |
} |
| 503 |
|
| 504 |
func (c *Compiler) arrayCode(typ reflect.Type) (*ArrayCode, error) { |
| 505 |
elem := typ.Elem() |
| 506 |
code, err := c.listElemCode(elem) |
| 507 |
if err != nil { |
| 508 |
return nil, err |
| 509 |
} |
| 510 |
if code.Kind() == CodeKindStruct { |
| 511 |
structCode := code.(*StructCode) |
| 512 |
structCode.enableIndirect() |
| 513 |
} |
| 514 |
return &ArrayCode{typ: typ, value: code}, nil |
| 515 |
} |
| 516 |
|
| 517 |
func (c *Compiler) mapCode(typ reflect.Type) (*MapCode, error) { |
| 518 |
keyCode, err := c.mapKeyCode(typ.Key()) |
| 519 |
if err != nil { |
| 520 |
return nil, err |
| 521 |
} |
| 522 |
valueCode, err := c.mapValueCode(typ.Elem()) |
| 523 |
if err != nil { |
| 524 |
return nil, err |
| 525 |
} |
| 526 |
if valueCode.Kind() == CodeKindStruct { |
| 527 |
structCode := valueCode.(*StructCode) |
| 528 |
structCode.enableIndirect() |
| 529 |
} |
| 530 |
return &MapCode{typ: typ, key: keyCode, value: valueCode}, nil |
| 531 |
} |
| 532 |
|
| 533 |
func (c *Compiler) listElemCode(typ reflect.Type) (Code, error) { |
| 534 |
switch { |
| 535 |
case c.isPtrMarshalJSONType(typ): |
| 536 |
// The opcode takes the address of the element, which is the very pointer the marshaler is called with. |
| 537 |
// So the opcode is the one of the pointer type, and neither a copy of the element nor reflect is needed. |
| 538 |
ptrType := reflect.PointerTo(typ) |
| 539 |
return &MarshalJSONCode{ |
| 540 |
typ: ptrType, |
| 541 |
isMarshalerContext: ptrType.Implements(marshalJSONContextType), |
| 542 |
}, nil |
| 543 |
case c.implementsMarshalJSONType(typ): |
| 544 |
return c.marshalJSONCode(typ) |
| 545 |
case !typ.Implements(marshalTextType) && reflect.PointerTo(typ).Implements(marshalTextType): |
| 546 |
return &MarshalTextCode{typ: reflect.PointerTo(typ)}, nil |
| 547 |
case typ.Kind() == reflect.Map: |
| 548 |
return c.ptrCode(reflect.PointerTo(typ)) |
| 549 |
default: |
| 550 |
// isPtr was originally used to indicate whether the type of top level is pointer. |
| 551 |
// However, since the slice/array element is a specification that can get the pointer address, explicitly set isPtr to true. |
| 552 |
// See here for related issues: https://github.com/goccy/go-json/issues/370 |
| 553 |
code, err := c.typeToCodeWithPtr(typ, true) |
| 554 |
if err != nil { |
| 555 |
return nil, err |
| 556 |
} |
| 557 |
ptr, ok := code.(*PtrCode) |
| 558 |
if ok { |
| 559 |
if ptr.value.Kind() == CodeKindMap { |
| 560 |
ptr.ptrNum++ |
| 561 |
} |
| 562 |
} |
| 563 |
return code, nil |
| 564 |
} |
| 565 |
} |
| 566 |
|
| 567 |
func (c *Compiler) mapKeyCode(typ reflect.Type) (Code, error) { |
| 568 |
switch { |
| 569 |
case typ.Kind() == reflect.Interface && (interfaceMapKeys || c.implementsMarshalText(typ)): |
| 570 |
// the name of a key is of its dynamic value, as encoding/json of the Go it is built with makes it: every |
| 571 |
// key of an interface type where it is built on encoding/json/v2, and else a key of an interface type |
| 572 |
// which has MarshalText ( see appendInterfaceMapKey ). |
| 573 |
return &MarshalTextCode{typ: typ, isInterfaceMapKey: true}, nil |
| 574 |
case c.implementsMarshalText(typ): |
| 575 |
code, err := c.marshalTextCode(typ) |
| 576 |
if err != nil { |
| 577 |
return nil, err |
| 578 |
} |
| 579 |
code.isMapKey = true |
| 580 |
return code, nil |
| 581 |
} |
| 582 |
switch typ.Kind() { |
| 583 |
case reflect.Ptr: |
| 584 |
code, err := c.ptrCode(typ) |
| 585 |
if err != nil { |
| 586 |
return nil, err |
| 587 |
} |
| 588 |
if text, ok := code.value.(*MarshalTextCode); ok { |
| 589 |
// a pointer to a value whose MarshalText has a value receiver |
| 590 |
text.isMapKey = true |
| 591 |
} |
| 592 |
return code, nil |
| 593 |
case reflect.String: |
| 594 |
return c.stringCode(typ, false) |
| 595 |
case reflect.Int: |
| 596 |
return c.intStringCode(typ) |
| 597 |
case reflect.Int8: |
| 598 |
return c.int8StringCode(typ) |
| 599 |
case reflect.Int16: |
| 600 |
return c.int16StringCode(typ) |
| 601 |
case reflect.Int32: |
| 602 |
return c.int32StringCode(typ) |
| 603 |
case reflect.Int64: |
| 604 |
return c.int64StringCode(typ) |
| 605 |
case reflect.Uint: |
| 606 |
return c.uintStringCode(typ) |
| 607 |
case reflect.Uint8: |
| 608 |
return c.uint8StringCode(typ) |
| 609 |
case reflect.Uint16: |
| 610 |
return c.uint16StringCode(typ) |
| 611 |
case reflect.Uint32: |
| 612 |
return c.uint32StringCode(typ) |
| 613 |
case reflect.Uint64: |
| 614 |
return c.uint64StringCode(typ) |
| 615 |
case reflect.Uintptr: |
| 616 |
return c.uintStringCode(typ) |
| 617 |
} |
| 618 |
return nil, &errors.UnsupportedTypeError{Type: typ} |
| 619 |
} |
| 620 |
|
| 621 |
func (c *Compiler) mapValueCode(typ reflect.Type) (Code, error) { |
| 622 |
switch { |
| 623 |
case typ.Kind() == reflect.Map && !c.implementsMarshalJSON(typ) && !c.implementsMarshalText(typ): |
| 624 |
// a map which has a marshaler is encoded by the marshaler, not as a map. |
| 625 |
return c.ptrCode(reflect.PointerTo(typ)) |
| 626 |
default: |
| 627 |
code, err := c.typeToCodeWithPtr(typ, false) |
| 628 |
if err != nil { |
| 629 |
return nil, err |
| 630 |
} |
| 631 |
ptr, ok := code.(*PtrCode) |
| 632 |
if ok { |
| 633 |
if ptr.value.Kind() == CodeKindMap { |
| 634 |
ptr.ptrNum++ |
| 635 |
} |
| 636 |
} |
| 637 |
return code, nil |
| 638 |
} |
| 639 |
} |
| 640 |
|
| 641 |
func (c *Compiler) structCode(typ reflect.Type, isPtr bool) (*StructCode, error) { |
| 642 |
embedded := c.nextIsEmbedded |
| 643 |
c.nextIsEmbedded = false |
| 644 |
return c.compileStruct(typ, isPtr, embedded, !embedded) |
| 645 |
} |
| 646 |
|
| 647 |
// compileStruct returns the code of the struct. embedded is whether it is an embedded struct. mayShare is |
| 648 |
// whether the struct may be encoded by a jump to one code of it, if it is large and has been compiled before |
| 649 |
// ( see sharedStructFieldCount ): an embedded struct is not, because its fields are the ones of the struct |
| 650 |
// which embeds it, which may hide some of them. |
| 651 |
func (c *Compiler) compileStruct(typ reflect.Type, isPtr, embedded, mayShare bool) (*StructCode, error) { |
| 652 |
typeptr := uintptr(runtime.TypePtr(typ)) |
| 653 |
if count, compiled := c.structFieldCounts[typeptr]; mayShare && compiled && count > sharedStructFieldCount { |
| 654 |
if _, onPath := c.structTypeToCode[typeptr]; !onPath { |
| 655 |
// the code which is jumped to is compiled when the recursive codes are linked. |
| 656 |
return &StructCode{typ: typ, isPtr: isPtr, isIndirect: runtime.IfaceIndir(typ), isRecursive: true}, nil |
| 657 |
} |
| 658 |
} |
| 659 |
if code, exists := c.structTypeToCode[typeptr]; exists { |
| 660 |
derefCode := *code |
| 661 |
derefCode.isRecursive = true |
| 662 |
if slices.Contains(c.embeddingChain, typeptr) { |
| 663 |
// The struct is embedded in itself, directly or through the other embedded structs. All of its |
| 664 |
// fields are hidden by the same fields of itself at the shallower depth of the same JSON |
| 665 |
// object, as in encoding/json, so it has nothing to write. |
| 666 |
derefCode.isHiddenByItself = true |
| 667 |
} |
| 668 |
return &derefCode, nil |
| 669 |
} |
| 670 |
c.embeddingChain = append(c.embeddingChain, typeptr) |
| 671 |
defer func() { c.embeddingChain = c.embeddingChain[:len(c.embeddingChain)-1] }() |
| 672 |
indirect := runtime.IfaceIndir(typ) |
| 673 |
code := &StructCode{typ: typ, isPtr: isPtr, isIndirect: indirect} |
| 674 |
c.structTypeToCode[typeptr] = code |
| 675 |
firstField := c.fieldCount |
| 676 |
|
| 677 |
fieldNum := typ.NumField() |
| 678 |
tags := c.typeToStructTags(typ) |
| 679 |
fields := []*StructFieldCode{} |
| 680 |
for i, tag := range tags { |
| 681 |
if (tag.IsOmitEmpty || tag.IsOmitZero) && tag.Field.Type.Kind() == reflect.Array && tag.Field.Type.Len() == 0 { |
| 682 |
// an array of no elements is always empty and zero, as in encoding/json. |
| 683 |
continue |
| 684 |
} |
| 685 |
isOnlyOneFirstField := i == 0 && fieldNum == 1 |
| 686 |
field, err := c.structFieldCode(code, tag, isPtr, isOnlyOneFirstField) |
| 687 |
if err != nil { |
| 688 |
return nil, err |
| 689 |
} |
| 690 |
if field.isAnonymous { |
| 691 |
structCode := field.getAnonymousStruct() |
| 692 |
if structCode != nil && structCode.isHiddenByItself { |
| 693 |
continue |
| 694 |
} |
| 695 |
if structCode != nil { |
| 696 |
structCode.removeFieldsByTags(c.keyTags(tags)) |
| 697 |
if c.isAssignableIndirect(field, isPtr) { |
| 698 |
if indirect { |
| 699 |
structCode.isIndirect = true |
| 700 |
} else { |
| 701 |
structCode.isIndirect = false |
| 702 |
} |
| 703 |
} |
| 704 |
} |
| 705 |
} else { |
| 706 |
structCode := field.getStruct() |
| 707 |
if structCode != nil { |
| 708 |
if indirect { |
| 709 |
// if parent is indirect type, set child indirect property to true |
| 710 |
structCode.isIndirect = true |
| 711 |
} else { |
| 712 |
// if parent is not indirect type, set child indirect property to false. |
| 713 |
// but if parent's indirect is false and isPtr is true, then indirect must be true. |
| 714 |
// Do this only if indirectConversion is enabled at the end of compileStruct. |
| 715 |
structCode.isIndirect = false |
| 716 |
} |
| 717 |
} |
| 718 |
} |
| 719 |
fields = append(fields, field) |
| 720 |
} |
| 721 |
fieldMap := c.getFieldMap(fields) |
| 722 |
duplicatedFieldMap := c.getDuplicatedFieldMap(fieldMap) |
| 723 |
code.fields = c.filteredDuplicatedFields(fields, duplicatedFieldMap) |
| 724 |
if c.optimizeFieldOrder { |
| 725 |
code.fields = orderFieldsForSpeed(code.fields, typ) |
| 726 |
} |
| 727 |
if !code.disableIndirectConversion && !indirect && isPtr { |
| 728 |
code.enableIndirect() |
| 729 |
} |
| 730 |
delete(c.structTypeToCode, typeptr) |
| 731 |
c.fieldCount += len(code.fields) |
| 732 |
if !embedded { |
| 733 |
c.structFieldCounts[typeptr] = c.fieldCount - firstField |
| 734 |
} |
| 735 |
return code, nil |
| 736 |
} |
| 737 |
|
| 738 |
// orderFieldsForSpeed returns the fields in the order they are encoded fastest ( OptimizeFieldOrderOption ): |
| 739 |
// the fields of a kind which has the opcodes of a run ( fieldRunOps ) are put together, where the first field |
| 740 |
// of the kind is, so that a run is as long as it can be; and a field which is a value of the struct's own type, |
| 741 |
// if there is one, is put last, so that a list of values is encoded in one frame ( markTailRecursion ). |
| 742 |
// The other fields stay in their order. |
| 743 |
func orderFieldsForSpeed(fields []*StructFieldCode, typ reflect.Type) []*StructFieldCode { |
| 744 |
recursive := -1 |
| 745 |
for i, field := range fields { |
| 746 |
if field.isRecursiveValueOf(typ) { |
| 747 |
if recursive >= 0 { |
| 748 |
recursive = -1 // more than one: none of them is the last |
| 749 |
break |
| 750 |
} |
| 751 |
recursive = i |
| 752 |
} |
| 753 |
} |
| 754 |
// the order key of a field: where the first field of its kind is, or its own place. |
| 755 |
keys := make([]int, len(fields)) |
| 756 |
firstOfKind := map[CodeKind]int{} |
| 757 |
for i, field := range fields { |
| 758 |
keys[i] = i |
| 759 |
if i == recursive { |
| 760 |
keys[i] = len(fields) |
| 761 |
continue |
| 762 |
} |
| 763 |
if kind, ok := field.runKind(); ok { |
| 764 |
if first, seen := firstOfKind[kind]; seen { |
| 765 |
keys[i] = first |
| 766 |
} else { |
| 767 |
firstOfKind[kind] = i |
| 768 |
} |
| 769 |
} |
| 770 |
} |
| 771 |
order := make([]int, len(fields)) |
| 772 |
for i := range order { |
| 773 |
order[i] = i |
| 774 |
} |
| 775 |
sort.SliceStable(order, func(i, j int) bool { return keys[order[i]] < keys[order[j]] }) |
| 776 |
ordered := make([]*StructFieldCode, len(fields)) |
| 777 |
for i, j := range order { |
| 778 |
ordered[i] = fields[j] |
| 779 |
} |
| 780 |
return ordered |
| 781 |
} |
| 782 |
|
| 783 |
func toElemType(t reflect.Type) reflect.Type { |
| 784 |
for t.Kind() == reflect.Ptr { |
| 785 |
t = t.Elem() |
| 786 |
} |
| 787 |
return t |
| 788 |
} |
| 789 |
|
| 790 |
func (c *Compiler) structFieldCode(structCode *StructCode, tag *runtime.StructTag, isPtr, isOnlyOneFirstField bool) (*StructFieldCode, error) { |
| 791 |
field := tag.Field |
| 792 |
fieldType := field.Type |
| 793 |
isIndirectSpecialCase := isPtr && isOnlyOneFirstField |
| 794 |
fieldCode := &StructFieldCode{ |
| 795 |
typ: fieldType, |
| 796 |
key: tag.Key, |
| 797 |
tag: tag, |
| 798 |
offset: field.Offset, |
| 799 |
isAnonymous: c.isEmbeddedStruct(tag), |
| 800 |
isTaggedKey: tag.IsTaggedKey, |
| 801 |
isNilableType: c.isNilableType(fieldType), |
| 802 |
// The check writes null instead of calling the marshaler, which encoding/json does only for a nil |
| 803 |
// pointer: the marshaler of a nil map is called. With omitempty the check is what decides that |
| 804 |
// the field is empty, for every kind. |
| 805 |
isNilCheck: tag.IsOmitEmpty || fieldType.Kind() == reflect.Ptr, |
| 806 |
} |
| 807 |
if !fieldCode.isAnonymous { |
| 808 |
// the value of the field is not a part of the JSON object being compiled. |
| 809 |
embeddingChain := c.embeddingChain |
| 810 |
c.embeddingChain = nil |
| 811 |
defer func() { c.embeddingChain = embeddingChain }() |
| 812 |
} |
| 813 |
if fieldCode.isAnonymous && (tag.IsOmitEmpty || tag.IsOmitZero) { |
| 814 |
// The fields of an embedded struct are written as the fields of the struct which embeds it, so there is |
| 815 |
// nothing for omitempty or omitzero of the embedded struct itself to omit, as in encoding/json. The |
| 816 |
// opcode for them would write the key of the embedded struct. |
| 817 |
inlined := *tag |
| 818 |
inlined.IsOmitEmpty = false |
| 819 |
inlined.IsOmitZero = false |
| 820 |
fieldCode.tag = &inlined |
| 821 |
} |
| 822 |
switch { |
| 823 |
case c.isMovePointerPositionFromHeadToFirstMarshalJSONFieldCase(fieldType, isIndirectSpecialCase): |
| 824 |
code, err := c.marshalJSONCode(fieldType) |
| 825 |
if err != nil { |
| 826 |
return nil, err |
| 827 |
} |
| 828 |
fieldCode.value = code |
| 829 |
fieldCode.isAddrForMarshaler = true |
| 830 |
fieldCode.isNilCheck = c.isNilCheckForAddrMarshaler(tag) |
| 831 |
structCode.isIndirect = false |
| 832 |
structCode.disableIndirectConversion = true |
| 833 |
case c.isMovePointerPositionFromHeadToFirstMarshalTextFieldCase(fieldType, isIndirectSpecialCase): |
| 834 |
code, err := c.marshalTextCode(fieldType) |
| 835 |
if err != nil { |
| 836 |
return nil, err |
| 837 |
} |
| 838 |
fieldCode.value = code |
| 839 |
fieldCode.isAddrForMarshaler = true |
| 840 |
fieldCode.isNilCheck = c.isNilCheckForAddrMarshaler(tag) |
| 841 |
structCode.isIndirect = false |
| 842 |
structCode.disableIndirectConversion = true |
| 843 |
case isPtr && c.isPtrMarshalJSONType(fieldType): |
| 844 |
// *struct{ field T } |
| 845 |
// func (*T) MarshalJSON() ([]byte, error) |
| 846 |
code, err := c.marshalJSONCode(fieldType) |
| 847 |
if err != nil { |
| 848 |
return nil, err |
| 849 |
} |
| 850 |
fieldCode.value = code |
| 851 |
fieldCode.isAddrForMarshaler = true |
| 852 |
fieldCode.isNilCheck = c.isNilCheckForAddrMarshaler(tag) |
| 853 |
case isPtr && c.isPtrMarshalTextType(fieldType): |
| 854 |
// *struct{ field T } |
| 855 |
// func (*T) MarshalText() ([]byte, error) |
| 856 |
code, err := c.marshalTextCode(fieldType) |
| 857 |
if err != nil { |
| 858 |
return nil, err |
| 859 |
} |
| 860 |
fieldCode.value = code |
| 861 |
fieldCode.isAddrForMarshaler = true |
| 862 |
fieldCode.isNilCheck = c.isNilCheckForAddrMarshaler(tag) |
| 863 |
default: |
| 864 |
c.nextIsEmbedded = fieldCode.isAnonymous |
| 865 |
code, err := c.typeToCodeWithPtr(fieldType, isPtr) |
| 866 |
c.nextIsEmbedded = false |
| 867 |
if err != nil { |
| 868 |
return nil, err |
| 869 |
} |
| 870 |
switch code.Kind() { |
| 871 |
case CodeKindPtr, CodeKindInterface: |
| 872 |
fieldCode.isNextOpPtrType = true |
| 873 |
} |
| 874 |
fieldCode.value = code |
| 875 |
} |
| 876 |
return fieldCode, nil |
| 877 |
} |
| 878 |
|
| 879 |
// isNilCheckForAddrMarshaler returns whether a field whose marshaler is called with its address is checked. |
| 880 |
// |
| 881 |
// The check is what decides that the field is empty for omitempty, by the kind of the value as encoding/json |
| 882 |
// does, so it is required for omitempty. Without omitempty it would write null instead of calling the |
| 883 |
// marshaler, which a pointer to the field never needs. |
| 884 |
func (c *Compiler) isNilCheckForAddrMarshaler(tag *runtime.StructTag) bool { |
| 885 |
return tag.IsOmitEmpty |
| 886 |
} |
| 887 |
|
| 888 |
// isEmbeddedStruct reports whether the field is an embedded struct whose fields are written as the fields of |
| 889 |
// the struct which embeds it. |
| 890 |
func (c *Compiler) isEmbeddedStruct(tag *runtime.StructTag) bool { |
| 891 |
return tag.Field.Anonymous && !tag.IsTaggedKey && toElemType(tag.Field.Type).Kind() == reflect.Struct |
| 892 |
} |
| 893 |
|
| 894 |
// keyTags returns the tags of the fields which are written with their own keys. |
| 895 |
// An embedded struct is not: its name is not a key, so it doesn't hide a field of the same name. |
| 896 |
func (c *Compiler) keyTags(tags runtime.StructTags) runtime.StructTags { |
| 897 |
keyTags := make(runtime.StructTags, 0, len(tags)) |
| 898 |
for _, tag := range tags { |
| 899 |
if c.isEmbeddedStruct(tag) { |
| 900 |
continue |
| 901 |
} |
| 902 |
keyTags = append(keyTags, tag) |
| 903 |
} |
| 904 |
return keyTags |
| 905 |
} |
| 906 |
|
| 907 |
func (c *Compiler) isAssignableIndirect(fieldCode *StructFieldCode, isPtr bool) bool { |
| 908 |
if isPtr { |
| 909 |
return false |
| 910 |
} |
| 911 |
codeType := fieldCode.value.Kind() |
| 912 |
if codeType == CodeKindMarshalJSON { |
| 913 |
return false |
| 914 |
} |
| 915 |
if codeType == CodeKindMarshalText { |
| 916 |
return false |
| 917 |
} |
| 918 |
return true |
| 919 |
} |
| 920 |
|
| 921 |
func (c *Compiler) getFieldMap(fields []*StructFieldCode) map[string][]*StructFieldCode { |
| 922 |
fieldMap := map[string][]*StructFieldCode{} |
| 923 |
for _, field := range fields { |
| 924 |
if field.isAnonymous { |
| 925 |
for k, v := range c.getAnonymousFieldMap(field) { |
| 926 |
fieldMap[k] = append(fieldMap[k], v...) |
| 927 |
} |
| 928 |
continue |
| 929 |
} |
| 930 |
fieldMap[field.key] = append(fieldMap[field.key], field) |
| 931 |
} |
| 932 |
return fieldMap |
| 933 |
} |
| 934 |
|
| 935 |
func (c *Compiler) getAnonymousFieldMap(field *StructFieldCode) map[string][]*StructFieldCode { |
| 936 |
fieldMap := map[string][]*StructFieldCode{} |
| 937 |
structCode := field.getAnonymousStruct() |
| 938 |
if structCode == nil || structCode.isRecursive { |
| 939 |
fieldMap[field.key] = append(fieldMap[field.key], field) |
| 940 |
return fieldMap |
| 941 |
} |
| 942 |
for k, v := range c.getFieldMapFromAnonymousParent(structCode.fields) { |
| 943 |
fieldMap[k] = append(fieldMap[k], v...) |
| 944 |
} |
| 945 |
return fieldMap |
| 946 |
} |
| 947 |
|
| 948 |
func (c *Compiler) getFieldMapFromAnonymousParent(fields []*StructFieldCode) map[string][]*StructFieldCode { |
| 949 |
fieldMap := map[string][]*StructFieldCode{} |
| 950 |
for _, field := range fields { |
| 951 |
if field.isAnonymous { |
| 952 |
for k, v := range c.getAnonymousFieldMap(field) { |
| 953 |
// Do not handle tagged key when embedding more than once |
| 954 |
for _, vv := range v { |
| 955 |
vv.isTaggedKey = false |
| 956 |
} |
| 957 |
fieldMap[k] = append(fieldMap[k], v...) |
| 958 |
} |
| 959 |
continue |
| 960 |
} |
| 961 |
fieldMap[field.key] = append(fieldMap[field.key], field) |
| 962 |
} |
| 963 |
return fieldMap |
| 964 |
} |
| 965 |
|
| 966 |
func (c *Compiler) getDuplicatedFieldMap(fieldMap map[string][]*StructFieldCode) map[*StructFieldCode]struct{} { |
| 967 |
duplicatedFieldMap := map[*StructFieldCode]struct{}{} |
| 968 |
for _, fields := range fieldMap { |
| 969 |
if len(fields) == 1 { |
| 970 |
continue |
| 971 |
} |
| 972 |
if c.isTaggedKeyOnly(fields) { |
| 973 |
for _, field := range fields { |
| 974 |
if field.isTaggedKey { |
| 975 |
continue |
| 976 |
} |
| 977 |
duplicatedFieldMap[field] = struct{}{} |
| 978 |
} |
| 979 |
} else { |
| 980 |
for _, field := range fields { |
| 981 |
duplicatedFieldMap[field] = struct{}{} |
| 982 |
} |
| 983 |
} |
| 984 |
} |
| 985 |
return duplicatedFieldMap |
| 986 |
} |
| 987 |
|
| 988 |
func (c *Compiler) filteredDuplicatedFields(fields []*StructFieldCode, duplicatedFieldMap map[*StructFieldCode]struct{}) []*StructFieldCode { |
| 989 |
filteredFields := make([]*StructFieldCode, 0, len(fields)) |
| 990 |
for _, field := range fields { |
| 991 |
if field.isAnonymous { |
| 992 |
structCode := field.getAnonymousStruct() |
| 993 |
if structCode != nil && !structCode.isRecursive { |
| 994 |
structCode.fields = c.filteredDuplicatedFields(structCode.fields, duplicatedFieldMap) |
| 995 |
if len(structCode.fields) > 0 { |
| 996 |
filteredFields = append(filteredFields, field) |
| 997 |
} |
| 998 |
continue |
| 999 |
} |
| 1000 |
} |
| 1001 |
if _, exists := duplicatedFieldMap[field]; exists { |
| 1002 |
continue |
| 1003 |
} |
| 1004 |
filteredFields = append(filteredFields, field) |
| 1005 |
} |
| 1006 |
return filteredFields |
| 1007 |
} |
| 1008 |
|
| 1009 |
func (c *Compiler) isTaggedKeyOnly(fields []*StructFieldCode) bool { |
| 1010 |
var taggedKeyFieldCount int |
| 1011 |
for _, field := range fields { |
| 1012 |
if field.isTaggedKey { |
| 1013 |
taggedKeyFieldCount++ |
| 1014 |
} |
| 1015 |
} |
| 1016 |
return taggedKeyFieldCount == 1 |
| 1017 |
} |
| 1018 |
|
| 1019 |
func (c *Compiler) typeToStructTags(typ reflect.Type) runtime.StructTags { |
| 1020 |
tags := runtime.StructTags{} |
| 1021 |
fieldNum := typ.NumField() |
| 1022 |
for i := 0; i < fieldNum; i++ { |
| 1023 |
field := typ.Field(i) |
| 1024 |
if runtime.IsIgnoredStructField(field) { |
| 1025 |
continue |
| 1026 |
} |
| 1027 |
tags = append(tags, runtime.StructTagFromField(field)) |
| 1028 |
} |
| 1029 |
return tags |
| 1030 |
} |
| 1031 |
|
| 1032 |
// *struct{ field T } => struct { field *T } |
| 1033 |
// func (*T) MarshalJSON() ([]byte, error) |
| 1034 |
func (c *Compiler) isMovePointerPositionFromHeadToFirstMarshalJSONFieldCase(typ reflect.Type, isIndirectSpecialCase bool) bool { |
| 1035 |
return isIndirectSpecialCase && !c.isNilableType(typ) && c.isPtrMarshalJSONType(typ) |
| 1036 |
} |
| 1037 |
|
| 1038 |
// *struct{ field T } => struct { field *T } |
| 1039 |
// func (*T) MarshalText() ([]byte, error) |
| 1040 |
func (c *Compiler) isMovePointerPositionFromHeadToFirstMarshalTextFieldCase(typ reflect.Type, isIndirectSpecialCase bool) bool { |
| 1041 |
return isIndirectSpecialCase && !c.isNilableType(typ) && c.isPtrMarshalTextType(typ) |
| 1042 |
} |
| 1043 |
|
| 1044 |
func (c *Compiler) implementsMarshalJSON(typ reflect.Type) bool { |
| 1045 |
if !c.implementsMarshalJSONType(typ) { |
| 1046 |
return false |
| 1047 |
} |
| 1048 |
if typ.Kind() != reflect.Ptr { |
| 1049 |
return true |
| 1050 |
} |
| 1051 |
// type kind is reflect.Ptr |
| 1052 |
if !c.implementsMarshalJSONType(typ.Elem()) { |
| 1053 |
return true |
| 1054 |
} |
| 1055 |
if !runtime.IfaceIndir(typ.Elem()) { |
| 1056 |
// the value is stored directly in an interface value ( a map, a func, a struct of one pointer, ... ): the |
| 1057 |
// method of the pointer takes the pointer, where the one of the value would take the value itself, which the |
| 1058 |
// opcodes of a dereferenced pointer don't load. |
| 1059 |
return true |
| 1060 |
} |
| 1061 |
// needs to dereference |
| 1062 |
return false |
| 1063 |
} |
| 1064 |
|
| 1065 |
func (c *Compiler) implementsMarshalText(typ reflect.Type) bool { |
| 1066 |
if !typ.Implements(marshalTextType) { |
| 1067 |
return false |
| 1068 |
} |
| 1069 |
if typ.Kind() != reflect.Ptr { |
| 1070 |
return true |
| 1071 |
} |
| 1072 |
// type kind is reflect.Ptr |
| 1073 |
if !typ.Elem().Implements(marshalTextType) { |
| 1074 |
return true |
| 1075 |
} |
| 1076 |
if !runtime.IfaceIndir(typ.Elem()) { |
| 1077 |
// the value is stored directly in an interface value ( a map, a func, a struct of one pointer, ... ): the |
| 1078 |
// method of the pointer takes the pointer, where the one of the value would take the value itself, which the |
| 1079 |
// opcodes of a dereferenced pointer don't load. |
| 1080 |
return true |
| 1081 |
} |
| 1082 |
// needs to dereference |
| 1083 |
return false |
| 1084 |
} |
| 1085 |
|
| 1086 |
func (c *Compiler) isNilableType(typ reflect.Type) bool { |
| 1087 |
if !runtime.IfaceIndir(typ) { |
| 1088 |
return true |
| 1089 |
} |
| 1090 |
switch typ.Kind() { |
| 1091 |
case reflect.Ptr: |
| 1092 |
return true |
| 1093 |
case reflect.Map: |
| 1094 |
return true |
| 1095 |
case reflect.Func: |
| 1096 |
return true |
| 1097 |
default: |
| 1098 |
return false |
| 1099 |
} |
| 1100 |
} |
| 1101 |
|
| 1102 |
func (c *Compiler) implementsMarshalJSONType(typ reflect.Type) bool { |
| 1103 |
return typ.Implements(marshalJSONType) || typ.Implements(marshalJSONContextType) |
| 1104 |
} |
| 1105 |
|
| 1106 |
func (c *Compiler) isPtrMarshalJSONType(typ reflect.Type) bool { |
| 1107 |
return !c.implementsMarshalJSONType(typ) && c.implementsMarshalJSONType(reflect.PointerTo(typ)) |
| 1108 |
} |
| 1109 |
|
| 1110 |
func (c *Compiler) isPtrMarshalTextType(typ reflect.Type) bool { |
| 1111 |
return !typ.Implements(marshalTextType) && reflect.PointerTo(typ).Implements(marshalTextType) |
| 1112 |
} |
| 1113 |
|
| 1114 |
func (c *Compiler) codeToOpcode(ctx *compileContext, typ reflect.Type, code Code) (*Opcode, error) { |
| 1115 |
codes := code.ToOpcode(ctx) |
| 1116 |
// the first opcode takes the address of the value, as the one of the value of a map does. |
| 1117 |
codes.First().Flags |= IndirectFlags |
| 1118 |
codes.Last().Next = newEndOp(ctx, typ) |
| 1119 |
if err := c.linkRecursiveCode(ctx); err != nil { |
| 1120 |
return nil, err |
| 1121 |
} |
| 1122 |
return codes.First(), nil |
| 1123 |
} |
| 1124 |
|
| 1125 |
// markTailRecursion marks the opcodes of code, the code of a recursive struct, which encode a value of the same |
| 1126 |
// type as its last field: such a value is encoded in the frame of the struct, without a frame of its own |
| 1127 |
// ( RuntimeContext.EnterTailRecursive ), and the end of the struct closes the braces of the values one by one |
| 1128 |
// when the last of them ends ( LeaveTailRecursive ), which is why the end opcode leads back to it. |
| 1129 |
// |
| 1130 |
// The opcodes of the struct which the code is copied from, the ones which are jumped to it from, are not |
| 1131 |
// marked: the first value of the type in a frame enters a frame, so that the last value returns from it. |
| 1132 |
func markTailRecursion(code, end *Opcode, compiled *CompiledCode) { |
| 1133 |
// the end of the struct is an opcode of its own only when the last field is not encoded by one opcode: |
| 1134 |
// then it is the end which closes the braces, and which a value in the last field is followed by. |
| 1135 |
if code.End.Op != OpStructEnd { |
| 1136 |
return |
| 1137 |
} |
| 1138 |
for c := code; !c.IsEnd(); c = c.IterNext() { |
| 1139 |
if (c.Op == OpRecursive || c.Op == OpRecursivePtr) && c.Jmp == compiled && c.Next == code.End { |
| 1140 |
c.Flags |= TailRecursiveFlags |
| 1141 |
// what the indent is deeper by for a value: LeaveTailRecursive takes it back. |
| 1142 |
end.Indent = c.Indent - (code.Indent - 1) |
| 1143 |
} |
| 1144 |
} |
| 1145 |
end.Next = code.End |
| 1146 |
} |
| 1147 |
|
| 1148 |
func (c *Compiler) linkRecursiveCode(ctx *compileContext) error { |
| 1149 |
type recursiveTarget struct { |
| 1150 |
typeptr uintptr |
| 1151 |
embedded bool |
| 1152 |
query *FieldQuery |
| 1153 |
} |
| 1154 |
recursiveCodes := map[recursiveTarget]*CompiledCode{} |
| 1155 |
// maxFrameLength is the length of the longest frame which a recursive code is jumped from. |
| 1156 |
var maxFrameLength uintptr |
| 1157 |
// the recursive codes may increase while they are linked, so the length is evaluated every time. |
| 1158 |
for i := 0; i < len(*ctx.recursiveCodes); i++ { |
| 1159 |
recursive := (*ctx.recursiveCodes)[i] |
| 1160 |
target := recursiveTarget{typeptr: uintptr(recursive.Type), embedded: recursive.Jmp.Embedded, query: recursive.FieldQuery} |
| 1161 |
typeptr := target.typeptr |
| 1162 |
if recursiveCode, ok := recursiveCodes[target]; ok { |
| 1163 |
*recursive.Jmp = *recursiveCode |
| 1164 |
continue |
| 1165 |
} |
| 1166 |
codes, exists := ctx.structTypeToCodes[typeptr] |
| 1167 |
if target.embedded || !exists || c.isFiltered { |
| 1168 |
// structTypeToCodes has the opcodes of the struct itself, with the braces and the check of nil. |
| 1169 |
// - A recursive struct which is embedded jumps to the opcodes only of the fields. |
| 1170 |
// - A struct which has been compiled only as an embedded struct is not in structTypeToCodes. |
| 1171 |
// - The opcodes of a struct filtered by a field query are filtered by the query of their place, |
| 1172 |
// and the struct is filtered by the query of the code which jumps to it. |
| 1173 |
// In these cases the opcodes to jump to are compiled here. |
| 1174 |
structCode, err := c.compileStruct(runtime.TypeOfPtr(recursive.Type), false, target.embedded, false) |
| 1175 |
if err != nil { |
| 1176 |
return err |
| 1177 |
} |
| 1178 |
if target.query != nil { |
| 1179 |
structCode = structCode.Filter(target.query).(*StructCode) |
| 1180 |
} |
| 1181 |
structCode.enableIndirect() |
| 1182 |
if target.embedded { |
| 1183 |
codes = structCode.ToAnonymousOpcode(ctx) |
| 1184 |
} else { |
| 1185 |
codes = structCode.ToOpcode(ctx) |
| 1186 |
} |
| 1187 |
// the opcodes are copied up to the end, as the ones in the code which jumps to them are. |
| 1188 |
codes.Last().Next = newEndOp(ctx, runtime.TypeOfPtr(recursive.Type)) |
| 1189 |
} |
| 1190 |
|
| 1191 |
code := copyOpcode(codes.First()) |
| 1192 |
code.Op = code.Op.PtrHeadToHead() |
| 1193 |
lastCode := newEndOp(&compileContext{}, runtime.TypeOfPtr(recursive.Type)) |
| 1194 |
lastCode.Op = OpRecursiveEnd |
| 1195 |
|
| 1196 |
// OpRecursiveEnd must set before call TotalLength |
| 1197 |
code.End.Next = lastCode |
| 1198 |
markTailRecursion(code, lastCode, recursive.Jmp) |
| 1199 |
|
| 1200 |
totalLength := code.TotalLength() |
| 1201 |
|
| 1202 |
// Idx, ElemIdx, Length must set after call TotalLength |
| 1203 |
lastCode.Idx = opcodeOffset(totalLength + 1) |
| 1204 |
lastCode.setEndSlots() |
| 1205 |
|
| 1206 |
// An interface in the recursive code allocates its frame after the frame it is in, which is |
| 1207 |
// the one of the recursive code, not of the code which jumps to it. The length must include |
| 1208 |
// the slots of OpRecursiveEnd, so it is set after they are decided. |
| 1209 |
setTotalLengthToInterfaceOp(code) |
| 1210 |
|
| 1211 |
// The frame of the recursive code has the slots up to the ones of OpRecursiveEnd |
| 1212 |
// ( the offset to return to, the opcode to return to and the indent to restore ), |
| 1213 |
// so its length is the last index + 1. |
| 1214 |
nextTotalLength := uintptr(code.TotalLength()) + 1 |
| 1215 |
if maxFrameLength < nextTotalLength { |
| 1216 |
maxFrameLength = nextTotalLength |
| 1217 |
} |
| 1218 |
// extend length to alloc slot for elemIdx + length |
| 1219 |
if curTotalLength := uintptr(recursive.TotalLength()) + 3; maxFrameLength < curTotalLength { |
| 1220 |
maxFrameLength = curTotalLength |
| 1221 |
} |
| 1222 |
|
| 1223 |
compiled := recursive.Jmp |
| 1224 |
compiled.Code = code |
| 1225 |
compiled.NextLen = nextTotalLength |
| 1226 |
compiled.Linked = true |
| 1227 |
|
| 1228 |
recursiveCodes[target] = compiled |
| 1229 |
} |
| 1230 |
// The new frame is allocated after the frame which the recursive code is jumped from, and CurLen is the |
| 1231 |
// length of that frame. The same CompiledCode is jumped to from the code of the top level and from every |
| 1232 |
// recursive code, including itself, so CurLen must not be less than any of those frames: otherwise the |
| 1233 |
// new frame overlaps the slots of OpRecursiveEnd of the frame it is jumped from, and the indent to |
| 1234 |
// restore is broken by a pointer. |
| 1235 |
for _, compiled := range recursiveCodes { |
| 1236 |
compiled.CurLen = maxFrameLength |
| 1237 |
} |
| 1238 |
for _, recursive := range *ctx.recursiveCodes { |
| 1239 |
recursive.Jmp.CurLen = maxFrameLength |
| 1240 |
} |
| 1241 |
return nil |
| 1242 |
} |