checker: add option type inference on if expr (implement most of #23827, except the error for v := if c { none } else { none }) (#23829)

This commit is contained in:
Felipe Pena 2025-02-28 17:36:28 -03:00 committed by GitHub
parent 80477e3acf
commit 8dbde185ef
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 17 additions and 0 deletions

View File

@ -510,6 +510,15 @@ fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type {
stmt.typ = ast.error_type
continue
}
if (node.typ == ast.none_type && stmt.typ != ast.none_type)
|| (stmt.typ == ast.none_type && node.typ != ast.none_type) {
node.typ = if stmt.typ != ast.none_type {
stmt.typ.set_flag(.option)
} else {
node.typ.set_flag(.option)
}
continue
}
c.error('mismatched types `${c.table.type_to_str(node.typ)}` and `${c.table.type_to_str(stmt.typ)}`',
node.pos)
} else {

View File

@ -0,0 +1,8 @@
fn test_main() {
v := if true { none } else { 1 }
assert '${v}' == 'Option(none)'
v2 := if false { 1 } else { none }
assert '${v2}' == 'Option(none)'
v3 := if true { 1 } else { none }
assert '${v3}' == 'Option(1)'
}