From 4ef10c92f44d7ef684784ec8212bcb8d6bea2641 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Sat, 26 Oct 2019 14:25:03 +0300 Subject: [PATCH] array: map() method --- vlib/compiler/comptime.v | 39 +++++++++++++++++++++++++++++++++++++++ vlib/compiler/parser.v | 4 ++++ 2 files changed, 43 insertions(+) diff --git a/vlib/compiler/comptime.v b/vlib/compiler/comptime.v index 709d9d0ae8..6b035b7760 100644 --- a/vlib/compiler/comptime.v +++ b/vlib/compiler/comptime.v @@ -374,3 +374,42 @@ fn (p mut Parser) gen_array_filter(str_typ string, method_ph int) { p.check(.rpar) p.close_scope() } + +fn (p mut Parser) gen_array_map(str_typ string, method_ph int) { + /* + // V + a := [1,2,3,4] + b := a.map(it * 2) + + // C + array_int a = ...; + array_int tmp2 = new_array(0, 4, 4); + for (int i = 0; i < a.len; i++) { + int it = ((int*)a.data)[i]; + _PUSH(tmp2, it * 2, tmp3, int) + } + array_int b = tmp2; + */ + val_type:=str_typ.right(6) + p.open_scope() + p.register_var(Var{ + name: 'it' + typ: val_type + }) + p.next() + p.check(.lpar) + p.cgen.resetln('') + tmp := p.get_tmp() + tmp_elm := p.get_tmp() + a := p.expr_var.name + map_type, expr := p.tmp_expr() + p.cgen.set_placeholder(method_ph,'\narray $tmp = new_array(0, $a .len, ' + + 'sizeof($map_type));\n') + p.genln('for (int i = 0; i < ${a}.len; i++) {') + p.genln('$val_type it = (($val_type*)${a}.data)[i];') + p.genln('_PUSH(&$tmp, $expr, $tmp_elm, $map_type)') + p.genln('}') + p.gen(tmp) // TODO why does this `gen()` work? + p.check(.rpar) + p.close_scope() +} diff --git a/vlib/compiler/parser.v b/vlib/compiler/parser.v index b031c8a6f3..e06d166cee 100644 --- a/vlib/compiler/parser.v +++ b/vlib/compiler/parser.v @@ -1947,6 +1947,10 @@ fn (p mut Parser) dot(str_typ_ string, method_ph int) string { p.gen_array_filter(str_typ, method_ph) return str_typ } + else if field_name == 'map' && str_typ.starts_with('array_') { + p.gen_array_map(str_typ, method_ph) + return str_typ + } fname_tidx := p.cur_tok_index() p.fgen(field_name)