@@ -1042,18 +1042,25 @@ def parse_comment
10421042
10431043 # Check for a line comment `//...` or `#...`
10441044 elsif @scanner . scan ( %r{//|#} )
1045- # Determine valid line comment termination characters based on context.
1046- termination_chars = [ "\n " , "\r " ]
1047- termination_chars << ']' if context_contain? ( :array )
1048- termination_chars << '}' if context_contain? ( :object_value )
1049- termination_chars << ':' if context_contain? ( :object_key )
1050-
1051- # Create a regex that will scan until it hits one of the terminators.
1052- # The terminators are positive lookaheads, so they aren't consumed by the scan.
1053- terminator_regex = Regexp . new ( "(?=#{ termination_chars . map { |c | Regexp . escape ( c ) } . join ( '|' ) } )" )
1054-
1055- # Scan until the end of the comment.
1056- @scanner . scan_until ( terminator_regex )
1045+ in_array = context_contain? ( :array )
1046+ in_object = context_contain? ( :object_value )
1047+
1048+ if context_contain? ( :object_key )
1049+ # If parsing a key, we must stop at ':' and structural closers
1050+ @scanner . scan_until ( /(?=[\n \r :}\] ])/ )
1051+ elsif in_array && in_object
1052+ # Nested ambiguity, stop at any closer
1053+ @scanner . scan_until ( /(?=[\n \r }\] ])/ )
1054+ elsif in_array
1055+ # Inside array, stop at ']'
1056+ @scanner . scan_until ( /(?=[\n \r \] ])/ )
1057+ elsif in_object
1058+ # Inside object value, stop at '}'
1059+ @scanner . scan_until ( /(?=[\n \r }])/ )
1060+ else
1061+ # Top level or neutral, stop at newline
1062+ @scanner . scan_until ( /(?=[\n \r ])/ )
1063+ end
10571064 else
10581065 # The character at the current position (likely '/') is not the start of a
10591066 # valid comment. To prevent an infinite loop in the calling parser, we must
0 commit comments