Skip to content

Commit

Permalink
encoding/json: fix location for JSON syntax error
Browse files Browse the repository at this point in the history
The JSON decoder utilizes `parser.ParseExpr` to parse input data,
which could be a valid CUE expression but an invalid JSON.

Using the error position returned by `parser.ParseExpr` as output
may cause cue to either omit the position or report the wrong position

This change uses the offset returned by the JSON parser and
recalculate the position to ensure the reported position is accurate.

Fixes #3317

Change-Id: I019ab80c275d658f5773501d766ee9d03261ab58
Signed-off-by: haoqixu <[email protected]>
Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/1199094
Reviewed-by: Daniel Martí <[email protected]>
TryBot-Result: CUEcueckoo <[email protected]>
  • Loading branch information
haoqixu authored and mvdan committed Aug 8, 2024
1 parent 677ece8 commit 596a8c3
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
26 changes: 26 additions & 0 deletions cmd/cue/cmd/testdata/script/json_syntax_error.txtar
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
! exec cue export x1.json
stderr 'x1*.json:4:3'

! exec cue export x2.json
stderr 'x2.json:1:6'

! exec cue export x3.json
stderr 'x3.json:1:1'

! exec cue export x4.json
stderr 'x4.json:1:1'

-- x1.json --
{
"foo": true,
"bar": 2
"baz": false
}

-- x2.json --
"baz": false

-- x3.json --
baz: false

-- x4.json --
10 changes: 10 additions & 0 deletions encoding/json/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,16 @@ func extract(path string, b []byte) (ast.Expr, error) {
}
var x interface{}
err := json.Unmarshal(b, &x)

if len(b) > 0 {
var synErr *json.SyntaxError
if errors.As(err, &synErr) {
tokFile := token.NewFile(path, 0, len(b))
tokFile.SetLinesForContent(b)
p = tokFile.Pos(int(synErr.Offset-1), token.NoRelPos)
}
}

return nil, errors.Wrapf(err, p, "invalid JSON for file %q", path)
}
return expr, nil
Expand Down

0 comments on commit 596a8c3

Please sign in to comment.