From 2f57f40467e09e74f8375142f228afa186e43850 Mon Sep 17 00:00:00 2001 From: tompng Date: Mon, 20 Jan 2025 20:44:37 +0900 Subject: [PATCH] Raise parse error on invalid comments --- ext/json/ext/parser/parser.c | 14 +++++++------- test/json/json_parser_test.rb | 5 +++++ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/ext/json/ext/parser/parser.c b/ext/json/ext/parser/parser.c index 907bd047..4e28e6ef 100644 --- a/ext/json/ext/parser/parser.c +++ b/ext/json/ext/parser/parser.c @@ -476,7 +476,7 @@ static const bool whitespace[256] = { ['/'] = 1, }; -static bool +static void json_eat_comments(JSON_ParserState *state) { if (state->cursor + 1 < state->end) { @@ -496,7 +496,7 @@ json_eat_comments(JSON_ParserState *state) state->cursor = memchr(state->cursor, '*', state->end - state->cursor); if (!state->cursor) { state->cursor = state->end; - break; + raise_parse_error("unexpected end of input, expected closing '*/'", state->cursor); } else { state->cursor++; if (state->cursor < state->end && *state->cursor == '/') { @@ -508,10 +508,12 @@ json_eat_comments(JSON_ParserState *state) break; } default: - return false; + raise_parse_error("unexpected token at '%s'", state->cursor); + break; } + } else { + raise_parse_error("unexpected token at '%s'", state->cursor); } - return true; } static inline void @@ -521,9 +523,7 @@ json_eat_whitespace(JSON_ParserState *state) if (RB_LIKELY(*state->cursor != '/')) { state->cursor++; } else { - if (!json_eat_comments(state)) { - return; - } + json_eat_comments(state); } } } diff --git a/test/json/json_parser_test.rb b/test/json/json_parser_test.rb index c5ce0232..b41c929f 100644 --- a/test/json/json_parser_test.rb +++ b/test/json/json_parser_test.rb @@ -398,6 +398,11 @@ def test_parse_comments } JSON assert_equal({ "key1" => "value1" }, parse(json)) + assert_equal({}, parse('{} /**/')) + assert_raise(ParserError) { parse('{} /* comment not closed') } + assert_raise(ParserError) { parse('{} /*/') } + assert_raise(ParserError) { parse('{} /x wrong comment') } + assert_raise(ParserError) { parse('{} /') } end def test_nesting