From 29e0396eca390dc8442752a64e89efa12655892b Mon Sep 17 00:00:00 2001 From: Henrixounez Date: Thu, 29 Aug 2019 18:46:03 +0200 Subject: [PATCH] compiler: adds handling of two variables for loop on string --- compiler/parser.v | 16 ++++++++++++++-- vlib/builtin/string_test.v | 18 ++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/compiler/parser.v b/compiler/parser.v index c4e46fba09..b2e91fce29 100644 --- a/compiler/parser.v +++ b/compiler/parser.v @@ -3125,7 +3125,7 @@ fn (p mut Parser) for_st() { expr := p.cgen.end_tmp() p.genln('$typ $tmp = $expr ;') pad := if is_arr { 6 } else { 4 } - var_typ := typ.right(pad) + var_typ := if is_str { 'byte' } else { typ.right(pad) } // typ = strings.Replace(typ, "_ptr", "*", -1) // Register temp var val_var := Var { @@ -3134,7 +3134,7 @@ fn (p mut Parser) for_st() { ptr: typ.contains('*') } p.register_var(val_var) - if is_arr || is_str { + if is_arr { i_var := Var { name: i typ: 'int' @@ -3163,6 +3163,18 @@ fn (p mut Parser) for_st() { // the tree (replace `map_keys()` above with `map_key_vals()`) p.genln('$var_typ $val = $def; map_get($tmp, $i, & $val);') } + else if is_str { + i_var := Var { + name: i + typ: 'byte' + is_mut: true + is_changed: true + } + p.register_var(i_var) + p.genln('array_byte bytes_$tmp = string_bytes( $tmp );') + p.genln(';\nfor (int $i = 0; $i < $tmp .len; $i ++) {') + p.genln('$var_typ $val = (($var_typ *) bytes_$tmp . data)[$i];') + } } // `for val in vals` else if p.peek() == .key_in { diff --git a/vlib/builtin/string_test.v b/vlib/builtin/string_test.v index 1a4531d83b..7fa15c51dc 100644 --- a/vlib/builtin/string_test.v +++ b/vlib/builtin/string_test.v @@ -400,3 +400,21 @@ fn test_title() { s.to_lower() assert s.title() == 'Hello World' } + +fn test_for_loop() { + mut i := 0 + s := 'abcd' + + for c in s { + assert c == s[i] + i++ + } +} + +fn test_for_loop_two() { + s := 'abcd' + + for i, c in s { + assert c == s[i] + } +} \ No newline at end of file