1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

cgen: support for error('abc').str() and printing errors

This commit is contained in:
Delyan Angelov 2020-04-24 18:35:33 +03:00
parent 323ca2b3bb
commit c6a829ce82
3 changed files with 42 additions and 1 deletions

View File

@ -21,6 +21,16 @@ struct Option {
is_none bool
}
pub fn (o Option) str() string {
if o.ok && !o.is_none {
return 'Option{ data: ' + o.data[0..32].hex() + ' }'
}
if o.is_none {
return 'Option{ none }'
}
return 'Option{ error: "${o.error}" }'
}
// `fn foo() ?Foo { return foo }` => `fn foo() ?Foo { return opt_ok(foo); }`
fn opt_ok(data voidptr, size int) Option {
if size >= 400 {
@ -52,4 +62,3 @@ pub fn error_with_code(s string, code int) Option {
ecode: code
}
}

View File

@ -2315,6 +2315,8 @@ fn (mut g Gen) string_inter_literal(node ast.StringInterLiteral) {
g.write('%"PRId64"')
} else if node.expr_types[i] == table.u64_type {
g.write('%"PRIu64"')
} else if g.typ( node.expr_types[i] ).starts_with('Option') {
g.write('%.*s')
} else {
g.write('%"PRId32"')
}
@ -2405,6 +2407,15 @@ fn (mut g Gen) string_inter_literal(node ast.StringInterLiteral) {
g.write('${str_fn_name}(')
g.expr(expr)
g.write(',0).str')
} else if g.typ( node.expr_types[i] ).starts_with('Option') {
str_fn_name := 'Option_str'
g.write('${str_fn_name}((Option)')
g.expr(expr)
g.write(')')
g.write('.len, ')
g.write('${str_fn_name}((Option)')
g.expr(expr)
g.write(').str')
} else {
g.expr(expr)
}

View File

@ -0,0 +1,21 @@
fn test_error_can_be_converted_to_string(){
assert 'Option{ error: "an error" }' == error('an error').str()
}
fn test_error_can_be_assigned_to_a_variable(){
f := error('an error')
assert 'Option{ error: "an error" }' == f.str()
}
fn test_error_can_be_printed(){
f := error('an error')
println(f)
assert true
}
fn test_error_can_be_interpolated_in_a_string(){
f := error('an error')
s := 'hi $f'
assert s == 'hi Option{ error: "an error" }'
}