cgen: fix generic json bug (#6731)

pull/6736/head
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 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 { struct User2 {
age int age int
nums []int nums []int

View File

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