From 79c727f014166164e425faacb01fde38984320d2 Mon Sep 17 00:00:00 2001 From: teggot Date: Wed, 14 Aug 2019 17:38:28 +0300 Subject: [PATCH] Add support for raw json fields in structs --- compiler/jsgen.v | 33 ++++++++++++++++++++++----------- compiler/parser.v | 3 +++ 2 files changed, 25 insertions(+), 11 deletions(-) diff --git a/compiler/jsgen.v b/compiler/jsgen.v index 5923407a44..6d4329049e 100644 --- a/compiler/jsgen.v +++ b/compiler/jsgen.v @@ -85,22 +85,33 @@ string res = tos2(""); if field.attr == 'skip' { continue } + field_type := p.table.find_type(field.typ) - // Now generate decoders for all field types in this struct - // need to do it here so that these functions are generated first - p.gen_json_for_type(field_type) name := field.name _typ := field.typ.replace('*', '') + enc_name := js_enc_name(_typ) - dec_name := js_dec_name(_typ) - if is_js_prim(_typ) { - dec += ' /*prim*/ res->$name = $dec_name(js_get(root, "$field.name"))' - // dec += '.data' + + if field.attr == 'raw' { + dec += ' /*prim*/ res->$name = tos2(cJSON_PrintUnformatted(js_get(root, "$field.name")));\n' + + } else { + // Now generate decoders for all field types in this struct + // need to do it here so that these functions are generated first + p.gen_json_for_type(field_type) + + dec_name := js_dec_name(_typ) + + if is_js_prim(_typ) { + dec += ' /*prim*/ res->$name = $dec_name(js_get(root, "$field.name"))' + // dec += '.data' + } + else { + dec += ' /*!!*/ $dec_name(js_get(root, "$field.name"), & (res->$name))' + } + dec += ';\n' } - else { - dec += ' /*!!*/ $dec_name(js_get(root, "$field.name"), & (res->$name))' - } - dec += ';\n' + enc += ' cJSON_AddItemToObject(o, "$name", $enc_name(val.$name)); \n' } // cJSON_delete diff --git a/compiler/parser.v b/compiler/parser.v index 3bdd63efa0..45cb5e8253 100644 --- a/compiler/parser.v +++ b/compiler/parser.v @@ -645,6 +645,9 @@ fn (p mut Parser) struct_decl() { attr = p.check_name() p.check(.rsbr) } + if attr == 'raw' && field_type != 'string' { + p.error('struct field with attribute "raw" should be of type "string" but got "$field_type"') + } did_gen_something = true typ.add_field(field_name, field_type, is_mut, attr, access_mod)