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

cgen: fix generic json bug (#6731)

This commit is contained in:
Daniel Däschle 2020-11-04 09:21:30 +01:00 committed by GitHub
parent cc4bb71f29
commit 25912673a9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 4 deletions

View File

@ -29,6 +29,18 @@ fn test_simple() {
assert y.title == .worker
}
fn bar<T>(payload string) ?Bar { // ?T doesn't work currently
result := json.decode(T, payload)?
return result
}
struct Bar {
x string
}
fn test_generic() {
result := bar<Bar>('{"x":"test"}') or { Bar{} }
assert result.x == 'test'
}
struct User2 {
age int
nums []int

View File

@ -19,10 +19,11 @@ import strings
// }
// Codegen json_decode/encode funcs
fn (mut g Gen) gen_json_for_type(typ table.Type) {
utyp := g.unwrap_generic(typ)
mut dec := strings.new_builder(100)
mut enc := strings.new_builder(100)
sym := g.table.get_type_symbol(typ)
styp := g.typ(typ)
sym := g.table.get_type_symbol(utyp)
styp := g.typ(utyp)
if is_js_prim(sym.name) || sym.kind == .enum_ {
return
}
@ -39,7 +40,7 @@ fn (mut g Gen) gen_json_for_type(typ table.Type) {
// Code gen decoder
dec_fn_name := js_dec_name(styp)
// Make sure that this optional type actually exists
g.register_optional(typ)
g.register_optional(utyp)
dec_fn_dec := 'Option_$styp ${dec_fn_name}(cJSON* root)'
dec.writeln('
//Option_$styp ${dec_fn_name}(cJSON* root, $styp* res) {
@ -66,7 +67,7 @@ $enc_fn_dec {
\tcJSON *o;')
if sym.kind == .array {
// Handle arrays
value_type := g.table.value_type(typ)
value_type := g.table.value_type(utyp)
// If we have `[]Profile`, have to register a Profile en(de)coder first
g.gen_json_for_type(value_type)
dec.writeln(g.decode_array(value_type))