diff --git a/vlib/builtin/option.v b/vlib/builtin/option.v index 2007a29623..17783296d5 100644 --- a/vlib/builtin/option.v +++ b/vlib/builtin/option.v @@ -7,6 +7,7 @@ module builtin struct Option { data [255]byte error string + ecode int ok bool is_none bool } @@ -34,4 +35,12 @@ pub fn error(s string) Option { } } +pub fn error_with_code(s string, code int) Option { + return Option { + error: s + ecode: code + } +} + + diff --git a/vlib/compiler/gen_c.v b/vlib/compiler/gen_c.v index 708ef60516..62a2922790 100644 --- a/vlib/compiler/gen_c.v +++ b/vlib/compiler/gen_c.v @@ -42,7 +42,14 @@ fn (p mut Parser) gen_var_decl(name string, is_static bool) string { is_mut: false is_used: true }) + p.register_var(Var { + name: 'errcode' + typ: 'int' + is_mut: false + is_used: true + }) p.genln('string err = $tmp . error;') + p.genln('int errcode = $tmp . ecode;') p.statements() p.genln('$typ $name = *($typ*) $tmp . data;') if !p.returns && p.prev_tok2 != .key_continue && p.prev_tok2 != .key_break { @@ -114,7 +121,14 @@ fn (p mut Parser) gen_blank_identifier_assign() { is_mut: false is_used: true }) + p.register_var(Var { + name: 'errcode' + typ: 'int' + is_mut: false + is_used: true + }) p.genln('string err = $tmp . error;') + p.genln('int errcode = $tmp . ecode;') p.statements() p.returns = false } else { diff --git a/vlib/compiler/tests/option_test.v b/vlib/compiler/tests/option_test.v index c288340f9d..a661fbe369 100644 --- a/vlib/compiler/tests/option_test.v +++ b/vlib/compiler/tests/option_test.v @@ -1,3 +1,15 @@ + +fn opt_err_with_code() ?string {return error_with_code('hi',137)} +fn test_err_with_code(){ + v := opt_err_with_code() or { + assert err == 'hi' + assert errcode == 137 + return + } + assert false + println(v) // suppress not used error +} + fn opt_err() ?string {return error('hi')} fn test_err(){