diff --git a/src/c0vm.js b/src/c0vm.js index 2c0696f..3bce00e 100755 --- a/src/c0vm.js +++ b/src/c0vm.js @@ -394,10 +394,16 @@ ProgramState.prototype.step = function() { // Read offset into an array var elt_index = this.pop(); var index = this.pop(); - var array_length = this.heap[index]; - var elt_size = this.heap[index+1]; - if (elt_index >= array_length) c0_memory_error("Array index out of bounds."); - this.push(index + 2 + (elt_size*elt_index)); + + if (typeof index == "string") { + this.push(index.slice(elt_index)); + } else { + var array_length = this.heap[index]; + var elt_size = this.heap[index+1]; + if (elt_index >= array_length) + c0_memory_error("Array index out of bounds."); + this.push(index + 2 + (elt_size*elt_index)); + } this.frame.pc++; break; @@ -438,7 +444,10 @@ ProgramState.prototype.step = function() { case op.CMLOAD: var addr = this.pop(); - this.push(this.heap[addr]); + if (typeof addr == "string") + this.push(addr); + else + this.push(this.heap[addr]); this.frame.pc++; break; diff --git a/test/strings.c0.bc0 b/test/strings.c0.bc0 index b27a4fc..0b7b6c7 100644 --- a/test/strings.c0.bc0 +++ b/test/strings.c0.bc0 @@ -109,10 +109,10 @@ B0 # return # 00 06 # native count # native pool -00 01 00 47 # char_ord -00 01 00 46 # char_chr -00 01 00 50 # string_length -00 01 00 53 # string_to_chararray -00 01 00 4B # string_from_chararray -00 01 00 06 # print +00 01 00 51 # char_ord +00 01 00 50 # char_chr +00 01 00 5A # string_length +00 01 00 5D # string_to_chararray +00 01 00 55 # string_from_chararray +00 01 00 10 # print diff --git a/test/tests.js b/test/tests.js index 324a672..9d6a198 100644 --- a/test/tests.js +++ b/test/tests.js @@ -20,6 +20,30 @@ callbacks[c0ffi.NATIVE_PRINTLN] = function(args) { return 0; } +callbacks[c0ffi.NATIVE_STRING_LENGTH] = function(args) { + return args[0].length; +} + +callbacks[c0ffi.NATIVE_STRING_TO_CHARARRAY] = function(args) { + return args[0]; +} + +callbacks[c0ffi.NATIVE_STRING_FROM_CHARARRAY] = function(args) { + console.log("string_from_chararray: " + args); + return args[0]; +} + +callbacks[c0ffi.NATIVE_CHAR_CHR] = function(args) { + return String.fromCharCode(args[0]); +} + +callbacks[c0ffi.NATIVE_CHAR_ORD] = function(args) { + console.log("native_car_ord: " + args); + if (typeof args[0] == "string") + return args[0].charCodeAt(0); + return args[0]; +} + function doTest(filename, expected_result) { return function(test) { var result = c0vm.execute(parser.parse(filename), callbacks, false); @@ -98,3 +122,14 @@ exports.testArith = function(test) { printout); test.done(); } + +exports.testPIAZZA1 = doTest("piazza1.c0.bc0", 18); + +exports.testSTRINGS = function(test) { + printout = ""; + var result = c0vm.execute(parser.parse("strings.c0.bc0"), callbacks, false); + test.ok(printout == "hello there!?", + "strings.c0.bc0 - Did not print to screen correctly, result was " + + printout); + test.done(); +}