Skip to content

Commit aa90625

Browse files
authored
js: initial support for optional return unwrapping (#6926)
1 parent 7899122 commit aa90625

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

vlib/builtin/js/builtin.v

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,52 @@ pub fn exit(c int) {
3737
JS.process.exit(c)
3838
}
3939

40+
pub fn unwrap(opt any) any {
41+
o := &Option(opt)
42+
if o.not_ok {
43+
panic(o.error)
44+
return o.error
45+
}
46+
return opt
47+
}
48+
4049
pub fn panic(s string) {
4150
eprintln('V panic: $s')
4251
exit(1)
4352
}
53+
54+
55+
struct Option {
56+
not_ok bool
57+
is_none bool
58+
error string
59+
ecode int
60+
data any
61+
}
62+
63+
pub fn (o Option) str() string {
64+
if !o.not_ok {
65+
return 'Option{ ok }'
66+
}
67+
if o.is_none {
68+
return 'Option{ none }'
69+
}
70+
return 'Option{ error: "${o.error}" }'
71+
}
72+
73+
pub fn error(s string) Option {
74+
return Option{
75+
not_ok: true
76+
is_none: false
77+
error: s
78+
}
79+
}
80+
81+
pub fn error_with_code(s string, code int) Option {
82+
return Option{
83+
not_ok: true
84+
is_none: false
85+
error: s
86+
ecode: code
87+
}
88+
}

vlib/v/gen/js/js.v

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1175,6 +1175,10 @@ fn (mut g JsGen) gen_call_expr(it ast.CallExpr) {
11751175
} else {
11761176
name = g.js_name(it.name)
11771177
}
1178+
call_return_is_optional := it.return_type.has_flag(.optional)
1179+
if call_return_is_optional {
1180+
g.write('builtin.unwrap(')
1181+
}
11781182
g.expr(it.left)
11791183
if it.is_method { // foo.bar.baz()
11801184
sym := g.table.get_type_symbol(it.receiver_type)
@@ -1224,7 +1228,11 @@ fn (mut g JsGen) gen_call_expr(it ast.CallExpr) {
12241228
g.write(', ')
12251229
}
12261230
}
1227-
g.write(')')
1231+
if call_return_is_optional {
1232+
g.write('))')
1233+
} else {
1234+
g.write(')')
1235+
}
12281236
}
12291237

12301238
fn (mut g JsGen) gen_ident(node ast.Ident) {

0 commit comments

Comments
 (0)