cgen: fix error for print smartcast variable (#13634)

pull/13635/head
yuyi 2022-03-02 18:32:54 +08:00 committed by GitHub
parent 22017ff8f4
commit ffe6ff3cc8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 41 additions and 5 deletions

View File

@ -910,15 +910,16 @@ 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.get_str_fn(rec_type)
} else if node.name == 'free' {
mut rec_type := node.receiver_type
@ -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]
}

View File

@ -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]
}

View File

@ -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')
}
}