Support all the types of EOF

This commit is contained in:
Juhani Krekelä 2018-05-27 12:56:02 +03:00
parent 1b262941ca
commit d74b6ab594
3 changed files with 32 additions and 14 deletions

View File

@ -20,9 +20,6 @@ Gir supports following optimizations:
TODO
----
### gir.js
* Support for other types of EOF?
### gir.html
* Implement a UI

View File

@ -11,10 +11,13 @@ cells that wrap around
IO
--
`.` and `,` operate on a utf-8 stream. `,` produces `0` on EOF
`.` and `,` operate on a utf-8 stream. `,` produces `0` by default on EOF.
This can be changed by passing a third parameter to newVM, where 0/-1 sets
the cell to that and null keeps it unchanged
`:` produces a decimal representation of the current cell. `;` skips any
space (U+20) characters in the input stream and then reads 1 or more ASCII
digit (U+30 to U+39), clamps the number to the range [0, 255] and sets the
cell to it. If it can't read a digit and EOF has been reached it returns 0,
but if EOF hasn't been reached it raises an error flag and stops execution
cell to it. If it can't read a digit and EOF has been reached it produces an
EOF similarily to `,` (by default sets to 0, but can be changed), but if EOF
hasn't been reached it raises an error flag and stops execution

34
gir.js
View File

@ -573,8 +573,10 @@ function optimize(parsed) {
// Virtual machine
// ------------------------------------------------------------------
// ([flatCommandObject], [int]) → girVMState
function newVM(program, input) {
// ([flatCommandObject], [int], int/null) → girVMState
// onEof tells what to set the cell to in case of EOF, or if it null to keep
// the same value
function newVM(program, input, onEof = 0) {
return {
// Initial state for the machine
program: program,
@ -584,7 +586,10 @@ function newVM(program, input) {
tapeHead: 0,
input: input,
output: []
output: [],
// Configuration
onEof: onEof
};
}
@ -684,8 +689,15 @@ function runVM(state, maxCycles = null) {
case readByte:
// Have we reached EOF?
if(input.length == 0) {
// Yes, return 0
memory.set(index, 0);
// Yes
// If state.onEof is null, don't
// change the value
// If it's something else, set the
// cell to that
if(state.onEof !== null) {
memory.set(index,
state.onEof & 0xff);
}
} else {
// No, return character
memory.set(index, input.shift());
@ -765,9 +777,15 @@ function runVM(state, maxCycles = null) {
0);
memory.set(index, number);
} else if(input.length == 0) {
// No, but there was an EOF, so set
// the cell to 0
memory.set(index, 0);
// No, but there was an EOF
// If state.onEof is null, don't
// change the value
// If it's something else, set the
// cell to that
if(state.onEof !== null) {
memory.set(index,
state.onEof & 0xff);
}
} else {
// No, and there wasn't an EOF, so
// signal an error