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

Conversation

felipensp
Copy link
Member

@felipensp felipensp commented Dec 25, 2023

Fix #20176

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 main() {
    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
}

@felipensp felipensp marked this pull request as ready for review December 29, 2023 14:02
@@ -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?

Copy link
Member

@spytheman spytheman left a comment

Choose a reason for hiding this comment

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

Excellent work!

@spytheman spytheman merged commit cb525f0 into vlang:master Dec 29, 2023
54 checks passed
@felipensp felipensp deleted the smartcast_comptime branch December 29, 2023 19:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

compiler: support for $for G in field_value.$variants { and $if field_value is G {
2 participants