Skip to content

Commit

Permalink
cgen: fix assert expr handling + print with comptime smartcast (#20399)
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp committed Jan 6, 2024
1 parent b35988d commit a321ef6
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
15 changes: 15 additions & 0 deletions vlib/v/gen/c/assert.v
Expand Up @@ -17,11 +17,17 @@ fn (mut g Gen) assert_stmt(original_assert_statement ast.AssertStmt) {
}
mut node := original_assert_statement
g.writeln('// assert')

mut save_left := ast.empty_expr
mut save_right := ast.empty_expr

if mut node.expr is ast.InfixExpr {
if subst_expr := g.assert_subexpression_to_ctemp(node.expr.left, node.expr.left_type) {
save_left = node.expr.left
node.expr.left = subst_expr
}
if subst_expr := g.assert_subexpression_to_ctemp(node.expr.right, node.expr.right_type) {
save_right = node.expr.right
node.expr.right = subst_expr
}
}
Expand Down Expand Up @@ -56,6 +62,15 @@ fn (mut g Gen) assert_stmt(original_assert_statement ast.AssertStmt) {
g.gen_assert_postfailure_mode(node)
g.writeln('}')
}

if mut node.expr is ast.InfixExpr {
if node.expr.left is ast.CTempVar {
node.expr.left = save_left
}
if node.expr.right is ast.CTempVar {
node.expr.right = save_right
}
}
}

struct UnsupportedAssertCtempTransform {
Expand Down
2 changes: 2 additions & 0 deletions vlib/v/gen/c/fn.v
Expand Up @@ -1816,6 +1816,8 @@ fn (mut g Gen) fn_call(node ast.CallExpr) {
cast_sym := g.table.sym(typ)
if cast_sym.info is ast.Aggregate {
typ = cast_sym.info.types[g.aggregate_type_idx]
} else if expr.obj.ct_type_var == .smartcast {
typ = g.unwrap_generic(g.comptime.get_comptime_var_type(expr))
}
}
// handling println( var or { ... })
Expand Down
45 changes: 45 additions & 0 deletions vlib/v/tests/comptime_smartcast_assert_test.v
@@ -0,0 +1,45 @@
pub type Any = []Any
| bool
| f32
| f64
| i16
| i64
| i8
| int
| map[string]Any
| string
| u16
| u32
| u64
| u8

fn test_main() {
ana := Any([Any('')])
name(ana)
match ana {
[]Any {
for i := 0; i < ana.len; i++ {
name(ana[i])
}
}
else {
assert false
}
}
assert true
}

fn name[T](val T) {
$for v in val.variants {
if val is v {
dump(val.str())
$if val is []Any {
assert val.str() == "[Any('')]"
} $else {
assert val.str() == ''
}
dump(val)
println(val)
}
}
}

0 comments on commit a321ef6

Please sign in to comment.