[ruby/json] Raise parse error on invalid comments

https://github.com/ruby/json/commit/2f57f40467
This commit is contained in:
tompng 2025-01-20 20:44:37 +09:00 committed by Jean Boussier
parent c026e44bb5
commit 525d7a68e4
Notes: git 2025-01-20 13:21:12 +00:00
2 changed files with 12 additions and 7 deletions

View File

@ -476,7 +476,7 @@ static const bool whitespace[256] = {
['/'] = 1, ['/'] = 1,
}; };
static bool static void
json_eat_comments(JSON_ParserState *state) json_eat_comments(JSON_ParserState *state)
{ {
if (state->cursor + 1 < state->end) { 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); state->cursor = memchr(state->cursor, '*', state->end - state->cursor);
if (!state->cursor) { if (!state->cursor) {
state->cursor = state->end; state->cursor = state->end;
break; raise_parse_error("unexpected end of input, expected closing '*/'", state->cursor);
} else { } else {
state->cursor++; state->cursor++;
if (state->cursor < state->end && *state->cursor == '/') { if (state->cursor < state->end && *state->cursor == '/') {
@ -508,10 +508,12 @@ json_eat_comments(JSON_ParserState *state)
break; break;
} }
default: 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 static inline void
@ -521,9 +523,7 @@ json_eat_whitespace(JSON_ParserState *state)
if (RB_LIKELY(*state->cursor != '/')) { if (RB_LIKELY(*state->cursor != '/')) {
state->cursor++; state->cursor++;
} else { } else {
if (!json_eat_comments(state)) { json_eat_comments(state);
return;
}
} }
} }
} }

View File

@ -406,6 +406,11 @@ class JSONParserTest < Test::Unit::TestCase
} }
JSON JSON
assert_equal({ "key1" => "value1" }, parse(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 end
def test_nesting def test_nesting