Skip to content

Commit

Permalink
checker: fix sumtype cast of comptime var (#17287)
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp committed Feb 13, 2023
1 parent fbcb1f3 commit 16344cf
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
14 changes: 14 additions & 0 deletions vlib/v/checker/checker.v
Original file line number Diff line number Diff line change
Expand Up @@ -2688,12 +2688,26 @@ pub fn (mut c Checker) expr(node_ ast.Expr) ast.Type {
// return ast.void_type
// }

fn (mut c Checker) get_comptime_selector_type(node ast.ComptimeSelector, default_type ast.Type) ast.Type {
if node.field_expr is ast.SelectorExpr
&& c.check_comptime_is_field_selector(node.field_expr as ast.SelectorExpr)
&& (node.field_expr as ast.SelectorExpr).field_name == 'name' {
return c.comptime_fields_default_type
}
return default_type
}

fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type {
// Given: `Outside( Inside(xyz) )`,
// node.expr_type: `Inside`
// node.typ: `Outside`
node.expr_type = c.expr(node.expr) // type to be casted

if node.expr is ast.ComptimeSelector {
node.expr_type = c.get_comptime_selector_type(node.expr as ast.ComptimeSelector,
node.expr_type)
}

mut from_type := c.unwrap_generic(node.expr_type)
from_sym := c.table.sym(from_type)
final_from_sym := c.table.final_sym(from_type)
Expand Down
29 changes: 29 additions & 0 deletions vlib/v/tests/comptime_sumtype_cast_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
pub type Any = bool | int | map[string]Any | string

struct StructType {
mut:
val string
}

fn test_main() {
struct_to_map_string()
}

fn map_from[T](t T) {
$if T is $Struct {
$for field in T.fields {
assert Any('string').str() == "Any('string')"
assert t.$(field.name).str() == 'true'
a := t.$(field.name)
assert Any(a).str() == "Any('true')"
assert Any(t.$(field.name)).str() == "Any('true')"
}
}
}

fn struct_to_map_string() {
struct_type := StructType{
val: 'true'
}
map_from(struct_type)
}

0 comments on commit 16344cf

Please sign in to comment.