aboutsummaryrefslogtreecommitdiffstats
path: root/Godeps/_workspace/src/github.com/robertkrimen
diff options
context:
space:
mode:
Diffstat (limited to 'Godeps/_workspace/src/github.com/robertkrimen')
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/README.markdown8
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/array_test.go716
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/bug_test.go617
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/builtin_array.go2
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/builtin_test.go136
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/clone.go18
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/cmpl_evaluate_expression.go8
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/cmpl_evaluate_statement.go3
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/cmpl_test.go54
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/date_test.go481
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/dbg/dbg.go2
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/documentation_test.go95
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/error_test.go192
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/function_test.go280
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/global_test.go355
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/json_test.go183
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/math_test.go303
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/number_test.go165
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/object_test.go639
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/otto.go91
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/otto_.go4
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/otto_error_test.go48
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/otto_test.go1379
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/panic_test.go40
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/parser/expression.go2
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/parser/lexer_test.go380
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/parser/marshal_test.go930
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/parser/parser.go3
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/parser/parser_test.go1004
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/parser/regexp_test.go149
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/parser_test.go42
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/reflect_test.go483
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/regexp_test.go290
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/repl/repl.go115
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/runtime.go213
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/runtime_test.go778
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/script_test.go78
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/stash.go21
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/string_test.go365
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/testing_test.go135
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/type_function.go11
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/type_go_map.go2
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/underscore/source.go1
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_arrays_test.go344
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_chaining_test.go95
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_collections_test.go698
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_functions_test.go208
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_objects_test.go826
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_test.go165
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_utility_test.go419
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/value.go44
-rw-r--r--Godeps/_workspace/src/github.com/robertkrimen/otto/value_test.go281
52 files changed, 518 insertions, 13383 deletions
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/README.markdown b/Godeps/_workspace/src/github.com/robertkrimen/otto/README.markdown
index 571743bf1..fe8e1bd4a 100644
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/README.markdown
+++ b/Godeps/_workspace/src/github.com/robertkrimen/otto/README.markdown
@@ -20,8 +20,10 @@ Run something in the VM
Get a value out of the VM
- value, err := vm.Get("abc")
- value, _ := value.ToInteger()
+ if value, err := vm.Get("abc"); err == nil {
+ if value_int, err := value.ToInteger(); err == nil {
+ fmt.Printf("", value_int, err)
+ }
}
Set a number
@@ -221,7 +223,7 @@ the interrupt channel to do this:
Where is setTimeout/setInterval?
These timing functions are not actually part of the ECMA-262 specification.
-Typically, they belong to the `windows` object (in the browser). It would not be
+Typically, they belong to the `window` object (in the browser). It would not be
difficult to provide something like these via Go, but you probably want to wrap
otto in an event loop in that case.
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/array_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/array_test.go
deleted file mode 100644
index 06f481bd4..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/array_test.go
+++ /dev/null
@@ -1,716 +0,0 @@
-package otto
-
-import (
- "testing"
-)
-
-func TestArray(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc = [ undefined, "Nothing happens." ];
- abc.length;
- `, 2)
-
- test(`
- abc = ""+[0, 1, 2, 3];
- def = [].toString();
- ghi = [null, 4, "null"].toString();
- [ abc, def, ghi ];
- `, "0,1,2,3,,,4,null")
-
- test(`new Array(0).length`, 0)
-
- test(`new Array(11).length`, 11)
-
- test(`new Array(11, 1).length`, 2)
-
- test(`
- abc = [0, 1, 2, 3];
- abc.xyzzy = "Nothing happens.";
- delete abc[1];
- var xyzzy = delete abc.xyzzy;
- [ abc, xyzzy, abc.xyzzy ];
- `, "0,,2,3,true,")
-
- test(`
- var abc = [0, 1, 2, 3, 4];
- abc.length = 2;
- abc;
- `, "0,1")
-
- test(`raise:
- [].length = 3.14159;
- `, "RangeError")
-
- test(`raise:
- new Array(3.14159);
- `, "RangeError")
-
- test(`
- Object.defineProperty(Array.prototype, "0", {
- value: 100,
- writable: false,
- configurable: true
- });
- abc = [101];
- abc.hasOwnProperty("0") && abc[0] === 101;
- `, true)
-
- test(`
- abc = [,,undefined];
- [ abc.hasOwnProperty(0), abc.hasOwnProperty(1), abc.hasOwnProperty(2) ];
- `, "false,false,true")
-
- test(`
- abc = Object.getOwnPropertyDescriptor(Array, "prototype");
- [ [ typeof Array.prototype ],
- [ abc.writable, abc.enumerable, abc.configurable ] ];
- `, "object,false,false,false")
- })
-}
-
-func TestArray_toString(t *testing.T) {
- tt(t, func() {
- {
- test(`
- Array.prototype.toString = function() {
- return "Nothing happens.";
- }
- abc = Array.prototype.toString();
- def = [].toString();
- ghi = [null, 4, "null"].toString();
-
- [ abc, def, ghi ].join(",");
- `, "Nothing happens.,Nothing happens.,Nothing happens.")
- }
-
- {
- test(`
- Array.prototype.join = undefined
- abc = Array.prototype.toString()
- def = [].toString()
- ghi = [null, 4, "null"].toString()
-
- abc + "," + def + "," + ghi;
- `, "[object Array],[object Array],[object Array]")
- }
- })
-}
-
-func TestArray_toLocaleString(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- test(`
- [ 3.14159, "abc", undefined, new Date(0) ].toLocaleString();
- `, "3.14159,abc,,1970-01-01 00:00:00")
-
- test(`raise:
- [ { toLocaleString: undefined } ].toLocaleString();
- `, "TypeError")
- })
-}
-
-func TestArray_concat(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = [0, 1, 2];
- def = [-1, -2, -3];
- ghi = abc.concat(def);
- jkl = abc.concat(def, 3, 4, 5);
- mno = def.concat(-4, -5, abc);
-
- [ ghi, jkl, mno ].join(";");
- `, "0,1,2,-1,-2,-3;0,1,2,-1,-2,-3,3,4,5;-1,-2,-3,-4,-5,0,1,2")
-
- test(`
- var abc = [,1];
- var def = abc.concat([], [,]);
-
- def.getClass = Object.prototype.toString;
-
- [ def.getClass(), typeof def[0], def[1], typeof def[2], def.length ];
- `, "[object Array],undefined,1,undefined,3")
-
- test(`
- Object.defineProperty(Array.prototype, "0", {
- value: 100,
- writable: false,
- configurable: true
- });
-
- var abc = Array.prototype.concat.call(101);
-
- var hasProperty = abc.hasOwnProperty("0");
- var instanceOfVerify = typeof abc[0] === "object";
- var verifyValue = false;
- verifyValue = abc[0] == 101;
-
- var verifyEnumerable = false;
- for (var property in abc) {
- if (property === "0" && abc.hasOwnProperty("0")) {
- verifyEnumerable = true;
- }
- }
-
- var verifyWritable = false;
- abc[0] = 12;
- verifyWritable = abc[0] === 12;
-
- var verifyConfigurable = false;
- delete abc[0];
- verifyConfigurable = abc.hasOwnProperty("0");
-
- [ hasProperty, instanceOfVerify, verifyValue, !verifyConfigurable, verifyEnumerable, verifyWritable ];
- `, "true,true,true,true,true,true")
- })
-}
-
-func TestArray_splice(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = [0, 1, 2];
- def = abc.splice(1, 2, 3, 4, 5);
- ghi = [].concat(abc);
- jkl = ghi.splice(17, 21, 7, 8, 9);
- [ abc, def, ghi, jkl ].join(";");
- `, "0,3,4,5;1,2;0,3,4,5,7,8,9;")
- })
-}
-
-func TestArray_shift(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = [0, 1, 2];
- def = abc.shift();
- ghi = [].concat(abc);
- jkl = abc.shift();
- mno = [].concat(abc);
- pqr = abc.shift();
- stu = [].concat(abc);
- vwx = abc.shift();
-
- [ abc, def, ghi, jkl, mno, pqr, stu, vwx ].join(";");
- `, ";0;1,2;1;2;2;;")
- })
-}
-
-func TestArray_push(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = [0];
- def = abc.push(1);
- ghi = [].concat(abc);
- jkl = abc.push(2,3,4);
-
- [ abc, def, ghi, jkl ].join(";");
- `, "0,1,2,3,4;2;0,1;5")
- })
-}
-
-func TestArray_pop(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = [0,1];
- def = abc.pop();
- ghi = [].concat(abc);
- jkl = abc.pop();
- mno = [].concat(abc);
- pqr = abc.pop();
-
- [ abc, def, ghi, jkl, mno, pqr ].join(";");
- `, ";1;0;0;;")
- })
-}
-
-func TestArray_slice(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = [0,1,2,3];
- def = abc.slice();
- ghi = abc.slice(1);
- jkl = abc.slice(3,-1);
- mno = abc.slice(2,-1);
- pqr = abc.slice(-1, -10);
-
- [ abc, def, ghi, jkl, mno, pqr ].join(";");
- `, "0,1,2,3;0,1,2,3;1,2,3;;2;")
-
- // Array.protoype.slice is generic
- test(`
- abc = { 0: 0, 1: 1, 2: 2, 3: 3 };
- abc.length = 4;
- def = Array.prototype.slice.call(abc);
- ghi = Array.prototype.slice.call(abc,1);
- jkl = Array.prototype.slice.call(abc,3,-1);
- mno = Array.prototype.slice.call(abc,2,-1);
- pqr = Array.prototype.slice.call(abc,-1,-10);
-
- [ abc, def, ghi, jkl, pqr ].join(";");
- `, "[object Object];0,1,2,3;1,2,3;;")
- })
-}
-
-func TestArray_sliceArguments(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- (function(){
- return Array.prototype.slice.call(arguments, 1)
- })({}, 1, 2, 3);
- `, "1,2,3")
- })
-}
-
-func TestArray_unshift(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = [];
- def = abc.unshift(0);
- ghi = [].concat(abc);
- jkl = abc.unshift(1,2,3,4);
-
- [ abc, def, ghi, jkl ].join(";");
- `, "1,2,3,4,0;1;0;5")
- })
-}
-
-func TestArray_reverse(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = [0,1,2,3].reverse();
- def = [0,1,2].reverse();
-
- [ abc, def ];
- `, "3,2,1,0,2,1,0")
- })
-}
-
-func TestArray_sort(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = [0,1,2,3].sort();
- def = [3,2,1,0].sort();
- ghi = [].sort();
- jkl = [0].sort();
- mno = [1,0].sort();
- pqr = [1,5,-10, 100, 8, 72, 401, 0.05].sort();
- stu = [1,5,-10, 100, 8, 72, 401, 0.05].sort(function(x, y){
- return x == y ? 0 : x < y ? -1 : 1
- });
-
- [ abc, def, ghi, jkl, mno, pqr, stu ].join(";");
- `, "0,1,2,3;0,1,2,3;;0;0,1;-10,0.05,1,100,401,5,72,8;-10,0.05,1,5,8,72,100,401")
-
- test(`Array.prototype.sort.length`, 1)
- })
-}
-
-func TestArray_isArray(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- [ Array.isArray.length, Array.isArray(), Array.isArray([]), Array.isArray({}) ];
- `, "1,false,true,false")
-
- test(`Array.isArray(Math)`, false)
- })
-}
-
-func TestArray_indexOf(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`['a', 'b', 'c', 'b'].indexOf('b')`, 1)
-
- test(`['a', 'b', 'c', 'b'].indexOf('b', 2)`, 3)
-
- test(`['a', 'b', 'c', 'b'].indexOf('b', -2)`, 3)
-
- test(`
- Object.prototype.indexOf = Array.prototype.indexOf;
- var abc = {0: 'a', 1: 'b', 2: 'c', length: 3};
- abc.indexOf('c');
- `, 2)
-
- test(`[true].indexOf(true, "-Infinity")`, 0)
-
- test(`
- var target = {};
- Math[3] = target;
- Math.length = 5;
- Array.prototype.indexOf.call(Math, target) === 3;
- `, true)
-
- test(`
- var _NaN = NaN;
- var abc = new Array("NaN", undefined, 0, false, null, {toString:function(){return NaN}}, "false", _NaN, NaN);
- abc.indexOf(NaN);
- `, -1)
-
- test(`
- var abc = {toString:function (){return 0}};
- var def = 1;
- var ghi = -(4/3);
- var jkl = new Array(false, undefined, null, "0", abc, -1.3333333333333, "string", -0, true, +0, def, 1, 0, false, ghi, -(4/3));
- [ jkl.indexOf(-(4/3)), jkl.indexOf(0), jkl.indexOf(-0), jkl.indexOf(1) ];
- `, "14,7,7,10")
- })
-}
-
-func TestArray_lastIndexOf(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`['a', 'b', 'c', 'b'].lastIndexOf('b')`, 3)
-
- test(`['a', 'b', 'c', 'b'].lastIndexOf('b', 2)`, 1)
-
- test(`['a', 'b', 'c', 'b'].lastIndexOf('b', -2)`, 1)
-
- test(`
- Object.prototype.lastIndexOf = Array.prototype.lastIndexOf;
- var abc = {0: 'a', 1: 'b', 2: 'c', 3: 'b', length: 4};
- abc.lastIndexOf('b');
- `, 3)
-
- test(`
- var target = {};
- Math[3] = target;
- Math.length = 5;
- [ Array.prototype.lastIndexOf.call(Math, target) === 3 ];
- `, "true")
-
- test(`
- var _NaN = NaN;
- var abc = new Array("NaN", undefined, 0, false, null, {toString:function(){return NaN}}, "false", _NaN, NaN);
- abc.lastIndexOf(NaN);
- `, -1)
-
- test(`
- var abc = {toString:function (){return 0}};
- var def = 1;
- var ghi = -(4/3);
- var jkl = new Array(false, undefined, null, "0", abc, -1.3333333333333, "string", -0, true, +0, def, 1, 0, false, ghi, -(4/3));
- [ jkl.lastIndexOf(-(4/3)), jkl.indexOf(0), jkl.indexOf(-0), jkl.indexOf(1) ];
- `, "15,7,7,10")
- })
-}
-
-func TestArray_every(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`raise: [].every()`, "TypeError")
-
- test(`raise: [].every("abc")`, "TypeError")
-
- test(`[].every(function() { return false })`, true)
-
- test(`[1,2,3].every(function() { return false })`, false)
-
- test(`[1,2,3].every(function() { return true })`, true)
-
- test(`[1,2,3].every(function(_, index) { if (index === 1) return true })`, false)
-
- test(`
- var abc = function(value, index, object) {
- return ('[object Math]' !== Object.prototype.toString.call(object));
- };
-
- Math.length = 1;
- Math[0] = 1;
- !Array.prototype.every.call(Math, abc);
- `, true)
-
- test(`
- var def = false;
-
- var abc = function(value, index, object) {
- def = true;
- return this === Math;
- };
-
- [11].every(abc, Math) && def;
- `, true)
-
- test(`
- var def = false;
-
- var abc = function(value, index, object) {
- def = true;
- return Math;
- };
-
- [11].every(abc) && def;
- `, true)
- })
-}
-
-func TestArray_some(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`raise: [].some("abc")`, "TypeError")
-
- test(`[].some(function() { return true })`, false)
-
- test(`[1,2,3].some(function() { return false })`, false)
-
- test(`[1,2,3].some(function() { return true })`, true)
-
- test(`[1,2,3].some(function(_, index) { if (index === 1) return true })`, true)
-
- test(`
- var abc = function(value, index, object) {
- return ('[object Math]' !== Object.prototype.toString.call(object));
- };
-
- Math.length = 1;
- Math[0] = 1;
- !Array.prototype.some.call(Math, abc);
- `, true)
-
- test(`
- var abc = function(value, index, object) {
- return this === Math;
- };
-
- [11].some(abc, Math);
- `, true)
-
- test(`
- var abc = function(value, index, object) {
- return Math;
- };
-
- [11].some(abc);
- `, true)
- })
-}
-
-func TestArray_forEach(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`raise: [].forEach("abc")`, "TypeError")
-
- test(`
- var abc = 0;
- [].forEach(function(value) {
- abc += value;
- });
- abc;
- `, 0)
-
- test(`
- abc = 0;
- var def = [];
- [1,2,3].forEach(function(value, index) {
- abc += value;
- def.push(index);
- });
- [ abc, def ];
- `, "6,0,1,2")
-
- test(`
- var def = false;
- var abc = function(value, index, object) {
- def = ('[object Math]' === Object.prototype.toString.call(object));
- };
-
- Math.length = 1;
- Math[0] = 1;
- Array.prototype.forEach.call(Math, abc);
- def;
- `, true)
-
- test(`
- var def = false;
- var abc = function(value, index, object) {
- def = this === Math;
- };
-
- [11].forEach(abc, Math);
- def;
- `, true)
- })
-}
-
-func TestArray_indexing(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc = new Array(0, 1);
- var def = abc.length;
- abc[4294967296] = 10; // 2^32 => 0
- abc[4294967297] = 11; // 2^32+1 => 1
- [ def, abc.length, abc[0], abc[1], abc[4294967296] ];
- `, "2,2,0,1,10")
-
- test(`
- abc = new Array(0, 1);
- def = abc.length;
- abc[4294967295] = 10;
- var ghi = abc.length;
- abc[4294967299] = 12;
- var jkl = abc.length;
- abc[4294967294] = 11;
- [ def, ghi, jkl, abc.length, abc[4294967295], abc[4294967299] ];
- `, "2,2,2,4294967295,10,12")
- })
-}
-
-func TestArray_map(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`raise: [].map("abc")`, "TypeError")
-
- test(`[].map(function() { return 1 }).length`, 0)
-
- test(`[1,2,3].map(function(value) { return value * value })`, "1,4,9")
-
- test(`[1,2,3].map(function(value) { return 1 })`, "1,1,1")
-
- test(`
- var abc = function(value, index, object) {
- return ('[object Math]' === Object.prototype.toString.call(object));
- };
-
- Math.length = 1;
- Math[0] = 1;
- Array.prototype.map.call(Math, abc)[0];
- `, true)
-
- test(`
- var abc = function(value, index, object) {
- return this === Math;
- };
-
- [11].map(abc, Math)[0];
- `, true)
- })
-}
-
-func TestArray_filter(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`raise: [].filter("abc")`, "TypeError")
-
- test(`[].filter(function() { return 1 }).length`, 0)
-
- test(`[1,2,3].filter(function() { return false }).length`, 0)
-
- test(`[1,2,3].filter(function() { return true })`, "1,2,3")
- })
-}
-
-func TestArray_reduce(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`raise: [].reduce("abc")`, "TypeError")
-
- test(`raise: [].reduce(function() {})`, "TypeError")
-
- test(`[].reduce(function() {}, 0)`, 0)
-
- test(`[].reduce(function() {}, undefined)`, "undefined")
-
- test(`['a','b','c'].reduce(function(result, value) { return result+', '+value })`, "a, b, c")
-
- test(`[1,2,3].reduce(function(result, value) { return result + value }, 4)`, 10)
-
- test(`[1,2,3].reduce(function(result, value) { return result + value })`, 6)
- })
-}
-
-func TestArray_reduceRight(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`raise: [].reduceRight("abc")`, "TypeError")
-
- test(`raise: [].reduceRight(function() {})`, "TypeError")
-
- test(`[].reduceRight(function() {}, 0)`, 0)
-
- test(`[].reduceRight(function() {}, undefined)`, "undefined")
-
- test(`['a','b','c'].reduceRight(function(result, value) { return result+', '+value })`, "c, b, a")
-
- test(`[1,2,3].reduceRight(function(result, value) { return result + value }, 4)`, 10)
-
- test(`[1,2,3].reduceRight(function(result, value) { return result + value })`, 6)
- })
-}
-
-func TestArray_defineOwnProperty(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc = [];
- Object.defineProperty(abc, "length", {
- writable: false
- });
- abc.length;
- `, 0)
-
- test(`raise:
- var abc = [];
- var exception;
- Object.defineProperty(abc, "length", {
- writable: false
- });
- Object.defineProperty(abc, "length", {
- writable: true
- });
- `, "TypeError")
- })
-}
-
-func TestArray_new(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc = new Array(null);
- var def = new Array(undefined);
- [ abc.length, abc[0] === null, def.length, def[0] === undefined ]
- `, "1,true,1,true")
-
- test(`
- var abc = new Array(new Number(0));
- var def = new Array(new Number(4294967295));
- [ abc.length, typeof abc[0], abc[0] == 0, def.length, typeof def[0], def[0] == 4294967295 ]
- `, "1,object,true,1,object,true")
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/bug_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/bug_test.go
deleted file mode 100644
index 5e4d90bae..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/bug_test.go
+++ /dev/null
@@ -1,617 +0,0 @@
-package otto
-
-import (
- "testing"
- "time"
-)
-
-func Test_262(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- // 11.13.1-1-1
- test(`raise:
- eval("42 = 42;");
- `, "ReferenceError: Invalid left-hand side in assignment")
- })
-}
-
-func Test_issue5(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`'abc' === 'def'`, false)
- test(`'\t' === '\r'`, false)
- })
-}
-
-func Test_issue13(t *testing.T) {
- tt(t, func() {
- test, tester := test()
- vm := tester.vm
-
- value, err := vm.ToValue(map[string]interface{}{
- "string": "Xyzzy",
- "number": 42,
- "array": []string{"def", "ghi"},
- })
- if err != nil {
- t.Error(err)
- t.FailNow()
- }
-
- fn, err := vm.Object(`
- (function(value){
- return ""+[value.string, value.number, value.array]
- })
- `)
- if err != nil {
- t.Error(err)
- t.FailNow()
- }
-
- result, err := fn.Value().Call(fn.Value(), value)
- if err != nil {
- t.Error(err)
- t.FailNow()
- }
- is(result.string(), "Xyzzy,42,def,ghi")
-
- anything := struct {
- Abc interface{}
- }{
- Abc: map[string]interface{}{
- "def": []interface{}{
- []interface{}{
- "a", "b", "c", "", "d", "e",
- },
- map[string]interface{}{
- "jkl": "Nothing happens.",
- },
- },
- "ghi": -1,
- },
- }
-
- vm.Set("anything", anything)
- test(`
- [
- anything,
- "~",
- anything.Abc,
- "~",
- anything.Abc.def,
- "~",
- anything.Abc.def[1].jkl,
- "~",
- anything.Abc.ghi,
- ];
- `, "[object Object],~,[object Object],~,a,b,c,,d,e,[object Object],~,Nothing happens.,~,-1")
- })
-}
-
-func Test_issue16(t *testing.T) {
- tt(t, func() {
- test, vm := test()
-
- test(`
- var def = {
- "abc": ["abc"],
- "xyz": ["xyz"]
- };
- def.abc.concat(def.xyz);
- `, "abc,xyz")
-
- vm.Set("ghi", []string{"jkl", "mno"})
-
- test(`
- def.abc.concat(def.xyz).concat(ghi);
- `, "abc,xyz,jkl,mno")
-
- test(`
- ghi.concat(def.abc.concat(def.xyz));
- `, "jkl,mno,abc,xyz")
-
- vm.Set("pqr", []interface{}{"jkl", 42, 3.14159, true})
-
- test(`
- pqr.concat(ghi, def.abc, def, def.xyz);
- `, "jkl,42,3.14159,true,jkl,mno,abc,[object Object],xyz")
-
- test(`
- pqr.concat(ghi, def.abc, def, def.xyz).length;
- `, 9)
- })
-}
-
-func Test_issue21(t *testing.T) {
- tt(t, func() {
- vm1 := New()
- vm1.Run(`
- abc = {}
- abc.ghi = "Nothing happens.";
- var jkl = 0;
- abc.def = function() {
- jkl += 1;
- return 1;
- }
- `)
- abc, err := vm1.Get("abc")
- is(err, nil)
-
- vm2 := New()
- vm2.Set("cba", abc)
- _, err = vm2.Run(`
- var pqr = 0;
- cba.mno = function() {
- pqr -= 1;
- return 1;
- }
- cba.def();
- cba.def();
- cba.def();
- `)
- is(err, nil)
-
- jkl, err := vm1.Get("jkl")
- is(err, nil)
- is(jkl, 3)
-
- _, err = vm1.Run(`
- abc.mno();
- abc.mno();
- abc.mno();
- `)
- is(err, nil)
-
- pqr, err := vm2.Get("pqr")
- is(err, nil)
- is(pqr, -3)
- })
-}
-
-func Test_issue24(t *testing.T) {
- tt(t, func() {
- _, vm := test()
-
- {
- vm.Set("abc", []string{"abc", "def", "ghi"})
- value, err := vm.Get("abc")
- is(err, nil)
- export, _ := value.Export()
- {
- value, valid := export.([]string)
- is(valid, true)
-
- is(value[0], "abc")
- is(value[2], "ghi")
- }
- }
-
- {
- vm.Set("abc", [...]string{"abc", "def", "ghi"})
- value, err := vm.Get("abc")
- is(err, nil)
- export, _ := value.Export()
- {
- value, valid := export.([3]string)
- is(valid, true)
-
- is(value[0], "abc")
- is(value[2], "ghi")
- }
- }
-
- {
- vm.Set("abc", &[...]string{"abc", "def", "ghi"})
- value, err := vm.Get("abc")
- is(err, nil)
- export, _ := value.Export()
- {
- value, valid := export.(*[3]string)
- is(valid, true)
-
- is(value[0], "abc")
- is(value[2], "ghi")
- }
- }
-
- {
- vm.Set("abc", map[int]string{0: "abc", 1: "def", 2: "ghi"})
- value, err := vm.Get("abc")
- is(err, nil)
- export, _ := value.Export()
- {
- value, valid := export.(map[int]string)
- is(valid, true)
-
- is(value[0], "abc")
- is(value[2], "ghi")
- }
- }
-
- {
- vm.Set("abc", _abcStruct{Abc: true, Ghi: "Nothing happens."})
- value, err := vm.Get("abc")
- is(err, nil)
- export, _ := value.Export()
- {
- value, valid := export.(_abcStruct)
- is(valid, true)
-
- is(value.Abc, true)
- is(value.Ghi, "Nothing happens.")
- }
- }
-
- {
- vm.Set("abc", &_abcStruct{Abc: true, Ghi: "Nothing happens."})
- value, err := vm.Get("abc")
- is(err, nil)
- export, _ := value.Export()
- {
- value, valid := export.(*_abcStruct)
- is(valid, true)
-
- is(value.Abc, true)
- is(value.Ghi, "Nothing happens.")
- }
- }
- })
-}
-
-func Test_issue39(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc = 0, def = [], ghi = function() {
- if (abc < 10) return ++abc;
- return undefined;
- }
- for (var jkl; (jkl = ghi());) def.push(jkl);
- def;
- `, "1,2,3,4,5,6,7,8,9,10")
-
- test(`
- var abc = ["1", "2", "3", "4"];
- var def = [];
- for (var ghi; (ghi = abc.shift());) {
- def.push(ghi);
- }
- def;
- `, "1,2,3,4")
- })
-}
-
-func Test_issue64(t *testing.T) {
- tt(t, func() {
- test, vm := test()
-
- defer mockTimeLocal(time.UTC)()
-
- abc := map[string]interface{}{
- "time": time.Unix(0, 0),
- }
- vm.Set("abc", abc)
-
- def := struct {
- Public string
- private string
- }{
- "Public", "private",
- }
- vm.Set("def", def)
-
- test(`"sec" in abc.time`, false)
-
- test(`
- [ "Public" in def, "private" in def, def.Public, def.private ];
- `, "true,false,Public,")
-
- test(`JSON.stringify(abc)`, `{"time":"1970-01-01T00:00:00Z"}`)
- })
-}
-
-func Test_issue73(t *testing.T) {
- tt(t, func() {
- test, vm := test()
-
- vm.Set("abc", [4]int{3, 2, 1, 0})
-
- test(`
- var def = [ 0, 1, 2, 3 ];
- JSON.stringify(def) + JSON.stringify(abc);
- `, "[0,1,2,3][3,2,1,0]")
- })
-}
-
-func Test_7_3_1(t *testing.T) {
- tt(t, func() {
- test(`
- eval("var test7_3_1\u2028abc = 66;");
- [ abc, typeof test7_3_1 ];
- `, "66,undefined")
- })
-}
-
-func Test_7_3_3(t *testing.T) {
- tt(t, func() {
- test(`raise:
- eval("//\u2028 =;");
- `, "SyntaxError: Unexpected token =")
- })
-}
-
-func Test_S7_3_A2_1_T1(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`raise:
- eval("'\u000Astr\u000Aing\u000A'")
- `, "SyntaxError: Unexpected token ILLEGAL")
- })
-}
-
-func Test_S7_8_3_A2_1_T1(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- [ .0 === 0.0, .0, .1 === 0.1, .1 ]
- `, "true,0,true,0.1")
- })
-}
-
-func Test_S7_8_4_A4_2_T3(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- "\a"
- `, "a")
- })
-}
-
-func Test_S7_9_A1(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var def;
- abc: for (var i = 0; i <= 0; i++) {
- for (var j = 0; j <= 1; j++) {
- if (j === 0) {
- continue abc;
- } else {
- def = true;
- }
- }
- }
- [ def, i, j ];
- `, ",1,0")
- })
-}
-
-func Test_S7_9_A3(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- (function(){
- return
- 1;
- })()
- `, "undefined")
- })
-}
-
-func Test_7_3_10(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- eval("var \u0061\u0062\u0063 = 3.14159;");
- abc;
- `, 3.14159)
-
- test(`
- abc = undefined;
- eval("var \\u0061\\u0062\\u0063 = 3.14159;");
- abc;
- `, 3.14159)
- })
-}
-
-func Test_bug(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- // 10.4.2-1-5
- test(`
- "abc\
-def"
- `, "abcdef")
-
- test(`
- eval("'abc';\
- 'def'")
- `, "def")
-
- // S12.6.1_A10
- test(`
- var abc = 0;
- do {
- if(typeof(def) === "function"){
- abc = -1;
- break;
- } else {
- abc = 1;
- break;
- }
- } while(function def(){});
- abc;
- `, 1)
-
- // S12.7_A7
- test(`raise:
- abc:
- while (true) {
- eval("continue abc");
- }
- `, "SyntaxError: Undefined label 'abc'")
-
- // S15.1.2.1_A3.3_T3
- test(`raise:
- eval("return");
- `, "SyntaxError: Illegal return statement")
-
- // 15.2.3.3-2-33
- test(`
- var abc = { "AB\n\\cd": 1 };
- Object.getOwnPropertyDescriptor(abc, "AB\n\\cd").value;
- `, 1)
-
- // S15.3_A2_T1
- test(`raise:
- Function.call(this, "var x / = 1;");
- `, "SyntaxError: Unexpected token /")
-
- // ?
- test(`
- (function(){
- var abc = [];
- (function(){
- abc.push(0);
- abc.push(1);
- })(undefined);
- if ((function(){ return true; })()) {
- (function(){
- abc.push(2);
- })();
- }
- return abc;
- })();
- `, "0,1,2")
-
- if false {
- // 15.9.5.43-0-10
- // Should be an invalid date
- test(`
- date = new Date(1970, 0, -99999999, 0, 0, 0, 1);
- `, "")
- }
-
- // S7.8.3_A1.2_T1
- test(`
- [ 0e1, 1e1, 2e1, 3e1, 4e1, 5e1, 6e1, 7e1, 8e1, 9e1 ];
- `, "0,10,20,30,40,50,60,70,80,90")
-
- // S15.10.2.7_A3_T2
- test(`
- var abc = /\s+abc\s+/.exec("\t abc def");
- [ abc.length, abc.index, abc.input, abc ];
- `, "1,0,\t abc def,\t abc ")
- })
-}
-
-func Test_issue79(t *testing.T) {
- tt(t, func() {
- test, vm := test()
-
- vm.Set("abc", []_abcStruct{
- {
- Ghi: "一",
- Def: 1,
- },
- {
- Def: 3,
- Ghi: "三",
- },
- {
- Def: 2,
- Ghi: "二",
- },
- {
- Def: 4,
- Ghi: "å››",
- },
- })
-
- test(`
- abc.sort(function(a,b){ return b.Def-a.Def });
- def = [];
- for (i = 0; i < abc.length; i++) {
- def.push(abc[i].String())
- }
- def;
- `, "四,三,二,一")
- })
-}
-
-func Test_issue80(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- JSON.stringify([
- 1401868959,
- 14018689591,
- 140186895901,
- 1401868959001,
- 14018689590001,
- 140186895900001,
- 1401868959000001,
- 1401868959000001.5,
- 14018689590000001,
- 140186895900000001,
- 1401868959000000001,
- 14018689590000000001,
- 140186895900000000001,
- 140186895900000000001.5
- ]);
- `, "[1401868959,14018689591,140186895901,1401868959001,14018689590001,140186895900001,1401868959000001,1.4018689590000015e+15,14018689590000001,140186895900000001,1401868959000000001,1.401868959e+19,1.401868959e+20,1.401868959e+20]")
- })
-}
-
-func Test_issue87(t *testing.T) {
- tt(t, func() {
- test, vm := test()
-
- test(`
- var def = 0;
- abc: {
- for (;;) {
- def = !1;
- break abc;
- }
- def = !0;
- }
- def;
- `, false)
-
- _, err := vm.Run(`
-/*
-CryptoJS v3.1.2
-code.google.com/p/crypto-js
-(c) 2009-2013 by Jeff Mott. All rights reserved.
-code.google.com/p/crypto-js/wiki/License
-*/
-var CryptoJS=CryptoJS||function(h,s){var f={},g=f.lib={},q=function(){},m=g.Base={extend:function(a){q.prototype=this;var c=new q;a&&c.mixIn(a);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},
-r=g.WordArray=m.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=s?c:4*a.length},toString:function(a){return(a||k).stringify(this)},concat:function(a){var c=this.words,d=a.words,b=this.sigBytes;a=a.sigBytes;this.clamp();if(b%4)for(var e=0;e<a;e++)c[b+e>>>2]|=(d[e>>>2]>>>24-8*(e%4)&255)<<24-8*((b+e)%4);else if(65535<d.length)for(e=0;e<a;e+=4)c[b+e>>>2]=d[e>>>2];else c.push.apply(c,d);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<<
-32-8*(c%4);a.length=h.ceil(c/4)},clone:function(){var a=m.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],d=0;d<a;d+=4)c.push(4294967296*h.random()|0);return new r.init(c,a)}}),l=f.enc={},k=l.Hex={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b<a;b++){var e=c[b>>>2]>>>24-8*(b%4)&255;d.push((e>>>4).toString(16));d.push((e&15).toString(16))}return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b<c;b+=2)d[b>>>3]|=parseInt(a.substr(b,
-2),16)<<24-4*(b%8);return new r.init(d,c/2)}},n=l.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b<a;b++)d.push(String.fromCharCode(c[b>>>2]>>>24-8*(b%4)&255));return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b<c;b++)d[b>>>2]|=(a.charCodeAt(b)&255)<<24-8*(b%4);return new r.init(d,c)}},j=l.Utf8={stringify:function(a){try{return decodeURIComponent(escape(n.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return n.parse(unescape(encodeURIComponent(a)))}},
-u=g.BufferedBlockAlgorithm=m.extend({reset:function(){this._data=new r.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,d=c.words,b=c.sigBytes,e=this.blockSize,f=b/(4*e),f=a?h.ceil(f):h.max((f|0)-this._minBufferSize,0);a=f*e;b=h.min(4*a,b);if(a){for(var g=0;g<a;g+=e)this._doProcessBlock(d,g);g=d.splice(0,a);c.sigBytes-=b}return new r.init(g,b)},clone:function(){var a=m.clone.call(this);
-a._data=this._data.clone();return a},_minBufferSize:0});g.Hasher=u.extend({cfg:m.extend(),init:function(a){this.cfg=this.cfg.extend(a);this.reset()},reset:function(){u.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);return this._doFinalize()},blockSize:16,_createHelper:function(a){return function(c,d){return(new a.init(d)).finalize(c)}},_createHmacHelper:function(a){return function(c,d){return(new t.HMAC.init(a,
-d)).finalize(c)}}});var t=f.algo={};return f}(Math);
-(function(h){for(var s=CryptoJS,f=s.lib,g=f.WordArray,q=f.Hasher,f=s.algo,m=[],r=[],l=function(a){return 4294967296*(a-(a|0))|0},k=2,n=0;64>n;){var j;a:{j=k;for(var u=h.sqrt(j),t=2;t<=u;t++)if(!(j%t)){j=!1;break a}j=!0}j&&(8>n&&(m[n]=l(h.pow(k,0.5))),r[n]=l(h.pow(k,1/3)),n++);k++}var a=[],f=f.SHA256=q.extend({_doReset:function(){this._hash=new g.init(m.slice(0))},_doProcessBlock:function(c,d){for(var b=this._hash.words,e=b[0],f=b[1],g=b[2],j=b[3],h=b[4],m=b[5],n=b[6],q=b[7],p=0;64>p;p++){if(16>p)a[p]=
-c[d+p]|0;else{var k=a[p-15],l=a[p-2];a[p]=((k<<25|k>>>7)^(k<<14|k>>>18)^k>>>3)+a[p-7]+((l<<15|l>>>17)^(l<<13|l>>>19)^l>>>10)+a[p-16]}k=q+((h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25))+(h&m^~h&n)+r[p]+a[p];l=((e<<30|e>>>2)^(e<<19|e>>>13)^(e<<10|e>>>22))+(e&f^e&g^f&g);q=n;n=m;m=h;h=j+k|0;j=g;g=f;f=e;e=k+l|0}b[0]=b[0]+e|0;b[1]=b[1]+f|0;b[2]=b[2]+g|0;b[3]=b[3]+j|0;b[4]=b[4]+h|0;b[5]=b[5]+m|0;b[6]=b[6]+n|0;b[7]=b[7]+q|0},_doFinalize:function(){var a=this._data,d=a.words,b=8*this._nDataBytes,e=8*a.sigBytes;
-d[e>>>5]|=128<<24-e%32;d[(e+64>>>9<<4)+14]=h.floor(b/4294967296);d[(e+64>>>9<<4)+15]=b;a.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var a=q.clone.call(this);a._hash=this._hash.clone();return a}});s.SHA256=q._createHelper(f);s.HmacSHA256=q._createHmacHelper(f)})(Math);
-(function(){var h=CryptoJS,s=h.enc.Utf8;h.algo.HMAC=h.lib.Base.extend({init:function(f,g){f=this._hasher=new f.init;"string"==typeof g&&(g=s.parse(g));var h=f.blockSize,m=4*h;g.sigBytes>m&&(g=f.finalize(g));g.clamp();for(var r=this._oKey=g.clone(),l=this._iKey=g.clone(),k=r.words,n=l.words,j=0;j<h;j++)k[j]^=1549556828,n[j]^=909522486;r.sigBytes=l.sigBytes=m;this.reset()},reset:function(){var f=this._hasher;f.reset();f.update(this._iKey)},update:function(f){this._hasher.update(f);return this},finalize:function(f){var g=
-this._hasher;f=g.finalize(f);g.reset();return g.finalize(this._oKey.clone().concat(f))}})})();
- `)
- is(err, nil)
-
- test(`CryptoJS.HmacSHA256("Message", "secret");`, "aa747c502a898200f9e4fa21bac68136f886a0e27aec70ba06daf2e2a5cb5597")
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/builtin_array.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/builtin_array.go
index 44bf88569..160a251c6 100644
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/builtin_array.go
+++ b/Godeps/_workspace/src/github.com/robertkrimen/otto/builtin_array.go
@@ -420,7 +420,7 @@ func arraySortQuickPartition(thisObject *_object, left, right, pivot uint, compa
arraySortSwap(thisObject, pivot, right) // Right is now the pivot value
cursor := left
for index := left; index < right; index++ {
- if sortCompare(thisObject, index, right, compare) == -1 { // Compare to the pivot value
+ if sortCompare(thisObject, index, right, compare) < 0 { // Compare to the pivot value
arraySortSwap(thisObject, index, cursor)
cursor += 1
}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/builtin_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/builtin_test.go
deleted file mode 100644
index f5be00ab6..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/builtin_test.go
+++ /dev/null
@@ -1,136 +0,0 @@
-package otto
-
-import (
- "testing"
-)
-
-func TestString_substr(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- [
- "abc".substr(0,1), // "a"
- "abc".substr(0,2), // "ab"
- "abc".substr(0,3), // "abc"
- "abc".substr(0,4), // "abc"
- "abc".substr(0,9), // "abc"
- ];
- `, "a,ab,abc,abc,abc")
-
- test(`
- [
- "abc".substr(1,1), // "b"
- "abc".substr(1,2), // "bc"
- "abc".substr(1,3), // "bc"
- "abc".substr(1,4), // "bc"
- "abc".substr(1,9), // "bc"
- ];
- `, "b,bc,bc,bc,bc")
-
- test(`
- [
- "abc".substr(2,1), // "c"
- "abc".substr(2,2), // "c"
- "abc".substr(2,3), // "c"
- "abc".substr(2,4), // "c"
- "abc".substr(2,9), // "c"
- ];
- `, "c,c,c,c,c")
-
- test(`
- [
- "abc".substr(3,1), // ""
- "abc".substr(3,2), // ""
- "abc".substr(3,3), // ""
- "abc".substr(3,4), // ""
- "abc".substr(3,9), // ""
- ];
- `, ",,,,")
-
- test(`
- [
- "abc".substr(0), // "abc"
- "abc".substr(1), // "bc"
- "abc".substr(2), // "c"
- "abc".substr(3), // ""
- "abc".substr(9), // ""
- ];
- `, "abc,bc,c,,")
-
- test(`
- [
- "abc".substr(-9), // "abc"
- "abc".substr(-3), // "abc"
- "abc".substr(-2), // "bc"
- "abc".substr(-1), // "c"
- ];
- `, "abc,abc,bc,c")
-
- test(`
- [
- "abc".substr(-9, 1), // "a"
- "abc".substr(-3, 1), // "a"
- "abc".substr(-2, 1), // "b"
- "abc".substr(-1, 1), // "c"
- "abc".substr(-1, 2), // "c"
- ];
- `, "a,a,b,c,c")
-
- test(`"abcd".substr(3, 5)`, "d")
- })
-}
-
-func Test_builtin_escape(t *testing.T) {
- tt(t, func() {
- is(builtin_escape("abc"), "abc")
-
- is(builtin_escape("="), "%3D")
-
- is(builtin_escape("abc=%+32"), "abc%3D%25+32")
-
- is(builtin_escape("世界"), "%u4E16%u754C")
- })
-}
-
-func Test_builtin_unescape(t *testing.T) {
- tt(t, func() {
- is(builtin_unescape("abc"), "abc")
-
- is(builtin_unescape("=%3D"), "==")
-
- is(builtin_unescape("abc%3D%25+32"), "abc=%+32")
-
- is(builtin_unescape("%u4E16%u754C"), "世界")
- })
-}
-
-func TestGlobal_escape(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- [
- escape("abc"), // "abc"
- escape("="), // "%3D"
- escape("abc=%+32"), // "abc%3D%25+32"
- escape("\u4e16\u754c"), // "%u4E16%u754C"
- ];
- `, "abc,%3D,abc%3D%25+32,%u4E16%u754C")
- })
-}
-
-func TestGlobal_unescape(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- [
- unescape("abc"), // "abc"
- unescape("=%3D"), // "=="
- unescape("abc%3D%25+32"), // "abc=%+32"
- unescape("%u4E16%u754C"), // "世界"
- ];
- `, "abc,==,abc=%+32,世界")
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/clone.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/clone.go
index f79901b35..82cb0f0af 100644
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/clone.go
+++ b/Godeps/_workspace/src/github.com/robertkrimen/otto/clone.go
@@ -140,11 +140,23 @@ func (clone *_clone) stash(in _stash) _stash {
func (clone *_clone) property(in _property) _property {
out := in
- if value, valid := in.value.(Value); valid {
+
+ switch value := in.value.(type) {
+ case Value:
out.value = clone.value(value)
- } else {
- panic(fmt.Errorf("in.value.(Value) != true"))
+ case _propertyGetSet:
+ p := _propertyGetSet{}
+ if value[0] != nil {
+ p[0] = clone.object(value[0])
+ }
+ if value[1] != nil {
+ p[1] = clone.object(value[1])
+ }
+ out.value = p
+ default:
+ panic(fmt.Errorf("in.value.(Value) != true; in.value is %T", in.value))
}
+
return out
}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/cmpl_evaluate_expression.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/cmpl_evaluate_expression.go
index 34449970e..8586a484f 100644
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/cmpl_evaluate_expression.go
+++ b/Godeps/_workspace/src/github.com/robertkrimen/otto/cmpl_evaluate_expression.go
@@ -173,7 +173,11 @@ func (self *_runtime) cmpl_evaluate_nodeBracketExpression(node *_nodeBracketExpr
memberValue := member.resolve()
// TODO Pass in base value as-is, and defer toObject till later?
- return toValue(newPropertyReference(self, self.toObject(targetValue), memberValue.string(), false, _at(node.idx)))
+ object, err := self.objectCoerce(targetValue)
+ if err != nil {
+ panic(self.panicTypeError("Cannot access member '%s' of %s", memberValue.string(), err.Error(), _at(node.idx)))
+ }
+ return toValue(newPropertyReference(self, object, memberValue.string(), false, _at(node.idx)))
}
func (self *_runtime) cmpl_evaluate_nodeCallExpression(node *_nodeCallExpression, withArgumentList []interface{}) Value {
@@ -255,7 +259,7 @@ func (self *_runtime) cmpl_evaluate_nodeDotExpression(node *_nodeDotExpression)
// TODO Pass in base value as-is, and defer toObject till later?
object, err := self.objectCoerce(targetValue)
if err != nil {
- panic(self.panicTypeError("Cannot access member '%s' of %s", node.identifier, err.Error()))
+ panic(self.panicTypeError("Cannot access member '%s' of %s", node.identifier, err.Error(), _at(node.idx)))
}
return toValue(newPropertyReference(self, object, node.identifier, false, _at(node.idx)))
}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/cmpl_evaluate_statement.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/cmpl_evaluate_statement.go
index 7be158487..e16c6ac6c 100644
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/cmpl_evaluate_statement.go
+++ b/Godeps/_workspace/src/github.com/robertkrimen/otto/cmpl_evaluate_statement.go
@@ -47,6 +47,9 @@ func (self *_runtime) cmpl_evaluate_nodeStatement(node _nodeStatement) Value {
}
case *_nodeDebuggerStatement:
+ if self.debugger != nil {
+ self.debugger(self.otto)
+ }
return emptyValue // Nothing happens.
case *_nodeDoWhileStatement:
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/cmpl_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/cmpl_test.go
deleted file mode 100644
index 34b050f00..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/cmpl_test.go
+++ /dev/null
@@ -1,54 +0,0 @@
-package otto
-
-import (
- "testing"
-
- "github.com/robertkrimen/otto/parser"
-)
-
-func Test_cmpl(t *testing.T) {
- tt(t, func() {
- vm := New()
-
- test := func(src string, expect ...interface{}) {
- program, err := parser.ParseFile(nil, "", src, 0)
- is(err, nil)
- {
- program := cmpl_parse(program)
- value := vm.runtime.cmpl_evaluate_nodeProgram(program, false)
- if len(expect) > 0 {
- is(value, expect[0])
- }
- }
- }
-
- test(``, Value{})
-
- test(`var abc = 1; abc;`, 1)
-
- test(`var abc = 1 + 1; abc;`, 2)
-
- test(`1 + 2;`, 3)
- })
-}
-
-func TestParse_cmpl(t *testing.T) {
- tt(t, func() {
-
- test := func(src string) {
- program, err := parser.ParseFile(nil, "", src, 0)
- is(err, nil)
- is(cmpl_parse(program), "!=", nil)
- }
-
- test(``)
-
- test(`var abc = 1; abc;`)
-
- test(`
- function abc() {
- return;
- }
- `)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/date_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/date_test.go
deleted file mode 100644
index a9c71edde..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/date_test.go
+++ /dev/null
@@ -1,481 +0,0 @@
-package otto
-
-import (
- "math"
- "testing"
- "time"
-)
-
-func mockTimeLocal(location *time.Location) func() {
- local := time.Local
- time.Local = location
- return func() {
- time.Local = local
- }
-}
-
-// Passing or failing should not be dependent on what time zone we're in
-func mockUTC() func() {
- return mockTimeLocal(time.UTC)
-}
-
-func TestDate(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- time0 := time.Unix(1348616313, 47*1000*1000).Local()
-
- test(`Date`, "function Date() { [native code] }")
- test(`new Date(0).toUTCString()`, "Thu, 01 Jan 1970 00:00:00 UTC")
- test(`new Date(0).toGMTString()`, "Thu, 01 Jan 1970 00:00:00 GMT")
- if false {
- // TODO toLocale{Date,Time}String
- test(`new Date(0).toLocaleString()`, "")
- test(`new Date(0).toLocaleDateString()`, "")
- test(`new Date(0).toLocaleTimeString()`, "")
- }
- test(`new Date(1348616313).getTime()`, 1348616313)
- test(`new Date(1348616313).toUTCString()`, "Fri, 16 Jan 1970 14:36:56 UTC")
- test(`abc = new Date(1348616313047); abc.toUTCString()`, "Tue, 25 Sep 2012 23:38:33 UTC")
- test(`abc.getYear()`, time0.Year()-1900)
- test(`abc.getFullYear()`, time0.Year())
- test(`abc.getUTCFullYear()`, 2012)
- test(`abc.getMonth()`, int(time0.Month())-1) // Remember, the JavaScript month is 0-based
- test(`abc.getUTCMonth()`, 8)
- test(`abc.getDate()`, time0.Day())
- test(`abc.getUTCDate()`, 25)
- test(`abc.getDay()`, int(time0.Weekday()))
- test(`abc.getUTCDay()`, 2)
- test(`abc.getHours()`, time0.Hour())
- test(`abc.getUTCHours()`, 23)
- test(`abc.getMinutes()`, time0.Minute())
- test(`abc.getUTCMinutes()`, 38)
- test(`abc.getSeconds()`, time0.Second())
- test(`abc.getUTCSeconds()`, 33)
- test(`abc.getMilliseconds()`, time0.Nanosecond()/(1000*1000)) // In honor of the 47%
- test(`abc.getUTCMilliseconds()`, 47)
- _, offset := time0.Zone()
- test(`abc.getTimezoneOffset()`, offset/-60)
-
- test(`new Date("Xyzzy").getTime()`, math.NaN())
-
- test(`abc.setFullYear(2011); abc.toUTCString()`, "Sun, 25 Sep 2011 23:38:33 UTC")
- test(`new Date(12564504e5).toUTCString()`, "Sun, 25 Oct 2009 06:00:00 UTC")
- test(`new Date(2009, 9, 25).toUTCString()`, "Sun, 25 Oct 2009 00:00:00 UTC")
- test(`+(new Date(2009, 9, 25))`, 1256428800000)
-
- format := "Mon, 2 Jan 2006 15:04:05 MST"
-
- time1 := time.Unix(1256450400, 0)
- time0 = time.Date(time1.Year(), time1.Month(), time1.Day(), time1.Hour(), time1.Minute(), time1.Second(), time1.Nanosecond(), time1.Location()).UTC()
-
- time0 = time.Date(time1.Year(), time1.Month(), time1.Day(), time1.Hour(), time1.Minute(), time1.Second(), 2001*1000*1000, time1.Location()).UTC()
- test(`abc = new Date(12564504e5); abc.setMilliseconds(2001); abc.toUTCString()`, time0.Format(format))
-
- time0 = time.Date(time1.Year(), time1.Month(), time1.Day(), time1.Hour(), time1.Minute(), 61, time1.Nanosecond(), time1.Location()).UTC()
- test(`abc = new Date(12564504e5); abc.setSeconds("61"); abc.toUTCString()`, time0.Format(format))
-
- time0 = time.Date(time1.Year(), time1.Month(), time1.Day(), time1.Hour(), 61, time1.Second(), time1.Nanosecond(), time1.Location()).UTC()
- test(`abc = new Date(12564504e5); abc.setMinutes("61"); abc.toUTCString()`, time0.Format(format))
-
- time0 = time.Date(time1.Year(), time1.Month(), time1.Day(), 5, time1.Minute(), time1.Second(), time1.Nanosecond(), time1.Location()).UTC()
- test(`abc = new Date(12564504e5); abc.setHours("5"); abc.toUTCString()`, time0.Format(format))
-
- time0 = time.Date(time1.Year(), time1.Month(), 26, time1.Hour(), time1.Minute(), time1.Second(), time1.Nanosecond(), time1.Location()).UTC()
- test(`abc = new Date(12564504e5); abc.setDate("26"); abc.toUTCString()`, time0.Format(format))
-
- time0 = time.Date(time1.Year(), 10, time1.Day(), time1.Hour(), time1.Minute(), time1.Second(), time1.Nanosecond(), time1.Location()).UTC()
- test(`abc = new Date(12564504e5); abc.setMonth(9); abc.toUTCString()`, time0.Format(format))
- test(`abc = new Date(12564504e5); abc.setMonth("09"); abc.toUTCString()`, time0.Format(format))
-
- time0 = time.Date(time1.Year(), 11, time1.Day(), time1.Hour(), time1.Minute(), time1.Second(), time1.Nanosecond(), time1.Location()).UTC()
- test(`abc = new Date(12564504e5); abc.setMonth("10"); abc.toUTCString()`, time0.Format(format))
-
- time0 = time.Date(2010, time1.Month(), time1.Day(), time1.Hour(), time1.Minute(), time1.Second(), time1.Nanosecond(), time1.Location()).UTC()
- test(`abc = new Date(12564504e5); abc.setFullYear(2010); abc.toUTCString()`, time0.Format(format))
-
- test(`new Date("2001-01-01T10:01:02.000").getTime()`, 978343262000)
-
- // Date()
- test(`typeof Date()`, "string")
- test(`typeof Date(2006, 1, 2)`, "string")
-
- test(`
- abc = Object.getOwnPropertyDescriptor(Date, "parse");
- [ abc.value === Date.parse, abc.writable, abc.enumerable, abc.configurable ];
- `, "true,true,false,true")
-
- test(`
- abc = Object.getOwnPropertyDescriptor(Date.prototype, "toTimeString");
- [ abc.value === Date.prototype.toTimeString, abc.writable, abc.enumerable, abc.configurable ];
- `, "true,true,false,true")
-
- test(`
- var abc = Object.getOwnPropertyDescriptor(Date, "prototype");
- [ [ typeof Date.prototype ],
- [ abc.writable, abc.enumerable, abc.configurable ] ];
- `, "object,false,false,false")
- })
-}
-
-func TestDate_parse(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- test(`Date.parse("2001-01-01T10:01:02.000")`, 978343262000)
-
- test(`Date.parse("2006-01-02T15:04:05.000")`, 1136214245000)
-
- test(`Date.parse("2006")`, 1136073600000)
-
- test(`Date.parse("1970-01-16T14:36:56+00:00")`, 1348616000)
-
- test(`Date.parse("1970-01-16T14:36:56.313+00:00")`, 1348616313)
-
- test(`Date.parse("1970-01-16T14:36:56.000")`, 1348616000)
-
- test(`Date.parse.length`, 1)
- })
-}
-
-func TestDate_UTC(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- test(`Date.UTC(2009, 9, 25)`, 1256428800000)
-
- test(`Date.UTC.length`, 7)
- })
-}
-
-func TestDate_now(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- // FIXME I think this too risky
- test(`+(""+Date.now()).substr(0, 10)`, float64(epochToInteger(timeToEpoch(time.Now()))/1000))
-
- test(`Date.now() - Date.now(1,2,3) < 24 * 60 * 60`, true)
- })
-}
-
-func TestDate_toISOString(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- test(`new Date(0).toISOString()`, "1970-01-01T00:00:00.000Z")
- })
-}
-
-func TestDate_toJSON(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- test(`new Date(0).toJSON()`, "1970-01-01T00:00:00.000Z")
- })
-}
-
-func TestDate_setYear(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- test(`new Date(12564504e5).setYear(96)`, 846223200000)
-
- test(`new Date(12564504e5).setYear(1996)`, 846223200000)
-
- test(`new Date(12564504e5).setYear(2000)`, 972453600000)
- })
-}
-
-func TestDateDefaultValue(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- test(`
- var date = new Date();
- date + 0 === date.toString() + "0";
- `, true)
- })
-}
-
-func TestDate_April1978(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- test(`
- var abc = new Date(1978,3);
- [ abc.getYear(), abc.getMonth(), abc.valueOf() ];
- `, "78,3,260236800000")
- })
-}
-
-func TestDate_setMilliseconds(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- test(`
- abc = new Date();
- def = abc.setMilliseconds();
- [ abc, def ];
- `, "Invalid Date,NaN")
- })
-}
-
-func TestDate_new(t *testing.T) {
- // FIXME?
- // This is probably incorrect, due to differences in Go date/time handling
- // versus ECMA date/time handling, but we'll leave this here for
- // future reference
-
- if true {
- return
- }
-
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- test(`
- [
- new Date(1899, 11).valueOf(),
- new Date(1899, 12).valueOf(),
- new Date(1900, 0).valueOf()
- ]
- `, "-2211638400000,-2208960000000,-2208960000000")
- })
-}
-
-func TestDateComparison(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- test(`
- var now0 = Date.now();
- var now1 = (new Date()).toString();
- [ now0 === now1, Math.abs(now0 - Date.parse(now1)) <= 1000 ];
- `, "false,true")
- })
-}
-
-func TestDate_setSeconds(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- test(`
- abc = new Date(1980, 10);
- def = new Date(abc);
-
- abc.setSeconds(10, 12);
-
- def.setSeconds(10);
- def.setMilliseconds(12);
-
- abc.valueOf() === def.valueOf();
- `, true)
-
- test(`
- abc = new Date(1980, 10);
- def = new Date(abc);
-
- abc.setUTCSeconds(10, 12);
-
- def.setUTCSeconds(10);
- def.setUTCMilliseconds(12);
-
- abc.valueOf() === def.valueOf();
- `, true)
-
- test(`Date.prototype.setSeconds.length`, 2)
- test(`Date.prototype.setUTCSeconds.length`, 2)
- })
-}
-
-func TestDate_setMinutes(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- test(`
- abc = new Date(1980, 10);
- def = new Date(abc);
-
- abc.setMinutes(8, 10, 12);
-
- def.setMinutes(8);
- def.setSeconds(10);
- def.setMilliseconds(12);
-
- abc.valueOf() === def.valueOf();
- `, true)
-
- test(`
- abc = new Date(1980, 10);
- def = new Date(abc);
-
- abc.setUTCMinutes(8, 10, 12);
-
- def.setUTCMinutes(8);
- def.setUTCSeconds(10);
- def.setUTCMilliseconds(12);
-
- abc.valueOf() === def.valueOf();
- `, true)
-
- test(`Date.prototype.setMinutes.length`, 3)
- test(`Date.prototype.setUTCMinutes.length`, 3)
- })
-}
-
-func TestDate_setHours(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- test(`
- abc = new Date(1980, 10);
- def = new Date(abc);
-
- abc.setHours(6, 8, 10, 12);
-
- def.setHours(6);
- def.setMinutes(8);
- def.setSeconds(10);
- def.setMilliseconds(12);
-
- abc.valueOf() === def.valueOf();
- `, true)
-
- test(`
- abc = new Date(1980, 10);
- def = new Date(abc);
-
- abc.setUTCHours(6, 8, 10, 12);
-
- def.setUTCHours(6);
- def.setUTCMinutes(8);
- def.setUTCSeconds(10);
- def.setUTCMilliseconds(12);
-
- abc.valueOf() === def.valueOf();
- `, true)
-
- test(`Date.prototype.setHours.length`, 4)
- test(`Date.prototype.setUTCHours.length`, 4)
- })
-}
-
-func TestDate_setMonth(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- test(`
- abc = new Date(1980, 10);
- def = new Date(abc);
-
- abc.setMonth(6, 8);
-
- def.setMonth(6);
- def.setDate(8);
-
- abc.valueOf() === def.valueOf();
- `, true)
-
- test(`
- abc = new Date(1980, 10);
- def = new Date(abc);
-
- abc.setUTCMonth(6, 8);
-
- def.setUTCMonth(6);
- def.setUTCDate(8);
-
- abc.valueOf() === def.valueOf();
- `, true)
-
- test(`Date.prototype.setMonth.length`, 2)
- test(`Date.prototype.setUTCMonth.length`, 2)
- })
-}
-
-func TestDate_setFullYear(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- test(`
- abc = new Date(1980, 10);
- def = new Date(abc);
-
- abc.setFullYear(1981, 6, 8);
-
- def.setFullYear(1981);
- def.setMonth(6);
- def.setDate(8);
-
- abc.valueOf() === def.valueOf();
- `, true)
-
- test(`
- abc = new Date(1980, 10);
- def = new Date(abc);
-
- abc.setUTCFullYear(1981, 6, 8);
-
- def.setUTCFullYear(1981);
- def.setUTCMonth(6);
- def.setUTCDate(8);
-
- abc.valueOf() === def.valueOf();
- `, true)
-
- test(`Date.prototype.setFullYear.length`, 3)
- test(`Date.prototype.setUTCFullYear.length`, 3)
- })
-}
-
-func TestDate_setTime(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- test(`
- var abc = new Date(1999, 6, 1);
- var def = new Date();
- def.setTime(abc.getTime());
- [ def, abc.valueOf() == def.valueOf() ];
- `, "Thu, 01 Jul 1999 00:00:00 UTC,true")
-
- test(`Date.prototype.setTime.length`, 1)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/dbg/dbg.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/dbg/dbg.go
index 83bf6c573..8c27fa293 100644
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/dbg/dbg.go
+++ b/Godeps/_workspace/src/github.com/robertkrimen/otto/dbg/dbg.go
@@ -282,7 +282,7 @@ func (self *Dbgr) getEmit() _emit {
// SetOutput will accept the following as a destination for output:
//
// *log.Logger Print*/Panic*/Fatal* of the logger
-// io.Writer -
+// io.Writer -
// nil Reset to the default output (os.Stderr)
// "log" Print*/Panic*/Fatal* via the "log" package
//
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/documentation_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/documentation_test.go
deleted file mode 100644
index 04646117f..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/documentation_test.go
+++ /dev/null
@@ -1,95 +0,0 @@
-package otto
-
-import (
- "fmt"
-)
-
-func ExampleSynopsis() {
-
- vm := New()
- vm.Run(`
- abc = 2 + 2;
- console.log("The value of abc is " + abc); // 4
- `)
-
- value, _ := vm.Get("abc")
- {
- value, _ := value.ToInteger()
- fmt.Println(value)
- }
-
- vm.Set("def", 11)
- vm.Run(`
- console.log("The value of def is " + def);
- `)
-
- vm.Set("xyzzy", "Nothing happens.")
- vm.Run(`
- console.log(xyzzy.length);
- `)
-
- value, _ = vm.Run("xyzzy.length")
- {
- value, _ := value.ToInteger()
- fmt.Println(value)
- }
-
- value, err := vm.Run("abcdefghijlmnopqrstuvwxyz.length")
- fmt.Println(value)
- fmt.Println(err)
-
- vm.Set("sayHello", func(call FunctionCall) Value {
- fmt.Printf("Hello, %s.\n", call.Argument(0).String())
- return UndefinedValue()
- })
-
- vm.Set("twoPlus", func(call FunctionCall) Value {
- right, _ := call.Argument(0).ToInteger()
- result, _ := vm.ToValue(2 + right)
- return result
- })
-
- value, _ = vm.Run(`
- sayHello("Xyzzy");
- sayHello();
-
- result = twoPlus(2.0);
- `)
- fmt.Println(value)
-
- // Output:
- // The value of abc is 4
- // 4
- // The value of def is 11
- // 16
- // 16
- // undefined
- // ReferenceError: 'abcdefghijlmnopqrstuvwxyz' is not defined
- // Hello, Xyzzy.
- // Hello, undefined.
- // 4
-}
-
-func ExampleConsole() {
-
- vm := New()
- console := map[string]interface{}{
- "log": func(call FunctionCall) Value {
- fmt.Println("console.log:", formatForConsole(call.ArgumentList))
- return UndefinedValue()
- },
- }
-
- err := vm.Set("console", console)
-
- value, err := vm.Run(`
- console.log("Hello, World.");
- `)
- fmt.Println(value)
- fmt.Println(err)
-
- // Output:
- // console.log: Hello, World.
- // undefined
- // <nil>
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/error_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/error_test.go
deleted file mode 100644
index 7f1b16af7..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/error_test.go
+++ /dev/null
@@ -1,192 +0,0 @@
-package otto
-
-import (
- "testing"
-)
-
-func TestError(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- [ Error.prototype.name, Error.prototype.message, Error.prototype.hasOwnProperty("message") ];
- `, "Error,,true")
- })
-}
-
-func TestError_instanceof(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`(new TypeError()) instanceof Error`, true)
- })
-}
-
-func TestPanicValue(t *testing.T) {
- tt(t, func() {
- test, vm := test()
-
- vm.Set("abc", func(call FunctionCall) Value {
- value, err := call.Otto.Run(`({ def: 3.14159 })`)
- is(err, nil)
- panic(value)
- })
-
- test(`
- try {
- abc();
- }
- catch (err) {
- error = err;
- }
- [ error instanceof Error, error.message, error.def ];
- `, "false,,3.14159")
- })
-}
-
-func Test_catchPanic(t *testing.T) {
- tt(t, func() {
- vm := New()
-
- _, err := vm.Run(`
- A syntax error that
- does not define
- var;
- abc;
- `)
- is(err, "!=", nil)
-
- _, err = vm.Call(`abc.def`, nil)
- is(err, "!=", nil)
- })
-}
-
-func TestErrorContext(t *testing.T) {
- tt(t, func() {
- vm := New()
-
- _, err := vm.Run(`
- undefined();
- `)
- {
- err := err.(*Error)
- is(err.message, "'undefined' is not a function")
- is(len(err.trace), 1)
- is(err.trace[0].location(), "<anonymous>:2:13")
- }
-
- _, err = vm.Run(`
- ({}).abc();
- `)
- {
- err := err.(*Error)
- is(err.message, "'abc' is not a function")
- is(len(err.trace), 1)
- is(err.trace[0].location(), "<anonymous>:2:14")
- }
-
- _, err = vm.Run(`
- ("abc").abc();
- `)
- {
- err := err.(*Error)
- is(err.message, "'abc' is not a function")
- is(len(err.trace), 1)
- is(err.trace[0].location(), "<anonymous>:2:14")
- }
-
- _, err = vm.Run(`
- var ghi = "ghi";
- ghi();
- `)
- {
- err := err.(*Error)
- is(err.message, "'ghi' is not a function")
- is(len(err.trace), 1)
- is(err.trace[0].location(), "<anonymous>:3:13")
- }
-
- _, err = vm.Run(`
- function def() {
- undefined();
- }
- function abc() {
- def();
- }
- abc();
- `)
- {
- err := err.(*Error)
- is(err.message, "'undefined' is not a function")
- is(len(err.trace), 3)
- is(err.trace[0].location(), "def (<anonymous>:3:17)")
- is(err.trace[1].location(), "abc (<anonymous>:6:17)")
- is(err.trace[2].location(), "<anonymous>:8:13")
- }
-
- _, err = vm.Run(`
- function abc() {
- xyz();
- }
- abc();
- `)
- {
- err := err.(*Error)
- is(err.message, "'xyz' is not defined")
- is(len(err.trace), 2)
- is(err.trace[0].location(), "abc (<anonymous>:3:17)")
- is(err.trace[1].location(), "<anonymous>:5:13")
- }
-
- _, err = vm.Run(`
- mno + 1;
- `)
- {
- err := err.(*Error)
- is(err.message, "'mno' is not defined")
- is(len(err.trace), 1)
- is(err.trace[0].location(), "<anonymous>:2:13")
- }
-
- _, err = vm.Run(`
- eval("xyz();");
- `)
- {
- err := err.(*Error)
- is(err.message, "'xyz' is not defined")
- is(len(err.trace), 1)
- is(err.trace[0].location(), "<anonymous>:1:1")
- }
-
- _, err = vm.Run(`
- xyzzy = "Nothing happens."
- eval("xyzzy();");
- `)
- {
- err := err.(*Error)
- is(err.message, "'xyzzy' is not a function")
- is(len(err.trace), 1)
- is(err.trace[0].location(), "<anonymous>:1:1")
- }
-
- _, err = vm.Run(`
- throw Error("xyzzy");
- `)
- {
- err := err.(*Error)
- is(err.message, "xyzzy")
- is(len(err.trace), 1)
- is(err.trace[0].location(), "<anonymous>:2:19")
- }
-
- _, err = vm.Run(`
- throw new Error("xyzzy");
- `)
- {
- err := err.(*Error)
- is(err.message, "xyzzy")
- is(len(err.trace), 1)
- is(err.trace[0].location(), "<anonymous>:2:23")
- }
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/function_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/function_test.go
deleted file mode 100644
index c10bf8592..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/function_test.go
+++ /dev/null
@@ -1,280 +0,0 @@
-package otto
-
-import (
- "testing"
-)
-
-func TestFunction(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc = Object.getOwnPropertyDescriptor(Function, "prototype");
- [ [ typeof Function.prototype, typeof Function.prototype.length, Function.prototype.length ],
- [ abc.writable, abc.enumerable, abc.configurable ] ];
- `, "function,number,0,false,false,false")
- })
-}
-
-func Test_argumentList2parameterList(t *testing.T) {
- tt(t, func() {
- is(argumentList2parameterList([]Value{toValue("abc, def"), toValue("ghi")}), []string{"abc", "def", "ghi"})
- })
-}
-
-func TestFunction_new(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`raise:
- new Function({});
- `, "SyntaxError: Unexpected identifier")
-
- test(`
- var abc = Function("def, ghi", "jkl", "return def+ghi+jkl");
- [ typeof abc, abc instanceof Function, abc("ab", "ba", 1) ];
- `, "function,true,abba1")
-
- test(`raise:
- var abc = {
- toString: function() { throw 1; }
- };
- var def = {
- toString: function() { throw 2; }
- };
- var ghi = new Function(abc, def);
- ghi;
- `, "1")
-
- // S15.3.2.1_A3_T10
- test(`raise:
- var abc = {
- toString: function() { return "z;x"; }
- };
- var def = "return this";
- var ghi = new Function(abc, def);
- ghi;
- `, "SyntaxError: Unexpected token ;")
-
- test(`raise:
- var abc;
- var def = "return true";
- var ghi = new Function(null, def);
- ghi;
- `, "SyntaxError: Unexpected token null")
- })
-}
-
-func TestFunction_apply(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Function.prototype.apply.length`, 2)
- test(`String.prototype.substring.apply("abc", [1, 11])`, "bc")
- })
-}
-
-func TestFunction_call(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Function.prototype.call.length`, 1)
- test(`String.prototype.substring.call("abc", 1, 11)`, "bc")
- })
-}
-
-func TestFunctionArguments(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- // Should not be able to delete arguments
- test(`
- function abc(def, arguments){
- delete def;
- return def;
- }
- abc(1);
- `, 1)
-
- // Again, should not be able to delete arguments
- test(`
- function abc(def){
- delete def;
- return def;
- }
- abc(1);
- `, 1)
-
- // Test typeof of a function argument
- test(`
- function abc(def, ghi, jkl){
- return typeof jkl
- }
- abc("1st", "2nd", "3rd", "4th", "5th");
- `, "string")
-
- test(`
- function abc(def, ghi, jkl){
- arguments[0] = 3.14;
- arguments[1] = 'Nothing happens';
- arguments[2] = 42;
- if (3.14 === def && 'Nothing happens' === ghi && 42 === jkl)
- return true;
- }
- abc(-1, 4.2, 314);
- `, true)
- })
-}
-
-func TestFunctionDeclarationInFunction(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- // Function declarations happen AFTER parameter/argument declarations
- // That is, a function declared within a function will shadow/overwrite
- // declared parameters
-
- test(`
- function abc(def){
- return def;
- function def(){
- return 1;
- }
- }
- typeof abc();
- `, "function")
- })
-}
-
-func TestArguments_defineOwnProperty(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc;
- var def = true;
- var ghi = {};
- (function (a, b, c) {
- Object.defineProperty(arguments, "0", {
- value: 42,
- writable: false,
- enumerable: false,
- configurable: false
- });
- Object.defineProperty(arguments, "1", {
- value: 3.14,
- configurable: true,
- enumerable: true
- });
- abc = Object.getOwnPropertyDescriptor(arguments, "0");
- for (var name in arguments) {
- ghi[name] = (ghi[name] || 0) + 1;
- if (name === "0") {
- def = false;
- }
- }
- }(0, 1, 2));
- [ abc.value, abc.writable, abc.enumerable, abc.configurable, def, ghi["1"] ];
- `, "42,false,false,false,true,1")
- })
-}
-
-func TestFunction_bind(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- test(`
- abc = function(){
- return "abc";
- };
- def = abc.bind();
- [ typeof def.prototype, typeof def.hasOwnProperty, def.hasOwnProperty("caller"), def.hasOwnProperty("arguments"), def() ];
- `, "object,function,true,true,abc")
-
- test(`
- abc = function(){
- return arguments[1];
- };
- def = abc.bind(undefined, "abc");
- ghi = abc.bind(undefined, "abc", "ghi");
- [ def(), def("def"), ghi("def") ];
- `, ",def,ghi")
-
- test(`
- var abc = function () {};
- var ghi;
- try {
- Object.defineProperty(Function.prototype, "xyzzy", {
- value: 1001,
- writable: true,
- enumerable: true,
- configurable: true
- });
- var def = abc.bind({});
- ghi = !def.hasOwnProperty("xyzzy") && ghi.xyzzy === 1001;
- } finally {
- delete Function.prototype.xyzzy;
- }
- [ ghi ];
- `, "true")
-
- test(`
- var abc = function (def, ghi) {};
- var jkl = abc.bind({});
- var mno = abc.bind({}, 1, 2);
- [ jkl.length, mno.length ];
- `, "2,0")
-
- test(`raise:
- Math.bind();
- `, "TypeError: 'bind' is not a function")
-
- test(`
- function construct(fn, arguments) {
- var bound = Function.prototype.bind.apply(fn, [null].concat(arguments));
- return new bound();
- }
- var abc = construct(Date, [1957, 4, 27]);
- Object.prototype.toString.call(abc);
- `, "[object Date]")
-
- test(`
- var fn = function (x, y, z) {
- var result = {};
- result.abc = x + y + z;
- result.def = arguments[0] === "a" && arguments.length === 3;
- return result;
- };
- var newFn = Function.prototype.bind.call(fn, {}, "a", "b", "c");
- var result = new newFn();
- [ result.hasOwnProperty("abc"), result.hasOwnProperty("def"), result.abc, result.def ];
- `, "true,true,abc,true")
-
- test(`
- abc = function(){
- return "abc";
- };
- def = abc.bind();
- def.toString();
- `, "function () { [native code] }")
- })
-}
-
-func TestFunction_toString(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`raise:
- Function.prototype.toString.call(undefined);
- `, "TypeError")
-
- test(`
- abc = function() { return -1 ;
-}
- 1;
- abc.toString();
- `, "function() { return -1 ;\n}")
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/global_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/global_test.go
deleted file mode 100644
index 9257b58c3..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/global_test.go
+++ /dev/null
@@ -1,355 +0,0 @@
-package otto
-
-import (
- "fmt"
- "math"
- "strings"
- "testing"
-)
-
-func TestGlobal(t *testing.T) {
- tt(t, func() {
- test, vm := test()
-
- runtime := vm.vm.runtime
-
- {
- call := func(object interface{}, src string, argumentList ...interface{}) Value {
- var tgt *Object
- switch object := object.(type) {
- case Value:
- tgt = object.Object()
- case *Object:
- tgt = object
- case *_object:
- tgt = toValue_object(object).Object()
- default:
- panic("Here be dragons.")
- }
- value, err := tgt.Call(src, argumentList...)
- is(err, nil)
- return value
- }
-
- // FIXME enterGlobalScope
- if false {
- value := runtime.scope.lexical.getBinding("Object", false)._object().call(UndefinedValue(), []Value{toValue(runtime.newObject())}, false, nativeFrame)
- is(value.IsObject(), true)
- is(value, "[object Object]")
- is(value._object().prototype == runtime.global.ObjectPrototype, true)
- is(value._object().prototype == runtime.global.Object.get("prototype")._object(), true)
- is(value._object().get("toString"), "function toString() { [native code] }")
- is(call(value.Object(), "hasOwnProperty", "hasOwnProperty"), false)
-
- is(call(value._object().get("toString")._object().prototype, "toString"), "function () { [native code] }") // TODO Is this right?
- is(value._object().get("toString")._object().get("toString"), "function toString() { [native code] }")
- is(value._object().get("toString")._object().get("toString")._object(), "function toString() { [native code] }")
-
- is(call(value._object(), "propertyIsEnumerable", "isPrototypeOf"), false)
- value._object().put("xyzzy", toValue_string("Nothing happens."), false)
- is(call(value, "propertyIsEnumerable", "isPrototypeOf"), false)
- is(call(value, "propertyIsEnumerable", "xyzzy"), true)
- is(value._object().get("xyzzy"), "Nothing happens.")
-
- is(call(runtime.scope.lexical.getBinding("Object", false), "isPrototypeOf", value), false)
- is(call(runtime.scope.lexical.getBinding("Object", false)._object().get("prototype"), "isPrototypeOf", value), true)
- is(call(runtime.scope.lexical.getBinding("Function", false), "isPrototypeOf", value), false)
-
- is(runtime.newObject().prototype == runtime.global.Object.get("prototype")._object(), true)
-
- abc := runtime.newBoolean(toValue_bool(true))
- is(toValue_object(abc), "true") // TODO Call primitive?
-
- //def := runtime.localGet("Boolean")._object().Construct(UndefinedValue(), []Value{})
- //is(def, "false") // TODO Call primitive?
- }
- }
-
- test(`new Number().constructor == Number`, true)
-
- test(`this.hasOwnProperty`, "function hasOwnProperty() { [native code] }")
-
- test(`eval.length === 1`, true)
- test(`eval.prototype === undefined`, true)
- test(`raise: new eval()`, "TypeError: function eval() { [native code] } is not a constructor")
-
- test(`
- [
- [ delete undefined, undefined ],
- [ delete NaN, NaN ],
- [ delete Infinity, Infinity ],
- ];
- `, "false,,false,NaN,false,Infinity")
-
- test(`
- Object.getOwnPropertyNames(Function('return this')()).sort();
- `, "Array,Boolean,Date,Error,EvalError,Function,Infinity,JSON,Math,NaN,Number,Object,RangeError,ReferenceError,RegExp,String,SyntaxError,TypeError,URIError,console,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,escape,eval,isFinite,isNaN,parseFloat,parseInt,undefined,unescape")
-
- // __defineGetter__,__defineSetter__,__lookupGetter__,__lookupSetter__,constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf
- test(`
- Object.getOwnPropertyNames(Object.prototype).sort();
- `, "constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf")
-
- // arguments,caller,length,name,prototype
- test(`
- Object.getOwnPropertyNames(EvalError).sort();
- `, "length,prototype")
-
- test(`
- var abc = [];
- var def = [EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError];
- for (constructor in def) {
- abc.push(def[constructor] === def[constructor].prototype.constructor);
- }
- def = [Array, Boolean, Date, Function, Number, Object, RegExp, String, SyntaxError];
- for (constructor in def) {
- abc.push(def[constructor] === def[constructor].prototype.constructor);
- }
- abc;
- `, "true,true,true,true,true,true,true,true,true,true,true,true,true,true,true")
-
- test(`
- [ Array.prototype.constructor === Array, Array.constructor === Function ];
- `, "true,true")
-
- test(`
- [ Number.prototype.constructor === Number, Number.constructor === Function ];
- `, "true,true")
-
- test(`
- [ Function.prototype.constructor === Function, Function.constructor === Function ];
- `, "true,true")
- })
-}
-
-func TestGlobalLength(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- [ Object.length, Function.length, RegExp.length, Math.length ];
- `, "1,1,2,")
- })
-}
-
-func TestGlobalError(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- [ TypeError.length, TypeError(), TypeError("Nothing happens.") ];
- `, "1,TypeError,TypeError: Nothing happens.")
-
- test(`
- [ URIError.length, URIError(), URIError("Nothing happens.") ];
- `, "1,URIError,URIError: Nothing happens.")
- })
-}
-
-func TestGlobalReadOnly(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Number.POSITIVE_INFINITY`, math.Inf(1))
-
- test(`
- Number.POSITIVE_INFINITY = 1;
- `, 1)
-
- test(`Number.POSITIVE_INFINITY`, math.Inf(1))
-
- test(`
- Number.POSITIVE_INFINITY = 1;
- Number.POSITIVE_INFINITY;
- `, math.Inf(1))
- })
-}
-
-func Test_isNaN(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`isNaN(0)`, false)
- test(`isNaN("Xyzzy")`, true)
- test(`isNaN()`, true)
- test(`isNaN(NaN)`, true)
- test(`isNaN(Infinity)`, false)
-
- test(`isNaN.length === 1`, true)
- test(`isNaN.prototype === undefined`, true)
- })
-}
-
-func Test_isFinite(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`isFinite(0)`, true)
- test(`isFinite("Xyzzy")`, false)
- test(`isFinite()`, false)
- test(`isFinite(NaN)`, false)
- test(`isFinite(Infinity)`, false)
- test(`isFinite(new Number(451));`, true)
-
- test(`isFinite.length === 1`, true)
- test(`isFinite.prototype === undefined`, true)
- })
-}
-
-func Test_parseInt(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`parseInt("0")`, 0)
- test(`parseInt("11")`, 11)
- test(`parseInt(" 11")`, 11)
- test(`parseInt("11 ")`, 11)
- test(`parseInt(" 11 ")`, 11)
- test(`parseInt(" 11\n")`, 11)
- test(`parseInt(" 11\n", 16)`, 17)
-
- test(`parseInt("Xyzzy")`, _NaN)
-
- test(`parseInt(" 0x11\n", 16)`, 17)
- test(`parseInt("0x0aXyzzy", 16)`, 10)
- test(`parseInt("0x1", 0)`, 1)
- test(`parseInt("0x10000000000000000000", 16)`, float64(75557863725914323419136))
-
- test(`parseInt.length === 2`, true)
- test(`parseInt.prototype === undefined`, true)
- })
-}
-
-func Test_parseFloat(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`parseFloat("0")`, 0)
- test(`parseFloat("11")`, 11)
- test(`parseFloat(" 11")`, 11)
- test(`parseFloat("11 ")`, 11)
- test(`parseFloat(" 11 ")`, 11)
- test(`parseFloat(" 11\n")`, 11)
- test(`parseFloat(" 11\n", 16)`, 11)
- test(`parseFloat("11.1")`, 11.1)
-
- test(`parseFloat("Xyzzy")`, _NaN)
-
- test(`parseFloat(" 0x11\n", 16)`, 0)
- test(`parseFloat("0x0a")`, 0)
- test(`parseFloat("0x0aXyzzy")`, 0)
- test(`parseFloat("Infinity")`, _Infinity)
- test(`parseFloat("infinity")`, _NaN)
- test(`parseFloat("0x")`, 0)
- test(`parseFloat("11x")`, 11)
- test(`parseFloat("Infinity1")`, _Infinity)
-
- test(`parseFloat.length === 1`, true)
- test(`parseFloat.prototype === undefined`, true)
- })
-}
-
-func Test_encodeURI(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`encodeURI("http://example.com/ Nothing happens.")`, "http://example.com/%20Nothing%20happens.")
- test(`encodeURI("http://example.com/ _^#")`, "http://example.com/%20_%5E#")
- test(`encodeURI(String.fromCharCode("0xE000"))`, "%EE%80%80")
- test(`encodeURI(String.fromCharCode("0xFFFD"))`, "%EF%BF%BD")
- test(`raise: encodeURI(String.fromCharCode("0xDC00"))`, "URIError: URI malformed")
-
- test(`encodeURI.length === 1`, true)
- test(`encodeURI.prototype === undefined`, true)
- })
-}
-
-func Test_encodeURIComponent(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`encodeURIComponent("http://example.com/ Nothing happens.")`, "http%3A%2F%2Fexample.com%2F%20Nothing%20happens.")
- test(`encodeURIComponent("http://example.com/ _^#")`, "http%3A%2F%2Fexample.com%2F%20_%5E%23")
- })
-}
-
-func Test_decodeURI(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`decodeURI(encodeURI("http://example.com/ Nothing happens."))`, "http://example.com/ Nothing happens.")
- test(`decodeURI(encodeURI("http://example.com/ _^#"))`, "http://example.com/ _^#")
- test(`raise: decodeURI("http://example.com/ _^#%")`, "URIError: URI malformed")
- test(`raise: decodeURI("%DF%7F")`, "URIError: URI malformed")
- for _, check := range strings.Fields("+ %3B %2F %3F %3A %40 %26 %3D %2B %24 %2C %23") {
- test(fmt.Sprintf(`decodeURI("%s")`, check), check)
- }
-
- test(`decodeURI.length === 1`, true)
- test(`decodeURI.prototype === undefined`, true)
- })
-}
-
-func Test_decodeURIComponent(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`decodeURIComponent(encodeURI("http://example.com/ Nothing happens."))`, "http://example.com/ Nothing happens.")
- test(`decodeURIComponent(encodeURI("http://example.com/ _^#"))`, "http://example.com/ _^#")
-
- test(`decodeURIComponent.length === 1`, true)
- test(`decodeURIComponent.prototype === undefined`, true)
-
- test(`
- var global = Function('return this')();
- var abc = Object.getOwnPropertyDescriptor(global, "decodeURIComponent");
- [ abc.value === global.decodeURIComponent, abc.writable, abc.enumerable, abc.configurable ];
- `, "true,true,false,true")
- })
-}
-
-func TestGlobal_skipEnumeration(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var found = [];
- for (var test in this) {
- if (false ||
- test === 'NaN' ||
- test === 'undefined' ||
- test === 'Infinity' ||
- false) {
- found.push(test)
- }
- }
- found.length;
- `, 0)
-
- test(`
- var found = [];
- for (var test in this) {
- if (false ||
- test === 'Object' ||
- test === 'Function' ||
- test === 'String' ||
- test === 'Number' ||
- test === 'Array' ||
- test === 'Boolean' ||
- test === 'Date' ||
- test === 'RegExp' ||
- test === 'Error' ||
- test === 'EvalError' ||
- test === 'RangeError' ||
- test === 'ReferenceError' ||
- test === 'SyntaxError' ||
- test === 'TypeError' ||
- test === 'URIError' ||
- false) {
- found.push(test)
- }
- }
- found.length;
- `, 0)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/json_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/json_test.go
deleted file mode 100644
index 4dd2ed7bf..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/json_test.go
+++ /dev/null
@@ -1,183 +0,0 @@
-package otto
-
-import (
- "testing"
-)
-
-func BenchmarkJSON_parse(b *testing.B) {
- vm := New()
- for i := 0; i < b.N; i++ {
- vm.Run(`JSON.parse("1")`)
- vm.Run(`JSON.parse("[1,2,3]")`)
- vm.Run(`JSON.parse('{"a":{"x":100,"y":110},"b":[10,20,30],"c":"zazazaza"}')`)
- vm.Run(`JSON.parse("[1,2,3]", function(k, v) { return undefined })`)
- }
-}
-
-func TestJSON_parse(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- JSON.parse("1");
- `, 1)
-
- test(`
- JSON.parse("null");
- `, "null") // TODO Can we make this nil?
-
- test(`
- var abc = JSON.parse('"a\uFFFFbc"');
- [ abc[0], abc[2], abc[3], abc.length ];
- `, "a,b,c,4")
-
- test(`
- JSON.parse("[1, 2, 3]");
- `, "1,2,3")
-
- test(`
- JSON.parse('{ "abc": 1, "def":2 }').abc;
- `, 1)
-
- test(`
- JSON.parse('{ "abc": { "x": 100, "y": 110 }, "def": [ 10, 20 ,30 ], "ghi": "zazazaza" }').def;
- `, "10,20,30")
-
- test(`raise:
- JSON.parse("12\t\r\n 34");
- `, "SyntaxError: invalid character '3' after top-level value")
-
- test(`
- JSON.parse("[1, 2, 3]", function() { return undefined });
- `, "undefined")
-
- test(`raise:
- JSON.parse("");
- `, "SyntaxError: unexpected end of JSON input")
-
- test(`raise:
- JSON.parse("[1, 2, 3");
- `, "SyntaxError: unexpected end of JSON input")
-
- test(`raise:
- JSON.parse("[1, 2, ; abc=10");
- `, "SyntaxError: invalid character ';' looking for beginning of value")
-
- test(`raise:
- JSON.parse("[1, 2, function(){}]");
- `, "SyntaxError: invalid character 'u' in literal false (expecting 'a')")
- })
-}
-
-func TestJSON_stringify(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- defer mockUTC()()
-
- test(`
- JSON.stringify(function(){});
- `, "undefined")
-
- test(`
- JSON.stringify(new Boolean(false));
- `, "false")
-
- test(`
- JSON.stringify({a1: {b1: [1,2,3,4], b2: {c1: 1, c2: 2}}, a2: 'a2'}, null, -5);
- `, `{"a1":{"b1":[1,2,3,4],"b2":{"c1":1,"c2":2}},"a2":"a2"}`)
-
- test(`
- JSON.stringify(undefined);
- `, "undefined")
-
- test(`
- JSON.stringify(1);
- `, "1")
-
- test(`
- JSON.stringify("abc def");
- `, "\"abc def\"")
-
- test(`
- JSON.stringify(3.14159);
- `, "3.14159")
-
- test(`
- JSON.stringify([]);
- `, "[]")
-
- test(`
- JSON.stringify([1, 2, 3]);
- `, "[1,2,3]")
-
- test(`
- JSON.stringify([true, false, null]);
- `, "[true,false,null]")
-
- test(`
- JSON.stringify({
- abc: { x: 100, y: 110 },
- def: [ 10, 20, 30 ],
- ghi: "zazazaza"
- });
- `, `{"abc":{"x":100,"y":110},"def":[10,20,30],"ghi":"zazazaza"}`)
-
- test(`
- JSON.stringify([
- 'e',
- {pluribus: 'unum'}
- ], null, '\t');
- `, "[\n\t\"e\",\n\t{\n\t\t\"pluribus\": \"unum\"\n\t}\n]")
-
- test(`
- JSON.stringify(new Date(0));
- `, `"1970-01-01T00:00:00.000Z"`)
-
- test(`
- JSON.stringify([ new Date(0) ], function(key, value){
- return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value
- });
- `, `["Date(Thu, 01 Jan 1970 00:00:00 UTC)"]`)
-
- test(`
- JSON.stringify({
- abc: 1,
- def: 2,
- ghi: 3
- }, ['abc','def']);
- `, `{"abc":1,"def":2}`)
-
- test(`raise:
- var abc = {
- def: null
- };
- abc.def = abc;
- JSON.stringify(abc)
- `, "TypeError: Converting circular structure to JSON")
-
- test(`raise:
- var abc= [ null ];
- abc[0] = abc;
- JSON.stringify(abc);
- `, "TypeError: Converting circular structure to JSON")
-
- test(`raise:
- var abc = {
- def: {}
- };
- abc.def.ghi = abc;
- JSON.stringify(abc)
- `, "TypeError: Converting circular structure to JSON")
-
- test(`
- var ghi = { "pi": 3.14159 };
- var abc = {
- def: {}
- };
- abc.ghi = ghi;
- abc.def.ghi = ghi;
- JSON.stringify(abc);
- `, `{"def":{"ghi":{"pi":3.14159}},"ghi":{"pi":3.14159}}`)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/math_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/math_test.go
deleted file mode 100644
index 499998b14..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/math_test.go
+++ /dev/null
@@ -1,303 +0,0 @@
-package otto
-
-import (
- "math"
- "testing"
-)
-
-var _NaN = math.NaN()
-var _Infinity = math.Inf(1)
-
-func TestMath_toString(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Math.toString()`, "[object Math]")
- })
-}
-
-func TestMath_abs(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Math.abs(NaN)`, _NaN)
- test(`Math.abs(2)`, 2)
- test(`Math.abs(-2)`, 2)
- test(`Math.abs(-Infinity)`, _Infinity)
-
- test(`Math.acos(0.5)`, 1.0471975511965976)
-
- test(`Math.abs('-1')`, 1)
- test(`Math.abs(-2)`, 2)
- test(`Math.abs(null)`, 0)
- test(`Math.abs("string")`, _NaN)
- test(`Math.abs()`, _NaN)
- })
-}
-
-func TestMath_acos(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Math.acos(NaN)`, _NaN)
- test(`Math.acos(2)`, _NaN)
- test(`Math.acos(-2)`, _NaN)
- test(`1/Math.acos(1)`, _Infinity)
-
- test(`Math.acos(0.5)`, 1.0471975511965976)
- })
-}
-
-func TestMath_asin(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Math.asin(NaN)`, _NaN)
- test(`Math.asin(2)`, _NaN)
- test(`Math.asin(-2)`, _NaN)
- test(`1/Math.asin(0)`, _Infinity)
- test(`1/Math.asin(-0)`, -_Infinity)
-
- test(`Math.asin(0.5)`, 0.5235987755982989)
- })
-}
-
-func TestMath_atan(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Math.atan(NaN)`, _NaN)
- test(`1/Math.atan(0)`, _Infinity)
- test(`1/Math.atan(-0)`, -_Infinity)
- test(`Math.atan(Infinity)`, 1.5707963267948966)
- test(`Math.atan(-Infinity)`, -1.5707963267948966)
-
- // freebsd/386 1.03 => 0.4636476090008061
- // darwin 1.03 => 0.46364760900080604
- test(`Math.atan(0.5).toPrecision(10)`, "0.463647609")
- })
-}
-
-func TestMath_atan2(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Math.atan2()`, _NaN)
- test(`Math.atan2(NaN)`, _NaN)
- test(`Math.atan2(0, NaN)`, _NaN)
-
- test(`Math.atan2(1, 0)`, 1.5707963267948966)
- test(`Math.atan2(1, -0)`, 1.5707963267948966)
-
- test(`1/Math.atan2(0, 1)`, _Infinity)
- test(`1/Math.atan2(0, 0)`, _Infinity)
- test(`Math.atan2(0, -0)`, 3.141592653589793)
- test(`Math.atan2(0, -1)`, 3.141592653589793)
-
- test(`1/Math.atan2(-0, 1)`, -_Infinity)
- test(`1/Math.atan2(-0, 0)`, -_Infinity)
- test(`Math.atan2(-0, -0)`, -3.141592653589793)
- test(`Math.atan2(-0, -1)`, -3.141592653589793)
-
- test(`Math.atan2(-1, 0)`, -1.5707963267948966)
- test(`Math.atan2(-1, -0)`, -1.5707963267948966)
-
- test(`1/Math.atan2(1, Infinity)`, _Infinity)
- test(`Math.atan2(1, -Infinity)`, 3.141592653589793)
- test(`1/Math.atan2(-1, Infinity)`, -_Infinity)
- test(`Math.atan2(-1, -Infinity)`, -3.141592653589793)
-
- test(`Math.atan2(Infinity, 1)`, 1.5707963267948966)
- test(`Math.atan2(-Infinity, 1)`, -1.5707963267948966)
-
- test(`Math.atan2(Infinity, Infinity)`, 0.7853981633974483)
- test(`Math.atan2(Infinity, -Infinity)`, 2.356194490192345)
- test(`Math.atan2(-Infinity, Infinity)`, -0.7853981633974483)
- test(`Math.atan2(-Infinity, -Infinity)`, -2.356194490192345)
- })
-}
-
-func TestMath_ceil(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Math.ceil(NaN)`, _NaN)
- test(`Math.ceil(+0)`, 0)
- test(`1/Math.ceil(-0)`, -_Infinity)
- test(`Math.ceil(Infinity)`, _Infinity)
- test(`Math.ceil(-Infinity)`, -_Infinity)
- test(`1/Math.ceil(-0.5)`, -_Infinity)
-
- test(`Math.ceil(-11)`, -11)
- test(`Math.ceil(-0.5)`, 0)
- test(`Math.ceil(1.5)`, 2)
- })
-}
-
-func TestMath_cos(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Math.cos(NaN)`, _NaN)
- test(`Math.cos(+0)`, 1)
- test(`Math.cos(-0)`, 1)
- test(`Math.cos(Infinity)`, _NaN)
- test(`Math.cos(-Infinity)`, _NaN)
-
- test(`Math.cos(0.5)`, 0.8775825618903728)
- })
-}
-
-func TestMath_exp(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Math.exp(NaN)`, _NaN)
- test(`Math.exp(+0)`, 1)
- test(`Math.exp(-0)`, 1)
- test(`Math.exp(Infinity)`, _Infinity)
- test(`Math.exp(-Infinity)`, 0)
- })
-}
-
-func TestMath_floor(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Math.floor(NaN)`, _NaN)
- test(`Math.floor(+0)`, 0)
- test(`1/Math.floor(-0)`, -_Infinity)
- test(`Math.floor(Infinity)`, _Infinity)
- test(`Math.floor(-Infinity)`, -_Infinity)
-
- test(`Math.floor(-11)`, -11)
- test(`Math.floor(-0.5)`, -1)
- test(`Math.floor(1.5)`, 1)
- })
-}
-
-func TestMath_log(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Math.log(NaN)`, _NaN)
- test(`Math.log(-1)`, _NaN)
- test(`Math.log(+0)`, -_Infinity)
- test(`Math.log(-0)`, -_Infinity)
- test(`1/Math.log(1)`, _Infinity)
- test(`Math.log(Infinity)`, _Infinity)
-
- test(`Math.log(0.5)`, -0.6931471805599453)
- })
-}
-
-func TestMath_max(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Math.max(-11, -1, 0, 1, 2, 3, 11)`, 11)
- })
-}
-
-func TestMath_min(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Math.min(-11, -1, 0, 1, 2, 3, 11)`, -11)
- })
-}
-
-func TestMath_pow(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Math.pow(0, NaN)`, _NaN)
- test(`Math.pow(0, 0)`, 1)
- test(`Math.pow(NaN, 0)`, 1)
- test(`Math.pow(0, -0)`, 1)
- test(`Math.pow(NaN, -0)`, 1)
- test(`Math.pow(NaN, 1)`, _NaN)
- test(`Math.pow(2, Infinity)`, _Infinity)
- test(`1/Math.pow(2, -Infinity)`, _Infinity)
- test(`Math.pow(1, Infinity)`, _NaN)
- test(`Math.pow(1, -Infinity)`, _NaN)
- test(`1/Math.pow(0.1, Infinity)`, _Infinity)
- test(`Math.pow(0.1, -Infinity)`, _Infinity)
- test(`Math.pow(Infinity, 1)`, _Infinity)
- test(`1/Math.pow(Infinity, -1)`, _Infinity)
- test(`Math.pow(-Infinity, 1)`, -_Infinity)
- test(`Math.pow(-Infinity, 2)`, _Infinity)
- test(`1/Math.pow(-Infinity, -1)`, -_Infinity)
- test(`1/Math.pow(-Infinity, -2)`, _Infinity)
- test(`1/Math.pow(0, 1)`, _Infinity)
- test(`Math.pow(0, -1)`, _Infinity)
- test(`1/Math.pow(-0, 1)`, -_Infinity)
- test(`1/Math.pow(-0, 2)`, _Infinity)
- test(`Math.pow(-0, -1)`, -_Infinity)
- test(`Math.pow(-0, -2)`, _Infinity)
- test(`Math.pow(-1, 0.1)`, _NaN)
-
- test(`
- [ Math.pow(-1, +Infinity), Math.pow(1, Infinity) ];
- `, "NaN,NaN")
- })
-}
-
-func TestMath_round(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Math.round(NaN)`, _NaN)
- test(`1/Math.round(0)`, _Infinity)
- test(`1/Math.round(-0)`, -_Infinity)
- test(`Math.round(Infinity)`, _Infinity)
- test(`Math.round(-Infinity)`, -_Infinity)
- test(`1/Math.round(0.1)`, _Infinity)
- test(`1/Math.round(-0.1)`, -_Infinity)
-
- test(`Math.round(3.5)`, 4)
- test(`Math.round(-3.5)`, -3)
- })
-}
-
-func TestMath_sin(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Math.sin(NaN)`, _NaN)
- test(`1/Math.sin(+0)`, _Infinity)
- test(`1/Math.sin(-0)`, -_Infinity)
- test(`Math.sin(Infinity)`, _NaN)
- test(`Math.sin(-Infinity)`, _NaN)
-
- test(`Math.sin(0.5)`, 0.479425538604203)
- })
-}
-
-func TestMath_sqrt(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Math.sqrt(NaN)`, _NaN)
- test(`Math.sqrt(-1)`, _NaN)
- test(`1/Math.sqrt(+0)`, _Infinity)
- test(`1/Math.sqrt(-0)`, -_Infinity)
- test(`Math.sqrt(Infinity)`, _Infinity)
-
- test(`Math.sqrt(2)`, 1.4142135623730951)
- })
-}
-
-func TestMath_tan(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Math.tan(NaN)`, _NaN)
- test(`1/Math.tan(+0)`, _Infinity)
- test(`1/Math.tan(-0)`, -_Infinity)
- test(`Math.tan(Infinity)`, _NaN)
- test(`Math.tan(-Infinity)`, _NaN)
-
- test(`Math.tan(0.5)`, 0.5463024898437905)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/number_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/number_test.go
deleted file mode 100644
index 8db01cfc7..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/number_test.go
+++ /dev/null
@@ -1,165 +0,0 @@
-package otto
-
-import (
- "testing"
-)
-
-func TestNumber(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc = Object.getOwnPropertyDescriptor(Number, "prototype");
- [ [ typeof Number.prototype ],
- [ abc.writable, abc.enumerable, abc.configurable ] ];
- `, "object,false,false,false")
- })
-}
-
-func TestNumber_toString(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- new Number(451).toString();
- `, "451")
-
- test(`
- new Number(451).toString(10);
- `, "451")
-
- test(`
- new Number(451).toString(8);
- `, "703")
-
- test(`raise:
- new Number(451).toString(1);
- `, "RangeError: RangeError: toString() radix must be between 2 and 36")
-
- test(`raise:
- new Number(451).toString(Infinity);
- `, "RangeError: RangeError: toString() radix must be between 2 and 36")
-
- test(`
- new Number(NaN).toString()
- `, "NaN")
-
- test(`
- new Number(Infinity).toString()
- `, "Infinity")
-
- test(`
- new Number(Infinity).toString(16)
- `, "Infinity")
-
- test(`
- [
- Number.prototype.toString(undefined),
- new Number().toString(undefined),
- new Number(0).toString(undefined),
- new Number(-1).toString(undefined),
- new Number(1).toString(undefined),
- new Number(Number.NaN).toString(undefined),
- new Number(Number.POSITIVE_INFINITY).toString(undefined),
- new Number(Number.NEGATIVE_INFINITY).toString(undefined)
- ]
- `, "0,0,0,-1,1,NaN,Infinity,-Infinity")
- })
-}
-
-func TestNumber_toFixed(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`new Number(451).toFixed(2)`, "451.00")
- test(`12345.6789.toFixed()`, "12346")
- test(`12345.6789.toFixed(1)`, "12345.7")
- test(`12345.6789.toFixed(6)`, "12345.678900")
- test(`(1.23e-20).toFixed(2)`, "0.00")
- test(`2.34.toFixed(1)`, "2.3") // FIXME Wtf? "2.3"
- test(`-2.34.toFixed(1)`, -2.3) // FIXME Wtf? -2.3
- test(`(-2.34).toFixed(1)`, "-2.3")
-
- test(`raise:
- new Number("a").toFixed(Number.POSITIVE_INFINITY);
- `, "RangeError: toFixed() precision must be between 0 and 20")
-
- test(`
- [
- new Number(1e21).toFixed(),
- new Number(1e21).toFixed(0),
- new Number(1e21).toFixed(1),
- new Number(1e21).toFixed(1.1),
- new Number(1e21).toFixed(0.9),
- new Number(1e21).toFixed("1"),
- new Number(1e21).toFixed("1.1"),
- new Number(1e21).toFixed("0.9"),
- new Number(1e21).toFixed(Number.NaN),
- new Number(1e21).toFixed("some string")
- ];
- `, "1e+21,1e+21,1e+21,1e+21,1e+21,1e+21,1e+21,1e+21,1e+21,1e+21")
-
- test(`raise:
- new Number(1e21).toFixed(Number.POSITIVE_INFINITY);
- `, "RangeError: toFixed() precision must be between 0 and 20")
- })
-}
-
-func TestNumber_toExponential(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`new Number(451).toExponential(2)`, "4.51e+02")
- test(`77.1234.toExponential()`, "7.71234e+01")
- test(`77.1234.toExponential(4)`, "7.7123e+01")
- test(`77.1234.toExponential(2)`, "7.71e+01")
- test(`77 .toExponential()`, "7.7e+01")
- })
-}
-
-func TestNumber_toPrecision(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`new Number(451).toPrecision()`, "451")
- test(`new Number(451).toPrecision(1)`, "5e+02")
- test(`5.123456.toPrecision()`, "5.123456")
- test(`5.123456.toPrecision(5)`, "5.1235")
- test(`5.123456.toPrecision(2)`, "5.1")
- test(`5.123456.toPrecision(1)`, "5")
- })
-}
-
-func TestNumber_toLocaleString(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- [
- new Number(451).toLocaleString(),
- new Number(451).toLocaleString(10),
- new Number(451).toLocaleString(8)
- ];
- `, "451,451,703")
- })
-}
-
-func TestValue_number(t *testing.T) {
- tt(t, func() {
- nm := toValue(0.0).number()
- is(nm.kind, numberInteger)
-
- nm = toValue(3.14159).number()
- is(nm.kind, numberFloat)
- })
-}
-
-func Test_NaN(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- [ NaN === NaN, NaN == NaN ];
- `, "false,false")
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/object_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/object_test.go
deleted file mode 100644
index d1e90680b..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/object_test.go
+++ /dev/null
@@ -1,639 +0,0 @@
-package otto
-
-import (
- "testing"
-)
-
-func TestObject_(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- object := newObject(nil, "")
- is(object != nil, true)
-
- object.put("xyzzy", toValue("Nothing happens."), true)
- is(object.get("xyzzy"), "Nothing happens.")
-
- test(`
- var abc = Object.getOwnPropertyDescriptor(Object, "prototype");
- [ [ typeof Object.prototype, abc.writable, abc.enumerable, abc.configurable ],
- ];
- `, "object,false,false,false")
- })
-}
-
-func TestStringObject(t *testing.T) {
- tt(t, func() {
- object := New().runtime.newStringObject(toValue("xyzzy"))
- is(object.get("1"), "y")
- is(object.get("10"), "undefined")
- is(object.get("2"), "z")
- })
-}
-
-func TestObject_getPrototypeOf(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = {};
- def = Object.getPrototypeOf(abc);
- ghi = Object.getPrototypeOf(def);
- [abc,def,ghi,ghi+""];
- `, "[object Object],[object Object],,null")
-
- test(`
- abc = Object.getOwnPropertyDescriptor(Object, "getPrototypeOf");
- [ abc.value === Object.getPrototypeOf, abc.writable, abc.enumerable, abc.configurable ];
- `, "true,true,false,true")
- })
-}
-
-func TestObject_new(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- [ new Object("abc"), new Object(2+2) ];
- `, "abc,4")
- })
-}
-
-func TestObject_create(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`raise: Object.create()`, "TypeError")
-
- test(`
- var abc = Object.create(null)
- var def = Object.create({x: 10, y: 20})
- var ghi = Object.create(Object.prototype)
-
- var jkl = Object.create({x: 10, y: 20}, {
- z: {
- value: 30,
- writable: true
- },
- // sum: {
- // get: function() {
- // return this.x + this.y + this.z
- // }
- // }
- });
- [ abc.prototype, def.x, def.y, ghi, jkl.x, jkl.y, jkl.z ]
- `, ",10,20,[object Object],10,20,30")
-
- test(`
- var properties = {};
- Object.defineProperty(properties, "abc", {
- value: {},
- enumerable: false
- });
- var mno = Object.create({}, properties);
- mno.hasOwnProperty("abc");
- `, false)
- })
-}
-
-func TestObject_toLocaleString(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- ({}).toLocaleString();
- `, "[object Object]")
-
- test(`
- object = {
- toString: function() {
- return "Nothing happens.";
- }
- };
- object.toLocaleString();
- `, "Nothing happens.")
- })
-}
-
-func TestObject_isExtensible(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`raise:
- Object.isExtensible();
- `, "TypeError")
-
- // FIXME terst, Why raise?
- test(`raise:
- Object.isExtensible({});
- `, true)
-
- test(`Object.isExtensible.length`, 1)
- test(`Object.isExtensible.prototype`, "undefined")
- })
-}
-
-func TestObject_preventExtensions(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`raise:
- Object.preventExtensions()
- `, "TypeError")
-
- test(`raise:
- var abc = { def: true };
- var ghi = Object.preventExtensions(abc);
- [ ghi.def === true, Object.isExtensible(abc), Object.isExtensible(ghi) ];
- `, "true,false,false")
-
- test(`
- var abc = new String();
- var def = Object.isExtensible(abc);
- Object.preventExtensions(abc);
- var ghi = false;
- try {
- Object.defineProperty(abc, "0", { value: "~" });
- } catch (err) {
- ghi = err instanceof TypeError;
- }
- [ def, ghi, abc.hasOwnProperty("0"), typeof abc[0] ];
- `, "true,true,false,undefined")
-
- test(`Object.preventExtensions.length`, 1)
- test(`Object.preventExtensions.prototype`, "undefined")
- })
-}
-
-func TestObject_isSealed(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Object.isSealed.length`, 1)
- test(`Object.isSealed.prototype`, "undefined")
- })
-}
-
-func TestObject_seal(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`raise: Object.seal()`, "TypeError")
-
- test(`
- var abc = {a:1,b:1,c:3};
- var sealed = Object.isSealed(abc);
- Object.seal(abc);
- [sealed, Object.isSealed(abc)];
- `, "false,true")
-
- test(`
- var abc = {a:1,b:1,c:3};
- var sealed = Object.isSealed(abc);
- var caught = false;
- Object.seal(abc);
- abc.b = 5;
- Object.defineProperty(abc, "a", {value:4});
- try {
- Object.defineProperty(abc, "a", {value:42,enumerable:false});
- } catch (e) {
- caught = e instanceof TypeError;
- }
- [sealed, Object.isSealed(abc), caught, abc.a, abc.b];
- `, "false,true,true,4,5")
-
- test(`Object.seal.length`, 1)
- test(`Object.seal.prototype`, "undefined")
- })
-}
-
-func TestObject_isFrozen(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`raise: Object.isFrozen()`, "TypeError")
- test(`Object.isFrozen(Object.preventExtensions({a:1}))`, false)
- test(`Object.isFrozen({})`, false)
-
- test(`
- var abc = {};
- Object.defineProperty(abc, "def", {
- value: "def",
- writable: true,
- configurable: false
- });
- Object.preventExtensions(abc);
- !Object.isFrozen(abc);
- `, true)
-
- test(`Object.isFrozen.length`, 1)
- test(`Object.isFrozen.prototype`, "undefined")
- })
-}
-
-func TestObject_freeze(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`raise: Object.freeze()`, "TypeError")
-
- test(`
- var abc = {a:1,b:2,c:3};
- var frozen = Object.isFrozen(abc);
- Object.freeze(abc);
- abc.b = 5;
- [frozen, Object.isFrozen(abc), abc.b];
- `, "false,true,2")
-
- test(`
- var abc = {a:1,b:2,c:3};
- var frozen = Object.isFrozen(abc);
- var caught = false;
- Object.freeze(abc);
- abc.b = 5;
- try {
- Object.defineProperty(abc, "a", {value:4});
- } catch (e) {
- caught = e instanceof TypeError;
- }
- [frozen, Object.isFrozen(abc), caught, abc.a, abc.b];
- `, "false,true,true,1,2")
-
- test(`Object.freeze.length`, 1)
- test(`Object.freeze.prototype`, "undefined")
- })
-}
-
-func TestObject_defineProperty(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- (function(abc, def, ghi){
- Object.defineProperty(arguments, "0", {
- enumerable: false
- });
- return true;
- })(0, 1, 2);
- `, true)
-
- test(`
- var abc = {};
- abc.def = 3.14; // Default: writable: true, enumerable: true, configurable: true
-
- Object.defineProperty(abc, "def", {
- value: 42
- });
-
- var ghi = Object.getOwnPropertyDescriptor(abc, "def");
- [ ghi.value, ghi.writable, ghi.enumerable, ghi.configurable ];
- `, "42,true,true,true")
-
- // Test that we handle the case of DefineOwnProperty
- // where [[Writable]] is something but [[Value]] is not
- test(`
- var abc = [];
- Object.defineProperty(abc, "0", { writable: false });
- 0 in abc;
- `, true)
-
- // Test that we handle the case of DefineOwnProperty
- // where [[Writable]] is something but [[Value]] is not
- // (and the property originally had something for [[Value]]
- test(`
- abc = {
- def: 42
- };
- Object.defineProperty(abc, "def", { writable: false });
- abc.def;
- `, 42)
- })
-}
-
-func TestObject_keys(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Object.keys({ abc:undefined, def:undefined })`, "abc,def")
-
- test(`
- function abc() {
- this.abc = undefined;
- this.def = undefined;
- }
- Object.keys(new abc())
- `, "abc,def")
-
- test(`
- function def() {
- this.ghi = undefined;
- }
- def.prototype = new abc();
- Object.keys(new def());
- `, "ghi")
-
- test(`
- var ghi = Object.create(
- {
- abc: undefined,
- def: undefined
- },
- {
- ghi: { value: undefined, enumerable: true },
- jkl: { value: undefined, enumerable: false }
- }
- );
- Object.keys(ghi);
- `, "ghi")
-
- test(`
- (function(abc, def, ghi){
- return Object.keys(arguments)
- })(undefined, undefined);
- `, "0,1")
-
- test(`
- (function(abc, def, ghi){
- return Object.keys(arguments)
- })(undefined, undefined, undefined, undefined);
- `, "0,1,2,3")
- })
-}
-
-func TestObject_getOwnPropertyNames(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`Object.getOwnPropertyNames({ abc:undefined, def:undefined })`, "abc,def")
-
- test(`
- var ghi = Object.create(
- {
- abc: undefined,
- def: undefined
- },
- {
- ghi: { value: undefined, enumerable: true },
- jkl: { value: undefined, enumerable: false }
- }
- );
- Object.getOwnPropertyNames(ghi)
- `, "ghi,jkl")
- })
-}
-
-func TestObjectGetterSetter(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`raise:
- Object.create({}, {
- abc: {
- get: function(){
- return "true";
- },
- writable: true
- }
- }).abc;
- `, "TypeError")
-
- test(`raise:
- Object.create({}, {
- abc: {
- get: function(){
- return "true";
- },
- writable: false
- }
- }).abc;
- `, "TypeError")
-
- test(`
- Object.create({}, {
- abc: {
- get: function(){
- return "true";
- }
- }
- }).abc;
- `, "true")
-
- test(`
- Object.create({xyz:true},{abc:{get:function(){return this.xyx}}}).abc;
- Object.create({
- xyz: true
- }, {
- abc: {
- get: function(){
- return this.xyz;
- }
- }
- }).abc;
- `, true)
-
- test(`
- var abc = false;
- var def = Object.create({}, {
- xyz: {
- set: function(value) {
- abc = value;
- }
- }
- });
- def.xyz = true;
- [ abc ];
- `, "true")
-
- test(`
- var abc = {};
- Object.defineProperty(abc, "def", {
- value: "xyzzy",
- configurable: true
- });
- Object.preventExtensions(abc);
- Object.defineProperty(abc, "def", {
- get: function() {
- return 5;
- }
- });
- var def = Object.getOwnPropertyDescriptor(abc, "def");
- [ abc.def, typeof def.get, typeof def.set, typeof def.value, def.configurable, def.enumerable, typeof def.writable ];
- `, "5,function,undefined,undefined,true,false,undefined")
-
- test(`
- var abc = {};
- Object.defineProperty(abc, "def", {
- get: function() {
- return 5;
- }
- configurable: true
- });
- Object.preventExtensions(abc);
- Object.defineProperty(abc, "def", {
- value: "xyzzy",
- });
- var def = Object.getOwnPropertyDescriptor(abc, "def");
- [ abc.def, typeof def.get, typeof def.set, def.value, def.configurable, def.enumerable, def.writable ];
- `, "xyzzy,undefined,undefined,xyzzy,true,false,false")
-
- test(`
- var abc = {};
-
- function _get0() {
- return 10;
- }
-
- function _set(value) {
- abc.def = value;
- }
-
- Object.defineProperty(abc, "ghi", {
- get: _get0,
- set: _set,
- configurable: true
- });
-
- function _get1() {
- return 20;
- }
-
- Object.defineProperty(abc, "ghi", {
- get: _get0
- });
-
- var descriptor = Object.getOwnPropertyDescriptor(abc, "ghi");
- [ typeof descriptor.set ];
- `, "function")
-
- test(`raise:
- var abc = [];
- Object.defineProperty(abc, "length", {
- get: function () {
- return 2;
- }
- });
- `, "TypeError")
-
- test(`
- var abc = {};
-
- var getter = function() {
- return 1;
- }
-
- Object.defineProperty(abc, "def", {
- get: getter,
- configurable: false
- });
-
- var jkl = undefined;
- try {
- Object.defineProperty(abc, "def", {
- get: undefined
- });
- }
- catch (err) {
- jkl = err;
- }
- var ghi = Object.getOwnPropertyDescriptor(abc, "def");
- [ jkl instanceof TypeError, ghi.get === getter, ghi.configurable, ghi.enumerable ];
- `, "true,true,false,false")
-
- test(`
- var abc = {};
-
- var getter = function() {
- return 1;
- };
-
- Object.defineProperty(abc, "def", {
- get: getter
- });
-
- Object.defineProperty(abc, "def", {
- set: undefined
- });
-
- var ghi = Object.getOwnPropertyDescriptor(abc, "def");
- [ ghi.get === getter, ghi.set === undefined, ghi.configurable, ghi.enumerable ];
- `, "true,true,false,false")
-
- test(`
- var abc = {};
-
- var getter = function() {
- return 1;
- };
-
- Object.defineProperty(abc, "def", {
- get: getter
- });
-
- var jkl = undefined;
- try {
- Object.defineProperty(abc, "def", {
- set: function() {}
- });
- }
- catch (err) {
- jkl = err;
- }
-
- var ghi = Object.getOwnPropertyDescriptor(abc, "def");
- [ jkl instanceof TypeError, ghi.get === getter, ghi.set, ghi.configurable, ghi.enumerable ];
- `, "true,true,,false,false")
-
- test(`
- var abc = {};
- var def = "xyzzy";
-
- Object.defineProperty(abc, "ghi", {
- get: undefined,
- set: function(value) {
- def = value;
- },
- enumerable: true,
- configurable: true
- });
-
- var hasOwn = abc.hasOwnProperty("ghi");
- var descriptor = Object.getOwnPropertyDescriptor(abc, "ghi");
-
- [ hasOwn, typeof descriptor.get ];
- `, "true,undefined")
-
- test(`
- var abc = "xyzzy";
- Object.defineProperty(Array.prototype, "abc", {
- get: function () {
- return abc;
- },
- set: function (value) {
- abc = value;
- },
- enumerable: true,
- configurable: true
- });
- var def = [];
- def.abc = 3.14159;
- [ def.hasOwnProperty("abc"), def.abc, abc ];
- `, "false,3.14159,3.14159")
- })
-}
-
-func TestProperty(t *testing.T) {
- tt(t, func() {
- property := _property{}
- property.writeOn()
- is(property.writeSet(), true)
-
- property.writeClear()
- is(property.writeSet(), false)
-
- property.writeOff()
- is(property.writeSet(), true)
-
- property.writeClear()
- is(property.writeSet(), false)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/otto.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/otto.go
index 9de3e08c5..2ec033cbc 100644
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/otto.go
+++ b/Godeps/_workspace/src/github.com/robertkrimen/otto/otto.go
@@ -296,6 +296,24 @@ func (self Otto) Run(src interface{}) (Value, error) {
return value, err
}
+// Eval will do the same thing as Run, except without leaving the current scope.
+//
+// By staying in the same scope, the code evaluated has access to everything
+// already defined in the current stack frame. This is most useful in, for
+// example, a debugger call.
+func (self Otto) Eval(src interface{}) (Value, error) {
+ if self.runtime.scope == nil {
+ self.runtime.enterGlobalScope()
+ defer self.runtime.leaveScope()
+ }
+
+ value, err := self.runtime.cmpl_eval(src)
+ if !value.safe() {
+ value = Value{}
+ }
+ return value, err
+}
+
// Get the value of the top-level binding of the given name.
//
// If there is an error (like the binding does not exist), then the value
@@ -341,6 +359,79 @@ func (self Otto) setValue(name string, value Value) {
self.runtime.globalStash.setValue(name, value, false)
}
+func (self Otto) SetDebuggerHandler(fn func(vm *Otto)) {
+ self.runtime.debugger = fn
+}
+
+// Context is a structure that contains information about the current execution
+// context.
+type Context struct {
+ Filename string
+ Line int
+ Column int
+ Callee string
+ Symbols map[string]Value
+ This Value
+ Stacktrace []string
+}
+
+// Context returns the current execution context of the vm
+func (self Otto) Context() (ctx Context) {
+ // Ensure we are operating in a scope
+ if self.runtime.scope == nil {
+ self.runtime.enterGlobalScope()
+ defer self.runtime.leaveScope()
+ }
+
+ scope := self.runtime.scope
+ frame := scope.frame
+
+ // Get location information
+ ctx.Filename = "<unknown>"
+ ctx.Callee = frame.callee
+ if frame.file != nil {
+ ctx.Filename = frame.file.Name()
+ if ctx.Filename == "" {
+ ctx.Filename = "<anonymous>"
+ }
+ ctx.Line, ctx.Column = _position(frame.file, frame.offset)
+ }
+
+ // Get the current scope this Value
+ ctx.This = toValue_object(scope.this)
+
+ // Build stacktrace (up to 10 levels deep)
+ limit := 10
+ ctx.Symbols = make(map[string]Value)
+ ctx.Stacktrace = append(ctx.Stacktrace, frame.location())
+ for limit > 0 {
+ // Get variables
+ stash := scope.lexical
+ for {
+ for _, name := range getStashProperties(stash) {
+ if _, ok := ctx.Symbols[name]; !ok {
+ ctx.Symbols[name] = stash.getBinding(name, true)
+ }
+ }
+ stash = stash.outer()
+ if stash == nil || stash.outer() == nil {
+ break
+ }
+ }
+
+ scope = scope.outer
+ if scope == nil {
+ break
+ }
+ if scope.frame.offset >= 0 {
+ ctx.Stacktrace = append(ctx.Stacktrace, scope.frame.location())
+ }
+ limit--
+ }
+
+ return
+}
+
// Call the given JavaScript with a given this and arguments.
//
// If this is nil, then some special handling takes place to determine the proper
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/otto_.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/otto_.go
index e053b54e2..304a83150 100644
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/otto_.go
+++ b/Godeps/_workspace/src/github.com/robertkrimen/otto/otto_.go
@@ -20,12 +20,12 @@ func (self *_runtime) toValueArray(arguments ...interface{}) []Value {
if valueArray, ok := arguments[0].([]Value); ok {
return valueArray
}
- return []Value{toValue(arguments[0])}
+ return []Value{self.toValue(arguments[0])}
}
valueArray := make([]Value, length)
for index, value := range arguments {
- valueArray[index] = toValue(value)
+ valueArray[index] = self.toValue(value)
}
return valueArray
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/otto_error_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/otto_error_test.go
deleted file mode 100644
index 5ce358819..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/otto_error_test.go
+++ /dev/null
@@ -1,48 +0,0 @@
-package otto
-
-import (
- "testing"
-)
-
-func TestOttoError(t *testing.T) {
- tt(t, func() {
- vm := New()
-
- _, err := vm.Run(`throw "Xyzzy"`)
- is(err, "Xyzzy")
-
- _, err = vm.Run(`throw new TypeError()`)
- is(err, "TypeError")
-
- _, err = vm.Run(`throw new TypeError("Nothing happens.")`)
- is(err, "TypeError: Nothing happens.")
-
- _, err = ToValue([]byte{})
- is(err, "TypeError: invalid value (slice): missing runtime: [] ([]uint8)")
-
- _, err = vm.Run(`
- (function(){
- return abcdef.length
- })()
- `)
- is(err, "ReferenceError: 'abcdef' is not defined")
-
- _, err = vm.Run(`
- function start() {
- }
-
- start()
-
- xyzzy()
- `)
- is(err, "ReferenceError: 'xyzzy' is not defined")
-
- _, err = vm.Run(`
- // Just a comment
-
- xyzzy
- `)
- is(err, "ReferenceError: 'xyzzy' is not defined")
-
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/otto_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/otto_test.go
deleted file mode 100644
index 2f1e1c35f..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/otto_test.go
+++ /dev/null
@@ -1,1379 +0,0 @@
-package otto
-
-import (
- "bytes"
- "io"
- "testing"
-
- "github.com/robertkrimen/otto/parser"
-)
-
-func TestOtto(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test("xyzzy = 2", 2)
-
- test("xyzzy + 2", 4)
-
- test("xyzzy += 16", 18)
-
- test("xyzzy", 18)
-
- test(`
- (function(){
- return 1
- })()
- `, 1)
-
- test(`
- (function(){
- return 1
- }).call(this)
- `, 1)
-
- test(`
- (function(){
- var result
- (function(){
- result = -1
- })()
- return result
- })()
- `, -1)
-
- test(`
- var abc = 1
- abc || (abc = -1)
- abc
- `, 1)
-
- test(`
- var abc = (function(){ 1 === 1 })();
- abc;
- `, "undefined")
- })
-}
-
-func TestFunction__(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- function abc() {
- return 1;
- };
- abc();
- `, 1)
- })
-}
-
-func TestIf(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = undefined;
- def = undefined;
- if (true) abc = 1
- else abc = 2;
- if (false) {
- def = 3;
- }
- else def = 4;
-
- [ abc, def ];
- `, "1,4")
-
- test(`
- if (1) {
- abc = 1;
- }
- else {
- abc = 0;
- }
- abc;
- `, 1)
-
- test(`
- if (0) {
- abc = 1;
- }
- else {
- abc = 0;
- }
- abc;
- `, 0)
-
- test(`
- abc = 0;
- if (0) {
- abc = 1;
- }
- abc;
- `, 0)
-
- test(`
- abc = 0;
- if (abc) {
- abc = 1;
- }
- abc;
- `, 0)
- })
-}
-
-func TestSequence(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- 1, 2, 3;
- `, 3)
- })
-}
-
-func TestCall(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- Math.pow(3, 2);
- `, 9)
- })
-}
-
-func TestMember(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = [ 0, 1, 2 ];
- def = {
- "abc": 0,
- "def": 1,
- "ghi": 2,
- };
- [ abc[2], def.abc, abc[1], def.def ];
- `, "2,0,1,1")
- })
-}
-
-func Test_this(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- typeof this;
- `, "object")
- })
-}
-
-func TestWhile(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- limit = 4
- abc = 0
- while (limit) {
- abc = abc + 1
- limit = limit - 1
- }
- abc;
- `, 4)
- })
-}
-
-func TestSwitch_break(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc = true;
- var ghi = "Xyzzy";
- while (abc) {
- switch ('def') {
- case 'def':
- break;
- }
- ghi = "Nothing happens.";
- abc = false;
- }
- ghi;
- `, "Nothing happens.")
-
- test(`
- var abc = true;
- var ghi = "Xyzzy";
- WHILE:
- while (abc) {
- switch ('def') {
- case 'def':
- break WHILE;
- }
- ghi = "Nothing happens."
- abc = false
- }
- ghi;
- `, "Xyzzy")
-
- test(`
- var ghi = "Xyzzy";
- FOR:
- for (;;) {
- switch ('def') {
- case 'def':
- break FOR;
- ghi = "";
- }
- ghi = "Nothing happens.";
- }
- ghi;
- `, "Xyzzy")
-
- test(`
- var ghi = "Xyzzy";
- FOR:
- for (var jkl in {}) {
- switch ('def') {
- case 'def':
- break FOR;
- ghi = "Something happens.";
- }
- ghi = "Nothing happens.";
- }
- ghi;
- `, "Xyzzy")
-
- test(`
- var ghi = "Xyzzy";
- function jkl() {
- switch ('def') {
- case 'def':
- break;
- ghi = "";
- }
- ghi = "Nothing happens.";
- }
- while (abc) {
- jkl();
- abc = false;
- ghi = "Something happens.";
- }
- ghi;
- `, "Something happens.")
- })
-}
-
-func TestTryFinally(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc;
- try {
- abc = 1;
- }
- finally {
- abc = 2;
- }
- abc;
- `, 2)
-
- test(`
- var abc = false, def = 0;
- do {
- def += 1;
- if (def > 100) {
- break;
- }
- try {
- continue;
- }
- finally {
- abc = true;
- }
- }
- while(!abc && def < 10)
- def;
- `, 1)
-
- test(`
- var abc = false, def = 0, ghi = 0;
- do {
- def += 1;
- if (def > 100) {
- break;
- }
- try {
- throw 0;
- }
- catch (jkl) {
- continue;
- }
- finally {
- abc = true;
- ghi = 11;
- }
- ghi -= 1;
- }
- while(!abc && def < 10)
- ghi;
- `, 11)
-
- test(`
- var abc = 0, def = 0;
- do {
- try {
- abc += 1;
- throw "ghi";
- }
- finally {
- def = 1;
- continue;
- }
- def -= 1;
- }
- while (abc < 2)
- [ abc, def ];
- `, "2,1")
- })
-}
-
-func TestTryCatch(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc = 1;
- try {
- throw 4;
- abc = -1;
- }
- catch (xyzzy) {
- abc += xyzzy + 1;
- }
- abc;
- `, 6)
-
- test(`
- abc = 1;
- var def;
- try {
- try {
- throw 4;
- abc = -1;
- }
- catch (xyzzy) {
- abc += xyzzy + 1;
- throw 64;
- }
- }
- catch (xyzzy) {
- def = xyzzy;
- abc = -2;
- }
- [ def, abc ];
- `, "64,-2")
- })
-}
-
-func TestWith(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var def;
- with({ abc: 9 }) {
- def = abc;
- }
- def;
- `, 9)
-
- test(`
- var def;
- with({ abc: function(){
- return 11;
- } }) {
- def = abc();
- }
- def;
- `, 11)
- })
-}
-
-func TestSwitch(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc = 0;
- switch (0) {
- default:
- abc += 1;
- case 1:
- abc += 2;
- case 2:
- abc += 4;
- case 3:
- abc += 8;
- }
- abc;
- `, 15)
-
- test(`
- abc = 0;
- switch (3) {
- default:
- abc += 1;
- case 1:
- abc += 2;
- case 2:
- abc += 4;
- case 3:
- abc += 8;
- }
- abc;
- `, 8)
-
- test(`
- abc = 0;
- switch (60) {
- case 1:
- abc += 2;
- case 2:
- abc += 4;
- case 3:
- abc += 8;
- }
- abc;
- `, 0)
- })
-}
-
-func TestForIn(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc;
- for (property in { a: 1 }) {
- abc = property;
- }
- abc;
- `, "a")
-
- test(`
- var ghi;
- for (property in new String("xyzzy")) {
- ghi = property;
- }
- ghi;
- `, "4")
- })
-}
-
-func TestFor(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc = 7;
- for (i = 0; i < 3; i += 1) {
- abc += 1;
- }
- abc;
- `, 10)
-
- test(`
- abc = 7;
- for (i = 0; i < 3; i += 1) {
- abc += 1;
- if (i == 1) {
- break;
- }
- }
- abc;
- `, 9)
-
- test(`
- abc = 7;
- for (i = 0; i < 3; i += 1) {
- if (i == 2) {
- continue;
- }
- abc += 1;
- }
- abc;
- `, 9)
-
- test(`
- abc = 0;
- for (;;) {
- abc += 1;
- if (abc == 3)
- break;
- }
- abc;
- `, 3)
-
- test(`
- for (abc = 0; ;) {
- abc += 1;
- if (abc == 3)
- break;
- }
- abc;
- `, 3)
-
- test(`
- for (abc = 0; ; abc += 1) {
- abc += 1;
- if (abc == 3)
- break;
- }
- abc;
- `, 3)
- })
-}
-
-func TestLabelled(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- // TODO Add emergency break
-
- test(`
- xyzzy: for (var abc = 0; abc <= 0; abc++) {
- for (var def = 0; def <= 1; def++) {
- if (def === 0) {
- continue xyzzy;
- } else {
- }
- }
- }
- `)
-
- test(`
- abc = 0
- def:
- while (true) {
- while (true) {
- abc = abc + 1
- if (abc > 11) {
- break def;
- }
- }
- }
- abc;
- `, 12)
-
- test(`
- abc = 0
- def:
- do {
- do {
- abc = abc + 1
- if (abc > 11) {
- break def;
- }
- } while (true)
- } while (true)
- abc;
- `, 12)
- })
-}
-
-func TestConditional(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- [ true ? false : true, true ? 1 : 0, false ? 3.14159 : "abc" ];
- `, "false,1,abc")
- })
-}
-
-func TestArrayLiteral(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- [ 1, , 3.14159 ];
- `, "1,,3.14159")
- })
-}
-
-func TestAssignment(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc = 1;
- abc;
- `, 1)
-
- test(`
- abc += 2;
- abc;
- `, 3)
- })
-}
-
-func TestBinaryOperation(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`0 == 1`, false)
- test(`1 == "1"`, true)
- test(`0 === 1`, false)
- test(`1 === "1"`, false)
- test(`"1" === "1"`, true)
- })
-}
-
-func Test_typeof(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`typeof abc`, "undefined")
- test(`typeof abc === 'undefined'`, true)
- test(`typeof {}`, "object")
- test(`typeof null`, "object")
- })
-}
-
-func Test_PrimitiveValueObjectValue(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- Number11 := test(`new Number(11)`)
- is(Number11.float64(), 11)
- })
-}
-
-func Test_eval(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- // FIXME terst, Is this correct?
- test(`
- var abc = 1;
- `, "undefined")
-
- test(`
- eval("abc += 1");
- `, 2)
-
- test(`
- (function(){
- var abc = 11;
- eval("abc += 1");
- return abc;
- })();
- `, 12)
- test(`abc`, 2)
-
- test(`
- (function(){
- try {
- eval("var prop = \\u2029;");
- return false;
- } catch (abc) {
- return [ abc instanceof SyntaxError, abc.toString() ];
- }
- })();
- `, "true,SyntaxError: Unexpected token ILLEGAL")
-
- test(`
- function abc(){
- this.THIS = eval("this");
- }
- var def = new abc();
- def === def.THIS;
- `, true)
- })
-}
-
-func Test_evalDirectIndirect(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- // (function () {return this;}()).abc = "global";
- test(`
- var abc = "global";
- (function(){
- try {
- var _eval = eval;
- var abc = "function";
- return [
- _eval("\'global\' === abc"), // eval (Indirect)
- eval("\'function\' === abc"), // eval (Direct)
- ];
- } finally {
- delete this.abc;
- }
- })();
- `, "true,true")
- })
-}
-
-func TestError_URIError(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`new URIError() instanceof URIError`, true)
-
- test(`
- var abc
- try {
- decodeURI("http://example.com/ _^#%")
- }
- catch (def) {
- abc = def instanceof URIError
- }
- abc
- `, true)
- })
-}
-
-func TestTo(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- {
- value, _ := test(`"11"`).ToFloat()
- is(value, float64(11))
- }
-
- {
- value, _ := test(`"11"`).ToInteger()
- is(value, int64(11))
-
- value, _ = test(`1.1`).ToInteger()
- is(value, int64(1))
- }
- })
-}
-
-func TestShouldError(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`raise:
- xyzzy
- throw new TypeError("Nothing happens.")
- `, "ReferenceError: 'xyzzy' is not defined")
- })
-}
-
-func TestAPI(t *testing.T) {
- tt(t, func() {
- test, vm := test()
-
- test(`
- String.prototype.xyzzy = function(){
- return this.length + 11 + (arguments[0] || 0)
- }
- abc = new String("xyzzy")
- def = "Nothing happens."
- abc.xyzzy()
- `, 16)
- abc, _ := vm.Get("abc")
- def, _ := vm.Get("def")
- object := abc.Object()
- result, _ := object.Call("xyzzy")
- is(result, 16)
- result, _ = object.Call("xyzzy", 1)
- is(result, 17)
- value, _ := object.Get("xyzzy")
- result, _ = value.Call(def)
- is(result, 27)
- result, _ = value.Call(def, 3)
- is(result, 30)
- object = value.Object() // Object xyzzy
- result, _ = object.Value().Call(def, 3)
- is(result, 30)
-
- test(`
- abc = {
- 'abc': 1,
- 'def': false,
- 3.14159: NaN,
- };
- abc['abc'];
- `, 1)
- abc, err := vm.Get("abc")
- is(err, nil)
- object = abc.Object() // Object abc
- value, err = object.Get("abc")
- is(err, nil)
- is(value, 1)
- is(object.Keys(), []string{"abc", "def", "3.14159"})
-
- test(`
- abc = [ 0, 1, 2, 3.14159, "abc", , ];
- abc.def = true;
- `)
- abc, err = vm.Get("abc")
- is(err, nil)
- object = abc.Object() // Object abc
- is(object.Keys(), []string{"0", "1", "2", "3", "4", "def"})
- })
-}
-
-func TestUnicode(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`var abc = eval("\"a\uFFFFa\"");`, "undefined")
-
- test(`abc.length`, 3)
-
- test(`abc != "aa"`, true)
-
- test("abc[1] === \"\uFFFF\"", true)
- })
-}
-
-func TestDotMember(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = {
- ghi: 11,
- }
- abc.def = "Xyzzy"
- abc.null = "Nothing happens."
- `)
- test(`abc.def`, "Xyzzy")
- test(`abc.null`, "Nothing happens.")
- test(`abc.ghi`, 11)
-
- test(`
- abc = {
- null: 11,
- }
- `)
- test(`abc.def`, "undefined")
- test(`abc.null`, 11)
- test(`abc.ghi`, "undefined")
- })
-}
-
-func Test_stringToFloat(t *testing.T) {
- tt(t, func() {
-
- is(parseNumber("10e10000"), _Infinity)
- is(parseNumber("10e10_."), _NaN)
- })
-}
-
-func Test_delete(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- delete 42;
- `, true)
-
- test(`
- var abc = delete $_undefined_$;
- abc = abc && delete ($_undefined_$);
- abc;
- `, true)
-
- // delete should not trigger get()
- test(`
- var abc = {
- get def() {
- throw "Test_delete: delete should not trigger get()"
- }
- };
- delete abc.def
- `, true)
- })
-}
-
-func TestObject_defineOwnProperty(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var object = {};
-
- var descriptor = new Boolean(false);
- descriptor.configurable = true;
-
- Object.defineProperties(object, {
- property: descriptor
- });
-
- var abc = object.hasOwnProperty("property");
- delete object.property;
- var def = object.hasOwnProperty("property");
-
- [ abc, def ];
- `, "true,false")
-
- test(`
- var object = [0, 1, 2];
- Object.defineProperty(object, "0", {
- value: 42,
- writable: false,
- enumerable: false,
- configurable: false
- });
- var abc = Object.getOwnPropertyDescriptor(object, "0");
- [ abc.value, abc.writable, abc.enumerable, abc.configurable ];
- `, "42,false,false,false")
-
- test(`
- var abc = { "xyzzy": 42 };
- var def = Object.defineProperties(abc, "");
- abc === def;
- `, true)
- })
-}
-
-func Test_assignmentEvaluationOrder(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc = 0;
- ((abc = 1) & abc);
- `, 1)
-
- test(`
- var abc = 0;
- (abc & (abc = 1));
- `, 0)
- })
-}
-
-func TestOttoCall(t *testing.T) {
- tt(t, func() {
- vm := New()
-
- _, err := vm.Run(`
- var abc = {
- ghi: 1,
- def: function(def){
- var ghi = 0;
- if (this.ghi) {
- ghi = this.ghi;
- }
- return "def: " + (def + 3.14159 + ghi);
- }
- };
- `)
- is(err, nil)
-
- value, err := vm.Call(`abc.def`, nil, 2)
- is(err, nil)
- is(value, "def: 6.14159")
-
- value, err = vm.Call(`abc.def`, "", 2)
- is(err, nil)
- is(value, "def: 5.14159")
-
- // Do not attempt to do a ToValue on a this of nil
- value, err = vm.Call(`jkl.def`, nil, 1, 2, 3)
- is(err, "!=", nil)
- is(value, "undefined")
-
- value, err = vm.Call(`[ 1, 2, 3, undefined, 4 ].concat`, nil, 5, 6, 7, "abc")
- is(err, nil)
- is(value, "1,2,3,,4,5,6,7,abc")
- })
-}
-
-func TestOttoCall_new(t *testing.T) {
- tt(t, func() {
- test, vm := test()
-
- vm.Set("abc", func(call FunctionCall) Value {
- value, err := call.Otto.Call(`new Object`, nil, "Nothing happens.")
- is(err, nil)
- return value
- })
- test(`
- def = abc();
- [ def, def instanceof String ];
- `, "Nothing happens.,true")
- })
-}
-
-func TestOttoCall_throw(t *testing.T) {
- // FIXME? (Been broken for a while)
- // Looks like this has been broken for a while... what
- // behavior do we want here?
-
- if true {
- return
- }
-
- tt(t, func() {
- test, vm := test()
-
- vm.Set("abc", func(call FunctionCall) Value {
- if false {
- call.Otto.Call(`throw eval`, nil, "({ def: 3.14159 })")
- }
- call.Otto.Call(`throw Error`, nil, "abcdef")
- return Value{}
- })
- // TODO try { abc(); } catch (err) { error = err }
- // Possible unrelated error case:
- // If error is not declared beforehand, is later referencing it a ReferenceError?
- // Should the catch { } declare error in the outer scope?
- test(`
- var error;
- try {
- abc();
- }
- catch (err) {
- error = err;
- }
- [ error instanceof Error, error.message, error.def ];
- `, "true,abcdef,")
-
- vm.Set("def", func(call FunctionCall) Value {
- call.Otto.Call(`throw new Object`, nil, 3.14159)
- return UndefinedValue()
- })
- test(`
- try {
- def();
- }
- catch (err) {
- error = err;
- }
- [ error instanceof Error, error.message, error.def, typeof error, error, error instanceof Number ];
- `, "false,,,object,3.14159,true")
- })
-}
-
-func TestOttoCopy(t *testing.T) {
- tt(t, func() {
- vm0 := New()
- vm0.Run(`
- var abc = function() {
- return "Xyzzy";
- };
-
- function def() {
- return abc() + (0 + {});
- }
- `)
-
- value, err := vm0.Run(`
- def();
- `)
- is(err, nil)
- is(value, "Xyzzy0[object Object]")
-
- vm1 := vm0.Copy()
- value, err = vm1.Run(`
- def();
- `)
- is(err, nil)
- is(value, "Xyzzy0[object Object]")
-
- vm1.Run(`
- abc = function() {
- return 3.14159;
- };
- `)
- value, err = vm1.Run(`
- def();
- `)
- is(err, nil)
- is(value, "3.141590[object Object]")
-
- value, err = vm0.Run(`
- def();
- `)
- is(err, nil)
- is(value, "Xyzzy0[object Object]")
-
- {
- vm0 := New()
- vm0.Run(`
- var global = (function () {return this;}())
- var abc = 0;
- var vm = "vm0";
-
- var def = (function(){
- var jkl = 0;
- var abc = function() {
- global.abc += 1;
- jkl += 1;
- return 1;
- };
-
- return function() {
- return [ vm, global.abc, jkl, abc() ];
- };
- })();
- `)
-
- value, err := vm0.Run(`
- def();
- `)
- is(err, nil)
- is(value, "vm0,0,0,1")
-
- vm1 := vm0.Copy()
- vm1.Set("vm", "vm1")
- value, err = vm1.Run(`
- def();
- `)
- is(err, nil)
- is(value, "vm1,1,1,1")
-
- value, err = vm0.Run(`
- def();
- `)
- is(err, nil)
- is(value, "vm0,1,1,1")
-
- value, err = vm1.Run(`
- def();
- `)
- is(err, nil)
- is(value, "vm1,2,2,1")
- }
- })
-}
-
-func TestOttoCall_clone(t *testing.T) {
- tt(t, func() {
- vm := New().clone()
- rt := vm.runtime
-
- {
- // FIXME terst, Check how this comparison is done
- is(rt.global.Array.prototype, rt.global.FunctionPrototype)
- is(rt.global.ArrayPrototype, "!=", nil)
- is(rt.global.Array.runtime, rt)
- is(rt.global.Array.prototype.runtime, rt)
- is(rt.global.Array.get("prototype")._object().runtime, rt)
- }
-
- {
- value, err := vm.Run(`[ 1, 2, 3 ].toString()`)
- is(err, nil)
- is(value, "1,2,3")
- }
-
- {
- value, err := vm.Run(`[ 1, 2, 3 ]`)
- is(err, nil)
- is(value, "1,2,3")
- object := value._object()
- is(object, "!=", nil)
- is(object.prototype, rt.global.ArrayPrototype)
-
- value, err = vm.Run(`Array.prototype`)
- is(err, nil)
- object = value._object()
- is(object.runtime, rt)
- is(object, "!=", nil)
- is(object, rt.global.ArrayPrototype)
- }
-
- {
- otto1 := New()
- _, err := otto1.Run(`
- var abc = 1;
- var def = 2;
- `)
- is(err, nil)
-
- otto2 := otto1.clone()
- value, err := otto2.Run(`abc += 1; abc;`)
- is(err, nil)
- is(value, 2)
-
- value, err = otto1.Run(`abc += 4; abc;`)
- is(err, nil)
- is(value, 5)
- }
-
- {
- vm1 := New()
- _, err := vm1.Run(`
- var abc = 1;
- var def = function(value) {
- abc += value;
- return abc;
- }
- `)
- is(err, nil)
-
- vm2 := vm1.clone()
- value, err := vm2.Run(`def(1)`)
- is(err, nil)
- is(value, 2)
-
- value, err = vm1.Run(`def(4)`)
- is(err, nil)
- is(value, 5)
- }
-
- {
- vm1 := New()
- _, err := vm1.Run(`
- var abc = {
- ghi: 1,
- jkl: function(value) {
- this.ghi += value;
- return this.ghi;
- }
- };
- var def = {
- abc: abc
- };
- `)
- is(err, nil)
-
- otto2 := vm1.clone()
- value, err := otto2.Run(`def.abc.jkl(1)`)
- is(err, nil)
- is(value, 2)
-
- value, err = vm1.Run(`def.abc.jkl(4)`)
- is(err, nil)
- is(value, 5)
- }
-
- {
- vm1 := New()
- _, err := vm1.Run(`
- var abc = function() { return "abc"; };
- var def = function() { return "def"; };
- `)
- is(err, nil)
-
- vm2 := vm1.clone()
- value, err := vm2.Run(`
- [ abc.toString(), def.toString() ];
- `)
- is(value, `function() { return "abc"; },function() { return "def"; }`)
-
- _, err = vm2.Run(`
- var def = function() { return "ghi"; };
- `)
- is(err, nil)
-
- value, err = vm1.Run(`
- [ abc.toString(), def.toString() ];
- `)
- is(value, `function() { return "abc"; },function() { return "def"; }`)
-
- value, err = vm2.Run(`
- [ abc.toString(), def.toString() ];
- `)
- is(value, `function() { return "abc"; },function() { return "ghi"; }`)
- }
-
- })
-}
-
-func TestOttoRun(t *testing.T) {
- tt(t, func() {
- vm := New()
-
- program, err := parser.ParseFile(nil, "", "", 0)
- is(err, nil)
- value, err := vm.Run(program)
- is(err, nil)
- is(value, UndefinedValue())
-
- program, err = parser.ParseFile(nil, "", "2 + 2", 0)
- is(err, nil)
- value, err = vm.Run(program)
- is(err, nil)
- is(value, 4)
- value, err = vm.Run(program)
- is(err, nil)
- is(value, 4)
-
- program, err = parser.ParseFile(nil, "", "var abc; if (!abc) abc = 0; abc += 2; abc;", 0)
- value, err = vm.Run(program)
- is(err, nil)
- is(value, 2)
- value, err = vm.Run(program)
- is(err, nil)
- is(value, 4)
- value, err = vm.Run(program)
- is(err, nil)
- is(value, 6)
-
- {
- src := []byte("var abc; if (!abc) abc = 0; abc += 2; abc;")
- value, err = vm.Run(src)
- is(err, nil)
- is(value, 8)
-
- value, err = vm.Run(bytes.NewBuffer(src))
- is(err, nil)
- is(value, 10)
-
- value, err = vm.Run(io.Reader(bytes.NewBuffer(src)))
- is(err, nil)
- is(value, 12)
- }
-
- {
- script, err := vm.Compile("", `var abc; if (!abc) abc = 0; abc += 2; abc;`)
- is(err, nil)
-
- value, err = vm.Run(script)
- is(err, nil)
- is(value, 14)
-
- value, err = vm.Run(script)
- is(err, nil)
- is(value, 16)
-
- is(script.String(), "// \nvar abc; if (!abc) abc = 0; abc += 2; abc;")
- }
- })
-}
-
-func Test_objectLength(t *testing.T) {
- tt(t, func() {
- _, vm := test()
-
- value := vm.Set("abc", []string{"jkl", "mno"})
- is(objectLength(value._object()), 2)
-
- value, _ = vm.Run(`[1, 2, 3]`)
- is(objectLength(value._object()), 3)
-
- value, _ = vm.Run(`new String("abcdefghi")`)
- is(objectLength(value._object()), 9)
-
- value, _ = vm.Run(`"abcdefghi"`)
- is(objectLength(value._object()), 0)
- })
-}
-
-func BenchmarkNew(b *testing.B) {
- for i := 0; i < b.N; i++ {
- New()
- }
-}
-
-func BenchmarkClone(b *testing.B) {
- vm := New()
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- vm.clone()
- }
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/panic_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/panic_test.go
deleted file mode 100644
index 06f0a64fc..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/panic_test.go
+++ /dev/null
@@ -1,40 +0,0 @@
-package otto
-
-import (
- "testing"
-)
-
-func Test_panic(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- // Test that property.value is set to something if writable is set
- // to something
- test(`
- var abc = [];
- Object.defineProperty(abc, "0", { writable: false });
- Object.defineProperty(abc, "0", { writable: false });
- "0" in abc;
- `, true)
-
- test(`raise:
- var abc = [];
- Object.defineProperty(abc, "0", { writable: false });
- Object.defineProperty(abc, "0", { value: false, writable: false });
- `, "TypeError")
-
- // Test that a regular expression can contain \c0410 (CYRILLIC CAPITAL LETTER A)
- // without panicking
- test(`
- var abc = 0x0410;
- var def = String.fromCharCode(abc);
- new RegExp("\\c" + def).exec(def);
- `, "null")
-
- // Test transforming a transformable regular expression without a panic
- test(`
- new RegExp("\\u0000");
- new RegExp("\\undefined").test("undefined");
- `, true)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/expression.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/expression.go
index dc397b5cb..8baf22f7c 100644
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/expression.go
+++ b/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/expression.go
@@ -417,7 +417,7 @@ func (self *_parser) parseLeftHandSideExpression() ast.Expression {
for {
if self.token == token.PERIOD {
left = self.parseDotMember(left)
- } else if self.token == token.LEFT_BRACE {
+ } else if self.token == token.LEFT_BRACKET {
left = self.parseBracketMember(left)
} else {
break
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/lexer_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/lexer_test.go
deleted file mode 100644
index 37eb7a464..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/lexer_test.go
+++ /dev/null
@@ -1,380 +0,0 @@
-package parser
-
-import (
- "../terst"
- "testing"
-
- "github.com/robertkrimen/otto/file"
- "github.com/robertkrimen/otto/token"
-)
-
-var tt = terst.Terst
-var is = terst.Is
-
-func TestLexer(t *testing.T) {
- tt(t, func() {
- setup := func(src string) *_parser {
- parser := newParser("", src)
- return parser
- }
-
- test := func(src string, test ...interface{}) {
- parser := setup(src)
- for len(test) > 0 {
- tkn, literal, idx := parser.scan()
- if len(test) > 0 {
- is(tkn, test[0].(token.Token))
- test = test[1:]
- }
- if len(test) > 0 {
- is(literal, test[0].(string))
- test = test[1:]
- }
- if len(test) > 0 {
- // FIXME terst, Fix this so that cast to file.Idx is not necessary?
- is(idx, file.Idx(test[0].(int)))
- test = test[1:]
- }
- }
- }
-
- test("",
- token.EOF, "", 1,
- )
-
- test("1",
- token.NUMBER, "1", 1,
- token.EOF, "", 2,
- )
-
- test(".0",
- token.NUMBER, ".0", 1,
- token.EOF, "", 3,
- )
-
- test("abc",
- token.IDENTIFIER, "abc", 1,
- token.EOF, "", 4,
- )
-
- test("abc(1)",
- token.IDENTIFIER, "abc", 1,
- token.LEFT_PARENTHESIS, "", 4,
- token.NUMBER, "1", 5,
- token.RIGHT_PARENTHESIS, "", 6,
- token.EOF, "", 7,
- )
-
- test(".",
- token.PERIOD, "", 1,
- token.EOF, "", 2,
- )
-
- test("===.",
- token.STRICT_EQUAL, "", 1,
- token.PERIOD, "", 4,
- token.EOF, "", 5,
- )
-
- test(">>>=.0",
- token.UNSIGNED_SHIFT_RIGHT_ASSIGN, "", 1,
- token.NUMBER, ".0", 5,
- token.EOF, "", 7,
- )
-
- test(">>>=0.0.",
- token.UNSIGNED_SHIFT_RIGHT_ASSIGN, "", 1,
- token.NUMBER, "0.0", 5,
- token.PERIOD, "", 8,
- token.EOF, "", 9,
- )
-
- test("\"abc\"",
- token.STRING, "\"abc\"", 1,
- token.EOF, "", 6,
- )
-
- test("abc = //",
- token.IDENTIFIER, "abc", 1,
- token.ASSIGN, "", 5,
- token.EOF, "", 9,
- )
-
- test("abc = 1 / 2",
- token.IDENTIFIER, "abc", 1,
- token.ASSIGN, "", 5,
- token.NUMBER, "1", 7,
- token.SLASH, "", 9,
- token.NUMBER, "2", 11,
- token.EOF, "", 12,
- )
-
- test("xyzzy = 'Nothing happens.'",
- token.IDENTIFIER, "xyzzy", 1,
- token.ASSIGN, "", 7,
- token.STRING, "'Nothing happens.'", 9,
- token.EOF, "", 27,
- )
-
- test("abc = !false",
- token.IDENTIFIER, "abc", 1,
- token.ASSIGN, "", 5,
- token.NOT, "", 7,
- token.BOOLEAN, "false", 8,
- token.EOF, "", 13,
- )
-
- test("abc = !!true",
- token.IDENTIFIER, "abc", 1,
- token.ASSIGN, "", 5,
- token.NOT, "", 7,
- token.NOT, "", 8,
- token.BOOLEAN, "true", 9,
- token.EOF, "", 13,
- )
-
- test("abc *= 1",
- token.IDENTIFIER, "abc", 1,
- token.MULTIPLY_ASSIGN, "", 5,
- token.NUMBER, "1", 8,
- token.EOF, "", 9,
- )
-
- test("if 1 else",
- token.IF, "if", 1,
- token.NUMBER, "1", 4,
- token.ELSE, "else", 6,
- token.EOF, "", 10,
- )
-
- test("null",
- token.NULL, "null", 1,
- token.EOF, "", 5,
- )
-
- test(`"\u007a\x79\u000a\x78"`,
- token.STRING, "\"\\u007a\\x79\\u000a\\x78\"", 1,
- token.EOF, "", 23,
- )
-
- test(`"[First line \
-Second line \
- Third line\
-. ]"
- `,
- token.STRING, "\"[First line \\\nSecond line \\\n Third line\\\n. ]\"", 1,
- token.EOF, "", 53,
- )
-
- test("/",
- token.SLASH, "", 1,
- token.EOF, "", 2,
- )
-
- test("var abc = \"abc\uFFFFabc\"",
- token.VAR, "var", 1,
- token.IDENTIFIER, "abc", 5,
- token.ASSIGN, "", 9,
- token.STRING, "\"abc\uFFFFabc\"", 11,
- token.EOF, "", 22,
- )
-
- test(`'\t' === '\r'`,
- token.STRING, "'\\t'", 1,
- token.STRICT_EQUAL, "", 6,
- token.STRING, "'\\r'", 10,
- token.EOF, "", 14,
- )
-
- test(`var \u0024 = 1`,
- token.VAR, "var", 1,
- token.IDENTIFIER, "$", 5,
- token.ASSIGN, "", 12,
- token.NUMBER, "1", 14,
- token.EOF, "", 15,
- )
-
- test("10e10000",
- token.NUMBER, "10e10000", 1,
- token.EOF, "", 9,
- )
-
- test(`var if var class`,
- token.VAR, "var", 1,
- token.IF, "if", 5,
- token.VAR, "var", 8,
- token.KEYWORD, "class", 12,
- token.EOF, "", 17,
- )
-
- test(`-0`,
- token.MINUS, "", 1,
- token.NUMBER, "0", 2,
- token.EOF, "", 3,
- )
-
- test(`.01`,
- token.NUMBER, ".01", 1,
- token.EOF, "", 4,
- )
-
- test(`.01e+2`,
- token.NUMBER, ".01e+2", 1,
- token.EOF, "", 7,
- )
-
- test(";",
- token.SEMICOLON, "", 1,
- token.EOF, "", 2,
- )
-
- test(";;",
- token.SEMICOLON, "", 1,
- token.SEMICOLON, "", 2,
- token.EOF, "", 3,
- )
-
- test("//",
- token.EOF, "", 3,
- )
-
- test(";;//",
- token.SEMICOLON, "", 1,
- token.SEMICOLON, "", 2,
- token.EOF, "", 5,
- )
-
- test("1",
- token.NUMBER, "1", 1,
- )
-
- test("12 123",
- token.NUMBER, "12", 1,
- token.NUMBER, "123", 4,
- )
-
- test("1.2 12.3",
- token.NUMBER, "1.2", 1,
- token.NUMBER, "12.3", 5,
- )
-
- test("/ /=",
- token.SLASH, "", 1,
- token.QUOTIENT_ASSIGN, "", 3,
- )
-
- test(`"abc"`,
- token.STRING, `"abc"`, 1,
- )
-
- test(`'abc'`,
- token.STRING, `'abc'`, 1,
- )
-
- test("++",
- token.INCREMENT, "", 1,
- )
-
- test(">",
- token.GREATER, "", 1,
- )
-
- test(">=",
- token.GREATER_OR_EQUAL, "", 1,
- )
-
- test(">>",
- token.SHIFT_RIGHT, "", 1,
- )
-
- test(">>=",
- token.SHIFT_RIGHT_ASSIGN, "", 1,
- )
-
- test(">>>",
- token.UNSIGNED_SHIFT_RIGHT, "", 1,
- )
-
- test(">>>=",
- token.UNSIGNED_SHIFT_RIGHT_ASSIGN, "", 1,
- )
-
- test("1 \"abc\"",
- token.NUMBER, "1", 1,
- token.STRING, "\"abc\"", 3,
- )
-
- test(",",
- token.COMMA, "", 1,
- )
-
- test("1, \"abc\"",
- token.NUMBER, "1", 1,
- token.COMMA, "", 2,
- token.STRING, "\"abc\"", 4,
- )
-
- test("new abc(1, 3.14159);",
- token.NEW, "new", 1,
- token.IDENTIFIER, "abc", 5,
- token.LEFT_PARENTHESIS, "", 8,
- token.NUMBER, "1", 9,
- token.COMMA, "", 10,
- token.NUMBER, "3.14159", 12,
- token.RIGHT_PARENTHESIS, "", 19,
- token.SEMICOLON, "", 20,
- )
-
- test("1 == \"1\"",
- token.NUMBER, "1", 1,
- token.EQUAL, "", 3,
- token.STRING, "\"1\"", 6,
- )
-
- test("1\n[]\n",
- token.NUMBER, "1", 1,
- token.LEFT_BRACKET, "", 3,
- token.RIGHT_BRACKET, "", 4,
- )
-
- test("1\ufeff[]\ufeff",
- token.NUMBER, "1", 1,
- token.LEFT_BRACKET, "", 5,
- token.RIGHT_BRACKET, "", 6,
- )
-
- // ILLEGAL
-
- test(`3ea`,
- token.ILLEGAL, "3e", 1,
- token.IDENTIFIER, "a", 3,
- token.EOF, "", 4,
- )
-
- test(`3in`,
- token.ILLEGAL, "3", 1,
- token.IN, "in", 2,
- token.EOF, "", 4,
- )
-
- test("\"Hello\nWorld\"",
- token.ILLEGAL, "", 1,
- token.IDENTIFIER, "World", 8,
- token.ILLEGAL, "", 13,
- token.EOF, "", 14,
- )
-
- test("\u203f = 10",
- token.ILLEGAL, "", 1,
- token.ASSIGN, "", 5,
- token.NUMBER, "10", 7,
- token.EOF, "", 9,
- )
-
- test(`"\x0G"`,
- token.STRING, "\"\\x0G\"", 1,
- token.EOF, "", 7,
- )
-
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/marshal_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/marshal_test.go
deleted file mode 100644
index f54cd2d4f..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/marshal_test.go
+++ /dev/null
@@ -1,930 +0,0 @@
-package parser
-
-import (
- "bytes"
- "encoding/json"
- "fmt"
- "os"
- "reflect"
- "strings"
- "testing"
-
- "github.com/robertkrimen/otto/ast"
-)
-
-func marshal(name string, children ...interface{}) interface{} {
- if len(children) == 1 {
- if name == "" {
- return testMarshalNode(children[0])
- }
- return map[string]interface{}{
- name: children[0],
- }
- }
- map_ := map[string]interface{}{}
- length := len(children) / 2
- for i := 0; i < length; i++ {
- name := children[i*2].(string)
- value := children[i*2+1]
- map_[name] = value
- }
- if name == "" {
- return map_
- }
- return map[string]interface{}{
- name: map_,
- }
-}
-
-func testMarshalNode(node interface{}) interface{} {
- switch node := node.(type) {
-
- // Expression
-
- case *ast.ArrayLiteral:
- return marshal("Array", testMarshalNode(node.Value))
-
- case *ast.AssignExpression:
- return marshal("Assign",
- "Left", testMarshalNode(node.Left),
- "Right", testMarshalNode(node.Right),
- )
-
- case *ast.BinaryExpression:
- return marshal("BinaryExpression",
- "Operator", node.Operator.String(),
- "Left", testMarshalNode(node.Left),
- "Right", testMarshalNode(node.Right),
- )
-
- case *ast.BooleanLiteral:
- return marshal("Literal", node.Value)
-
- case *ast.CallExpression:
- return marshal("Call",
- "Callee", testMarshalNode(node.Callee),
- "ArgumentList", testMarshalNode(node.ArgumentList),
- )
-
- case *ast.ConditionalExpression:
- return marshal("Conditional",
- "Test", testMarshalNode(node.Test),
- "Consequent", testMarshalNode(node.Consequent),
- "Alternate", testMarshalNode(node.Alternate),
- )
-
- case *ast.DotExpression:
- return marshal("Dot",
- "Left", testMarshalNode(node.Left),
- "Member", node.Identifier.Name,
- )
-
- case *ast.NewExpression:
- return marshal("New",
- "Callee", testMarshalNode(node.Callee),
- "ArgumentList", testMarshalNode(node.ArgumentList),
- )
-
- case *ast.NullLiteral:
- return marshal("Literal", nil)
-
- case *ast.NumberLiteral:
- return marshal("Literal", node.Value)
-
- case *ast.ObjectLiteral:
- return marshal("Object", testMarshalNode(node.Value))
-
- case *ast.RegExpLiteral:
- return marshal("Literal", node.Literal)
-
- case *ast.StringLiteral:
- return marshal("Literal", node.Literal)
-
- case *ast.VariableExpression:
- return []interface{}{node.Name, testMarshalNode(node.Initializer)}
-
- // Statement
-
- case *ast.Program:
- return testMarshalNode(node.Body)
-
- case *ast.BlockStatement:
- return marshal("BlockStatement", testMarshalNode(node.List))
-
- case *ast.EmptyStatement:
- return "EmptyStatement"
-
- case *ast.ExpressionStatement:
- return testMarshalNode(node.Expression)
-
- case *ast.ForInStatement:
- return marshal("ForIn",
- "Into", marshal("", node.Into),
- "Source", marshal("", node.Source),
- "Body", marshal("", node.Body),
- )
-
- case *ast.FunctionLiteral:
- return marshal("Function", testMarshalNode(node.Body))
-
- case *ast.Identifier:
- return marshal("Identifier", node.Name)
-
- case *ast.IfStatement:
- if_ := marshal("",
- "Test", testMarshalNode(node.Test),
- "Consequent", testMarshalNode(node.Consequent),
- ).(map[string]interface{})
- if node.Alternate != nil {
- if_["Alternate"] = testMarshalNode(node.Alternate)
- }
- return marshal("If", if_)
-
- case *ast.LabelledStatement:
- return marshal("Label",
- "Name", node.Label.Name,
- "Statement", testMarshalNode(node.Statement),
- )
- case ast.Property:
- return marshal("",
- "Key", node.Key,
- "Value", testMarshalNode(node.Value),
- )
-
- case *ast.ReturnStatement:
- return marshal("Return", testMarshalNode(node.Argument))
-
- case *ast.SequenceExpression:
- return marshal("Sequence", testMarshalNode(node.Sequence))
-
- case *ast.ThrowStatement:
- return marshal("Throw", testMarshalNode(node.Argument))
-
- case *ast.VariableStatement:
- return marshal("Var", testMarshalNode(node.List))
-
- }
-
- {
- value := reflect.ValueOf(node)
- if value.Kind() == reflect.Slice {
- tmp0 := []interface{}{}
- for index := 0; index < value.Len(); index++ {
- tmp0 = append(tmp0, testMarshalNode(value.Index(index).Interface()))
- }
- return tmp0
- }
- }
-
- if node != nil {
- fmt.Fprintf(os.Stderr, "testMarshalNode(%T)\n", node)
- }
-
- return nil
-}
-
-func testMarshal(node interface{}) string {
- value, err := json.Marshal(testMarshalNode(node))
- if err != nil {
- panic(err)
- }
- return string(value)
-}
-
-func TestParserAST(t *testing.T) {
- tt(t, func() {
-
- test := func(inputOutput string) {
- match := matchBeforeAfterSeparator.FindStringIndex(inputOutput)
- input := strings.TrimSpace(inputOutput[0:match[0]])
- wantOutput := strings.TrimSpace(inputOutput[match[1]:])
- _, program, err := testParse(input)
- is(err, nil)
- haveOutput := testMarshal(program)
- tmp0, tmp1 := bytes.Buffer{}, bytes.Buffer{}
- json.Indent(&tmp0, []byte(haveOutput), "\t\t", " ")
- json.Indent(&tmp1, []byte(wantOutput), "\t\t", " ")
- is("\n\t\t"+tmp0.String(), "\n\t\t"+tmp1.String())
- }
-
- test(`
- ---
-[]
- `)
-
- test(`
- ;
- ---
-[
- "EmptyStatement"
-]
- `)
-
- test(`
- ;;;
- ---
-[
- "EmptyStatement",
- "EmptyStatement",
- "EmptyStatement"
-]
- `)
-
- test(`
- 1; true; abc; "abc"; null;
- ---
-[
- {
- "Literal": 1
- },
- {
- "Literal": true
- },
- {
- "Identifier": "abc"
- },
- {
- "Literal": "\"abc\""
- },
- {
- "Literal": null
- }
-]
- `)
-
- test(`
- { 1; null; 3.14159; ; }
- ---
-[
- {
- "BlockStatement": [
- {
- "Literal": 1
- },
- {
- "Literal": null
- },
- {
- "Literal": 3.14159
- },
- "EmptyStatement"
- ]
- }
-]
- `)
-
- test(`
- new abc();
- ---
-[
- {
- "New": {
- "ArgumentList": [],
- "Callee": {
- "Identifier": "abc"
- }
- }
- }
-]
- `)
-
- test(`
- new abc(1, 3.14159)
- ---
-[
- {
- "New": {
- "ArgumentList": [
- {
- "Literal": 1
- },
- {
- "Literal": 3.14159
- }
- ],
- "Callee": {
- "Identifier": "abc"
- }
- }
- }
-]
- `)
-
- test(`
- true ? false : true
- ---
-[
- {
- "Conditional": {
- "Alternate": {
- "Literal": true
- },
- "Consequent": {
- "Literal": false
- },
- "Test": {
- "Literal": true
- }
- }
- }
-]
- `)
-
- test(`
- true || false
- ---
-[
- {
- "BinaryExpression": {
- "Left": {
- "Literal": true
- },
- "Operator": "||",
- "Right": {
- "Literal": false
- }
- }
- }
-]
- `)
-
- test(`
- 0 + { abc: true }
- ---
-[
- {
- "BinaryExpression": {
- "Left": {
- "Literal": 0
- },
- "Operator": "+",
- "Right": {
- "Object": [
- {
- "Key": "abc",
- "Value": {
- "Literal": true
- }
- }
- ]
- }
- }
- }
-]
- `)
-
- test(`
- 1 == "1"
- ---
-[
- {
- "BinaryExpression": {
- "Left": {
- "Literal": 1
- },
- "Operator": "==",
- "Right": {
- "Literal": "\"1\""
- }
- }
- }
-]
- `)
-
- test(`
- abc(1)
- ---
-[
- {
- "Call": {
- "ArgumentList": [
- {
- "Literal": 1
- }
- ],
- "Callee": {
- "Identifier": "abc"
- }
- }
- }
-]
- `)
-
- test(`
- Math.pow(3, 2)
- ---
-[
- {
- "Call": {
- "ArgumentList": [
- {
- "Literal": 3
- },
- {
- "Literal": 2
- }
- ],
- "Callee": {
- "Dot": {
- "Left": {
- "Identifier": "Math"
- },
- "Member": "pow"
- }
- }
- }
- }
-]
- `)
-
- test(`
- 1, 2, 3
- ---
-[
- {
- "Sequence": [
- {
- "Literal": 1
- },
- {
- "Literal": 2
- },
- {
- "Literal": 3
- }
- ]
- }
-]
- `)
-
- test(`
- / abc / gim;
- ---
-[
- {
- "Literal": "/ abc / gim"
- }
-]
- `)
-
- test(`
- if (0)
- 1;
- ---
-[
- {
- "If": {
- "Consequent": {
- "Literal": 1
- },
- "Test": {
- "Literal": 0
- }
- }
- }
-]
- `)
-
- test(`
- 0+function(){
- return;
- }
- ---
-[
- {
- "BinaryExpression": {
- "Left": {
- "Literal": 0
- },
- "Operator": "+",
- "Right": {
- "Function": {
- "BlockStatement": [
- {
- "Return": null
- }
- ]
- }
- }
- }
- }
-]
- `)
-
- test(`
- xyzzy // Ignore it
- // Ignore this
- // And this
- /* And all..
-
-
-
- ... of this!
- */
- "Nothing happens."
- // And finally this
- ---
-[
- {
- "Identifier": "xyzzy"
- },
- {
- "Literal": "\"Nothing happens.\""
- }
-]
- `)
-
- test(`
- ((x & (x = 1)) !== 0)
- ---
-[
- {
- "BinaryExpression": {
- "Left": {
- "BinaryExpression": {
- "Left": {
- "Identifier": "x"
- },
- "Operator": "\u0026",
- "Right": {
- "Assign": {
- "Left": {
- "Identifier": "x"
- },
- "Right": {
- "Literal": 1
- }
- }
- }
- }
- },
- "Operator": "!==",
- "Right": {
- "Literal": 0
- }
- }
- }
-]
- `)
-
- test(`
- { abc: 'def' }
- ---
-[
- {
- "BlockStatement": [
- {
- "Label": {
- "Name": "abc",
- "Statement": {
- "Literal": "'def'"
- }
- }
- }
- ]
- }
-]
- `)
-
- test(`
- // This is not an object, this is a string literal with a label!
- ({ abc: 'def' })
- ---
-[
- {
- "Object": [
- {
- "Key": "abc",
- "Value": {
- "Literal": "'def'"
- }
- }
- ]
- }
-]
- `)
-
- test(`
- [,]
- ---
-[
- {
- "Array": [
- null
- ]
- }
-]
- `)
-
- test(`
- [,,]
- ---
-[
- {
- "Array": [
- null,
- null
- ]
- }
-]
- `)
-
- test(`
- ({ get abc() {} })
- ---
-[
- {
- "Object": [
- {
- "Key": "abc",
- "Value": {
- "Function": {
- "BlockStatement": []
- }
- }
- }
- ]
- }
-]
- `)
-
- test(`
- /abc/.source
- ---
-[
- {
- "Dot": {
- "Left": {
- "Literal": "/abc/"
- },
- "Member": "source"
- }
- }
-]
- `)
-
- test(`
- xyzzy
-
- throw new TypeError("Nothing happens.")
- ---
-[
- {
- "Identifier": "xyzzy"
- },
- {
- "Throw": {
- "New": {
- "ArgumentList": [
- {
- "Literal": "\"Nothing happens.\""
- }
- ],
- "Callee": {
- "Identifier": "TypeError"
- }
- }
- }
- }
-]
- `)
-
- // When run, this will call a type error to be thrown
- // This is essentially the same as:
- //
- // var abc = 1(function(){})()
- //
- test(`
- var abc = 1
- (function(){
- })()
- ---
-[
- {
- "Var": [
- [
- "abc",
- {
- "Call": {
- "ArgumentList": [],
- "Callee": {
- "Call": {
- "ArgumentList": [
- {
- "Function": {
- "BlockStatement": []
- }
- }
- ],
- "Callee": {
- "Literal": 1
- }
- }
- }
- }
- }
- ]
- ]
- }
-]
- `)
-
- test(`
- "use strict"
- ---
-[
- {
- "Literal": "\"use strict\""
- }
-]
- `)
-
- test(`
- "use strict"
- abc = 1 + 2 + 11
- ---
-[
- {
- "Literal": "\"use strict\""
- },
- {
- "Assign": {
- "Left": {
- "Identifier": "abc"
- },
- "Right": {
- "BinaryExpression": {
- "Left": {
- "BinaryExpression": {
- "Left": {
- "Literal": 1
- },
- "Operator": "+",
- "Right": {
- "Literal": 2
- }
- }
- },
- "Operator": "+",
- "Right": {
- "Literal": 11
- }
- }
- }
- }
- }
-]
- `)
-
- test(`
- abc = function() { 'use strict' }
- ---
-[
- {
- "Assign": {
- "Left": {
- "Identifier": "abc"
- },
- "Right": {
- "Function": {
- "BlockStatement": [
- {
- "Literal": "'use strict'"
- }
- ]
- }
- }
- }
- }
-]
- `)
-
- test(`
- for (var abc in def) {
- }
- ---
-[
- {
- "ForIn": {
- "Body": {
- "BlockStatement": []
- },
- "Into": [
- "abc",
- null
- ],
- "Source": {
- "Identifier": "def"
- }
- }
- }
-]
- `)
-
- test(`
- abc = {
- '"': "'",
- "'": '"',
- }
- ---
-[
- {
- "Assign": {
- "Left": {
- "Identifier": "abc"
- },
- "Right": {
- "Object": [
- {
- "Key": "\"",
- "Value": {
- "Literal": "\"'\""
- }
- },
- {
- "Key": "'",
- "Value": {
- "Literal": "'\"'"
- }
- }
- ]
- }
- }
- }
-]
- `)
-
- return
-
- test(`
- if (!abc && abc.jkl(def) && abc[0] === +abc[0] && abc.length < ghi) {
- }
- ---
-[
- {
- "If": {
- "Consequent": {
- "BlockStatement": []
- },
- "Test": {
- "BinaryExpression": {
- "Left": {
- "BinaryExpression": {
- "Left": {
- "BinaryExpression": {
- "Left": null,
- "Operator": "\u0026\u0026",
- "Right": {
- "Call": {
- "ArgumentList": [
- {
- "Identifier": "def"
- }
- ],
- "Callee": {
- "Dot": {
- "Left": {
- "Identifier": "abc"
- },
- "Member": "jkl"
- }
- }
- }
- }
- }
- },
- "Operator": "\u0026\u0026",
- "Right": {
- "BinaryExpression": {
- "Left": null,
- "Operator": "===",
- "Right": null
- }
- }
- }
- },
- "Operator": "\u0026\u0026",
- "Right": {
- "BinaryExpression": {
- "Left": {
- "Dot": {
- "Left": {
- "Identifier": "abc"
- },
- "Member": "length"
- }
- },
- "Operator": "\u003c",
- "Right": {
- "Identifier": "ghi"
- }
- }
- }
- }
- }
- }
- }
-]
- `)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/parser.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/parser.go
index 1536344d7..92ac5b0c7 100644
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/parser.go
+++ b/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/parser.go
@@ -52,7 +52,6 @@ const (
)
type _parser struct {
- filename string
str string
length int
base int
@@ -260,7 +259,7 @@ func (self *_parser) position(idx file.Idx) file.Position {
position := file.Position{}
offset := int(idx) - self.base
str := self.str[:offset]
- position.Filename = self.filename
+ position.Filename = self.file.Name()
line, last := lineCount(str)
position.Line = 1 + line
if last >= 0 {
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/parser_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/parser_test.go
deleted file mode 100644
index 8f9457745..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/parser_test.go
+++ /dev/null
@@ -1,1004 +0,0 @@
-package parser
-
-import (
- "errors"
- "regexp"
- "strings"
- "testing"
-
- "github.com/robertkrimen/otto/ast"
- "github.com/robertkrimen/otto/file"
-)
-
-func firstErr(err error) error {
- switch err := err.(type) {
- case ErrorList:
- return err[0]
- }
- return err
-}
-
-var matchBeforeAfterSeparator = regexp.MustCompile(`(?m)^[ \t]*---$`)
-
-func testParse(src string) (parser *_parser, program *ast.Program, err error) {
- defer func() {
- if tmp := recover(); tmp != nil {
- switch tmp := tmp.(type) {
- case string:
- if strings.HasPrefix(tmp, "SyntaxError:") {
- parser = nil
- program = nil
- err = errors.New(tmp)
- return
- }
- }
- panic(tmp)
- }
- }()
- parser = newParser("", src)
- program, err = parser.parse()
- return
-}
-
-func TestParseFile(t *testing.T) {
- tt(t, func() {
- _, err := ParseFile(nil, "", `/abc/`, 0)
- is(err, nil)
-
- _, err = ParseFile(nil, "", `/(?!def)abc/`, IgnoreRegExpErrors)
- is(err, nil)
-
- _, err = ParseFile(nil, "", `/(?!def)abc/`, 0)
- is(err, "(anonymous): Line 1:1 Invalid regular expression: re2: Invalid (?!) <lookahead>")
-
- _, err = ParseFile(nil, "", `/(?!def)abc/; return`, IgnoreRegExpErrors)
- is(err, "(anonymous): Line 1:15 Illegal return statement")
- })
-}
-
-func TestParseFunction(t *testing.T) {
- tt(t, func() {
- test := func(prm, bdy string, expect interface{}) *ast.FunctionLiteral {
- function, err := ParseFunction(prm, bdy)
- is(firstErr(err), expect)
- return function
- }
-
- test("a, b,c,d", "", nil)
-
- test("a, b;,c,d", "", "(anonymous): Line 1:15 Unexpected token ;")
-
- test("this", "", "(anonymous): Line 1:11 Unexpected token this")
-
- test("a, b, c, null", "", "(anonymous): Line 1:20 Unexpected token null")
-
- test("a, b,c,d", "return;", nil)
-
- test("a, b,c,d", "break;", "(anonymous): Line 2:1 Illegal break statement")
-
- test("a, b,c,d", "{}", nil)
- })
-}
-
-func TestParserErr(t *testing.T) {
- tt(t, func() {
- test := func(input string, expect interface{}) (*ast.Program, *_parser) {
- parser := newParser("", input)
- program, err := parser.parse()
- is(firstErr(err), expect)
- return program, parser
- }
-
- program, parser := test("", nil)
-
- program, parser = test(`
- var abc;
- break; do {
- } while(true);
- `, "(anonymous): Line 3:9 Illegal break statement")
- {
- stmt := program.Body[1].(*ast.BadStatement)
- is(parser.position(stmt.From).Column, 9)
- is(parser.position(stmt.To).Column, 16)
- is(parser.slice(stmt.From, stmt.To), "break; ")
- }
-
- test("{", "(anonymous): Line 1:2 Unexpected end of input")
-
- test("}", "(anonymous): Line 1:1 Unexpected token }")
-
- test("3ea", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("3in", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("3in []", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("3e", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("3e+", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("3e-", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("3x", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("3x0", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("0x", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("09", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("018", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("01.0", "(anonymous): Line 1:3 Unexpected number")
-
- test("01a", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("0x3in[]", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("\"Hello\nWorld\"", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("\u203f = 10", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("x\\", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("x\\\\", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("x\\u005c", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("x\\u002a", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("x\\\\u002a", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("/\n", "(anonymous): Line 1:1 Invalid regular expression: missing /")
-
- test("var x = /(s/g", "(anonymous): Line 1:9 Invalid regular expression: Unterminated group")
-
- test("0 = 1", "(anonymous): Line 1:1 Invalid left-hand side in assignment")
-
- test("func() = 1", "(anonymous): Line 1:1 Invalid left-hand side in assignment")
-
- test("(1 + 1) = 2", "(anonymous): Line 1:2 Invalid left-hand side in assignment")
-
- test("1++", "(anonymous): Line 1:2 Invalid left-hand side in assignment")
-
- test("1--", "(anonymous): Line 1:2 Invalid left-hand side in assignment")
-
- test("--1", "(anonymous): Line 1:1 Invalid left-hand side in assignment")
-
- test("for((1 + 1) in abc) def();", "(anonymous): Line 1:1 Invalid left-hand side in for-in")
-
- test("[", "(anonymous): Line 1:2 Unexpected end of input")
-
- test("[,", "(anonymous): Line 1:3 Unexpected end of input")
-
- test("1 + {", "(anonymous): Line 1:6 Unexpected end of input")
-
- test("1 + { abc:abc", "(anonymous): Line 1:14 Unexpected end of input")
-
- test("1 + { abc:abc,", "(anonymous): Line 1:15 Unexpected end of input")
-
- test("var abc = /\n/", "(anonymous): Line 1:11 Invalid regular expression: missing /")
-
- test("var abc = \"\n", "(anonymous): Line 1:11 Unexpected token ILLEGAL")
-
- test("var if = 0", "(anonymous): Line 1:5 Unexpected token if")
-
- test("abc + 0 = 1", "(anonymous): Line 1:1 Invalid left-hand side in assignment")
-
- test("+abc = 1", "(anonymous): Line 1:1 Invalid left-hand side in assignment")
-
- test("1 + (", "(anonymous): Line 1:6 Unexpected end of input")
-
- test("\n\n\n{", "(anonymous): Line 4:2 Unexpected end of input")
-
- test("\n/* Some multiline\ncomment */\n)", "(anonymous): Line 4:1 Unexpected token )")
-
- // TODO
- //{ set 1 }
- //{ get 2 }
- //({ set: s(if) { } })
- //({ set s(.) { } })
- //({ set: s() { } })
- //({ set: s(a, b) { } })
- //({ get: g(d) { } })
- //({ get i() { }, i: 42 })
- //({ i: 42, get i() { } })
- //({ set i(x) { }, i: 42 })
- //({ i: 42, set i(x) { } })
- //({ get i() { }, get i() { } })
- //({ set i(x) { }, set i(x) { } })
-
- test("function abc(if) {}", "(anonymous): Line 1:14 Unexpected token if")
-
- test("function abc(true) {}", "(anonymous): Line 1:14 Unexpected token true")
-
- test("function abc(false) {}", "(anonymous): Line 1:14 Unexpected token false")
-
- test("function abc(null) {}", "(anonymous): Line 1:14 Unexpected token null")
-
- test("function null() {}", "(anonymous): Line 1:10 Unexpected token null")
-
- test("function true() {}", "(anonymous): Line 1:10 Unexpected token true")
-
- test("function false() {}", "(anonymous): Line 1:10 Unexpected token false")
-
- test("function if() {}", "(anonymous): Line 1:10 Unexpected token if")
-
- test("a b;", "(anonymous): Line 1:3 Unexpected identifier")
-
- test("if.a", "(anonymous): Line 1:3 Unexpected token .")
-
- test("a if", "(anonymous): Line 1:3 Unexpected token if")
-
- test("a class", "(anonymous): Line 1:3 Unexpected reserved word")
-
- test("break\n", "(anonymous): Line 1:1 Illegal break statement")
-
- test("break 1;", "(anonymous): Line 1:7 Unexpected number")
-
- test("for (;;) { break 1; }", "(anonymous): Line 1:18 Unexpected number")
-
- test("continue\n", "(anonymous): Line 1:1 Illegal continue statement")
-
- test("continue 1;", "(anonymous): Line 1:10 Unexpected number")
-
- test("for (;;) { continue 1; }", "(anonymous): Line 1:21 Unexpected number")
-
- test("throw", "(anonymous): Line 1:1 Unexpected end of input")
-
- test("throw;", "(anonymous): Line 1:6 Unexpected token ;")
-
- test("throw \n", "(anonymous): Line 1:1 Unexpected end of input")
-
- test("for (var abc, def in {});", "(anonymous): Line 1:19 Unexpected token in")
-
- test("for ((abc in {});;);", nil)
-
- test("for ((abc in {}));", "(anonymous): Line 1:17 Unexpected token )")
-
- test("for (+abc in {});", "(anonymous): Line 1:1 Invalid left-hand side in for-in")
-
- test("if (false)", "(anonymous): Line 1:11 Unexpected end of input")
-
- test("if (false) abc(); else", "(anonymous): Line 1:23 Unexpected end of input")
-
- test("do", "(anonymous): Line 1:3 Unexpected end of input")
-
- test("while (false)", "(anonymous): Line 1:14 Unexpected end of input")
-
- test("for (;;)", "(anonymous): Line 1:9 Unexpected end of input")
-
- test("with (abc)", "(anonymous): Line 1:11 Unexpected end of input")
-
- test("try {}", "(anonymous): Line 1:1 Missing catch or finally after try")
-
- test("try {} catch {}", "(anonymous): Line 1:14 Unexpected token {")
-
- test("try {} catch () {}", "(anonymous): Line 1:15 Unexpected token )")
-
- test("\u203f = 1", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- // TODO
- // const x = 12, y;
- // const x, y = 12;
- // const x;
- // if(true) let a = 1;
- // if(true) const a = 1;
-
- test(`new abc()."def"`, "(anonymous): Line 1:11 Unexpected string")
-
- test("/*", "(anonymous): Line 1:3 Unexpected end of input")
-
- test("/**", "(anonymous): Line 1:4 Unexpected end of input")
-
- test("/*\n\n\n", "(anonymous): Line 4:1 Unexpected end of input")
-
- test("/*\n\n\n*", "(anonymous): Line 4:2 Unexpected end of input")
-
- test("/*abc", "(anonymous): Line 1:6 Unexpected end of input")
-
- test("/*abc *", "(anonymous): Line 1:9 Unexpected end of input")
-
- test("\n]", "(anonymous): Line 2:1 Unexpected token ]")
-
- test("\r\n]", "(anonymous): Line 2:1 Unexpected token ]")
-
- test("\n\r]", "(anonymous): Line 3:1 Unexpected token ]")
-
- test("//\r\n]", "(anonymous): Line 2:1 Unexpected token ]")
-
- test("//\n\r]", "(anonymous): Line 3:1 Unexpected token ]")
-
- test("/abc\\\n/", "(anonymous): Line 1:1 Invalid regular expression: missing /")
-
- test("//\r \n]", "(anonymous): Line 3:1 Unexpected token ]")
-
- test("/*\r\n*/]", "(anonymous): Line 2:3 Unexpected token ]")
-
- test("/*\r \n*/]", "(anonymous): Line 3:3 Unexpected token ]")
-
- test("\\\\", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("\\u005c", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("\\abc", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("\\u0000", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("\\u200c = []", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("\\u200D = []", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test(`"\`, "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test(`"\u`, "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("return", "(anonymous): Line 1:1 Illegal return statement")
-
- test("continue", "(anonymous): Line 1:1 Illegal continue statement")
-
- test("break", "(anonymous): Line 1:1 Illegal break statement")
-
- test("switch (abc) { default: continue; }", "(anonymous): Line 1:25 Illegal continue statement")
-
- test("do { abc } *", "(anonymous): Line 1:12 Unexpected token *")
-
- test("while (true) { break abc; }", "(anonymous): Line 1:16 Undefined label 'abc'")
-
- test("while (true) { continue abc; }", "(anonymous): Line 1:16 Undefined label 'abc'")
-
- test("abc: while (true) { (function(){ break abc; }); }", "(anonymous): Line 1:34 Undefined label 'abc'")
-
- test("abc: while (true) { (function(){ abc: break abc; }); }", nil)
-
- test("abc: while (true) { (function(){ continue abc; }); }", "(anonymous): Line 1:34 Undefined label 'abc'")
-
- test(`abc: if (0) break abc; else {}`, nil)
-
- test(`abc: if (0) { break abc; } else {}`, nil)
-
- test(`abc: if (0) { break abc } else {}`, nil)
-
- test("abc: while (true) { abc: while (true) {} }", "(anonymous): Line 1:21 Label 'abc' already exists")
-
- if false {
- // TODO When strict mode is implemented
- test("(function () { 'use strict'; delete abc; }())", "")
- }
-
- test("_: _: while (true) {]", "(anonymous): Line 1:4 Label '_' already exists")
-
- test("_:\n_:\nwhile (true) {]", "(anonymous): Line 2:1 Label '_' already exists")
-
- test("_:\n _:\nwhile (true) {]", "(anonymous): Line 2:4 Label '_' already exists")
-
- test("/Xyzzy(?!Nothing happens)/",
- "(anonymous): Line 1:1 Invalid regular expression: re2: Invalid (?!) <lookahead>")
-
- test("function(){}", "(anonymous): Line 1:9 Unexpected token (")
-
- test("\n/*/", "(anonymous): Line 2:4 Unexpected end of input")
-
- test("/*/.source", "(anonymous): Line 1:11 Unexpected end of input")
-
- test("/\\1/.source", "(anonymous): Line 1:1 Invalid regular expression: re2: Invalid \\1 <backreference>")
-
- test("var class", "(anonymous): Line 1:5 Unexpected reserved word")
-
- test("var if", "(anonymous): Line 1:5 Unexpected token if")
-
- test("object Object", "(anonymous): Line 1:8 Unexpected identifier")
-
- test("[object Object]", "(anonymous): Line 1:9 Unexpected identifier")
-
- test("\\u0xyz", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test(`for (var abc, def in {}) {}`, "(anonymous): Line 1:19 Unexpected token in")
-
- test(`for (abc, def in {}) {}`, "(anonymous): Line 1:1 Invalid left-hand side in for-in")
-
- test(`for (var abc=def, ghi=("abc" in {}); true;) {}`, nil)
-
- {
- // Semicolon insertion
-
- test("this\nif (1);", nil)
-
- test("while (1) { break\nif (1); }", nil)
-
- test("throw\nif (1);", "(anonymous): Line 1:1 Illegal newline after throw")
-
- test("(function(){ return\nif (1); })", nil)
-
- test("while (1) { continue\nif (1); }", nil)
-
- test("debugger\nif (1);", nil)
- }
-
- { // Reserved words
-
- test("class", "(anonymous): Line 1:1 Unexpected reserved word")
- test("abc.class = 1", nil)
- test("var class;", "(anonymous): Line 1:5 Unexpected reserved word")
-
- test("const", "(anonymous): Line 1:1 Unexpected reserved word")
- test("abc.const = 1", nil)
- test("var const;", "(anonymous): Line 1:5 Unexpected reserved word")
-
- test("enum", "(anonymous): Line 1:1 Unexpected reserved word")
- test("abc.enum = 1", nil)
- test("var enum;", "(anonymous): Line 1:5 Unexpected reserved word")
-
- test("export", "(anonymous): Line 1:1 Unexpected reserved word")
- test("abc.export = 1", nil)
- test("var export;", "(anonymous): Line 1:5 Unexpected reserved word")
-
- test("extends", "(anonymous): Line 1:1 Unexpected reserved word")
- test("abc.extends = 1", nil)
- test("var extends;", "(anonymous): Line 1:5 Unexpected reserved word")
-
- test("import", "(anonymous): Line 1:1 Unexpected reserved word")
- test("abc.import = 1", nil)
- test("var import;", "(anonymous): Line 1:5 Unexpected reserved word")
-
- test("super", "(anonymous): Line 1:1 Unexpected reserved word")
- test("abc.super = 1", nil)
- test("var super;", "(anonymous): Line 1:5 Unexpected reserved word")
- }
-
- { // Reserved words (strict)
-
- test(`implements`, nil)
- test(`abc.implements = 1`, nil)
- test(`var implements;`, nil)
-
- test(`interface`, nil)
- test(`abc.interface = 1`, nil)
- test(`var interface;`, nil)
-
- test(`let`, nil)
- test(`abc.let = 1`, nil)
- test(`var let;`, nil)
-
- test(`package`, nil)
- test(`abc.package = 1`, nil)
- test(`var package;`, nil)
-
- test(`private`, nil)
- test(`abc.private = 1`, nil)
- test(`var private;`, nil)
-
- test(`protected`, nil)
- test(`abc.protected = 1`, nil)
- test(`var protected;`, nil)
-
- test(`public`, nil)
- test(`abc.public = 1`, nil)
- test(`var public;`, nil)
-
- test(`static`, nil)
- test(`abc.static = 1`, nil)
- test(`var static;`, nil)
-
- test(`yield`, nil)
- test(`abc.yield = 1`, nil)
- test(`var yield;`, nil)
- }
- })
-}
-
-func TestParser(t *testing.T) {
- tt(t, func() {
- test := func(source string, chk interface{}) *ast.Program {
- _, program, err := testParse(source)
- is(firstErr(err), chk)
- return program
- }
-
- test(`
- abc
- --
- []
- `, "(anonymous): Line 3:13 Invalid left-hand side in assignment")
-
- test(`
- abc--
- []
- `, nil)
-
- test("1\n[]\n", "(anonymous): Line 2:2 Unexpected token ]")
-
- test(`
- function abc() {
- }
- abc()
- `, nil)
-
- program := test("", nil)
-
- test("//", nil)
-
- test("/* */", nil)
-
- test("/** **/", nil)
-
- test("/*****/", nil)
-
- test("/*", "(anonymous): Line 1:3 Unexpected end of input")
-
- test("#", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("/**/#", "(anonymous): Line 1:5 Unexpected token ILLEGAL")
-
- test("new +", "(anonymous): Line 1:5 Unexpected token +")
-
- program = test(";", nil)
- is(len(program.Body), 1)
- is(program.Body[0].(*ast.EmptyStatement).Semicolon, file.Idx(1))
-
- program = test(";;", nil)
- is(len(program.Body), 2)
- is(program.Body[0].(*ast.EmptyStatement).Semicolon, file.Idx(1))
- is(program.Body[1].(*ast.EmptyStatement).Semicolon, file.Idx(2))
-
- program = test("1.2", nil)
- is(len(program.Body), 1)
- is(program.Body[0].(*ast.ExpressionStatement).Expression.(*ast.NumberLiteral).Literal, "1.2")
-
- program = test("/* */1.2", nil)
- is(len(program.Body), 1)
- is(program.Body[0].(*ast.ExpressionStatement).Expression.(*ast.NumberLiteral).Literal, "1.2")
-
- program = test("\n", nil)
- is(len(program.Body), 0)
-
- test(`
- if (0) {
- abc = 0
- }
- else abc = 0
- `, nil)
-
- test("if (0) abc = 0 else abc = 0", "(anonymous): Line 1:16 Unexpected token else")
-
- test(`
- if (0) {
- abc = 0
- } else abc = 0
- `, nil)
-
- test(`
- if (0) {
- abc = 1
- } else {
- }
- `, nil)
-
- test(`
- do {
- } while (true)
- `, nil)
-
- test(`
- try {
- } finally {
- }
- `, nil)
-
- test(`
- try {
- } catch (abc) {
- } finally {
- }
- `, nil)
-
- test(`
- try {
- }
- catch (abc) {
- }
- finally {
- }
- `, nil)
-
- test(`try {} catch (abc) {} finally {}`, nil)
-
- test(`
- do {
- do {
- } while (0)
- } while (0)
- `, nil)
-
- test(`
- (function(){
- try {
- if (
- 1
- ) {
- return 1
- }
- return 0
- } finally {
- }
- })()
- `, nil)
-
- test("abc = ''\ndef", nil)
-
- test("abc = 1\ndef", nil)
-
- test("abc = Math\ndef", nil)
-
- test(`"\'"`, nil)
-
- test(`
- abc = function(){
- }
- abc = 0
- `, nil)
-
- test("abc.null = 0", nil)
-
- test("0x41", nil)
-
- test(`"\d"`, nil)
-
- test(`(function(){return this})`, nil)
-
- test(`
- Object.defineProperty(Array.prototype, "0", {
- value: 100,
- writable: false,
- configurable: true
- });
- abc = [101];
- abc.hasOwnProperty("0") && abc[0] === 101;
- `, nil)
-
- test(`new abc()`, nil)
- test(`new {}`, nil)
-
- test(`
- limit = 4
- result = 0
- while (limit) {
- limit = limit - 1
- if (limit) {
- }
- else {
- break
- }
- result = result + 1
- }
- `, nil)
-
- test(`
- while (0) {
- if (0) {
- continue
- }
- }
- `, nil)
-
- test("var \u0061\u0062\u0063 = 0", nil)
-
- // 7_3_1
- test("var test7_3_1\nabc = 66;", nil)
- test("var test7_3_1\u2028abc = 66;", nil)
-
- // 7_3_3
- test("//\u2028 =;", "(anonymous): Line 2:2 Unexpected token =")
-
- // 7_3_10
- test("var abc = \u2029;", "(anonymous): Line 2:1 Unexpected token ;")
- test("var abc = \\u2029;", "(anonymous): Line 1:11 Unexpected token ILLEGAL")
- test("var \\u0061\\u0062\\u0063 = 0;", nil)
-
- test("'", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- test("'\nstr\ning\n'", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
-
- // S7.6_A4.3_T1
- test(`var $\u0030 = 0;`, nil)
-
- // S7.6.1.1_A1.1
- test(`switch = 1`, "(anonymous): Line 1:8 Unexpected token =")
-
- // S7.8.3_A2.1_T1
- test(`.0 === 0.0`, nil)
-
- // 7.8.5-1
- test("var regExp = /\\\rn/;", "(anonymous): Line 1:14 Invalid regular expression: missing /")
-
- // S7.8.5_A1.1_T2
- test("var regExp = /=/;", nil)
-
- // S7.8.5_A1.2_T1
- test("/*/", "(anonymous): Line 1:4 Unexpected end of input")
-
- // Sbp_7.9_A9_T3
- test(`
- do {
- ;
- } while (false) true
- `, nil)
-
- // S7.9_A10_T10
- test(`
- {a:1
- } 3
- `, nil)
-
- test(`
- abc
- ++def
- `, nil)
-
- // S7.9_A5.2_T1
- test(`
- for(false;false
- ) {
- break;
- }
- `, "(anonymous): Line 3:13 Unexpected token )")
-
- // S7.9_A9_T8
- test(`
- do {};
- while (false)
- `, "(anonymous): Line 2:18 Unexpected token ;")
-
- // S8.4_A5
- test(`
- "x\0y"
- `, nil)
-
- // S9.3.1_A6_T1
- test(`
- 10e10000
- `, nil)
-
- // 10.4.2-1-5
- test(`
- "abc\
- def"
- `, nil)
-
- test("'\\\n'", nil)
-
- test("'\\\r\n'", nil)
-
- //// 11.13.1-1-1
- test("42 = 42;", "(anonymous): Line 1:1 Invalid left-hand side in assignment")
-
- // S11.13.2_A4.2_T1.3
- test(`
- abc /= "1"
- `, nil)
-
- // 12.1-1
- test(`
- try{};catch(){}
- `, "(anonymous): Line 2:13 Missing catch or finally after try")
-
- // 12.1-3
- test(`
- try{};finally{}
- `, "(anonymous): Line 2:13 Missing catch or finally after try")
-
- // S12.6.3_A11.1_T3
- test(`
- while (true) {
- break abc;
- }
- `, "(anonymous): Line 3:17 Undefined label 'abc'")
-
- // S15.3_A2_T1
- test(`var x / = 1;`, "(anonymous): Line 1:7 Unexpected token /")
-
- test(`
- function abc() {
- if (0)
- return;
- else {
- }
- }
- `, nil)
-
- test("//\u2028 var =;", "(anonymous): Line 2:6 Unexpected token =")
-
- test(`
- throw
- {}
- `, "(anonymous): Line 2:13 Illegal newline after throw")
-
- // S7.6.1.1_A1.11
- test(`
- function = 1
- `, "(anonymous): Line 2:22 Unexpected token =")
-
- // S7.8.3_A1.2_T1
- test(`0e1`, nil)
-
- test("abc = 1; abc\n++", "(anonymous): Line 2:3 Unexpected end of input")
-
- // ---
-
- test("({ get abc() {} })", nil)
-
- test(`for (abc.def in {}) {}`, nil)
-
- test(`while (true) { break }`, nil)
-
- test(`while (true) { continue }`, nil)
-
- test(`abc=/^(?:(\w+:)\/{2}(\w+(?:\.\w+)*\/?)|(.{0,2}\/{1}))?([/.]*?(?:[^?]+)?\/)?((?:[^/?]+)\.(\w+))(?:\?(\S+)?)?$/,def=/^(?:(\w+:)\/{2})|(.{0,2}\/{1})?([/.]*?(?:[^?]+)?\/?)?$/`, nil)
-
- test(`(function() { try {} catch (err) {} finally {} return })`, nil)
-
- test(`0xde0b6b3a7640080.toFixed(0)`, nil)
-
- test(`/[^-._0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u37f-\u1fff\u200c-\u200d\u203f\u2040\u2070-\u218f]/`, nil)
-
- test(`/[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE-\uFFFF]/`, nil)
-
- test("var abc = 1;\ufeff", nil)
-
- test("\ufeff/* var abc = 1; */", nil)
-
- test(`if (-0x8000000000000000<=abc&&abc<=0x8000000000000000) {}`, nil)
-
- test(`(function(){debugger;return this;})`, nil)
-
- test(`
-
- `, nil)
-
- test(`
- var abc = ""
- debugger
- `, nil)
-
- test(`
- var abc = /\[\]$/
- debugger
- `, nil)
-
- test(`
- var abc = 1 /
- 2
- debugger
- `, nil)
- })
-}
-
-func Test_parseStringLiteral(t *testing.T) {
- tt(t, func() {
- test := func(have, want string) {
- have, err := parseStringLiteral(have)
- is(err, nil)
- is(have, want)
- }
-
- test("", "")
-
- test("1(\\\\d+)", "1(\\d+)")
-
- test("\\u2029", "\u2029")
-
- test("abc\\uFFFFabc", "abc\uFFFFabc")
-
- test("[First line \\\nSecond line \\\n Third line\\\n. ]",
- "[First line Second line Third line. ]")
-
- test("\\u007a\\x79\\u000a\\x78", "zy\nx")
-
- // S7.8.4_A4.2_T3
- test("\\a", "a")
- test("\u0410", "\u0410")
-
- // S7.8.4_A5.1_T1
- test("\\0", "\u0000")
-
- // S8.4_A5
- test("\u0000", "\u0000")
-
- // 15.5.4.20
- test("'abc'\\\n'def'", "'abc''def'")
-
- // 15.5.4.20-4-1
- test("'abc'\\\r\n'def'", "'abc''def'")
-
- // Octal
- test("\\0", "\000")
- test("\\00", "\000")
- test("\\000", "\000")
- test("\\09", "\0009")
- test("\\009", "\0009")
- test("\\0009", "\0009")
- test("\\1", "\001")
- test("\\01", "\001")
- test("\\001", "\001")
- test("\\0011", "\0011")
- test("\\1abc", "\001abc")
-
- test("\\\u4e16", "\u4e16")
-
- // err
- test = func(have, want string) {
- have, err := parseStringLiteral(have)
- is(err.Error(), want)
- is(have, "")
- }
-
- test(`\u`, `invalid escape: \u: len("") != 4`)
- test(`\u0`, `invalid escape: \u: len("0") != 4`)
- test(`\u00`, `invalid escape: \u: len("00") != 4`)
- test(`\u000`, `invalid escape: \u: len("000") != 4`)
-
- test(`\x`, `invalid escape: \x: len("") != 2`)
- test(`\x0`, `invalid escape: \x: len("0") != 2`)
- test(`\x0`, `invalid escape: \x: len("0") != 2`)
- })
-}
-
-func Test_parseNumberLiteral(t *testing.T) {
- tt(t, func() {
- test := func(input string, expect interface{}) {
- result, err := parseNumberLiteral(input)
- is(err, nil)
- is(result, expect)
- }
-
- test("0", 0)
-
- test("0x8000000000000000", float64(9.223372036854776e+18))
- })
-}
-
-func TestPosition(t *testing.T) {
- tt(t, func() {
- parser := newParser("", "// Lorem ipsum")
-
- // Out of range, idx0 (error condition)
- is(parser.slice(0, 1), "")
- is(parser.slice(0, 10), "")
-
- // Out of range, idx1 (error condition)
- is(parser.slice(1, 128), "")
-
- is(parser.str[0:0], "")
- is(parser.slice(1, 1), "")
-
- is(parser.str[0:1], "/")
- is(parser.slice(1, 2), "/")
-
- is(parser.str[0:14], "// Lorem ipsum")
- is(parser.slice(1, 15), "// Lorem ipsum")
-
- parser = newParser("", "(function(){ return 0; })")
- program, err := parser.parse()
- is(err, nil)
-
- var node ast.Node
- node = program.Body[0].(*ast.ExpressionStatement).Expression.(*ast.FunctionLiteral)
- is(node.Idx0(), file.Idx(2))
- is(node.Idx1(), file.Idx(25))
- is(parser.slice(node.Idx0(), node.Idx1()), "function(){ return 0; }")
- is(parser.slice(node.Idx0(), node.Idx1()+1), "function(){ return 0; })")
- is(parser.slice(node.Idx0(), node.Idx1()+2), "")
- is(node.(*ast.FunctionLiteral).Source, "function(){ return 0; }")
-
- node = program
- is(node.Idx0(), file.Idx(2))
- is(node.Idx1(), file.Idx(25))
- is(parser.slice(node.Idx0(), node.Idx1()), "function(){ return 0; }")
-
- parser = newParser("", "(function(){ return abc; })")
- program, err = parser.parse()
- is(err, nil)
- node = program.Body[0].(*ast.ExpressionStatement).Expression.(*ast.FunctionLiteral)
- is(node.(*ast.FunctionLiteral).Source, "function(){ return abc; }")
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/regexp_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/regexp_test.go
deleted file mode 100644
index 3222db1a7..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/parser/regexp_test.go
+++ /dev/null
@@ -1,149 +0,0 @@
-package parser
-
-import (
- "regexp"
- "testing"
-)
-
-func TestRegExp(t *testing.T) {
- tt(t, func() {
- {
- // err
- test := func(input string, expect interface{}) {
- _, err := TransformRegExp(input)
- is(err, expect)
- }
-
- test("[", "Unterminated character class")
-
- test("(", "Unterminated group")
-
- test("(?=)", "re2: Invalid (?=) <lookahead>")
-
- test("(?=)", "re2: Invalid (?=) <lookahead>")
-
- test("(?!)", "re2: Invalid (?!) <lookahead>")
-
- // An error anyway
- test("(?=", "re2: Invalid (?=) <lookahead>")
-
- test("\\1", "re2: Invalid \\1 <backreference>")
-
- test("\\90", "re2: Invalid \\90 <backreference>")
-
- test("\\9123456789", "re2: Invalid \\9123456789 <backreference>")
-
- test("\\(?=)", "Unmatched ')'")
-
- test(")", "Unmatched ')'")
- }
-
- {
- // err
- test := func(input, expect string, expectErr interface{}) {
- output, err := TransformRegExp(input)
- is(output, expect)
- is(err, expectErr)
- }
-
- test("(?!)", "(?!)", "re2: Invalid (?!) <lookahead>")
-
- test(")", "", "Unmatched ')'")
-
- test("(?!))", "", "re2: Invalid (?!) <lookahead>")
-
- test("\\0", "\\0", nil)
-
- test("\\1", "\\1", "re2: Invalid \\1 <backreference>")
-
- test("\\9123456789", "\\9123456789", "re2: Invalid \\9123456789 <backreference>")
- }
-
- {
- // err
- test := func(input string, expect string) {
- result, err := TransformRegExp(input)
- is(err, nil)
- if is(result, expect) {
- _, err := regexp.Compile(result)
- if !is(err, nil) {
- t.Log(result)
- }
- }
- }
-
- test("", "")
-
- test("abc", "abc")
-
- test(`\abc`, `abc`)
-
- test(`\a\b\c`, `a\bc`)
-
- test(`\x`, `x`)
-
- test(`\c`, `c`)
-
- test(`\cA`, `\x01`)
-
- test(`\cz`, `\x1a`)
-
- test(`\ca`, `\x01`)
-
- test(`\cj`, `\x0a`)
-
- test(`\ck`, `\x0b`)
-
- test(`\+`, `\+`)
-
- test(`[\b]`, `[\x08]`)
-
- test(`\u0z01\x\undefined`, `u0z01xundefined`)
-
- test(`\\|'|\r|\n|\t|\u2028|\u2029`, `\\|'|\r|\n|\t|\x{2028}|\x{2029}`)
-
- test("]", "]")
-
- test("}", "}")
-
- test("%", "%")
-
- test("(%)", "(%)")
-
- test("(?:[%\\s])", "(?:[%\\s])")
-
- test("[[]", "[[]")
-
- test("\\101", "\\x41")
-
- test("\\51", "\\x29")
-
- test("\\051", "\\x29")
-
- test("\\175", "\\x7d")
-
- test("\\04", "\\x04")
-
- test(`<%([\s\S]+?)%>`, `<%([\s\S]+?)%>`)
-
- test(`(.)^`, "(.)^")
-
- test(`<%-([\s\S]+?)%>|<%=([\s\S]+?)%>|<%([\s\S]+?)%>|$`, `<%-([\s\S]+?)%>|<%=([\s\S]+?)%>|<%([\s\S]+?)%>|$`)
-
- test(`\$`, `\$`)
-
- test(`[G-b]`, `[G-b]`)
-
- test(`[G-b\0]`, `[G-b\0]`)
- }
- })
-}
-
-func TestTransformRegExp(t *testing.T) {
- tt(t, func() {
- pattern, err := TransformRegExp(`\s+abc\s+`)
- is(err, nil)
- is(pattern, `\s+abc\s+`)
- is(regexp.MustCompile(pattern).MatchString("\t abc def"), true)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/parser_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/parser_test.go
deleted file mode 100644
index 7db43d239..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/parser_test.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package otto
-
-import (
- "testing"
-)
-
-func TestPersistence(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- function abc() { return 1; }
- abc.toString();
- `, "function abc() { return 1; }")
-
- test(`
- function def() { return 3.14159; }
- [ abc.toString(), def.toString() ];
- `, "function abc() { return 1; },function def() { return 3.14159; }")
-
- test(`
- eval("function ghi() { return 'ghi' }");
- [ abc.toString(), def.toString(), ghi.toString() ];
- `, "function abc() { return 1; },function def() { return 3.14159; },function ghi() { return 'ghi' }")
-
- test(`
- [ abc.toString(), def.toString(), ghi.toString() ];
- `, "function abc() { return 1; },function def() { return 3.14159; },function ghi() { return 'ghi' }")
-
- test(`/*
-
-
-
-
-
-
-
-
-
- */`, UndefinedValue())
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/reflect_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/reflect_test.go
deleted file mode 100644
index e4e83adeb..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/reflect_test.go
+++ /dev/null
@@ -1,483 +0,0 @@
-package otto
-
-import (
- "math"
- "reflect"
- "testing"
-)
-
-type _abcStruct struct {
- Abc bool
- Def int
- Ghi string
- Jkl interface{}
- Mno _mnoStruct
- Pqr map[string]int8
-}
-
-func (abc _abcStruct) String() string {
- return abc.Ghi
-}
-
-func (abc *_abcStruct) FuncPointer() string {
- return "abc"
-}
-
-func (abc _abcStruct) Func() {
- return
-}
-
-func (abc _abcStruct) FuncReturn1() string {
- return "abc"
-}
-
-func (abc _abcStruct) FuncReturn2() (string, error) {
- return "def", nil
-}
-
-func (abc _abcStruct) Func1Return1(a string) string {
- return a
-}
-
-func (abc _abcStruct) Func2Return1(x, y string) string {
- return x + y
-}
-
-func (abc _abcStruct) FuncEllipsis(xyz ...string) int {
- return len(xyz)
-}
-
-func (abc _abcStruct) FuncReturnStruct() _mnoStruct {
- return _mnoStruct{}
-}
-
-type _mnoStruct struct {
- Ghi string
-}
-
-func (mno _mnoStruct) Func() string {
- return "mno"
-}
-
-func TestReflect(t *testing.T) {
- if true {
- return
- }
- tt(t, func() {
- // Testing dbgf
- // These should panic
- toValue("Xyzzy").toReflectValue(reflect.Ptr)
- stringToReflectValue("Xyzzy", reflect.Ptr)
- })
-}
-
-func Test_reflectStruct(t *testing.T) {
- tt(t, func() {
- test, vm := test()
-
- // _abcStruct
- {
- abc := &_abcStruct{}
- vm.Set("abc", abc)
-
- test(`
- [ abc.Abc, abc.Ghi ];
- `, "false,")
-
- abc.Abc = true
- abc.Ghi = "Nothing happens."
-
- test(`
- [ abc.Abc, abc.Ghi ];
- `, "true,Nothing happens.")
-
- *abc = _abcStruct{}
-
- test(`
- [ abc.Abc, abc.Ghi ];
- `, "false,")
-
- abc.Abc = true
- abc.Ghi = "Xyzzy"
- vm.Set("abc", abc)
-
- test(`
- [ abc.Abc, abc.Ghi ];
- `, "true,Xyzzy")
-
- is(abc.Abc, true)
- test(`
- abc.Abc = false;
- abc.Def = 451;
- abc.Ghi = "Nothing happens.";
- abc.abc = "Something happens.";
- [ abc.Def, abc.abc ];
- `, "451,Something happens.")
- is(abc.Abc, false)
- is(abc.Def, 451)
- is(abc.Ghi, "Nothing happens.")
-
- test(`
- delete abc.Def;
- delete abc.abc;
- [ abc.Def, abc.abc ];
- `, "451,")
- is(abc.Def, 451)
-
- test(`
- abc.FuncPointer();
- `, "abc")
-
- test(`
- abc.Func();
- `, "undefined")
-
- test(`
- abc.FuncReturn1();
- `, "abc")
-
- test(`
- abc.Func1Return1("abc");
- `, "abc")
-
- test(`
- abc.Func2Return1("abc", "def");
- `, "abcdef")
-
- test(`
- abc.FuncEllipsis("abc", "def", "ghi");
- `, 3)
-
- test(`raise:
- abc.FuncReturn2();
- `, "TypeError")
-
- test(`
- abc.FuncReturnStruct();
- `, "[object Object]")
-
- test(`
- abc.FuncReturnStruct().Func();
- `, "mno")
- }
- })
-}
-
-func Test_reflectMap(t *testing.T) {
- tt(t, func() {
- test, vm := test()
-
- // map[string]string
- {
- abc := map[string]string{
- "Xyzzy": "Nothing happens.",
- "def": "1",
- }
- vm.Set("abc", abc)
-
- test(`
- abc.xyz = "pqr";
- [ abc.Xyzzy, abc.def, abc.ghi ];
- `, "Nothing happens.,1,")
-
- is(abc["xyz"], "pqr")
- }
-
- // map[string]float64
- {
- abc := map[string]float64{
- "Xyzzy": math.Pi,
- "def": 1,
- }
- vm.Set("abc", abc)
-
- test(`
- abc.xyz = "pqr";
- abc.jkl = 10;
- [ abc.Xyzzy, abc.def, abc.ghi ];
- `, "3.141592653589793,1,")
-
- is(abc["xyz"], math.NaN())
- is(abc["jkl"], float64(10))
- }
-
- // map[string]int32
- {
- abc := map[string]int32{
- "Xyzzy": 3,
- "def": 1,
- }
- vm.Set("abc", abc)
-
- test(`
- abc.xyz = "pqr";
- abc.jkl = 10;
- [ abc.Xyzzy, abc.def, abc.ghi ];
- `, "3,1,")
-
- is(abc["xyz"], 0)
- is(abc["jkl"], int32(10))
-
- test(`
- delete abc["Xyzzy"];
- `)
-
- _, exists := abc["Xyzzy"]
- is(exists, false)
- is(abc["Xyzzy"], 0)
- }
-
- // map[int32]string
- {
- abc := map[int32]string{
- 0: "abc",
- 1: "def",
- }
- vm.Set("abc", abc)
-
- test(`
- abc[2] = "pqr";
- //abc.jkl = 10;
- abc[3] = 10;
- [ abc[0], abc[1], abc[2], abc[3] ]
- `, "abc,def,pqr,10")
-
- is(abc[2], "pqr")
- is(abc[3], "10")
-
- test(`
- delete abc[2];
- `)
-
- _, exists := abc[2]
- is(exists, false)
- }
-
- })
-}
-
-func Test_reflectSlice(t *testing.T) {
- tt(t, func() {
- test, vm := test()
-
- // []bool
- {
- abc := []bool{
- false,
- true,
- true,
- false,
- }
- vm.Set("abc", abc)
-
- test(`
- abc;
- `, "false,true,true,false")
-
- test(`
- abc[0] = true;
- abc[abc.length-1] = true;
- delete abc[2];
- abc;
- `, "true,true,false,true")
-
- is(abc, []bool{true, true, false, true})
- is(abc[len(abc)-1], true)
- }
-
- // []int32
- {
- abc := make([]int32, 4)
- vm.Set("abc", abc)
-
- test(`
- abc;
- `, "0,0,0,0")
-
- test(`
- abc[0] = 4.2;
- abc[1] = "42";
- abc[2] = 3.14;
- abc;
- `, "4,42,3,0")
-
- is(abc, []int32{4, 42, 3, 0})
-
- test(`
- delete abc[1];
- delete abc[2];
- `)
- is(abc[1], 0)
- is(abc[2], 0)
- }
- })
-}
-
-func Test_reflectArray(t *testing.T) {
- tt(t, func() {
- test, vm := test()
-
- // []bool
- {
- abc := [4]bool{
- false,
- true,
- true,
- false,
- }
- vm.Set("abc", abc)
-
- test(`
- abc;
- `, "false,true,true,false")
- // Unaddressable array
-
- test(`
- abc[0] = true;
- abc[abc.length-1] = true;
- abc;
- `, "false,true,true,false")
- // Again, unaddressable array
-
- is(abc, [4]bool{false, true, true, false})
- is(abc[len(abc)-1], false)
- // ...
- }
-
- // []int32
- {
- abc := make([]int32, 4)
- vm.Set("abc", abc)
-
- test(`
- abc;
- `, "0,0,0,0")
-
- test(`
- abc[0] = 4.2;
- abc[1] = "42";
- abc[2] = 3.14;
- abc;
- `, "4,42,3,0")
-
- is(abc, []int32{4, 42, 3, 0})
- }
-
- // []bool
- {
- abc := [4]bool{
- false,
- true,
- true,
- false,
- }
- vm.Set("abc", &abc)
-
- test(`
- abc;
- `, "false,true,true,false")
-
- test(`
- abc[0] = true;
- abc[abc.length-1] = true;
- delete abc[2];
- abc;
- `, "true,true,false,true")
-
- is(abc, [4]bool{true, true, false, true})
- is(abc[len(abc)-1], true)
- }
-
- })
-}
-
-func Test_reflectArray_concat(t *testing.T) {
- tt(t, func() {
- test, vm := test()
-
- vm.Set("ghi", []string{"jkl", "mno"})
- vm.Set("pqr", []interface{}{"jkl", 42, 3.14159, true})
- test(`
- var def = {
- "abc": ["abc"],
- "xyz": ["xyz"]
- };
- xyz = pqr.concat(ghi, def.abc, def, def.xyz);
- [ xyz, xyz.length ];
- `, "jkl,42,3.14159,true,jkl,mno,abc,[object Object],xyz,9")
- })
-}
-
-func Test_reflectMapInterface(t *testing.T) {
- tt(t, func() {
- test, vm := test()
-
- {
- abc := map[string]interface{}{
- "Xyzzy": "Nothing happens.",
- "def": "1",
- "jkl": "jkl",
- }
- vm.Set("abc", abc)
- vm.Set("mno", &_abcStruct{})
-
- test(`
- abc.xyz = "pqr";
- abc.ghi = {};
- abc.jkl = 3.14159;
- abc.mno = mno;
- mno.Abc = true;
- mno.Ghi = "Something happens.";
- [ abc.Xyzzy, abc.def, abc.ghi, abc.mno ];
- `, "Nothing happens.,1,[object Object],[object Object]")
-
- is(abc["xyz"], "pqr")
- is(abc["ghi"], "[object Object]")
- is(abc["jkl"], float64(3.14159))
- mno, valid := abc["mno"].(*_abcStruct)
- is(valid, true)
- is(mno.Abc, true)
- is(mno.Ghi, "Something happens.")
- }
- })
-}
-
-func TestPassthrough(t *testing.T) {
- tt(t, func() {
- test, vm := test()
-
- {
- abc := &_abcStruct{
- Mno: _mnoStruct{
- Ghi: "<Mno.Ghi>",
- },
- }
- vm.Set("abc", abc)
-
- test(`
- abc.Mno.Ghi;
- `, "<Mno.Ghi>")
-
- vm.Set("pqr", map[string]int8{
- "xyzzy": 0,
- "Nothing happens.": 1,
- })
-
- test(`
- abc.Ghi = "abc";
- abc.Pqr = pqr;
- abc.Pqr["Nothing happens."];
- `, 1)
-
- mno := _mnoStruct{
- Ghi: "<mno.Ghi>",
- }
- vm.Set("mno", mno)
-
- test(`
- abc.Mno = mno;
- abc.Mno.Ghi;
- `, "<mno.Ghi>")
- }
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/regexp_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/regexp_test.go
deleted file mode 100644
index 8e65ee46a..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/regexp_test.go
+++ /dev/null
@@ -1,290 +0,0 @@
-package otto
-
-import (
- "fmt"
- "testing"
-)
-
-func TestRegExp(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- [
- /abc/.toString(),
- /abc/gim.toString(),
- ""+/abc/gi.toString(),
- new RegExp("1(\\d+)").toString(),
- ];
- `, "/abc/,/abc/gim,/abc/gi,/1(\\d+)/")
-
- test(`
- [
- new RegExp("abc").exec("123abc456"),
- null === new RegExp("xyzzy").exec("123abc456"),
- new RegExp("1(\\d+)").exec("123abc456"),
- new RegExp("xyzzy").test("123abc456"),
- new RegExp("1(\\d+)").test("123abc456"),
- new RegExp("abc").exec("123abc456"),
- ];
- `, "abc,true,123,23,false,true,abc")
-
- test(`new RegExp("abc").toString()`, "/abc/")
- test(`new RegExp("abc", "g").toString()`, "/abc/g")
- test(`new RegExp("abc", "mig").toString()`, "/abc/gim")
-
- result := test(`/(a)?/.exec('b')`, ",")
- is(result._object().get("0"), "")
- is(result._object().get("1"), "undefined")
- is(result._object().get("length"), 2)
-
- result = test(`/(a)?(b)?/.exec('b')`, "b,,b")
- is(result._object().get("0"), "b")
- is(result._object().get("1"), "undefined")
- is(result._object().get("2"), "b")
- is(result._object().get("length"), 3)
-
- test(`/\u0041/.source`, "\\u0041")
- test(`/\a/.source`, "\\a")
- test(`/\;/.source`, "\\;")
-
- test(`/a\a/.source`, "a\\a")
- test(`/,\;/.source`, ",\\;")
- test(`/ \ /.source`, " \\ ")
-
- // Start sanity check...
- test("eval(\"/abc/\").source", "abc")
- test("eval(\"/\u0023/\").source", "#")
- test("eval(\"/\u0058/\").source", "X")
- test("eval(\"/\\\u0023/\").source == \"\\\u0023\"", true)
- test("'0x' + '0058'", "0x0058")
- test("'\\\\' + '0x' + '0058'", "\\0x0058")
- // ...stop sanity check
-
- test(`abc = '\\' + String.fromCharCode('0x' + '0058'); eval('/' + abc + '/').source`, "\\X")
- test(`abc = '\\' + String.fromCharCode('0x0058'); eval('/' + abc + '/').source == "\\\u0058"`, true)
- test(`abc = '\\' + String.fromCharCode('0x0023'); eval('/' + abc + '/').source == "\\\u0023"`, true)
- test(`abc = '\\' + String.fromCharCode('0x0078'); eval('/' + abc + '/').source == "\\\u0078"`, true)
-
- test(`
- var abc = Object.getOwnPropertyDescriptor(RegExp, "prototype");
- [ [ typeof RegExp.prototype ],
- [ abc.writable, abc.enumerable, abc.configurable ] ];
- `, "object,false,false,false")
- })
-}
-
-func TestRegExp_global(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc = /(?:ab|cd)\d?/g;
- var found = [];
- do {
- match = abc.exec("ab cd2 ab34 cd");
- if (match !== null) {
- found.push(match[0]);
- } else {
- break;
- }
- } while (true);
- found;
- `, "ab,cd2,ab3,cd")
- })
-}
-
-func TestRegExp_exec(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = /./g;
- def = '123456';
- ghi = 0;
- while (ghi < 100 && abc.exec(def) !== null) {
- ghi += 1;
- }
- [ ghi, def.length, ghi == def.length ];
- `, "6,6,true")
-
- test(`
- abc = /[abc](\d)?/g;
- def = 'a0 b c1 d3';
- ghi = 0;
- lastIndex = 0;
- while (ghi < 100 && abc.exec(def) !== null) {
- lastIndex = abc.lastIndex;
- ghi += 1;
-
- }
- [ ghi, lastIndex ];
- `, "3,7")
-
- test(`
- var abc = /[abc](\d)?/.exec("a0 b c1 d3");
- [ abc.length, abc.input, abc.index, abc ];
- `, "2,a0 b c1 d3,0,a0,0")
-
- test(`raise:
- var exec = RegExp.prototype.exec;
- exec("Xyzzy");
- `, "TypeError: Calling RegExp.exec on a non-RegExp object")
-
- test(`
- var abc = /\w{3}\d?/.exec("CE\uFFFFL\uFFDDbox127");
- [ abc.input.length, abc.length, abc.input, abc.index, abc ];
- `, "11,1,CE\uFFFFL\uFFDDbox127,5,box1")
-
- test(`RegExp.prototype.exec.length`, 1)
- test(`RegExp.prototype.exec.prototype`, "undefined")
- })
-}
-
-func TestRegExp_test(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`RegExp.prototype.test.length`, 1)
- test(`RegExp.prototype.test.prototype`, "undefined")
- })
-}
-
-func TestRegExp_toString(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`RegExp.prototype.toString.length`, 0)
- test(`RegExp.prototype.toString.prototype`, "undefined")
- })
-}
-
-func TestRegExp_zaacbbbcac(t *testing.T) {
- if true {
- return
- }
-
- tt(t, func() {
- test, _ := test()
-
- // FIXME? TODO /(z)((a+)?(b+)?(c))*/.exec("zaacbbbcac")
- test(`
- var abc = /(z)((a+)?(b+)?(c))*/.exec("zaacbbbcac");
- [ abc.length, abc.index, abc ];
- `, "6,0,zaacbbbcac,z,ac,a,,c")
- })
-}
-
-func TestRegExpCopying(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = /xyzzy/i;
- def = RegExp(abc);
- abc.indicator = 1;
- [ abc.indicator, def.indicator ];
- `, "1,1")
-
- test(`raise:
- RegExp(new RegExp("\\d"), "1");
- `, "TypeError: Cannot supply flags when constructing one RegExp from another")
- })
-}
-
-func TestRegExp_multiline(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc = /s$/m.exec("pairs\nmakes\tdouble");
- [ abc.length, abc.index, abc ];
- `, "1,4,s")
- })
-}
-
-func TestRegExp_source(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- [ /xyzzy/i.source, /./i.source ];
- `, "xyzzy,.")
-
- test(`
- var abc = /./i;
- var def = new RegExp(abc);
- [ abc.source, def.source, abc.source === def.source ];
- `, ".,.,true")
-
- test(`
- var abc = /./i;
- var def = abc.hasOwnProperty("source");
- var ghi = abc.source;
- abc.source = "xyzzy";
- [ def, abc.source ];
- `, "true,.")
- })
-}
-
-func TestRegExp_newRegExp(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- Math.toString();
- var abc = new RegExp(Math,eval("\"g\""));
- [ abc, abc.global ];
- `, "/[object Math]/g,true")
- })
-}
-
-func TestRegExp_flags(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc = /./i;
- var def = new RegExp(abc);
- [ abc.multiline == def.multiline, abc.global == def.global, abc.ignoreCase == def.ignoreCase ];
- `, "true,true,true")
- })
-}
-
-func TestRegExp_controlCharacter(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- for code := 0x41; code < 0x5a; code++ {
- string_ := string(code - 64)
- test(fmt.Sprintf(`
- var code = 0x%x;
- var string = String.fromCharCode(code %% 32);
- var result = (new RegExp("\\c" + String.fromCharCode(code))).exec(string);
- [ code, string, result ];
- `, code), fmt.Sprintf("%d,%s,%s", code, string_, string_))
- }
- })
-}
-
-func TestRegExp_notNotEmptyCharacterClass(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc = /[\s\S]a/m.exec("a\naba");
- [ abc.length, abc.input, abc ];
- `, "1,a\naba,\na")
- })
-}
-
-func TestRegExp_compile(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc = /[\s\S]a/;
- abc.compile('^\w+');
- `, "undefined")
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/repl/repl.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/repl/repl.go
new file mode 100644
index 000000000..0d70cc051
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/robertkrimen/otto/repl/repl.go
@@ -0,0 +1,115 @@
+// Package repl implements a REPL (read-eval-print loop) for otto.
+package repl
+
+import (
+ "fmt"
+ "io"
+ "strings"
+ "sync/atomic"
+
+ "github.com/robertkrimen/otto"
+ "gopkg.in/readline.v1"
+)
+
+var counter uint32
+
+// DebuggerHandler implements otto's debugger handler signature, providing a
+// simple drop-in debugger implementation.
+func DebuggerHandler(vm *otto.Otto) {
+ i := atomic.AddUint32(&counter, 1)
+
+ // purposefully ignoring the error here - we can't do anything useful with
+ // it except panicking, and that'd be pretty rude. it'd be easy enough for a
+ // consumer to define an equivalent function that _does_ panic if desired.
+ _ = RunWithPrompt(vm, fmt.Sprintf("DEBUGGER[%d]>", i))
+}
+
+// Run creates a REPL with the default prompt and no prelude.
+func Run(vm *otto.Otto) error {
+ return RunWithPromptAndPrelude(vm, "", "")
+}
+
+// RunWithPrompt runs a REPL with the given prompt and no prelude.
+func RunWithPrompt(vm *otto.Otto, prompt string) error {
+ return RunWithPromptAndPrelude(vm, prompt, "")
+}
+
+// RunWithPrelude runs a REPL with the default prompt and the given prelude.
+func RunWithPrelude(vm *otto.Otto, prelude string) error {
+ return RunWithPromptAndPrelude(vm, "", prelude)
+}
+
+// RunWithPromptAndPrelude runs a REPL with the given prompt and prelude.
+func RunWithPromptAndPrelude(vm *otto.Otto, prompt, prelude string) error {
+ if prompt == "" {
+ prompt = ">"
+ }
+
+ prompt = strings.Trim(prompt, " ")
+ prompt += " "
+
+ rl, err := readline.New(prompt)
+ if err != nil {
+ return err
+ }
+
+ if prelude != "" {
+ if _, err := io.Copy(rl.Stderr(), strings.NewReader(prelude+"\n")); err != nil {
+ return err
+ }
+
+ rl.Refresh()
+ }
+
+ var d []string
+
+ for {
+ l, err := rl.Readline()
+ if err != nil {
+ if err == readline.ErrInterrupt {
+ if d != nil {
+ d = nil
+
+ rl.SetPrompt(prompt)
+ rl.Refresh()
+
+ continue
+ }
+
+ break
+ }
+
+ return err
+ }
+
+ if l == "" {
+ continue
+ }
+
+ d = append(d, l)
+
+ s, err := vm.Compile("repl", strings.Join(d, "\n"))
+ if err != nil {
+ rl.SetPrompt(strings.Repeat(" ", len(prompt)))
+ } else {
+ rl.SetPrompt(prompt)
+
+ d = nil
+
+ v, err := vm.Eval(s)
+ if err != nil {
+ if oerr, ok := err.(*otto.Error); ok {
+ io.Copy(rl.Stdout(), strings.NewReader(oerr.String()))
+ } else {
+ io.Copy(rl.Stdout(), strings.NewReader(err.Error()))
+ }
+ } else {
+ rl.Stdout().Write([]byte(v.String() + "\n"))
+ }
+ }
+
+ rl.Refresh()
+ }
+
+ return rl.Close()
+}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/runtime.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/runtime.go
index 1ac1b435e..168cb1cde 100644
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/runtime.go
+++ b/Godeps/_workspace/src/github.com/robertkrimen/otto/runtime.go
@@ -2,6 +2,8 @@ package otto
import (
"errors"
+ "fmt"
+ "math"
"reflect"
"sync"
@@ -52,6 +54,7 @@ type _runtime struct {
scope *_scope
otto *Otto
eval *_object // The builtin eval, for determine indirect versus direct invocation
+ debugger func(*Otto)
labels []string // FIXME
lck sync.Mutex
@@ -191,6 +194,148 @@ func (self *_runtime) safeToValue(value interface{}) (Value, error) {
return result, err
}
+// convertNumeric converts numeric parameter val from js to that of type t if it is safe to do so, otherwise it panics.
+// This allows literals (int64), bitwise values (int32) and the general form (float64) of javascript numerics to be passed as parameters to go functions easily.
+func convertNumeric(val reflect.Value, t reflect.Type) reflect.Value {
+ if val.Kind() == t.Kind() {
+ return val
+ }
+
+ if val.Kind() == reflect.Interface {
+ val = reflect.ValueOf(val.Interface())
+ }
+
+ switch val.Kind() {
+ case reflect.Float32, reflect.Float64:
+ f64 := val.Float()
+ switch t.Kind() {
+ case reflect.Float64:
+ return reflect.ValueOf(f64)
+ case reflect.Float32:
+ if reflect.Zero(t).OverflowFloat(f64) {
+ panic("converting float64 to float32 would overflow")
+ }
+
+ return val.Convert(t)
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
+ i64 := int64(f64)
+ if float64(i64) != f64 {
+ panic(fmt.Sprintf("converting %v to %v would cause loss of precision", val.Type(), t))
+ }
+
+ // The float represents an integer
+ val = reflect.ValueOf(i64)
+ default:
+ panic(fmt.Sprintf("cannot convert %v to %v", val.Type(), t))
+ }
+ }
+
+ switch val.Kind() {
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ i64 := val.Int()
+ switch t.Kind() {
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ if reflect.Zero(t).OverflowInt(i64) {
+ panic(fmt.Sprintf("converting %v to %v would overflow", val.Type(), t))
+ }
+ return val.Convert(t)
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
+ if i64 < 0 {
+ panic(fmt.Sprintf("converting %v to %v would underflow", val.Type(), t))
+ }
+ if reflect.Zero(t).OverflowUint(uint64(i64)) {
+ panic(fmt.Sprintf("converting %v to %v would overflow", val.Type(), t))
+ }
+ return val.Convert(t)
+ }
+
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
+ u64 := val.Uint()
+ switch t.Kind() {
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ if u64 > math.MaxInt64 || reflect.Zero(t).OverflowInt(int64(u64)) {
+ panic(fmt.Sprintf("converting %v to %v would overflow", val.Type(), t))
+ }
+ return val.Convert(t)
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
+ if reflect.Zero(t).OverflowUint(u64) {
+ panic(fmt.Sprintf("converting %v to %v would overflow", val.Type(), t))
+ }
+ return val.Convert(t)
+ }
+ }
+
+ panic(fmt.Sprintf("unsupported type %v for numeric conversion", val.Type()))
+}
+
+// callParamConvert converts request val to type t if possible.
+// If the conversion fails due to overflow or type miss-match then it panics.
+// If no conversion is known then the original value is returned.
+func callParamConvert(val reflect.Value, t reflect.Type) reflect.Value {
+ if val.Kind() == reflect.Interface {
+ val = reflect.ValueOf(val.Interface())
+ }
+
+ switch t.Kind() {
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64:
+ if val.Kind() == t.Kind() {
+ // Types already match
+ return val
+ }
+ return convertNumeric(val, t)
+ case reflect.Slice:
+ if val.Kind() != reflect.Slice {
+ // Conversion from none slice type to slice not possible
+ panic(fmt.Sprintf("cannot use %v as type %v", val, t))
+ }
+ default:
+ // No supported conversion
+ return val
+ }
+
+ elemType := t.Elem()
+ switch elemType.Kind() {
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.Slice:
+ // Attempt to convert to slice of the type t
+ s := reflect.MakeSlice(reflect.SliceOf(elemType), val.Len(), val.Len())
+ for i := 0; i < val.Len(); i++ {
+ s.Index(i).Set(callParamConvert(val.Index(i), elemType))
+ }
+
+ return s
+ }
+
+ // Not a slice type we can convert
+ return val
+}
+
+// callSliceRequired returns true if CallSlice is required instead of Call.
+func callSliceRequired(param reflect.Type, val reflect.Value) bool {
+ vt := val.Type()
+ for param.Kind() == reflect.Slice {
+ if val.Kind() == reflect.Interface {
+ val = reflect.ValueOf(val.Interface())
+ vt = val.Type()
+ }
+
+ if vt.Kind() != reflect.Slice {
+ return false
+ }
+
+ vt = vt.Elem()
+ if val.Kind() != reflect.Invalid {
+ if val.Len() > 0 {
+ val = val.Index(0)
+ } else {
+ val = reflect.Value{}
+ }
+ }
+ param = param.Elem()
+ }
+
+ return true
+}
+
func (self *_runtime) toValue(value interface{}) Value {
switch value := value.(type) {
case Value:
@@ -217,19 +362,61 @@ func (self *_runtime) toValue(value interface{}) Value {
case reflect.Func:
// TODO Maybe cache this?
return toValue_object(self.newNativeFunction("", func(call FunctionCall) Value {
- in := make([]reflect.Value, len(call.ArgumentList))
+ argsCount := len(call.ArgumentList)
+ in := make([]reflect.Value, argsCount)
+ t := value.Type()
+ callSlice := false
+ paramsCount := t.NumIn()
+ lastParam := paramsCount - 1
+ lastArg := argsCount - 1
+ isVariadic := t.IsVariadic()
for i, value := range call.ArgumentList {
- in[i] = reflect.ValueOf(value.export())
+ var paramType reflect.Type
+ if isVariadic && i == lastArg && argsCount == paramsCount {
+ // Variadic functions last parameter and parameter numbers match incoming args
+ paramType = t.In(lastArg)
+ val := reflect.ValueOf(value.export())
+ callSlice = callSliceRequired(paramType, val)
+ if callSlice {
+ in[i] = callParamConvert(reflect.ValueOf(value.export()), paramType)
+ continue
+ }
+ }
+
+ if i >= lastParam {
+ if isVariadic {
+ paramType = t.In(lastParam).Elem()
+ } else {
+ paramType = t.In(lastParam)
+ }
+ } else {
+ paramType = t.In(i)
+ }
+ in[i] = callParamConvert(reflect.ValueOf(value.export()), paramType)
}
- out := value.Call(in)
- if len(out) == 1 {
- return self.toValue(out[0].Interface())
- } else if len(out) == 0 {
+ var out []reflect.Value
+ if callSlice {
+ out = value.CallSlice(in)
+ } else {
+ out = value.Call(in)
+ }
+
+ l := len(out)
+ switch l {
+ case 0:
return Value{}
+ case 1:
+ return self.toValue(out[0].Interface())
}
- panic(call.runtime.panicTypeError())
+ // Return an array of the values to emulate multi value return.
+ // In the future this can be used along side destructuring assignment.
+ s := make([]interface{}, l)
+ for i, v := range out {
+ s[i] = self.toValue(v.Interface())
+ }
+ return self.toValue(s)
}))
case reflect.Struct:
return toValue_object(self.newGoStructObject(value))
@@ -280,7 +467,7 @@ func (self *_runtime) parseSource(src interface{}) (*_nodeProgram, *ast.Program,
return nil, program, err
}
-func (self *_runtime) cmpl_run(src interface{}) (Value, error) {
+func (self *_runtime) cmpl_runOrEval(src interface{}, eval bool) (Value, error) {
result := Value{}
cmpl_program, program, err := self.parseSource(src)
if err != nil {
@@ -290,7 +477,7 @@ func (self *_runtime) cmpl_run(src interface{}) (Value, error) {
cmpl_program = cmpl_parse(program)
}
err = catchPanic(func() {
- result = self.cmpl_evaluate_nodeProgram(cmpl_program, false)
+ result = self.cmpl_evaluate_nodeProgram(cmpl_program, eval)
})
switch result.kind {
case valueEmpty:
@@ -301,6 +488,14 @@ func (self *_runtime) cmpl_run(src interface{}) (Value, error) {
return result, err
}
+func (self *_runtime) cmpl_run(src interface{}) (Value, error) {
+ return self.cmpl_runOrEval(src, false)
+}
+
+func (self *_runtime) cmpl_eval(src interface{}) (Value, error) {
+ return self.cmpl_runOrEval(src, true)
+}
+
func (self *_runtime) parseThrow(err error) {
if err == nil {
return
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/runtime_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/runtime_test.go
deleted file mode 100644
index 2510a0b3f..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/runtime_test.go
+++ /dev/null
@@ -1,778 +0,0 @@
-package otto
-
-import (
- "math"
- "testing"
-)
-
-// FIXME terst, Review tests
-
-func TestOperator(t *testing.T) {
- tt(t, func() {
- test, vm := test()
-
- test("xyzzy = 1")
- test("xyzzy", 1)
-
- if true {
- vm.Set("twoPlusTwo", func(FunctionCall) Value {
- return toValue(5)
- })
- test("twoPlusTwo( 1 )", 5)
-
- test("1 + twoPlusTwo( 1 )", 6)
-
- test("-1 + twoPlusTwo( 1 )", 4)
- }
-
- test("result = 4")
- test("result", 4)
-
- test("result += 1")
- test("result", 5)
-
- test("result *= 2")
- test("result", 10)
-
- test("result /= 2")
- test("result", 5)
-
- test("result = 112.51 % 3.1")
- test("result", 0.9100000000000019)
-
- test("result = 'Xyzzy'")
- test("result", "Xyzzy")
-
- test("result = 'Xyz' + 'zy'")
- test("result", "Xyzzy")
-
- test("result = \"Xyzzy\"")
- test("result", "Xyzzy")
-
- test("result = 1; result = result")
- test("result", 1)
-
- test(`
- var result64
- =
- 64
- , result10 =
- 10
- `)
- test("result64", 64)
- test("result10", 10)
-
- test(`
- result = 1;
- result += 1;
- `)
- test("result", 2)
- })
-}
-
-func TestFunction_(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- result = 2
- xyzzy = function() {
- result += 1
- }
- xyzzy()
- result;
- `, 3)
-
- test(`
- xyzzy = function() {
- return 1
- }
- result = xyzzy()
- `, 1)
-
- test(`
- xyzzy = function() {}
- result = xyzzy()
- `, "undefined")
-
- test(`
- xyzzy = function() {
- return 64
- return 1
- }
- result = xyzzy()
- `, 64)
-
- test(`
- result = 4
- xyzzy = function() {
- result = 2
- }
- xyzzy();
- result;
- `, 2)
-
- test(`
- result = 4
- xyzzy = function() {
- var result
- result = 2
- }
- xyzzy();
- result;
- `, 4)
-
- test(`
- xyzzy = function() {
- var result = 4
- return result
- }
- result = xyzzy()
- `, 4)
-
- test(`
- xyzzy = function() {
- function test() {
- var result = 1
- return result
- }
- return test() + 1
- }
- result = xyzzy() + 1
- `, 3)
-
- test(`
- xyzzy = function() {
- function test() {
- var result = 1
- return result
- }
- _xyzzy = 2
- var result = _xyzzy + test() + 1
- return result
- }
- result = xyzzy() + 1;
- [ result, _xyzzy ];
- `, "5,2")
-
- test(`
- xyzzy = function(apple) {
- return 1
- }
- result = xyzzy(1)
- `, 1)
-
- test(`
- xyzzy = function(apple) {
- return apple + 1
- }
- result = xyzzy(2)
- `, 3)
-
- test(`
- {
- result = 1
- result += 1;
- }
- `, 2)
-
- test(`
- var global = 1
- outer = function() {
- var global = 2
- var inner = function(){
- return global
- }
- return inner()
- }
- result = outer()
- `, 2)
-
- test(`
- var apple = 1
- var banana = function() {
- return apple
- }
- var cherry = function() {
- var apple = 2
- return banana()
- }
- result = cherry()
- `, 1)
-
- test(`
- function xyz() {
- };
- delete xyz;
- `, false)
-
- test(`
- var abc = function __factorial(def){
- if (def === 1) {
- return def;
- } else {
- return __factorial(def-1)*def;
- }
- };
- abc(3);
- `, 6)
- })
-}
-
-func TestDoWhile(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- limit = 4;
- result = 0;
- do {
- result = result + 1;
- limit = limit - 1;
- } while (limit);
- result;
- `, 4)
-
- test(`
- result = eval("do {abc=1; break; abc=2;} while (0);");
- [ result, abc ];
- `, "1,1")
- })
-}
-
-func TestContinueBreak(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- limit = 4
- result = 0
- while (limit) {
- limit = limit - 1
- if (limit) {
- }
- else {
- break
- }
- result = result + 1
- }
- [ result, limit ];
- `, "3,0")
-
- test(`
- limit = 4
- result = 0
- while (limit) {
- limit = limit - 1
- if (limit) {
- continue
- }
- else {
- break
- }
- result = result + 1
- }
- result;
- `, 0)
-
- test(`
- limit = 4
- result = 0
- do {
- limit = limit - 1
- if (limit) {
- continue
- }
- else {
- break
- }
- result = result + 1
- } while (limit)
- result;
- `, 0)
- })
-}
-
-func TestTryCatchError(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc
- try {
- 1()
- }
- catch (def) {
- abc = def
- }
- abc;
- `, "TypeError: 1 is not a function")
-
- })
-}
-
-func TestPositiveNegativeZero(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`1/0`, _Infinity)
- test(`1/-0`, -_Infinity)
- test(`
- abc = -0
- 1/abc
- `, -_Infinity)
- })
-}
-
-func TestComparison(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- undefined = 1; undefined;
- `, "undefined")
-
- test("undefined == undefined", true)
-
- test("undefined != undefined", false)
-
- test("null == null", true)
-
- test("null != null", false)
-
- test("0 == 1", false)
-
- is(negativeZero(), -0)
- is(positiveZero(), 0)
- is(math.Signbit(negativeZero()), true)
- is(positiveZero() == negativeZero(), true)
-
- test("1 == 1", true)
-
- test("'Hello, World.' == 'Goodbye, World.'", false)
-
- test("'Hello, World.' == true", false)
-
- test("'Hello, World.' == false", false)
-
- test("'Hello, World.' == 1", false)
-
- test("1 == 'Hello, World.'", false)
-
- is(parseNumber("-1"), -1)
-
- test("0+Object", "0function Object() { [native code] }")
- })
-}
-
-func TestComparisonRelational(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test("0 < 0", false)
-
- test("0 > 0", false)
-
- test("0 <= 0", true)
-
- test("0 >= 0", true)
-
- test("' 0' >= 0", true)
-
- test("'_ 0' >= 0", false)
- })
-}
-
-func TestArguments(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- xyzzy = function() {
- return arguments[0]
- }
- result = xyzzy("xyzzy");
- `, "xyzzy")
-
- test(`
- xyzzy = function() {
- arguments[0] = "abcdef"
- return arguments[0]
- }
- result = xyzzy("xyzzy");
- `, "abcdef")
-
- test(`
- xyzzy = function(apple) {
- apple = "abcdef"
- return arguments[0]
- }
- result = xyzzy("xyzzy");
- `, "abcdef")
-
- test(`
- (function(){
- return arguments
- })()
- `, "[object Arguments]")
-
- test(`
- (function(){
- return arguments.length
- })()
- `, 0)
-
- test(`
- (function(){
- return arguments.length
- })(1, 2, 4, 8, 10)
- `, 5)
- })
-}
-
-func TestObjectLiteral(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- ({});
- `, "[object Object]")
-
- test(`
- var abc = {
- xyzzy: "Nothing happens.",
- get 1e2() {
- return 3.14159;
- },
- get null() {
- return true;
- },
- get "[\n]"() {
- return "<>";
- }
- };
- [ abc["1e2"], abc.null, abc["[\n]"] ];
- `, "3.14159,true,<>")
-
- test(`
- var abc = {
- xyzzy: "Nothing happens.",
- set 1e2() {
- this[3.14159] = 100;
- return Math.random();
- },
- set null(def) {
- this.def = def;
- return Math.random();
- },
- };
- [ abc["1e2"] = Infinity, abc[3.14159], abc.null = "xyz", abc.def ];
- `, "Infinity,100,xyz,xyz")
- })
-}
-
-func TestUnaryPrefix(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var result = 0;
- [++result, result];
- `, "1,1")
-
- test(`
- result = 0;
- [--result, result];
- `, "-1,-1")
-
- test(`
- var object = { valueOf: function() { return 1; } };
- result = ++object;
- [ result, typeof result ];
- `, "2,number")
-
- test(`
- var object = { valueOf: function() { return 1; } };
- result = --object;
- [ result, typeof result ];
- `, "0,number")
- })
-}
-
-func TestUnaryPostfix(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var result = 0;
- result++;
- [ result++, result ];
- `, "1,2")
-
- test(`
- result = 0;
- result--;
- [ result--, result ];
- `, "-1,-2")
-
- test(`
- var object = { valueOf: function() { return 1; } };
- result = object++;
- [ result, typeof result ];
- `, "1,number")
-
- test(`
- var object = { valueOf: function() { return 1; } };
- result = object--
- [ result, typeof result ];
- `, "1,number")
- })
-}
-
-func TestBinaryLogicalOperation(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = true
- def = false
- ghi = false
- jkl = false
- result = abc && def || ghi && jkl
- `, false)
-
- test(`
- abc = true
- def = true
- ghi = false
- jkl = false
- result = abc && def || ghi && jkl
- `, true)
-
- })
-}
-
-func TestBinaryBitwiseOperation(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = 1 & 2;
- def = 1 & 3;
- ghi = 1 | 3;
- jkl = 1 ^ 2;
- mno = 1 ^ 3;
- [ abc, def, ghi, jkl, mno ];
- `, "0,1,3,3,2")
- })
-}
-
-func TestBinaryShiftOperation(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- high = (1 << 30) - 1 + (1 << 30)
- low = -high - 1
- abc = 23 << 1
- def = -105 >> 1
- ghi = 23 << 2
- jkl = 1 >>> 31
- mno = 1 << 64
- pqr = 1 >> 2
- stu = -2 >> 4
- vwx = low >> 1
- yz = low >>> 1
- `)
- test("abc", 46)
- test("def", -53)
- test("ghi", 92)
- test("jkl", 0)
- test("mno", 1)
- test("pqr", 0)
- test("stu", -1)
- test("vwx", -1073741824)
- test("yz", 1073741824)
- })
-}
-
-func TestParenthesizing(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = 1 + 2 * 3
- def = (1 + 2) * 3
- ghi = !(false || true)
- jkl = !false || true
- `)
- test("abc", 7)
- test("def", 9)
- test("ghi", false)
- test("jkl", true)
- })
-}
-
-func Test_instanceof(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = {} instanceof Object;
- `, true)
-
- test(`
- abc = "abc" instanceof Object;
- `, false)
-
- test(`raise:
- abc = {} instanceof "abc";
- `, "TypeError: Expecting a function in instanceof check, but got: abc")
-
- test(`raise:
- "xyzzy" instanceof Math;
- `, "TypeError")
- })
-}
-
-func TestIn(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = "prototype" in Object;
- def = "xyzzy" in Object;
- [ abc, def ];
- `, "true,false")
- })
-}
-
-func Test_new(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = new Boolean;
- def = new Boolean(1);
- [ abc, def ];
- `, "false,true")
- })
-}
-
-func TestNewFunction(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- new Function("return 11")()
- `, 11)
-
- test(`
- abc = 10
- new Function("abc += 1")()
- abc
- `, 11)
-
- test(`
- new Function("a", "b", "c", "return b + 2")(10, 11, 12)
- `, 13)
-
- test(`raise:
- new 1
- `, "TypeError: 1 is not a function")
-
- // TODO Better error reporting: new this
- test(`raise:
- new this
- `, "TypeError: [object environment] is not a function")
-
- test(`raise:
- new {}
- `, "TypeError: [object Object] is not a function")
- })
-}
-
-func TestNewPrototype(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = { 'xyzzy': 'Nothing happens.' }
- function Xyzzy(){}
- Xyzzy.prototype = abc;
- (new Xyzzy()).xyzzy
- `, "Nothing happens.")
- })
-}
-
-func TestBlock(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc=0;
- var ghi;
- def: {
- do {
- abc++;
- if (!(abc < 10)) {
- break def;
- ghi = "ghi";
- }
- } while (true);
- }
- [ abc,ghi ];
- `, "10,")
- })
-}
-
-func Test_toString(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- [undefined+""]
- `, "undefined")
- })
-}
-
-func TestEvaluationOrder(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- var abc = 0;
- abc < (abc = 1) === true;
- `, true)
- })
-}
-
-func TestClone(t *testing.T) {
- tt(t, func() {
- vm1 := New()
- vm1.Run(`
- var abc = 1;
- `)
-
- vm2 := vm1.clone()
- vm1.Run(`
- abc += 2;
- `)
- vm2.Run(`
- abc += 4;
- `)
-
- is(vm1.getValue("abc"), 3)
- is(vm2.getValue("abc"), 5)
- })
-}
-
-func Test_debugger(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- debugger;
- `, "undefined")
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/script_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/script_test.go
deleted file mode 100644
index 4c35c646e..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/script_test.go
+++ /dev/null
@@ -1,78 +0,0 @@
-package otto
-
-import (
- "testing"
-)
-
-func TestScript(t *testing.T) {
- tt(t, func() {
- vm := New()
-
- script, err := vm.Compile("xyzzy", `var abc; if (!abc) abc = 0; abc += 2; abc;`)
- is(err, nil)
-
- str := script.String()
- is(str, "// xyzzy\nvar abc; if (!abc) abc = 0; abc += 2; abc;")
-
- value, err := vm.Run(script)
- is(err, nil)
- is(value, 2)
-
- if true {
- return
- }
-
- tmp, err := script.marshalBinary()
- is(err, nil)
- is(len(tmp), 1228)
-
- {
- script := &Script{}
- err = script.unmarshalBinary(tmp)
- is(err, nil)
-
- is(script.String(), str)
-
- value, err = vm.Run(script)
- is(err, nil)
- is(value, 4)
-
- tmp, err = script.marshalBinary()
- is(err, nil)
- is(len(tmp), 1228)
- }
-
- {
- script := &Script{}
- err = script.unmarshalBinary(tmp)
- is(err, nil)
-
- is(script.String(), str)
-
- value, err := vm.Run(script)
- is(err, nil)
- is(value, 6)
-
- tmp, err = script.marshalBinary()
- is(err, nil)
- is(len(tmp), 1228)
- }
-
- {
- version := scriptVersion
- scriptVersion = "bogus"
-
- script := &Script{}
- err = script.unmarshalBinary(tmp)
- is(err, "version mismatch")
-
- is(script.String(), "// \n")
- is(script.version, "")
- is(script.program == nil, true)
- is(script.filename, "")
- is(script.src, "")
-
- scriptVersion = version
- }
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/stash.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/stash.go
index 578708d3f..0d3ffa511 100644
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/stash.go
+++ b/Godeps/_workspace/src/github.com/robertkrimen/otto/stash.go
@@ -273,3 +273,24 @@ func (in *_fnStash) clone(clone *_clone) _stash {
}
return out
}
+
+func getStashProperties(stash _stash) (keys []string) {
+ switch vars := stash.(type) {
+ case *_dclStash:
+ for k := range vars.property {
+ keys = append(keys, k)
+ }
+ case *_fnStash:
+ for k := range vars.property {
+ keys = append(keys, k)
+ }
+ case *_objectStash:
+ for k := range vars.object.property {
+ keys = append(keys, k)
+ }
+ default:
+ panic("unknown stash type")
+ }
+
+ return
+}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/string_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/string_test.go
deleted file mode 100644
index b7b06324b..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/string_test.go
+++ /dev/null
@@ -1,365 +0,0 @@
-package otto
-
-import (
- "testing"
-)
-
-func TestString(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = (new String("xyzzy")).length;
- def = new String().length;
- ghi = new String("Nothing happens.").length;
- `)
- test("abc", 5)
- test("def", 0)
- test("ghi", 16)
- test(`"".length`, 0)
- test(`"a\uFFFFbc".length`, 4)
- test(`String(+0)`, "0")
- test(`String(-0)`, "0")
- test(`""+-0`, "0")
- test(`
- var abc = Object.getOwnPropertyDescriptor(String, "prototype");
- [ [ typeof String.prototype ],
- [ abc.writable, abc.enumerable, abc.configurable ] ];
- `, "object,false,false,false")
- })
-}
-
-func TestString_charAt(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = "xyzzy".charAt(0)
- def = "xyzzy".charAt(11)
- `)
- test("abc", "x")
- test("def", "")
- })
-}
-
-func TestString_charCodeAt(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`
- abc = "xyzzy".charCodeAt(0)
- def = "xyzzy".charCodeAt(11)
- `)
- test("abc", 120)
- test("def", _NaN)
- })
-}
-
-func TestString_fromCharCode(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`String.fromCharCode()`, []uint16{})
- test(`String.fromCharCode(88, 121, 122, 122, 121)`, []uint16{88, 121, 122, 122, 121}) // FIXME terst, Double-check these...
- test(`String.fromCharCode("88", 121, 122, 122.05, 121)`, []uint16{88, 121, 122, 122, 121})
- test(`String.fromCharCode("88", 121, 122, NaN, 121)`, []uint16{88, 121, 122, 0, 121})
- test(`String.fromCharCode("0x21")`, []uint16{33})
- test(`String.fromCharCode(-1).charCodeAt(0)`, 65535)
- test(`String.fromCharCode(65535).charCodeAt(0)`, 65535)
- test(`String.fromCharCode(65534).charCodeAt(0)`, 65534)
- test(`String.fromCharCode(4294967295).charCodeAt(0)`, 65535)
- test(`String.fromCharCode(4294967294).charCodeAt(0)`, 65534)
- test(`String.fromCharCode(0x0024) === "$"`, true)
- })
-}
-
-func TestString_concat(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`"".concat()`, "")
- test(`"".concat("abc", "def")`, "abcdef")
- test(`"".concat("abc", undefined, "def")`, "abcundefineddef")
- })
-}
-
-func TestString_indexOf(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`"".indexOf("")`, 0)
- test(`"".indexOf("", 11)`, 0)
- test(`"abc".indexOf("")`, 0)
- test(`"abc".indexOf("", 11)`, 3)
- test(`"abc".indexOf("a")`, 0)
- test(`"abc".indexOf("bc")`, 1)
- test(`"abc".indexOf("bc", 11)`, -1)
- test(`"$$abcdabcd".indexOf("ab", function(){return -Infinity;}())`, 2)
- test(`"$$abcdabcd".indexOf("ab", function(){return NaN;}())`, 2)
-
- test(`
- var abc = {toString:function(){return "\u0041B";}}
- var def = {valueOf:function(){return true;}}
- var ghi = "ABB\u0041BABAB";
- var jkl;
- with(ghi) {
- jkl = indexOf(abc, def);
- }
- jkl;
- `, 3)
- })
-}
-
-func TestString_lastIndexOf(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`"".lastIndexOf("")`, 0)
- test(`"".lastIndexOf("", 11)`, 0)
- test(`"abc".lastIndexOf("")`, 3)
- test(`"abc".lastIndexOf("", 11)`, 3)
- test(`"abc".lastIndexOf("a")`, 0)
- test(`"abc".lastIndexOf("bc")`, 1)
- test(`"abc".lastIndexOf("bc", 11)`, 1)
- test(`"abc".lastIndexOf("bc", 0)`, -1)
- test(`"abc".lastIndexOf("abcabcabc", 2)`, -1)
- test(`"abc".lastIndexOf("abc", 0)`, 0)
- test(`"abc".lastIndexOf("abc", 1)`, 0)
- test(`"abc".lastIndexOf("abc", 2)`, 0)
- test(`"abc".lastIndexOf("abc", 3)`, 0)
-
- test(`
- abc = new Object(true);
- abc.lastIndexOf = String.prototype.lastIndexOf;
- abc.lastIndexOf(true, false);
- `, 0)
- })
-}
-
-func TestString_match(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`"abc____abc_abc___".match(/__abc/)`, "__abc")
- test(`"abc___abc_abc__abc__abc".match(/abc/g)`, "abc,abc,abc,abc,abc")
- test(`"abc____abc_abc___".match(/__abc/g)`, "__abc")
- test(`
- abc = /abc/g
- "abc___abc_abc__abc__abc".match(abc)
- `, "abc,abc,abc,abc,abc")
- test(`abc.lastIndex`, 23)
- })
-}
-
-func TestString_replace(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`"abc_abc".replace(/abc/, "$&123")`, "abc123_abc")
- test(`"abc_abc".replace(/abc/g, "$&123")`, "abc123_abc123")
- test(`"abc_abc_".replace(/abc/g, "$&123")`, "abc123_abc123_")
- test(`"_abc_abc_".replace(/abc/g, "$&123")`, "_abc123_abc123_")
- test(`"abc".replace(/abc/, "$&123")`, "abc123")
- test(`"abc_".replace(/abc/, "$&123")`, "abc123_")
- test("\"^abc$\".replace(/abc/, \"$`def\")", "^^def$")
- test("\"^abc$\".replace(/abc/, \"def$`\")", "^def^$")
- test(`"_abc_abd_".replace(/ab(c|d)/g, "$1")`, "_c_d_")
- test(`
- "_abc_abd_".replace(/ab(c|d)/g, function(){
- })
- `, "_undefined_undefined_")
-
- test(`"b".replace(/(a)?(b)?/, "_$1_")`, "__")
- test(`
- "b".replace(/(a)?(b)?/, function(a, b, c, d, e, f){
- return [a, b, c, d, e, f]
- })
- `, "b,,b,0,b,")
-
- test(`
- var abc = 'She sells seashells by the seashore.';
- var def = /sh/;
- [ abc.replace(def, "$'" + 'sch') ];
- `, "She sells seaells by the seashore.schells by the seashore.")
- })
-}
-
-func TestString_search(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`"abc".search(/abc/)`, 0)
- test(`"abc".search(/def/)`, -1)
- test(`"abc".search(/c$/)`, 2)
- test(`"abc".search(/$/)`, 3)
- })
-}
-
-func TestString_split(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`"abc".split("", 1)`, "a")
- test(`"abc".split("", 2)`, "a,b")
- test(`"abc".split("", 3)`, "a,b,c")
- test(`"abc".split("", 4)`, "a,b,c")
- test(`"abc".split("", 11)`, "a,b,c")
- test(`"abc".split("", 0)`, "")
- test(`"abc".split("")`, "a,b,c")
-
- test(`"abc".split(undefined)`, "abc")
-
- test(`"__1__3_1__2__".split("_")`, ",,1,,3,1,,2,,")
-
- test(`"__1__3_1__2__".split(/_/)`, ",,1,,3,1,,2,,")
-
- test(`"ab".split(/a*/)`, ",b")
-
- test(`_ = "A<B>bold</B>and<CODE>coded</CODE>".split(/<(\/)?([^<>]+)>/)`, "A,,B,bold,/,B,and,,CODE,coded,/,CODE,")
- test(`_.length`, 13)
- test(`_[1] === undefined`, true)
- test(`_[12] === ""`, true)
-
- test(`
- var abc = new String("one-1 two-2 three-3");
- var def = abc.split(new RegExp);
-
- [ def.constructor === Array, abc.length, def.length, def.join('') ];
- `, "true,19,19,one-1 two-2 three-3")
- })
-}
-
-func TestString_slice(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`"abc".slice()`, "abc")
- test(`"abc".slice(0)`, "abc")
- test(`"abc".slice(0,11)`, "abc")
- test(`"abc".slice(0,-1)`, "ab")
- test(`"abc".slice(-1,11)`, "c")
- test(`abc = "abc"; abc.slice(abc.length+1, 0)`, "")
- })
-}
-
-func TestString_substring(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`"abc".substring()`, "abc")
- test(`"abc".substring(0)`, "abc")
- test(`"abc".substring(0,11)`, "abc")
- test(`"abc".substring(11,0)`, "abc")
- test(`"abc".substring(0,-1)`, "")
- test(`"abc".substring(-1,11)`, "abc")
- test(`"abc".substring(11,1)`, "bc")
- test(`"abc".substring(1)`, "bc")
- test(`"abc".substring(Infinity, Infinity)`, "")
- })
-}
-
-func TestString_toCase(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`"abc".toLowerCase()`, "abc")
- test(`"ABC".toLowerCase()`, "abc")
- test(`"abc".toLocaleLowerCase()`, "abc")
- test(`"ABC".toLocaleLowerCase()`, "abc")
- test(`"abc".toUpperCase()`, "ABC")
- test(`"ABC".toUpperCase()`, "ABC")
- test(`"abc".toLocaleUpperCase()`, "ABC")
- test(`"ABC".toLocaleUpperCase()`, "ABC")
- })
-}
-
-func Test_floatToString(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`String(-1234567890)`, "-1234567890")
- test(`-+String(-(-1234567890))`, -1234567890)
- test(`String(-1e128)`, "-1e+128")
- test(`String(0.12345)`, "0.12345")
- test(`String(-0.00000012345)`, "-1.2345e-7")
- test(`String(0.0000012345)`, "0.0000012345")
- test(`String(1000000000000000000000)`, "1e+21")
- test(`String(1e21)`, "1e+21")
- test(`String(1E21)`, "1e+21")
- test(`String(-1000000000000000000000)`, "-1e+21")
- test(`String(-1e21)`, "-1e+21")
- test(`String(-1E21)`, "-1e+21")
- test(`String(0.0000001)`, "1e-7")
- test(`String(1e-7)`, "1e-7")
- test(`String(1E-7)`, "1e-7")
- test(`String(-0.0000001)`, "-1e-7")
- test(`String(-1e-7)`, "-1e-7")
- test(`String(-1E-7)`, "-1e-7")
- })
-}
-
-func TestString_indexing(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- // Actually a test of stringToArrayIndex, under the hood.
- test(`
- abc = new String("abc");
- index = Math.pow(2, 32);
- [ abc.length, abc[index], abc[index+1], abc[index+2], abc[index+3] ];
- `, "3,,,,")
- })
-}
-
-func TestString_trim(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`' \n abc \t \n'.trim();`, "abc")
- test(`" abc\u000B".trim()`, "abc")
- test(`"abc ".trim()`, "abc")
- test(`
- var a = "\u180Eabc \u000B "
- var b = a.trim()
- a.length + b.length
- `, 10)
- })
-}
-
-func TestString_trimLeft(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`" abc\u000B".trimLeft()`, "abc\u000B")
- test(`"abc ".trimLeft()`, "abc ")
- test(`
- var a = "\u180Eabc \u000B "
- var b = a.trimLeft()
- a.length + b.length
- `, 13)
- })
-}
-
-func TestString_trimRight(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`" abc\u000B".trimRight()`, " abc")
- test(`" abc ".trimRight()`, " abc")
- test(`
- var a = "\u180Eabc \u000B "
- var b = a.trimRight()
- a.length + b.length
- `, 11)
- })
-}
-
-func TestString_localeCompare(t *testing.T) {
- tt(t, func() {
- test, _ := test()
-
- test(`'a'.localeCompare('c');`, -1)
- test(`'c'.localeCompare('a');`, 1)
- test(`'a'.localeCompare('a');`, 0)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/testing_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/testing_test.go
deleted file mode 100644
index bf820bc0c..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/testing_test.go
+++ /dev/null
@@ -1,135 +0,0 @@
-package otto
-
-import (
- "./terst"
- "errors"
- "strings"
- "testing"
- "time"
-)
-
-func tt(t *testing.T, arguments ...func()) {
- halt := errors.New("A test was taking too long")
- timer := time.AfterFunc(2*time.Second, func() {
- panic(halt)
- })
- defer func() {
- timer.Stop()
- }()
- terst.Terst(t, arguments...)
-}
-
-func is(arguments ...interface{}) bool {
- var got, expect interface{}
-
- switch len(arguments) {
- case 0, 1:
- return terst.Is(arguments...)
- case 2:
- got, expect = arguments[0], arguments[1]
- default:
- got, expect = arguments[0], arguments[2]
- }
-
- switch value := got.(type) {
- case Value:
- if value.value != nil {
- got = value.value
- }
- case *Error:
- if value != nil {
- got = value.Error()
- }
- if expect == nil {
- // FIXME This is weird
- expect = ""
- }
- }
-
- if len(arguments) == 2 {
- arguments[0] = got
- arguments[1] = expect
- } else {
- arguments[0] = got
- arguments[2] = expect
- }
-
- return terst.Is(arguments...)
-}
-
-func test(arguments ...interface{}) (func(string, ...interface{}) Value, *_tester) {
- tester := newTester()
- if len(arguments) > 0 {
- tester.test(arguments[0].(string))
- }
- return tester.test, tester
-}
-
-type _tester struct {
- vm *Otto
-}
-
-func newTester() *_tester {
- return &_tester{
- vm: New(),
- }
-}
-
-func (self *_tester) Get(name string) (Value, error) {
- return self.vm.Get(name)
-}
-
-func (self *_tester) Set(name string, value interface{}) Value {
- err := self.vm.Set(name, value)
- is(err, nil)
- if err != nil {
- terst.Caller().T().FailNow()
- }
- return self.vm.getValue(name)
-}
-
-func (self *_tester) Run(src interface{}) (Value, error) {
- return self.vm.Run(src)
-}
-
-func (self *_tester) test(name string, expect ...interface{}) Value {
- vm := self.vm
- raise := false
- defer func() {
- if caught := recover(); caught != nil {
- if exception, ok := caught.(*_exception); ok {
- caught = exception.eject()
- }
- if raise {
- if len(expect) > 0 {
- is(caught, expect[0])
- }
- } else {
- dbg("Panic, caught:", caught)
- panic(caught)
- }
- }
- }()
- var value Value
- var err error
- if isIdentifier(name) {
- value = vm.getValue(name)
- } else {
- source := name
- index := strings.Index(source, "raise:")
- if index == 0 {
- raise = true
- source = source[6:]
- source = strings.TrimLeft(source, " ")
- }
- value, err = vm.runtime.cmpl_run(source)
- if err != nil {
- panic(err)
- }
- }
- value = value.resolve()
- if len(expect) > 0 {
- is(value, expect[0])
- }
- return value
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/type_function.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/type_function.go
index a5eb7554a..8581afd39 100644
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/type_function.go
+++ b/Godeps/_workspace/src/github.com/robertkrimen/otto/type_function.go
@@ -147,10 +147,13 @@ func (self *_object) call(this Value, argumentList []Value, eval bool, frame _fr
case _nodeFunctionObject:
rt := self.runtime
stash := rt.enterFunctionScope(fn.stash, this)
+ rt.scope.frame = _frame{
+ callee: fn.node.name,
+ file: fn.node.file,
+ }
defer func() {
rt.leaveScope()
}()
- rt.scope.frame = frame
callValue := rt.cmpl_call_nodeFunction(self, stash, fn.node, this, argumentList)
if value, valid := callValue.value.(_result); valid {
return value.value
@@ -260,3 +263,9 @@ func (self *FunctionCall) thisClassObject(class string) *_object {
func (self FunctionCall) toObject(value Value) *_object {
return self.runtime.toObject(value)
}
+
+// CallerLocation will return file location information (file:line:pos) where this function is being called.
+func (self FunctionCall) CallerLocation() string {
+ // see error.go for location()
+ return self.runtime.scope.frame.location()
+}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/type_go_map.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/type_go_map.go
index 542a2c29d..3e204a028 100644
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/type_go_map.go
+++ b/Godeps/_workspace/src/github.com/robertkrimen/otto/type_go_map.go
@@ -60,7 +60,7 @@ func goMapEnumerate(self *_object, all bool, each func(string) bool) {
object := self.value.(*_goMapObject)
keys := object.value.MapKeys()
for _, key := range keys {
- if !each(key.String()) {
+ if !each(toValue(key).String()) {
return
}
}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore/source.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore/source.go
index 65754ab71..7c5df9714 100644
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore/source.go
+++ b/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore/source.go
@@ -3456,6 +3456,7 @@ func underscore() []byte {
0x69, 0x73, 0x29, 0x3b, 0x0a,
}
}
+
// Underscore.js 1.4.4
// http://underscorejs.org
// (c) 2009-2013 Jeremy Ashkenas, DocumentCloud Inc.
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_arrays_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_arrays_test.go
deleted file mode 100644
index 9d6297820..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_arrays_test.go
+++ /dev/null
@@ -1,344 +0,0 @@
-package otto
-
-import (
- "testing"
-)
-
-// first
-func Test_underscore_arrays_0(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("first", function() {
- equal(_.first([1,2,3]), 1, 'can pull out the first element of an array');
- equal(_([1, 2, 3]).first(), 1, 'can perform OO-style "first()"');
- equal(_.first([1,2,3], 0).join(', '), "", 'can pass an index to first');
- equal(_.first([1,2,3], 2).join(', '), '1, 2', 'can pass an index to first');
- equal(_.first([1,2,3], 5).join(', '), '1, 2, 3', 'can pass an index to first');
- var result = (function(){ return _.first(arguments); })(4, 3, 2, 1);
- equal(result, 4, 'works on an arguments object.');
- result = _.map([[1,2,3],[1,2,3]], _.first);
- equal(result.join(','), '1,1', 'works well with _.map');
- result = (function() { return _.take([1,2,3], 2); })();
- equal(result.join(','), '1,2', 'aliased as take');
-
- equal(_.first(null), undefined, 'handles nulls');
- });
- `)
- })
-}
-
-// rest
-func Test_underscore_arrays_1(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("rest", function() {
- var numbers = [1, 2, 3, 4];
- equal(_.rest(numbers).join(", "), "2, 3, 4", 'working rest()');
- equal(_.rest(numbers, 0).join(", "), "1, 2, 3, 4", 'working rest(0)');
- equal(_.rest(numbers, 2).join(', '), '3, 4', 'rest can take an index');
- var result = (function(){ return _(arguments).tail(); })(1, 2, 3, 4);
- equal(result.join(', '), '2, 3, 4', 'aliased as tail and works on arguments object');
- result = _.map([[1,2,3],[1,2,3]], _.rest);
- equal(_.flatten(result).join(','), '2,3,2,3', 'works well with _.map');
- result = (function(){ return _(arguments).drop(); })(1, 2, 3, 4);
- equal(result.join(', '), '2, 3, 4', 'aliased as drop and works on arguments object');
- });
- `)
- })
-}
-
-// initial
-func Test_underscore_arrays_2(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("initial", function() {
- equal(_.initial([1,2,3,4,5]).join(", "), "1, 2, 3, 4", 'working initial()');
- equal(_.initial([1,2,3,4],2).join(", "), "1, 2", 'initial can take an index');
- var result = (function(){ return _(arguments).initial(); })(1, 2, 3, 4);
- equal(result.join(", "), "1, 2, 3", 'initial works on arguments object');
- result = _.map([[1,2,3],[1,2,3]], _.initial);
- equal(_.flatten(result).join(','), '1,2,1,2', 'initial works with _.map');
- });
- `)
- })
-}
-
-// last
-func Test_underscore_arrays_3(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("last", function() {
- equal(_.last([1,2,3]), 3, 'can pull out the last element of an array');
- equal(_.last([1,2,3], 0).join(', '), "", 'can pass an index to last');
- equal(_.last([1,2,3], 2).join(', '), '2, 3', 'can pass an index to last');
- equal(_.last([1,2,3], 5).join(', '), '1, 2, 3', 'can pass an index to last');
- var result = (function(){ return _(arguments).last(); })(1, 2, 3, 4);
- equal(result, 4, 'works on an arguments object');
- result = _.map([[1,2,3],[1,2,3]], _.last);
- equal(result.join(','), '3,3', 'works well with _.map');
-
- equal(_.last(null), undefined, 'handles nulls');
- });
- `)
- })
-}
-
-// compact
-func Test_underscore_arrays_4(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("compact", function() {
- equal(_.compact([0, 1, false, 2, false, 3]).length, 3, 'can trim out all falsy values');
- var result = (function(){ return _.compact(arguments).length; })(0, 1, false, 2, false, 3);
- equal(result, 3, 'works on an arguments object');
- });
- `)
- })
-}
-
-// flatten
-func Test_underscore_arrays_5(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("flatten", function() {
- var list = [1, [2], [3, [[[4]]]]];
- deepEqual(_.flatten(list), [1,2,3,4], 'can flatten nested arrays');
- deepEqual(_.flatten(list, true), [1,2,3,[[[4]]]], 'can shallowly flatten nested arrays');
- var result = (function(){ return _.flatten(arguments); })(1, [2], [3, [[[4]]]]);
- deepEqual(result, [1,2,3,4], 'works on an arguments object');
- });
- `)
- })
-}
-
-// without
-func Test_underscore_arrays_6(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("without", function() {
- var list = [1, 2, 1, 0, 3, 1, 4];
- equal(_.without(list, 0, 1).join(', '), '2, 3, 4', 'can remove all instances of an object');
- var result = (function(){ return _.without(arguments, 0, 1); })(1, 2, 1, 0, 3, 1, 4);
- equal(result.join(', '), '2, 3, 4', 'works on an arguments object');
-
- var list = [{one : 1}, {two : 2}];
- ok(_.without(list, {one : 1}).length == 2, 'uses real object identity for comparisons.');
- ok(_.without(list, list[0]).length == 1, 'ditto.');
- });
- `)
- })
-}
-
-// uniq
-func Test_underscore_arrays_7(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("uniq", function() {
- var list = [1, 2, 1, 3, 1, 4];
- equal(_.uniq(list).join(', '), '1, 2, 3, 4', 'can find the unique values of an unsorted array');
-
- var list = [1, 1, 1, 2, 2, 3];
- equal(_.uniq(list, true).join(', '), '1, 2, 3', 'can find the unique values of a sorted array faster');
-
- var list = [{name:'moe'}, {name:'curly'}, {name:'larry'}, {name:'curly'}];
- var iterator = function(value) { return value.name; };
- equal(_.map(_.uniq(list, false, iterator), iterator).join(', '), 'moe, curly, larry', 'can find the unique values of an array using a custom iterator');
-
- equal(_.map(_.uniq(list, iterator), iterator).join(', '), 'moe, curly, larry', 'can find the unique values of an array using a custom iterator without specifying whether array is sorted');
-
- var iterator = function(value) { return value +1; };
- var list = [1, 2, 2, 3, 4, 4];
- equal(_.uniq(list, true, iterator).join(', '), '1, 2, 3, 4', 'iterator works with sorted array');
-
- var result = (function(){ return _.uniq(arguments); })(1, 2, 1, 3, 1, 4);
- equal(result.join(', '), '1, 2, 3, 4', 'works on an arguments object');
- });
- `)
- })
-}
-
-// intersection
-func Test_underscore_arrays_8(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("intersection", function() {
- var stooges = ['moe', 'curly', 'larry'], leaders = ['moe', 'groucho'];
- equal(_.intersection(stooges, leaders).join(''), 'moe', 'can take the set intersection of two arrays');
- equal(_(stooges).intersection(leaders).join(''), 'moe', 'can perform an OO-style intersection');
- var result = (function(){ return _.intersection(arguments, leaders); })('moe', 'curly', 'larry');
- equal(result.join(''), 'moe', 'works on an arguments object');
- });
- `)
- })
-}
-
-// union
-func Test_underscore_arrays_9(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("union", function() {
- var result = _.union([1, 2, 3], [2, 30, 1], [1, 40]);
- equal(result.join(' '), '1 2 3 30 40', 'takes the union of a list of arrays');
-
- var result = _.union([1, 2, 3], [2, 30, 1], [1, 40, [1]]);
- equal(result.join(' '), '1 2 3 30 40 1', 'takes the union of a list of nested arrays');
- });
- `)
- })
-}
-
-// difference
-func Test_underscore_arrays_10(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("difference", function() {
- var result = _.difference([1, 2, 3], [2, 30, 40]);
- equal(result.join(' '), '1 3', 'takes the difference of two arrays');
-
- var result = _.difference([1, 2, 3, 4], [2, 30, 40], [1, 11, 111]);
- equal(result.join(' '), '3 4', 'takes the difference of three arrays');
- });
- `)
- })
-}
-
-// zip
-func Test_underscore_arrays_11(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('zip', function() {
- var names = ['moe', 'larry', 'curly'], ages = [30, 40, 50], leaders = [true];
- var stooges = _.zip(names, ages, leaders);
- equal(String(stooges), 'moe,30,true,larry,40,,curly,50,', 'zipped together arrays of different lengths');
- });
- `)
- })
-}
-
-// object
-func Test_underscore_arrays_12(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('object', function() {
- var result = _.object(['moe', 'larry', 'curly'], [30, 40, 50]);
- var shouldBe = {moe: 30, larry: 40, curly: 50};
- ok(_.isEqual(result, shouldBe), 'two arrays zipped together into an object');
-
- result = _.object([['one', 1], ['two', 2], ['three', 3]]);
- shouldBe = {one: 1, two: 2, three: 3};
- ok(_.isEqual(result, shouldBe), 'an array of pairs zipped together into an object');
-
- var stooges = {moe: 30, larry: 40, curly: 50};
- ok(_.isEqual(_.object(_.pairs(stooges)), stooges), 'an object converted to pairs and back to an object');
-
- ok(_.isEqual(_.object(null), {}), 'handles nulls');
- });
- `)
- })
-}
-
-// indexOf
-func Test_underscore_arrays_13(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("indexOf", function() {
- var numbers = [1, 2, 3];
- numbers.indexOf = null;
- equal(_.indexOf(numbers, 2), 1, 'can compute indexOf, even without the native function');
- var result = (function(){ return _.indexOf(arguments, 2); })(1, 2, 3);
- equal(result, 1, 'works on an arguments object');
- equal(_.indexOf(null, 2), -1, 'handles nulls properly');
-
- var numbers = [10, 20, 30, 40, 50], num = 35;
- var index = _.indexOf(numbers, num, true);
- equal(index, -1, '35 is not in the list');
-
- numbers = [10, 20, 30, 40, 50]; num = 40;
- index = _.indexOf(numbers, num, true);
- equal(index, 3, '40 is in the list');
-
- numbers = [1, 40, 40, 40, 40, 40, 40, 40, 50, 60, 70]; num = 40;
- index = _.indexOf(numbers, num, true);
- equal(index, 1, '40 is in the list');
-
- numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3];
- index = _.indexOf(numbers, 2, 5);
- equal(index, 7, 'supports the fromIndex argument');
- });
- `)
- })
-}
-
-// lastIndexOf
-func Test_underscore_arrays_14(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("lastIndexOf", function() {
- var numbers = [1, 0, 1];
- equal(_.lastIndexOf(numbers, 1), 2);
-
- numbers = [1, 0, 1, 0, 0, 1, 0, 0, 0];
- numbers.lastIndexOf = null;
- equal(_.lastIndexOf(numbers, 1), 5, 'can compute lastIndexOf, even without the native function');
- equal(_.lastIndexOf(numbers, 0), 8, 'lastIndexOf the other element');
- var result = (function(){ return _.lastIndexOf(arguments, 1); })(1, 0, 1, 0, 0, 1, 0, 0, 0);
- equal(result, 5, 'works on an arguments object');
- equal(_.indexOf(null, 2), -1, 'handles nulls properly');
-
- numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3];
- var index = _.lastIndexOf(numbers, 2, 2);
- equal(index, 1, 'supports the fromIndex argument');
- });
- `)
- })
-}
-
-// range
-func Test_underscore_arrays_15(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("range", function() {
- equal(_.range(0).join(''), '', 'range with 0 as a first argument generates an empty array');
- equal(_.range(4).join(' '), '0 1 2 3', 'range with a single positive argument generates an array of elements 0,1,2,...,n-1');
- equal(_.range(5, 8).join(' '), '5 6 7', 'range with two arguments a &amp; b, a&lt;b generates an array of elements a,a+1,a+2,...,b-2,b-1');
- equal(_.range(8, 5).join(''), '', 'range with two arguments a &amp; b, b&lt;a generates an empty array');
- equal(_.range(3, 10, 3).join(' '), '3 6 9', 'range with three arguments a &amp; b &amp; c, c &lt; b-a, a &lt; b generates an array of elements a,a+c,a+2c,...,b - (multiplier of a) &lt; c');
- equal(_.range(3, 10, 15).join(''), '3', 'range with three arguments a &amp; b &amp; c, c &gt; b-a, a &lt; b generates an array with a single element, equal to a');
- equal(_.range(12, 7, -2).join(' '), '12 10 8', 'range with three arguments a &amp; b &amp; c, a &gt; b, c &lt; 0 generates an array of elements a,a-c,a-2c and ends with the number not less than b');
- equal(_.range(0, -10, -1).join(' '), '0 -1 -2 -3 -4 -5 -6 -7 -8 -9', 'final example in the Python docs');
- });
- `)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_chaining_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_chaining_test.go
deleted file mode 100644
index accf04fdc..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_chaining_test.go
+++ /dev/null
@@ -1,95 +0,0 @@
-package otto
-
-import (
- "testing"
-)
-
-// map/flatten/reduce
-func Test_underscore_chaining_0(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("map/flatten/reduce", function() {
- var lyrics = [
- "I'm a lumberjack and I'm okay",
- "I sleep all night and I work all day",
- "He's a lumberjack and he's okay",
- "He sleeps all night and he works all day"
- ];
- var counts = _(lyrics).chain()
- .map(function(line) { return line.split(''); })
- .flatten()
- .reduce(function(hash, l) {
- hash[l] = hash[l] || 0;
- hash[l]++;
- return hash;
- }, {}).value();
- ok(counts['a'] == 16 && counts['e'] == 10, 'counted all the letters in the song');
- });
- `)
- })
-}
-
-// select/reject/sortBy
-func Test_underscore_chaining_1(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("select/reject/sortBy", function() {
- var numbers = [1,2,3,4,5,6,7,8,9,10];
- numbers = _(numbers).chain().select(function(n) {
- return n % 2 == 0;
- }).reject(function(n) {
- return n % 4 == 0;
- }).sortBy(function(n) {
- return -n;
- }).value();
- equal(numbers.join(', '), "10, 6, 2", "filtered and reversed the numbers");
- });
- `)
- })
-}
-
-// select/reject/sortBy in functional style
-func Test_underscore_chaining_2(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("select/reject/sortBy in functional style", function() {
- var numbers = [1,2,3,4,5,6,7,8,9,10];
- numbers = _.chain(numbers).select(function(n) {
- return n % 2 == 0;
- }).reject(function(n) {
- return n % 4 == 0;
- }).sortBy(function(n) {
- return -n;
- }).value();
- equal(numbers.join(', '), "10, 6, 2", "filtered and reversed the numbers");
- });
- `)
- })
-}
-
-// reverse/concat/unshift/pop/map
-func Test_underscore_chaining_3(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("reverse/concat/unshift/pop/map", function() {
- var numbers = [1,2,3,4,5];
- numbers = _(numbers).chain()
- .reverse()
- .concat([5, 5, 5])
- .unshift(17)
- .pop()
- .map(function(n){ return n * 2; })
- .value();
- equal(numbers.join(', '), "34, 10, 8, 6, 4, 2, 10, 10", 'can chain together array functions.');
- });
- `)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_collections_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_collections_test.go
deleted file mode 100644
index 9afc2a2b2..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_collections_test.go
+++ /dev/null
@@ -1,698 +0,0 @@
-package otto
-
-import (
- "testing"
-)
-
-// each
-func Test_underscore_collections_0(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("each", function() {
- _.each([1, 2, 3], function(num, i) {
- equal(num, i + 1, 'each iterators provide value and iteration count');
- });
-
- var answers = [];
- _.each([1, 2, 3], function(num){ answers.push(num * this.multiplier);}, {multiplier : 5});
- equal(answers.join(', '), '5, 10, 15', 'context object property accessed');
-
- answers = [];
- _.forEach([1, 2, 3], function(num){ answers.push(num); });
- equal(answers.join(', '), '1, 2, 3', 'aliased as "forEach"');
-
- answers = [];
- var obj = {one : 1, two : 2, three : 3};
- obj.constructor.prototype.four = 4;
- _.each(obj, function(value, key){ answers.push(key); });
- equal(answers.join(", "), 'one, two, three', 'iterating over objects works, and ignores the object prototype.');
- delete obj.constructor.prototype.four;
-
- var answer = null;
- _.each([1, 2, 3], function(num, index, arr){ if (_.include(arr, num)) answer = true; });
- ok(answer, 'can reference the original collection from inside the iterator');
-
- answers = 0;
- _.each(null, function(){ ++answers; });
- equal(answers, 0, 'handles a null properly');
- });
- `)
- })
-}
-
-// map
-func Test_underscore_collections_1(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('map', function() {
- var doubled = _.map([1, 2, 3], function(num){ return num * 2; });
- equal(doubled.join(', '), '2, 4, 6', 'doubled numbers');
-
- doubled = _.collect([1, 2, 3], function(num){ return num * 2; });
- equal(doubled.join(', '), '2, 4, 6', 'aliased as "collect"');
-
- var tripled = _.map([1, 2, 3], function(num){ return num * this.multiplier; }, {multiplier : 3});
- equal(tripled.join(', '), '3, 6, 9', 'tripled numbers with context');
-
- var doubled = _([1, 2, 3]).map(function(num){ return num * 2; });
- equal(doubled.join(', '), '2, 4, 6', 'OO-style doubled numbers');
-
- // TEST: ReferenceError: document is not defined
- return;
-
- if (document.querySelectorAll) {
- var ids = _.map(document.querySelectorAll('#map-test *'), function(n){ return n.id; });
- deepEqual(ids, ['id1', 'id2'], 'Can use collection methods on NodeLists.');
- }
-
- var ids = _.map($('#map-test').children(), function(n){ return n.id; });
- deepEqual(ids, ['id1', 'id2'], 'Can use collection methods on jQuery Array-likes.');
-
- var ids = _.map(document.images, function(n){ return n.id; });
- ok(ids[0] == 'chart_image', 'can use collection methods on HTMLCollections');
-
- var ifnull = _.map(null, function(){});
- ok(_.isArray(ifnull) && ifnull.length === 0, 'handles a null properly');
- });
- `)
- })
-}
-
-// reduce
-func Test_underscore_collections_2(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('reduce', function() {
- var sum = _.reduce([1, 2, 3], function(sum, num){ return sum + num; }, 0);
- equal(sum, 6, 'can sum up an array');
-
- var context = {multiplier : 3};
- sum = _.reduce([1, 2, 3], function(sum, num){ return sum + num * this.multiplier; }, 0, context);
- equal(sum, 18, 'can reduce with a context object');
-
- sum = _.inject([1, 2, 3], function(sum, num){ return sum + num; }, 0);
- equal(sum, 6, 'aliased as "inject"');
-
- sum = _([1, 2, 3]).reduce(function(sum, num){ return sum + num; }, 0);
- equal(sum, 6, 'OO-style reduce');
-
- var sum = _.reduce([1, 2, 3], function(sum, num){ return sum + num; });
- equal(sum, 6, 'default initial value');
-
- var ifnull;
- try {
- _.reduce(null, function(){});
- } catch (ex) {
- ifnull = ex;
- }
- ok(ifnull instanceof TypeError, 'handles a null (without inital value) properly');
-
- ok(_.reduce(null, function(){}, 138) === 138, 'handles a null (with initial value) properly');
- equal(_.reduce([], function(){}, undefined), undefined, 'undefined can be passed as a special case');
- raises(function() { _.reduce([], function(){}); }, TypeError, 'throws an error for empty arrays with no initial value');
- });
- `)
- })
-}
-
-// reduceRight
-func Test_underscore_collections_3(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('reduceRight', function() {
- var list = _.reduceRight(["foo", "bar", "baz"], function(memo, str){ return memo + str; }, '');
- equal(list, 'bazbarfoo', 'can perform right folds');
-
- var list = _.foldr(["foo", "bar", "baz"], function(memo, str){ return memo + str; }, '');
- equal(list, 'bazbarfoo', 'aliased as "foldr"');
-
- var list = _.foldr(["foo", "bar", "baz"], function(memo, str){ return memo + str; });
- equal(list, 'bazbarfoo', 'default initial value');
-
- var ifnull;
- try {
- _.reduceRight(null, function(){});
- } catch (ex) {
- ifnull = ex;
- }
- ok(ifnull instanceof TypeError, 'handles a null (without inital value) properly');
-
- var sum = _.reduceRight({a: 1, b: 2, c: 3}, function(sum, num){ return sum + num; });
- equal(sum, 6, 'default initial value on object');
-
- ok(_.reduceRight(null, function(){}, 138) === 138, 'handles a null (with initial value) properly');
-
- equal(_.reduceRight([], function(){}, undefined), undefined, 'undefined can be passed as a special case');
- raises(function() { _.reduceRight([], function(){}); }, TypeError, 'throws an error for empty arrays with no initial value');
-
- // Assert that the correct arguments are being passed.
-
- var args,
- memo = {},
- object = {a: 1, b: 2},
- lastKey = _.keys(object).pop();
-
- var expected = lastKey == 'a'
- ? [memo, 1, 'a', object]
- : [memo, 2, 'b', object];
-
- _.reduceRight(object, function() {
- args || (args = _.toArray(arguments));
- }, memo);
-
- deepEqual(args, expected);
-
- // And again, with numeric keys.
-
- object = {'2': 'a', '1': 'b'};
- lastKey = _.keys(object).pop();
- args = null;
-
- expected = lastKey == '2'
- ? [memo, 'a', '2', object]
- : [memo, 'b', '1', object];
-
- _.reduceRight(object, function() {
- args || (args = _.toArray(arguments));
- }, memo);
-
- deepEqual(args, expected);
- });
- `)
- })
-}
-
-// find
-func Test_underscore_collections_4(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('find', function() {
- var array = [1, 2, 3, 4];
- strictEqual(_.find(array, function(n) { return n > 2; }), 3, 'should return first found <value>');
- strictEqual(_.find(array, function() { return false; }), void 0, 'should return <undefined> if <value> is not found');
- });
- `)
- })
-}
-
-// detect
-func Test_underscore_collections_5(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('detect', function() {
- var result = _.detect([1, 2, 3], function(num){ return num * 2 == 4; });
- equal(result, 2, 'found the first "2" and broke the loop');
- });
- `)
- })
-}
-
-// select
-func Test_underscore_collections_6(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('select', function() {
- var evens = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
- equal(evens.join(', '), '2, 4, 6', 'selected each even number');
-
- evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
- equal(evens.join(', '), '2, 4, 6', 'aliased as "filter"');
- });
- `)
- })
-}
-
-// reject
-func Test_underscore_collections_7(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('reject', function() {
- var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
- equal(odds.join(', '), '1, 3, 5', 'rejected each even number');
-
- var context = "obj";
-
- var evens = _.reject([1, 2, 3, 4, 5, 6], function(num){
- equal(context, "obj");
- return num % 2 != 0;
- }, context);
- equal(evens.join(', '), '2, 4, 6', 'rejected each odd number');
- });
- `)
- })
-}
-
-// all
-func Test_underscore_collections_8(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('all', function() {
- ok(_.all([], _.identity), 'the empty set');
- ok(_.all([true, true, true], _.identity), 'all true values');
- ok(!_.all([true, false, true], _.identity), 'one false value');
- ok(_.all([0, 10, 28], function(num){ return num % 2 == 0; }), 'even numbers');
- ok(!_.all([0, 11, 28], function(num){ return num % 2 == 0; }), 'an odd number');
- ok(_.all([1], _.identity) === true, 'cast to boolean - true');
- ok(_.all([0], _.identity) === false, 'cast to boolean - false');
- ok(_.every([true, true, true], _.identity), 'aliased as "every"');
- ok(!_.all([undefined, undefined, undefined], _.identity), 'works with arrays of undefined');
- });
- `)
- })
-}
-
-// any
-func Test_underscore_collections_9(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('any', function() {
- var nativeSome = Array.prototype.some;
- Array.prototype.some = null;
- ok(!_.any([]), 'the empty set');
- ok(!_.any([false, false, false]), 'all false values');
- ok(_.any([false, false, true]), 'one true value');
- ok(_.any([null, 0, 'yes', false]), 'a string');
- ok(!_.any([null, 0, '', false]), 'falsy values');
- ok(!_.any([1, 11, 29], function(num){ return num % 2 == 0; }), 'all odd numbers');
- ok(_.any([1, 10, 29], function(num){ return num % 2 == 0; }), 'an even number');
- ok(_.any([1], _.identity) === true, 'cast to boolean - true');
- ok(_.any([0], _.identity) === false, 'cast to boolean - false');
- ok(_.some([false, false, true]), 'aliased as "some"');
- Array.prototype.some = nativeSome;
- });
- `)
- })
-}
-
-// include
-func Test_underscore_collections_10(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('include', function() {
- ok(_.include([1,2,3], 2), 'two is in the array');
- ok(!_.include([1,3,9], 2), 'two is not in the array');
- ok(_.contains({moe:1, larry:3, curly:9}, 3) === true, '_.include on objects checks their values');
- ok(_([1,2,3]).include(2), 'OO-style include');
- });
- `)
- })
-}
-
-// invoke
-func Test_underscore_collections_11(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('invoke', function() {
- var list = [[5, 1, 7], [3, 2, 1]];
- var result = _.invoke(list, 'sort');
- equal(result[0].join(', '), '1, 5, 7', 'first array sorted');
- equal(result[1].join(', '), '1, 2, 3', 'second array sorted');
- });
- `)
- })
-}
-
-// invoke w/ function reference
-func Test_underscore_collections_12(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('invoke w/ function reference', function() {
- var list = [[5, 1, 7], [3, 2, 1]];
- var result = _.invoke(list, Array.prototype.sort);
- equal(result[0].join(', '), '1, 5, 7', 'first array sorted');
- equal(result[1].join(', '), '1, 2, 3', 'second array sorted');
- });
- `)
- })
-}
-
-// invoke when strings have a call method
-func Test_underscore_collections_13(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('invoke when strings have a call method', function() {
- String.prototype.call = function() {
- return 42;
- };
- var list = [[5, 1, 7], [3, 2, 1]];
- var s = "foo";
- equal(s.call(), 42, "call function exists");
- var result = _.invoke(list, 'sort');
- equal(result[0].join(', '), '1, 5, 7', 'first array sorted');
- equal(result[1].join(', '), '1, 2, 3', 'second array sorted');
- delete String.prototype.call;
- equal(s.call, undefined, "call function removed");
- });
- `)
- })
-}
-
-// pluck
-func Test_underscore_collections_14(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('pluck', function() {
- var people = [{name : 'moe', age : 30}, {name : 'curly', age : 50}];
- equal(_.pluck(people, 'name').join(', '), 'moe, curly', 'pulls names out of objects');
- });
- `)
- })
-}
-
-// where
-func Test_underscore_collections_15(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('where', function() {
- var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}];
- var result = _.where(list, {a: 1});
- equal(result.length, 3);
- equal(result[result.length - 1].b, 4);
- result = _.where(list, {b: 2});
- equal(result.length, 2);
- equal(result[0].a, 1);
- });
- `)
- })
-}
-
-// findWhere
-func Test_underscore_collections_16(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('findWhere', function() {
- var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}, {a: 2, b: 4}];
- var result = _.findWhere(list, {a: 1});
- deepEqual(result, {a: 1, b: 2});
- result = _.findWhere(list, {b: 4});
- deepEqual(result, {a: 1, b: 4});
- });
- `)
- })
-}
-
-// max
-func Test_underscore_collections_17(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('max', function() {
- equal(3, _.max([1, 2, 3]), 'can perform a regular Math.max');
-
- var neg = _.max([1, 2, 3], function(num){ return -num; });
- equal(neg, 1, 'can perform a computation-based max');
-
- equal(-Infinity, _.max({}), 'Maximum value of an empty object');
- equal(-Infinity, _.max([]), 'Maximum value of an empty array');
- equal(_.max({'a': 'a'}), -Infinity, 'Maximum value of a non-numeric collection');
-
- // TEST: Takes too long
- return;
-
- equal(299999, _.max(_.range(1,300000)), "Maximum value of a too-big array");
- });
- `)
- })
-}
-
-// min
-func Test_underscore_collections_18(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('min', function() {
- equal(1, _.min([1, 2, 3]), 'can perform a regular Math.min');
-
- var neg = _.min([1, 2, 3], function(num){ return -num; });
- equal(neg, 3, 'can perform a computation-based min');
-
- equal(Infinity, _.min({}), 'Minimum value of an empty object');
- equal(Infinity, _.min([]), 'Minimum value of an empty array');
- equal(_.min({'a': 'a'}), Infinity, 'Minimum value of a non-numeric collection');
-
- var now = new Date(9999999999);
- var then = new Date(0);
- equal(_.min([now, then]), then);
-
- // TEST: Takes too long
- return;
-
- equal(1, _.min(_.range(1,300000)), "Minimum value of a too-big array");
- });
- `)
- })
-}
-
-// sortBy
-func Test_underscore_collections_19(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('sortBy', function() {
- var people = [{name : 'curly', age : 50}, {name : 'moe', age : 30}];
- people = _.sortBy(people, function(person){ return person.age; });
- equal(_.pluck(people, 'name').join(', '), 'moe, curly', 'stooges sorted by age');
-
- var list = [undefined, 4, 1, undefined, 3, 2];
- equal(_.sortBy(list, _.identity).join(','), '1,2,3,4,,', 'sortBy with undefined values');
-
- var list = ["one", "two", "three", "four", "five"];
- var sorted = _.sortBy(list, 'length');
- equal(sorted.join(' '), 'one two four five three', 'sorted by length');
-
- function Pair(x, y) {
- this.x = x;
- this.y = y;
- }
-
- var collection = [
- new Pair(1, 1), new Pair(1, 2),
- new Pair(1, 3), new Pair(1, 4),
- new Pair(1, 5), new Pair(1, 6),
- new Pair(2, 1), new Pair(2, 2),
- new Pair(2, 3), new Pair(2, 4),
- new Pair(2, 5), new Pair(2, 6),
- new Pair(undefined, 1), new Pair(undefined, 2),
- new Pair(undefined, 3), new Pair(undefined, 4),
- new Pair(undefined, 5), new Pair(undefined, 6)
- ];
-
- var actual = _.sortBy(collection, function(pair) {
- return pair.x;
- });
-
- deepEqual(actual, collection, 'sortBy should be stable');
- });
- `)
- })
-}
-
-// groupBy
-func Test_underscore_collections_20(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('groupBy', function() {
- var parity = _.groupBy([1, 2, 3, 4, 5, 6], function(num){ return num % 2; });
- ok('0' in parity && '1' in parity, 'created a group for each value');
- equal(parity[0].join(', '), '2, 4, 6', 'put each even number in the right group');
-
- var list = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"];
- var grouped = _.groupBy(list, 'length');
- equal(grouped['3'].join(' '), 'one two six ten');
- equal(grouped['4'].join(' '), 'four five nine');
- equal(grouped['5'].join(' '), 'three seven eight');
-
- var context = {};
- _.groupBy([{}], function(){ ok(this === context); }, context);
-
- grouped = _.groupBy([4.2, 6.1, 6.4], function(num) {
- return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';
- });
- equal(grouped.constructor.length, 1);
- equal(grouped.hasOwnProperty.length, 2);
-
- var array = [{}];
- _.groupBy(array, function(value, index, obj){ ok(obj === array); });
-
- var array = [1, 2, 1, 2, 3];
- var grouped = _.groupBy(array);
- equal(grouped['1'].length, 2);
- equal(grouped['3'].length, 1);
- });
- `)
- })
-}
-
-// countBy
-func Test_underscore_collections_21(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('countBy', function() {
- var parity = _.countBy([1, 2, 3, 4, 5], function(num){ return num % 2 == 0; });
- equal(parity['true'], 2);
- equal(parity['false'], 3);
-
- var list = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"];
- var grouped = _.countBy(list, 'length');
- equal(grouped['3'], 4);
- equal(grouped['4'], 3);
- equal(grouped['5'], 3);
-
- var context = {};
- _.countBy([{}], function(){ ok(this === context); }, context);
-
- grouped = _.countBy([4.2, 6.1, 6.4], function(num) {
- return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';
- });
- equal(grouped.constructor, 1);
- equal(grouped.hasOwnProperty, 2);
-
- var array = [{}];
- _.countBy(array, function(value, index, obj){ ok(obj === array); });
-
- var array = [1, 2, 1, 2, 3];
- var grouped = _.countBy(array);
- equal(grouped['1'], 2);
- equal(grouped['3'], 1);
- });
- `)
- })
-}
-
-// sortedIndex
-func Test_underscore_collections_22(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('sortedIndex', function() {
- var numbers = [10, 20, 30, 40, 50], num = 35;
- var indexForNum = _.sortedIndex(numbers, num);
- equal(indexForNum, 3, '35 should be inserted at index 3');
-
- var indexFor30 = _.sortedIndex(numbers, 30);
- equal(indexFor30, 2, '30 should be inserted at index 2');
-
- var objects = [{x: 10}, {x: 20}, {x: 30}, {x: 40}];
- var iterator = function(obj){ return obj.x; };
- strictEqual(_.sortedIndex(objects, {x: 25}, iterator), 2);
- strictEqual(_.sortedIndex(objects, {x: 35}, 'x'), 3);
-
- var context = {1: 2, 2: 3, 3: 4};
- iterator = function(obj){ return this[obj]; };
- strictEqual(_.sortedIndex([1, 3], 2, iterator, context), 1);
- });
- `)
- })
-}
-
-// shuffle
-func Test_underscore_collections_23(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('shuffle', function() {
- var numbers = _.range(10);
- var shuffled = _.shuffle(numbers).sort();
- notStrictEqual(numbers, shuffled, 'original object is unmodified');
- equal(shuffled.join(','), numbers.join(','), 'contains the same members before and after shuffle');
- });
- `)
- })
-}
-
-// toArray
-func Test_underscore_collections_24(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('toArray', function() {
- ok(!_.isArray(arguments), 'arguments object is not an array');
- ok(_.isArray(_.toArray(arguments)), 'arguments object converted into array');
- var a = [1,2,3];
- ok(_.toArray(a) !== a, 'array is cloned');
- equal(_.toArray(a).join(', '), '1, 2, 3', 'cloned array contains same elements');
-
- var numbers = _.toArray({one : 1, two : 2, three : 3});
- equal(numbers.join(', '), '1, 2, 3', 'object flattened into array');
-
- // TEST: ReferenceError: document is not defined
- return;
-
- // test in IE < 9
- try {
- var actual = _.toArray(document.childNodes);
- } catch(ex) { }
-
- ok(_.isArray(actual), 'should not throw converting a node list');
- });
- `)
- })
-}
-
-// size
-func Test_underscore_collections_25(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('size', function() {
- equal(_.size({one : 1, two : 2, three : 3}), 3, 'can compute the size of an object');
- equal(_.size([1, 2, 3]), 3, 'can compute the size of an array');
-
- var func = function() {
- return _.size(arguments);
- };
-
- equal(func(1, 2, 3, 4), 4, 'can test the size of the arguments object');
-
- equal(_.size('hello'), 5, 'can compute the size of a string');
-
- equal(_.size(null), 0, 'handles nulls');
- });
- `)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_functions_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_functions_test.go
deleted file mode 100644
index be59e16b3..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_functions_test.go
+++ /dev/null
@@ -1,208 +0,0 @@
-package otto
-
-import (
- "testing"
-)
-
-// bind
-func Test_underscore_functions_0(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("bind", function() {
- var context = {name : 'moe'};
- var func = function(arg) { return "name: " + (this.name || arg); };
- var bound = _.bind(func, context);
- equal(bound(), 'name: moe', 'can bind a function to a context');
-
- bound = _(func).bind(context);
- equal(bound(), 'name: moe', 'can do OO-style binding');
-
- bound = _.bind(func, null, 'curly');
- equal(bound(), 'name: curly', 'can bind without specifying a context');
-
- func = function(salutation, name) { return salutation + ': ' + name; };
- func = _.bind(func, this, 'hello');
- equal(func('moe'), 'hello: moe', 'the function was partially applied in advance');
-
- func = _.bind(func, this, 'curly');
- equal(func(), 'hello: curly', 'the function was completely applied in advance');
-
- func = function(salutation, firstname, lastname) { return salutation + ': ' + firstname + ' ' + lastname; };
- func = _.bind(func, this, 'hello', 'moe', 'curly');
- equal(func(), 'hello: moe curly', 'the function was partially applied in advance and can accept multiple arguments');
-
- func = function(context, message) { equal(this, context, message); };
- _.bind(func, 0, 0, 'can bind a function to <0>')();
- _.bind(func, '', '', 'can bind a function to an empty string')();
- _.bind(func, false, false, 'can bind a function to <false>')();
-
- // These tests are only meaningful when using a browser without a native bind function
- // To test this with a modern browser, set underscore's nativeBind to undefined
- var F = function () { return this; };
- var Boundf = _.bind(F, {hello: "moe curly"});
- equal(Boundf().hello, "moe curly", "When called without the new operator, it's OK to be bound to the context");
- });
- `)
- })
-}
-
-// partial
-func Test_underscore_functions_1(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("partial", function() {
- var obj = {name: 'moe'};
- var func = function() { return this.name + ' ' + _.toArray(arguments).join(' '); };
-
- obj.func = _.partial(func, 'a', 'b');
- equal(obj.func('c', 'd'), 'moe a b c d', 'can partially apply');
- });
- `)
- })
-}
-
-// bindAll
-func Test_underscore_functions_2(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("bindAll", function() {
- var curly = {name : 'curly'}, moe = {
- name : 'moe',
- getName : function() { return 'name: ' + this.name; },
- sayHi : function() { return 'hi: ' + this.name; }
- };
- curly.getName = moe.getName;
- _.bindAll(moe, 'getName', 'sayHi');
- curly.sayHi = moe.sayHi;
- equal(curly.getName(), 'name: curly', 'unbound function is bound to current object');
- equal(curly.sayHi(), 'hi: moe', 'bound function is still bound to original object');
-
- curly = {name : 'curly'};
- moe = {
- name : 'moe',
- getName : function() { return 'name: ' + this.name; },
- sayHi : function() { return 'hi: ' + this.name; }
- };
- _.bindAll(moe);
- curly.sayHi = moe.sayHi;
- equal(curly.sayHi(), 'hi: moe', 'calling bindAll with no arguments binds all functions to the object');
- });
- `)
- })
-}
-
-// memoize
-func Test_underscore_functions_3(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("memoize", function() {
- var fib = function(n) {
- return n < 2 ? n : fib(n - 1) + fib(n - 2);
- };
- var fastFib = _.memoize(fib);
- equal(fib(10), 55, 'a memoized version of fibonacci produces identical results');
- equal(fastFib(10), 55, 'a memoized version of fibonacci produces identical results');
-
- var o = function(str) {
- return str;
- };
- var fastO = _.memoize(o);
- equal(o('toString'), 'toString', 'checks hasOwnProperty');
- equal(fastO('toString'), 'toString', 'checks hasOwnProperty');
- });
- `)
- })
-}
-
-// once
-func Test_underscore_functions_4(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("once", function() {
- var num = 0;
- var increment = _.once(function(){ num++; });
- increment();
- increment();
- equal(num, 1);
- });
- `)
- })
-}
-
-// wrap
-func Test_underscore_functions_5(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("wrap", function() {
- var greet = function(name){ return "hi: " + name; };
- var backwards = _.wrap(greet, function(func, name){ return func(name) + ' ' + name.split('').reverse().join(''); });
- equal(backwards('moe'), 'hi: moe eom', 'wrapped the saluation function');
-
- var inner = function(){ return "Hello "; };
- var obj = {name : "Moe"};
- obj.hi = _.wrap(inner, function(fn){ return fn() + this.name; });
- equal(obj.hi(), "Hello Moe");
-
- var noop = function(){};
- var wrapped = _.wrap(noop, function(fn){ return Array.prototype.slice.call(arguments, 0); });
- var ret = wrapped(['whats', 'your'], 'vector', 'victor');
- deepEqual(ret, [noop, ['whats', 'your'], 'vector', 'victor']);
- });
- `)
- })
-}
-
-// compose
-func Test_underscore_functions_6(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("compose", function() {
- var greet = function(name){ return "hi: " + name; };
- var exclaim = function(sentence){ return sentence + '!'; };
- var composed = _.compose(exclaim, greet);
- equal(composed('moe'), 'hi: moe!', 'can compose a function that takes another');
-
- composed = _.compose(greet, exclaim);
- equal(composed('moe'), 'hi: moe!', 'in this case, the functions are also commutative');
- });
- `)
- })
-}
-
-// after
-func Test_underscore_functions_7(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("after", function() {
- var testAfter = function(afterAmount, timesCalled) {
- var afterCalled = 0;
- var after = _.after(afterAmount, function() {
- afterCalled++;
- });
- while (timesCalled--) after();
- return afterCalled;
- };
-
- equal(testAfter(5, 5), 1, "after(N) should fire after being called N times");
- equal(testAfter(5, 4), 0, "after(N) should not fire unless called N times");
- equal(testAfter(0, 0), 1, "after(0) should fire immediately");
- });
- `)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_objects_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_objects_test.go
deleted file mode 100644
index 1973af8dd..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_objects_test.go
+++ /dev/null
@@ -1,826 +0,0 @@
-package otto
-
-import (
- "testing"
-)
-
-// keys
-func Test_underscore_objects_0(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("keys", function() {
- equal(_.keys({one : 1, two : 2}).join(', '), 'one, two', 'can extract the keys from an object');
- // the test above is not safe because it relies on for-in enumeration order
- var a = []; a[1] = 0;
- equal(_.keys(a).join(', '), '1', 'is not fooled by sparse arrays; see issue #95');
- raises(function() { _.keys(null); }, TypeError, 'throws an error for <null> values');
- raises(function() { _.keys(void 0); }, TypeError, 'throws an error for <undefined> values');
- raises(function() { _.keys(1); }, TypeError, 'throws an error for number primitives');
- raises(function() { _.keys('a'); }, TypeError, 'throws an error for string primitives');
- raises(function() { _.keys(true); }, TypeError, 'throws an error for boolean primitives');
- });
- `)
- })
-}
-
-// values
-func Test_underscore_objects_1(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("values", function() {
- equal(_.values({one: 1, two: 2}).join(', '), '1, 2', 'can extract the values from an object');
- equal(_.values({one: 1, two: 2, length: 3}).join(', '), '1, 2, 3', '... even when one of them is "length"');
- });
- `)
- })
-}
-
-// pairs
-func Test_underscore_objects_2(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("pairs", function() {
- deepEqual(_.pairs({one: 1, two: 2}), [['one', 1], ['two', 2]], 'can convert an object into pairs');
- deepEqual(_.pairs({one: 1, two: 2, length: 3}), [['one', 1], ['two', 2], ['length', 3]], '... even when one of them is "length"');
- });
- `)
- })
-}
-
-// invert
-func Test_underscore_objects_3(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("invert", function() {
- var obj = {first: 'Moe', second: 'Larry', third: 'Curly'};
- equal(_.keys(_.invert(obj)).join(' '), 'Moe Larry Curly', 'can invert an object');
- ok(_.isEqual(_.invert(_.invert(obj)), obj), 'two inverts gets you back where you started');
-
- var obj = {length: 3};
- ok(_.invert(obj)['3'] == 'length', 'can invert an object with "length"')
- });
- `)
- })
-}
-
-// functions
-func Test_underscore_objects_4(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("functions", function() {
- var obj = {a : 'dash', b : _.map, c : (/yo/), d : _.reduce};
- ok(_.isEqual(['b', 'd'], _.functions(obj)), 'can grab the function names of any passed-in object');
-
- var Animal = function(){};
- Animal.prototype.run = function(){};
- equal(_.functions(new Animal).join(''), 'run', 'also looks up functions on the prototype');
- });
- `)
- })
-}
-
-// extend
-func Test_underscore_objects_5(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("extend", function() {
- var result;
- equal(_.extend({}, {a:'b'}).a, 'b', 'can extend an object with the attributes of another');
- equal(_.extend({a:'x'}, {a:'b'}).a, 'b', 'properties in source override destination');
- equal(_.extend({x:'x'}, {a:'b'}).x, 'x', 'properties not in source dont get overriden');
- result = _.extend({x:'x'}, {a:'a'}, {b:'b'});
- ok(_.isEqual(result, {x:'x', a:'a', b:'b'}), 'can extend from multiple source objects');
- result = _.extend({x:'x'}, {a:'a', x:2}, {a:'b'});
- ok(_.isEqual(result, {x:2, a:'b'}), 'extending from multiple source objects last property trumps');
- result = _.extend({}, {a: void 0, b: null});
- equal(_.keys(result).join(''), 'ab', 'extend does not copy undefined values');
-
- try {
- result = {};
- _.extend(result, null, undefined, {a:1});
- } catch(ex) {}
-
- equal(result.a, 1, 'should not error on <null> or <undefined> sources');
- });
- `)
- })
-}
-
-// pick
-func Test_underscore_objects_6(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("pick", function() {
- var result;
- result = _.pick({a:1, b:2, c:3}, 'a', 'c');
- ok(_.isEqual(result, {a:1, c:3}), 'can restrict properties to those named');
- result = _.pick({a:1, b:2, c:3}, ['b', 'c']);
- ok(_.isEqual(result, {b:2, c:3}), 'can restrict properties to those named in an array');
- result = _.pick({a:1, b:2, c:3}, ['a'], 'b');
- ok(_.isEqual(result, {a:1, b:2}), 'can restrict properties to those named in mixed args');
-
- var Obj = function(){};
- Obj.prototype = {a: 1, b: 2, c: 3};
- ok(_.isEqual(_.pick(new Obj, 'a', 'c'), {a:1, c: 3}), 'include prototype props');
- });
- `)
- })
-}
-
-// omit
-func Test_underscore_objects_7(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("omit", function() {
- var result;
- result = _.omit({a:1, b:2, c:3}, 'b');
- ok(_.isEqual(result, {a:1, c:3}), 'can omit a single named property');
- result = _.omit({a:1, b:2, c:3}, 'a', 'c');
- ok(_.isEqual(result, {b:2}), 'can omit several named properties');
- result = _.omit({a:1, b:2, c:3}, ['b', 'c']);
- ok(_.isEqual(result, {a:1}), 'can omit properties named in an array');
-
- var Obj = function(){};
- Obj.prototype = {a: 1, b: 2, c: 3};
- ok(_.isEqual(_.omit(new Obj, 'b'), {a:1, c: 3}), 'include prototype props');
- });
- `)
- })
-}
-
-// defaults
-func Test_underscore_objects_8(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("defaults", function() {
- var result;
- var options = {zero: 0, one: 1, empty: "", nan: NaN, string: "string"};
-
- _.defaults(options, {zero: 1, one: 10, twenty: 20});
- equal(options.zero, 0, 'value exists');
- equal(options.one, 1, 'value exists');
- equal(options.twenty, 20, 'default applied');
-
- _.defaults(options, {empty: "full"}, {nan: "nan"}, {word: "word"}, {word: "dog"});
- equal(options.empty, "", 'value exists');
- ok(_.isNaN(options.nan), "NaN isn't overridden");
- equal(options.word, "word", 'new value is added, first one wins');
-
- try {
- options = {};
- _.defaults(options, null, undefined, {a:1});
- } catch(ex) {}
-
- equal(options.a, 1, 'should not error on <null> or <undefined> sources');
- });
- `)
- })
-}
-
-// clone
-func Test_underscore_objects_9(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("clone", function() {
- var moe = {name : 'moe', lucky : [13, 27, 34]};
- var clone = _.clone(moe);
- equal(clone.name, 'moe', 'the clone as the attributes of the original');
-
- clone.name = 'curly';
- ok(clone.name == 'curly' && moe.name == 'moe', 'clones can change shallow attributes without affecting the original');
-
- clone.lucky.push(101);
- equal(_.last(moe.lucky), 101, 'changes to deep attributes are shared with the original');
-
- equal(_.clone(undefined), void 0, 'non objects should not be changed by clone');
- equal(_.clone(1), 1, 'non objects should not be changed by clone');
- equal(_.clone(null), null, 'non objects should not be changed by clone');
- });
- `)
- })
-}
-
-// isEqual
-func Test_underscore_objects_10(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("isEqual", function() {
- function First() {
- this.value = 1;
- }
- First.prototype.value = 1;
- function Second() {
- this.value = 1;
- }
- Second.prototype.value = 2;
-
- // Basic equality and identity comparisons.
- ok(_.isEqual(null, null), "<null> is equal to <null>");
- ok(_.isEqual(), "<undefined> is equal to <undefined>");
-
- ok(!_.isEqual(0, -0), "<0> is not equal to <-0>");
- ok(!_.isEqual(-0, 0), "Commutative equality is implemented for <0> and <-0>");
- ok(!_.isEqual(null, undefined), "<null> is not equal to <undefined>");
- ok(!_.isEqual(undefined, null), "Commutative equality is implemented for <null> and <undefined>");
-
- // String object and primitive comparisons.
- ok(_.isEqual("Curly", "Curly"), "Identical string primitives are equal");
- ok(_.isEqual(new String("Curly"), new String("Curly")), "String objects with identical primitive values are equal");
- ok(_.isEqual(new String("Curly"), "Curly"), "String primitives and their corresponding object wrappers are equal");
- ok(_.isEqual("Curly", new String("Curly")), "Commutative equality is implemented for string objects and primitives");
-
- ok(!_.isEqual("Curly", "Larry"), "String primitives with different values are not equal");
- ok(!_.isEqual(new String("Curly"), new String("Larry")), "String objects with different primitive values are not equal");
- ok(!_.isEqual(new String("Curly"), {toString: function(){ return "Curly"; }}), "String objects and objects with a custom <toString> method are not equal");
-
- // Number object and primitive comparisons.
- ok(_.isEqual(75, 75), "Identical number primitives are equal");
- ok(_.isEqual(new Number(75), new Number(75)), "Number objects with identical primitive values are equal");
- ok(_.isEqual(75, new Number(75)), "Number primitives and their corresponding object wrappers are equal");
- ok(_.isEqual(new Number(75), 75), "Commutative equality is implemented for number objects and primitives");
- ok(!_.isEqual(new Number(0), -0), "<new Number(0)> and <-0> are not equal");
- ok(!_.isEqual(0, new Number(-0)), "Commutative equality is implemented for <new Number(0)> and <-0>");
-
- ok(!_.isEqual(new Number(75), new Number(63)), "Number objects with different primitive values are not equal");
- ok(!_.isEqual(new Number(63), {valueOf: function(){ return 63; }}), "Number objects and objects with a <valueOf> method are not equal");
-
- // Comparisons involving <NaN>.
- ok(_.isEqual(NaN, NaN), "<NaN> is equal to <NaN>");
- ok(!_.isEqual(61, NaN), "A number primitive is not equal to <NaN>");
- ok(!_.isEqual(new Number(79), NaN), "A number object is not equal to <NaN>");
- ok(!_.isEqual(Infinity, NaN), "<Infinity> is not equal to <NaN>");
-
- // Boolean object and primitive comparisons.
- ok(_.isEqual(true, true), "Identical boolean primitives are equal");
- ok(_.isEqual(new Boolean, new Boolean), "Boolean objects with identical primitive values are equal");
- ok(_.isEqual(true, new Boolean(true)), "Boolean primitives and their corresponding object wrappers are equal");
- ok(_.isEqual(new Boolean(true), true), "Commutative equality is implemented for booleans");
- ok(!_.isEqual(new Boolean(true), new Boolean), "Boolean objects with different primitive values are not equal");
-
- // Common type coercions.
- ok(!_.isEqual(true, new Boolean(false)), "Boolean objects are not equal to the boolean primitive <true>");
- ok(!_.isEqual("75", 75), "String and number primitives with like values are not equal");
- ok(!_.isEqual(new Number(63), new String(63)), "String and number objects with like values are not equal");
- ok(!_.isEqual(75, "75"), "Commutative equality is implemented for like string and number values");
- ok(!_.isEqual(0, ""), "Number and string primitives with like values are not equal");
- ok(!_.isEqual(1, true), "Number and boolean primitives with like values are not equal");
- ok(!_.isEqual(new Boolean(false), new Number(0)), "Boolean and number objects with like values are not equal");
- ok(!_.isEqual(false, new String("")), "Boolean primitives and string objects with like values are not equal");
- ok(!_.isEqual(12564504e5, new Date(2009, 9, 25)), "Dates and their corresponding numeric primitive values are not equal");
-
- // Dates.
- ok(_.isEqual(new Date(2009, 9, 25), new Date(2009, 9, 25)), "Date objects referencing identical times are equal");
- ok(!_.isEqual(new Date(2009, 9, 25), new Date(2009, 11, 13)), "Date objects referencing different times are not equal");
- ok(!_.isEqual(new Date(2009, 11, 13), {
- getTime: function(){
- return 12606876e5;
- }
- }), "Date objects and objects with a <getTime> method are not equal");
- ok(!_.isEqual(new Date("Curly"), new Date("Curly")), "Invalid dates are not equal");
-
- // Functions.
- ok(!_.isEqual(First, Second), "Different functions with identical bodies and source code representations are not equal");
-
- // RegExps.
- ok(_.isEqual(/(?:)/gim, /(?:)/gim), "RegExps with equivalent patterns and flags are equal");
- ok(!_.isEqual(/(?:)/g, /(?:)/gi), "RegExps with equivalent patterns and different flags are not equal");
- ok(!_.isEqual(/Moe/gim, /Curly/gim), "RegExps with different patterns and equivalent flags are not equal");
- ok(!_.isEqual(/(?:)/gi, /(?:)/g), "Commutative equality is implemented for RegExps");
- ok(!_.isEqual(/Curly/g, {source: "Larry", global: true, ignoreCase: false, multiline: false}), "RegExps and RegExp-like objects are not equal");
-
- // Empty arrays, array-like objects, and object literals.
- ok(_.isEqual({}, {}), "Empty object literals are equal");
- ok(_.isEqual([], []), "Empty array literals are equal");
- ok(_.isEqual([{}], [{}]), "Empty nested arrays and objects are equal");
- ok(!_.isEqual({length: 0}, []), "Array-like objects and arrays are not equal.");
- ok(!_.isEqual([], {length: 0}), "Commutative equality is implemented for array-like objects");
-
- ok(!_.isEqual({}, []), "Object literals and array literals are not equal");
- ok(!_.isEqual([], {}), "Commutative equality is implemented for objects and arrays");
-
- // Arrays with primitive and object values.
- ok(_.isEqual([1, "Larry", true], [1, "Larry", true]), "Arrays containing identical primitives are equal");
- ok(_.isEqual([(/Moe/g), new Date(2009, 9, 25)], [(/Moe/g), new Date(2009, 9, 25)]), "Arrays containing equivalent elements are equal");
-
- // Multi-dimensional arrays.
- var a = [new Number(47), false, "Larry", /Moe/, new Date(2009, 11, 13), ['running', 'biking', new String('programming')], {a: 47}];
- var b = [new Number(47), false, "Larry", /Moe/, new Date(2009, 11, 13), ['running', 'biking', new String('programming')], {a: 47}];
- ok(_.isEqual(a, b), "Arrays containing nested arrays and objects are recursively compared");
-
- // Overwrite the methods defined in ES 5.1 section 15.4.4.
- a.forEach = a.map = a.filter = a.every = a.indexOf = a.lastIndexOf = a.some = a.reduce = a.reduceRight = null;
- b.join = b.pop = b.reverse = b.shift = b.slice = b.splice = b.concat = b.sort = b.unshift = null;
-
- // Array elements and properties.
- ok(_.isEqual(a, b), "Arrays containing equivalent elements and different non-numeric properties are equal");
- a.push("White Rocks");
- ok(!_.isEqual(a, b), "Arrays of different lengths are not equal");
- a.push("East Boulder");
- b.push("Gunbarrel Ranch", "Teller Farm");
- ok(!_.isEqual(a, b), "Arrays of identical lengths containing different elements are not equal");
-
- // Sparse arrays.
- ok(_.isEqual(Array(3), Array(3)), "Sparse arrays of identical lengths are equal");
- ok(!_.isEqual(Array(3), Array(6)), "Sparse arrays of different lengths are not equal when both are empty");
-
- // Simple objects.
- ok(_.isEqual({a: "Curly", b: 1, c: true}, {a: "Curly", b: 1, c: true}), "Objects containing identical primitives are equal");
- ok(_.isEqual({a: /Curly/g, b: new Date(2009, 11, 13)}, {a: /Curly/g, b: new Date(2009, 11, 13)}), "Objects containing equivalent members are equal");
- ok(!_.isEqual({a: 63, b: 75}, {a: 61, b: 55}), "Objects of identical sizes with different values are not equal");
- ok(!_.isEqual({a: 63, b: 75}, {a: 61, c: 55}), "Objects of identical sizes with different property names are not equal");
- ok(!_.isEqual({a: 1, b: 2}, {a: 1}), "Objects of different sizes are not equal");
- ok(!_.isEqual({a: 1}, {a: 1, b: 2}), "Commutative equality is implemented for objects");
- ok(!_.isEqual({x: 1, y: undefined}, {x: 1, z: 2}), "Objects with identical keys and different values are not equivalent");
-
- // <A> contains nested objects and arrays.
- a = {
- name: new String("Moe Howard"),
- age: new Number(77),
- stooge: true,
- hobbies: ["acting"],
- film: {
- name: "Sing a Song of Six Pants",
- release: new Date(1947, 9, 30),
- stars: [new String("Larry Fine"), "Shemp Howard"],
- minutes: new Number(16),
- seconds: 54
- }
- };
-
- // <B> contains equivalent nested objects and arrays.
- b = {
- name: new String("Moe Howard"),
- age: new Number(77),
- stooge: true,
- hobbies: ["acting"],
- film: {
- name: "Sing a Song of Six Pants",
- release: new Date(1947, 9, 30),
- stars: [new String("Larry Fine"), "Shemp Howard"],
- minutes: new Number(16),
- seconds: 54
- }
- };
- ok(_.isEqual(a, b), "Objects with nested equivalent members are recursively compared");
-
- // Instances.
- ok(_.isEqual(new First, new First), "Object instances are equal");
- ok(!_.isEqual(new First, new Second), "Objects with different constructors and identical own properties are not equal");
- ok(!_.isEqual({value: 1}, new First), "Object instances and objects sharing equivalent properties are not equal");
- ok(!_.isEqual({value: 2}, new Second), "The prototype chain of objects should not be examined");
-
- // Circular Arrays.
- (a = []).push(a);
- (b = []).push(b);
- ok(_.isEqual(a, b), "Arrays containing circular references are equal");
- a.push(new String("Larry"));
- b.push(new String("Larry"));
- ok(_.isEqual(a, b), "Arrays containing circular references and equivalent properties are equal");
- a.push("Shemp");
- b.push("Curly");
- ok(!_.isEqual(a, b), "Arrays containing circular references and different properties are not equal");
-
- // More circular arrays #767.
- a = ["everything is checked but", "this", "is not"];
- a[1] = a;
- b = ["everything is checked but", ["this", "array"], "is not"];
- ok(!_.isEqual(a, b), "Comparison of circular references with non-circular references are not equal");
-
- // Circular Objects.
- a = {abc: null};
- b = {abc: null};
- a.abc = a;
- b.abc = b;
- ok(_.isEqual(a, b), "Objects containing circular references are equal");
- a.def = 75;
- b.def = 75;
- ok(_.isEqual(a, b), "Objects containing circular references and equivalent properties are equal");
- a.def = new Number(75);
- b.def = new Number(63);
- ok(!_.isEqual(a, b), "Objects containing circular references and different properties are not equal");
-
- // More circular objects #767.
- a = {everything: "is checked", but: "this", is: "not"};
- a.but = a;
- b = {everything: "is checked", but: {that:"object"}, is: "not"};
- ok(!_.isEqual(a, b), "Comparison of circular references with non-circular object references are not equal");
-
- // Cyclic Structures.
- a = [{abc: null}];
- b = [{abc: null}];
- (a[0].abc = a).push(a);
- (b[0].abc = b).push(b);
- ok(_.isEqual(a, b), "Cyclic structures are equal");
- a[0].def = "Larry";
- b[0].def = "Larry";
- ok(_.isEqual(a, b), "Cyclic structures containing equivalent properties are equal");
- a[0].def = new String("Larry");
- b[0].def = new String("Curly");
- ok(!_.isEqual(a, b), "Cyclic structures containing different properties are not equal");
-
- // Complex Circular References.
- a = {foo: {b: {foo: {c: {foo: null}}}}};
- b = {foo: {b: {foo: {c: {foo: null}}}}};
- a.foo.b.foo.c.foo = a;
- b.foo.b.foo.c.foo = b;
- ok(_.isEqual(a, b), "Cyclic structures with nested and identically-named properties are equal");
-
- // Chaining.
- ok(!_.isEqual(_({x: 1, y: undefined}).chain(), _({x: 1, z: 2}).chain()), 'Chained objects containing different values are not equal');
-
- a = _({x: 1, y: 2}).chain();
- b = _({x: 1, y: 2}).chain();
- equal(_.isEqual(a.isEqual(b), _(true)), true, '<isEqual> can be chained');
-
- // TEST: ???
- return;
-
- // Objects from another frame.
- ok(_.isEqual({}, iObject));
- });
- `)
- })
-}
-
-// isEmpty
-func Test_underscore_objects_11(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("isEmpty", function() {
- ok(!_([1]).isEmpty(), '[1] is not empty');
- ok(_.isEmpty([]), '[] is empty');
- ok(!_.isEmpty({one : 1}), '{one : 1} is not empty');
- ok(_.isEmpty({}), '{} is empty');
- ok(_.isEmpty(new RegExp('')), 'objects with prototype properties are empty');
- ok(_.isEmpty(null), 'null is empty');
- ok(_.isEmpty(), 'undefined is empty');
- ok(_.isEmpty(''), 'the empty string is empty');
- ok(!_.isEmpty('moe'), 'but other strings are not');
-
- var obj = {one : 1};
- delete obj.one;
- ok(_.isEmpty(obj), 'deleting all the keys from an object empties it');
- });
- `)
- })
-}
-
-// isElement
-func Test_underscore_objects_12(t *testing.T) {
- // TEST: ReferenceError: $ is not defined
- if true {
- return
- }
-
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("isElement", function() {
- ok(!_.isElement('div'), 'strings are not dom elements');
- ok(_.isElement($('html')[0]), 'the html tag is a DOM element');
- ok(_.isElement(iElement), 'even from another frame');
- });
- `)
- })
-}
-
-// isArguments
-func Test_underscore_objects_13(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("isArguments", function() {
- var args = (function(){ return arguments; })(1, 2, 3);
- ok(!_.isArguments('string'), 'a string is not an arguments object');
- ok(!_.isArguments(_.isArguments), 'a function is not an arguments object');
- ok(_.isArguments(args), 'but the arguments object is an arguments object');
- ok(!_.isArguments(_.toArray(args)), 'but not when it\'s converted into an array');
- ok(!_.isArguments([1,2,3]), 'and not vanilla arrays.');
-
- // TEST: ReferenceError: iArguments is not defined
- return;
- ok(_.isArguments(iArguments), 'even from another frame');
- });
- `)
- })
-}
-
-// isObject
-func Test_underscore_objects_14(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("isObject", function() {
- ok(_.isObject(arguments), 'the arguments object is object');
- ok(_.isObject([1, 2, 3]), 'and arrays');
- // TEST: ReferenceError: $ is not defined
- return;
- ok(_.isObject($('html')[0]), 'and DOM element');
- ok(_.isObject(iElement), 'even from another frame');
- ok(_.isObject(function () {}), 'and functions');
- ok(_.isObject(iFunction), 'even from another frame');
- ok(!_.isObject(null), 'but not null');
- ok(!_.isObject(undefined), 'and not undefined');
- ok(!_.isObject('string'), 'and not string');
- ok(!_.isObject(12), 'and not number');
- ok(!_.isObject(true), 'and not boolean');
- ok(_.isObject(new String('string')), 'but new String()');
- });
- `)
- })
-}
-
-// isArray
-func Test_underscore_objects_15(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("isArray", function() {
- ok(!_.isArray(arguments), 'the arguments object is not an array');
- ok(_.isArray([1, 2, 3]), 'but arrays are');
- // TEST: ???
- return;
- ok(_.isArray(iArray), 'even from another frame');
- });
- `)
- })
-}
-
-// isString
-func Test_underscore_objects_16(t *testing.T) {
- // TEST: ReferenceError: document is not defined
- if true {
- return
- }
-
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("isString", function() {
- ok(!_.isString(document.body), 'the document body is not a string');
- ok(_.isString([1, 2, 3].join(', ')), 'but strings are');
- // TEST: ???
- return;
- ok(_.isString(iString), 'even from another frame');
- });
- `)
- })
-}
-
-// isNumber
-func Test_underscore_objects_17(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("isNumber", function() {
- ok(!_.isNumber('string'), 'a string is not a number');
- ok(!_.isNumber(arguments), 'the arguments object is not a number');
- ok(!_.isNumber(undefined), 'undefined is not a number');
- ok(_.isNumber(3 * 4 - 7 / 10), 'but numbers are');
- ok(_.isNumber(NaN), 'NaN *is* a number');
- ok(_.isNumber(Infinity), 'Infinity is a number');
- // TEST: ???
- return;
- ok(_.isNumber(iNumber), 'even from another frame');
- ok(!_.isNumber('1'), 'numeric strings are not numbers');
- });
- `)
- })
-}
-
-// isBoolean
-func Test_underscore_objects_18(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("isBoolean", function() {
- ok(!_.isBoolean(2), 'a number is not a boolean');
- ok(!_.isBoolean("string"), 'a string is not a boolean');
- ok(!_.isBoolean("false"), 'the string "false" is not a boolean');
- ok(!_.isBoolean("true"), 'the string "true" is not a boolean');
- ok(!_.isBoolean(arguments), 'the arguments object is not a boolean');
- ok(!_.isBoolean(undefined), 'undefined is not a boolean');
- ok(!_.isBoolean(NaN), 'NaN is not a boolean');
- ok(!_.isBoolean(null), 'null is not a boolean');
- ok(_.isBoolean(true), 'but true is');
- ok(_.isBoolean(false), 'and so is false');
- // TEST: ???
- return;
- ok(_.isBoolean(iBoolean), 'even from another frame');
- });
- `)
- })
-}
-
-// isFunction
-func Test_underscore_objects_19(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("isFunction", function() {
- ok(!_.isFunction([1, 2, 3]), 'arrays are not functions');
- ok(!_.isFunction('moe'), 'strings are not functions');
- ok(_.isFunction(_.isFunction), 'but functions are');
- // TEST: ???
- return;
- ok(_.isFunction(iFunction), 'even from another frame');
- });
- `)
- })
-}
-
-// isDate
-func Test_underscore_objects_20(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("isDate", function() {
- ok(!_.isDate(100), 'numbers are not dates');
- ok(!_.isDate({}), 'objects are not dates');
- ok(_.isDate(new Date()), 'but dates are');
- // TEST: ???
- return;
- ok(_.isDate(iDate), 'even from another frame');
- });
- `)
- })
-}
-
-// isRegExp
-func Test_underscore_objects_21(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("isRegExp", function() {
- ok(!_.isRegExp(_.identity), 'functions are not RegExps');
- ok(_.isRegExp(/identity/), 'but RegExps are');
- // TEST: ???
- return;
- ok(_.isRegExp(iRegExp), 'even from another frame');
- });
- `)
- })
-}
-
-// isFinite
-func Test_underscore_objects_22(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("isFinite", function() {
- ok(!_.isFinite(undefined), 'undefined is not Finite');
- ok(!_.isFinite(null), 'null is not Finite');
- ok(!_.isFinite(NaN), 'NaN is not Finite');
- ok(!_.isFinite(Infinity), 'Infinity is not Finite');
- ok(!_.isFinite(-Infinity), '-Infinity is not Finite');
- ok(_.isFinite('12'), 'Numeric strings are numbers');
- ok(!_.isFinite('1a'), 'Non numeric strings are not numbers');
- ok(!_.isFinite(''), 'Empty strings are not numbers');
- var obj = new Number(5);
- ok(_.isFinite(obj), 'Number instances can be finite');
- ok(_.isFinite(0), '0 is Finite');
- ok(_.isFinite(123), 'Ints are Finite');
- ok(_.isFinite(-12.44), 'Floats are Finite');
- });
- `)
- })
-}
-
-// isNaN
-func Test_underscore_objects_23(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("isNaN", function() {
- ok(!_.isNaN(undefined), 'undefined is not NaN');
- ok(!_.isNaN(null), 'null is not NaN');
- ok(!_.isNaN(0), '0 is not NaN');
- ok(_.isNaN(NaN), 'but NaN is');
- // TEST: ???
- return;
- ok(_.isNaN(iNaN), 'even from another frame');
- ok(_.isNaN(new Number(NaN)), 'wrapped NaN is still NaN');
- });
- `)
- })
-}
-
-// isNull
-func Test_underscore_objects_24(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("isNull", function() {
- ok(!_.isNull(undefined), 'undefined is not null');
- ok(!_.isNull(NaN), 'NaN is not null');
- ok(_.isNull(null), 'but null is');
- // TEST: ???
- return;
- ok(_.isNull(iNull), 'even from another frame');
- });
- `)
- })
-}
-
-// isUndefined
-func Test_underscore_objects_25(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("isUndefined", function() {
- ok(!_.isUndefined(1), 'numbers are defined');
- ok(!_.isUndefined(null), 'null is defined');
- ok(!_.isUndefined(false), 'false is defined');
- ok(!_.isUndefined(NaN), 'NaN is defined');
- ok(_.isUndefined(), 'nothing is undefined');
- ok(_.isUndefined(undefined), 'undefined is undefined');
- // TEST: ???
- return;
- ok(_.isUndefined(iUndefined), 'even from another frame');
- });
- `)
- })
-}
-
-// tap
-func Test_underscore_objects_26(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("tap", function() {
- var intercepted = null;
- var interceptor = function(obj) { intercepted = obj; };
- var returned = _.tap(1, interceptor);
- equal(intercepted, 1, "passes tapped object to interceptor");
- equal(returned, 1, "returns tapped object");
-
- returned = _([1,2,3]).chain().
- map(function(n){ return n * 2; }).
- max().
- tap(interceptor).
- value();
- ok(returned == 6 && intercepted == 6, 'can use tapped objects in a chain');
- });
- `)
- })
-}
-
-// has
-func Test_underscore_objects_27(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("has", function () {
- var obj = {foo: "bar", func: function () {} };
- ok (_.has(obj, "foo"), "has() checks that the object has a property.");
- ok (_.has(obj, "baz") == false, "has() returns false if the object doesn't have the property.");
- ok (_.has(obj, "func"), "has() works for functions too.");
- obj.hasOwnProperty = null;
- ok (_.has(obj, "foo"), "has() works even when the hasOwnProperty method is deleted.");
- var child = {};
- child.prototype = obj;
- ok (_.has(child, "foo") == false, "has() does not check the prototype chain for a property.")
- });
- `)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_test.go
deleted file mode 100644
index d8bf2da18..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_test.go
+++ /dev/null
@@ -1,165 +0,0 @@
-package otto
-
-import (
- "./terst"
- "testing"
-
- "github.com/robertkrimen/otto/underscore"
-)
-
-func init() {
- underscore.Disable()
-}
-
-// A persistent handle for the underscore tester
-// We do not run underscore tests in parallel, so it is okay to stash globally
-// (Maybe use sync.Pool in the future...)
-var tester_ *_tester
-
-// A tester for underscore: test_ => test(underscore) :)
-func test_(arguments ...interface{}) (func(string, ...interface{}) Value, *_tester) {
- tester := tester_
- if tester == nil {
- tester = newTester()
- tester.underscore() // Load underscore and testing shim, etc.
- tester_ = tester
- }
-
- return tester.test, tester
-}
-
-func (self *_tester) underscore() {
- vm := self.vm
- _, err := vm.Run(underscore.Source())
- if err != nil {
- panic(err)
- }
-
- vm.Set("assert", func(call FunctionCall) Value {
- if !call.Argument(0).bool() {
- message := "Assertion failed"
- if len(call.ArgumentList) > 1 {
- message = call.ArgumentList[1].string()
- }
- t := terst.Caller().T()
- is(message, nil)
- t.Fail()
- return falseValue
- }
- return trueValue
- })
-
- vm.Run(`
- var templateSettings;
-
- function _setup() {
- templateSettings = _.clone(_.templateSettings);
- }
-
- function _teardown() {
- _.templateSettings = templateSettings;
- }
-
- function module() {
- /* Nothing happens. */
- }
-
- function equals(a, b, emit) {
- assert(a == b, emit + ", <" + a + "> != <" + b + ">");
- }
- var equal = equals;
-
- function notStrictEqual(a, b, emit) {
- assert(a !== b, emit);
- }
-
- function strictEqual(a, b, emit) {
- assert(a === b, emit);
- }
-
- function ok(a, emit) {
- assert(a, emit);
- }
-
- function raises(fn, want, emit) {
- var have, _ok = false;
- if (typeof want === "string") {
- emit = want;
- want = null;
- }
-
- try {
- fn();
- } catch(tmp) {
- have = tmp;
- }
-
- if (have) {
- if (!want) {
- _ok = true;
- }
- else if (want instanceof RegExp) {
- _ok = want.test(have);
- }
- else if (have instanceof want) {
- _ok = true
- }
- else if (want.call({}, have) === true) {
- _ok = true;
- }
- }
-
- ok(_ok, emit);
- }
-
- function test(name){
- _setup()
- try {
- templateSettings = _.clone(_.templateSettings);
- if (arguments.length == 3) {
- count = 0
- for (count = 0; count < arguments[1]; count++) {
- arguments[2]()
- }
- } else {
- // For now.
- arguments[1]()
- }
- }
- finally {
- _teardown()
- }
- }
-
- function deepEqual(a, b, emit) {
- // Also, for now.
- assert(_.isEqual(a, b), emit)
- }
- `)
-}
-
-func Test_underscore(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- _.map([1, 2, 3], function(value){
- return value + 1
- })
- `, "2,3,4")
-
- test(`
- abc = _.find([1, 2, 3, -1], function(value) { return value == -1 })
- `, -1)
-
- test(`_.isEqual(1, 1)`, true)
- test(`_.isEqual([], [])`, true)
- test(`_.isEqual(['b', 'd'], ['b', 'd'])`, true)
- test(`_.isEqual(['b', 'd', 'c'], ['b', 'd', 'e'])`, false)
- test(`_.isFunction(function(){})`, true)
- test(`_.template('<p>\u2028<%= "\\u2028\\u2029" %>\u2029</p>')()`, "<p>\u2028\u2028\u2029\u2029</p>")
- })
-}
-
-// TODO Test: typeof An argument reference
-// TODO Test: abc = {}; abc == Object(abc)
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_utility_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_utility_test.go
deleted file mode 100644
index ebabb083b..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/underscore_utility_test.go
+++ /dev/null
@@ -1,419 +0,0 @@
-package otto
-
-import (
- "testing"
-)
-
-// #750 - Return _ instance.
-func Test_underscore_utility_0(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("#750 - Return _ instance.", 2, function() {
- var instance = _([]);
- ok(_(instance) === instance);
- ok(new _(instance) === instance);
- });
- `)
- })
-}
-
-// identity
-func Test_underscore_utility_1(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("identity", function() {
- var moe = {name : 'moe'};
- equal(_.identity(moe), moe, 'moe is the same as his identity');
- });
- `)
- })
-}
-
-// random
-func Test_underscore_utility_2(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("random", function() {
- var array = _.range(1000);
- var min = Math.pow(2, 31);
- var max = Math.pow(2, 62);
-
- ok(_.every(array, function() {
- return _.random(min, max) >= min;
- }), "should produce a random number greater than or equal to the minimum number");
-
- ok(_.some(array, function() {
- return _.random(Number.MAX_VALUE) > 0;
- }), "should produce a random number when passed <Number.MAX_VALUE>");
- });
- `)
- })
-}
-
-// uniqueId
-func Test_underscore_utility_3(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("uniqueId", function() {
- var ids = [], i = 0;
- while(i++ < 100) ids.push(_.uniqueId());
- equal(_.uniq(ids).length, ids.length, 'can generate a globally-unique stream of ids');
- });
- `)
- })
-}
-
-// times
-func Test_underscore_utility_4(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("times", function() {
- var vals = [];
- _.times(3, function (i) { vals.push(i); });
- ok(_.isEqual(vals, [0,1,2]), "is 0 indexed");
- //
- vals = [];
- _(3).times(function(i) { vals.push(i); });
- ok(_.isEqual(vals, [0,1,2]), "works as a wrapper");
- // collects return values
- ok(_.isEqual([0, 1, 2], _.times(3, function(i) { return i; })), "collects return values");
- });
- `)
- })
-}
-
-// mixin
-func Test_underscore_utility_5(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("mixin", function() {
- _.mixin({
- myReverse: function(string) {
- return string.split('').reverse().join('');
- }
- });
- equal(_.myReverse('panacea'), 'aecanap', 'mixed in a function to _');
- equal(_('champ').myReverse(), 'pmahc', 'mixed in a function to the OOP wrapper');
- });
- `)
- })
-}
-
-// _.escape
-func Test_underscore_utility_6(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("_.escape", function() {
- equal(_.escape("Curly & Moe"), "Curly &amp; Moe");
- equal(_.escape("Curly &amp; Moe"), "Curly &amp;amp; Moe");
- equal(_.escape(null), '');
- });
- `)
- })
-}
-
-// _.unescape
-func Test_underscore_utility_7(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("_.unescape", function() {
- var string = "Curly & Moe";
- equal(_.unescape("Curly &amp; Moe"), string);
- equal(_.unescape("Curly &amp;amp; Moe"), "Curly &amp; Moe");
- equal(_.unescape(null), '');
- equal(_.unescape(_.escape(string)), string);
- });
- `)
- })
-}
-
-// template
-func Test_underscore_utility_8(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test("template", function() {
- var basicTemplate = _.template("<%= thing %> is gettin' on my noives!");
- var result = basicTemplate({thing : 'This'});
- equal(result, "This is gettin' on my noives!", 'can do basic attribute interpolation');
-
- var sansSemicolonTemplate = _.template("A <% this %> B");
- equal(sansSemicolonTemplate(), "A B");
-
- var backslashTemplate = _.template("<%= thing %> is \\ridanculous");
- equal(backslashTemplate({thing: 'This'}), "This is \\ridanculous");
-
- var escapeTemplate = _.template('<%= a ? "checked=\\"checked\\"" : "" %>');
- equal(escapeTemplate({a: true}), 'checked="checked"', 'can handle slash escapes in interpolations.');
-
- var fancyTemplate = _.template("<ul><% \
- for (var key in people) { \
- %><li><%= people[key] %></li><% } %></ul>");
- result = fancyTemplate({people : {moe : "Moe", larry : "Larry", curly : "Curly"}});
- equal(result, "<ul><li>Moe</li><li>Larry</li><li>Curly</li></ul>", 'can run arbitrary javascript in templates');
-
- var escapedCharsInJavascriptTemplate = _.template("<ul><% _.each(numbers.split('\\n'), function(item) { %><li><%= item %></li><% }) %></ul>");
- result = escapedCharsInJavascriptTemplate({numbers: "one\ntwo\nthree\nfour"});
- equal(result, "<ul><li>one</li><li>two</li><li>three</li><li>four</li></ul>", 'Can use escaped characters (e.g. \\n) in Javascript');
-
- var namespaceCollisionTemplate = _.template("<%= pageCount %> <%= thumbnails[pageCount] %> <% _.each(thumbnails, function(p) { %><div class=\"thumbnail\" rel=\"<%= p %>\"></div><% }); %>");
- result = namespaceCollisionTemplate({
- pageCount: 3,
- thumbnails: {
- 1: "p1-thumbnail.gif",
- 2: "p2-thumbnail.gif",
- 3: "p3-thumbnail.gif"
- }
- });
- equal(result, "3 p3-thumbnail.gif <div class=\"thumbnail\" rel=\"p1-thumbnail.gif\"></div><div class=\"thumbnail\" rel=\"p2-thumbnail.gif\"></div><div class=\"thumbnail\" rel=\"p3-thumbnail.gif\"></div>");
-
- var noInterpolateTemplate = _.template("<div><p>Just some text. Hey, I know this is silly but it aids consistency.</p></div>");
- result = noInterpolateTemplate();
- equal(result, "<div><p>Just some text. Hey, I know this is silly but it aids consistency.</p></div>");
-
- var quoteTemplate = _.template("It's its, not it's");
- equal(quoteTemplate({}), "It's its, not it's");
-
- var quoteInStatementAndBody = _.template("<%\
- if(foo == 'bar'){ \
- %>Statement quotes and 'quotes'.<% } %>");
- equal(quoteInStatementAndBody({foo: "bar"}), "Statement quotes and 'quotes'.");
-
- var withNewlinesAndTabs = _.template('This\n\t\tis: <%= x %>.\n\tok.\nend.');
- equal(withNewlinesAndTabs({x: 'that'}), 'This\n\t\tis: that.\n\tok.\nend.');
-
- var template = _.template("<i><%- value %></i>");
- var result = template({value: "<script>"});
- equal(result, '<i>&lt;script&gt;</i>');
-
- var stooge = {
- name: "Moe",
- template: _.template("I'm <%= this.name %>")
- };
- equal(stooge.template(), "I'm Moe");
-
- // TEST: ReferenceError: $ is not defined
- if (false) {
- if (!$.browser.msie) {
- var fromHTML = _.template($('#template').html());
- equal(fromHTML({data : 12345}).replace(/\s/g, ''), '<li>24690</li>');
- }
- }
-
- _.templateSettings = {
- evaluate : /\{\{([\s\S]+?)\}\}/g,
- interpolate : /\{\{=([\s\S]+?)\}\}/g
- };
-
- var custom = _.template("<ul>{{ for (var key in people) { }}<li>{{= people[key] }}</li>{{ } }}</ul>");
- result = custom({people : {moe : "Moe", larry : "Larry", curly : "Curly"}});
- equal(result, "<ul><li>Moe</li><li>Larry</li><li>Curly</li></ul>", 'can run arbitrary javascript in templates');
-
- var customQuote = _.template("It's its, not it's");
- equal(customQuote({}), "It's its, not it's");
-
- var quoteInStatementAndBody = _.template("{{ if(foo == 'bar'){ }}Statement quotes and 'quotes'.{{ } }}");
- equal(quoteInStatementAndBody({foo: "bar"}), "Statement quotes and 'quotes'.");
-
- _.templateSettings = {
- evaluate : /<\?([\s\S]+?)\?>/g,
- interpolate : /<\?=([\s\S]+?)\?>/g
- };
-
- var customWithSpecialChars = _.template("<ul><? for (var key in people) { ?><li><?= people[key] ?></li><? } ?></ul>");
- result = customWithSpecialChars({people : {moe : "Moe", larry : "Larry", curly : "Curly"}});
- equal(result, "<ul><li>Moe</li><li>Larry</li><li>Curly</li></ul>", 'can run arbitrary javascript in templates');
-
- var customWithSpecialCharsQuote = _.template("It's its, not it's");
- equal(customWithSpecialCharsQuote({}), "It's its, not it's");
-
- var quoteInStatementAndBody = _.template("<? if(foo == 'bar'){ ?>Statement quotes and 'quotes'.<? } ?>");
- equal(quoteInStatementAndBody({foo: "bar"}), "Statement quotes and 'quotes'.");
-
- _.templateSettings = {
- interpolate : /\{\{(.+?)\}\}/g
- };
-
- var mustache = _.template("Hello {{planet}}!");
- equal(mustache({planet : "World"}), "Hello World!", "can mimic mustache.js");
-
- var templateWithNull = _.template("a null undefined {{planet}}");
- equal(templateWithNull({planet : "world"}), "a null undefined world", "can handle missing escape and evaluate settings");
- });
- `)
- })
-}
-
-// _.template provides the generated function source, when a SyntaxError occurs
-func Test_underscore_utility_9(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('_.template provides the generated function source, when a SyntaxError occurs', function() {
- try {
- _.template('<b><%= if x %></b>');
- } catch (ex) {
- var source = ex.source;
- }
- ok(/__p/.test(source));
- });
- `)
- })
-}
-
-// _.template handles \\u2028 & \\u2029
-func Test_underscore_utility_10(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('_.template handles \\u2028 & \\u2029', function() {
- var tmpl = _.template('<p>\u2028<%= "\\u2028\\u2029" %>\u2029</p>');
- strictEqual(tmpl(), '<p>\u2028\u2028\u2029\u2029</p>');
- });
- `)
- })
-}
-
-// result calls functions and returns primitives
-func Test_underscore_utility_11(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('result calls functions and returns primitives', function() {
- var obj = {w: '', x: 'x', y: function(){ return this.x; }};
- strictEqual(_.result(obj, 'w'), '');
- strictEqual(_.result(obj, 'x'), 'x');
- strictEqual(_.result(obj, 'y'), 'x');
- strictEqual(_.result(obj, 'z'), undefined);
- strictEqual(_.result(null, 'x'), null);
- });
- `)
- })
-}
-
-// _.templateSettings.variable
-func Test_underscore_utility_12(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('_.templateSettings.variable', function() {
- var s = '<%=data.x%>';
- var data = {x: 'x'};
- strictEqual(_.template(s, data, {variable: 'data'}), 'x');
- _.templateSettings.variable = 'data';
- strictEqual(_.template(s)(data), 'x');
- });
- `)
- })
-}
-
-// #547 - _.templateSettings is unchanged by custom settings.
-func Test_underscore_utility_13(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('#547 - _.templateSettings is unchanged by custom settings.', function() {
- ok(!_.templateSettings.variable);
- _.template('', {}, {variable: 'x'});
- ok(!_.templateSettings.variable);
- });
- `)
- })
-}
-
-// #556 - undefined template variables.
-func Test_underscore_utility_14(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('#556 - undefined template variables.', function() {
- var template = _.template('<%=x%>');
- strictEqual(template({x: null}), '');
- strictEqual(template({x: undefined}), '');
-
- var templateEscaped = _.template('<%-x%>');
- strictEqual(templateEscaped({x: null}), '');
- strictEqual(templateEscaped({x: undefined}), '');
-
- var templateWithProperty = _.template('<%=x.foo%>');
- strictEqual(templateWithProperty({x: {} }), '');
- strictEqual(templateWithProperty({x: {} }), '');
-
- var templateWithPropertyEscaped = _.template('<%-x.foo%>');
- strictEqual(templateWithPropertyEscaped({x: {} }), '');
- strictEqual(templateWithPropertyEscaped({x: {} }), '');
- });
- `)
- })
-}
-
-// interpolate evaluates code only once.
-func Test_underscore_utility_15(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('interpolate evaluates code only once.', 2, function() {
- var count = 0;
- var template = _.template('<%= f() %>');
- template({f: function(){ ok(!(count++)); }});
-
- var countEscaped = 0;
- var templateEscaped = _.template('<%- f() %>');
- templateEscaped({f: function(){ ok(!(countEscaped++)); }});
- });
- `)
- })
-}
-
-// #746 - _.template settings are not modified.
-func Test_underscore_utility_16(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('#746 - _.template settings are not modified.', 1, function() {
- var settings = {};
- _.template('', null, settings);
- deepEqual(settings, {});
- });
- `)
- })
-}
-
-// #779 - delimeters are applied to unescaped text.
-func Test_underscore_utility_17(t *testing.T) {
- tt(t, func() {
- test, _ := test_()
-
- test(`
- test('#779 - delimeters are applied to unescaped text.', 1, function() {
- var template = _.template('<<\nx\n>>', null, {evaluate: /<<(.*?)>>/g});
- strictEqual(template(), '<<\nx\n>>');
- });
- `)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/value.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/value.go
index 05d61dd62..a1c341f4d 100644
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/value.go
+++ b/Godeps/_workspace/src/github.com/robertkrimen/otto/value.go
@@ -680,15 +680,36 @@ func (self Value) export() interface{} {
result := make([]interface{}, 0)
lengthValue := object.get("length")
length := lengthValue.value.(uint32)
+ kind := reflect.Invalid
+ state := 0
+ var t reflect.Type
for index := uint32(0); index < length; index += 1 {
name := strconv.FormatInt(int64(index), 10)
if !object.hasProperty(name) {
continue
}
- value := object.get(name)
- result = append(result, value.export())
+ value := object.get(name).export()
+ t = reflect.TypeOf(value)
+ if state == 0 {
+ kind = t.Kind()
+ state = 1
+ } else if state == 1 && kind != t.Kind() {
+ state = 2
+ }
+ result = append(result, value)
}
- return result
+
+ if state != 1 || kind == reflect.Interface {
+ // No common type
+ return result
+ }
+
+ // Convert to the common type
+ val := reflect.MakeSlice(reflect.SliceOf(t), len(result), len(result))
+ for i, v := range result {
+ val.Index(i).Set(reflect.ValueOf(v))
+ }
+ return val.Interface()
} else {
result := make(map[string]interface{})
// TODO Should we export everything? Or just what is enumerable?
@@ -770,6 +791,21 @@ func (self Value) exportNative() interface{} {
// Make a best effort to return a reflect.Value corresponding to reflect.Kind, but
// fallback to just returning the Go value we have handy.
func (value Value) toReflectValue(kind reflect.Kind) (reflect.Value, error) {
+ if kind != reflect.Float32 && kind != reflect.Float64 && kind != reflect.Interface {
+ switch value := value.value.(type) {
+ case float32:
+ _, frac := math.Modf(float64(value))
+ if frac > 0 {
+ return reflect.Value{}, fmt.Errorf("RangeError: %v to reflect.Kind: %v", value, kind)
+ }
+ case float64:
+ _, frac := math.Modf(value)
+ if frac > 0 {
+ return reflect.Value{}, fmt.Errorf("RangeError: %v to reflect.Kind: %v", value, kind)
+ }
+ }
+ }
+
switch kind {
case reflect.Bool: // Bool
return reflect.ValueOf(value.bool()), nil
@@ -857,7 +893,7 @@ func (value Value) toReflectValue(kind reflect.Kind) (reflect.Value, error) {
if 0 > tmp1 {
tmp1 = -tmp1
}
- if tmp1 < math.SmallestNonzeroFloat32 || tmp1 > math.MaxFloat32 {
+ if tmp1 > 0 && (tmp1 < math.SmallestNonzeroFloat32 || tmp1 > math.MaxFloat32) {
return reflect.Value{}, fmt.Errorf("RangeError: %f (%v) to float32", tmp, value)
} else {
return reflect.ValueOf(float32(tmp)), nil
diff --git a/Godeps/_workspace/src/github.com/robertkrimen/otto/value_test.go b/Godeps/_workspace/src/github.com/robertkrimen/otto/value_test.go
deleted file mode 100644
index 4a9bd546f..000000000
--- a/Godeps/_workspace/src/github.com/robertkrimen/otto/value_test.go
+++ /dev/null
@@ -1,281 +0,0 @@
-package otto
-
-import (
- "encoding/json"
- "math"
- "testing"
-)
-
-func TestValue(t *testing.T) {
- tt(t, func() {
- value := UndefinedValue()
- is(value.IsUndefined(), true)
- is(value, UndefinedValue())
- is(value, "undefined")
-
- is(toValue(false), false)
- is(toValue(1), 1)
- is(toValue(1).float64(), float64(1))
- })
-}
-
-func TestObject(t *testing.T) {
- tt(t, func() {
- is(emptyValue.isEmpty(), true)
- //is(newObject().Value(), "[object]")
- //is(newBooleanObject(false).Value(), "false")
- //is(newFunctionObject(nil).Value(), "[function]")
- //is(newNumberObject(1).Value(), "1")
- //is(newStringObject("Hello, World.").Value(), "Hello, World.")
- })
-}
-
-type intAlias int
-
-func TestToValue(t *testing.T) {
- tt(t, func() {
- _, tester := test()
- vm := tester.vm
-
- value, _ := vm.ToValue(nil)
- is(value, "undefined")
-
- value, _ = vm.ToValue((*byte)(nil))
- is(value, "undefined")
-
- value, _ = vm.ToValue(intAlias(5))
- is(value, 5)
-
- {
- tmp := new(int)
-
- value, _ = vm.ToValue(&tmp)
- is(value, 0)
-
- *tmp = 1
-
- value, _ = vm.ToValue(&tmp)
- is(value, 1)
-
- tmp = nil
-
- value, _ = vm.ToValue(&tmp)
- is(value, "undefined")
- }
-
- {
- tmp0 := new(int)
- tmp1 := &tmp0
- tmp2 := &tmp1
-
- value, _ = vm.ToValue(&tmp2)
- is(value, 0)
-
- *tmp0 = 1
-
- value, _ = vm.ToValue(&tmp2)
- is(value, 1)
-
- tmp0 = nil
-
- value, _ = vm.ToValue(&tmp2)
- is(value, "undefined")
- }
- })
-}
-
-func TestToBoolean(t *testing.T) {
- tt(t, func() {
- is := func(left interface{}, right bool) {
- is(toValue(left).bool(), right)
- }
-
- is("", false)
- is("xyzzy", true)
- is(1, true)
- is(0, false)
- //is(toValue(newObject()), true)
- is(UndefinedValue(), false)
- is(NullValue(), false)
- })
-}
-
-func TestToFloat(t *testing.T) {
- tt(t, func() {
- {
- is := func(left interface{}, right float64) {
- is(toValue(left).float64(), right)
- }
- is("", 0)
- is("xyzzy", math.NaN())
- is("2", 2)
- is(1, 1)
- is(0, 0)
- is(NullValue(), 0)
- //is(newObjectValue(), math.NaN())
- }
- is(math.IsNaN(UndefinedValue().float64()), true)
- })
-}
-
-func TestToString(t *testing.T) {
- tt(t, func() {
- is("undefined", UndefinedValue().string())
- is("null", NullValue().string())
- is("true", toValue(true).string())
- is("false", toValue(false).string())
-
- is(UndefinedValue(), "undefined")
- is(NullValue(), "null")
- is(toValue(true), true)
- is(toValue(false), false)
- })
-}
-
-func Test_toInt32(t *testing.T) {
- tt(t, func() {
- test := []interface{}{
- 0, int32(0),
- 1, int32(1),
- -2147483649.0, int32(2147483647),
- -4294967297.0, int32(-1),
- -4294967296.0, int32(0),
- -4294967295.0, int32(1),
- math.Inf(+1), int32(0),
- math.Inf(-1), int32(0),
- }
- for index := 0; index < len(test)/2; index++ {
- // FIXME terst, Make strict again?
- is(
- toInt32(toValue(test[index*2])),
- test[index*2+1].(int32),
- )
- }
- })
-}
-
-func Test_toUint32(t *testing.T) {
- tt(t, func() {
- test := []interface{}{
- 0, uint32(0),
- 1, uint32(1),
- -2147483649.0, uint32(2147483647),
- -4294967297.0, uint32(4294967295),
- -4294967296.0, uint32(0),
- -4294967295.0, uint32(1),
- math.Inf(+1), uint32(0),
- math.Inf(-1), uint32(0),
- }
- for index := 0; index < len(test)/2; index++ {
- // FIXME terst, Make strict again?
- is(
- toUint32(toValue(test[index*2])),
- test[index*2+1].(uint32),
- )
- }
- })
-}
-
-func Test_toUint16(t *testing.T) {
- tt(t, func() {
- test := []interface{}{
- 0, uint16(0),
- 1, uint16(1),
- -2147483649.0, uint16(65535),
- -4294967297.0, uint16(65535),
- -4294967296.0, uint16(0),
- -4294967295.0, uint16(1),
- math.Inf(+1), uint16(0),
- math.Inf(-1), uint16(0),
- }
- for index := 0; index < len(test)/2; index++ {
- // FIXME terst, Make strict again?
- is(
- toUint16(toValue(test[index*2])),
- test[index*2+1].(uint16),
- )
- }
- })
-}
-
-func Test_sameValue(t *testing.T) {
- tt(t, func() {
- is(sameValue(positiveZeroValue(), negativeZeroValue()), false)
- is(sameValue(positiveZeroValue(), toValue(0)), true)
- is(sameValue(NaNValue(), NaNValue()), true)
- is(sameValue(NaNValue(), toValue("Nothing happens.")), false)
- })
-}
-
-func TestExport(t *testing.T) {
- tt(t, func() {
- test, vm := test()
-
- is(test(`null;`).export(), nil)
- is(test(`undefined;`).export(), nil)
- is(test(`true;`).export(), true)
- is(test(`false;`).export(), false)
- is(test(`0;`).export(), 0)
- is(test(`3.1459`).export(), 3.1459)
- is(test(`"Nothing happens";`).export(), "Nothing happens")
- is(test(`String.fromCharCode(97,98,99,100,101,102)`).export(), "abcdef")
- {
- value := test(`({ abc: 1, def: true, ghi: undefined });`).export().(map[string]interface{})
- is(value["abc"], 1)
- is(value["def"], true)
- _, exists := value["ghi"]
- is(exists, false)
- }
- {
- value := test(`[ "abc", 1, "def", true, undefined, null ];`).export().([]interface{})
- is(value[0], "abc")
- is(value[1], 1)
- is(value[2], "def")
- is(value[3], true)
- is(value[4], nil)
- is(value[5], nil)
- is(value[5], interface{}(nil))
- }
-
- roundtrip := []interface{}{
- true,
- false,
- 0,
- 3.1459,
- []interface{}{true, false, 0, 3.1459, "abc"},
- map[string]interface{}{
- "Boolean": true,
- "Number": 3.1459,
- "String": "abc",
- "Array": []interface{}{false, 0, "", nil},
- "Object": map[string]interface{}{
- "Boolean": false,
- "Number": 0,
- "String": "def",
- },
- },
- }
-
- for _, value := range roundtrip {
- input, err := json.Marshal(value)
- is(err, nil)
-
- output, err := json.Marshal(test("(" + string(input) + ");").export())
- is(err, nil)
-
- is(string(input), string(output))
- }
-
- {
- abc := struct {
- def int
- ghi interface{}
- xyz float32
- }{}
- abc.def = 3
- abc.xyz = 3.1459
- vm.Set("abc", abc)
- is(test(`abc;`).export(), abc)
- }
- })
-}