diff --git a/vlib/v/checker/fn.v b/vlib/v/checker/fn.v index 1677877f58ad38..5b20afe9f527e5 100644 --- a/vlib/v/checker/fn.v +++ b/vlib/v/checker/fn.v @@ -794,7 +794,20 @@ fn (mut c Checker) fn_call(mut node ast.CallExpr, mut continue_check &bool) ast. } c.expected_type = ast.string_type node.args[1].typ = c.expr(mut node.args[1].expr) - if node.args[1].typ != ast.string_type { + if node.args[1].typ == ast.string_type { + if node.args[1].expr is ast.StringLiteral { + str_arg := node.args[1].expr + if str_arg.val.len > 2 && str_arg.val[0] != `{` && str_arg.val[0] != `[` { + c.error('json.decode: invalid json string', str_arg.pos) + } + } else if node.args[1].expr is ast.Ident && node.args[1].expr.obj is ast.Var { + str_var := (node.args[1].expr.obj as ast.Var).expr + str_var_val := str_var.str() + if str_var_val.len > 2 && str_var_val[1] != `{` && str_var_val[1] != `[` { + c.error('json.decode: invalid json string', str_var.pos()) + } + } + } else { c.error('json.decode: second argument needs to be a string', node.pos) } typ := expr as ast.TypeNode diff --git a/vlib/v/checker/tests/json_decode_invalid_string.out b/vlib/v/checker/tests/json_decode_invalid_string.out new file mode 100644 index 00000000000000..2499e82b7ef898 --- /dev/null +++ b/vlib/v/checker/tests/json_decode_invalid_string.out @@ -0,0 +1,12 @@ +vlib/v/checker/tests/json_decode_invalid_string.vv:7:8: error: json.decode: invalid json string + 5 | } + 6 | + 7 | txt := '"{"host": "localhost"}' + | ~~~~~~~~~~~~~~~~~~~~~~~~ + 8 | json.decode(TestStruct, txt)! + 9 | json.decode(TestStruct, txt.trim_string_right('"'))! +vlib/v/checker/tests/json_decode_invalid_string.vv:10:25: error: json.decode: invalid json string + 8 | json.decode(TestStruct, txt)! + 9 | json.decode(TestStruct, txt.trim_string_right('"'))! + 10 | json.decode(TestStruct, 'h{ost: "localhost"}')! + | ~~~~~~~~~~~~~~~~~~~~~ diff --git a/vlib/v/checker/tests/json_decode_invalid_string.vv b/vlib/v/checker/tests/json_decode_invalid_string.vv new file mode 100644 index 00000000000000..646767ef254ca8 --- /dev/null +++ b/vlib/v/checker/tests/json_decode_invalid_string.vv @@ -0,0 +1,10 @@ +import json + +struct TestStruct { + host string +} + +txt := '"{"host": "localhost"}' +json.decode(TestStruct, txt)! +json.decode(TestStruct, txt.trim_string_right('"'))! +json.decode(TestStruct, 'h{ost: "localhost"}')!