package decoder

import (
	
	
	
	
	

	
	
)

// CompileToGetDecoder returns the decoder of the type.
// The type is given by the pointer to its type descriptor, which the caller reads from an interface value,
// because reflect.Type is required only when the decoder is not cached yet.
func ( unsafe.Pointer) (Decoder, error) {
	 := uintptr()
	if  := cachedDecoder.Load();  != nil {
		return *, nil
	}
	,  := compileHead(runtime.TypeOfPtr(), newCompiler(false))
	if  != nil {
		return nil, 
	}
	return *cachedDecoder.Store(, &), nil
}

var (
	jsonNumberType = reflect.TypeOf(json.Number(""))
	cachedDecoder  runtime.TypeCache[Decoder]
)

// compiler compiles the decoder of a type and the ones of the types of its values.
type compiler struct {
	// decoders has the decoders of the struct types compiled by this compile, and of the array, slice and map types
	// which are being compiled ( see compileKind ).
	decoders map[uintptr]Decoder
	// v2 is set for the decoders of the semantics of encoding/json/v2 ( see compileV2 ).
	v2 bool
	// stringifyNumbers is set, with v2, for the decoders of its option StringifyNumbers, and of the names of the
	// objects decoded into maps; stringTag, with stringifyNumbers, for the decoders of the values of a field of the
	// `string` option ( see compiler.stringTagCompiler ).
	stringifyNumbers bool
	stringTag        bool
	// v1Options are the options of encoding/json which the decoders of v2 are compiled for ( see v1DecoderOptions ).
	v1Options V2Flags
	// mapKeys is set for the decoders of the keys of a map, which the methods of JSON don't decode with
	// CallMethodsWithLegacySemantics ( see compileV2 ): the type of a key doesn't tell it is one.
	mapKeys bool
	// funcs are the functions of unmarshaling which the decoders of v2 are compiled for, or nil.
	funcs *UnmarshalFuncs
}

func newCompiler( bool) *compiler {
	return &compiler{decoders: map[uintptr]Decoder{}, v2: }
}

func compileHead( reflect.Type,  *compiler) (Decoder, error) {
	// The kind is validated here, once per type, instead of for every call of the decoding functions:
	// the decoder of a non-pointer type is never created, so it is never cached either.
	if .Kind() != reflect.Ptr {
		return nil, &errors.InvalidUnmarshalError{Type: }
	}
	if .v2 {
		return compile(.Elem(), "", "", )
	}
	switch {
	case implementsUnmarshalJSONType(reflect.PointerTo()):
		return newUnmarshalJSONDecoder(reflect.PointerTo()), nil
	case reflect.PointerTo().Implements(unmarshalTextType):
		return newUnmarshalTextDecoder(reflect.PointerTo()), nil
	}
	return compile(.Elem(), "", "", )
}

func compile( reflect.Type, ,  string,  *compiler) (Decoder, error) {
	if .v2 {
		return .compileV2(, , )
	}
	if implementsUnmarshalFrom(reflect.PointerTo()) {
		,  := compileAfterFrom(, , , )
		if  != nil {
			return nil, 
		}
		return newUnmarshalFromDecoder(reflect.PointerTo(), ), nil
	}
	return compileAfterFrom(, , , )
}

// compileAfterFrom returns the decoder of a value of the type by its methods of unmarshaling after
// UnmarshalJSONFrom, or by its kind.
func compileAfterFrom( reflect.Type, ,  string,  *compiler) (Decoder, error) {
	switch {
	case implementsUnmarshalJSONType(reflect.PointerTo()):
		return newUnmarshalJSONDecoder(reflect.PointerTo()), nil
	case reflect.PointerTo().Implements(unmarshalTextType):
		return newUnmarshalTextDecoder(reflect.PointerTo()), nil
	}
	return compileKind(, , , )
}

// compileKind returns the decoder of a value of the type by its kind, without its methods of unmarshaling.
// c.decoders has the decoders of the struct types compiled by this compile, and of the array, slice and map types
// which are being compiled: a value of such a type inside itself, or a struct met again, is decoded by its decoder.
func compileKind( reflect.Type, ,  string,  *compiler) (Decoder, error) {
	if ,  := .decoders[uintptr(runtime.TypePtr())];  {
		return , nil
	}
	switch .Kind() {
	case reflect.Ptr:
		return compilePtr(, , , )
	case reflect.Struct:
		return compileStruct(, , , )
	case reflect.Slice:
		 := .Elem()
		if .Kind() == reflect.Uint8 {
			return compileBytes(, , )
		}
		return compileSlice(, , , )
	case reflect.Array:
		return compileArray(, , , )
	case reflect.Map:
		return compileMap(, , , )
	case reflect.Interface:
		return compileInterface(, , )
	case reflect.Uintptr:
		return compileUint(, , )
	case reflect.Int:
		return compileInt(, , )
	case reflect.Int8:
		return compileInt8(, , )
	case reflect.Int16:
		return compileInt16(, , )
	case reflect.Int32:
		return compileInt32(, , )
	case reflect.Int64:
		return compileInt64(, , )
	case reflect.Uint:
		return compileUint(, , )
	case reflect.Uint8:
		return compileUint8(, , )
	case reflect.Uint16:
		return compileUint16(, , )
	case reflect.Uint32:
		return compileUint32(, , )
	case reflect.Uint64:
		return compileUint64(, , )
	case reflect.String:
		return compileString(, , )
	case reflect.Bool:
		return compileBool(, , )
	case reflect.Float32:
		return compileFloat32(, , )
	case reflect.Float64:
		return compileFloat64(, , )
	case reflect.Func:
		return compileFunc(, , )
	}
	return newInvalidDecoder(, , ), nil
}

func isStringTagSupportedType( reflect.Type) bool {
	// The option applies to a field of a string, a number or a bool, as encoding/json documents it. As encoding/json
	// of Go 1.27 does, it follows one pointer, named or not, and does not apply to the value of a pointer to a pointer,
	// nor to a value which has a method of unmarshaling.
	if .Kind() == reflect.Pointer {
		 = .Elem()
	}
	switch {
	case implementsUnmarshalFrom(reflect.PointerTo()), implementsUnmarshalJSONType(reflect.PointerTo()):
		return false
	case reflect.PointerTo().Implements(unmarshalTextType):
		return false
	}
	switch .Kind() {
	case reflect.Bool,
		reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
		reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
		reflect.Float32, reflect.Float64,
		reflect.String:
		return true
	}
	return false
}

func compileMapKey( reflect.Type, ,  string,  *compiler) (Decoder, error) {
	if reflect.PointerTo().Implements(unmarshalTextType) {
		return &textKeyDecoder{unmarshalTextDecoder{typ: reflect.PointerTo()}}, nil
	}
	if .Kind() == reflect.String {
		 := newStringDecoder(, )
		.typ = 
		return , nil
	}
	if .Kind() == reflect.Pointer {
		if isPointerCycle() {
			return newInvalidDecoder(, , ), nil
		}
		// a key of a pointer type is the key the pointer points to, which is allocated
		,  := (.Elem(), , , )
		if  != nil {
			return nil, 
		}
		if ,  := .(*invalidDecoder);  {
			return newInvalidDecoder(, , ), nil
		}
		return newPtrDecoder(, .Elem(), , ), nil
	}
	switch .Kind() {
	case reflect.Array, reflect.Struct, reflect.Slice, reflect.Map:
		// No key is decoded into a value of these kinds: their decoders would end as an invalidDecoder by the switch
		// below. They are not compiled, so that a type which holds the map, as in type M map[*M]int, ends here.
		return newInvalidDecoder(, , ), nil
	}
	// The other keys are decoded by their kind, whatever other methods they have, as encoding/json decodes them: an
	// integer, a float, a bool, and an empty interface, which a key of a string is stored in.
	,  := compileKind(, , , )
	if  != nil {
		return nil, 
	}
	switch .(type) {
	case *interfaceDecoder:
		if .NumMethod() == 0 {
			return , nil
		}
	case *boolDecoder, *intDecoder, *uintDecoder, *floatDecoder, *float32Decoder, *numberDecoder:
		 := newWrappedStringDecoder(, , , )
		.isMapKey = true
		return , nil
	}
	return newInvalidDecoder(, , ), nil
}

func compilePtr( reflect.Type, ,  string,  *compiler) (Decoder, error) {
	if isPointerCycle() {
		// No value but null can be decoded into it, which sets the pointer to nil.
		return newPtrDecoder(newInvalidDecoder(.Elem(), , ), .Elem(), , ), nil
	}
	,  := compile(.Elem(), , , )
	if  != nil {
		return nil, 
	}
	return newPtrDecoder(, .Elem(), , ), nil
}

// isPointerCycle reports whether the pointer type points to pointers only, without an end, as type R *R does:
// the pointers are followed two at a time and one at a time, which meet in a cycle.
func isPointerCycle( reflect.Type) bool {
	,  := , 
	for .Kind() == reflect.Pointer && .Elem().Kind() == reflect.Pointer {
		,  = .Elem(), .Elem().Elem()
		if  ==  {
			return true
		}
	}
	return false
}

func compileInt( reflect.Type, ,  string) (Decoder, error) {
	return newIntDecoder(, , , func( unsafe.Pointer,  int64) {
		*(*int)() = int()
	}), nil
}

func compileInt8( reflect.Type, ,  string) (Decoder, error) {
	return newIntDecoder(, , , func( unsafe.Pointer,  int64) {
		*(*int8)() = int8()
	}), nil
}

func compileInt16( reflect.Type, ,  string) (Decoder, error) {
	return newIntDecoder(, , , func( unsafe.Pointer,  int64) {
		*(*int16)() = int16()
	}), nil
}

func compileInt32( reflect.Type, ,  string) (Decoder, error) {
	return newIntDecoder(, , , func( unsafe.Pointer,  int64) {
		*(*int32)() = int32()
	}), nil
}

func compileInt64( reflect.Type, ,  string) (Decoder, error) {
	return newIntDecoder(, , , func( unsafe.Pointer,  int64) {
		*(*int64)() = 
	}), nil
}

func compileUint( reflect.Type, ,  string) (Decoder, error) {
	return newUintDecoder(, , , func( unsafe.Pointer,  uint64) {
		*(*uint)() = uint()
	}), nil
}

func compileUint8( reflect.Type, ,  string) (Decoder, error) {
	return newUintDecoder(, , , func( unsafe.Pointer,  uint64) {
		*(*uint8)() = uint8()
	}), nil
}

func compileUint16( reflect.Type, ,  string) (Decoder, error) {
	return newUintDecoder(, , , func( unsafe.Pointer,  uint64) {
		*(*uint16)() = uint16()
	}), nil
}

func compileUint32( reflect.Type, ,  string) (Decoder, error) {
	return newUintDecoder(, , , func( unsafe.Pointer,  uint64) {
		*(*uint32)() = uint32()
	}), nil
}

func compileUint64( reflect.Type, ,  string) (Decoder, error) {
	return newUintDecoder(, , , func( unsafe.Pointer,  uint64) {
		*(*uint64)() = 
	}), nil
}

func compileFloat32( reflect.Type, ,  string) (Decoder, error) {
	 := newFloatDecoder(, , func( unsafe.Pointer,  float64) {
		*(*float32)() = float32()
	})
	.typ, .is32 = , true
	return &float32Decoder{floatDecoder: *}, nil
}

func compileFloat64( reflect.Type, ,  string) (Decoder, error) {
	 := newFloatDecoder(, , func( unsafe.Pointer,  float64) {
		*(*float64)() = 
	})
	.typ = 
	return , nil
}

func compileString( reflect.Type, ,  string) (Decoder, error) {
	if  == jsonNumberType {
		return newNumberDecoder(, , func( unsafe.Pointer,  json.Number) {
			*(*json.Number)() = 
		}), nil
	}
	 := newStringDecoder(, )
	.typ = 
	return , nil
}

func compileBool( reflect.Type, ,  string) (Decoder, error) {
	 := newBoolDecoder(, )
	.typ = 
	return , nil
}

func compileBytes( reflect.Type, ,  string) (Decoder, error) {
	 := newBytesDecoder(.Elem(), , )
	.sliceType = 
	return , nil
}

func compileSlice( reflect.Type, ,  string,  *compiler) (Decoder, error) {
	 := .Elem()
	 := newSliceDecoder(nil, , .Size(), , )
	.typ = 
	var  Decoder = 
	if .v2 {
		 = newV2SliceDecoder()
	}
	,  := compileElem(, , , , )
	if  != nil {
		return nil, 
	}
	.valueDecoder = .goOnDecoder()
	return , nil
}

// compileElem returns the decoder of the elements of typ, an array, a slice or a map type whose decoder is dec, which
// decodes the values of typ inside them, as compileStruct does for the fields of a struct.
func compileElem( reflect.Type,  Decoder, ,  string,  *compiler) (Decoder, error) {
	 := uintptr(runtime.TypePtr())
	if ,  := .decoders[];  {
		// a decoder of v2 which declines values to dec, which the values of typ in the element are decoded by ( see
		// compileNextV2 )
		return compile(.Elem(), , , )
	}
	.decoders[] = 
	,  := compile(.Elem(), , , )
	delete(.decoders, )
	return , 
}

func compileArray( reflect.Type, ,  string,  *compiler) (Decoder, error) {
	 := newArrayDecoder(nil, , , )
	,  := compileElem(, , , , )
	if  != nil {
		return nil, 
	}
	.valueDecoder = 
	return , nil
}

func compileMap( reflect.Type, ,  string,  *compiler) (Decoder, error) {
	,  := compileMapKey(.Key(), , , )
	if  != nil {
		return nil, 
	}
	 := newMapDecoder(, .Key(), , .Elem(), nil, , )
	,  := compileElem(, , , , )
	if  != nil {
		return nil, 
	}
	.valueDecoder = 
	return , nil
}

func compileInterface( reflect.Type, ,  string) (Decoder, error) {
	return newInterfaceDecoder(, , ), nil
}

func compileFunc( reflect.Type, ,  string) (Decoder, error) {
	return newFuncDecoder(, , ), nil
}

// embeddedStruct is a struct type whose fields are found for the struct being compiled: the struct itself, at no
// indexes, or a struct embedded in it, through the embedded fields at the indexes of index.
type embeddedStruct struct {
	typ   reflect.Type
	index []int
}

// fieldCandidate is a field of the struct being compiled or of a struct embedded in it, at the indexes of index.
type fieldCandidate struct {
	set   *structFieldSet
	index []int
}

func ( fieldCandidate) () int        { return len(.index) - 1 }
func ( fieldCandidate) () bool { return .set.isTaggedKey }

// compileStruct returns the decoder of the struct type typ. It stays in c.decoders after the compile, so that a
// struct type met again in the same compile, by another field or by the fields of the structs it is embedded in, which
// are compiled as fields of each struct it is embedded in, is not compiled again.
func compileStruct( reflect.Type, ,  string,  *compiler) (Decoder, error) {
	 := newStructDecoder(, )
	.typ = 
	.decoders[uintptr(runtime.TypePtr())] = 
	,  := structFields(, )
	if  != nil {
		return nil, 
	}
	.setFields()
	return , nil
}

// structFields returns the fields of the struct type typ in their order, as encoding/json finds them: the fields of
// the structs embedded without a key are promoted, the least nested first, and a struct already met is not met again.
// Of the fields of a key, the one runtime.DominantField chooses is taken.
func structFields( reflect.Type,  *compiler) ([]*structFieldSet, error) {
	var  []fieldCandidate
	 := map[reflect.Type]bool{}
	// the structs of a level and of the next one, and how many times each is embedded at its level
	var  []embeddedStruct
	 := []embeddedStruct{{typ: }}
	,  := map[reflect.Type]int{}, map[reflect.Type]int{}
	for len() > 0 {
		,  = , [:0]
		,  = , 
		clear()
		for ,  := range  {
			if [.typ] {
				continue
			}
			[.typ] = true
			for  := 0;  < .typ.NumField(); ++ {
				 := .typ.Field()
				if runtime.IsIgnoredStructField() {
					continue
				}
				 := runtime.StructTagFromField()
				 := append(slices.Clip(.index), )
				if  := promotingStruct(, );  != nil {
					[]++
					if [] == 1 {
						 = append(, embeddedStruct{typ: , index: })
					}
					continue
				}
				,  := compile(.Type, .typ.Name(), .Name, )
				if  != nil {
					return nil, 
				}
				if .IsString && isStringTagSupportedType(.Type) {
					 = newWrappedStringDecoder(.Type, , .typ.Name(), .Name)
				}
				, ,  := promotedField(, , )
				 := &structFieldSet{
					dec:         ,
					offset:      ,
					isTaggedKey: .IsTaggedKey,
					key:         .Key,
					keyLen:      int64(len(.Key)),
					err:         ,
				}
				 = append(, fieldCandidate{set: , index: })
				if [.typ] > 1 {
					// a struct embedded more than once at this level promotes each field more than once: none is taken
					 = append(, fieldCandidate{set: , index: })
				}
			}
		}
	}
	slices.SortStableFunc(, func(,  fieldCandidate) int { return strings.Compare(.set.key, .set.key) })
	 := [:0]
	for  := 0;  < len(); {
		 :=  + 1
		for  < len() && [].set.key == [].set.key {
			++
		}
		if  := runtime.DominantField([:]);  >= 0 {
			 = append(, [+])
		}
		 = 
	}
	slices.SortFunc(, func(,  fieldCandidate) int { return slices.Compare(.index, .index) })
	 := make([]*structFieldSet, 0, len())
	for ,  := range  {
		 = append(, .set)
	}
	return , nil
}

// promotingStruct returns the struct type of an embedded field without a key, or a pointer to it, whose fields are
// promoted, or nil. Its methods of unmarshaling don't matter, as in encoding/json: a struct to which they are promoted
// is decoded by them instead of by its fields.
func promotingStruct( reflect.StructField,  *runtime.StructTag) reflect.Type {
	if !.Anonymous || .IsTaggedKey {
		return nil
	}
	 := .Type
	if .Kind() == reflect.Pointer {
		 = .Elem()
	}
	if .Kind() != reflect.Struct {
		return nil
	}
	return 
}

// promotedField returns the decoder and the offset in the struct type typ of the field at index, a field of a struct
// embedded in typ when index has more than one, whose decoder in the struct which has it is dec, and the error of the
// field when the embedded pointer at that offset can't be allocated ( see structFieldSet ). An embedded pointer is
// allocated by the decoder when it is nil. Only the error of the pointer at the offset is returned: the one of an
// unexported pointer embedded in the struct it points to is not.
func promotedField( reflect.Type,  []int,  Decoder) (Decoder, uintptr, error) {
	 := .Field([0])
	if len() == 1 {
		return , .Offset, nil
	}
	if .Type.Kind() != reflect.Pointer {
		, ,  := (.Type, [1:], )
		return , .Offset + , 
	}
	 := .Type.Elem()
	, ,  := (, [1:], )
	 = newAnonymousFieldDecoder(, , )
	if !.IsExported() {
		return , .Offset, errUnsettableEmbeddedPointer
	}
	return , .Offset, nil
}

func implementsUnmarshalJSONType( reflect.Type) bool {
	return .Implements(unmarshalJSONType) || .Implements(unmarshalJSONContextType)
}