gir/api.md

99 lines
2.8 KiB
Markdown

Compiling and inspecting programs
---------------------------------
### compile
`compile(program, enableExtensions = true)`
* `program`: String containing the program to compile
* `enableExtensions`: Whether to recognize `:;#` or ignore them
*Returns*: An array holding flat IR
*Example*: `let compiled = compile(',[>+<,]>:');`
### prettifyIR
`prettifyIR(ir)`
* `ir`: An array holding any type of IR used by Gir
*Returns*: A string suitable for creating IR listings
*Example*: `console.log(prettifyIR(compiled));`
Executing programs
------------------
Gir executes the flattened IR in a simple virtual machine. `runVM()` doesn't
mutate a state object that is passed to it but rather returns a new one.
### VM state object
property | default value | description
-----------|-----------------------|------------
`program` | (set by caller) | `compile()`d program
`ip` | `0` | Instruction pointer
`memory` | `Map {}` | Tape
`tapeHead` | `0` | Tape head position
`input` | (set by caller) | `encodeUTF8()`d input
`output` | `[]` | Output (needs to be `decodeUTF8()`d)
`onEof` | `0` / (set by caller) | What to do in case of EOF¹
¹ If `onEof` is null the cell will not be changed, but otherwise the cell
will be set to the value of `onEof`
### newVM
`newVM(program, input, onEof = 0)`
* `program`: An array holding flat IR
* `input`: An array of integers which is interpreted as a byte stream
* `onEof`: See description of `onEof` field of the VM state object
*Returns*: VM state object
*Example*: `let vm = newVM(compile('.[,[-].]'), encodeUTF('foobar'), null);`
### runVM
`runVM(vm, maxCycles = null)`
* `vm`: VM state object
* `maxCycles`: Number of cycles the program is allowed to run. `null` means
no limit
*Returns*: An object like following
property | description
------------------|------------
state | VM state object of the state after `runVM()` has completed
complete | Boolean describing whether the program completed or not
cycles | How many cycles did the program run during this invocation of `runVM()`
intParseFailed | Boolean describing if `runVM()` exited because `;` failed to parse an int
breakPointReached | Boolean describing if `runVM()` exited because it hit `#`
lastIndex | Last cell that was accessed by the VM
*Example*: `let output = decodeUTF8(runVM(vm, 400000).state.output);`
Helper functions
----------------
### encodeUTF8
`encodeUTF8(string)`
* *string*: A javascript string
*Returns*: An array of integers that interpreted as bytes encode that string
*Example*: `let encoded = encodeUTF8(input);`
### decodeUTF8
`decodeUTF8(encoded)`
* *encoded*: An array of integers
*Returns*: A string encoded by that array
*Example*: `let output = decodeUTF8(result.state.output);`