package encoder

import (
	
	
	
	
	
	
	

	ierrors 
	
	
	
)

// The semantics of encoding/json/v2, which the compiler gives the opcodes of a type in the v2 mode: they are the
// ones of v1 but where v2 differs.

var (
	timeDurationType = reflect.TypeFor[time.Duration]()
	timeTimeType     = reflect.TypeFor[time.Time]()
)

var (
	errYearRange     = errors.New("year outside of range [0,9999]")
	errTimezoneRange = errors.New("timezone hour outside of range [0,23]")
	// errNoDuration is the error of a time.Duration, which has no representation of its own until
	// encoding/json/v2 decides one.
	errNoDuration = errors.New("no default representation")
)

// appendTime appends the time.Time at p in RFC 3339 with nanosecond precision, which can't represent a year
// before 0 or after 9999, nor a time zone of 24 hours or more.
// Its error is the one of MarshalJSON, as encoding/json reports it with ReportErrorsWithLegacySemantics, which the v2
// json package reports as the SemanticError of the time at its place otherwise.
func appendTime( *RuntimeContext,  []byte,  unsafe.Pointer) ([]byte, error) {
	 := (*time.Time)()
	if  := .Year();  < 0 ||  > 9999 {
		return , &ierrors.MethodError{GoType: timeTimeType, Err: errYearRange, Kind: ierrors.MethodMarshalJSON}
	}
	if ,  := .Zone();  <= -24*60*60 ||  >= 24*60*60 {
		return , &ierrors.MethodError{GoType: timeTimeType, Err: errTimezoneRange, Kind: ierrors.MethodMarshalJSON}
	}
	 = append(, '"')
	 = .AppendFormat(, time.RFC3339Nano)
	return append(, '"'), nil
}

// v2Code returns the code of a value of typ by the semantics of encoding/json/v2, and true, if they differ from
// the ones of v1 for the type: false lets the type be compiled as v1 compiles it. A type with a method of a
// marshaler is not given to it. addressable is whether the value is addressable, which a method of a pointer
// receiver is called for only with CallMethodsWithLegacySemantics ( see v2MethodOfAt ).
func ( *Compiler) ( reflect.Type,  bool) (Code, bool) {
	// the type of a default representation, which the functions and the method c.v2DefaultAfter declined, is
	// written by what is after them, once: a value of the type in it is written as any other ( see
	// appendDefault ).
	,  := noMethod,  == .v2DefaultType
	switch {
	case .nextIsEmbedded:
		// the fields of an embedded struct are members of the struct which embeds it, which no function or
		// method writes.
		return nil, false
	case .stringTag:
		// the value of the option, whose code is the one of a field of the option: a value which it doesn't apply to
		// is written without it, and so are the values in it, as the option applies to the value of its depth only
		,  := .stringTagCode(, )
		switch {
		case  != nil:
			return , true
		case !:
			 := allMethods
			if  {
				 = .v2DefaultAfter
			}
			return .appendFuncCode(, appendWithoutStringTag(, , )), true
		}
	}
	switch {
	case :
		 = .v2DefaultAfter
		.v2DefaultType = nil
	default:
		if ,  := .v2FuncsCode(, );  {
			return , true
		}
	}
	switch {
	case  == timeDurationType && .v1Options&modeFormatDurationAsNano == 0:
		// a time.Duration has no representation, but its nanoseconds as an int64 with FormatDurationAsNano, which
		// its kind gives
		return .appendFuncCode(, appendError(, errNoDuration)), true
	case  == timeTimeType:
		return .appendFuncCode(, appendTime), true
	}
	if ,  := .v2MethodCode(, , );  {
		return , true
	}
	switch .Kind() {
	case reflect.Interface:
		if .v1Options&modeCallMethodsWithLegacySemantics == 0 {
			break
		}
		if  := v2MethodOfInterface();  != noMethod {
			return .appendFuncCode(, appendV1Interface(, )), true
		}
	case reflect.Struct:
		if  := v2FieldsOf(); .Err != nil && .v1Options&modeReportErrorsWithLegacySemantics == 0 {
			// with ReportErrorsWithLegacySemantics, the members which jsonfields found are written, as encoding/json
			// writes them
			return .appendFuncCode(, appendError(.Err.GoType, .Err.Err)), true
		} else if .FormatErr != nil {
			return .appendFuncCode(, appendError(.FormatErr.GoType, .FormatErr.Err)), true
		}
	case reflect.Complex64, reflect.Complex128, reflect.Chan, reflect.Func, reflect.UnsafePointer:
		// a value of a type which has no representation fails when it is marshaled, not when its type is
		// compiled: an empty map of it is {}.
		return .appendFuncCode(, appendError(, nil)), true
	case reflect.Slice:
		if  := .Elem(); .Kind() == reflect.Uint8 && .PkgPath() != "" {
			if !v2BytesAsArray(, .v1Options&modeFormatByteArrayAsArray != 0,
				.v1Options&modeFormatBytesWithLegacySemantics != 0) {
				// the base64 of its bytes, as of a []byte, with FormatBytesWithLegacySemantics
				,  := .bytesCode(, false)
				return , true
			}
			// a slice of a named byte type is a list of its values, of their own representation: only []byte is
			// base64.
			,  := .sliceCode()
			if  != nil {
				return nil, false
			}
			return , true
		}
	case reflect.Array:
		if .Elem().Kind() == reflect.Uint8 && !v2BytesAsArray(, .v1Options&modeFormatByteArrayAsArray != 0,
			.v1Options&modeFormatBytesWithLegacySemantics != 0) {
			 := .Len()
			return .appendFuncCode(, func( *RuntimeContext,  []byte,  unsafe.Pointer) ([]byte, error) {
				return AppendByteSlice(, , unsafe.Slice((*byte)(), )), nil
			}), true
		}
	case reflect.Ptr:
		// with CallMethodsWithLegacySemantics, the opcodes of its type are the ones of a value given by itself,
		// which is not addressable: a value which a method writes is written by the code of the value of the
		// pointer, addressable, which is the code of the method.
		if  := .Elem().Kind(); ( == reflect.Map ||  == reflect.Slice) &&
			(.v1Options&modeCallMethodsWithLegacySemantics == 0 || !.v2HasMethod(.Elem())) {
			// A nil map or slice is {} or [], and a nil pointer is null: the opcodes of a map or a slice which a
			// pointer is followed to can't tell the one from the other, so the value is encoded by the opcodes
			// of its type, as a value of interface{} is, after the pointer.
			return &PtrCode{typ: , value: &InterfaceCode{typ: .Elem(), static: true}, ptrNum: 1}, true
		}
	}
	return nil, false
}

// v2BytesAsArray reports whether typ, a slice or an array of a byte kind, is written as a JSON array of its elements
// rather than as the base64 string of its bytes, by the options of encoding/json which say it: a [N]byte with
// FormatByteArrayAsArray, and a slice or an array of a named byte type, but with FormatBytesWithLegacySemantics for
// one of a type which has no method of marshaling.
func v2BytesAsArray( reflect.Type, ,  bool) bool {
	 := .Elem()
	switch {
	case .Kind() == reflect.Array && :
		return true
	case .PkgPath() == "":
		return false
	}
	return ! || v2MethodOf(, noMethod) != noMethod
}

// appendFuncCode returns the code which writes a value of typ by fn, which is given the address of the value, as
// a method on the pointer is.
func ( *Compiler) ( reflect.Type,  AppendFunc) *MarshalJSONCode {
	return &MarshalJSONCode{typ: , appendValue: , isAddrForMarshaler: true}
}

// hasNoRepresentation reports whether a value of the kind has no JSON representation: a complex number, a channel, a
// function or an unsafe.Pointer.
func hasNoRepresentation( reflect.Kind) bool {
	switch  {
	case reflect.Complex64, reflect.Complex128, reflect.Chan, reflect.Func, reflect.UnsafePointer:
		return true
	}
	return false
}

// appendError returns the function which fails for a value of typ with err.
func appendError( reflect.Type,  error) AppendFunc {
	return func( *RuntimeContext,  []byte,  unsafe.Pointer) ([]byte, error) {
		return , &ierrors.SemanticError{GoType: , Err: }
	}
}

// v2Fields are the JSON object members of the struct types, which v2FieldsOf found.
var v2Fields sync.Map // map[reflect.Type]*jsonfields.Fields

// v2FieldsOf returns the JSON object members of the struct type t.
func v2FieldsOf( reflect.Type) *jsonfields.Fields {
	if ,  := v2Fields.Load();  {
		return .(*jsonfields.Fields)
	}
	,  := v2Fields.LoadOrStore(, jsonfields.Of())
	return .(*jsonfields.Fields)
}

// v2Object is the JSON object of a struct of the v2 semantics, while the struct and the structs embedded in it are
// compiled.
type v2Object struct {
	// members are the members of the object, by the key of their indexes ( see indexKey ).
	members map[string]*jsonfields.Field
	// embeds are the embedded structs which a member is in, by the key of their indexes.
	embeds map[string]bool
	// path is the index of the struct being compiled in the struct of the object.
	path []int
}

// indexKey is the key of the index of a field by reflect.Type.FieldByIndex.
func indexKey( []int) string {
	return fmt.Sprint()
}

func newV2Object( *jsonfields.Fields) *v2Object {
	 := &v2Object{members: map[string]*jsonfields.Field{}, embeds: map[string]bool{}}
	for  := range .List {
		 := &.List[]
		.members[indexKey(.Index)] = 
		for  := 1;  < len(.Index); ++ {
			.embeds[indexKey(.Index[:])] = true
		}
	}
	return 
}

// v2StructTags returns the tags of the fields of the struct type typ which are written to the JSON object of the
// v2 semantics, in their order: the members, and the embedded structs which members are in, whose indexes are
// in embeds. An embedded struct is a part of the object being compiled, at v2EmbedPath; another struct is the
// object of its own. The returned function ends the compile of the struct.
func ( *Compiler) ( reflect.Type,  bool) (runtime.StructTags, map[*runtime.StructTag][]int, func()) {
	 := .v2Object
	var  *v2Object
	if  &&  != nil {
		 = &v2Object{members: .members, embeds: .embeds, path: .v2EmbedPath}
	} else {
		 = newV2Object(v2FieldsOf())
	}
	.v2Object = 
	var  runtime.StructTags
	 := map[*runtime.StructTag][]int{}
	for  := range .NumField() {
		 := append(slices.Clip(.path), )
		 := indexKey()
		 := .Field()
		if ,  := .members[];  {
			 = append(, &runtime.StructTag{
				Key:         .Name,
				QuotedKey:   .QuotedName,
				IsTaggedKey: .HasName,
				IsOmitEmpty: .OmitEmpty,
				IsOmitZero:  .OmitZero || .omitZeroStructFields,
				IsString:    .String,
				Field:       ,
			})
		} else if .embeds[] {
			 := &runtime.StructTag{Key: .Name, Field: }
			 = append(, )
			[] = 
		}
	}
	return , , func() { .v2Object =  }
}

// v2HiddenNames returns the names of the members of typ, a recursive struct embedded at path in the object being
// compiled, which the object doesn't write from it: its code is compiled when the recursive codes are linked, as
// the object of its own ( see StructCode.hiddenNames ).
func ( *Compiler) ( reflect.Type,  []int) []string {
	 := map[string]bool{}
	for ,  := range .v2Object.members {
		if len(.Index) > len() && slices.Equal(.Index[:len()], ) {
			[.Name] = true
		}
	}
	var  []string
	for ,  := range v2FieldsOf().List {
		if ![.Name] {
			 = append(, .Name)
		}
	}
	return 
}

var errInvalidStringTag = errors.New("invalid use of `string` tag option")

// v2FieldValueCode returns the code of the value of a field of the v2 semantics, addressable if the struct is, and
// true, if the options of its tag make it differ from the code of its type. The options of the field are changed for
// its opcodes: the `string` option is kept for a number, which the opcodes of its type write in a string, and dropped
// for any other value, which the code of the option writes ( see stringTagCode ), or the code of its type if the
// option doesn't apply to it.
func ( *Compiler) ( *StructFieldCode,  bool) (Code, bool) {
	 := *.tag
	.tag = &
	// with OmitEmptyWithLegacySemantics, the value is omitted if it is false, 0, nil or of no length, as v1 omits it,
	// which the opcodes of omitempty decide by the kind of the field ( see emptyKindOf ), before it is written.
	if .IsOmitEmpty && .v1Options&modeOmitEmptyWithLegacySemantics == 0 {
		// the value is omitted if it would be null, "", {} or []: some kinds are known to be empty or not by the
		// value ( the check of omitempty of v1 ), the others by what they write ( unwriteEmpty ).
		switch  := .typ.Kind(); {
		case  == reflect.Ptr && !.v2HasMethod(.typ) && .v2NeverEmpty(.typ.Elem()):
			// a nil pointer is null, and the value it points to is never empty.
		case  == reflect.Ptr && !.v2HasMethod(.typ) && !.v2HasMethod(.typ.Elem()) &&
			.typ.Elem().Kind() == reflect.String && !.IsString:
			// a nil pointer is null, and the string it points to is empty only if it is "".
			.omitEmptyString = true
		case ( == reflect.Ptr ||  == reflect.Interface) && len(.funcs.funcsOf(.typ)) == 0:
			// a nil value is null, unless a function writes it, as a function of the pointer to it does: with
			// functions, it is omitted by what is written, as a value of a method is.
			.unwriteEmpty = true
		case .typ == rawMessageType && v2MethodOf(.typ, noMethod) == methodMarshalJSON &&
			len(.funcs.funcsOf(.typ)) == 0:
			// a nil json.RawMessage is null, which its method writes without a call ( see v2MethodCode ): it is
			// omitted by the check of nil, the others by what they write.
			.emptyNil = true
			.unwriteEmpty = true
		case .v2HasMethod(.typ):
			.IsOmitEmpty = false
			.unwriteEmpty = true
		case .v2NeverEmpty(.typ):
			.IsOmitEmpty = false
		case  == reflect.String ||  == reflect.Map ||  == reflect.Slice ||  == reflect.Array:
			// empty if its length is 0.
		default:
			.IsOmitEmpty = false
			.unwriteEmpty = true
		}
	}
	// the check of nil writes null instead of calling a marshaler, which only a nil pointer is.
	.isNilCheck = .IsOmitEmpty || .typ.Kind() == reflect.Ptr
	if !.IsString {
		return nil, false
	}
	,  := .stringTagCode(.typ, )
	if  &&  == nil {
		return nil, false
	}
	.IsString = false
	return ,  != nil
}

// stringTagCode returns the code of a value of typ of the `string` option, addressable or not, as encoding/json/v2
// writes it: nil for a number, after the pointers to it, whose nil is null, which is written in a string, and for a
// value which a method or a function writes in the compile mode of the option, whose options they are given ( see
// appendStringTag ); the error of the option for a value of another kind. It reports false if the option doesn't
// apply, which the value is written without.
//
// With StringifyWithLegacySemantics, the option applies to a bool, whose JSON value is written in a string, and to a
// string, whose JSON string is, through one pointer only: a pointer to a pointer is the error of the option.
//
// With ReportErrorsWithLegacySemantics, a value of another kind is not an error: the option doesn't apply to it, as
// encoding/json writes it, but to the value which an interface value holds, without StringifyWithLegacySemantics.
func ( *Compiler) ( reflect.Type,  bool) (Code, bool) {
	 := 
	 := 0
	// the walk ends where it comes back to a pointer which it passed, in pointers to pointers without an end, as type
	// P *P, which hold null or themselves
	var  []reflect.Type
	for .Kind() == reflect.Ptr && !.v2HasMethod() && !slices.Contains(, ) {
		 = append(, )
		 = .Elem()
		++
	}
	 := .v1Options&modeStringifyWithLegacySemantics != 0
	 := .v1Options&modeReportErrorsWithLegacySemantics != 0
	// the value which a pointer points to is addressable
	 =  ||  > 0
	// with StringifyWithLegacySemantics, a pointer to a pointer, as a pointer of a cycle of pointers is, which no
	// function of the type of the field writes, whatever functions its pointers have, as encoding/json/v2 reads the
	// type of the field
	 := .Kind() == reflect.Ptr && .Elem().Kind() == reflect.Ptr && !.v2HasMethod()
	var  Code
	switch {
	case  &&  && :
		return nil, false
	case  && :
		return .appendFuncCode(, appendError(, errInvalidStringTag)), true
	case .v2HasMethodAt(, ) &&  != timeTimeType,
		 && ! && .Kind() == reflect.Interface:
		if .stringTag {
			return nil, true
		}
		 = .appendFuncCode(, appendStringTag(, ))
	case .Kind() == reflect.Ptr:
		// a pointer of a cycle of pointers, which the walk came back to: the option doesn't apply to it, as
		// encoding/json/v2 writes null at the end of the pointers
		return nil, false
	case  == timeDurationType && .v1Options&modeFormatDurationAsNano == 0:
		 = .appendFuncCode(, appendError(, errNoDuration))
	case isNumberKind(.Kind()) ||  == jsonNumberType:
		return nil, true
	case  && .Kind() == reflect.Bool:
		 = .appendFuncCode(, appendStringifiedBool)
	case  && .Kind() == reflect.String:
		 = .appendFuncCode(, appendStringifiedString())
	case hasNoRepresentation(.Kind()):
		// the error of the type, which has no representation whatever its options are
		 = .appendFuncCode(, appendError(, nil))
	case :
		return nil, false
	default:
		 = .appendFuncCode(, appendError(, errInvalidStringTag))
	}
	if  > 0 {
		 = &PtrCode{typ: , value: , ptrNum: uint8()}
	}
	return , true
}

// appendStringifiedBool appends the bool at p in a JSON string, as the `string` option writes it with
// StringifyWithLegacySemantics.
func appendStringifiedBool( *RuntimeContext,  []byte,  unsafe.Pointer) ([]byte, error) {
	if *(*bool)() {
		return append(, `"true"`...), nil
	}
	return append(, `"false"`...), nil
}

// appendStringifiedString returns the function which appends the string at p, of typ, as a JSON string in a JSON
// string, as the `string` option writes it with StringifyWithLegacySemantics: the string is escaped by the options,
// and its invalid UTF-8 is the error of a value of typ, unless allowed; the JSON string is quoted where JSON needs
// it only.
func appendStringifiedString( reflect.Type) AppendFunc {
	return func( *RuntimeContext,  []byte,  unsafe.Pointer) ([]byte, error) {
		,  := jsonstring.AppendQuoted(textEscaper(), .MarshalBuf[:0], *(*string)())
		if ! {
			var  error
			if ,  = InvalidUTF8(, nil, );  != nil {
				return , &ierrors.SemanticError{GoType: , Err: }
			}
		}
		.MarshalBuf = [:0]
		,  := jsonstring.AppendQuoted(jsonstring.EscaperOf(uint(TextEscapeOption)), , *(*string)(unsafe.Pointer(&)))
		return , nil
	}
}

// appendStringTag returns the function which appends a value of typ, addressable or not, which a method or a function
// writes, or which an interface value of typ holds, in the compile mode of the `string` option, whose options a
// method or a function is given, as the value written after them is ( see stringTagCode ).
func appendStringTag( reflect.Type,  bool) AppendFunc {
	return func( *RuntimeContext,  []byte,  unsafe.Pointer) ([]byte, error) {
		 := .Option.Flag
		.Option.Flag |= StringTagOption
		,  := appendDefault(, , , , allMethods, )
		.Option.Flag = 
		return , 
	}
}

// appendWithoutStringTag returns the function which appends a value of typ, addressable or not, after the method
// after ( see appendDefault ), in the compile mode of the `string` option, which doesn't apply to it, without the
// option: the values in an object or an array are written as without it, as encoding/json writes them with
// ReportErrorsWithLegacySemantics.
func appendWithoutStringTag( reflect.Type,  int,  bool) AppendFunc {
	return func( *RuntimeContext,  []byte,  unsafe.Pointer) ([]byte, error) {
		 := .Option.Flag
		.Option.Flag &^= StringTagOption
		,  := appendDefault(, , , , , )
		.Option.Flag = 
		return , 
	}
}

// v2NeverEmpty reports whether a value of typ is known to be written as none of the empty values of omitempty:
// a boolean, a number, or an object with a member which is always written. The value of a type which a method or
// a function writes may be any.
func ( *Compiler) ( reflect.Type) bool {
	if .v2HasMethod() {
		// MarshalJSON of time.Time, or of a type which has it by embedding a time.Time, writes a time.
		return  != .v2DefaultType && len(.funcs.funcsOf()) == 0 &&
			v2MethodOf(, noMethod) == methodMarshalJSON && addrJSONAppender() != nil
	}
	switch  := .Kind(); {
	case  == reflect.Bool || isNumberKind(),  == jsonNumberType:
		// a json.Number is a number, 0 if it is "".
		return true
	case  == reflect.Struct && !.omitZeroStructFields:
		 := v2FieldsOf()
		if .Err != nil {
			return false
		}
		for ,  := range .List {
			// a member of an embedded struct is not written if a pointer to the struct is nil.
			if !.OmitEmpty && !.OmitZero && len(.Index) == 1 {
				return true
			}
		}
	}
	return false
}

// isNumberKind reports whether a value of the kind is a JSON number.
func isNumberKind( reflect.Kind) bool {
	switch  {
	case 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:
		return true
	}
	return false
}