package encoder

import (
	
	

	
)

// The frames of the VM.
//
// The value held by an interface value and the value of a recursive type are encoded by the opcodes of their
// own type, in a frame of slots after the frame of the opcodes which reached them. The opcode which ends
// such a frame has three slots: the opcode to return to with the tail levels to restore, the offset of the
// previous frame and the indent to restore.
//
// Entering and leaving a frame is done here, not in the VM: it needs several calls and many variables, and
// the VM, which is a large function, has to spill and restore its variables around each of them.

type nonEmptyInterface struct {
	itab *struct {
		ityp unsafe.Pointer // static interface type
		typ  unsafe.Pointer // dynamic concrete type
		// unused fields...
	}
	ptr unsafe.Pointer
}

func storeSlotPtr( unsafe.Pointer,  uint32,  unsafe.Pointer) {
	*(*uintptr)(unsafe.Add(, )) = uintptr()
}

func storeSlotInt( unsafe.Pointer,  uint32,  uintptr) {
	*(*uintptr)(unsafe.Add(, )) = 
}

func loadSlotPtr( unsafe.Pointer,  uint32) unsafe.Pointer {
	return *(*unsafe.Pointer)(unsafe.Add(, ))
}

func loadSlotInt( unsafe.Pointer,  uint32) uintptr {
	return *(*uintptr)(unsafe.Add(, ))
}

// recordSeen records the value to detect a cycle, after the nesting got deep: a cycle keeps passing the same
// values, so it is still detected, and the values which are not nested deeply cost nothing.
func ( *RuntimeContext) ( *Opcode,  unsafe.Pointer) error {
	 := SeenValue{p: , typ: .Type}
	if  != nil && .seen() {
		return ErrUnsupportedValue(, , )
	}
	.SeenPtr = append(.SeenPtr, )
	return nil
}

// seen reports whether id is recorded: by its address first, which the other records rarely have.
func ( *RuntimeContext) ( SeenValue) bool {
	for ,  := range .SeenPtr {
		if .p == .p &&  ==  {
			return true
		}
	}
	return false
}

// entersNilValue is whether the value of the type typ, held by an interface value whose data word is nil, is
// encoded by the opcodes of typ: a struct or an array stored directly, whose single pointer is nil, and for the
// v2 semantics a value of any type but a pointer, which writes a nil map as {} and fails for a nil func. The
// other values are null, as no type is.
func ( *RuntimeContext) ( unsafe.Pointer) bool {
	if  == nil {
		return false
	}
	if .Option.Flag&MarshalFuncsOption != 0 {
		// a function of marshaling may take a nil pointer: its type tells.
		return true
	}
	if .Option.Flag&V2Option != 0 {
		return runtime.TypeOfPtr().Kind() != reflect.Ptr
	}
	return ShapeOf() == ValueShapeAggregate && !IfaceIndir()
}

// recordSeenValue is recordSeen of the value at p, of the type of codeSet, which a frame of an interface value
// encodes: the value is recorded by its identity, as the interface value which holds it may be a copy, as the
// value of a map is.
func ( *RuntimeContext) ( *OpcodeSet,  unsafe.Pointer) error {
	 := seenValueOf(, )
	if .p != nil && .seen() {
		return errCycle(, .Type, )
	}
	.SeenPtr = append(.SeenPtr, )
	return nil
}

// seenValueOf returns the record of the value at p, of the type of codeSet, by its identity ( see recordSeenValue ).
func seenValueOf( *OpcodeSet,  unsafe.Pointer) SeenValue {
	 := SeenValue{p: , typ: runtime.TypePtr(.Type)}
	// a value is identified by its first word, which a cycle passes again and again, if it is a map, a slice (
	// the address of its array ), or a type stored directly in an interface value, as a pointer which a function
	// of marshaling takes. The identity of another value, as a pointer which is its address, is its address.
	if !.DataWordIsAddr || .Type.Kind() == reflect.Slice {
		.p = *(*unsafe.Pointer)()
		switch .Type.Kind() {
		case reflect.Slice:
			.n = (*runtime.SliceHeader)().Len
		case reflect.Struct:
			// a struct stored directly in the interface value, recorded by the pointer it holds, is not the struct
			// of its type which a recursive frame records at that address.
			.n = -1
		}
	}
	return 
}

// EnterNested makes c, which encodes the value at p by codeSet within the encoding by outer, the frame after the
// ones of outer for the detection of cycles: a default representation of a value, which runs in a context of its
// own ( see runInner ), or MarshalEncode called by a method, whose cycles pass no frame of the VM. Past
// StartDetectingCyclesAfter, c has the records of outer, in the same arrays, as outer goes on only after c ends, and
// records the value by codeSet, not by its type: a value which a function declined is encoded again by the opcodes
// of its default representation, at the same address.
func (,  *RuntimeContext,  *OpcodeSet,  unsafe.Pointer) error {
	.RecursiveLevel = .RecursiveLevel + 1
	if .RecursiveLevel <= StartDetectingCyclesAfter {
		return nil
	}
	return recordNested(, , , )
}

// recordNested is EnterNested past StartDetectingCyclesAfter, apart from it, so that the calls which are not nested
// deeply have EnterNested inlined. It is a function, not a method: a method of RuntimeContext changes its method
// table, which moved data the encodings read and made them slower.
func recordNested(,  *RuntimeContext,  *OpcodeSet,  unsafe.Pointer) error {
	.SeenPtr, .seenMaps = .SeenPtr, .seenMaps
	.nested, .sharedSeen, .nested = true, true, true
	 := seenValueOf(, )
	.typ = unsafe.Pointer()
	if .p != nil && .seen() {
		return errCycle(, .Type, )
	}
	.SeenPtr = append(.SeenPtr, )
	return nil
}

// enterFrame allocates the frame of the code after the current one, stores the value at its first slot and
// what the end opcode restores, and returns the base of the slots of the new frame.
func ( *RuntimeContext) (, ,  *Opcode,  unsafe.Pointer, ,  uintptr,  uint32) unsafe.Pointer {
	 := .SlotOffset
	.SlotOffset +=  * slotSize
	.ReserveSlots(/slotSize +  + )
	 := unsafe.Add(.Ptr(), .SlotOffset)
	storeSlotPtr(, .Idx, )
	storeSlotPtr(, .Idx, unsafe.Pointer())
	storeSlotInt(, .ElemIdx, )
	storeSlotInt(, .Length, uintptr(.BaseIndent))
	// the tail levels of the frame left are in the other half of the slot of the opcode to return to.
	storeSlotInt(, .Idx+slotIntOffset, uintptr(.TailLevels))
	.BaseIndent = 
	.TailLevels = 0
	.RecursiveLevel++
	return 
}

// EnterInterface enters the frame of the value held by the interface value at p, which is the operand of
// code. It returns the first opcode of the frame and the base of its slots, or a nil opcode if the value is
// nil, which the caller writes as null.
//
// If the value is a scalar, no frame is entered: it returns the opcode of the scalar, the address of the value
// and true, and the caller encodes the value by the opcode in its own frame. It saves the frame and two
// dispatches for the values which JSON has in a value of interface{}.
//
//go:noinline
func ( *RuntimeContext) ( *Opcode,  unsafe.Pointer) (*Opcode, unsafe.Pointer, bool, error) {
	var ,  unsafe.Pointer
	// a value of interface{} is told from the others by one check.
	switch {
	case .Flags&(NonEmptyInterfaceFlags|StaticTypeFlags) == 0:
		 := (*emptyInterface)()
		 = .ptr
		 = .typ
	case .Flags&StaticTypeFlags != 0:
		// a value of the type of the opcode, encoded as it would be held by an interface value, by the opcodes
		// of the type. p is what they take: the address of the value, or, for a pointer type compiled to the value
		// it points to, the pointer itself ( see InterfaceCode.static ).
		 = .Type
		 = 
	default:
		 := (*nonEmptyInterface)()
		 = .ptr
		if .itab != nil {
			 = .itab.typ
		}
	}
	if  == nil && !.entersNilValue() {
		return nil, nil, false, nil
	}
	 := .RecentCodeSet(uintptr())
	if  == nil {
		if .Option.Flag&UncachedOption == 0 {
			 = .SharedCodeSets().LoadFirst(uintptr())
		}
		if  != nil {
			.RememberCodeSet(uintptr(), )
		} else {
			var  error
			,  = CompileToGetCodeSet(, uintptr())
			if  != nil {
				return nil, nil, false, 
			}
		}
	}
	if .Scalar != nil {
		// a scalar is never stored directly in an interface value: the data word is its address.
		return .Scalar, , true, nil
	}
	// The opcodes take the address of the value. The data word of the interface value is the address for
	// most of the types, and the value itself for a type of a pointer shape which is not a pointer, such as a
	// map: then the address of the data word, in the interface value at p, is the address of the value.
	 := 
	if !.DataWordIsAddr && .Flags&StaticTypeFlags == 0 {
		 = unsafe.Add(, unsafe.Sizeof(uintptr(0)))
	}
	 := .BaseIndent + .Indent
	if +.Levels > MaxDepth {
		return nil, nil, false, ErrMaxDepth()
	}
	// after every path which doesn't go into the value, so that a record always has its end.
	if .RecursiveLevel > StartDetectingCyclesAfter {
		if  := .recordSeenValue(, );  != nil {
			return nil, nil, false, 
		}
	}
	 := .InterfaceKeyCodes[.Option.Flag&KeyEscapeOptions]
	 := .enterFrame(, .EndCode, .Next, ,
		uintptr(.Length)+interfaceEndSlots, uintptr(.CodeLength)+interfaceEndSlots, )
	return , , false, nil
}

// interfaceEndSlots is the number of the slots which a frame of an interface value has after the ones of
// the code.
const interfaceEndSlots = 3

// EnterRecursive enters the frame of the value of the recursive type at p, which is the operand of code.
// It returns the first opcode of the frame and the base of its slots.
//
//go:noinline
func ( *RuntimeContext) ( *Opcode,  unsafe.Pointer) (*Opcode, unsafe.Pointer, error) {
	if .Jmp.Code == nil {
		// an embedded struct which has no field to write there ( see Compiler.linkRecursiveCode ): no frame.
		return .Next, unsafe.Add(.Ptr(), .SlotOffset), nil
	}
	if .RecursiveLevel > StartDetectingCyclesAfter {
		if  := .recordSeen(, );  != nil {
			return nil, nil, 
		}
	}
	 := .Jmp.Code
	// the fields of the value are one level deeper than the place of the value, which opens it, and at the level
	// of the place of an embedded struct, which writes them to the object it is embedded in.
	 := .Indent - 1
	if .Jmp.Embedded {
		++
	}
	 := .BaseIndent + .Indent - 
	if +.Jmp.Levels > MaxDepth &&  != nil {
		// a nil pointer is null, which opens no level.
		return nil, nil, ErrMaxDepth()
	}
	 := .enterFrame(, .End.Next, .Next, , .Jmp.CurLen, .Jmp.NextLen, )
	return , , nil
}

// LeaveFrame leaves the frame which the end opcode ends, and returns the opcode to go on with and the base of
// the slots of the previous frame.
//
//go:noinline
func ( *RuntimeContext) ( *Opcode) (*Opcode, unsafe.Pointer) {
	 := unsafe.Add(.Ptr(), .SlotOffset)
	.RecursiveLevel--
	if .RecursiveLevel > StartDetectingCyclesAfter {
		.SeenPtr = .SeenPtr[:len(.SeenPtr)-1]
	}
	.BaseIndent = uint32(loadSlotInt(, .Length))
	.TailLevels = uint32(loadSlotInt(, .Idx+slotIntOffset))
	.SlotOffset = loadSlotInt(, .ElemIdx)
	return (*Opcode)(loadSlotPtr(, .Idx)), unsafe.Add(.Ptr(), .SlotOffset)
}

// The last field of a value of a recursive type may be a value of the same type: a list. Such a value is
// encoded in the frame of the value it is the field of ( TailRecursiveFlags ): the slots of that value are not
// needed any more, and the only thing left to do for it is to close its braces, which the end of the last
// value of the list does for every value of the list. No frame is entered and left for a value of the list, so
// the slots, the offsets and the opcode to return to are neither stored nor restored, and the end of a value
// is not dispatched: that makes a list as cheap as a nest of values of different types. The VM does it inline,
// as the functions here cost more than the inliner allows into it; the end opcode of the list has what the
// indent is deeper by for a value of it.

// RecordSeen records the value of a recursive type at p for the detection of cycles: the VM calls it before
// it begins a value of a list, when the level is deep enough for the detection.
func ( *RuntimeContext) ( *Opcode,  unsafe.Pointer) error {
	return .recordSeen(, )
}