Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

checker, json: return error on invalid string input instead of empty string result #21184

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion vlib/v/checker/fn.v
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions vlib/v/checker/tests/json_decode_invalid_string.out
Original file line number Diff line number Diff line change
@@ -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"}')!
| ~~~~~~~~~~~~~~~~~~~~~
10 changes: 10 additions & 0 deletions vlib/v/checker/tests/json_decode_invalid_string.vv
Original file line number Diff line number Diff line change
@@ -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"}')!
Loading