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

cgen: fix it variable casting on map call when arr is a comptime variable #18083

This commit is contained in:
Felipe Pena 2023-04-30 10:18:44 -03:00 committed by GitHub
parent 580e079b1e
commit d086cc26cd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 41 additions and 0 deletions

View File

@ -484,6 +484,17 @@ fn (mut g Gen) gen_array_map(node ast.CallExpr) {
g.write('${ret_elem_type} ti = ')
g.expr(node.args[0].expr)
}
ast.CastExpr {
// value.map(Type(it)) when `value` is a comptime var
if expr.expr is ast.Ident && node.left is ast.Ident && g.is_comptime_var(node.left) {
ctyp := g.get_comptime_var_type(node.left)
if ctyp != ast.void_type {
expr.expr_type = g.table.value_type(ctyp)
}
}
g.write('${ret_elem_type} ti = ')
g.expr(node.args[0].expr)
}
else {
if closure_var_decl != '' {
g.write('${closure_var_decl} = ')

View File

@ -0,0 +1,30 @@
type Any = []Any | f64 | int | map[string]Any | string
struct Arr {
ints []int
floats []f64
strs []string
}
fn encode[T](typ T) map[string]Any {
mut mp := map[string]Any{}
$for field in T.fields {
value := typ.$(field.name)
$if field.is_enum {
mp[field.name] = Any(int(value))
} $else $if field.is_array {
mp[field.name] = value.map(Any(it))
} $else {
mp[field.name] = Any(value)
}
}
return mp
}
fn test_main() {
a := Arr{[5], [2.0], ['asdf']}
r := encode[Arr](a)
assert r['ints'] == Any([Any(5)])
assert r['floats'] == Any([Any(2.0)])
assert r['strs'] == Any([Any('asdf')])
}