json: fix encoding pointers

pull/7023/head
Alexander Medvednikov 2020-11-29 17:45:22 +01:00
parent adeebad2a6
commit c7cefa9ce6
3 changed files with 14 additions and 3 deletions

View File

@ -76,8 +76,12 @@ fn test_parse_user() {
assert u.pets == '{"name":"Bob","animal":"Dog"}' assert u.pets == '{"name":"Bob","animal":"Dog"}'
} }
fn (mut u User) foo() string {
return json.encode(u)
}
fn test_encode_user() { fn test_encode_user() {
usr := User{ mut usr := User{
age: 10 age: 10
nums: [1, 2, 3] nums: [1, 2, 3]
last_name: 'Johnson' last_name: 'Johnson'
@ -89,6 +93,8 @@ fn test_encode_user() {
out := json.encode(usr) out := json.encode(usr)
println(out) println(out)
assert out == expected assert out == expected
// Test json.encode on mutable pointers
assert usr.foo() == expected
} }
struct Color { struct Color {

View File

@ -483,10 +483,14 @@ fn (mut g Gen) fn_call(node ast.CallExpr) {
g.gen_json_for_type(node.args[0].typ) g.gen_json_for_type(node.args[0].typ)
json_type_str = g.typ(node.args[0].typ) json_type_str = g.typ(node.args[0].typ)
// `json__encode` => `json__encode_User` // `json__encode` => `json__encode_User`
encode_name := c_name(name) + '_' + util.no_dots(json_type_str) // encode_name := c_name(name) + '_' + util.no_dots(json_type_str)
encode_name := js_enc_name(json_type_str)
g.writeln('// json.encode') g.writeln('// json.encode')
g.write('cJSON* $json_obj = ${encode_name}(') g.write('cJSON* $json_obj = ${encode_name}(')
// g.call_args(node.args, node.expected_arg_types) // , []) // g.call_args(node.args, node.expected_arg_types) // , [])
if node.args[0].typ.is_ptr() {
g.write('*')
}
g.call_args(node) g.call_args(node)
g.writeln(');') g.writeln(');')
tmp2 = g.new_tmp_var() tmp2 = g.new_tmp_var()

View File

@ -139,7 +139,8 @@ $enc_fn_dec {
} }
fn js_enc_name(typ string) string { fn js_enc_name(typ string) string {
name := 'json__encode_$typ' suffix := if typ.ends_with('*') { typ.replace('*', '') } else { typ }
name := 'json__encode_$suffix'
return util.no_dots(name) return util.no_dots(name)
} }