Skip to content

RubyParser: slice comments by byte offset - #4376

Merged
kddnewton merged 1 commit into
ruby:mainfrom
sourya2704:fix-ruby-parser-multibyte-comments
Nov 14, 2026
Merged

kddnewton merged 1 commit into
ruby:mainfrom
sourya2704:fix-ruby-parser-multibyte-comments

Conversation

@sourya2704

Copy link
Copy Markdown
Contributor

Fixes #4369.

attach_comments sliced source_string with String#[] using prism's byte offsets, but String#[] counts characters. With multibyte characters in the comments before a def, the slice landed in the wrong place:

  • "# ああああああ\ndef x; end\n": the comments included def x; end
  • "# あああああああ\ndef x; end\n": NoMethodError (undefined method 'match?' for nil)
  • "# é\n# 日本語\n\n# ü\ndef x; end\n": the comments were dropped (nil)

This uses String#byteslice for both slices. The new test compares the comments with ruby_parser for those three sources. It fails without the change.

bundle exec rake test passes.

attach_comments used prism's byte offsets to index the source string
with String#[], which counts characters. With multibyte characters
before a def, the slice was taken at the wrong place: the comments
could include the code after them, be dropped entirely, or raise
NoMethodError when the slice ran past the end of the string.

Use String#byteslice instead.

Fixes ruby#4369
@kddnewton
kddnewton merged commit d36198b into ruby:main Nov 14, 2026
103 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Prism::Translation::RubyParser may fail to parse code containing multibyte characters

2 participants