From 40120bce701e1cb45f2ad637ec37d976e0c4b979 Mon Sep 17 00:00:00 2001 From: John Hawthorn Date: Mon, 19 Sep 2022 17:56:19 -0700 Subject: [PATCH] Fix "unexpected token" offset for Infinity Previously in the JSON::Ext parser, when we encountered an "Infinity" token (and weren't allowing NaN/Infinity) we would try to display the "unexpected token" at the character before. --- ext/json/ext/parser/parser.c | 2 +- ext/json/ext/parser/parser.rl | 2 +- tests/json_ext_parser_test.rb | 17 +++++++++++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/ext/json/ext/parser/parser.c b/ext/json/ext/parser/parser.c index 9bd7f1971..71f59f095 100644 --- a/ext/json/ext/parser/parser.c +++ b/ext/json/ext/parser/parser.c @@ -990,7 +990,7 @@ static char *JSON_parse_value(JSON_Parser *json, char *p, char *pe, VALUE *resul if (json->allow_nan) { *result = CInfinity; } else { - rb_enc_raise(EXC_ENCODING eParserError, "unexpected token at '%s'", p - 8); + rb_enc_raise(EXC_ENCODING eParserError, "unexpected token at '%s'", p - 7); } } diff --git a/ext/json/ext/parser/parser.rl b/ext/json/ext/parser/parser.rl index 2dbdc7ef2..aafafc153 100644 --- a/ext/json/ext/parser/parser.rl +++ b/ext/json/ext/parser/parser.rl @@ -229,7 +229,7 @@ static char *JSON_parse_object(JSON_Parser *json, char *p, char *pe, VALUE *resu if (json->allow_nan) { *result = CInfinity; } else { - rb_enc_raise(EXC_ENCODING eParserError, "unexpected token at '%s'", p - 8); + rb_enc_raise(EXC_ENCODING eParserError, "unexpected token at '%s'", p - 7); } } action parse_string { diff --git a/tests/json_ext_parser_test.rb b/tests/json_ext_parser_test.rb index c5a030ea8..9815c41a3 100644 --- a/tests/json_ext_parser_test.rb +++ b/tests/json_ext_parser_test.rb @@ -3,6 +3,8 @@ class JSONExtParserTest < Test::Unit::TestCase if defined?(JSON::Ext::Parser) + include JSON + def test_allocate parser = JSON::Ext::Parser.new("{}") assert_raise(TypeError, '[ruby-core:35079]') do @@ -11,5 +13,20 @@ def test_allocate parser = JSON::Ext::Parser.allocate assert_raise(TypeError, '[ruby-core:35079]') { parser.source } end + + def test_error_messages + ex = assert_raise(ParserError) { parse('Infinity') } + assert_equal "unexpected token at 'Infinity'", ex.message + + ex = assert_raise(ParserError) { parse('-Infinity') } + assert_equal "unexpected token at 'Infinity'", ex.message + + ex = assert_raise(ParserError) { parse('NaN') } + assert_equal "unexpected token at 'NaN'", ex.message + end + + def parse(json) + JSON::Ext::Parser.new(json).parse + end end end