Skip to content

Commit

Permalink
checker, cgen: fix const initialized with array (#21131)
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp authored Mar 29, 2024
1 parent 5cc67bb commit 143f0cc
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
1 change: 1 addition & 0 deletions vlib/v/checker/checker.v
Original file line number Diff line number Diff line change
Expand Up @@ -1732,6 +1732,7 @@ fn (mut c Checker) const_decl(mut node ast.ConstDecl) {
prev_const_var := c.const_var
c.const_var = unsafe { field }
mut typ := c.check_expr_option_or_result_call(field.expr, c.expr(mut field.expr))
typ = c.cast_fixed_array_ret(typ, c.table.sym(typ))
if ct_value := c.eval_comptime_const_expr(field.expr, 0) {
field.comptime_expr_value = ct_value
if ct_value is u64 {
Expand Down
3 changes: 3 additions & 0 deletions vlib/v/gen/c/cgen.v
Original file line number Diff line number Diff line change
Expand Up @@ -5986,6 +5986,9 @@ fn (mut g Gen) const_decl_init_later(mod string, name string, expr ast.Expr, typ
init.writeln(g.expr_string_surround('\t${cname} = *(${styp}*)', expr, '.data;'))
} else if expr is ast.ArrayInit && (expr as ast.ArrayInit).has_index {
init.writeln(g.expr_string_surround('\tmemcpy(&${cname}, &', expr, ', sizeof(${styp}));'))
} else if expr is ast.CallExpr
&& g.table.final_sym(g.unwrap_generic((expr as ast.CallExpr).return_type)).kind == .array_fixed {
init.writeln(g.expr_string_surround('\tmemcpy(&${cname}, ', expr, ', sizeof(${styp}));'))
} else {
init.writeln(g.expr_string_surround('\t${cname} = ', expr, ';'))
}
Expand Down
17 changes: 17 additions & 0 deletions vlib/v/tests/const_array_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const some_arr = make_array()
const some_arr2 = make_array2()

fn make_array() [64]u8 {
mut arr := [64]u8{}
return arr
}

fn make_array2() []u8 {
mut arr := []u8{}
return arr
}

fn test_main() {
assert some_arr.len == 64
assert some_arr2.len == 0
}

0 comments on commit 143f0cc

Please sign in to comment.