[{"name":"ZMachine","comment":" A pure Elm Z-Machine interpreter for interactive fiction.\nSupports version 3 story files fully and version 5 partially — see\nthe package README for the current v5 coverage.\n\nThis module is the main entry point for the library. All functions needed\nto load and run a `.z3` or `.z5` story file are here. For pattern\nmatching on result types, also import the constructors from\n[`ZMachine.Types`](ZMachine-Types):\n\n    import ZMachine exposing (load, runSteps, provideInput)\n    import ZMachine.Types exposing (StepResult(..), OutputEvent(..))\n\nEach [`StepResult`](ZMachine-Types#StepResult) variant carries the\noutput events accumulated during the call that produced it, so the\nhost never needs to inspect the machine's output buffer directly.\n\n\n# Types\n\n@docs ZMachine, StepResult, OutputEvent, LineInputInfo, ZMachineError, StatusLine, Window, Snapshot\n\n\n# Loading\n\n@docs load\n\n\n# Running\n\n@docs step, runSteps, provideInput, provideChar\n\n\n# Save and restore\n\nSee [`ZMachine.Snapshot`](ZMachine-Snapshot) for building custom save\nschemes. A standard portable Quetzal codec is planned but not yet\nshipped in this release.\n\n@docs snapshot, restoreSnapshot, provideSaveResult, provideRestoreResult\n\n\n# Story identity\n\n@docs storyRelease, storySerial, storyChecksum\n\n","unions":[],"aliases":[{"name":"LineInputInfo","comment":" Metadata about a line-input request. Carried by the `NeedInput`\nvariant of `StepResult`.\n","args":[],"type":"ZMachine.Types.LineInputInfo"},{"name":"OutputEvent","comment":" Structured output events for the host to render. See\n[`ZMachine.Types.OutputEvent`](ZMachine-Types#OutputEvent) for the full\nlist of constructors.\n","args":[],"type":"ZMachine.Types.OutputEvent"},{"name":"Snapshot","comment":" Opaque snapshot of machine state. See\n[`ZMachine.Snapshot`](ZMachine-Snapshot) for operations.\n","args":[],"type":"ZMachine.Types.Snapshot"},{"name":"StatusLine","comment":" Status line data including location name, score, and turns.\n","args":[],"type":"ZMachine.Types.StatusLine"},{"name":"StepResult","comment":" Result of executing one or more instructions. See\n[`ZMachine.Types.StepResult`](ZMachine-Types#StepResult) for the\nconstructors you will pattern match on.\n","args":[],"type":"ZMachine.Types.StepResult"},{"name":"Window","comment":" Screen window identifier (`Upper` or `Lower`).\n","args":[],"type":"ZMachine.Types.Window"},{"name":"ZMachine","comment":" The complete state of a running Z-Machine.\n","args":[],"type":"ZMachine.Types.ZMachine"},{"name":"ZMachineError","comment":" Errors that can halt the machine.\n","args":[],"type":"ZMachine.Types.ZMachineError"}],"values":[{"name":"load","comment":" Load a `.z3` story file from raw bytes and initialize the machine.\n\n    case ZMachine.load storyBytes of\n        Ok machine ->\n            -- ready to run\n            ...\n\n        Err err ->\n            -- invalid story file\n            ...\n\n","type":"Bytes.Bytes -> Result.Result String.String ZMachine.ZMachine"},{"name":"provideChar","comment":" Provide a character to a machine that returned `NeedChar`.\n\nPass a single-character string — only the first character is used.\nThe ZSCII code is stored as the result of the `read_char` opcode.\n\n    case ZMachine.runSteps 10000 machine of\n        NeedChar _ machineWithOutput ->\n            ZMachine.provideChar \"y\" machineWithOutput\n\n        _ ->\n            ...\n\n","type":"String.String -> ZMachine.ZMachine -> ZMachine.StepResult"},{"name":"provideInput","comment":" Provide a line of input to a machine that returned `NeedInput`.\n\nWrites the text into the story's text buffer, tokenizes it, and\nresumes execution. In V5, also stores the terminating character (13\nfor newline).\n\n    case ZMachine.runSteps 10000 machine of\n        NeedInput info _ machineWithOutput ->\n            ZMachine.provideInput \"open mailbox\" info machineWithOutput\n\n        _ ->\n            ...\n\n","type":"String.String -> ZMachine.LineInputInfo -> ZMachine.ZMachine -> ZMachine.StepResult"},{"name":"provideRestoreResult","comment":" Resume a machine that returned `NeedRestore`. Pass `Just snapshot`\nto rehydrate from the snapshot (the original `save` opcode's branch is\ntaken as true); pass `Nothing` to report failure (the `restore` opcode\nbranches false and execution continues normally). Mismatched-story\nsnapshots are treated as failures.\n","type":"Maybe.Maybe ZMachine.Snapshot -> ZMachine.ZMachine -> ZMachine.StepResult"},{"name":"provideSaveResult","comment":" Resume a machine that returned `NeedSave`. Pass `True` if the host\nsuccessfully persisted the snapshot, `False` otherwise. The `save`\nopcode's branch is evaluated against the result.\n\n    case ZMachine.runSteps 10000 machine of\n        NeedSave snap m ->\n            writeToFile (ZMachine.Snapshot.encode snap)\n                |> Task.map (\\_ -> ZMachine.provideSaveResult True m)\n\n","type":"Basics.Bool -> ZMachine.ZMachine -> ZMachine.StepResult"},{"name":"restoreSnapshot","comment":" Rehydrate a running machine from a snapshot. Used to load an\nautosave at startup (or any time the host wants to swap state outside\nof a `restore` opcode).\n\nFails with a [`RestoreError`](ZMachine-Snapshot#RestoreError) if the\nsnapshot is for a different story or its dynamic-memory image is\ncorrupt.\n\n","type":"ZMachine.Snapshot -> ZMachine.ZMachine -> Result.Result ZMachine.Snapshot.RestoreError ZMachine.ZMachine"},{"name":"runSteps","comment":" Execute up to `n` instructions, stopping early if input is needed,\nthe machine halts, or an error occurs.\n\n    case ZMachine.runSteps 10000 machine of\n        Continue nextMachine ->\n            -- budget exhausted, call runSteps again to keep going\n            ...\n\n        NeedInput request machineWithOutput ->\n            -- prompt the player for input\n            ...\n\n","type":"Basics.Int -> ZMachine.ZMachine -> ZMachine.StepResult"},{"name":"snapshot","comment":" Capture a snapshot of the current machine state. Safe to call any\ntime the host is holding a `ZMachine` between steps — useful for\nautosaves or quick-save UIs. The resulting snapshot is tagged\n`ResumeAt`, meaning on restore execution picks up at the next\ninstruction.\n\nTo persist a snapshot, serialize it with\n[`ZMachine.Snapshot.encode`](ZMachine-Snapshot#encode). The built-in\ncodec is a native format that round-trips cleanly but isn't\ncross-interpreter portable; a Quetzal codec for interop is planned.\n\n","type":"ZMachine.ZMachine -> ZMachine.Snapshot"},{"name":"step","comment":" Execute a single instruction. Returns a `StepResult` indicating\nwhether the machine can continue, needs input, halted, or hit an error.\n\n    case ZMachine.step machine of\n        Continue nextMachine ->\n            ...\n\n        NeedInput request machineWithOutput ->\n            ...\n\n","type":"ZMachine.ZMachine -> ZMachine.StepResult"},{"name":"storyChecksum","comment":" The story file's checksum (header word 0x1C). Sum of all bytes\nfrom 0x40 onward, mod 65536. Returns 0 for early V3 files that predate\nthe checksum field.\n","type":"ZMachine.ZMachine -> Basics.Int"},{"name":"storyRelease","comment":" The story file's release number (header word 0x02).\n\nCombined with [`storySerial`](#storySerial) and [`storyChecksum`](#storyChecksum)\nthis uniquely identifies the story file edition — useful for tagging\nsnapshots so a host can reject loading a save against the wrong story.\n\n","type":"ZMachine.ZMachine -> Basics.Int"},{"name":"storySerial","comment":" The story file's serial number — six ASCII bytes at header 0x12.\nInfocom convention is a `YYMMDD` build date.\n","type":"ZMachine.ZMachine -> String.String"}],"binops":[]},{"name":"ZMachine.Snapshot","comment":" Save/restore snapshots for the Z-Machine.\n\nA `Snapshot` captures the mutable state of a running Z-Machine so that\nit can be serialized to bytes and later fed back to restore execution.\nThere are two ways to produce one:\n\n1.  The host calls [`ZMachine.snapshot`](ZMachine#snapshot) at any point\n    between steps — produces an **autosave** snapshot tagged `ResumeAt`.\n2.  The interpreter produces one automatically when a running story\n    executes the `save` opcode — tagged `ResumeByBranchTrue`, meaning\n    that on restore the save instruction's branch-on-success is taken.\n\nFor simple round-tripping, serialize with [`encode`](#encode) and\nreload with [`decode`](#decode) — this built-in codec covers both\nresume kinds but is not cross-interpreter portable. A Quetzal codec\nfor interop with other interpreters is planned. Clients building\ncustom schemes (transcript + notes, etc.) can use the projection\nfunctions and reconstruct a `Snapshot` via [`fromParts`](#fromParts).\n\n@docs Snapshot, SnapshotMeta, ResumeKind, RestoreError\n\n\n# Capture and restore\n\n@docs capture, restore\n\n\n# Inspection\n\n@docs meta, resumeKind, pc, dynamicMemory, stack, callStack\n\n\n# Custom schemes\n\n@docs fromParts\n\n\n# Native binary format\n\n@docs encode, decode\n\n","unions":[{"name":"RestoreError","comment":" Errors returned by [`restore`](#restore).\n\n  - `WrongStory` — snapshot metadata does not match the currently-loaded\n    story. Compare `expected` (current story) against `found` (snapshot).\n  - `SnapshotCorrupt` — snapshot data failed an integrity check.\n\n","args":[],"cases":[["WrongStory",["{ expected : ZMachine.Snapshot.SnapshotMeta, found : ZMachine.Snapshot.SnapshotMeta }"]],["SnapshotCorrupt",["String.String"]]]},{"name":"ResumeKind","comment":" How the interpreter should resume after restoring this snapshot.\n\n  - `ResumeAt` — host-initiated snapshot (autosave). Execution continues\n    from `pc` as if nothing happened.\n  - `ResumeByBranchTrue` — produced by the V3 `save` opcode. Execution\n    re-runs the save instruction at `pc` with a success result,\n    following its branch-on-true target.\n  - `ResumeByStoreResult` — produced by the V5 `ext_save` opcode.\n    Execution re-runs the save instruction at `pc`, storing a\n    non-zero result to indicate success.\n\n","args":[],"cases":[["ResumeAt",[]],["ResumeByBranchTrue",[]],["ResumeByStoreResult",[]]]},{"name":"Snapshot","comment":" Opaque snapshot of Z-Machine state.\n","args":[],"cases":[]}],"aliases":[{"name":"SnapshotMeta","comment":" Story-identifying metadata stored inside a snapshot. Used to reject\nsnapshots that belong to a different story or a different release.\n","args":[],"type":"{ release : Basics.Int, serial : String.String, checksum : Basics.Int }"}],"values":[{"name":"callStack","comment":" The active call frames at capture time, outermost-first.\n","type":"ZMachine.Snapshot.Snapshot -> List.List ZMachine.Stack.CallFrame"},{"name":"capture","comment":" Build a snapshot from the live pieces of a running Z-Machine.\nMetadata is read from the supplied memory image's header.\n","type":"{ memory : ZMachine.Memory.Memory, pc : Basics.Int, stack : List.List Basics.Int, callStack : List.List ZMachine.Stack.CallFrame, resumeKind : ZMachine.Snapshot.ResumeKind } -> ZMachine.Snapshot.Snapshot"},{"name":"decode","comment":" Decode a snapshot from bytes produced by [`encode`](#encode).\n\nThe `Memory` argument is the **original** story memory — it is needed\nto decompress the dynamic memory diff stored in the snapshot.\n\nReturns `Err` with a reason string on any format error.\n\n","type":"ZMachine.Memory.Memory -> Bytes.Bytes -> Result.Result String.String ZMachine.Snapshot.Snapshot"},{"name":"dynamicMemory","comment":" Raw dynamic memory bytes captured in the snapshot. Length equals the\ndynamic memory size of the story (i.e. the header's static base).\n","type":"ZMachine.Snapshot.Snapshot -> Array.Array Basics.Int"},{"name":"encode","comment":" Encode a snapshot as bytes using the interpreter's native format.\n\nThe `Memory` argument is the **original** story memory — it is used to\nproduce a compressed diff (XOR + run-length encoding) of dynamic memory\nrather than storing the full image. This typically reduces the dynamic\nmemory payload from ~16 KB to a few hundred bytes.\n\nUseful for storing autosaves in `localStorage`, a file, etc. The output\nis not portable between different Z-Machine interpreters; a Quetzal\ncodec for interop is planned.\n\n","type":"ZMachine.Memory.Memory -> ZMachine.Snapshot.Snapshot -> Bytes.Bytes"},{"name":"fromParts","comment":" Build a `Snapshot` directly from its constituent parts. Useful for\nclients implementing custom save formats: after decoding your format,\ncall this to produce a `Snapshot` that can be fed to\n[`restore`](#restore).\n","type":"{ dynamicMemory : Array.Array Basics.Int, pc : Basics.Int, stack : List.List Basics.Int, callStack : List.List ZMachine.Stack.CallFrame, resumeKind : ZMachine.Snapshot.ResumeKind, meta : ZMachine.Snapshot.SnapshotMeta } -> ZMachine.Snapshot.Snapshot"},{"name":"meta","comment":" Story metadata recorded in the snapshot.\n","type":"ZMachine.Snapshot.Snapshot -> ZMachine.Snapshot.SnapshotMeta"},{"name":"pc","comment":" The program counter stored in the snapshot. For a `ResumeAt`\nsnapshot this is the next instruction to execute; for\n`ResumeByBranchTrue` it points at the save opcode whose branch will be\nre-evaluated as true.\n","type":"ZMachine.Snapshot.Snapshot -> Basics.Int"},{"name":"restore","comment":" Validate a snapshot against the currently-loaded story's memory and\nproduce the pieces needed to rehydrate a running machine.\n\nThe supplied `Memory` must be the **original** image of the currently\nloaded story (i.e. `ZMachine.originalMemory`), so that metadata can be\ncompared and the static/high memory region can be reused when rebuilding\nthe dynamic memory image.\n\n","type":"ZMachine.Snapshot.Snapshot -> ZMachine.Memory.Memory -> Result.Result ZMachine.Snapshot.RestoreError { memory : ZMachine.Memory.Memory, pc : Basics.Int, stack : List.List Basics.Int, callStack : List.List ZMachine.Stack.CallFrame }"},{"name":"resumeKind","comment":" Which resume policy this snapshot was tagged with.\n","type":"ZMachine.Snapshot.Snapshot -> ZMachine.Snapshot.ResumeKind"},{"name":"stack","comment":" The interpreter's current evaluation stack at capture time.\n","type":"ZMachine.Snapshot.Snapshot -> List.List Basics.Int"}],"binops":[]},{"name":"ZMachine.Types","comment":" Types for the Z-Machine interpreter.\n\nImport this module to pattern match on result types:\n\n    import ZMachine.Types exposing (StepResult(..), OutputEvent(..))\n\n\n# Machine State\n\n@docs ZMachine, Memory, CallFrame, Snapshot\n\n\n# Step Results\n\n@docs StepResult, ZMachineError, LineInputInfo\n\n\n# Output\n\n@docs OutputEvent, StatusLine, StatusLineMode, Window, UpperWindow\n\n","unions":[{"name":"OutputEvent","comment":" Structured output events for the host to render.\n\n  - `PrintText` — display a string. Line breaks are embedded as `\\n`\n    in the string; consecutive prints are coalesced into a single\n    event, so a rendered paragraph typically arrives as one\n    `PrintText`.\n  - `PrintObject` — display a string that the game identified as an\n    object's short name (via `print_obj` or `print_addr`). Rendered\n    identically to `PrintText`; split out so clients can learn the\n    names of the objects the game refers to.\n  - `ShowStatusLine` — update the status bar with a [`StatusLine`](#StatusLine).\n  - `SetBufferMode` — enable or disable word-wrap buffering.\n  - `SetTextStyle` — change text style (bold, italic, etc.).\n  - `SetColour` — change foreground/background colours.\n  - `PlaySound` — play a sound effect by number.\n\n","args":[],"cases":[["PrintText",["String.String"]],["PrintObject",["String.String"]],["ShowStatusLine",["ZMachine.Types.StatusLine"]],["SetBufferMode",["Basics.Bool"]],["SetTextStyle",["Basics.Int"]],["SetColour",["Basics.Int","Basics.Int"]],["PlaySound",["Basics.Int"]]]},{"name":"StatusLineMode","comment":" How the status line content is provided.\n\n  - `ScoreAndTurns score turns` — V3 score game.\n  - `TimeOfDay hours minutes` — V3 time game (hours 0–23, minutes 0–59).\n  - `ScreenRows rows` — V5+ game that draws its own status area.\n    Each string is one rendered row of the upper window, trimmed.\n\n","args":[],"cases":[["ScoreAndTurns",["Basics.Int","Basics.Int"]],["TimeOfDay",["Basics.Int","Basics.Int"]],["ScreenRows",["List.List String.String"]]]},{"name":"StepResult","comment":" Result of executing one or more instructions.\n\nEvery variant carries a `List OutputEvent` containing the output\naccumulated during the call that produced this result, followed by the\ncurrent `ZMachine`. The returned machine's output buffer is always\nempty — the run-loop drains it into the variant, so callers never need\nto manage output state themselves.\n\n  - `Continue` — step budget exhausted, call\n    [`ZMachine.runSteps`](ZMachine#runSteps) again to keep going.\n  - `NeedInput` — the machine is waiting for a line of player input.\n    Call [`ZMachine.provideInput`](ZMachine#provideInput) to resume.\n  - `NeedChar` — the machine is waiting for a single keypress.\n    Call [`ZMachine.provideChar`](ZMachine#provideChar) to resume.\n  - `NeedSave` — the story executed a `save` opcode. The attached\n    snapshot captures the state to be persisted; call\n    [`ZMachine.provideSaveResult`](ZMachine#provideSaveResult) to resume.\n  - `NeedRestore` — the story executed a `restore` opcode. Call\n    [`ZMachine.provideRestoreResult`](ZMachine#provideRestoreResult)\n    with a snapshot (or `Nothing` on failure) to resume.\n  - `Halted` — the story called `quit`.\n  - `Error` — an unrecoverable error occurred.\n\n","args":[],"cases":[["Continue",["List.List ZMachine.Types.OutputEvent","ZMachine.Types.ZMachine"]],["NeedInput",["ZMachine.Types.LineInputInfo","List.List ZMachine.Types.OutputEvent","ZMachine.Types.ZMachine"]],["NeedChar",["List.List ZMachine.Types.OutputEvent","ZMachine.Types.ZMachine"]],["NeedSave",["ZMachine.Types.Snapshot","List.List ZMachine.Types.OutputEvent","ZMachine.Types.ZMachine"]],["NeedRestore",["List.List ZMachine.Types.OutputEvent","ZMachine.Types.ZMachine"]],["Halted",["List.List ZMachine.Types.OutputEvent","ZMachine.Types.ZMachine"]],["Error",["ZMachine.Types.ZMachineError","List.List ZMachine.Types.OutputEvent","ZMachine.Types.ZMachine"]]]},{"name":"Window","comment":" Screen window identifier. Z-Machine v3 has two windows:\n\n  - `Upper` — the fixed-size status area at the top.\n  - `Lower` — the scrolling main text area.\n\n","args":[],"cases":[["Upper",[]],["Lower",[]]]},{"name":"ZMachineError","comment":" Errors that can halt the machine.\n\n  - `DivisionByZero` — a `div` or `mod` instruction divided by zero.\n  - `StackUnderflow` — a pop from an empty evaluation stack.\n  - `InvalidOpcode` — an unrecognised opcode number.\n  - `InvalidVariable` — a variable reference outside 0–255.\n\n","args":[],"cases":[["DivisionByZero",[]],["StackUnderflow",[]],["InvalidOpcode",["Basics.Int"]],["InvalidVariable",["Basics.Int"]]]}],"aliases":[{"name":"CallFrame","comment":" A single call stack frame, re-exported so consumers can annotate\n[`ZMachine`](#ZMachine) fields without a second import.\n","args":[],"type":"ZMachine.Stack.CallFrame"},{"name":"LineInputInfo","comment":" Metadata about a line-input request from `sread`/`aread`.\nCarried by the `NeedInput` variant of `StepResult`.\n","args":[],"type":"{ maxLength : Basics.Int, textBufferAddr : Basics.Int, parseBufferAddr : Basics.Int }"},{"name":"Memory","comment":" Opaque Z-Machine memory image, re-exported so consumers can annotate\n[`ZMachine`](#ZMachine) fields without a second import.\n","args":[],"type":"ZMachine.Memory.Memory"},{"name":"Snapshot","comment":" Opaque snapshot of Z-Machine state, produced by the save path and\nconsumed by the restore path. See [`ZMachine.Snapshot`](ZMachine-Snapshot)\nfor operations.\n","args":[],"type":"ZMachine.Snapshot.Snapshot"},{"name":"StatusLine","comment":" Status line data shown at the top of the screen.\n\n  - `locationId` — the object number of the current location.\n  - `locationName` — the short name of the current location.\n  - `mode` — score/turns, time, or raw screen rows depending on version.\n\n","args":[],"type":"{ locationId : Basics.Int, locationName : String.String, mode : ZMachine.Types.StatusLineMode }"},{"name":"UpperWindow","comment":" Virtual upper window state. V5 games draw the status line by\nwriting directly to the upper window with cursor positioning. The\ninterpreter tracks this internally and emits a `ShowStatusLine` event\nwhen the game switches back to the lower window.\n","args":[],"type":"{ height : Basics.Int, rows : Dict.Dict Basics.Int (Array.Array Char.Char), cursorRow : Basics.Int, cursorCol : Basics.Int, width : Basics.Int, firstPrintedObj : Basics.Int }"},{"name":"ZMachine","comment":" The complete state of a running Z-Machine. You will receive this\ninside each [`StepResult`](#StepResult) variant.\n","args":[],"type":"{ memory : ZMachine.Types.Memory, originalMemory : ZMachine.Types.Memory, pc : Basics.Int, stack : List.List Basics.Int, callStack : List.List ZMachine.Types.CallFrame, output : List.List ZMachine.Types.OutputEvent, outputStreams : { stream1 : Basics.Bool, stream2 : Basics.Bool }, stream3Stack : List.List { tableAddr : Basics.Int, count : Basics.Int }, randomState : { seed : Basics.Int, count : Basics.Int }, currentWindow : ZMachine.Types.Window, upperWindow : ZMachine.Types.UpperWindow, playerTracking : ZMachine.Types.PlayerTracking }"}],"values":[],"binops":[]}]