Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cgen: fix comptime variant string interpolation #22368

Merged
merged 2 commits into from
Oct 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion vlib/v/gen/c/str_intp.v
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,9 @@ fn (mut g Gen) str_val(node ast.StringInterLiteral, i int, fmts []u8) {
} else if fmt == `s` || typ.has_flag(.variadic) {
mut exp_typ := typ
if expr is ast.Ident {
if expr.obj is ast.Var {
if g.comptime.get_ct_type_var(expr) == .smartcast {
exp_typ = g.comptime.get_comptime_var_type(expr)
} else if expr.obj is ast.Var {
if expr.obj.smartcasts.len > 0 {
exp_typ = g.unwrap_generic(expr.obj.smartcasts.last())
cast_sym := g.table.sym(exp_typ)
Expand Down
23 changes: 23 additions & 0 deletions vlib/v/tests/comptime/comptime_variant_interp_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
module main

struct Foo {
a int
}

type SumType = Foo | int | string

fn (v SumType) cast[T](val T) string {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hm, that seems complicated for what it is testing.
val is not used anywhere, and seems to have no relation to the bug.

Using fn cast(v SumType) string {, will make it clearer and simpler.

mut res := ''
$for variant_value in v.variants {
if v is variant_value {
println('v: ${v}')
res = 'v: ${v}'
println(res)
}
}
return res
}

fn test_main() {
assert SumType(1).cast[int](1) == 'v: 1'
}
Loading