cgen: fix if infix expr with array.all/any() (#11567)

pull/11568/head
yuyi 2021-09-21 21:20:41 +08:00 committed by GitHub
parent 108a01d65f
commit de4c0c237b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 53 additions and 2 deletions

View File

@ -602,11 +602,15 @@ fn (mut g Gen) gen_array_any(node ast.CallExpr) {
// styp := g.typ(node.return_type)
elem_type_str := g.typ(info.elem_type)
g.empty_line = true
g.writeln('bool $tmp = false;')
if g.infix_left_var_name.len > 0 {
g.writeln('if ($g.infix_left_var_name) {')
g.indent++
}
g.write('${g.typ(node.left_type)} ${tmp}_orig = ')
g.expr(node.left)
g.writeln(';')
g.writeln('int ${tmp}_len = ${tmp}_orig.len;')
g.writeln('bool $tmp = false;')
i := g.new_tmp_var()
g.writeln('for (int $i = 0; $i < ${tmp}_len; ++$i) {')
g.writeln('\t$elem_type_str it = (($elem_type_str*) ${tmp}_orig.data)[$i];')
@ -654,6 +658,10 @@ fn (mut g Gen) gen_array_any(node ast.CallExpr) {
g.stmt_path_pos << g.out.len
}
g.write('\n')
if g.infix_left_var_name.len > 0 {
g.indent--
g.writeln('}')
}
g.write(s)
g.write(tmp)
}
@ -666,11 +674,15 @@ fn (mut g Gen) gen_array_all(node ast.CallExpr) {
// styp := g.typ(node.return_type)
elem_type_str := g.typ(info.elem_type)
g.empty_line = true
g.writeln('bool $tmp = true;')
if g.infix_left_var_name.len > 0 {
g.writeln('if ($g.infix_left_var_name) {')
g.indent++
}
g.write('${g.typ(node.left_type)} ${tmp}_orig = ')
g.expr(node.left)
g.writeln(';')
g.writeln('int ${tmp}_len = ${tmp}_orig.len;')
g.writeln('bool $tmp = true;')
i := g.new_tmp_var()
g.writeln('for (int $i = 0; $i < ${tmp}_len; ++$i) {')
g.writeln('\t$elem_type_str it = (($elem_type_str*) ${tmp}_orig.data)[$i];')
@ -718,6 +730,10 @@ fn (mut g Gen) gen_array_all(node ast.CallExpr) {
g.stmt_path_pos << g.out.len
}
g.write('\n')
if g.infix_left_var_name.len > 0 {
g.indent--
g.writeln('}')
}
g.write(s)
g.write(tmp)
}

View File

@ -630,6 +630,24 @@ fn (mut g Gen) infix_expr_and_or_op(node ast.InfixExpr) {
return
}
g.inside_ternary = prev_inside_ternary
} else if node.right is ast.CallExpr {
if node.right.left_type != 0 {
sym := g.table.get_type_symbol(node.right.left_type)
if sym.kind == .array && node.right.name in ['map', 'filter', 'all', 'any'] {
tmp := g.new_tmp_var()
cur_line := g.go_before_stmt(0).trim_space()
g.empty_line = true
g.write('bool $tmp = (')
g.expr(node.left)
g.writeln(');')
g.stmt_path_pos << g.out.len
g.write('$cur_line $tmp $node.op.str() ')
g.infix_left_var_name = if node.op == .and { tmp } else { '!$tmp' }
g.expr(node.right)
g.infix_left_var_name = ''
return
}
}
}
g.gen_plain_infix_expr(node)
}

View File

@ -0,0 +1,17 @@
fn test_if_expr_with_array_all_any() {
arr := ['']
for i in arr {
if i.len == 0 || i[1..].bytes().all(it.is_letter()) {
println('empty or all char from second is letter!')
assert true
}
}
for i in arr {
if i.len == 0 || i[1..].bytes().any(it.is_letter()) {
println('empty or all char from second is letter!')
assert true
}
}
}