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

v: smartcast comptime variable #20270

Merged
merged 6 commits into from
Dec 29, 2023
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
1 change: 1 addition & 0 deletions vlib/v/ast/ast.v
Original file line number Diff line number Diff line change
Expand Up @@ -804,6 +804,7 @@ pub enum ComptimeVarKind {
value_var // map value from `for k,v in t.$(field.name)`
field_var // comptime field var `a := t.$(field.name)`
generic_param // generic fn parameter
smartcast // smart cast when used in `is v` (when `v` is from $for .variants)
}

@[minify]
Expand Down
9 changes: 8 additions & 1 deletion vlib/v/checker/checker.v
Original file line number Diff line number Diff line change
Expand Up @@ -3843,6 +3843,7 @@ fn (mut c Checker) smartcast(mut expr ast.Expr, cur_type ast.Type, to_type_ ast.
mut is_already_casted := false
mut orig_type := 0
mut is_inherited := false
mut ct_type_var := ast.ComptimeVarKind.no_comptime
if mut expr.obj is ast.Var {
is_mut = expr.obj.is_mut
smartcasts << expr.obj.smartcasts
Expand All @@ -3851,19 +3852,25 @@ fn (mut c Checker) smartcast(mut expr ast.Expr, cur_type ast.Type, to_type_ ast.
orig_type = expr.obj.typ
}
is_inherited = expr.obj.is_inherited
ct_type_var = if expr.obj.ct_type_var == .field_var {
.smartcast
} else {
.no_comptime
}
}
// smartcast either if the value is immutable or if the mut argument is explicitly given
if (!is_mut || expr.is_mut) && !is_already_casted {
smartcasts << to_type
scope.register(ast.Var{
name: expr.name
typ: cur_type
typ: if ct_type_var == .smartcast { to_type } else { cur_type }
pos: expr.pos
is_used: true
is_mut: expr.is_mut
is_inherited: is_inherited
smartcasts: smartcasts
orig_type: orig_type
ct_type_var: ct_type_var
})
} else if is_mut && !expr.is_mut {
c.smartcast_mut_pos = expr.pos
Expand Down
18 changes: 15 additions & 3 deletions vlib/v/checker/if.v
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,6 @@ fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type {
if sym.kind == .placeholder || got_type.has_flag(.generic) {
c.error('unknown type `${sym.name}`', branch.cond.right.pos())
}

if left is ast.SelectorExpr {
comptime_field_name = left.expr.str()
c.comptime.type_map[comptime_field_name] = got_type
Expand Down Expand Up @@ -519,6 +518,9 @@ fn (mut c Checker) smartcast_if_conds(mut node ast.Expr, mut scope ast.Scope) {
c.smartcast(mut node.left, node.left_type, node.left_type.clear_flag(.option), mut
scope)
} else if node.op == .key_is {
if node.left_type == ast.Type(0) {
spytheman marked this conversation as resolved.
Show resolved Hide resolved
node.left_type = c.expr(mut node.left)
}
right_expr := node.right
right_type := match right_expr {
ast.TypeNode {
Expand All @@ -527,15 +529,24 @@ fn (mut c Checker) smartcast_if_conds(mut node ast.Expr, mut scope ast.Scope) {
ast.None {
ast.none_type_idx
}
ast.Ident {
if right_expr.name == c.comptime.comptime_for_variant_var {
println(c.comptime.type_map['${c.comptime.comptime_for_variant_var}.typ'])
Copy link
Member

Choose a reason for hiding this comment

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

comment/remove this?

c.comptime.type_map['${c.comptime.comptime_for_variant_var}.typ']
} else {
c.error('invalid type `${right_expr}`', right_expr.pos)
ast.Type(0)
}
}
else {
c.error('invalid type `${right_expr}`', right_expr.pos())
ast.Type(0)
}
}
if right_type != ast.Type(0) {
left_sym := c.table.sym(node.left_type)
right_sym := c.table.sym(right_type)
mut expr_type := c.expr(mut node.left)
left_sym := c.table.sym(expr_type)
if left_sym.kind == .aggregate {
expr_type = (left_sym.info as ast.Aggregate).sum_type
}
Expand All @@ -548,7 +559,8 @@ fn (mut c Checker) smartcast_if_conds(mut node ast.Expr, mut scope ast.Scope) {
expr_str := c.table.type_to_str(expr_type)
c.error('cannot use type `${expect_str}` as type `${expr_str}`', node.pos)
}
if node.left in [ast.Ident, ast.SelectorExpr] && node.right is ast.TypeNode {
if node.left in [ast.Ident, ast.SelectorExpr]
&& node.right in [ast.ComptimeType, ast.TypeNode, ast.Ident] {
is_variable := if mut node.left is ast.Ident {
node.left.kind == .variable
} else {
Expand Down
8 changes: 8 additions & 0 deletions vlib/v/checker/infix.v
Original file line number Diff line number Diff line change
Expand Up @@ -648,6 +648,14 @@ fn (mut c Checker) infix_expr(mut node ast.InfixExpr) ast.Type {
ast.None {
ast.none_type_idx
}
ast.Ident {
if right_expr.name == c.comptime.comptime_for_variant_var {
c.comptime.type_map['${c.comptime.comptime_for_variant_var}.typ']
} else {
c.error('invalid type `${right_expr}`', right_expr.pos)
ast.Type(0)
}
}
else {
c.error('invalid type `${right_expr}`', right_expr.pos())
ast.Type(0)
Expand Down
3 changes: 3 additions & 0 deletions vlib/v/comptime/comptimeinfo.v
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ pub fn (mut ct ComptimeInfo) get_comptime_var_type(node ast.Expr) ast.Type {
// generic parameter from current function
node.obj.typ
}
.smartcast {
ct.type_map['${ct.comptime_for_variant_var}.typ'] or { ast.void_type }
}
.key_var, .value_var {
// key and value variables from normal for stmt
ct.type_map[node.name] or { ast.void_type }
Expand Down
12 changes: 9 additions & 3 deletions vlib/v/gen/c/cgen.v
Original file line number Diff line number Diff line change
Expand Up @@ -4402,7 +4402,8 @@ fn (mut g Gen) ident(node ast.Ident) {
mut is_option := false
if node.info is ast.IdentVar {
if node.obj is ast.Var {
if !g.is_assign_lhs && node.obj.ct_type_var !in [.generic_param, .no_comptime] {
if !g.is_assign_lhs
&& node.obj.ct_type_var !in [.smartcast, .generic_param, .no_comptime] {
comptime_type := g.comptime.get_comptime_var_type(node)
if comptime_type.has_flag(.option) {
if (g.inside_opt_or_res || g.left_is_opt) && node.or_expr.kind == .absent {
Expand Down Expand Up @@ -4508,7 +4509,8 @@ fn (mut g Gen) ident(node ast.Ident) {
} else {
g.write('*')
}
} else if g.inside_interface_deref && g.table.is_interface_var(node.obj) {
} else if (g.inside_interface_deref && g.table.is_interface_var(node.obj))
|| node.obj.ct_type_var == .smartcast {
g.write('*')
} else if is_option {
g.write('*(${g.base_type(node.obj.typ)}*)')
Expand Down Expand Up @@ -4542,7 +4544,11 @@ fn (mut g Gen) ident(node ast.Ident) {
g.write(')')
}
}
if !is_option_unwrap && obj_sym.kind in [.sum_type, .interface_] {
if node.obj.ct_type_var == .smartcast {
cur_variant_sym := g.table.sym(g.comptime.type_map['${g.comptime.comptime_for_variant_var}.typ'])
g.write('${dot}_${cur_variant_sym.cname}')
} else if !is_option_unwrap
&& obj_sym.kind in [.sum_type, .interface_] {
g.write('${dot}_${cast_sym.cname}')
}
}
Expand Down
8 changes: 6 additions & 2 deletions vlib/v/gen/c/comptime.v
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,11 @@ fn (mut g Gen) comptime_if(node ast.IfExpr) {
fn (mut g Gen) get_expr_type(cond ast.Expr) ast.Type {
match cond {
ast.Ident {
return g.unwrap_generic(cond.obj.typ)
return if g.comptime.is_comptime_var(cond) {
g.unwrap_generic(g.comptime.get_comptime_var_type(cond))
} else {
g.unwrap_generic(cond.obj.typ)
}
}
ast.TypeNode {
return g.unwrap_generic(cond.typ)
Expand Down Expand Up @@ -922,7 +926,7 @@ fn (mut g Gen) comptime_for(node ast.ComptimeFor) {
g.comptime.inside_comptime_for = true
g.push_new_comptime_info()
for variant in sym.info.variants {
g.comptime.comptime_for_field_var = node.val_var
g.comptime.comptime_for_variant_var = node.val_var
g.comptime.type_map['${node.val_var}.typ'] = variant

g.writeln('/* variant ${i} */ {')
Expand Down
5 changes: 5 additions & 0 deletions vlib/v/gen/c/infix.v
Original file line number Diff line number Diff line change
Expand Up @@ -720,6 +720,11 @@ fn (mut g Gen) infix_expr_is_op(node ast.InfixExpr) {
}
if node.right is ast.None {
g.write('${ast.none_type.idx()} /* none */')
} else if node.right is ast.Ident && node.right.name == g.comptime.comptime_for_variant_var {
variant_idx := g.comptime.type_map['${g.comptime.comptime_for_variant_var}.typ'] or {
ast.void_type
}
g.write('${variant_idx.idx()}')
} else {
g.expr(node.right)
}
Expand Down
1 change: 1 addition & 0 deletions vlib/v/parser/parse_type.v
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,7 @@ fn (mut p Parser) parse_sum_type_variants() []ast.TypeNode {
pos: type_pos
end_comments: end_comments
}

if p.tok.kind != .pipe {
break
}
Expand Down
16 changes: 11 additions & 5 deletions vlib/v/parser/parser.v
Original file line number Diff line number Diff line change
Expand Up @@ -2536,11 +2536,17 @@ fn (mut p Parser) name_expr() ast.Expr {
}
p.expecting_type = false
// get type position before moving to next
type_pos := p.tok.pos()
typ := p.parse_type()
return ast.TypeNode{
typ: typ
pos: type_pos
is_known_var := p.scope.known_var(p.tok.lit)
if is_known_var {
p.mark_var_as_used(p.tok.lit)
return p.ident(ast.Language.v)
} else {
type_pos := p.tok.pos()
typ := p.parse_type()
return ast.TypeNode{
typ: typ
pos: type_pos
}
}
}
language := match p.tok.lit {
Expand Down
45 changes: 45 additions & 0 deletions vlib/v/tests/comptime_smartcast_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
type TestSum = int | string

struct Abc {
s TestSum
}

fn gen[T, R](struc T) R {
$if T is $struct {
$for field in T.fields {
field_value := struc.$(field.name)
$if field_value is $sumtype {
$for v in field_value.variants {
if field_value is v { // smartcast
$if field_value is R {
dump(field_value)
return field_value
}
}
}
}
}
}
return R{}
}

fn test_int() {
a := Abc{TestSum(123)}
int_var := gen[Abc, int](a)
assert dump(int_var) == 123
}

fn test_str() {
b := Abc{TestSum('foo')}
str_var := gen[Abc, string](b)
assert dump(str_var) == 'foo'
}

fn test_both() {
a := Abc{TestSum(123)}
b := Abc{TestSum('foo')}
int_var := gen[Abc, int](a)
str_var := gen[Abc, string](b)
assert dump(str_var) == 'foo'
assert dump(int_var) == 123
}
Loading