diff --git a/vlib/v/gen/c/fn.v b/vlib/v/gen/c/fn.v index 3d7e06364d..df1dbcdc29 100644 --- a/vlib/v/gen/c/fn.v +++ b/vlib/v/gen/c/fn.v @@ -910,12 +910,13 @@ fn (mut g Gen) method_call(node ast.CallExpr) { g.gen_expr_to_string(node.left, rec_type) return } else if node.left.obj.smartcasts.len > 0 { - cast_sym := g.table.sym(node.left.obj.smartcasts.last()) + rec_type = node.left.obj.smartcasts.last() + cast_sym := g.table.sym(rec_type) if cast_sym.info is ast.Aggregate { rec_type = cast_sym.info.types[g.aggregate_type_idx] - g.gen_expr_to_string(node.left, rec_type) - return } + g.gen_expr_to_string(node.left, rec_type) + return } } } @@ -1297,7 +1298,8 @@ fn (mut g Gen) fn_call(node ast.CallExpr) { if expr.obj is ast.Var { typ = expr.obj.typ if expr.obj.smartcasts.len > 0 { - cast_sym := g.table.sym(expr.obj.smartcasts.last()) + typ = expr.obj.smartcasts.last() + cast_sym := g.table.sym(typ) if cast_sym.info is ast.Aggregate { typ = cast_sym.info.types[g.aggregate_type_idx] } diff --git a/vlib/v/gen/c/str_intp.v b/vlib/v/gen/c/str_intp.v index c34d2bcc7c..9817e4abdb 100644 --- a/vlib/v/gen/c/str_intp.v +++ b/vlib/v/gen/c/str_intp.v @@ -156,7 +156,8 @@ fn (mut g Gen) str_val(node ast.StringInterLiteral, i int) { if g.comptime_var_type_map.len > 0 || g.comptime_for_method.len > 0 { exp_typ = expr.obj.typ } else if expr.obj.smartcasts.len > 0 { - cast_sym := g.table.sym(expr.obj.smartcasts.last()) + exp_typ = expr.obj.smartcasts.last() + cast_sym := g.table.sym(exp_typ) if cast_sym.info is ast.Aggregate { exp_typ = cast_sym.info.types[g.aggregate_type_idx] } diff --git a/vlib/v/tests/print_smartcast_variable_test.v b/vlib/v/tests/print_smartcast_variable_test.v new file mode 100644 index 0000000000..dfb989729a --- /dev/null +++ b/vlib/v/tests/print_smartcast_variable_test.v @@ -0,0 +1,33 @@ +struct Point { + x int + y int +} + +struct Line { + p1 Point + p2 Point +} + +// Sum type +type ObjSumType = Line | Point + +fn test_print_smartcast_variable() { + // Type checking and casts + mut point := ObjSumType(Point{2, 5}) + + if point is Point { + println('Point') + } + + if point !is Point { + println('Not Point') + } + + if mut point is Point { + println(point) + assert point.str().contains('x: 2') + assert point.str().contains('y: 5') + assert '$point'.contains('x: 2') + assert '$point'.contains('y: 5') + } +}