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

for: ranging through fixed size arrays

This commit is contained in:
Alexander Medvednikov 2019-12-05 02:11:51 +03:00
parent fb546f376e
commit 867f952d6b
2 changed files with 16 additions and 5 deletions

View File

@ -145,14 +145,15 @@ fn (p mut Parser) for_st() {
} }
is_arr := typ.contains('array') is_arr := typ.contains('array')
is_fixed := typ.starts_with('[')
is_str := typ == 'string' is_str := typ == 'string'
if !is_arr && !is_str && !is_range && !is_variadic_arg { if !is_arr && !is_str && !is_range && !is_fixed && !is_variadic_arg {
p.error('cannot range over type `$typ`') p.error('cannot range over type `$typ`')
} }
if !is_variadic_arg { if !is_variadic_arg {
if p.is_js { if p.is_js {
p.genln('var $tmp = $expr;') p.genln('var $tmp = $expr;')
} else { } else if !is_fixed { // Don't copy if it's a fixed array
p.genln('$typ $tmp = $expr;') p.genln('$typ $tmp = $expr;')
} }
} }
@ -174,6 +175,10 @@ fn (p mut Parser) for_st() {
typ = 'byte' typ = 'byte'
p.gen_for_str_header(i, tmp, typ, val) p.gen_for_str_header(i, tmp, typ, val)
} }
else if is_fixed {
typ = typ.all_after(']')
p.gen_for_fixed_header(i, expr, typ, val)
}
// println('for typ=$typ vartyp=$var_typ') // println('for typ=$typ vartyp=$var_typ')
// Register temp var // Register temp var
if val != '_' { if val != '_' {

View File

@ -365,6 +365,12 @@ fn (p mut Parser) gen_for_header(i, tmp, var_typ, val string) {
p.genln('$var_typ $val = (($var_typ *) $tmp . data)[$i];') p.genln('$var_typ $val = (($var_typ *) $tmp . data)[$i];')
} }
fn (p mut Parser) gen_for_fixed_header(i, tmp, var_typ, val string) {
p.genln('for (int $i = 0; $i < sizeof(${tmp}) / sizeof($tmp [0]); $i++) {')
if val == '_' { return }
p.genln('$var_typ $val = $tmp[$i];')
}
fn (p mut Parser) gen_for_str_header(i, tmp, var_typ, val string) { fn (p mut Parser) gen_for_str_header(i, tmp, var_typ, val string) {
// TODO var_typ is always byte // TODO var_typ is always byte
//p.genln('array_byte bytes_$tmp = string_bytes( $tmp );') //p.genln('array_byte bytes_$tmp = string_bytes( $tmp );')