package encoder

import (
	
	stderrors 
	
	
	

	
	
)

// The methods of marshaling of the semantics of encoding/json/v2. The method of the pointer to a type is called for
// a value of the type, at its address, as a value is addressable for them, but for a value which is not addressable
// with CallMethodsWithLegacySemantics ( see v2MethodOfAt ). The first of them which a type has writes its value:
// MarshalJSONTo, MarshalJSON, AppendText, MarshalText.

// V2Hooks are what the v2 json package gives the encoder: the functions which take jsontext, which the encoder
// doesn't import.
var V2Hooks struct {
	// MarshalerToType is the interface of MarshalJSONTo.
	MarshalerToType reflect.Type
	// FormatRaw appends the raw value which a method or a function returned, checked and formatted as the options
	// of the context want it, which AppendFormattedRaw doesn't append ( see AppendRaw ): a SyntacticError of
	// jsontext for a value which is not valid, at its place in the output.
	FormatRaw func(ctx *RuntimeContext, b, raw []byte) ([]byte, error)
	// AppendRawMembers appends the members of the JSON object raw, a jsontext.Value embedded as a fallback, after
	// b, each followed by a comma: insertName records a name, and reports whether it may be written, if it is not
	// nil. Its errors are the ones of the v2 json package, at their places in the output.
	AppendRawMembers func(ctx *RuntimeContext, b, raw []byte, insertName func(name []byte) bool) ([]byte, error)
	// MarshalTo calls MarshalJSONTo of recv, the pointer to a value of typ, with an encoder which writes after the
	// output b.
	MarshalTo func(ctx *RuntimeContext, b []byte, typ reflect.Type, recv any) ([]byte, error)
	// MarshalToOf returns the function which calls MarshalJSONTo of the value of typ at an address, as MarshalTo
	// does, with the method found once for the type, or appendDefault if it declines ( see ErrUseDefault ).
	MarshalToOf func(typ reflect.Type, appendDefault AppendFunc) AppendFunc
}

// ErrUseDefault is the error of a method or a function of marshaling which declined to write the value: the
// value is written as if it didn't have it.
var ErrUseDefault = stderrors.New("use the default representation")

// implementsAddr reports whether a value of the type t, which is addressable, has the methods of iface.
func implementsAddr(,  reflect.Type) bool {
	return .Implements() || reflect.PointerTo().Implements()
}

// allMethods is the method after which appendDefault appends a value: none, its functions included.
const allMethods = -1

// The methods of marshaling, in the order of their precedence.
const (
	noMethod = iota
	methodMarshalJSONTo
	methodMarshalJSON
	methodAppendText
	methodMarshalText
)

// v2MethodOf returns the method of marshaling which writes a value of the type, after the method after, or
// noMethod. A pointer or an interface value has none: the value it points to or holds has, which is addressable.
func v2MethodOf( reflect.Type,  int) int {
	if .Kind() == reflect.Pointer || .Kind() == reflect.Interface {
		return noMethod
	}
	switch {
	case  < methodMarshalJSONTo && V2Hooks.MarshalerToType != nil && implementsAddr(, V2Hooks.MarshalerToType):
		return methodMarshalJSONTo
	case  < methodMarshalJSON && implementsAddr(, marshalJSONType):
		return methodMarshalJSON
	case  < methodAppendText && implementsAddr(, appendTextType):
		return methodAppendText
	case  < methodMarshalText && implementsAddr(, marshalTextType):
		return methodMarshalText
	}
	return noMethod
}

// v2MethodOfAt is v2MethodOf of a value which is addressable or not: with CallMethodsWithLegacySemantics, a method of
// a pointer receiver is not called for a value which is not addressable, as encoding/json doesn't call it, and the
// method after it or the kind writes the value.
func ( *Compiler) ( reflect.Type,  int,  bool) int {
	return methodOfAt(, ,  || .v1Options&modeCallMethodsWithLegacySemantics == 0)
}

// methodOfAt is v2MethodOf of a value which is addressable or not: a method of a pointer receiver is passed over for
// a value which is not, for the method after it.
func methodOfAt( reflect.Type,  int,  bool) int {
	 := v2MethodOf(, )
	for ! &&  != noMethod && !.Implements(marshalerTypeOf()) {
		 = v2MethodOf(, )
	}
	return 
}

// marshalerTypeOf returns the interface type of the method of marshaling m.
func marshalerTypeOf( int) reflect.Type {
	switch  {
	case methodMarshalJSONTo:
		return V2Hooks.MarshalerToType
	case methodMarshalJSON:
		return marshalJSONType
	case methodAppendText:
		return appendTextType
	}
	return marshalTextType
}

// v2MethodOfInterface returns the first method of marshaling which the interface type typ has, or noMethod.
func v2MethodOfInterface( reflect.Type) int {
	for  := methodMarshalJSONTo;  <= methodMarshalText; ++ {
		if  := marshalerTypeOf();  != nil && .Implements() {
			return 
		}
	}
	return noMethod
}

// appendV1Interface returns the function which appends the value of the interface type typ at p, of the method
// of marshaling m, with CallMethodsWithLegacySemantics: a nil pointer which it holds is written by the method, called
// for the nil pointer, as encoding/json calls it, if the method is of the pointer; any other value as the one of an
// interface{}.
func appendV1Interface( reflect.Type,  int) AppendFunc {
	return func( *RuntimeContext,  []byte,  unsafe.Pointer) ([]byte, error) {
		 := reflect.NewAt(, ).Elem()
		if .IsNil() {
			return append(, "null"...), nil
		}
		 := .Elem()
		if .Kind() != reflect.Pointer || !.IsNil() || .Type().Elem().Implements(marshalerTypeOf()) {
			// a value, or a nil pointer whose method is of the value it points to, which can't be called for it:
			// written as any other
			 := .Interface()
			return appendValueOf(, , emptyInterfaceType, unsafe.Pointer(&))
		}
		 := .Interface()
		switch  {
		case methodMarshalJSONTo:
			return V2Hooks.MarshalTo(, , .Type(), )
		case methodMarshalJSON:
			,  := .(json.Marshaler).MarshalJSON()
			return appendV2Raw(, .Type(), , , )
		}
		return appendTextOf(, , .Type(), , )
	}
}

// v2HasMethod reports whether an addressable value of the type is written by a function or a method of marshaling:
// of the type of a default representation, after the ones which declined it ( see v2Code ).
func ( *Compiler) ( reflect.Type) bool {
	return .v2HasMethodAt(, true)
}

// v2HasMethodAt is v2HasMethod for a value which is addressable or not: with CallMethodsWithLegacySemantics, the
// methods of the pointer don't write a value which is not ( see v2MethodOfAt ).
func ( *Compiler) ( reflect.Type,  bool) bool {
	if  == .v2DefaultType {
		return .v2MethodOfAt(, .v2DefaultAfter, ) != noMethod
	}
	return len(.funcs.funcsOf()) > 0 || .v2MethodOfAt(, noMethod, ) != noMethod
}

// v2MethodCode returns the code of a value of typ, addressable or not, written by its method of marshaling after the
// method after, and true, if it has one.
func ( *Compiler) ( reflect.Type,  int,  bool) (Code, bool) {
	switch .v2MethodOfAt(, , ) {
	case methodMarshalJSONTo:
		return .appendFuncCode(, V2Hooks.MarshalToOf(, func( *RuntimeContext,  []byte,  unsafe.Pointer) ([]byte, error) {
			return appendDefault(, , , , methodMarshalJSONTo, )
		})), true
	case methodMarshalJSON:
		if  == rawMessageType {
			// the output of its method is the value itself, or null: the method, which allocates null, is not
			// called.
			return .appendFuncCode(, func( *RuntimeContext,  []byte,  unsafe.Pointer) ([]byte, error) {
				 := *(*[]byte)()
				if  == nil {
					 = nullJSON
				}
				,  := AppendRaw(, , )
				if  != nil {
					return , &errors.MethodError{GoType: , Err: , Kind: errors.MethodMarshalJSON}
				}
				return , nil
			}), true
		}
		 := addrJSONAppender()
		// the method is called by its code, as the encoder of v1 calls it ( see MarshalerCall ).
		 := addrMethod[func(unsafe.Pointer) ([]byte, error)](, marshalJSONInterface)
		 := .appendFuncCode(, func( *RuntimeContext,  []byte,  unsafe.Pointer) ([]byte, error) {
			if  != nil {
				// the output is known, and valid: the method is called only for its error.
				if ,  := (, );  {
					return , nil
				}
			}
			,  := ()
			return appendV2Raw(, , , , )
		})
		if  := newMarshalerCall(reflect.PointerTo(), marshalJSONInterface);  != nil {
			// called by appendValue without the function ( see MarshalerCall.v2Raw ).
			.nilIsNull, .trusted, .appendOutput, .v2Raw, .recv = false, false, , true, 
			.appendValue = .appendValue
			.call = 
		}
		return , true
	case methodAppendText:
		 := addrMethod[func(unsafe.Pointer, []byte) ([]byte, error)](, appendTextInterface)
		return .appendFuncCode(, func( *RuntimeContext,  []byte,  unsafe.Pointer) ([]byte, error) {
			return appendMethodText(, , , errors.MethodAppendText, , )
		}), true
	case methodMarshalText:
		 := addrMethod[func(unsafe.Pointer) ([]byte, error)](, marshalTextInterface)
		return .appendFuncCode(, func( *RuntimeContext,  []byte,  unsafe.Pointer) ([]byte, error) {
			return appendMethodText(, , , errors.MethodMarshalText, , func( unsafe.Pointer,  []byte) ([]byte, error) {
				,  := ()
				return append(, ...), 
			})
		}), true
	}
	return nil, false
}

var (
	// rawMessageType is the type of json.RawMessage, which is jsontext.Value of the standard library where Go has
	// it.
	rawMessageType = reflect.TypeOf(json.RawMessage(nil))
	nullJSON       = []byte("null")
)

// appendV2Raw appends raw, which MarshalJSON of a value of typ returned with err, as a raw value of the v2
// semantics ( see AppendRaw ), or returns the error of the method.
func appendV2Raw( *RuntimeContext,  reflect.Type, ,  []byte,  error) ([]byte, error) {
	if  == nil && .Option.Flag&(RawRewriteOption|NormalizeUTF8Option|HTMLEscapeOption) == 0 && len() > 0 &&
		!notPureRaw.Has() && walkRaw[plainStrings](nil, , .levelsOfRaw()) {
		// a value of ASCII without a control character and an escape, as most are, for the options which append
		// it as it is ( see AppendFormattedRaw ), without the calls of AppendRaw.
		return append(, ...), nil
	}
	if  != nil {
		return , &errors.MethodError{GoType: , Err: unsupportedError(, errors.MethodMarshalJSON), Kind: errors.MethodMarshalJSON}
	}
	,  := AppendRaw(, , )
	if  != nil {
		return , &errors.MethodError{GoType: , Err: , Kind: errors.MethodMarshalJSON}
	}
	return , nil
}

// AppendRaw appends the raw value which a method or a function returned, checked and formatted as the options of
// the context want it: as it is, or as AppendFormattedRaw writes it, without a call of the v2 json package, which
// formats the other values.
func ( *RuntimeContext, ,  []byte) ([]byte, error) {
	if .Option.Flag&RawRewriteOption == 0 {
		if ,  := AppendFormattedRaw(, , );  {
			return , nil
		}
	}
	return V2Hooks.FormatRaw(, , )
}

// addrMethod returns the method of iface of a value of typ at an address, which the value or the pointer to it
// has, as a function of the address, which is the data word of the pointer: it is looked up when the type is
// compiled, as the encoder of v1 does ( see methodCode ), and not converted to an interface value by every call.
// The pointer to typ implements iface ( see v2MethodOf ), so the method is found by its name.
func addrMethod[ any]( reflect.Type,  *marshalerInterface)  {
	,  := methodCode(reflect.PointerTo(), )
	 := & // a func value is a pointer to its code
	return *(*)(unsafe.Pointer(&))
}

// addrJSONAppender returns the function which writes the output of MarshalJSON of the value of typ at an address
// without calling it, as the encoder of v1 does ( see newMarshalerCall ): for a type of the standard library whose
// output is known, or a type which has the method from such a type embedded in its value. It returns nil for the
// other types.
func addrJSONAppender( reflect.Type) func([]byte, unsafe.Pointer) ([]byte, bool) {
	if runtime.IsStdMarshalerType() {
		return stdJSONAppender()
	}
	if , , ,  := runtime.PromotedStdMethod(, runtime.MarshalJSONMethod);  &&  {
		return embeddedAppender(stdJSONAppender(), )
	}
	return nil
}

// RunHook runs the VM of the options of ctx for the opcodes of a value, which ctx is set up for, after the output
// b: the run package sets it, which the encoder can't import.
var RunHook func(ctx *RuntimeContext, b []byte, codeSet *OpcodeSet) ([]byte, error)

// defaultKey is the key of the opcodes of the default representation of a type, in a compile mode, after the
// functions and a method, of a value which is addressable or not ( see appendDefault ).
type defaultKey struct {
	typ         reflect.Type
	mode        compileMode
	addressable bool
	after       int
}

// defaultCodeSets are the opcodes of the default representations ( see appendDefault ) without functions of
// marshaling: the ones with functions are kept by the functions.
var defaultCodeSets sync.Map // map[defaultKey]*OpcodeSet

// appendDefault appends the value at p, of typ, by its representation after the functions of marshaling and the
// method after, which declined to write it: the next method of it, or the representation of its type. The value
// is written by the opcodes of the representation, in a context of their own, after the output b: the VM runs
// once more within the method which called this. The value is addressable or not, as the one which the method was
// called for: with CallMethodsWithLegacySemantics, which calls the methods of pointers for addressable values only,
// the opcodes of an addressable value are the ones of the value of a pointer. Without it, all the values are written
// alike, by the opcodes of a value given by itself.
func appendDefault( *RuntimeContext,  []byte,  reflect.Type,  unsafe.Pointer,  int,  bool) ([]byte, error) {
	 := .compileMode()
	 := defaultKey{typ: , mode: , after: , addressable:  && &modeCallMethodsWithLegacySemantics != 0}
	var  *MarshalFuncs
	 := &defaultCodeSets
	if .Option.Flag&MarshalFuncsOption != 0 {
		 = .Option.Funcs
		 = &.defaults
	}
	,  := .Load()
	if ! {
		 := newCompiler(.mode)
		.funcs = 
		if  != allMethods {
			.v2DefaultType, .v2DefaultAfter = , 
		}
		 := .valueCode
		if .addressable {
			 = .pointeeCode
		}
		,  := ()
		if  != nil {
			return , 
		}
		,  := .codeToOpcodeSet(, )
		if  != nil {
			return , 
		}
		, _ = .LoadOrStore(, )
	}
	 := .(*OpcodeSet)
	return runInner(, , , )
}

// appendAddressable returns the function which appends the addressable value of typ at p by its representation, as
// appendDefault compiles it, with its functions and its methods ( see recursiveValueCode ).
func appendAddressable( reflect.Type) AppendFunc {
	return func( *RuntimeContext,  []byte,  unsafe.Pointer) ([]byte, error) {
		return appendDefault(, , , , allMethods, true)
	}
}

// runInner runs the opcodes of the value at p in a context of its own, after the output b, and returns the output
// without the comma after the value, which the caller writes. An error is at its place in that output.
func runInner( *RuntimeContext,  []byte,  *OpcodeSet,  unsafe.Pointer) ([]byte, error) {
	if .ValueDepth+.Levels > MaxDepth {
		// the depth of the value, which the frames of the VM check when they enter it ( see EnterInterface ), but
		// which a context of its own starts at.
		return , &errors.OutputError{Out: , Err: ErrMaxDepth()}
	}
	 := TakeRuntimeContext()
	*.Option = *.Option
	// the recent opcodes of inner, which are the ones of the options of encoding/json of ctx
	SetFlags(, .Option.Flag)
	// the escaper of the options of ctx is the one of ctx, which records invalid UTF-8 for it: inner sets its own.
	.Option.EscaperFlags = noEscaperFlags
	.Init(, .CodeLength)
	// the value is where the function or the method which called this was called: one which declined it, or the one
	// of an inline fallback map, whose values these are ( see appendValueOf ).
	.BaseIndent = .ValueDepth
	.Prefix, .IndentStr = .Prefix, .IndentStr
	.RescanNames = false
	.RewriteFrom = .RewriteFrom
	,  := , EnterNested(, , , )
	if  == nil {
		,  = RunHook(, , )
	}
	if ,  := .InvalidUTF8Output();  {
		// the first error, before which the encoding went on.
		,  = , &errors.TextError{Err: errors.ErrInvalidUTF8}
	}
	.RescanNames = .RescanNames || .RescanNames
	.RewriteFrom = .RewriteFrom
	.Option.V2, .Option.Funcs = nil, nil
	ReleaseRuntimeContext()
	if  != nil {
		if ,  := .(*errors.OutputError); ! {
			 = &errors.OutputError{Out: , Err: }
		}
		return , 
	}
	// without the comma after the value, which the caller writes, and the newline after it in an indented output
	// ( see AppendCommaIndent )
	 := len() - 1
	if .Option.Flag&IndentOption != 0 {
		--
	}
	.Rewrote()
	return [:], nil
}

// appendMethodText appends the text which appendText, the method kind, appends for the value at p, as a JSON string.
func appendMethodText( *RuntimeContext,  []byte,  reflect.Type,  errors.MethodKind,  unsafe.Pointer,  func(unsafe.Pointer, []byte) ([]byte, error)) ([]byte, error) {
	 := len()
	,  := (, .MarshalBuf[:0])
	if  != nil {
		return , &errors.MethodError{GoType: , Err: unsupportedError(, ), Kind: }
	}
	.MarshalBuf = [:0]
	,  := appendName(, , *(*string)(unsafe.Pointer(&)))
	if  != nil {
		// invalid UTF-8, of the string at the place of the value.
		return [:], &errors.MethodError{GoType: , Err: , Kind: }
	}
	return , nil
}

// unsupportedError returns the error of the method kind, which must not report errors.ErrUnsupported: only
// MarshalJSONTo and the functions of MarshalToFunc may.
func unsupportedError( error,  errors.MethodKind) error {
	if stderrors.Is(, stderrors.ErrUnsupported) {
		return stderrors.New(.String() + " method may not return errors.ErrUnsupported")
	}
	return 
}