Skip to content

Commit

Permalink
add test
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp committed Nov 17, 2024
1 parent 10d4385 commit 919741d
Show file tree
Hide file tree
Showing 4 changed files with 82 additions and 3 deletions.
3 changes: 2 additions & 1 deletion vlib/v/checker/checker.v
Original file line number Diff line number Diff line change
Expand Up @@ -4204,7 +4204,8 @@ fn (mut c Checker) smartcast(mut expr ast.Expr, cur_type ast.Type, to_type_ ast.
smartcasts << field.smartcasts
}
// smartcast either if the value is immutable or if the mut argument is explicitly given
if !is_mut || expr.is_mut {
if !is_mut || expr.is_mut
|| (cur_type.has_flag(.option) && cur_type.clear_flag(.option) == to_type_) {
smartcasts << to_type
scope.register_struct_field(expr.expr.str(), ast.ScopeStructField{
struct_type: expr.expr_type
Expand Down
4 changes: 2 additions & 2 deletions vlib/v/gen/c/cgen.v
Original file line number Diff line number Diff line change
Expand Up @@ -4043,7 +4043,7 @@ fn (mut g Gen) selector_expr(node ast.SelectorExpr) {
}
for i, typ in field.smartcasts {
if i == 0 && is_option_unwrap {
g.write('*(${g.styp(typ)}*)')
g.write('(*(${g.styp(typ)}*)')
}
g.write('(')
if field_sym.kind == .sum_type && !is_option {
Expand Down Expand Up @@ -4203,7 +4203,7 @@ fn (mut g Gen) selector_expr(node ast.SelectorExpr) {
}
g.write(field_name)
if is_option_unwrap {
g.write('.data)')
g.write('.data))')
}
if sum_type_deref_field != '' {
g.write('${sum_type_dot}${sum_type_deref_field})')
Expand Down
31 changes: 31 additions & 0 deletions vlib/v/tests/options/option_selector_unwrap_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import datatypes { DoublyLinkedList }

pub type LayoutBoxId = usize

pub struct LayoutBox {
}

pub struct LayoutTree {
mut:
root ?LayoutBoxId
boxes []LayoutBox
}

pub fn LayoutTree.new() LayoutTree {
return LayoutTree{
root: ?LayoutBoxId(none)
boxes: []LayoutBox{}
}
}

fn test_main() {
mut tree := LayoutTree.new()
tree.root = 1
if tree.root != none {
mut parents := DoublyLinkedList[LayoutBoxId]{}
parents.push_back(tree.root)
assert parents.len == 1
} else {
assert false
}
}
47 changes: 47 additions & 0 deletions vlib/v/tests/options/option_selector_unwrap_types_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
type SumType = int | string

struct Struct {
a int
}

struct Foo {
a ?int
b ?string
c ?SumType
d ?Struct
}

fn test_main() {
w := Foo{
a: 123
b: 'foo'
c: SumType(123)
d: Struct{
a: 123
}
}
if w.a != none {
dump(w.a)
assert w.a == 123
} else {
assert false
}
if w.b != none {
dump(w.b)
assert w.b == 'foo'
} else {
assert false
}
if w.c != none {
dump(w.c)
assert w.c is int
} else {
assert false
}
if w.d != none {
dump(w.d)
assert w.d.a == 123
} else {
assert false
}
}

0 comments on commit 919741d

Please sign in to comment.