Compare commits

...

3 Commits

Author SHA1 Message Date
Juhani Krekelä 4853e42992 run() can now take a maxCycles argument 2018-05-24 23:36:24 +03:00
Juhani Krekelä d2a97cebb2 Add correct charset info 2018-05-24 23:35:50 +03:00
Juhani Krekelä d2e4da1939 Change the values runVM returns that relate to cycle limit 2018-05-24 23:20:52 +03:00
3 changed files with 22 additions and 13 deletions

View File

@ -25,7 +25,6 @@ TODO
* Make VM use a Proxied object that gives out 0 for nonexistent elements for
its memory
* Implement UTF-8 I/O
* Allow cycle maximum to be passed to `run()`
* Keep a cache of compiled programs in `run()`
### gir.html

View File

@ -1,6 +1,7 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Gir testbench</title>
<script type="text/javascript" src="gir.js"></script>
</head>

33
gir.js
View File

@ -457,9 +457,9 @@ function newVM(program, input) {
};
}
// (girVMState, int) → {state: girVMState, reachedLimit: bool}
// reachedLimit is set to true if the program ran for maxCycles and did not
// terminate
// (girVMState, int) → {state: girVMState, complete: bool, cycles: int}
// complete is set to true is the program completed its execution
// cycles is the number of cycles the VM ran
// If maxCycles is null, the program runs until completion
function runVM(state, maxCycles = null) {
let program = state.program;
@ -477,12 +477,13 @@ function runVM(state, maxCycles = null) {
let input = state.input;
let output = state.output;
let reachedLimit = true;
for(let cycle = 0; maxCycles === null || cycle < maxCycles; cycle++) {
let complete = false;
let cycle = 0;
for(; maxCycles === null || cycle < maxCycles; cycle++) {
// Exit the loop if we run to the end of the program
if(ip >= program.length) {
// Did not reach limit, program finished
reachedLimit = false;
// Program completed
complete = true;
break;
}
@ -585,7 +586,7 @@ function runVM(state, maxCycles = null) {
output
};
return {state: newState, reachedLimit: reachedLimit};
return {state: newState, complete: complete, cycles: cycle};
}
// ------------------------------------------------------------------
@ -597,11 +598,19 @@ function compile(program) {
return optimize(parse(program));
}
// (string, string) → string
function run(program, input) {
// TODO: Allow setting cycle maximum
// (string, string, bool) → string
function run(program, input, maxCycles = null) {
// TODO; Cache programs
let compiled = compile(program);
let vm = newVM(compiled, input);
return runVM(vm).state.output;
let result = runVM(vm, maxCycles);
let output = result.state.output;
// If didn't complete, mark it in the output
if(!result.complete) {
output += '«TLE»';
}
return output;
}