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

json: fix ptr field access (#17690)

This commit is contained in:
Felipe Pena 2023-03-18 09:47:40 -03:00 committed by GitHub
parent aee76c5819
commit 2df23a6698
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 51 additions and 5 deletions

View File

@ -0,0 +1,42 @@
module main
import json
pub enum PlatformType {
unknown
osx
ubuntu
alpine
}
pub enum CPUType {
unknown
intel
arm
intel32
arm32
}
[heap]
pub struct Node {
pub:
name string = 'mymachine'
pub mut:
platform PlatformType
cputype CPUType
done map[string]string
environment map[string]string
}
pub fn (mut node Node) save() ! {
data := json.encode(node)
dump(data)
}
fn test_encode_with_mut_struct() {
mut n := Node{
platform: .osx
cputype: .unknown
}
n.save() or { panic(err) }
}

View File

@ -520,21 +520,25 @@ fn (mut g Gen) gen_struct_enc_dec(utyp ast.Type, type_info ast.TypeInfo, styp st
}
}
if field_sym.kind == .enum_ {
enc.writeln('\tcJSON_AddItemToObject(o, "${name}", json__encode_u64(${prefix_enc}.${c_name(field.name)}));\n')
enc.writeln('\tcJSON_AddItemToObject(o, "${name}", json__encode_u64(${prefix_enc}${op}${c_name(field.name)}));\n')
} else {
if field_sym.name == 'time.Time' {
// time struct requires special treatment
// it has to be encoded as a unix timestamp number
enc.writeln('\tcJSON_AddItemToObject(o, "${name}", json__encode_u64(${prefix_enc}.${c_name(field.name)}._v_unix));')
enc.writeln('\tcJSON_AddItemToObject(o, "${name}", json__encode_u64(${prefix_enc}${op}${c_name(field.name)}._v_unix));')
} else {
if !field.typ.is_real_pointer() {
enc.writeln('\tcJSON_AddItemToObject(o, "${name}", ${enc_name}(${prefix_enc}${op}${c_name(field.name)})); /*A*/')
} else {
arg_prefix := if field.typ.is_ptr() { '' } else { '*' }
sptr_value := '${prefix_enc}${op}${c_name(field.name)}'
enc.writeln('\tif (${sptr_value} != 0) {')
enc.writeln('\t\tcJSON_AddItemToObject(o, "${name}", ${enc_name}(${arg_prefix}${sptr_value}));')
enc.writeln('\t}\n')
if !field.typ.has_flag(.option) {
enc.writeln('\tif (${sptr_value} != 0) {')
enc.writeln('\t\tcJSON_AddItemToObject(o, "${name}", ${enc_name}(${arg_prefix}${sptr_value}));')
enc.writeln('\t}\n')
} else {
enc.writeln('\t\tcJSON_AddItemToObject(o, "${name}", ${enc_name}(${arg_prefix}${sptr_value}));')
}
}
}
}