---
source: framec/tests/swift_snapshots.rs
expression: "compile_fixture(\"12_no_persist\", \"swift\")"
---
import Foundation

class NoPersistFrameEvent {
    var _message: String
    var _parameters: [Any]

    init(message: String, parameters: [Any] = []) {
        self._message = message
        self._parameters = parameters
    }
}

class NoPersistFrameContext {
    var _event: NoPersistFrameEvent
    var _return: Any?
    var _data: [String: Any] = [:]
    var _transitioned: Bool = false

    init(event: NoPersistFrameEvent, defaultReturn: Any? = nil) {
        self._event = event
        self._return = defaultReturn
    }
}

class NoPersistCompartment {
    var state: String
    var state_args: [Any] = []
    var state_vars: [String: Any] = [:]
    var enter_args: [Any] = []
    var exit_args: [Any] = []
    var forward_event: NoPersistFrameEvent?
    var parent_compartment: NoPersistCompartment?

    init(state: String) {
        self.state = state
    }

    func copy() -> NoPersistCompartment {
        let c = NoPersistCompartment(state: self.state)
        c.state_args = self.state_args
        c.state_vars = self.state_vars
        c.enter_args = self.enter_args
        c.exit_args = self.exit_args
        c.forward_event = self.forward_event
        c.parent_compartment = self.parent_compartment
        return c
    }
}

public class NoPersist {
    private var _state_stack: [NoPersistCompartment] = []
    private var __compartment: NoPersistCompartment
    private var __next_compartment: NoPersistCompartment? = nil
    private var _context_stack: [NoPersistFrameContext] = []
    public var count: Int = 0
    public var cache: Int = -1

    init() {
        _state_stack = []
        _context_stack = []
        self.__compartment = NoPersist.__prepareEnter("Active", [], [])
        self.__next_compartment = nil
    }

    func __frame_init() {
        let __e = NoPersistFrameEvent(message: "$>", parameters: __compartment.enter_args)
        let __ctx = NoPersistFrameContext(event: __e)
        _context_stack.append(__ctx)
        __kernel(__e)
        _context_stack.removeLast()
    }

    static func __create() -> NoPersist {
        let c = NoPersist()
        c.__frame_init()
        return c
    }

    private static func hsm_chain() -> [String: [String]] {
        return [
            "Active": ["Active"],
        ]
    }
    private static func __prepareEnter(_ leaf: String, _ state_args: [Any], _ enter_args: [Any]) -> NoPersistCompartment {
        var comp: NoPersistCompartment? = nil
        for name in NoPersist.hsm_chain()[leaf]! {
            let new_comp = NoPersistCompartment(state: name)
            new_comp.state_args = state_args
            new_comp.enter_args = enter_args
            new_comp.parent_compartment = comp
            comp = new_comp
        }
        return comp!
    }
    private func __prepareExit(_ exit_args: [Any]) {
        var comp: NoPersistCompartment? = __compartment
        while comp != nil {
            comp!.exit_args = exit_args
            comp = comp!.parent_compartment
        }
    }

    private func __kernel(_ __e: NoPersistFrameEvent) {
        // Route event to current state.
        __router(__e)
        // Drain any transitions queued by the handler.
        while __next_compartment != nil {
            let next_compartment: NoPersistCompartment = __next_compartment!
            __next_compartment = nil
            // Exit the current (leaf) state.
            let exit_event = NoPersistFrameEvent(message: "<$", parameters: __compartment.exit_args)
            __router(exit_event)
            // Switch to the new compartment.
            __compartment = next_compartment
            // Three-branch forward-event handling.
            let forward_event: NoPersistFrameEvent? = next_compartment.forward_event
            next_compartment.forward_event = nil
            if forward_event == nil {
                // No forwarded event — synthesize a fresh $>.
                let enter_event = NoPersistFrameEvent(message: "$>", parameters: __compartment.enter_args)
                __router(enter_event)
            } else if forward_event!._message == "$>" {
                // Forwarded event IS $> — dispatch directly so the
                // destination's $> handler receives the caller's payload.
                __router(forward_event!)
            } else {
                // Forwarded event is not $> — initialize the destination
                // with a fresh $>, then dispatch the forward.
                let enter_event = NoPersistFrameEvent(message: "$>", parameters: __compartment.enter_args)
                __router(enter_event)
                __router(forward_event!)
            }
            for ctx in _context_stack {
                ctx._transitioned = true
            }
        }
    }

    private func __router(_ __e: NoPersistFrameEvent) {
        if __compartment.state == "Active" {
            _state_Active(__e, __compartment)
        }
    }

    private func __transition(_ next: NoPersistCompartment) {
        __next_compartment = next
    }

    public func bump() {
        let __e = NoPersistFrameEvent(message: "bump", parameters: [])
        let __ctx = NoPersistFrameContext(event: __e)
        _context_stack.append(__ctx)
        __kernel(_context_stack[_context_stack.count - 1]._event)
        _context_stack.removeLast()
    }

    public func set_cache(_ v: Int) {
        let __e = NoPersistFrameEvent(message: "set_cache", parameters: [v])
        let __ctx = NoPersistFrameContext(event: __e)
        _context_stack.append(__ctx)
        __kernel(_context_stack[_context_stack.count - 1]._event)
        _context_stack.removeLast()
    }

    public func get_count() -> Int {
        let __e = NoPersistFrameEvent(message: "get_count", parameters: [])
        let __ctx = NoPersistFrameContext(event: __e, defaultReturn: 0)
        _context_stack.append(__ctx)
        __kernel(_context_stack[_context_stack.count - 1]._event)
        let __result = _context_stack[_context_stack.count - 1]._return as! Int
        _context_stack.removeLast()
        return __result
    }

    public func get_cache() -> Int {
        let __e = NoPersistFrameEvent(message: "get_cache", parameters: [])
        let __ctx = NoPersistFrameContext(event: __e, defaultReturn: 0)
        _context_stack.append(__ctx)
        __kernel(_context_stack[_context_stack.count - 1]._event)
        let __result = _context_stack[_context_stack.count - 1]._return as! Int
        _context_stack.removeLast()
        return __result
    }

    private func _state_Active(_ __e: NoPersistFrameEvent, _ compartment: NoPersistCompartment) {
        if __e._message == "bump" {
            self._s_Active_hdl_user_bump(__e, compartment)
            return
        }
        if __e._message == "get_cache" {
            self._s_Active_hdl_user_get_cache(__e, compartment)
            return
        }
        if __e._message == "get_count" {
            self._s_Active_hdl_user_get_count(__e, compartment)
            return
        }
        if __e._message == "set_cache" {
            self._s_Active_hdl_user_set_cache(__e, compartment)
            return
        }
    }

    private func _s_Active_hdl_user_bump(_ __e: NoPersistFrameEvent, _ compartment: NoPersistCompartment) {
        self.count = self.count + 1
    }

    private func _s_Active_hdl_user_get_cache(_ __e: NoPersistFrameEvent, _ compartment: NoPersistCompartment) {
        _context_stack[_context_stack.count - 1]._return = self.cache
    }

    private func _s_Active_hdl_user_get_count(_ __e: NoPersistFrameEvent, _ compartment: NoPersistCompartment) {
        _context_stack[_context_stack.count - 1]._return = self.count
    }

    private func _s_Active_hdl_user_set_cache(_ __e: NoPersistFrameEvent, _ compartment: NoPersistCompartment) {
        let v = __e._parameters[0] as! Int
        self.cache = v
    }

    private func __serComp(_ comp: NoPersistCompartment?) -> [String: Any]? {
        if comp == nil { return nil }
        var j: [String: Any] = [:]
        j["state"] = comp!.state
        var sv: [String: Any] = [:]
        for (k, v) in comp!.state_vars { sv[k] = v }
        j["state_vars"] = sv
        j["state_args"] = comp!.state_args
        j["enter_args"] = comp!.enter_args
        j["parent"] = __serComp(comp!.parent_compartment) as Any
        return j
    }

    private func __deserComp(_ dict: [String: Any]?) -> NoPersistCompartment? {
        guard let d = dict else { return nil }
        guard let state = d["state"] as? String else { return nil }
        let c = NoPersistCompartment(state: state)
        if let sv = d["state_vars"] as? [String: Any] {
            for (k, v) in sv { c.state_vars[k] = v }
        }
        if let sa = d["state_args"] as? [Any] {
            c.state_args = sa
        }
        if let ea = d["enter_args"] as? [Any] {
            c.enter_args = ea
        }
        if let parent = d["parent"] as? [String: Any] {
            c.parent_compartment = __deserComp(parent)
        }
        return c
    }

    public func snapshot() -> String {
        if !_context_stack.isEmpty { fatalError("E700: system not quiescent") }
        var j: [String: Any] = [:]
        j["_compartment"] = __serComp(__compartment) as Any
        var stack: [[String: Any]] = []
        for c in _state_stack { if let s = __serComp(c) { stack.append(s) } }
        j["_state_stack"] = stack
        j["count"] = count
        let data = try! JSONSerialization.data(withJSONObject: j)
        return String(data: data, encoding: .utf8)!
    }

    public func restore(_ json: String) {
        let data = json.data(using: .utf8)!
        let _parsed = try! JSONSerialization.jsonObject(with: data) as! [String: Any]
        self.__compartment = self.__deserComp(_parsed["_compartment"] as? [String: Any])!
        if let stack = _parsed["_state_stack"] as? [[String: Any]] {
            self._state_stack = []
            for sc in stack { if let c = self.__deserComp(sc) { self._state_stack.append(c) } }
        }
        if let __raw = _parsed["count"], let __data = try? JSONSerialization.data(withJSONObject: [__raw]), let __arr = try? JSONDecoder().decode([Int].self, from: __data), let __v = __arr.first { self.count = __v }
    }
}
