1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

compiler: adds handling of two variables for loop on string

This commit is contained in:
Henrixounez 2019-08-29 18:46:03 +02:00 committed by Alexander Medvednikov
parent 519028e263
commit 29e0396eca
2 changed files with 32 additions and 2 deletions

View File

@ -3125,7 +3125,7 @@ fn (p mut Parser) for_st() {
expr := p.cgen.end_tmp() expr := p.cgen.end_tmp()
p.genln('$typ $tmp = $expr ;') p.genln('$typ $tmp = $expr ;')
pad := if is_arr { 6 } else { 4 } 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) // typ = strings.Replace(typ, "_ptr", "*", -1)
// Register temp var // Register temp var
val_var := Var { val_var := Var {
@ -3134,7 +3134,7 @@ fn (p mut Parser) for_st() {
ptr: typ.contains('*') ptr: typ.contains('*')
} }
p.register_var(val_var) p.register_var(val_var)
if is_arr || is_str { if is_arr {
i_var := Var { i_var := Var {
name: i name: i
typ: 'int' typ: 'int'
@ -3163,6 +3163,18 @@ fn (p mut Parser) for_st() {
// the tree (replace `map_keys()` above with `map_key_vals()`) // the tree (replace `map_keys()` above with `map_key_vals()`)
p.genln('$var_typ $val = $def; map_get($tmp, $i, & $val);') 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` // `for val in vals`
else if p.peek() == .key_in { else if p.peek() == .key_in {

View File

@ -400,3 +400,21 @@ fn test_title() {
s.to_lower() s.to_lower()
assert s.title() == 'Hello World' 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]
}
}