cgen: fix error caused by fixed size array init syntax with variable it (#12314)

pull/12318/head
ChAoS_UnItY 2021-10-28 07:20:49 +08:00 committed by GitHub
parent 8fd66994c7
commit 8cd01e0eac
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 68 additions and 17 deletions

View File

@ -23,6 +23,61 @@ fn (mut g Gen) array_init(node ast.ArrayInit) {
g.write('HEAP($array_styp, ')
}
if array_type.unaliased_sym.kind == .array_fixed {
if node.has_it {
g.inside_lambda = true
tmp := g.new_tmp_var()
mut s := g.go_before_stmt(0)
s_ends_with_ln := s.ends_with('\n')
s = s.trim_space()
ret_typ := g.typ(node.typ)
elem_typ := g.typ(node.elem_type)
g.empty_line = true
g.write('$ret_typ $tmp =')
g.write('{')
if node.has_val {
for i, expr in node.exprs {
if expr.is_auto_deref_var() {
g.write('*')
}
g.write('0')
if i != node.exprs.len - 1 {
g.write(', ')
}
}
} else if node.has_default {
g.write('0')
info := array_type.unaliased_sym.info as ast.ArrayFixed
for _ in 1 .. info.size {
g.write(', ')
g.write('0')
}
} else {
g.write('0')
}
g.write('}')
g.writeln(';')
g.writeln('{')
g.indent++
g.writeln('$elem_typ* pelem = ($elem_typ*)$tmp;')
g.writeln('int _len = (int)sizeof($tmp) / sizeof($elem_typ);')
g.writeln('for(int it=0; it<_len; it++, pelem++) {')
g.indent++
g.write('*pelem = ')
g.expr(node.default_expr)
g.writeln(';')
g.indent--
g.writeln('}')
g.indent--
g.writeln('}')
if s_ends_with_ln {
g.writeln(s)
} else {
g.write(s)
}
g.write(tmp)
g.inside_lambda = false
return
}
g.write('{')
if node.has_val {
for i, expr in node.exprs {

View File

@ -3197,18 +3197,7 @@ fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) {
} else if is_decl {
if is_fixed_array_init && !has_val {
if val is ast.ArrayInit {
if val.has_default {
g.write('{')
g.expr(val.default_expr)
info := right_sym.info as ast.ArrayFixed
for _ in 1 .. info.size {
g.write(', ')
g.expr(val.default_expr)
}
g.write('}')
} else {
g.write('{0}')
}
g.array_init(val)
} else {
g.write('{0}')
}

View File

@ -163,14 +163,18 @@ fn (mut g Gen) infix_expr_eq_op(node ast.InfixExpr) {
g.write('*')
}
if node.left is ast.ArrayInit {
s := g.typ(left.unaliased)
g.write('($s)')
if !node.left.has_it {
s := g.typ(left.unaliased)
g.write('($s)')
}
}
g.expr(node.left)
g.write(', ')
if node.right is ast.ArrayInit {
s := g.typ(right.unaliased)
g.write('($s)')
if !node.right.has_it {
s := g.typ(right.unaliased)
g.write('($s)')
}
}
g.expr(node.right)
g.write(')')

View File

@ -119,7 +119,9 @@ fn (mut g Gen) gen_expr_to_string(expr ast.Expr, etype ast.Type) {
if expr is ast.ArrayInit {
if expr.is_fixed {
s := g.typ(expr.typ)
g.write('($s)')
if !expr.has_it {
g.write('($s)')
}
}
}
g.expr_with_cast(expr, typ, typ)

View File

@ -1,4 +1,5 @@
fn test_array_with_it() {
assert [0, 1, 2, 3, 4, 5]! == [6]int{init: it}
assert [0, 1, 4, 9, 16, 25] == []int{len: 6, init: it * it}
assert [1, 2, 3, 4, 5] == []int{len: 5, init: it + 1}
assert [5, 4, 3, 2, 1] == []int{len: 5, init: 5 - it}