From 4333a53f280556c62c2595ea6dd48edac324a159 Mon Sep 17 00:00:00 2001 From: playX Date: Wed, 29 Sep 2021 15:33:14 +0300 Subject: [PATCH] js: support running `.js.v` tests in `v test-self`, fixes for array methods & codegen (#12011) --- cmd/tools/modules/testing/common.v | 18 +- cmd/tools/vtest-self.v | 4 +- vlib/builtin/js/array.js.v | 24 +- vlib/builtin/js/array_test.js.v | 1490 ++++++++++++++++++++++++ vlib/v/builder/compile.v | 2 +- vlib/v/gen/js/array.v | 12 +- vlib/v/gen/js/auto_eq_methods.v | 12 +- vlib/v/gen/js/auto_str_methods.v | 188 +-- vlib/v/gen/js/builtin_types.v | 2 +- vlib/v/gen/js/fn.v | 11 + vlib/v/gen/js/infix.v | 31 +- vlib/v/gen/js/js.v | 58 +- vlib/v/gen/js/str.v | 72 ++ vlib/v/gen/js/tests/testdata/array.out | 302 ----- vlib/v/gen/js/tests/testdata/array.v | 1187 ------------------- 15 files changed, 1803 insertions(+), 1610 deletions(-) create mode 100644 vlib/builtin/js/array_test.js.v delete mode 100644 vlib/v/gen/js/tests/testdata/array.out delete mode 100644 vlib/v/gen/js/tests/testdata/array.v diff --git a/cmd/tools/modules/testing/common.v b/cmd/tools/modules/testing/common.v index 63e67ca5a8..402fe8530d 100644 --- a/cmd/tools/modules/testing/common.v +++ b/cmd/tools/modules/testing/common.v @@ -268,7 +268,18 @@ fn worker_trunner(mut p pool.PoolProcessor, idx int, thread_id int) voidptr { tls_bench.no_cstep = true mut relative_file := os.real_path(p.get_item(idx)) mut cmd_options := [ts.vargs] - if relative_file.contains('global') && !ts.vargs.contains('fmt') { + mut run_js := false + + is_fmt := ts.vargs.contains('fmt') + + if relative_file.ends_with('js.v') { + if !is_fmt { + cmd_options << ' -b js' + } + run_js = true + } + + if relative_file.contains('global') && !is_fmt { cmd_options << ' -enable-globals' } if ts.root_relative { @@ -279,8 +290,10 @@ fn worker_trunner(mut p pool.PoolProcessor, idx int, thread_id int) voidptr { // Ensure that the generated binaries will be stored in the temporary folder. // Remove them after a test passes/fails. fname := os.file_name(file) - generated_binary_fname := if os.user_os() == 'windows' { + generated_binary_fname := if os.user_os() == 'windows' && !run_js { fname.replace('.v', '.exe') + } else if !run_js { + fname.replace('.v', '') } else { fname.replace('.v', '') } @@ -290,6 +303,7 @@ fn worker_trunner(mut p pool.PoolProcessor, idx int, thread_id int) voidptr { os.rm(generated_binary_fpath) or {} } } + if !ts.vargs.contains('fmt') { cmd_options << ' -o "$generated_binary_fpath"' } diff --git a/cmd/tools/vtest-self.v b/cmd/tools/vtest-self.v index 8ef97ee781..fc654df056 100644 --- a/cmd/tools/vtest-self.v +++ b/cmd/tools/vtest-self.v @@ -91,6 +91,7 @@ const ( 'vlib/net/http/header_test.v', 'vlib/net/http/server_test.v', 'vlib/net/http/response_test.v', + 'vlib/builtin/js/array_test.js.v', ] skip_on_linux = [ 'do_not_remove', @@ -142,7 +143,8 @@ fn main() { args_string := args[1..].join(' ') cmd_prefix := args_string.all_before('test-self') title := 'testing vlib' - all_test_files := os.walk_ext(os.join_path(vroot, 'vlib'), '_test.v') + mut all_test_files := os.walk_ext(os.join_path(vroot, 'vlib'), '_test.v') + all_test_files << os.walk_ext(os.join_path(vroot, 'vlib'), '_test.js.v') testing.eheader(title) mut tsession := testing.new_test_session(cmd_prefix, true) tsession.files << all_test_files.filter(!it.contains('testdata' + os.path_separator)) diff --git a/vlib/builtin/js/array.js.v b/vlib/builtin/js/array.js.v index a01b98e6a4..f9124bdaf0 100644 --- a/vlib/builtin/js/array.js.v +++ b/vlib/builtin/js/array.js.v @@ -1,7 +1,9 @@ module builtin +import strings /// Internal representation of `array` type. It is used to implement slices and to make slices behave correctly /// it simply stores reference to original array and to index them properly it does index array relative to `index_start`. + struct array_buffer { arr JS.Array index_start int @@ -43,6 +45,7 @@ fn (mut a array_buffer) set(ix int, val voidptr) { #array_buffer.prototype.set = function(ix,val) { array_buffer_set(this,ix,val); } struct array { +mut: arr array_buffer pub: len int @@ -175,8 +178,9 @@ pub fn (a array) index(v string) int { pub fn (a array) slice(start int, end int) array { mut result := a #let slice = a.arr.arr.slice(start,end) - #result = new array(new array_buffer({arr: a.arr.arr, len: new int(slice.length),cap: new int(slice.length),index_start: new int(start)})) + #result = new array(new array_buffer({arr: a.arr.arr, len: new int(slice.length),cap: new int(slice.length),index_start: new int(start),has_slice: new bool(true)})) #a.arr.has_slice = true + //#v_makeSlice(result) return result } @@ -199,7 +203,10 @@ pub fn (mut a array) join(separator string) string { fn (mut a array) push(val voidptr) { #a.val.arr.make_copy() + #if (arguments[2] && arguments[2].valueOf()) {a.val.arr.arr.push(...val)} else { #a.val.arr.arr.push(val) + #} + #a.val.arr.len.val += 1 } fn v_filter(arr array, callback fn (voidptr) bool) array { @@ -271,6 +278,12 @@ pub fn (mut a array) delete(i int) { a.delete_many(i, 1) } +fn arr_copy(mut dst array, src array, count int) { + for i := 0; i < count; i++ { + dst.arr.set(i, src.arr.get(i)) + } +} + // delete_many deletes `size` elements beginning with index `i` pub fn (mut a array) delete_many(i int, size int) { #a.val.arr.make_copy() @@ -301,6 +314,11 @@ pub fn (mut a array) reverse_in_place() { #array.prototype.$includes = function (elem) { return this.arr.arr.find(function(e) { return vEq(elem,e); }) !== undefined;} +pub fn (mut a array) clear() { + #a.val.arr.make_copy() + #a.val.arr.arr.clear() +} + // reduce executes a given reducer function on each element of the array, // resulting in a single output value. pub fn (a array) reduce(iter fn (int, int) int, accum_start int) int { @@ -319,6 +337,7 @@ pub fn (mut a array) pop() voidptr { mut res := voidptr(0) #a.val.arr.make_copy() #res = a.val.arr.arr.pop() + #a.val.arr.len.val -= 1 return res } @@ -361,7 +380,6 @@ pub fn (a array) bytestr() string { return res } -/* pub fn (a []string) str() string { mut sb := strings.new_builder(a.len * 3) sb.write_string('[') @@ -377,4 +395,4 @@ pub fn (a []string) str() string { sb.write_string(']') res := sb.str() return res -}*/ +} diff --git a/vlib/builtin/js/array_test.js.v b/vlib/builtin/js/array_test.js.v new file mode 100644 index 0000000000..b90a8073dc --- /dev/null +++ b/vlib/builtin/js/array_test.js.v @@ -0,0 +1,1490 @@ +fn test_js() { + $if js_node { + assert true + } $else { + assert false + } +} + +fn test_pointer() { + mut arr := []&int{} + a := 1 + b := 2 + c := 3 + arr << &a + arr << &b + arr << &c + assert *arr[0] == 1 + arr[1] = &c + assert *arr[1] == 3 + mut d_arr := [arr] // [][]&int + d_arr << arr + assert *d_arr[0][1] == 3 + println(*d_arr[0][1]) + assert *d_arr[1][0] == 1 +} + +fn test_assign() { + mut arr := [2, 4, 8, 16, 32, 64, 128] + arr[0] = 2 + arr[1] &= 255 + arr[2] |= 255 + arr[3] <<= 4 + arr[4] >>= 4 + arr[5] %= 5 + arr[6] ^= 3 + assert arr[0] == 2 + assert arr[1] == 4 & 255 + assert arr[2] == 8 | 255 + assert arr[3] == 16 << 4 + assert arr[4] == 32 >> 4 + assert arr[5] == 64 % 5 + assert arr[6] == 128 ^ 3 +} + +fn test_ints() { + mut a := [1, 5, 2, 3] + assert a.len == 4 + assert a[0] == 1 + assert a[2] == 2 + assert a.last() == 3 + a << 4 + assert a.len == 5 + assert a[4] == 4 + assert a.last() == 4 + s := a.str() + assert s == '[1, 5, 2, 3, 4]' + assert a[1] == 5 + assert a.last() == 4 +} + +fn test_deleting() { + mut a := [1, 5, 2, 3, 4] + assert a.len == 5 + assert a.str() == '[1, 5, 2, 3, 4]' + a.delete(0) + assert a.str() == '[5, 2, 3, 4]' + assert a.len == 4 + a.delete(1) + assert a.str() == '[5, 3, 4]' + assert a.len == 3 + a.delete(a.len - 1) + assert a.str() == '[5, 3]' + assert a.len == 2 +} + +fn test_slice_delete() { + mut a := [1.5, 2.5, 3.25, 4.5, 5.75] + b := a[2..4] + a.delete(0) + assert a == [2.5, 3.25, 4.5, 5.75] + assert b == [3.25, 4.5] + a = [3.75, 4.25, -1.5, 2.25, 6.0] + c := a[..3] + a.delete(2) + assert a == [3.75, 4.25, 2.25, 6.0] + assert c == [3.75, 4.25, -1.5] +} + +fn test_delete_many() { + mut a := [1, 2, 3, 4, 5, 6, 7, 8, 9] + b := a[2..6] + a.delete_many(4, 3) + assert a == [1, 2, 3, 4, 8, 9] + assert b == [3, 4, 5, 6] + c := a[..a.len] + a.delete_many(2, 0) // this should just clone + a[1] = 17 + assert a == [1, 17, 3, 4, 8, 9] + assert c == [1, 2, 3, 4, 8, 9] + a.delete_many(0, a.len) + assert a == []int{} +} + +fn test_short() { + a := [1, 2, 3] + assert a.len == 3 + assert a.cap == 3 + assert a[0] == 1 + assert a[1] == 2 + assert a[2] == 3 +} + +fn test_large() { + mut a := [0].repeat(0) + for i in 0 .. 10000 { + a << i + } + assert a.len == 10000 + assert a[234] == 234 +} + +struct Chunk { + val string +} + +struct Kkk { + q []Chunk +} + +fn test_empty() { + mut chunks := []Chunk{} + a := Chunk{} + assert chunks.len == 0 + chunks << a + assert chunks.len == 1 + chunks = [] + assert chunks.len == 0 + chunks << a + assert chunks.len == 1 +} + +fn test_push() { + mut a := []int{} + a << 1 + a << 3 + assert a[1] == 3 + assert a.str() == '[1, 3]' +} + +fn test_insert() { + mut a := [1, 2] + a.insert(0, 3) + assert a[0] == 3 + assert a[2] == 2 + assert a.len == 3 + a.insert(1, 4) + assert a[1] == 4 + assert a[2] == 1 + assert a.len == 4 + a.insert(4, 5) + assert a[4] == 5 + assert a[3] == 2 + assert a.len == 5 + mut b := []f64{} + assert b.len == 0 + b.insert(0, f64(1.1)) + assert b.len == 1 + assert b[0] == f64(1.1) +} + +fn test_insert_many() { + mut a := [3, 4] + a.insert(0, [1, 2]) + assert a == [1, 2, 3, 4] + b := [5, 6] + a.insert(1, b) + assert a == [1, 5, 6, 2, 3, 4] +} + +fn test_prepend() { + mut a := []int{} + assert a.len == 0 + a.prepend(1) + assert a.len == 1 + assert a[0] == 1 + mut b := []f64{} + assert b.len == 0 + b.prepend(f64(1.1)) + assert b.len == 1 + assert b[0] == f64(1.1) +} + +fn test_prepend_many() { + mut a := [3, 4] + a.prepend([1, 2]) + assert a == [1, 2, 3, 4] + b := [5, 6] + a.prepend(b) + assert a == [5, 6, 1, 2, 3, 4] +} + +fn test_strings() { + a := ['a', 'b', 'c'] + assert a.str() == "['a', 'b', 'c']" +} + +/* +fn test_compare_ints() { + assert compare_ints(1, 2) == -1 + assert compare_ints(2, 1) == 1 + assert compare_ints(0, 0) == 0 + + a := 1 + b := 2 + assert compare_ints(a, b) == -1 + assert compare_ints(b, a) == 1 + assert compare_ints(a, a) == 0 +} +*/ +fn test_repeat() { + { + a := [0].repeat(5) + assert a.len == 5 + assert a[0] == 0 && a[1] == 0 && a[2] == 0 && a[3] == 0 && a[4] == 0 + } + { + a := [1.1].repeat(10) + assert a[0] == 1.1 + assert a[5] == 1.1 + assert a[9] == 1.1 + } + { + a := [i64(-123)].repeat(10) + assert a[0] == -123 + assert a[5] == -123 + assert a[9] == -123 + } + { + a := [u64(123)].repeat(10) + assert a[0] == 123 + assert a[5] == 123 + assert a[9] == 123 + } + { + a := [1.1].repeat(10) + assert a[0] == 1.1 + assert a[5] == 1.1 + assert a[9] == 1.1 + } + { + a := [1, 2].repeat(2) + assert a[0] == 1 + assert a[1] == 2 + assert a[2] == 1 + assert a[3] == 2 + } + { + a := ['1', 'abc'].repeat(2) + assert a[0] == '1' + assert a[1] == 'abc' + assert a[2] == '1' + assert a[3] == 'abc' + } + { + mut a := ['1', 'abc'].repeat(0) + assert a.len == 0 + a << 'abc' + assert a[0] == 'abc' + } +} + +/* +fn test_deep_repeat() { + mut a3 := [[[1, 1], [2, 2], [3, 3]], [[4, 4], [5, 5], [6, 6]]] + r := a3.repeat(3) + a3[1][1][0] = 17 + assert r == [ + [[1, 1], [2, 2], [3, 3]], + [[4, 4], [5, 5], [6, 6]], + [[1, 1], [2, 2], [3, 3]], + [[4, 4], [5, 5], [6, 6]], + [[1, 1], [2, 2], [3, 3]], + [[4, 4], [5, 5], [6, 6]], + ] + assert a3 == [[[1, 1], [2, 2], [3, 3]], [[4, 4], [17, 5], [6, 6]]] +} +*/ +fn test_right() { + a := [1, 2, 3, 4] + c := a[1..a.len] + d := a[1..] + assert c[0] == 2 + assert c[1] == 3 + assert d[0] == 2 + assert d[1] == 3 +} + +fn test_left() { + a := [1, 2, 3] + c := a[0..2] + d := a[..2] + assert c[0] == 1 + assert c[1] == 2 + assert d[0] == 1 + assert d[1] == 2 +} + +fn test_slice() { + a := [1, 2, 3, 4] + b := a[2..4] + assert b.len == 2 + assert a[1..2].len == 1 + assert a.len == 4 +} + +fn test_push_many() { + mut a := [1, 2, 3] + b := [4, 5, 6] + a << b + assert a.len == 6 + assert a[0] == 1 + assert a[3] == 4 + assert a[5] == 6 +} + +fn test_reverse() { + a := [1, 2, 3, 4] + b := ['test', 'array', 'reverse'] + c := a.reverse() + println(c) + d := b.reverse() + for i, _ in c { + assert c[i] == a[a.len - i - 1] + } + for i, _ in d { + assert d[i] == b[b.len - i - 1] + } + e := []int{} + f := e.reverse() + assert f.len == 0 +} + +const ( + c_n = 5 +) + +struct Foooj { + a [5]int // c_n +} + +fn test_fixed() { + mut nums := [4]int{} + // x := nums[1..3] + // assert x.len == 2 + assert nums[0] == 0 + assert nums[1] == 0 + assert nums[2] == 0 + assert nums[3] == 0 + nums[1] = 7 + assert nums[1] == 7 + nums2 := [5]int{} // c_n + assert nums2[c_n - 1] == 0 +} + +fn modify(mut numbers []int) { + numbers[0] = 777 +} + +fn test_mut_slice() { + mut n := [1, 2, 3] + // modify(mut n) + modify(mut n[..2]) + assert n[0] == 777 + modify(mut n[2..]) + assert n[2] == 777 + println(n) +} + +fn double_up(mut a []int) { + for i := 0; i < a.len; i++ { + a[i] = a[i] * 2 + } +} + +fn double_up_v2(mut a []int) { + for i, _ in a { + a[i] = a[i] * 2 // or val*2, doesn't matter + } +} + +fn test_mut_arg() { + mut arr := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + double_up(mut arr) + assert arr.str() == '[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]' + arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + double_up_v2(mut arr) + assert arr.str() == '[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]' +} + +fn test_clone() { + nums := [1, 2, 3, 4, 100] + _ = nums + nums2 := nums.clone() + assert nums2.len == 5 + assert nums.str() == '[1, 2, 3, 4, 100]' + assert nums2.str() == '[1, 2, 3, 4, 100]' + assert nums[1..3].str() == '[2, 3]' +} + +/* +fn test_copy() { + a := [1, 2, 3] + b := a + assert b[0] == 1 + assert b[1] == 2 + assert b[2] == 3 +} +*/ +fn test_multi_array_clone() { + // 2d array_int + mut a2_1 := [[1, 2, 3], [4, 5, 6]] + mut a2_2 := a2_1.clone() + a2_1[0][1] = 0 + a2_2[1][0] = 0 + assert a2_1 == [[1, 0, 3], [4, 5, 6]] + assert a2_2 == [[1, 2, 3], [0, 5, 6]] + // 2d array_string + mut b2_1 := [['1', '2', '3'], ['4', '5', '6']] + mut b2_2 := b2_1.clone() + b2_1[0][1] = '0' + b2_2[1][0] = '0' + assert b2_1 == [['1', '0', '3'], ['4', '5', '6']] + assert b2_2 == [['1', '2', '3'], ['0', '5', '6']] + // 3d array_int + mut a3_1 := [[[1, 1], [2, 2], [3, 3]], [[4, 4], [5, 5], [6, 6]]] + mut a3_2 := a3_1.clone() + a3_1[0][0][1] = 0 + a3_2[0][1][0] = 0 + assert a3_1 == [[[1, 0], [2, 2], [3, 3]], [[4, 4], [5, 5], + [6, 6]]] + assert a3_2 == [[[1, 1], [0, 2], [3, 3]], [[4, 4], [5, 5], + [6, 6]]] + // 3d array_string + mut b3_1 := [[['1', '1'], ['2', '2'], ['3', '3']], [['4', '4'], + ['5', '5'], ['6', '6']]] + mut b3_2 := b3_1.clone() + b3_1[0][0][1] = '0' + b3_2[0][1][0] = '0' + assert b3_1 == [[['1', '0'], ['2', '2'], ['3', '3']], [['4', '4'], + ['5', '5'], ['6', '6']]] + assert b3_2 == [[['1', '1'], ['0', '2'], ['3', '3']], [['4', '4'], + ['5', '5'], ['6', '6']]] +} + +fn test_doubling() { + mut nums := [1, 2, 3, 4, 5] + for i in 0 .. nums.len { + nums[i] *= 2 + } + println(nums.str()) + assert nums.str() == '[2, 4, 6, 8, 10]' +} + +struct Test2 { + one int + two int +} + +struct Test { + a string +mut: + b []Test2 +} + +// TODO: default array/struct str methods +fn (ta []Test2) str() string { + mut s := '[' + for i, t in ta { + s += t.str() + if i < ta.len - 1 { + s += ', ' + } + } + s += ']' + return s +} + +fn (t Test2) str() string { + return '{$t.one $t.two}' +} + +fn (t Test) str() string { + return '{$t.a $t.b}' +} + +fn test_struct_print() { + mut a := Test{ + a: 'Test' + b: [] + } + b := Test2{ + one: 1 + two: 2 + } + a.b << b + a.b << b + assert a.str() == '{Test [{1 2}, {1 2}]}' + assert b.str() == '{1 2}' + assert a.b.str() == '[{1 2}, {1 2}]' +} + +fn test_single_element() { + mut a := [1] + a << 2 + assert a.len == 2 + assert a[0] == 1 + assert a[1] == 2 + println(a) +} + +fn test_find_index() { + // string + a := ['v', 'is', 'great'] + assert a.index('v') == 0 + assert a.index('is') == 1 + assert a.index('gre') == -1 + // int + b := [1, 2, 3, 4] + assert b.index(1) == 0 + assert b.index(4) == 3 + assert b.index(5) == -1 + // byte + c := [0x22, 0x33, 0x55] + assert c.index(0x22) == 0 + assert c.index(0x55) == 2 + assert c.index(0x99) == -1 + // char + d := [`a`, `b`, `c`] + assert d.index(`b`) == 1 + assert d.index(`c`) == 2 + assert d.index(`u`) == -1 +} + +fn test_multi() { + a := [[1, 2, 3], [4, 5, 6]] + assert a.len == 2 + assert a[0].len == 3 + assert a[0][0] == 1 + assert a[0][2] == 3 + assert a[1][2] == 6 + // TODO + // b := [ [[1,2,3],[4,5,6]], [[1,2]] ] + // assert b[0][0][0] == 1 +} + +fn test_in() { + a := [1, 2, 3] + assert 1 in a + assert 2 in a + assert 3 in a + assert 4 !in a + assert 0 !in a + assert 0 !in a + assert 4 !in a + b := [1, 4, 0] + c := [3, 6, 2, 0] + assert 0 in b + assert 0 in c +} + +fn sum(prev int, curr int) int { + return prev + curr +} + +fn sub(prev int, curr int) int { + return prev - curr +} + +fn test_reduce() { + a := [1, 2, 3, 4, 5] + b := a.reduce(sum, 0) + c := a.reduce(sum, 5) + d := a.reduce(sum, -1) + assert b == 15 + assert c == 20 + assert d == 14 + e := [1, 2, 3] + f := e.reduce(sub, 0) + g := e.reduce(sub, -1) + assert f == -6 + assert g == -7 +} + +fn filter_test_helper_1(a int) bool { + return a > 3 +} + +fn test_filter() { + a := [1, 2, 3, 4, 5, 6] + b := a.filter(it % 2 == 0) + assert b.len == 3 + assert b[0] == 2 + assert b[1] == 4 + assert b[2] == 6 + c := ['v', 'is', 'awesome'] + d := c.filter(it.len > 1) + assert d[0] == 'is' + assert d[1] == 'awesome' + //////// + arr := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + println(arr.filter(it % 2 == 0 || it % 3 == 0)) + assert true + assert [1, 2, 3].len == 3 + mut mut_arr := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + mut_arr = mut_arr.filter(it < 4) + assert mut_arr.len == 3 + assert a.filter(filter_test_helper_1) == [4, 5, 6] + assert [1, 5, 10].filter(filter_test_helper_1) == [5, 10] + // TODO + // assert arr.filter(arr % 2).len == 5 +} + +fn test_anon_fn_filter() { + filter_num := fn (i int) bool { + return i % 2 == 0 + } + assert [1, 2, 3, 4, 5].filter(filter_num) == [2, 4] +} + +fn test_anon_fn_arg_filter() { + a := [1, 2, 3, 4].filter(fn (i int) bool { + return i % 2 == 0 + }) + assert a == [2, 4] +} + +fn map_test_helper_1(i int) int { + return i * i +} + +fn map_test_helper_2(i int, b string) int { + return i + b.len +} + +fn map_test_helper_3(i int, b []string) int { + return i + b.map(it.len)[i % b.len] +} + +fn test_map() { + nums := [1, 2, 3, 4, 5, 6] + strs := ['v', 'is', 'awesome'] + // assert nums.map() == + // assert nums.map(it, 'excessive') == + // identity + assert nums.map(it) == [1, 2, 3, 4, 5, 6] + assert strs.map(it) == ['v', 'is', 'awesome'] + assert nums.map(it - it) == [0, 0, 0, 0, 0, 0] + assert nums.map(it - it)[0] == 0 + // type switch + assert nums.map(it * 10) == [10, 20, 30, 40, 50, 60] + assert nums.map(it * it) == [1, 4, 9, 16, 25, 36] + assert nums.map('$it') == ['1', '2', '3', '4', '5', '6'] + assert nums.map(it % 2 == 0) == [false, true, false, true, false, true] + assert strs.map(it.to_upper()) == ['V', 'IS', 'AWESOME'] + assert strs.map(it == 'awesome') == [false, false, true] + assert strs.map(it.len in nums) == [true, true, false] + assert strs.map(int(7)) == [7, 7, 7] + // external func + assert nums.map(map_test_helper_1(it)) == [1, 4, 9, 16, 25, 36] + assert nums.map(map_test_helper_2(it, 'bb')) == [3, 4, 5, 6, 7, 8] + assert nums.map(map_test_helper_3(it, strs)) == [3, 9, 4, 6, 12, 7] + // empty array as input + assert []int{len: 0}.map(it * 2) == [] + // nested maps (where it is of same type) + assert nums.map(strs.map(int(7)) == [7, 7, 7]) == [true, true, true, true, true, true] + assert nums.map('$it' + strs.map('a')[0]) == ['1a', '2a', '3a', '4a', '5a', '6a'] + assert nums.map(it + strs.map(int(7))[0]) == [8, 9, 10, 11, 12, 13] + assert nums.map(it + strs.map(it.len)[0]) == [2, 3, 4, 5, 6, 7] + assert strs.map(it.len + strs.map(it.len)[0]) == [2, 3, 8] + // nested (different it types) + assert strs.map(it[nums.map(it - it)[0]]) == [byte(`v`), `i`, `a`] + assert nums[0..3].map('$it' + strs.map(it)[it - 1]) == ['1v', '2is', '3awesome'] + assert nums.map(map_test_helper_1) == [1, 4, 9, 16, 25, 36] + assert [1, 5, 10].map(map_test_helper_1) == [1, 25, 100] + assert nums == [1, 2, 3, 4, 5, 6] + assert strs == ['v', 'is', 'awesome'] +} + +fn test_anon_fn_map() { + add_num := fn (i int) int { + return i + 1 + } + assert [1, 2, 3].map(add_num) == [2, 3, 4] +} + +fn test_multi_anon_fn_map() { + a := [1, 2, 3].map(fn (i int) int { + return i + 1 + }) + b := [1, 2, 3].map(fn (i int) int { + return i + 2 + }) + assert a == [2, 3, 4] + assert b == [3, 4, 5] +} + +fn test_anon_fn_arg_map() { + a := [1, 2, 3].map(fn (i int) int { + return i + 1 + }) + assert a == [2, 3, 4] +} + +fn test_anon_fn_arg_different_type_map() { + i_to_str := fn (i int) string { + return i.str() + } + a := [1, 2, 3].map(i_to_str) + assert a == ['1', '2', '3'] +} + +fn test_anon_fn_inline_different_type_map() { + a := [1, 2, 3].map(fn (i int) string { + return i.str() + }) + assert a == ['1', '2', '3'] +} + +fn test_array_str() { + numbers := [1, 2, 3] + assert numbers == [1, 2, 3] + numbers2 := [numbers, [4, 5, 6]] // dup str() bug + println(numbers2) + assert true + assert numbers.str() == '[1, 2, 3]' + // QTODO + // assert numbers2.str() == '[[1, 2, 3], [4, 5, 6]]' +} + +struct User { + age int + name string +} + +fn test_eq() { + assert [5, 6, 7] != [6, 7] + assert [`a`, `b`] == [`a`, `b`] + assert [User{ + age: 22 + name: 'bob' + }] == [User{ + age: 22 + name: 'bob' + }] + /* + assert [{ + 'bob': 22 + }, { + 'tom': 33 + }] == [{ + 'bob': 22 + }, { + 'tom': 33 + }]*/ + assert [[1, 2, 3], [4]] == [[1, 2, 3], [4]] +} + +fn test_fixed_array_eq() { + a1 := [1, 2, 3]! + assert a1 == [1, 2, 3]! + assert a1 != [2, 3, 4]! + + a2 := [[1, 2]!, [3, 4]!]! + assert a2 == [[1, 2]!, [3, 4]!]! + assert a2 != [[3, 4]!, [1, 2]!]! + + a3 := [[1, 2], [3, 4]]! + assert a3 == [[1, 2], [3, 4]]! + assert a3 != [[1, 1], [2, 2]]! + + a4 := [[`a`, `b`], [`c`, `d`]]! + assert a4 == [[`a`, `b`], [`c`, `d`]]! + assert a4 != [[`c`, `a`], [`a`, `b`]]! + + a5 := [['aaa', 'bbb'], ['ccc', 'ddd']]! + assert a5 == [['aaa', 'bbb'], ['ccc', 'ddd']]! + assert a5 != [['abc', 'def'], ['ccc', 'ddd']]! + + a6 := [['aaa', 'bbb']!, ['ccc', 'ddd']!]! + assert a6 == [['aaa', 'bbb']!, ['ccc', 'ddd']!]! + assert a6 != [['aaa', 'bbb']!, ['aaa', 'ddd']!]! + + a7 := [[1, 2]!, [3, 4]!] + assert a7 == [[1, 2]!, [3, 4]!] + assert a7 != [[2, 3]!, [1, 2]!] + + a8 := [['aaa', 'bbb']!, ['ccc', 'ddd']!] + assert a8 == [['aaa', 'bbb']!, ['ccc', 'ddd']!] + assert a8 != [['bbb', 'aaa']!, ['cccc', 'dddd']!] +} + +fn test_fixed_array_literal_eq() { + assert [1, 2, 3]! == [1, 2, 3]! + assert [1, 1, 1]! != [1, 2, 3]! + + assert [[1, 2], [3, 4]]! == [[1, 2], [3, 4]]! + assert [[1, 1], [2, 2]]! != [[1, 2], [3, 4]]! + + assert [[1, 1]!, [2, 2]!]! == [[1, 1]!, [2, 2]!]! + assert [[1, 1]!, [2, 2]!]! != [[1, 2]!, [2, 3]!]! + + assert [[1, 1]!, [2, 2]!] == [[1, 1]!, [2, 2]!] + assert [[1, 1]!, [2, 2]!] != [[1, 2]!, [2, 3]!] +} + +fn test_sort() { + mut a := ['hi', '1', '5', '3'] + a.sort() + assert a == ['1', '3', '5', 'hi'] + + mut nums := [67, -3, 108, 42, 7] + nums.sort() + assert nums == [-3, 7, 42, 67, 108] + + nums.sort(a < b) + assert nums == [-3, 7, 42, 67, 108] + + nums.sort(b < a) + assert nums == [108, 67, 42, 7, -3] + + mut users := [User{22, 'Peter'}, User{20, 'Bob'}, User{25, 'Alice'}] + users.sort(a.age < b.age) + assert users[0].age == 20 + assert users[1].age == 22 + assert users[2].age == 25 + assert users[0].name == 'Bob' + assert users[1].name == 'Peter' + assert users[2].name == 'Alice' + + users.sort(a.age > b.age) + assert users[0].age == 25 + assert users[1].age == 22 + assert users[2].age == 20 + + users.sort(b.age > a.age) + assert users[0].age == 20 + assert users[1].age == 22 + assert users[2].age == 25 + + users.sort(a.name < b.name) + assert users[0].name == 'Alice' + assert users[1].name == 'Bob' + assert users[2].name == 'Peter' +} + +fn test_rune_sort() { + mut bs := [`f`, `e`, `d`, `b`, `c`, `a`] + bs.sort() + println(bs) + assert bs == [`a`, `b`, `c`, `d`, `e`, `f`] + + bs.sort(a > b) + println(bs) + assert bs == [`f`, `e`, `d`, `c`, `b`, `a`] + + bs.sort(a < b) + println(bs) + assert bs == [`a`, `b`, `c`, `d`, `e`, `f`] +} + +fn test_sort_by_different_order_of_a_b() { + mut x := [1, 2, 3] + x.sort(a < b) + println(x) + assert x == [1, 2, 3] + + mut y := [1, 2, 3] + y.sort(b < a) + println(y) + assert y == [3, 2, 1] +} + +fn test_f32_sort() { + mut f := [f32(50.0), 15, 1, 79, 38, 0, 27] + f.sort() + assert f == [f32(0.0), 1, 15, 27, 38, 50, 79] + + f.sort(a < b) + assert f == [f32(0.0), 1, 15, 27, 38, 50, 79] + + f.sort(b > a) + assert f == [f32(0.0), 1, 15, 27, 38, 50, 79] + + f.sort(b < a) + assert f == [f32(79.0), 50, 38, 27, 15, 1, 0] + + f.sort(a > b) + assert f == [f32(79.0), 50, 38, 27, 15, 1, 0] +} + +fn test_f64_sort() { + mut f := [50.0, 15, 1, 79, 38, 0, 27] + f.sort() + assert f[0] == 0.0 + assert f[1] == 1.0 + assert f[6] == 79.0 +} + +fn test_i64_sort() { + mut f := [i64(50), 15, 1, 79, 38, 0, 27] + f.sort() + assert f[0] == 0 + assert f[1] == 1 + assert f[6] == 79 +} + +fn test_sort_index_expr() { + mut f := [[i64(50), 48], [i64(15)], [i64(1)], [i64(79)], [i64(38)], + [i64(0)], [i64(27)]] + // TODO This currently gives "indexing pointer" error without unsafe + unsafe { + f.sort(a[0] < b[0]) + } + assert f == [[i64(0)], [i64(1)], [i64(15)], [i64(27)], [i64(38)], + [i64(50), 48], [i64(79)]] +} + +fn test_a_b_paras_sort() { + mut arr_i := [1, 3, 2] + arr_i.sort(a < b) + println(arr_i) + assert arr_i == [1, 2, 3] + arr_i.sort(b < a) + println(arr_i) + assert arr_i == [3, 2, 1] + + mut arr_f := [1.1, 3.3, 2.2] + arr_f.sort(a < b) + println(arr_f) + assert arr_f == [1.1, 2.2, 3.3] + arr_f.sort(b < a) + println(arr_f) + assert arr_f == [3.3, 2.2, 1.1] +} + +/* +fn test_for_last() { + numbers := [1, 2, 3, 4] + mut s := '[' + for num in numbers { + s += '$num' + if !last { + s += ', ' + + } + } + s += ']' + assert s == '[1, 2, 3, 4]' +} +*/ +struct Foo { +mut: + bar []int +} + +fn test_in_struct() { + mut baz := Foo{ + bar: [0, 0, 0] + } + baz.bar[0] += 2 + baz.bar[0]++ + assert baz.bar[0] == 3 +} + +[direct_array_access] +fn test_direct_modification() { + mut foo := [2, 0, 5] + foo[1] = 3 + foo[0] *= 7 + foo[1]-- + foo[2] -= 2 + assert foo[0] == 14 + assert foo[1] == 2 + assert foo[2] == 3 +} + +fn test_bools() { + println('test b') + mut a := [true, false] + a << true + println(a) +} + +fn test_push_many_self() { + mut actual_arr := [1, 2, 3, 4] + actual_arr << actual_arr + expected_arr := [1, 2, 3, 4, 1, 2, 3, 4] + assert actual_arr.len == expected_arr.len + for i in 0 .. actual_arr.len { + assert actual_arr[i] == expected_arr[i] + } +} + +fn test_for() { + nums := [1, 2, 3] + mut sum := 0 + for num in nums { + sum += num + } + assert sum == 6 +} + +fn test_clear() { + mut arr := [1, 2, 3] + assert arr.len == 3 + arr.clear() + assert arr.len == 0 + arr << 3 + arr << 2 + arr << 1 + arr << 0 + assert arr.len == 4 + assert arr[0] == 3 + assert arr[1] == 2 + assert arr[2] == 1 + assert arr[3] == 0 + arr.clear() + assert arr.len == 0 +} + +/* +fn test_trim() { + mut arr := [1, 2, 3, 4, 5, 6, 7, 8, 9] + assert arr.len == 9 + arr.trim(9) + assert arr.len == 9 + assert arr.last() == 9 + arr.trim(7) + assert arr.len == 7 + assert arr.last() == 7 + arr.trim(2) + assert arr.len == 2 + assert arr.last() == 2 +}*/ +/* +fn test_hex() { + // array hex + st := [byte(`V`), `L`, `A`, `N`, `G`] + assert st.hex() == '564c414e47' + assert st.hex().len == 10 + st1 := [byte(0x41)].repeat(100) + assert st1.hex() == '41'.repeat(100) +}*/ + +fn test_left_shift_precendence() { + mut arr := []int{} + arr << 1 + 1 + arr << 1 - 1 + arr << 2 / 1 + arr << 2 * 1 + assert arr[0] == 2 + assert arr[1] == 0 + assert arr[2] == 2 + assert arr[3] == 2 +} + +/* +fn test_array_with_cap() { + a4 := []int{len: 1, cap: 10} + assert a4.len == 1 + assert a4.cap == 10 + a5 := []int{len: 1, cap: 10} + assert a5.len == 1 + assert a5.cap == 10 +}*/ +fn test_multi_array_index() { + mut a := [][]int{len: 2, init: []int{len: 3, init: 0}} + a[0][0] = 1 + assert '$a' == '[[1, 0, 0], [0, 0, 0]]' + // mut b := [[0].repeat(3)].repeat(2) + // b[0][0] = 1 + // assert '$b' == '[[1, 0, 0], [0, 0, 0]]' +} + +fn test_plus_assign_string() { + mut a := [''] + a[0] += 'abc' + assert a == ['abc'] +} + +fn mut_arr_with_eq_in_fn(mut a []int) { + if a == [1, 2, 3, 4] { + a[0] = 0 + } + if [0, 2, 3, 4] == a { + a[1] = 0 + } + if !(a != [0, 0, 3, 4]) { + a[2] = 0 + } + if !([0, 0, 0, 4] != a) { + a[3] = 0 + } +} + +fn test_mut_arr_with_eq_in_fn() { + mut a := [1, 2, 3, 4] + mut_arr_with_eq_in_fn(mut a) + assert a == [0, 0, 0, 0] +} + +fn array_in_mut(mut a []int) { + if 1 in a { + a[0] = 2 + } +} + +fn test_array_in_mut() { + mut a := [1, 2] + array_in_mut(mut a) + assert a == [2, 2] +} + +// test array delete in function with mut argument +fn delete_nums(mut arr []int) { + arr.delete(0) +} + +fn test_array_delete_in_mut() { + mut nums := [1, 2, 3] + delete_nums(mut nums) + assert nums == [2, 3] +} + +// test array add in function with mut argument +fn add_nums(mut arr []int) { + arr << 4 +} + +fn test_array_add_in_mut() { + mut nums := [1, 2, 3] + add_nums(mut nums) + assert nums == [1, 2, 3, 4] +} + +fn test_reverse_in_place() { + mut a := [1, 2, 3, 4] + a.reverse_in_place() + assert a == [4, 3, 2, 1] + mut b := ['a', 'b', 'c'] + b.reverse_in_place() + assert b == ['c', 'b', 'a'] + mut c := [[1, 2], [3, 4], [5, 6]] + c.reverse_in_place() + assert c == [[5, 6], [3, 4], [1, 2]] +} + +fn test_array_int_pop() { + mut a := [1, 2, 3, 4, 5] + assert a.len == 5 + x := a.last() + y := a.pop() + assert x == y + assert a.len == 4 + z := a.pop() + assert a.len == 3 + assert z == 4 + x1 := a.pop() + x2 := a.pop() + final := a.pop() + assert final == 1 +} + +fn test_array_string_pop() { + mut a := ['abc', 'def', 'xyz'] + assert a.len == 3 + assert a.pop() == 'xyz' + assert a.pop() == 'def' + assert a.pop() == 'abc' + assert a.len == 0 + // assert a.cap == 3 +} + +fn test_array_first() { + a := [3] + assert a.first() == 3 + b := [1, 2, 3, 4] + assert b.first() == 1 + c := ['abc', 'def'] + assert c.first()[0] == `a` + s := [Chunk{'a'}] + assert s.first().val == 'a' +} + +fn test_array_last() { + a := [3] + assert a.last() == 3 + b := [1, 2, 3, 4] + assert b.last() == 4 + c := ['abc', 'def'] + assert c.last()[0] == `d` + s := [Chunk{'a'}] + assert s.last().val == 'a' +} + +[direct_array_access] +fn test_direct_array_access() { + mut a := [11, 22, 33, 44] + assert a[0] == 11 + assert a[2] == 33 + x := a[0] + a[0] = 21 + a[1] += 2 + a[2] = x + 3 + a[3] -= a[1] + assert a == [21, 24, 14, 20] +} + +[direct_array_access] +fn test_direct_array_access_via_ptr() { + mut b := [11, 22, 33, 44] + unsafe { + mut a := &b + assert a[0] == 11 + assert a[2] == 33 + x := a[0] + a[0] = 21 + a[1] += 2 + a[2] = x + 3 + a[3] -= a[1] + assert a == [21, 24, 14, 20] + } +} + +fn test_push_arr_string_free() { + mut lines := ['hi'] + s := 'a' + 'b' + lines << s + // make sure the data in the array is valid after freeing the string + unsafe { s.free() } + // + println(lines) + assert lines.len == 2 + assert lines[0] == 'hi' + assert lines[1] == 'ab' +} + +const ( + grid_size_1 = 2 + grid_size_2 = 3 + grid_size_3 = 4 + cell_value = 123 +) + +fn test_multidimensional_array_initialization_with_consts() { + mut data := [][][]int{len: grid_size_1, init: [][]int{len: grid_size_2, init: []int{len: grid_size_3, init: cell_value}}} + assert data.len == grid_size_1 + assert data[0].len == grid_size_2 + assert data[0][0].len == grid_size_3 + assert data[0][0][0] == cell_value + assert data[1][1][1] == cell_value +} + +fn test_multi_array_prepend() { + mut a := [][]int{} + a.prepend([1, 2, 3]) + assert a == [[1, 2, 3]] + mut b := [][]int{} + b.prepend([[1, 2, 3]]) + assert b == [[1, 2, 3]] +} + +fn test_multi_array_insert() { + mut a := [][]int{} + a.insert(0, [1, 2, 3]) + assert a == [[1, 2, 3]] + mut b := [][]int{} + b.insert(0, [[1, 2, 3]]) + assert b == [[1, 2, 3]] +} + +fn test_multi_array_in() { + a := [[1]] + println([1] in a) + assert [1] in a +} + +fn test_any_type_array_contains() { + a := [true, false] + assert a.contains(true) + assert true in a + assert a.contains(false) + assert false in a + b := [i64(2), 3, 4] + assert b.contains(i64(3)) + assert 5 !in b + c := [[1], [2]] + assert c.contains([1]) + assert [2] in c + assert [3] !in c +} + +struct Person { + name string + nums []int + kv map[string]string +} + +fn test_struct_array_of_multi_type_in() { + ivan := Person{ + name: 'ivan' + nums: [1, 2, 3] + kv: { + 'aaa': '111' + } + } + people := [ + Person{ + name: 'ivan' + nums: [1, 2, 3] + kv: { + 'aaa': '111' + } + }, + Person{ + name: 'bob' + nums: [2] + kv: { + 'bbb': '222' + } + }, + ] + println(ivan in people) + println('TODO: Map eq') + // assert ivan in people +} + +fn test_struct_array_of_multi_type_index() { + ivan := Person{ + name: 'ivan' + nums: [1, 2, 3] + kv: { + 'aaa': '111' + } + } + people := [ + Person{ + name: 'ivan' + nums: [1, 2, 3] + kv: { + 'aaa': '111' + } + }, + Person{ + name: 'bob' + nums: [2] + kv: { + 'bbb': '222' + } + }, + ] + println(people.index(ivan)) + assert people.index(ivan) == 0 +} + +struct Coord { + x int + y int + z int +} + +fn test_array_struct_contains() { + mut coords := []Coord{} + coord_1 := Coord{ + x: 1 + y: 2 + z: -1 + } + coords << coord_1 + exists := coord_1 in coords + not_exists := coord_1 !in coords + println('`exists`: $exists and `not exists`: $not_exists') + assert exists == true + assert not_exists == false +} + +fn test_array_struct_ref_contains() { + mut coords := []&Coord{} + coord_1 := &Coord{ + x: 1 + y: 2 + z: -1 + } + coords << coord_1 + exists := coord_1 in coords + println(exists) + assert exists == true +} + +fn test_array_struct_ref_index() { + mut coords := []&Coord{} + coord_1 := &Coord{ + x: 1 + y: 2 + z: -1 + } + coords << coord_1 + println(coords.index(coord_1)) + assert coords.index(coord_1) == 0 +} + +fn test_array_of_array_append() { + mut x := [][]int{len: 4} + println(x) // OK + x[2] << 123 // RTE + println(x) + assert '$x' == '[[], [], [123], []]' +} + +fn test_array_of_map_insert() { + mut x := []map[string]int{len: 4} + println(x) // OK + x[2]['123'] = 123 // RTE + println(x) + println('TODO: Map eq') + // assert '$x' == "[{}, {}, {'123': 123}, {}]" +} + +fn test_multi_fixed_array_init() { + a := [3][3]int{} + assert '$a' == '[[0, 0, 0], [0, 0, 0], [0, 0, 0]]' +} + +struct Numbers { + odds []int + evens []int +} + +fn test_array_of_multi_filter() { + arr := [1, 2, 3, 4, 5] + nums := Numbers{ + odds: arr.filter(it % 2 == 1) + evens: arr.filter(it % 2 == 0) + } + println(nums) + assert nums.odds == [1, 3, 5] + assert nums.evens == [2, 4] +} + +fn test_array_of_multi_map() { + arr := [1, 3, 5] + nums := Numbers{ + odds: arr.map(it + 2) + evens: arr.map(it * 2) + } + println(nums) + assert nums.odds == [3, 5, 7] + assert nums.evens == [2, 6, 10] +} + +fn test_multi_fixed_array_with_default_init() { + a := [3][3]int{init: [3]int{init: 10}} + println(a) + assert a == [[10, 10, 10]!, [10, 10, 10]!, [10, 10, 10]!]! +} + +struct Abc { +mut: + x i64 + y i64 + z i64 +} + +fn test_clone_of_same_elem_size_array() { + mut arr := []Abc{} + arr << Abc{1, 2, 3} + arr << Abc{2, 3, 4} + arr2 := arr.clone() + println(arr2) + assert arr2 == [Abc{1, 2, 3}, Abc{2, 3, 4}] +} + +pub fn example(mut arr []T) []T { + return arr.clone() +} + +fn test_generic_mutable_arrays() { + mut arr := [1, 2, 3] + assert example(mut arr) == [1, 2, 3] +} diff --git a/vlib/v/builder/compile.v b/vlib/v/builder/compile.v index 4f7f7f8fe0..67cd937af0 100644 --- a/vlib/v/builder/compile.v +++ b/vlib/v/builder/compile.v @@ -121,7 +121,7 @@ fn (mut b Builder) run_compiled_executable_and_exit() { mut exefile := os.real_path(b.pref.out_name) mut cmd := '"$exefile"' if b.pref.backend.is_js() { - exefile = os.real_path('${b.pref.out_name}.js') + exefile = os.real_path('${b.pref.out_name}.js').replace('.js.js', '.js') cmd = 'node "$exefile"' } for arg in b.pref.run_args { diff --git a/vlib/v/gen/js/array.v b/vlib/v/gen/js/array.v index 0c4d214aeb..ac9f96afe7 100644 --- a/vlib/v/gen/js/array.v +++ b/vlib/v/gen/js/array.v @@ -180,20 +180,20 @@ fn (mut g JsGen) gen_array_contains_method(left_type ast.Type) string { fn_builder.writeln('function ${fn_name}(a,v) {') fn_builder.writeln('\tfor (let i = 0; i < a.len; ++i) {') if elem_sym.kind == .string { - fn_builder.writeln('\t\tif (a.arr.arr[i].str == v.str) {') + fn_builder.writeln('\t\tif (a.arr.get(new int(i)).str == v.str) {') } else if elem_sym.kind == .array && left_info.elem_type.nr_muls() == 0 { ptr_typ := g.gen_array_equality_fn(left_info.elem_type) - fn_builder.writeln('\t\tif (${ptr_typ}_arr_eq(a.arr.arr[i],v)) {') + fn_builder.writeln('\t\tif (${ptr_typ}_arr_eq(a.arr.get(new int(i)),v).val) {') } else if elem_sym.kind == .function { - fn_builder.writeln('\t\tif (a.arr.arr[i] == v) {') + fn_builder.writeln('\t\tif (a.arr.get(new int(i)) == v) {') } else if elem_sym.kind == .map && left_info.elem_type.nr_muls() == 0 { ptr_typ := g.gen_map_equality_fn(left_info.elem_type) - fn_builder.writeln('\t\tif (${ptr_typ}_map_eq(a.arr.arr[i],v)) {') + fn_builder.writeln('\t\tif (${ptr_typ}_map_eq(a.arr.get(new int(i)),v).val) {') } else if elem_sym.kind == .struct_ && left_info.elem_type.nr_muls() == 0 { ptr_typ := g.gen_struct_equality_fn(left_info.elem_type) - fn_builder.writeln('\t\tif (${ptr_typ}_struct_eq(a.arr.arr[i],v)) {') + fn_builder.writeln('\t\tif (${ptr_typ}_struct_eq(a.arr.get(new int(i)),v).val) {') } else { - fn_builder.writeln('\t\tif (vEq(a.arr.arr[i],v)) {') + fn_builder.writeln('\t\tif (vEq(a.arr.get(new int(i)),v)) {') } fn_builder.writeln('\t\t\treturn new bool(true);') fn_builder.writeln('\t\t}') diff --git a/vlib/v/gen/js/auto_eq_methods.v b/vlib/v/gen/js/auto_eq_methods.v index 039cda4988..a0723afcda 100644 --- a/vlib/v/gen/js/auto_eq_methods.v +++ b/vlib/v/gen/js/auto_eq_methods.v @@ -237,22 +237,22 @@ fn (mut g JsGen) gen_fixed_array_equality_fn(left_type ast.Type) string { fn_builder.writeln('\t\tif (a.arr.get(new int(i)).str != b.arr.get(new int(i)).str) {') } else if elem.sym.kind == .sum_type && !elem.typ.is_ptr() { eq_fn := g.gen_sumtype_equality_fn(elem.typ) - fn_builder.writeln('\t\tif (!${eq_fn}_sumtype_eq(a.arr.get(new int(i)), b.arr.get(new int(i)))) {') + fn_builder.writeln('\t\tif (!${eq_fn}_sumtype_eq(a.arr.get(new int(i)), b.arr.get(new int(i))).val) {') } else if elem.sym.kind == .struct_ && !elem.typ.is_ptr() { eq_fn := g.gen_struct_equality_fn(elem.typ) - fn_builder.writeln('\t\tif (!${eq_fn}_struct_eq(a.arr.get(new int(i)), b.arr.get(new int(i)))) {') + fn_builder.writeln('\t\tif (!${eq_fn}_struct_eq(a.arr.get(new int(i)), b.arr.get(new int(i))).val) {') } else if elem.sym.kind == .array && !elem.typ.is_ptr() { eq_fn := g.gen_array_equality_fn(elem.typ) - fn_builder.writeln('\t\tif (!${eq_fn}_arr_eq(a.arr.get(new int(i)), b.arr.get(new int(i)))) {') + fn_builder.writeln('\t\tif (!${eq_fn}_arr_eq(a.arr.get(new int(i)), b.arr.get(new int(i))).val) {') } else if elem.sym.kind == .array_fixed && !elem.typ.is_ptr() { eq_fn := g.gen_fixed_array_equality_fn(elem.typ) - fn_builder.writeln('\t\tif (!${eq_fn}_arr_eq(a.arr.get(new int(i)), b.arr.get(new int(i)))) {') + fn_builder.writeln('\t\tif (!${eq_fn}_arr_eq(a.arr.get(new int(i)), b.arr.get(new int(i))).val) {') } else if elem.sym.kind == .map && !elem.typ.is_ptr() { eq_fn := g.gen_map_equality_fn(elem.typ) - fn_builder.writeln('\t\tif (!${eq_fn}_map_eq(a.arr.get(new int(i)), b.arr.get(new int(i)))) {') + fn_builder.writeln('\t\tif (!${eq_fn}_map_eq(a.arr.get(new int(i)), b.arr.get(new int(i))).val) {') } else if elem.sym.kind == .alias && !elem.typ.is_ptr() { eq_fn := g.gen_alias_equality_fn(elem.typ) - fn_builder.writeln('\t\tif (!${eq_fn}_alias_eq(a.arr.get(new int(i)), b.arr.get(new int(i)))) {') + fn_builder.writeln('\t\tif (!${eq_fn}_alias_eq(a.arr.get(new int(i)), b.arr.get(new int(i))).val) {') } else if elem.sym.kind == .function { fn_builder.writeln('\t\tif (a.arr.get(new int(i)) != b.arr.get(new int(i))) {') } else { diff --git a/vlib/v/gen/js/auto_str_methods.v b/vlib/v/gen/js/auto_str_methods.v index 18e881f818..2c7cedccc6 100644 --- a/vlib/v/gen/js/auto_str_methods.v +++ b/vlib/v/gen/js/auto_str_methods.v @@ -6,6 +6,102 @@ import v.ast import v.util import strings +struct StrType { + styp string +mut: + typ ast.Type +} + +fn (mut g JsGen) get_str_fn(typ ast.Type) string { + mut unwrapped := g.unwrap_generic(typ).set_nr_muls(0).clear_flag(.variadic) + if g.pref.nofloat { + if typ == ast.f32_type { + unwrapped = ast.u32_type + } else if typ == ast.f64_type { + unwrapped = ast.u64_type + } + } + if typ.has_flag(.optional) { + unwrapped.set_flag(.optional) + } + styp := g.typ(unwrapped) + mut sym := g.table.get_type_symbol(unwrapped) + mut str_fn_name := styp_to_str_fn_name(styp) + if mut sym.info is ast.Alias { + if sym.info.is_import { + sym = g.table.get_type_symbol(sym.info.parent_type) + str_fn_name = styp_to_str_fn_name(sym.name) + } + } + g.str_types << StrType{ + typ: unwrapped + styp: styp + } + return str_fn_name +} + +fn (mut g JsGen) final_gen_str(typ StrType) { + if typ in g.generated_str_fns { + return + } + g.generated_str_fns << typ + sym := g.table.get_type_symbol(typ.typ) + if sym.has_method('str') && !typ.typ.has_flag(.optional) { + return + } + styp := typ.styp + str_fn_name := styp_to_str_fn_name(styp) + if typ.typ.has_flag(.optional) { + g.gen_str_for_option(typ.typ, styp, str_fn_name) + return + } + match mut sym.info { + ast.Alias { + if sym.info.is_import { + g.gen_str_default(sym, styp, str_fn_name) + } else { + g.gen_str_for_alias(sym.info, styp, str_fn_name) + } + } + ast.Array { + g.gen_str_for_array(sym.info, styp, str_fn_name) + } + ast.ArrayFixed { + g.gen_str_for_array_fixed(sym.info, styp, str_fn_name) + } + ast.Enum { + g.gen_str_for_enum(sym.info, styp, str_fn_name) + } + ast.FnType { + g.gen_str_for_fn_type(sym.info, styp, str_fn_name) + } + ast.Struct { + g.gen_str_for_struct(sym.info, styp, str_fn_name) + } + ast.Map { + g.gen_str_for_map(sym.info, styp, str_fn_name) + } + ast.MultiReturn { + g.gen_str_for_multi_return(sym.info, styp, str_fn_name) + } + ast.SumType { + g.gen_str_for_union_sum_type(sym.info, styp, str_fn_name) + } + ast.Interface { + g.gen_str_for_interface(sym.info, styp, str_fn_name) + } + ast.Chan { + g.gen_str_for_chan(sym.info, styp, str_fn_name) + } + ast.Thread { + g.gen_str_for_thread(sym.info, styp, str_fn_name) + } + else { + verror("could not generate string method $str_fn_name for type '$styp'") + } + } +} + pub enum StrIntpType { si_no_str = 0 // no parameter to print only fix string si_c @@ -116,85 +212,11 @@ fn (mut g JsGen) gen_str_default(sym ast.TypeSymbol, styp string, str_fn_name st g.definitions.writeln('}') } -fn (mut g JsGen) gen_str_for_type(typ ast.Type) string { - styp := g.typ(typ).replace('*', '') - mut sym := g.table.get_type_symbol(g.unwrap_generic(typ)) - mut str_fn_name := styp_to_str_fn_name(styp) - if mut sym.info is ast.Alias { - if sym.info.is_import { - sym = g.table.get_type_symbol(sym.info.parent_type) - str_fn_name = styp_to_str_fn_name(sym.name) - } - } - sym_has_str_method, str_method_expects_ptr, str_nr_args := sym.str_method_info() - already_generated_key := '$styp:$str_fn_name' - if !sym_has_str_method && already_generated_key !in g.str_types && !typ.has_flag(.optional) { - $if debugautostr ? { - eprintln('> gen_str_for_type: |typ: ${typ:5}, ${sym.name:20}|has_str: ${sym_has_str_method:5}|expects_ptr: ${str_method_expects_ptr:5}|nr_args: ${str_nr_args:1}|fn_name: ${str_fn_name:20}') - } - g.str_types << already_generated_key - match mut sym.info { - ast.Alias { - if sym.info.is_import { - g.gen_str_default(sym, styp, str_fn_name) - } else { - g.gen_str_for_alias(sym.info, styp, str_fn_name) - } - } - ast.Array { - g.gen_str_for_array(sym.info, styp, str_fn_name) - } - ast.ArrayFixed { - g.gen_str_for_array_fixed(sym.info, styp, str_fn_name) - } - ast.Enum { - g.gen_str_for_enum(sym.info, styp, str_fn_name) - } - ast.FnType { - g.gen_str_for_fn_type(sym.info, styp, str_fn_name) - } - ast.Struct { - g.gen_str_for_struct(sym.info, styp, str_fn_name) - } - ast.Map { - g.gen_str_for_map(sym.info, styp, str_fn_name) - } - ast.MultiReturn { - g.gen_str_for_multi_return(sym.info, styp, str_fn_name) - } - ast.SumType { - g.gen_str_for_union_sum_type(sym.info, styp, str_fn_name) - } - ast.Interface { - g.gen_str_for_interface(sym.info, styp, str_fn_name) - } - ast.Chan { - g.gen_str_for_chan(sym.info, styp, str_fn_name) - } - ast.Thread { - g.gen_str_for_thread(sym.info, styp, str_fn_name) - } - else { - panic("could not generate string method $str_fn_name for type '$styp'") - } - } - } - if typ.has_flag(.optional) { - option_already_generated_key := 'option_$already_generated_key' - if option_already_generated_key !in g.str_types { - g.gen_str_for_option(typ, styp, str_fn_name) - g.str_types << option_already_generated_key - } - return str_fn_name - } - return str_fn_name -} - fn (mut g JsGen) gen_str_for_option(typ ast.Type, styp string, str_fn_name string) { parent_type := typ.clear_flag(.optional) sym := g.table.get_type_symbol(parent_type) sym_has_str_method, _, _ := sym.str_method_info() - parent_str_fn_name := g.gen_str_for_type(parent_type) + parent_str_fn_name := g.get_str_fn(parent_type) g.definitions.writeln('function ${str_fn_name}(it) { return indent_${str_fn_name}(it, 0); }') g.definitions.writeln('function indent_${str_fn_name}(it, indent_count) {') @@ -219,7 +241,7 @@ fn (mut g JsGen) gen_str_for_option(typ ast.Type, styp string, str_fn_name strin } fn (mut g JsGen) gen_str_for_alias(info ast.Alias, styp string, str_fn_name string) { - parent_str_fn_name := g.gen_str_for_type(info.parent_type) + parent_str_fn_name := g.get_str_fn(info.parent_type) g.definitions.writeln('function ${str_fn_name}(it) { return indent_${str_fn_name}(it, 0); }') g.definitions.writeln('function indent_${str_fn_name}(it, indent_count) {') @@ -239,7 +261,7 @@ fn (mut g JsGen) gen_str_for_multi_return(info ast.MultiReturn, styp string, str sym := g.table.get_type_symbol(typ) is_arg_ptr := typ.is_ptr() sym_has_str_method, str_method_expects_ptr, _ := sym.str_method_info() - arg_str_fn_name := g.gen_str_for_type(typ) + arg_str_fn_name := g.get_str_fn(typ) if should_use_indent_func(sym.kind) && !sym_has_str_method { fn_builder.writeln('\tstrings__Builder_write_string(sb, ${arg_str_fn_name}(a.arg$i));') @@ -323,7 +345,7 @@ fn (mut g JsGen) gen_str_for_interface(info ast.Interface, styp string, str_fn_n fn_builder.writeln('function indent_${str_fn_name}(x,indent_count) { /* gen_str_for_interface */') for typ in info.types { subtype := g.table.get_type_symbol(typ) - mut func_name := g.gen_str_for_type(typ) + mut func_name := g.get_str_fn(typ) sym_has_str_method, _, _ := subtype.str_method_info() if should_use_indent_func(subtype.kind) && !sym_has_str_method { func_name = 'indent_$func_name' @@ -431,7 +453,7 @@ fn (mut g JsGen) gen_str_for_array(info ast.Array, styp string, str_fn_name stri } is_elem_ptr := typ.is_ptr() sym_has_str_method, str_method_expects_ptr, _ := sym.str_method_info() - mut elem_str_fn_name := g.gen_str_for_type(typ) + mut elem_str_fn_name := g.get_str_fn(typ) if sym.kind == .byte { elem_str_fn_name = elem_str_fn_name + '_escaped' } @@ -490,7 +512,7 @@ fn (mut g JsGen) gen_str_for_array_fixed(info ast.ArrayFixed, styp string, str_f } is_elem_ptr := typ.is_ptr() sym_has_str_method, str_method_expects_ptr, _ := sym.str_method_info() - elem_str_fn_name := g.gen_str_for_type(typ) + elem_str_fn_name := g.get_str_fn(typ) g.definitions.writeln('function ${str_fn_name}(a) { return indent_${str_fn_name}(a, 0);}') @@ -545,7 +567,7 @@ fn (mut g JsGen) gen_str_for_map(info ast.Map, styp string, str_fn_name string) key_styp := g.typ(key_typ) key_str_fn_name := key_styp.replace('*', '') + '_str' if !key_sym.has_method('str') { - g.gen_str_for_type(key_typ) + g.get_str_fn(key_typ) } mut val_typ := info.value_type @@ -557,7 +579,7 @@ fn (mut g JsGen) gen_str_for_map(info ast.Map, styp string, str_fn_name string) val_styp := g.typ(val_typ) elem_str_fn_name := val_styp.replace('*', '') + '_str' if !val_sym.has_method('str') { - g.gen_str_for_type(val_typ) + g.get_str_fn(val_typ) } g.definitions.writeln('function ${str_fn_name}(m) { return indent_${str_fn_name}(m, 0);}') @@ -701,7 +723,7 @@ fn (mut g JsGen) gen_str_for_struct(info ast.Struct, styp string, str_fn_name st field_styp_fn_name := if has_custom_str { '${field_styp}_str' } else { - g.gen_str_for_type(field.typ) + g.get_str_fn(field.typ) } mut func := struct_auto_str_func1(mut g, sym, field.typ, field_styp_fn_name, field.name) diff --git a/vlib/v/gen/js/builtin_types.v b/vlib/v/gen/js/builtin_types.v index 19687f25c4..4e0e8d6f39 100644 --- a/vlib/v/gen/js/builtin_types.v +++ b/vlib/v/gen/js/builtin_types.v @@ -406,7 +406,7 @@ fn (mut g JsGen) gen_builtin_type_defs() { typ_name: typ_name val_name: 'arr' default_value: 'new array_buffer({})' - constructor: 'this.arr = arr\nif (arr.index_start.val != 0) { v_makeSlice(this); } ' + constructor: 'this.arr = arr\nif (arr.index_start.val != 0 || arr.has_slice.val) { v_makeSlice(this); } ' value_of: 'this' to_string: 'JSON.stringify(this.arr.map(it => it.valueOf()))' eq: 'new bool(vEq(self, other))' diff --git a/vlib/v/gen/js/fn.v b/vlib/v/gen/js/fn.v index e4bf0e5f03..6e68b881a3 100644 --- a/vlib/v/gen/js/fn.v +++ b/vlib/v/gen/js/fn.v @@ -96,6 +96,10 @@ fn (mut g JsGen) js_method_call(node ast.CallExpr) { fn (mut g JsGen) method_call(node ast.CallExpr) { g.call_stack << node it := node + if it.name == 'str' { + g.gen_expr_to_string(node.left, node.left_type) + return + } call_return_is_optional := it.return_type.has_flag(.optional) if call_return_is_optional { g.writeln('(function(){') @@ -104,6 +108,13 @@ fn (mut g JsGen) method_call(node ast.CallExpr) { g.inc_indent() g.write('return builtin.unwrap(') } + if node.name == 'str' { + mut rec_type := node.receiver_type + if rec_type.has_flag(.shared_f) { + rec_type = rec_type.clear_flag(.shared_f).set_nr_muls(0) + } + g.get_str_fn(rec_type) + } mut unwrapped_rec_type := node.receiver_type if g.table.cur_fn.generic_names.len > 0 { unwrapped_rec_type = g.unwrap_generic(node.receiver_type) diff --git a/vlib/v/gen/js/infix.v b/vlib/v/gen/js/infix.v index ec53b6253c..010c89ca9d 100644 --- a/vlib/v/gen/js/infix.v +++ b/vlib/v/gen/js/infix.v @@ -89,6 +89,9 @@ fn (mut g JsGen) infix_expr_eq_op(node ast.InfixExpr) { g.expr(node.right) g.gen_deref_ptr(node.right_type) g.write(')') + if node.op == .ne { + g.write('.valueOf()') + } } else if left.typ.idx() == right.typ.idx() && left.sym.kind in [.array, .array_fixed, .alias, .map, .struct_, .sum_type] { match left.sym.kind { @@ -104,6 +107,9 @@ fn (mut g JsGen) infix_expr_eq_op(node ast.InfixExpr) { g.expr(node.right) g.gen_deref_ptr(node.right_type) g.write(')') + if node.op == .ne { + g.write('.valueOf()') + } } .array { ptr_typ := g.gen_array_equality_fn(left.unaliased.clear_flag(.shared_f)) @@ -117,6 +123,9 @@ fn (mut g JsGen) infix_expr_eq_op(node ast.InfixExpr) { g.expr(node.right) g.gen_deref_ptr(node.right_type) g.write(')') + if node.op == .ne { + g.write('.valueOf()') + } } .array_fixed { ptr_typ := g.gen_fixed_array_equality_fn(left.unaliased) @@ -130,6 +139,9 @@ fn (mut g JsGen) infix_expr_eq_op(node ast.InfixExpr) { g.expr(node.right) g.gen_deref_ptr(node.right_type) g.write(')') + if node.op == .ne { + g.write('.valueOf()') + } } .map { ptr_typ := g.gen_map_equality_fn(left.unaliased) @@ -143,6 +155,9 @@ fn (mut g JsGen) infix_expr_eq_op(node ast.InfixExpr) { g.expr(node.right) g.gen_deref_ptr(node.right_type) g.write(')') + if node.op == .ne { + g.write('.valueOf()') + } } .struct_ { ptr_typ := g.gen_struct_equality_fn(left.unaliased) @@ -156,6 +171,9 @@ fn (mut g JsGen) infix_expr_eq_op(node ast.InfixExpr) { g.expr(node.right) g.gen_deref_ptr(node.right_type) g.write(')') + if node.op == .ne { + g.write('.valueOf()') + } } .sum_type { ptr_typ := g.gen_sumtype_equality_fn(left.unaliased) @@ -170,6 +188,9 @@ fn (mut g JsGen) infix_expr_eq_op(node ast.InfixExpr) { g.expr(node.right) g.gen_deref_ptr(node.right_type) g.write(')') + if node.op == .ne { + g.write('.valueOf()') + } } else {} } @@ -231,22 +252,22 @@ fn (mut g JsGen) infix_expr_left_shift_op(node ast.InfixExpr) { if left.unaliased_sym.kind == .array { // arr << val array_info := left.unaliased_sym.info as ast.Array - g.write('Array.prototype.push.call(') + g.write('array_push(') //&& array_info.elem_type != g.unwrap_generic(node.right_type) if right.unaliased_sym.kind == .array && array_info.elem_type != right.typ { g.expr(node.left) g.gen_deref_ptr(left.typ) - g.write('.arr.arr,...') + g.write(',') g.expr(node.right) g.gen_deref_ptr(right.typ) g.write('.arr.arr') - g.write(')') + g.write(',true)') } else { g.expr(node.left) g.gen_deref_ptr(left.typ) - g.write('.arr.arr,') + g.write(',') g.expr(node.right) - g.write(')') + g.write(',false)') } } else { g.gen_plain_infix_expr(node) diff --git a/vlib/v/gen/js/js.v b/vlib/v/gen/js/js.v index cb19f660a6..ac1cb511fc 100644 --- a/vlib/v/gen/js/js.v +++ b/vlib/v/gen/js/js.v @@ -64,14 +64,15 @@ mut: stmt_start_pos int defer_stmts []ast.DeferStmt fn_decl &ast.FnDecl // pointer to the FnDecl we are currently inside otherwise 0 - str_types []string // types that need automatic str() generation - array_fn_definitions []string // array equality functions that have been defined - map_fn_definitions []string // map equality functions that have been defined - struct_fn_definitions []string // struct equality functions that have been defined - sumtype_fn_definitions []string // sumtype equality functions that have been defined - alias_fn_definitions []string // alias equality functions that have been defined - auto_fn_definitions []string // auto generated functions defination list - anon_fn_definitions []string // anon generated functions defination list + generated_str_fns []StrType + str_types []StrType // types that need automatic str() generation + array_fn_definitions []string // array equality functions that have been defined + map_fn_definitions []string // map equality functions that have been defined + struct_fn_definitions []string // struct equality functions that have been defined + sumtype_fn_definitions []string // sumtype equality functions that have been defined + alias_fn_definitions []string // alias equality functions that have been defined + auto_fn_definitions []string // auto generated functions defination list + anon_fn_definitions []string // anon generated functions defination list method_fn_decls map[string][]ast.FnDecl builtin_fns []string // Functions defined in `builtin` empty_line bool @@ -156,6 +157,9 @@ pub fn gen(files []&ast.File, table &ast.Table, pref &pref.Preferences) string { // store the current namespace g.escape_namespace() } + for i := 0; i < g.str_types.len; i++ { + g.final_gen_str(g.str_types[i]) + } if g.pref.is_test { g.gen_js_main_for_tests() } @@ -1031,10 +1035,10 @@ fn (mut g JsGen) gen_assert_single_expr(expr ast.Expr, typ ast.Type) { g.write('$sym.name') } else { - g.writeln(unknown_value) + g.write(unknown_value) } } - g.write(' /* typeof: ' + expr.type_name() + ' type: ' + typ.str() + ' */ ') + // g.writeln(' /* typeof: ' + expr.type_name() + ' type: ' + typ.str() + ' */ ') } // TODO @@ -1150,6 +1154,7 @@ fn (mut g JsGen) gen_assign_stmt(stmt ast.AssignStmt, semicolon bool) { is_ptr = true g.write('.val') } + if g.inside_map_set && op == .assign { g.inside_map_set = false g.write(', ') @@ -1160,6 +1165,7 @@ fn (mut g JsGen) gen_assign_stmt(stmt ast.AssignStmt, semicolon bool) { g.write(')') } else { if is_assign && array_set { + g.write('new ${styp}(') g.expr(left) if l_sym.kind == .string { g.write('.str') @@ -1272,6 +1278,9 @@ fn (mut g JsGen) gen_assign_stmt(stmt ast.AssignStmt, semicolon bool) { g.write(')') g.cast_stack.delete_last() } + if is_assign && array_set { + g.write(')') + } } if array_set { g.write(')') @@ -1741,7 +1750,13 @@ fn (mut g JsGen) gen_array_init_expr(it ast.ArrayInit) { g.expr(it.exprs[0]) g.write(')') } else { - c := g.gen_array_init_values(it.exprs) + styp := g.typ(it.elem_type) + + c := if styp in js.v_types { + g.gen_array_init_values_prim(it.exprs, styp) + } else { + g.gen_array_init_values(it.exprs) + } g.write(', len: new int($c), cap: new int($c)') } g.dec_indent() @@ -1762,6 +1777,22 @@ fn (mut g JsGen) gen_array_init_values(exprs []ast.Expr) int { return c } +fn (mut g JsGen) gen_array_init_values_prim(exprs []ast.Expr, typ string) int { + g.write('[') + mut c := 0 + for i, expr in exprs { + g.write('new ${typ}(') + g.expr(expr) + g.write(')') + if i < exprs.len - 1 { + g.write(', ') + } + c++ + } + g.write(']') + return c +} + fn (mut g JsGen) gen_ident(node ast.Ident) { mut name := g.js_name(node.name) if node.kind == .blank_ident || name in ['', '_'] { @@ -2258,10 +2289,11 @@ fn (mut g JsGen) gen_index_expr(expr ast.IndexExpr) { g.write('.valueOf()') } g.write(',') + if expr.index.has_low { g.expr(expr.index.low) } else { - g.write('0') + g.write('new int(0)') } g.write(', ') if expr.index.has_high { @@ -2407,7 +2439,7 @@ fn (mut g JsGen) gen_infix_expr(it ast.InfixExpr) { g.write(')') } } else if l_sym.kind == .array && it.op == .left_shift { // arr << 1 - g.write('Array.prototype.push.call(') + g.write('array_push(') g.expr(it.left) mut ltyp := it.left_type for ltyp.is_ptr() { diff --git a/vlib/v/gen/js/str.v b/vlib/v/gen/js/str.v index af4bac4450..3c0e3f80f9 100644 --- a/vlib/v/gen/js/str.v +++ b/vlib/v/gen/js/str.v @@ -2,6 +2,7 @@ module js import v.ast +/* fn (mut g JsGen) gen_expr_to_string(expr ast.Expr, etype ast.Type) { is_shared := etype.has_flag(.shared_f) mut typ := etype @@ -72,4 +73,75 @@ fn (mut g JsGen) gen_expr_to_string(expr ast.Expr, etype ast.Type) { } g.write(')') } +}*/ + +fn (mut g JsGen) gen_expr_to_string(expr ast.Expr, etype ast.Type) { + is_shared := etype.has_flag(.shared_f) + mut typ := etype + if is_shared { + typ = typ.clear_flag(.shared_f).set_nr_muls(0) + } + mut sym := g.table.get_type_symbol(typ) + // when type is alias, print the aliased value + if mut sym.info is ast.Alias { + parent_sym := g.table.get_type_symbol(sym.info.parent_type) + if parent_sym.has_method('str') { + typ = sym.info.parent_type + sym = parent_sym + } + } + sym_has_str_method, str_method_expects_ptr, _ := sym.str_method_info() + if typ.has_flag(.variadic) { + str_fn_name := g.get_str_fn(typ) + g.write('${str_fn_name}(') + g.expr(expr) + g.write(')') + } else if typ == ast.string_type { + g.expr(expr) + } else if typ == ast.bool_type { + g.expr(expr) + g.write('.valueOf() ? new string("true") : new string("false")') + } else if sym.kind == .none_ { + g.write('new string("")') + } else if sym.kind == .enum_ { + if expr !is ast.EnumVal { + str_fn_name := g.get_str_fn(typ) + g.write('${str_fn_name}(') + g.expr(expr) + g.write(')') + } else { + g.write('new string("') + g.expr(expr) + g.write('")') + } + } else if sym_has_str_method + || sym.kind in [.array, .array_fixed, .map, .struct_, .multi_return, .sum_type, .interface_] { + is_ptr := typ.is_ptr() + is_var_mut := expr.is_auto_deref_var() + str_fn_name := g.get_str_fn(typ) + g.write('${str_fn_name}(') + if str_method_expects_ptr && !is_ptr { + g.write('new \$ref(') + } + + g.expr(expr) + if (!str_method_expects_ptr && is_ptr && !is_shared) || is_var_mut { + g.write('.val') + } + g.write(')') + if str_method_expects_ptr && !is_ptr { + g.write(')') + } + } else { + str_fn_name := g.get_str_fn(typ) + g.write('${str_fn_name}(') + + if sym.kind != .function { + g.expr(expr) + } + if expr.is_auto_deref_var() { + g.write('.val') + } + g.write(')') + } } diff --git a/vlib/v/gen/js/tests/testdata/array.out b/vlib/v/gen/js/tests/testdata/array.out deleted file mode 100644 index 0359ecd32d..0000000000 --- a/vlib/v/gen/js/tests/testdata/array.out +++ /dev/null @@ -1,302 +0,0 @@ -3 -1 -2 -4 -255 -256 -2 -4 -131 -4 -1 -2 -3 -5 -4 -4 -[1, 5, 2, 3, 4] -5 -4 -5 -[1, 5, 2, 3, 4] -[5, 2, 3, 4] -4 -[5, 3, 4] -3 -[5, 3] -2 -[2.5, 3.25, 4.5, 5.75] -true -true -true -false -true -true -true -true -true -true -true -1 -2 -3 -10000 -234 -0 -1 -0 -1 -3 -[1, 3] -3 -2 -3 -4 -1 -4 -5 -2 -5 -0 -1 -1.1 -[1, 2, 3, 4] -[1, 5, 6, 2, 3, 4] -0 -1 -1 -0 -1 -1.1 -[1, 2, 3, 4] -[5, 6, 1, 2, 3, 4] -5 -true -1.1 -1.1 -1.1 --123 --123 --123 -123 -123 -123 -1.1 -1.1 -1.1 -1 -2 -1 -2 -1 -abc -1 -abc -0 -abc -2 -3 -2 -3 -1 -2 -1 -2 -2 -1 -4 -6 -1 -4 -6 -[] -0 -[0, 0, 0, 0] -[0, 7, 0, 0] -0 -[2, 4, 6, 8, 10, 12, 14, 16, 18, 20] -[2, 4, 6, 8, 10, 12, 14, 16, 18, 20] -[2, 4, 6, 8, 10] -2 -[1, 2] -0 -1 --1 -0 -3 --1 -0 -2 --1 -1 -2 --1 -2 -3 -1 -3 -6 -true -true -true -false -false -false -false -true -true -15 -20 -14 --6 --7 -[2, 4, 6] -[is, awesome] -[2, 3, 4, 6, 8, 9, 10] -[4, 5, 6] -[5, 10] -[2, 4] -[2, 4] -[1, 2, 3, 4, 5, 6] -[v, is, awesome] -[0, 0, 0, 0, 0, 0] -0 -[10, 20, 30, 40, 50, 60] -[1, 4, 9, 16, 25, 36] -[1, 2, 3, 4, 5, 6] -[false, true, false, true, false, true] -[V, IS, AWESOME] -[false, false, true] -[true, true, false] -[7, 7, 7] -[1, 4, 9, 16, 25, 36] -[3, 4, 5, 6, 7, 8] -[3, 9, 4, 6, 12, 7] -[] -[true, true, true, true, true, true] -[1a, 2a, 3a, 4a, 5a, 6a] -[2, 3, 4, 5, 6, 7] -[2, 3, 8] -[1v, 2is, 3awesome] -[1, 4, 9, 16, 25, 36] -[1, 25, 100] -[1, 2, 3, 4, 5, 6] -[v, is, awesome] -[2, 3, 4] -[2, 3, 4] -[3, 4, 5] -[2, 3, 4] -[1, 2, 3] -[1, 2, 3] -[[1, 2, 3], [4, 5, 6]] -false -true -true -true -true -false -true -false -true -false -true -false -true -false -true -false -true -false -true -false -true -false -true -false -true -false -true -false -[1, 3, 5, hi] -[-3, 7, 42, 67, 108] -0 -1 -79 -[0, 1, 15, 27, 38, 50, 79] -[0, 1, 15, 27, 38, 50, 79] -2 -[14, 2, 3] -test b -[true, false, true] -1,1 -2,2 -3,3 -4,4 -1,1 -2,2 -3,3 -4,4 -{ val: 0 } -6 -[2, 0, 2, 2] -[[1, 0, 0], [0, 0, 0]] -[[1, 0, 0], [1, 0, 0]] -[abc] -[0, 0, 0, 0] -[2, 2] -[1, 2, 3, 4] -[4, 3, 2, 1] -[c, b, a] -[[5, 6], [3, 4], [1, 2]] -5,5 -4 -1 -xyz -def -abc -3 -1 -abc -a -3 -4 -def -a -11 -33 -[21, 24, 14, 20] -2 -3 -4 -123 -123 -[[1, 2, 3]] -[[1, 2, 3]] -[[1, 2, 3]] -[[1, 2, 3]] -true -true -true -true -true -false -false -true -true -false -true -0 -`exists`: true and `not exists`: false -[[], [], [], []] -[[], [], [123], []] -[{}, {}, {}, {}] -[{}, {}, {123: 123}, {}] -Numbers{ - odds: [1, 3, 5] - evens: [2, 4] -} -Numbers{ - odds: [3, 5, 7] - evens: [2, 6, 10] -} -[[10, 10, 10], [10, 10, 10], [10, 10, 10]] diff --git a/vlib/v/gen/js/tests/testdata/array.v b/vlib/v/gen/js/tests/testdata/array.v deleted file mode 100644 index 9af1eaef0e..0000000000 --- a/vlib/v/gen/js/tests/testdata/array.v +++ /dev/null @@ -1,1187 +0,0 @@ -struct Chunk { - val string -} - -struct Kkk { - q []Chunk -} - -const ( - c_n = 5 -) - -struct Coord { - x int - y int - z int -} - -struct Numbers { - odds []int - evens []int -} - -struct Person { - name string - nums []int - kv map[string]string -} - -// test array add in function with mut argument -fn add_nums(mut arr []int) { - arr << 4 -} - -const ( - grid_size_1 = 2 - grid_size_2 = 3 - grid_size_3 = 4 - cell_value = 123 -) - -struct User { - age int - name string -} - -struct Foo { -mut: - bar []int -} - -fn array_in_mut(mut a []int) { - if 1 in a { - a[0] = 2 - } -} - -fn mut_arr_with_eq_in_fn(mut a []int) { - if a == [1, 2, 3, 4] { - a[0] = 0 - } - if [0, 2, 3, 4] == a { - a[1] = 0 - } - if !(a != [0, 0, 3, 4]) { - a[2] = 0 - } - if !([0, 0, 0, 4] != a) { - a[3] = 0 - } -} - -fn map_test_helper_1(i int) int { - return i * i -} - -fn map_test_helper_2(i int, b string) int { - return i + b.len -} - -fn map_test_helper_3(i int, b []string) int { - return i + b.map(it.len)[i % b.len] -} - -fn filter_test_helper_1(a int) bool { - return a > 3 -} - -fn sum(prev int, curr int) int { - return prev + curr -} - -fn sub(prev int, curr int) int { - return prev - curr -} - -struct Foooj { - a [5]int // c_n -} - -fn double_up(mut a []int) { - for i := 0; i < a.len; i++ { - a[i] = a[i] * 2 - } -} - -fn double_up_v2(mut a []int) { - for i, _ in a { - a[i] = a[i] * 2 // or val*2, doesn't matter - } -} - -fn modify(mut numbers []int) { - numbers[0] = 777 -} - -fn main() { - { - // test pointer - mut arr := []&int{} - a := 1 - b := 2 - c := 3 - arr << &a - arr << &b - arr << &c - assert *arr[0] == 1 - arr[1] = &c - assert *arr[1] == 3 - mut d_arr := [arr] // [][]&int - d_arr << arr - println(*d_arr[0][1]) // 3 - println(*d_arr[1][0]) // 1 - } - { - // test assign - mut arr := [2, 4, 8, 16, 32, 64, 128] - arr[0] = 2 - arr[1] &= 255 - arr[2] |= 255 - arr[3] <<= 4 - arr[4] >>= 4 - arr[5] %= 5 - arr[6] ^= 3 - println(arr[0]) - println(arr[1]) - println(arr[2]) - println(arr[3]) - println(arr[4]) - println(arr[5]) - println(arr[6]) - } - { - // test ints - mut a := [1, 5, 2, 3] - println(a.len) // 4 - println(a[0]) - println(a[2]) - println(a.last()) - - a << 4 - println(a.len) - println(a[4]) - println(a.last()) - - s := a.str() - println(s) - println(a[1]) - println(a.last()) - } - { - // test deleting - mut a := [1, 5, 2, 3, 4] - - println(a.len) - println(a.str()) - - a.delete(0) - - println(a.str()) - println(a.len) // 4 - - a.delete(1) - - println(a.str()) - println(a.len) - a.delete(a.len - 1) - - println(a.str()) - println(a.len) - } - { - // test slice delete - mut a := [1.5, 2.5, 3.25, 4.5, 5.75] - b := a[2..4] - a.delete(0) - // assert a == [2.5, 3.25, 4.5, 5.75] - // assert b == [3.25, 4.5] - println(a) - println(a == [2.5, 3.25, 4.5, 5.75]) - println(b == [3.25, 4.5]) - a = [3.75, 4.25, -1.5, 2.25, 6.0] - c := a[..3] - a.delete(2) - println(a == [3.75, 4.25, 2.25, 6.0]) - println(c == [3.75, 4.25, -1.5]) - } - { - // test delete many - mut a := [1, 2, 3, 4, 5, 6, 7, 8, 9] - b := a[2..6] - a.delete_many(4, 3) - println(a == [1, 2, 3, 4, 8, 9]) - println(b == [3, 4, 5, 6]) - - c := a[..a.len] - a.delete_many(2, 0) // this should just clone - a[1] = 17 - - println(a == [1, 17, 3, 4, 8, 9]) - println(c == [1, 2, 3, 4, 8, 9]) - a.delete_many(0, a.len) - println(a == []int{}) - } - { - // test short - a := [1, 2, 3] - println(a.len == 3) - println(a.cap == 3) - println(a[0]) - println(a[1]) - println(a[2]) - } - { - // test large - mut a := [0].repeat(0) - for i in 0 .. 10000 { - a << i - } - println(a.len) - println(a[234]) - } - { - // test empty - mut chunks := []Chunk{} - a := Chunk{} - println(chunks.len) - chunks << a - println(chunks.len) - chunks = [] - println(chunks.len) - chunks << a - println(chunks.len) - } - { - // test push - mut a := []int{} - a << 1 - a << 3 - println(a[1]) - println(a.str()) - } - { - // test insert - mut a := [1, 2] - a.insert(0, 3) - println(a[0]) - println(a[2]) - println(a.len) - a.insert(1, 4) - println(a[1]) - println(a[2]) - println(a.len) - a.insert(4, 5) - println(a[4]) - println(a[3]) - println(a.len) - mut b := []f64{} - println(b.len) - b.insert(0, f64(1.1)) - println(b.len) - println(b[0]) - } - { - // test insert many - mut a := [3, 4] - a.insert(0, [1, 2]) - println(a) - - b := [5, 6] - a.insert(1, b) - println(a) - } - { - // test prepend - mut a := []int{} - println(a.len) - a.prepend(1) - println(a.len) - println(a[0]) - mut b := []f64{} - - println(b.len) - - b.prepend(f64(1.1)) - - println(b.len) - - println(b[0]) - } - { - // test prepend many - mut a := [3, 4] - a.prepend([1, 2]) - println(a) - b := [5, 6] - a.prepend(b) - println(a) - } - { - // test repeat - { - a := [0].repeat(5) - println(a.len) - println(a[0] == 0 && a[1] == 0 && a[2] == 0 && a[3] == 0 && a[4] == 0) - } - { - a := [1.1].repeat(10) - println(a[0]) - println(a[5]) - println(a[9]) - } - { - a := [i64(-123)].repeat(10) - println(a[0]) - println(a[5]) - println(a[9]) - } - { - a := [u64(123)].repeat(10) - println(a[0]) - println(a[5]) - println(a[9]) - } - { - a := [1.1].repeat(10) - println(a[0]) - println(a[5]) - println(a[9]) - } - { - a := [1, 2].repeat(2) - println(a[0]) - println(a[1]) - println(a[2]) - println(a[3]) - } - { - a := ['1', 'abc'].repeat(2) - println(a[0]) - println(a[1]) - println(a[2]) - println(a[3]) - } - { - mut a := ['1', 'abc'].repeat(0) - println(a.len) - a << 'abc' - println(a[0]) - } - } - { - // todo(playX): deep repeat does not yet work. - /* - // test deep repeat - mut a3 := [[[1, 1], [2, 2], [3, 3]], [[4, 4], [5, 5], [6, 6]]] - r := a3.repeat(3) - a3[1][1][0] = 17 - print(r) - assert r == [ - [[1, 1], [2, 2], [3, 3]], - [[4, 4], [5, 5], [6, 6]], - [[1, 1], [2, 2], [3, 3]], - [[4, 4], [5, 5], [6, 6]], - [[1, 1], [2, 2], [3, 3]], - [[4, 4], [5, 5], [6, 6]], - ] - assert a3 == [[[1, 1], [2, 2], [3, 3]], [[4, 4], [17, 5], - [6, 6], - ]] - */ - } - { - // test right - a := [1, 2, 3, 4] - c := a[1..a.len] - d := a[1..] - println(c[0]) - println(c[1]) - println(d[0]) - println(d[1]) - } - { - // test left - a := [1, 2, 3] - c := a[0..2] - d := a[..2] - println(c[0]) - println(c[1]) - println(d[0]) - println(d[1]) - } - { - // test slice - a := [1, 2, 3, 4] - b := a[2..4] - println(b.len) - println(a[1..2].len) - println(a.len) - } - { - // test push many - mut a := [1, 2, 3] - b := [4, 5, 6] - a << b - println(a.len) - println(a[0]) - println(a[3]) - println(a[5]) - } - { - // test reverse - a := [1, 2, 3, 4] - b := ['test', 'array', 'reverse'] - c := a.reverse() - println(c) - d := b.reverse() - for i, _ in c { - println(c[i] == a[a.len - i - 1]) - } - for i, _ in d { - println(d[i] == b[b.len - i - 1]) - } - e := []int{} - f := e.reverse() - println(f.len) - } - { - // test fixed - mut nums := [4]int{} - // x := nums[1..3] - // assert x.len == 2 - - println(nums) - nums[1] = 7 - println(nums) - nums2 := [5]int{} // c_n - println(nums2[c_n - 1]) - } - { - // test mut slice - /* - todo(playX): slices do not work yet. We have to implement custom wrapper for them. - mut n := [1, 2, 3] - // modify(mut n) - modify(mut n[..2]) - assert n[0] == 777 - modify(mut n[2..]) - assert n[2] == 777 - println(n) - */ - } - { - // test mut arg - mut arr := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - double_up(mut arr) - println(arr.str()) - arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - double_up_v2(mut arr) - println(arr.str()) - } - { - // test doubling - mut nums := [1, 2, 3, 4, 5] - for i in 0 .. nums.len { - nums[i] *= 2 - } - println(nums.str()) - } - { - // test single element - - mut a := [1] - a << 2 - println(a.len) - assert a[0] == 1 - assert a[1] == 2 - println(a) - } - { - // test find index - - // string - a := ['v', 'is', 'great'] - println(a.index('v')) - println(a.index('is')) - println(a.index('gre')) - // int - b := [1, 2, 3, 4] - println(b.index(1)) - println(b.index(4)) - println(b.index(5)) - // byte - c := [0x22, 0x33, 0x55] - println(c.index(0x22)) - println(c.index(0x55)) - println(c.index(0x99)) - // char - d := [`a`, `b`, `c`] - println(d.index(`b`)) - println(d.index(`c`)) - println(d.index(`u`)) - } - { - // test multi - - a := [[1, 2, 3], [4, 5, 6]] - println(a.len) - println(a[0].len) - println(a[0][0]) - println(a[0][2]) - println(a[1][2]) - } - { - // test in - a := [1, 2, 3] - println(1 in a) - println(2 in a) - println(3 in a) - println(4 !in a) - println(0 !in a) - println(0 !in a) - println(4 !in a) - b := [1, 4, 0] - c := [3, 6, 2, 0] - println(0 in b) - println(0 in c) - } - { - // test reduce - a := [1, 2, 3, 4, 5] - b := a.reduce(sum, 0) - c := a.reduce(sum, 5) - d := a.reduce(sum, -1) - println(b) - println(c) - println(d) - e := [1, 2, 3] - f := e.reduce(sub, 0) - g := e.reduce(sub, -1) - println(f) - println(g) - } - { - a := [1, 2, 3, 4, 5, 6] - b := a.filter(it % 2 == 0) - println(b) - - c := ['v', 'is', 'awesome'] - d := c.filter(it.len > 1) - println(d) - assert d[0] == 'is' - assert d[1] == 'awesome' - //////// - arr := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - println(arr.filter(it % 2 == 0 || it % 3 == 0)) - - mut mut_arr := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - mut_arr = mut_arr.filter(it < 4) - assert mut_arr.len == 3 - println(a.filter(filter_test_helper_1)) - println([1, 5, 10].filter(filter_test_helper_1)) - } - { - // test anon fn filter - filter_num := fn (i int) bool { - return i % 2 == 0 - } - println([1, 2, 3, 4, 5].filter(filter_num)) - } - { - a := [1, 2, 3, 4].filter(fn (i int) bool { - return i % 2 == 0 - }) - println(a) - } - { - // test map - nums := [1, 2, 3, 4, 5, 6] - strs := ['v', 'is', 'awesome'] - // assert nums.map() == - // assert nums.map(it, 'excessive') == - // identity - println(nums.map(it)) - println(strs.map(it)) - println(nums.map(it - it)) - println(nums.map(it - it)[0]) - // type switch - println(nums.map(it * 10)) - println(nums.map(it * it)) - println(nums.map('$it')) - println(nums.map(it % 2 == 0)) - println(strs.map(it.to_upper())) - println(strs.map(it == 'awesome')) - println(strs.map(it.len in nums)) - println(strs.map(int(7))) - // external func - println(nums.map(map_test_helper_1(it))) - println(nums.map(map_test_helper_2(it, 'bb'))) - println(nums.map(map_test_helper_3(it, strs))) - // empty array as input - println([]int{len: 0}.map(it * 2)) - // nested maps (where it is of same type) - println(nums.map(strs.map(int(7)) == [7, 7, 7])) - println(nums.map('$it' + strs.map('a')[0])) - // assert nums.map(it + strs.map(int(7))[0]) == [8, 9, 10, 11, 12, 13] - println(nums.map(it + strs.map(it.len)[0])) - println(strs.map(it.len + strs.map(it.len)[0])) - // nested (different it types) - // todo(playX): this one produces invalid JS code. - // assert strs.map(it[nums.map(it - it)[0]]) == [byte(`v`), `i`, `a`] - println(nums[0..3].map('$it' + strs.map(it)[it - 1])) - println(nums.map(map_test_helper_1)) - println([1, 5, 10].map(map_test_helper_1)) - println(nums) - println(strs) - } - { - // test anon fn map - add_num := fn (i int) int { - return i + 1 - } - println([1, 2, 3].map(add_num)) - } - { - // test multi anon fn map - a := [1, 2, 3].map(fn (i int) int { - return i + 1 - }) - b := [1, 2, 3].map(fn (i int) int { - return i + 2 - }) - println(a) - println(b) - } - { - // test anon fn arg map - a := [1, 2, 3].map(fn (i int) int { - return i + 1 - }) - println(a) - } - { - // test anon fn arg different type map - i_to_str := fn (i int) string { - return i.str() - } - a := [1, 2, 3].map(i_to_str) - println(a) - } - { - // test anon fn inline different type map - a := [1, 2, 3].map(fn (i int) string { - return i.str() - }) - println(a) - } - { - // test array str - - numbers := [1, 2, 3] - assert numbers == [1, 2, 3] - numbers2 := [numbers, [4, 5, 6]] // dup str() bug - println(numbers2) - assert true - assert numbers.str() == '[1, 2, 3]' - } - { - // test eq - println([5, 6, 7] != [6, 7]) - println([`a`, `b`] == [`a`, `b`]) - println([User{ - age: 22 - name: 'bob' - }] == [User{ - age: 22 - name: 'bob' - }]) - // todo(playX): map cmp does not work yet - /* - assert [map{ - 'bob': 22 - }, map{ - 'tom': 33 - }] == [map{ - 'bob': 22 - }, map{ - 'tom': 33 - }]*/ - println([[1, 2, 3], [4]] == [[1, 2, 3], [4]]) - } - { - // test fixed array eq - a1 := [1, 2, 3]! - println(a1 == [1, 2, 3]!) - println(a1 != [2, 3, 4]!) - - a2 := [[1, 2]!, [3, 4]!]! - println(a2 == [[1, 2]!, [3, 4]!]!) - println(a2 != [[3, 4]!, [1, 2]!]!) - - a3 := [[1, 2], [3, 4]]! - println(a3 == [[1, 2], [3, 4]]!) - println(a3 != [[1, 1], [2, 2]]!) - - a4 := [[`a`, `b`], [`c`, `d`]]! - println(a4 == [[`a`, `b`], [`c`, `d`]]!) - println(a4 != [[`c`, `a`], [`a`, `b`]]!) - - a5 := [['aaa', 'bbb'], ['ccc', 'ddd']]! - println(a5 == [['aaa', 'bbb'], ['ccc', 'ddd']]!) - println(a5 != [['abc', 'def'], ['ccc', 'ddd']]!) - - a6 := [['aaa', 'bbb']!, ['ccc', 'ddd']!]! - println(a6 == [['aaa', 'bbb']!, ['ccc', 'ddd']!]!) - println(a6 != [['aaa', 'bbb']!, ['aaa', 'ddd']!]!) - - a7 := [[1, 2]!, [3, 4]!] - println(a7 == [[1, 2]!, [3, 4]!]) - println(a7 != [[2, 3]!, [1, 2]!]) - - a8 := [['aaa', 'bbb']!, ['ccc', 'ddd']!] - println(a8 == [['aaa', 'bbb']!, ['ccc', 'ddd']!]) - println(a8 != [['bbb', 'aaa']!, ['cccc', 'dddd']!]) - } - { - // test fixed array literal eq - println([1, 2, 3]! == [1, 2, 3]!) - println([1, 1, 1]! != [1, 2, 3]!) - - println([[1, 2], [3, 4]]! == [[1, 2], [3, 4]]!) - println([[1, 1], [2, 2]]! != [[1, 2], [3, 4]]!) - - println([[1, 1]!, [2, 2]!]! == [[1, 1]!, [2, 2]!]!) - println([[1, 1]!, [2, 2]!]! != [[1, 2]!, [2, 3]!]!) - - println([[1, 1]!, [2, 2]!] == [[1, 1]!, [2, 2]!]) - println([[1, 1]!, [2, 2]!] != [[1, 2]!, [2, 3]!]) - } - { - // test sort - mut a := ['hi', '1', '5', '3'] - a.sort() - println(a) - - mut nums := [67, -3, 108, 42, 7] - nums.sort() - println(nums) - assert nums[0] == -3 - assert nums[1] == 7 - assert nums[2] == 42 - assert nums[3] == 67 - assert nums[4] == 108 - // todo(playX): add codegen for comparator fn passed - /* - nums.sort(a < b) - assert nums[0] == -3 - assert nums[1] == 7 - assert nums[2] == 42 - assert nums[3] == 67 - assert nums[4] == 108 - - mut users := [User{22, 'Peter'}, User{20, 'Bob'}, User{25, 'Alice'}] - users.sort(a.age < b.age) - assert users[0].age == 20 - assert users[1].age == 22 - assert users[2].age == 25 - assert users[0].name == 'Bob' - assert users[1].name == 'Peter' - assert users[2].name == 'Alice' - - users.sort(a.age > b.age) - assert users[0].age == 25 - assert users[1].age == 22 - assert users[2].age == 20 - - users.sort(a.name < b.name) // Test sorting by string fields - */ - } - { - /* - // test rune sort - mut bs := [`f`, `e`, `d`, `b`, `c`, `a`] - bs.sort() - println(bs)*/ - - /* - bs.sort(a > b) - println(bs) - assert '$bs' == '[`f`, `e`, `d`, `c`, `b`, `a`]' - - bs.sort(a < b) - println(bs) - assert '$bs' == '[`a`, `b`, `c`, `d`, `e`, `f`]' - */ - } - { - // test f32 sort - mut f := [f32(50.0), 15, 1, 79, 38, 0, 27] - f.sort() - println(f[0]) - println(f[1]) - println(f[6]) - } - { - // test f64 sort - mut f := [50.0, 15, 1, 79, 38, 0, 27] - f.sort() - println(f) - assert f[0] == 0.0 - assert f[1] == 1.0 - assert f[6] == 79.0 - } - { - // test i64 sort - mut f := [i64(50), 15, 1, 79, 38, 0, 27] - f.sort() - println(f) - assert f[0] == 0 - assert f[1] == 1 - assert f[6] == 79 - } - { - // test in struct - - mut baz := Foo{ - bar: [0, 0, 0] - } - baz.bar[0] += 2 - baz.bar[0]++ - println(baz.bar[0]) - } - { - // test direct modification - mut foo := [2, 0, 5] - foo[1] = 3 - foo[0] *= 7 - foo[1]-- - foo[2] -= 2 - println(foo) - } - { - // test bools - println('test b') - mut a := [true, false] - a << true - println(a) - } - { - // test push many self - mut actual_arr := [1, 2, 3, 4] - actual_arr << actual_arr - expected_arr := [1, 2, 3, 4, 1, 2, 3, 4] - assert actual_arr.len == expected_arr.len - for i in 0 .. actual_arr.len { - print(actual_arr[i]) - print(',') - println(expected_arr[i]) - } - } - { - // test for - nums := [1, 2, 3] - mut sum := 0 - for num in nums { - sum += num - } - println(sum) - } - { - // test left shift precedence - - mut arr := []int{} - arr << 1 + 1 - arr << 1 - 1 - arr << 2 / 1 - arr << 2 * 1 - println(arr) - } - { - // todo(playX): what we should do with cap on the JS backend? - /* - // test array with cap - a4 := []int{len: 1, cap: 10} - println(a4.cap) - assert a4.len == 1 - assert a4.cap == 10 - a5 := []int{len: 1, cap: 10} - assert a5.len == 1 - assert a5.cap == 10 - */ - } - { - // test multi array index - mut a := [][]int{len: 2, init: []int{len: 3, init: 0}} - a[0][0] = 1 - println('$a') - mut b := [[0].repeat(3)].repeat(2) - b[0][0] = 1 - println('$b') - } - { - // test plus assign string - mut a := [''] - a[0] += 'abc' - - println(a) - } - { - // test mut arr with eq in fn - mut a := [1, 2, 3, 4] - mut_arr_with_eq_in_fn(mut a) - println(a) - } - { - // test array in mut - mut a := [1, 2] - array_in_mut(mut a) - println(a) - } - { - mut nums := [1, 2, 3] - add_nums(mut nums) - println(nums) - } - { - // test reverse in place - mut a := [1, 2, 3, 4] - a.reverse_in_place() - println(a) - mut b := ['a', 'b', 'c'] - b.reverse_in_place() - println(b) - mut c := [[1, 2], [3, 4], [5, 6]] - c.reverse_in_place() - println(c) - } - { - // test array int pop - mut a := [1, 2, 3, 4, 5] - assert a.len == 5 - x := a.last() - y := a.pop() - println('$x,$y') - assert a.len == 4 - z := a.pop() - assert a.len == 3 - println(z) - a.pop() - a.pop() - final := a.pop() - println(final) - } - { - // test array string pop - mut a := ['abc', 'def', 'xyz'] - assert a.len == 3 - println(a.pop()) - println(a.pop()) - println(a.pop()) - assert a.len == 0 - } - { - // test array first - a := [3] - println(a.first()) - b := [1, 2, 3, 4] - println(b.first()) - c := ['abc', 'def'] - println(c.first()) - // todo(playX): we should implement byte str cmp - - s := [Chunk{'a'}] - println(s.first().val) - } - { - // test array last - a := [3] - println(a.last()) - b := [1, 2, 3, 4] - println(b.last()) - c := ['abc', 'def'] - println(c.last()) - s := [Chunk{'a'}] - println(s.last().val) - } - { - // test direct array access - mut a := [11, 22, 33, 44] - println(a[0]) - println(a[2]) - x := a[0] - a[0] = 21 - a[1] += 2 - a[2] = x + 3 - a[3] -= a[1] - println(a) - } - { - // test multidimensional array initialization with consts - mut data := [][][]int{len: grid_size_1, init: [][]int{len: grid_size_2, init: []int{len: grid_size_3, init: cell_value}}} - println(data.len) - println(data[0].len) - println(data[0][0].len) - println(data[0][0][0]) - println(data[1][1][1]) - } - { - // test multi array prepend - mut a := [][]int{} - a.prepend([1, 2, 3]) - println(a) - mut b := [][]int{} - b.prepend([[1, 2, 3]]) - println(b) - } - { - // test multi array insert - mut a := [][]int{} - a.insert(0, [1, 2, 3]) - println(a) - mut b := [][]int{} - b.insert(0, [[1, 2, 3]]) - println(b) - } - { - // test multi array in - a := [[1]] - println([1] in a) - } - { - // test any type array contains - a := [true, false] - println(a.contains(true)) - println(true in a) - println(a.contains(false)) - println(false in a) - b := [i64(2), 3, 4] - println(b.contains(i64(3))) - println(5 !in b) - c := [[1], [2]] - println(c.contains([1])) - println([2] in c) - println([3] !in c) - } - { - // test struct array of multi type in - ivan := Person{ - name: 'ivan' - nums: [1, 2, 3] - kv: { - 'aaa': '111' - } - } - people := [ - Person{ - name: 'ivan' - nums: [1, 2, 3] - kv: { - 'aaa': '111' - } - }, - Person{ - name: 'bob' - nums: [2] - kv: { - 'bbb': '222' - } - }, - ] - println(ivan in people) - } - { - // test struct array of multi type index - ivan := Person{ - name: 'ivan' - nums: [1, 2, 3] - kv: { - 'aaa': '111' - } - } - people := [ - Person{ - name: 'ivan' - nums: [1, 2, 3] - kv: { - 'aaa': '111' - } - }, - Person{ - name: 'bob' - nums: [2] - kv: { - 'bbb': '222' - } - }, - ] - println(people.index(ivan)) - assert people.index(ivan) == 0 - } - { - // test array struct contains - - mut coords := []Coord{} - coord_1 := Coord{ - x: 1 - y: 2 - z: -1 - } - coords << coord_1 - exists := coord_1 in coords - not_exists := coord_1 !in coords - println('`exists`: $exists and `not exists`: $not_exists') - assert exists == true - assert not_exists == false - } - { - // test array of array append - mut x := [][]int{len: 4} - println(x) // OK - x[2] << 123 // RTE - println(x) - } - { - // test array of map insert - mut x := []map[string]int{len: 4} - println(x) // OK - x[2]['123'] = 123 // RTE - println(x) - } - { - // todo(playX): does not work - /* - // test multi fixed array init - a := [3][3]int{} - println(a) - */ - } - { - // test array of multi filter - arr := [1, 2, 3, 4, 5] - nums := Numbers{ - odds: arr.filter(it % 2 == 1) - evens: arr.filter(it % 2 == 0) - } - println(nums) - assert nums.odds == [1, 3, 5] - assert nums.evens == [2, 4] - } - { - // test array of multi map - arr := [1, 3, 5] - nums := Numbers{ - odds: arr.map(it + 2) - evens: arr.map(it * 2) - } - println(nums) - assert nums.odds == [3, 5, 7] - assert nums.evens == [2, 6, 10] - } - { - // test multi fixed array with default init - a := [3][3]int{init: [3]int{init: 10}} - println(a) - assert a == [[10, 10, 10]!, [10, 10, 10]!, [10, 10, 10]!]! - } -}