Skip to content

Commit ffe6ff3

Browse files
authored
cgen: fix error for print smartcast variable (#13634)
1 parent 22017ff commit ffe6ff3

File tree

3 files changed

+41
-5
lines changed

3 files changed

+41
-5
lines changed

vlib/v/gen/c/fn.v

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -910,12 +910,13 @@ fn (mut g Gen) method_call(node ast.CallExpr) {
910910
g.gen_expr_to_string(node.left, rec_type)
911911
return
912912
} else if node.left.obj.smartcasts.len > 0 {
913-
cast_sym := g.table.sym(node.left.obj.smartcasts.last())
913+
rec_type = node.left.obj.smartcasts.last()
914+
cast_sym := g.table.sym(rec_type)
914915
if cast_sym.info is ast.Aggregate {
915916
rec_type = cast_sym.info.types[g.aggregate_type_idx]
916-
g.gen_expr_to_string(node.left, rec_type)
917-
return
918917
}
918+
g.gen_expr_to_string(node.left, rec_type)
919+
return
919920
}
920921
}
921922
}
@@ -1297,7 +1298,8 @@ fn (mut g Gen) fn_call(node ast.CallExpr) {
12971298
if expr.obj is ast.Var {
12981299
typ = expr.obj.typ
12991300
if expr.obj.smartcasts.len > 0 {
1300-
cast_sym := g.table.sym(expr.obj.smartcasts.last())
1301+
typ = expr.obj.smartcasts.last()
1302+
cast_sym := g.table.sym(typ)
13011303
if cast_sym.info is ast.Aggregate {
13021304
typ = cast_sym.info.types[g.aggregate_type_idx]
13031305
}

vlib/v/gen/c/str_intp.v

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,8 @@ fn (mut g Gen) str_val(node ast.StringInterLiteral, i int) {
156156
if g.comptime_var_type_map.len > 0 || g.comptime_for_method.len > 0 {
157157
exp_typ = expr.obj.typ
158158
} else if expr.obj.smartcasts.len > 0 {
159-
cast_sym := g.table.sym(expr.obj.smartcasts.last())
159+
exp_typ = expr.obj.smartcasts.last()
160+
cast_sym := g.table.sym(exp_typ)
160161
if cast_sym.info is ast.Aggregate {
161162
exp_typ = cast_sym.info.types[g.aggregate_type_idx]
162163
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
struct Point {
2+
x int
3+
y int
4+
}
5+
6+
struct Line {
7+
p1 Point
8+
p2 Point
9+
}
10+
11+
// Sum type
12+
type ObjSumType = Line | Point
13+
14+
fn test_print_smartcast_variable() {
15+
// Type checking and casts
16+
mut point := ObjSumType(Point{2, 5})
17+
18+
if point is Point {
19+
println('Point')
20+
}
21+
22+
if point !is Point {
23+
println('Not Point')
24+
}
25+
26+
if mut point is Point {
27+
println(point)
28+
assert point.str().contains('x: 2')
29+
assert point.str().contains('y: 5')
30+
assert '$point'.contains('x: 2')
31+
assert '$point'.contains('y: 5')
32+
}
33+
}

0 commit comments

Comments
 (0)