Skip to content

Commit 82b6b21

Browse files
mamebyroot
andcommitted
Fix off-by-one line number in parse error messages
cursor_position consumed the newline ending the previous line (post-decrement) before counting lines, so any error past the first line was reported one line too low (e.g. "[1,\n@" reported '@' at line 1 instead of line 2). Count that newline when the column loop breaks on it. Co-Authored-By: Jean Boussier <jean.boussier@gmail.com>
1 parent 56d16de commit 82b6b21

2 files changed

Lines changed: 11 additions & 1 deletion

File tree

ext/json/ext/parser/parser.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -593,6 +593,7 @@ static void cursor_position(JSON_ParserState *state, long *line_out, long *colum
593593

594594
while (cursor >= state->start) {
595595
if (*cursor-- == '\n') {
596+
line++;
596597
break;
597598
}
598599
column++;

test/json/json_parser_test.rb

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -862,7 +862,7 @@ def test_parse_error_incomplete_hash
862862
end
863863

864864
def test_parse_error_snippet
865-
omit "C ext only test" unless RUBY_ENGINE == "ruby"
865+
omit "JRuby errors don't contain positions" unless RUBY_ENGINE == "ruby"
866866

867867
error = assert_raise(JSON::ParserError) { JSON.parse("あああああああああああああああああああああああ") }
868868
assert_equal "unexpected character: 'ああああああああああ' at line 1 column 1", error.message
@@ -875,6 +875,15 @@ def test_parse_error_snippet
875875

876876
error = assert_raise(JSON::ParserError) { JSON.parse("abcあああああああああああああああああああああああ") }
877877
assert_equal "unexpected character: 'abcあああああああああ' at line 1 column 1", error.message
878+
879+
error = assert_raise(JSON::ParserError) { JSON.parse("[1,\n@") }
880+
assert_equal "unexpected character: '@' at line 2 column 1", error.message
881+
882+
error = assert_raise(JSON::ParserError) { JSON.parse("[\n 1,\n @\n]") }
883+
assert_equal "unexpected character: '@' at line 3 column 3", error.message
884+
885+
error = assert_raise(JSON::ParserError) { JSON.parse("@") }
886+
assert_equal "unexpected character: '@' at line 1 column 1", error.message
878887
end
879888

880889
def test_parse_leading_slash

0 commit comments

Comments
 (0)